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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
import type { PromptTemplateSnapshot } from '@features/generation/core/promptTemplates';
import type { PromptTemplateCatalog } from '@features/generation/ui/usePromptTemplates';
import { ChakraProvider } from '@chakra-ui/react';
import { PromptTemplatesButton } from '@features/generation/ui/promptFields/PromptTemplatesButton';
import { setPendingPromptTemplateDraft } from '@features/generation/ui/promptTemplateDraftStore';
import { Tooltip } from '@platform/ui/Tooltip';
import { system } from '@theme/system';
import i18next from 'i18next';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
const catalog: PromptTemplateCatalog = {
create: vi.fn(),
defaultTemplates: [],
errorDetail: null,
exportCsv: vi.fn(),
importFile: vi.fn(),
isError: false,
isLoaded: true,
isLoading: false,
isRetrying: false,
personalTemplates: [],
remove: vi.fn(),
retry: vi.fn(),
sharedTemplates: [],
templates: [],
update: vi.fn(),
};
const usePromptTemplates = vi.fn((_options?: { isEnabled?: boolean }) => catalog);
const i18n = i18next.createInstance();
await i18n.use(initReactI18next).init({ fallbackLng: 'en', lng: 'en' });
vi.mock('@features/generation/ui/usePromptTemplates', async (importOriginal) => ({
...(await importOriginal<object>()),
usePromptTemplates: (options?: { isEnabled?: boolean }) => usePromptTemplates(options),
}));
vi.mock('@features/generation/ui/GenerationUiContext', async (importOriginal) => ({
...(await importOriginal<object>()),
useGenerationUi: () => ({
capabilities: { canManagePromptTemplates: false },
notifications: { error: vi.fn(), info: vi.fn(), reportError: vi.fn() },
}),
}));
vi.mock('@features/gallery/mediaSlot', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
GalleryMediaSlot: () => null,
}));
let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const applied: PromptTemplateSnapshot = {
id: 'user-1',
name: 'Cinematic',
negativePrompt: '',
positivePrompt: '{prompt}, cinematic',
};
const render = async (activeTemplate: PromptTemplateSnapshot | null, { withOtherTooltip = false } = {}) => {
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
await act(() => {
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
{withOtherTooltip ? (
<Tooltip content="Other tip">
<button type="button">other</button>
</Tooltip>
) : null}
<PromptTemplatesButton activeTemplate={activeTemplate} showSyntaxHighlighting={false} onApply={vi.fn()} />
</ChakraProvider>
</I18nextProvider>
);
});
};
const lastIsEnabled = (): boolean | undefined => usePromptTemplates.mock.calls.at(-1)?.[0]?.isEnabled;
beforeEach(() => {
usePromptTemplates.mockClear();
usePromptTemplates.mockReturnValue(catalog);
});
afterEach(async () => {
await act(() => root?.unmount());
host?.remove();
host = null;
root = null;
});
describe('the prompt templates button', () => {
it('opens the catalog lazily', async () => {
await render(null);
expect(lastIsEnabled()).toBe(false);
await act(async () => {
await userEvent.click(host!.querySelector('button')!);
});
expect(lastIsEnabled()).toBe(true);
expect(document.querySelector('[data-scope="popover"][data-part="content"]')).not.toBeNull();
});
it('keeps its tooltip shut while the panel is open, even when the pointer leaves and returns', async () => {
await render(null);
const trigger = host!.querySelector('button')!;
const openTooltip = () => document.querySelector('[data-scope="tooltip"][data-part="content"][data-state="open"]');
await userEvent.hover(trigger);
await expect.poll(openTooltip).not.toBeNull();
await act(async () => {
await userEvent.click(trigger);
});
await userEvent.unhover(trigger);
await userEvent.hover(trigger);
// Past the tooltip's 400ms open delay.
await new Promise((resolve) => {
setTimeout(resolve, 700);
});
expect(document.querySelector('[data-scope="popover"][data-part="content"]')).not.toBeNull();
expect(openTooltip()).toBeNull();
});
it('keeps its tooltip shut while the panel is open when the pointer arrives from another tooltip', async () => {
await render(null, { withOtherTooltip: true });
const [other, trigger] = [...host!.querySelectorAll('button')];
const openTooltips = () =>
[...document.querySelectorAll('[data-scope="tooltip"][data-part="content"][data-state="open"]')].map(
(tooltip) => tooltip.textContent
);
await act(async () => {
await userEvent.click(trigger!);
});
expect(document.querySelector('[data-scope="popover"][data-part="content"]')).not.toBeNull();
await userEvent.hover(other!);
await expect.poll(openTooltips).toEqual(['Other tip']);
await userEvent.hover(trigger!);
// Past the tooltip's 400ms open delay.
await new Promise((resolve) => {
setTimeout(resolve, 700);
});
expect(openTooltips()).toEqual([]);
});
it('dims the name and says so when the applied template is gone', async () => {
await render(applied);
const name = [...host!.querySelectorAll('span')].find((span) => span.textContent === 'Cinematic');
expect(lastIsEnabled()).toBe(true);
expect(name).toBeTruthy();
expect(getComputedStyle(name!).opacity).toBe('0.5');
});
it('is a labeled primary at rest, swapping the label for the applied name', async () => {
await render(null);
const restLabel = [...host!.querySelectorAll('span')].find(
(span) => span.textContent === 'widgets.generate.templatesButton'
);
expect(restLabel).toBeDefined();
await act(() => root?.unmount());
host?.remove();
await render(applied);
const name = [...host!.querySelectorAll('span')].find((span) => span.textContent === 'Cinematic');
expect(name).toBeDefined();
expect(
[...host!.querySelectorAll('span')].find((span) => span.textContent === 'widgets.generate.templatesButton')
).toBeUndefined();
});
it('leaves a template draft handed over from the gallery to the field that takes it', async () => {
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
await act(() => {
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
<div data-testid="upscale">
<PromptTemplatesButton
activeTemplate={null}
showSyntaxHighlighting={false}
takesPendingDraft={false}
onApply={vi.fn()}
/>
</div>
<div data-testid="generate">
<PromptTemplatesButton activeTemplate={null} showSyntaxHighlighting={false} onApply={vi.fn()} />
</div>
</ChakraProvider>
</I18nextProvider>
);
});
await act(() => setPendingPromptTemplateDraft({ negativePrompt: '', positivePrompt: 'a lighthouse' }));
const triggerState = (testId: string) =>
host!.querySelector(`[data-testid="${testId}"] button`)?.getAttribute('aria-expanded');
expect(triggerState('upscale')).toBe('false');
expect(triggerState('generate')).toBe('true');
});
it('says nothing while the catalog is unread', async () => {
usePromptTemplates.mockReturnValue({ ...catalog, isLoaded: false });
await render(applied);
const name = [...host!.querySelectorAll('span')].find((span) => span.textContent === 'Cinematic');
expect(getComputedStyle(name!).opacity).toBe('1');
usePromptTemplates.mockReturnValue(catalog);
});
});