Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(sheets-formula-ui): hide mirrored formula editor carets (#8147)
白熱79c656bbe559
diff --git a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx b/packages/sheets-formula-ui/src/views/formula-editor/index.tsxindex c3a43fb092..0c5b2b4793 100644--- a/packages/sheets-formula-ui/src/views/formula-editor/index.tsx+++ b/packages/sheets-formula-ui/src/views/formula-editor/index.tsx@@ -18,15 +18,11 @@ import type { DocumentDataModel, IDisposable, ITextRange } from '@univerjs/core'import type { Editor, IKeyboardEventConfig } from '@univerjs/docs-ui';import type { KeyCode, MetaKeys } from '@univerjs/ui';import type { CSSProperties, ReactNode, Ref } from 'react';-import type { IUniverSheetsFormulaUIConfig } from '../../config/config';-import type { FormulaSelectingType } from './hooks/use-formula-selection';-import type { IRefSelection } from './hooks/use-highlight';import {BuildTextUtils,createInternalEditorID,DisposableCollection,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,- DOCS_NORMAL_EDITOR_UNIT_ID_KEY,DocumentFlavor,generateRandomId,HorizontalAlign,@@ -52,6 +48,9 @@ import { EMBEDDING_FORMULA_EDITOR } from '@univerjs/sheets-ui';import { useDependency, useEvent, useObservable, useUpdateEffect } from '@univerjs/ui';import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';import { map } from 'rxjs';+import type { IUniverSheetsFormulaUIConfig } from '../../config/config';+import type { FormulaSelectingType } from './hooks/use-formula-selection';+import type { IRefSelection } from './hooks/use-highlight';import { PLUGIN_CONFIG_KEY_BASE } from '../../config/config';import { findIndexFromSequenceNodes, findRefSequenceIndex } from '../range-selector/utils/find-index-from-sequence-nodes';import {@@ -75,6 +74,7 @@ import { useSwitchSheet } from './hooks/use-switch-sheet';import { useVerify } from './hooks/use-verify';import { SearchFunction } from './search-function/SearchFunction';import { getFormulaText } from './utils/get-formula-text';+import { syncCounterpartFormulaEditorSelection } from './utils/sync-counterpart-formula-editor-selection';export interface IFormulaEditorProps {unitId: string;@@ -122,32 +122,6 @@ export function shouldApplyFormulaSelectionChange(return Boolean(selectingMode) || Boolean(isFocusing) || hasActiveInteraction;}-interface IFormulaEditorSelectionSyncService {- getEditor: (editorId: string) => Pick<Editor, 'setSelectionRanges'> | null | undefined | void;-}--export function syncCounterpartFormulaEditorSelection(- editorService: IFormulaEditorSelectionSyncService,- editorId: string,- selections: ITextRange[] | undefined-): void {- if (!selections?.length) {- return;- }-- const syncEditorId = editorId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY- ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY- : editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY- ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY- : null;-- if (!syncEditorId) {- return;- }-- editorService.getEditor(syncEditorId)?.setSelectionRanges(selections, false);-}-export const FormulaEditor = forwardRef((props: IFormulaEditorProps, ref: Ref<IFormulaEditorRef>) => {const {errorText,diff --git a/packages/sheets-formula-ui/src/views/formula-editor/utils/__tests__/sync-counterpart-formula-editor-selection.spec.ts b/packages/sheets-formula-ui/src/views/formula-editor/utils/__tests__/sync-counterpart-formula-editor-selection.spec.tsnew file mode 100644index 0000000000..ccaf8a7a70--- /dev/null+++ b/packages/sheets-formula-ui/src/views/formula-editor/utils/__tests__/sync-counterpart-formula-editor-selection.spec.ts@@ -0,0 +1,135 @@+/**+ * 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 type { RenderUnit } from '@univerjs/engine-render';+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, IUndoRedoService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';+import { DocLayoutExecutorService, DocSelectionManagerService, DocSkeletonManagerService, SetTextSelectionsOperation } from '@univerjs/docs';+import { DocSelectionRenderService, Editor } from '@univerjs/docs-ui';+import { CanvasColorService, Documents, ICanvasColorService, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { DesktopLayoutService, ILayoutService } from '@univerjs/ui';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { syncCounterpartFormulaEditorSelection } from '../sync-counterpart-formula-editor-selection';++describe('formula editor counterpart selection', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ const context = new Proxy({+ measureText: (text: string) => ({+ width: text.length * 8,+ actualBoundingBoxAscent: 8,+ actualBoundingBoxDescent: 2,+ fontBoundingBoxAscent: 8,+ fontBoundingBoxDescent: 2,+ }),+ }, { get: (target, key) => key in target ? Reflect.get(target, key) : () => {} });+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(context as never);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ vi.useRealTimers();+ });++ it.each([+ [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY],+ [DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY],+ ])('keeps only the active caret when %s picks a formula reference', (editorId, counterpartId) => {+ const univer = new Univer();+ const root = document.createElement('div');+ document.body.appendChild(root);+ const injector = univer.__getInjector();+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ICanvasColorService, { useClass: CanvasColorService }]);+ injector.add([DocLayoutExecutorService]);+ injector.add([DocSelectionManagerService]);+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);+ injector.get(ILayoutService).registerRootContainerElement(root);+ const editors = new Map<string, Editor>();+ const selectionManager = injector.get(DocSelectionManagerService);+ const commandService = injector.get(ICommandService);+ commandService.registerCommand(SetTextSelectionsOperation);+ const service = { getEditor: (id: string) => editors.get(id) };+ try {+ for (const id of [editorId, counterpartId]) {+ univer.createUnit(UniverInstanceType.UNIVER_DOC, {+ id,+ body: {+ dataStream: '=SUM(A1:A2,3)\r\n',+ paragraphs: [{ startIndex: 13, paragraphId: 'formula' }],+ },+ documentStyle: { pageSize: { width: 400, height: 100 } },+ });+ const render = injector.get(IRenderManagerService).createRender(id) as RenderUnit;+ render.deactivate();+ render.addRenderDependencies([[DocSkeletonManagerService], [DocSelectionRenderService]]);+ const skeleton = render.with(DocSkeletonManagerService).getSkeleton();+ const documents = new Documents(id, skeleton);+ render.mainComponent = documents;+ render.scene.addObject(documents);+ const selectionRender = render.with(DocSelectionRenderService);+ render.disposeWithMe(selectionManager.refreshSelection$.subscribe((params) => {+ if (params?.unitId === id) {+ selectionRender.replaceDocRanges(params.docRanges, params.isEditing, params.options);+ }+ }));+ render.disposeWithMe(selectionRender.textSelectionInner$.subscribe((params) => {+ if (params) {+ selectionManager.__replaceTextRangesWithNoRefresh(params, { unitId: id, subUnitId: id });+ }+ }));+ const editor = injector.createInstance(+ Editor,+ { initialSnapshot: { id, documentStyle: {} }, render, editorDom: root },+ injector.get(IUniverInstanceService),+ selectionManager,+ commandService,+ injector.get(IUndoRedoService),+ injector+ );+ render.disposeWithMe(editor);+ editors.set(id, editor);+ }+ const active = service.getEditor(editorId)!;+ const counterpart = service.getEditor(counterpartId)!;+ active.docSelectionRenderService.focus();+ for (const offset of [10, 11, 13]) {+ const selections = [{ startOffset: offset, endOffset: offset, collapsed: true }];+ active.setSelectionRanges(selections, false);+ syncCounterpartFormulaEditorSelection(service, editorId, selections);++ expect(active.docSelectionRenderService.isFocusing).toBe(true);+ expect(active.docSelectionRenderService.getActiveTextRange()?.startOffset).toBe(offset);+ expect(counterpart.getSelectionRanges()).toMatchObject([+ { startOffset: offset, endOffset: offset },+ ]);+ counterpart.docSelectionRenderService.refreshRanges();+ expect(counterpart.docSelectionRenderService.getAllTextRanges()).toEqual([]);+ }++ // Switching editors must restore a usable caret at the mirrored position.+ const selections = counterpart.getSelectionRanges();+ counterpart.docSelectionRenderService.focus();+ counterpart.setSelectionRanges(selections, false);+ expect(counterpart.docSelectionRenderService.isFocusing).toBe(true);+ expect(counterpart.docSelectionRenderService.getActiveTextRange()?.startOffset).toBe(13);+ } finally {+ univer.dispose();+ root.remove();+ }+ });+});diff --git a/packages/sheets-formula-ui/src/views/formula-editor/utils/sync-counterpart-formula-editor-selection.ts b/packages/sheets-formula-ui/src/views/formula-editor/utils/sync-counterpart-formula-editor-selection.tsnew file mode 100644index 0000000000..0974a6c803--- /dev/null+++ b/packages/sheets-formula-ui/src/views/formula-editor/utils/sync-counterpart-formula-editor-selection.ts@@ -0,0 +1,48 @@+/**+ * Copyright 2023-present DreamNum Co., Ltd.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import type { ITextRange } from '@univerjs/core';+import type { Editor } from '@univerjs/docs-ui';+import { DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY } from '@univerjs/core';++interface IFormulaEditorSelectionSyncService {+ getEditor: (editorId: string) => Pick<Editor, 'setSelectionRanges' | 'docSelectionRenderService'> | null | undefined | void;+}++export function syncCounterpartFormulaEditorSelection(+ editorService: IFormulaEditorSelectionSyncService,+ editorId: string,+ selections: ITextRange[] | undefined+): void {+ if (!selections?.length) {+ return;+ }++ const syncEditorId = editorId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY+ ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY+ : editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY+ ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY+ : null;++ if (!syncEditorId) {+ return;+ }++ const syncEditor = editorService.getEditor(syncEditorId);+ syncEditor?.setSelectionRanges(selections, false);+ // Keep the mirrored position for focus changes without displaying a second caret.+ syncEditor?.docSelectionRenderService.removeAllRanges();+}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.tsxindex fc881fd3a8..0dd6797981 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@@ -18,9 +18,6 @@ import type { DocumentDataModel, IDisposable, ITextRange } from '@univerjs/core'import type { Editor, IKeyboardEventConfig } from '@univerjs/docs-ui';import type { KeyCode, MetaKeys } from '@univerjs/ui';import type { CSSProperties, ReactNode, Ref } from 'react';-import type { IUniverSheetsFormulaUIConfig } from '../../../config/config';-import type { FormulaSelectingType } from '../../formula-editor/hooks/use-formula-selection';-import type { IRefSelection } from '../../formula-editor/hooks/use-highlight';import {BuildTextUtils,createInternalEditorID,@@ -53,6 +50,9 @@ import { EMBEDDING_FORMULA_EDITOR, MOBILE_FORMULA_FUNCTION_PANEL_OPEN } from '@uimport { useDependency, useEvent, useObservable, useUpdateEffect } from '@univerjs/ui';import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';import { map } from 'rxjs';+import type { IUniverSheetsFormulaUIConfig } from '../../../config/config';+import type { FormulaSelectingType } from '../../formula-editor/hooks/use-formula-selection';+import type { IRefSelection } from '../../formula-editor/hooks/use-highlight';import { PLUGIN_CONFIG_KEY_BASE } from '../../../config/config';import {IFormulaEmbedInteractionBoundaryService,@@ -73,6 +73,7 @@ import { useStateRef } from '../../formula-editor/hooks/use-state-ref';import { useSwitchSheet } from '../../formula-editor/hooks/use-switch-sheet';import { useVerify } from '../../formula-editor/hooks/use-verify';import { getFormulaText } from '../../formula-editor/utils/get-formula-text';+import { syncCounterpartFormulaEditorSelection } from '../../formula-editor/utils/sync-counterpart-formula-editor-selection';import { findIndexFromSequenceNodes, findRefSequenceIndex } from '../../range-selector/utils/find-index-from-sequence-nodes';import { MobileFunctionPanel } from './mobile-function-panel/MobileFunctionPanel';import { MobileSearchFunction } from './search-function/MobileSearchFunction';@@ -127,32 +128,6 @@ export function shouldApplyFormulaSelectionChange(return Boolean(selectingMode) || Boolean(isFocusing) || hasActiveInteraction;}-interface IFormulaEditorSelectionSyncService {- getEditor: (editorId: string) => Pick<Editor, 'setSelectionRanges'> | null | undefined | void;-}--export function syncCounterpartFormulaEditorSelection(- editorService: IFormulaEditorSelectionSyncService,- editorId: string,- selections: ITextRange[] | undefined-): void {- if (!selections?.length) {- return;- }-- const syncEditorId = editorId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY- ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY- : editorId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY- ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY- : null;-- if (!syncEditorId) {- return;- }-- editorService.getEditor(syncEditorId)?.setSelectionRanges(selections, false);-}-export function restoreMobileFormulaEditorHostFocus(editorService: Pick<IEditorService, 'blur' | 'getFocusId'>,univerInstanceService: Pick<IUniverInstanceService, 'focusUnit' | 'getCurrentUnitOfType' | 'getUnit'>,@@ -655,7 +630,7 @@ export const MobileFormulaEditor = forwardRef((props: IMobileFormulaEditorProps,if (counterpartEditorId) {const counterpartEditor = editorService.getEditor(counterpartEditorId);counterpartEditor?.replaceText(result.text, false);- counterpartEditor?.setSelectionRanges([selection], false);+ syncCounterpartFormulaEditorSelection(editorService, editorId, [selection]);}highlight(result.text, false, true, [selection]);