diff --git a/README.md b/README.md index 8dabccb..c2c4b74 100644 --- a/README.md +++ b/README.md @@ -198,8 +198,10 @@ source snapshots without Git metadata. Dependencies, the database, environment file, backups, and benchmark reports stay under `TEST_ARTIFACTS` (default `/tmp/wippy-session-tests`). The database is backed up before each reset. Override `TEST_BACKUP_DIR` for another backup -location or `TEST_CONFIG` for an external runtime configuration. These targets -require Wippy, Bash, jq, and SQLite; set `WIPPY` when it is not on PATH. +location or `TEST_CONFIG` for an external runtime configuration. An external +configuration must also carry the `app.forms:fixtures:directory` override that +`make prepare` writes, or the form fixture suites cannot find their files. These +targets require Wippy, Bash, jq, and SQLite; set `WIPPY` when it is not on PATH. ## Session retirement @@ -629,24 +631,36 @@ Only `session:`-prefixed topics are relayed to clients. ## Session Forms -Session forms let an agent ask the user structured choice questions with the -`ask_user` tool and get the answer back as an ordinary user message. A form -is stored as a `wippy-component-tag-1.0` artifact (see Artifacts above) with -one extra metadata key, `meta.session_form`; no new SQL table is used. +Session forms let an agent ask the user structured questions in the chat and +get the answer back as an ordinary user message. A form is stored as a +`wippy-component-tag-1.0` artifact (see Artifacts above) with one extra +metadata key, `meta.session_form`; no new SQL table is used. ### Enable -Add the trait to an agent: +Add one of the two traits to an agent: ```yaml traits: + # Choice questions only. - id: wippy.session.forms:ask_user + # Or: choice questions and the standard fields. + # - id: wippy.session.forms:ask_user_fields ``` -The agent gets `ask_user` (create a form; ends the turn) and `read_form` -(read an earlier form's questions, or its answer record, by `form_id`). Every -agent, with or without the trait, gets a bounded index of the session's forms -injected into its prompt so it can find a form id without the trait. +| Trait | Tool it adds | Field types | +| --- | --- | --- | +| `wippy.session.forms:ask_user` | `ask_user` | `choice` | +| `wippy.session.forms:ask_user_fields` | `ask_user_fields` | `choice`, `text`, `textarea`, `number`, `email`, `date`, `checkbox` | + +The tool creates a form and ends the turn. Each tool's schema lists only its +own field types, and the server refuses any other type from it with +`unsupported_type`, so an agent with `ask_user` can never create a form with +standard fields. Both traits also add `read_form` (read an earlier form's +questions, or its answer record, by `form_id`). Attach one of them: the two +tools have different names, so an agent with both gets both tools and both +prompts. Every agent, with or without a trait, gets a bounded index of the +session's forms injected into its prompt so it can find a form id. ### API @@ -657,8 +671,13 @@ commits the accepted answer and its user message in one transaction, then wakes the owning session process; a missed wake-up is recovered from the stored row on the next session start. -V1 supports choice fields only: single selection, multiple selection, -optional/required, notes on a chosen option, and a free-text "Other" answer. +A form holds choice fields (single or multiple selection, notes on a chosen +option, a free-text "Other" answer) and standard fields: `text`, `textarea`, +`email`, `number`, `date` and `checkbox`, each optional or required. A form +with only choice fields is form version 1; a form with any standard field is +version 2, and an older `wippy-form` shows a "needs a newer version" notice +for it. The server checks every answer, including a text field's `pattern`, +which the browser never evaluates. ### Answers and steering @@ -676,7 +695,7 @@ that asks a form still ends there; steering sent during that turn starts the next turn. See [Session Forms (framework)](https://docs.wippy.ai/en/framework/session-forms) -for the full `ask_user` / `read_form` contract, the answer record shape, late +for the full `ask_user`, `ask_user_fields` and `read_form` contract, the answer record shape, late answers, and how an answer is admitted into the conversation, and [Session Forms (frontend)](https://docs.wippy.ai/en/frontend/micro-frontends/session-forms) for the `wippy-form` / `wippy-form-answers` components and the HTTP contract diff --git a/frontend/wippy-form-answers/vite.config.ts b/frontend/wippy-form-answers/vite.config.ts index 6d217a0..48570a1 100644 --- a/frontend/wippy-form-answers/vite.config.ts +++ b/frontend/wippy-form-answers/vite.config.ts @@ -6,6 +6,12 @@ export default defineConfig({ plugins: [ wippyComponentPlugin(), ], + // An inline PostCSS config stops Vite from searching parent folders, where a + // checkout nested in another project finds that project's Tailwind setup. + // The element's one rule needs no PostCSS plugin. + css: { + postcss: {}, + }, build: { target: 'esnext', // The npm build scripts pass `--outDir`, so the output path is not set here. diff --git a/frontend/wippy-form/README.md b/frontend/wippy-form/README.md index b75f179..594fc7e 100644 --- a/frontend/wippy-form/README.md +++ b/frontend/wippy-form/README.md @@ -1,17 +1,21 @@ # @wippy-session/wippy-form -The `` web component renders one Session `ask_user` form artifact as a question card and sends the answer back to the owning session through the Host's artifact-state API. Agents never write the tag. The Session `ask_user` tool creates it. +The `` web component renders one Session form artifact, as a question card or a fields form, and sends the answer back to the owning session through the Host's artifact-state API. Agents never write the tag. The Session `ask_user` and `ask_user_fields` tools create it. ## What it renders -A question card. A form with several questions shows one at a time, with a counter and a review step before sending. Each question supports per-answer notes and, when the definition allows it, an Other free-text row. After the answer is accepted, the card becomes a read-only summary. A definition with no fields shows an error message instead of a card. +A form of choice questions only (form version 1) renders as a question card. A form with several questions shows one at a time, with a counter and a review step before sending. Each question supports per-answer notes and, when the definition allows it, an Other free-text row. After the answer is accepted, the card becomes a read-only summary. See "Question card" below. + +A form with at least one standard field (`text`, `textarea`, `number`, `email`, `date`, `checkbox`), alone or mixed with choices (form version 2), renders as a fields form: one labelled control per field and a single Submit button (`ActiveForm` while open, `IdleForm` once answered, both built on `FieldShell` and `FormHeader`). A choice inside it is a plain radio group or checkbox group, with no per-option notes and no click-to-answer. See "Fields form" below. + +A form that cannot be answered here shows its questions as disabled controls under a message (`FormNotice`). A definition with no fields shows an error message instead of a form. ## Props | Prop (HTML attribute) | Type | Default | Description | | --- | --- | --- | --- | -| `form-version` | `number` | `1` | Form definition schema version. A value other than 1, from this prop or from the loaded state's `form_version`, disables the card and shows a "needs a newer version of the app" notice. | -| `definition` | `object` | `null` | The questions: `title`, optional `description`, and `fields`, each `{ id, type: "choice", label, description?, required, options: [{value, label, description?}], multiple, allow_other }`. Optional `submit_label` and `answered_message` are accepted and not shown. | +| `form-version` | `number` | `1` | Form definition schema version. 1 is a form of choices only and 2 is a form with at least one standard field; both render. A higher value, from this prop or from the loaded state's `form_version`, disables the form and shows a "needs a newer version of the app" notice. So does a field whose `type` this version does not know, so a question is never silently dropped. | +| `definition` | `object` | `null` | The questions: `title`, optional `description`, and `fields`. A field is `{ id, type, label, description?, required }` plus the keys of its type. A `choice` adds `options: [{value, label, description?}]`, `multiple` and `allow_other`, and "Fields form" lists the keys of the standard types. Optional `submit_label` is the fields form's Submit button text (the card does not show it), and optional `answered_message` is accepted and not shown. | | `state` | `string` | `"active"` | The lifecycle mirrored from the artifact: `"active"` while the form can be answered, `"idle"` once it was answered. A change of this prop reloads the form state from the Host. | ## Events @@ -27,7 +31,7 @@ The base element dispatches these events. They bubble and cross the shadow bound ## Answer shapes -A field's answer is one of three shapes, or an array of them for a multiple-choice field. They match the state API of the Session module. +A choice field's answer is one of three shapes, or an array of them for a multiple-choice field. They match the state API of the Session module. - A plain option value: `"backfill"`. - A chosen option with a note: `{ "value": "backfill", "note": "Regenerate the lockfile too." }`. A note that trims to blank sends the plain value. @@ -35,6 +39,16 @@ A field's answer is one of three shapes, or an array of them for a multiple-choi Notes are limited to 1,000 Unicode code points and Other text to 2,000. The types are in `src/lib/definition.ts` and the limits in `src/lib/answers.ts`. +A standard field's answer is one JSON scalar. The key is left out when an optional field is not answered: + +| Type | Answer sent | Notes | +| --- | --- | --- | +| `text`, `textarea` | string, exactly as typed | Inner and outer whitespace kept. A whitespace-only value is unanswered. Line breaks are LF | +| `email` | string, trimmed | Case kept | +| `number` | JSON number | Never a numeric string. A whole value is sent as an integer (`3.0` becomes `3`) | +| `date` | `"YYYY-MM-DD"` string | No timezone, not trimmed | +| `checkbox` | `true` or `false` | Always explicit: an optional box left unchecked sends `false` | + ## Styling API The card is styled through the tokens, parts, classes and host attributes below. Every value is a `--wippy-form-*` token with a semantic `--p-*` theme variable as its fallback, so a facade retint or a dark-mode flip restyles the card without edits here. A literal hex value is only a fallback for development without a theme. @@ -121,7 +135,7 @@ The component reflects these onto the `wippy-form` element, for styling only. | `card-state` | `loading`, `active`, `review`, `answered`, `unsupported` | Named `card-state` because `state` is an observed prop. `unsupported` outranks the others and covers an unrecognized form version and a Host without the artifact-state API. `loading` lasts until the first GET resolves | | `collapsed` | present or absent | Present while the active card is collapsed | -When the Host has no artifact-state API, the component shows the questions with their options disabled under a notice. The notice says the form was answered, when the `state` prop is `idle`, or that a newer Web Host is needed. Both point to the chat for an answer already sent. +When the Host has no artifact-state API, the component shows the questions as disabled controls under a notice. The notice says the form was answered, when the `state` prop is `idle`, or that a newer Web Host is needed. Both point to the chat for an answer already sent. ### Keyboard @@ -174,3 +188,124 @@ wippy-form::part(option-selected) { - The send buttons and the composer send buttons are PrimeVue defaults. They follow the theme's primary colour and not `--wippy-form-accent`, because a `.p-button` override would shadow the theme. - The note and Other textareas use the theme's `.p-textarea` colours, and no token exists for them. Their only local rule is `flex: 1 1 auto; min-width: 0` in `src/styles.css`, because the theme's input group rule does not grow a bare `Textarea`. + +--- + +## Fields form + +The renderer for a form that has at least one standard field (form version 2). Every field of the definition is one labelled control, in definition order, followed by one Submit button. It is built from `src/app/active-form.vue` (open), `src/app/idle-form.vue` (answered), `src/app/form-header.vue` (the title and description they share with `src/app/form-notice.vue`), `src/app/fields/*` (the fields) and `src/lib/answers.ts` with `src/lib/scalar-answers.ts` (the checks before sending). It follows the same styling contract as the question card: `--wippy-form-*` tokens, `part` names with `-` state parts and matching `w-form__` classes, host attributes. + +A form with only choices never reaches it (that is the question card). A form that mixes choices with standard fields renders its choices here as a radio group (one answer) or a checkbox group (several), without per-option notes. + +### Fields + +| Type | Control | What it adds | Draft held while editing | +| --- | --- | --- | --- | +| `text` | PrimeVue `InputText` | `type="text"`, `placeholder` | The typed text | +| `email` | `InputText` | `type="email"`, `inputmode="email"`, `autocomplete="off"` (an agent may ask for someone else's address, so the browser must not offer the user's own); no `placeholder` | The typed text | +| `number` | `InputText` | `type="text"`, `autocomplete="off"`, and an on-screen keyboard chosen by what can be typed (see "Number keyboard" below); not `InputNumber` (it clamps to min/max, rounds extra digits and strips the locale's group character); no `placeholder` | The typed text, judged by a strict parser: dot decimal, optional minus, no separators or exponent | +| `textarea` | `Textarea` (auto-resize, three rows) | `placeholder`; Enter adds a line and never submits | The typed text with its line breaks | +| `date` | `DatePicker`, `updateModelType="string"`, `dateFormat="yy-mm-dd"` | A calendar from its button, and on a touch screen also by tapping the box (not on focus); `min`/`max` grey out days; typing allowed | The text in the box, as typed. A date the picker reads from loose text (`2026-6-5`) is held as the full date (`2026-06-05`), and the box shows that once it is left. A year below 1000 is kept with four digits (`0999-05-15`) and a typed year below 100 is reported as typed (`0050-03-04`, which PrimeVue alone would read as 1950) | +| `checkbox` | `Checkbox` (binary) | The label is clickable | An explicit boolean | + +`placeholder` belongs to `text` and `textarea` only (the server refuses it on any other type, and the other controls ignore it). + +A definition `default` prefills the control; clearing an optional prefilled value sends nothing for that field. A checkbox starts unchecked (its only possible default is `false`). + +### Number keyboard + +A phone shows the on-screen keyboard its `inputmode` asks for, and the two digit keypads cannot type everything the parser accepts: `numeric` has no minus key and no separator, `decimal` has no minus key on iOS and shows the locale's own separator (a comma in many locales, which the dot-only parser rejects). So the field asks for a digit keypad only where it cannot lock the user out: + +| Field | `inputmode` | +| --- | --- | +| `integer: true` with `min` of 0 or more | `numeric` | +| Not `integer`, `min` of 0 or more, and the browser's locale writes decimals with a dot (`Intl.NumberFormat(undefined)`) | `decimal` | +| Anything else (no `min`, a negative `min`, or a fraction in a comma-decimal locale) | `text`, the full keyboard | + +Whatever the keyboard, the parser takes only a dot for decimals, and its message is "Enter a number, using a dot for decimals (for example 12 or -3.5)." + +### Client-side checks + +A convenience mirror of the server's rules, run on submit so an obvious mistake is named before a round trip. The Session state API stays the authority, and its 422 errors show on the same fields. Codes are the server's; messages never echo the value. `test/forms/fixtures/v2_conformance.json` is run through both implementations (`src/lib/conformance.test.ts` here). + +| Type | Checks (code) | +| --- | --- | +| all | Required: no non-whitespace content, no number, an unchecked checkbox (`required`) | +| `text`, `textarea` | Control characters, tab and line feed allowed in a textarea only (`invalid_text`); `min_length` (`too_short`); `max_length`, default 500 for text and 8,000 for a textarea, never above 2,000 and 8,000 (`too_long`), counted in code points. A text field's `pattern` is not checked here (see "Pattern" below) | +| `email` | ASCII address, one `@`, dot-atom local part up to 64, DNS-label domain with a dot, 254 in all (`invalid_email`) | +| `number` | Strict text (`invalid_number`); at most 1e12 in absolute value (`invalid_number`); `integer` (`not_integer`); `min`, `max` (`below_min`, `above_max`); `step` from `min`, else from 0, with exact decimal arithmetic and no tolerance (`not_on_step`) | +| `date` | A real calendar day written `YYYY-MM-DD`, years 0001 to 9999, not trimmed (`invalid_date`); `min`, `max` inclusive (`below_min`, `above_max`) | + +### Pattern: checked on submit by the server, never in the browser + +A `text` field may carry a `pattern` (a full-match expression). The component does not evaluate it. The pattern is written by the agent, and a browser regular-expression engine backtracks: an overlapping repeat such as `(a|a)*b` or `a*a*a*a*b` against a 2,000-character answer can freeze the user's tab, and the accepted pattern subset does not rule those out. The server checks the pattern with a linear-time engine (RE2), so it is the only place the pattern runs. A pattern counts at most 100 with every repeat written out (`form_pattern.MAX_EXPANDED`), which keeps that check to about 8 ms on a 2,000-character ASCII answer. A value that does not match is sent like any other, and the server answers `422` with `pattern_mismatch` under that field's id. The form shows it exactly like a client error: the message under the field, linked to the real input by `aria-describedby`, the field marked invalid (`aria-invalid`, the `field-invalid` part), focus on the first invalid field, and what the user typed kept in the box. Any other per-field code in a `422` is shown the same way, and `form_errors` appear under the fields. The only cost is one round trip for a pattern mistake, which the server's message names. `src/lib/scalar-answers.ts` builds no regular expression from a definition, and `src/lib/scalar-answers.test.ts` fails if that changes. + +### Tokens + +All the shared tokens of the question card apply to the root (`--wippy-form-font`, `-font-size`, `-small-size`, `-question-size`, `-question-weight` for the title, `-surface`, `-border`, `-radius`, `-padding`, `-text`, `-text-muted`, `-focus`). Three tokens are new: + +| Token | Default (as coded) | Used for | +| --- | --- | --- | +| `--wippy-form-field-gap` | 16px | Space between fields, and between the form's header, fields, errors and button | +| `--wippy-form-label-weight` | `500` | Field label weight | +| `--wippy-form-date-width` | `20rem` | Width of the date control, which is full width only when the form is narrower than that. The theme opens the calendar at least as wide as the control, so the calendar follows this width; set it larger to get a wider box and calendar | + +The inputs themselves are PrimeVue controls, so their surface, border and focus styling is the theme's (there are no input tokens, and no `.p-*` override). + +### Parts and classes + +Same convention as the question card: a state adds a part `-` and a class `w-form__--`. + +| Part | States | What it is | +| --- | --- | --- | +| `card`, `fields` | `answered` (the answered view), `unsupported` (a notice) on `card` | The whole form; the same element carries both parts and the `w-form` class | +| `fields-title` | | Form title | +| `form-description` | | The form's own description (shared with the card) | +| `notice` | | "Asked earlier" and offline lines (shared with the card) | +| `fields-error` | | Form-level errors from a 422 (also spoken in the status region, see "Accessibility and keyboard") | +| `field` | `required`, `invalid`, `readonly`, `disabled`, `group`, `inline` | One field. `group` is a choice (fieldset), `inline` is a checkbox | +| `field-label` | | The label (or the legend of a choice) | +| `field-marker` | | The "(required)" text, shown on an editable required field | +| `field-description` | | The field's own description | +| `field-control` | | Wrapper around the control | +| `field-row` | | The row of an editable checkbox: its control and its label side by side | +| `field-input` | `date` (on the date picker) | The PrimeVue control: the input, the textarea, the checkbox, the date picker. The `date` state is what `--wippy-form-date-width` bounds | +| `field-calendar` | | The date picker's calendar panel (class `w-form__field-calendar`). It opens in the theme plugin's overlay layer, not inside the form, so it is never clipped by the message around a short form; it carries the form's `w-theme-dark` or `w-theme-light` class, so it follows the theme. Its width follows the date control (see `--wippy-form-date-width`); no rule in this package overrides it | +| `field-error` | | The error list; linked to the control by `aria-describedby` | +| `field-value` | `empty` | The stored answer in the read-only view ("Skipped" when empty). Spaces and line breaks show as stored | +| `field-item` | | One chosen answer of a choice in the read-only view | +| `field-note` | | The note on a chosen option in the read-only view | +| `field-options` | | A choice's group of rows | +| `field-option` | `other` | One radio or checkbox row | +| `field-option-input`, `field-option-label`, `field-option-description` | | Pieces of a row | +| `field-other`, `field-other-input` | | The Other row's label and text box | +| `status` | | Delivery and answered-time lines in the read-only view (shared with the card) | +| `send` | `sending` (fields form only) | The Submit button (shared with the card). The `sending` state lasts while a send is in flight: the label reads "Sending…", a spinner icon turns beside it (still under `prefers-reduced-motion`), and the pointer shows `cursor: progress`. An offline form is blocked but not `sending` | + +### Host attributes + +`card-state` is reflected as for the card: `loading`, `active`, `answered`, `unsupported`. A fields form never reports `review` and has no `collapsed`. + +### Accessibility and keyboard + +- Every control has a label whose `for` points at the real input. The description and the error list are linked by `aria-describedby` on that input (for a checkbox or a date picker, whose wrapper would otherwise take the attribute, through the PrimeVue pass-through). A choice is a `fieldset` with a `legend`, described as a whole, and every radio or checkbox in it, and the Other text box, carries the same `aria-describedby` (the field description and the error list, so a screen reader that lands on one input reads the blank-Other message) and `aria-invalid` while the group is in error (a `group` role may not carry `aria-invalid`, so it sits on the inputs). A single choice adds a `radiogroup` role with `aria-required` around its radios; a multiple choice adds no role and no `aria-required`, because its fieldset already is the group and `aria-required` is not allowed on that role (the "(required)" text in the legend says it). `aria-invalid` and `aria-required` follow the state. +- The form is `novalidate`, so the browser's own bubble never replaces the form's error flow. A failed submit names each field, focuses the first invalid control, and announces "N questions need attention." in one polite status region. Only fields in error count as questions: a form-level error from a 422 is spoken as its own text after the count ("2 questions need attention. This form changed since you loaded it."), or alone when no field is in error. As the user fixes questions the text in that region is updated, once per fixed question and not once per key, and emptied when nothing is left. Errors carry no `role="alert"` of their own, and neither does the submit-failure message (a PrimeVue `Message`, which is `role="alert"` and `aria-live="assertive"` by default). Its role and live attributes are removed through the pass-through, so its text is shown with its Retry button and announced once, by the status region. Starting a send clears the previous server errors, as it does the banner. +- Submit stays focusable while a send is in flight or the browser is offline: it is `aria-disabled` and carries the theme's `p-disabled` marker instead of the `disabled` attribute, and the form ignores a submit then. The fields are disabled during a send, so a box that had focus loses it, and a failed send that left no focus gives it to Submit. Focus on another control of the page is left alone. +- A send in flight shows on Submit itself: the label becomes "Sending…" (and returns to the form's `submit_label`, or "Submit", when the send fails), with a Tabler `loader-2` icon, hidden from screen readers, that spins with Tailwind's `animate-spin` and stops under `motion-reduce`. The changed label is what a screen reader reads from the focused button. The status region says "Sending your answers." only when a send runs longer than 2 seconds, and drops that line when the send ends, so a fast send is announced once. The `p-disabled` marker makes the button inert to the pointer, so `.w-form .w-form__send--sending` gives pointer events back to show `cursor: progress`; a click is still ignored by the form. +- Retry checks the answers as Submit does, so a value edited into something invalid after a failed send is named on its field and not left out of the answer. +- The status region is emptied when a send starts, so a failure with the same text as the last one is announced again. +- Required is text ("(required)"), never colour alone. A read-only answer is plain selectable text. +- Enter in a single-line field submits the form; Enter in a textarea adds a line; Space toggles a checkbox. +- Date: type `YYYY-MM-DD` one key at a time, press the calendar button or ArrowDown to open the calendar, Tab and Shift+Tab move inside it, Escape closes it. The box always shows what the user typed, including after an error appears and after the box is left. Text the picker cannot parse is never dropped or replaced by the last good date: it stays in the box and is named on submit (`invalid_date`, or `below_min` / `above_max` for a well-formed date out of range). The calendar opens in the theme plugin's overlay layer inside the component's shadow root. On a touch screen PrimeVue sets `inputmode="none"` on the box (no keyboard), and the field does not open on focus, so a tap on the box opens the calendar when the primary pointer is coarse (`matchMedia('(pointer: coarse)')`, read at the tap) and the field is enabled; a click with a mouse and focus from a keyboard do not open it. Typing with an input method (IME composition) works: the box is written only with what the user typed. A state reload that hands over the same field leaves an open calendar on the month the user navigated to (`min` and `max` become a new `Date` only when their text changes). +- Date focus: when the calendar closes with focus still inside it (a day picked from the keyboard, or Escape), focus goes to the date box, also when PrimeVue's own delayed re-focus of its day cells has moved it into the calendar after the pick. Focus the user has already moved elsewhere (a click outside, Tab) is left where it is. +- How the date box keeps the typed text. PrimeVue's `DatePicker` box is uncontrolled: it follows only the last date the picker accepted, and Vue writes that date over the box on every re-render of the box (an error appearing, the form changing, a submit disabling the control), which would erase each key as it is typed. The field owns the box text and hands it to the box as its `value` through the picker's pass-through, so every render writes exactly what was typed (Vue skips a write that changes nothing, so the caret stays). The one thing PrimeVue still does on its own is reset the box to the last accepted date when it loses focus; the typed text is put back after that. + +### Known gaps + +- The error text and the "(required)" marker take `ERROR_TEXT_CLASS` from `src/lib/error-text.ts`, the theme's severity utilities the question card uses, and not `--wippy-form-danger`. The submit-failure message takes `ERROR_TEXT_CLASS`, or `WARN_TEXT_CLASS` when it can be retried, through `FormMessage`, as on the card. +- The unchecked checkbox and input edge contrast is the theme's, left to a theme-level fix. There is no local `.p-*` override. +- A `pattern` mistake is only reported after submit (by the server), not as the user types; see "Pattern" above. +- The calendar's day cells have no accessible name beyond the day number (PrimeVue's default); the panel itself is a dialog labelled "Choose Date". Not changed here. +- The theme (and PrimeVue's own alignment of an overlay) opens the calendar at least as wide as the date control. The date control is bounded to `--wippy-form-date-width` (20rem), so the calendar follows that width on its own. There is no override of the calendar and no `!important` in `styles.css` for it (`styles.test.ts` checks both). +- The calendar cannot show a year below 100: PrimeVue reads one as a two-digit year, so the calendar opens on 19xx or 20xx for such a date. The box and the saved answer keep the year as typed. +- In the Dark theme the textarea is darker than the single-line inputs. Both are the same PrimeVue components this form uses for the other fields; the difference is in the theme's own styles (`@wippy-fe/theme/primevue/textarea.css` uses `dark:bg-surface-950`, `inputtext.css` uses `dark:bg-surface-800`), so it is a theme-level change, not something to override here. diff --git a/frontend/wippy-form/package-lock.json b/frontend/wippy-form/package-lock.json index 9406e83..9f03da8 100644 --- a/frontend/wippy-form/package-lock.json +++ b/frontend/wippy-form/package-lock.json @@ -15,6 +15,8 @@ }, "devDependencies": { "@iconify/vue": "^5.0.5", + "@testing-library/dom": "^10.4.2", + "@testing-library/user-event": "^14.6.7", "@typescript-eslint/eslint-plugin": "^7.0.0", "@typescript-eslint/parser": "^7.0.0", "@vitejs/plugin-vue": "^5.0.0", @@ -71,6 +73,21 @@ "lru-cache": "^10.4.3" } }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/helper-string-parser": { "version": "7.29.13", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.13.tgz", @@ -104,6 +121,16 @@ "node": ">=6.0.0" } }, + "node_modules/@babel/runtime": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.13.tgz", + "integrity": "sha512-v+oN26xP4YIlQsbQ/CbTH1WG5m/l/DjKKZNy/Kp3f/AFvbgt7Em/D0FeMM3O2hX0YzeN2M16W8lOpyhIkfCBcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, "node_modules/@babel/types": { "version": "7.29.11", "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.11.tgz", @@ -1354,6 +1381,47 @@ "dev": true, "license": "MIT" }, + "node_modules/@testing-library/dom": { + "version": "10.4.2", + "resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-10.4.2.tgz", + "integrity": "sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.10.4", + "@babel/runtime": "^7.12.5", + "@types/aria-query": "^5.0.1", + "aria-query": "5.3.0", + "dom-accessibility-api": "^0.5.9", + "lz-string": "^1.5.0", + "picocolors": "1.1.1", + "pretty-format": "^27.0.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@testing-library/user-event": { + "version": "14.6.8", + "resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.8.tgz", + "integrity": "sha512-vgSSqnANMnkcYR/vUNDbwS7aM3OErRLNUG8vCVVlj4oc6cKffUrccX7UAS5AmJQQNZTSibi9z5GvvRZ0aYgUCQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12", + "npm": ">=6" + }, + "peerDependencies": { + "@testing-library/dom": ">=7.21.4" + } + }, + "node_modules/@types/aria-query": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz", + "integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", @@ -2153,6 +2221,16 @@ "dev": true, "license": "Python-2.0" }, + "node_modules/aria-query": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", + "integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "dequal": "^2.0.3" + } + }, "node_modules/array-union": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", @@ -2642,6 +2720,16 @@ "node": ">=0.4.0" } }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/didyoumean": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", @@ -2680,6 +2768,13 @@ "node": ">=6.0.0" } }, + "node_modules/dom-accessibility-api": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz", + "integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==", + "dev": true, + "license": "MIT" + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -3814,6 +3909,13 @@ "dev": true, "license": "MIT" }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, "node_modules/js-yaml": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", @@ -3988,6 +4090,16 @@ "dev": true, "license": "ISC" }, + "node_modules/lz-string": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/lz-string/-/lz-string-1.5.0.tgz", + "integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==", + "dev": true, + "license": "MIT", + "bin": { + "lz-string": "bin/bin.js" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -4641,6 +4753,34 @@ "node": ">= 0.8.0" } }, + "node_modules/pretty-format": { + "version": "27.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", + "integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1", + "ansi-styles": "^5.0.0", + "react-is": "^17.0.1" + }, + "engines": { + "node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0" + } + }, + "node_modules/pretty-format/node_modules/ansi-styles": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", + "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/primevue": { "version": "4.5.5", "resolved": "https://registry.npmjs.org/primevue/-/primevue-4.5.5.tgz", @@ -4694,6 +4834,13 @@ ], "license": "MIT" }, + "node_modules/react-is": { + "version": "17.0.2", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz", + "integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==", + "dev": true, + "license": "MIT" + }, "node_modules/read-cache": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.2.tgz", diff --git a/frontend/wippy-form/package.json b/frontend/wippy-form/package.json index 4ad4ecc..94cd0d8 100644 --- a/frontend/wippy-form/package.json +++ b/frontend/wippy-form/package.json @@ -4,7 +4,7 @@ "private": true, "specification": "wippy-component-1.0", "title": "Session Form", - "description": "Renders a session ask_user form (single/multiple choice with Other) and submits the answer back to the owning session.", + "description": "Renders one Session form and submits the answer back to the owning session: a choice-only form as a question card, a form with standard fields (text, textarea, number, email, date, checkbox, alone or mixed with choices) as one fields form.", "browser": "dist/index.js", "files": [ "dist/", @@ -19,6 +19,8 @@ }, "devDependencies": { "@iconify/vue": "^5.0.5", + "@testing-library/dom": "^10.4.2", + "@testing-library/user-event": "^14.6.7", "@typescript-eslint/eslint-plugin": "^7.0.0", "@typescript-eslint/parser": "^7.0.0", "@vitejs/plugin-vue": "^5.0.0", @@ -51,19 +53,19 @@ "wippy": { "tagName": "wippy-form", "type": "widget", - "description": "Renders one Session `ask_user` form as a question card and sends the answer back to the owning session through the Host's artifact-state API. Each question supports per-answer notes and, when the definition allows it, an Other free-text row. A form with several questions shows one at a time, with a counter and a review step before sending. Once the answer is accepted, the card becomes a read-only summary. The inputs are `definition` (the questions and options), `form-version` (a version other than 1 disables submission), and `state` (`active` while the form can be answered, `idle` after it was answered). The component loads and submits by itself, so the tag only needs these attributes. Agents must never write the `` tag, because it is created only through the Session `ask_user` tool.", + "description": "Renders one Session form (from the `ask_user` or `ask_user_fields` tool) and sends the answer back to the owning session through the Host's artifact-state API. A form of choice questions only (form version 1) renders as a question card: each question supports per-answer notes and, when the definition allows it, an Other free-text row, and a form with several questions shows one at a time, with a counter and a review step before sending. A form with at least one standard field (form version 2: `text`, `textarea`, `number`, `email`, `date` or `checkbox`, alone or with choices) renders as a fields form: a labelled control for every field, each error tied to its control, and one Submit button. Once the answer is accepted, either becomes a read-only summary. The inputs are `definition` (the questions), `form-version` (1 and 2 render; a higher version, or a field type this version does not know, disables submission), and `state` (`active` while the form can be answered, `idle` after it was answered). The component loads and submits by itself, so the tag only needs these attributes. Agents must never write the `` tag, because it is created only through the Session `ask_user` and `ask_user_fields` tools.", "props": { "type": "object", "properties": { "form-version": { "type": "number", "default": 1, - "description": "Form definition schema version (currently 1). A value other than 1, from this prop or from the loaded state's own `form_version`, disables the interactive form and shows the notice \"This form needs a newer version of the app.\" instead." + "description": "Form definition schema version: 1 is a choice-only form, 2 is a form with at least one standard field (`text`, `textarea`, `number`, `email`, `date`, `checkbox`). A higher value, from this prop or from the loaded state's own `form_version`, disables the interactive form and shows the notice \"This form needs a newer version of the app.\" instead, and so does a field whose type this version does not know." }, "definition": { "type": "object", "default": null, - "description": "The questions to ask: `title`, optional `description`, and `fields`, a list of choice questions, each `{ id, type: \"choice\", label, description?, required, options: [{value, label, description?}], multiple, allow_other }`. Optional `submit_label` and `answered_message` are accepted and not shown. A definition with no fields shows an error message." + "description": "The questions to ask: `title`, optional `description`, and `fields`. Every field is `{ id, type, label, description?, required }` plus the keys of its type: `choice` adds `options: [{value, label, description?}]`, `multiple` and `allow_other`; `text` and `textarea` add `min_length`, `max_length`, `placeholder` and `default` (`text` also `pattern`, a full-match expression that only the server checks, answering a mismatch with a 422 `pattern_mismatch` on the field); `number` adds `min`, `max`, `step`, `integer` and `default`; `email` adds `default`; `date` adds `min`, `max` (`YYYY-MM-DD`) and `default`; `checkbox` adds `default` (only `false`). Optional `submit_label` is the fields form's Submit button text (the question card does not show it), and optional `answered_message` is accepted and not shown. When every field is a choice the question card renders, otherwise the fields form. A definition with no fields shows an error message." }, "state": { "type": "string", diff --git a/frontend/wippy-form/src/app/active-form-v2.test.ts b/frontend/wippy-form/src/app/active-form-v2.test.ts new file mode 100644 index 0000000..f22b41e --- /dev/null +++ b/frontend/wippy-form/src/app/active-form-v2.test.ts @@ -0,0 +1,663 @@ +import type { FormState } from '../lib/definition' +import { PrimeVuePlugin } from '@wippy-fe/theme/primevue-plugin' +import { mount } from '@vue/test-utils' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { nextTick } from 'vue' +import { SLOW_SEND_MS } from '../lib/send-state' +import { applyFocusFixup } from '../test-support/dom' +import ActiveForm from './active-form.vue' + +const v2State: FormState = { + form_version: 2, + artifact_id: 'artifact-1', + session_id: 'session-1', + status: 'active', + stale: false, + late: false, + content_version: 1, + definition: { + title: 'Delivery details', + description: 'Where should it go?', + fields: [ + { id: 'name', type: 'text', min_length: 0, max_length: 500, label: 'Full name', required: true }, + { id: 'mail', type: 'email', label: 'Email', required: true }, + { id: 'qty', type: 'number', label: 'Parcels', required: false, integer: true, min: 1, max: 9 }, + { id: 'day', type: 'date', label: 'Delivery date', required: false }, + { id: 'notes', type: 'textarea', min_length: 0, max_length: 8000, label: 'Notes', required: false }, + { id: 'consent', type: 'checkbox', label: 'I agree', required: true }, + ], + }, + data: null, + submitted_at: null, + answer_message_id: null, + delivery: null, +} + +function mountForm(state: FormState = v2State) { + return mount(ActiveForm, { + props: { state, submitting: false, banner: null }, + global: { plugins: [PrimeVuePlugin] }, + attachTo: document.body, + }) +} + +function inputOf(wrapper: ReturnType, label: string) { + const labelEl = wrapper.findAll('label').find(l => l.text().startsWith(label)) + if (!labelEl) + throw new Error(`no label starting with "${label}"`) + return wrapper.find(`[id="${labelEl.attributes('for')}"]`) +} + +async function fillValid(wrapper: ReturnType) { + await inputOf(wrapper, 'Full name').setValue(' Ada Lovelace ') + await inputOf(wrapper, 'Email').setValue(' ada@example.com ') + await inputOf(wrapper, 'I agree').setValue(true) +} + +describe('ActiveForm — V2 standard fields', () => { + it('renders a labelled control for every field type and a form the browser may not validate natively', () => { + const wrapper = mountForm() + expect(wrapper.find('form').attributes('novalidate')).toBeDefined() + expect(wrapper.findAll('input[type="text"]')).toHaveLength(3) + expect(wrapper.find('input[type="email"]').exists()).toBe(true) + expect(wrapper.find('textarea').exists()).toBe(true) + expect(wrapper.find('input[type="checkbox"]').exists()).toBe(true) + expect(wrapper.text()).toContain('Delivery details') + expect(wrapper.text()).toContain('Where should it go?') + }) + + it('does not submit an empty required form: names each missing field and moves focus to the first', async () => { + const wrapper = mountForm() + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + await wrapper.vm.$nextTick() + + expect(wrapper.emitted('submit')).toBeUndefined() + expect(wrapper.findAll('ul').map(ul => ul.text())).toEqual([ + 'This question is required.', + 'This question is required.', + 'This question is required.', + ]) + expect(document.activeElement).toBe(inputOf(wrapper, 'Full name').element) + expect(wrapper.find('[role="status"]').text()).toBe('3 questions need attention.') + }) + + it('reports an invalid email on its own field, linked to the real input, and does not echo the value', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + await inputOf(wrapper, 'Email').setValue('not-an-email') + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + await wrapper.vm.$nextTick() + + expect(wrapper.emitted('submit')).toBeUndefined() + const mail = inputOf(wrapper, 'Email') + const error = wrapper.find('ul') + expect(error.text()).toBe('Enter a valid email address.') + expect(mail.attributes('aria-describedby')).toBe(error.attributes('id')) + expect(mail.attributes('aria-invalid')).toBe('true') + expect(document.activeElement).toBe(mail.element) + expect(wrapper.find('[role="status"]').text()).toBe('1 question needs attention.') + expect(wrapper.text()).not.toContain('not-an-email') + }) + + it('names an unparseable typed date instead of dropping it', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + await inputOf(wrapper, 'Delivery date').setValue('next tuesday') + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + + expect(wrapper.emitted('submit')).toBeUndefined() + expect(wrapper.find('ul').text()).toBe('Enter a valid date as YYYY-MM-DD.') + }) + + it('names a typed date outside the allowed range', async () => { + const state: FormState = { ...v2State, definition: { title: 'T', fields: [{ id: 'day', type: 'date', label: 'Delivery date', required: false, min: '2026-10-01', max: '2026-12-31' }] } } + const wrapper = mountForm(state) + await inputOf(wrapper, 'Delivery date').setValue('2026-09-30') + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + expect(wrapper.emitted('submit')).toBeUndefined() + expect(wrapper.find('ul').text()).toBe('Choose 2026-10-01 or later.') + + await inputOf(wrapper, 'Delivery date').setValue('2027-01-01') + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + expect(wrapper.find('ul').text()).toBe('Choose 2026-12-31 or earlier.') + + await inputOf(wrapper, 'Delivery date').setValue('2026-10-01') + await wrapper.find('form').trigger('submit') + expect(wrapper.emitted('submit')?.[0]).toEqual([{ day: '2026-10-01' }]) + }) + + it('names a number that is not strictly a number', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + await inputOf(wrapper, 'Parcels').setValue('1,5') + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + + expect(wrapper.emitted('submit')).toBeUndefined() + expect(wrapper.find('ul').text()).toContain('Enter a number') + }) + + it('submits the exact wire values: text as typed, number as a number, trimmed email, explicit booleans', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + await inputOf(wrapper, 'Parcels').setValue('3') + await inputOf(wrapper, 'Delivery date').setValue('2026-10-15') + await inputOf(wrapper, 'Notes').setValue('line one\nline two') + await wrapper.find('form').trigger('submit') + + expect(wrapper.emitted('submit')?.[0]).toEqual([{ + name: ' Ada Lovelace ', + mail: 'ada@example.com', + qty: 3, + day: '2026-10-15', + notes: 'line one\nline two', + consent: true, + }]) + }) + + it('omits blank optional fields', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + await wrapper.find('form').trigger('submit') + expect(wrapper.emitted('submit')?.[0]).toEqual([{ name: ' Ada Lovelace ', mail: 'ada@example.com', consent: true }]) + }) + + it('sends an untouched optional checkbox as false', async () => { + const state: FormState = { ...v2State, definition: { title: 'T', fields: [{ id: 'news', type: 'checkbox', label: 'Newsletter', required: false }] } } + const wrapper = mountForm(state) + await wrapper.find('form').trigger('submit') + expect(wrapper.emitted('submit')?.[0]).toEqual([{ news: false }]) + }) + + it('will not submit a required checkbox left unchecked', async () => { + const wrapper = mountForm() + await inputOf(wrapper, 'Full name').setValue('Ada') + await inputOf(wrapper, 'Email').setValue('ada@example.com') + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + + expect(wrapper.emitted('submit')).toBeUndefined() + const consent = inputOf(wrapper, 'I agree') + expect(consent.attributes('aria-invalid')).toBe('true') + }) + + it('clears a field\'s error once the user changes that field', async () => { + const wrapper = mountForm() + await wrapper.find('form').trigger('submit') + expect(wrapper.findAll('ul')).toHaveLength(3) + await inputOf(wrapper, 'Full name').setValue('Ada') + expect(wrapper.findAll('ul')).toHaveLength(2) + expect(inputOf(wrapper, 'Full name').attributes('aria-describedby')).toBeUndefined() + }) + + it('shows a server field error on the right field, linked and focused', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + const vm = wrapper.vm as unknown as { setServerErrors: (e?: Record, f?: { code: string, message: string }[]) => void } + vm.setServerErrors({ mail: [{ code: 'invalid_email', message: 'That address is not accepted.' }] }, []) + await wrapper.vm.$nextTick() + await wrapper.vm.$nextTick() + + const mail = inputOf(wrapper, 'Email') + expect(wrapper.find('ul').text()).toBe('That address is not accepted.') + expect(mail.attributes('aria-describedby')).toBe(wrapper.find('ul').attributes('id')) + expect(document.activeElement).toBe(mail.element) + }) +}) + +describe('ActiveForm — defaults', () => { + const withDefaults: FormState = { + ...v2State, + definition: { + title: 'Defaults', + fields: [ + { id: 'city', type: 'text', min_length: 0, max_length: 500, label: 'City', required: false, default: 'Berlin' }, + { id: 'qty', type: 'number', label: 'Quantity', required: false, default: 3 }, + { id: 'agree', type: 'checkbox', label: 'Agree', required: false, default: false }, + ], + }, + } + + it('prefills the controls from the definition', () => { + const wrapper = mountForm(withDefaults) + expect((inputOf(wrapper, 'City').element as HTMLInputElement).value).toBe('Berlin') + expect((inputOf(wrapper, 'Quantity').element as HTMLInputElement).value).toBe('3') + expect((inputOf(wrapper, 'Agree').element as HTMLInputElement).checked).toBe(false) + }) + + it('submits a prefilled default as it stands', async () => { + const wrapper = mountForm(withDefaults) + await wrapper.find('form').trigger('submit') + expect(wrapper.emitted('submit')?.[0]).toEqual([{ city: 'Berlin', qty: 3, agree: false }]) + }) + + it('submits nothing for an optional prefilled value the user cleared', async () => { + const wrapper = mountForm(withDefaults) + await inputOf(wrapper, 'City').setValue('') + await inputOf(wrapper, 'Quantity').setValue('') + await wrapper.find('form').trigger('submit') + expect(wrapper.emitted('submit')?.[0]).toEqual([{ agree: false }]) + }) +}) + +describe('ActiveForm — hasUnsentInput', () => { + function unsent(wrapper: ReturnType) { + return (wrapper.vm as unknown as { hasUnsentInput: () => boolean }).hasUnsentInput() + } + + it('is false for an untouched form, even one whose controls start with a value', () => { + expect(unsent(mountForm())).toBe(false) + }) + + it('is true once the user typed something, even something invalid', async () => { + const wrapper = mountForm() + await inputOf(wrapper, 'Email').setValue('half-typed') + expect(unsent(wrapper)).toBe(true) + }) + + it('is true once a checkbox was ticked, and false again when it is put back', async () => { + const wrapper = mountForm() + await inputOf(wrapper, 'I agree').setValue(true) + expect(unsent(wrapper)).toBe(true) + await inputOf(wrapper, 'I agree').setValue(false) + expect(unsent(wrapper)).toBe(false) + }) +}) + +describe('ActiveForm — styling API', () => { + it('names the form, its title, description, fields and submit button as parts and w-form__ classes', () => { + const wrapper = mountForm() + const root = wrapper.find('form') + expect(root.attributes('part')?.split(' ')).toContain('fields') + expect(root.classes()).toEqual(expect.arrayContaining(['w-form', 'w-form__fields'])) + expect(wrapper.find('[part~="fields-title"]').text()).toBe('Delivery details') + expect(wrapper.find('[part~="form-description"]').text()).toBe('Where should it go?') + expect(wrapper.findAll('[part~="field"]')).toHaveLength(6) + expect(wrapper.find('button[type="submit"]').attributes('part')).toContain('send') + }) +}) + +describe('ActiveForm — status summary stays accurate', () => { + function status(wrapper: ReturnType) { + return wrapper.find('[role="status"]').text() + } + + async function failSubmit(wrapper: ReturnType) { + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + await wrapper.vm.$nextTick() + } + + it('says how many questions still need attention as each one is fixed, and clears when none do', async () => { + const wrapper = mountForm() + await failSubmit(wrapper) + expect(status(wrapper)).toBe('3 questions need attention.') + + await inputOf(wrapper, 'Full name').setValue('Ada') + expect(status(wrapper)).toBe('2 questions need attention.') + await inputOf(wrapper, 'Email').setValue('ada@example.com') + expect(status(wrapper)).toBe('1 question needs attention.') + await inputOf(wrapper, 'I agree').setValue(true) + expect(status(wrapper)).toBe('') + }) + + it('does not touch the status text while the user keeps typing, only when the count changes', async () => { + const wrapper = mountForm() + await failSubmit(wrapper) + const statusEl = wrapper.find('[role="status"]').element + let changes = 0 + const observer = new MutationObserver((records) => { changes += records.length }) + observer.observe(statusEl, { childList: true, characterData: true, subtree: true }) + + // The first key fixes this field's error: the count goes 3 to 2, one change. + const name = inputOf(wrapper, 'Full name') + await name.setValue('A') + await Promise.resolve() + const afterFirstKey = changes + expect(afterFirstKey).toBeGreaterThan(0) + // The rest of the typing leaves the count alone. + await name.setValue('Ad') + await name.setValue('Ada') + await name.setValue('Ada L') + await Promise.resolve() + expect(changes).toBe(afterFirstKey) + expect(status(wrapper)).toBe('2 questions need attention.') + observer.disconnect() + }) + + it('clears after a server error on a field is fixed', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + const vm = wrapper.vm as unknown as { setServerErrors: (e?: Record, f?: { code: string, message: string }[]) => void } + vm.setServerErrors({ mail: [{ code: 'invalid_email', message: 'That address is not accepted.' }] }, []) + await wrapper.vm.$nextTick() + expect(status(wrapper)).toBe('1 question needs attention.') + + await inputOf(wrapper, 'Email').setValue('ada@elsewhere.example') + expect(status(wrapper)).toBe('') + }) + + it('keeps a submit-failure message in the status when a field is fixed afterwards', async () => { + const wrapper = mountForm() + await failSubmit(wrapper) + await wrapper.setProps({ banner: { message: 'Could not send. Check your connection.', retryable: true } }) + expect(status(wrapper)).toBe('Could not send. Check your connection.') + await inputOf(wrapper, 'Full name').setValue('Ada') + expect(status(wrapper)).toBe('Could not send. Check your connection.') + }) + + it('starts empty and says nothing before a submit', () => { + expect(status(mountForm())).toBe('') + }) +}) + +describe('ActiveForm — a form-level error is its own text, not a question', () => { + type ServerErrors = { setServerErrors: (e?: Record, f?: { code: string, message: string }[]) => void } + const STALE = { code: 'stale', message: 'This form changed since you loaded it.' } + const MAIL = { code: 'invalid_email', message: 'That address is not accepted.' } + const status = (wrapper: ReturnType) => wrapper.find('[role="status"]').text() + + async function serverErrors(wrapper: ReturnType, fields: Record, form: { code: string, message: string }[]) { + await fillValid(wrapper) + ;(wrapper.vm as unknown as ServerErrors).setServerErrors(fields, form) + await wrapper.vm.$nextTick() + } + + it('says the form-level message in the status region and counts no question for it', async () => { + const wrapper = mountForm() + await serverErrors(wrapper, {}, [STALE]) + expect(status(wrapper)).toBe('This form changed since you loaded it.') + expect(status(wrapper)).not.toContain('question') + }) + + it('counts only the fields in error as questions and adds the form-level message after them', async () => { + const wrapper = mountForm() + await serverErrors(wrapper, { mail: [MAIL] }, [STALE]) + expect(status(wrapper)).toBe('1 question needs attention. This form changed since you loaded it.') + }) + + it('joins several form-level messages', async () => { + const wrapper = mountForm() + await serverErrors(wrapper, {}, [STALE, { code: 'closed', message: 'This form is closed.' }]) + expect(status(wrapper)).toBe('This form changed since you loaded it. This form is closed.') + }) + + it('keeps the form-level message when the last field error is fixed, and drops the count', async () => { + const wrapper = mountForm() + await serverErrors(wrapper, { mail: [MAIL] }, [STALE]) + await inputOf(wrapper, 'Email').setValue('ada@elsewhere.example') + expect(status(wrapper)).toBe('This form changed since you loaded it.') + }) + + it('shows the form-level message under the fields as before', async () => { + const wrapper = mountForm() + await serverErrors(wrapper, { mail: [MAIL] }, [STALE]) + expect(wrapper.find('[part~="fields-error"]').text()).toBe('This form changed since you loaded it.') + }) + + it('clears the form-level message from the status when the form is submitted again', async () => { + const wrapper = mountForm() + await serverErrors(wrapper, {}, [STALE]) + expect(status(wrapper)).toBe('This form changed since you loaded it.') + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + // The client check passes and hands the answers over; the server decides again. + expect(wrapper.emitted('submit')).toHaveLength(1) + expect(status(wrapper)).toBe('') + expect(wrapper.find('[part~="fields-error"]').exists()).toBe(false) + }) +}) + +describe('ActiveForm — a submit-failure banner is announced once', () => { + const BANNER = { message: 'Could not send. Check your connection.', retryable: true } + + /** Every element a screen reader treats as a live region. */ + const liveRegions = (wrapper: ReturnType) => wrapper.findAll('[role="alert"], [role="status"], [role="log"], [aria-live]') + + it('puts the message in the polite status region and nowhere else that is live', async () => { + const wrapper = mountForm() + await wrapper.setProps({ banner: BANNER }) + const announcing = liveRegions(wrapper).filter(el => el.text().includes(BANNER.message)) + expect(announcing).toHaveLength(1) + expect(announcing[0].attributes('role')).toBe('status') + }) + + it('still shows the message and its Retry button, which is not a live region', async () => { + const wrapper = mountForm() + await wrapper.setProps({ banner: BANNER }) + expect(wrapper.find('.p-message').text()).toContain(BANNER.message) + expect(wrapper.find('.p-message button').text()).toBe('Retry') + expect(wrapper.find('.p-message').attributes('role')).toBeUndefined() + expect(wrapper.find('.p-message').attributes('aria-live')).toBeUndefined() + }) + + it('does the same for a message that cannot be retried', async () => { + const wrapper = mountForm() + await wrapper.setProps({ banner: { message: 'This form was already answered.' } }) + expect(liveRegions(wrapper).filter(el => el.text().includes('This form was already answered.'))).toHaveLength(1) + }) + + it('announces a repeated failure with the same text: the region is emptied when the send starts', async () => { + const wrapper = mountForm() + const status = wrapper.find('[role="status"]') + await wrapper.setProps({ banner: BANNER }) + expect(status.text()).toBe(BANNER.message) + await wrapper.setProps({ banner: null, submitting: true }) + expect(status.text()).toBe('') + await wrapper.setProps({ banner: BANNER, submitting: false }) + expect(status.text()).toBe(BANNER.message) + }) +}) + +describe('ActiveForm — screen reader text', () => { + it('hides the status region from sight, so it shows no text and takes no space', async () => { + const wrapper = mountForm() + expect(wrapper.find('[role="status"]').classes()).toContain('sr-only') + }) +}) + +describe('ActiveForm — Retry', () => { + const BANNER = { message: 'Could not send.', retryable: true } + + it('checks the answers first, so a value edited into something invalid is shown and not dropped', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + await wrapper.setProps({ banner: BANNER }) + await inputOf(wrapper, 'Email').setValue('not an address') + + ;(wrapper.vm as unknown as { retry: () => void }).retry() + await nextTick() + + expect(wrapper.emitted('submit')).toBeUndefined() + expect(wrapper.text()).toContain('Enter a valid email address.') + expect(inputOf(wrapper, 'Email').attributes('aria-invalid')).toBe('true') + }) + + it('sends valid answers', async () => { + const wrapper = mountForm() + await fillValid(wrapper) + await wrapper.setProps({ banner: BANNER }) + ;(wrapper.vm as unknown as { retry: () => void }).retry() + expect(wrapper.emitted('submit')).toHaveLength(1) + }) +}) + +describe('ActiveForm — focus around a send', () => { + const BANNER = { message: 'Could not send.', retryable: true } + + function mountWatched() { + const wrapper = mountForm() + const stop = applyFocusFixup(wrapper.element) + return { wrapper, stop, submit: () => wrapper.find('button[type="submit"]') } + } + + it('keeps focus on Submit while a send is in flight: it is aria-disabled, not disabled', async () => { + const { wrapper, stop, submit } = mountWatched() + ;(submit().element as HTMLElement).focus() + await wrapper.setProps({ submitting: true }) + await nextTick() + expect(submit().attributes('disabled')).toBeUndefined() + expect(submit().attributes('aria-disabled')).toBe('true') + expect(submit().classes()).toContain('p-disabled') + expect(document.activeElement).toBe(submit().element) + + await wrapper.setProps({ submitting: false, banner: BANNER }) + await nextTick() + expect(submit().attributes('aria-disabled')).toBeUndefined() + expect(document.activeElement).toBe(submit().element) + stop() + wrapper.unmount() + }) + + it('ignores a submit while one is in flight', async () => { + const { wrapper, stop } = mountWatched() + await fillValid(wrapper) + await wrapper.setProps({ submitting: true }) + await wrapper.find('form').trigger('submit') + expect(wrapper.emitted('submit')).toBeUndefined() + stop() + wrapper.unmount() + }) + + it('gives focus to Submit after a failed send left none: a text box is disabled while it sends', async () => { + const { wrapper, stop, submit } = mountWatched() + const box = inputOf(wrapper, 'Full name') + ;(box.element as HTMLElement).focus() + await wrapper.setProps({ submitting: true }) + await nextTick() + await new Promise(resolve => setTimeout(resolve)) + // Positive control: the disabled box really dropped focus. + expect(document.activeElement).toBe(document.body) + + await wrapper.setProps({ submitting: false, banner: BANNER }) + await nextTick() + expect(document.activeElement).toBe(submit().element) + stop() + wrapper.unmount() + }) + + it('gives focus to Submit after a form-level 422, and leaves focus that moved elsewhere alone', async () => { + const { wrapper, stop, submit } = mountWatched() + const vm = wrapper.vm as unknown as { setServerErrors: (e?: unknown, f?: { code: string, message: string }[]) => void } + vm.setServerErrors(undefined, [{ code: 'version_conflict', message: 'The form changed.' }]) + await nextTick() + await nextTick() + expect(document.activeElement).toBe(submit().element) + + const elsewhere = document.createElement('button') + document.body.append(elsewhere) + elsewhere.focus() + await wrapper.setProps({ banner: BANNER }) + await nextTick() + expect(document.activeElement).toBe(elsewhere) + elsewhere.remove() + stop() + wrapper.unmount() + }) +}) + +describe('ActiveForm — Submit while a send is in flight', () => { + const BANNER = { message: 'Could not send.', retryable: true } + const submit = (wrapper: ReturnType) => wrapper.find('button[type="submit"]') + + it('reads "Sending…" while the send runs and gets its label back after a failed send', async () => { + const wrapper = mountForm() + expect(submit(wrapper).text()).toBe('Submit') + await wrapper.setProps({ submitting: true }) + expect(submit(wrapper).text()).toBe('Sending…') + await wrapper.setProps({ submitting: false, banner: BANNER }) + expect(submit(wrapper).text()).toBe('Submit') + }) + + it('swaps a custom submit label too, and restores it', async () => { + const wrapper = mountForm({ ...v2State, definition: { ...v2State.definition, submit_label: 'Place order' } }) + expect(submit(wrapper).text()).toBe('Place order') + await wrapper.setProps({ submitting: true }) + expect(submit(wrapper).text()).toBe('Sending…') + await wrapper.setProps({ submitting: false }) + expect(submit(wrapper).text()).toBe('Place order') + }) + + it('keeps the button focusable and aria-disabled, never disabled, so focus stays on it', async () => { + const wrapper = mountForm() + const stop = applyFocusFixup(wrapper.element) + ;(submit(wrapper).element as HTMLElement).focus() + await wrapper.setProps({ submitting: true }) + expect(submit(wrapper).attributes('disabled')).toBeUndefined() + expect(submit(wrapper).attributes('aria-disabled')).toBe('true') + expect(document.activeElement).toBe(submit(wrapper).element) + stop() + }) + + it('shows a spinner that stops under reduced motion, hidden from screen readers, only while sending', async () => { + const wrapper = mountForm() + expect(submit(wrapper).find('.animate-spin').exists()).toBe(false) + await wrapper.setProps({ submitting: true }) + const spinner = submit(wrapper).find('.animate-spin') + expect(spinner.exists()).toBe(true) + expect(spinner.classes()).toContain('motion-reduce:animate-none') + expect(spinner.attributes('aria-hidden')).toBe('true') + await wrapper.setProps({ submitting: false }) + expect(submit(wrapper).find('.animate-spin').exists()).toBe(false) + }) + + it('adds the send-sending part and class while sending, and not while only offline', async () => { + const wrapper = mountForm() + expect(submit(wrapper).attributes('part')).toBe('send') + await wrapper.setProps({ submitting: true }) + expect(submit(wrapper).attributes('part')).toBe('send send-sending') + expect(submit(wrapper).classes()).toEqual(expect.arrayContaining(['w-form__send', 'w-form__send--sending'])) + await wrapper.setProps({ submitting: false, offline: true }) + expect(submit(wrapper).attributes('part')).toBe('send') + expect(submit(wrapper).text()).toBe('Submit') + expect(submit(wrapper).attributes('aria-disabled')).toBe('true') + }) + + describe('the status region', () => { + beforeEach(() => { + vi.useFakeTimers() + }) + + afterEach(() => { + vi.useRealTimers() + }) + + const statusOf = (wrapper: ReturnType) => wrapper.find('[role="status"]').text() + + it('stays silent for a send that ends quickly', async () => { + const wrapper = mountForm() + await wrapper.setProps({ submitting: true }) + vi.advanceTimersByTime(SLOW_SEND_MS - 1) + await nextTick() + expect(statusOf(wrapper)).toBe('') + await wrapper.setProps({ submitting: false, banner: BANNER }) + vi.advanceTimersByTime(SLOW_SEND_MS) + await nextTick() + expect(statusOf(wrapper)).toBe(BANNER.message) + }) + + it('says "Sending your answers." once a send runs long, and hands the region to the failure after it', async () => { + const wrapper = mountForm() + await wrapper.setProps({ submitting: true }) + vi.advanceTimersByTime(SLOW_SEND_MS) + await nextTick() + expect(statusOf(wrapper)).toBe('Sending your answers.') + await wrapper.setProps({ submitting: false, banner: BANNER }) + expect(statusOf(wrapper)).toBe(BANNER.message) + }) + + it('empties the region when a slow send ends without a message', async () => { + const wrapper = mountForm() + await wrapper.setProps({ submitting: true }) + vi.advanceTimersByTime(SLOW_SEND_MS) + await nextTick() + await wrapper.setProps({ submitting: false }) + expect(statusOf(wrapper)).toBe('') + }) + }) +}) diff --git a/frontend/wippy-form/src/app/active-form.test.ts b/frontend/wippy-form/src/app/active-form.test.ts new file mode 100644 index 0000000..181ed00 --- /dev/null +++ b/frontend/wippy-form/src/app/active-form.test.ts @@ -0,0 +1,157 @@ +import type { FormState } from '../lib/definition' +import { PrimeVuePlugin } from '@wippy-fe/theme/primevue-plugin' +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import ActiveForm from './active-form.vue' + +const state: FormState = { + form_version: 1, + artifact_id: 'artifact-1', + session_id: 'session-1', + status: 'active', + stale: false, + late: false, + content_version: 1, + definition: { + title: 'Question', + fields: [ + { + id: 'f1', + type: 'choice', + label: 'Pick one', + required: true, + options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }], + multiple: false, + allow_other: false, + }, + ], + }, + data: null, + submitted_at: null, + answer_message_id: null, + delivery: null, +} + +describe('ActiveForm — server-side validation errors', () => { + it('renders the field error text next to the field, connected via aria-describedby, with no role="alert"', async () => { + const wrapper = mount(ActiveForm, { + props: { state, submitting: false, banner: null }, + global: { plugins: [PrimeVuePlugin] }, + }) + + const vm = wrapper.vm as unknown as { + setServerErrors: (e?: Record, f?: { code: string, message: string }[]) => void + } + vm.setServerErrors({ f1: [{ code: 'required', message: 'This question is required.' }] }, []) + await wrapper.vm.$nextTick() + + expect(wrapper.find('[role="alert"]').exists()).toBe(false) + expect(wrapper.text()).toContain('This question is required.') + + const fieldset = wrapper.find('fieldset') + const errorList = wrapper.find('ul[id]') + expect(errorList.exists()).toBe(true) + expect(fieldset.attributes('aria-describedby')).toContain(errorList.attributes('id')) + }) + + it('clears a question\'s error once the user answers it', async () => { + const wrapper = mount(ActiveForm, { + props: { state, submitting: false, banner: null }, + global: { plugins: [PrimeVuePlugin] }, + }) + + await wrapper.find('form').trigger('submit') + expect(wrapper.text()).toContain('This question is required.') + + await wrapper.find('input[type="radio"]').setValue(true) + expect(wrapper.text()).not.toContain('This question is required.') + expect(wrapper.find('fieldset').attributes('aria-describedby')).toBeUndefined() + }) + + it('renders form-level errors from a 422 response', async () => { + const wrapper = mount(ActiveForm, { + props: { state, submitting: false, banner: null }, + global: { plugins: [PrimeVuePlugin] }, + }) + + const vm = wrapper.vm as unknown as { + setServerErrors: (e?: Record, f?: { code: string, message: string }[]) => void + } + vm.setServerErrors({}, [{ code: 'stale', message: 'This form changed since you loaded it.' }]) + await wrapper.vm.$nextTick() + + expect(wrapper.text()).toContain('This form changed since you loaded it.') + }) + + it('announces the error summary in the polite status region on a validation failure', async () => { + const wrapper = mount(ActiveForm, { + props: { state, submitting: false, banner: null }, + global: { plugins: [PrimeVuePlugin] }, + }) + + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + + const status = wrapper.find('[role="status"]') + expect(status.exists()).toBe(true) + expect(status.text()).toBe('1 question needs attention.') + }) + + it('mirrors a submit-failure banner into the polite status region', async () => { + const wrapper = mount(ActiveForm, { + props: { state, submitting: false, banner: null }, + global: { plugins: [PrimeVuePlugin] }, + }) + await wrapper.setProps({ banner: { message: 'Network problem. Retrying…', retryable: true } }) + await wrapper.vm.$nextTick() + + expect(wrapper.find('[role="status"]').text()).toBe('Network problem. Retrying…') + }) +}) + +describe('ActiveForm — offline', () => { + it('blocks Submit and shows a polite offline notice', () => { + const wrapper = mount(ActiveForm, { + props: { state, submitting: false, banner: null, offline: true }, + global: { plugins: [PrimeVuePlugin] }, + }) + + expect(wrapper.text()).toContain('You are offline. Your choices are kept.') + const submitButton = wrapper.find('button[type="submit"]') + // Blocked and still focusable, as during a send: a disabled button would drop focus. + expect(submitButton.attributes('aria-disabled')).toBe('true') + }) +}) + +describe('ActiveForm — blank Other answer', () => { + it('asks for the Other text on that question instead of silently dropping it', async () => { + const withOther: FormState = { + ...state, + definition: { + title: 'Question', + fields: [{ + id: 'extras', + type: 'choice', + label: 'Extras', + required: false, + options: [{ value: 'gift', label: 'Gift wrap' }], + multiple: true, + allow_other: true, + }], + }, + data: { extras: ['gift', { other: '' }] }, + } + const wrapper = mount(ActiveForm, { + props: { state: withOther, submitting: false, banner: null }, + global: { plugins: [PrimeVuePlugin] }, + attachTo: document.body, + }) + await wrapper.find('form').trigger('submit') + await wrapper.vm.$nextTick() + + expect(wrapper.emitted('submit')).toBeUndefined() + expect(wrapper.text()).toContain('Enter the other answer.') + expect(wrapper.find('[role="status"]').text()).toContain('1 question needs attention.') + wrapper.unmount() + }) +}) diff --git a/frontend/wippy-form/src/app/active-form.vue b/frontend/wippy-form/src/app/active-form.vue new file mode 100644 index 0000000..3f4697f --- /dev/null +++ b/frontend/wippy-form/src/app/active-form.vue @@ -0,0 +1,350 @@ + + + diff --git a/frontend/wippy-form/src/app/fields/checkbox-field.vue b/frontend/wippy-form/src/app/fields/checkbox-field.vue new file mode 100644 index 0000000..aaac925 --- /dev/null +++ b/frontend/wippy-form/src/app/fields/checkbox-field.vue @@ -0,0 +1,67 @@ + + + diff --git a/frontend/wippy-form/src/app/fields/choice-field.test.ts b/frontend/wippy-form/src/app/fields/choice-field.test.ts index fc841c2..ef76f62 100644 --- a/frontend/wippy-form/src/app/fields/choice-field.test.ts +++ b/frontend/wippy-form/src/app/fields/choice-field.test.ts @@ -1,16 +1,16 @@ -import type { FormField } from '../../lib/definition' -import { mount } from '@vue/test-utils' +import type { ChoiceFormField, FieldError } from '../../lib/definition' import { PrimeVuePlugin } from '@wippy-fe/theme/primevue-plugin' +import { mount } from '@vue/test-utils' import { describe, expect, it } from 'vitest' import ChoiceField from './choice-field.vue' -const trickyField: FormField = { +const trickyField: ChoiceFormField = { id: 'f1', type: 'choice', label: 'Pick one', required: true, - // One value is the reserved word "other" and one contains a space, so - // neither can be used directly as an HTML id. + // One option value literally equals the reserved "other" id fragment, and + // one contains spaces — neither is safe to use directly as an HTML id. options: [ { value: 'other', label: 'Literally "other"' }, { value: 'has spaces', label: 'Has spaces' }, @@ -19,62 +19,224 @@ const trickyField: FormField = { allow_other: true, } -function mountField(field: FormField = trickyField) { - return mount(ChoiceField, { props: { field }, global: { plugins: [PrimeVuePlugin] } }) +function mountField(props: Partial['$props']> = {}) { + return mount(ChoiceField, { + props: { + field: trickyField, + modelValue: undefined, + errors: [], + disabled: false, + readonly: false, + ...props, + }, + global: { plugins: [PrimeVuePlugin] }, + }) } -describe('ChoiceField', () => { - it('builds option ids from the index and keeps the Other control id distinct', () => { +describe('ChoiceField: the Other box label', () => { + it.each([false, true])('is for screen readers only (several answers: %s)', (multiple) => { + const wrapper = mountField({ field: { ...trickyField, multiple } }) + const label = wrapper.findAll('label').find(l => l.text() === 'Other answer') + expect(label?.classes()).toContain('sr-only') + }) +}) + +describe('ChoiceField — DOM id uniqueness', () => { + it('builds option ids from index, never from option values, and keeps the Other control id distinct', () => { const wrapper = mountField() - const ids = wrapper.findAll('[id]').map(el => el.attributes('id') as string) - expect(new Set(ids).size).toBe(ids.length) + const ids = wrapper.findAll('[id]').map(el => el.attributes('id')) + const uniqueIds = new Set(ids) + expect(ids.length).toBe(uniqueIds.size) + + // No id contains a raw space from the "has spaces" option value. for (const id of ids) expect(id).not.toContain(' ') - const radios = wrapper.findAll('input[type="radio"]') - expect(radios).toHaveLength(3) - expect(radios[0].attributes('id')).toMatch(/-opt-0$/) - expect(radios[1].attributes('id')).toMatch(/-opt-1$/) - expect(radios[2].attributes('id')).toMatch(/-other$/) + const inputs = wrapper.findAll('input[type="radio"]') + // Two options + the Other radio = three radio inputs. + expect(inputs.length).toBe(3) + const firstOptionId = inputs[0].attributes('id') as string + const secondOptionId = inputs[1].attributes('id') as string + const otherRadioId = inputs[2].attributes('id') as string + + // Option ids come from index, never from the option's own value — so + // the option whose value literally is "other" does not collide with + // the real Other control's reserved id. + expect(firstOptionId).toMatch(/-opt-0$/) + expect(secondOptionId).toMatch(/-opt-1$/) + expect(otherRadioId).not.toBe(firstOptionId) + expect(otherRadioId).not.toBe(secondOptionId) + expect([firstOptionId, secondOptionId, otherRadioId].every(id => !!id)).toBe(true) }) +}) +describe('ChoiceField — Other control accessible name', () => { it('gives the Other radio and its text input separate accessible names', () => { const wrapper = mountField() - const otherRadioId = wrapper.findAll('input[type="radio"]')[2].attributes('id') as string - expect(wrapper.find(`label[for="${otherRadioId}"]`).text()).toBe('Other') + const otherRadio = wrapper.findAll('input[type="radio"]')[2] + const otherRadioId = otherRadio.attributes('id') as string + const otherRadioLabel = wrapper.find(`label[for="${otherRadioId}"]`) + expect(otherRadioLabel.exists()).toBe(true) + expect(otherRadioLabel.text()).toBe('Other') - const otherTextId = wrapper.find('input[type="text"]').attributes('id') as string + const otherTextInput = wrapper.find('input[type="text"]') + const otherTextId = otherTextInput.attributes('id') as string expect(otherTextId).not.toBe(otherRadioId) - expect(wrapper.find(`label[for="${otherTextId}"]`).text()).toBe('Other answer') + const otherTextLabel = wrapper.find(`label[for="${otherTextId}"]`) + expect(otherTextLabel.exists()).toBe(true) + expect(otherTextLabel.text()).toBe('Other answer') + }) +}) + +describe('ChoiceField — fieldset aria-describedby', () => { + it('describes the fieldset with the description and error ids, not an inner div', () => { + const described: ChoiceFormField = { ...trickyField, description: 'Pick carefully' } + const wrapper = mountField({ + field: described, + errors: [{ code: 'required', message: 'This question is required.' }], + }) + + const fieldset = wrapper.find('fieldset') + const describedBy = fieldset.attributes('aria-describedby') ?? '' + const descP = wrapper.find('p') + expect(describedBy).toContain(descP.attributes('id')) + + const errorList = wrapper.find('ul[id]') + expect(errorList.exists()).toBe(true) + expect(describedBy).toContain(errorList.attributes('id') as string) + expect(errorList.attributes('role')).toBeUndefined() }) +}) - it('shows every control disabled and unselected', () => { +describe('ChoiceField — group role and required', () => { + it('marks a required single-choice group with role="radiogroup" and aria-required', () => { const wrapper = mountField() - const controls = wrapper.findAll('input') - expect(controls.length).toBeGreaterThan(0) - expect(controls.every(c => (c.element as HTMLInputElement).disabled && !(c.element as HTMLInputElement).checked)).toBe(true) + const group = wrapper.find('[role="radiogroup"]') + expect(group.exists()).toBe(true) + expect(group.attributes('aria-required')).toBe('true') + }) + + it('does not mark an optional single-choice group as required', () => { + const wrapper = mountField({ field: { ...trickyField, required: false } }) + expect(wrapper.find('[role="radiogroup"]').attributes('aria-required')).toBeUndefined() + }) + + // The fieldset is already the group, and aria-required is not allowed on a + // group role, so a multiple-choice field adds neither. + it('adds no role and no aria-required to a multiple-choice field, whose fieldset is the group', () => { + const wrapper = mountField({ field: { ...trickyField, multiple: true } }) + expect(wrapper.find('fieldset').exists()).toBe(true) + expect(wrapper.find('[role]').exists()).toBe(false) + expect(wrapper.find('[aria-required]').exists()).toBe(false) + }) +}) + +describe('ChoiceField — required indicator hidden when read-only', () => { + it('does not render "(required)" for a read-only (answered) field', () => { + const wrapper = mountField({ readonly: true, disabled: true, modelValue: 'other' }) + expect(wrapper.text()).not.toContain('(required)') }) - it('describes the fieldset with the description', () => { - const wrapper = mountField({ ...trickyField, description: 'Pick carefully' }) - const description = wrapper.find('p') - expect(description.text()).toBe('Pick carefully') - expect(wrapper.find('fieldset').attributes('aria-describedby')).toBe(description.attributes('id')) + it('still renders "(required)" for an editable required field', () => { + const wrapper = mountField({ readonly: false }) + expect(wrapper.text()).toContain('(required)') }) +}) + +describe('ChoiceField — invalid state for assistive technology', () => { + const REQUIRED: FieldError[] = [{ code: 'required', message: 'This question is required.' }] + const BLANK: FieldError[] = [{ code: 'blank', message: 'Write your answer in the Other box.' }] - it('uses role="radiogroup" for single choice and role="group" for multiple choice', () => { - expect(mountField().find('[role="radiogroup"]').exists()).toBe(true) + function invalidStates(wrapper: ReturnType, selector: string) { + return wrapper.findAll(selector).map(input => input.attributes('aria-invalid')) + } + + it('marks every radio of a single-choice group in error as invalid, on the input a screen reader lands on', () => { + const wrapper = mountField({ errors: REQUIRED }) + // Two options plus Other. + expect(invalidStates(wrapper, 'input[type="radio"]')).toEqual(['true', 'true', 'true']) + }) + + it('marks every checkbox of a multiple-choice group in error as invalid', () => { + const wrapper = mountField({ field: { ...trickyField, multiple: true }, errors: REQUIRED }) + expect(invalidStates(wrapper, 'input[type="checkbox"]')).toEqual(['true', 'true', 'true']) + }) + + it('marks no control invalid while the group has no error', () => { + expect(invalidStates(mountField(), 'input[type="radio"]')).toEqual([undefined, undefined, undefined]) + expect(invalidStates(mountField({ field: { ...trickyField, multiple: true } }), 'input[type="checkbox"]')).toEqual([undefined, undefined, undefined]) + }) + + it('drops the invalid state when the error is gone', async () => { + const wrapper = mountField({ errors: REQUIRED }) + await wrapper.setProps({ errors: [] }) + expect(invalidStates(wrapper, 'input[type="radio"]')).toEqual([undefined, undefined, undefined]) + }) + + it('shows no invalid state on a read-only group', () => { + const wrapper = mountField({ errors: REQUIRED, readonly: true, disabled: true, modelValue: 'other' }) + expect(wrapper.find('[aria-invalid]').exists()).toBe(false) + }) + + it('marks the Other text box invalid when that blank text is what is wrong, and not for a missing choice', () => { + const blank = mountField({ errors: BLANK, modelValue: { other: '' } }) + expect(blank.find('input[type="text"]').attributes('aria-invalid')).toBe('true') + const required = mountField({ errors: REQUIRED }) + expect(required.find('input[type="text"]').attributes('aria-invalid')).toBeUndefined() + }) + + it('keeps the error linked to the group as before', () => { + const wrapper = mountField({ errors: REQUIRED }) + expect(wrapper.find('fieldset').attributes('aria-describedby')).toBe(wrapper.find('ul').attributes('id')) + }) +}) + +describe('ChoiceField — description and error linked to the inputs', () => { + const described: ChoiceFormField = { ...trickyField, description: 'Pick carefully' } + const BLANK: FieldError[] = [{ code: 'blank', message: 'Write your answer in the Other box.' }] + + /** The ids an input is described by. */ + const describedBy = (input: { attributes: (name: string) => string | undefined }) => (input.attributes('aria-describedby') ?? '').split(' ').filter(Boolean) + + it.each([ + ['single choice', 'radio', false], + ['multiple choice', 'checkbox', true], + ] as const)('links the description and the error to every %s input and the Other box, not only to the fieldset', (_name, kind, multiple) => { + const wrapper = mountField({ field: { ...described, multiple }, errors: BLANK, modelValue: multiple ? [{ other: '' }] : { other: '' } }) + const descriptionId = wrapper.find('p').attributes('id') + const errorId = wrapper.find('ul').attributes('id') + expect(descriptionId).toBeTruthy() + expect(errorId).toBeTruthy() + + const inputs = [...wrapper.findAll(`input[type="${kind}"]`), wrapper.find('input[type="text"]')] + // Two options, the Other choice and the Other text box. + expect(inputs).toHaveLength(4) + for (const input of inputs) + expect(describedBy(input), input.attributes('id')).toEqual([descriptionId, errorId]) + }) + + it('links only the error when the field has no description, and nothing when there is none', () => { + const withError = mountField({ errors: BLANK, modelValue: { other: '' } }) + for (const input of withError.findAll('input')) + expect(describedBy(input)).toEqual([withError.find('ul').attributes('id')]) + + const quiet = mountField() + for (const input of quiet.findAll('input')) + expect(input.attributes('aria-describedby')).toBeUndefined() + }) - const multiple = mountField({ ...trickyField, multiple: true }) - expect(multiple.find('[role="group"]').exists()).toBe(true) - expect(multiple.find('[role="radiogroup"]').exists()).toBe(false) - expect(multiple.findAll('input[type="checkbox"]')).toHaveLength(3) + it('drops the error link from the inputs once the error is gone, and keeps the description', async () => { + const wrapper = mountField({ field: described, errors: BLANK, modelValue: { other: '' } }) + await wrapper.setProps({ errors: [] }) + const descriptionId = wrapper.find('p').attributes('id') + for (const input of wrapper.findAll('input')) + expect(describedBy(input)).toEqual([descriptionId]) }) - it('marks a required question', () => { - expect(mountField().text()).toContain('(required)') - expect(mountField({ ...trickyField, required: false }).text()).not.toContain('(required)') + it('links nothing in the read-only view, which has no inputs', () => { + const wrapper = mountField({ field: described, readonly: true, disabled: true, modelValue: 'other' }) + expect(wrapper.find('input').exists()).toBe(false) }) }) diff --git a/frontend/wippy-form/src/app/fields/choice-field.vue b/frontend/wippy-form/src/app/fields/choice-field.vue index a134ca4..934a7d7 100644 --- a/frontend/wippy-form/src/app/fields/choice-field.vue +++ b/frontend/wippy-form/src/app/fields/choice-field.vue @@ -1,104 +1,341 @@ + + - + diff --git a/frontend/wippy-form/src/app/fields/date-field.test.ts b/frontend/wippy-form/src/app/fields/date-field.test.ts new file mode 100644 index 0000000..6b9553d --- /dev/null +++ b/frontend/wippy-form/src/app/fields/date-field.test.ts @@ -0,0 +1,800 @@ +import type { DateFormField, FieldAnswer, FieldError } from '../../lib/definition' +import { PrimeVuePlugin } from '@wippy-fe/theme/primevue-plugin' +import { flushPromises, mount } from '@vue/test-utils' +import userEvent from '@testing-library/user-event' +import { createApp, defineComponent, h, nextTick, ref } from 'vue' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import DateField from './date-field.vue' +import FormFieldControl from './form-field.vue' + +/* + * The date box is typed into one key at a time. These tests drive it the way + * a keyboard does (one `input` event per key, the parent feeding the reported + * draft straight back in), because a test that sets a whole value at once + * never lets the parent re-render between keys — which is exactly where a + * date picker that rewrites its own box loses what was typed. + */ + +const field: DateFormField = { id: 'day', type: 'date', label: 'Delivery date', required: true, min: '2026-01-01', max: '2027-12-31' } + +interface Mounted { + wrapper: ReturnType + input: HTMLInputElement + /** The draft the form would hold: the last value the field reported. */ + draft: () => FieldAnswer | undefined + /** Shows errors on the field, as a failed submit does. */ + setErrors: (errors: FieldError[]) => Promise +} + +/** The field with a parent that feeds every reported value back in, like the form does. */ +function mountField(initial?: string, errors: FieldError[] = [], dateField: DateFormField = field): Mounted { + let reported: FieldAnswer | undefined = initial + const wrapper = mount(DateField, { + props: { + field: dateField, + modelValue: initial, + errors, + disabled: false, + readonly: false, + 'onUpdate:modelValue': (value: FieldAnswer | undefined) => { + reported = value + void wrapper.setProps({ modelValue: value }) + }, + }, + global: { plugins: [PrimeVuePlugin] }, + attachTo: document.body, + }) + return { + wrapper, + input: wrapper.find('input').element as HTMLInputElement, + draft: () => reported, + setErrors: async (next) => { await wrapper.setProps({ errors: next }) }, + } +} + +/** One `input` event for the text now in the box, like a key press or a paste. */ +async function inputEvent(input: HTMLInputElement, text: string) { + input.value = text + input.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: text })) + await flushPromises() +} + +/** Types `text` at the end of the box, one key at a time, checking after each key that the box still holds what was typed. */ +async function typeKeys(input: HTMLInputElement, text: string) { + input.focus() + let typed = input.value + for (const key of text) { + typed += key + await inputEvent(input, typed) + expect(input.value, `after typing "${typed}"`).toBe(typed) + } +} + +async function blur(input: HTMLInputElement) { + input.dispatchEvent(new FocusEvent('blur')) + await flushPromises() +} + +const INVALID_DATE: FieldError[] = [{ code: 'invalid_date', message: 'Enter a valid date as YYYY-MM-DD.' }] + +describe('date field: typing', () => { + it('keeps every key in the box while a date is typed one key at a time', async () => { + const { input } = mountField() + await typeKeys(input, '2026-06-15') + expect(input.value).toBe('2026-06-15') + }) + + it('updates the draft with the full date once it is typed', async () => { + const { input, draft } = mountField() + await typeKeys(input, '2026-06-15') + expect(draft()).toBe('2026-06-15') + }) + + it('shows what was typed at every step, including the steps that are not dates yet', async () => { + const { input, draft } = mountField() + await typeKeys(input, '2026-06-') + expect(input.value).toBe('2026-06-') + expect(draft()).toBe('2026-06-') + }) + + it('reports text it cannot parse as typed, and keeps it in the box', async () => { + const { input, draft } = mountField() + await typeKeys(input, 'next tuesday') + expect(input.value).toBe('next tuesday') + expect(draft()).toBe('next tuesday') + }) + + it('reports an impossible day (February 30) as typed, and keeps it in the box', async () => { + const { input, draft } = mountField() + await typeKeys(input, '2026-02-30') + expect(input.value).toBe('2026-02-30') + expect(draft()).toBe('2026-02-30') + }) + + it('reports a date outside min and max as typed, and keeps it in the box', async () => { + const { input, draft } = mountField() + await typeKeys(input, '2025-12-31') + expect(input.value).toBe('2025-12-31') + expect(draft()).toBe('2025-12-31') + await inputEvent(input, '2028-01-01') + expect(input.value).toBe('2028-01-01') + expect(draft()).toBe('2028-01-01') + }) + + it('keeps the old text of a valid date out of the box when invalid text is pasted over it', async () => { + const { input, draft } = mountField('2026-12-31') + await inputEvent(input, '2026-02-30') + expect(input.value).toBe('2026-02-30') + expect(draft()).toBe('2026-02-30') + await inputEvent(input, 'not a date') + expect(input.value).toBe('not a date') + expect(draft()).toBe('not a date') + await inputEvent(input, '31/12/2026') + expect(input.value).toBe('31/12/2026') + }) + + it('does not rewrite the box while the user edits in the middle of the text', async () => { + const { input } = mountField() + await typeKeys(input, '2026-06-15') + input.setSelectionRange(5, 5) + input.value = '2026-x06-15' + input.setSelectionRange(6, 6) + input.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText', data: 'x' })) + await flushPromises() + expect(input.value).toBe('2026-x06-15') + // A rewrite of the box would have moved the caret to the end. + expect(input.selectionStart).toBe(6) + }) + + it('reports an emptied box as empty text', async () => { + const { input, draft } = mountField('2026-06-15') + await inputEvent(input, '') + expect(input.value).toBe('') + expect(draft()).toBe('') + }) + + it('keeps the typed text when an error appears on the field', async () => { + const { input, setErrors } = mountField('2026-12-31') + await inputEvent(input, '2026-02-30') + await setErrors(INVALID_DATE) + expect(input.value).toBe('2026-02-30') + }) + + it('keeps the typed text when the field is disabled and enabled again (a submit in flight)', async () => { + const { wrapper, input } = mountField() + await typeKeys(input, 'next tuesday') + await wrapper.setProps({ disabled: true }) + await wrapper.setProps({ disabled: false }) + expect(input.value).toBe('next tuesday') + }) + + it('keeps unparseable text in the box after leaving it, so the user can correct it', async () => { + const { input, draft } = mountField('2026-06-15') + input.focus() + await inputEvent(input, 'next tuesday') + await blur(input) + expect(input.value).toBe('next tuesday') + expect(draft()).toBe('next tuesday') + }) + + it('keeps an impossible date in the box after leaving it', async () => { + const { input } = mountField() + await typeKeys(input, '2026-02-30') + await blur(input) + expect(input.value).toBe('2026-02-30') + }) + + it('leaves a valid typed date as it was typed after leaving the box', async () => { + const { input, draft } = mountField() + await typeKeys(input, '2026-06-15') + await blur(input) + expect(input.value).toBe('2026-06-15') + expect(draft()).toBe('2026-06-15') + }) + + it('shows a date typed in a looser form in the form it is saved in once the box is left', async () => { + const { input, draft } = mountField() + await typeKeys(input, '2026-6-5') + // The picker understood the text, so what will be saved is the full date. + expect(draft()).toBe('2026-06-05') + await blur(input) + expect(input.value).toBe('2026-06-05') + }) + + it('goes on typing after a blur', async () => { + const { input, draft } = mountField() + await typeKeys(input, '2026-06') + await blur(input) + await typeKeys(input, '-15') + expect(input.value).toBe('2026-06-15') + expect(draft()).toBe('2026-06-15') + }) +}) + +/** The enabled days of the month the calendar shows (not the greyed days of the months around it). */ +function enabledDays(): HTMLElement[] { + return Array.from(document.querySelectorAll('.p-datepicker-day')) + .filter(el => el.getAttribute('aria-disabled') !== 'true' && !(el.getAttribute('data-p') ?? '').includes('other-month')) +} + +function dayCell(label: string): HTMLElement { + const cell = enabledDays().find(el => el.textContent?.trim() === label) + if (!cell) + throw new Error(`no enabled day cell "${label}"`) + return cell +} + +/** The month name in the open calendar's header. */ +function shownMonth(): string | undefined { + return document.querySelector('.p-datepicker-select-month')?.textContent?.trim() +} + +async function openCalendar(wrapper: Mounted['wrapper']) { + await wrapper.find('button[aria-haspopup="dialog"]').trigger('click') + await nextTick() +} + +describe('date field: width of the control', () => { + // The stylesheet bounds the control through this part and class (see + // styles.test.ts); without them the date box would fill the whole form and + // so would the calendar the theme opens at least as wide as it. + it('names the picker as the date state of the input part and class, which the stylesheet bounds in width', () => { + const { wrapper } = mountField() + const picker = wrapper.find('.p-datepicker') + expect(picker.attributes('part')?.split(' ')).toEqual(['field-input', 'field-input-date']) + expect(picker.classes()).toEqual(expect.arrayContaining(['w-form__field-input', 'w-form__field-input--date'])) + }) + + it('leaves the input fields of other types without the date state', () => { + const wrapper = mount(FormFieldControl, { props: { field: { id: 'a', type: 'text', min_length: 0, max_length: 500, label: 'A', required: false }, modelValue: undefined, errors: [], disabled: false, readonly: false }, global: { plugins: [PrimeVuePlugin] } }) + expect(wrapper.find('input').attributes('part')).toBe('field-input') + }) +}) + +describe('date field: calendar', () => { + it('puts a day picked in the calendar in the draft and the box', async () => { + const { wrapper, input, draft } = mountField('2026-10-15') + await wrapper.find('button[aria-haspopup="dialog"]').trigger('click') + await nextTick() + dayCell('20').click() + await flushPromises() + expect(draft()).toBe('2026-10-20') + expect(input.value).toBe('2026-10-20') + }) + + it('replaces unparseable typed text when a day is picked', async () => { + const { wrapper, input, draft } = mountField() + await typeKeys(input, 'next tuesday') + await wrapper.find('button[aria-haspopup="dialog"]').trigger('click') + await nextTick() + // The calendar opens on the current month; any enabled day will do. + enabledDays()[0]?.click() + await flushPromises() + expect(draft()).toMatch(/^\d{4}-\d{2}-\d{2}$/) + expect(input.value).toBe(draft()) + }) + + it('keeps the typed text in the box when the calendar is opened and closed without a pick', async () => { + const { wrapper, input, draft } = mountField('2026-06-15') + await inputEvent(input, 'next tuesday') + await wrapper.find('button[aria-haspopup="dialog"]').trigger('click') + await nextTick() + expect(input.value).toBe('next tuesday') + input.dispatchEvent(new KeyboardEvent('keydown', { code: 'Escape', bubbles: true })) + await flushPromises() + expect(input.value).toBe('next tuesday') + expect(draft()).toBe('next tuesday') + }) + + it('shows a value the draft changes to from outside', async () => { + const { wrapper, input } = mountField('2026-06-15') + await wrapper.setProps({ modelValue: '2026-07-01' }) + await flushPromises() + expect(input.value).toBe('2026-07-01') + }) +}) + +describe('date field: calendar overlay', () => { + /** The field mounted inside a shadow root, as the web component is: a themed container next to the overlay layer the theme plugin creates. */ + function mountInShadow(themeClass = 'w-theme-dark') { + const host = document.createElement('div') + document.body.appendChild(host) + const shadow = host.attachShadow({ mode: 'open' }) + const container = document.createElement('div') + container.setAttribute('data-wippy-theme-root', '') + if (themeClass) + container.className = themeClass + shadow.appendChild(container) + const app = createApp(defineComponent({ + setup: () => { + const value = ref('2026-10-15') + return () => h(DateField, { 'field': field, 'modelValue': value.value, 'errors': [], 'disabled': false, 'readonly': false, 'onUpdate:modelValue': (v: FieldAnswer | undefined) => { value.value = v } }) + }, + })) + app.use(PrimeVuePlugin) + app.mount(container) + return { host, shadow, container, app } + } + + async function openCalendar(shadow: ShadowRoot) { + await nextTick() + shadow.querySelector('button[aria-haspopup="dialog"]')?.click() + await nextTick() + await nextTick() + const panel = shadow.querySelector('.p-datepicker-panel') + expect(panel, 'the calendar is open').not.toBeNull() + return panel as HTMLElement + } + + /** The layer around the calendar, where the theme plugin puts the theme class. */ + function overlayLayer(panel: HTMLElement): HTMLElement { + return panel.closest('[data-wippy-overlay-layer]') as HTMLElement + } + + it('opens in a layer with the forced Dark theme class of the container, so the Dark theme reaches it', async () => { + const { host, shadow, app } = mountInShadow('w-theme-dark') + const layer = overlayLayer(await openCalendar(shadow)) + expect(layer.classList.contains('w-theme-dark')).toBe(true) + expect(layer.classList.contains('w-theme-light')).toBe(false) + app.unmount() + host.remove() + }) + + it('opens in a layer with the forced Light theme class of the container', async () => { + const { host, shadow, app } = mountInShadow('w-theme-light') + const layer = overlayLayer(await openCalendar(shadow)) + expect(layer.classList.contains('w-theme-light')).toBe(true) + expect(layer.classList.contains('w-theme-dark')).toBe(false) + app.unmount() + host.remove() + }) + + it('opens in a layer with no theme class when the theme follows the OS, so the OS scheme applies', async () => { + const { host, shadow, app } = mountInShadow('') + const layer = overlayLayer(await openCalendar(shadow)) + expect(layer.classList.contains('w-theme-dark')).toBe(false) + expect(layer.classList.contains('w-theme-light')).toBe(false) + app.unmount() + host.remove() + }) + + it('follows the theme while the calendar is open', async () => { + const { host, shadow, container, app } = mountInShadow('w-theme-light') + const layer = overlayLayer(await openCalendar(shadow)) + container.classList.replace('w-theme-light', 'w-theme-dark') + await Promise.resolve() + await nextTick() + expect(layer.classList.contains('w-theme-dark')).toBe(true) + expect(layer.classList.contains('w-theme-light')).toBe(false) + app.unmount() + host.remove() + }) + + it('opens in the theme plugin\'s overlay layer, outside the message around the form, so no ancestor clips it', async () => { + const { host, shadow, container, app } = mountInShadow() + const panel = await openCalendar(shadow) + expect(panel.closest('[data-wippy-overlay-layer]'), 'inside the overlay layer').not.toBeNull() + expect(container.contains(panel), 'not inline in the form').toBe(false) + app.unmount() + host.remove() + }) + + it('names the calendar as a part and a class, for the styling API', async () => { + const { host, shadow, app } = mountInShadow() + const panel = await openCalendar(shadow) + expect(panel.getAttribute('part')).toContain('field-calendar') + expect(panel.classList.contains('w-form__field-calendar')).toBe(true) + app.unmount() + host.remove() + }) +}) + +describe('date field: a tap on a touch screen', () => { + afterEach(() => { + vi.restoreAllMocks() + }) + + /** Makes `(pointer: coarse)` match or not, as on a touch screen or with a mouse. */ + function usePointer(coarse: boolean) { + vi.spyOn(window, 'matchMedia').mockImplementation((query: string) => ({ + matches: coarse && query === '(pointer: coarse)', + media: query, + onchange: null, + addEventListener() {}, + removeEventListener() {}, + addListener() {}, + removeListener() {}, + dispatchEvent: () => false, + }) as MediaQueryList) + } + + const tap = (input: HTMLInputElement) => input.dispatchEvent(new MouseEvent('click', { bubbles: true })) + const expanded = (input: HTMLInputElement) => input.getAttribute('aria-expanded') + + // PrimeVue gives the box inputmode="none" (no keyboard on a phone) and the + // field never opens on focus, so without this a tap on the box did nothing. + it('opens the calendar when the box is tapped', async () => { + usePointer(true) + const { input } = mountField() + expect(expanded(input)).toBe('false') + tap(input) + await flushPromises() + expect(expanded(input)).toBe('true') + expect(document.querySelector('.p-datepicker-panel')).not.toBeNull() + }) + + it('leaves the calendar open on a second tap', async () => { + usePointer(true) + const { input } = mountField() + tap(input) + await flushPromises() + tap(input) + await flushPromises() + expect(expanded(input)).toBe('true') + }) + + it('does not open the calendar on a click with a mouse: it opens from its button, so a typist can just type', async () => { + usePointer(false) + const { input } = mountField() + tap(input) + await flushPromises() + expect(expanded(input)).toBe('false') + expect(document.querySelector('.p-datepicker-panel')).toBeNull() + }) + + it('does not open the calendar on focus, even on a touch screen, so a hardware keyboard can still type', async () => { + usePointer(true) + const { input } = mountField() + input.focus() + input.dispatchEvent(new FocusEvent('focus')) + await flushPromises() + expect(expanded(input)).toBe('false') + }) + + it('does not open the calendar of a disabled field', async () => { + usePointer(true) + const { wrapper, input } = mountField() + await wrapper.setProps({ disabled: true }) + tap(input) + await flushPromises() + expect(expanded(input)).toBe('false') + }) +}) + +describe('date field: a reload of the form', () => { + it('leaves the calendar on the month the user navigated to when the field arrives again with the same content', async () => { + const { wrapper } = mountField('2026-10-15') + await openCalendar(wrapper) + expect(shownMonth()).toBe('October') + document.querySelector('.p-datepicker-next-button')?.click() + await flushPromises() + expect(shownMonth()).toBe('November') + + // A state reload hands over a new field object; its min and max are the same text. + await wrapper.setProps({ field: { ...field } }) + await flushPromises() + expect(shownMonth()).toBe('November') + }) + + it('still applies a bound that really changed', async () => { + const { wrapper } = mountField('2026-10-15') + await openCalendar(wrapper) + expect(enabledDays().some(el => el.textContent?.trim() === '25')).toBe(true) + await wrapper.setProps({ field: { ...field, max: '2026-10-20' } }) + await flushPromises() + expect(enabledDays().some(el => el.textContent?.trim() === '25')).toBe(false) + expect(enabledDays().some(el => el.textContent?.trim() === '20')).toBe(true) + }) +}) + +describe('date field: years before 1000', () => { + // No min and max: with them PrimeVue would refuse the text instead of rewriting it. + const unbounded: DateFormField = { id: 'day', type: 'date', label: 'Delivery date', required: true } + + // PrimeVue reads a year below 100 as a two-digit year (0050 becomes 1950). + it.each(['0050-03-04', '0099-12-31'])('reports %s as typed, not as the date the picker reads from it', async (text) => { + const { input, draft } = mountField(undefined, [], unbounded) + await typeKeys(input, text) + expect(draft()).toBe(text) + expect(input.value).toBe(text) + await blur(input) + expect(input.value).toBe(text) + expect(draft()).toBe(text) + }) + + // PrimeVue writes the year without padding (999-05-15). + it.each(['0100-02-03', '0999-05-15'])('reports %s with its four-digit year', async (text) => { + const { input, draft } = mountField(undefined, [], unbounded) + await typeKeys(input, text) + expect(draft()).toBe(text) + await blur(input) + expect(input.value).toBe(text) + }) + + it('pads the year of a day picked in the calendar', async () => { + const { wrapper, input, draft } = mountField('0999-05-15', [], unbounded) + await openCalendar(wrapper) + dayCell('20').click() + await flushPromises() + expect(draft()).toBe('0999-05-20') + expect(input.value).toBe('0999-05-20') + }) + + it('leaves a four-digit year as the picker writes it', async () => { + const { wrapper, draft } = mountField('2026-10-15', [], unbounded) + await openCalendar(wrapper) + dayCell('20').click() + await flushPromises() + expect(draft()).toBe('2026-10-20') + }) +}) + +describe('date field: keyboard and input methods', () => { + it('keeps a loosely typed date through Tab and Enter, and opens the calendar on that day', async () => { + const user = userEvent.setup() + const { input, draft } = mountField() + await user.click(input) + await user.keyboard('2026-6-5') + expect(draft()).toBe('2026-06-05') + + // Tab leaves the box for the calendar button, and the box shows the full date. + await user.tab() + expect(document.activeElement).not.toBe(input) + expect(input.value).toBe('2026-06-05') + + // Enter on the calendar button opens the calendar on the date that was typed. + await user.keyboard('{Enter}') + await flushPromises() + expect(input.getAttribute('aria-expanded')).toBe('true') + expect(shownMonth()).toBe('June') + expect(document.querySelector('.p-datepicker-day-selected')?.textContent?.trim()).toBe('5') + expect(input.value).toBe('2026-06-05') + expect(draft()).toBe('2026-06-05') + }) + + it('keeps the composed text and never rewrites the box while an input method is composing', async () => { + const { input, draft } = mountField() + input.focus() + const native = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value') as PropertyDescriptor & { get: () => string, set: (v: string) => void } + // Records every write to the box that changes what it shows while a render runs. + let rendering = false + const rewrites: string[] = [] + Object.defineProperty(input, 'value', { + configurable: true, + get() { return native.get.call(this) }, + set(next: string) { + if (rendering && next !== native.get.call(this)) + rewrites.push(next) + native.set.call(this, next) + }, + }) + + input.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true })) + for (const text of ['2', '20', '202', '2026']) { + input.value = text + input.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertCompositionText', isComposing: true, data: text })) + rendering = true + await flushPromises() + rendering = false + expect(input.value, `while composing "${text}"`).toBe(text) + } + input.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '2026' })) + await typeKeys(input, '-06-15') + + expect(rewrites).toEqual([]) + expect(input.value).toBe('2026-06-15') + expect(draft()).toBe('2026-06-15') + }) +}) + +describe('date field: focus when the calendar closes', () => { + /* + * PrimeVue puts focus on the box with `input.focus()` when a day is picked, + * but its own delayed re-focus of the calendar's cells (a + * `setTimeout(updateFocus, 0)` queued by every render of the picker, which + * only skips a cell when `overlay.contains(document.activeElement)`) can run + * after that and put focus on the first day cell. Inside the component's + * shadow root `document.activeElement` is the shadow host, so the check never + * sees the box, and when the calendar closes a moment later the browser drops + * focus to the page. These tests run in a shadow root with fake timers, as the + * web component does, and drive the keyboard path the calendar offers. + */ + // The calendar's keyboard focus starts on today's cell, so today is pinned to + // 1 October 2026 (local time) and the picked day does not depend on the clock. + beforeEach(() => { + vi.useFakeTimers({ now: new Date(2026, 9, 1, 12) }) + }) + + const hosts: HTMLElement[] = [] + + afterEach(() => { + hosts.splice(0).forEach(host => host.remove()) + vi.useRealTimers() + vi.restoreAllMocks() + }) + + const ERROR: FieldError[] = [{ code: 'required', message: 'Choose a date.' }] + + /** + * The field in a shadow root, with a button beside it to move focus to, and a way to re-render the field. + * It keeps the real Transition: the picker reports `hide` from its leave hook, and the stub Test Utils + * puts in its place by default never runs it. + */ + function mountView() { + const host = document.createElement('div') + document.body.appendChild(host) + hosts.push(host) + const shadow = host.attachShadow({ mode: 'open' }) + const container = document.createElement('div') + container.setAttribute('data-wippy-theme-root', '') + const elsewhere = document.createElement('button') + elsewhere.textContent = 'Elsewhere' + shadow.append(container, elsewhere) + const wrapper = mount(DateField, { + props: { + field, + modelValue: '2026-10-15', + errors: [], + disabled: false, + readonly: false, + 'onUpdate:modelValue': (value: FieldAnswer | undefined) => { void wrapper.setProps({ modelValue: value }) }, + }, + global: { plugins: [PrimeVuePlugin], stubs: { transition: false } }, + attachTo: container, + }) + return { + shadow, + elsewhere, + input: () => shadow.querySelector('input') as HTMLInputElement, + focused: () => shadow.activeElement, + /** The form re-rendering the field a moment after something happened to it. */ + rerender: async () => { + await wrapper.setProps({ errors: wrapper.props('errors').length > 0 ? [] : ERROR }) + }, + } + } + + type View = ReturnType + + function press(target: Element | null, code: string, shiftKey = false) { + target?.dispatchEvent(new KeyboardEvent('keydown', { code, shiftKey, bubbles: true, cancelable: true })) + } + + /** ArrowDown in the box opens the calendar. */ + async function openCalendar(view: View) { + await nextTick() + view.input().focus() + press(view.input(), 'ArrowDown') + await nextTick() + await nextTick() + await vi.advanceTimersByTimeAsync(100) + expect(view.shadow.querySelector('.p-datepicker-panel'), 'the calendar is open').not.toBeNull() + } + + /** A second ArrowDown moves focus from the box into the days. */ + async function openIntoDays(view: View) { + await openCalendar(view) + press(view.input(), 'ArrowDown') + expect(view.focused()?.closest('.p-datepicker-panel'), 'focus is in the calendar').not.toBeNull() + } + + /** + * Waits out the delay after a pick (the calendar closes 150 ms after it) and the render that removes it. + * The renders the last key queued run first, as they do in a browser, where microtasks run before any timer. + */ + async function settle() { + await nextTick() + await vi.advanceTimersByTimeAsync(1000) + await nextTick() + } + + /** A mouse press somewhere outside the field, which is what closes the calendar for a mouse user. */ + function pressOutside(target: Element) { + target.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, composed: true })) + } + + function expectClosed(view: View) { + expect(view.shadow.querySelector('.p-datepicker-panel'), 'the calendar has closed').toBeNull() + } + + it('walks Tab and Shift+Tab through the calendar in a shadow root, where document.activeElement is the host', async () => { + const view = mountView() + await openIntoDays(view) + const day = view.focused() + expect(day?.tagName).toBe('SPAN') + + // Round the panel from the day: its last stop, so Tab goes to the first. + press(view.focused(), 'Tab') + const first = view.focused() + expect(first?.tagName).toBe('BUTTON') + press(view.focused(), 'Tab') + const second = view.focused() + expect(second?.tagName).toBe('BUTTON') + expect(second).not.toBe(first) + press(view.focused(), 'Tab', true) + expect(view.focused()).toBe(first) + press(view.focused(), 'Tab', true) + expect(view.focused()).toBe(day) + }) + + it('puts focus on the box after a day is picked from the keyboard', async () => { + const view = mountView() + await openIntoDays(view) + press(view.focused(), 'ArrowRight') + press(view.focused(), 'Enter') + await settle() + expectClosed(view) + expect(view.input().value).toBe('2026-10-02') + expect(view.focused()).toBe(view.input()) + }) + + it('puts focus on the box after a keyboard pick even when the form re-renders the field just after it', async () => { + const view = mountView() + await openIntoDays(view) + press(view.focused(), 'ArrowRight') + press(view.focused(), 'Enter') + await nextTick() + // Two renders of the picker before its zero-delay re-focus timers run: the first + // timer consumes the picker's "do not focus" flag, the second focuses a day cell. + await view.rerender() + await vi.advanceTimersByTimeAsync(20) + expect(view.focused()?.closest('.p-datepicker-panel'), 'PrimeVue has moved focus into the calendar').not.toBeNull() + await settle() + expectClosed(view) + expect(view.focused()).toBe(view.input()) + }) + + it('puts focus on the box after Escape closes the calendar from a day', async () => { + const view = mountView() + await openIntoDays(view) + press(view.focused(), 'Escape') + await settle() + expectClosed(view) + expect(view.input().value).toBe('2026-10-15') + expect(view.focused()).toBe(view.input()) + }) + + it('does not scroll the page when it gives the box focus back', async () => { + const view = mountView() + await openIntoDays(view) + const focus = vi.spyOn(view.input(), 'focus') + press(view.focused(), 'ArrowRight') + press(view.focused(), 'Enter') + await nextTick() + await view.rerender() + await settle() + expect(focus.mock.calls.some(([options]) => options?.preventScroll === true)).toBe(true) + }) + + it('leaves focus where the user put it when they moved it before the calendar closed', async () => { + const view = mountView() + await openIntoDays(view) + view.elsewhere.focus() + pressOutside(view.elsewhere) + await settle() + expectClosed(view) + expect(view.focused()).toBe(view.elsewhere) + }) + + it('does not take focus when nothing in the form had it as the calendar closed', async () => { + const view = mountView() + await openIntoDays(view) + ;(view.focused() as HTMLElement).blur() + expect(view.focused()).toBeNull() + pressOutside(view.elsewhere) + await settle() + expectClosed(view) + expect(view.focused()).toBeNull() + }) + + it('leaves focus on the control Tab moves it to when the calendar closes as the box is left', async () => { + const view = mountView() + await openCalendar(view) + // Tab from the box closes the calendar; the browser then moves focus on, here to the button beside the form. + press(view.input(), 'Tab') + view.elsewhere.focus() + await settle() + expectClosed(view) + expect(view.focused()).toBe(view.elsewhere) + }) +}) diff --git a/frontend/wippy-form/src/app/fields/date-field.vue b/frontend/wippy-form/src/app/fields/date-field.vue new file mode 100644 index 0000000..489fa42 --- /dev/null +++ b/frontend/wippy-form/src/app/fields/date-field.vue @@ -0,0 +1,306 @@ + + + diff --git a/frontend/wippy-form/src/app/fields/field-label.test.ts b/frontend/wippy-form/src/app/fields/field-label.test.ts new file mode 100644 index 0000000..13913b2 --- /dev/null +++ b/frontend/wippy-form/src/app/fields/field-label.test.ts @@ -0,0 +1,40 @@ +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import FieldLabel from './field-label.vue' + +function mountLabel(props: Partial<{ tag: 'label' | 'legend' | 'span', required: boolean }> = {}) { + return mount(FieldLabel, { props: { tag: 'label', controlId: 'control-1', label: 'Full name', required: false, ...props } }) +} + +describe('FieldLabel', () => { + it('is a label pointing at the control, under the field-label part and class', () => { + const wrapper = mountLabel() + expect(wrapper.element.tagName).toBe('LABEL') + expect(wrapper.attributes('for')).toBe('control-1') + expect(wrapper.attributes('part')).toBe('field-label') + expect(wrapper.classes()).toContain('w-form__field-label') + expect(wrapper.text()).toBe('Full name') + }) + + it('is a legend or a span that points at nothing', () => { + for (const tag of ['legend', 'span'] as const) { + const wrapper = mountLabel({ tag }) + expect(wrapper.element.tagName).toBe(tag.toUpperCase()) + expect(wrapper.attributes('for'), tag).toBeUndefined() + } + }) + + it('adds the required marker as text, under its own part and class, in every tag', () => { + for (const tag of ['label', 'legend', 'span'] as const) { + const wrapper = mountLabel({ tag, required: true }) + expect(wrapper.text(), tag).toBe('Full name (required)') + const marker = wrapper.find('[part~="field-marker"]') + expect(marker.text(), tag).toBe('(required)') + expect(marker.classes(), tag).toContain('w-form__field-marker') + } + }) + + it('shows no marker when the field is not required', () => { + expect(mountLabel().find('[part~="field-marker"]').exists()).toBe(false) + }) +}) diff --git a/frontend/wippy-form/src/app/fields/field-label.vue b/frontend/wippy-form/src/app/fields/field-label.vue new file mode 100644 index 0000000..bf78316 --- /dev/null +++ b/frontend/wippy-form/src/app/fields/field-label.vue @@ -0,0 +1,38 @@ + + + diff --git a/frontend/wippy-form/src/app/fields/field-shell.test.ts b/frontend/wippy-form/src/app/fields/field-shell.test.ts new file mode 100644 index 0000000..6300798 --- /dev/null +++ b/frontend/wippy-form/src/app/fields/field-shell.test.ts @@ -0,0 +1,178 @@ +import type { FieldAnswer, FieldError, FormField } from '../../lib/definition' +import { PrimeVuePlugin } from '@wippy-fe/theme/primevue-plugin' +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import FieldShell from './field-shell.vue' + +const textField: FormField = { id: 'name', type: 'text', min_length: 0, max_length: 500, label: 'Full name', required: true, description: 'As on the parcel' } + +const CONTROL_SLOT = `` + +function mountShell(props: Partial<{ field: FormField, modelValue: FieldAnswer | undefined, errors: FieldError[], readonly: boolean, disabled: boolean, layout: 'group' | 'stacked' | 'inline' }> = {}) { + return mount(FieldShell, { + props: { field: textField, modelValue: undefined, errors: [], readonly: false, disabled: false, layout: 'stacked', ...props }, + slots: { default: CONTROL_SLOT }, + global: { plugins: [PrimeVuePlugin] }, + }) +} + +describe('FieldShell — stacked layout (one labelled control)', () => { + it('labels the real control: the label points at the id the slot receives', () => { + const wrapper = mountShell() + const input = wrapper.find('input') + const label = wrapper.find('label') + expect(label.attributes('for')).toBe(input.attributes('id')) + expect(label.text()).toContain('Full name') + }) + + it('shows the required marker as text on an editable required field', () => { + expect(mountShell().find('label').text()).toContain('(required)') + expect(mountShell({ field: { ...textField, required: false } }).find('label').text()).not.toContain('(required)') + }) + + it('describes the control with the description and, once there are errors, the error list', () => { + const wrapper = mountShell({ errors: [{ code: 'required', message: 'This question is required.' }] }) + const describedBy = wrapper.find('input').attributes('aria-describedby') ?? '' + const description = wrapper.find('p') + const errorList = wrapper.find('ul') + expect(description.text()).toBe('As on the parcel') + expect(describedBy.split(' ')).toEqual([description.attributes('id'), errorList.attributes('id')]) + expect(errorList.text()).toContain('This question is required.') + expect(wrapper.find('input').attributes('aria-invalid')).toBe('true') + }) + + it('does not point aria-describedby at an error list that is not rendered', () => { + const wrapper = mountShell({ field: { ...textField, description: undefined } }) + expect(wrapper.find('input').attributes('aria-describedby')).toBeUndefined() + expect(wrapper.find('ul').exists()).toBe(false) + expect(wrapper.find('input').attributes('aria-invalid')).toBeUndefined() + }) + + it('derives the control, description and error ids from one base, all distinct', () => { + const wrapper = mountShell({ errors: [{ code: 'required', message: 'This question is required.' }] }) + const ids = [wrapper.find('input').attributes('id'), wrapper.find('p').attributes('id'), wrapper.find('ul').attributes('id')] + expect(ids.every(id => !!id)).toBe(true) + expect(new Set(ids).size).toBe(3) + }) + + it('never uses role="alert" (one polite live region announces the summary instead)', () => { + const wrapper = mountShell({ errors: [{ code: 'required', message: 'This question is required.' }] }) + expect(wrapper.find('[role="alert"]').exists()).toBe(false) + }) + + it('exposes focusFirstControl, which focuses the slotted control', async () => { + const wrapper = mount(FieldShell, { + props: { field: textField, modelValue: undefined, errors: [], readonly: false, disabled: false, layout: 'stacked' }, + slots: { default: CONTROL_SLOT }, + global: { plugins: [PrimeVuePlugin] }, + attachTo: document.body, + }) + ;(wrapper.vm as unknown as { focusFirstControl: () => void }).focusFirstControl() + expect(document.activeElement).toBe(wrapper.find('input').element) + }) +}) + +describe('FieldShell — styling API of the row and the stored answer items', () => { + it('names the row of a checkbox and its label', () => { + const wrapper = mountShell({ layout: 'inline', field: { id: 'ok', type: 'checkbox', label: 'I agree', required: true } }) + const row = wrapper.find('.w-form__field-row') + expect(row.attributes('part')).toBe('field-row') + }) + + it('names each item of a stored choice', () => { + const field: FormField = { id: 'pick', type: 'choice', label: 'Pick', required: false, multiple: false, allow_other: false, options: [{ value: 'a', label: 'A' }] } + const wrapper = mountShell({ layout: 'group', readonly: true, field, modelValue: 'a' }) + const item = wrapper.find('.w-form__field-item') + expect(item.attributes('part')).toBe('field-item') + }) +}) + +describe('FieldShell — inline layout (checkbox)', () => { + it('puts the control first and a clickable label that points at it', () => { + const wrapper = mountShell({ layout: 'inline', field: { id: 'ok', type: 'checkbox', label: 'I agree', required: true } }) + const input = wrapper.find('input') + const label = wrapper.find('label') + expect(label.attributes('for')).toBe(input.attributes('id')) + expect(label.text()).toContain('I agree') + const html = wrapper.html() + expect(html.indexOf(' { + it('is a fieldset with a legend and describes the fieldset itself', () => { + const wrapper = mountShell({ layout: 'group', errors: [{ code: 'required', message: 'This question is required.' }] }) + const fieldset = wrapper.find('fieldset') + expect(fieldset.exists()).toBe(true) + expect(fieldset.find('legend').text()).toContain('Full name') + expect(fieldset.attributes('aria-describedby')).toContain(wrapper.find('ul').attributes('id') as string) + expect(wrapper.find('label').exists()).toBe(false) + }) +}) + +describe('FieldShell — read-only', () => { + it('shows the value instead of the control, with no required marker and no errors', () => { + const wrapper = mountShell({ readonly: true, modelValue: 'Ada', errors: [{ code: 'required', message: 'x' }] }) + expect(wrapper.find('input').exists()).toBe(false) + expect(wrapper.text()).toContain('Ada') + expect(wrapper.text()).not.toContain('(required)') + expect(wrapper.find('ul').exists()).toBe(false) + expect(wrapper.find('label').exists()).toBe(false) + }) + + it('keeps a text value\'s line breaks as real line breaks', () => { + const wrapper = mountShell({ readonly: true, field: { id: 'n', type: 'textarea', min_length: 0, max_length: 8000, label: 'Notes', required: false }, modelValue: 'one\ntwo' }) + expect(wrapper.find('[part~="field-value"]').html()).toContain('one
two') + }) + + it('words an unanswered field "Skipped"', () => { + const wrapper = mountShell({ readonly: true, modelValue: undefined }) + expect(wrapper.find('[part~="field-value"]').text()).toBe('Skipped') + expect(wrapper.find('[part~="field-value-empty"]').exists()).toBe(true) + }) + + it('shows a checkbox as Yes or No and a number as stored', () => { + const yes = mountShell({ readonly: true, field: { id: 'c', type: 'checkbox', label: 'C', required: false }, modelValue: true }) + expect(yes.find('[part~="field-value"]').text()).toBe('Yes') + const no = mountShell({ readonly: true, field: { id: 'c', type: 'checkbox', label: 'C', required: false }, modelValue: false }) + expect(no.find('[part~="field-value"]').text()).toBe('No') + const num = mountShell({ readonly: true, field: { id: 'n', type: 'number', label: 'N', required: false }, modelValue: 0.5 }) + expect(num.find('[part~="field-value"]').text()).toBe('0.5') + }) + + it('shows a choice answer with its note and an Other entry', () => { + const choice: FormField = { id: 'p', type: 'choice', label: 'Speed', required: false, options: [{ value: 'a', label: 'Alpha' }], multiple: true, allow_other: true } + const wrapper = mountShell({ readonly: true, layout: 'group', field: choice, modelValue: [{ value: 'a', note: 'because' }, { other: 'mine' }] }) + const text = wrapper.find('[part~="field-value"]').text() + expect(text).toContain('Alpha') + expect(text).toContain('because') + expect(text).toContain('Other: mine') + }) +}) + +describe('FieldShell — styling API', () => { + it('names the field and its states as parts and w-form__ classes', () => { + const wrapper = mountShell({ errors: [{ code: 'required', message: 'x' }], disabled: true }) + const root = wrapper.element as HTMLElement + expect(root.getAttribute('part')?.split(' ')).toEqual(expect.arrayContaining(['field', 'field-required', 'field-invalid', 'field-disabled'])) + expect(root.className).toContain('w-form__field') + expect(root.className).toContain('w-form__field--required') + expect(root.className).toContain('w-form__field--invalid') + for (const part of ['field-label', 'field-marker', 'field-description', 'field-control', 'field-error']) + expect(wrapper.find(`[part~="${part}"]`).exists(), part).toBe(true) + expect(wrapper.find('[part~="field-label"]').classes()).toContain('w-form__field-label') + }) + + it('marks a read-only field with the readonly state part', () => { + const root = mountShell({ readonly: true }).element as HTMLElement + expect(root.getAttribute('part')?.split(' ')).toContain('field-readonly') + expect(root.className).toContain('w-form__field--readonly') + }) + + it('marks the layout as a state so styling can target it', () => { + expect((mountShell({ layout: 'group' }).element as HTMLElement).getAttribute('part')?.split(' ')).toContain('field-group') + expect((mountShell({ layout: 'inline' }).element as HTMLElement).getAttribute('part')?.split(' ')).toContain('field-inline') + }) +}) diff --git a/frontend/wippy-form/src/app/fields/field-shell.vue b/frontend/wippy-form/src/app/fields/field-shell.vue new file mode 100644 index 0000000..be8a0f6 --- /dev/null +++ b/frontend/wippy-form/src/app/fields/field-shell.vue @@ -0,0 +1,220 @@ + + + diff --git a/frontend/wippy-form/src/app/fields/form-field.test.ts b/frontend/wippy-form/src/app/fields/form-field.test.ts new file mode 100644 index 0000000..7d2c9cb --- /dev/null +++ b/frontend/wippy-form/src/app/fields/form-field.test.ts @@ -0,0 +1,370 @@ +import type { FieldAnswer, FieldError, FormField, NumberFormField } from '../../lib/definition' +import { PrimeVuePlugin } from '@wippy-fe/theme/primevue-plugin' +import { mount } from '@vue/test-utils' +import userEvent from '@testing-library/user-event' +import { afterEach, describe, expect, it, vi } from 'vitest' +import FormFieldControl from './form-field.vue' + +function mountField(field: FormField, props: Partial<{ modelValue: FieldAnswer | undefined, errors: FieldError[], disabled: boolean, readonly: boolean }> = {}) { + return mount(FormFieldControl, { + props: { field, modelValue: undefined, errors: [], disabled: false, readonly: false, ...props }, + global: { plugins: [PrimeVuePlugin] }, + attachTo: document.body, + }) +} + +const REQUIRED_ERROR: FieldError[] = [{ code: 'required', message: 'This question is required.' }] + +/** The last value a control reported through v-model. */ +function lastValue(wrapper: ReturnType): unknown { + const events = wrapper.emitted('update:modelValue') ?? [] + return events[events.length - 1]?.[0] +} + +describe('text field', () => { + const field: FormField = { id: 'name', type: 'text', min_length: 0, max_length: 500, label: 'Full name', required: true, description: 'As on the parcel', placeholder: 'Ada Lovelace' } + + it('is an InputText labelled by its own label element', () => { + const wrapper = mountField(field) + const input = wrapper.find('input') + expect(input.attributes('type')).toBe('text') + expect(input.attributes('placeholder')).toBe('Ada Lovelace') + expect(wrapper.find('label').attributes('for')).toBe(input.attributes('id')) + }) + + it('links the error and the description to the real input, not a wrapper', () => { + const wrapper = mountField(field, { errors: REQUIRED_ERROR }) + const input = wrapper.find('input') + const describedBy = (input.attributes('aria-describedby') ?? '').split(' ') + expect(describedBy).toContain(wrapper.find('p').attributes('id')) + expect(describedBy).toContain(wrapper.find('ul').attributes('id')) + expect(input.attributes('aria-invalid')).toBe('true') + expect(input.attributes('aria-required')).toBe('true') + }) + + it('reports what is typed through v-model, untrimmed', async () => { + const wrapper = mountField(field) + await wrapper.find('input').setValue(' Ada ') + expect(lastValue(wrapper)).toBe(' Ada ') + }) + + it('shows the draft it is given', () => { + expect((mountField(field, { modelValue: 'Berlin' }).find('input').element as HTMLInputElement).value).toBe('Berlin') + }) + + it('takes a placeholder from the definition, and only text and textarea do', () => { + expect(mountField({ id: 'a', type: 'textarea', min_length: 0, max_length: 8000, label: 'A', required: false, placeholder: 'Say more' }).find('textarea').attributes('placeholder')).toBe('Say more') + // The contract gives `placeholder` to text and textarea alone; a stray key on another type is not shown. + for (const type of ['email', 'number'] as const) { + const stray = { id: 'a', type, label: 'A', required: false, placeholder: 'ignored' } as unknown as FormField + expect(mountField(stray).find('input').attributes('placeholder'), type).toBeUndefined() + } + }) + + it('is disabled while the form is submitting', () => { + expect(mountField(field, { disabled: true }).find('input').attributes('disabled')).toBeDefined() + }) + + it('focuses its input on focusFirstControl', () => { + const wrapper = mountField(field) + ;(wrapper.vm as unknown as { focusFirstControl: () => void }).focusFirstControl() + expect(document.activeElement).toBe(wrapper.find('input').element) + }) +}) + +describe('textarea field', () => { + const field: FormField = { id: 'notes', type: 'textarea', min_length: 0, max_length: 8000, label: 'Notes', required: false } + + it('is a textarea whose newlines are kept', async () => { + const wrapper = mountField(field) + const textarea = wrapper.find('textarea') + expect(textarea.exists()).toBe(true) + await textarea.setValue('one\ntwo') + expect(lastValue(wrapper)).toBe('one\ntwo') + }) + + it('links its error to the textarea itself', () => { + const wrapper = mountField(field, { errors: [{ code: 'too_long', message: 'Use at most 8000 characters.' }] }) + expect(wrapper.find('textarea').attributes('aria-describedby')).toBe(wrapper.find('ul').attributes('id')) + expect(wrapper.find('textarea').attributes('aria-invalid')).toBe('true') + }) + + it('does not mark an optional field as required', () => { + expect(mountField(field).find('textarea').attributes('aria-required')).toBeUndefined() + }) +}) + +describe('email field', () => { + const field: FormField = { id: 'mail', type: 'email', label: 'Email', required: true } + + it('is an InputText of type email with the email keyboard hint', () => { + const input = mountField(field).find('input') + expect(input.attributes('type')).toBe('email') + expect(input.attributes('inputmode')).toBe('email') + }) + + // An agent may ask for someone else's address (a colleague, a recipient), so + // the browser must not offer the user's own. + it('turns autofill off: the address asked for is not necessarily the user\'s own', () => { + expect(mountField(field).find('input').attributes('autocomplete')).toBe('off') + }) + + it('links its error to the input', () => { + const wrapper = mountField(field, { errors: [{ code: 'invalid_email', message: 'Enter a valid email address.' }] }) + expect(wrapper.find('input').attributes('aria-describedby')).toBe(wrapper.find('ul').attributes('id')) + }) +}) + +describe('number field', () => { + const field: NumberFormField = { id: 'qty', type: 'number', label: 'Parcels', required: false, integer: true } + + afterEach(() => { + vi.restoreAllMocks() + }) + + /** Makes the browser's locale write decimals with `separator` (what `Intl.NumberFormat(undefined)` reports). */ + function useDecimalSeparator(separator: string) { + // A `function`, not an arrow: the code under test calls it with `new`. + vi.spyOn(Intl, 'NumberFormat').mockImplementation(function () { + return { + formatToParts: () => [{ type: 'integer', value: '1' }, { type: 'decimal', value: separator }, { type: 'fraction', value: '1' }], + } as unknown as Intl.NumberFormat + }) + } + + const keypad = (f: NumberFormField) => mountField(f).find('input').attributes('inputmode') + const fraction: NumberFormField = { id: 'w', type: 'number', label: 'Weight', required: false } + + it('is a text input, not a native number input or a spinner', () => { + const wrapper = mountField(field) + expect(wrapper.find('input').attributes('type')).toBe('text') + expect(wrapper.find('[role="spinbutton"]').exists()).toBe(false) + }) + + // `numeric` has no minus key and `decimal` has none on iOS, so either one + // locks out a negative value; the `decimal` keypad of a comma-decimal locale + // shows a comma, which the dot-only parser rejects. + it('shows the digit keypad for a whole number that cannot be negative', () => { + expect(keypad({ ...field, min: 0 })).toBe('numeric') + expect(keypad({ ...field, min: 5 })).toBe('numeric') + }) + + it('shows the full keyboard for a whole number that may be negative, so the minus key is there', () => { + expect(keypad(field)).toBe('text') + expect(keypad({ ...field, min: -5 })).toBe('text') + expect(keypad({ ...field, max: -1 })).toBe('text') + }) + + it('shows the decimal keypad for a fraction that cannot be negative when the locale writes a dot', () => { + useDecimalSeparator('.') + expect(keypad({ ...fraction, min: 0 })).toBe('decimal') + expect(keypad({ ...fraction, min: 0.5 })).toBe('decimal') + }) + + it('shows the full keyboard for a fraction in a locale that writes a comma, whose decimal keypad would type a comma', () => { + useDecimalSeparator(',') + expect(keypad({ ...fraction, min: 0 })).toBe('text') + // A whole number needs no separator, so the locale does not matter for it. + expect(keypad({ ...field, min: 0 })).toBe('numeric') + }) + + it('shows the full keyboard for a fraction that may be negative, in any locale', () => { + useDecimalSeparator('.') + expect(keypad(fraction)).toBe('text') + expect(keypad({ ...fraction, min: -1 })).toBe('text') + }) + + it('reports exactly the text typed, so the strict parser sees it (no rounding, no clamping, no group stripping)', async () => { + const wrapper = mountField(field) + await wrapper.find('input').setValue('1,5') + expect(lastValue(wrapper)).toBe('1,5') + await wrapper.find('input').setValue('12345678.123456789') + expect(lastValue(wrapper)).toBe('12345678.123456789') + }) + + it('links its error to the input', () => { + const wrapper = mountField(field, { errors: [{ code: 'invalid_number', message: 'Enter a number.' }] }) + expect(wrapper.find('input').attributes('aria-describedby')).toBe(wrapper.find('ul').attributes('id')) + }) +}) + +describe('checkbox field', () => { + const field: FormField = { id: 'ok', type: 'checkbox', label: 'I agree to the terms', required: true, description: 'Required to continue' } + + it('is a real checkbox with a clickable label, control first', () => { + const wrapper = mountField(field) + const input = wrapper.find('input[type="checkbox"]') + expect(input.exists()).toBe(true) + expect(wrapper.find('label').attributes('for')).toBe(input.attributes('id')) + }) + + it('reports an explicit boolean when the box or its label is clicked', async () => { + const wrapper = mountField(field) + await wrapper.find('input[type="checkbox"]').setValue(true) + expect(lastValue(wrapper)).toBe(true) + await wrapper.find('input[type="checkbox"]').setValue(false) + expect(lastValue(wrapper)).toBe(false) + await wrapper.find('label').trigger('click') + expect(lastValue(wrapper)).toBe(true) + }) + + it('links description and error to the checkbox input itself, not to the wrapper div', () => { + const wrapper = mountField(field, { errors: REQUIRED_ERROR }) + const input = wrapper.find('input[type="checkbox"]') + const describedBy = (input.attributes('aria-describedby') ?? '').split(' ') + expect(describedBy).toContain(wrapper.find('p').attributes('id')) + expect(describedBy).toContain(wrapper.find('ul').attributes('id')) + expect(input.attributes('aria-invalid')).toBe('true') + expect(input.attributes('aria-required')).toBe('true') + // The PrimeVue root div must not carry a stray aria-describedby. + expect(wrapper.find('.p-checkbox').attributes('aria-describedby')).toBeUndefined() + }) + + it('shows a checked draft', () => { + const wrapper = mountField(field, { modelValue: true }) + expect((wrapper.find('input[type="checkbox"]').element as HTMLInputElement).checked).toBe(true) + }) + + // user-event presses the key the way a browser does (keydown, then a click + // on keyup for Space), which a bare `trigger('keyup')` does not. Without it + // this test would only prove that a click toggles. + it('toggles with the Space key and with no other key', async () => { + const user = userEvent.setup() + const wrapper = mountField(field) + ;(wrapper.find('input[type="checkbox"]').element as HTMLInputElement).focus() + + await user.keyboard('a{Enter}') + expect(wrapper.emitted('update:modelValue')).toBeUndefined() + + await user.keyboard(' ') + expect(lastValue(wrapper)).toBe(true) + + // The parent hands the answer back, as the form does, so the next press unticks it. + await wrapper.setProps({ modelValue: true }) + await user.keyboard(' ') + expect(lastValue(wrapper)).toBe(false) + expect(wrapper.emitted('update:modelValue')).toHaveLength(2) + }) + + it('focuses the checkbox on focusFirstControl', () => { + const wrapper = mountField(field) + ;(wrapper.vm as unknown as { focusFirstControl: () => void }).focusFirstControl() + expect(document.activeElement).toBe(wrapper.find('input[type="checkbox"]').element) + }) +}) + +describe('date field', () => { + const field: FormField = { id: 'day', type: 'date', label: 'Delivery date', required: true, min: '2026-10-01', max: '2026-12-31' } + + it('is a date picker input labelled by the field label', () => { + const wrapper = mountField(field) + const input = wrapper.find('input') + expect(input.exists()).toBe(true) + expect(wrapper.find('label').attributes('for')).toBe(input.attributes('id')) + expect(input.attributes('placeholder')).toBe('YYYY-MM-DD') + }) + + it('links the error and description to the real input, not the picker wrapper', () => { + const wrapper = mountField({ ...field, description: 'Pick a weekday' }, { errors: [{ code: 'invalid_date', message: 'Enter a valid date as YYYY-MM-DD.' }] }) + const input = wrapper.find('input') + const describedBy = (input.attributes('aria-describedby') ?? '').split(' ') + expect(describedBy).toContain(wrapper.find('p').attributes('id')) + expect(describedBy).toContain(wrapper.find('ul').attributes('id')) + expect(input.attributes('aria-invalid')).toBe('true') + expect(input.attributes('aria-required')).toBe('true') + }) + + it('reports a typed date in the wire format', async () => { + const wrapper = mountField(field) + await wrapper.find('input').setValue('2026-10-15') + expect(lastValue(wrapper)).toBe('2026-10-15') + }) + + it('reports typed text that is not a date instead of dropping it', async () => { + const wrapper = mountField(field) + await wrapper.find('input').setValue('next tuesday') + expect(lastValue(wrapper)).toBe('next tuesday') + }) + + it('reports a typed date outside min and max as typed, for the client check to name', async () => { + const wrapper = mountField(field) + await wrapper.find('input').setValue('2026-09-30') + expect(lastValue(wrapper)).toBe('2026-09-30') + }) + + it('reports an emptied field as empty text', async () => { + const wrapper = mountField(field, { modelValue: '2026-10-15' }) + await wrapper.find('input').setValue('') + expect(lastValue(wrapper)).toBe('') + }) + + it('shows a stored date', () => { + const wrapper = mountField(field, { modelValue: '2026-10-15' }) + expect((wrapper.find('input').element as HTMLInputElement).value).toBe('2026-10-15') + }) + + it('keeps the typed text in the box after leaving it, so the user can correct it', async () => { + const wrapper = mountField(field) + const input = wrapper.find('input') + await input.setValue('next tuesday') + await input.trigger('blur') + await wrapper.vm.$nextTick() + expect((input.element as HTMLInputElement).value).toBe('next tuesday') + }) + + it('opens no calendar on focus: it opens from its button, so keyboard users can just type', async () => { + const wrapper = mountField(field) + await wrapper.find('input').trigger('focus') + expect(document.querySelector('.p-datepicker-panel')).toBeNull() + expect(wrapper.find('button[aria-haspopup="dialog"]').exists()).toBe(true) + }) + + it('opens the calendar from the keyboard with ArrowDown and closes it with Escape', async () => { + const wrapper = mountField(field) + const input = wrapper.find('input') + await input.trigger('keydown', { code: 'ArrowDown' }) + await wrapper.vm.$nextTick() + expect(input.attributes('aria-expanded')).toBe('true') + await input.trigger('keydown', { code: 'Escape' }) + await wrapper.vm.$nextTick() + expect(input.attributes('aria-expanded')).toBe('false') + }) + + it('opens the calendar from its button', async () => { + const wrapper = mountField(field) + await wrapper.find('button[aria-haspopup="dialog"]').trigger('click') + await wrapper.vm.$nextTick() + expect(wrapper.find('input').attributes('aria-expanded')).toBe('true') + }) +}) + +describe('choice field through the dispatcher', () => { + it('still renders the V1 radio group', () => { + const wrapper = mountField({ id: 'c', type: 'choice', label: 'Speed', required: false, options: [{ value: 'a', label: 'A' }, { value: 'b', label: 'B' }], multiple: false, allow_other: false }) + expect(wrapper.findAll('input[type="radio"]')).toHaveLength(2) + }) + + it('forwards focusOtherText to the choice field', () => { + const wrapper = mountField({ id: 'c', type: 'choice', label: 'Speed', required: false, options: [{ value: 'a', label: 'A' }], multiple: false, allow_other: true }, { modelValue: { other: '' } }) + ;(wrapper.vm as unknown as { focusOtherText: () => void }).focusOtherText() + expect(document.activeElement).toBe(wrapper.find('input[type="text"]').element) + }) +}) + +describe('read-only through the dispatcher', () => { + it('renders no control for any type and shows the stored value', () => { + const cases: Array<[FormField, FieldAnswer | undefined, string]> = [ + [{ id: 'a', type: 'text', min_length: 0, max_length: 500, label: 'A', required: true }, 'Ada', 'Ada'], + [{ id: 'b', type: 'email', label: 'B', required: false }, 'a@b.co', 'a@b.co'], + [{ id: 'c', type: 'number', label: 'C', required: false }, 3, '3'], + [{ id: 'd', type: 'date', label: 'D', required: false }, '2026-10-01', '2026-10-01'], + [{ id: 'e', type: 'checkbox', label: 'E', required: false }, true, 'Yes'], + [{ id: 'f', type: 'textarea', min_length: 0, max_length: 8000, label: 'F', required: false }, 'x', 'x'], + ] + for (const [field, value, shown] of cases) { + const wrapper = mountField(field, { readonly: true, disabled: true, modelValue: value }) + expect(wrapper.find('input, textarea').exists(), field.type).toBe(false) + expect(wrapper.find('[part~="field-value"]').text(), field.type).toBe(shown) + } + }) +}) diff --git a/frontend/wippy-form/src/app/fields/form-field.vue b/frontend/wippy-form/src/app/fields/form-field.vue new file mode 100644 index 0000000..5665623 --- /dev/null +++ b/frontend/wippy-form/src/app/fields/form-field.vue @@ -0,0 +1,95 @@ + + + diff --git a/frontend/wippy-form/src/app/fields/input-field.vue b/frontend/wippy-form/src/app/fields/input-field.vue new file mode 100644 index 0000000..61820c5 --- /dev/null +++ b/frontend/wippy-form/src/app/fields/input-field.vue @@ -0,0 +1,106 @@ + + + diff --git a/frontend/wippy-form/src/app/fields/textarea-field.vue b/frontend/wippy-form/src/app/fields/textarea-field.vue new file mode 100644 index 0000000..885917d --- /dev/null +++ b/frontend/wippy-form/src/app/fields/textarea-field.vue @@ -0,0 +1,60 @@ + + +