Files
nexu-io-open-design/apps/web/tests/components/DesignKitView.test.tsx
Tom Huang ca89845d03 feat(brands): surface the draft design system live and browse images in a lightbox (#4777)
* feat(brand-extraction): enhance programmatic extraction with reconciliation and UI improvements

- Introduced `reconcileProgrammaticExtractionTranscript` to manage the state of brand extraction transcripts, ensuring accurate status updates during extraction processes.
- Updated the `cancel-extraction` route to handle asynchronous operations, allowing for better user feedback and immediate reconciliation of extraction states.
- Enhanced the `startBrandExtraction` function to support draft design system creation, ensuring that users can see their systems immediately, even if extraction fails or is stopped.
- Improved error handling and logging for reconciliation processes, providing clearer insights into failures during brand extraction.
- Added tests to validate the new reconciliation logic and ensure that the extraction process behaves as expected under various scenarios.

These changes improve the overall user experience by providing more robust handling of brand extraction states and enhancing the visibility of the extraction process.

* feat(brand-extraction): enhance brand preview rendering and UI feedback

- Added functionality to render brand previews into projects when a draft is stopped, improving user experience by providing immediate visual feedback.
- Updated the `startBrandExtraction` function to include metadata for design system IDs and statuses, ensuring accurate tracking of brand extraction states.
- Enhanced the `renderBrandPreviewIntoProject` function to support new status types, including 'draft', allowing for better representation of brand states.
- Introduced new localization strings for draft-related messages, improving clarity for users during the brand extraction process.
- Added tests to validate the new preview rendering and status handling, ensuring robustness in the brand extraction workflow.

These changes improve the overall user experience by providing clearer feedback and enhancing the visibility of brand extraction processes.

* feat(design-kit): browse design-system images in a lightbox carousel

The image-preview lightbox showed a single static image with no way to move
between samples. Replace the single-image state with an index into the
visible, non-broken samples so the modal becomes a carousel: prev/next
chevrons, an "N / total" counter, ArrowLeft/ArrowRight keys, and wrap-around.
Broken tiles are filtered once through a shared lightboxItems memo so the
gallery and lightbox indices stay aligned with the delete handler.

* feat(brands): reveal the draft design system the moment extraction starts

A brand extraction pre-creates a draft `user:` design system, but the project
view only rendered it once the registry summary had refreshed, leaving the
Design System tab empty for the whole extraction. Build a fallback summary
from project metadata so the draft renders immediately, auto-open the Design
System tab when extraction begins or is cancelled, and hydrate the freshly
created project with its brand metadata. Draft pre-create now records the
source URL in provenance and fails loudly instead of swallowing the error.

Because ProjectView imports DESIGN_SYSTEM_TAB at module scope, every
FileWorkspace test mock must export the constant.

* fix(design-system-picker): restore fullscreen preview styles dropped in routines.css reorg

The brand-extraction routines.css reorganization accidentally removed the
`.project-ds-picker-fullscreen` rule block, its `project-ds-picker-fullscreen-in`
keyframes, and its responsive overrides. The modal-window drag guard and two
style specs still depend on those rules (the fullscreen design-system preview
must stay above modal chrome), so they went red. Restore the block verbatim to
match main.

* feat(brand-extraction): add continue extraction functionality for incomplete brands

- Introduced a new API endpoint to restart the deterministic programmatic extraction for existing brands without creating duplicates.
- Implemented a tracking mechanism for ongoing extractions to manage their state effectively.
- Enhanced the UI components to support the new continue extraction action, including loading states and callbacks.
- Updated relevant tests to ensure the new functionality works as expected and integrates smoothly with existing workflows.

These changes improve the user experience by allowing users to resume brand extractions seamlessly, enhancing the overall efficiency of the brand management process.

* feat(skills): integrate skill management into the application

- Added a new SkillDetailsModal component to display detailed information about skills.
- Enhanced the ChatComposer and HomeHero components to support skill selection and details viewing.
- Updated the ComposerPlusMenu to include a skills submenu, allowing users to search and pick skills.
- Implemented functionality to handle skill details in various components, improving user interaction with skills.
- Refactored existing components to accommodate skill-related features, ensuring a cohesive user experience.

These changes enhance the application's capabilities by providing users with better access to skill information and management, streamlining workflows involving skills.

* feat(brand-extraction): improve brand assistant message handling and UI feedback

- Enhanced the AssistantMessage component to better manage events and display content, ensuring that messages are rendered correctly based on their content and events.
- Updated the ChatPane component to hide empty brand assistant messages and improve the visibility of relevant content, enhancing user experience during brand extraction processes.
- Introduced new utility functions to determine the visibility of brand assistant events and content, streamlining the logic for displaying messages.
- Refactored the ProjectView component to handle brand browser assist confirmations more effectively, ensuring that the UI responds appropriately to user interactions.
- Added tests to validate the new message handling logic and ensure that brand extraction messages are displayed correctly.

These changes enhance the overall user experience by providing clearer feedback and improving the management of brand assistant messages during extraction workflows.

* fix(brands): address browser assist review blockers

* fix(web): restore new project modal entrypoints

* fix(web): switch to replacement brand retry conversations

* fix(web): restore skill-change preview invalidation

* fix(brand): harden retry completion flow

* fix(brand): close extraction lifecycle races

* test(e2e): wait for privacy banner dismissal

* fix(brand): guard retry startup races

* fix(brand): isolate extraction retry attempts

* fix(design-systems): clean up partial draft creation

* fix(brands): let stop supersede stalled transcript

* fix(brands): fail thin browser html retries

* fix(brands): preserve stopped html retries

* fix(brands): reject off-path browser retries

* fix(brands): expose deterministic retry in cli

* fix(brands): serialize cancel with finalization

* fix(brands): bound cancel settlement wait

* fix(brands): bound retry takeover waits

* refactor(next-step-actions): replace titles with localized keys and update related prompts

* fix(brands): retry after browser read failures

* fix(brands): accept canonical browser redirects

* fix(brands): reset retry assist stall timer

* test(web): align picker compact preview assertions

* fix(brands): harden design kit cleanup paths

* test(e2e): stabilize AMR runtime recovery checks

* feat(brands): enhance brand extraction from post-wall pages

- Introduced `browserHarvestIsUnusable` function to determine if a harvested page lacks usable brand signals, allowing for more permissive extraction from content-rich pages that may embed anti-bot widgets.
- Updated `extractBrandFromHtml` to utilize the new function, ensuring that valid post-wall pages are processed correctly.
- Enhanced `isChallengePage` to differentiate between genuine content-rich pages and bot protection interstitials, improving the accuracy of brand extraction.
- Added tests to validate the new behavior, ensuring that pages with minimal color palettes or embedded widgets are handled appropriately.

* feat(brands): improve handling of recoverable extraction states

- Refactored brand extraction logic to maintain a `needs_input` status for recoverable scenarios, such as blocked pages or mid-load content, instead of marking them as `failed`.
- Updated related functions and routes to reflect this change, ensuring that the user interface presents a calm, retryable state rather than a terminal failure.
- Enhanced tests to validate the new behavior, confirming that the system correctly identifies and manages recoverable extraction attempts.

* feat(projects): add design-system project creation from existing projects

- Implemented a new command `od project create-design-system` to duplicate a regular project as a design-system workspace, including a prompt for design-system generation.
- Enhanced the API to support the creation of design-system projects, ensuring proper metadata and file copying from the source project.
- Added a detailed prompt structure for the design-system generation process, outlining requirements and expected outputs.
- Introduced tests to validate the new functionality, ensuring that design-system projects are created correctly with the appropriate context and files.
- Updated the UI components to integrate the new design-system creation functionality, allowing users to initiate the process seamlessly.

* feat(projects): add project duplication workflow

* fix(brand): keep browser assist recovery retryable

* fix(plugins): roll back failed template duplicates

* feat(brand): enhance browser assist functionality and improve user guidance

- Introduced a new `brandBrowserAssistOdCard` function to generate browser assist cards for better user interaction.
- Updated the content structure in `reconcileProgrammaticExtractionTranscript` to include browser assist cards when applicable.
- Enhanced user guidance in error messages for stalled and stopped extraction processes, providing clearer instructions for recovery actions.
- Added tests to ensure the new browser assist card functionality is correctly integrated and displayed in the chat interface.
- Improved localization for various user prompts and messages related to browser assist actions.

* feat(design-browser): enhance design file handling and user notifications

- Added support for opening design files directly from the status message in the DesignBrowserPanel.
- Introduced a new `actionTarget` property to differentiate between design files and regular files in status messages.
- Implemented a `stopLoading` function to halt page loading when necessary, improving user experience during snapshot captures.
- Updated localization files to include new status messages and project type labels.
- Enhanced toast notifications for browser snapshots with improved styling and functionality.
- Added tests to ensure new features work as expected and do not interfere with existing functionality.

* feat(app): implement design system project creation with preset prompts

- Updated project creation logic to route through the default design router, ensuring user interaction prompts for design system selection.
- Introduced a new localization key for the design system creation prompt, enhancing user guidance.
- Adjusted plugin ID to avoid assumptions about prototypes, improving the flexibility of project creation.
- Updated tests to reflect changes in project creation behavior and ensure correct routing and prompt handling.

* feat(chat): update icon sizes and implement draft persistence in HomeView

- Increased icon sizes in ChatComposer from 13px to 16px for better visibility.
- Added localStorage persistence for the Home composer prompt and design system selection to retain user input across tab switches.
- Implemented functions to read and write drafts to localStorage, ensuring a seamless user experience.
- Cleared drafts upon run creation to prevent reappearance of previous inputs.
- Enhanced Toast component to handle auto-dismissal correctly, even with changing parent components.

* fix(pr): address review blockers

* fix(web): preserve authoring prompt confirmation

* test(daemon): cover project CLI copy commands

* fix(web): surface skill detail load failures
2026-06-30 13:22:29 +00:00

477 lines
17 KiB
TypeScript

// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { DesignKitView } from '../../src/components/DesignKitView';
import { PreviewModal } from '../../src/components/PreviewModal';
import { I18nProvider } from '../../src/i18n';
import type { DesignKit } from '../../src/runtime/design-kit';
function previewKit(): DesignKit {
return {
designSystemId: 'user:preview-kit',
name: 'Preview Kit',
editable: true,
canUpload: false,
logoSrc: null,
logoAlternates: [],
colors: [{ role: 'Primary', name: 'Primary', hex: '#123456', usage: 'Primary actions' }],
typography: {
display: { family: 'Inter', fallbacks: [], weights: [700] },
body: { family: 'Inter', fallbacks: [], weights: [400] },
},
fonts: [],
system: {
kitUrl: '/raw/projects/preview/system/kit.html',
},
assets: [{
kind: 'landing',
label: 'Landing page',
url: '/raw/projects/preview/system/artifacts/landing.html',
}],
showcaseHtml: '<main><a target="_blank" href="/">Open</a></main>',
};
}
afterEach(() => {
cleanup();
vi.useRealTimers();
});
describe('DesignKitView iframe sandboxing', () => {
it('does not let generated kit previews escape the iframe sandbox', () => {
const { container } = render(
<I18nProvider initial="en">
<DesignKitView kit={previewKit()} />
</I18nProvider>,
);
const iframes = Array.from(container.querySelectorAll('iframe'));
expect(iframes.length).toBeGreaterThan(0);
for (const iframe of iframes) {
expect(iframe.getAttribute('sandbox')).toBe('allow-scripts allow-popups');
}
expect(container.innerHTML).not.toContain('allow-popups-to-escape-sandbox');
expect(container.innerHTML).not.toContain('allow-same-origin');
});
it('renders new kit actions with the active non-English locale', () => {
const kit = { ...previewKit(), canUpload: true };
render(
<I18nProvider initial="zh-CN">
<DesignKitView
kit={kit}
designMd={{
body: '# Preview Kit',
onSave: async () => {},
saving: false,
}}
onUploadModule={() => {}}
onRefresh={() => {}}
/>
</I18nProvider>,
);
expect(screen.getAllByTitle('复制 DESIGN.md').length).toBeGreaterThan(0);
expect(screen.getByTitle('添加字体文件')).toBeTruthy();
expect(screen.getByTitle('复制字体排版段落')).toBeTruthy();
expect(screen.getByTitle('刷新')).toBeTruthy();
expect(screen.queryByText('Add font file')).toBeNull();
expect(screen.queryByText('Copy Typography section')).toBeNull();
expect(screen.queryByText('Copy DESIGN.md')).toBeNull();
});
it('edits only the selected DESIGN.md module section', async () => {
const onSave = vi.fn().mockResolvedValue(undefined);
render(
<I18nProvider initial="en">
<DesignKitView
kit={previewKit()}
designMd={{
body: [
'# Preview Kit',
'',
'The system overview.',
'',
'## Color Palette',
'',
'| Role | Name | Hex | Usage |',
'| --- | --- | --- | --- |',
'| primary | Primary | `#123456` | Primary actions |',
'',
'## Voice & Tone',
'',
'- Direct and clear.',
].join('\n'),
onSave,
saving: false,
}}
/>
</I18nProvider>,
);
fireEvent.click(screen.getByTitle('Edit Palette section'));
const textarea = screen.getByRole('textbox', { name: 'Palette DESIGN.md section' }) as HTMLTextAreaElement;
expect(textarea.value).toContain('## Color Palette');
expect(textarea.value).not.toContain('## Voice & Tone');
fireEvent.change(textarea, {
target: {
value: [
'## Color Palette',
'',
'| Role | Name | Hex | Usage |',
'| --- | --- | --- | --- |',
'| primary | Primary | `#FF6A3D` | Primary actions |',
].join('\n'),
},
});
fireEvent.click(screen.getByRole('button', { name: 'Save module' }));
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
const saved = onSave.mock.calls[0]?.[0] as string;
expect(saved).toContain('# Preview Kit');
expect(saved).toContain('## Voice & Tone');
expect(saved).toContain('`#FF6A3D`');
expect(saved).not.toContain('`#123456`');
});
it('keeps upload, full-system preview, and shortcut help out of the sticky more menu', () => {
const baseKit = previewKit();
const kit = {
...baseKit,
canUpload: true,
system: {
kitUrl: baseKit.system!.kitUrl,
kitDarkUrl: baseKit.system?.kitDarkUrl,
tokensUrl: baseKit.system?.tokensUrl,
indexUrl: '/raw/projects/preview/system/index.html',
},
};
render(
<I18nProvider initial="en">
<DesignKitView
kit={kit}
stickyHeader
designMd={{
body: '# Preview Kit',
onSave: async () => {},
saving: false,
}}
onUploadModule={() => {}}
onRefresh={() => {}}
/>
</I18nProvider>,
);
expect(screen.queryByTestId('design-kit-shortcuts-hint')).toBeNull();
fireEvent.click(screen.getByTestId('design-kit-more-actions'));
expect(screen.getByRole('menuitem', { name: 'Edit DESIGN.md' })).toBeTruthy();
expect(screen.getByRole('menuitem', { name: 'Copy DESIGN.md' })).toBeTruthy();
expect(screen.queryByRole('menuitem', { name: 'Upload MD' })).toBeNull();
expect(screen.queryByRole('menuitem', { name: 'Open full system' })).toBeNull();
});
it('renders sticky header action loading state in the overflow menu', () => {
render(
<I18nProvider initial="en">
<DesignKitView
kit={previewKit()}
stickyHeader
headerMenuActions={[
{
id: 'refresh',
label: 'Refresh',
icon: 'refresh',
onClick: () => {},
disabled: true,
loading: true,
},
]}
/>
</I18nProvider>,
);
fireEvent.click(screen.getByTestId('design-kit-more-actions'));
const refresh = screen.getByRole('menuitem', { name: 'Refresh' });
expect(refresh.getAttribute('aria-busy')).toBe('true');
expect((refresh as HTMLButtonElement).disabled).toBe(true);
});
it('reports clipboard success for DESIGN.md copy actions', async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText },
});
const onActionFeedback = vi.fn();
render(
<I18nProvider initial="en">
<DesignKitView
kit={previewKit()}
stickyHeader
designMd={{ body: '# Preview Kit' }}
onActionFeedback={onActionFeedback}
/>
</I18nProvider>,
);
fireEvent.click(screen.getByTestId('design-kit-more-actions'));
fireEvent.click(screen.getByRole('menuitem', { name: 'Copy DESIGN.md' }));
await waitFor(() => expect(writeText).toHaveBeenCalledWith('# Preview Kit'));
expect(onActionFeedback).toHaveBeenCalledWith('loading', 'Copy DESIGN.md...');
expect(onActionFeedback).toHaveBeenCalledWith('success', 'Copied!');
});
it('renders the embedded component kit without an Open full system action', () => {
const baseKit = previewKit();
const kit = {
...baseKit,
system: {
kitUrl: baseKit.system!.kitUrl,
indexUrl: '/raw/projects/preview/system/index.html',
},
};
const { container } = render(
<I18nProvider initial="en">
<DesignKitView kit={kit} />
</I18nProvider>,
);
expect(screen.queryByRole('button', { name: 'Open full system' })).toBeNull();
expect(container.querySelector('iframe[src="/raw/projects/preview/system/kit.html"]')).toBeTruthy();
});
it('opens the component kit on the light file before explicit dark selection', () => {
const baseKit = previewKit();
const kit = {
...baseKit,
system: {
kitUrl: baseKit.system!.kitUrl,
kitDarkUrl: '/raw/projects/preview/system/kit.dark.html',
},
};
const { container } = render(
<I18nProvider initial="en">
<DesignKitView kit={kit} />
</I18nProvider>,
);
expect(container.querySelector('iframe[src="/raw/projects/preview/system/kit.html"]')).toBeTruthy();
expect(container.querySelector('iframe[src="/raw/projects/preview/system/kit.dark.html"]')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Dark' }));
expect(container.querySelector('iframe[src="/raw/projects/preview/system/kit.dark.html"]')).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: 'Light' }));
expect(container.querySelector('iframe[src="/raw/projects/preview/system/kit.html"]')).toBeTruthy();
});
it('lets users browse design-system images inside the preview modal', () => {
const kit: DesignKit = {
...previewKit(),
imagery: {
style: '',
subjects: [],
treatment: '',
avoid: [],
samples: [
{ url: '/raw/projects/preview/imagery/hero.png', caption: 'Hero image', kind: 'hero' },
{ url: '/raw/projects/preview/imagery/detail.png', caption: 'Detail image', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-3.png', caption: 'Filler image 3', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-4.png', caption: 'Filler image 4', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-5.png', caption: 'Filler image 5', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-6.png', caption: 'Filler image 6', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-7.png', caption: 'Filler image 7', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-8.png', caption: 'Filler image 8', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/hidden.png', caption: 'Hidden image', kind: 'detail' },
],
},
};
render(
<I18nProvider initial="en">
<DesignKitView kit={kit} />
</I18nProvider>,
);
fireEvent.click(screen.getByRole('button', { name: 'Hero image' }));
let dialog = screen.getByRole('dialog', { name: 'Hero image' });
expect(within(dialog).getByRole('img', { name: 'Hero image' }).getAttribute('src')).toBe(
'/raw/projects/preview/imagery/hero.png',
);
expect(within(dialog).getByText('1 / 9')).toBeTruthy();
fireEvent.click(within(dialog).getByRole('button', { name: 'Previous' }));
dialog = screen.getByRole('dialog', { name: 'Hidden image' });
expect(within(dialog).getByRole('img', { name: 'Hidden image' }).getAttribute('src')).toBe(
'/raw/projects/preview/imagery/hidden.png',
);
expect(within(dialog).getByText('9 / 9')).toBeTruthy();
fireEvent.keyDown(document, { key: 'ArrowRight' });
dialog = screen.getByRole('dialog', { name: 'Hero image' });
expect(within(dialog).getByRole('img', { name: 'Hero image' }).getAttribute('src')).toBe(
'/raw/projects/preview/imagery/hero.png',
);
fireEvent.click(within(dialog).getByRole('button', { name: 'Next' }));
dialog = screen.getByRole('dialog', { name: 'Detail image' });
expect(within(dialog).getByRole('img', { name: 'Detail image' }).getAttribute('src')).toBe(
'/raw/projects/preview/imagery/detail.png',
);
expect(within(dialog).getByText('2 / 9')).toBeTruthy();
fireEvent.keyDown(document, { key: 'ArrowLeft' });
dialog = screen.getByRole('dialog', { name: 'Hero image' });
expect(within(dialog).getByRole('img', { name: 'Hero image' }).getAttribute('src')).toBe(
'/raw/projects/preview/imagery/hero.png',
);
});
it('skips a hidden gallery image when it fails after opening in the lightbox', async () => {
const kit: DesignKit = {
...previewKit(),
imagery: {
style: '',
subjects: [],
treatment: '',
avoid: [],
samples: [
{ url: '/raw/projects/preview/imagery/hero.png', caption: 'Hero image', kind: 'hero' },
{ url: '/raw/projects/preview/imagery/detail.png', caption: 'Detail image', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-3.png', caption: 'Filler image 3', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-4.png', caption: 'Filler image 4', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-5.png', caption: 'Filler image 5', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-6.png', caption: 'Filler image 6', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-7.png', caption: 'Filler image 7', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/filler-8.png', caption: 'Filler image 8', kind: 'detail' },
{ url: '/raw/projects/preview/imagery/hidden.png', caption: 'Hidden image', kind: 'detail' },
],
},
};
render(
<I18nProvider initial="en">
<DesignKitView kit={kit} />
</I18nProvider>,
);
expect(screen.queryByRole('button', { name: 'Hidden image' })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Hero image' }));
fireEvent.click(
within(screen.getByRole('dialog', { name: 'Hero image' })).getByRole('button', { name: 'Previous' }),
);
const hiddenDialog = screen.getByRole('dialog', { name: 'Hidden image' });
fireEvent.error(within(hiddenDialog).getByRole('img', { name: 'Hidden image' }));
await waitFor(() => {
expect(screen.queryByRole('dialog', { name: 'Hidden image' })).toBeNull();
expect(screen.getByRole('dialog', { name: 'Filler image 8' })).toBeTruthy();
});
const fallbackDialog = screen.getByRole('dialog', { name: 'Filler image 8' });
expect(within(fallbackDialog).getByRole('img', { name: 'Filler image 8' }).getAttribute('src')).toBe(
'/raw/projects/preview/imagery/filler-8.png',
);
expect(within(fallbackDialog).getByText('8 / 8')).toBeTruthy();
});
it('lets Escape close an image lightbox before the outer preview modal', () => {
const onClose = vi.fn();
const kit: DesignKit = {
...previewKit(),
imagery: {
style: '',
subjects: [],
treatment: '',
avoid: [],
samples: [
{ url: '/raw/projects/preview/imagery/hero.png', caption: 'Hero image', kind: 'hero' },
],
},
};
render(
<I18nProvider initial="en">
<PreviewModal
title="Preview Kit"
views={[{
id: 'kit',
label: 'Kit',
custom: <DesignKitView kit={kit} />,
}]}
exportTitleFor={() => 'preview-kit'}
onClose={onClose}
/>
</I18nProvider>,
);
fireEvent.click(screen.getByRole('button', { name: 'Hero image' }));
expect(screen.getByRole('dialog', { name: 'Hero image' })).toBeTruthy();
fireEvent.keyDown(document, { key: 'Escape' });
expect(onClose).not.toHaveBeenCalled();
expect(screen.queryByRole('dialog', { name: 'Hero image' })).toBeNull();
expect(screen.getByRole('dialog', { name: 'Preview Kit preview' })).toBeTruthy();
fireEvent.keyDown(document, { key: 'Escape' });
expect(onClose).toHaveBeenCalledTimes(1);
});
it('scrolls to Logo and reveals edit controls for edit focus requests', () => {
vi.useFakeTimers();
const scrollIntoView = vi.fn();
const originalScrollIntoView = HTMLElement.prototype.scrollIntoView;
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
configurable: true,
value: scrollIntoView,
});
const { container, unmount } = render(
<I18nProvider initial="en">
<DesignKitView
kit={previewKit()}
editFocusRequest={{ module: 'logo', nonce: 1 }}
/>
</I18nProvider>,
);
try {
const logoSection = container.querySelector<HTMLElement>('[data-testid="design-kit-logo-section"]');
if (!logoSection) throw new Error('Expected Logo section to render');
expect(logoSection.textContent).toContain(
'Edit Logo here. Hover this section to reveal controls.',
);
expect(scrollIntoView).toHaveBeenCalledWith({ block: 'center', behavior: 'smooth' });
} finally {
unmount();
vi.useRealTimers();
if (originalScrollIntoView) {
Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
configurable: true,
value: originalScrollIntoView,
});
} else {
delete (HTMLElement.prototype as { scrollIntoView?: unknown }).scrollIntoView;
}
}
});
});