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-ui): keep the open cell editor draft through external updates (#8181)
wpxp1234564f6db924fbe5
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.tsindex c4bbcf7e37..df8a42c2d3 100644--- 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@@ -15,7 +15,6 @@*/import type { ICommandInfo, IDocumentBody, IDocumentData, IDrawings, Nullable } from '@univerjs/core';-import type { ICellEditorState } from '../../../services/editor-bridge.service';import {BooleanNumber,DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,@@ -36,9 +35,11 @@ import {WorksheetProtectionRuleModel,} from '@univerjs/sheets';import { BehaviorSubject, EMPTY } from 'rxjs';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest';+import type { ICellEditorState } from '../../../services/editor-bridge.service';import { IEditorBridgeService } from '../../../services/editor-bridge.service';import { IFormulaEditorManagerService } from '../../../services/editor/formula-editor-manager.service';+import { createChartRenderTestBed } from '../../render-controllers/__tests__/chart-render-test-bed';import { EditorDataSyncController } from '../data-sync.controller';import { FormulaEditorController } from '../formula-editor.controller';@@ -83,11 +84,15 @@ describe('EditorDataSyncController', () => {eventType?: DeviceInputEventType;formulaBarPosition?: { width: number; height: number } | null;documentDataModel?: DocumentDataModel;+ editUnitId?: string;+ editSheetId?: string;} = {}) {const commandService = new TestCommandService();const editorBridgeService = {currentEditCellState$: new BehaviorSubject<Nullable<ICellEditorState>>(null),getEditLocation: vi.fn(() => ({+ unitId: options.editUnitId ?? 'test-unit',+ sheetId: options.editSheetId ?? 'sheet1',row: 1,column: 2,isInArrayFormulaRange: options.isInArrayFormulaRange ?? false,@@ -97,6 +102,7 @@ describe('EditorDataSyncController', () => {eventType: options.eventType ?? DeviceInputEventType.Dblclick,})),refreshEditCellState: vi.fn(),+ changeEditorDirty: vi.fn(),isForceKeepVisible: vi.fn(() => false),};const contextService = {@@ -280,6 +286,8 @@ describe('EditorDataSyncController', () => {commandService.emit({id: SetRangeValuesMutation.id,params: {+ unitId: 'test-unit',+ subUnitId: 'sheet1',cellValue: {1: {2: { v: 'updated' },@@ -297,6 +305,8 @@ describe('EditorDataSyncController', () => {commandService.emit({id: SetRangeValuesMutation.id,params: {+ unitId: 'test-unit',+ subUnitId: 'sheet1',cellValue: {1: {2: null,@@ -314,6 +324,7 @@ describe('EditorDataSyncController', () => {commandService.emit({id: MoveRangeMutation.id,params: {+ unitId: 'test-unit',from: {subUnitId: 'sheet1',value: {@@ -332,6 +343,268 @@ describe('EditorDataSyncController', () => {expect(editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(1);});+ it('refreshes the current edit cell when move-range writes into it', () => {+ const { commandService, editorBridgeService } = createController();++ commandService.emit({+ id: MoveRangeMutation.id,+ params: {+ unitId: 'test-unit',+ from: {+ subUnitId: 'sheet2',+ value: {+ 1: {+ 2: null,+ },+ },+ },+ to: {+ subUnitId: 'sheet1',+ value: {+ 1: {+ 2: { v: 'moved' },+ },+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(1);+ });++ it('ignores set-values on the same coordinates of another sheet', () => {+ const { commandService, editorBridgeService } = createController();++ commandService.emit({+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'test-unit',+ subUnitId: 'sheet2',+ cellValue: {+ 1: {+ 2: { v: 'recalculated' },+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.refreshEditCellState).not.toHaveBeenCalled();+ });++ it('ignores set-values on the same coordinates of another workbook', () => {+ const { commandService, editorBridgeService } = createController();++ commandService.emit({+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'other-unit',+ subUnitId: 'sheet1',+ cellValue: {+ 1: {+ 2: { v: 'updated' },+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.refreshEditCellState).not.toHaveBeenCalled();+ });++ it('ignores move-range on the same coordinates of another sheet', () => {+ const { commandService, editorBridgeService } = createController();++ commandService.emit({+ id: MoveRangeMutation.id,+ params: {+ unitId: 'test-unit',+ from: {+ subUnitId: 'sheet2',+ value: {+ 1: {+ 2: { v: 'moved' },+ },+ },+ },+ to: {+ subUnitId: 'sheet3',+ value: {},+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.refreshEditCellState).not.toHaveBeenCalled();+ });++ it('marks the open editor dirty when an external update replaces the edited cell content', () => {+ const { commandService, editorBridgeService } = createController({ isEditorVisible: true });++ commandService.emit({+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'test-unit',+ subUnitId: 'sheet1',+ cellValue: {+ 1: {+ 2: { f: '=SUM(A1:A2)' },+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.changeEditorDirty).toHaveBeenCalledWith(true);+ expect(editorBridgeService.refreshEditCellState).not.toHaveBeenCalled();+ });++ it('marks the open editor dirty when the edited cell is cleared externally', () => {+ const { commandService, editorBridgeService } = createController({ isEditorVisible: true });++ commandService.emit({+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'test-unit',+ subUnitId: 'sheet1',+ cellValue: {+ 1: {+ 2: null,+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.changeEditorDirty).toHaveBeenCalledWith(true);+ });++ it('leaves the open editor untouched when an external update only changes cell style', () => {+ const { commandService, editorBridgeService } = createController({ isEditorVisible: true });++ commandService.emit({+ id: SetRangeValuesMutation.id,+ params: {+ unitId: 'test-unit',+ subUnitId: 'sheet1',+ cellValue: {+ 1: {+ 2: { s: { bg: { rgb: '#ff0000' }, bl: 1 } },+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.changeEditorDirty).not.toHaveBeenCalled();+ expect(editorBridgeService.refreshEditCellState).not.toHaveBeenCalled();+ });++ it('marks the open editor dirty when move-range writes the edited cell', () => {+ const { commandService, editorBridgeService } = createController({ isEditorVisible: true });++ commandService.emit({+ id: MoveRangeMutation.id,+ params: {+ unitId: 'test-unit',+ from: {+ subUnitId: 'sheet1',+ value: {+ 1: {+ 2: null,+ },+ },+ },+ to: {+ subUnitId: 'sheet1',+ value: {},+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.changeEditorDirty).toHaveBeenCalledWith(true);+ expect(editorBridgeService.refreshEditCellState).not.toHaveBeenCalled();+ });++ it('marks the open editor dirty when move-range moves cells into the edited cell', () => {+ const { commandService, editorBridgeService } = createController({ isEditorVisible: true });++ commandService.emit({+ id: MoveRangeMutation.id,+ params: {+ unitId: 'test-unit',+ from: {+ subUnitId: 'sheet2',+ value: {},+ },+ to: {+ subUnitId: 'sheet1',+ value: {+ 1: {+ 2: { v: 'moved' },+ },+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.changeEditorDirty).toHaveBeenCalledWith(true);+ });++ it('leaves the open editor untouched when move-range does not involve the edited cell', () => {+ const { commandService, editorBridgeService } = createController({ isEditorVisible: true });++ commandService.emit({+ id: MoveRangeMutation.id,+ params: {+ unitId: 'test-unit',+ from: {+ subUnitId: 'sheet1',+ value: {+ 5: {+ 7: null,+ },+ },+ },+ to: {+ subUnitId: 'sheet1',+ value: {+ 6: {+ 8: { v: 'moved' },+ },+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.changeEditorDirty).not.toHaveBeenCalled();+ expect(editorBridgeService.refreshEditCellState).not.toHaveBeenCalled();+ });++ it('leaves the open editor untouched when move-range writes the edited coordinates on another sheet', () => {+ const { commandService, editorBridgeService } = createController({ isEditorVisible: true });++ commandService.emit({+ id: MoveRangeMutation.id,+ params: {+ unitId: 'test-unit',+ from: {+ subUnitId: 'sheet2',+ value: {+ 1: {+ 2: null,+ },+ },+ },+ to: {+ subUnitId: 'sheet2',+ value: {+ 1: {+ 2: { v: 'moved' },+ },+ },+ },+ },+ } as ICommandInfo);++ expect(editorBridgeService.changeEditorDirty).not.toHaveBeenCalled();+ expect(editorBridgeService.refreshEditCellState).not.toHaveBeenCalled();+ });+it('renders formula reference styles in the cell editor when the cell editor is focused', () => {const { controller } = createController();const cellEditorSnapshot: IDocumentData = {@@ -424,3 +697,94 @@ describe('EditorDataSyncController', () => {expect(formulaBarSnapshot.documentStyle.renderConfig?.isRenderStyle).toBe(BooleanNumber.TRUE);});});++describe('EditorDataSyncController cell refresh with real sheet providers', () => {+ function createRealController() {+ const { injector, workbook, render, manager, commands } = createChartRenderTestBed();+ const worksheet = workbook.getSheetBySheetId('grid')!;++ // The formula bar has its own unit and render stack; keep it out of this bed so the assertions+ // observe the cell editor snapshot only.+ injector.add([FormulaEditorController, { useValue: { autoScroll: vi.fn() } as never }]);+ injector.add([IFormulaEditorManagerService, { useValue: { getPosition: () => null } as never }]);+ injector.add([RangeProtectionRuleModel, { useValue: { getRangeRuleInitState: () => true } as never }]);+ injector.add([WorksheetProtectionRuleModel, { useValue: { getSheetRuleInitState: () => true } as never }]);+ injector.add([EditorDataSyncController]);++ commands.registerCommand(SetRangeValuesMutation);+ manager.setCurrent({ sheetId: 'grid' });+ worksheet.getCellMatrix().setValue(0, 0, { v: 'old' });++ const controller = injector.get(EditorDataSyncController);+ onTestFinished(() => controller.dispose());++ const bridge = injector.get(IEditorBridgeService);+ bridge.setEditCell({+ unitId: workbook.getUnitId(),+ sheetId: 'grid',+ scene: render.scene,+ engine: render.engine,+ primary: worksheet.getCellInfoInMergeData(0, 0),+ });+ // A closed editor is what #6715 (and the formula bar) relies on: the snapshot follows the model.+ bridge.changeVisible({+ visible: false,+ eventType: DeviceInputEventType.Keyboard,+ unitId: workbook.getUnitId(),+ });++ return {+ bridge,+ commands,+ worksheet,+ unitId: workbook.getUnitId(),+ editedDocumentModel: () => bridge.getEditCellState()?.documentLayoutObject.documentModel,+ editedBody: () => bridge.getEditCellState()?.documentLayoutObject.documentModel?.getBody()?.dataStream,+ writeCell: (value: string) => commands.syncExecuteCommand(SetRangeValuesMutation.id, {+ unitId: workbook.getUnitId(),+ subUnitId: 'grid',+ cellValue: { 0: { 0: { v: value } } },+ }),+ };+ }++ it('keeps a closed cell editor snapshot aligned with an external write to the edited cell (#6715)', () => {+ const { bridge, worksheet, writeCell, editedBody } = createRealController();+ expect(bridge.isVisible().visible).toBe(false);+ expect(editedBody()).toBe('old\r\n');++ writeCell('Hello World');++ expect(worksheet.getCellRaw(0, 0)?.v).toBe('Hello World');+ // #6715: opening the editor afterwards must show the written value, not the pre-write snapshot.+ expect(editedBody()).toBe('Hello World\r\n');+ });++ it('keeps the open draft and marks it for submission when an external write hits the edited cell', () => {+ const { bridge, worksheet, unitId, writeCell, editedBody, editedDocumentModel } = createRealController();+ const draftDocumentModel = editedDocumentModel();++ bridge.changeVisible({ visible: true, eventType: DeviceInputEventType.Keyboard, unitId });+ expect(bridge.getEditorDirty()).toBe(false);+ writeCell('remote value');++ expect(worksheet.getCellRaw(0, 0)?.v).toBe('remote value');+ // The draft is left alone, so the editor keeps showing it and submits it when editing ends.+ expect(editedDocumentModel()).toBe(draftDocumentModel);+ expect(editedBody()).toBe('old\r\n');+ expect(bridge.getEditorDirty()).toBe(true);+ });++ it('keeps the open draft clean when an external write only changes cell style', () => {+ const { bridge, unitId, commands } = createRealController();+ bridge.changeVisible({ visible: true, eventType: DeviceInputEventType.Keyboard, unitId });++ commands.syncExecuteCommand(SetRangeValuesMutation.id, {+ unitId,+ subUnitId: 'grid',+ cellValue: { 0: { 0: { s: { bg: { rgb: '#ff0000' } } } } },+ });++ expect(bridge.getEditorDirty()).toBe(false);+ });+});diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.tsindex 3f479e812e..7947a5bd4c 100644--- a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts@@ -699,6 +699,23 @@ describe('EditingRenderController business methods', () => {expect(controller._editorBridgeService.refreshEditCellState).toHaveBeenCalledTimes(1);});+ it('commits the draft when a pointer click closes the editor', async () => {+ const { controller } = createController();++ await controller._handleEditorInvisible({+ visible: false,+ eventType: DeviceInputEventType.PointerDown,+ unitId: 'unit-1',+ });++ expect(controller._commandService.syncExecuteCommand).toHaveBeenCalledWith(SetRangeValuesCommand.id, expect.objectContaining({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ range: { startRow: 2, startColumn: 3, endRow: 2, endColumn: 3 },+ value: expect.objectContaining({ v: 'new value' }),+ }));+ });+it('moves the cursor inside the editor and resets editor state on exit', () => {const { controller, formulaBarEditor } = createController();diff --git a/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts b/packages/sheets-ui/src/controllers/editor/data-sync.controller.tsindex 5919331922..5f60dafff5 100644--- a/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts+++ b/packages/sheets-ui/src/controllers/editor/data-sync.controller.ts@@ -18,7 +18,6 @@ import type { DocumentDataModel, ICommandInfo, IDocumentBody, IDocumentStyle, IDimport 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,createParagraphId,@@ -43,6 +42,7 @@ import { ReplaceSnapshotCommand } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { MoveRangeMutation, RangeProtectionRuleModel, SetRangeValuesMutation, WorksheetProtectionRuleModel } from '@univerjs/sheets';import { skip } from 'rxjs';+import type { ICellEditorState } from '../../services/editor-bridge.service';import { IEditorBridgeService } from '../../services/editor-bridge.service';import { IFormulaEditorManagerService } from '../../services/editor/formula-editor-manager.service';import { FormulaEditorController } from './formula-editor.controller';@@ -68,6 +68,12 @@ const formulaEditorStyle: IDocumentStyle = {},};+/**+ * Cell properties an editor works on. `s` (cell style) is rendered by the editor but never owned by it,+ * so a style-only write must not invalidate an open draft.+ */+const CELL_CONTENT_KEYS = new Set(['v', 't', 'f', 'si', 'p']);+/*** sync data between cell editor and formula editor*/@@ -181,37 +187,85 @@ export class EditorDataSyncController extends Disposable {const editCellState = this._editorBridgeService.getEditLocation();- if (editCellState == null) {+ if (editCellState == null || !this._shouldRefreshCurrentEditCell(command, editCellState)) {return;}- const { row, column } = editCellState;+ /**+ * While the cell editor is open its document holds an uncommitted draft, so an external update+ * must not rebuild it. When such an update replaces the edited cell's content, the draft no+ * longer describes the cell and is committed when editing ends.+ */+ if (this._editorBridgeService.isVisible().visible) {+ if (this._writesCellContent(command, editCellState)) {+ this._editorBridgeService.changeEditorDirty(true);+ }- 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();+ return;}++ /**+ * 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 {+ private _shouldRefreshCurrentEditCell(command: ICommandInfo, editCell: ICellEditorState): boolean {+ const { row, column } = editCell;+if (command.id === SetRangeValuesMutation.id && command.params) {const params = command.params as ISetRangeValuesMutationParams;- return this._hasMatrixCell(params.cellValue, row, column);+ return this._isEditedUnit(editCell, params.unitId, params.subUnitId)+ && 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 (this._isEditedUnit(editCell, params.unitId, params.from.subUnitId)+ && this._hasMatrixCell(params.from.value, row, column))+ || (this._isEditedUnit(editCell, params.unitId, params.to.subUnitId)+ && this._hasMatrixCell(params.to.value, row, column));}return false;}+ /**+ * Whether a matched mutation replaces the edited cell's content. Moving cells into or out of the edited+ * cell does; a style-only write does not, because the editor does not own the cell style it renders with.+ */+ private _writesCellContent(command: ICommandInfo, editCell: ICellEditorState): boolean {+ // MoveRange only reaches this point when it writes or clears the edited cell's coordinates.+ if (command.id === MoveRangeMutation.id) {+ return true;+ }++ if (command.id !== SetRangeValuesMutation.id || !command.params) {+ return false;+ }++ const params = command.params as ISetRangeValuesMutationParams;+ const cell = params.cellValue?.[editCell.row]?.[editCell.column];++ // Clearing the cell changes its content just like writing a value does.+ if (cell == null) {+ return true;+ }++ return Object.keys(cell).some((key) => CELL_CONTENT_KEYS.has(key));+ }++ /**+ * A row/column pair is only meaningful inside the workbook and worksheet it belongs to, so a mutation+ * on another sheet or another workbook must not be treated as an update of the edit cell.+ */+ private _isEditedUnit(editCell: ICellEditorState, unitId: string, subUnitId: string): boolean {+ return editCell.unitId === unitId && editCell.sheetId === subUnitId;+ }+private _hasMatrixCell(matrix: ISetRangeValuesMutationParams['cellValue'] | IMoveRangeMutationParams['from']['value'],row: number,diff --git a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.tsindex 3ed9191527..bc034bcf6f 100644--- a/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/editor-bridge.render-controller.ts@@ -171,19 +171,6 @@ export class EditorBridgeRenderController extends RxDisposable implements IRendeif (this._editorBridgeService.isVisible().visible) return;this._editorBridgeService.refreshEditCellState();}-- // if (command.id === SetRangeValuesMutation.id) {- // const params = command.params as ISetRangeValuesMutationParams;- // const { cellValue, unitId, subUnitId } = params;- // if (!cellValue) return;- // const editCell = this._editorBridgeService.getEditLocation();- // if (editCell) {- // const { unitId: editingUnitId, sheetId: editingSheetId, row, column } = editCell;- // if (unitId === editingUnitId && subUnitId === editingSheetId && cellValue && cellValue[row] && Object.prototype.hasOwnProperty.call(cellValue[row], column)) {- // this._editorBridgeService.refreshEditCellState();- // }- // }- // }}));d.add(this._commandService.beforeCommandExecuted((command: ICommandInfo, options?: IExecutionOptions) => {diff --git a/packages/sheets-ui/src/services/editor-bridge.service.ts b/packages/sheets-ui/src/services/editor-bridge.service.tsindex 1b8c486d13..480f73315a 100644--- a/packages/sheets-ui/src/services/editor-bridge.service.ts+++ b/packages/sheets-ui/src/services/editor-bridge.service.ts@@ -113,6 +113,10 @@ export interface IEditorBridgeService {* Do not use it directly. Use the `SetCellEditVisibleOperation` command instead.*/changeVisible(param: IEditorBridgeServiceVisibleParam): void;+ /**+ * Mark the open editor content as pending submission. Besides user edits, an external write that+ * replaces the edited cell's content is marked too, so the draft still wins when editing ends.+ */changeEditorDirty(dirtyStatus: boolean): void;getEditorDirty(): boolean;isVisible(): IEditorBridgeServiceVisibleParam;