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.

13.1 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 { IDisposable, ITextRangeParam } from '@univerjs/core';
import {
    Disposable,
    DocumentDataModel,
    ICommandService,
    Inject,
    IPermissionService,
    IUniverInstanceService,
    LocaleService,
    UniverInstanceType,
} from '@univerjs/core';
import {
    canEditDocumentTargets,
    DocSelectionManagerService,
    getDocumentEntityParentPermissionObjectIds,
    getDocumentEntityPermissionObjectId,
} from '@univerjs/docs';
import { DocCanvasPopManagerService, getEditorRuntimeConfig } from '@univerjs/docs-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
import { IDialogService } from '@univerjs/ui';
import { BehaviorSubject } from 'rxjs';
import { DeleteDocHyperLinkCommand } from '../commands/commands/delete-link.command';
import { DocHyperLinkEdit } from '../views/DocHyperLinkEdit';
import { DocLinkPopup } from '../views/DocLinkPopup';

export interface ILinkInfo {
    unitId: string;
    linkId: string;
    segmentId?: string;
    segmentPage?: number;
    startIndex: number;
    endIndex: number;
}

const INFO_POPUP_HIDE_DELAY = 150;
const INFO_POPUP_REPLACEMENT_DELAY = 200;

function isSameLinkInfo(current: ILinkInfo | null, next: ILinkInfo): boolean {
    return current?.linkId === next.linkId &&
        current.unitId === next.unitId &&
        (current.segmentId ?? '') === (next.segmentId ?? '') &&
        current.segmentPage === next.segmentPage &&
        current.startIndex === next.startIndex &&
        current.endIndex === next.endIndex;
}

export class DocHyperLinkPopupService extends Disposable {
    private readonly _editingLink$ = new BehaviorSubject<ILinkInfo | null>(null);
    private readonly _showingLink$ = new BehaviorSubject<ILinkInfo | null>(null);
    readonly editingLink$ = this._editingLink$.asObservable();
    readonly showingLink$ = this._showingLink$.asObservable();

    private _editPopup: IDisposable | null = null;
    private _editPopupUnitId: string | null = null;
    private _infoPopup: IDisposable | null = null;
    private _infoPopupPinned = false;
    private _infoPopupHovered = false;
    private _infoPopupHideTimer: ReturnType<typeof setTimeout> | null = null;
    private _infoPopupReplacement: { info: ILinkInfo; timer: ReturnType<typeof setTimeout> } | null = null;
    private _infoPopupSuppressed = false;
    private _infoPopupSuppressionTimer: ReturnType<typeof setTimeout> | null = null;

    constructor(
        @Inject(DocCanvasPopManagerService) protected readonly _docCanvasPopupManagerService: DocCanvasPopManagerService,
        @Inject(DocSelectionManagerService) private readonly _textSelectionManagerService: DocSelectionManagerService,
        @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
        @IPermissionService private readonly _permissionService: IPermissionService,
        @IRenderManagerService private readonly _renderManagerService: IRenderManagerService,
        @IDialogService protected readonly _dialogService: IDialogService,
        @Inject(LocaleService) protected readonly _localeService: LocaleService,
        @ICommandService private readonly _commandService: ICommandService
    ) {
        super();

        this.disposeWithMe(() => {
            this.cancelScheduledHideInfoPopup();
            if (this._infoPopupSuppressionTimer !== null) {
                clearTimeout(this._infoPopupSuppressionTimer);
            }
            this._editingLink$.complete();
            this._showingLink$.complete();
        });

        this.disposeWithMe(this._permissionService.permissionPointUpdate$.subscribe(() => {
            const editing = this.editing;
            if (editing && !this.canEditLink(editing.unitId, editing)) {
                this.hideEditPopup();
            }
            const showing = this.showing;
            if (showing) {
                this._showingLink$.next({ ...showing });
            }
        }));
        this.disposeWithMe(this._renderManagerService.disposed$.subscribe((unitId) => {
            if (this._infoPopupReplacement?.info.unitId === unitId) {
                this._cancelScheduledInfoPopupReplacement();
            }
            if (this._editPopupUnitId === unitId) {
                this.hideEditPopup();
            }
            if (this.showing?.unitId === unitId) {
                this.hideInfoPopup();
            }
        }));
    }

    override dispose(): void {
        this.hideEditPopup();
        this.hideInfoPopup();
        super.dispose();
    }

    get editing() {
        return this._editingLink$.value;
    }

    get showing() {
        return this._showingLink$.value;
    }

    get infoPopupPinned() {
        return this._infoPopupPinned;
    }

    showEditPopup(unitId: string, linkInfo: ILinkInfo | null): IDisposable | null {
        this._cancelScheduledInfoPopupReplacement();
        const doc = this._univerInstanceService.getUnit<DocumentDataModel>(unitId, UniverInstanceType.UNIVER_DOC);
        if (doc && getEditorRuntimeConfig(doc)?.customHyperLinkUI) {
            return null;
        }
        if (!this.canEditLink(unitId, linkInfo)) {
            return null;
        }
        if (this._editPopup) {
            this._editPopup.dispose();
            this._editPopup = null;
            this._editPopupUnitId = null;
        }
        this._editingLink$.next(linkInfo);
        const textRanges = this._textSelectionManagerService.getTextRanges({ unitId, subUnitId: unitId });
        let activeRange = textRanges?.[textRanges.length - 1];

        if (linkInfo) {
            const { segmentId, segmentPage, startIndex, endIndex } = linkInfo;
            activeRange = {
                collapsed: false,
                startOffset: startIndex,
                endOffset: endIndex + 1,
                segmentId,
                segmentPage,
            };

            this._textSelectionManagerService.replaceDocRanges([{
                startOffset: startIndex,
                endOffset: endIndex + 1,
            }]);
        }

        if (activeRange) {
            this._editPopup = this._openEditSurface(activeRange, unitId);
            this._editPopupUnitId = unitId;
            return this._editPopup;
        }

        return null;
    }

    hideEditPopup() {
        this._editingLink$.next(null);
        const popup = this._editPopup;
        this._editPopup = null;
        popup?.dispose();
        this._editPopupUnitId = null;
    }

    showInfoPopup(info: ILinkInfo, options?: { pinned?: boolean }): IDisposable | null | undefined {
        const doc = this._univerInstanceService.getUnit(info.unitId, UniverInstanceType.UNIVER_DOC);
        if (!(doc instanceof DocumentDataModel) || getEditorRuntimeConfig(doc)?.customHyperLinkUI) {
            return;
        }
        this._cancelScheduledInfoPopupReplacement();
        this.cancelScheduledHideInfoPopup();
        if (this._infoPopupSuppressed) {
            return;
        }

        const { linkId, unitId, segmentId, segmentPage, startIndex, endIndex } = info;
        const isSameLink = isSameLinkInfo(this.showing, info);
        if (isSameLink) {
            if (options?.pinned) {
                this._infoPopupPinned = true;
            }
            return;
        }

        if (this._infoPopup) {
            this._infoPopup.dispose();
            this._infoPopup = null;
        }
        this._infoPopupPinned = options?.pinned ?? false;
        this._infoPopupHovered = false;
        this._showingLink$.next({ unitId, linkId, segmentId, segmentPage, startIndex, endIndex });

        this._infoPopup = this._openInfoSurface(info);
        return this._infoPopup;
    }

    protected _openEditSurface(activeRange: ITextRangeParam, unitId: string): IDisposable {
        return this._docCanvasPopupManagerService.attachPopupToRange(activeRange, {
            componentKey: DocHyperLinkEdit.componentKey,
            direction: 'bottom',
            offset: [0, 10],
        }, unitId);
    }

    protected _openInfoSurface(info: ILinkInfo, componentKey = DocLinkPopup.componentKey): IDisposable {
        const { unitId, linkId, segmentId, segmentPage, startIndex, endIndex } = info;
        return this._docCanvasPopupManagerService.attachPopupToRange(
            {
                collapsed: false,
                startOffset: startIndex,
                endOffset: endIndex + 1,
                segmentId,
                segmentPage,
            },
            {
                componentKey,
                extraProps: {
                    onEdit: () => {
                        this.hideInfoPopup();
                        this.showEditPopup(unitId, info);
                    },
                    onDelete: async () => {
                        if (await this._commandService.executeCommand(DeleteDocHyperLinkCommand.id, { unitId, linkId, segmentId })) {
                            this.hideInfoPopup();
                        }
                    },
                },
                direction: 'top-center',
                multipleDirection: 'top',
                offset: [0, 10],
                onClickOutside: () => {
                    this.hideInfoPopup();
                },
            },
            unitId
        );
    }

    showInfoPopupFromHover(info: ILinkInfo): void {
        this.cancelScheduledHideInfoPopup();
        if (this._infoPopupPinned || this._infoPopupHovered || this._infoPopupSuppressed) {
            return;
        }
        if (!this.showing || isSameLinkInfo(this.showing, info)) {
            this.showInfoPopup(info);
            return;
        }
        if (isSameLinkInfo(this._infoPopupReplacement?.info ?? null, info)) {
            return;
        }
        this._cancelScheduledInfoPopupReplacement();
        const pendingInfo = { ...info };
        this._infoPopupReplacement = {
            info: pendingInfo,
            timer: setTimeout(() => {
                this._infoPopupReplacement = null;
                this.showInfoPopup(pendingInfo);
            }, INFO_POPUP_REPLACEMENT_DELAY),
        };
    }

    setInfoPopupHovered(hovered: boolean): void {
        this._infoPopupHovered = hovered && this.showing !== null;
        if (this._infoPopupHovered) {
            this._cancelScheduledInfoPopupReplacement();
            this.cancelScheduledHideInfoPopup();
        }
    }

    private _cancelScheduledInfoPopupReplacement(): void {
        if (this._infoPopupReplacement) {
            clearTimeout(this._infoPopupReplacement.timer);
            this._infoPopupReplacement = null;
        }
    }

    hideInfoPopup() {
        this._cancelScheduledInfoPopupReplacement();
        this.cancelScheduledHideInfoPopup();
        this._infoPopupPinned = false;
        this._infoPopupHovered = false;
        this._showingLink$.next(null);
        const popup = this._infoPopup;
        this._infoPopup = null;
        popup?.dispose();
    }

    scheduleHideInfoPopup() {
        this._cancelScheduledInfoPopupReplacement();
        if (this._infoPopupPinned || this._infoPopupHovered || !this.showing) {
            return;
        }

        this.cancelScheduledHideInfoPopup();
        this._infoPopupHideTimer = setTimeout(() => {
            this._infoPopupHideTimer = null;
            if (!this._infoPopupPinned) {
                this.hideInfoPopup();
            }
        }, INFO_POPUP_HIDE_DELAY);
    }

    cancelScheduledHideInfoPopup() {
        if (this._infoPopupHideTimer !== null) {
            clearTimeout(this._infoPopupHideTimer);
            this._infoPopupHideTimer = null;
        }
    }

    hideInfoPopupOnPointerDown() {
        this._infoPopupSuppressed = true;
        if (this._infoPopupSuppressionTimer !== null) {
            clearTimeout(this._infoPopupSuppressionTimer);
        }

        this.hideInfoPopup();
        this._infoPopupSuppressionTimer = setTimeout(() => {
            this._infoPopupSuppressed = false;
            this._infoPopupSuppressionTimer = null;
        }, 0);
    }

    canEditLink(unitId: string, linkInfo: ILinkInfo | null): boolean {
        const document = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
        if (!(document instanceof DocumentDataModel)) {
            return false;
        }
        if (!linkInfo) {
            return canEditDocumentTargets(this._permissionService, unitId, []);
        }
        const segmentId = linkInfo.segmentId ?? '';
        return canEditDocumentTargets(this._permissionService, unitId, [
            ...getDocumentEntityParentPermissionObjectIds(document, segmentId, 'custom-range', linkInfo.linkId),
            getDocumentEntityPermissionObjectId(segmentId, 'custom-range', linkInfo.linkId),
        ]);
    }
}