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.

17.9 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 { Nullable, Workbook } from '@univerjs/core';
import type { IDefinedNamesServiceParam, ISetDefinedNameMutationParam } from '@univerjs/engine-formula';
import { generateRandomId, ICommandService, IPermissionService, IUniverInstanceService, LocaleService, UniverInstanceType } from '@univerjs/core';
import { Button, clsx, Confirm, scrollbarClassName, Tooltip } from '@univerjs/design';
import { IDefinedNamesService, serializeRangeWithSheet } from '@univerjs/engine-formula';
import { DeleteIcon, IncreaseIcon, PenIcon } from '@univerjs/icons';
import {
    InsertDefinedNameCommand,
    RemoveDefinedNameCommand,
    SCOPE_WORKBOOK_VALUE_DEFINED_NAME,
    SetDefinedNameCommand,
    SetWorksheetShowCommand,
    SheetPermissionCheckController,
    SheetsSelectionsService,
    WorkbookEditablePermission,
    WorksheetEditPermission,
} from '@univerjs/sheets';
import { useDependency, useObservable, useVirtualList } from '@univerjs/ui';
import { useRef, useState } from 'react';
import { map, startWith } from 'rxjs';
import type { LocaleKey } from '../../locale/types';
import { DefinedNameInput } from './DefinedNameInput';

export interface IDefinedNameContainerProps {
    ConfirmComponent?: typeof Confirm;
    DefinedNameInputComponent?: typeof DefinedNameInput;
}

export const DefinedNameContainer = ({
    ConfirmComponent = Confirm,
    DefinedNameInputComponent = DefinedNameInput,
}: IDefinedNameContainerProps = {}) => {
    const commandService = useDependency(ICommandService);
    const univerInstanceService = useDependency(IUniverInstanceService);
    const localeService = useDependency(LocaleService);
    const definedNamesService = useDependency(IDefinedNamesService);
    const selectionManagerService = useDependency(SheetsSelectionsService);
    const permissionService = useDependency(IPermissionService);
    const sheetPermissionCheckController = useDependency(SheetPermissionCheckController);

    const workbook = univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
    const unitId = workbook?.getUnitId();
    const getDefinedNameMap = () => {
        if (!unitId) {
            return [];
        }
        const definedNameMap = definedNamesService.getDefinedNameMap(unitId);
        if (definedNameMap) {
            return Object.values(definedNameMap);
        }
        return [];
    };

    const [editState, setEditState] = useState(false);
    const definedNames = useObservable(
        () => definedNamesService.update$.pipe(map(getDefinedNameMap), startWith(getDefinedNameMap())),
        getDefinedNameMap(),
        false,
        [definedNamesService, unitId]
    );
    const [editorKey, setEditorKey] = useState<Nullable<string>>(null);
    const [deleteConformKey, setDeleteConformKey] = useState<Nullable<string>>();

    const listContainerRef = useRef<HTMLDivElement>(undefined!);
    const [virtualDefinedNames, virtualActions] = useVirtualList(definedNames, {
        containerTarget: listContainerRef,
        itemHeight: (index, item) => {
            if (item.id === editorKey) {
                return 240;
            }
            return 72;
        },
        overscan: 6,
    });

    const resolvePermissionState = () => {
        if (!unitId) {
            return { workbook: false, worksheets: new Map<string, boolean>() };
        }

        return {
            workbook: sheetPermissionCheckController.permissionCheckWithoutRange(
                { workbookTypes: [WorkbookEditablePermission] },
                unitId
            ),
            worksheets: new Map(definedNames.map((definedName) => [
                definedName.id,
                !definedName.localSheetId || definedName.localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME
                    ? sheetPermissionCheckController.permissionCheckWithoutRange(
                        { workbookTypes: [WorkbookEditablePermission] },
                        unitId
                    )
                    : sheetPermissionCheckController.permissionCheckWithoutRange(
                        { worksheetTypes: [WorksheetEditPermission] },
                        unitId,
                        definedName.localSheetId
                    ),
            ])),
        };
    };
    const permissionState = useObservable(
        () => permissionService.permissionPointUpdate$.pipe(
            map(resolvePermissionState),
            startWith(resolvePermissionState())
        ),
        resolvePermissionState(),
        false,
        [definedNames, permissionService, sheetPermissionCheckController, unitId]
    );

    if (!workbook || !unitId) {
        return;
    }

    // check defined name permission
    const checkWorkbookPermission = permissionState.workbook;
    const checkDefinedNamePermission = (definedName: IDefinedNamesServiceParam): boolean => {
        return permissionState.worksheets.get(definedName.id) ?? checkWorkbookPermission;
    };

    const insertConfirm = (param: IDefinedNamesServiceParam) => {
        const { name, formulaOrRefString, comment, localSheetId, hidden } = param;

        let id = param.id;
        if (id == null || id.length === 0) {
            id = generateRandomId(10);
            commandService.executeCommand(InsertDefinedNameCommand.id, { id, unitId, name, formulaOrRefString, comment, localSheetId, hidden });
        } else {
            const newDefinedName: ISetDefinedNameMutationParam = { id, unitId, name, formulaOrRefString, comment, localSheetId, hidden };
            commandService.executeCommand(SetDefinedNameCommand.id, newDefinedName);
        }
        setEditState(false);
        setEditorKey(null);
    };

    const deleteDefinedName = (id: string) => {
        setDeleteConformKey(id);
    };

    function handleDeleteClose() {
        setDeleteConformKey(null);
    }

    function handleDeleteConfirm(id: string) {
        if (!unitId) return;
        const item = definedNamesService.getValueById(unitId, id);
        commandService.executeCommand(RemoveDefinedNameCommand.id, { ...item, unitId });
        setDeleteConformKey(null);
    }

    const focusDefinedName = async (definedName: IDefinedNamesServiceParam) => {
        // The worksheet may be hidden, so we need to show it first
        const { formulaOrRefString, id } = definedName;
        const worksheet = definedNamesService.getWorksheetByRef(unitId, formulaOrRefString);
        if (!worksheet) {
            return;
        }

        const isHidden = worksheet.isSheetHidden();
        if (isHidden) {
            await commandService.executeCommand(SetWorksheetShowCommand.id, { unitId, subUnitId: worksheet.getSheetId() });
        }

        definedNamesService.focusRange(unitId, id);
    };

    const getInsertDefinedName = () => {
        const count = definedNames.length + 1;
        const name = localeService.t<LocaleKey>('sheets-ui.definedName.defaultName') + count;
        if (definedNamesService.getValueByName(unitId, name) == null) {
            return name;
        }

        let i = count + 1;
        while (true) {
            const newName = localeService.t<LocaleKey>('sheets-ui.definedName.defaultName') + i;
            if (definedNamesService.getValueByName(unitId, newName) == null) {
                return newName;
            }
            i++;
        }
    };

    const getInertFormulaOrRefString = () => {
        const sheetName = workbook.getActiveSheet()?.getName();
        if (!sheetName) {
            return '';
        }

        const selections = selectionManagerService.getCurrentSelections();
        if (selections == null) {
            return '';
        }

        const formulaOrRefs = selections.map((selection) => {
            return serializeRangeWithSheet(sheetName, selection.range);
        });

        return formulaOrRefs.join(',');
    };

    const closeInput = () => {
        setEditState(false);
        setEditorKey(null);
    };

    const openInsertCloseKeyEditor = () => {
        setEditState(true);
        setEditorKey(null);
    };

    const closeInsertOpenKeyEditor = (id: string) => {
        setEditState(false);
        setEditorKey(id);
    };

    const getSheetNameBySheetId = (sheetId: string) => {
        const sheet = workbook.getSheetBySheetId(sheetId);
        if (sheet == null) {
            return '';
        }

        return sheet.getName();
    };

    return (
        <div
            data-u-comp="defined-name-container"
            className="
              univer-relative univer-box-border univer-flex univer-h-0 univer-min-h-full univer-w-full univer-flex-col
              univer-overflow-hidden
            "
        >
            <div key="insertDefinedName" className="univer-mb-4">
                <Button
                    className={clsx(
                        'univer-w-full',
                        {
                            'univer-hidden': editState,
                        }
                    )}
                    disabled={!checkWorkbookPermission}
                    onClick={openInsertCloseKeyEditor}
                >
                    <IncreaseIcon />
                    <span className="univer-ml-1">{localeService.t<LocaleKey>('sheets-ui.definedName.addButton')}</span>
                </Button>
                {editState && (
                    <DefinedNameInputComponent
                        confirm={insertConfirm}
                        cancel={closeInput}
                        state={editState}
                        inputId="insertDefinedName"
                        name={getInsertDefinedName()}
                        formulaOrRefString={getInertFormulaOrRefString()}
                    />
                )}
            </div>

            <div
                ref={listContainerRef}
                className={clsx('univer-min-h-0 univer-flex-1 univer-overflow-y-auto', scrollbarClassName)}
                {...virtualActions.containerProps}
            >
                <div className="univer-box-content univer-pb-4" style={virtualActions.wrapperStyle}>
                    {virtualDefinedNames.map(({ data: definedName, index }) => {
                        return (
                            <div
                                key={index}
                                className={`
                                  univer-relative univer-w-full univer-divide-x-0 univer-divide-y univer-divide-solid
                                  univer-divide-gray-200
                                  dark:!univer-divide-gray-600
                                `}
                            >
                                <div
                                    className={clsx(`
                                      univer-group univer-relative univer-box-border univer-flex univer-w-full
                                      univer-cursor-default univer-select-none univer-items-center
                                      univer-justify-between univer-rounded-md univer-p-2
                                      hover:univer-bg-gray-50
                                      dark:hover:!univer-bg-gray-700
                                    `, {
                                        'univer-hidden': definedName.id === editorKey,
                                    })}
                                    onClick={() => { focusDefinedName(definedName); }}
                                >
                                    <div title={definedName.comment}>
                                        <div
                                            className={`
                                              univer-my-1 univer-max-h-[100px] univer-max-w-[190px] univer-truncate
                                              univer-text-sm univer-font-medium univer-text-gray-900
                                              dark:!univer-text-gray-0
                                            `}
                                        >
                                            {definedName.name}
                                            <span className="univer-ml-1 univer-text-xs univer-text-gray-400">
                                                {(definedName.localSheetId === SCOPE_WORKBOOK_VALUE_DEFINED_NAME || definedName.localSheetId == null) ? '' : getSheetNameBySheetId(definedName.localSheetId)}
                                            </span>
                                        </div>
                                        <div
                                            className={`
                                              univer-my-1 univer-max-h-[100px] univer-w-full univer-max-w-[190px]
                                              univer-truncate univer-text-xs univer-text-gray-500
                                            `}
                                            title={definedName.formulaOrRefString}
                                        >
                                            {definedName.formulaOrRefString}
                                        </div>
                                    </div>
                                    {checkDefinedNamePermission(definedName) && (
                                        <div
                                            className={`
                                              univer-absolute univer-right-5 univer-top-1/2 univer-hidden
                                              -univer-translate-y-1/2 univer-cursor-pointer univer-items-center
                                              univer-justify-end univer-gap-7 univer-text-xs univer-text-primary-600
                                              group-hover:univer-flex
                                              dark:hover:!univer-bg-gray-600
                                            `}
                                        >
                                            <Tooltip
                                                title={localeService.t<LocaleKey>('sheets-ui.definedName.updateButton')}
                                                placement="top"
                                            >
                                                <a
                                                    className={`
                                                      univer-rounded univer-p-1
                                                      hover:univer-bg-gray-100
                                                    `}
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        closeInsertOpenKeyEditor(definedName.id);
                                                    }}
                                                >
                                                    <PenIcon />
                                                </a>
                                            </Tooltip>
                                            <Tooltip
                                                title={localeService.t<LocaleKey>('sheets-ui.definedName.deleteButton')}
                                                placement="top"
                                            >
                                                <a
                                                    className={`
                                                      univer-rounded univer-p-1 univer-text-red-600
                                                      hover:univer-bg-gray-100
                                                    `}
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        deleteDefinedName(definedName.id);
                                                    }}
                                                >
                                                    <DeleteIcon />
                                                </a>
                                            </Tooltip>
                                        </div>
                                    )}
                                </div>

                                <ConfirmComponent
                                    visible={deleteConformKey === definedName.id}
                                    onClose={handleDeleteClose}
                                    onConfirm={() => { handleDeleteConfirm(definedName.id); }}
                                >
                                    {localeService.t<LocaleKey>('sheets-ui.definedName.deleteConfirmText')}
                                </ConfirmComponent>

                                {definedName.id === editorKey && (
                                    <DefinedNameInputComponent
                                        confirm={insertConfirm}
                                        cancel={closeInput}
                                        state={definedName.id === editorKey}
                                        id={definedName.id}
                                        inputId={definedName.id + index}
                                        name={definedName.name}
                                        formulaOrRefString={definedName.formulaOrRefString}
                                        comment={definedName.comment}
                                        localSheetId={definedName.localSheetId}
                                    />
                                )}
                            </div>
                        );
                    })}
                </div>
            </div>
        </div>
    );
};