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.

18.8 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, ICommandInfo, IDocumentBody, IDocumentStyle, IDrawings, IParagraph, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type { DocumentViewModel } from '@univerjs/engine-render';
import type { IMoveRangeMutationParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';
import {
    BooleanNumber,
    createParagraphId,
    Disposable,
    DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY,
    DOCS_NORMAL_EDITOR_UNIT_ID_KEY,
    DocumentFlavor,
    FOCUSING_FX_BAR_EDITOR,
    HorizontalAlign,
    ICommandService,
    IContextService,
    Inject,
    IUniverInstanceService,
    ThemeService,
    Tools,
    UniverInstanceType,
    VerticalAlign,
    WrapStrategy,
} from '@univerjs/core';
import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';
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';

const formulaEditorStyle: IDocumentStyle = {
    pageSize: {
        width: Number.POSITIVE_INFINITY,
        height: Number.POSITIVE_INFINITY,
    },
    documentFlavor: DocumentFlavor.UNSPECIFIED,
    marginTop: 5,
    marginBottom: 5,
    marginRight: 0,
    marginLeft: 0,
    paragraphLineGapDefault: 0,
    renderConfig: {
        horizontalAlign: HorizontalAlign.UNSPECIFIED,
        verticalAlign: VerticalAlign.TOP,
        centerAngle: 0,
        vertexAngle: 0,
        wrapStrategy: WrapStrategy.WRAP,
        isRenderStyle: BooleanNumber.FALSE,
    },
};

/**
 * 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
 */
export class EditorDataSyncController extends Disposable {
    constructor(
        @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
        @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
        @IEditorBridgeService private readonly _editorBridgeService: IEditorBridgeService,
        @ICommandService private readonly _commandService: ICommandService,
        @Inject(RangeProtectionRuleModel) private readonly _rangeProtectionRuleModel: RangeProtectionRuleModel,
        @Inject(WorksheetProtectionRuleModel) private readonly _worksheetProtectionRuleModel: WorksheetProtectionRuleModel,
        @Inject(FormulaEditorController) private readonly _formulaEditorController: FormulaEditorController,
        @IFormulaEditorManagerService private readonly _formulaEditorManagerService: IFormulaEditorManagerService,
        @IContextService private readonly _contextService: IContextService,
        @Inject(ThemeService) private readonly _themeService: ThemeService
    ) {
        super();

        this._initialize();
    }

    private _initialize() {
        this._syncFormulaEditorContent();
        this._commandExecutedListener();
        this._syncFormulaRefRenderStyleOnFocusChange();
        this._syncFormulaBarTextColorOnThemeChange();
    }

    private _getEditorViewModel(unitId: string): Nullable<DocumentViewModel> {
        return this._renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService).getViewModel();
    }

    // Sync cell content to formula editor bar when sheet selection changed.
    private _syncFormulaEditorContent() {
        this.disposeWithMe(this._editorBridgeService.currentEditCellState$.subscribe((editCellState) => {
            if (
                editCellState == null
                || this._editorBridgeService.isForceKeepVisible()
                // If permissions are not initialized, data synchronization will not be performed.
                || !this._rangeProtectionRuleModel.getRangeRuleInitState()
                || !this._worksheetProtectionRuleModel.getSheetRuleInitState()
            ) {
                return;
            }

            this._editorSyncHandler(editCellState);
        }));
    }

    // Sync cell content to formula editor bar when sheet selection changed or visible changed.
    private _editorSyncHandler(param: ICellEditorState) {
        let body = Tools.deepClone(param.documentLayoutObject.documentModel?.getBody());
        const drawings = Tools.deepClone(param.documentLayoutObject.documentModel?.drawings);
        const drawingsOrder = Tools.deepClone(param.documentLayoutObject.documentModel?.getDrawingsOrder());
        const { visible } = this._editorBridgeService.isVisible();

        if (
            !body ||
            (param.isInArrayFormulaRange === true && visible)
        ) {
            body = {
                dataStream: '\r\n',
                paragraphs: [
                    {
                        startIndex: 0,
                        paragraphId: createParagraphId(new Set()),
                    },
                ],
                textRuns: [],
            };
        }

        this._syncContentAndRender(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY, body, drawings, drawingsOrder);
    }

    private _commandExecutedListener() {
        const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];

        this.disposeWithMe(
            this._commandService.onCommandExecuted((command: ICommandInfo) => {
                if (command.id === RichTextEditingMutation.id) {
                    const params = command.params as IRichTextEditingMutationParams;
                    const { unitId, trigger, isSync } = params;
                    if (isSync || trigger === ReplaceSnapshotCommand.id) {
                        return;
                    }

                    if (INCLUDE_LIST.includes(unitId)) {
                        // sync cell content to formula editor bar when edit cell editor and vice verse.
                        const editorDocDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);

                        const syncId =
                            unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY
                                ? DOCS_NORMAL_EDITOR_UNIT_ID_KEY
                                : DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;

                        this._checkAndSetRenderStyleConfig(editorDocDataModel!);
                        this._syncActionsAndRender(syncId, params);
                    }
                }
            })
        );

        // Update formula bar content when you call SetRangeValuesMutation and MoveRangeMutation.
        const needUpdateFormulaEditorContentCommandList = [SetRangeValuesMutation.id, MoveRangeMutation.id];
        this.disposeWithMe(
            this._commandService.onCommandExecuted((command: ICommandInfo) => {
                if (!needUpdateFormulaEditorContentCommandList.includes(command.id)) {
                    return;
                }

                const editCellState = this._editorBridgeService.getEditLocation();

                if (editCellState == null || !this._shouldRefreshCurrentEditCell(command, editCellState)) {
                    return;
                }

                /**
                 * 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);
                    }

                    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, editCell: ICellEditorState): boolean {
        const { row, column } = editCell;

        if (command.id === SetRangeValuesMutation.id && command.params) {
            const params = command.params as ISetRangeValuesMutationParams;
            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._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,
        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,
        parmas: IRichTextEditingMutationParams
    ) {
        const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];
        const currentRender = this._renderManagerService.getRenderUnitById(unitId);
        if (currentRender == null) {
            return;
        }

        const skeleton = currentRender.with(DocSkeletonManagerService).getSkeleton();
        const docDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
        const docViewModel = this._getEditorViewModel(unitId);

        if (docDataModel == null || docViewModel == null) {
            return;
        }

        this._commandService.syncExecuteCommand(RichTextEditingMutation.id, {
            ...parmas,
            textRanges: null,
            isSync: true,
            unitId,
            syncer: parmas.unitId,
        });

        this._checkAndSetRenderStyleConfig(docDataModel);
        docViewModel.reset(docDataModel);

        skeleton.calculate();

        if (INCLUDE_LIST.includes(unitId)) {
            currentRender.mainComponent?.makeDirty();
        }
    }

    private _syncContentAndRender(
        unitId: string,
        body: IDocumentBody,
        drawings: Nullable<IDrawings>,
        drawingsOrder: Nullable<string[]>
    ) {
        if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
            if (body.paragraphs) {
                body.paragraphs = this._clearParagraph(body.paragraphs);
            }
        }
        const INCLUDE_LIST = [DOCS_NORMAL_EDITOR_UNIT_ID_KEY, DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY];

        const skeleton = this._renderManagerService.getRenderUnitById(unitId)?.with(DocSkeletonManagerService).getSkeleton();
        const docDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
        const docViewModel = this._getEditorViewModel(unitId);

        if (docDataModel == null || docViewModel == null || skeleton == null) {
            return;
        }

        docDataModel.reset({
            ...docDataModel.getSnapshot(),
            body,
            drawings: drawings ?? {},
            drawingsOrder: drawingsOrder ?? [],
        });

        this._checkAndSetRenderStyleConfig(docDataModel);
        docViewModel.reset(docDataModel);
        const currentRender = this._renderManagerService.getRenderUnitById(unitId);
        if (currentRender == null) {
            return;
        }

        skeleton.calculate();

        if (INCLUDE_LIST.includes(unitId)) {
            currentRender.mainComponent?.makeDirty();
        }

        if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
            this._formulaEditorController.autoScroll();
        }
    }

    private _syncFormulaRefRenderStyleOnFocusChange() {
        this.disposeWithMe(this._contextService.subscribeContextValue$(FOCUSING_FX_BAR_EDITOR).subscribe(() => {
            this._refreshRenderStyleConfig(DOCS_NORMAL_EDITOR_UNIT_ID_KEY);
            this._refreshRenderStyleConfig(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
        }));
    }

    private _syncFormulaBarTextColorOnThemeChange() {
        this.disposeWithMe(this._themeService.currentTheme$.pipe(skip(1)).subscribe(() => {
            this._refreshRenderStyleConfig(DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY);
        }));
    }

    private _refreshRenderStyleConfig(unitId: string) {
        const currentRender = this._renderManagerService.getRenderUnitById(unitId);
        const skeleton = currentRender?.with(DocSkeletonManagerService).getSkeleton();
        const docDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
        const docViewModel = this._getEditorViewModel(unitId);

        if (currentRender == null || skeleton == null || docDataModel == null || docViewModel == null) {
            return;
        }

        this._checkAndSetRenderStyleConfig(docDataModel);
        docViewModel.reset(docDataModel);
        skeleton.calculate();
        currentRender.mainComponent?.makeDirty();

        if (unitId === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY) {
            this._formulaEditorController.autoScroll();
        }
    }

    private _checkAndSetRenderStyleConfig(documentDataModel: DocumentDataModel) {
        const snapshot = documentDataModel.getSnapshot();

        if (snapshot.id !== DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY && snapshot.id !== DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
            return;
        }

        const isFormulaBar = snapshot.id === DOCS_FORMULA_BAR_EDITOR_UNIT_ID_KEY;
        const previousPageWidth = snapshot.documentStyle?.pageSize?.width;
        if (isFormulaBar) {
            snapshot.documentStyle = {
                ...formulaEditorStyle,
                pageSize: { ...formulaEditorStyle.pageSize },
                renderConfig: { ...formulaEditorStyle.renderConfig },
                textStyle: {
                    cl: {
                        rgb: this._getFormulaBarTextColor(),
                    },
                },
            };
        } else {
            snapshot.documentStyle ??= {};
        }
        let renderConfig = snapshot.documentStyle.renderConfig;

        if (renderConfig == null) {
            renderConfig = {};
            snapshot.documentStyle.renderConfig = renderConfig;
        }
        const position = isFormulaBar ? this._formulaEditorManagerService.getPosition() : null;
        if (isFormulaBar && position) {
            // A non-positive width means the formula bar is not laid out, so keep the last valid width.
            const width = position.width > 0 ? position.width : previousPageWidth;
            if (width != null && width > 0) {
                snapshot.documentStyle.pageSize = {
                    width,
                    height: Infinity,
                };
            }
        }

        const isFormula = (snapshot.body?.dataStream ?? '').startsWith('=');
        if (!isFormula) {
            renderConfig.isRenderStyle = this._getSourceStyleRenderValue(isFormulaBar);
            return;
        }

        const isFocusFxBar = this._contextService.getContextValue(FOCUSING_FX_BAR_EDITOR);
        renderConfig.isRenderStyle = isFormulaBar === isFocusFxBar ? BooleanNumber.TRUE : BooleanNumber.FALSE;
    }

    private _getFormulaBarTextColor(): string {
        const isInheritedFormula = this._editorBridgeService.getEditLocation()?.isInArrayFormulaRange === true
            && !this._editorBridgeService.isVisible().visible;
        return this._themeService.getColorFromTheme(isInheritedFormula ? 'gray.300' : 'gray.900');
    }

    protected _getSourceStyleRenderValue(isFormulaBar: boolean): BooleanNumber {
        return isFormulaBar ? BooleanNumber.FALSE : BooleanNumber.TRUE;
    }

    private _clearParagraph(paragraphs: IParagraph[]) {
        const newParagraphs = Tools.deepClone(paragraphs);
        for (const paragraph of newParagraphs) {
            if (paragraph.paragraphStyle) {
                paragraph.paragraphStyle.horizontalAlign = HorizontalAlign.UNSPECIFIED;
            }
        }

        return newParagraphs;
    }
}