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(sheets): preserve menu input selection and apply values on Enter (#8152)

白熱d6e0c32ed485
diff --git a/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx b/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx
index 6e5ba678b0..214a894836 100644
--- a/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx
+++ b/packages/sheets-ui/src/views/menu-item-input/MenuItemInput.tsx
@@ -67,14 +67,8 @@ export const MenuItemInput = (props: IMenuItemInputProps) => {
}
}, [value]);
- function handlePressEnter() {
- if (inputValue) {
- onChange(inputValue);
- }
- }
-
function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
- if (event.key === 'Escape' && !event.nativeEvent.isComposing && !composingRef.current) {
+ if ((event.key === 'Escape' || event.key === 'Enter') && !event.nativeEvent.isComposing && !composingRef.current) {
return;
}
event.stopPropagation();
@@ -117,7 +111,6 @@ export const MenuItemInput = (props: IMenuItemInputProps) => {
min={min}
max={max}
disabled={disabled}
- onPressEnter={handlePressEnter}
onKeyDown={handleKeyDown}
onChange={handleChange}
/>
diff --git a/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx b/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx
index 0d6929243f..07a2464c5c 100644
--- a/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx
+++ b/packages/sheets-ui/src/views/menu-item-input/__tests__/MenuItemInput.spec.tsx
@@ -150,11 +150,15 @@ describe('MenuItemInput', () => {
});
it.each([
- ['column', '0'],
- ['row', '0'],
- ['column', ''],
- ['row', ''],
- ])('applies zero %s size from input %j through the real context menu and supports undo/redo', async (axis, text) => {
+ ['column', '0', 'click', 0],
+ ['row', '0', 'click', 0],
+ ['column', '', 'Enter', 0],
+ ['row', '', 'Enter', 0],
+ ['column', '240', 'Enter', 240],
+ ['row', '64', 'Enter', 64],
+ ['column', '2000', 'Enter', 1000],
+ ['column', '240', 'IME', 240],
+ ] as const)('applies %s size from input %j with %s through the real context menu and supports undo/redo', async (axis, text, confirmation, expectedSize) => {
const testBed = createCommandTestBed(undefined, [[SheetSkeletonService]]);
const injector = testBed.univer.__getInjector();
const commands = injector.get(ICommandService);
@@ -224,40 +228,34 @@ describe('MenuItemInput', () => {
act(() => input.focus());
act(() => input.select());
act(() => setInputText(input, text));
- expect(input.value).toBe('0');
+ expect(input.value).toBe(String(expectedSize));
const button = input.closest('button');
if (!(button instanceof HTMLButtonElement)) {
throw new TypeError('Dimension menu item not found');
}
- act(() => button.focus());
- act(() => button.click());
+ if (confirmation === 'click') {
+ act(() => button.focus());
+ act(() => button.click());
+ } else {
+ if (confirmation === 'IME') {
+ act(() => {
+ input.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, isComposing: true }));
+ input.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true }));
+ input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
+ });
+ expect(executions).toEqual([]);
+ expect(getSize()).toBe(original);
+ await act(async () => new Promise((resolve) => setTimeout(resolve, 0)));
+ }
+ act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })));
+ }
expect(await Promise.all(executions)).toEqual([true]);
- expect(getSize()).toBe(0);
+ expect(getSize()).toBe(expectedSize);
await commands.executeCommand(UndoCommand.id);
expect(getSize()).toBe(original);
await commands.executeCommand(RedoCommand.id);
- expect(getSize()).toBe(0);
- });
-
- it('reports zero immediately when the configured minimum allows collapsed dimensions', () => {
- const { container, unmount } = renderWithDependencies(
- <MenuItemInput
- prefix="sheets-ui.rightClick.rowHeight"
- suffix="px"
- value="24"
- min={0}
- max={1000}
- onChange={(value) => ChangeRecords.push(value)}
- />
- );
- disposals.push(unmount);
-
- act(() => {
- setInputText(getInput(container), '0');
- });
-
- expect(getInput(container).value).toBe('0');
- expect(ChangeRecords.values).toEqual(['0']);
+ expect(getSize()).toBe(expectedSize);
});
it('reports the positive minimum when the input is cleared', () => {
@@ -373,7 +371,7 @@ describe('MenuItemInput', () => {
);
disposals.push(unmount);
const input = getInput(container);
- for (const key of ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'Backspace', 'Delete', 'Enter']) {
+ for (const key of ['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'Backspace', 'Delete']) {
act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })));
}
for (const modifier of [{ ctrlKey: true }, { metaKey: true }]) {
diff --git a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
index a511771ae5..9f1481ef12 100644
--- a/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
+++ b/packages/ui/src/views/components/context-menu/ContextMenuPanel.tsx
@@ -778,7 +778,7 @@ export function ContextMenuPanel(props: IContextMenuPanelProps) {
event.preventDefault();
event.stopPropagation();
- const activeIndex = focusableButtons.findIndex((button) => button === activeElement);
+ const activeIndex = focusableButtons.findIndex((button) => button.contains(activeElement ?? null));
if (event.key === 'Enter') {
const button = activeIndex >= 0 ? focusableButtons[activeIndex] : getFirstMenuButtonByVisualOrder(focusableButtons);
@@ -1164,6 +1164,7 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
const [keyboardSubmenuFocusRequested, setKeyboardSubmenuFocusRequested] = useState(false);
const menuItemElementRef = useRef<HTMLDivElement | null>(null);
const menuButtonRef = useRef<HTMLButtonElement | null>(null);
+ const mouseDownOnInputRef = useRef(false);
const submenuElementRef = useRef<HTMLDivElement | null>(null);
const submenuCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pendingHoverActionRef = useRef<(() => void) | null>(null);
@@ -1447,6 +1448,9 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
aria-haspopup={hasSubmenu ? 'menu' : undefined}
aria-expanded={hasSubmenu ? submenuVisible : undefined}
aria-controls={hasSubmenu ? submenuId : undefined}
+ onMouseDownCapture={(event) => {
+ mouseDownOnInputRef.current = event.target instanceof HTMLInputElement;
+ }}
onKeyDown={(event) => {
const openDirection = direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight';
if (!hasSubmenu || event.key !== openDirection) {
@@ -1461,6 +1465,10 @@ function ContextMenuMenuItem(props: IContextMenuMenuItemProps) {
setActiveSubmenuKey(menuKey);
}}
onClick={(event) => {
+ // Text selection can end outside the input and dispatch a click on this button.
+ if (event.detail > 0 && mouseDownOnInputRef.current) {
+ return;
+ }
pointerGraceRef.current?.cancel();
clearSubmenuCloseTimer();
if (hasSubmenu) {
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 6ba58d82b5..585345848c 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
@@ -32,7 +32,7 @@ import {
import { RediContext } from '@wendellhu/redi/react-bindings';
import { BehaviorSubject } from 'rxjs';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import type { IValueOption } from '../../../../services/menu/menu';
+import type { ICustomComponentProps, IValueOption } from '../../../../services/menu/menu';
import type { IMenuSchema, MenuSchemaType } from '../../../../services/menu/menu-manager.service';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
@@ -44,7 +44,6 @@ import {
CONTEXT_MENU_SUBMENU_CLOSE_DELAY,
CONTEXT_MENU_SUBMENU_PORTAL_ATTR,
ContextMenuPanel,
- getContextMenuQuickGroupColumns,
getContextMenuSchemaRenderGroups,
getNextMenuButtonByDirection,
shouldShowContextMenuGroupSeparator,
@@ -160,6 +159,10 @@ async function nextFrame() {
});
}
+function TestMenuInput({ value, onChange }: ICustomComponentProps<string>) {
+ return <input aria-label="Size" value={value} onChange={(event) => onChange(event.target.value)} />;
+}
+
describe('ContextMenuPanel', () => {
afterEach(() => {
cleanup();
@@ -246,7 +249,6 @@ describe('ContextMenuPanel', () => {
menuSchemas: [schemas[2]],
},
]);
- expect(getContextMenuQuickGroupColumns(schemas[0])).toBe(6);
});
it('renders paragraph quick menus with real tiny groups and submits the clicked command', () => {
@@ -425,6 +427,50 @@ describe('ContextMenuPanel', () => {
expect(TestState.cancels).toBe(1);
});
+ it.each(['Enter', 'label click'])('confirms the edited menu item with %s after selecting text across its input boundary', (confirmation) => {
+ renderWithDependencies(
+ <ContextMenuPanel
+ menuType="input-menu"
+ onOptionSelect={(option) => TestState.selectedOptions.push(option)}
+ />,
+ {
+ 'input-menu': [
+ createButtonItem('first-action', { title: 'First action' }),
+ {
+ key: 'set-size',
+ order: 1,
+ item: {
+ id: 'set-size',
+ type: MenuItemType.BUTTON,
+ title: 'Apply size',
+ label: 'test-menu-input',
+ value$: new BehaviorSubject('100'),
+ },
+ },
+ ],
+ },
+ (injector) => injector.get(ComponentManager).register('test-menu-input', TestMenuInput)
+ );
+ const input = screen.getByRole('textbox', { name: 'Size' });
+ const label = screen.getByText('Apply size');
+ input.focus();
+ fireEvent.change(input, { target: { value: '240' } });
+ fireEvent.mouseDown(input);
+ fireEvent.mouseUp(label);
+ // A browser targets the common ancestor when a text-selection drag ends outside the input.
+ fireEvent.click(input.closest('button')!, { detail: 1 });
+ expect(TestState.selectedOptions).toEqual([]);
+
+ if (confirmation === 'Enter') {
+ fireEvent.keyDown(input, { key: 'Enter' });
+ } else {
+ fireEvent.mouseDown(label);
+ fireEvent.mouseUp(label);
+ fireEvent.click(label, { detail: 1 });
+ }
+ expect(TestState.selectedOptions).toEqual([expect.objectContaining({ id: 'set-size', value: 240 })]);
+ });
+
it.each(['ltr', 'rtl'] as const)('enters, navigates, and exits a submenu with arrow keys in %s', async (direction) => {
renderWithDependencies(<ContextMenuPanel menuType="root" />, {
root: [