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): restore design components and handle editor interactions upstream (#7662)

Univer6cac0bd1a435
diff --git a/packages/design/src/components/color-picker/ColorInput.tsx b/packages/design/src/components/color-picker/ColorInput.tsx
index f92aa31343..65e48e46ae 100644
--- a/packages/design/src/components/color-picker/ColorInput.tsx
+++ b/packages/design/src/components/color-picker/ColorInput.tsx
@@ -15,7 +15,7 @@
*/
import type { ChangeEvent } from 'react';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { borderClassName } from '../../helper/class-utilities';
import { clsx } from '../../helper/clsx';
import { hexToHsv, hsvToHex, hsvToRgb, rgbToHsv } from './color-conversion';
@@ -34,102 +34,51 @@ interface IInputProps {
onChange?: (h: number, s: number, v: number, a?: number) => void;
}
-const FULL_HEX_COLOR_PATTERN = /^[0-9a-f]{6}$/i;
-
function HexInput({ hsv, onChange }: IInputProps) {
- const inputRef = useRef<HTMLInputElement>(null);
- const isComposingRef = useRef(false);
const [inputValue, setInputValue] = useState('');
const hexValue = useMemo(() => hsvToHex(hsv[0], hsv[1], hsv[2]), [hsv]);
useEffect(() => {
- if (isComposingRef.current) {
- return;
- }
-
- const nextValue = hexValue.replace(/^#/, '');
- // Preserve the user's casing so color echoes do not rewrite native selection or undo history.
- setInputValue((previous) => previous.toLowerCase() === nextValue ? previous : nextValue);
+ setInputValue(hexValue.replace(/^#/, ''));
}, [hexValue]);
- const updateInputValue = useCallback((newValue: string) => {
- if (!/^[0-9a-f]{0,6}$/i.test(newValue)) {
- return;
- }
+ const isValidHex = (hex: string) => {
+ return /^[0-9A-Fa-f]{6}$/.test(hex);
+ };
+
+ const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
+ const newValue = e.target.value.trim();
+
+ if (newValue.length > 6) return;
+
+ if (newValue !== '' && !/^[0-9A-Fa-f]*$/.test(newValue)) return;
setInputValue(newValue);
- if (FULL_HEX_COLOR_PATTERN.test(newValue)) {
+ if (isValidHex(newValue)) {
const hsvValue = hexToHsv(newValue);
if (hsvValue && onChange) {
onChange(...hsvValue);
}
}
- }, [onChange]);
-
- const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
- const newValue = e.target.value.trim();
- if (isComposingRef.current || (e.nativeEvent as InputEvent).isComposing) {
- setInputValue(newValue);
- return;
- }
-
- updateInputValue(newValue);
};
- useEffect(() => {
- const input = inputRef.current;
- if (!input) {
- return;
- }
-
- const handleCompositionStart = (event: CompositionEvent) => {
- event.stopPropagation();
- isComposingRef.current = true;
- };
- const handleCompositionUpdate = (event: CompositionEvent) => {
- event.stopPropagation();
- };
- const handleCompositionEnd = (event: CompositionEvent) => {
- event.stopPropagation();
- isComposingRef.current = false;
- const value = input.value.trim();
- if (value !== '' && !FULL_HEX_COLOR_PATTERN.test(value)) {
- setInputValue(hexValue.replace(/^#/, ''));
- return;
- }
- updateInputValue(value);
- };
-
- // Stop native composition before it reaches the host editor's DOM listeners.
- input.addEventListener('compositionstart', handleCompositionStart);
- input.addEventListener('compositionupdate', handleCompositionUpdate);
- input.addEventListener('compositionend', handleCompositionEnd);
- return () => {
- input.removeEventListener('compositionstart', handleCompositionStart);
- input.removeEventListener('compositionupdate', handleCompositionUpdate);
- input.removeEventListener('compositionend', handleCompositionEnd);
- };
- }, [hexValue, updateInputValue]);
-
const handleBlur = () => {
- if (!FULL_HEX_COLOR_PATTERN.test(inputRef.current?.value ?? '')) {
- const nextValue = hexValue.replace(/^#/, '');
- setInputValue(nextValue);
+ if (!isValidHex(inputValue)) {
+ setInputValue(hexValue.replace(/^#/, ''));
}
};
return (
<>
<input
- ref={inputRef}
- value={inputValue}
className={clsx(`
univer-w-full univer-px-2 !univer-pl-4 univer-uppercase
focus:univer-border-primary-500 focus:univer-outline-none
rtl:!univer-pl-2 rtl:!univer-pr-4
dark:!univer-text-gray-0
`, borderClassName)}
+ value={inputValue}
onChange={handleChange}
onBlur={handleBlur}
maxLength={6}
diff --git a/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx b/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx
deleted file mode 100644
index bde3e76675..0000000000
--- a/packages/design/src/components/color-picker/__tests__/ColorInput.spec.tsx
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * 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 { fireEvent, render } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-import { hexToHsv } from '../color-conversion';
-import { ColorInput } from '../ColorInput';
-
-describe('ColorInput', () => {
- it.each(['F05252', 'aB12Cd'])('preserves the native input value when its own color %s is echoed back', (value) => {
- const onChange = vi.fn();
- const { container, rerender } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />
- );
- const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
- fireEvent.change(input, { target: { value } });
- input.setSelectionRange(2, 4);
- const writeValue = vi.spyOn(input, 'value', 'set');
-
- expect(onChange).toHaveBeenLastCalledWith(...hexToHsv(value)!);
- rerender(<ColorInput hsv={hexToHsv(value)!} alpha={1} format="hex" onChange={onChange} />);
-
- expect(writeValue).not.toHaveBeenCalled();
- expect(input.value).toBe(value);
- expect([input.selectionStart, input.selectionEnd]).toEqual([2, 4]);
- writeValue.mockRestore();
- });
-
- it('synchronizes a different external color while a partial hex value is being edited', () => {
- const onChange = vi.fn();
- const { container, rerender } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />
- );
- const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
- fireEvent.change(input, { target: { value: 'F0' } });
- expect(onChange).not.toHaveBeenCalled();
-
- rerender(<ColorInput hsv={[120, 100, 100]} alpha={1} format="hex" onChange={onChange} />);
-
- expect(input.value).toBe('00ff00');
- expect(onChange).not.toHaveBeenCalled();
- });
-
- it('restores the latest accepted color when an incomplete edit loses focus', () => {
- const onChange = vi.fn();
- const { container, rerender } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />
- );
- const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
- fireEvent.change(input, { target: { value: 'F05252' } });
- rerender(<ColorInput hsv={hexToHsv('F05252')!} alpha={1} format="hex" onChange={onChange} />);
- fireEvent.change(input, { target: { value: 'F0' } });
- fireEvent.blur(input);
-
- expect(input.value).toBe('f05252');
- expect(onChange).toHaveBeenCalledTimes(1);
- });
-
- it('preserves native IME text until composition ends, then restores an invalid hex value', () => {
- const onChange = vi.fn();
- const { container } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />
- );
- const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
-
- fireEvent.compositionStart(input);
- fireEvent.compositionUpdate(input, { data: 'ni' });
- fireEvent.input(input, {
- inputType: 'insertCompositionText',
- isComposing: true,
- target: { value: 'ni' },
- });
- expect(input.value).toBe('ni');
- expect(onChange).not.toHaveBeenCalled();
-
- fireEvent.compositionEnd(input);
- expect(input.value).toBe('ff0000');
- expect(onChange).not.toHaveBeenCalled();
- });
-
- it('commits a valid hex value once native composition ends', () => {
- const onChange = vi.fn();
- const { container } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />
- );
- const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
-
- fireEvent.compositionStart(input);
- fireEvent.compositionUpdate(input, { data: 'F05252' });
- fireEvent.input(input, {
- inputType: 'insertCompositionText',
- isComposing: true,
- target: { value: 'F05252' },
- });
- expect(onChange).not.toHaveBeenCalled();
-
- fireEvent.compositionEnd(input);
- expect(onChange).toHaveBeenCalledOnce();
- expect(onChange).toHaveBeenCalledWith(...hexToHsv('F05252')!);
- });
-
- it.each(['F05252', 'ni'])('keeps composition %s local and uses current props after a rerender', (value) => {
- const previousOnChange = vi.fn();
- const onChange = vi.fn();
- const hostComposition = vi.fn();
- const { container, rerender, unmount } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={previousOnChange} />
- );
- const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
- const events = ['compositionstart', 'compositionupdate', 'compositionend'];
- for (const event of events) {
- container.addEventListener(event, hostComposition);
- }
- try {
- fireEvent.compositionStart(input);
- fireEvent.compositionUpdate(input, { data: value });
- fireEvent.input(input, { isComposing: true, target: { value } });
- rerender(<ColorInput hsv={[120, 100, 100]} alpha={1} format="hex" onChange={onChange} />);
- expect(input.value).toBe(value);
- fireEvent.compositionEnd(input);
-
- expect(hostComposition).not.toHaveBeenCalled();
- expect(previousOnChange).not.toHaveBeenCalled();
- if (value === 'F05252') {
- expect(onChange).toHaveBeenCalledExactlyOnceWith(...hexToHsv(value)!);
- } else {
- expect(input.value).toBe('00ff00');
- expect(onChange).not.toHaveBeenCalled();
- }
-
- onChange.mockClear();
- unmount();
- fireEvent.compositionEnd(input);
- expect(onChange).not.toHaveBeenCalled();
- } finally {
- for (const event of events) {
- container.removeEventListener(event, hostComposition);
- }
- }
- });
-
- it.each(['F0!', 'F012345'])('rejects invalid draft %s without committing a color', (value) => {
- const onChange = vi.fn();
- const { container } = render(
- <ColorInput hsv={[0, 100, 100]} alpha={1} format="hex" onChange={onChange} />
- );
- const input = container.querySelector('input[maxlength="6"]') as HTMLInputElement;
- fireEvent.change(input, { target: { value: 'F0' } });
- fireEvent.change(input, { target: { value } });
- expect(input.value).toBe('F0');
- expect(onChange).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/design/src/components/dialog/Dialog.tsx b/packages/design/src/components/dialog/Dialog.tsx
index d439b94e7f..3ed9bda864 100644
--- a/packages/design/src/components/dialog/Dialog.tsx
+++ b/packages/design/src/components/dialog/Dialog.tsx
@@ -27,7 +27,6 @@ import {
Dialog as DialogProvider,
DialogTitle,
} from './DialogPrimitive';
-import { useDialogFocus } from './use-dialog-focus';
export interface IDialogProps {
children: ReactNode;
@@ -118,9 +117,6 @@ export interface IDialogProps {
*/
onClose?: () => void;
- /** Prevent default to provide a caller-owned focus destination when the dialog closes. */
- onCloseAutoFocus?: (event: Event) => void;
-
showOk?: boolean;
showCancel?: boolean;
@@ -286,13 +282,11 @@ export function Dialog(props: IDialogProps) {
showCancel,
onOpenChange,
onClose,
- onCloseAutoFocus,
onOk,
onCancel,
} = props;
const { locale, mountContainer, direction } = useContext(ConfigContext);
- const { handleContentRef, handleOpenAutoFocus, handleCloseAutoFocus } = useDialogFocus(mask, onCloseAutoFocus);
const { position, isDragging, setElementRef, handleMouseDown } = useDraggable({ defaultPosition, enabled: draggable });
@@ -313,12 +307,11 @@ export function Dialog(props: IDialogProps) {
)
: null);
- const handleDraggableContentRef = useCallback((node: HTMLDivElement | null) => {
- handleContentRef(node);
+ const handleContentRef = useCallback((node: HTMLDivElement | null) => {
if (node && draggable) {
setElementRef(node);
}
- }, [draggable, handleContentRef, setElementRef]);
+ }, [draggable, setElementRef]);
const handleOpenChange = useCallback((isOpen: boolean) => {
if (!mask && !isOpen) {
@@ -344,7 +337,7 @@ export function Dialog(props: IDialogProps) {
modal={mask !== false}
>
<DialogContent
- ref={handleDraggableContentRef}
+ ref={handleContentRef}
className={clsx(className, {
'!univer-animate-none': draggable,
})}
@@ -369,14 +362,7 @@ export function Dialog(props: IDialogProps) {
overlayClassName={overlayClassName}
dir={direction}
onClickClose={handleClickClose}
- onOpenAutoFocus={handleOpenAutoFocus}
- onCloseAutoFocus={handleCloseAutoFocus}
onEscapeKeyDown={(e) => {
- if (e.isComposing) {
- e.preventDefault();
- return;
- }
-
if (keyboard) {
handleClickClose();
}
diff --git a/packages/design/src/components/dialog/MobileDialog.tsx b/packages/design/src/components/dialog/MobileDialog.tsx
index f10198cab1..2d84b82ef4 100644
--- a/packages/design/src/components/dialog/MobileDialog.tsx
+++ b/packages/design/src/components/dialog/MobileDialog.tsx
@@ -27,7 +27,6 @@ import {
Dialog as DialogProvider,
DialogTitle,
} from './DialogPrimitive';
-import { useDialogFocus } from './use-dialog-focus';
export type IMobileDialogProps = IDialogProps;
@@ -48,12 +47,10 @@ export function MobileDialog(props: IMobileDialogProps) {
showCancel,
onOpenChange,
onClose,
- onCloseAutoFocus,
onOk,
onCancel,
} = props;
const { locale, mountContainer, direction } = useContext(ConfigContext);
- const { handleContentRef, handleOpenAutoFocus, handleCloseAutoFocus } = useDialogFocus(mask, onCloseAutoFocus);
const maxHeight = globalThis.CSS?.supports('height', '1dvh') ? '80dvh' : '80vh';
const footer = propFooter ?? (showOk || showCancel
? (
@@ -83,7 +80,6 @@ export function MobileDialog(props: IMobileDialogProps) {
return (
<DialogProvider open={open} onOpenChange={handleOpenChange} modal={mask !== false}>
<DialogContent
- ref={handleContentRef}
className={clsx(`
!univer-bottom-0 !univer-left-0 !univer-right-0 !univer-top-auto !univer-max-w-none
!univer-translate-x-0 !univer-translate-y-0 !univer-gap-4 !univer-overflow-y-auto
@@ -111,13 +107,7 @@ export function MobileDialog(props: IMobileDialogProps) {
overlayClassName={overlayClassName}
dir={direction}
onClickClose={close}
- onOpenAutoFocus={handleOpenAutoFocus}
- onCloseAutoFocus={handleCloseAutoFocus}
onEscapeKeyDown={(event) => {
- if (event.isComposing) {
- event.preventDefault();
- return;
- }
if (keyboard) {
close();
}
diff --git a/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx b/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx
deleted file mode 100644
index 3dfa19a688..0000000000
--- a/packages/design/src/components/dialog/__tests__/Dialog.spec.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-/**
- * 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 { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { Dialog } from '../Dialog';
-import { MobileDialog } from '../MobileDialog';
-
-afterEach(cleanup);
-
-describe.each([['Dialog', Dialog], ['MobileDialog', MobileDialog]] as const)('%s focus recovery', (_name, DialogComponent) => {
- it('keeps composition Escape inside the real dialog and allows ordinary Escape afterwards', async () => {
- const onClose = vi.fn();
- const onOpenChange = vi.fn();
- const { getByRole } = render(
- <DialogComponent open title="Color" onClose={onClose} onOpenChange={onOpenChange}>
- <input aria-label="Hex color" />
- </DialogComponent>
- );
- const input = getByRole('textbox', { name: 'Hex color' });
- await waitFor(() => expect(document.activeElement).toBe(input));
-
- fireEvent.compositionStart(input);
- const composingEscape = new KeyboardEvent('keydown', {
- key: 'Escape',
- isComposing: true,
- bubbles: true,
- cancelable: true,
- });
- fireEvent(input, composingEscape);
- expect(composingEscape.defaultPrevented).toBe(true);
- expect(onClose).not.toHaveBeenCalled();
- expect(onOpenChange).not.toHaveBeenCalled();
- expect(document.activeElement).toBe(input);
- expect(getByRole('dialog').contains(input)).toBe(true);
-
- fireEvent.compositionEnd(input);
- fireEvent.keyDown(input, { key: 'Escape' });
- expect(onClose).toHaveBeenCalledOnce();
- expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false);
- });
-
- it('restores input before delayed teardown and preserves subsequently chosen focus', async () => {
- const editor = document.createElement('input');
- const nextTarget = document.createElement('input');
- document.body.append(editor, nextTarget);
- try {
- editor.focus();
- const { rerender, getByRole } = render(<DialogComponent open title="Validation"><button>OK</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));
- vi.useFakeTimers();
- await act(async () => {
- rerender(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);
- await Promise.resolve();
- });
- expect(document.activeElement).toBe(editor);
- nextTarget.focus();
- act(() => vi.runOnlyPendingTimers());
- expect(document.activeElement).toBe(nextTarget);
- } finally {
- if (vi.isFakeTimers()) {
- act(() => vi.runOnlyPendingTimers());
- vi.useRealTimers();
- }
- editor.remove();
- nextTarget.remove();
- }
- });
-
- it('honors a caller override instead of restoring the transient opener', async () => {
- const opener = document.createElement('button');
- const returnTarget = document.createElement('button');
- document.body.append(opener, returnTarget);
- const restoreFocus = (event: Event) => {
- event.preventDefault();
- returnTarget.focus();
- };
- try {
- opener.focus();
- const { rerender, getByRole } = render(<DialogComponent open title="Validation" onCloseAutoFocus={restoreFocus}><button>OK</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));
- rerender(<DialogComponent open={false} title="Validation" onCloseAutoFocus={restoreFocus}><button>OK</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(returnTarget));
- } finally {
- opener.remove();
- returnTarget.remove();
- }
- });
-
- it('returns focus through the parent modal before returning to the editor', async () => {
- const editor = document.createElement('input');
- document.body.appendChild(editor);
- try {
- editor.focus();
- const { rerender, getByRole } = render(
- <DialogComponent open title="Parent">
- <button>Parent action</button>
- <DialogComponent open={false} title="Child"><button>Child action</button></DialogComponent>
- </DialogComponent>
- );
- const parentAction = getByRole('button', { name: 'Parent action' });
- await waitFor(() => expect(document.activeElement).toBe(parentAction));
- rerender(
- <DialogComponent open title="Parent">
- <button>Parent action</button>
- <DialogComponent open title="Child"><button>Child action</button></DialogComponent>
- </DialogComponent>
- );
- await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'Child action' })));
- rerender(
- <DialogComponent open title="Parent">
- <button>Parent action</button>
- <DialogComponent open={false} title="Child"><button>Child action</button></DialogComponent>
- </DialogComponent>
- );
- await waitFor(() => expect(document.activeElement).toBe(parentAction));
- rerender(<DialogComponent open={false} title="Parent"><button>Parent action</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(editor));
- } finally {
- editor.remove();
- }
- });
-
- it('captures the current editor separately on each open', async () => {
- const first = document.createElement('input');
- const second = document.createElement('input');
- document.body.append(first, second);
- try {
- const { rerender, getByRole } = render(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);
- for (const editor of [first, second]) {
- editor.focus();
- rerender(<DialogComponent open title="Validation"><button>OK</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));
- rerender(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(editor));
- }
- } finally {
- first.remove();
- second.remove();
- }
- });
-
- it('does not focus a removed editor when closing', async () => {
- const editor = document.createElement('input');
- document.body.appendChild(editor);
- editor.focus();
- const { rerender, getByRole, queryByRole } = render(<DialogComponent open title="Validation"><button>OK</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));
- editor.remove();
- rerender(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);
- await waitFor(() => expect(queryByRole('dialog')).toBeNull());
- expect(document.activeElement).toBe(document.body);
- });
-
- it('returns focus to the editor after a programmatically opened modal closes', async () => {
- const editor = document.createElement('input');
- document.body.appendChild(editor);
- try {
- editor.focus();
- const { rerender, getByRole } = render(<DialogComponent open title="Validation"><button>OK</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(getByRole('button', { name: 'OK' })));
- rerender(<DialogComponent open={false} title="Validation"><button>OK</button></DialogComponent>);
- await waitFor(() => expect(document.activeElement).toBe(editor));
- } finally {
- editor.remove();
- }
- });
-});
diff --git a/packages/design/src/components/dialog/__tests__/logic.spec.tsx b/packages/design/src/components/dialog/__tests__/logic.spec.tsx
index 374cccd199..e2ee765f4d 100644
--- a/packages/design/src/components/dialog/__tests__/logic.spec.tsx
+++ b/packages/design/src/components/dialog/__tests__/logic.spec.tsx
@@ -38,7 +38,7 @@ vi.mock('../DialogPrimitive', async () => {
ref={ref}
role="dialog"
tabIndex={0}
- onKeyDown={(e) => onEscapeKeyDown?.(e.nativeEvent)}
+ onKeyDown={(e) => onEscapeKeyDown?.(e)}
onPointerDown={(e) => onPointerDownOutside?.(e)}
>
<button type="button" data-slot="close" onClick={onClickClose}>
@@ -108,29 +108,6 @@ describe('Dialog logic branches', () => {
expect(onClose).toHaveBeenCalled();
});
- it('should keep the dialog open when escape is used to cancel an IME composition', () => {
- const onOpenChange = vi.fn();
- const onClose = vi.fn();
-
- render(
- <Dialog open keyboard onOpenChange={onOpenChange} onClose={onClose}>
- content
- </Dialog>
- );
-
- const event = new KeyboardEvent('keydown', {
- bubbles: true,
- cancelable: true,
- isComposing: true,
- key: 'Escape',
- });
- screen.getByRole('dialog').dispatchEvent(event);
-
- expect(event.defaultPrevented).toBe(true);
- expect(onOpenChange).not.toHaveBeenCalled();
- expect(onClose).not.toHaveBeenCalled();
- });
-
it('should not close from pointer outside when maskClosable is false', () => {
const onOpenChange = vi.fn();
const onClose = vi.fn();
diff --git a/packages/design/src/components/dialog/use-dialog-focus.ts b/packages/design/src/components/dialog/use-dialog-focus.ts
deleted file mode 100644
index 9b16ba43a4..0000000000
--- a/packages/design/src/components/dialog/use-dialog-focus.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * 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 { useCallback, useRef } from 'react';
-
-export function useDialogFocus(mask: boolean, onCloseAutoFocus?: (event: Event) => void) {
- const returnFocusRef = useRef<HTMLElement | null>(null);
- const contentRef = useRef<HTMLDivElement | null>(null);
-
- const handleContentRef = useCallback((node: HTMLDivElement | null) => {
- const previousContent = contentRef.current;
- contentRef.current = node;
- if (!node && previousContent && mask && !onCloseAutoFocus) {
- // Restore input after DOM removal, before FocusScope's deferred unmount timer.
- Promise.resolve().then(() => {
- const returnFocus = returnFocusRef.current;
- if (!contentRef.current && !previousContent.isConnected && returnFocus?.isConnected &&
- returnFocus.ownerDocument.activeElement === returnFocus.ownerDocument.body) {
- returnFocus.focus({ preventScroll: true });
- }
- });
- }
- }, [mask, onCloseAutoFocus]);
-
- function handleOpenAutoFocus() {
- const activeElement = document.activeElement;
- returnFocusRef.current = activeElement instanceof HTMLElement ? activeElement : null;
- }
-
- function handleCloseAutoFocus(event: Event) {
- const returnFocus = returnFocusRef.current;
- returnFocusRef.current = null;
- onCloseAutoFocus?.(event);
- if (event.defaultPrevented) {
- return;
- }
- if (mask && returnFocus?.isConnected) {
- // Controlled dialogs have no Radix Trigger to receive focus on close.
- event.preventDefault();
- const activeElement = returnFocus.ownerDocument.activeElement;
- const focusInClosingDialog = event.target instanceof HTMLElement && event.target.contains(activeElement);
- if (activeElement === returnFocus.ownerDocument.body || activeElement === returnFocus || focusInClosingDialog) {
- returnFocus.focus({ preventScroll: true });
- }
- }
- }
-
- return { handleContentRef, handleOpenAutoFocus, handleCloseAutoFocus };
-}
diff --git a/packages/design/src/components/dropdown-menu/DropdownMenuPrimitive.tsx b/packages/design/src/components/dropdown-menu/DropdownMenuPrimitive.tsx
index 9f06bb33af..01b69f51c5 100644
--- a/packages/design/src/components/dropdown-menu/DropdownMenuPrimitive.tsx
+++ b/packages/design/src/components/dropdown-menu/DropdownMenuPrimitive.tsx
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { ComponentProps, PointerEvent } from 'react';
+import type { ComponentProps } from 'react';
import {
CheckboxItem,
Content,
@@ -33,18 +33,9 @@ import {
Trigger,
} from '@radix-ui/react-dropdown-menu';
import { CheckMarkIcon, MoreRightIcon } from '@univerjs/icons';
-import { useCallback, useRef } from 'react';
import { borderClassName, scrollbarClassName } from '../../helper/class-utilities';
import { clsx } from '../../helper/clsx';
-function handleMenuPointerEvent<T extends HTMLElement>(event: PointerEvent<T>, handler?: (event: PointerEvent<T>) => void) {
- if (event.currentTarget.closest('[data-radix-menu-content]')?.getAttribute('data-state') === 'closed') {
- event.preventDefault();
- return;
- }
- handler?.(event);
-}
-
function DropdownMenuPrimitive({
...props
}: ComponentProps<typeof Root>) {
@@ -120,8 +111,6 @@ function DropdownMenuSubTrigger({
className
)}
{...props}
- onPointerMove={(event) => handleMenuPointerEvent(event, props.onPointerMove)}
- onPointerLeave={(event) => handleMenuPointerEvent(event, props.onPointerLeave)}
>
{children}
<MoreRightIcon className="ml-auto" />
@@ -163,26 +152,8 @@ function DropdownMenuSubContent({
function DropdownMenuContent({
className,
sideOffset = 4,
- ref,
- onPointerDownOutside,
...props
}: ComponentProps<typeof Content>) {
- const contentRef = useRef<HTMLDivElement>(null);
- const setContentRef = useCallback((node: HTMLDivElement | null) => {
- contentRef.current = node;
- if (typeof ref === 'function') {
- const cleanup = ref(node);
- if (typeof cleanup === 'function') {
- return () => {
- contentRef.current = null;
- cleanup();
- };
- }
- } else if (ref) {
- ref.current = node;
- }
- }, [ref]);
-
return (
<Portal>
<Content
@@ -208,17 +179,6 @@ function DropdownMenuContent({
className
)}
{...props}
- ref={setContentRef}
- onPointerDownOutside={(event) => {
- onPointerDownOutside?.(event);
- const content = contentRef.current;
- const triggerId = content?.getAttribute('aria-labelledby');
- const trigger = triggerId ? content?.ownerDocument.getElementById(triggerId) : null;
- if (trigger?.contains(event.detail.originalEvent.target as Node)) {
- // The trigger already toggles this menu, including while its exit animation is running.
- event.preventDefault();
- }
- }}
/>
</Portal>
);
@@ -255,8 +215,6 @@ function DropdownMenuItem({
className
)}
{...props}
- onPointerMove={(event) => handleMenuPointerEvent(event, props.onPointerMove)}
- onPointerLeave={(event) => handleMenuPointerEvent(event, props.onPointerLeave)}
/>
);
}
@@ -287,8 +245,6 @@ function DropdownMenuCheckboxItem({
)}
checked={checked}
{...props}
- onPointerMove={(event) => handleMenuPointerEvent(event, props.onPointerMove)}
- onPointerLeave={(event) => handleMenuPointerEvent(event, props.onPointerLeave)}
>
{!hideIndicator && (
<span
@@ -333,8 +289,6 @@ function DropdownMenuRadioItem({
className
)}
{...props}
- onPointerMove={(event) => handleMenuPointerEvent(event, props.onPointerMove)}
- onPointerLeave={(event) => handleMenuPointerEvent(event, props.onPointerLeave)}
>
{!hideIndicator && (
<span
diff --git a/packages/design/src/components/dropdown-menu/__tests__/DropdownMenuPrimitive.spec.tsx b/packages/design/src/components/dropdown-menu/__tests__/DropdownMenuPrimitive.spec.tsx
deleted file mode 100644
index 81519fc8f0..0000000000
--- a/packages/design/src/components/dropdown-menu/__tests__/DropdownMenuPrimitive.spec.tsx
+++ /dev/null
@@ -1,177 +0,0 @@
-/**
- * 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 { Content, Portal } from '@radix-ui/react-dropdown-menu';
-import { act, cleanup, createEvent, fireEvent, render, screen } from '@testing-library/react';
-import { createRef } from 'react';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuPrimitive, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSub, DropdownMenuSubTrigger, DropdownMenuTrigger } from '../DropdownMenuPrimitive';
-import '@testing-library/jest-dom/vitest';
-
-afterEach(cleanup);
-
-describe('dropdown trigger ownership', () => {
- it('reopens on its trigger before the closing animation finishes', async () => {
- const getComputedStyle = window.getComputedStyle.bind(window);
- const styleSpy = vi.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudoElement) => {
- const styles = getComputedStyle(element, pseudoElement);
- if (element.getAttribute('data-slot') !== 'dropdown-menu-content') {
- return styles;
- }
- // Presence needs the browser's live animation style, which the test DOM does not animate.
- return new Proxy(styles, {
- get(target, property) {
- if (property === 'animationName') {
- return element.getAttribute('data-state') === 'closed' ? 'menu-exit' : 'none';
- }
- return Reflect.get(target, property);
- },
- });
- });
- try {
- render(
- <DropdownMenuPrimitive defaultOpen modal={false}>
- <DropdownMenuTrigger>Open</DropdownMenuTrigger>
- <DropdownMenuContent><DropdownMenuItem>Action</DropdownMenuItem></DropdownMenuContent>
- </DropdownMenuPrimitive>
- );
- const trigger = screen.getByRole('button', { name: 'Open' });
- for (const open of [false, true]) {
- await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
- const event = createEvent.pointerDown(trigger, { bubbles: true, cancelable: true });
- Object.defineProperties(event, { button: { value: 0 }, pointerType: { value: 'mouse' }, ctrlKey: { value: false } });
- fireEvent(trigger, event);
- expect(trigger).toHaveAttribute('aria-expanded', String(open));
- expect(screen.getByText('Action').closest('[data-radix-menu-content]')).toHaveAttribute('data-state', open ? 'open' : 'closed');
- }
- } finally {
- cleanup();
- styleSpy.mockRestore();
- }
- });
-
- it('opens and closes on its own trigger', async () => {
- render(
- <DropdownMenuPrimitive modal={false}>
- <DropdownMenuTrigger><span>Open</span></DropdownMenuTrigger>
- <DropdownMenuContent>
- <DropdownMenuItem>Action</DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenuPrimitive>
- );
- // DismissableLayer installs its document pointer listener on the next task.
- await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
- const event = createEvent.pointerDown(screen.getByText('Open'), { bubbles: true, cancelable: true });
- Object.defineProperties(event, { button: { value: 0 }, pointerType: { value: 'mouse' }, ctrlKey: { value: false } });
- fireEvent(screen.getByText('Open'), event);
- expect(screen.getByRole('button', { name: 'Open' })).toHaveAttribute('aria-expanded', 'true');
- await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
- const closeEvent = createEvent.pointerDown(screen.getByText('Open'), { bubbles: true, cancelable: true });
- Object.defineProperties(closeEvent, { button: { value: 0 }, pointerType: { value: 'mouse' }, ctrlKey: { value: false } });
- fireEvent(screen.getByText('Open'), closeEvent);
- expect(screen.getByRole('button', { name: 'Open' })).toHaveAttribute('aria-expanded', 'false');
- });
-
- it('closes for another trigger or outside target and preserves the outside callback', async () => {
- const onOutside = vi.fn();
- render(
- <>
- <button>Outside</button>
- {['First', 'Second'].map((name) => (
- <DropdownMenuPrimitive key={name} modal={false}>
- <DropdownMenuTrigger>{name}</DropdownMenuTrigger>
- <DropdownMenuContent onPointerDownOutside={onOutside}>
- <DropdownMenuItem>
- {name}
- {' '}
- action
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenuPrimitive>
- ))}
- </>
- );
- await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
- for (const name of ['First', 'Second', 'Outside']) {
- const button = screen.getByRole('button', { name });
- const event = createEvent.pointerDown(button, { bubbles: true, cancelable: true });
- Object.defineProperties(event, { button: { value: 0 }, pointerType: { value: 'mouse' }, ctrlKey: { value: false } });
- fireEvent(button, event);
- await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
- expect(screen.getByRole('button', { name: 'First' })).toHaveAttribute('aria-expanded', String(name === 'First'));
- expect(screen.getByRole('button', { name: 'Second' })).toHaveAttribute('aria-expanded', String(name === 'Second'));
- }
- expect(onOutside).toHaveBeenCalled();
- });
-
- it('forwards the mounted content and clears an object ref on unmount', () => {
- const ref = createRef<HTMLDivElement>();
- const { unmount } = render(
- <DropdownMenuPrimitive defaultOpen modal={false}>
- <DropdownMenuTrigger>Open</DropdownMenuTrigger>
- <DropdownMenuContent ref={ref}><DropdownMenuItem>Action</DropdownMenuItem></DropdownMenuContent>
- </DropdownMenuPrimitive>
- );
- expect(ref.current).toBe(screen.getByRole('menu'));
- unmount();
- expect(ref.current).toBeNull();
- });
-
- it('preserves callback ref cleanup', () => {
- const cleanupRef = vi.fn();
- const ref = vi.fn(() => cleanupRef);
- const { unmount } = render(
- <DropdownMenuPrimitive defaultOpen modal={false}>
- <DropdownMenuTrigger>Open</DropdownMenuTrigger>
- <DropdownMenuContent ref={ref}><DropdownMenuItem>Action</DropdownMenuItem></DropdownMenuContent>
- </DropdownMenuPrimitive>
- );
- expect(ref).toHaveBeenCalledWith(screen.getByRole('menu'));
- unmount();
- expect(cleanupRef).toHaveBeenCalledOnce();
- });
-});
-
-describe.each([
- ['normal', <DropdownMenuItem key="normal">Action</DropdownMenuItem>],
- ['checkbox', <DropdownMenuCheckboxItem key="checkbox">Action</DropdownMenuCheckboxItem>],
- ['radio', <DropdownMenuRadioGroup key="radio" value="a"><DropdownMenuRadioItem value="a">Action</DropdownMenuRadioItem></DropdownMenuRadioGroup>],
- ['submenu', <DropdownMenuSub key="submenu"><DropdownMenuSubTrigger>Action</DropdownMenuSubTrigger></DropdownMenuSub>],
-])('closed %s dropdown pointer ownership', (_name, content) => {
- it.each(['pointerMove', 'pointerOut'] as const)('does not reclaim focus on %s while retained for exit', (eventType) => {
- render(
- <>
- <input aria-label="External" />
- <DropdownMenuPrimitive open={false} modal={false}>
- <DropdownMenuTrigger>Open</DropdownMenuTrigger>
- <Portal forceMount>
- <Content forceMount>
- {content}
- </Content>
- </Portal>
- </DropdownMenuPrimitive>
- </>
- );
- const external = screen.getByRole('textbox');
- const item = screen.getByText('Action');
- expect(item.closest('[data-radix-menu-content]')).toHaveAttribute('data-state', 'closed');
- external.focus();
- const event = createEvent[eventType](item, { bubbles: true, cancelable: true, relatedTarget: external });
- Object.defineProperty(event, 'pointerType', { value: 'mouse' });
- fireEvent(item, event);
- expect(external).toHaveFocus();
- });
-});
diff --git a/packages/design/src/components/tooltip/__tests__/index.spec.tsx b/packages/design/src/components/tooltip/__tests__/index.spec.tsx
index 070bf6c052..574730c874 100644
--- a/packages/design/src/components/tooltip/__tests__/index.spec.tsx
+++ b/packages/design/src/components/tooltip/__tests__/index.spec.tsx
@@ -187,27 +187,6 @@ describe('Tooltip', () => {
});
});
- it('allows callers to make tooltip content pointer-transparent through className', async () => {
- render(
- <Tooltip title="pass-through-tip">
- interactive-trigger
- </Tooltip>
- );
- fireEvent.mouseEnter(screen.getByText('interactive-trigger'));
- expect(await screen.findByRole('tooltip')).toHaveClass('univer-pointer-events-auto');
-
- cleanup();
- render(
- <Tooltip title="pass-through-tip" className="univer-pointer-events-none">
- pass-through-trigger
- </Tooltip>
- );
- fireEvent.mouseEnter(screen.getByText('pass-through-trigger'));
- const tooltip = await screen.findByRole('tooltip');
- expect(tooltip).toHaveClass('univer-pointer-events-none');
- expect(tooltip).not.toHaveClass('univer-pointer-events-auto');
- });
-
it('should execute left-placement recompute branch on scroll', async () => {
vi.restoreAllMocks();
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function getRect(this: HTMLElement) {
diff --git a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
index 815d128c84..4662259e12 100644
--- a/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
+++ b/packages/docs-ui/src/controllers/render-controllers/__tests__/doc.render-controller.spec.ts
@@ -71,6 +71,11 @@ import { DocSelectionRenderController } from '../doc-selection-render.controller
import { DocRenderController } from '../doc.render-controller';
function createEditor(paragraphCount = 8, withDrawing = true, workerBeforeLayout = false, documentFlavor = DocumentFlavor.TRADITIONAL, withFootnote = false) {
+ if (workerBeforeLayout) {
+ // Model computation cost separately from fake timers so foreground work yields before Worker handoff.
+ let elapsed = 0;
+ vi.spyOn(performance, 'now').mockImplementation(() => ++elapsed);
+ }
const univer = new Univer();
const injector = univer.__getInjector();
const root = document.createElement('div');
@@ -231,6 +236,19 @@ describe('DocRenderController bounded input publication', () => {
}),
}, { get: (target, key) => key in target ? Reflect.get(target, key) : () => {} });
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);
+ const getBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {
+ // Match the fixture's 14pt Canvas metrics; jsdom returns zero and cannot cache normal leading.
+ if (this.style.visibility === 'hidden' && this.style.whiteSpace === 'pre' && this.style.lineHeight === 'normal') {
+ const fontSize = Number.parseFloat(this.style.fontSize);
+ const pointsPerUnit = this.style.fontSize.endsWith('px') ? 3 / 4 : 1;
+ const lineCount = (this.textContent ?? '').split('\n').length;
+ const metrics = context.measureText('Hg');
+ const lineHeight = metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent;
+ return new DOMRect(0, 0, 0, fontSize * pointsPerUnit / 14 * lineHeight * lineCount);
+ }
+ return getBoundingClientRect.call(this);
+ });
});
afterEach(() => {
vi.restoreAllMocks();
@@ -325,10 +343,14 @@ describe('DocRenderController bounded input publication', () => {
window.setTimeout(() => callback({ didTimeout: false, timeRemaining: () => 10 }), 0));
vi.stubGlobal('cancelIdleCallback', (id: number) => window.clearTimeout(id));
const editor = createEditor(paragraphCount, false, true);
+ const layoutSteps = vi.spyOn(editor.skeleton, 'stepIncrementalLayout');
try {
await vi.advanceTimersByTimeAsync(1_000);
expect(editor.startWorkerLayout).toHaveBeenCalledTimes(paragraphCount === 1 ? 0 : 1);
expect(editor.skeleton.hasCompleteLayout()).toBe(paragraphCount === 1);
+ if (paragraphCount > 1) {
+ expect(layoutSteps.mock.results[0].value.processedBlockCount).toBeLessThan(paragraphCount);
+ }
const pages = editor.skeleton.getSkeletonData()!.pages;
expect(pages.length).toBeGreaterThan(0);
expect(pages.length).toBeLessThanOrEqual(5);
diff --git a/packages/ui/src/views/components/dialog-part/DialogPart.tsx b/packages/ui/src/views/components/dialog-part/DialogPart.tsx
index ef5cd4a1ab..fad5695fdc 100644
--- a/packages/ui/src/views/components/dialog-part/DialogPart.tsx
+++ b/packages/ui/src/views/components/dialog-part/DialogPart.tsx
@@ -17,11 +17,70 @@
import type { IDialogProps } from '@univerjs/design';
import type { IDialogPartMethodOptions } from './interface';
import { Dialog } from '@univerjs/design';
-import { useMemo } from 'react';
+import { useCallback, useLayoutEffect, useMemo, useRef } from 'react';
import { IDialogService } from '../../../services/dialog/dialog.service';
import { useDependency, useObservable } from '../../../utils/di';
+import { getEmbedBoundaryOwner } from '../../../utils/embed-boundary';
import { CustomLabel } from '../../custom-label/CustomLabel';
+function DialogItem(props: IDialogProps) {
+ const dialogRef = useRef<Element | null>(null);
+ const openRef = useRef(false);
+ const handleContentRef = useCallback((node: HTMLDivElement | null) => {
+ if (node) {
+ dialogRef.current = node.closest('[role="dialog"]');
+ }
+ }, []);
+
+ useLayoutEffect(() => {
+ openRef.current = !!props.open;
+ if (!props.open) {
+ return;
+ }
+ // Capture before the portal mounts and its focus scope moves focus into the dialog.
+ const ownerDocument = document;
+ const opener = ownerDocument.activeElement;
+ const owner = getEmbedBoundaryOwner(opener);
+ const ownerWindow = ownerDocument?.defaultView;
+ const handleCompositionEscape = (event: KeyboardEvent) => {
+ if (event.key === 'Escape' && event.isComposing &&
+ event.target instanceof Element && event.target.closest('[role="dialog"]') === dialogRef.current) {
+ // The candidate window owns Escape before the dialog's document-level listener sees it.
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ };
+ ownerWindow?.addEventListener('keydown', handleCompositionEscape, true);
+ return () => {
+ openRef.current = false;
+ const content = dialogRef.current;
+ ownerWindow?.removeEventListener('keydown', handleCompositionEscape, true);
+ if (props.mask === false) {
+ return;
+ }
+ queueMicrotask(() => {
+ if (openRef.current) {
+ return;
+ }
+ if (dialogRef.current === content) {
+ dialogRef.current = null;
+ }
+ const active = ownerDocument?.activeElement;
+ if (opener instanceof HTMLElement && opener.isConnected && getEmbedBoundaryOwner(opener) === owner &&
+ (active === ownerDocument?.body || (active && content?.contains(active)))) {
+ opener.focus({ preventScroll: true });
+ }
+ });
+ };
+ }, [props.open, props.mask]);
+
+ return (
+ <Dialog {...props}>
+ <div ref={handleContentRef} className="univer-contents">{props.children}</div>
+ </Dialog>
+ );
+}
+
export function DialogPart() {
const dialogService = useDependency(IDialogService);
@@ -46,6 +105,6 @@ export function DialogPart() {
}), [dialogOptions]);
return attrs?.map((options) => (
- <Dialog key={options.id} {...options} />
+ <DialogItem key={options.id} {...options} />
));
}
diff --git a/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx b/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx
index 5c24a716a2..d914c80ff5 100644
--- a/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx
+++ b/packages/ui/src/views/components/dialog-part/__tests__/DialogPart.spec.tsx
@@ -16,10 +16,11 @@
import type { ReactElement } from 'react';
import type { IDialogPartMethodOptions } from '../interface';
-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
-import { DesktopLogService, ILogService, Injector, LocaleService } from '@univerjs/core';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { DesktopLogService, ILogService, Injector, LocaleService, LocaleType } from '@univerjs/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { ComponentManager, IconManager } from '../../../../common';
+import { ComponentManager } from '../../../../common/component-manager';
+import { IconManager } from '../../../../common/icon-manager';
import { DesktopDialogService } from '../../../../services/dialog/desktop-dialog.service';
import { IDialogService } from '../../../../services/dialog/dialog.service';
import { IUIPartsService, UIPartsService } from '../../../../services/parts/parts.service';
@@ -36,6 +37,10 @@ function renderWithDependencies(element: ReactElement) {
injector.add([LocaleService]);
injector.add([ComponentManager]);
injector.add([IconManager]);
+ const localeService = injector.get(LocaleService);
+ localeService.load({ [LocaleType.EN_US]: {} });
+ localeService.setLocale(LocaleType.EN_US);
+ localeService.setDirection('ltr');
const result = render(
<RediProvider value={{ injector }}>
@@ -49,6 +54,7 @@ function renderWithDependencies(element: ReactElement) {
dispose: () => {
result.unmount();
cleanup();
+ injector.dispose();
},
};
}
@@ -59,6 +65,60 @@ describe('DialogPart', () => {
cleanup();
});
+ it.each([false, true])('restores the caller after close without stealing a newer focus (%s)', async (moveFocus) => {
+ const editor = document.createElement('input');
+ const nextEditor = document.createElement('input');
+ document.body.append(editor, nextEditor);
+ const rendered = renderWithDependencies(<DialogPart />);
+ try {
+ const dialogService = rendered.injector.get(IDialogService);
+ for (const opener of [editor, nextEditor]) {
+ opener.focus();
+ act(() => dialogService.open({
+ id: 'editing',
+ title: { title: 'Editing' },
+ children: { title: <input aria-label="Dialog draft" /> },
+ }));
+ await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'Dialog draft' })));
+ const newTarget = opener === editor ? nextEditor : editor;
+ act(() => {
+ dialogService.close('editing');
+ });
+ if (moveFocus) {
+ newTarget.focus();
+ }
+ await waitFor(() => expect(document.activeElement).toBe(moveFocus ? newTarget : opener));
+ }
+ } finally {
+ rendered.dispose();
+ editor.remove();
+ nextEditor.remove();
+ }
+ });
+
+ it('leaves composing Escape to the candidate window, then closes on ordinary Escape', async () => {
+ const rendered = renderWithDependencies(<DialogPart />);
+ try {
+ const dialogService = rendered.injector.get(IDialogService);
+ const onClose = vi.fn(() => dialogService.close('editing'));
+ act(() => dialogService.open({
+ id: 'editing',
+ title: { title: 'Editing' },
+ children: { title: <input aria-label="Dialog draft" /> },
+ onClose,
+ }));
+ const input = screen.getByRole('textbox', { name: 'Dialog draft' });
+ fireEvent.keyDown(input, { key: 'Escape', isComposing: true });
+ expect(onClose).not.toHaveBeenCalled();
+ expect(screen.getByRole('dialog').contains(input)).toBe(true);
+ fireEvent.keyDown(input, { key: 'Escape' });
+ expect(onClose).toHaveBeenCalledOnce();
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ } finally {
+ rendered.dispose();
+ }
+ });
+
it('renders service-opened dialog labels and clears the requested dialog when service closes it', async () => {
const rendered = renderWithDependencies(<DialogPart />);
const dialogService = rendered.injector.get(IDialogService);
diff --git a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
index 931ee6f982..28469145ab 100644
--- a/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
+++ b/packages/ui/src/views/components/ribbon/TooltipButtonWrapper.tsx
@@ -297,6 +297,7 @@ export function DropdownMenuWrapper({
const instanceService = useDependency(IUniverInstanceService);
const layoutService = useDependency(ILayoutService);
const editorFocusRef = useRef<{ element: HTMLElement; owner?: string } | null>(null);
+ const menuContentRef = useRef<HTMLElement | null>(null);
const sheetTargetRef = useRef<{ unitId: string; sheetId: string; valid: boolean } | null>(null);
const sheetTarget = sheetTargetRef.current;
@@ -425,12 +426,32 @@ export function DropdownMenuWrapper({
editorFocus.element.focus({ preventScroll: true });
}
- function handlePointerDownOutside(event: { currentTarget: EventTarget | null; target: EventTarget | null; preventDefault: () => void }) {
+ const handleMenuFocus: NonNullable<IDropdownMenuProps['onFocusCapture']> = (event) => {
+ menuContentRef.current = event.currentTarget;
+ };
+
+ const handleClosedMenuPointer: NonNullable<IDropdownMenuProps['onPointerMoveCapture']> = (event) => {
+ if (event.currentTarget.dataset.state === 'closed') {
+ // Exit-animation DOM must not take focus back from the editor or a newly opened menu.
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ };
+
+ const handlePointerDownOutside: NonNullable<IDropdownMenuProps['onPointerDownOutside']> = (event) => {
+ const content = menuContentRef.current;
+ const triggerId = content?.getAttribute('aria-labelledby');
+ const trigger = triggerId ? content?.ownerDocument.getElementById(triggerId) : null;
+ if (trigger?.contains(event.detail.originalEvent.target as Node)) {
+ // The Ribbon trigger owns toggling, including when the previous menu is still exiting.
+ event.preventDefault();
+ return;
+ }
if (editorFocusRef.current && (!editorFocusRef.current.owner || getEmbedBoundaryOwner(event.target) !== editorFocusRef.current.owner)) {
editorFocusRef.current = null;
}
keepInteractionInsideSameEmbedBoundary(event);
- }
+ };
function handleEmbedBoundaryFocusOutside(event: { currentTarget: EventTarget | null; target: EventTarget | null; preventDefault: () => void }) {
keepInteractionInsideSameEmbedBoundary(event);
@@ -554,6 +575,9 @@ export function DropdownMenuWrapper({
disabled={disabled}
open={dropdownVisible}
onOpenChange={handleVisibleChange}
+ onFocusCapture={handleMenuFocus}
+ onPointerMoveCapture={handleClosedMenuPointer}
+ onPointerOutCapture={handleClosedMenuPointer}
onCloseAutoFocus={handleCloseAutoFocus}
onPointerDownOutside={handlePointerDownOutside}
onFocusOutside={handleEmbedBoundaryFocusOutside}
@@ -607,6 +631,9 @@ export function DropdownMenuWrapper({
disabled={disabled}
open={dropdownVisible}
onOpenChange={handleVisibleChange}
+ onFocusCapture={handleMenuFocus}
+ onPointerMoveCapture={handleClosedMenuPointer}
+ onPointerOutCapture={handleClosedMenuPointer}
onCloseAutoFocus={handleCloseAutoFocus}
onPointerDownOutside={handlePointerDownOutside}
onFocusOutside={handleEmbedBoundaryFocusOutside}
diff --git a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
index eb3983760a..005c637a29 100644
--- a/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
+++ b/packages/ui/src/views/components/ribbon/__tests__/TooltipButtonWrapper.spec.tsx
@@ -19,7 +19,7 @@
*/
import type { ComponentType, ReactElement } from 'react';
-import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/react';
+import { act, cleanup, createEvent, fireEvent, render, waitFor } from '@testing-library/react';
import {
CommandService,
ConfigService,
@@ -148,6 +148,58 @@ describe('ToolbarTooltip', () => {
});
describe('DropdownMenuLabel', () => {
+ it('keeps Ribbon trigger toggling and closed-menu pointer focus separate during exit', async () => {
+ const getComputedStyle = window.getComputedStyle.bind(window);
+ const styleSpy = vi.spyOn(window, 'getComputedStyle').mockImplementation((element, pseudoElement) => {
+ const styles = getComputedStyle(element, pseudoElement);
+ if (element.getAttribute('data-slot') !== 'dropdown-menu-content') {
+ return styles;
+ }
+ // jsdom does not animate; keep the real Presence exit lifecycle alive.
+ return new Proxy(styles, {
+ get(target, property) {
+ if (property === 'animationName') {
+ return element.getAttribute('data-state') === 'closed' ? 'menu-exit' : 'none';
+ }
+ return Reflect.get(target, property);
+ },
+ });
+ });
+ try {
+ const { getByRole, getByText } = renderWithDependencies(
+ <>
+ <input aria-label="Next editor" />
+ <TooltipWrapper dropdownKey="exit-menu">
+ <DropdownMenuWrapper menuId="test-menu" options={[{ label: 'Center', value: 'center' }]} onOptionSelect={vi.fn()}>
+ <button type="button">Align</button>
+ </DropdownMenuWrapper>
+ </TooltipWrapper>
+ </>
+ );
+ const trigger = getByRole('button', { name: 'Align' });
+ for (const open of [true, false, true, false]) {
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
+ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' });
+ expect(trigger.getAttribute('aria-expanded')).toBe(String(open));
+ const item = getByText('Center');
+ expect(item.closest('[data-radix-menu-content]')?.getAttribute('data-state')).toBe(open ? 'open' : 'closed');
+ if (!open) {
+ const editor = getByRole('textbox', { name: 'Next editor' });
+ editor.focus();
+ for (const type of ['pointerMove', 'pointerOut'] as const) {
+ const event = createEvent[type](item, { bubbles: true, cancelable: true, relatedTarget: editor });
+ Object.defineProperty(event, 'pointerType', { value: 'mouse' });
+ fireEvent(item, event);
+ expect(document.activeElement).toBe(editor);
+ }
+ }
+ }
+ } finally {
+ cleanup();
+ styleSpy.mockRestore();
+ }
+ });
+
it('preserves option metadata when a custom label emits a dynamic value', () => {
const onOptionSelect = vi.fn();
const params = (value?: string | number) => ({ value });