Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

7.9 KB
Raw Blame
import type * as projectsApi from '@workbench/projects/api';

import { ChakraProvider, Menu, Portal } from '@chakra-ui/react';
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
import { settleAnimations } from '@platform/browser/settleAnimations.testing';
import { accountLifecycle, captureAccountScope } from '@platform/state/accountLifecycle';
import { closingFrames, recordDialogExit } from '@platform/ui/dialogExit.testing';
import { isModalPresent } from '@platform/ui/modalPresence';
import { system } from '@theme/system';
import { getWorkbenchPreferences, patchWorkbenchPreferences } from '@workbench/settings/store';
import { createInstance } from 'i18next';
import { act, useState } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, expect, it, vi } from 'vitest';
import { page } from 'vitest/browser';

import { ProjectFileOptionsProvider, useProjectFileOptions } from './ProjectFileOptionsProvider';

// The preference store is real; only its backend write is stubbed.
vi.mock('@workbench/projects/api', async (importOriginal) => ({
  ...(await importOriginal<typeof projectsApi>()),
  setClientStateValue: async () => {},
}));

const i18n = createInstance();
await i18n.use(initReactI18next).init({
  interpolation: { escapeValue: false },
  lng: 'en',
  resources: { en: { translation: await fetch('/locales/en.json').then((response) => response.json()) } },
});

let root: Root | undefined;
let host: HTMLDivElement | undefined;
let results: ({ includeFonts: boolean; includeWorkspace: boolean } | null)[] = [];
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

const Harness = () => {
  const { requestExportOptions } = useProjectFileOptions();
  return (
    <button
      type="button"
      onClick={() => {
        void requestExportOptions('Typography', captureAccountScope()).then((result) => results.push(result));
      }}
    >
      Export
    </button>
  );
};

// Like the project menus, the menu is controlled: it closes in the same render that mounts the dialog.
const MenuHarness = () => {
  const { requestExportOptions } = useProjectFileOptions();
  const [isOpen, setIsOpen] = useState(false);
  return (
    <Menu.Root
      open={isOpen}
      onOpenChange={(details) => setIsOpen(details.open)}
      onSelect={() => {
        void requestExportOptions('Typography', captureAccountScope()).then((result) => results.push(result));
      }}
    >
      <Menu.Trigger asChild>
        <button type="button">Project actions</button>
      </Menu.Trigger>
      <Portal>
        <Menu.Positioner>
          <Menu.Content>
            <Menu.Item value="export">Export…</Menu.Item>
          </Menu.Content>
        </Menu.Positioner>
      </Portal>
    </Menu.Root>
  );
};

const render = async (harness = <Harness />) => {
  await page.viewport(1280, 900);
  results = [];
  accountLifecycle.activate('fonts-test');
  host = document.createElement('div');
  document.body.append(host);
  root = createRoot(host);
  await act(() =>
    root!.render(
      <ChakraProvider value={system}>
        <I18nextProvider i18n={i18n}>
          <ProjectFileOptionsProvider>{harness}</ProjectFileOptionsProvider>
        </I18nextProvider>
      </ChakraProvider>
    )
  );
};

afterEach(async () => {
  await act(() => root?.unmount());
  host?.remove();
  accountLifecycle.invalidate();
});

it('defaults to references, includes files only when selected, and restores focus', async () => {
  await render();
  const trigger = page.getByRole('button', { name: 'Export', exact: true });
  await act(() => trigger.click());
  const checkbox = page.getByRole('checkbox', { name: 'Include font files' });
  await expect.element(checkbox).not.toBeChecked();
  await act(() => page.getByRole('button', { name: 'Export project', exact: true }).click());
  expect(results).toEqual([{ includeFonts: false, includeWorkspace: true }]);
  await expect.element(trigger).toHaveFocus();

  await act(() => trigger.click());
  await act(() => page.getByText('Include font files', { exact: true }).click());
  await expect.element(page.getByText(/permission to redistribute/)).toBeVisible();
  await settleAnimations();
  await page.screenshot({ path: '../../../../artifacts/fonts/export-dialog.png' });
  await act(() => page.getByRole('button', { name: 'Export project', exact: true }).click());
  expect(results).toEqual([
    { includeFonts: false, includeWorkspace: true },
    { includeFonts: true, includeWorkspace: true },
  ]);
});

it('includes my workspace unless I turn it off, and remembers that choice for the next export', async () => {
  await render();
  const trigger = page.getByRole('button', { name: 'Export', exact: true });
  const checkbox = page.getByRole('checkbox', { name: 'Include my settings for this project' });
  try {
    await act(() => trigger.click());
    await expect.element(checkbox).toBeChecked();
    await expect.element(checkbox).toHaveAccessibleDescription(/layout, generation settings, prompt history/);
    await expect
      .element(page.getByRole('checkbox', { name: 'Include font files' }))
      .toHaveAccessibleDescription(/install or replace fonts/);
    await act(() => page.getByText('Include my settings for this project', { exact: true }).click());
    await act(() => page.getByRole('button', { name: 'Export project', exact: true }).click());
    expect(results).toEqual([{ includeFonts: false, includeWorkspace: false }]);
    expect(getWorkbenchPreferences().exportIncludesWorkspace).toBe(false);

    await act(() => trigger.click());
    await expect.element(checkbox).not.toBeChecked();
  } finally {
    await act(() => patchWorkbenchPreferences({ exportIncludesWorkspace: true }));
  }
});

it('exports again from a menu without the closing menu dismissing the dialog', async () => {
  await render(<MenuHarness />);
  // The first request loads the dialog module; later ones mount it at once, while the menu is still leaving.
  for (const attempt of [1, 2, 3]) {
    await act(() => page.getByRole('button', { name: 'Project actions', exact: true }).click());
    await act(() => page.getByRole('menuitem', { name: 'Export…', exact: true }).click());
    await settleAnimations();
    await expect.element(page.getByRole('dialog')).toBeVisible();
    expect(results).toHaveLength(attempt - 1);
    await act(() => page.getByRole('button', { name: 'Export project', exact: true }).click());
    await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
  }
  expect(results).toEqual(Array.from({ length: 3 }, () => ({ includeFonts: false, includeWorkspace: true })));
});

it('cancels a pending choice when its account goes away', async () => {
  await render();
  await act(() => page.getByRole('button', { name: 'Export', exact: true }).click());
  await expect.element(page.getByRole('dialog')).toBeVisible();
  await act(() => accountLifecycle.activate('another-account'));
  expect(results).toEqual([null]);
  await expect.element(page.getByRole('dialog')).not.toBeInTheDocument();
});

it('animates the dialog out instead of unmounting it when the choice settles', async () => {
  await render();
  await act(() => page.getByRole('button', { name: 'Export', exact: true }).click());
  await expect.poll(() => document.querySelector('[role="dialog"]')?.getAttribute('data-state')).toBe('open');
  const dialog = document.querySelector('[role="dialog"]')!;

  const frames = await recordDialogExit(dialog, async () => {
    await act(() => page.getByRole('button', { name: 'Cancel', exact: true }).click());
    expect(results).toEqual([null]);
    // Workbench hotkeys resume at close, not after the exit animation.
    expect(isModalPresent()).toBe(false);
  });

  // An unmounted dialog never reaches its closed state, so it cannot animate out; a retained one does, then leaves.
  expect(closingFrames(frames)).not.toHaveLength(0);
  await expect.poll(() => document.querySelector('[role="dialog"]')).toBeNull();
  expect(results).toEqual([null]);
});