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): preserve editor input, focus and error feedback (#7671)

Univere6098a7166f3
diff --git a/packages/design/src/components/input-number/InputNumber.tsx b/packages/design/src/components/input-number/InputNumber.tsx
index 82b51ad9be..1299644d24 100644
--- a/packages/design/src/components/input-number/InputNumber.tsx
+++ b/packages/design/src/components/input-number/InputNumber.tsx
@@ -224,8 +224,10 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
}
function handleBlur(e: FocusEvent<HTMLInputElement>) {
+ // Focus can move before the controlled-value effect has rendered its state updates.
+ const currentValue = value !== undefined ? value : internalValue;
// If allowEmpty is true and input is empty, do not restore the last valid value
- if (internalValue === null) {
+ if (currentValue === null) {
if (inputValue === '' && allowEmpty) {
// Keep the input empty
if (onChange) {
@@ -246,7 +248,7 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
}
// When blurring, format the value properly
- let valueInRange = internalValue;
+ let valueInRange = currentValue;
// Apply min/max constraints
if (max !== undefined && valueInRange > max) {
@@ -256,14 +258,15 @@ export const InputNumber = forwardRef<HTMLInputElement, IInputNumberProps>(
valueInRange = min;
}
- if (valueInRange !== internalValue) {
+ if (valueInRange !== currentValue) {
setInternalValue(valueInRange);
setInputValue(formatValue(valueInRange));
onChange?.(valueInRange);
} else {
// Just ensure the display is formatted correctly
- setInputValue(formatValue(internalValue));
+ setInternalValue(currentValue);
+ setInputValue(formatValue(currentValue));
}
onBlur?.(e);
diff --git a/packages/design/src/components/input-number/__tests__/InputNumber.spec.tsx b/packages/design/src/components/input-number/__tests__/InputNumber.spec.tsx
new file mode 100644
index 0000000000..259cb618cf
--- /dev/null
+++ b/packages/design/src/components/input-number/__tests__/InputNumber.spec.tsx
@@ -0,0 +1,58 @@
+/**
+ * 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 { cleanup, fireEvent, render } from '@testing-library/react';
+import { useEffect, useRef, useState } from 'react';
+import { afterEach, describe, expect, it } from 'vitest';
+import { InputNumber } from '../InputNumber';
+
+function BlurOnControlledReset() {
+ const [value, setValue] = useState(24);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ if (value === 11) {
+ inputRef.current?.blur();
+ }
+ }, [value]);
+
+ return (
+ <InputNumber
+ ref={inputRef}
+ value={value}
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') {
+ setValue(11);
+ }
+ }}
+ />
+ );
+}
+
+describe('InputNumber controlled reset', () => {
+ afterEach(cleanup);
+
+ it('keeps the new controlled value when focus leaves during reset effects', () => {
+ const { container } = render(<BlurOnControlledReset />);
+ const input = container.querySelector('input')!;
+ input.focus();
+
+ fireEvent.keyDown(input, { key: 'Escape', code: 'Escape' });
+
+ expect(input.value).toBe('11');
+ expect(document.activeElement).not.toBe(input);
+ });
+});
diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
index f24ca2ed27..68554d3c5d 100644
--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts
@@ -1336,6 +1336,43 @@ describe('DocSelectionRenderService', () => {
expect(document.activeElement).toBe(control);
});
+ it('preserves focus inside an open popover during selection synchronization', () => {
+ const { input, renderUnit, service, univer } = createRealSelectionRenderService();
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ TestLayoutService.root.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');
+ input.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');
+ const popover = document.createElement('div');
+ popover.dataset.slot = 'popover-content';
+ popover.dataset.state = 'open';
+ const button = document.createElement('button');
+ popover.appendChild(button);
+ TestLayoutService.root.appendChild(popover);
+ button.focus();
+
+ service.sync();
+ expect(document.activeElement).toBe(button);
+ service.activate(12, 34, true);
+ expect(document.activeElement).toBe(button);
+
+ popover.dataset.state = 'closed';
+ service.sync();
+ expect(document.activeElement).toBe(input);
+ });
+
+ it.each(['button', 'tab'])('refocuses the document from a Ribbon %s when setting a selection', (role) => {
+ const { input, renderUnit, service, univer } = createRealSelectionRenderService();
+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());
+ TestLayoutService.root.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');
+ input.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');
+ const button = document.createElement('button');
+ button.setAttribute('role', role);
+ TestLayoutService.root.appendChild(button);
+ button.focus();
+
+ service.sync();
+ expect(document.activeElement).toBe(input);
+ });
+
it('allows the internal sheet cell editor to refocus from an embed-owned canvas', () => {
const focusCoordinator = new EmbedRuntimeFocusCoordinator();
const { input, renderUnit, service, univer } = createRealSelectionRenderService({
diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
index 1c815cafef..f7b7b99ac8 100644
--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts
@@ -1750,8 +1750,8 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
const ownerDocument = this._getOwnerDocument();
const activeElement = ownerDocument.activeElement;
const currentEmbedOwner = this._getCurrentEmbedOwner();
- // Sharing an embed runtime does not transfer focus away from its native controls.
- if (activeElement?.matches('input, textarea, select')) {
+ // Layout and drawing refreshes must not take focus from native controls or open menu buttons.
+ if (activeElement?.closest('input, textarea, select, [data-slot="popover-content"][data-state="open"]')) {
return true;
}
diff --git a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
index 983da2a25b..4da1cba73a 100644
--- a/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/__tests__/doc-skeleton.spec.ts
@@ -3154,7 +3154,8 @@ describe('doc skeleton', () => {
const localeService = univer.__getInjector().get(LocaleService);
const content = Array.from(
{ length: paragraphCount },
- (_, index) => `Short paragraph ${index}.\r`
+ // Keep single-line paragraphs inexpensive while preserving the multi-page fixture.
+ (_, index) => `P${index}.\r`
).join('');
const documentModel = createDocumentModelWithStyle(content, {}, { horizontalAlign });
documentModel.updateDocumentDataPageSize(600, 600);
diff --git a/packages/ui/src/mobile-plugin.ts b/packages/ui/src/mobile-plugin.ts
index f9ee83fab2..8a3dfd30d4 100644
--- a/packages/ui/src/mobile-plugin.ts
+++ b/packages/ui/src/mobile-plugin.ts
@@ -142,7 +142,8 @@ export class UniverMobileUIPlugin extends Plugin {
[IDialogService, { useClass: MobileDialogService, lazy: true }],
[IConfirmService, { useClass: MobileConfirmService, lazy: true }],
[ISidebarService, { useClass: DesktopSidebarService, lazy: true }],
- [IMessageService, { useClass: DesktopMessageService, lazy: true }],
+ // Mount the message host before a command can publish its first error.
+ [IMessageService, { useClass: DesktopMessageService }],
[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
[ILocalFileService, { useClass: DesktopLocalFileService }],
diff --git a/packages/ui/src/plugin.ts b/packages/ui/src/plugin.ts
index 3c5912b74f..5b612cb1d6 100644
--- a/packages/ui/src/plugin.ts
+++ b/packages/ui/src/plugin.ts
@@ -145,7 +145,8 @@ export class UniverUIPlugin extends Plugin {
[IDialogService, { useClass: DesktopDialogService, lazy: true }],
[IConfirmService, { useClass: DesktopConfirmService, lazy: true }],
[ISidebarService, { useClass: DesktopSidebarService, lazy: true }],
- [IMessageService, { useClass: DesktopMessageService, lazy: true }],
+ // Mount the message host before a command can publish its first error.
+ [IMessageService, { useClass: DesktopMessageService }],
[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
[ILocalFileService, { useClass: DesktopLocalFileService }],
diff --git a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts
index 8bc3698ff5..39a7ff0b57 100644
--- a/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts
+++ b/packages/ui/src/services/shortcut/__tests__/shortcut.service.spec.ts
@@ -130,7 +130,17 @@ describe('ShortcutService', () => {
vi.unstubAllGlobals();
});
- it.each([KeyCode.BACKSPACE, KeyCode.DELETE])('keeps toolbar input deletion key %s out of grid shortcuts', (keyCode) => {
+ it.each([
+ { keyCode: KeyCode.BACKSPACE, ctrlKey: false, shiftKey: false },
+ { keyCode: KeyCode.DELETE, ctrlKey: false, shiftKey: false },
+ { keyCode: KeyCode.A, ctrlKey: true, shiftKey: false },
+ { keyCode: KeyCode.X, ctrlKey: true, shiftKey: false },
+ { keyCode: KeyCode.C, ctrlKey: true, shiftKey: false },
+ { keyCode: KeyCode.V, ctrlKey: true, shiftKey: false },
+ { keyCode: KeyCode.Z, ctrlKey: true, shiftKey: false },
+ { keyCode: KeyCode.Z, ctrlKey: true, shiftKey: true },
+ { keyCode: KeyCode.Y, ctrlKey: true, shiftKey: false },
+ ])('keeps toolbar input key $keyCode (ctrl=$ctrlKey, shift=$shiftKey) out of grid shortcuts', (keys) => {
const injector = new Injector([
[ICommandService, { useClass: CommandService }],
[IConfigService, { useClass: ConfigService }],
@@ -147,15 +157,16 @@ describe('ShortcutService', () => {
document.body.appendChild(control);
try {
const service = injector.get(ShortcutService);
- service.registerShortcut({ id: 'test.grid-delete', binding: keyCode });
- const event = new KeyboardEvent('input-delete-test', { keyCode, cancelable: true });
+ const binding = keys.keyCode | (keys.ctrlKey ? MetaKeys.CTRL_COMMAND : 0) | (keys.shiftKey ? MetaKeys.SHIFT : 0);
+ service.registerShortcut({ id: 'test.grid-edit', binding });
+ const event = new KeyboardEvent('input-key-test', { ...keys, cancelable: true });
input.dispatchEvent(event);
expect(service.dispatch(event)).toBeUndefined();
expect(event.defaultPrevented).toBe(false);
const canvas = document.createElement('canvas');
- const canvasEvent = new KeyboardEvent('input-delete-test', { keyCode });
+ const canvasEvent = new KeyboardEvent('input-key-test', keys);
canvas.dispatchEvent(canvasEvent);
- expect(service.dispatch(canvasEvent)?.id).toBe('test.grid-delete');
+ expect(service.dispatch(canvasEvent)?.id).toBe('test.grid-edit');
} finally {
control.remove();
injector.dispose();
diff --git a/packages/ui/src/services/shortcut/shortcut.service.ts b/packages/ui/src/services/shortcut/shortcut.service.ts
index 765bc75938..251f8ca1ef 100644
--- a/packages/ui/src/services/shortcut/shortcut.service.ts
+++ b/packages/ui/src/services/shortcut/shortcut.service.ts
@@ -318,10 +318,8 @@ export class ShortcutService extends Disposable implements IShortcutService {
return;
}
- if (
- (e.keyCode === KeyCode.BACKSPACE || e.keyCode === KeyCode.DELETE) &&
- e.target instanceof HTMLInputElement && e.target.closest('[data-u-command]')
- ) {
+ // 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;
}