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.

15.7 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, IDisposable, IDocumentBody, IDocumentData, Nullable } from '@univerjs/core';
import type { DocBackground, ISuccinctDocRangeParam, Scene } from '@univerjs/engine-render';
import type { Observable } from 'rxjs';
import type { IEditorCanvasStyle, IEditorConfigParams } from './editor';
import {
    createIdentifier,
    createParagraphId,
    DEFAULT_EMPTY_DOCUMENT_VALUE,
    Disposable,
    EDITOR_ACTIVATED,
    FOCUSING_COMMENT_EDITOR,
    FOCUSING_EDITOR_STANDALONE,
    HorizontalAlign,
    ICommandService,
    IContextService,
    Inject,
    Injector,
    isCommentEditorID,
    isInternalEditorID,
    IUndoRedoService,
    IUniverInstanceService,
    toDisposable,
    UniverInstanceType,
    VerticalAlign,
} from '@univerjs/core';
import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
import { fromEvent, Subject } from 'rxjs';
import { DOCS_VIEW_KEY } from '../../basics/docs-view-key';
import { resolveDocRenderBackground } from '../doc-render-background';
import { Editor } from './editor';
import { getEditorRuntimeConfig, registerEditorRuntimeConfig } from './editor-runtime-config';

export interface IEditorRenderConfig {
    canvasStyle: IEditorCanvasStyle;
    preserveHostFocus?: boolean;
    scrollBar?: boolean;
    backScrollOffset?: number;
    disableBackScroll?: boolean;
}

/**
 * Not these elements will be considered as editor blur.
 */
const editorFocusInElements = [
    'editor',
    'render-canvas',
    // 'univer-range-selector',
    // 'univer-range-selector-editor',
    // 'univer-text-editor-container-placeholder',
];

export interface IEditorSetValueParam {
    editorUnitId: string;
    body: IDocumentBody;
}

export interface IEditorInputFormulaParam {
    editorUnitId: string;
    formulaString: string;
}

export interface IEditorService {
    getEditor(id?: string): Readonly<Nullable<Editor>>;

    register(config: IEditorConfigParams, container: HTMLDivElement): IDisposable;

    getAllEditor(): Map<string, Editor>;

    isEditor(editorUnitId: string): boolean;

    getEditorRenderConfig(editorUnitId: string): Nullable<IEditorRenderConfig>;

    isSheetEditor(editorUnitId: string): boolean;

    blur$: Observable<unknown>;
    blur(force?: boolean): void;

    focus$: Observable<ISuccinctDocRangeParam>;
    focus(editorUnitId: string): void;

    getFocusId(): Nullable<string>;
    getFocusEditor(): Readonly<Nullable<Editor>>;
}

export class EditorService extends Disposable implements IEditorService, IDisposable {
    private _editors = new Map<string, Editor>();

    private _editorRenderConfigs = new Map<string, IEditorRenderConfig>();

    private _focusEditorUnitId: Nullable<string>;

    private _preservedHostUnitId: Nullable<string>;

    private readonly _blur$ = new Subject();
    readonly blur$ = this._blur$.asObservable();

    private readonly _focus$ = new Subject<ISuccinctDocRangeParam>();
    readonly focus$ = this._focus$.asObservable();

    constructor(
        @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
        @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
        @Inject(DocSelectionManagerService) private readonly _docSelectionManagerService: DocSelectionManagerService,
        @IContextService private readonly _contextService: IContextService,
        @ICommandService private readonly _commandService: ICommandService,
        @IUndoRedoService private readonly _undoRedoService: IUndoRedoService,
        @Inject(Injector) private readonly _injector: Injector
    ) {
        super();

        this._initUniverFocusListener();
    }

    // REFACTOR: @Gggpound The specific business processing should not be placed here,
    // I moved from the layout service. https://github.com/dream-num/univer-pro/issues/1708
    private _initUniverFocusListener() {
        this.disposeWithMe(
            fromEvent(window, 'focusin').subscribe((event) => {
                const target = event.target as HTMLElement;
                this._blurSheetEditor(target);
            })
        );
    }

    private _blurSheetEditor(target: HTMLElement) {
        if (editorFocusInElements.some((item) => target.dataset.uComp === item)) {
            return;
        }

        const focusEditor = this.getFocusEditor();
        if (focusEditor && focusEditor.isSheetEditor() !== true) {
            this.blur();
        }
    }

    private _setFocusId(id: Nullable<string>) {
        this._focusEditorUnitId = id;
    }

    getFocusId() {
        return this._focusEditorUnitId;
    }

    getFocusEditor() {
        if (this._focusEditorUnitId) {
            return this.getEditor(this._focusEditorUnitId);
        }
    }

    isEditor(editorUnitId: string) {
        return this._editorRenderConfigs.has(editorUnitId) || this._editors.has(editorUnitId);
    }

    isSheetEditor(editorUnitId: string) {
        const editor = this._editors.get(editorUnitId);
        return !!(editor && editor.isSheetEditor());
    }

    blur(force?: boolean) {
        const focusingEditor = this.getFocusEditor();
        const preservedHostUnitId = this._preservedHostUnitId;
        if (force) {
            focusingEditor?.setSelectionRanges([]);
        }
        focusingEditor?.blur();

        this._contextService.setContextValue(EDITOR_ACTIVATED, false);
        this._contextService.setContextValue(FOCUSING_EDITOR_STANDALONE, false);
        this._contextService.setContextValue(FOCUSING_COMMENT_EDITOR, false);
        this._setFocusId(null);
        this._preservedHostUnitId = null;
        if (
            preservedHostUnitId &&
            this._univerInstanceService.getUnit(preservedHostUnitId, UniverInstanceType.UNIVER_DOC)
        ) {
            this._univerInstanceService.setCurrentUnitForType(preservedHostUnitId);
        }
        this._blur$.next(null);
    }

    focus(editorUnitId: string) {
        if (editorUnitId === this._focusEditorUnitId) {
            return;
        }
        if (this._focusEditorUnitId) {
            this.blur();
        }
        if (editorUnitId == null) {
            return;
        }

        const editor = this.getEditor(editorUnitId);
        if (editor == null) {
            return;
        }

        const currentDoc = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(
            UniverInstanceType.UNIVER_DOC
        );
        this._preservedHostUnitId = this._editorRenderConfigs.get(editorUnitId)?.preserveHostFocus &&
            currentDoc?.getUnitId() !== editorUnitId
            ? currentDoc?.getUnitId()
            : null;
        this._univerInstanceService.setCurrentUnitForType(editorUnitId);
        const dataStream = editor.getDocumentData().body?.dataStream ?? '';
        const valueCount = dataStream.replace(/\r?\n/g, '').length;

        this._contextService.setContextValue(EDITOR_ACTIVATED, true);

        if (!isInternalEditorID(editorUnitId)) {
            this._contextService.setContextValue(FOCUSING_EDITOR_STANDALONE, true);
        }

        if (isCommentEditorID(editorUnitId)) {
            this._contextService.setContextValue(FOCUSING_COMMENT_EDITOR, true);
        }

        editor.focus();
        this._setFocusId(editorUnitId);

        this._focus$.next({
            startOffset: valueCount,
            endOffset: valueCount,
        });
    }

    override dispose(): void {
        if (this._disposed) {
            return;
        }

        for (const editorUnitId of this._editors.keys()) {
            this._unRegister(editorUnitId);
        }
        this._editorRenderConfigs.clear();
        this._blur$.complete();
        this._focus$.complete();
        super.dispose();
    }

    getEditor(id: string = this._getCurrentEditorUnitId()): Readonly<Nullable<Editor>> {
        return this._editors.get(id);
    }

    getAllEditor() {
        return this._editors;
    }

    getEditorRenderConfig(editorUnitId: string): Nullable<IEditorRenderConfig> {
        const editor = this._editors.get(editorUnitId);
        return this._editorRenderConfigs.get(editorUnitId) ?? editor?.getRenderConfig() ?? null;
    }

    register(config: IEditorConfigParams, container: HTMLDivElement): IDisposable {
        this.ensureNotDisposed();
        const { initialSnapshot, canvasStyle = {} } = config;
        const editorUnitId = initialSnapshot.id;
        const documentDataModel = this._univerInstanceService.getUnit<DocumentDataModel>(editorUnitId, UniverInstanceType.UNIVER_DOC);
        const previousLayout = documentDataModel && getEditorRuntimeConfig(documentDataModel)?.layout;
        this._editors.get(editorUnitId)?.dispose(false);
        this._editors.delete(editorUnitId);
        const renderConfig: IEditorRenderConfig = {
            canvasStyle,
            scrollBar: config.scrollBar,
            ...(config.backScrollOffset === undefined ? {} : { backScrollOffset: config.backScrollOffset }),
            ...(config.disableBackScroll === undefined ? {} : { disableBackScroll: config.disableBackScroll }),
            ...(config.preserveHostFocus === undefined ? {} : { preserveHostFocus: config.preserveHostFocus }),
        };
        this._editorRenderConfigs.set(editorUnitId, renderConfig);

        if (documentDataModel == null) {
            this._univerInstanceService.createUnit<IDocumentData, DocumentDataModel>(
                UniverInstanceType.UNIVER_DOC,
                initialSnapshot || this._getBlank(editorUnitId),
                { makeCurrent: false }
            );
        }

        const model = this._univerInstanceService.getUnit<DocumentDataModel>(editorUnitId, UniverInstanceType.UNIVER_DOC)!;
        const runtime = config.renderConfig && registerEditorRuntimeConfig(model, config.renderConfig);

        let render = this._renderManagerService.getRenderUnitById(editorUnitId);
        try {
            if (render != null && (previousLayout || config.renderConfig?.layout)) {
                render.with(DocSkeletonManagerService).getViewModel()?.reset(model);
            }
            if (render == null) {
                render = this._renderManagerService.createRender(editorUnitId);
            }

            if (render) {
                render.engine.mount(container, !config.cancelDefaultResizeListener);

                const editor = new Editor(
                    { ...config, render, editorDom: container, canvasStyle },
                    this._univerInstanceService,
                    this._docSelectionManagerService,
                    this._commandService,
                    this._undoRedoService,
                    this._injector
                );

                if (runtime) {
                    editor.disposeWithMe(runtime);
                }
                this._editors.set(editorUnitId, editor);

                const resolvedEditorBackground = resolveDocRenderBackground({
                    canvasColorService: render.engine.canvasColorService,
                    editorBackgroundColor: canvasStyle.backgroundColor,
                    isEditor: true,
                });
                render.engine.getCanvas().getCanvasEle().style.backgroundColor = resolvedEditorBackground.canvasElementBackgroundColor;
                const docBackground = render.components.get(DOCS_VIEW_KEY.BACKGROUND) as DocBackground | undefined;
                docBackground?.setFillColors(
                    resolvedEditorBackground.docBackgroundFillColor,
                    resolvedEditorBackground.docBackgroundFillColor,
                    resolvedEditorBackground.docBackgroundFillColor,
                    resolvedEditorBackground.docBackgroundFillColor
                );

                // Delete scroll bar
                if (!config.scrollBar) {
                    const viewport = (render.mainComponent?.getScene() as Scene)?.getViewports()?.[0];
                    viewport?.getScrollBar()?.dispose();
                    viewport?.updateScrollVal({
                        scrollX: 0,
                        scrollY: 0,
                        viewportScrollX: 0,
                        viewportScrollY: 0,
                    });
                }
            }
        } catch (error) {
            runtime?.dispose();
            this._editors.get(editorUnitId)?.dispose(false);
            this._editors.delete(editorUnitId);
            this._editorRenderConfigs.delete(editorUnitId);
            throw error;
        }
        return toDisposable(() => {
            runtime?.dispose();
            // An older container may unmount after a replacement has registered the same ID.
            if (this._editorRenderConfigs.get(editorUnitId) === renderConfig) {
                this._unRegister(editorUnitId);
            }
        });
    }

    private _unRegister(editorUnitId: string) {
        const editor = this._editors.get(editorUnitId);
        if (editor == null) {
            this._editorRenderConfigs.delete(editorUnitId);
            return;
        }

        if (this._focusEditorUnitId === editorUnitId) {
            this.blur(true);
        }

        const preserveHostFocus = this._editorRenderConfigs.get(editorUnitId)?.preserveHostFocus === true;
        const currentDoc = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);
        const focusedHost = preserveHostFocus ? this._univerInstanceService.getFocusedUnit() : null;
        const focusedHostId = focusedHost?.getUnitId();
        const restoreHostUnitId = currentDoc?.getUnitId() === editorUnitId
            && focusedHostId != null
            && focusedHostId !== editorUnitId
            && this._univerInstanceService.getUnitType(focusedHostId) === UniverInstanceType.UNIVER_DOC
            ? focusedHostId
            : null;
        if (this._focusEditorUnitId === editorUnitId) {
            this.blur();
        }

        this._renderManagerService.removeRender(editorUnitId);
        editor.dispose();
        this._editors.delete(editorUnitId);
        this._editorRenderConfigs.delete(editorUnitId);
        this._univerInstanceService.disposeUnit(editorUnitId);
        if (restoreHostUnitId != null) {
            this._univerInstanceService.setCurrentUnitForType(restoreHostUnitId);
        }
    }

    private _getCurrentEditorUnitId() {
        const current = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC)!;
        return current.getUnitId();
    }

    private _getBlank(id: string) {
        return {
            id,
            body: {
                dataStream: `${DEFAULT_EMPTY_DOCUMENT_VALUE}`,
                textRuns: [],
                paragraphs: [
                    {
                        startIndex: 0,
                        paragraphId: createParagraphId(new Set()),
                    },
                ],
            },
            documentStyle: {
                renderConfig: {
                    verticalAlign: VerticalAlign.TOP,
                    horizontalAlign: HorizontalAlign.LEFT,
                },
                marginLeft: 3,
                marginTop: 0,
                marginRight: 3,
            },
        } as IDocumentData;
    }
}

export const IEditorService = createIdentifier<IEditorService>('univer.editor.service');