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.

8.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 type { ReactElement } from 'react';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { DesktopLogService, ILogService, Injector, LocaleService, LocaleType } from '@univerjs/core';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { IDialogPartMethodOptions } from '../interface';
import { ComponentManager } from '../../../../common/component-manager';
import { IconManager } from '../../../../common/icon-manager';
import {
    ContextMenuHostService,
    IContextMenuHostService,
} from '../../../../services/contextmenu/contextmenu-host.service';
import { DesktopDialogService } from '../../../../services/dialog/desktop-dialog.service';
import { IDialogService } from '../../../../services/dialog/dialog.service';
import { IUIPartsService, UIPartsService } from '../../../../services/parts/parts.service';
import { RediProvider } from '../../../../utils/di';
import { DialogPart } from '../DialogPart';

(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

function renderWithDependencies(element: ReactElement) {
    const injector = new Injector();
    injector.add([IUIPartsService, { useClass: UIPartsService }]);
    injector.add([IContextMenuHostService, { useClass: ContextMenuHostService }]);
    injector.add([IDialogService, { useClass: DesktopDialogService }]);
    injector.add([ILogService, { useClass: DesktopLogService }]);
    injector.add([LocaleService]);
    injector.add([ComponentManager]);
    injector.add([IconManager]);
    const localeService = injector.get(LocaleService);
    localeService.load({ [LocaleType.EN_US]: {} });
    localeService.setLocale(LocaleType.EN_US);
    localeService.setDirection('ltr');

    const result = render(
        <RediProvider value={{ injector }}>
            {element}
        </RediProvider>
    );

    return {
        ...result,
        injector,
        dispose: () => {
            result.unmount();
            cleanup();
            injector.dispose();
        },
    };
}

describe('DialogPart', () => {
    afterEach(() => {
        vi.restoreAllMocks();
        cleanup();
    });

    it.each([false, true])('restores the caller after close without stealing a newer focus (%s)', async (moveFocus) => {
        const editor = document.createElement('input');
        const nextEditor = document.createElement('input');
        document.body.append(editor, nextEditor);
        const rendered = renderWithDependencies(<DialogPart />);
        try {
            const dialogService = rendered.injector.get(IDialogService);
            for (const opener of [editor, nextEditor]) {
                opener.focus();
                act(() => dialogService.open({
                    id: 'editing',
                    title: { title: 'Editing' },
                    children: { title: <input aria-label="Dialog draft" /> },
                }));
                await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('textbox', { name: 'Dialog draft' })));
                const newTarget = opener === editor ? nextEditor : editor;
                act(() => {
                    dialogService.close('editing');
                });
                if (moveFocus) {
                    newTarget.focus();
                }
                await waitFor(() => expect(document.activeElement).toBe(moveFocus ? newTarget : opener));
            }
        } finally {
            rendered.dispose();
            editor.remove();
            nextEditor.remove();
        }
    });

    it('leaves composing Escape to the candidate window, then closes on ordinary Escape', async () => {
        const rendered = renderWithDependencies(<DialogPart />);
        try {
            const dialogService = rendered.injector.get(IDialogService);
            const onClose = vi.fn(() => dialogService.close('editing'));
            const onKeyDown = vi.fn();
            act(() => dialogService.open({
                id: 'editing',
                title: { title: 'Editing' },
                children: { title: <input aria-label="Dialog draft" onKeyDown={onKeyDown} /> },
                onClose,
            }));
            const input = screen.getByRole('textbox', { name: 'Dialog draft' });
            fireEvent.keyDown(input, { key: 'Escape', isComposing: true });
            expect(onClose).not.toHaveBeenCalled();
            expect(onKeyDown).toHaveBeenCalledOnce();
            expect(screen.getByRole('dialog').contains(input)).toBe(true);
            fireEvent.keyDown(input, { key: 'Escape' });
            expect(onClose).toHaveBeenCalledOnce();
            await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
        } finally {
            rendered.dispose();
        }
    });

    it('renders service-opened dialog labels and clears the requested dialog when service closes it', async () => {
        const rendered = renderWithDependencies(<DialogPart />);
        const dialogService = rendered.injector.get(IDialogService);
        const snapshots: IDialogPartMethodOptions[][] = [];
        const subscription = dialogService.getDialogs$().subscribe((options) => snapshots.push(options));

        act(() => {
            dialogService.open({
                id: 'permission-dialog',
                title: { title: <span>Permission needed</span> },
                children: { title: <span>Grant access before editing.</span> },
                width: 320,
            });
        });

        expect(await screen.findByText('Permission needed')).toBeTruthy();
        expect(screen.getByText('Grant access before editing.')).toBeTruthy();

        act(() => {
            dialogService.close('permission-dialog');
        });

        await waitFor(() => {
            expect(screen.queryByText('Grant access before editing.')).toBeNull();
        });
        expect(snapshots.at(-1)).toMatchObject([{ id: 'permission-dialog', open: false }]);

        subscription.unsubscribe();
        rendered.dispose();
    });

    it('passes custom label keys without spreading them into JSX', async () => {
        const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
        const rendered = renderWithDependencies(<DialogPart />);
        const dialogService = rendered.injector.get(IDialogService);
        const children = {
            key: 'pivot-filter',
            title: <span>Keyed dialog content</span>,
        };

        act(() => {
            dialogService.open({
                id: 'keyed-dialog',
                children,
            });
        });

        expect(await screen.findByText('Keyed dialog content')).toBeTruthy();
        expect(consoleErrorSpy.mock.calls.some(([message]) =>
            typeof message === 'string' && message.includes('A props object containing a "key" prop is being spread into JSX')
        )).toBe(false);

        rendered.dispose();
    });

    it('keeps excepted dialogs visible when service closes the rest', async () => {
        const rendered = renderWithDependencies(<DialogPart />);
        const dialogService = rendered.injector.get(IDialogService);
        const snapshots: IDialogPartMethodOptions[][] = [];
        const subscription = dialogService.getDialogs$().subscribe((options) => snapshots.push(options));

        act(() => {
            dialogService.open({
                id: 'first-dialog',
                title: { title: <span>First dialog</span> },
                children: { title: <span>Draft changes</span> },
            });
            dialogService.open({
                id: 'second-dialog',
                title: { title: <span>Second dialog</span> },
                children: { title: <span>Keep this open</span> },
            });
        });

        expect(await screen.findByText('Draft changes')).toBeTruthy();
        expect(screen.getByText('Keep this open')).toBeTruthy();

        act(() => {
            dialogService.closeAll(['second-dialog']);
        });

        await waitFor(() => {
            expect(screen.queryByText('Draft changes')).toBeNull();
        });
        expect(screen.getByText('Keep this open')).toBeTruthy();
        expect(snapshots.at(-1)).toMatchObject([
            { id: 'first-dialog', open: false },
            { id: 'second-dialog', open: true },
        ]);

        subscription.unsubscribe();
        rendered.dispose();
    });
});