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.2 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 { Worksheet } from '@univerjs/core';
import type { IDefinedNamesServiceParam } from '@univerjs/engine-formula';
import type { ChangeEvent, KeyboardEvent } from 'react';
import {
    debounce,
    generateRandomId,
    ICommandService,
    IUniverInstanceService,
    SheetTypes,
    ThemeService,
} from '@univerjs/core';
import { borderRightClassName, clsx, Dropdown } from '@univerjs/design';
import {
    deserializeRangeWithSheet,
    IDefinedNamesService,
    IFunctionService,
    ISuperTableService,
    LexerTreeBuilder,
} from '@univerjs/engine-formula';
import { MoreDownIcon } from '@univerjs/icons';
import {
    getPrimaryForRange,
    InsertDefinedNameCommand,
    SCOPE_WORKBOOK_VALUE_DEFINED_NAME,
    SetSelectionsOperation,
    SetWorksheetShowCommand,
    SheetPermissionCheckController,
    SheetsSelectionsService,
    WorkbookEditablePermission,
} from '@univerjs/sheets';
import { ILayoutService, useDependency, useObservable } from '@univerjs/ui';
import { useEffect, useMemo, useRef, useState } from 'react';
import { map, startWith } from 'rxjs';
import type { IScrollToCellCommandParams } from '../../commands/commands/set-scroll.command';
import { ScrollToCellCommand } from '../../commands/commands/set-scroll.command';
import { genNormalSelectionStyle } from '../../services/selection/const';
import {
    DefinedNameBoxActionType,
    getAbsoluteRefStringFromSelection,
    resolveDefinedNameBoxAction,
} from '../../services/utils/defined-name-utils';
import { useActiveWorkbook, useActiveWorksheet } from '../hook';
import { DefinedNameOverlay } from './DefinedNameOverlay';

export function DefinedName({ disable }: { disable: boolean }) {
    const [rangeString, setRangeString] = useState('');
    const [inputValue, setInputValue] = useState('');
    const definedNamesService = useDependency(IDefinedNamesService);
    const commandService = useDependency(ICommandService);
    const univerInstanceService = useDependency(IUniverInstanceService);
    const selectionManagerService = useDependency(SheetsSelectionsService);
    const lexerTreeBuilder = useDependency(LexerTreeBuilder);
    const superTableService = useDependency(ISuperTableService);
    const functionService = useDependency(IFunctionService);
    const layoutService = useDependency(ILayoutService);
    const sheetPermissionCheckController = useDependency(SheetPermissionCheckController);

    const workbook = useActiveWorkbook()!;
    const worksheet = useActiveWorksheet(workbook);
    const isGridSheet = !!worksheet && (worksheet.getConfig().type ?? SheetTypes.GRID) === SheetTypes.GRID;
    const disabled = disable || !isGridSheet;
    const unitId = workbook?.getUnitId();
    const themeService = useDependency(ThemeService);

    const [open, setOpen] = useState(false);
    const [isInputEvent, setIsInputEvent] = useState(false);
    const nameBoxRef = useRef<HTMLDivElement>(null);
    const inputRef = useRef<HTMLInputElement>(null);

    const getDefinedNameMap = () => {
        const definedNameMap = definedNamesService.getDefinedNameMap(unitId);
        if (definedNameMap) {
            return Object.values(definedNameMap);
        }

        return [];
    };

    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 focusSelection = (refString: string) => {
        const worksheet = workbook.getActiveSheet();
        const subUnitId = worksheet.getSheetId();

        getSelections(worksheet, refString).then((selections) => {
            if (!selections) {
                return;
            }

            commandService.executeCommand(SetSelectionsOperation.id, {
                unitId,
                subUnitId,
                selections,
            });

            commandService.executeCommand(
                ScrollToCellCommand.id,
                { range: selections[0].range } as IScrollToCellCommandParams
            );
        });
    };

    const definedNames = useObservable(
        () => definedNamesService.update$.pipe(map(getDefinedNameMap), startWith(getDefinedNameMap())),
        getDefinedNameMap(),
        false,
        [definedNamesService, unitId]
    );

    useEffect(() => {
        const subscription = definedNamesService.currentRange$.subscribe(() => {
            const selections = selectionManagerService.getCurrentSelections();
            const absoluteRef = getAbsoluteRefStringFromSelection(workbook, selections, lexerTreeBuilder);
            const definedName = definedNamesService.getDefinedNameByRefString(unitId, absoluteRef);

            if (definedName) {
                setRangeString(definedName.name);
                setInputValue(definedName.name);
            } else {
                const range = definedNamesService.getCurrentRangeForString();
                setRangeString(range);
                setInputValue(range);
            }
        });

        return () => {
            subscription.unsubscribe();
        };
    }, [definedNamesService, lexerTreeBuilder, selectionManagerService, unitId, workbook]);

    const handleDefinedNamesList = useMemo(() => debounce((value: string) => {
        const hasMatch = definedNames.find((i) => i.name.toLowerCase().includes(value.toLowerCase()));

        if (hasMatch && !open) {
            setOpen(true);
        } else if (!hasMatch && open) {
            setOpen(false);
        }
    }, 100), [definedNames, open]);

    useEffect(() => () => handleDefinedNamesList.cancel(), [handleDefinedNamesList, isGridSheet]);

    useEffect(() => {
        const subscription = workbook?.activeSheet$.subscribe(() => setOpen(false));
        return () => subscription?.unsubscribe();
    }, [workbook]);

    function handleChangeSelection(e: ChangeEvent<HTMLInputElement>) {
        if (disabled) {
            return;
        }
        const value = e.target.value.trim();
        setInputValue(value);
        setIsInputEvent(true);

        if (!value) {
            if (open) {
                setOpen(false);
            }
            return;
        }

        handleDefinedNamesList(value);
    }

    function confirm() {
        if (disabled) {
            return false;
        }
        const formulaOrRefString = getAbsoluteRefStringFromSelection(workbook, selectionManagerService.getCurrentSelections(), lexerTreeBuilder);
        const action = resolveDefinedNameBoxAction({
            inputValue,
            rangeString,
            unitId,
            formulaOrRefString,
            worksheet: workbook.getActiveSheet(),
            univerInstanceService,
            definedNamesService,
            superTableService,
            functionService,
        });

        switch (action.type) {
            case DefinedNameBoxActionType.Noop:
                return true;
            case DefinedNameBoxActionType.FocusDefinedName:
                setRangeString(action.definedName.name);
                setInputValue(action.definedName.name);
                focusDefinedName(action.definedName);
                return true;
            case DefinedNameBoxActionType.FocusSelection:
                setRangeString(action.refString);
                setInputValue(action.refString);
                focusSelection(action.refString);
                return true;
            case DefinedNameBoxActionType.CreateDefinedName: {
                if (
                    !formulaOrRefString ||
                    !sheetPermissionCheckController.permissionCheckWithoutRange(
                        {
                            workbookTypes: [WorkbookEditablePermission],
                        },
                        unitId
                    )
                ) {
                    resetValue();
                    return false;
                }

                const result = commandService.syncExecuteCommand(InsertDefinedNameCommand.id, {
                    id: generateRandomId(10),
                    unitId,
                    name: action.name,
                    formulaOrRefString,
                    localSheetId: SCOPE_WORKBOOK_VALUE_DEFINED_NAME,
                });

                if (result) {
                    setRangeString(action.name);
                    setInputValue(action.name);
                } else {
                    resetValue();
                }
                return !!result;
            }
            case DefinedNameBoxActionType.Reset:
                resetValue();
                return false;
        }
    }

    function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
        if (disabled) {
            return;
        }

        if (e.key === 'Enter') {
            const handled = confirm();
            setIsInputEvent(false);
            setOpen(false);
            if (handled) {
                layoutService.focus();
            }
        } else if (e.key === 'Escape') {
            e.preventDefault();
            setIsInputEvent(false);
            resetValue();
        }
    }

    function resetValue() {
        setInputValue(rangeString);
    }

    async function getSelections(worksheet: Worksheet, formulaOrRefString: string) {
        if (!worksheet) {
            return;
        }

        const unitRange = deserializeRangeWithSheet(formulaOrRefString.trim());

        const range = unitRange.range;
        const { startRow, startColumn, endRow, endColumn } = range;
        const primary = getPrimaryForRange({
            startRow,
            startColumn,
            endRow,
            endColumn,
        }, worksheet);

        const selections = [];
        selections.push({
            range: unitRange.range,
            style: genNormalSelectionStyle(themeService),
            primary,
        });

        return selections;
    }

    return (
        <div
            ref={nameBoxRef}
            data-u-comp="defined-name"
            onMouseDown={(e) => {
                if (disabled) {
                    e.preventDefault();
                }
            }}
            className={`
              univer-relative univer-box-border univer-flex univer-h-full univer-w-24 univer-border-r-gray-200
              univer-py-1.5 univer-transition-all
            `}
        >
            <input
                ref={inputRef}
                className={clsx(`
                  univer-box-border univer-size-full univer-appearance-none univer-bg-transparent univer-pl-1.5
                  univer-pr-5 univer-text-gray-900
                  focus:univer-outline-none
                  dark:!univer-border-r-gray-700 dark:!univer-text-gray-0
                `, borderRightClassName, {
                    'univer-cursor-not-allowed': disabled,
                })}
                type="text"
                disabled={disabled}
                value={isGridSheet ? inputValue : ''}
                onChange={handleChangeSelection}
                onKeyDown={handleKeyDown}
                onBlur={() => setIsInputEvent(false)}
            />

            <Dropdown
                align="start"
                anchorRef={nameBoxRef}
                overlay={(
                    <div className="univer-z-[1001]">
                        <DefinedNameOverlay
                            search={inputValue}
                            isInputEvent={isInputEvent}
                            onClose={() => setOpen(false)}
                        />
                    </div>
                )}
                disabled={disabled}
                open={!disabled && open}
                onOpenChange={setOpen}
                onOpenAutoFocus={(e) => e.preventDefault()}
            >
                <a
                    className={clsx(`
                      univer-absolute univer-right-0 univer-top-0 univer-flex univer-h-full univer-cursor-pointer
                      univer-items-center univer-justify-center univer-px-1 univer-transition-colors univer-duration-200
                      hover:univer-bg-gray-100
                      dark:!univer-text-gray-0
                      dark:hover:!univer-bg-gray-800
                    `, {
                        'univer-cursor-not-allowed univer-text-gray-300 hover:univer-bg-transparent dark:!univer-text-gray-700': disabled,
                    })}
                >
                    <MoreDownIcon />
                </a>
            </Dropdown>
        </div>
    );
}