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): focus editors through selection services (#7837)

白熱f1356cda846a
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 fea37ace4f..9744728a68 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
@@ -181,6 +181,14 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo
return this._input === this._getOwnerDocument().activeElement;
}
+ get inputElement(): HTMLDivElement {
+ return this._input;
+ }
+
+ get selectionContainer(): HTMLDivElement {
+ return this._container;
+ }
+
get isEditing() {
return this._textSelectionInner$.value?.isEditing === true;
}
diff --git a/packages/engine-formula/src/__tests__/formula-editor-helpers.spec.ts b/packages/engine-formula/src/__tests__/formula-editor-helpers.spec.ts
index 2d8ce081a6..0098415823 100644
--- a/packages/engine-formula/src/__tests__/formula-editor-helpers.spec.ts
+++ b/packages/engine-formula/src/__tests__/formula-editor-helpers.spec.ts
@@ -14,9 +14,12 @@
* limitations under the License.
*/
-import { FunctionType, matchToken, sequenceNodeType } from '@univerjs/engine-formula';
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
+import { FunctionType } from '../basics/function';
+import { matchToken } from '../basics/token';
+import { sequenceNodeType } from '../engine/utils/sequence';
import {
+ buildFormulaTextRuns,
findFormulaStructuredReferences,
getFormulaHighlightDataStream,
getFormulaReplaceResult,
@@ -129,3 +132,53 @@ describe('formula editor helpers', () => {
}]);
});
});
+
+describe('engine-formula regression scenarios', () => {
+ it('preserves incomplete formula editor text while applying token highlights', () => {
+ expect(getFormulaHighlightDataStream('=', [
+ 'SUM(',
+ { token: 'D37', nodeType: sequenceNodeType.REFERENCE, startIndex: 4, endIndex: 6 },
+ ',',
+ { token: 'F40', nodeType: sequenceNodeType.REFERENCE, startIndex: 8, endIndex: 10 },
+ ], 'SUM(D37,F40,J36,J42')).toBe('=SUM(D37,F40,J36,J42\r\n');
+ });
+
+ it('builds colored text runs for references, numbers, strings, arrays, defined names, and plain text', () => {
+ const result = buildFormulaTextRuns(
+ { hasDefinedNameDescription: vi.fn((token: string) => token === 'SalesTotal') } as never,
+ {
+ formulaRefColors: ['#ff0000', '#00ff00'],
+ numberColor: '#0000ff',
+ stringColor: '#ff00ff',
+ plainTextColor: '#111111',
+ },
+ [
+ 'SUM(',
+ { token: 'A1', nodeType: sequenceNodeType.REFERENCE, startIndex: 4, endIndex: 5 },
+ ',',
+ { token: '42', nodeType: sequenceNodeType.NUMBER, startIndex: 7, endIndex: 8 },
+ { token: '"ok"', nodeType: sequenceNodeType.STRING, startIndex: 9, endIndex: 12 },
+ { token: '{1,2}', nodeType: sequenceNodeType.ARRAY, startIndex: 13, endIndex: 17 },
+ { token: 'SalesTotal', nodeType: sequenceNodeType.DEFINED_NAME, startIndex: 18, endIndex: 27 },
+ { token: '+', nodeType: sequenceNodeType.NORMAL, startIndex: 28, endIndex: 28 },
+ { token: 'A1', nodeType: sequenceNodeType.REFERENCE, startIndex: 29, endIndex: 30 },
+ ]
+ );
+
+ expect(result.refSelections).toEqual([
+ expect.objectContaining({ token: 'A1', themeColor: '#ff0000', refIndex: 1, index: 0 }),
+ expect.objectContaining({ token: 'A1', themeColor: '#ff0000', refIndex: 8, index: 1 }),
+ ]);
+ expect(result.textRuns.map((run) => run.ts?.cl?.rgb)).toEqual([
+ '#111111',
+ '#ff0000',
+ '#111111',
+ '#0000ff',
+ '#ff00ff',
+ '#ff00ff',
+ '#111111',
+ '#111111',
+ '#ff0000',
+ ]);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/__tests__/formula-embed-integration.service.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/__tests__/formula-embed-integration.service.spec.ts
new file mode 100644
index 0000000000..6b92415732
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/__tests__/formula-embed-integration.service.spec.ts
@@ -0,0 +1,97 @@
+/**
+ * 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.
+ */
+
+// @vitest-environment jsdom
+
+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, Injector, toDisposable } from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { describe, expect, it } from 'vitest';
+import {
+ FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,
+ FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE,
+ IFormulaEmbedInteractionBoundaryService,
+ IFormulaEmbedRuntimeFocusCoordinator,
+ registerFormulaEditorRuntimePortal,
+} from '../formula-embed-integration.service';
+
+describe('formula-embed-integration.service regression scenarios', () => {
+ it('registers formula editor portal elements as embedded child editors', () => {
+ const editorId = DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;
+ const portalRoot = document.createElement('div');
+ const editorElement = document.createElement('div');
+ portalRoot.id = `univer-doc-selection-container-${editorId}`;
+ editorElement.id = `__editor_${editorId}`;
+ portalRoot.appendChild(editorElement);
+ document.body.appendChild(portalRoot);
+
+ const registeredFocusElements = new Set<Element>();
+ const registeredBoundaryElements = new Set<Element>();
+ const focusCoordinator = {
+ resolveRuntimeScopeByChildUnitId: () => undefined,
+ acquireLease: () => toDisposable(() => {}),
+ registerElement: ({ element, role }: { element: HTMLElement; role: string }) => {
+ registeredFocusElements.add(element);
+ element.setAttribute(FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE, role);
+ return toDisposable(() => {
+ registeredFocusElements.delete(element);
+ element.removeAttribute(FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE);
+ });
+ },
+ };
+ const interactionBoundaryService = {
+ registerOwnedElement: (embedId: string, element: Element) => {
+ registeredBoundaryElements.add(element);
+ element.setAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, embedId);
+ return toDisposable(() => {
+ registeredBoundaryElements.delete(element);
+ element.removeAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE);
+ });
+ },
+ };
+ const injector = new Injector();
+ injector.add([IEditorService, { useValue: {
+ getEditor: () => ({ docSelectionRenderService: { selectionContainer: portalRoot, inputElement: editorElement } }),
+ } as never }]);
+ injector.add([IFormulaEmbedInteractionBoundaryService, { useValue: interactionBoundaryService }]);
+ injector.add([IFormulaEmbedRuntimeFocusCoordinator, { useValue: focusCoordinator }]);
+ const otherPortal = portalRoot.cloneNode(true) as HTMLElement;
+ document.body.prepend(otherPortal);
+ const disposable = registerFormulaEditorRuntimePortal({
+ editorService: injector.get(IEditorService),
+ embedId: 'embed-1',
+ editorId,
+ interactionBoundaryService: injector.get(IFormulaEmbedInteractionBoundaryService),
+ focusCoordinator: injector.get(IFormulaEmbedRuntimeFocusCoordinator),
+ });
+
+ expect(registeredBoundaryElements.has(otherPortal)).toBe(false);
+ expect(registeredFocusElements.has(otherPortal)).toBe(false);
+ expect(portalRoot.getAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe('embed-1');
+ expect(editorElement.getAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe('embed-1');
+ expect(portalRoot.getAttribute(FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe('child-editor');
+ expect(editorElement.getAttribute(FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe('child-editor');
+ expect(registeredBoundaryElements.has(editorElement)).toBe(true);
+ expect(registeredFocusElements.has(editorElement)).toBe(true);
+
+ disposable.dispose();
+
+ expect(portalRoot.hasAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe(false);
+ expect(editorElement.hasAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe(false);
+ portalRoot.remove();
+ otherPortal.remove();
+ injector.dispose();
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/formula-embed-integration.service.ts b/packages/sheets-formula-ui/src/views/formula-editor/formula-embed-integration.service.ts
index e45d118dfd..7d72634926 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/formula-embed-integration.service.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/formula-embed-integration.service.ts
@@ -15,6 +15,7 @@
*/
import type { IDisposable } from '@univerjs/core';
+import type { DocSelectionRenderService, IEditorService } from '@univerjs/docs-ui';
import { createIdentifier, DisposableCollection, toDisposable } from '@univerjs/core';
export const FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE = 'data-embed-interaction-boundary-owner';
@@ -57,6 +58,7 @@ export const IFormulaEmbedInteractionBoundaryService = createIdentifier<IFormula
interface IRegisterFormulaEditorRuntimePortalOptions {
embedId: string;
editorId: string;
+ editorService: IEditorService;
ownerDocument?: Document;
interactionBoundaryService?: IFormulaEmbedInteractionBoundaryService;
focusCoordinator?: IFormulaEmbedRuntimeFocusCoordinator;
@@ -81,7 +83,8 @@ export function registerFormulaEditorRuntimePortal(options: IRegisterFormulaEdit
return;
}
- const portalRoot = resolveFormulaEditorPortalRoot(options.editorId, ownerDocument);
+ const selection = options.editorService.getEditor(options.editorId)?.docSelectionRenderService;
+ const portalRoot = selection?.selectionContainer.isConnected ? selection.selectionContainer : null;
if (portalRoot === registeredPortalRoot) {
return;
}
@@ -89,12 +92,12 @@ export function registerFormulaEditorRuntimePortal(options: IRegisterFormulaEdit
portalRegistration?.dispose();
portalRegistration = undefined;
registeredPortalRoot = null;
- if (!portalRoot) {
+ if (!portalRoot || !selection) {
return;
}
registeredPortalRoot = portalRoot;
- portalRegistration = registerFormulaEditorPortalRoot(options, ownerDocument, portalRoot);
+ portalRegistration = registerFormulaEditorPortalRoot(options, selection);
};
const scheduleRetry = (remaining: number) => {
@@ -138,19 +141,12 @@ export function registerFormulaEditorRuntimePortal(options: IRegisterFormulaEdit
return collection;
}
-function resolveFormulaEditorPortalRoot(editorId: string, ownerDocument: Document): HTMLElement | null {
- return (ownerDocument.getElementById(`univer-doc-selection-container-${editorId}`) as HTMLElement | null)
- ?? (ownerDocument.getElementById(`__editor_${editorId}`) as HTMLElement | null);
-}
-
function registerFormulaEditorPortalRoot(
options: IRegisterFormulaEditorRuntimePortalOptions,
- ownerDocument: Document,
- portalRoot: HTMLElement
+ selection: DocSelectionRenderService
): IDisposable {
const collection = new DisposableCollection();
- const editorElement = ownerDocument.getElementById(`__editor_${options.editorId}`) as HTMLElement | null;
- const elements = editorElement && editorElement !== portalRoot ? [portalRoot, editorElement] : [portalRoot];
+ const elements = [selection.selectionContainer, selection.inputElement];
elements.forEach((element) => {
if (options.interactionBoundaryService) {
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/formula-selection-business.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/formula-selection-business.spec.ts
deleted file mode 100644
index f420aac508..0000000000
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/formula-selection-business.spec.ts
+++ /dev/null
@@ -1,867 +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.
- */
-
-// @vitest-environment jsdom
-
-import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, toDisposable } from '@univerjs/core';
-import {
- buildFormulaTextRuns,
- getFormulaHighlightDataStream,
- getFormulaSequenceCharacterAtOffset,
- isFormulaReferenceAddingContext,
- isFormulaReferenceAddingTextContext,
- sequenceNodeType,
-} from '@univerjs/engine-formula';
-import { describe, expect, it, vi } from 'vitest';
-import {
- FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,
- FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE,
- isEventTargetInSameFormulaEmbedInteractionBoundary,
- registerFormulaEditorRuntimePortal,
-} from '../../formula-embed-integration.service';
-import {
- focusFormulaEditor,
- hasActiveFormulaEmbedInteraction,
- shouldRefocusFormulaEditorOnMouseUp,
- shouldSkipFormulaEditorMouseUpFocus,
-} from '../use-focus';
-import {
- FormulaSelectingType,
- resolveFormulaSelectingIntent,
- resolveFormulaSelectionCursorIndex,
- resolveFormulaSelectionDataStream,
- resolveFormulaSelectionWorkbook,
- shouldAddFormulaReference,
- shouldSkipReferenceEditingByPointer,
-} from '../use-formula-selection';
-import { calcHighlightRanges, createFormulaHighlightBody, createHighlightTextRuns } from '../use-highlight';
-import {
- isFormulaEditorInteractionOwner,
- shouldMoveFormulaSelectionFromCurrentSelection,
-} from '../use-left-and-right-arrow';
-import {
- createSelectionChangeDuplicateEndGuard,
- createSelectionChangeHandler,
- getInitialFormulaReferenceSelectionCount,
- getLastFormulaSelection,
- getSelectionsForFormulaRefUpdate,
- getSharedSelectionChangeDuplicateEndGuard,
- insertFormulaReferenceText,
- isSameFormulaSelection,
- prepareSelectionChangeContext,
- replaceFormulaControlSelection,
- shouldSkipFormulaReferenceUpdate,
-} from '../use-sheet-selection-change';
-
-function range(row: number, col: number, sheetId = 'sheet1', unitId = 'unit1') {
- return {
- startRow: row,
- endRow: row,
- startColumn: col,
- endColumn: col,
- sheetId,
- unitId,
- };
-}
-
-describe('formula selection update helpers', () => {
- it('does not rewrite editor selections while doc pointer selection is in progress', () => {
- const editorService = {
- focus: vi.fn(),
- };
- const editor = {
- getEditorId: vi.fn(() => 'editor-1'),
- getSelectionRanges: vi.fn(() => [{ startOffset: 1, endOffset: 1, collapsed: true }]),
- setSelectionRanges: vi.fn(),
- getDocumentData: vi.fn(() => ({ body: { dataStream: 'abc\r\n' } })),
- docSelectionRenderService: {
- isOnPointerEvent: true,
- },
- };
-
- focusFormulaEditor(editorService as never, editor as never);
-
- expect(editorService.focus).toHaveBeenCalledWith('editor-1');
- expect(editor.setSelectionRanges).not.toHaveBeenCalled();
- });
-
- it('keeps formula editor mouse-up refocus available when the editor canvas handled the pointer interaction', () => {
- const canvas = document.createElement('canvas');
- canvas.dataset.uComp = 'render-canvas';
- const button = document.createElement('button');
-
- expect(shouldSkipFormulaEditorMouseUpFocus(canvas)).toBe(false);
- expect(shouldSkipFormulaEditorMouseUpFocus(button)).toBe(false);
- });
-
- it('does not refocus the formula editor on mouse-up when the editor is already focused', () => {
- const canvas = document.createElement('canvas');
- canvas.dataset.uComp = 'render-canvas';
-
- expect(shouldRefocusFormulaEditorOnMouseUp({
- target: canvas,
- isFocusing: true,
- isPointerSelecting: false,
- })).toBe(false);
- });
-
- it('does not refocus the formula editor while pointer text selection is active', () => {
- const canvas = document.createElement('canvas');
- canvas.dataset.uComp = 'render-canvas';
-
- expect(shouldRefocusFormulaEditorOnMouseUp({
- target: canvas,
- isFocusing: false,
- isPointerSelecting: true,
- })).toBe(false);
- });
-
- it('refocuses the formula editor on mouse-up only when focus was lost and no pointer selection is active', () => {
- const canvas = document.createElement('canvas');
- canvas.dataset.uComp = 'render-canvas';
-
- expect(shouldRefocusFormulaEditorOnMouseUp({
- target: canvas,
- isFocusing: false,
- isPointerSelecting: false,
- })).toBe(true);
- });
-
- it('treats sheet range selection inside the same embed owner as an active formula interaction', () => {
- const block = document.createElement('div');
- const editorHost = document.createElement('div');
- const sheetCanvas = document.createElement('canvas');
- block.setAttribute('data-embed-interaction-boundary-owner', 'embed-1');
- block.append(editorHost, sheetCanvas);
- document.body.appendChild(block);
-
- sheetCanvas.tabIndex = -1;
- sheetCanvas.focus();
-
- expect(isEventTargetInSameFormulaEmbedInteractionBoundary(editorHost, sheetCanvas)).toBe(true);
- expect(hasActiveFormulaEmbedInteraction(editorHost)).toBe(true);
-
- block.remove();
- });
-
- it('registers formula editor portal elements as embedded child editors', () => {
- const editorId = DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;
- const portalRoot = document.createElement('div');
- const editorElement = document.createElement('div');
- portalRoot.id = `univer-doc-selection-container-${editorId}`;
- editorElement.id = `__editor_${editorId}`;
- portalRoot.appendChild(editorElement);
- document.body.appendChild(portalRoot);
-
- const registeredFocusElements = new Set<Element>();
- const registeredBoundaryElements = new Set<Element>();
- const focusCoordinator = {
- resolveRuntimeScopeByChildUnitId: () => undefined,
- acquireLease: () => toDisposable(() => {}),
- registerElement: ({ element, role }: { element: HTMLElement; role: string }) => {
- registeredFocusElements.add(element);
- element.setAttribute(FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE, role);
- return toDisposable(() => {
- registeredFocusElements.delete(element);
- element.removeAttribute(FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE);
- });
- },
- };
- const interactionBoundaryService = {
- registerOwnedElement: (embedId: string, element: Element) => {
- registeredBoundaryElements.add(element);
- element.setAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, embedId);
- return toDisposable(() => {
- registeredBoundaryElements.delete(element);
- element.removeAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE);
- });
- },
- };
- const disposable = registerFormulaEditorRuntimePortal({
- embedId: 'embed-1',
- editorId,
- interactionBoundaryService,
- focusCoordinator,
- });
-
- expect(portalRoot.getAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe('embed-1');
- expect(editorElement.getAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe('embed-1');
- expect(portalRoot.getAttribute(FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe('child-editor');
- expect(editorElement.getAttribute(FORMULA_EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe('child-editor');
- expect(registeredBoundaryElements.has(editorElement)).toBe(true);
- expect(registeredFocusElements.has(editorElement)).toBe(true);
-
- disposable.dispose();
-
- expect(portalRoot.hasAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe(false);
- expect(editorElement.hasAttribute(FORMULA_EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe(false);
- portalRoot.remove();
- });
-
- it('only skips reference editing when pointer-origin editing is still disabled and click editing is allowed', () => {
- expect(shouldSkipReferenceEditingByPointer(true)).toBe(true);
- expect(shouldSkipReferenceEditingByPointer(true, true)).toBe(false);
- expect(shouldSkipReferenceEditingByPointer(false)).toBe(false);
- });
-
- it('falls back to the formula editor workbook when the focused current workbook is unavailable', () => {
- const fallbackWorkbook = { unitId: 'embedded-sheet' };
-
- expect(resolveFormulaSelectionWorkbook(undefined, fallbackWorkbook)).toBe(fallbackWorkbook);
- expect(resolveFormulaSelectionWorkbook(null, fallbackWorkbook)).toBe(fallbackWorkbook);
- expect(resolveFormulaSelectionWorkbook({ unitId: 'current-sheet' }, fallbackWorkbook)).toEqual({ unitId: 'current-sheet' });
- });
-
- it('treats the hidden normal editor as the fx bar owner while the fx bar owns formula selection', () => {
- expect(isFormulaEditorInteractionOwner(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, {
- fxBarFocused: true,
- })).toBe(true);
- });
-
- it('lets the fx bar own formula selection when the canvas leaves no focused editor', () => {
- expect(isFormulaEditorInteractionOwner(null, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, {
- fxBarFocused: true,
- allowMissingFocus: true,
- })).toBe(true);
- });
-
- it('does not let the hidden normal editor own the fx bar outside an fx formula selection session', () => {
- expect(isFormulaEditorInteractionOwner(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, {
- fxBarFocused: false,
- })).toBe(false);
- });
-
- it('reads formula selection text from the formula editor instead of the current host document', () => {
- const accessor = {
- get: vi.fn(() => ({
- getCurrentUniverDocInstance: vi.fn(() => ({
- getBody: () => ({ dataStream: 'host document text\r\n' }),
- })),
- })),
- };
- const editor = {
- getDocumentDataModel: vi.fn(() => ({
- getBody: () => ({ dataStream: '=SUM(\r\n' }),
- })),
- };
-
- expect(resolveFormulaSelectionDataStream(accessor as never, editor as never)).toEqual({
- dataStream: '=SUM(\r\n',
- offset: 0,
- });
- });
-
- it('falls back to the editor unit when the formula editor document model has been disposed', () => {
- const accessor = {
- get: vi.fn(() => ({
- getUnit: vi.fn((unitId: string) => unitId === 'formula-editor'
- ? { getBody: () => ({ dataStream: '=A1\r\n' }) }
- : undefined),
- getCurrentUnitOfType: vi.fn(() => ({
- getBody: () => ({ dataStream: 'host document text\r\n' }),
- })),
- })),
- };
- const editor = {
- getDocumentDataModel: vi.fn(() => null),
- };
-
- expect(resolveFormulaSelectionDataStream(accessor as never, editor as never, 'formula-editor')).toEqual({
- dataStream: '=A1\r\n',
- offset: 0,
- });
- });
-
- it('reads formula selection text from the editor unit before falling back to the current host document', () => {
- const accessor = {
- get: vi.fn(() => ({
- getUnit: vi.fn((unitId: string) => unitId === 'formula-editor'
- ? { getBody: () => ({ dataStream: '=A1\r\n' }) }
- : undefined),
- getCurrentUniverDocInstance: vi.fn(() => ({
- getBody: () => ({ dataStream: 'host document text\r\n' }),
- })),
- })),
- };
-
- expect(resolveFormulaSelectionDataStream(accessor as never, undefined, 'formula-editor')).toEqual({
- dataStream: '=A1\r\n',
- offset: 0,
- });
- });
-
- it('uses the end of a fresh formula when the editor selection offset is still stale', () => {
- expect(resolveFormulaSelectionCursorIndex({ collapsed: true, startOffset: 0 }, '=')).toBe(1);
- expect(resolveFormulaSelectionCursorIndex({ collapsed: true, startOffset: 0 }, '=SUM(')).toBe(5);
- expect(resolveFormulaSelectionCursorIndex({ collapsed: true, startOffset: 0 }, 'plain')).toBe(0);
- expect(resolveFormulaSelectionCursorIndex({ collapsed: true, startOffset: 2 }, '=A1')).toBe(2);
- });
-
- it('prefers adding a new formula reference when the cursor is after a delimiter', () => {
- expect(resolveFormulaSelectingIntent(true, true)).toBe(FormulaSelectingType.NEED_ADD);
- expect(resolveFormulaSelectingIntent(true, false)).toBe(FormulaSelectingType.NEED_ADD);
- expect(resolveFormulaSelectingIntent(false, true)).toBe(FormulaSelectingType.CAN_EDIT);
- expect(resolveFormulaSelectingIntent(false, false)).toBe(FormulaSelectingType.NOT_SELECT);
- });
-
- it('only arms reference picking after formula delimiters and operators', () => {
- expect(shouldAddFormulaReference('=', 1)).toBe(true);
- expect(shouldAddFormulaReference('=SUM(', 5)).toBe(true);
- expect(shouldAddFormulaReference('=SUM(A1,', 8)).toBe(true);
- expect(shouldAddFormulaReference('=A1+', 4)).toBe(true);
- expect(shouldAddFormulaReference('=Sheet1!', 8)).toBe(true);
- expect(shouldAddFormulaReference('=SUM', 4)).toBe(false);
- expect(shouldAddFormulaReference('=A1', 3)).toBe(false);
- });
-
- it('reorders the active selection into the formula reference being edited and keeps ctrl-added ranges separate', () => {
- const selections = [range(0, 0), range(1, 1), range(2, 2)];
-
- expect(getSelectionsForFormulaRefUpdate(selections, 0)).toEqual({
- orderedSelections: [range(2, 2), range(0, 0), range(1, 1)],
- });
- expect(getSelectionsForFormulaRefUpdate(selections, 1, true)).toEqual({
- orderedSelections: [range(0, 0), range(1, 1)],
- insertedSelection: range(2, 2),
- });
- expect(getSelectionsForFormulaRefUpdate(selections, -1)).toEqual({
- orderedSelections: selections,
- });
- });
-
- it('previews ctrl-add selection updates before move end and ignores initial selection events', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 1,
- onSelectionsChange,
- });
-
- handler([range(0, 0)], true, { initial: true });
- handler([range(0, 0), range(1, 1)], false);
- expect(onSelectionsChange).toHaveBeenCalledWith([range(0, 0), range(1, 1)], false, true);
-
- handler([range(0, 0), range(1, 1)], true);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
-
- handler([range(3, 3)], false);
- expect(onSelectionsChange).toHaveBeenLastCalledWith([range(3, 3)], false, false);
- });
-
- it('ignores replayed initial formula references when no initial reference selection exists', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 0,
- onSelectionsChange,
- });
-
- handler([range(7, 5)], true, { initial: true });
-
- expect(onSelectionsChange).not.toHaveBeenCalled();
- });
-
- it('uses the formula text end as the insertion context when the embedded editor selection is temporarily empty', () => {
- const lexerTreeBuilder = {
- sequenceNodesBuilder: vi.fn(() => []),
- };
- const editor = {
- getSelectionRanges: vi.fn(() => []),
- getDocumentData: vi.fn(() => ({ body: { dataStream: '=\r\n' } })),
- };
-
- expect(prepareSelectionChangeContext({
- editor: editor as never,
- lexerTreeBuilder: lexerTreeBuilder as never,
- })).toMatchObject({
- offset: 0,
- nodeIndex: -1,
- updatingRefIndex: -1,
- sequenceNodes: [],
- });
- });
-
- it('does not create a fallback formula context for non-formula editor text', () => {
- const lexerTreeBuilder = {
- sequenceNodesBuilder: vi.fn(() => []),
- };
- const editor = {
- getSelectionRanges: vi.fn(() => []),
- getDocumentData: vi.fn(() => ({ body: { dataStream: 'plain\r\n' } })),
- };
-
- expect(prepareSelectionChangeContext({
- editor: editor as never,
- lexerTreeBuilder: lexerTreeBuilder as never,
- })).toBeUndefined();
- });
-
- it('starts the first keyboard-added formula reference from the edited cell selection', () => {
- expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.NEED_ADD, 0)).toBe(true);
- });
-
- it('routes formula editor interactions only to the focused formula editor', () => {
- expect(isFormulaEditorInteractionOwner('__INTERNAL_EDITOR__DOCS_NORMAL', '__INTERNAL_EDITOR__DOCS_NORMAL')).toBe(true);
- expect(isFormulaEditorInteractionOwner('__INTERNAL_EDITOR__DOCS_FORMULA_BAR', '__INTERNAL_EDITOR__DOCS_NORMAL')).toBe(false);
- expect(isFormulaEditorInteractionOwner(null, '__INTERNAL_EDITOR__DOCS_NORMAL')).toBe(false);
- });
-
- it('continues keyboard-added formula references from the last reference selection after a delimiter', () => {
- expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.NEED_ADD, 1)).toBe(false);
- expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.NEED_ADD, 2)).toBe(false);
- });
-
- it('keeps cross-sheet reference editing anchored to the current sheet selection', () => {
- expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.EDIT_OTHER_SHEET_REFERENCE, 1)).toBe(true);
- expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.CAN_EDIT, 1)).toBe(false);
- });
-
- it('recognizes delimiter-adjacent formula context as a new reference insertion point', () => {
- const nodes = [
- { token: 'M28', nodeType: sequenceNodeType.REFERENCE },
- ',',
- ];
-
- expect(getFormulaSequenceCharacterAtOffset(nodes, 3)).toBe('8');
- expect(getFormulaSequenceCharacterAtOffset(nodes, 4)).toBe(',');
- expect(isFormulaReferenceAddingContext(nodes, 3)).toBe(false);
- expect(isFormulaReferenceAddingContext(nodes, 4)).toBe(true);
- expect(isFormulaReferenceAddingTextContext('M28,', 4)).toBe(true);
- expect(insertFormulaReferenceText('M28,', 'M27', 4)).toBe('M28,M27');
- });
-
- it('skips stale non-add formula selection updates when no rendered reference exists', () => {
- expect(shouldSkipFormulaReferenceUpdate(false, 0)).toBe(true);
- expect(shouldSkipFormulaReferenceUpdate(false, 1)).toBe(false);
- expect(shouldSkipFormulaReferenceUpdate(true, 0)).toBe(false);
- });
-
- it('applies a click-created formula reference from selection start before pointer-up controls are reset', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 0,
- onSelectionsChange,
- });
-
- handler([range(7, 5)], false);
- handler([], true);
-
- expect(onSelectionsChange).toHaveBeenCalledWith([range(7, 5)], false, false);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
- });
-
- it('does not reapply the same click-created formula reference on selection end', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 0,
- onSelectionsChange,
- });
-
- handler([range(7, 5)], false);
- handler([range(7, 5)], true);
-
- expect(onSelectionsChange).toHaveBeenCalledWith([range(7, 5)], false, false);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
- });
-
- it('commits duplicate selection end without reapplying formula text changes', () => {
- const onSelectionsChange = vi.fn();
- const onDuplicateEnd = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 0,
- onSelectionsChange,
- onDuplicateEnd,
- });
-
- handler([range(7, 5)], false);
- handler([range(7, 5)], true);
-
- expect(onSelectionsChange).toHaveBeenCalledWith([range(7, 5)], false, false);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
- expect(onDuplicateEnd).toHaveBeenCalledWith([range(7, 5)]);
- expect(onDuplicateEnd).toHaveBeenCalledTimes(1);
- });
-
- it('does not reapply the same click-created formula reference while selection is still moving', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 0,
- onSelectionsChange,
- });
-
- handler([range(7, 5)], false);
- handler([range(7, 5)], false);
-
- expect(onSelectionsChange).toHaveBeenCalledWith([range(7, 5)], false, false);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
- });
-
- it('previews a ctrl-added formula reference before selection end', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 1,
- onSelectionsChange,
- });
- const existingRange = range(7, 5);
- const addedRange = range(8, 6);
-
- handler([existingRange, addedRange], false);
-
- expect(onSelectionsChange).toHaveBeenCalledWith([existingRange, addedRange], false, true);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
- });
-
- it('updates a pending ctrl-added reference as the active reference while dragging', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 1,
- onSelectionsChange,
- });
- const existingRange = range(7, 5);
- const firstAddedRange = range(8, 6);
- const movedAddedRange = { ...range(8, 6), endRow: 10, endColumn: 8 };
-
- handler([existingRange, firstAddedRange], false);
- handler([existingRange, movedAddedRange], false);
-
- expect(onSelectionsChange).toHaveBeenNthCalledWith(1, [existingRange, firstAddedRange], false, true);
- expect(onSelectionsChange).toHaveBeenNthCalledWith(2, [existingRange, movedAddedRange], false, false);
- expect(onSelectionsChange).toHaveBeenCalledTimes(2);
- });
-
- it('does not append duplicate ctrl-added previews for the same range', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 1,
- onSelectionsChange,
- });
- const existingRange = range(7, 5);
- const addedRange = range(8, 6);
-
- handler([existingRange, addedRange], false);
- handler([existingRange, addedRange], false);
-
- expect(onSelectionsChange).toHaveBeenCalledWith([existingRange, addedRange], false, true);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
- });
-
- it('keeps ordinary same-count dragging in replace mode', () => {
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 2,
- onSelectionsChange,
- });
- const existingRange = range(7, 5);
- const movedRange = { ...range(8, 6), endRow: 10, endColumn: 8 };
-
- handler([existingRange, movedRange], false);
-
- expect(onSelectionsChange).toHaveBeenCalledWith([existingRange, movedRange], false, false);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
- });
-
- it('dedupes the same formula reference when selection end is reported by another source', () => {
- const duplicateEndGuard = createSelectionChangeDuplicateEndGuard();
- const onSelectionsChange = vi.fn();
- const handler = createSelectionChangeHandler({
- initialSelectionsCount: 0,
- duplicateEndGuard,
- onSelectionsChange,
- });
- const selectedRange = range(7, 5);
- const renderedRange = { ...selectedRange, startX: 10, endX: 20, startY: 30, endY: 40 };
-
- handler([renderedRange], false);
- if (!duplicateEndGuard.shouldSkip([selectedRange], true)) {
- onSelectionsChange([selectedRange], true);
- }
-
- expect(onSelectionsChange).toHaveBeenCalledWith([renderedRange], false, false);
- expect(onSelectionsChange).toHaveBeenCalledTimes(1);
- });
-
- it('matches formula selections by range identity instead of render coordinates', () => {
- expect(isSameFormulaSelection(
- { ...range(7, 5), startX: 10, endX: 20 },
- range(7, 5, 'other-sheet', 'other-unit')
- )).toBe(true);
- expect(isSameFormulaSelection(
- { ...range(7, 5), startX: 10, endX: 20 },
- range(7, 6)
- )).toBe(false);
- });
-
- it('shares duplicate formula selection guards across paired formula editors', () => {
- const guardFromCellEditor = getSharedSelectionChangeDuplicateEndGuard('unit1:sheet1:test');
- const guardFromFormulaBar = getSharedSelectionChangeDuplicateEndGuard('unit1:sheet1:test');
-
- expect(guardFromCellEditor.shouldSkip([range(7, 5)], false)).toBe(false);
- expect(guardFromFormulaBar.shouldSkip([range(7, 5)], false)).toBe(true);
-
- guardFromCellEditor.reset();
- });
-
- it('counts only rendered formula reference controls and parsed formula references as initial references', () => {
- expect(getInitialFormulaReferenceSelectionCount(0, 0)).toBe(0);
- expect(getInitialFormulaReferenceSelectionCount(0, 2)).toBe(2);
- expect(getInitialFormulaReferenceSelectionCount(1, 0)).toBe(1);
- expect(getInitialFormulaReferenceSelectionCount(1, 0, FormulaSelectingType.NEED_ADD)).toBe(1);
- expect(getInitialFormulaReferenceSelectionCount(1, 1, FormulaSelectingType.NEED_ADD)).toBe(1);
- });
-
- it('keeps formula control ranges scoped to the current selection unit and sheet', () => {
- const selections = [range(0, 0, 'sheet1', 'unit1')];
-
- expect(replaceFormulaControlSelection(selections, 0, range(2, 2, 'other-sheet', 'other-unit'))).toEqual([
- range(2, 2, 'sheet1', 'unit1'),
- ]);
- });
-
- it('ignores stale formula control events when the matching selection data is unavailable', () => {
- expect(replaceFormulaControlSelection([], 0, range(2, 2))).toBeUndefined();
- });
-
- it('returns no formula selection for empty selection events', () => {
- expect(getLastFormulaSelection([])).toBeUndefined();
- expect(getLastFormulaSelection([range(1, 1), range(2, 2)])).toEqual(range(2, 2));
- });
-});
-
-describe('formula highlight helpers', () => {
- it('does not cover the first highlighted character when there is no leading marker', () => {
- const textRuns = [{ st: 0, ed: 12, ts: { cl: { rgb: '#ff0000' } } }];
-
- expect(createHighlightTextRuns(textRuns, 0)).toEqual(textRuns);
- });
-
- it('does not copy stale paragraph metadata into a formula text replacement', () => {
- const body = createFormulaHighlightBody('=F40', [
- { st: 0, ed: 1, ts: { fs: 11 } },
- { st: 1, ed: 4, ts: { fs: 11 } },
- ]);
-
- expect(body).toEqual({
- dataStream: '=F40',
- textRuns: [
- { st: 0, ed: 1, ts: { fs: 11 } },
- { st: 1, ed: 4, ts: { fs: 11 } },
- ],
- });
- expect(body.paragraphs).toBeUndefined();
- expect(body.sectionBreaks).toBeUndefined();
- });
-
- it('preserves incomplete formula editor text while applying token highlights', () => {
- expect(getFormulaHighlightDataStream('=', [
- 'SUM(',
- { token: 'D37', nodeType: sequenceNodeType.REFERENCE, startIndex: 4, endIndex: 6 },
- ',',
- { token: 'F40', nodeType: sequenceNodeType.REFERENCE, startIndex: 8, endIndex: 10 },
- ], 'SUM(D37,F40,J36,J42')).toBe('=SUM(D37,F40,J36,J42\r\n');
- });
-
- it('builds colored text runs for references, numbers, strings, arrays, defined names, and plain text', () => {
- const result = buildFormulaTextRuns(
- { hasDefinedNameDescription: vi.fn((token: string) => token === 'SalesTotal') } as any,
- {
- formulaRefColors: ['#ff0000', '#00ff00'],
- numberColor: '#0000ff',
- stringColor: '#ff00ff',
- plainTextColor: '#111111',
- },
- [
- 'SUM(',
- { token: 'A1', nodeType: sequenceNodeType.REFERENCE, startIndex: 4, endIndex: 5 },
- ',',
- { token: '42', nodeType: sequenceNodeType.NUMBER, startIndex: 7, endIndex: 8 },
- { token: '"ok"', nodeType: sequenceNodeType.STRING, startIndex: 9, endIndex: 12 },
- { token: '{1,2}', nodeType: sequenceNodeType.ARRAY, startIndex: 13, endIndex: 17 },
- { token: 'SalesTotal', nodeType: sequenceNodeType.DEFINED_NAME, startIndex: 18, endIndex: 27 },
- { token: '+', nodeType: sequenceNodeType.NORMAL, startIndex: 28, endIndex: 28 },
- { token: 'A1', nodeType: sequenceNodeType.REFERENCE, startIndex: 29, endIndex: 30 },
- ]
- );
-
- expect(result.refSelections).toEqual([
- expect.objectContaining({ token: 'A1', themeColor: '#ff0000', refIndex: 1, index: 0 }),
- expect.objectContaining({ token: 'A1', themeColor: '#ff0000', refIndex: 8, index: 1 }),
- ]);
- expect(result.textRuns.map((run) => run.ts?.cl?.rgb)).toEqual([
- '#111111',
- '#ff0000',
- '#111111',
- '#0000ff',
- '#ff00ff',
- '#ff00ff',
- '#111111',
- '#111111',
- '#ff0000',
- ]);
- });
-
- it('calculates visible formula reference selections and activates the reference under the editor cursor', () => {
- const currentSelections = [{
- range: range(0, 0),
- primary: { actualRow: 9, actualColumn: 9 },
- }];
- const refSelectionsService = {
- getCurrentSelections: vi.fn(() => currentSelections),
- setSelections: vi.fn(),
- };
- const refSelectionsRenderService = {
- setActiveSelectionIndex: vi.fn(),
- resetActiveSelectionIndex: vi.fn(),
- };
- const workbook = {
- getUnitId: vi.fn(() => 'unit1'),
- getActiveSheet: vi.fn(() => ({
- getSheetId: () => 'sheet1',
- getName: () => 'Sheet1',
- getRowCount: () => 100,
- getColumnCount: () => 50,
- })),
- getSheetBySheetName: vi.fn((name: string) => name === 'Sheet2'
- ? { getSheetId: () => 'sheet2' }
- : { getSheetId: () => 'sheet1' }),
- };
- const univerInstanceService = {
- getUnit: vi.fn(() => workbook),
- };
- const result = calcHighlightRanges({
- unitId: 'unit1',
- subUnitId: 'sheet1',
- currentWorkbook: workbook as any,
- refSelections: [
- { token: 'A1', themeColor: '#ff0000', refIndex: 0, startIndex: 0, endIndex: 1, index: 0 },
- { token: 'Sheet2!A1', themeColor: '#00ff00', refIndex: 1, startIndex: 3, endIndex: 11, index: 1 },
- { token: 'Book2#Sheet1!A1', themeColor: '#0000ff', refIndex: 2, startIndex: 12, endIndex: 26, index: 2 },
- ],
- editor: {
- getSelectionRanges: vi.fn(() => [{ startOffset: 3 }]),
- } as any,
- refSelectionsService: refSelectionsService as any,
- refSelectionsRenderService: refSelectionsRenderService as any,
- sheetSkeletonManagerService: {
- getSkeleton: vi.fn(() => ({})),
- } as any,
- themeService: { getColorFromTheme: vi.fn((key: string) => key === 'gray.0' ? '#fff' : key) } as any,
- univerInstanceService: univerInstanceService as any,
- });
-
- expect(result).toHaveLength(2);
- expect(result?.[0].range).toMatchObject({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0, unitId: 'unit1', sheetId: 'sheet1' });
- expect(result?.[0].primary).toBe(currentSelections[0].primary);
- expect(result?.[0].style).toMatchObject({ stroke: '#ff0000', widgetStroke: '#fff' });
- expect(refSelectionsRenderService.setActiveSelectionIndex).toHaveBeenCalledWith(0);
- });
-
- it('does not assign the active keyboard selection primary to an earlier formula reference', () => {
- const activeKeyboardSelection = {
- range: range(7, 2),
- primary: { actualRow: 7, actualColumn: 2 },
- };
- const workbook = {
- getUnitId: vi.fn(() => 'unit1'),
- getActiveSheet: vi.fn(() => ({
- getSheetId: () => 'sheet1',
- getName: () => 'Sheet1',
- getRowCount: () => 100,
- getColumnCount: () => 50,
- })),
- getSheetBySheetName: vi.fn(() => ({ getSheetId: () => 'sheet1' })),
- };
-
- const result = calcHighlightRanges({
- unitId: 'unit1',
- subUnitId: 'sheet1',
- currentWorkbook: workbook as any,
- refSelections: [
- { token: 'C10', themeColor: '#ff0000', refIndex: 0, startIndex: 0, endIndex: 2, index: 0 },
- { token: 'C8', themeColor: '#00ff00', refIndex: 1, startIndex: 4, endIndex: 5, index: 1 },
- ],
- editor: undefined,
- refSelectionsService: {
- getCurrentSelections: vi.fn(() => [activeKeyboardSelection]),
- setSelections: vi.fn(),
- } as any,
- refSelectionsRenderService: undefined,
- sheetSkeletonManagerService: {
- getSkeleton: vi.fn(() => ({})),
- } as any,
- themeService: { getColorFromTheme: vi.fn((key: string) => key === 'gray.0' ? '#fff' : key) } as any,
- univerInstanceService: { getUnit: vi.fn(() => workbook) } as any,
- });
-
- expect(result?.[0].range).toMatchObject(range(9, 2));
- expect(result?.[0].primary).toBeUndefined();
- expect(result?.[1].range).toMatchObject(range(7, 2));
- expect(result?.[1].primary).toBe(activeKeyboardSelection.primary);
- });
-
- it('ignores primary-only selections when calculating formula reference highlight primary cells', () => {
- const workbook = {
- getUnitId: vi.fn(() => 'unit1'),
- getActiveSheet: vi.fn(() => ({
- getSheetId: () => 'sheet1',
- getName: () => 'Sheet1',
- getRowCount: () => 100,
- getColumnCount: () => 50,
- })),
- getSheetBySheetName: vi.fn(() => ({ getSheetId: () => 'sheet1' })),
- };
-
- const result = calcHighlightRanges({
- unitId: 'unit1',
- subUnitId: 'sheet1',
- currentWorkbook: workbook as any,
- refSelections: [
- { token: 'A1', themeColor: '#ff0000', refIndex: 0, startIndex: 0, endIndex: 1, index: 0 },
- ],
- editor: undefined,
- refSelectionsService: {
- getCurrentSelections: vi.fn(() => [{ primary: { actualRow: 9, actualColumn: 9 } }]),
- setSelections: vi.fn(),
- } as any,
- refSelectionsRenderService: undefined,
- sheetSkeletonManagerService: {
- getSkeleton: vi.fn(() => ({})),
- } as any,
- themeService: { getColorFromTheme: vi.fn((key: string) => key === 'gray.0' ? '#fff' : key) } as any,
- univerInstanceService: { getUnit: vi.fn(() => workbook) } as any,
- });
-
- expect(result?.[0].primary).toBeUndefined();
- });
-
- it('returns empty highlight selections when the workbook or active sheet is unavailable', () => {
- const refSelectionsService = {
- getCurrentSelections: vi.fn(() => []),
- setSelections: vi.fn(),
- };
-
- expect(calcHighlightRanges({
- unitId: 'missing',
- subUnitId: 'sheet1',
- currentWorkbook: { getUnitId: () => 'unit1' } as any,
- refSelections: [{ token: 'A1', themeColor: '#ff0000', refIndex: 0, startIndex: 0, endIndex: 1, index: 0 }],
- editor: undefined,
- refSelectionsService: refSelectionsService as any,
- refSelectionsRenderService: undefined,
- sheetSkeletonManagerService: undefined,
- themeService: { getColorFromTheme: vi.fn(() => '#fff') } as any,
- univerInstanceService: { getUnit: vi.fn(() => null) } as any,
- })).toEqual([]);
- expect(refSelectionsService.setSelections).not.toHaveBeenCalled();
- });
-});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-focus.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-focus.spec.ts
new file mode 100644
index 0000000000..31feb8e93f
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-focus.spec.ts
@@ -0,0 +1,119 @@
+/**
+ * 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.
+ */
+
+// @vitest-environment jsdom
+
+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, Injector } from '@univerjs/core';
+import { IEditorService } from '@univerjs/docs-ui';
+import { describe, expect, it, vi } from 'vitest';
+import { isEventTargetInSameFormulaEmbedInteractionBoundary } from '../../formula-embed-integration.service';
+import { focusFormulaEditor, hasActiveFormulaEmbedInteraction, shouldRefocusFormulaEditorOnMouseUp } from '../use-focus';
+
+describe('use-focus regression scenarios', () => {
+ it('does not rewrite editor selections while doc pointer selection is in progress', () => {
+ const editorService = {
+ focus: vi.fn(),
+ };
+ const editor = {
+ getEditorId: vi.fn(() => 'editor-1'),
+ getSelectionRanges: vi.fn(() => [{ startOffset: 1, endOffset: 1, collapsed: true }]),
+ setSelectionRanges: vi.fn(),
+ getDocumentData: vi.fn(() => ({ body: { dataStream: 'abc\r\n' } })),
+ docSelectionRenderService: {
+ isOnPointerEvent: true,
+ focus: vi.fn(),
+ },
+ };
+
+ const injector = new Injector();
+ injector.add([IEditorService, { useValue: { ...editorService, getEditor: () => editor } as never }]);
+ try {
+ const service = injector.get(IEditorService);
+ focusFormulaEditor(service, service.getEditor('editor-1')!);
+ expect(editor.setSelectionRanges).not.toHaveBeenCalled();
+ } finally {
+ injector.dispose();
+ }
+ });
+
+ it('does not refocus the formula editor on mouse-up when the editor is already focused', () => {
+ expect(shouldRefocusFormulaEditorOnMouseUp({
+ isFocusing: true,
+ isPointerSelecting: false,
+ })).toBe(false);
+ });
+
+ it('does not refocus the formula editor while pointer text selection is active', () => {
+ expect(shouldRefocusFormulaEditorOnMouseUp({
+ isFocusing: false,
+ isPointerSelecting: true,
+ })).toBe(false);
+ });
+
+ it('refocuses the formula editor on mouse-up only when focus was lost and no pointer selection is active', () => {
+ expect(shouldRefocusFormulaEditorOnMouseUp({
+ isFocusing: false,
+ isPointerSelecting: false,
+ })).toBe(true);
+ });
+
+ it('treats sheet range selection inside the same embed owner as an active formula interaction', () => {
+ const block = document.createElement('div');
+ const editorHost = document.createElement('div');
+ const sheetCanvas = document.createElement('canvas');
+ block.setAttribute('data-embed-interaction-boundary-owner', 'embed-1');
+ block.append(editorHost, sheetCanvas);
+ document.body.appendChild(block);
+
+ sheetCanvas.tabIndex = -1;
+ sheetCanvas.focus();
+
+ expect(isEventTargetInSameFormulaEmbedInteractionBoundary(editorHost, sheetCanvas)).toBe(true);
+ expect(hasActiveFormulaEmbedInteraction(editorHost)).toBe(true);
+
+ block.remove();
+ });
+});
+
+it.each([DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY])('focuses its own formula input when another instance has editor %s', (editorId) => {
+ const injector = new Injector();
+ const leftInput = document.createElement('div');
+ const rightInput = document.createElement('div');
+ for (const input of [leftInput, rightInput]) {
+ input.id = `__editor_${editorId}`;
+ input.tabIndex = -1;
+ document.body.appendChild(input);
+ }
+ const editor = {
+ getEditorId: () => editorId,
+ getSelectionRanges: () => [{ startOffset: 1, endOffset: 1 }],
+ setSelectionRanges: vi.fn(),
+ getDocumentData: () => ({ body: { dataStream: '=A1\r\n' } }),
+ docSelectionRenderService: { focus: () => rightInput.focus(), isOnPointerEvent: false },
+ };
+ injector.add([IEditorService, { useValue: { getEditor: () => editor, focus: () => rightInput.focus() } as never }]);
+ try {
+ const editorService = injector.get(IEditorService);
+ leftInput.focus();
+ focusFormulaEditor(editorService, editorService.getEditor(editorId)!);
+ expect(document.activeElement).toBe(rightInput);
+ expect(editor.setSelectionRanges).toHaveBeenCalledWith([{ startOffset: 1, endOffset: 1 }]);
+ } finally {
+ injector.dispose();
+ leftInput.remove();
+ rightInput.remove();
+ }
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-selection.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-selection.spec.ts
new file mode 100644
index 0000000000..de65e01ca7
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-formula-selection.spec.ts
@@ -0,0 +1,127 @@
+/**
+ * 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.
+ */
+
+// @vitest-environment jsdom
+
+import { describe, expect, it, vi } from 'vitest';
+import {
+ FormulaSelectingType,
+ resolveFormulaSelectingIntent,
+ resolveFormulaSelectionCursorIndex,
+ resolveFormulaSelectionDataStream,
+ resolveFormulaSelectionWorkbook,
+ shouldAddFormulaReference,
+ shouldSkipReferenceEditingByPointer,
+} from '../use-formula-selection';
+
+describe('use-formula-selection regression scenarios', () => {
+ it('only skips reference editing when pointer-origin editing is still disabled and click editing is allowed', () => {
+ expect(shouldSkipReferenceEditingByPointer(true)).toBe(true);
+ expect(shouldSkipReferenceEditingByPointer(true, true)).toBe(false);
+ expect(shouldSkipReferenceEditingByPointer(false)).toBe(false);
+ });
+
+ it('falls back to the formula editor workbook when the focused current workbook is unavailable', () => {
+ const fallbackWorkbook = { unitId: 'embedded-sheet' };
+
+ expect(resolveFormulaSelectionWorkbook(undefined, fallbackWorkbook)).toBe(fallbackWorkbook);
+ expect(resolveFormulaSelectionWorkbook(null, fallbackWorkbook)).toBe(fallbackWorkbook);
+ expect(resolveFormulaSelectionWorkbook({ unitId: 'current-sheet' }, fallbackWorkbook)).toEqual({ unitId: 'current-sheet' });
+ });
+
+ it('reads formula selection text from the formula editor instead of the current host document', () => {
+ const accessor = {
+ get: vi.fn(() => ({
+ getCurrentUniverDocInstance: vi.fn(() => ({
+ getBody: () => ({ dataStream: 'host document text\r\n' }),
+ })),
+ })),
+ };
+ const editor = {
+ getDocumentDataModel: vi.fn(() => ({
+ getBody: () => ({ dataStream: '=SUM(\r\n' }),
+ })),
+ };
+
+ expect(resolveFormulaSelectionDataStream(accessor as never, editor as never)).toEqual({
+ dataStream: '=SUM(\r\n',
+ offset: 0,
+ });
+ });
+
+ it('falls back to the editor unit when the formula editor document model has been disposed', () => {
+ const accessor = {
+ get: vi.fn(() => ({
+ getUnit: vi.fn((unitId: string) => unitId === 'formula-editor'
+ ? { getBody: () => ({ dataStream: '=A1\r\n' }) }
+ : undefined),
+ getCurrentUnitOfType: vi.fn(() => ({
+ getBody: () => ({ dataStream: 'host document text\r\n' }),
+ })),
+ })),
+ };
+ const editor = {
+ getDocumentDataModel: vi.fn(() => null),
+ };
+
+ expect(resolveFormulaSelectionDataStream(accessor as never, editor as never, 'formula-editor')).toEqual({
+ dataStream: '=A1\r\n',
+ offset: 0,
+ });
+ });
+
+ it('reads formula selection text from the editor unit before falling back to the current host document', () => {
+ const accessor = {
+ get: vi.fn(() => ({
+ getUnit: vi.fn((unitId: string) => unitId === 'formula-editor'
+ ? { getBody: () => ({ dataStream: '=A1\r\n' }) }
+ : undefined),
+ getCurrentUniverDocInstance: vi.fn(() => ({
+ getBody: () => ({ dataStream: 'host document text\r\n' }),
+ })),
+ })),
+ };
+
+ expect(resolveFormulaSelectionDataStream(accessor as never, undefined, 'formula-editor')).toEqual({
+ dataStream: '=A1\r\n',
+ offset: 0,
+ });
+ });
+
+ it('uses the end of a fresh formula when the editor selection offset is still stale', () => {
+ expect(resolveFormulaSelectionCursorIndex({ collapsed: true, startOffset: 0 }, '=')).toBe(1);
+ expect(resolveFormulaSelectionCursorIndex({ collapsed: true, startOffset: 0 }, '=SUM(')).toBe(5);
+ expect(resolveFormulaSelectionCursorIndex({ collapsed: true, startOffset: 0 }, 'plain')).toBe(0);
+ expect(resolveFormulaSelectionCursorIndex({ collapsed: true, startOffset: 2 }, '=A1')).toBe(2);
+ });
+
+ it('prefers adding a new formula reference when the cursor is after a delimiter', () => {
+ expect(resolveFormulaSelectingIntent(true, true)).toBe(FormulaSelectingType.NEED_ADD);
+ expect(resolveFormulaSelectingIntent(true, false)).toBe(FormulaSelectingType.NEED_ADD);
+ expect(resolveFormulaSelectingIntent(false, true)).toBe(FormulaSelectingType.CAN_EDIT);
+ expect(resolveFormulaSelectingIntent(false, false)).toBe(FormulaSelectingType.NOT_SELECT);
+ });
+
+ it('only arms reference picking after formula delimiters and operators', () => {
+ expect(shouldAddFormulaReference('=', 1)).toBe(true);
+ expect(shouldAddFormulaReference('=SUM(', 5)).toBe(true);
+ expect(shouldAddFormulaReference('=SUM(A1,', 8)).toBe(true);
+ expect(shouldAddFormulaReference('=A1+', 4)).toBe(true);
+ expect(shouldAddFormulaReference('=Sheet1!', 8)).toBe(true);
+ expect(shouldAddFormulaReference('=SUM', 4)).toBe(false);
+ expect(shouldAddFormulaReference('=A1', 3)).toBe(false);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-highlight.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-highlight.spec.ts
new file mode 100644
index 0000000000..9a2e750b0a
--- /dev/null
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-highlight.spec.ts
@@ -0,0 +1,211 @@
+/**
+ * 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.
+ */
+
+// @vitest-environment jsdom
+
+import { describe, expect, it, vi } from 'vitest';
+import { calcHighlightRanges, createFormulaHighlightBody, createHighlightTextRuns } from '../use-highlight';
+
+function range(row: number, col: number, sheetId = 'sheet1', unitId = 'unit1') {
+ return {
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ sheetId,
+ unitId,
+ };
+}
+
+describe('use-highlight regression scenarios', () => {
+ it('does not cover the first highlighted character when there is no leading marker', () => {
+ const textRuns = [{ st: 0, ed: 12, ts: { cl: { rgb: '#ff0000' } } }];
+
+ expect(createHighlightTextRuns(textRuns, 0)).toEqual(textRuns);
+ });
+
+ it('does not copy stale paragraph metadata into a formula text replacement', () => {
+ const body = createFormulaHighlightBody('=F40', [
+ { st: 0, ed: 1, ts: { fs: 11 } },
+ { st: 1, ed: 4, ts: { fs: 11 } },
+ ]);
+
+ expect(body).toEqual({
+ dataStream: '=F40',
+ textRuns: [
+ { st: 0, ed: 1, ts: { fs: 11 } },
+ { st: 1, ed: 4, ts: { fs: 11 } },
+ ],
+ });
+ expect(body.paragraphs).toBeUndefined();
+ expect(body.sectionBreaks).toBeUndefined();
+ });
+
+ it('calculates visible formula reference selections and activates the reference under the editor cursor', () => {
+ const currentSelections = [{
+ range: range(0, 0),
+ primary: { actualRow: 9, actualColumn: 9 },
+ }];
+ const refSelectionsService = {
+ getCurrentSelections: vi.fn(() => currentSelections),
+ setSelections: vi.fn(),
+ };
+ const refSelectionsRenderService = {
+ setActiveSelectionIndex: vi.fn(),
+ resetActiveSelectionIndex: vi.fn(),
+ };
+ const workbook = {
+ getUnitId: vi.fn(() => 'unit1'),
+ getActiveSheet: vi.fn(() => ({
+ getSheetId: () => 'sheet1',
+ getName: () => 'Sheet1',
+ getRowCount: () => 100,
+ getColumnCount: () => 50,
+ })),
+ getSheetBySheetName: vi.fn((name: string) => name === 'Sheet2'
+ ? { getSheetId: () => 'sheet2' }
+ : { getSheetId: () => 'sheet1' }),
+ };
+ const univerInstanceService = {
+ getUnit: vi.fn(() => workbook),
+ };
+ const result = calcHighlightRanges({
+ unitId: 'unit1',
+ subUnitId: 'sheet1',
+ currentWorkbook: workbook as never,
+ refSelections: [
+ { token: 'A1', themeColor: '#ff0000', refIndex: 0, startIndex: 0, endIndex: 1, index: 0 },
+ { token: 'Sheet2!A1', themeColor: '#00ff00', refIndex: 1, startIndex: 3, endIndex: 11, index: 1 },
+ { token: 'Book2#Sheet1!A1', themeColor: '#0000ff', refIndex: 2, startIndex: 12, endIndex: 26, index: 2 },
+ ],
+ editor: {
+ getSelectionRanges: vi.fn(() => [{ startOffset: 3 }]),
+ } as never,
+ refSelectionsService: refSelectionsService as never,
+ refSelectionsRenderService: refSelectionsRenderService as never,
+ sheetSkeletonManagerService: {
+ getSkeleton: vi.fn(() => ({})),
+ } as never,
+ themeService: { getColorFromTheme: vi.fn((key: string) => key === 'gray.0' ? '#fff' : key) } as never,
+ univerInstanceService: univerInstanceService as never,
+ });
+
+ expect(result).toHaveLength(2);
+ expect(result?.[0].range).toMatchObject({ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0, unitId: 'unit1', sheetId: 'sheet1' });
+ expect(result?.[0].primary).toBe(currentSelections[0].primary);
+ expect(result?.[0].style).toMatchObject({ stroke: '#ff0000', widgetStroke: '#fff' });
+ expect(refSelectionsRenderService.setActiveSelectionIndex).toHaveBeenCalledWith(0);
+ });
+
+ it('does not assign the active keyboard selection primary to an earlier formula reference', () => {
+ const activeKeyboardSelection = {
+ range: range(7, 2),
+ primary: { actualRow: 7, actualColumn: 2 },
+ };
+ const workbook = {
+ getUnitId: vi.fn(() => 'unit1'),
+ getActiveSheet: vi.fn(() => ({
+ getSheetId: () => 'sheet1',
+ getName: () => 'Sheet1',
+ getRowCount: () => 100,
+ getColumnCount: () => 50,
+ })),
+ getSheetBySheetName: vi.fn(() => ({ getSheetId: () => 'sheet1' })),
+ };
+
+ const result = calcHighlightRanges({
+ unitId: 'unit1',
+ subUnitId: 'sheet1',
+ currentWorkbook: workbook as never,
+ refSelections: [
+ { token: 'C10', themeColor: '#ff0000', refIndex: 0, startIndex: 0, endIndex: 2, index: 0 },
+ { token: 'C8', themeColor: '#00ff00', refIndex: 1, startIndex: 4, endIndex: 5, index: 1 },
+ ],
+ editor: undefined,
+ refSelectionsService: {
+ getCurrentSelections: vi.fn(() => [activeKeyboardSelection]),
+ setSelections: vi.fn(),
+ } as never,
+ refSelectionsRenderService: undefined,
+ sheetSkeletonManagerService: {
+ getSkeleton: vi.fn(() => ({})),
+ } as never,
+ themeService: { getColorFromTheme: vi.fn((key: string) => key === 'gray.0' ? '#fff' : key) } as never,
+ univerInstanceService: { getUnit: vi.fn(() => workbook) } as never,
+ });
+
+ expect(result?.[0].range).toMatchObject(range(9, 2));
+ expect(result?.[0].primary).toBeUndefined();
+ expect(result?.[1].range).toMatchObject(range(7, 2));
+ expect(result?.[1].primary).toBe(activeKeyboardSelection.primary);
+ });
+
+ it('ignores primary-only selections when calculating formula reference highlight primary cells', () => {
+ const workbook = {
+ getUnitId: vi.fn(() => 'unit1'),
+ getActiveSheet: vi.fn(() => ({
+ getSheetId: () => 'sheet1',
+ getName: () => 'Sheet1',
+ getRowCount: () => 100,
+ getColumnCount: () => 50,
+ })),
+ getSheetBySheetName: vi.fn(() => ({ getSheetId: () => 'sheet1' })),
+ };
+
+ const result = calcHighlightRanges({
+ unitId: 'unit1',
+ subUnitId: 'sheet1',
+ currentWorkbook: workbook as never,
+ refSelections: [
+ { token: 'A1', themeColor: '#ff0000', refIndex: 0, startIndex: 0, endIndex: 1, index: 0 },
+ ],
+ editor: undefined,
+ refSelectionsService: {
+ getCurrentSelections: vi.fn(() => [{ primary: { actualRow: 9, actualColumn: 9 } }]),
+ setSelections: vi.fn(),
+ } as never,
+ refSelectionsRenderService: undefined,
+ sheetSkeletonManagerService: {
+ getSkeleton: vi.fn(() => ({})),
+ } as never,
+ themeService: { getColorFromTheme: vi.fn((key: string) => key === 'gray.0' ? '#fff' : key) } as never,
+ univerInstanceService: { getUnit: vi.fn(() => workbook) } as never,
+ });
+
+ expect(result?.[0].primary).toBeUndefined();
+ });
+
+ it('returns empty highlight selections when the workbook or active sheet is unavailable', () => {
+ const refSelectionsService = {
+ getCurrentSelections: vi.fn(() => []),
+ setSelections: vi.fn(),
+ };
+
+ expect(calcHighlightRanges({
+ unitId: 'missing',
+ subUnitId: 'sheet1',
+ currentWorkbook: { getUnitId: () => 'unit1' } as never,
+ refSelections: [{ token: 'A1', themeColor: '#ff0000', refIndex: 0, startIndex: 0, endIndex: 1, index: 0 }],
+ editor: undefined,
+ refSelectionsService: refSelectionsService as never,
+ refSelectionsRenderService: undefined,
+ sheetSkeletonManagerService: undefined,
+ themeService: { getColorFromTheme: vi.fn(() => '#fff') } as never,
+ univerInstanceService: { getUnit: vi.fn(() => null) } as never,
+ })).toEqual([]);
+ expect(refSelectionsService.setSelections).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsx b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsx
index dceea03f73..a4b5634063 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-left-and-right-arrow.spec.tsx
@@ -51,12 +51,7 @@ import {
UniverDocsUIPlugin,
} from '@univerjs/docs-ui';
import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
-import {
- IRefSelectionsService,
- REF_SELECTIONS_ENABLED,
- SetSelectionsOperation,
- SheetsSelectionsService,
-} from '@univerjs/sheets';
+import { IRefSelectionsService, REF_SELECTIONS_ENABLED, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
import { ExpandSelectionCommand, JumpOver, MoveSelectionCommand, UniverSheetsUIPlugin } from '@univerjs/sheets-ui';
import {
ComponentManager,
@@ -73,7 +68,11 @@ import { act } from 'react';
import { createRoot } from 'react-dom/client';
import { describe, expect, it, vi } from 'vitest';
import { FormulaSelectingType } from '../use-formula-selection';
-import { useLeftAndRightArrow } from '../use-left-and-right-arrow';
+import {
+ isFormulaEditorInteractionOwner,
+ shouldMoveFormulaSelectionFromCurrentSelection,
+ useLeftAndRightArrow,
+} from '../use-left-and-right-arrow';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -323,3 +322,44 @@ describe('formula editor text navigation', () => {
}
});
});
+
+describe('use-left-and-right-arrow regression scenarios', () => {
+ it('treats the hidden normal editor as the fx bar owner while the fx bar owns formula selection', () => {
+ expect(isFormulaEditorInteractionOwner(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, {
+ fxBarFocused: true,
+ })).toBe(true);
+ });
+
+ it('lets the fx bar own formula selection when the canvas leaves no focused editor', () => {
+ expect(isFormulaEditorInteractionOwner(null, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, {
+ fxBarFocused: true,
+ allowMissingFocus: true,
+ })).toBe(true);
+ });
+
+ it('does not let the hidden normal editor own the fx bar outside an fx formula selection session', () => {
+ expect(isFormulaEditorInteractionOwner(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, {
+ fxBarFocused: false,
+ })).toBe(false);
+ });
+
+ it('starts the first keyboard-added formula reference from the edited cell selection', () => {
+ expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.NEED_ADD, 0)).toBe(true);
+ });
+
+ it('routes formula editor interactions only to the focused formula editor', () => {
+ expect(isFormulaEditorInteractionOwner('__INTERNAL_EDITOR__DOCS_NORMAL', '__INTERNAL_EDITOR__DOCS_NORMAL')).toBe(true);
+ expect(isFormulaEditorInteractionOwner('__INTERNAL_EDITOR__DOCS_FORMULA_BAR', '__INTERNAL_EDITOR__DOCS_NORMAL')).toBe(false);
+ expect(isFormulaEditorInteractionOwner(null, '__INTERNAL_EDITOR__DOCS_NORMAL')).toBe(false);
+ });
+
+ it('continues keyboard-added formula references from the last reference selection after a delimiter', () => {
+ expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.NEED_ADD, 1)).toBe(false);
+ expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.NEED_ADD, 2)).toBe(false);
+ });
+
+ it('keeps cross-sheet reference editing anchored to the current sheet selection', () => {
+ expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.EDIT_OTHER_SHEET_REFERENCE, 1)).toBe(true);
+ expect(shouldMoveFormulaSelectionFromCurrentSelection(FormulaSelectingType.CAN_EDIT, 1)).toBe(false);
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-sheet-selection-change.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-sheet-selection-change.spec.ts
index c9af1ee39b..27679a5980 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-sheet-selection-change.spec.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/__tests__/use-sheet-selection-change.spec.ts
@@ -15,8 +15,27 @@
*/
import type { IRange } from '@univerjs/core';
+import {
+ getFormulaSequenceCharacterAtOffset,
+ isFormulaReferenceAddingContext,
+ isFormulaReferenceAddingTextContext,
+ sequenceNodeType,
+} from '@univerjs/engine-formula';
import { describe, expect, it, vi } from 'vitest';
-import { createSelectionChangeDuplicateEndGuard, createSelectionChangeHandler } from '../use-sheet-selection-change';
+import { FormulaSelectingType } from '../use-formula-selection';
+import {
+ createSelectionChangeDuplicateEndGuard,
+ createSelectionChangeHandler,
+ getInitialFormulaReferenceSelectionCount,
+ getLastFormulaSelection,
+ getSelectionsForFormulaRefUpdate,
+ getSharedSelectionChangeDuplicateEndGuard,
+ insertFormulaReferenceText,
+ isSameFormulaSelection,
+ prepareSelectionChangeContext,
+ replaceFormulaControlSelection,
+ shouldSkipFormulaReferenceUpdate,
+} from '../use-sheet-selection-change';
describe('formula reference selection gesture boundaries', () => {
it.each([false, true])('accepts the same reference in a new editor after the previous gesture ends: %s', (completed) => {
@@ -48,3 +67,306 @@ describe('formula reference selection gesture boundaries', () => {
expect(commit).toHaveBeenCalledExactlyOnceWith([selectedRange]);
});
});
+
+function range(row: number, col: number, sheetId = 'sheet1', unitId = 'unit1') {
+ return {
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ sheetId,
+ unitId,
+ };
+}
+
+describe('use-sheet-selection-change regression scenarios', () => {
+ it('reorders the active selection into the formula reference being edited and keeps ctrl-added ranges separate', () => {
+ const selections = [range(0, 0), range(1, 1), range(2, 2)];
+
+ expect(getSelectionsForFormulaRefUpdate(selections, 0)).toEqual({
+ orderedSelections: [range(2, 2), range(0, 0), range(1, 1)],
+ });
+ expect(getSelectionsForFormulaRefUpdate(selections, 1, true)).toEqual({
+ orderedSelections: [range(0, 0), range(1, 1)],
+ insertedSelection: range(2, 2),
+ });
+ expect(getSelectionsForFormulaRefUpdate(selections, -1)).toEqual({
+ orderedSelections: selections,
+ });
+ });
+
+ it('previews ctrl-add selection updates before move end and ignores initial selection events', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 1,
+ onSelectionsChange,
+ });
+
+ handler([range(0, 0)], true, { initial: true });
+ handler([range(0, 0), range(1, 1)], false);
+ expect(onSelectionsChange).toHaveBeenCalledWith([range(0, 0), range(1, 1)], false, true);
+
+ handler([range(0, 0), range(1, 1)], true);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+
+ handler([range(3, 3)], false);
+ expect(onSelectionsChange).toHaveBeenLastCalledWith([range(3, 3)], false, false);
+ });
+
+ it('ignores replayed initial formula references when no initial reference selection exists', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 0,
+ onSelectionsChange,
+ });
+
+ handler([range(7, 5)], true, { initial: true });
+
+ expect(onSelectionsChange).not.toHaveBeenCalled();
+ });
+
+ it('uses the formula text end as the insertion context when the embedded editor selection is temporarily empty', () => {
+ const lexerTreeBuilder = {
+ sequenceNodesBuilder: vi.fn(() => []),
+ };
+ const editor = {
+ getSelectionRanges: vi.fn(() => []),
+ getDocumentData: vi.fn(() => ({ body: { dataStream: '=\r\n' } })),
+ };
+
+ expect(prepareSelectionChangeContext({
+ editor: editor as never,
+ lexerTreeBuilder: lexerTreeBuilder as never,
+ })).toMatchObject({
+ offset: 0,
+ nodeIndex: -1,
+ updatingRefIndex: -1,
+ sequenceNodes: [],
+ });
+ });
+
+ it('does not create a fallback formula context for non-formula editor text', () => {
+ const lexerTreeBuilder = {
+ sequenceNodesBuilder: vi.fn(() => []),
+ };
+ const editor = {
+ getSelectionRanges: vi.fn(() => []),
+ getDocumentData: vi.fn(() => ({ body: { dataStream: 'plain\r\n' } })),
+ };
+
+ expect(prepareSelectionChangeContext({
+ editor: editor as never,
+ lexerTreeBuilder: lexerTreeBuilder as never,
+ })).toBeUndefined();
+ });
+
+ it('recognizes delimiter-adjacent formula context as a new reference insertion point', () => {
+ const nodes = [
+ { token: 'M28', nodeType: sequenceNodeType.REFERENCE },
+ ',',
+ ];
+
+ expect(getFormulaSequenceCharacterAtOffset(nodes, 3)).toBe('8');
+ expect(getFormulaSequenceCharacterAtOffset(nodes, 4)).toBe(',');
+ expect(isFormulaReferenceAddingContext(nodes, 3)).toBe(false);
+ expect(isFormulaReferenceAddingContext(nodes, 4)).toBe(true);
+ expect(isFormulaReferenceAddingTextContext('M28,', 4)).toBe(true);
+ expect(insertFormulaReferenceText('M28,', 'M27', 4)).toBe('M28,M27');
+ });
+
+ it('skips stale non-add formula selection updates when no rendered reference exists', () => {
+ expect(shouldSkipFormulaReferenceUpdate(false, 0)).toBe(true);
+ expect(shouldSkipFormulaReferenceUpdate(false, 1)).toBe(false);
+ expect(shouldSkipFormulaReferenceUpdate(true, 0)).toBe(false);
+ });
+
+ it('applies a click-created formula reference from selection start before pointer-up controls are reset', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 0,
+ onSelectionsChange,
+ });
+
+ handler([range(7, 5)], false);
+ handler([], true);
+
+ expect(onSelectionsChange).toHaveBeenCalledWith([range(7, 5)], false, false);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not reapply the same click-created formula reference on selection end', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 0,
+ onSelectionsChange,
+ });
+
+ handler([range(7, 5)], false);
+ handler([range(7, 5)], true);
+
+ expect(onSelectionsChange).toHaveBeenCalledWith([range(7, 5)], false, false);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('commits duplicate selection end without reapplying formula text changes', () => {
+ const onSelectionsChange = vi.fn();
+ const onDuplicateEnd = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 0,
+ onSelectionsChange,
+ onDuplicateEnd,
+ });
+
+ handler([range(7, 5)], false);
+ handler([range(7, 5)], true);
+
+ expect(onSelectionsChange).toHaveBeenCalledWith([range(7, 5)], false, false);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+ expect(onDuplicateEnd).toHaveBeenCalledWith([range(7, 5)]);
+ expect(onDuplicateEnd).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not reapply the same click-created formula reference while selection is still moving', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 0,
+ onSelectionsChange,
+ });
+
+ handler([range(7, 5)], false);
+ handler([range(7, 5)], false);
+
+ expect(onSelectionsChange).toHaveBeenCalledWith([range(7, 5)], false, false);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('previews a ctrl-added formula reference before selection end', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 1,
+ onSelectionsChange,
+ });
+ const existingRange = range(7, 5);
+ const addedRange = range(8, 6);
+
+ handler([existingRange, addedRange], false);
+
+ expect(onSelectionsChange).toHaveBeenCalledWith([existingRange, addedRange], false, true);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('updates a pending ctrl-added reference as the active reference while dragging', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 1,
+ onSelectionsChange,
+ });
+ const existingRange = range(7, 5);
+ const firstAddedRange = range(8, 6);
+ const movedAddedRange = { ...range(8, 6), endRow: 10, endColumn: 8 };
+
+ handler([existingRange, firstAddedRange], false);
+ handler([existingRange, movedAddedRange], false);
+
+ expect(onSelectionsChange).toHaveBeenNthCalledWith(1, [existingRange, firstAddedRange], false, true);
+ expect(onSelectionsChange).toHaveBeenNthCalledWith(2, [existingRange, movedAddedRange], false, false);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not append duplicate ctrl-added previews for the same range', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 1,
+ onSelectionsChange,
+ });
+ const existingRange = range(7, 5);
+ const addedRange = range(8, 6);
+
+ handler([existingRange, addedRange], false);
+ handler([existingRange, addedRange], false);
+
+ expect(onSelectionsChange).toHaveBeenCalledWith([existingRange, addedRange], false, true);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps ordinary same-count dragging in replace mode', () => {
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 2,
+ onSelectionsChange,
+ });
+ const existingRange = range(7, 5);
+ const movedRange = { ...range(8, 6), endRow: 10, endColumn: 8 };
+
+ handler([existingRange, movedRange], false);
+
+ expect(onSelectionsChange).toHaveBeenCalledWith([existingRange, movedRange], false, false);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('dedupes the same formula reference when selection end is reported by another source', () => {
+ const duplicateEndGuard = createSelectionChangeDuplicateEndGuard();
+ const onSelectionsChange = vi.fn();
+ const handler = createSelectionChangeHandler({
+ initialSelectionsCount: 0,
+ duplicateEndGuard,
+ onSelectionsChange,
+ });
+ const selectedRange = range(7, 5);
+ const renderedRange = { ...selectedRange, startX: 10, endX: 20, startY: 30, endY: 40 };
+
+ handler([renderedRange], false);
+ if (!duplicateEndGuard.shouldSkip([selectedRange], true)) {
+ onSelectionsChange([selectedRange], true);
+ }
+
+ expect(onSelectionsChange).toHaveBeenCalledWith([renderedRange], false, false);
+ expect(onSelectionsChange).toHaveBeenCalledTimes(1);
+ });
+
+ it('matches formula selections by range identity instead of render coordinates', () => {
+ expect(isSameFormulaSelection(
+ { ...range(7, 5), startX: 10, endX: 20 },
+ range(7, 5, 'other-sheet', 'other-unit')
+ )).toBe(true);
+ expect(isSameFormulaSelection(
+ { ...range(7, 5), startX: 10, endX: 20 },
+ range(7, 6)
+ )).toBe(false);
+ });
+
+ it('shares duplicate formula selection guards across paired formula editors', () => {
+ const guardFromCellEditor = getSharedSelectionChangeDuplicateEndGuard('unit1:sheet1:test');
+ const guardFromFormulaBar = getSharedSelectionChangeDuplicateEndGuard('unit1:sheet1:test');
+
+ expect(guardFromCellEditor.shouldSkip([range(7, 5)], false)).toBe(false);
+ expect(guardFromFormulaBar.shouldSkip([range(7, 5)], false)).toBe(true);
+
+ guardFromCellEditor.reset();
+ });
+
+ it('counts only rendered formula reference controls and parsed formula references as initial references', () => {
+ expect(getInitialFormulaReferenceSelectionCount(0, 0)).toBe(0);
+ expect(getInitialFormulaReferenceSelectionCount(0, 2)).toBe(2);
+ expect(getInitialFormulaReferenceSelectionCount(1, 0)).toBe(1);
+ expect(getInitialFormulaReferenceSelectionCount(1, 0, FormulaSelectingType.NEED_ADD)).toBe(1);
+ expect(getInitialFormulaReferenceSelectionCount(1, 1, FormulaSelectingType.NEED_ADD)).toBe(1);
+ });
+
+ it('keeps formula control ranges scoped to the current selection unit and sheet', () => {
+ const selections = [range(0, 0, 'sheet1', 'unit1')];
+
+ expect(replaceFormulaControlSelection(selections, 0, range(2, 2, 'other-sheet', 'other-unit'))).toEqual([
+ range(2, 2, 'sheet1', 'unit1'),
+ ]);
+ });
+
+ it('ignores stale formula control events when the matching selection data is unavailable', () => {
+ expect(replaceFormulaControlSelection([], 0, range(2, 2))).toBeUndefined();
+ });
+
+ it('returns no formula selection for empty selection events', () => {
+ expect(getLastFormulaSelection([])).toBeUndefined();
+ expect(getLastFormulaSelection([range(1, 1), range(2, 2)])).toEqual(range(2, 2));
+ });
+});
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-focus.ts b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-focus.ts
index 3cd4ec108b..6823eeafbb 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-focus.ts
+++ b/packages/sheets-formula-ui/src/views/formula-editor/hooks/use-focus.ts
@@ -22,7 +22,7 @@ import { isEventTargetInSameFormulaEmbedInteractionBoundary } from '../formula-e
export function focusFormulaEditor(
editorService: Pick<IEditorService, 'focus'>,
- editor?: Pick<Editor, 'getEditorId' | 'getSelectionRanges' | 'setSelectionRanges' | 'getDocumentData' | 'docSelectionRenderService'> & { editorDOM?: HTMLElement },
+ editor?: Pick<Editor, 'getEditorId' | 'getSelectionRanges' | 'setSelectionRanges' | 'getDocumentData' | 'docSelectionRenderService'>,
offset?: number
) {
if (!editor) {
@@ -32,7 +32,7 @@ export function focusFormulaEditor(
// Blurring the previous editor can publish its stale rendered selection.
const selections = [...editor.getSelectionRanges()];
editorService.focus(editor.getEditorId());
- focusFormulaEditorElement(editor);
+ editor.docSelectionRenderService.focus();
if (editor.docSelectionRenderService.isOnPointerEvent) {
return;
}
@@ -48,25 +48,10 @@ export function focusFormulaEditor(
}
}
-function focusFormulaEditorElement(editor: Pick<Editor, 'getEditorId'> & { editorDOM?: HTMLElement }): void {
- const ownerDocument = editor.editorDOM?.ownerDocument ?? document;
- const editorElement = ownerDocument.getElementById(`__editor_${editor.getEditorId()}`);
- editorElement?.focus({ preventScroll: true });
-}
-
-export function shouldSkipFormulaEditorMouseUpFocus(_target: EventTarget | null): boolean {
- return false;
-}
-
export function shouldRefocusFormulaEditorOnMouseUp(options: {
- target: EventTarget | null;
isFocusing: boolean | undefined;
isPointerSelecting: boolean | undefined;
}): boolean {
- if (shouldSkipFormulaEditorMouseUpFocus(options.target)) {
- return false;
- }
-
if (options.isPointerSelecting || options.isFocusing) {
return false;
}
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
index 210120b281..c3a43fb092 100644
--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx
@@ -418,6 +418,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
element: formulaEditorContainer,
}));
collection.add(registerFormulaEditorRuntimePortal({
+ editorService,
embedId: scope.embedId,
editorId,
ownerDocument: formulaEditorContainer.ownerDocument,
@@ -426,7 +427,7 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
}));
return () => collection.dispose();
- }, [editorId, injector, isFocus]);
+ }, [editorId, editorService, injector, isFocus]);
useLayoutEffect(() => {
let focusRetryFrame = 0;
@@ -532,12 +533,11 @@ export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IF
}
};
- const handleMouseUp = (event: React.MouseEvent<HTMLDivElement>) => {
+ const handleMouseUp = () => {
if (hasActiveFormulaEmbedInteraction(formulaEditorContainerRef.current)) {
return;
}
if (!shouldRefocusFormulaEditorOnMouseUp({
- target: event.target,
isFocusing,
isPointerSelecting: docSelectionRenderService?.isOnPointerEvent,
})) {
diff --git a/packages/sheets-formula-ui/src/views/mobile/formula-editor/MobileFormulaEditor.tsx b/packages/sheets-formula-ui/src/views/mobile/formula-editor/MobileFormulaEditor.tsx
index 2333a6c2de..fc881fd3a8 100644
--- a/packages/sheets-formula-ui/src/views/mobile/formula-editor/MobileFormulaEditor.tsx
+++ b/packages/sheets-formula-ui/src/views/mobile/formula-editor/MobileFormulaEditor.tsx
@@ -511,6 +511,7 @@ export const MobileFormulaEditor = forwardRef((props: IMobileFormulaEditorProps,
element: formulaEditorContainer,
}));
collection.add(registerFormulaEditorRuntimePortal({
+ editorService,
embedId: scope.embedId,
editorId,
ownerDocument: formulaEditorContainer.ownerDocument,
@@ -519,7 +520,7 @@ export const MobileFormulaEditor = forwardRef((props: IMobileFormulaEditorProps,
}));
return () => collection.dispose();
- }, [editorId, injector, isFocus]);
+ }, [editorId, editorService, injector, isFocus]);
useLayoutEffect(() => {
let focusRetryFrame = 0;
@@ -694,12 +695,11 @@ export const MobileFormulaEditor = forwardRef((props: IMobileFormulaEditorProps,
});
};
- const handleMouseUp = (event: React.MouseEvent<HTMLDivElement>) => {
+ const handleMouseUp = () => {
if (hasActiveFormulaEmbedInteraction(formulaEditorContainerRef.current)) {
return;
}
if (!shouldRefocusFormulaEditorOnMouseUp({
- target: event.target,
isFocusing,
isPointerSelecting: docSelectionRenderService?.isOnPointerEvent,
})) {
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index ef102ceac7..b18983a9da 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -296,13 +296,14 @@ export { AutoFillPopupMenu } from './views/auto-fill-popup-menu/AutoFillPopupMen
export { BorderLine } from './views/border-panel/border-line/BorderLine';
export { BORDER_LINE_CHILDREN, BORDER_SIZE_CHILDREN } from './views/border-panel/interface';
export { DEFINED_NAME_CONTAINER } from './views/defined-name/component-name';
-export { EditorContainer, useKeyEventConfig } from './views/editor-container';
+export { EditorContainer } from './views/editor-container/EditorContainer';
+export { useKeyEventConfig } from './views/editor-container/hooks';
export { FormulaBar } from './views/formula-bar';
export { useActiveWorkbook, useActiveWorksheet, useWorkbooks } from './views/hook';
export type { IRangeProtectionRenderCellData } from './views/permission/extensions/range-protection.render';
-export { type IPermissionDetailUserPartProps } from './views/permission/panel-detail/PermissionDetailUserPart';
-export { type IBaseSheetBarProps } from './views/sheet-bar/sheet-bar-tabs/SheetBarItem';
+export type { IPermissionDetailUserPartProps } from './views/permission/panel-detail/PermissionDetailUserPart';
+export type { IBaseSheetBarProps } from './views/sheet-bar/sheet-bar-tabs/SheetBarItem';
export { SheetBar } from './views/sheet-bar/SheetBar';
export { SHEET_FOOTER_BAR_HEIGHT } from './views/sheet-container/SheetContainer';
-export { type IStatisticItem } from './views/status-bar/CopyableStatisticItem';
+export type { IStatisticItem } from './views/status-bar/CopyableStatisticItem';
export { functionDisplayNames } from './views/status-bar/CopyableStatisticItem';
diff --git a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
index c67a305fef..50b94afc65 100644
--- a/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
+++ b/packages/sheets-ui/src/views/editor-container/EditorContainer.tsx
@@ -360,7 +360,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
return;
}
- focusSheetCellEditorElement(ownerDocument);
+ focusSheetCellEditorElement(editorService);
if (delayedFocusTimer != null) {
ownerWindow.clearTimeout(delayedFocusTimer);
}
@@ -369,7 +369,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
if (shouldPreserveEmbedInteractiveFocus(scope?.embedId, ownerDocument)) {
return;
}
- focusSheetCellEditorElement(ownerDocument);
+ focusSheetCellEditorElement(editorService);
}, 0);
};
const focusEditor = () => {
@@ -384,13 +384,6 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
return;
}
- const editor = editorService.getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
- const docSelectionRenderService = editor?.render.with(DocSelectionRenderService);
-
- if (!docSelectionRenderService?.isFocusing) {
- docSelectionRenderService?.focus();
- }
-
focusCellEditorElement();
};
@@ -460,6 +453,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
element: editorRoot,
}));
collection.add(registerSheetCellEditorRuntimePortal({
+ editorService,
embedId: scope.embedId,
ownerDocument: rootRef.current.ownerDocument,
interactionBoundaryService,
@@ -473,14 +467,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
return;
}
- const editor = editorService.getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
- const docSelectionRenderService = editor?.render.with(DocSelectionRenderService);
-
- if (!docSelectionRenderService?.isFocusing) {
- docSelectionRenderService?.focus();
- }
-
- focusSheetCellEditorElement(ownerDocument);
+ focusSheetCellEditorElement(editorService);
};
const refocusEditorAfterRuntimePointer = (event: PointerEvent | MouseEvent) => {
if (!focusCoordinator.isChildUnitRuntimeEvent(scope.childUnitId, event.target, event) || isEmbedRuntimeEditorOrPopup(event.target)) {
@@ -530,6 +517,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
? injector.get(ISheetEmbedInteractionBoundaryService)
: undefined;
const portalRegistration = registerSheetCellEditorRuntimePortal({
+ editorService,
embedId: activeSessionScope.embedId,
ownerDocument,
interactionBoundaryService,
@@ -542,7 +530,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
return;
}
- focusSheetCellEditorElement(ownerDocument);
+ focusSheetCellEditorElement(editorService);
if (delayedFocusTimer != null) {
ownerWindow.clearTimeout(delayedFocusTimer);
}
@@ -551,7 +539,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
if (shouldPreserveEmbedInteractiveFocus(activeSessionScope.embedId, ownerDocument)) {
return;
}
- focusSheetCellEditorElement(ownerDocument);
+ focusSheetCellEditorElement(editorService);
}, 0);
};
const focusHiddenEditor = () => {
@@ -640,11 +628,7 @@ export function EditorContainer({ hidden = false }: IEditorContainerProps) {
pointerRefocusTimerRef.current = ownerWindow.setTimeout(() => {
pointerRefocusTimerRef.current = undefined;
- if (!docSelectionRenderService?.isFocusing) {
- docSelectionRenderService?.focus();
- }
-
- focusSheetCellEditorElement(ownerDocument);
+ focusSheetCellEditorElement(editorService);
}, 0);
});
diff --git a/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx b/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx
index bd22bace6a..50f9eb5389 100644
--- a/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx
+++ b/packages/sheets-ui/src/views/editor-container/__tests__/EditorContainer.spec.tsx
@@ -187,12 +187,27 @@ class TestEditorBridgeService {
dispose(): void {}
}
+const testInjectors: Injector[] = [];
+
function createTestBed(options: { disableAutoFocus?: boolean; docSelectionIsFocusing?: boolean; focusedUnitId?: string | null; sheetUnitIds?: string[] } = {}) {
const injector = new Injector();
- const componentManager = new ComponentManager();
- const focusCoordinator = new EmbedRuntimeFocusCoordinator();
- const interactionBoundaryService = new EmbedInteractionBoundaryService();
- const editorBridgeService = new TestEditorBridgeService();
+ testInjectors.push(injector);
+ injector.add([ComponentManager]);
+ injector.add([ISheetEmbedRuntimeFocusCoordinator, { useClass: EmbedRuntimeFocusCoordinator }]);
+ injector.add([ISheetEmbedInteractionBoundaryService, { useClass: EmbedInteractionBoundaryService }]);
+ injector.add([TestEditorBridgeService]);
+ injector.add([TestCellEditorManagerService]);
+ const componentManager = injector.get(ComponentManager);
+ const focusCoordinator = injector.get(ISheetEmbedRuntimeFocusCoordinator) as EmbedRuntimeFocusCoordinator;
+ const interactionBoundaryService = injector.get(ISheetEmbedInteractionBoundaryService) as EmbedInteractionBoundaryService;
+ const editorBridgeService = injector.get(TestEditorBridgeService);
+ const selectionContainer = document.createElement('div');
+ selectionContainer.id = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
+ const internalEditor = document.createElement('div');
+ internalEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
+ internalEditor.tabIndex = -1;
+ selectionContainer.appendChild(internalEditor);
+ document.body.appendChild(selectionContainer);
const editSheet = { getSheetId: () => 'worksheet-1', getName: () => 'Sheet1' };
const otherSheet = { getSheetId: () => 'worksheet-2', getName: () => 'Sheet2' };
const activeSheet$ = new BehaviorSubject(editSheet);
@@ -212,10 +227,12 @@ function createTestBed(options: { disableAutoFocus?: boolean; docSelectionIsFocu
};
const validViewportScrollInfo$ = new BehaviorSubject<Nullable<Record<string, never>>>({});
const docSelectionRenderService = {
- isFocusing: options.docSelectionIsFocusing ?? true,
- focus: vi.fn(),
+ get isFocusing() { return options.docSelectionIsFocusing ?? document.activeElement === internalEditor; },
+ inputElement: internalEditor,
+ selectionContainer,
+ focus: vi.fn(() => internalEditor.focus()),
};
- const cellEditorManagerService = new TestCellEditorManagerService();
+ const cellEditorManagerService = injector.get(TestCellEditorManagerService);
latestFormulaEditorProps = undefined;
componentManager.register(EMBEDDING_FORMULA_EDITOR_COMPONENT_KEY, (props: {
@@ -225,8 +242,6 @@ function createTestBed(options: { disableAutoFocus?: boolean; docSelectionIsFocu
latestFormulaEditorProps = props;
return <div data-testid="formula-editor" />;
});
- injector.add([Injector, injector]);
- injector.add([ComponentManager, componentManager]);
injector.add([IEditorBridgeService, { useValue: editorBridgeService as never }]);
injector.add([ICellEditorManagerService, { useValue: cellEditorManagerService }]);
injector.add([IEditorService, {
@@ -234,6 +249,7 @@ function createTestBed(options: { disableAutoFocus?: boolean; docSelectionIsFocu
getEditor: () => ({
getBoundingClientRect: () => ({ left: 0, top: 0, width: 120, height: 32 }),
render: { with: () => docSelectionRenderService },
+ docSelectionRenderService,
}),
} as never,
}]);
@@ -281,10 +297,8 @@ function createTestBed(options: { disableAutoFocus?: boolean; docSelectionIsFocu
}]);
injector.add([ILayoutService, { useValue: { focus: vi.fn() } as never }]);
injector.add([ISidebarService, { useValue: { getContainer: () => null } as never }]);
- injector.add([ISheetEmbedRuntimeFocusCoordinator, { useValue: focusCoordinator }]);
- injector.add([ISheetEmbedInteractionBoundaryService, { useValue: interactionBoundaryService }]);
- return { injector, editorBridgeService, focusCoordinator, interactionBoundaryService, docSelectionRenderService, cellEditorManagerService, cellEditorResizeService, validViewportScrollInfo$, activeSheet$, otherSheet };
+ return { injector, selectionContainer, internalEditor, editorBridgeService, focusCoordinator, interactionBoundaryService, docSelectionRenderService, cellEditorManagerService, cellEditorResizeService, validViewportScrollInfo$, activeSheet$, otherSheet };
}
function renderEditorContainer(root: Root, injector: Injector, props: { hidden?: boolean } = {}): void {
@@ -298,14 +312,31 @@ describe('EditorContainer embed focus lease', () => {
afterEach(() => {
act(() => root?.unmount());
- container?.remove();
- document.getElementById(`univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`)?.remove();
- document.getElementById(`__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`)?.remove();
+ testInjectors.splice(0).forEach((injector) => injector.dispose());
+ document.body.replaceChildren();
vi.useRealTimers();
root = undefined;
container = undefined;
});
+ it.each([false, true])('keeps cell editing in its own instance with duplicate IDs (nested: %s)', async (nested) => {
+ const left = createTestBed();
+ const right = createTestBed();
+ if (nested) {
+ left.selectionContainer.appendChild(right.selectionContainer);
+ }
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ renderEditorContainer(root!, right.injector);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ });
+
+ expect(document.activeElement).toBe(right.internalEditor);
+ });
+
it('keeps the cell editor mounted but non-interactive when hidden', async () => {
const { injector } = createTestBed();
container = document.createElement('div');
@@ -326,12 +357,7 @@ describe('EditorContainer embed focus lease', () => {
it('holds a child-editor lease while the embedded sheet cell editor is visible', async () => {
const { injector, editorBridgeService, focusCoordinator, interactionBoundaryService } = createTestBed();
- const selectionContainer = document.createElement('div');
- selectionContainer.id = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- const internalEditor = document.createElement('div');
- internalEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- selectionContainer.appendChild(internalEditor);
- document.body.appendChild(selectionContainer);
+ const { selectionContainer, inputElement: internalEditor } = injector.get(IEditorService).getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.docSelectionRenderService;
container = document.createElement('div');
container.setAttribute('data-embed-float-dom', 'true');
container.setAttribute('data-embed-id', 'embed-1');
@@ -391,12 +417,7 @@ describe('EditorContainer embed focus lease', () => {
childUnitId: 'scoped-child-sheet',
childType: UniverInstanceType.UNIVER_SHEET,
});
- const selectionContainer = document.createElement('div');
- selectionContainer.id = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- const internalEditor = document.createElement('div');
- internalEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- selectionContainer.appendChild(internalEditor);
- document.body.appendChild(selectionContainer);
+ const { selectionContainer, inputElement: internalEditor } = injector.get(IEditorService).getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.docSelectionRenderService;
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
@@ -422,12 +443,7 @@ describe('EditorContainer embed focus lease', () => {
const { injector, focusCoordinator, interactionBoundaryService } = createTestBed({
focusedUnitId: 'host-doc',
});
- const selectionContainer = document.createElement('div');
- selectionContainer.id = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- const internalEditor = document.createElement('div');
- internalEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- selectionContainer.appendChild(internalEditor);
- document.body.appendChild(selectionContainer);
+ const { selectionContainer, inputElement: internalEditor } = injector.get(IEditorService).getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.docSelectionRenderService;
container = document.createElement('div');
document.body.appendChild(container);
root = createRoot(container);
@@ -476,13 +492,7 @@ describe('EditorContainer embed focus lease', () => {
focusedUnitId: 'host-doc',
sheetUnitIds: ['scoped-child-sheet'],
});
- const selectionContainer = document.createElement('div');
- selectionContainer.id = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- const internalEditor = document.createElement('div');
- internalEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- internalEditor.tabIndex = -1;
- selectionContainer.appendChild(internalEditor);
- document.body.appendChild(selectionContainer);
+ const { selectionContainer, inputElement: internalEditor } = injector.get(IEditorService).getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.docSelectionRenderService;
const hostCanvas = document.createElement('canvas');
hostCanvas.tabIndex = -1;
document.body.appendChild(hostCanvas);
@@ -537,13 +547,7 @@ describe('EditorContainer embed focus lease', () => {
focusedUnitId: 'host-doc',
sheetUnitIds: ['scoped-child-sheet'],
});
- const selectionContainer = document.createElement('div');
- selectionContainer.id = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- const internalEditor = document.createElement('div');
- internalEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- internalEditor.tabIndex = -1;
- selectionContainer.appendChild(internalEditor);
- document.body.appendChild(selectionContainer);
+ const { selectionContainer } = injector.get(IEditorService).getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.docSelectionRenderService;
const hostCanvas = document.createElement('canvas');
hostCanvas.tabIndex = -1;
document.body.appendChild(hostCanvas);
@@ -595,13 +599,7 @@ describe('EditorContainer embed focus lease', () => {
focusedUnitId: 'host-doc',
sheetUnitIds: ['scoped-child-base'],
});
- const selectionContainer = document.createElement('div');
- selectionContainer.id = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- const internalEditor = document.createElement('div');
- internalEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- internalEditor.tabIndex = -1;
- selectionContainer.appendChild(internalEditor);
- document.body.appendChild(selectionContainer);
+ const { selectionContainer } = injector.get(IEditorService).getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.docSelectionRenderService;
const hostCanvas = document.createElement('canvas');
hostCanvas.tabIndex = -1;
document.body.appendChild(hostCanvas);
@@ -672,12 +670,7 @@ describe('EditorContainer embed focus lease', () => {
childUnitId: 'child-base',
childType: UniverInstanceType.UNIVER_BASE,
});
- const selectionContainer = document.createElement('div');
- selectionContainer.id = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- const internalEditor = document.createElement('div');
- internalEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- selectionContainer.appendChild(internalEditor);
- document.body.appendChild(selectionContainer);
+ const { selectionContainer, inputElement: internalEditor } = injector.get(IEditorService).getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.docSelectionRenderService;
container = document.createElement('div');
container.setAttribute('data-embed-float-dom', 'true');
container.setAttribute('data-embed-id', 'embed-sheet');
@@ -860,10 +853,7 @@ describe('EditorContainer embed focus lease', () => {
it('restores focus to the internal cell editor after pointer down inside the editor canvas', async () => {
const { injector, docSelectionRenderService } = createTestBed({ docSelectionIsFocusing: false });
- const hiddenEditor = document.createElement('div');
- hiddenEditor.id = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
- hiddenEditor.tabIndex = -1;
- document.body.appendChild(hiddenEditor);
+ const hiddenEditor = docSelectionRenderService.inputElement;
container = document.createElement('div');
container.setAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE, 'embed-1');
document.body.appendChild(container);
diff --git a/packages/sheets-ui/src/views/editor-container/__tests__/focus-editor.spec.ts b/packages/sheets-ui/src/views/editor-container/__tests__/focus-editor.spec.ts
index 1fd18cd972..d60bffdeba 100644
--- a/packages/sheets-ui/src/views/editor-container/__tests__/focus-editor.spec.ts
+++ b/packages/sheets-ui/src/views/editor-container/__tests__/focus-editor.spec.ts
@@ -18,121 +18,135 @@
* @vitest-environment jsdom
*/
-import { afterEach, describe, expect, it } from 'vitest';
-import {
- EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE,
- EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE,
- EmbedInteractionBoundaryService,
- EmbedRuntimeFocusCoordinator,
-} from '../../../services/sheet-embed-integration.service';
-import {
- focusSheetCellEditorElement,
- registerSheetCellEditorRuntimePortal,
- resolveSheetCellEditorPortalRoot,
-} from '../focus-editor';
-
-describe('focusSheetCellEditorElement', () => {
+import type { IDisposable } from '@univerjs/core';
+import { DOCS_NORMAL_EDITOR_UNIT_ID_KEY, toDisposable, Univer, UniverInstanceType } from '@univerjs/core';
+import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
+import { DocSelectionRenderService, IEditorService } from '@univerjs/docs-ui';
+import { RenderUnit } from '@univerjs/engine-render';
+import { ILayoutService } from '@univerjs/ui';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { EmbedInteractionBoundaryService, EmbedRuntimeFocusCoordinator } from '../../../services/sheet-embed-integration.service';
+import { focusSheetCellEditorElement, registerSheetCellEditorRuntimePortal } from '../focus-editor';
+
+const disposables: IDisposable[] = [];
+
+class TestDocSkeletonManagerService {
+ getSkeleton() { return null; }
+}
+
+function createTestBed() {
+ const univer = new Univer();
+ disposables.push(univer);
+ const injector = univer.__getInjector();
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ injector.add([DocSelectionManagerService]);
+ injector.add([EmbedInteractionBoundaryService]);
+ injector.add([EmbedRuntimeFocusCoordinator]);
+ injector.add([ILayoutService, { useValue: {
+ rootContainerElement: host,
+ registerContainerElement: () => toDisposable(() => {}),
+ } as never }]);
+ const unit = univer.createUnit(UniverInstanceType.UNIVER_DOC, {
+ id: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ body: { dataStream: '\r\n', paragraphs: [{ startIndex: 0 }], sectionBreaks: [] },
+ documentStyle: {},
+ });
+ const render = injector.createInstance(RenderUnit, {
+ engine: {} as never,
+ scene: { getViewports: () => [], getEngine: () => null } as never,
+ isMainScene: true,
+ unit,
+ });
+ disposables.push(render);
+ render.addRenderDependencies([
+ [DocSkeletonManagerService, { useClass: TestDocSkeletonManagerService }],
+ [DocSelectionRenderService],
+ ]);
+ const selection = render.with(DocSelectionRenderService);
+ injector.add([IEditorService, { useValue: {
+ getEditor: vi.fn(() => ({ docSelectionRenderService: selection })),
+ } as never }]);
+
+ return {
+ host,
+ selection,
+ editorService: injector.get(IEditorService),
+ interactionBoundaryService: injector.get(EmbedInteractionBoundaryService),
+ focusCoordinator: injector.get(EmbedRuntimeFocusCoordinator),
+ };
+}
+
+describe('sheet cell editor instance isolation', () => {
afterEach(() => {
+ disposables.splice(0).reverse().forEach((disposable) => disposable.dispose());
document.body.replaceChildren();
});
- it('focuses the sheet cell editor DOM node', () => {
- const hostEditor = document.createElement('div');
- hostEditor.id = '__editor_docs-embed-host';
- hostEditor.tabIndex = -1;
- const cellEditor = document.createElement('div');
- cellEditor.id = '__editor___INTERNAL_EDITOR__DOCS_NORMAL';
- cellEditor.tabIndex = -1;
- document.body.append(hostEditor, cellEditor);
- hostEditor.focus();
-
- expect(focusSheetCellEditorElement(document)).toBe(true);
-
- expect(document.activeElement).toBe(cellEditor);
+ it.each([false, true])('focuses its own editor with duplicate IDs (nested: %s)', (nested) => {
+ const left = createTestBed();
+ const right = createTestBed();
+ if (nested) {
+ left.host.prepend(right.host);
+ }
+ left.selection.focus();
+
+ expect(focusSheetCellEditorElement(right.editorService)).toBe(true);
+ expect(document.activeElement).toBe(right.selection.inputElement);
+ expect(focusSheetCellEditorElement(right.editorService)).toBe(false);
+ expect(focusSheetCellEditorElement(left.editorService)).toBe(true);
+ expect(document.activeElement).toBe(left.selection.inputElement);
});
- it('makes the sheet cell editor focusable when it has no tabindex', () => {
- const hostEditor = document.createElement('div');
- hostEditor.id = '__editor_docs-embed-host';
- hostEditor.tabIndex = -1;
- const cellEditor = document.createElement('div');
- cellEditor.id = '__editor___INTERNAL_EDITOR__DOCS_NORMAL';
- document.body.append(hostEditor, cellEditor);
- hostEditor.focus();
+ it('makes its own input focusable without taking focus from another instance when absent', () => {
+ const left = createTestBed();
+ const right = createTestBed();
+ right.selection.inputElement.removeAttribute('tabindex');
+ left.selection.focus();
- expect(focusSheetCellEditorElement(document)).toBe(true);
+ focusSheetCellEditorElement(right.editorService);
+ expect(document.activeElement).toBe(right.selection.inputElement);
- expect(cellEditor.tabIndex).toBe(-1);
- expect(document.activeElement).toBe(cellEditor);
+ vi.mocked(left.editorService.getEditor).mockReturnValue(undefined);
+ expect(focusSheetCellEditorElement(left.editorService)).toBe(false);
+ expect(document.activeElement).toBe(right.selection.inputElement);
});
- it('registers the sheet cell editor portal as an owned child editor while embedded', () => {
- const selectionContainer = document.createElement('div');
- selectionContainer.id = 'univer-doc-selection-container-__INTERNAL_EDITOR__DOCS_NORMAL';
- const cellEditor = document.createElement('div');
- cellEditor.id = '__editor___INTERNAL_EDITOR__DOCS_NORMAL';
- selectionContainer.appendChild(cellEditor);
- document.body.appendChild(selectionContainer);
- const interactionBoundaryService = new EmbedInteractionBoundaryService();
- const focusCoordinator = new EmbedRuntimeFocusCoordinator();
-
- const disposable = registerSheetCellEditorRuntimePortal({
- embedId: 'embed-1',
- interactionBoundaryService,
- focusCoordinator,
- });
-
- expect(resolveSheetCellEditorPortalRoot(document)).toBe(selectionContainer);
- expect(selectionContainer.getAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe('embed-1');
- expect(cellEditor.getAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe('embed-1');
- expect(selectionContainer.getAttribute(EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe('child-editor');
- expect(cellEditor.getAttribute(EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe('child-editor');
- expect(interactionBoundaryService.contains('embed-1', cellEditor)).toBe(true);
- expect(focusCoordinator.containsElement('embed-1', cellEditor)).toBe(true);
-
- disposable.dispose();
-
- expect(selectionContainer.hasAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe(false);
- expect(cellEditor.hasAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe(false);
- expect(selectionContainer.hasAttribute(EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe(false);
- expect(cellEditor.hasAttribute(EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe(false);
+ it('registers and releases only its own portal when another instance has the same IDs', () => {
+ const left = createTestBed();
+ const right = createTestBed();
+ const registration = registerSheetCellEditorRuntimePortal({ embedId: 'embed-right', ...right });
+ disposables.push(registration);
+
+ expect(right.interactionBoundaryService.contains('embed-right', right.selection.inputElement)).toBe(true);
+ expect(right.focusCoordinator.containsElement('embed-right', right.selection.inputElement)).toBe(true);
+ expect(right.focusCoordinator.containsElement('embed-right', right.selection.selectionContainer)).toBe(true);
+ expect(right.interactionBoundaryService.contains('embed-right', left.selection.inputElement)).toBe(false);
+ expect(right.focusCoordinator.containsElement('embed-right', left.selection.inputElement)).toBe(false);
+
+ registration.dispose();
+ expect(right.interactionBoundaryService.contains('embed-right', right.selection.inputElement)).toBe(false);
+ expect(right.focusCoordinator.containsElement('embed-right', right.selection.inputElement)).toBe(false);
});
- it('keeps ownership when the sheet cell editor portal is remounted while embedded', async () => {
- const selectionContainer = document.createElement('div');
- selectionContainer.id = 'univer-doc-selection-container-__INTERNAL_EDITOR__DOCS_NORMAL';
- const cellEditor = document.createElement('div');
- cellEditor.id = '__editor___INTERNAL_EDITOR__DOCS_NORMAL';
- selectionContainer.appendChild(cellEditor);
- document.body.appendChild(selectionContainer);
- const interactionBoundaryService = new EmbedInteractionBoundaryService();
- const focusCoordinator = new EmbedRuntimeFocusCoordinator();
-
- const disposable = registerSheetCellEditorRuntimePortal({
- embedId: 'embed-1',
- interactionBoundaryService,
- focusCoordinator,
- });
-
- selectionContainer.remove();
- const nextSelectionContainer = document.createElement('div');
- nextSelectionContainer.id = 'univer-doc-selection-container-__INTERNAL_EDITOR__DOCS_NORMAL';
- const nextCellEditor = document.createElement('div');
- nextCellEditor.id = '__editor___INTERNAL_EDITOR__DOCS_NORMAL';
- nextSelectionContainer.appendChild(nextCellEditor);
- document.body.appendChild(nextSelectionContainer);
+ it('releases a detached portal and registers the remounted instance editor', async () => {
+ const left = createTestBed();
+ const right = createTestBed();
+ const registration = registerSheetCellEditorRuntimePortal({ embedId: 'embed-right', ...right });
+ disposables.push(registration);
+ right.selection.selectionContainer.remove();
await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(right.focusCoordinator.containsElement('embed-right', right.selection.inputElement)).toBe(false);
+ expect(right.focusCoordinator.containsElement('embed-right', left.selection.inputElement)).toBe(false);
- expect(nextSelectionContainer.getAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe('embed-1');
- expect(nextCellEditor.getAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe('embed-1');
- expect(nextSelectionContainer.getAttribute(EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe('child-editor');
- expect(nextCellEditor.getAttribute(EMBED_RUNTIME_FOCUS_ROLE_ATTRIBUTE)).toBe('child-editor');
- expect(interactionBoundaryService.contains('embed-1', nextCellEditor)).toBe(true);
- expect(focusCoordinator.containsElement('embed-1', nextCellEditor)).toBe(true);
+ const replacement = createTestBed();
+ vi.mocked(right.editorService.getEditor).mockReturnValue({ docSelectionRenderService: replacement.selection } as never);
+ await new Promise((resolve) => setTimeout(resolve, 0));
- disposable.dispose();
+ expect(right.focusCoordinator.containsElement('embed-right', replacement.selection.inputElement)).toBe(true);
+ expect(right.interactionBoundaryService.contains('embed-right', replacement.selection.inputElement)).toBe(true);
- expect(nextSelectionContainer.hasAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe(false);
- expect(nextCellEditor.hasAttribute(EMBED_INTERACTION_BOUNDARY_OWNER_ATTRIBUTE)).toBe(false);
+ registration.dispose();
+ expect(right.focusCoordinator.containsElement('embed-right', replacement.selection.inputElement)).toBe(false);
});
});
diff --git a/packages/sheets-ui/src/views/editor-container/focus-editor.ts b/packages/sheets-ui/src/views/editor-container/focus-editor.ts
index 59294bd646..8e9dd02157 100644
--- a/packages/sheets-ui/src/views/editor-container/focus-editor.ts
+++ b/packages/sheets-ui/src/views/editor-container/focus-editor.ts
@@ -15,30 +15,28 @@
*/
import type { IDisposable } from '@univerjs/core';
+import type { IEditorService } from '@univerjs/docs-ui';
+import type {
+ ISheetEmbedInteractionBoundaryService,
+ ISheetEmbedRuntimeFocusCoordinator,
+} from '../../services/sheet-embed-integration.service';
import { DisposableCollection, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, toDisposable } from '@univerjs/core';
-import type { ISheetEmbedInteractionBoundaryService, ISheetEmbedRuntimeFocusCoordinator } from '../../services/sheet-embed-integration.service';
-const SHEET_CELL_EDITOR_ELEMENT_ID = `__editor_${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
-const SHEET_CELL_EDITOR_SELECTION_CONTAINER_ID = `univer-doc-selection-container-${DOCS_NORMAL_EDITOR_UNIT_ID_KEY}`;
+export function focusSheetCellEditorElement(editorService: IEditorService): boolean {
+ const selection = editorService.getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.docSelectionRenderService;
-export function focusSheetCellEditorElement(ownerDocument: Document = document): boolean {
- const element = ownerDocument.getElementById(SHEET_CELL_EDITOR_ELEMENT_ID) as HTMLElement | null;
-
- if (element == null || ownerDocument.activeElement === element) {
+ if (!selection || selection.isFocusing) {
return false;
}
- if (!element.hasAttribute('tabindex')) {
- element.tabIndex = -1;
- }
-
- element.focus({ preventScroll: true });
+ selection.focus();
- return ownerDocument.activeElement === element;
+ return selection.isFocusing;
}
export function registerSheetCellEditorRuntimePortal(options: {
embedId: string;
+ editorService: IEditorService;
ownerDocument?: Document;
interactionBoundaryService?: ISheetEmbedInteractionBoundaryService;
focusCoordinator?: ISheetEmbedRuntimeFocusCoordinator;
@@ -60,7 +58,8 @@ export function registerSheetCellEditorRuntimePortal(options: {
return;
}
- const portalRoot = resolveSheetCellEditorPortalRoot(ownerDocument);
+ const selection = options.editorService.getEditor(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.docSelectionRenderService;
+ const portalRoot = selection?.selectionContainer.isConnected ? selection.selectionContainer : null;
if (portalRoot === registeredPortalRoot) {
return;
}
@@ -85,7 +84,7 @@ export function registerSheetCellEditorRuntimePortal(options: {
element: portalRoot,
}));
- const editorElement = ownerDocument.getElementById(SHEET_CELL_EDITOR_ELEMENT_ID) as HTMLElement | null;
+ const editorElement = selection?.inputElement;
if (editorElement && editorElement !== portalRoot) {
rootRegistration.add(options.focusCoordinator.registerElement({
embedId: options.embedId,
@@ -136,8 +135,3 @@ export function registerSheetCellEditorRuntimePortal(options: {
return collection;
}
-
-export function resolveSheetCellEditorPortalRoot(ownerDocument: Document = document): HTMLElement | null {
- return (ownerDocument.getElementById(SHEET_CELL_EDITOR_SELECTION_CONTAINER_ID) as HTMLElement | null)
- ?? (ownerDocument.getElementById(SHEET_CELL_EDITOR_ELEMENT_ID) as HTMLElement | null);
-}
diff --git a/packages/sheets-ui/src/views/editor-container/index.ts b/packages/sheets-ui/src/views/editor-container/index.ts
deleted file mode 100644
index 925a29cac2..0000000000
--- a/packages/sheets-ui/src/views/editor-container/index.ts
+++ /dev/null
@@ -1,18 +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.
- */
-
-export * from './EditorContainer';
-export { useKeyEventConfig } from './hooks';