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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(ui): restore keyboard access to buttons and advanced find (#8113)
白熱e8cc1082d825
diff --git a/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx b/packages/find-replace/src/views/dialog/FindReplaceDialog.tsxindex 16be8d70d7..af5b27f8eb 100644--- a/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx+++ b/packages/find-replace/src/views/dialog/FindReplaceDialog.tsx@@ -88,7 +88,7 @@ export const FindDialog = forwardRef(function FindDialogImpl(_props, ref) {const { findCompleted, findString, matchesCount, matchesPosition } = state;const revealReplace = useCallback(() => {- commandService.executeCommand(OpenReplaceDialogOperation.id);+ return commandService.executeCommand(OpenReplaceDialogOperation.id);}, [commandService]);const onFindStringChange = useDebounceFn((findString: string) => {@@ -108,15 +108,9 @@ export const FindDialog = forwardRef(function FindDialogImpl(_props, ref) {onChange={onFindStringChange}/><div className="univer-mt-4 univer-text-center">- <a- className={`- univer-cursor-pointer univer-text-sm univer-text-primary-500 univer-transition-colors- hover:univer-text-primary-500- `}- onClick={revealReplace}- >+ <Button type="button" variant="link" size="small" onClick={revealReplace}>{localeService.t<LocaleKey>('find-replace.dialog.advanced-finding')}- </a>+ </Button></div></>);@@ -307,7 +301,9 @@ export function FindReplaceDialog() {const dialogContainerRef = useRef<HTMLDivElement>(null);useEffect(() => {const container = dialogContainerRef.current;- if (!container) return;+ if (!container) {+ return;+ }const disposable = layoutService.registerContainerElement(container);return () => disposable.dispose();diff --git a/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx b/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsxindex fad87fcd8f..0b5f162662 100644--- a/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx+++ b/packages/find-replace/src/views/dialog/__tests__/FindReplaceDialog.spec.tsx@@ -14,7 +14,7 @@* limitations under the License.*/-import { awaitTime, ICommandService, toDisposable, UniverInstanceType } from '@univerjs/core';+import { awaitTime, ICommandService, LocaleService, LocaleType, toDisposable, UniverInstanceType } from '@univerjs/core';import { ILayoutService, IMessageService, RediContext } from '@univerjs/ui';import { act } from 'react';import { createRoot } from 'react-dom/client';@@ -29,6 +29,7 @@ import {OpenFindDialogOperation,OpenReplaceDialogOperation,} from '../../../commands/operations/find-replace.operation';+import enUS from '../../../locale/en-US';import {FindBy,FindDirection,@@ -69,10 +70,10 @@ const INITIAL_ROWS: ICellText[] = [{ id: 'A4', text: 'banana' },];-const FIND_LABEL = 'find-replace.dialog.find';-const REPLACE_LABEL = 'find-replace.dialog.replace';-const REPLACE_ALL_LABEL = 'find-replace.dialog.replace-all';-const ADVANCED_LABEL = 'find-replace.dialog.advanced-finding';+const FIND_LABEL = enUS['find-replace'].dialog.find;+const REPLACE_LABEL = enUS['find-replace'].dialog.replace;+const REPLACE_ALL_LABEL = enUS['find-replace'].dialog['replace-all'];+const ADVANCED_LABEL = enUS['find-replace'].dialog['advanced-finding'];class TextFindModel extends FindModel {private readonly _matchesUpdate$ = new BehaviorSubject<FindMatch[]>([]);@@ -275,6 +276,10 @@ function createDialogTestBed(capabilities?: FindCapabilities) {[TestFindReplaceProvider],]);+ const localeService = testBed.get(LocaleService);+ localeService.load({ [LocaleType.EN_US]: enUS });+ localeService.setLocale(LocaleType.EN_US);+ localeService.setDirection('ltr');const commandService = testBed.get(ICommandService);[OpenFindDialogOperation,@@ -284,7 +289,9 @@ function createDialogTestBed(capabilities?: FindCapabilities) {].forEach((command) => commandService.registerCommand(command));const provider = testBed.get(TestFindReplaceProvider);- if (capabilities) provider.capabilities = capabilities;+ if (capabilities) {+ provider.capabilities = capabilities;+ }const findReplaceService = testBed.get(IFindReplaceService);findReplaceService.registerFindReplaceProvider(provider);@@ -323,15 +330,6 @@ function getButton(container: HTMLElement, text: string): HTMLButtonElement {return button as HTMLButtonElement;}-function getLink(container: HTMLElement, text: string): HTMLElement {- const link = Array.from(container.querySelectorAll('a')).find((item) => item.textContent?.trim() === text);- if (!link) {- throw new Error(`Link "${text}" was not found.`);- }-- return link as HTMLElement;-}-function setInputValue(input: HTMLInputElement, value: string): void {const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;setter?.call(input, value);@@ -388,7 +386,7 @@ describe('FindReplaceDialog', () => {expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 3, matchesPosition: 1 });});- it('reveals replace controls from the advanced link without restarting the session', async () => {+ it('reveals replace controls from a focusable advanced action without restarting the session', async () => {const testBed = createDialogTestBed();await act(async () => {testBed.commandService.syncExecuteCommand(OpenFindDialogOperation.id);@@ -399,7 +397,10 @@ describe('FindReplaceDialog', () => {container = rendered.container;await act(async () => {- getLink(container!, ADVANCED_LABEL).dispatchEvent(new MouseEvent('click', { bubbles: true }));+ const button = getButton(container!, ADVANCED_LABEL);+ button.focus();+ expect(document.activeElement).toBe(button);+ button.click();});expect(testBed.findReplaceService.replaceRevealed).toBe(true);@@ -426,10 +427,10 @@ describe('FindReplaceDialog', () => {root = rendered.root;container = rendered.container;- expect(container.textContent).toContain('find-replace.dialog.case-sensitive');- expect(container.textContent).toContain('find-replace.dialog.match-the-whole-word');- expect(container.textContent).not.toContain('find-replace.dialog.find-direction.title');- expect(container.textContent).not.toContain('find-replace.dialog.match-the-whole-cell');+ expect(container.textContent).toContain(enUS['find-replace'].dialog['case-sensitive']);+ expect(container.textContent).toContain(enUS['find-replace'].dialog['match-the-whole-word']);+ expect(container.textContent).not.toContain(enUS['find-replace'].dialog['find-direction'].title);+ expect(container.textContent).not.toContain(enUS['find-replace'].dialog['match-the-whole-cell']);});it('replaces the selected result and then replaces all remaining results', async () => {@@ -465,7 +466,7 @@ describe('FindReplaceDialog', () => {await flushSearch();expect(testBed.provider.rows.map((row) => row.text)).toEqual(['orange', 'orange', 'orange', 'banana']);- expect((testBed.get(IMessageService) as unknown as { messages: Array<{ content: string }> }).messages.at(-1)?.content).toBe('find-replace.replace.all-success');+ expect((testBed.get(IMessageService) as unknown as { messages: Array<{ content: string }> }).messages.at(-1)?.content).toBe(testBed.get(LocaleService).t('find-replace.replace.all-success', '2'));});it('moves to the next result when finding the same replace dialog input again', async () => {@@ -612,7 +613,7 @@ describe('FindReplaceDialog', () => {});expect(readState(testBed.findReplaceService)).toMatchObject({ matchesCount: 0, matchesPosition: 0 });expect(readCurrentMatch(testBed.findReplaceService)).toBeNull();- expect((testBed.get(IMessageService) as unknown as { messages: Array<{ content: string }> }).messages.at(-1)?.content).toBe('find-replace.dialog.no-match');+ expect((testBed.get(IMessageService) as unknown as { messages: Array<{ content: string }> }).messages.at(-1)?.content).toBe(enUS['find-replace'].dialog['no-match']);expect(getButton(container!, REPLACE_LABEL).disabled).toBe(true);expect(getButton(container!, REPLACE_ALL_LABEL).disabled).toBe(true);expect(testBed.provider.rows.map((row) => row.text)).toEqual(INITIAL_ROWS.map((row) => row.text));diff --git a/packages/ui/src/services/layout/__tests__/layout.service.spec.ts b/packages/ui/src/services/layout/__tests__/layout.service.spec.tsindex 466a51d2f5..f311dbc995 100644--- a/packages/ui/src/services/layout/__tests__/layout.service.spec.ts+++ b/packages/ui/src/services/layout/__tests__/layout.service.spec.ts@@ -214,7 +214,7 @@ describe('DesktopLayoutService', () => {});dispatchFocusIn(button);await Promise.resolve();- expect(focused).toEqual(['slide-1']);+ expect(focused).toEqual([]);expect(service.isFocused).toBe(true);expect(contextService.getContextValue(FOCUSING_UNIVER)).toBe(true);expect(contextService.getContextValue(FOCUSING_UNIVER_EDITOR)).toBe(false);diff --git a/packages/ui/src/services/layout/layout.service.ts b/packages/ui/src/services/layout/layout.service.tsindex fa109d7278..3de03df22c 100644--- a/packages/ui/src/services/layout/layout.service.ts+++ b/packages/ui/src/services/layout/layout.service.ts@@ -35,9 +35,6 @@ type FocusHandlerFn = (unitId: string) => void;export const FOCUSING_UNIVER = 'FOCUSING_UNIVER';const givingBackFocusElements = ['app-layout',- // 'univer-toolbar-btn',- // 'univer-menu-item',- 'button','sheet-bar-append-button','render-canvas','workbench-layout',diff --git a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.tsindex 39a7ff0b57..6556cc3268 100644--- a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts+++ b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts@@ -173,6 +173,43 @@ describe('ShortcutService', () => {}});+ it.each([+ ['Enter', KeyCode.ENTER, false],+ [' ', KeyCode.SPACE, false],+ ['Tab', KeyCode.TAB, false],+ ['Tab', KeyCode.TAB, true],+ ] as const)('keeps native button %s (shift=%s) out of canvas shortcuts', (key, keyCode, shiftKey) => {+ const injector = new Injector([+ [ICommandService, { useClass: CommandService }],+ [IConfigService, { useClass: ConfigService }],+ [IContextService, { useClass: ContextService }],+ [ILogService, { useClass: DesktopLogService }],+ [IPlatformService, { useClass: PlatformService }],+ [IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }],+ [ShortcutService],+ ]);+ try {+ const service = injector.get(ShortcutService);+ const binding = keyCode | (shiftKey ? MetaKeys.SHIFT : 0);+ service.registerShortcut({ id: 'test.canvas-navigation', binding });+ const button = document.createElement('button');+ const event = new KeyboardEvent('button-navigation', { key, keyCode, shiftKey, cancelable: true });+ button.dispatchEvent(event);+ expect(service.dispatch(event)).toBeUndefined();+ expect(event.defaultPrevented).toBe(false);+ const canvas = document.createElement('canvas');+ const canvasEvent = new KeyboardEvent('button-navigation', { key, keyCode, shiftKey });+ canvas.dispatchEvent(canvasEvent);+ expect(service.dispatch(canvasEvent)?.id).toBe('test.canvas-navigation');+ service.registerShortcut({ id: 'test.modified', binding: binding | MetaKeys.CTRL_COMMAND });+ const modifiedEvent = new KeyboardEvent('button-navigation', { key, keyCode, shiftKey, ctrlKey: true });+ button.dispatchEvent(modifiedEvent);+ expect(service.dispatch(modifiedEvent)?.id).toBe('test.modified');+ } finally {+ injector.dispose();+ }+ });+it.each([KeyCode.ENTER, KeyCode.SPACE, KeyCode.TAB, KeyCode.ESC, KeyCode.ARROW_DOWN, KeyCode.ARROW_UP, KeyCode.ARROW_LEFT, KeyCode.ARROW_RIGHT, KeyCode.HOME, KeyCode.END])('yields menu navigation key %s while retaining canvas shortcuts',(keyCode) => {diff --git a/packages/ui/src/services/shortcut/shortcut.service.ts b/packages/ui/src/services/shortcut/shortcut.service.tsindex 251f8ca1ef..56d7a86b87 100644--- a/packages/ui/src/services/shortcut/shortcut.service.ts+++ b/packages/ui/src/services/shortcut/shortcut.service.ts@@ -221,7 +221,9 @@ export class ShortcutService extends Disposable implements IShortcutService {registerShortcut(shortcut: IShortcutItem): IDisposable {// first map shortcut to a number, so it could be converted and fetched quicklyconst binding = this._getBindingFromItem(shortcut);- if (!binding) return toDisposable(() => {});+ if (!binding) {+ return toDisposable(() => {});+ }const bindingSet = this._shortCutMapping.get(binding);if (bindingSet) {@@ -270,7 +272,9 @@ export class ShortcutService extends Disposable implements IShortcutService {getShortcutDisplay(shortcut: IShortcutItem): string | null {const binding = this._getBindingFromItem(shortcut);- if (!binding) return null;+ if (!binding) {+ return null;+ }const ctrlKey = binding & MetaKeys.CTRL_COMMAND;const shiftKey = binding & MetaKeys.SHIFT;@@ -318,6 +322,12 @@ export class ShortcutService extends Disposable implements IShortcutService {return;}+ // A focused button owns activation and focus traversal even while the canvas context remains active.+ if (!e.ctrlKey && !e.metaKey && !e.altKey && e.target instanceof HTMLButtonElement+ && (e.key === 'Enter' || e.key === ' ' || e.key === 'Tab')) {+ return;+ }+// Toolbar fields own their native editing and history before component key handlers run.if (e.target instanceof HTMLInputElement && e.target.closest('[data-u-command]')) {return;@@ -338,7 +348,9 @@ export class ShortcutService extends Disposable implements IShortcutService {// Also we should check through escape list and force catching list.// if the target is not focused on the univer instance we should ignore the keyboard event.// Maybe the user has forcibly disabled the shortcut keys, and the shortcut keys should not be processed at this time.- if (this._forceEscapeCount > 0 || this._forceDisabled) return;+ if (this._forceEscapeCount > 0 || this._forceDisabled) {+ return;+ }if (this._layoutService &&