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.

53.2 KB
Raw Blame
/**
 * 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 {
    DocumentDataModel,
    ICellData,
    ICommandInfo,
    IDisposable,
    IDocumentBody,
    IDocumentData,
    IDocumentStyle,
    IMutationInfo,
    IStyleData,
    ITextRange,
    Nullable,
    Styles,
    Workbook,
} from '@univerjs/core';
import type { IInsertTextCommandParams, IRichTextEditingMutationParams } from '@univerjs/docs';
import type { IInnerPasteCommandParams } from '@univerjs/docs-ui';
import type {
    ISetRangeValuesCommandParams,
    ISetWorksheetActivateCommandParams,
    MutationsAffectRange,
} from '@univerjs/sheets';
import {
    BooleanNumber,
    CellValueType,
    createParagraphId,
    DEFAULT_EMPTY_DOCUMENT_VALUE,
    Direction,
    Disposable,
    DisposableCollection,
    DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
    DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
    EDITOR_ACTIVATED,
    FOCUSING_EDITOR_INPUT_FORMULA,
    FOCUSING_EDITOR_STANDALONE,
    FOCUSING_FX_BAR_EDITOR,
    generateRandomId,
    ICommandService,
    IConfigService,
    IContextService,
    Inject,
    isFormulaString,
    isTextFormat,
    IUndoRedoService,
    IUniverInstanceService,
    LocaleService,
    SheetTypes,
    toDisposable,
    Tools,
    UniverInstanceType,
    WrapStrategy,
} from '@univerjs/core';
import {
    DocSelectionManagerService,
    DocSkeletonManagerService,
    DocStateChangeManagerService,
    InsertTextCommand,
    RichTextEditingMutation,
} from '@univerjs/docs';
import {
    DocSelectionRenderService,
    IEditorService,
    InnerPasteCommand,
    MoveCursorOperation,
    MoveSelectionOperation,
    ReplaceSnapshotCommand,
    SetDocInputStyleCommand,
    VIEWPORT_KEY,
} from '@univerjs/docs-ui';
import { IFunctionService, LexerTreeBuilder, matchToken } from '@univerjs/engine-formula';
import {
    convertTextRotation,
    DeviceInputEventType,
    IRenderManagerService,
    NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
} from '@univerjs/engine-render';
import {
    adjustRangeOnMutation,
    COMMAND_LISTENER_SKELETON_CHANGE,
    getCellType,
    getCellValue,
    InsertColMutation,
    InsertRowMutation,
    isCellImage,
    MoveColsMutation,
    MoveRowsMutation,
    REF_SELECTIONS_ENABLED,
    RemoveColMutation,
    RemoveRowMutation,
    SetRangeValuesCommand,
    SetSelectionsOperation,
    SetWorksheetActivateCommand,
    SetWorksheetActiveOperation,
    SheetInterceptorService,
    SheetsSelectionsService,
} from '@univerjs/sheets';
import { DISABLE_AUTO_FOCUS_KEY, KeyCode, MetaKeys } from '@univerjs/ui';
import { distinctUntilChanged, filter } from 'rxjs';
import type { IDocObjectParam } from '../../basics/editor/get-editor-object';
import type { IUniverSheetsUIConfig } from '../../config/config';
import type { ICellEditorState, IEditorBridgeServiceVisibleParam } from '../../services/editor-bridge.service';
import { getEditorObject } from '../../basics/editor/get-editor-object';
import { MoveSelectionCommand, MoveSelectionEnterAndTabCommand } from '../../commands/commands/set-selection.command';
import {
    SetCellEditVisibleArrowOperation,
    SetCellEditVisibleOperation,
    SetCellEditVisibleWithF2Operation,
} from '../../commands/operations/cell-edit.operation';
import { ScrollToRangeOperation } from '../../commands/operations/scroll-to-range.operation';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
import { IEditorBridgeService } from '../../services/editor-bridge.service';
import { ICellEditorManagerService } from '../../services/editor/cell-editor-manager.service';
import { SheetCellEditorResizeService } from '../../services/editor/cell-editor-resize.service';
import { EditorBridgeRenderController } from '../render-controllers/editor-bridge.render-controller';
import { MOVE_SELECTION_KEYCODE_LIST } from '../shortcuts/editor.shortcut';
import { extractStringFromForceString, isForceString } from '../utils/cell-tools';
import { normalizeString } from '../utils/char-tools';
import { getEditCellInputPosition } from './utils/get-edit-cell-input-position';
import { isRangeSelector } from './utils/is-range-selector';

const HIDDEN_EDITOR_POSITION = -1000;

function getPercentOffset(editCellState: ICellEditorState, dataStream: string | undefined): Nullable<number> {
    if (!editCellState.isPercentFormat || editCellState.isInArrayFormulaRange) {
        return null;
    }

    const percentSuffix = `%${DEFAULT_EMPTY_DOCUMENT_VALUE}`;
    return dataStream?.endsWith(percentSuffix) ? dataStream.length - percentSuffix.length : null;
}

function getPercentEditorSelection(
    editCellState: ICellEditorState,
    visibleParam: IEditorBridgeServiceVisibleParam,
    dataStream: string | undefined
): Nullable<ITextRange> {
    const percentOffset = getPercentOffset(editCellState, dataStream);
    if (percentOffset == null || visibleParam.eventType !== DeviceInputEventType.Keyboard) {
        return null;
    }

    const { initialValue, keycode } = visibleParam;
    // A formula's trailing percent sign is an operator, not a retained number-format suffix.
    if (isFormulaString(dataStream) && keycode === KeyCode.F2) {
        return null;
    }

    if (keycode === KeyCode.F2) {
        return { startOffset: percentOffset, endOffset: percentOffset, collapsed: true };
    }

    if (keycode === KeyCode.BACKSPACE || keycode === KeyCode.DELETE || !/^\d/.test(initialValue ?? '')) {
        return null;
    }

    return { startOffset: 0, endOffset: percentOffset, collapsed: false };
}

enum CursorChange {
    InitialState,
    StartEditor,
    CursorChange,
}

export class EditingRenderController extends Disposable {
    /**
     * It is used to distinguish whether the user has actively moved the cursor in the editor, mainly through mouse clicks.
     */
    private _cursorChange: CursorChange = CursorChange.InitialState;

    /** If the corresponding unit is active and prepared for editing. */
    private _editingUnit = '';

    private _submitEmptyCellImageEdit = false;

    _cursorTimeout: NodeJS.Timeout;

    constructor(
        @IUndoRedoService private readonly _undoRedoService: IUndoRedoService,
        @IContextService private readonly _contextService: IContextService,
        @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
        @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
        @ICellEditorManagerService private readonly _cellEditorManagerService: ICellEditorManagerService,
        @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,
        @IFunctionService private readonly _functionService: IFunctionService,
        @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
        @ICommandService private readonly _commandService: ICommandService,
        @Inject(LocaleService) protected readonly _localService: LocaleService,
        @IEditorService private readonly _editorService: IEditorService,
        @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
        @Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,
        @Inject(SheetCellEditorResizeService) private readonly _sheetCellEditorResizeService: SheetCellEditorResizeService,
        @Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,
        @IConfigService private readonly _configService: IConfigService,
        @Inject(DocStateChangeManagerService) private readonly _docStateChangeManagerService: DocStateChangeManagerService
    ) {
        super();

        // EditingRenderController is per unit. It should only handle keyboard events when the unit is
        // the current of its type.

        this.disposeWithMe(this._init());
        this._initEditorVisibilityListener();
    }

    override dispose(): void {
        super.dispose();
    }

    private get _workbookSelections() {
        return this._selectionManagerService.getWorkbookSelections(this._editingUnit);
    }

    private _init(): IDisposable {
        const d = new DisposableCollection();
        this._subscribeToCurrentCell(d);
        this._initialCursorSync(d);
        this._listenEditorFocus(d);
        this._commandExecutedListener(d);
        this._initSkeletonListener(d);

        // RenderManagerService._disposeItem will calls EditingRenderController.dispose before unitDisposed$.subscribe,so that the timer won't be cleared
        d.add(() => {
            clearTimeout(this._cursorTimeout);
        });

        // FIXME: this problem is the same with slide. Should be fixed when refactoring editor.
        this._cursorTimeout = setTimeout(() => {
            this._cursorStateListener(d);
        }, 1000);

        return d;
    }

    private _initEditorVisibilityListener(): void {
        this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).subscribe(async (unit) => {
            if (this._editingUnit && !this._editorBridgeService.isForceKeepVisible() && (!unit || unit.getUnitId() !== this._editingUnit)) {
                this._commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, {
                    visible: false,
                    eventType: DeviceInputEventType.Keyboard,
                    keycode: KeyCode.ESC,
                    unitId: this._editingUnit,
                });

                if (!unit) return;

                const editorBridgeRenderController = this._renderManagerService.getRenderUnitById(unit.getUnitId())?.with(EditorBridgeRenderController);
                if (editorBridgeRenderController) {
                    editorBridgeRenderController.refreshEditorPosition();
                }
            }
        }));

        this.disposeWithMe(
            this._editorBridgeService.visible$
                .pipe(distinctUntilChanged((prev, curr) => prev.visible === curr.visible))
                .subscribe(async (params) => {
                    if (params.visible) {
                        this._editingUnit = params.unitId;
                        this._handleEditorVisible(params);
                    } else if (this._editingUnit) {
                        await this._handleEditorInvisible(params);
                        this._editingUnit = '';
                    }
                })
        );
    }

    private _listenEditorFocus(d: DisposableCollection) {
        const renderConfig = this._getEditorObject();
        if (!renderConfig) return;

        d.add(renderConfig.document.onPointerDown$.subscribeEvent(() => {
            // fix https://github.com/dream-num/univer/issues/628, need to recalculate the cell editor size after
            // it acquire focus.
            if (this._editingUnit && this._editorBridgeService.isVisible()) {
                const param = this._editorBridgeService.getEditCellState();
                const editorId = this._editorBridgeService.getCurrentEditorId();

                if (!param || !editorId) {
                    return;
                }

                this._sheetCellEditorResizeService?.fitTextSize();
            }
        }));
    }

    private _initialCursorSync(d: DisposableCollection) {
        d.add(this._cellEditorManagerService.focus$.pipe(filter((f) => !!f)).subscribe(() => {
            const editorId = this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR)
                ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
                : this._editorBridgeService.getCurrentEditorId();
            const docUnitId = editorId ?? this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC)?.getUnitId();
            if (!docUnitId) return;

            const docSelectionRenderManager = this._renderManagerService.getRenderUnitById(docUnitId)?.with(DocSelectionRenderService);
            if (!docSelectionRenderManager) return;

            docSelectionRenderManager.sync();
            this._cacheEmptyCellTextStyle();
        }));
    }

    private _initSkeletonListener(d: DisposableCollection) {
        const commandList = new Set(COMMAND_LISTENER_SKELETON_CHANGE);
        commandList.delete(SetWorksheetActiveOperation.id);

        d.add(this._commandService.onCommandExecuted((commandInfo) => {
            if (!commandList.has(commandInfo.id)) {
                return;
            }
            switch (commandInfo.id) {
                case MoveRowsMutation.id:
                case MoveColsMutation.id:
                case RemoveColMutation.id:
                case RemoveRowMutation.id:
                case InsertColMutation.id:
                case InsertRowMutation.id:
                {
                    const editLocation = this._editorBridgeService.getEditLocation();
                    if (!editLocation) break;
                    const currentRange = {
                        startRow: editLocation.row,
                        startColumn: editLocation.column,
                        endRow: editLocation.row,
                        endColumn: editLocation.column,
                    };
                    const newRange = adjustRangeOnMutation(currentRange, commandInfo as IMutationInfo<MutationsAffectRange>);
                    if (!newRange) break;
                    const newRow = newRange.startRow;
                    const newColumn = newRange.startColumn;
                    this._editorBridgeService.updateEditLocation(newRow, newColumn);
                    break;
                }
            }

            this._sheetCellEditorResizeService?.resizeCellEditor(() => {
                this._textSelectionManagerService.refreshSelection({
                    unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
                    subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
                });
            });
        }));
    }

    /**
     * Should update current editing cell info when selection is changed.
     * @param d DisposableCollection
     */
    private _subscribeToCurrentCell(d: DisposableCollection) {
        // TODO: After the sheet dispose, recreate the sheet, the first cell edit may be unsuccessful,
        // it should be the editor initialization late, and we need to pay attention to this problem in the future.
        d.add(this._editorBridgeService.currentEditCellState$.subscribe((editCellState) => {
            const disableEdit = this._configService.getConfig<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY)?.disableEdit;
            if (disableEdit) {
                return;
            }

            if (editCellState == null || this._editorBridgeService.isForceKeepVisible()) {
                return;
            }
            const state = this._editorBridgeService.getEditCellState();
            if (state == null) {
                return;
            }

            const { position, documentLayoutObject, scaleX, editorUnitId } = state;

            if (this._contextService.getContextValue(FOCUSING_EDITOR_STANDALONE)) {
                return;
            }

            const cellDocument = this._getDocumentDataModel();
            if (cellDocument == null) return;
            const { startX, endX } = position;
            const { textRotation, wrapStrategy, documentModel } = documentLayoutObject;
            const { vertexAngle: angle } = convertTextRotation(textRotation);

            if (wrapStrategy === WrapStrategy.WRAP && angle === 0) {
                cellDocument.updateDocumentDataPageSize((endX - startX) / scaleX);
            }

            this._commandService.syncExecuteCommand(ReplaceSnapshotCommand.id, {
                unitId: editorUnitId,
                snapshot: (documentModel!.getSnapshot()),
            });

            this._textSelectionManagerService.replaceDocRanges(
                [{
                    startOffset: 0,
                    endOffset: 0,
                }],
                {
                    unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
                    subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
                },
                true,
                { shouldFocus: !this._contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY) }
            );

            const cellSelectionRenderManager = this._renderManagerService.getRenderUnitById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.with(DocSelectionRenderService);
            const formulaSelectionRenderManager = this._renderManagerService.getRenderUnitById(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY)?.with(DocSelectionRenderService);
            if (cellSelectionRenderManager?.canFocusing || formulaSelectionRenderManager?.canFocusing) {
                this._univerInstanceService.setCurrentUnitForType(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
                if (this._contextService.getContextValue(DISABLE_AUTO_FOCUS_KEY)) {
                    cellSelectionRenderManager?.setInputPosition(HIDDEN_EDITOR_POSITION, HIDDEN_EDITOR_POSITION);
                } else {
                    // Keep the hidden input on the selected cell, so the IME candidate window opens next to it
                    // when the user starts typing before the cell editor is visible.
                    const { x, y } = getEditCellInputPosition(state, this._renderManagerService.getRenderUnitById(state.unitId)?.engine);
                    cellSelectionRenderManager?.activate(x, y, true);
                }
            }
        }));
    }

    /**
     * Listen to document edits to refresh the size of the sheet editor, not for normal editor.
     */
    private _commandExecutedListener(d: DisposableCollection) {
        d.add(this._commandService.beforeCommandExecuted((command: ICommandInfo) => {
            if (command.id !== InsertTextCommand.id && command.id !== InnerPasteCommand.id) {
                return;
            }

            const insertParams = command.id === InsertTextCommand.id ? command.params as IInsertTextCommandParams : null;
            const pasteParams = command.id === InnerPasteCommand.id ? command.params as IInnerPasteCommandParams : null;
            const unitId = insertParams?.unitId ?? pasteParams?.unitId;
            const visibleParam = this._editorBridgeService.isVisible();
            const editCellState = this._editorBridgeService.getEditLocation();
            if (unitId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY || !visibleParam.visible || editCellState == null) {
                return;
            }

            const dataStream = this._getDocumentDataModel()?.getBody()?.dataStream;
            if (dataStream == null) {
                return;
            }

            const percentOffset = getPercentOffset(editCellState, dataStream);
            if (percentOffset == null) {
                return;
            }

            // The input event captures its range before the editor opens, so the first digit still carries a stale range.
            if (
                insertParams &&
                !this._editorBridgeService.getEditorDirty() &&
                visibleParam.eventType === DeviceInputEventType.Keyboard &&
                /^\d/.test(visibleParam.initialValue ?? '') &&
                /^\d/.test(insertParams.body.dataStream)
            ) {
                insertParams.range = {
                    startOffset: 0,
                    endOffset: percentOffset + (insertParams.body.dataStream.endsWith('%') ? 1 : 0),
                    collapsed: false,
                };
            }

            const selectionParams = { unitId, subUnitId: unitId };
            const ranges = insertParams ? [insertParams.range] : this._textSelectionManagerService.getTextRanges(selectionParams);
            const input = insertParams?.body.dataStream ?? pasteParams?.doc.body?.dataStream;
            // Overtype the preserved suffix for typed and pasted percentages, but keep formula operators.
            if (
                !isFormulaString(dataStream) &&
                input?.endsWith('%') &&
                ranges?.length === 1 &&
                ranges[0].endOffset === percentOffset &&
                (!pasteParams || !this._textSelectionManagerService.getRectRanges(selectionParams)?.length)
            ) {
                const range = { ...ranges[0], endOffset: percentOffset + 1, collapsed: false };
                if (insertParams) {
                    insertParams.range = range;
                } else if (pasteParams) {
                    pasteParams.selections = [range];
                }
            }
        }));

        d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {
            if (command.id === RichTextEditingMutation.id) {
                const params = command.params as IRichTextEditingMutationParams;
                const { unitId: commandUnitId } = params;

                // Only when the sheet it attached to is focused. Maybe we should change it to the render unit sys.
                if (isRangeSelector(commandUnitId)) {
                    return;
                }

                this._editorBridgeService.changeEditorDirty(true);

                if (!this._editorBridgeService.isVisible().visible) {
                    return;
                }

                if (commandUnitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
                    this._sheetCellEditorResizeService?.fitTextSize();
                }
            }
        }));

        const closeEditorOperation = [SetCellEditVisibleArrowOperation.id];
        d.add(this._commandService.onCommandExecuted((command: ICommandInfo) => {
            if (closeEditorOperation.includes(command.id)) {
                const params = command.params as IEditorBridgeServiceVisibleParam & { isShift: boolean };
                const { keycode, isShift } = params;

                /**
                 * After the user enters the editor and actively moves the editor selection area with the mouse,
                 * the up, down, left, and right keys can no longer switch editing cells,
                 * but move the cursor within the editor instead.
                 */
                // Shift+arrows select text even when typing opened the editor without a pointer or F2.
                if (keycode != null && (
                    isShift ||
                    this._cursorChange === CursorChange.CursorChange ||
                    this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR)
                )) {
                    this._moveInEditor(keycode, isShift);
                    return;
                }

                // TODO@Jocs: After we merging editor related controllers, this seems verbose.
                // We can directly call SetRangeValues here.
                this._commandService.syncExecuteCommand(SetCellEditVisibleOperation.id, params);
            }

            if (command.id === SetCellEditVisibleWithF2Operation.id) {
                this._cursorChange = CursorChange.CursorChange;
            }
        }));
    }

    // You can double-click on the cell or input content by keyboard to put the cell into the edit state.
    private _handleEditorVisible(param: IEditorBridgeServiceVisibleParam) {
        const { eventType, keycode } = param;
        // Change `CursorChange` to changed status, when formula bar clicked.
        this._cursorChange =
            (eventType === DeviceInputEventType.PointerDown || eventType === DeviceInputEventType.Dblclick)
                ? CursorChange.CursorChange
                : CursorChange.StartEditor;

        const editCellState = this._editorBridgeService.getEditLocation();
        if (editCellState == null) {
            return;
        }

        const { unitId, isInArrayFormulaRange = false } = editCellState;

        this._clearEditorHistory();

        this._commandService.syncExecuteCommand(ScrollToRangeOperation.id, {
            unitId,
            range: {
                startRow: editCellState.row,
                startColumn: editCellState.column,
                endRow: editCellState.row,
                endColumn: editCellState.column,
            },
        });

        this._editorBridgeService.refreshEditCellPosition(false);
        const editorObject = this._getEditorObject();

        if (editorObject == null) {
            return;
        }

        const { document } = editorObject;

        this._contextService.setContextValue(EDITOR_ACTIVATED, true);

        const documentDataModel = this._getDocumentDataModel();
        const skeleton = this._getEditorSkeleton(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
        if (!skeleton || !documentDataModel) {
            return;
        }

        this._resizeEditorOnOpen(param, editorObject, !!isInArrayFormulaRange);

        const clearAndEdit = () => {
            const resetPointerSelection = isInArrayFormulaRange && eventType === DeviceInputEventType.PointerDown;
            const editorId = this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR)
                ? DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
                : this._editorBridgeService.getCurrentEditorId();
            if (resetPointerSelection) {
                // The pointer anchor was measured against inherited text that is about to be cleared.
                this._renderManagerService.getRenderUnitById(editorId)
                    ?.with(DocSelectionRenderService)
                    .cancelPointerSelection();
            }
            this._emptyDocumentDataModel(documentDataModel.getSnapshot().documentStyle, !!isInArrayFormulaRange);
            document.makeDirty();
            if (resetPointerSelection) {
                this._getEditorSkeleton(editorId)?.calculate();
            }

            // @JOCS, Why calculate here?
            if (keycode === KeyCode.BACKSPACE || eventType === DeviceInputEventType.Dblclick) {
                skeleton.calculate();
                this._editorBridgeService.changeEditorDirty(true);
            }

            this._textSelectionManagerService.replaceDocRanges(
                [{
                    startOffset: 0,
                    endOffset: 0,
                }],
                {
                    unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
                    subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
                }
            );
            if (resetPointerSelection && editorId !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
                const selectionTarget = { unitId: editorId, subUnitId: editorId };
                const previousSelection = this._textSelectionManagerService.getSelectionInfo(selectionTarget);
                // Native input must retain a caret while the refreshed formula-bar geometry is not ready.
                this._textSelectionManagerService.replaceSelectionInfoWithoutRefresh({
                    textRanges: [{ startOffset: 0, endOffset: 0, collapsed: true, isActive: true }],
                    rectRanges: [],
                    segmentId: '',
                    segmentPage: -1,
                    style: previousSelection?.style ?? NORMAL_TEXT_SELECTION_PLUGIN_STYLE,
                    isEditing: true,
                }, selectionTarget);
                this._textSelectionManagerService.refreshSelection(selectionTarget, true);
            }
        };
        const replaceSelection = (selection: ITextRange) => {
            // An embedded sheet may open its editor while the host document retains global focus.
            this._textSelectionManagerService.replaceDocRanges(
                [selection],
                {
                    unitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
                    subUnitId: DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
                }
            );
        };
        const percentSelection = getPercentEditorSelection(editCellState, param, documentDataModel.getBody()?.dataStream);
        const cellImage = isCellImage(documentDataModel.getSnapshot());
        this._submitEmptyCellImageEdit = cellImage && eventType === DeviceInputEventType.Keyboard && keycode === KeyCode.BACKSPACE;

        if (cellImage || isInArrayFormulaRange) {
            clearAndEdit();
        } else if (eventType === DeviceInputEventType.Keyboard && keycode === KeyCode.F2) {
            // f2, continue to edit
            document.makeDirty();
            replaceSelection({ startOffset: 0, endOffset: 0, collapsed: true });
            const endOffset = (documentDataModel.getBody()?.dataStream.length ?? 2) - 2;
            replaceSelection(percentSelection ?? { startOffset: endOffset, endOffset, collapsed: true });
        } else if (eventType === DeviceInputEventType.Keyboard) {
            if (percentSelection) {
                replaceSelection(percentSelection);
            } else {
                clearAndEdit();
            }
        } else if (eventType === DeviceInputEventType.Dblclick) {
            if (this._contextService.getContextValue(FOCUSING_EDITOR_INPUT_FORMULA)) {
                return;
            }

            const dataStream = documentDataModel.getBody()!.dataStream;
            const endOffset = (!isFormulaString(dataStream) ? getPercentOffset(editCellState, dataStream) : null) ?? dataStream.length - 2;
            replaceSelection({ startOffset: endOffset, endOffset, collapsed: true });
        }

        this._renderManagerService.getRenderUnitById(unitId)?.scene.resetCursor();
    }

    private _resizeEditorOnOpen(param: IEditorBridgeServiceVisibleParam, editorObject: IDocObjectParam, isInArrayFormulaRange: boolean) {
        const pointerPosition = param.eventType === DeviceInputEventType.Dblclick ? param.pointerPosition : undefined;
        this._sheetCellEditorResizeService?.fitTextSize(() => {
            if (pointerPosition && this._editorBridgeService.isVisible() !== param) {
                return;
            }

            const { engine, scene } = editorObject;
            scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)?.scrollToViewportPos({
                viewportScrollX: pointerPosition ? 0 : Number.POSITIVE_INFINITY,
                viewportScrollY: pointerPosition ? 0 : Number.POSITIVE_INFINITY,
            });
            if (!pointerPosition || isInArrayFormulaRange) {
                return;
            }

            const rect = engine.getCanvasElement().getBoundingClientRect();
            if (rect.width > 0 && rect.height > 0) {
                this._renderManagerService.getRenderUnitById(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.with(DocSelectionRenderService).setCursorManually(
                    (pointerPosition.x - rect.left) * engine.width / rect.width,
                    (pointerPosition.y - rect.top) * engine.height / rect.height,
                    true,
                    true,
                    { strict: false }
                );
            }
        });
    }

    private _cacheEmptyCellTextStyle(): void {
        const sourceBody = this._editorBridgeService.getEditLocation()?.documentLayoutObject.documentModel?.getBody();
        const textRun = sourceBody?.textRuns?.length === 1 ? sourceBody.textRuns[0] : null;
        if (
            sourceBody?.dataStream === DEFAULT_EMPTY_DOCUMENT_VALUE
            && textRun?.st === 0
            && textRun.ed === 0
        ) {
            this._commandService.syncExecuteCommand(SetDocInputStyleCommand.id, {
                style: Tools.deepClone(textRun.ts),
            });
        }
    }

    private _refreshCurrentSelections(sheetId: string) {
        const selections = this._workbookSelections.getSelectionsOfWorksheet(sheetId);
        if (selections) {
            this._contextService.setContextValue(REF_SELECTIONS_ENABLED, false);
            this._commandService.syncExecuteCommand(SetSelectionsOperation.id, {
                unitId: this._editingUnit,
                subUnitId: sheetId,
                selections,
            });
        }
    }

    private async _handleEditorInvisible(param: IEditorBridgeServiceVisibleParam) {
        const editCellState = this._editorBridgeService.getEditCellState();
        const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
        const snapshot = Tools.deepClone(documentDataModel?.getSnapshot());
        const { keycode, isShift } = param;
        const shouldSubmitEmptyCellImageEdit = this._submitEmptyCellImageEdit;
        this._submitEmptyCellImageEdit = false;
        this._cursorChange = CursorChange.InitialState;
        const currentUnitId = editCellState?.unitId ?? '';
        this._exitInput(param);
        if (editCellState == null) {
            return;
        }

        const workbook = this._univerInstanceService.getUnit<Workbook>(currentUnitId, UniverInstanceType.UNIVER_SHEET);
        const editWorksheet = workbook?.getSheetBySheetId(editCellState.sheetId);
        // A stale edit must not restore its former sheet or submit into a non-Grid sheet.
        if (!workbook || !editWorksheet || (editWorksheet.getConfig().type ?? SheetTypes.GRID) !== SheetTypes.GRID) {
            this._editorBridgeService.disableForceKeepVisible();
            this._editorBridgeService.refreshEditCellState();
            return;
        }
        const worksheet = workbook.getActiveSheet();
        const workbookId = workbook.getUnitId();
        const worksheetId = worksheet.getSheetId();

        const { unitId, sheetId } = editCellState;
        /**
         * When closing the editor, switch to the current tab of the editor.
         */
        if (workbookId === unitId && sheetId !== worksheetId) {
            // SetWorksheetActivateCommand handler uses Promise
            await this._commandService.executeCommand<ISetWorksheetActivateCommandParams>(SetWorksheetActivateCommand.id, {
                subUnitId: sheetId,
                unitId,
            });
        }

        // Reselect the current selections, when exist cell editor by press ESC.I
        if (keycode === KeyCode.ESC) {
            if (this._editorBridgeService.isForceKeepVisible()) {
                this._editorBridgeService.disableForceKeepVisible();
            }
            this._editorBridgeService.refreshEditCellState();
            this._refreshCurrentSelections(sheetId);
            return;
        }

        const isEmpty = snapshot?.body?.dataStream.length === 2;
        const cellImage = editCellState.documentLayoutObject.documentModel
            ? isCellImage(editCellState.documentLayoutObject.documentModel.getSnapshot())
            : false;

        if (snapshot && shouldSubmitCellEdit({ isEmpty, isCellImage: cellImage, shouldSubmitEmptyCellImageEdit })) {
            const res = await this._submitEdit(snapshot, keycode === (MetaKeys.CTRL_COMMAND | KeyCode.ENTER) || keycode === (MetaKeys.MAC_CTRL | KeyCode.ENTER));
            if (res === false) return; // if the submit was rejected, don't move selection
        }

        // moveSelection need to put behind of SetRangeValuesCommand, fix https://github.com/dream-num/univer/issues/1155
        if (keycode !== undefined) {
            this._moveSelection(keycode, currentUnitId, worksheetId, isShift);
        }
    }

    private _getEditorObject() {
        return getEditorObject(this._editorBridgeService.getCurrentEditorId(), this._renderManagerService);
    }

    submitCellData(documentDataModel: DocumentDataModel) {
        const snapshot = Tools.deepClone(documentDataModel.getSnapshot());
        const renderConfig = snapshot.documentStyle?.renderConfig;
        if (renderConfig) {
            renderConfig.isRenderStyle = BooleanNumber.FALSE;
        }

        return this._submitEdit(snapshot);
    }

    private async _submitEdit(snapshot: IDocumentData, wholeSelection = false) {
        const editCellState = this._editorBridgeService.getEditCellState();
        if (editCellState == null) {
            return true;
        }
        // The editor may display an expanded date/time value; do not write that intercepted text back unless it was edited.
        if (!this._editorBridgeService.getEditorDirty()) {
            return true;
        }
        const { unitId, sheetId, row, column } = editCellState;

        const workbook = this._univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET);
        if (!workbook) {
            return true;
        }
        let worksheet = workbook.getActiveSheet();

        // If the target cell does not exist, there is no need to execute setRangeValue
        const setRangeValueTargetSheet = workbook.getSheetBySheetId(sheetId);
        if (!setRangeValueTargetSheet) {
            return true;
        }

        worksheet = workbook.getActiveSheet();

        // If cross-sheet operation, switch current sheet first, then const cellData
        // This should moved to after cell editor
        const cellData: Nullable<ICellData> = getCellDataByInput(
            { ...(worksheet.getCellRaw(row, column) || {}) },
            snapshot,
            this._lexerTreeBuilder,
            this._localService,
            this._functionService,
            workbook.getStyles()
        );

        if (!cellData) {
            return true;
        }

        // Remove the same style attributes that have been set by composed style in the cell data.
        this._removeComposedCellStyleInCellData(cellData, worksheet.getComposedCellStyleWithoutSelf(row, column));

        const finalCell = this._sheetInterceptorService.onWriteCell(workbook, worksheet, row, column, cellData) as ICellData;

        // If the cell data after interceptor is the same as the raw cell data, there is no need to execute setRangeValue command, just return directly.
        const rawCell = worksheet.getCellRaw(row, column);
        const finalCellCleaned = getComparableCellData(finalCell, workbook.getStyles(), rawCell);
        const rawCellCleaned = getComparableCellData(rawCell, workbook.getStyles(), rawCell);
        if (Tools.diffValue(finalCellCleaned, rawCellCleaned)) {
            return true;
        }

        const range = wholeSelection
            ? this._workbookSelections.getCurrentLastSelection()?.range
            : {
                startRow: row,
                startColumn: column,
                endRow: row,
                endColumn: column,
            };

        const redoUndoId = generateRandomId(6);
        const res = this._commandService.syncExecuteCommand<ISetRangeValuesCommandParams>(SetRangeValuesCommand.id, {
            subUnitId: sheetId,
            unitId,
            range,
            value: Tools.deepClone(finalCell),
            redoUndoId,
        });

        if (res) {
            const isValid = await this._sheetInterceptorService.onValidateCell(workbook, worksheet, row, column);
            if (isValid === false) {
                this._undoRedoService.rollback(redoUndoId, unitId);
                return false;
            }
        }

        return true;
    }

    private _removeComposedCellStyleInCellData(cellData: ICellData, composedStyle: IStyleData) {
        if (!cellData.s || typeof cellData.s === 'string') {
            return;
        }

        const keys = Object.keys(cellData.s);

        for (const key of keys) {
            if (composedStyle[key as keyof IStyleData] !== undefined && Tools.diffValue(cellData.s[key as keyof IStyleData], composedStyle[key as keyof IStyleData])) {
                delete cellData.s[key as keyof IStyleData];
            }
        }
    }

    private _exitInput(param: IEditorBridgeServiceVisibleParam) {
        this._contextService.setContextValue(FOCUSING_EDITOR_INPUT_FORMULA, false);
        this._contextService.setContextValue(EDITOR_ACTIVATED, false);
        this._contextService.setContextValue(FOCUSING_FX_BAR_EDITOR, false);
        this._cellEditorManagerService.setState({
            show: param.visible,
        });
        // Formula range editing mirrors selections into the formula bar while the cell editor is
        // active. Clear the formula-bar editor on exit so its hidden input/caret cannot remain visible.
        const formulaBarEditor = this._editorService.getEditor(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
        formulaBarEditor?.setSelectionRanges([], false);
        formulaBarEditor?.blur();
        const editorObject = this._getEditorObject();
        editorObject?.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)?.scrollToViewportPos({
            viewportScrollX: 0,
            viewportScrollY: 0,
        });
        const editorUnitId = this._editorBridgeService.getCurrentEditorId();
        if (editorUnitId == null || !this._editorService.isSheetEditor(editorUnitId)) {
            return;
        }
        // Reset the width of the editor to the initial state after exiting the input.
        if (editorUnitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
            this._getEditorSkeleton(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)?.resetInitialWidth();
        }
        this._clearEditorHistory();
    }

    private _clearEditorHistory(): void {
        this._undoRedoService.clearUndoRedo(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
        this._undoRedoService.clearUndoRedo(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
        this._docStateChangeManagerService.clearHistory(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
        this._docStateChangeManagerService.clearHistory(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
    }

    private _moveSelection(keycode: KeyCode | undefined, currentUnitId: string, worksheetId: string, isShift = false) {
        if (keycode == null || !MOVE_SELECTION_KEYCODE_LIST.includes(keycode)) {
            this._refreshCurrentSelections(worksheetId);
            return;
        }

        let direction = Direction.LEFT;

        switch (keycode) {
            case KeyCode.ENTER:
                direction = isShift ? Direction.UP : Direction.DOWN;
                break;
            case KeyCode.TAB:
                direction = isShift ? Direction.LEFT : Direction.RIGHT;
                break;
            case KeyCode.ARROW_DOWN:
                direction = Direction.DOWN;
                break;
            case KeyCode.ARROW_UP:
                direction = Direction.UP;
                break;
            case KeyCode.ARROW_LEFT:
                direction = Direction.LEFT;
                break;
            case KeyCode.ARROW_RIGHT:
                direction = Direction.RIGHT;
                break;
        }
        const currentUnit = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_SHEET);
        if (currentUnitId && currentUnit?.getUnitId() !== currentUnitId) {
            this._univerInstanceService.setCurrentUnitForType(currentUnitId);
        }

        if (keycode === KeyCode.ENTER || keycode === KeyCode.TAB) {
            this._commandService.executeCommand(MoveSelectionEnterAndTabCommand.id, {
                keycode,
                direction,
            });
        } else {
            this._commandService.executeCommand(MoveSelectionCommand.id, {
                direction,
            });
        }
    }

    /**
     * The user's operations follow the sequence of opening the editor and then moving the cursor.
     * The logic here predicts the user's first cursor movement behavior based on this rule
     */
    private _cursorStateListener(d: DisposableCollection) {
        const editorObject = this._getEditorObject();
        if (!editorObject?.document) return;
        const { document: documentComponent } = editorObject;

        d.add(toDisposable(documentComponent.onPointerDown$.subscribeEvent(() => {
            if (this._cursorChange === CursorChange.StartEditor) {
                this._cursorChange = CursorChange.CursorChange;
            }
        })));
    }

    // TODO: @JOCS, is it necessary to move these commands MoveSelectionOperation\MoveCursorOperation to shortcut? and use multi-commands?
    private _moveInEditor(keycode: KeyCode, isShift: boolean) {
        let direction = Direction.LEFT;
        if (keycode === KeyCode.ARROW_DOWN) {
            direction = Direction.DOWN;
        } else if (keycode === KeyCode.ARROW_UP) {
            direction = Direction.UP;
        } else if (keycode === KeyCode.ARROW_RIGHT) {
            direction = Direction.RIGHT;
        }

        if (isShift) {
            this._commandService.executeCommand(MoveSelectionOperation.id, {
                direction,
            });
        } else {
            this._commandService.executeCommand(MoveCursorOperation.id, {
                direction,
            });
        }
    }

    private _getDocumentDataModel() {
        return this._univerInstanceService.getUnit<DocumentDataModel>(DOCS_NORMAL_EDITOR_UNIT_ID_KEY, UniverInstanceType.UNIVER_DOC);
    }

    private _getEditorSkeleton(editorId: string) {
        return this._renderManagerService.getRenderUnitById(editorId)?.with(DocSkeletonManagerService).getSkeleton();
    }

    private _getEditorViewModel(editorId: string) {
        return this._renderManagerService.getRenderUnitById(editorId)?.with(DocSkeletonManagerService).getViewModel();
    }

    private _getEditingUnit() {
        return this._editingUnit ? this._univerInstanceService.getUnit<Workbook>(this._editingUnit, UniverInstanceType.UNIVER_SHEET) : null;
    }

    private _emptyDocumentDataModel(documentStyle: IDocumentStyle, removeStyle: boolean) {
        const empty = (documentDataModel: DocumentDataModel, resetDocumentStyle?: boolean) => {
            const snapshot = Tools.deepClone(documentDataModel.getSnapshot());
            const documentViewModel = this._getEditorViewModel(documentDataModel.getUnitId());
            if (documentViewModel == null) {
                return;
            }

            emptyBody(snapshot.body!, removeStyle);
            if (resetDocumentStyle) {
                snapshot.documentStyle = documentStyle;
            }
            snapshot.drawings = {};
            snapshot.drawingsOrder = [];
            documentDataModel.reset(snapshot);
            documentViewModel.reset(documentDataModel);
        };

        const documentDataModel = this._getDocumentDataModel();
        documentDataModel && empty(documentDataModel, true);

        const formulaDocument = this._univerInstanceService.getUnit<DocumentDataModel>(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, UniverInstanceType.UNIVER_DOC);
        formulaDocument && empty(formulaDocument);
    }
}

export function getCellDataByInput(
    cellData: ICellData,
    snapshot: Nullable<IDocumentData>,
    lexerTreeBuilder: LexerTreeBuilder,
    localeService: LocaleService,
    functionService: IFunctionService,
    styles: Styles
) {
    if (snapshot?.body == null) {
        return null;
    }
    const { body } = snapshot;
    const previousFormula = cellData.f;
    cellData.t = undefined;

    const data = body.dataStream;
    const lastString = data.substring(data.length - 2, data.length);
    let newDataStream = lastString === DEFAULT_EMPTY_DOCUMENT_VALUE ? data.substring(0, data.length - 2) : data;

    const currentLocale = localeService.getCurrentLocale();
    newDataStream = normalizeString(newDataStream, lexerTreeBuilder, currentLocale, functionService);

    if (isCellImage(snapshot)) {
        cellData.v = '';
        cellData.f = null;
        cellData.si = null;
        cellData.p = snapshot;
        cellData.t = CellValueType.STRING;
    } else if (
        // Text format ('@' or '@@@') has the highest priority
        newDataStream !== '' && cellData.s && isTextFormat(styles?.get(cellData.s)?.n?.pattern)
    ) {
        // If the style is text format ('@'or  '@@@'), the data should be set as a string.
        cellData.v = newDataStream;
        cellData.f = null;
        cellData.si = null;
        cellData.p = null;
        cellData.t = CellValueType.STRING;

        // Text format supports rich text
        if (isRichText(body)) {
            cellData.p = snapshot;
        }

        // If the style length in textRun.ts is equal to the content length, it should be set as the cell style
        const style = getCellStyleBySnapshot(snapshot);
        if (style) {
            cellData.s = style;
        }
    } else if (isFormulaString(newDataStream)) {
        if (cellData.f === newDataStream) {
            return null;
        }

        const bracketCount = lexerTreeBuilder.checkIfAddBracket(newDataStream);
        for (let i = 0; i < bracketCount; i++) {
            newDataStream += matchToken.CLOSE_BRACKET;
        }

        cellData.f = newDataStream;
        cellData.si = null; // Disassociate from the original formula
        cellData.v = null;
        cellData.p = null;
    } else if (isForceString(newDataStream)) {
        const v = extractStringFromForceString(newDataStream);
        cellData.v = v;
        cellData.f = null;
        cellData.si = null;
        cellData.p = null;
        cellData.t = CellValueType.FORCE_STRING;
    } else if (newDataStream !== '' && isRichText(body)) {
        cellData.p = snapshot;
        cellData.v = null;
        cellData.f = null;
        cellData.si = null;
    } else {
        // An empty editor does not change an already empty cell.
        if (newDataStream === '' && cellData.v == null && cellData.p == null && cellData.f == null && cellData.si == null) {
            return null;
        }
        cellData.v = newDataStream === '' ? null : newDataStream;
        cellData.f = null;
        cellData.si = null;
        cellData.p = null;
        // If the style length in textRun.ts is equal to the content length, it should be set as the cell style
        const style = getCellStyleBySnapshot(snapshot);
        if (style) {
            cellData.s = style;
        }
    }

    // Editor input starts from a copy of the old cell, including imported metadata.
    if (cellData.f !== previousFormula && (cellData.ft !== undefined || cellData.fd !== undefined)) {
        cellData.ft = null;
        cellData.fd = null;
    }

    return cellData;
}

export function isRichText(body: IDocumentBody): boolean {
    const { textRuns = [], paragraphs = [], customRanges, customBlocks = [] } = body;

    const bodyNoLineBreak = body.dataStream.replace(/(\r\n)+$/, '');

    // Some styles are unique to rich text. When this style appears, we consider the value to be rich text.
    const richTextStyle = ['va'];

    return (
        // This is because after editing, an inexplicable second paragraph style will appear \r\n
        textRuns.filter((ts) => ts.st < bodyNoLineBreak.length).some((textRun) => {
            const hasRichTextStyle = Boolean(textRun.ts && Object.keys(textRun.ts).some((property) => {
                return richTextStyle.includes(property);
            }));
            return hasRichTextStyle || (Object.keys(textRun.ts ?? {}).length && (textRun.ed - textRun.st < bodyNoLineBreak.length));
        }) ||
        paragraphs.some((paragraph) => paragraph.bullet) ||
        paragraphs.length >= 2 ||
        Boolean(customRanges?.length) ||
        customBlocks.length > 0
    );
}

export function shouldSubmitCellEdit({
    isEmpty,
    isCellImage,
    shouldSubmitEmptyCellImageEdit,
}: {
    isEmpty?: boolean;
    isCellImage: boolean;
    shouldSubmitEmptyCellImageEdit: boolean;
}): boolean {
    if (!isEmpty || !isCellImage) {
        return true;
    }

    return shouldSubmitEmptyCellImageEdit;
}

export function getCellStyleBySnapshot(snapshot: IDocumentData): Nullable<IStyleData> {
    const { body } = snapshot;
    if (!body) return null;
    const { textRuns = [] } = body;

    let style = {};
    const bodyNoLineBreak = body.dataStream.replace('\r\n', '');
    textRuns.forEach((textRun) => {
        const { st, ed, ts } = textRun;
        if (ed - st >= bodyNoLineBreak.length) {
            style = { ...style, ...ts };
        }
    });
    if (Object.keys(style).length) {
        return style;
    }
    return null;
}

export function emptyBody(body: IDocumentBody, removeStyle = false) {
    body.dataStream = DEFAULT_EMPTY_DOCUMENT_VALUE;

    // Keep an empty collection initialized so the first formula highlight can be
    // applied without a Core TextX special case.
    if (body.textRuns?.length) {
        if (body.textRuns.length === 1 && !removeStyle) {
            body.textRuns[0].st = 0;
            body.textRuns[0].ed = 1;
        } else {
            body.textRuns = undefined;
        }
    }

    if (body.paragraphs != null) {
        body.paragraphs = [
            {
                startIndex: 0,
                paragraphId: createParagraphId(new Set()),
            },
        ];
    }

    if (body.sectionBreaks != null) {
        body.sectionBreaks = undefined;
    }

    if (body.tables != null) {
        body.tables = undefined;
    }

    if (body.customRanges != null) {
        body.customRanges = undefined;
    }

    if (body.customBlocks != null) {
        body.customBlocks = undefined;
    }
}

export function getComparableCellData(
    cellData: Nullable<ICellData>,
    styles: Styles,
    originalCell: Nullable<ICellData>
): Nullable<ICellData> {
    if (!cellData) {
        return cellData;
    }
    const normalized = { ...cellData };
    if (cellData.v != null) {
        // Compare the value that SetRangeValuesMutation will persist, including its inferred type.
        const type = getCellType(styles, cellData, originalCell ?? {});
        normalized.t = type;
        normalized.v = getCellValue(type, cellData);
    }
    if (normalized.s) {
        normalized.s = styles.get(normalized.s);
    }
    return Object.fromEntries(
        Object.entries(normalized).filter(([_, value]) => {
            if (value === undefined || value === null) {
                return false;
            }
            if (Array.isArray(value) && value.length === 0) {
                return false;
            }
            if (typeof value === 'object' && Object.keys(value).length === 0) {
                return false;
            }
            return true;
        })
    );
}