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.

15.8 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 { ICommandService, IContextService, LocaleService } from '@univerjs/core';
import { Button, Checkbox, FormDualColumnLayout, FormLayout, Input, MessageType, Select } from '@univerjs/design';
import { ILayoutService, IMessageService, useDebounceFn, useDependency, useObservable } from '@univerjs/ui';
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef } from 'react';
import { fromEvent } from 'rxjs';
import type { LocaleKey } from '../../locale/types';
import { ReplaceAllMatchesCommand, ReplaceCurrentMatchCommand } from '../../commands/commands/replace.command';
import { OpenReplaceDialogOperation } from '../../commands/operations/find-replace.operation';
import { FIND_REPLACE_DIALOG_FOCUS, FIND_REPLACE_INPUT_FOCUS } from '../../services/context-keys';
import { FindBy, FindDirection, FindScope, IFindReplaceService } from '../../services/find-replace.service';
import { SearchInput } from './SearchInput';

interface ISubFormRef {
    focus(): void;
    selectHasFocus(): boolean;
}

const FIND_SCOPE_OPTIONS: Array<{ label: LocaleKey; value: FindScope }> = [
    { label: 'find-replace.dialog.find-scope.current-sheet', value: FindScope.SUBUNIT },
    { label: 'find-replace.dialog.find-scope.workbook', value: FindScope.UNIT },
];

const FIND_DIRECTION_OPTIONS: Array<{ label: LocaleKey; value: FindDirection }> = [
    { label: 'find-replace.dialog.find-direction.row', value: FindDirection.ROW },
    { label: 'find-replace.dialog.find-direction.column', value: FindDirection.COLUMN },
];

const FIND_BY_OPTIONS: Array<{ label: LocaleKey; value: FindBy }> = [
    { label: 'find-replace.dialog.find-by.value', value: FindBy.VALUE },
    { label: 'find-replace.dialog.find-by.formula', value: FindBy.FORMULA },
];

function useFindInputFocus(findReplaceService: IFindReplaceService, ref: Parameters<typeof useImperativeHandle>[0]) {
    const pendingFocusFrameRef = useRef<number | null>(null);
    const focus = useCallback(() => {
        (document.querySelector('.univer-find-input input') as HTMLInputElement | null)?.focus();
    }, []);
    const focusAfterDialogClose = useCallback(() => {
        focus();
        pendingFocusFrameRef.current = requestAnimationFrame(() => {
            pendingFocusFrameRef.current = null;
            focus();
        });
    }, [focus]);

    const selectHasFocus = useCallback(() => {
        const allInputs = document.querySelectorAll('[data-u-comp=find-replace-dialog] [data-u-comp=search-input]');
        return Array.from(allInputs).some((input) => input === document.activeElement);
    }, []);

    useImperativeHandle(ref, () => ({ focus, selectHasFocus }));

    useEffect(() => {
        const subscription = findReplaceService.focusSignal$.subscribe(() => focus());
        return () => {
            subscription.unsubscribe();
            if (pendingFocusFrameRef.current !== null) {
                cancelAnimationFrame(pendingFocusFrameRef.current);
            }
        };
    }, [findReplaceService, focus]);

    return { focus, focusAfterDialogClose, selectHasFocus };
}

export const FindDialog = forwardRef(function FindDialogImpl(_props, ref) {
    const localeService = useDependency(LocaleService);
    const findReplaceService = useDependency(IFindReplaceService);
    const commandService = useDependency(ICommandService);

    const state = useObservable(findReplaceService.state$, undefined, true);
    const { findCompleted, findString, matchesCount, matchesPosition } = state;

    const revealReplace = useCallback(() => {
        return commandService.executeCommand(OpenReplaceDialogOperation.id);
    }, [commandService]);

    const onFindStringChange = useDebounceFn((findString: string) => {
        return findReplaceService.changeFindString(findString);
    }, 500);

    useFindInputFocus(findReplaceService, ref);

    return (
        <>
            <SearchInput
                findCompleted={findCompleted}
                matchesCount={matchesCount}
                matchesPosition={matchesPosition}
                findReplaceService={findReplaceService}
                initialFindString={findString}
                onChange={onFindStringChange}
            />
            <div className="univer-mt-4 univer-text-center">
                <Button type="button" variant="link" size="small" onClick={revealReplace}>
                    {localeService.t<LocaleKey>('find-replace.dialog.advanced-finding')}
                </Button>
            </div>
        </>
    );
});

export const ReplaceDialog = forwardRef(function ReplaceDialogImpl(_props, ref) {
    const findReplaceService = useDependency(IFindReplaceService);
    const localeService = useDependency(LocaleService);
    const commandService = useDependency(ICommandService);
    const messageService = useDependency(IMessageService);

    const currentMatch = useObservable(findReplaceService.currentMatch$, undefined, true);
    const replaceables = useObservable(findReplaceService.replaceables$, undefined, true);
    const capabilities = useObservable(findReplaceService.providerCapabilities$, null, true);
    const state = useObservable(findReplaceService.state$, undefined, true);
    const {
        matchesCount,
        matchesPosition,
        findString,
        inputtingFindString,
        replaceString,
        caseSensitive,
        matchesTheWholeCell,
        matchesTheWholeWord,
        findDirection,
        findScope,
        findBy,
        findCompleted,
    } = state;

    const findDisabled = inputtingFindString.length === 0;
    const replaceDisabled = matchesCount === 0 || !currentMatch?.replaceable;
    const replaceAllDisabled = replaceables.length === 0;

    const onFindStringChange = useCallback(
        (newValue: string) => findReplaceService.changeInputtingFindString(newValue),
        [findReplaceService]
    );
    const onReplaceStringChange = useCallback(
        (replaceString: string) => findReplaceService.changeReplaceString(replaceString),
        [findReplaceService]
    );

    const { focusAfterDialogClose } = useFindInputFocus(findReplaceService, ref);

    const onClickFindButton = useCallback(() => {
        if (findString === inputtingFindString) {
            findReplaceService.moveToNextMatch();
        } else {
            findReplaceService.changeFindString(inputtingFindString);
            findReplaceService.find();
        }
    }, [findString, inputtingFindString, findReplaceService]);
    const onClickReplaceButton = useCallback(() => commandService.executeCommand(ReplaceCurrentMatchCommand.id), [commandService]);
    const onClickReplaceAllButton = useCallback(async () => {
        await commandService.executeCommand(ReplaceAllMatchesCommand.id);
        focusAfterDialogClose();
    }, [commandService, focusAfterDialogClose]);

    const onChangeFindDirection = useCallback((findDirection: string) => {
        findReplaceService.changeFindDirection(findDirection as FindDirection);
    }, [findReplaceService]);
    const onChangeFindScope = useCallback((findScope: string) => {
        findReplaceService.changeFindScope(findScope as FindScope);
    }, [findReplaceService]);
    const onChangeFindBy = useCallback((findBy: string) => {
        findReplaceService.changeFindBy(findBy as FindBy);
    }, [findReplaceService]);

    const findScopeOptions = FIND_SCOPE_OPTIONS.map((option) => ({ ...option, label: localeService.t(option.label) }));
    const findDirectionOptions = FIND_DIRECTION_OPTIONS.map((option) => ({ ...option, label: localeService.t(option.label) }));
    const findByOptions = FIND_BY_OPTIONS.map((option) => ({ ...option, label: localeService.t(option.label) }));

    useEffect(() => {
        const shouldDisplayNoMatchInfo = findCompleted && matchesCount === 0;

        if (shouldDisplayNoMatchInfo) {
            messageService.show({
                content: localeService.t<LocaleKey>('find-replace.dialog.no-match'),
                type: MessageType.Warning,
                duration: 5000,
            });
        }
    }, [findCompleted, matchesCount, messageService, localeService]);

    return (
        <div>
            <FormLayout label={localeService.t<LocaleKey>('find-replace.dialog.find')}>
                <SearchInput
                    findCompleted={findCompleted}
                    className="univer-find-input"
                    matchesCount={matchesCount}
                    matchesPosition={matchesPosition}
                    findReplaceService={findReplaceService}
                    initialFindString={inputtingFindString}
                    onChange={onFindStringChange}
                />
            </FormLayout>
            <FormLayout label={localeService.t<LocaleKey>('find-replace.dialog.replace')}>
                <Input
                    placeholder={localeService.t<LocaleKey>('find-replace.dialog.replace-placeholder')}
                    value={replaceString}
                    onChange={(value) => onReplaceStringChange(value)}
                />
            </FormLayout>
            {capabilities?.findDirection && (
                <FormLayout label={localeService.t<LocaleKey>('find-replace.dialog.find-direction.title')}>
                    <Select value={findDirection} options={findDirectionOptions} onChange={onChangeFindDirection} />
                </FormLayout>
            )}
            {(capabilities?.findScope || capabilities?.findBy) && (
                <FormDualColumnLayout>
                    <>
                        {capabilities.findScope && (
                            <FormLayout label={localeService.t<LocaleKey>('find-replace.dialog.find-scope.title')}>
                                <Select value={findScope} options={findScopeOptions} onChange={onChangeFindScope} />
                            </FormLayout>
                        )}
                        {capabilities.findBy && (
                            <FormLayout label={localeService.t<LocaleKey>('find-replace.dialog.find-by.title')}>
                                <Select value={findBy} options={findByOptions} onChange={onChangeFindBy} />
                            </FormLayout>
                        )}
                    </>
                </FormDualColumnLayout>
            )}
            {(capabilities?.caseSensitive || capabilities?.matchesTheWholeCell || capabilities?.matchesTheWholeWord) && (
                <FormDualColumnLayout>
                    <>
                        {capabilities.caseSensitive && (
                            <FormLayout>
                                <Checkbox
                                    checked={caseSensitive}
                                    onChange={(checked) => {
                                        findReplaceService.changeCaseSensitive(Boolean(checked));
                                        if (findCompleted) {
                                            findReplaceService.find();
                                        }
                                    }}
                                >
                                    {localeService.t<LocaleKey>('find-replace.dialog.case-sensitive')}
                                </Checkbox>
                            </FormLayout>
                        )}
                        {capabilities.matchesTheWholeCell && (
                            <FormLayout>
                                <Checkbox checked={matchesTheWholeCell} onChange={(checked) => findReplaceService.changeMatchesTheWholeCell(Boolean(checked))}>
                                    {localeService.t<LocaleKey>('find-replace.dialog.match-the-whole-cell')}
                                </Checkbox>
                            </FormLayout>
                        )}
                        {capabilities.matchesTheWholeWord && (
                            <FormLayout>
                                <Checkbox
                                    checked={matchesTheWholeWord}
                                    onChange={(checked) => {
                                        findReplaceService.changeMatchesTheWholeWord(Boolean(checked));
                                        if (findCompleted) {
                                            findReplaceService.find();
                                        }
                                    }}
                                >
                                    {localeService.t<LocaleKey>('find-replace.dialog.match-the-whole-word')}
                                </Checkbox>
                            </FormLayout>
                        )}
                    </>
                </FormDualColumnLayout>
            )}
            <div className="univer-mt-6 univer-flex univer-justify-between">
                <Button variant="primary" onClick={onClickFindButton} disabled={findDisabled}>{localeService.t<LocaleKey>('find-replace.dialog.find')}</Button>
                <span className="univer-inline-flex univer-gap-2">
                    <Button disabled={replaceDisabled} onClick={onClickReplaceButton}>{localeService.t<LocaleKey>('find-replace.dialog.replace')}</Button>
                    <Button disabled={replaceAllDisabled} onClick={onClickReplaceAllButton}>{localeService.t<LocaleKey>('find-replace.dialog.replace-all')}</Button>
                </span>
            </div>
        </div>
    );
});

export function FindReplaceDialog() {
    const findReplaceService = useDependency(IFindReplaceService);
    const layoutService = useDependency(ILayoutService);
    const contextService = useDependency(IContextService);

    const state = useObservable(findReplaceService.state$, undefined, true);

    const dialogContainerRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const container = dialogContainerRef.current;
        if (!container) {
            return;
        }

        const disposable = layoutService.registerContainerElement(container);
        return () => disposable.dispose();
    }, [layoutService]);

    const focusRef = useRef<ISubFormRef>(null);
    const setDialogContainerFocus = useCallback(
        (focused: boolean) => contextService.setContextValue(FIND_REPLACE_DIALOG_FOCUS, focused),
        [contextService]
    );
    const setDialogInputFocus = useCallback(
        (focused: boolean) => contextService.setContextValue(FIND_REPLACE_INPUT_FOCUS, focused),
        [contextService]
    );

    useEffect(() => {
        const focusSubscription = fromEvent(document, 'focusin').subscribe((event) => {
            if (event.target && dialogContainerRef.current?.contains(event.target as Node)) {
                setDialogContainerFocus(true);
            } else {
                setDialogContainerFocus(false);
            }

            if (!focusRef.current || !focusRef.current.selectHasFocus()) {
                setDialogInputFocus(false);
            } else {
                setDialogInputFocus(true);
            }
        });

        // Sync focus after opening or switching forms, once the new input ref is attached.
        focusRef.current?.focus();

        setDialogContainerFocus(true);
        setDialogInputFocus(true);

        return () => {
            focusSubscription.unsubscribe();
            setDialogContainerFocus(false);
        };
    }, [setDialogContainerFocus, setDialogInputFocus, state.replaceRevealed]);

    return (
        <div ref={dialogContainerRef} data-u-comp="find-replace-dialog">
            {!state.replaceRevealed ? <FindDialog ref={focusRef} /> : <ReplaceDialog ref={focusRef} />}
        </div>
    );
}