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.

52.3 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 { DependencyIdentifier, DocumentDataModel, ICellCustomRender, IDisposable, Injector, Nullable } from '@univerjs/core';
import type { IRichTextEditingMutationParams } from '@univerjs/docs';
import type {
    IRender,
    RenderComponentType,
    SheetComponent,
    SheetExtension,
} from '@univerjs/engine-render';
import type { CommandListenerSkeletonChange } from '@univerjs/sheets';
import type { IEditorBridgeServiceVisibleParam, ISetZoomRatioCommandParams, ISheetPasteByShortKeyParams, IViewportScrollState } from '@univerjs/sheets-ui';
import type { FRange } from '@univerjs/sheets/facade';
import type { Observable } from 'rxjs';
import { CanceledError, DisposableCollection, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, ICommandService, ILogService, InterceptorEffectEnum, IPermissionService, IUniverInstanceService, LifecycleService, LifecycleStages, RichTextValue, toDisposable, UniverInstanceType } from '@univerjs/core';
import { FUniver } from '@univerjs/core/facade';
import { RichTextEditingMutation } from '@univerjs/docs';
import { IRenderManagerService } from '@univerjs/engine-render';
import { COMMAND_LISTENER_SKELETON_CHANGE, getSkeletonChangedEffectedRange, INTERCEPTOR_POINT, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
import {
    DragManagerService,
    HoverManagerService,
    IEditorBridgeService,
    ISheetClipboardService,
    SetCellEditVisibleOperation,
    SetZoomRatioCommand,
    SHEET_VIEW_KEY,
    SheetPasteShortKeyCommand,
    SheetPermissionRenderManagerService,
    SheetScrollManagerService,
} from '@univerjs/sheets-ui';
import { CopyCommand, CutCommand, HTML_CLIPBOARD_MIME_TYPE, IClipboardInterfaceService, KeyCode, PasteCommand, PLAIN_TEXT_CLIPBOARD_MIME_TYPE, supportClipboardAPI } from '@univerjs/ui';
import { combineLatest, filter, of, take } from 'rxjs';
import type {
    IBeforeClipboardChangeEventParams,
    IBeforeClipboardPasteEventParams,
    IBeforeSheetEditEndEventParams,
    IBeforeSheetEditStartEventParams,
    ICellEventParams,
    IClipboardChangedEventParams,
    IClipboardPastedEventParams,
    IDragEventParams,
    IScrollEventParams,
    ISelectionEventParams,
    ISheetColumnHeaderEventParams,
    ISheetEditChangingEventParams,
    ISheetEditEndedEventParams,
    ISheetEditStartedEventParams,
    ISheetRowHeaderEventParams,
    ISheetSkeletonChangedEventParams,
    ISheetZoomEventParams,
} from './f-event';

/**
 * @ignore
 */
export interface IFUniverSheetsUIMixin {
    /**
     * Register sheet row header render extensions.
     * @param {string} unitId The unit id of the spreadsheet.
     * @param {SheetExtension[]} extensions The extensions to register.
     * @returns {IDisposable} The disposable instance.
     */
    registerSheetRowHeaderExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable;
    /**
     * Register sheet column header render extensions.
     * @param {string} unitId The unit id of the spreadsheet.
     * @param {SheetExtension[]} extensions The extensions to register.
     * @returns {IDisposable} The disposable instance.
     */
    registerSheetColumnHeaderExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable;
    /**
     * Register sheet main render extensions.
     * @param {string} unitId The unit id of the spreadsheet.
     * @param {SheetExtension[]} extensions The extensions to register.
     * @returns {IDisposable} The disposable instance.
     */
    registerSheetMainExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable;

    /**
     * Register cell custom render.
     * @param {Nullable<ICellCustomRender[]>} customRender Custom render function.
     * @param {InterceptorEffectEnum} [effect] The effect of the interceptor, style or value.
     * @param {number} [priority] The priority of the interceptor.
     */
    registerCellCustomRender(customRender: Nullable<ICellCustomRender[]>, effect?: InterceptorEffectEnum, priority?: number): IDisposable;

    /**
     * Paste clipboard data or custom data into the active sheet at the current selection position.
     * @param {string} [htmlContent] - The HTML content from the clipboard or custom data.
     * @param {string} [textContent] - The plain text content from the clipboard or custom data.
     * @param {File[]} [files] - The files from the clipboard or custom data.
     * @return {Promise<boolean>} A promise that resolves to true if the paste operation was successful, otherwise false.
     * @example
     * ```typescript
     * // Listen for the paste event and call the pasteIntoSheet method
     * document.addEventListener('paste', async (event) => {
     *   const htmlContent = event.clipboardData.getData('text/html');
     *   const textContent = event.clipboardData.getData('text/plain');
     *   const files = Array.from(event.clipboardData.items)
     *     .map((item) => item.kind === 'file' ? item.getAsFile() : undefined)
     *     .filter(Boolean);
     *   await univerAPI.pasteIntoSheet(htmlContent, textContent, files);
     * });
     *
     * // Or paste custom data
     * univerAPI.pasteIntoSheet('<b>Bold Text</b>', 'Bold Text');
     * ```
     */
    pasteIntoSheet(htmlContent?: string, textContent?: string, files?: File[]): Promise<boolean>;

    /**
     * Set the global strategy for showing the protected range shadow.
     * This will apply to all workbooks in the current Univer instance.
     * @param {('always' | 'non-editable' | 'non-viewable' | 'none')} strategy - The shadow strategy to apply
     * - 'always': Show shadow for all protected ranges
     * - 'non-editable': Only show shadow for ranges that cannot be edited
     * - 'non-viewable': Only show shadow for ranges that cannot be viewed
     * - 'none': Never show shadow for protected ranges
     * @example
     * ```typescript
     * // Always show shadows (default)
     * univerAPI.setProtectedRangeShadowStrategy('always');
     *
     * // Only show shadows for non-editable ranges
     * univerAPI.setProtectedRangeShadowStrategy('non-editable');
     *
     * // Only show shadows for non-viewable ranges
     * univerAPI.setProtectedRangeShadowStrategy('non-viewable');
     *
     * // Never show shadows
     * univerAPI.setProtectedRangeShadowStrategy('none');
     * ```
     */
    setProtectedRangeShadowStrategy(strategy: 'always' | 'non-editable' | 'non-viewable' | 'none'): void;

    /**
     * Get the current global strategy for showing the protected range shadow.
     * @returns {('always' | 'non-editable' | 'non-viewable' | 'none')} The current shadow strategy
     * @example
     * ```typescript
     * const currentStrategy = univerAPI.getProtectedRangeShadowStrategy();
     * console.log(currentStrategy); // 'none', 'always', 'non-editable', or 'non-viewable'
     * ```
     */
    getProtectedRangeShadowStrategy(): 'always' | 'non-editable' | 'non-viewable' | 'none';

    /**
     * Get an observable of the global strategy for showing the protected range shadow.
     * This allows you to listen for strategy changes across all workbooks.
     * @returns {Observable<('always' | 'non-editable' | 'non-viewable' | 'none')>} An observable that emits the current shadow strategy
     * @example
     * ```typescript
     * const subscription = univerAPI.getProtectedRangeShadowStrategy$().subscribe((strategy) => {
     *     console.log('Global strategy changed to:', strategy);
     *     // Update UI or perform other actions
     * });
     *
     * // Later, unsubscribe to clean up
     * subscription.unsubscribe();
     * ```
     */
    getProtectedRangeShadowStrategy$(): Observable<'always' | 'non-editable' | 'non-viewable' | 'none'>;

    /**
     * Set visibility of unauthorized pop-up window
     * @param {boolean} visible - visibility of unauthorized pop-up window
     * @example
     * ```ts
     * const univerAPI = FUniver.newAPI(univer);
     * univerAPI.setPermissionDialogVisible(false);
     * ```
     */
    setPermissionDialogVisible(visible: boolean): void;
}

export class FUniverSheetsUIMixin extends FUniver implements IFUniverSheetsUIMixin {
    // eslint-disable-next-line max-lines-per-function
    private _initSheetUIEvent(injector: Injector): void {
        const commandService = injector.get(ICommandService);

        // Edit events
        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.BeforeSheetEditStart,
                () => commandService.beforeCommandExecuted((commandInfo) => {
                    if (commandInfo.id !== SetCellEditVisibleOperation.id) return;

                    const target = this.getActiveSheet();
                    if (!target) return;

                    const { workbook, worksheet } = target;
                    const editorBridgeService = injector.get(IEditorBridgeService);
                    const params = commandInfo.params as IEditorBridgeServiceVisibleParam;
                    const { visible, keycode, eventType } = params;
                    const loc = editorBridgeService.getEditLocation()!;
                    if (!visible) return;

                    const eventParams: IBeforeSheetEditStartEventParams = {
                        row: loc.row,
                        column: loc.column,
                        eventType,
                        keycode,
                        workbook,
                        worksheet,
                    };
                    this.fireEvent(this.Event.BeforeSheetEditStart, eventParams);
                    if (eventParams.cancel) {
                        throw new CanceledError();
                    }
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.BeforeSheetEditEnd,
                () => commandService.beforeCommandExecuted((commandInfo) => {
                    if (commandInfo.id !== SetCellEditVisibleOperation.id) return;

                    const target = this.getActiveSheet();
                    if (!target) return;

                    const { workbook, worksheet } = target;
                    const editorBridgeService = injector.get(IEditorBridgeService);
                    const univerInstanceService = injector.get(IUniverInstanceService);
                    const params = commandInfo.params as IEditorBridgeServiceVisibleParam;
                    const { visible, keycode, eventType } = params;
                    const loc = editorBridgeService.getEditLocation()!;
                    if (visible) return;

                    const eventParams: IBeforeSheetEditEndEventParams = {
                        row: loc.row,
                        column: loc.column,
                        eventType,
                        keycode,
                        workbook,
                        worksheet,
                        value: RichTextValue.create(univerInstanceService.getUnit<DocumentDataModel>(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.getSnapshot()),
                        isConfirm: keycode !== KeyCode.ESC,
                    };
                    this.fireEvent(this.Event.BeforeSheetEditEnd, eventParams);
                    if (eventParams.cancel) {
                        throw new CanceledError();
                    }
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.SheetEditStarted,
                () => commandService.onCommandExecuted((commandInfo) => {
                    if (commandInfo.id !== SetCellEditVisibleOperation.id) return;

                    const params = commandInfo.params as IEditorBridgeServiceVisibleParam;
                    const target = this.getSheetCommandTarget(params);
                    if (!target) return;

                    const { workbook, worksheet } = target;
                    const { visible, keycode, eventType } = params;
                    if (!visible) return;

                    const loc = injector.get(IEditorBridgeService).getEditLocation()!;

                    const eventParams: ISheetEditStartedEventParams = {
                        row: loc.row,
                        column: loc.column,
                        eventType,
                        keycode,
                        workbook,
                        worksheet,
                    };
                    this.fireEvent(this.Event.SheetEditStarted, eventParams);
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.SheetEditEnded,
                () => commandService.onCommandExecuted((commandInfo) => {
                    if (commandInfo.id !== SetCellEditVisibleOperation.id) return;

                    const params = commandInfo.params as IEditorBridgeServiceVisibleParam;
                    const target = this.getSheetCommandTarget(params);
                    if (!target) return;

                    const { workbook, worksheet } = target;
                    const { visible, keycode, eventType } = params;
                    if (visible) return;

                    const loc = injector.get(IEditorBridgeService).getEditLocation()!;

                    const eventParams: ISheetEditEndedEventParams = {
                        row: loc.row,
                        column: loc.column,
                        eventType,
                        keycode,
                        workbook,
                        worksheet,
                        isConfirm: keycode !== KeyCode.ESC,
                    };
                    this.fireEvent(this.Event.SheetEditEnded, eventParams);
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.SheetEditChanging,
                () => commandService.onCommandExecuted((commandInfo) => {
                    if (commandInfo.id !== RichTextEditingMutation.id) return;

                    const params = commandInfo.params as IRichTextEditingMutationParams;
                    const target = this.getActiveSheet();
                    if (!target) return;

                    const { workbook, worksheet } = target;
                    const editorBridgeService = injector.get(IEditorBridgeService);
                    const univerInstanceService = injector.get(IUniverInstanceService);

                    if (!editorBridgeService.isVisible().visible) return;

                    const { unitId } = params;
                    if (unitId === DOCS_NORMAL_EDITOR_UNIT_ID_KEY) {
                        const { row, column } = editorBridgeService.getEditLocation()!;
                        const eventParams: ISheetEditChangingEventParams = {
                            workbook,
                            worksheet,
                            row,
                            column,
                            value: RichTextValue.create(univerInstanceService.getUnit<DocumentDataModel>(DOCS_NORMAL_EDITOR_UNIT_ID_KEY)!.getSnapshot()),
                        };
                        this.fireEvent(this.Event.SheetEditChanging, eventParams);
                    }
                })
            )
        );

        // Zoom events
        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.BeforeSheetZoomChange,
                () => commandService.beforeCommandExecuted((commandInfo) => {
                    if (commandInfo.id !== SetZoomRatioCommand.id) return;

                    const params = commandInfo.params as ISetZoomRatioCommandParams;
                    const target = this.getSheetCommandTarget(params);
                    if (!target) return;

                    const { workbook, worksheet } = target;
                    const { zoomRatio: zoom } = params;

                    const eventParams: ISheetZoomEventParams = {
                        workbook,
                        worksheet,
                        zoom,
                    };
                    this.fireEvent(this.Event.BeforeSheetZoomChange, eventParams);

                    if (eventParams.cancel) {
                        throw new CanceledError();
                    }
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.SheetZoomChanged,
                () => commandService.onCommandExecuted((commandInfo) => {
                    if (commandInfo.id !== SetZoomRatioCommand.id) return;

                    const params = commandInfo.params as ISetZoomRatioCommandParams;
                    const target = this.getSheetCommandTarget(params);
                    if (!target) return;

                    const { workbook, worksheet } = target;
                    const { zoomRatio: zoom } = params;

                    const eventParams: ISheetZoomEventParams = {
                        workbook,
                        worksheet,
                        zoom,
                    };
                    this.fireEvent(this.Event.SheetZoomChanged, eventParams);
                })
            )
        );
    }

    // eslint-disable-next-line max-lines-per-function
    private _initObserverListener(injector: Injector): void {
        const renderManagerService = injector.get(IRenderManagerService);
        const lifeCycleService = injector.get(LifecycleService);
        const univerInstanceService = injector.get(IUniverInstanceService);

        const lifecycle$Disposable = new DisposableCollection();
        // eslint-disable-next-line max-lines-per-function
        const registerPointerEventListeners = (): void => {
            const hoverManagerService = injector.get(HoverManagerService);
            const dragManagerService = injector.get(DragManagerService);

            // Cell events
            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.CellClicked,
                    () => hoverManagerService.currentClickedCell$
                        ?.pipe(filter((cell) => !!cell))
                        .subscribe((cell) => {
                            const { unitId, subUnitId, row, col: column } = cell.location;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ICellEventParams = {
                                workbook,
                                worksheet,
                                row,
                                column,
                            };
                            this.fireEvent(this.Event.CellClicked, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.CellHover,
                    () => hoverManagerService.currentRichText$
                        ?.pipe(filter((cell) => !!cell))
                        .subscribe((cell) => {
                            const { unitId, subUnitId, row, col: column } = cell;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ICellEventParams = {
                                workbook,
                                worksheet,
                                row,
                                column,
                            };
                            this.fireEvent(this.Event.CellHover, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.CellPointerDown,
                    () => hoverManagerService.currentPointerDownCell$
                        ?.pipe(filter((cell) => !!cell))
                        .subscribe((cell) => {
                            const { unitId, subUnitId, row, col: column } = cell;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ICellEventParams = {
                                workbook,
                                worksheet,
                                row,
                                column,
                            };
                            this.fireEvent(this.Event.CellPointerDown, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.CellPointerUp,
                    () => hoverManagerService.currentPointerUpCell$
                        ?.pipe(filter((cell) => !!cell))
                        .subscribe((cell) => {
                            const { unitId, subUnitId, row, col: column } = cell;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ICellEventParams = {
                                workbook,
                                worksheet,
                                row,
                                column,
                            };
                            this.fireEvent(this.Event.CellPointerUp, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.CellPointerMove,
                    () => hoverManagerService.currentCellPosWithEvent$
                        ?.pipe(filter((cell) => !!cell))
                        .subscribe((cell) => {
                            const { unitId, subUnitId, row, col: column } = cell;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ICellEventParams = {
                                workbook,
                                worksheet,
                                row,
                                column,
                            };
                            this.fireEvent(this.Event.CellPointerMove, eventParams);
                        })
                )
            );

            // Drag events
            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.DragOver,
                    () => dragManagerService.currentCell$
                        ?.pipe(filter((cell) => !!cell))
                        .subscribe((cell) => {
                            const { unitId, subUnitId, row, col: column } = cell.location;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: IDragEventParams = {
                                workbook,
                                worksheet,
                                ...cell,
                                row,
                                column,
                            };
                            this.fireEvent(this.Event.DragOver, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.Drop,
                    () => dragManagerService.endCell$
                        ?.pipe(filter((cell) => !!cell))
                        .subscribe((cell) => {
                            const { unitId, subUnitId, row, col: column } = cell.location;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: IDragEventParams = {
                                workbook,
                                worksheet,
                                ...cell,
                                row,
                                column,
                            };
                            this.fireEvent(this.Event.Drop, eventParams);
                        })
                )
            );

            // Row Header events
            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.RowHeaderClick,
                    () => hoverManagerService.currentRowHeaderClick$
                        ?.pipe(filter((header) => !!header))
                        .subscribe((header) => {
                            const { unitId, subUnitId, index: row } = header;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ISheetRowHeaderEventParams = {
                                workbook,
                                worksheet,
                                row,
                            };
                            this.fireEvent(this.Event.RowHeaderClick, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.RowHeaderPointerDown,
                    () => hoverManagerService.currentRowHeaderPointerDown$
                        ?.pipe(filter((header) => !!header))
                        .subscribe((header) => {
                            const { unitId, subUnitId, index: row } = header;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ISheetRowHeaderEventParams = {
                                workbook,
                                worksheet,
                                row,
                            };
                            this.fireEvent(this.Event.RowHeaderPointerDown, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.RowHeaderPointerUp,
                    () => hoverManagerService.currentRowHeaderPointerUp$
                        ?.pipe(filter((header) => !!header))
                        .subscribe((header) => {
                            const { unitId, subUnitId, index: row } = header;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ISheetRowHeaderEventParams = {
                                workbook,
                                worksheet,
                                row,
                            };
                            this.fireEvent(this.Event.RowHeaderPointerUp, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.RowHeaderHover,
                    () => hoverManagerService.currentHoveredRowHeader$
                        ?.pipe(filter((header) => !!header))
                        .subscribe((header) => {
                            const { unitId, subUnitId, index: row } = header;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ISheetRowHeaderEventParams = {
                                workbook,
                                worksheet,
                                row,
                            };
                            this.fireEvent(this.Event.RowHeaderHover, eventParams);
                        })
                )
            );

            // Column Header events
            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.ColumnHeaderClick,
                    () => hoverManagerService.currentColHeaderClick$
                        ?.pipe(filter((header) => !!header))
                        .subscribe((header) => {
                            const { unitId, subUnitId, index: column } = header;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ISheetColumnHeaderEventParams = {
                                workbook,
                                worksheet,
                                column,
                            };
                            this.fireEvent(this.Event.ColumnHeaderClick, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.ColumnHeaderPointerDown,
                    () => hoverManagerService.currentColHeaderPointerDown$
                        ?.pipe(filter((header) => !!header))
                        .subscribe((header) => {
                            const { unitId, subUnitId, index: column } = header;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ISheetColumnHeaderEventParams = {
                                workbook,
                                worksheet,
                                column,
                            };
                            this.fireEvent(this.Event.ColumnHeaderPointerDown, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.ColumnHeaderPointerUp,
                    () => hoverManagerService.currentColHeaderPointerUp$
                        ?.pipe(filter((header) => !!header))
                        .subscribe((header) => {
                            const { unitId, subUnitId, index: column } = header;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ISheetColumnHeaderEventParams = {
                                workbook,
                                worksheet,
                                column,
                            };
                            this.fireEvent(this.Event.ColumnHeaderPointerUp, eventParams);
                        })
                )
            );

            lifecycle$Disposable.add(
                this.registerEventHandler(
                    this.Event.ColumnHeaderHover,
                    () => hoverManagerService.currentHoveredColHeader$
                        ?.pipe(filter((header) => !!header))
                        .subscribe((header) => {
                            const { unitId, subUnitId, index: column } = header;
                            const target = this.getSheetCommandTarget({ unitId, subUnitId });
                            if (!target) return;

                            const { workbook, worksheet } = target;

                            const eventParams: ISheetColumnHeaderEventParams = {
                                workbook,
                                worksheet,
                                column,
                            };
                            this.fireEvent(this.Event.ColumnHeaderHover, eventParams);
                        })
                )
            );

            this.disposeWithMe(lifecycle$Disposable);
        };

        const sheetAvailable$ = univerInstanceService.getAllUnitsForType(UniverInstanceType.UNIVER_SHEET).length > 0
            ? of(true)
            : univerInstanceService.getTypeOfUnitAdded$(UniverInstanceType.UNIVER_SHEET).pipe(take(1));
        this.disposeWithMe(
            combineLatest([sheetAvailable$, lifeCycleService.lifecycle$]).pipe(
                filter(([, lifecycle]) => lifecycle >= LifecycleStages.Rendered),
                take(1)
            ).subscribe(() => registerPointerEventListeners())
        );

        // UI Events in renderUnit
        let sheetRenderUnit: Nullable<IRender>;
        const combined$ = combineLatest([
            renderManagerService.created$,
            lifeCycleService.lifecycle$,
        ]);
        const combined$Disposable = new DisposableCollection();
        // eslint-disable-next-line max-lines-per-function
        this.disposeWithMe(combined$.subscribe(([created, lifecycle]) => {
            // univer & univer-pro are not same in life cycle.

            // for pro
            // type     2   2   1   1
            // stage    1   2   2   2
            // for univer
            // type     2   1   1   1
            // stage    1   1   1   2
            if (created.type === UniverInstanceType.UNIVER_SHEET) {
                sheetRenderUnit = created;
            }
            if (lifecycle <= LifecycleStages.Rendered) return;
            if (!sheetRenderUnit) return;

            const workbook = this.getWorkbook(sheetRenderUnit.unitId);
            if (!workbook) return;

            // Prevent multiple registrations
            combined$Disposable.dispose();

            const scrollManagerService = sheetRenderUnit.with(SheetScrollManagerService);
            const selectionService = this._tryGetRenderDependency(sheetRenderUnit, SheetsSelectionsService);

            // Register scroll event handler
            combined$Disposable.add(
                this.registerEventHandler(
                    this.Event.Scroll,
                    () => scrollManagerService.validViewportScrollInfo$.subscribe((params: Nullable<IViewportScrollState>) => {
                        if (!params) return;
                        const eventParams: IScrollEventParams = {
                            workbook,
                            worksheet: workbook.getActiveSheet(),
                            ...params,
                        };
                        this.fireEvent(this.Event.Scroll, eventParams);
                    })
                )
            );

            // Register selection event handlers
            if (selectionService) {
                combined$Disposable.add(
                    this.registerEventHandler(
                        this.Event.SelectionMoveStart,
                        () => selectionService.selectionMoveStart$.subscribe((selections) => {
                            const eventParams: ISelectionEventParams = {
                                workbook,
                                worksheet: workbook.getActiveSheet(),
                                selections: selections?.map((s) => s.range) ?? [],
                            };
                            this.fireEvent(this.Event.SelectionMoveStart, eventParams);
                        })
                    )
                );

                combined$Disposable.add(
                    this.registerEventHandler(
                        this.Event.SelectionMoving,
                        () => selectionService.selectionMoving$.subscribe((selections) => {
                            const eventParams: ISelectionEventParams = {
                                workbook,
                                worksheet: workbook.getActiveSheet(),
                                selections: selections?.map((s) => s.range) ?? [],
                            };
                            this.fireEvent(this.Event.SelectionMoving, eventParams);
                        })
                    )
                );

                combined$Disposable.add(
                    this.registerEventHandler(
                        this.Event.SelectionMoveEnd,
                        () => selectionService.selectionMoveEnd$.subscribe((selections) => {
                            const eventParams: ISelectionEventParams = {
                                workbook,
                                worksheet: workbook.getActiveSheet(),
                                selections: selections?.map((s) => s.range) ?? [],
                            };
                            this.fireEvent(this.Event.SelectionMoveEnd, eventParams);
                        })
                    )
                );

                combined$Disposable.add(
                    this.registerEventHandler(
                        this.Event.SelectionChanged,
                        () => selectionService.selectionChanged$.subscribe((selections) => {
                            const eventParams: ISelectionEventParams = {
                                workbook,
                                worksheet: workbook.getActiveSheet(),
                                selections: selections?.map((s) => s.range) ?? [],
                            };
                            this.fireEvent(this.Event.SelectionChanged, eventParams);
                        })
                    )
                );
            }
            // for pro, in pro, life cycle & created$ is not same as univer sdk
            // if not clear sheetRenderUnit, that would cause event bind twice!
            sheetRenderUnit = null;
            this.disposeWithMe(combined$Disposable);
        }));
    }

    private _tryGetRenderDependency<T>(render: IRender, dependency: DependencyIdentifier<T>): Nullable<T> {
        try {
            // `IRender.with` only resolves render modules registered on the render unit itself.
            // Global services such as `SheetsSelectionsService` live in an ancestor injector, so they
            // must be resolved through the render unit's injector lookup chain instead.
            const injector = render.getInjector?.();
            if (injector) {
                return injector.get(dependency);
            }

            return render.with(dependency);
        } catch (error) {
            if (error instanceof Error && (error.message.includes('DependencyNotFoundError') || error.message.includes('Cannot find'))) {
                return null;
            }

            throw error;
        }
    }

    /**
     * @ignore
     */
    // eslint-disable-next-line max-lines-per-function
    override _initialize(injector: Injector): void {
        this._initSheetUIEvent(injector);
        this._initObserverListener(injector);
        const commandService = injector.get(ICommandService);

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.BeforeClipboardChange,
                () => commandService.beforeCommandExecuted((commandInfo) => {
                    switch (commandInfo.id) {
                        case CopyCommand.id:
                        case CutCommand.id:
                            this._beforeClipboardChange();
                            break;
                    }
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.ClipboardChanged,
                () => commandService.onCommandExecuted((commandInfo) => {
                    switch (commandInfo.id) {
                        case CopyCommand.id:
                        case CutCommand.id:
                            this._clipboardChanged();
                            break;
                    }
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.BeforeClipboardPaste,
                () => commandService.beforeCommandExecuted((commandInfo) => {
                    switch (commandInfo.id) {
                        case SheetPasteShortKeyCommand.id:
                            this._beforeClipboardPaste(commandInfo.params);
                            break;
                        case PasteCommand.id:
                            this._beforeClipboardPasteAsync();
                            break;
                    }
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.ClipboardPasted,
                () => commandService.onCommandExecuted((commandInfo) => {
                    switch (commandInfo.id) {
                        case SheetPasteShortKeyCommand.id:
                            this._clipboardPaste(commandInfo.params);
                            break;
                        case PasteCommand.id:
                            this._clipboardPasteAsync();
                            break;
                    }
                })
            )
        );

        this.disposeWithMe(
            this.registerEventHandler(
                this.Event.SheetSkeletonChanged,
                () => commandService.onCommandExecuted((commandInfo) => {
                    if (COMMAND_LISTENER_SKELETON_CHANGE.indexOf(commandInfo.id) > -1) {
                        const sheet = this.getActiveSheet();
                        if (!sheet) return;
                        const ranges = getSkeletonChangedEffectedRange(commandInfo, sheet.worksheet.getMaxColumns())
                            .map((range) => this.getWorkbook(range.unitId)?.getSheetBySheetId(range.subUnitId)?.getRange(range.range))
                            .filter(Boolean) as FRange[];
                        if (!ranges.length) return;

                        const eventParams: ISheetSkeletonChangedEventParams = {
                            workbook: sheet.workbook,
                            worksheet: sheet.worksheet,
                            payload: commandInfo as CommandListenerSkeletonChange,
                            skeleton: sheet.worksheet.getSkeleton()!,
                            effectedRanges: ranges,
                        };
                        this.fireEvent(this.Event.SheetSkeletonChanged, eventParams);
                    }
                })
            )
        );
    }

    private _generateClipboardCopyParam(): IBeforeClipboardChangeEventParams | IClipboardChangedEventParams | undefined {
        const workbook = this.getActiveWorkbook();
        const worksheet = workbook?.getActiveSheet();
        const range = workbook?.getActiveRange();
        if (!workbook || !worksheet || !range) {
            return;
        }

        const clipboardService = this._injector.get(ISheetClipboardService);
        const content = clipboardService.generateCopyContent(workbook.getId(), worksheet.getSheetId(), range.getRange());
        if (!content) {
            return;
        }
        const { html, plain } = content;
        const eventParams: IBeforeClipboardChangeEventParams | IClipboardChangedEventParams = {
            workbook,
            worksheet,
            text: plain,
            html,
            fromSheet: worksheet,
            fromRange: range,
        };
        return eventParams;
    }

    private _beforeClipboardChange(): void {
        const eventParams = this._generateClipboardCopyParam() as IBeforeClipboardChangeEventParams;
        if (!eventParams) return;

        this.fireEvent(this.Event.BeforeClipboardChange, eventParams);
        if (eventParams.cancel) {
            throw new CanceledError();
        }
    }

    private _clipboardChanged(): void {
        const eventParams = this._generateClipboardCopyParam() as IClipboardChangedEventParams;
        if (!eventParams) return;

        this.fireEvent(this.Event.ClipboardChanged, eventParams);
    }

    private _generateClipboardPasteParam(params?: ISheetPasteByShortKeyParams): IBeforeClipboardPasteEventParams | IClipboardPastedEventParams | undefined {
        if (!params) {
            return;
        }
        const { htmlContent, textContent } = params as ISheetPasteByShortKeyParams;
        const workbook = this.getActiveWorkbook();
        const worksheet = workbook?.getActiveSheet();
        if (!workbook || !worksheet) {
            return;
        }
        const eventParams: IBeforeClipboardPasteEventParams | IClipboardPastedEventParams = {
            workbook,
            worksheet,
            text: textContent,
            html: htmlContent,
        };
        return eventParams;
    }

    private async _generateClipboardPasteParamAsync(): Promise<IBeforeClipboardPasteEventParams | undefined> {
        const workbook = this.getActiveWorkbook();
        const worksheet = workbook?.getActiveSheet();
        if (!workbook || !worksheet) {
            return;
        }
        const clipboardInterfaceService = this._injector.get(IClipboardInterfaceService);
        const clipboardItems = await clipboardInterfaceService.read();
        const item = clipboardItems[0];
        let eventParams: IBeforeClipboardPasteEventParams | undefined;
        if (item) {
            const types = item.types;
            const text =
                types.indexOf(PLAIN_TEXT_CLIPBOARD_MIME_TYPE) !== -1
                    ? await item.getType(PLAIN_TEXT_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text())
                    : '';
            const html =
                types.indexOf(HTML_CLIPBOARD_MIME_TYPE) !== -1
                    ? await item.getType(HTML_CLIPBOARD_MIME_TYPE).then((blob) => blob && blob.text())
                    : '';
            eventParams = {
                workbook,
                worksheet,
                text,
                html,
            };
        }
        return eventParams;
    }

    private _beforeClipboardPaste(params?: ISheetPasteByShortKeyParams): void {
        const eventParams = this._generateClipboardPasteParam(params) as IBeforeClipboardPasteEventParams;
        if (!eventParams) return;
        this.fireEvent(this.Event.BeforeClipboardPaste, eventParams);
        if (eventParams.cancel) {
            throw new CanceledError();
        }
    }

    private _clipboardPaste(params?: ISheetPasteByShortKeyParams): void {
        const eventParams = this._generateClipboardPasteParam(params) as IClipboardPastedEventParams;
        if (!eventParams) return;
        this.fireEvent(this.Event.ClipboardPasted, eventParams);
        if (eventParams.cancel) {
            throw new CanceledError();
        }
    }

    private async _beforeClipboardPasteAsync(): Promise<void> {
        if (!supportClipboardAPI()) {
            const logService = this._injector.get(ILogService);
            logService.warn('[Facade]: The navigator object only supports the browser environment');
            return;
        }
        const eventParams = await this._generateClipboardPasteParamAsync() as IBeforeClipboardPasteEventParams;
        if (!eventParams) return;
        this.fireEvent(this.Event.BeforeClipboardPaste, eventParams);
        if (eventParams.cancel) {
            throw new CanceledError();
        }
    }

    private async _clipboardPasteAsync(): Promise<void> {
        if (!supportClipboardAPI()) {
            const logService = this._injector.get(ILogService);
            logService.warn('[Facade]: The navigator object only supports the browser environment');
            return;
        }
        const eventParams = await this._generateClipboardPasteParamAsync();
        if (!eventParams) return;
        this.fireEvent(this.Event.ClipboardPasted, eventParams);
        if (eventParams.cancel) {
            throw new CanceledError();
        }
    }

    override registerSheetRowHeaderExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable {
        const sheetComponent = this._getSheetRenderComponent(unitId, SHEET_VIEW_KEY.ROW) as SheetComponent;
        const registerDisposable = sheetComponent.register(...extensions);

        return toDisposable(() => {
            registerDisposable.dispose();
            sheetComponent.makeDirty(true);
        });
    }

    override registerSheetColumnHeaderExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable {
        const sheetComponent = this._getSheetRenderComponent(unitId, SHEET_VIEW_KEY.COLUMN) as SheetComponent;
        const registerDisposable = sheetComponent.register(...extensions);

        return toDisposable(() => {
            registerDisposable.dispose();
            sheetComponent.makeDirty(true);
        });
    }

    override registerSheetMainExtension(unitId: string, ...extensions: SheetExtension[]): IDisposable {
        const sheetComponent = this._getSheetRenderComponent(unitId, SHEET_VIEW_KEY.MAIN) as SheetComponent;
        const registerDisposable = sheetComponent.register(...extensions);

        return toDisposable(() => {
            registerDisposable.dispose();
            sheetComponent.makeDirty(true);
        });
    }

    override registerCellCustomRender(customRender: Nullable<ICellCustomRender[]>, effect: InterceptorEffectEnum = InterceptorEffectEnum.Style, priority?: number): IDisposable {
        return this._injector.get(SheetInterceptorService).intercept(INTERCEPTOR_POINT.CELL_CONTENT, {
            effect,
            handler: (cell, pos, next) => {
                if (!cell) {
                    return next(cell);
                }

                if (!cell.customRender && customRender) {
                    cell.customRender = [...customRender];
                }

                return next(cell);
            },
            priority,
        });
    }

    /**
     * Get sheet render component from render by unitId and view key.
     * @private
     * @param {string} unitId The unit id of the spreadsheet.
     * @param {SHEET_VIEW_KEY} viewKey The view key of the spreadsheet.
     * @returns {Nullable<RenderComponentType>} The render component.
     */
    private _getSheetRenderComponent(unitId: string, viewKey: SHEET_VIEW_KEY): Nullable<RenderComponentType> {
        const renderManagerService = this._injector.get(IRenderManagerService);
        const render = renderManagerService.getRenderUnitById(unitId);
        if (!render) {
            throw new Error(`Render Unit with unitId ${unitId} not found`);
        }

        const { components } = render;

        const renderComponent = components.get(viewKey);
        if (!renderComponent) {
            throw new Error('Render component not found');
        }

        return renderComponent;
    }

    override pasteIntoSheet(htmlContent?: string, textContent?: string, files?: File[]): Promise<boolean> {
        return this._commandService.executeCommand(SheetPasteShortKeyCommand.id, { htmlContent, textContent, files });
    }

    override setProtectedRangeShadowStrategy(strategy: 'always' | 'non-editable' | 'non-viewable' | 'none'): void {
        const service = this._injector.get(SheetPermissionRenderManagerService);
        service.setProtectedRangeShadowStrategy(strategy);
    }

    override getProtectedRangeShadowStrategy(): 'always' | 'non-editable' | 'non-viewable' | 'none' {
        const service = this._injector.get(SheetPermissionRenderManagerService);
        return service.getProtectedRangeShadowStrategy();
    }

    override getProtectedRangeShadowStrategy$(): Observable<'always' | 'non-editable' | 'non-viewable' | 'none'> {
        const service = this._injector.get(SheetPermissionRenderManagerService);
        return service.getProtectedRangeShadowStrategy$();
    }

    override setPermissionDialogVisible(visible: boolean): void {
        const permissionService = this._injector.get(IPermissionService);
        permissionService.setShowComponents(visible);
    }
}

FUniver.extend(FUniverSheetsUIMixin);

declare module '@univerjs/core/facade' {
    // eslint-disable-next-line ts/naming-convention
    interface FUniver extends IFUniverSheetsUIMixin { }
}