Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(ui): improve interaction reliability (#7591)

Univerf7e1033814ee
diff --git a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts
index b85ee730d5..5dcc5dd510 100644
--- a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts
+++ b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts
@@ -15,13 +15,26 @@
*/
import type { IDrawingParam, IDrawingSearch } from '@univerjs/core';
-import { BooleanNumber, DrawingTypeEnum, Injector } from '@univerjs/core';
+import { BooleanNumber, DrawingTypeEnum, Injector, JSON1 } from '@univerjs/core';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { UnitDrawingService } from '../drawing-manager-impl.service';
const unitId = 'unit';
const subUnitId = 'subUnit';
+type SlideDrawingTestParam = IDrawingParam & {
+ element: {
+ name: string;
+ shapeData: { text: string };
+ };
+};
+
+function createSlideDrawingService(): UnitDrawingService<SlideDrawingTestParam> {
+ const injector = new Injector();
+ injector.add([UnitDrawingService]);
+ return injector.get<UnitDrawingService<SlideDrawingTestParam>>(UnitDrawingService);
+}
+
function createDrawing(drawingId: string, overrides: Partial<IDrawingParam> = {}): IDrawingParam {
return {
unitId,
@@ -123,6 +136,59 @@ describe('UnitDrawingService', () => {
});
});
+ it('preserves disjoint nested fields across concurrent drawing updates', () => {
+ const base: SlideDrawingTestParam = {
+ ...createDrawing('shape-1'),
+ element: {
+ name: 'before',
+ shapeData: { text: 'before' },
+ },
+ transform: { height: 80, left: 100, top: 100, width: 200 },
+ };
+ const textService = createSlideDrawingService();
+ const nameService = createSlideDrawingService();
+ [textService, nameService].forEach((drawingService) => {
+ drawingService.applyJson1(unitId, subUnitId, drawingService.getBatchAddOp([base]).redo);
+ });
+
+ const textOp = textService.getBatchUpdateOp([{
+ ...base,
+ element: {
+ ...base.element,
+ shapeData: { text: 'offline once' },
+ },
+ transform: { ...base.transform, left: 360 },
+ }]).redo;
+ const nameOp = nameService.getBatchUpdateOp([{
+ ...base,
+ element: { ...base.element, name: 'server while offline' },
+ }]).redo;
+ if (!textOp || !nameOp) {
+ throw new Error('Expected both drawing updates to produce JSON1 operations');
+ }
+
+ const textPrime = JSON1.type.transform(textOp, nameOp, 'left');
+ const namePrime = JSON1.type.transform(nameOp, textOp, 'right');
+ if (!textPrime || !namePrime) {
+ throw new Error('Expected concurrent drawing operations to transform');
+ }
+
+ textService.applyJson1(unitId, subUnitId, nameOp);
+ textService.applyJson1(unitId, subUnitId, textPrime);
+ nameService.applyJson1(unitId, subUnitId, textOp);
+ nameService.applyJson1(unitId, subUnitId, namePrime);
+
+ [textService, nameService].forEach((drawingService) => {
+ expect(drawingService.getDrawingByParam(createSearch('shape-1'))).toMatchObject({
+ element: {
+ name: 'server while offline',
+ shapeData: { text: 'offline once' },
+ },
+ transform: { left: 360 },
+ });
+ });
+ });
+
it('preserves previous drawing data when docs replace a subunit snapshot', () => {
service.registerDrawingData(unitId, {
[subUnitId]: {
diff --git a/packages/drawing/src/services/drawing-manager-impl.service.ts b/packages/drawing/src/services/drawing-manager-impl.service.ts
index eaa7722064..bcb35e4666 100644
--- a/packages/drawing/src/services/drawing-manager-impl.service.ts
+++ b/packages/drawing/src/services/drawing-manager-impl.service.ts
@@ -21,7 +21,6 @@ import type {
IDrawingSearch,
Nullable,
} from '@univerjs/core';
-import type { JSONOp, JSONOpList } from 'ot-json1';
import type { Observable } from 'rxjs';
import type {
IDrawingGroupUpdateParam,
@@ -37,12 +36,17 @@ import { DrawingTypeEnum, normalizeDrawingOrderIndex, sortRules, sortRulesByDesc
import * as json1 from 'ot-json1';
import { Subject } from 'rxjs';
-export interface IDrawingJsonUndo1 {
+type JSONOp = json1.JSONOp;
+type JSONOpList = json1.JSONOpList;
+
+export interface IDrawingJsonUndo1<
+ TObjects = IDrawingSearch[] | IDrawingOrderMapParam | IDrawingGroupUpdateParam | IDrawingGroupUpdateParam[]
+> {
undo: JSONOp;
redo: JSONOp;
unitId: string;
subUnitId: string;
- objects: IDrawingSearch[] | IDrawingOrderMapParam | IDrawingGroupUpdateParam | IDrawingGroupUpdateParam[];
+ objects: TObjects;
}
export interface IDrawingJson1Type {
@@ -66,10 +70,6 @@ function isJsonValueEqual(left: unknown, right: unknown): boolean {
return true;
}
- if (left == null || right == null || typeof left !== 'object' || typeof right !== 'object') {
- return false;
- }
-
if (Array.isArray(left) || Array.isArray(right)) {
if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) {
return false;
@@ -78,15 +78,74 @@ function isJsonValueEqual(left: unknown, right: unknown): boolean {
return left.every((item, index) => isJsonValueEqual(item, right[index]));
}
- const leftRecord = left as Record<string, unknown>;
- const rightRecord = right as Record<string, unknown>;
- const leftKeys = Object.keys(leftRecord);
- const rightKeys = Object.keys(rightRecord);
+ if (!isPlainObject(left) || !isPlainObject(right)) {
+ return false;
+ }
+
+ const leftKeys = Object.keys(left);
+ const rightKeys = Object.keys(right);
if (leftKeys.length !== rightKeys.length) {
return false;
}
- return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(rightRecord, key) && isJsonValueEqual(leftRecord[key], rightRecord[key]));
+ return leftKeys.every((key) => Object.prototype.hasOwnProperty.call(right, key) && isJsonValueEqual(left[key], right[key]));
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function isJsonDocument(value: unknown): value is json1.Doc {
+ if (value === null || typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
+ return true;
+ }
+
+ if (Array.isArray(value)) {
+ return value.every(isJsonDocument);
+ }
+
+ return isPlainObject(value) && Object.values(value).every(isJsonDocument);
+}
+
+function appendJsonUpdateOps(
+ ops: JSONOp[],
+ path: Array<number | string>,
+ newValue: unknown,
+ oldValue: unknown,
+ hasOldValue: boolean
+): void {
+ if (hasOldValue && isJsonValueEqual(oldValue, newValue)) {
+ return;
+ }
+
+ if (
+ hasOldValue &&
+ oldValue != null &&
+ newValue != null &&
+ isPlainObject(oldValue) &&
+ isPlainObject(newValue)
+ ) {
+ const keys = new Set([...Object.keys(oldValue), ...Object.keys(newValue)]);
+ keys.forEach((key) => appendJsonUpdateOps(
+ ops,
+ [...path, key],
+ newValue[key],
+ oldValue[key],
+ Object.prototype.hasOwnProperty.call(oldValue, key)
+ ));
+ return;
+ }
+
+ const op = !hasOldValue
+ ? newValue === undefined || !isJsonDocument(newValue) ? null : json1.insertOp(path, newValue)
+ : newValue === undefined
+ ? json1.removeOp(path, true)
+ : isJsonDocument(oldValue) && isJsonDocument(newValue)
+ ? json1.replaceOp(path, oldValue, newValue)
+ : null;
+ if (op && isNonEmptyOp(op)) {
+ ops.push(op);
+ }
}
interface IDrawingRefreshMetadata {
@@ -408,7 +467,7 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
return { undo: invertOp, redo: op, unitId, subUnitId, objects: allToRemove };
}
- getBatchUpdateOp(updateParams: T[]): IDrawingJsonUndo1 {
+ getBatchUpdateOp(updateParams: T[]): IDrawingJsonUndo1<IDrawingSearch[]> {
const objects: IDrawingSearch[] = [];
const ops: JSONOp[] = [];
const invertOps: JSONOp[] = [];
@@ -1007,36 +1066,8 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing
const newVal = newParam[key as keyof IDrawingParam];
const hasOldKey = Object.prototype.hasOwnProperty.call(oldParam, key);
const oldVal = oldParam[key as keyof IDrawingParam];
-
- if (hasOldKey && isJsonValueEqual(oldVal, newVal)) {
- return;
- }
-
const path = [unitId, subUnitId, DrawingMapItemType.data, drawingId, key];
- if (!hasOldKey) {
- if (newVal === undefined) {
- return;
- }
-
- const op = json1.insertOp(path, newVal as unknown as json1.Doc);
- if (isNonEmptyOp(op)) {
- ops.push(op);
- }
- return;
- }
-
- if (newVal === undefined) {
- const op = json1.removeOp(path, true);
- if (isNonEmptyOp(op)) {
- ops.push(op);
- }
- return;
- }
-
- const op = json1.replaceOp(path, oldVal as unknown as json1.Doc, newVal as unknown as json1.Doc);
- if (isNonEmptyOp(op)) {
- ops.push(op);
- }
+ appendJsonUpdateOps(ops, path, newVal, oldVal, hasOldKey);
});
return ops;
}
diff --git a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
index a273d841ad..5c2c2710a9 100644
--- a/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
+++ b/packages/engine-render/src/__tests__/engine-scene-viewport.spec.ts
@@ -941,6 +941,71 @@ describe('engine scene viewport extra', () => {
engine.dispose();
});
+ it('renders controls from resolved display geometry without changing the selected object', () => {
+ const { engine, scene } = createFixture();
+ engine.setActiveScene(scene.sceneKey);
+
+ const rect = scene.getObject('rect-main');
+ if (!(rect instanceof Rect)) {
+ throw new TypeError('Fixture should contain the main rectangle');
+ }
+ rect.transformerConfig = {
+ keepRatio: false,
+ controlStateResolver: (object) => ({
+ ...object.getState(),
+ left: object.left - 8,
+ top: object.top - 6,
+ width: object.width + 24,
+ height: object.height + 18,
+ }),
+ };
+ const transformer = new Transformer(scene);
+
+ transformer.setSelectedControl(rect);
+ const control = scene.getObject(`__SpreadsheetTransformer___${rect.oKey}`);
+ if (!(control instanceof Group)) {
+ throw new TypeError('Transformer should create a control group');
+ }
+
+ expect(control.getState()).toEqual(expect.objectContaining({
+ left: 2,
+ top: 4,
+ width: 124,
+ height: 78,
+ }));
+ expect(rect.getState()).toEqual(expect.objectContaining({
+ left: 10,
+ top: 10,
+ width: 100,
+ height: 60,
+ }));
+
+ rect.translate(30, 40);
+ transformer.updateControl();
+ expect(control.getState()).toEqual(expect.objectContaining({
+ left: 22,
+ top: 34,
+ width: 124,
+ height: 78,
+ }));
+
+ const resizeAnchor = control.getObjects().find((object) => object.oKey.includes('__SpreadsheetTransformerResizeRB__'));
+ if (!resizeAnchor) {
+ throw new TypeError('Transformer should create a bottom-right resize anchor');
+ }
+ resizeAnchor.triggerPointerDown(createInputEvent('pointerdown', { offsetX: 146, offsetY: 112 }));
+ scene.onPointerMove$.emitEvent(createInputEvent('pointermove', { offsetX: 186, offsetY: 137 }));
+ scene.onPointerUp$.emitEvent(createInputEvent('pointerup', { offsetX: 186, offsetY: 137 }));
+ expect(rect.getState()).toEqual(expect.objectContaining({
+ width: 140,
+ height: 85,
+ }));
+
+ transformer.dispose();
+ scene.dispose();
+ engine.dispose();
+ });
+
it('insets the icon inside a small rotate control and matches the connector to its border', () => {
const { engine, scene } = createFixture();
engine.setActiveScene(scene.sceneKey);
diff --git a/packages/engine-render/src/basics/transformer-config.ts b/packages/engine-render/src/basics/transformer-config.ts
index a84f83bdf3..2020ea542b 100644
--- a/packages/engine-render/src/basics/transformer-config.ts
+++ b/packages/engine-render/src/basics/transformer-config.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Nullable } from '@univerjs/core';
+import type { ITransformState, Nullable } from '@univerjs/core';
import type { BaseObject } from '../base-object';
import type { IMouseEvent, IPointerEvent } from './i-events';
@@ -76,6 +76,9 @@ export interface ITransformerConfig {
/** Render transformer controls on a layer independent from the selected object. */
controlLayerIndex?: number;
+ /** Resolve display geometry for controls without changing the object's persisted transform. */
+ controlStateResolver?: (object: BaseObject) => ITransformState;
+
zeroLeft?: number;
zeroTop?: number;
moveBoundaryEnabled?: boolean;
diff --git a/packages/engine-render/src/scene.transformer.ts b/packages/engine-render/src/scene.transformer.ts
index e8e42b102d..7846f0cfc4 100644
--- a/packages/engine-render/src/scene.transformer.ts
+++ b/packages/engine-render/src/scene.transformer.ts
@@ -1554,7 +1554,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
}
private _createResizeAnchor(type: TransformerManagerType, applyObject: BaseObject, zIndex: number) {
- const { height = 0, width = 0, scaleX = 1, scaleY = 1 } = applyObject.getState();
+ const { height = 0, width = 0 } = this._getControlState(applyObject);
const {
anchorFill,
@@ -1595,7 +1595,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
}
private _createCopperResizeAnchor(type: TransformerManagerType, applyObject: BaseObject, zIndex: number) {
- const { height = 0, width = 0, scaleX = 1, scaleY = 1 } = applyObject.getState();
+ const { height = 0, width = 0 } = this._getControlState(applyObject);
const { anchorFill, anchorStroke, anchorStrokeWidth, anchorSize } = this._getConfig(applyObject);
@@ -1758,9 +1758,13 @@ export class Transformer extends Disposable implements ITransformerConfig {
});
}
+ private _getControlState(applyObject: BaseObject): ReturnType<BaseObject['getState']> {
+ return applyObject.transformerConfig?.controlStateResolver?.(applyObject) ?? applyObject.getState();
+ }
+
private _updateControl() {
this._updateControlIterator((control, applyObject) => {
- const { left, top, height, width, angle } = applyObject.getState();
+ const { left, top, height, width, angle } = this._getControlState(applyObject);
control.transformByState({
left,
top,
@@ -1824,8 +1828,7 @@ export class Transformer extends Disposable implements ITransformerConfig {
// eslint-disable-next-line max-lines-per-function, complexity
private _createControl(applyObject: BaseObject, isSkipOnCropper = true) {
- const { left = 0, top = 0, height = 0, width = 0 } = applyObject.getState();
- const angle = applyObject.angle;
+ const { left = 0, top = 0, height = 0, width = 0, angle = 0 } = this._getControlState(applyObject);
const {
isCropper,
resizeEnabled,
@@ -1940,11 +1943,11 @@ export class Transformer extends Disposable implements ITransformerConfig {
transformerControl.evented = false;
transformerControl.openSelfSizeMode();
transformerControl.transformByState({
- left: applyObject.left || left,
- top: applyObject.top || top,
- angle: applyObject.angle || angle,
- width: applyObject.width || width,
- height: applyObject.height || height,
+ left,
+ top,
+ angle,
+ width,
+ height,
});
const scene = this.getScene();
scene.addObject(transformerControl, layerIndex);
diff --git a/packages/ui/src/services/contextmenu/contextmenu.service.ts b/packages/ui/src/services/contextmenu/contextmenu.service.ts
index 405ea4ba89..53f6dfddb2 100644
--- a/packages/ui/src/services/contextmenu/contextmenu.service.ts
+++ b/packages/ui/src/services/contextmenu/contextmenu.service.ts
@@ -19,6 +19,7 @@ import type { IMouseEvent, IPointerEvent } from '@univerjs/engine-render';
import { createIdentifier, Disposable, toDisposable } from '@univerjs/core';
export interface IContextMenuTriggerContext {
+ autoFocus?: boolean;
unitId?: string;
}
diff --git a/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx b/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx
index 193c40f31d..e573165373 100644
--- a/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx
+++ b/packages/ui/src/views/components/context-menu/AnchoredContextMenu.tsx
@@ -35,6 +35,7 @@ export interface IAnchoredContextMenuProps {
anchorRect: IContextMenuAnchorRect | null;
menuType: string;
anchorVertical?: 'top' | 'bottom';
+ autoFocus?: boolean;
menuOffset?: number;
menuManagerService?: IMenuManagerService;
layoutService?: ILayoutService;
@@ -49,6 +50,7 @@ export function AnchoredContextMenu(props: IAnchoredContextMenuProps) {
anchorRect,
menuType,
anchorVertical = 'bottom',
+ autoFocus,
menuOffset = 0,
menuManagerService,
layoutService,
@@ -61,6 +63,7 @@ export function AnchoredContextMenu(props: IAnchoredContextMenuProps) {
const menuSessionVersionRef = useRef(0);
const visibleRef = useRef(visible);
const menuTypeRef = useRef(menuType);
+ const focusReturnTargetRef = useRef<HTMLElement | null>(null);
useEffect(() => {
onRequestCloseRef.current = onRequestClose;
@@ -85,10 +88,32 @@ export function AnchoredContextMenu(props: IAnchoredContextMenuProps) {
useLayoutEffect(() => {
if (visible) {
+ const ownerDocument = contentRef.current?.ownerDocument ?? document;
+ const activeElement = ownerDocument.activeElement;
+ const isFocusInMenu = activeElement !== null
+ && (contentRef.current?.contains(activeElement)
+ || !!activeElement.closest(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}]`));
+ const HTMLElementConstructor = ownerDocument.defaultView?.HTMLElement;
+
+ if (!isFocusInMenu) {
+ focusReturnTargetRef.current = HTMLElementConstructor && activeElement instanceof HTMLElementConstructor
+ ? activeElement
+ : null;
+ }
contextMenuHostService.activateMenu(hostId);
return;
}
+ const ownerDocument = contentRef.current?.ownerDocument ?? document;
+ const activeElement = ownerDocument.activeElement;
+ const isFocusInMenu = activeElement !== null
+ && (contentRef.current?.contains(activeElement)
+ || !!activeElement.closest(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}]`));
+ const focusReturnTarget = focusReturnTargetRef.current;
+ if (isFocusInMenu && focusReturnTarget?.isConnected) {
+ focusReturnTarget.focus();
+ }
+ focusReturnTargetRef.current = null;
contextMenuHostService.deactivateMenu(hostId);
}, [contextMenuHostService, hostId, visible]);
@@ -167,9 +192,11 @@ export function AnchoredContextMenu(props: IAnchoredContextMenuProps) {
{menuType && (
<ContextMenuPanel
menuType={menuType}
+ autoFocus={autoFocus}
menuManagerService={menuManagerService}
layoutService={layoutService}
menuSessionVersion={menuSessionVersionRef.current}
+ onCancel={onRequestClose}
onOptionSelect={onOptionSelect}
/>
)}
diff --git a/packages/ui/src/views/components/context-menu/ContextMenu.tsx b/packages/ui/src/views/components/context-menu/ContextMenu.tsx
index 8822ab3ffc..edd68fc0a4 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenu.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenu.tsx
@@ -93,6 +93,7 @@ export function DesktopContextMenu() {
visible={visible}
anchorRect={anchorRect}
menuType={menuType}
+ autoFocus={menuContext?.autoFocus}
menuManagerService={activeMenuManagerService}
layoutService={activeLayoutService}
onRequestClose={handleClose}
diff --git a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
index 8684a3ceb9..1cb585dcf8 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
@@ -27,7 +27,7 @@ import type { IMenuSchema } from '../../../services/menu/menu-manager.service';
import { isRealNum, LocaleService } from '@univerjs/core';
import { borderBottomClassName, borderClassName, clsx, cva, scrollbarClassName } from '@univerjs/design';
import { CheckMarkIcon, MoreLeftIcon, MoreRightIcon } from '@univerjs/icons';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { combineLatest, isObservable, map, merge, of, scan, startWith } from 'rxjs';
import { ILayoutService } from '../../../services/layout/layout.service';
@@ -711,12 +711,13 @@ export function ContextMenuPanel(props: IContextMenuPanelProps) {
return preventBrowserZoomInContainers([menuElement]);
}, [menuElement]);
- const getFocusableMenuButtons = useCallback(() => {
- if (!menuElement) {
+ const getFocusableMenuButtons = useCallback((scope?: Element | null) => {
+ const menuScope = scope ?? menuElement;
+ if (!menuScope) {
return [];
}
- return Array.from(menuElement.querySelectorAll<HTMLButtonElement>('button:not(:disabled)'));
+ return Array.from(menuScope.querySelectorAll<HTMLButtonElement>('button:not(:disabled)'));
}, [menuElement]);
useEffect(() => {
@@ -754,7 +755,9 @@ export function ContextMenuPanel(props: IContextMenuPanelProps) {
return;
}
- const focusableButtons = getFocusableMenuButtons();
+ const activeElement = menuElement?.ownerDocument.activeElement;
+ const activeSubmenu = activeElement?.closest(`[${CONTEXT_MENU_SUBMENU_PORTAL_ATTR}]`) ?? null;
+ const focusableButtons = getFocusableMenuButtons(activeSubmenu);
if (!focusableButtons.length) {
return;
}
@@ -762,7 +765,6 @@ export function ContextMenuPanel(props: IContextMenuPanelProps) {
event.preventDefault();
event.stopPropagation();
- const activeElement = menuElement?.ownerDocument.activeElement;
const activeIndex = focusableButtons.findIndex((button) => button === activeElement);
if (event.key === 'Enter') {
@@ -1140,9 +1142,12 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
});
const [submenuPositionReady, setSubmenuPositionReady] = useState(false);
const [submenuPlacement, setSubmenuPlacement] = useState<'left' | 'right'>('right');
+ const [keyboardSubmenuFocusRequested, setKeyboardSubmenuFocusRequested] = useState(false);
const menuItemElementRef = useRef<HTMLDivElement | null>(null);
+ const menuButtonRef = useRef<HTMLButtonElement | null>(null);
const submenuElementRef = useRef<HTMLDivElement | null>(null);
const submenuCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const submenuId = useId();
const selections = useMemo(() => {
if (menuItem.type !== MenuItemType.SELECTOR && menuItem.type !== MenuItemType.BUTTON_SELECTOR) {
@@ -1213,6 +1218,15 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
return preventBrowserZoomInContainers([submenuElement]);
}, [submenuVisible]);
+ useLayoutEffect(() => {
+ if (!submenuVisible || !submenuPositionReady || !keyboardSubmenuFocusRequested) {
+ return;
+ }
+
+ const firstEnabledButton = submenuElementRef.current?.querySelector<HTMLButtonElement>('button:not(:disabled)');
+ firstEnabledButton?.focus();
+ }, [keyboardSubmenuFocusRequested, submenuPositionReady, submenuVisible]);
+
useEffect(() => {
if (!submenuVisible) {
setSubmenuPositionReady(false);
@@ -1316,6 +1330,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
onMouseEnter={() => {
clearSubmenuCloseTimer();
if (hasSubmenu && !disabled && !hoverSuppressed) {
+ setKeyboardSubmenuFocusRequested(false);
setSubmenuPositionReady(false);
setActiveSubmenuKey(menuKey);
return;
@@ -1359,14 +1374,32 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
)
: (
<button
+ ref={menuButtonRef}
type="button"
className={interactiveItemClassName}
disabled={disabled}
title={typeof menuItem.tooltip === 'string' ? localeService.t(menuItem.tooltip) : undefined}
- onClick={() => {
+ aria-haspopup={hasSubmenu ? 'menu' : undefined}
+ aria-expanded={hasSubmenu ? submenuVisible : undefined}
+ aria-controls={hasSubmenu ? submenuId : undefined}
+ onKeyDown={(event) => {
+ const openDirection = direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight';
+ if (!hasSubmenu || event.key !== openDirection) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ clearSubmenuCloseTimer();
+ setKeyboardSubmenuFocusRequested(true);
+ setSubmenuPositionReady(false);
+ setActiveSubmenuKey(menuKey);
+ }}
+ onClick={(event) => {
clearSubmenuCloseTimer();
if (hasSubmenu) {
if (headerAction) {
+ setKeyboardSubmenuFocusRequested(event.detail === 0);
setSubmenuPositionReady(false);
setActiveSubmenuKey(menuKey);
return;
@@ -1384,6 +1417,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
return;
}
+ setKeyboardSubmenuFocusRequested(event.detail === 0);
setSubmenuPositionReady(false);
setActiveSubmenuKey(menuKey);
return;
@@ -1421,6 +1455,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
? createPortal(
<div
ref={submenuElementRef}
+ id={submenuId}
dir={direction}
data-u-context-menu-submenu="true"
className="univer-z-[1080] univer-w-max univer-max-w-[calc(100vw-16px)]"
@@ -1452,6 +1487,17 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
scheduleSubmenuClose();
}}
+ onKeyDown={(event) => {
+ const closeDirection = direction === 'rtl' ? 'ArrowRight' : 'ArrowLeft';
+ if (event.key !== closeDirection) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+ closeSubmenu();
+ menuButtonRef.current?.focus();
+ }}
onWheel={(event) => event.stopPropagation()}
>
<div
diff --git a/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx
new file mode 100644
index 0000000000..b3c1ae8aa8
--- /dev/null
+++ b/packages/ui/src/views/components/context-menu/__tests__/AnchoredContextMenu.spec.tsx
@@ -0,0 +1,206 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { PropsWithChildren } from 'react';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { AnchoredContextMenu } from '../AnchoredContextMenu';
+
+const hostService = {
+ activateMenu: vi.fn(),
+ deactivateMenu: vi.fn(),
+ registerMenu: vi.fn(() => ({ dispose: vi.fn() })),
+};
+const panelProps = vi.fn();
+
+vi.mock('@univerjs/design', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@univerjs/design')>();
+
+ return {
+ ...actual,
+ Popup: ({ children }: PropsWithChildren) => <>{children}</>,
+ };
+});
+
+vi.mock('../../../../utils/di', () => ({
+ useDependency: () => hostService,
+}));
+
+vi.mock('../ContextMenuPanel', () => ({
+ CONTEXT_MENU_SUBMENU_PORTAL_ATTR: 'data-u-context-menu-submenu',
+ ContextMenuPanel: (props: { autoFocus?: boolean; onCancel?: () => void }) => {
+ panelProps(props);
+ return (
+ <button
+ type="button"
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') {
+ event.stopPropagation();
+ props.onCancel?.();
+ }
+ }}
+ >
+ Context menu item
+ </button>
+ );
+ },
+}));
+
+describe('AnchoredContextMenu', () => {
+ beforeEach(() => {
+ panelProps.mockClear();
+ });
+
+ afterEach(cleanup);
+
+ it('passes its close callback to the context menu panel', () => {
+ const close = vi.fn();
+ render(
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ onRequestClose={close}
+ />
+ );
+
+ fireEvent.keyDown(screen.getByRole('button', { name: 'Context menu item' }), {
+ key: 'Escape',
+ });
+
+ expect(close).toHaveBeenCalledOnce();
+ });
+
+ it('restores the element focused before the menu opened', () => {
+ const { rerender } = render(
+ <>
+ <button type="button">Editor canvas</button>
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible={false}
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ onRequestClose={vi.fn()}
+ />
+ </>
+ );
+ const editor = screen.getByRole('button', { name: 'Editor canvas' });
+ editor.focus();
+
+ rerender(
+ <>
+ <button type="button">Editor canvas</button>
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ onRequestClose={vi.fn()}
+ />
+ </>
+ );
+ screen.getByRole('button', { name: 'Context menu item' }).focus();
+
+ rerender(
+ <>
+ <button type="button">Editor canvas</button>
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible={false}
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ onRequestClose={vi.fn()}
+ />
+ </>
+ );
+
+ expect(document.activeElement).toBe(editor);
+ });
+
+ it('restores focus when the menu is mounted in another document', () => {
+ const iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ const iframeDocument = iframe.contentDocument;
+ if (!iframeDocument) {
+ throw new Error('Expected iframe document');
+ }
+
+ const container = iframeDocument.createElement('div');
+ iframeDocument.body.appendChild(container);
+ const rendered = render(
+ <>
+ <button type="button">Embedded editor canvas</button>
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible={false}
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ onRequestClose={vi.fn()}
+ />
+ </>,
+ { container }
+ );
+ const editor = rendered.getByRole('button', { name: 'Embedded editor canvas' });
+ editor.focus();
+
+ rendered.rerender(
+ <>
+ <button type="button">Embedded editor canvas</button>
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ onRequestClose={vi.fn()}
+ />
+ </>
+ );
+ rendered.getByRole('button', { name: 'Context menu item' }).focus();
+
+ rendered.rerender(
+ <>
+ <button type="button">Embedded editor canvas</button>
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible={false}
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ onRequestClose={vi.fn()}
+ />
+ </>
+ );
+
+ expect(iframeDocument.activeElement).toBe(editor);
+ rendered.unmount();
+ iframe.remove();
+ });
+
+ it('forwards keyboard autofocus to the context menu panel', () => {
+ render(
+ <AnchoredContextMenu
+ hostId="desktop"
+ visible
+ anchorRect={{ left: 0, top: 0, bottom: 0 }}
+ menuType="drawing"
+ autoFocus
+ onRequestClose={vi.fn()}
+ />
+ );
+
+ expect(panelProps).toHaveBeenCalledWith(expect.objectContaining({ autoFocus: true }));
+ });
+});
diff --git a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
index df388583af..d81080ad01 100644
--- a/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
+++ b/packages/ui/src/views/components/context-menu/__tests__/ContextMenuPanel.spec.tsx
@@ -386,6 +386,40 @@ describe('ContextMenuPanel', () => {
expect(TestState.cancels).toBe(1);
});
+ it('enters, navigates, and exits a submenu with arrow keys', async () => {
+ renderWithDependencies(<ContextMenuPanel menuType="root" />, {
+ root: [
+ {
+ key: 'arrange',
+ order: 0,
+ item: {
+ id: 'arrange',
+ type: MenuItemType.SUBITEMS,
+ title: 'Arrange',
+ },
+ },
+ ],
+ arrange: [
+ createButtonItem('bring-front', { title: 'Bring to Front' }),
+ createButtonItem('send-back', { title: 'Send to Back' }),
+ ],
+ });
+ const trigger = screen.getByRole('button', { name: 'translated:Arrange' });
+ trigger.focus();
+
+ fireEvent.keyDown(trigger, { key: 'ArrowRight' });
+ const first = await screen.findByRole('button', { name: 'translated:Bring to Front' });
+ await nextFrame();
+ await waitFor(() => expect(document.activeElement).toBe(first));
+
+ fireEvent.keyDown(first, { key: 'ArrowDown' });
+ const second = screen.getByRole('button', { name: 'translated:Send to Back' });
+ expect(document.activeElement).toBe(second);
+
+ fireEvent.keyDown(second, { key: 'ArrowLeft' });
+ expect(document.activeElement).toBe(trigger);
+ });
+
it('selects an option from a selector submenu with the selector command id', () => {
renderWithDependencies(
<ContextMenuPanel