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-ui): sync active editor after external cell updates (#6728)

白熱13e4a1095e9f
diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/data-sync.controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/data-sync.controller.spec.ts
new file mode 100644
index 0000000000..1c3f6b6884
--- /dev/null
+++ b/packages/sheets-ui/src/controllers/editor/__tests__/data-sync.controller.spec.ts
@@ -0,0 +1,134 @@
+/**
+ * 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 { ICommandInfo } from '@univerjs/core';
+import { MoveRangeMutation, SetRangeValuesMutation } from '@univerjs/sheets';
+import { BehaviorSubject } from 'rxjs';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { EditorDataSyncController } from '../data-sync.controller';
+
+class TestCommandService {
+ private readonly _listeners = new Set<(command: ICommandInfo) => void>();
+
+ onCommandExecuted(listener: (command: ICommandInfo) => void) {
+ this._listeners.add(listener);
+
+ return {
+ dispose: () => this._listeners.delete(listener),
+ };
+ }
+
+ emit(command: ICommandInfo) {
+ this._listeners.forEach((listener) => listener(command));
+ }
+}
+
+describe('EditorDataSyncController', () => {
+ const controllers: EditorDataSyncController[] = [];
+
+ afterEach(() => {
+ controllers.splice(0).forEach((controller) => controller.dispose());
+ });
+
+ function createController() {
+ const commandService = new TestCommandService();
+ const editorBridgeService = {
+ currentEditCellState$: new BehaviorSubject(null),
+ getEditLocation: vi.fn(() => ({
+ row: 1,
+ column: 2,
+ })),
+ refreshEditCellState: vi.fn(),
+ isForceKeepVisible: vi.fn(() => false),
+ };
+
+ const controller = new EditorDataSyncController(
+ {} as never,
+ {} as never,
+ editorBridgeService as never,
+ commandService as never,
+ { getRangeRuleInitState: () => true } as never,
+ { getSheetRuleInitState: () => true } as never,
+ { autoScroll: vi.fn() } as never,
+ { getPosition: () => null } as never
+ );
+
+ controllers.push(controller);
+
+ return {
+ commandService,
+ editorBridgeService,
+ };
+ }
+
+ it('refreshes the current edit cell when set-values updates the edited cell', () => {
+ const { commandService, editorBridgeService } = createController();
+
+ commandService.emit({
+ id: SetRangeValuesMutation.id,
+ params: {
+ cellValue: {
+ 1: {
+ 2: { v: 'updated' },
+ },
+ },
+ },
+ } as ICommandInfo);
+
+ expect(editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(1);
+ });
+
+ it('refreshes the current edit cell when set-values clears the edited cell', () => {
+ const { commandService, editorBridgeService } = createController();
+
+ commandService.emit({
+ id: SetRangeValuesMutation.id,
+ params: {
+ cellValue: {
+ 1: {
+ 2: null,
+ },
+ },
+ },
+ } as ICommandInfo);
+
+ expect(editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(1);
+ });
+
+ it('refreshes the current edit cell when move-range changes the edited cell', () => {
+ const { commandService, editorBridgeService } = createController();
+
+ commandService.emit({
+ id: MoveRangeMutation.id,
+ params: {
+ from: {
+ subUnitId: 'sheet1',
+ value: {
+ 1: {
+ 2: null,
+ },
+ },
+ },
+ to: {
+ subUnitId: 'sheet1',
+ value: {},
+ },
+ },
+ } as ICommandInfo);
+
+ expect(editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts b/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts
index e6c6f0bb5e..f497343784 100644
--- a/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts
+++ b/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts
@@ -19,7 +19,21 @@ import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { DocumentViewModel } from '@univerjs/engine-render';
import type { IMoveRangeMutationParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';
import type { ICellEditorState } from '../../services/editor-bridge.service';
-import { BooleanNumber, Disposable, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DocumentFlavor, HorizontalAlign, ICommandService, Inject, IUniverInstanceService, Tools, UniverInstanceType, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import {
+ BooleanNumber,
+ Disposable,
+ DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
+ DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
+ DocumentFlavor,
+ HorizontalAlign,
+ ICommandService,
+ Inject,
+ IUniverInstanceService,
+ Tools,
+ UniverInstanceType,
+ VerticalAlign,
+ WrapStrategy,
+} from '@univerjs/core';
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
import { ReplaceSnapshotCommand } from '@univerjs/docs-ui';
import { DeviceInputEventType, IRenderManagerService } from '@univerjs/engine-render';
@@ -150,44 +164,52 @@ export class EditorDataSyncController extends Disposable {
const needUpdateFormulaEditorContentCommandList = [SetRangeValuesMutation.id, MoveRangeMutation.id];
this.disposeWithMe(
this._commandService.onCommandExecuted((command: ICommandInfo) => {
- if (needUpdateFormulaEditorContentCommandList.includes(command.id)) {
- const editCellState = this._editorBridgeService.getLatestEditCellState();
-
- if (editCellState == null) {
- return;
- }
-
- let needUpdate = false;
+ if (!needUpdateFormulaEditorContentCommandList.includes(command.id)) {
+ return;
+ }
- const { row, column } = editCellState;
+ const editCellState = this._editorBridgeService.getEditLocation();
- if (command.id === SetRangeValuesMutation.id && command.params) {
- const params = command.params as ISetRangeValuesMutationParams;
- if (params.cellValue?.[row]?.[column]) {
- needUpdate = true;
- }
- } else if (command.id === MoveRangeMutation.id && command.params) {
- const params = command.params as IMoveRangeMutationParams;
- if (params.to.value?.[row]?.[column]) {
- needUpdate = true;
- }
- }
+ if (editCellState == null) {
+ return;
+ }
- if (needUpdate) {
- const body = Tools.deepClone(editCellState.documentLayoutObject.documentModel?.getBody());
- const drawings = Tools.deepClone(editCellState.documentLayoutObject.documentModel?.drawings);
- const drawingsOrder = Tools.deepClone(editCellState.documentLayoutObject.documentModel?.getDrawingsOrder());
+ const { row, column } = editCellState;
- if (body == null) {
- return;
- }
- this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, body, drawings, drawingsOrder);
- }
+ if (this._shouldRefreshCurrentEditCell(command, row, column)) {
+ /**
+ * Refresh the current edit-cell snapshot so both the hidden cell editor and
+ * the formula bar stay aligned with external cell mutations.
+ */
+ this._editorBridgeService.refreshEditCellState();
}
})
);
}
+ private _shouldRefreshCurrentEditCell(command: ICommandInfo, row: number, column: number): boolean {
+ if (command.id === SetRangeValuesMutation.id && command.params) {
+ const params = command.params as ISetRangeValuesMutationParams;
+ return this._hasMatrixCell(params.cellValue, row, column);
+ }
+
+ if (command.id === MoveRangeMutation.id && command.params) {
+ const params = command.params as IMoveRangeMutationParams;
+ return this._hasMatrixCell(params.from.value, row, column) || this._hasMatrixCell(params.to.value, row, column);
+ }
+
+ return false;
+ }
+
+ private _hasMatrixCell(
+ matrix: ISetRangeValuesMutationParams['cellValue'] | IMoveRangeMutationParams['from']['value'],
+ row: number,
+ column: number
+ ): boolean {
+ const rowData = matrix?.[row];
+ return rowData != null && Object.prototype.hasOwnProperty.call(rowData, column);
+ }
+
// Sync actions between cell editor and formula editor, and make `dataStream` and `paragraph` is the same.
private _syncActionsAndRender(
unitId: string,