Files
nexu-io-open-design/apps/web/tests/components/QuestionForm.test.tsx
Tom Huang 6be4e56544 feat(workspace): add plan mode and Excalidraw sketch flows (#4862)
* feat(daemon): add 'plan' session mode and update related functionality

- Introduced a new session mode 'plan' alongside existing 'design' and 'chat' modes, allowing for editable document creation.
- Updated various functions and interfaces to accommodate the new session mode, including normalization and usage in commands.
- Enhanced markdown rendering capabilities by integrating micromark and its GFM extension for improved markdown processing.
- Added new input types for question forms, expanding the range of user interactions.
- Updated UI components to reflect changes in session modes and ensure proper handling of next steps based on the current mode.

* feat(chat): integrate SessionModeToggle into ChatComposer and HomeHero

- Added SessionModeToggle component to both ChatComposer and HomeHero for improved session management.
- Updated HomeHero styles to accommodate the new mode switcher layout.
- Adjusted countdown timer in QuestionsPanel to extend the skip countdown from 120 seconds to 10 minutes, enhancing user experience.
- Added tests to ensure the countdown functionality works as expected.

* feat(FileViewer): implement synchronized scrolling for Markdown editor and preview

- Added functionality to synchronize scrolling between the Markdown editor and preview panes.
- Introduced new types and utility functions for managing scroll behavior.
- Enhanced the MarkdownViewer component to handle scroll events and maintain scroll position across different modes.
- Updated the component's state management to accommodate the new scrolling features.

* feat(excalidraw): integrate Excalidraw into the project

- Added @excalidraw/excalidraw as a dependency in package.json.
- Updated vitest configuration to include an alias for Excalidraw.
- Imported Excalidraw CSS in the layout component for styling.
- Modified AssistantMessage component to handle optional projectId.
- Enhanced FileOpsSummary to display delete operations.
- Implemented new Excalidraw scene management in SketchEditor and FileWorkspace components.
- Updated MarkdownViewer to support file mentions and improved file handling.
- Refactored various components to accommodate Excalidraw integration and ensure compatibility with existing features.

* feat(files): improve sketch and file handoff flows

* test: align post-merge expectations

* chore(nix): refresh pnpm deps hash

* fix(workspace): stabilize sketch persistence and ci checks

* fix(workspace): address review blockers in editable files

* fix(workspace): persist cleared sketch scenes

* test(workspace): type sketch editor mock scene

* fix(workspace): serialize sketch autosaves

* fix(workspace): keep sketch save revisions current

* test(e2e): stabilize project workspace smoke flows

* fix(analytics): preserve plan mode for BYOK runs

* test(e2e): stabilize new project rail interactions

* fix(files): stop bash delete parsing at shell operators

* test(e2e): stabilize ui cold-start suites

* fix(viewer): preserve absolute markdown image sources

* feat(workspace): preload sketches and enhance markdown save options

- Added functionality to preload persisted sketches before opening the tab.
- Introduced new MarkdownSaveOptions type to manage save behavior.
- Updated saveMarkdownText to handle options for refreshing files and showing saving state.
- Enhanced FileViewer to maintain focus and selection during metadata refresh.
- Implemented a Toast component for user feedback on save and export actions.

* fix(web): stabilize markdown and sketch editor polish

* fix(web): finish sketch editor merge resolution

* chore(nix): refresh pnpm deps hash

* fix(plan): bypass discovery and stabilize markdown sync

* fix(web): simplify scene retrieval in SketchEditor component

* feat(web): enhance markdown viewer with auto-save functionality

- Implemented passive auto-save status in the MarkdownViewer component, replacing the manual Save button with an auto-save indicator.
- Introduced new hooks and state management for tracking auto-save events and displaying the last saved time.
- Added support for synchronized scrolling between the markdown editor and preview.
- Created a new markdown-scroll-sync module to handle scroll synchronization logic.
- Updated localization files to include new strings for auto-save messages.
- Added a SketchEnginePrewarm component to optimize Excalidraw loading times.

* feat(web): enhance session mode toggle with cost indicators

- Added cost tiers for each session mode in the SessionModeToggle component, providing users with a visual representation of usage costs.
- Introduced a new ModeCostTag component to display cost information alongside session mode labels.
- Updated localization files to include new keys for cost labels and notes.
- Enhanced styling for cost indicators to improve user experience and clarity.
- Refactored EntryShell to open the new project modal instead of creating a blank project directly from the rail.
- Implemented a utility function in markdown-scroll-sync to check for vertical progression in block offsets.

* feat(web): add max height adjustment for session mode description card

- Introduced maxHeight prop to the ModeDescriptionCard component to control the height of the description card based on available space.
- Implemented useLayoutEffect in SessionModeToggle to dynamically calculate and set the maximum height of the description card, ensuring it does not overlap with the project tab bar.
- Updated tests to verify that session modes display their expected usage/cost correctly in the UI.
- Enhanced localization files to include new cost-related strings for various languages.

* feat(web): implement goBack function for improved navigation and update auto-open logic

- Added a new `goBack` function to handle in-app navigation, allowing users to return to the previous route instead of a hardcoded destination.
- Updated the `navigate` function to maintain history state for better back navigation.
- Refactored auto-open logic to prioritize produced artifacts, allowing markdown files to be opened alongside HTML files.
- Updated tests to cover new navigation behavior and artifact selection logic.
- Enhanced localization files to include new descriptions for workspace actions.

* refactor(web): remove create design system functionality and update design files panel actions

- Removed the `onCreateDesignSystem` prop and associated button from the DesignFilesPanel component.
- Updated the empty state actions to include a button for creating a new document via the `onPaste` function.
- Adjusted tests to reflect the removal of the design system creation action and ensure the new document button is functional.
- Enhanced the MarkdownViewer component by adding a placeholder for the text area and removing the header bar for a cleaner interface.
- Updated localization files to include a new placeholder string for the markdown editor.

* fix(web): restore markdown placeholder translations

* refactor(web): streamline MarkdownViewer and enhance localization

- Removed unnecessary state management and reload functionality from the MarkdownViewer component for improved performance.
- Added a placeholder text for the markdown editor in multiple localization files to enhance user guidance.
- Updated styles for the save state indicator in the viewer to improve visual clarity and alignment.
- Adjusted tests to reflect changes in the MarkdownViewer and ensure proper functionality.

* fix(web): adjust SketchEditor button size and remove shortcut hints

- Reduced the icon size in the SketchEditor component from 13 to 12 for better alignment.
- Updated the removeSketchMermaidShortcutHints function to also remove the submit shortcut hints from the dialog, enhancing the user interface by decluttering unnecessary elements.
- Adjusted tests to verify the absence of shortcut hints in the modal after updates.

* fix(web): address plan mode follow-up polish

* fix(web): align ci expectations after merge

* test(e2e): stabilize project workspace helpers

* test(e2e): scale settings visual timeout

* fix(prompts): lock ElevenLabs voice picker choices

* test(e2e): pin project workspace P0 worker

* test(e2e): use rail new project entry

* test(e2e): relax app restoration startup waits

* fix(web): limit markdown pipe escaping to tables

---------

Co-authored-by: open-design-bot[bot] <282769551+open-design-bot[bot]@users.noreply.github.com>
Co-authored-by: Amy <1184569493@qq.com>
2026-07-01 04:38:31 +00:00

349 lines
12 KiB
TypeScript

// @vitest-environment jsdom
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { QuestionFormView, parseSubmittedAnswers } from '../../src/components/QuestionForm';
import type { QuestionForm } from '../../src/artifacts/question-form';
const form: QuestionForm = {
id: 'discovery',
title: 'Quick brief',
questions: [
{
id: 'tone',
label: 'Visual tone (pick up to two)',
type: 'checkbox',
options: [
{ label: 'Editorial / magazine', value: 'Editorial / magazine' },
{ label: 'Modern minimal', value: 'Modern minimal' },
{ label: 'Soft gradients', value: 'Soft gradients' },
],
maxSelections: 2,
required: true,
},
],
};
const voiceForm: QuestionForm = {
id: 'elevenlabs-voice',
title: 'Choose an ElevenLabs voice',
description:
'Pick a voice by description. The selected answer will be the exact voice_id passed to the renderer.',
questions: [
{
id: 'voice',
label: 'Voice',
type: 'select',
required: true,
allowCustom: false,
placeholder: 'Choose a voice',
help: 'Select a voice description; the answer submits the matching Voice ID.',
options: [
{ label: 'Rachel — american · female', value: '21m00Tcm4TlvDq8ikWAM' },
{ label: 'Adam — american · male', value: 'pNInz6obpgDQGcFmaJgB' },
],
},
],
submitLabel: 'Use voice',
};
const richForm = {
id: 'discovery',
title: 'Quick brief',
questions: [
{
id: 'platform',
label: 'Primary surface',
type: 'radio',
required: true,
options: [
{ label: 'Responsive', value: 'Responsive' },
{
label: 'Mobile (iOS/Android)',
description: 'Phone-first app prototype',
value: 'mobile',
},
{
label: 'Desktop web',
description: 'Browser-first prototype',
value: 'Desktop web',
},
],
},
],
} as QuestionForm;
const checkboxObjectForm = {
id: 'discovery',
title: 'Quick brief',
questions: [
{
id: 'tone',
label: 'Visual tone',
type: 'checkbox',
required: true,
options: [
{ label: 'Editorial / magazine', value: 'editorial' },
{ label: 'Soft gradients', value: 'soft-gradients' },
{ label: 'Modern minimal', value: 'modern-minimal' },
],
},
],
} as QuestionForm;
const selectObjectForm = {
id: 'discovery',
title: 'Quick brief',
questions: [
{
id: 'platform',
label: 'Primary surface',
type: 'select',
required: true,
options: [
{ label: 'Mobile (iOS/Android)', value: 'mobile' },
{ label: 'Desktop web', value: 'desktop-web' },
],
},
],
} as QuestionForm;
describe('QuestionFormView', () => {
afterEach(() => cleanup());
it('updates locked answers when submitted history arrives after the initial render', () => {
const onSubmit = vi.fn();
const { container, rerender } = render(
<QuestionFormView form={form} interactive submittedAnswers={undefined} onSubmit={onSubmit} />,
);
expect(container.querySelectorAll('input[type="checkbox"]:checked')).toHaveLength(0);
rerender(
<QuestionFormView
form={form}
interactive={false}
submittedAnswers={{ tone: ['Editorial / magazine', 'Modern minimal'] }}
onSubmit={onSubmit}
/>,
);
expect(screen.getByText('answered')).toBeTruthy();
expect(container.querySelectorAll('input[type="checkbox"]:checked')).toHaveLength(2);
});
it('renders select options with labels and submits the selected voice id', () => {
const onSubmit = vi.fn();
const { container, rerender } = render(
<QuestionFormView form={voiceForm} interactive submittedAnswers={undefined} onSubmit={onSubmit} />,
);
const select = screen.getByRole('combobox') as HTMLSelectElement;
expect(container.querySelector('option[value="21m00Tcm4TlvDq8ikWAM"]')?.textContent).toBe(
'Rachel — american · female',
);
expect(screen.queryByLabelText('Custom answer')).toBeNull();
fireEvent.change(select, { target: { value: '21m00Tcm4TlvDq8ikWAM' } });
fireEvent.click(screen.getByRole('button', { name: 'Use voice' }));
expect(onSubmit).toHaveBeenCalledWith(
'[form answers — elevenlabs-voice]\n- Voice: Rachel — american · female [value: 21m00Tcm4TlvDq8ikWAM]',
{ voice: '21m00Tcm4TlvDq8ikWAM' },
);
rerender(
<QuestionFormView
form={voiceForm}
interactive={false}
submittedAnswers={{ voice: 'Rachel — american · female' }}
onSubmit={onSubmit}
/>,
);
expect((screen.getByRole('combobox') as HTMLSelectElement).value).toBe(
'21m00Tcm4TlvDq8ikWAM',
);
});
it('parses submitted object-option values from readable answer text', () => {
expect(
parseSubmittedAnswers(
richForm,
[
'[form answers - discovery]',
'- Primary surface: Mobile (iOS/Android) [value: mobile]',
].join('\n'),
),
).toEqual({ platform: 'mobile' });
});
it('renders radio object options and submits the readable label with stable value', () => {
const onSubmit = vi.fn();
render(<QuestionFormView form={richForm} interactive onSubmit={onSubmit} />);
expect(screen.getByText('Responsive')).toBeTruthy();
expect(screen.getByText('Mobile (iOS/Android)')).toBeTruthy();
expect(screen.getByText('Phone-first app prototype')).toBeTruthy();
expect(screen.getByText('Desktop web')).toBeTruthy();
fireEvent.click(screen.getByLabelText('Mobile (iOS/Android)'));
fireEvent.click(screen.getByRole('button', { name: 'Send answers' }));
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit.mock.calls[0]?.[0]).toContain(
'- Primary surface: Mobile (iOS/Android) [value: mobile]',
);
expect(onSubmit.mock.calls[0]?.[1]).toEqual({ platform: 'mobile' });
});
it('lets users override generated radio options with a custom answer', () => {
const onSubmit = vi.fn();
render(<QuestionFormView form={richForm} interactive onSubmit={onSubmit} />);
fireEvent.change(screen.getByLabelText('Custom answer'), {
target: { value: 'Wearable kiosk' },
});
fireEvent.click(screen.getByRole('button', { name: 'Send answers' }));
expect(onSubmit).toHaveBeenCalledWith(
expect.stringContaining('- Primary surface: Wearable kiosk'),
{ platform: 'Wearable kiosk' },
);
});
it('combines checkbox presets with custom user entries', () => {
const onSubmit = vi.fn();
render(<QuestionFormView form={checkboxObjectForm} interactive onSubmit={onSubmit} />);
fireEvent.click(screen.getByLabelText('Editorial / magazine'));
fireEvent.change(screen.getByLabelText('Custom answer'), {
target: { value: 'Neo-museum, Field notebook' },
});
fireEvent.click(screen.getByRole('button', { name: 'Send answers' }));
expect(onSubmit.mock.calls[0]?.[0]).toContain('Editorial / magazine [value: editorial]');
expect(onSubmit.mock.calls[0]?.[0]).toContain('Neo-museum');
expect(onSubmit.mock.calls[0]?.[0]).toContain('Field notebook');
expect(onSubmit.mock.calls[0]?.[1]).toEqual({
tone: ['editorial', 'Neo-museum', 'Field notebook'],
});
});
it('can hide custom choice input for exact machine-id pickers', () => {
const exactForm = {
...selectObjectForm,
questions: [{ ...selectObjectForm.questions[0], allowCustom: false }],
} as QuestionForm;
render(<QuestionFormView form={exactForm} interactive onSubmit={vi.fn()} />);
expect(screen.queryByLabelText('Custom answer')).toBeNull();
});
it('submits required checkbox object options with stable values', () => {
const onSubmit = vi.fn();
const { container } = render(
<QuestionFormView form={checkboxObjectForm} interactive onSubmit={onSubmit} />,
);
const submit = screen.getByRole('button', { name: 'Send answers' });
// Required field unanswered → submit stays disabled (regression guard:
// the Questions-tab refactor must not make required fields optional on the
// standard submit path).
expect((submit as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(screen.getByLabelText('Editorial / magazine'));
fireEvent.click(screen.getByLabelText('Soft gradients'));
expect(container.querySelectorAll('input[type="checkbox"]:checked')).toHaveLength(2);
expect((submit as HTMLButtonElement).disabled).toBe(false);
fireEvent.click(submit);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit.mock.calls[0]?.[0]).toContain('Editorial / magazine [value: editorial]');
expect(onSubmit.mock.calls[0]?.[0]).toContain('Soft gradients [value: soft-gradients]');
expect(onSubmit.mock.calls[0]?.[1]).toEqual({
tone: ['editorial', 'soft-gradients'],
});
});
it('marks required fields with the inline indicator even when the footer is hidden', () => {
// Panel path (Questions tab): hideInternalSubmit hides the form footer, so
// the inline "*" next to a required label is the only per-field cue that a
// field is mandatory. A mixed required/optional form must still advertise
// which fields block the disabled Continue button.
const mixedForm = {
id: 'discovery',
title: 'Quick brief',
questions: [
{ id: 'taskType', label: 'Task type', type: 'text', required: true },
{ id: 'notes', label: 'Notes', type: 'text' },
],
} as QuestionForm;
const onSubmit = vi.fn();
const { container } = render(
<QuestionFormView form={mixedForm} interactive hideInternalSubmit onSubmit={onSubmit} />,
);
const fields = container.querySelectorAll('.qf-field');
const requiredField = fields[0]!;
const optionalField = fields[1]!;
expect(requiredField.querySelector('.qf-required')?.textContent).toBe('*');
expect(optionalField.querySelector('.qf-required')).toBeNull();
});
it('submits required select object options with stable values', () => {
const onSubmit = vi.fn();
const { container } = render(
<QuestionFormView form={selectObjectForm} interactive onSubmit={onSubmit} />,
);
const submit = screen.getByRole('button', { name: 'Send answers' });
// Required select unanswered → submit stays disabled (regression guard).
expect((submit as HTMLButtonElement).disabled).toBe(true);
const select = container.querySelector('select');
if (!select) throw new Error('expected select control');
fireEvent.change(select, { target: { value: 'mobile' } });
expect((submit as HTMLButtonElement).disabled).toBe(false);
fireEvent.click(submit);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit.mock.calls[0]?.[0]).toContain(
'- Primary surface: Mobile (iOS/Android) [value: mobile]',
);
expect(onSubmit.mock.calls[0]?.[1]).toEqual({ platform: 'mobile' });
});
it('submits native defaults for required color and defaultless range controls', () => {
const nativeDefaultsForm = {
id: 'native-defaults',
title: 'Native defaults',
questions: [
{ id: 'accent', label: 'Accent color', type: 'color', required: true },
{ id: 'weight', label: 'Weight', type: 'range', required: true, max: 10 },
],
} as QuestionForm;
const onSubmit = vi.fn();
render(<QuestionFormView form={nativeDefaultsForm} interactive onSubmit={onSubmit} />);
const submit = screen.getByRole('button', { name: 'Send answers' }) as HTMLButtonElement;
expect(submit.disabled).toBe(false);
fireEvent.click(submit);
expect(onSubmit).toHaveBeenCalledWith(
[
'[form answers — native-defaults]',
'- Accent color: #000000',
'- Weight: 0',
].join('\n'),
{ accent: '#000000', weight: '0' },
);
});
});