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 { DeepReadonly, ISelectionCell, IStyleData, Nullable, Workbook } from '@univerjs/core';
import type { Observable } from 'rxjs';
import type { ISelectionWithStyle } from '../../basics/selection';
import type { ISelectionManagerSearchParam } from './type';
import { IUniverInstanceService, RxDisposable, Tools, UniverInstanceType } from '@univerjs/core';
import { distinctUntilChanged, of, share, shareReplay, skip, switchMap, takeUntil } from 'rxjs';
import { WorkbookSelectionModel } from './selection-data-model';
import { SelectionMoveType } from './type';

/**
 * For normal selection.
 * Ref selection is in RefSelectionService which extends this class.
 */
export class SheetsSelectionsService extends RxDisposable {
    private get _currentSelectionPos(): Nullable<ISelectionManagerSearchParam> {
        const workbook = this._instanceSrv.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
        if (!workbook) return null;

        const worksheet = workbook.getActiveSheet();
        return { unitId: workbook.getUnitId(), sheetId: worksheet.getSheetId() };
    }

    get currentSelectionParam() {
        return this._currentSelectionPos;
    }

    /**
     * Cache cell styles for current selections, key is `${row}_${column}`.
     */
    private _cellStylesCache = new Map<string, IStyleData>();

    /**
     * Selection Events, usually triggered when pointerdown in spreadsheet by selection render service after selectionModel has updated.
     */
    selectionMoveStart$: Observable<Nullable<ISelectionWithStyle[]>>;

    /**
     * Selection Events, usually triggered when pointermove in spreadsheet by selection render service after selectionModel has updated.
     */
    selectionMoving$: Observable<Nullable<ISelectionWithStyle[]>>;

    /**
     * Selection Events, usually triggered when pointerup in spreadsheet by selection render service after selectionModel has updated.
     */
    selectionMoveEnd$: Observable<ISelectionWithStyle[]>;

    /**
     * Selection Events, usually triggered when changing unit.(focus in formula editor)
     */
    selectionSet$: Observable<Nullable<ISelectionWithStyle[]>>;

    /**
     * Selection Events, merge moveEnd$ and selectionSet$
     */
    selectionChanged$: Observable<Nullable<ISelectionWithStyle[]>>;

    constructor(
        @IUniverInstanceService protected readonly _instanceSrv: IUniverInstanceService
    ) {
        super();
        this._init();
    }

    protected _init(): void {
        const c$ = this._instanceSrv.getCurrentTypeOfUnit$(UniverInstanceType.UNIVER_SHEET).pipe(shareReplay({ bufferSize: 1, refCount: true }), takeUntil(this.dispose$));
        // When workbook changed, unsubscribe the previous workbook selection$ and subscribe the new workbook selection$.
        this.selectionMoveStart$ = c$.pipe(
            switchMap((workbook) => !workbook ? of() : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoveStart$),
            takeUntil(this.dispose$)
        );
        this.selectionMoving$ = c$.pipe(
            switchMap((workbook) => !workbook ? of() : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoving$),
            takeUntil(this.dispose$)
        );
        this.selectionMoveEnd$ = c$.pipe(
            switchMap((workbook) => !workbook ? of([]) : this._ensureWorkbookSelection(workbook.getUnitId()).selectionMoveEnd$),
            takeUntil(this.dispose$)
        );
        this.selectionSet$ = c$.pipe(
            switchMap((workbook) => !workbook ? of([]) : this._ensureWorkbookSelection(workbook.getUnitId()).selectionSet$),
            takeUntil(this.dispose$)
        );
        this.selectionChanged$ = c$.pipe(
            switchMap((workbook) => !workbook ? of([]) : this._ensureWorkbookSelection(workbook.getUnitId()).selectionChanged$),
            distinctUntilChanged((prev, curr) => {
                if (prev.length !== curr.length) return false;
                if (prev.length === 0 && curr.length === 0) return true;
                return prev.every((item, index) => {
                    return JSON.stringify(item) === JSON.stringify(curr[index]);
                });
            }),
            skip(1),
            takeUntil(this.dispose$),
            share()
        );

        this.disposeWithMe(
            this._instanceSrv.getTypeOfUnitDisposed$(UniverInstanceType.UNIVER_SHEET).pipe(takeUntil(this.dispose$)).subscribe((workbook) => {
                this._removeWorkbookSelection(workbook.getUnitId());
            })
        );

        // Clear cell styles cache when current selections changed.
        this.disposeWithMe(
            this.selectionChanged$.pipe(takeUntil(this.dispose$)).subscribe(() => {
                this._cellStylesCache.clear();
            })
        );
    }

    override dispose(): void {
        super.dispose();
        this._cellStylesCache.clear();
        this._workbookSelections.forEach((wbSelection) => wbSelection.dispose());
        this._workbookSelections.clear();
        // Observables do not have unsubscribe(); active subscriptions are handled via takeUntil(this.dispose$) and disposeWithMe.
        // Replace exposed observables with simple completed values to avoid holding references.
        this.selectionMoveStart$ = of(null);
        this.selectionMoving$ = of(null);
        this.selectionMoveEnd$ = of([]);
        this.selectionSet$ = of(null);
        this.selectionChanged$ = of(null);
    }

    /**
     * Clear all selections in all workbooks.
     * invoked by prompt.controller
     */
    clear(): void {
        this._workbookSelections.forEach((wbSelection) => wbSelection.clear());
    }

    getCurrentSelections(): Readonly<ISelectionWithStyle[]> {
        return this._getCurrentSelections();
    }

    getCurrentLastSelection(): DeepReadonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>> {
        const selectionData = this._getCurrentSelections();
        return selectionData?.[selectionData.length - 1] as Readonly<Nullable<ISelectionWithStyle & { primary: ISelectionCell }>>;
    }

    getCurrentLastSelectionPrimaryCell(): DeepReadonly<Nullable<ISelectionCell>> {
        const current = this._currentSelectionPos;
        if (!current) {
            return null;
        }

        const { unitId, sheetId } = current;
        return this._ensureWorkbookSelection(unitId).getLastSelectionPrimaryCellOfWorksheet(sheetId);
    }

    addSelections(selectionsData: ISelectionWithStyle[]): void;
    addSelections(unitId: string, worksheetId: string, selectionDatas: ISelectionWithStyle[]): void;
    addSelections(unitIdOrSelections: string | ISelectionWithStyle[], worksheetId?: string, selectionDatas?: ISelectionWithStyle[]): void {
        if (typeof unitIdOrSelections === 'string') {
            this._ensureWorkbookSelection(unitIdOrSelections).addSelections(worksheetId!, selectionDatas!);
            return;
        }

        const current = this._currentSelectionPos;
        if (!current) {
            throw new Error('[SheetsSelectionsService]: cannot find current selection position!');
        }
        const { unitId, sheetId } = current;
        this._ensureWorkbookSelection(unitId).addSelections(sheetId, unitIdOrSelections);
    }

    /**
     * Set selection data to WorkbookSelectionModel.
     *
     * @param unitIdOrSelections
     * @param worksheetIdOrType
     * @param selectionDatas
     * @param type
     */
    setSelections(selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
    setSelections(unitId: string, worksheetId: string, selectionDatas: ISelectionWithStyle[], type?: SelectionMoveType): void;
    setSelections(
        unitIdOrSelections: string | ISelectionWithStyle[],
        worksheetIdOrType: string | SelectionMoveType | undefined,
        selectionDatas?: ISelectionWithStyle[],
        type?: SelectionMoveType
    ): void {
        if (typeof unitIdOrSelections === 'string' && typeof worksheetIdOrType === 'string') {
            const unitId = unitIdOrSelections as string;
            this._ensureWorkbookSelection(unitId).setSelections(
                worksheetIdOrType,
                selectionDatas || [],
                type ?? SelectionMoveType.ONLY_SET
            );
            return;
        }

        const current = this._currentSelectionPos;
        if (!current) {
            throw new Error('[SheetsSelectionsService]: cannot find current selection position!');
        }

        const { unitId, sheetId } = current;
        if (typeof unitIdOrSelections === 'object') {
            const selectionData = unitIdOrSelections ?? selectionDatas;
            const type = worksheetIdOrType as SelectionMoveType ?? SelectionMoveType.ONLY_SET;
            this._ensureWorkbookSelection(unitId).setSelections(sheetId, selectionData, type);
        }
    }

    clearCurrentSelections(): void {
        const selectionData = this._getCurrentSelections();
        selectionData.splice(0);
    }

    protected _getCurrentSelections() {
        const current = this._currentSelectionPos;
        if (!current) {
            return [];
        }

        const { unitId, sheetId } = current;
        return this._ensureWorkbookSelection(unitId).getSelectionsOfWorksheet(sheetId);
    }

    getWorkbookSelections(unitId: string): WorkbookSelectionModel {
        return this._ensureWorkbookSelection(unitId);
    }

    protected _workbookSelections = new Map<string, WorkbookSelectionModel>();
    protected _ensureWorkbookSelection(unitId: string): WorkbookSelectionModel {
        let wbSelection = this._workbookSelections.get(unitId);
        if (!wbSelection) {
            const workbook = this._instanceSrv.getUnit<Workbook>(unitId);
            if (!workbook) {
                throw new Error(`[SheetsSelectionsService]: cannot resolve unit with id "${unitId}"!`);
            }

            wbSelection = new WorkbookSelectionModel(workbook);
            this._workbookSelections.set(unitId, wbSelection);
        }

        return wbSelection;
    }

    protected _removeWorkbookSelection(unitId: string): void {
        this._workbookSelections.delete(unitId);
    }

    /**
     * This method is used to get the common value of a specific cell style property in the current selections.
     * Used to determine the state related to color panels in the toolbar.
     * Because in Excel, only the color panels need to show the common color of the current selections, other properties based on the current selection primary cell.
     * Now only handles text color, fill color, border style, border color.
     */
    getCellStylesProperty(property: keyof IStyleData): {
        isAllValuesSame: boolean;
        value: Nullable<IStyleData[keyof IStyleData]>;
    } {
        const worksheet = this._instanceSrv.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet();
        const selections = this.getCurrentSelections();
        if (!worksheet || selections.length === 0) {
            return {
                isAllValuesSame: false,
                value: null,
            };
        }

        let value: Nullable<IStyleData[keyof IStyleData]> = null;

        for (let i = 0; i < selections.length; i++) {
            const selection = selections[i];
            const { startRow, endRow, startColumn, endColumn } = selection.range;

            for (let row = startRow; row <= endRow; row++) {
                for (let column = startColumn; column <= endColumn; column++) {
                    const key = `${row}_${column}`;
                    let style: IStyleData;
                    if (this._cellStylesCache.has(key)) {
                        style = this._cellStylesCache.get(key)!;
                    } else {
                        style = worksheet.getComposedCellStyle(row, column);
                        this._cellStylesCache.set(key, style);
                    }

                    const _value = style[property];

                    if (value !== undefined && value !== null && !Tools.diffValue(value, _value)) {
                        return {
                            isAllValuesSame: false,
                            value: null,
                        };
                    }

                    value = _value;
                }
            }
        }

        return {
            isAllValuesSame: true,
            value,
        };
    }
}

/** An context key to disable normal selections if its value is set to `true`. */
// so Bad! why not enableXXX
export const DISABLE_NORMAL_SELECTIONS = 'DISABLE_NORMAL_SELECTIONS';
export const SELECTIONS_ENABLED = 'SELECTIONS_ENABLED';
export const REF_SELECTIONS_ENABLED = 'REF_SELECTIONS_ENABLED';
export const SELECTION_MODE = '__SELECTION_MODE__';
export enum SelectionMode {
    NORMAL,
    REF,
}