@barqjs/aria 0.0.0-stage → 0.2.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
@@ -0,0 +1,1717 @@
1
+ /**
2
+ * A questionnaire: several questions, asked one at a time, answered as one form.
3
+ *
4
+ * The decisions that shape it:
5
+ *
6
+ * - **It is a native form.** Every answer is a real radio, checkbox or text
7
+ * input carrying the question's `name`, so the answers are read with
8
+ * `FormData` and the page needs no state of its own to collect them. An
9
+ * inactive question stays in the document, `hidden` and `inert`, so its
10
+ * answer is still submitted.
11
+ * - **A question has three states, not two.** `unanswered`, `answered` and
12
+ * `skipped`. An optional question somebody chose to skip is a decision and
13
+ * is valid; one nobody has reached is neither. Skipping takes the `name` off
14
+ * the inputs, so a skipped question submits nothing rather than a stale
15
+ * choice.
16
+ * - **A typed answer is an answer like any other.** `<QuestionnaireInput>`
17
+ * beside the choices is selected by typing into it, not by focusing it, and
18
+ * only carries the question's `name` while it is the selected answer. Radios
19
+ * therefore stop being `required` where one is present, or the browser would
20
+ * refuse a form whose question was answered in words.
21
+ * - **Validation is the questionnaire's own by default.** `noValidate` is on,
22
+ * so the browser's bubbles do not compete with `<QuestionnaireError>`;
23
+ * turning it off adds `reportValidity()` for a malformed typed answer on top
24
+ * of the same rules.
25
+ * - **Order is the document's.** Questions and answers register as they are
26
+ * built, which is not the order they sit in once a `<Show>` adds one in the
27
+ * middle, so both are sorted by position and re-sorted when the tree changes.
28
+ * `items` on the root declares the questions up front, which is what gives a
29
+ * server render the right count and the right shortcuts before anything has
30
+ * registered.
31
+ * - **The horizontal arrows follow the writing direction.** Back is towards
32
+ * the start of the line, so they swap under `dir="rtl"`; up and down never
33
+ * do.
34
+ */
35
+
36
+ import {
37
+ cells,
38
+ type Accessor,
39
+ type Child,
40
+ createContext,
41
+ createEffect,
42
+ createMemo,
43
+ createSignal,
44
+ createUniqueId,
45
+ flush,
46
+ getContext,
47
+ getOwner,
48
+ type Incoming,
49
+ install,
50
+ type JSXElement,
51
+ onCleanup,
52
+ untrack,
53
+ } from "@barqjs/core";
54
+ import { isServer } from "@barqjs/web";
55
+ import { mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
56
+ import { useDirection } from "./i18n.ts";
57
+ import {
58
+ type DOMProps,
59
+ filterDOMProps,
60
+ fromProps,
61
+ mergeProps,
62
+ partRender,
63
+ type RenderPart,
64
+ type StyleProps,
65
+ styleProps,
66
+ } from "./utils.ts";
67
+
68
+ export type QuestionnaireItemStatus = "unanswered" | "answered" | "skipped";
69
+ export type QuestionnaireShortcutMode = "letters" | "numbers";
70
+
71
+ export interface QuestionnaireChoiceDefinition {
72
+ value: string;
73
+ disabled?: boolean;
74
+ }
75
+
76
+ export interface QuestionnaireItemDefinition {
77
+ name: string;
78
+ choices?: readonly QuestionnaireChoiceDefinition[];
79
+ disabled?: boolean;
80
+ required?: boolean;
81
+ }
82
+
83
+ export type QuestionnaireInputType =
84
+ | "date"
85
+ | "datetime-local"
86
+ | "email"
87
+ | "month"
88
+ | "number"
89
+ | "password"
90
+ | "search"
91
+ | "tel"
92
+ | "text"
93
+ | "time"
94
+ | "url"
95
+ | "week";
96
+
97
+ export interface QuestionnaireRootState {
98
+ readonly current: Accessor<number>;
99
+ readonly first: Accessor<boolean>;
100
+ readonly last: Accessor<boolean>;
101
+ readonly total: Accessor<number>;
102
+ }
103
+
104
+ export type QuestionnaireProgressState = QuestionnaireRootState;
105
+
106
+ export interface QuestionnaireItemState {
107
+ readonly active: Accessor<boolean>;
108
+ readonly disabled: Accessor<boolean>;
109
+ readonly invalid: Accessor<boolean>;
110
+ readonly multiple: Accessor<boolean>;
111
+ readonly required: Accessor<boolean>;
112
+ readonly status: Accessor<QuestionnaireItemStatus>;
113
+ }
114
+
115
+ export interface QuestionnaireChoicesState {
116
+ readonly shortcuts: Accessor<QuestionnaireShortcutMode | null>;
117
+ }
118
+
119
+ export interface QuestionnaireChoiceState {
120
+ readonly checked: Accessor<boolean>;
121
+ readonly disabled: Accessor<boolean>;
122
+ readonly invalid: Accessor<boolean>;
123
+ readonly shortcut: Accessor<string | null>;
124
+ readonly type: Accessor<"checkbox" | "radio">;
125
+ }
126
+
127
+ export type QuestionnaireChoiceShortcutState = Pick<QuestionnaireChoiceState, "shortcut">;
128
+
129
+ export interface QuestionnaireInputState {
130
+ readonly disabled: Accessor<boolean>;
131
+ readonly filled: Accessor<boolean>;
132
+ readonly invalid: Accessor<boolean>;
133
+ }
134
+
135
+ export interface QuestionnaireNavigationState {
136
+ readonly disabled: Accessor<boolean>;
137
+ readonly shortcut: Accessor<"Enter" | null>;
138
+ readonly status: Accessor<QuestionnaireItemStatus | null>;
139
+ readonly visible: Accessor<boolean>;
140
+ }
141
+
142
+ // ---------------------------------------------------------------------------
143
+ // Pure helpers
144
+ // ---------------------------------------------------------------------------
145
+
146
+ function hasInputValue(value: string | number | null | undefined): boolean {
147
+ return value !== undefined && value !== null && String(value).trim().length > 0;
148
+ }
149
+
150
+ function shortcutKeys(mode: QuestionnaireShortcutMode | null): string[] {
151
+ if (mode === "letters") {
152
+ return Array.from({ length: 26 }, (_, index) => String.fromCharCode(65 + index));
153
+ }
154
+ if (mode === "numbers") return Array.from({ length: 9 }, (_, index) => String(index + 1));
155
+ return [];
156
+ }
157
+
158
+ function shortcutFromKey(key: string, mode: QuestionnaireShortcutMode): string | null {
159
+ const normalized = mode === "letters" ? key.toUpperCase() : key;
160
+ return shortcutKeys(mode).includes(normalized) ? normalized : null;
161
+ }
162
+
163
+ function keyShortcuts(...keys: (string | null | undefined | false)[]): string | undefined {
164
+ const present = keys.filter((key) => typeof key === "string" && key !== "");
165
+ return present.length === 0 ? undefined : present.join(" ");
166
+ }
167
+
168
+ const TEXT_NAVIGABLE = new Set(["email", "password", "search", "tel", "text", "url"]);
169
+ const NOT_TEXT_ENTRY = new Set(["button", "checkbox", "radio", "reset", "submit"]);
170
+
171
+ function isTextEntryTarget(element: Element): boolean {
172
+ if (element instanceof HTMLTextAreaElement || element instanceof HTMLSelectElement) return true;
173
+ if (element instanceof HTMLInputElement) return !NOT_TEXT_ENTRY.has(element.type);
174
+ return element instanceof HTMLElement && element.isContentEditable;
175
+ }
176
+
177
+ function isRadioTarget(element: Element): boolean {
178
+ return element instanceof HTMLInputElement && element.type === "radio";
179
+ }
180
+
181
+ /**
182
+ * The entries, in the order their elements sit under `scope`.
183
+ *
184
+ * One not under it yet goes last and keeps the order it arrived in, which is
185
+ * every entry while the questionnaire is first being built, and is right then.
186
+ */
187
+ function inDocumentOrder<T>(
188
+ entries: readonly T[],
189
+ scope: Element | null,
190
+ selector: string,
191
+ elementOf: (entry: T) => Element,
192
+ ): T[] {
193
+ if (scope === null) return [...entries];
194
+ const position = new Map<Element, number>();
195
+ for (const [index, element] of scope.querySelectorAll(selector).entries()) {
196
+ position.set(element, index);
197
+ }
198
+ const at = (entry: T): number => position.get(elementOf(entry)) ?? position.size;
199
+ return entries.toSorted((first, second) => at(first) - at(second));
200
+ }
201
+
202
+ interface Collection {
203
+ readonly enabled: readonly QuestionnaireItemDefinition[];
204
+ readonly byName: ReadonlyMap<string, QuestionnaireItemDefinition>;
205
+ }
206
+
207
+ function createCollection(
208
+ items: readonly QuestionnaireItemDefinition[] | undefined,
209
+ ): Collection | null {
210
+ if (items === undefined) return null;
211
+ return {
212
+ enabled: items.filter((item) => item.disabled !== true),
213
+ byName: new Map(items.map((item) => [item.name, item])),
214
+ };
215
+ }
216
+
217
+ function initialItemName(collection: Collection | null, wanted: string | undefined): string | null {
218
+ if (collection === null) return wanted ?? null;
219
+ const definition = wanted === undefined ? undefined : collection.byName.get(wanted);
220
+ if (definition !== undefined && definition.disabled !== true) return definition.name;
221
+ return collection.enabled[0]?.name ?? null;
222
+ }
223
+
224
+ function shortcutsByChoiceValue(
225
+ item: QuestionnaireItemDefinition | undefined,
226
+ mode: QuestionnaireShortcutMode | null,
227
+ ): Map<string, string> {
228
+ const out = new Map<string, string>();
229
+ if (item === undefined || mode === null) return out;
230
+ const keys = shortcutKeys(mode);
231
+ let index = 0;
232
+ for (const choice of item.choices ?? []) {
233
+ if (choice.disabled === true) continue;
234
+ const key = keys[index];
235
+ if (key === undefined) break;
236
+ out.set(choice.value, key);
237
+ index++;
238
+ }
239
+ return out;
240
+ }
241
+
242
+ // ---------------------------------------------------------------------------
243
+ // Shared state
244
+ // ---------------------------------------------------------------------------
245
+
246
+ interface Answer {
247
+ readonly id: string;
248
+ readonly type: "choice" | "input";
249
+ readonly element: HTMLInputElement;
250
+ readonly disabled: Accessor<boolean>;
251
+ /** A choice's `value`; nothing for a typed answer. */
252
+ readonly value: Accessor<string>;
253
+ /** What the state says a choice's input should show. */
254
+ readonly checked: Accessor<boolean>;
255
+ }
256
+
257
+ function isAnswerFilled(answer: Answer): boolean {
258
+ if (answer.type === "choice") return answer.element.checked;
259
+ return answer.element.hasAttribute("name") && hasInputValue(answer.element.value);
260
+ }
261
+
262
+ function isEmptyNavigableInput(answer: Answer | null): boolean {
263
+ return (
264
+ answer !== null &&
265
+ answer.type === "input" &&
266
+ TEXT_NAVIGABLE.has(answer.element.type) &&
267
+ !hasInputValue(answer.element.value)
268
+ );
269
+ }
270
+
271
+ interface ItemHandle {
272
+ readonly element: HTMLFieldSetElement;
273
+ readonly name: Accessor<string>;
274
+ readonly disabled: Accessor<boolean>;
275
+ readonly required: Accessor<boolean>;
276
+ readonly status: Accessor<QuestionnaireItemStatus>;
277
+ focus(): void;
278
+ focusInvalid(): void;
279
+ validate(): boolean;
280
+ reset(): void;
281
+ skip(): void;
282
+ answerByElement(element: Element): Answer | null;
283
+ answerByShortcut(shortcut: string): Answer | null;
284
+ moveAnswerFocus(element: Element, direction: "next" | "previous"): boolean;
285
+ }
286
+
287
+ interface RootValue {
288
+ readonly activeName: Accessor<string | null>;
289
+ readonly activeRequired: Accessor<boolean | null>;
290
+ readonly activeStatus: Accessor<QuestionnaireItemStatus | null>;
291
+ readonly current: Accessor<number>;
292
+ readonly total: Accessor<number>;
293
+ readonly first: Accessor<boolean>;
294
+ readonly last: Accessor<boolean>;
295
+ readonly declared: Accessor<boolean>;
296
+ readonly definition: (name: string) => QuestionnaireItemDefinition | undefined;
297
+ readonly domVersion: Accessor<number>;
298
+ readonly nativeValidation: Accessor<boolean>;
299
+ readonly shortcuts: Accessor<QuestionnaireShortcutMode | null>;
300
+ readonly backKey: Accessor<"ArrowLeft" | "ArrowRight">;
301
+ readonly forwardKey: Accessor<"ArrowLeft" | "ArrowRight">;
302
+ register(handle: ItemHandle): () => void;
303
+ readonly goNext: () => void;
304
+ readonly goPrevious: () => void;
305
+ readonly skipCurrent: () => void;
306
+ }
307
+
308
+ interface ItemValue {
309
+ readonly name: Accessor<string>;
310
+ readonly disabled: Accessor<boolean>;
311
+ readonly required: Accessor<boolean>;
312
+ readonly multiple: Accessor<boolean>;
313
+ readonly invalid: Accessor<boolean>;
314
+ readonly status: Accessor<QuestionnaireItemStatus>;
315
+ readonly hasInputAnswer: Accessor<boolean>;
316
+ readonly resetVersion: Accessor<number>;
317
+ readonly shortcuts: Accessor<QuestionnaireShortcutMode | null>;
318
+ isSelected(answerId: string): boolean;
319
+ shortcutFor(answerId: string, value: string | undefined): string | null;
320
+ registerAnswer(answer: Answer): () => void;
321
+ registerSelection(answerId: string, selected: boolean): () => void;
322
+ setDefault(answerId: string, selected: boolean): void;
323
+ selectFromInteraction(answerId: string, selected: boolean): void;
324
+ syncControlled(answerId: string, selected: boolean): void;
325
+ /** Put every choice input back to what the state says, after the browser moved one. */
326
+ repair(): void;
327
+ registerDescription(id: string): () => void;
328
+ registerError(id: string): () => void;
329
+ }
330
+
331
+ interface ChoiceValue {
332
+ readonly inputProps: DOMProps;
333
+ readonly stateProps: DOMProps;
334
+ readonly state: QuestionnaireChoiceState;
335
+ }
336
+
337
+ const RootContext = createContext<RootValue | null>(null);
338
+ const ItemContext = createContext<ItemValue | null>(null);
339
+ const ChoiceContext = createContext<ChoiceValue | null>(null);
340
+
341
+ function useRoot(): RootValue {
342
+ const value = getContext(RootContext);
343
+ if (value === null || value === undefined) {
344
+ throw new Error("This must be rendered inside a <Questionnaire>.");
345
+ }
346
+ return value;
347
+ }
348
+
349
+ function useItem(): ItemValue {
350
+ const value = getContext(ItemContext);
351
+ if (value === null || value === undefined) {
352
+ throw new Error("This must be rendered inside a <QuestionnaireItem>.");
353
+ }
354
+ return value;
355
+ }
356
+
357
+ function useChoice(): ChoiceValue {
358
+ const value = getContext(ChoiceContext);
359
+ if (value === null || value === undefined) {
360
+ throw new Error("This must be rendered inside a <QuestionnaireChoice>.");
361
+ }
362
+ return value;
363
+ }
364
+
365
+ /** A list other components add themselves to while they are being built. */
366
+ function registry<T>(): [
367
+ Accessor<readonly T[]>,
368
+ (entry: T, same?: (other: T) => boolean) => () => void,
369
+ ] {
370
+ const [entries, setEntries] = createSignal<readonly T[]>([], { ownedWrite: true });
371
+ const add = (entry: T, same?: (other: T) => boolean): (() => void) => {
372
+ setEntries((current) => [
373
+ ...current.filter((other) => other !== entry && same?.(other) !== true),
374
+ entry,
375
+ ]);
376
+ return () => {
377
+ setEntries((current) => current.filter((other) => other !== entry));
378
+ };
379
+ };
380
+ return [entries, add];
381
+ }
382
+
383
+ const present = (value: boolean): "" | undefined => (value ? "" : undefined);
384
+
385
+ const FORM_PROPS = new Set([
386
+ "action",
387
+ "method",
388
+ "encType",
389
+ "target",
390
+ "name",
391
+ "autoComplete",
392
+ "acceptCharset",
393
+ "rel",
394
+ "role",
395
+ ]);
396
+
397
+ const INPUT_PROPS = new Set([
398
+ "placeholder",
399
+ "autoComplete",
400
+ "autoFocus",
401
+ "autoCapitalize",
402
+ "autoCorrect",
403
+ "spellCheck",
404
+ "enterKeyHint",
405
+ "inputMode",
406
+ "maxLength",
407
+ "minLength",
408
+ "min",
409
+ "max",
410
+ "step",
411
+ "pattern",
412
+ "readOnly",
413
+ "required",
414
+ "list",
415
+ "size",
416
+ "aria-required",
417
+ "aria-errormessage",
418
+ "onInput",
419
+ "onChange",
420
+ "onKeyDown",
421
+ "onKeyUp",
422
+ "onCopy",
423
+ "onCut",
424
+ "onPaste",
425
+ "onCompositionStart",
426
+ "onCompositionEnd",
427
+ "onSelect",
428
+ ]);
429
+
430
+ const BUTTON_PROPS = new Set(["name", "value", "form", "formAction", "formMethod", "formTarget"]);
431
+
432
+ // ---------------------------------------------------------------------------
433
+ // Root
434
+ // ---------------------------------------------------------------------------
435
+
436
+ export interface QuestionnaireProps extends StyleProps {
437
+ children?: Child;
438
+ /** The question shown first. @default the first enabled one */
439
+ defaultItem?: string;
440
+ /** The question shown, when the caller owns that. */
441
+ item?: string;
442
+ /** The questions, declared up front so a server render knows them all. */
443
+ items?: readonly QuestionnaireItemDefinition[];
444
+ onItemChange?: (item: string) => void;
445
+ /** Give each choice a key that selects it. */
446
+ shortcuts?: QuestionnaireShortcutMode;
447
+ /** @default true */
448
+ noValidate?: boolean;
449
+ onSubmit?: (event: SubmitEvent) => void;
450
+ onReset?: (event: Event) => void;
451
+ onKeyDown?: (event: KeyboardEvent) => void;
452
+ action?: string;
453
+ method?: string;
454
+ name?: string;
455
+ role?: string;
456
+ "aria-label"?: string;
457
+ "aria-labelledby"?: string;
458
+ "aria-describedby"?: string;
459
+ ref?: RefTarget<HTMLFormElement>;
460
+ }
461
+
462
+ /**
463
+ * ```tsx
464
+ * <Questionnaire onSubmit={(event) => send(new FormData(event.currentTarget))}>
465
+ * <QuestionnaireProgress />
466
+ * <QuestionnaireItem name="plan" required>
467
+ * <QuestionnaireTitle>Which plan?</QuestionnaireTitle>
468
+ * <QuestionnaireChoices>
469
+ * <QuestionnaireChoice value="plus">
470
+ * <QuestionnaireChoiceInput />
471
+ * <QuestionnaireChoiceLabel>Plus</QuestionnaireChoiceLabel>
472
+ * </QuestionnaireChoice>
473
+ * </QuestionnaireChoices>
474
+ * <QuestionnaireError />
475
+ * </QuestionnaireItem>
476
+ * <QuestionnairePrevious />
477
+ * <QuestionnaireNext />
478
+ * <QuestionnaireSubmit />
479
+ * </Questionnaire>
480
+ * ```
481
+ */
482
+ export function Questionnaire(props: QuestionnaireProps) {
483
+ const options = fromProps(cells(props));
484
+ const direction = useDirection();
485
+
486
+ const shortcuts = (): QuestionnaireShortcutMode | null => props.shortcuts ?? null;
487
+ const noValidate = (): boolean => props.noValidate ?? true;
488
+ const backKey = (): "ArrowLeft" | "ArrowRight" =>
489
+ direction() === "rtl" ? "ArrowRight" : "ArrowLeft";
490
+ const forwardKey = (): "ArrowLeft" | "ArrowRight" =>
491
+ direction() === "rtl" ? "ArrowLeft" : "ArrowRight";
492
+
493
+ const collection = createMemo(() => createCollection(props.items));
494
+ const [handles, register] = registry<ItemHandle>();
495
+ // `ownedWrite`: the form's own `ref` bumps it, and a ref is called while this
496
+ // component is still being built.
497
+ const [domVersion, setDomVersion] = createSignal(0, { ownedWrite: true });
498
+ const [uncontrolled, setUncontrolled] = createSignal<string | null>(
499
+ untrack(() => initialItemName(collection(), props.defaultItem)),
500
+ );
501
+ let form: HTMLFormElement | null = null;
502
+ let observer: MutationObserver | undefined;
503
+ let pendingFocus: { name: string; target: "invalid" | "item" } | null = null;
504
+
505
+ const controlled = (): boolean => props.item !== undefined;
506
+
507
+ const runtimeItems = createMemo(() => {
508
+ domVersion();
509
+ return inDocumentOrder(handles(), form, "fieldset", (handle) => handle.element).filter(
510
+ (handle) => !handle.disabled(),
511
+ );
512
+ });
513
+ const names = createMemo<readonly string[]>(() => {
514
+ const declared = collection();
515
+ return declared === null
516
+ ? runtimeItems().map((handle) => handle.name())
517
+ : declared.enabled.map((definition) => definition.name);
518
+ });
519
+ const requested = (): string | null => props.item ?? uncontrolled();
520
+ // Before the first question has been made current, the first one is.
521
+ const activeName = (): string | null =>
522
+ requested() ?? (controlled() ? null : (names()[0] ?? null));
523
+ const currentIndex = createMemo(() => {
524
+ const name = activeName();
525
+ return name === null ? -1 : names().indexOf(name);
526
+ });
527
+ const activeItem = createMemo<ItemHandle | null>(() => {
528
+ if (currentIndex() < 0) return null;
529
+ const name = activeName();
530
+ return runtimeItems().find((handle) => handle.name() === name) ?? null;
531
+ });
532
+ const total = (): number => names().length;
533
+ const current = (): number => currentIndex() + 1;
534
+ const first = (): boolean => total() > 0 && currentIndex() === 0;
535
+ const last = (): boolean => total() > 0 && currentIndex() === total() - 1;
536
+
537
+ const activeRequired = (): boolean | null => {
538
+ if (currentIndex() < 0) return null;
539
+ const definition = collection()?.byName.get(activeName() ?? "");
540
+ if (definition !== undefined) return definition.required === true;
541
+ return activeItem()?.required() ?? false;
542
+ };
543
+ const activeStatus = (): QuestionnaireItemStatus | null => {
544
+ if (currentIndex() < 0) return null;
545
+ return activeItem()?.status() ?? "unanswered";
546
+ };
547
+
548
+ const setItem = (next: string, target: "invalid" | "item" = "item"): void => {
549
+ if (next === requested()) return;
550
+ pendingFocus = { name: next, target };
551
+ if (!controlled()) setUncontrolled(next);
552
+ options.onItemChange?.(next);
553
+ };
554
+
555
+ let previousName = untrack(activeName);
556
+ createEffect(
557
+ () => ({ name: activeName(), item: activeItem(), index: currentIndex(), names: names() }),
558
+ (now) => {
559
+ const firstName = now.names[0];
560
+ if (firstName === undefined) return;
561
+
562
+ if (untrack(requested) === null && !untrack(controlled)) {
563
+ setUncontrolled(firstName);
564
+ return;
565
+ }
566
+ if (now.index < 0) {
567
+ setItem(firstName);
568
+ return;
569
+ }
570
+
571
+ const changed = previousName !== now.name;
572
+ previousName = now.name;
573
+ const pending = pendingFocus;
574
+
575
+ if (pending === null || pending.name !== now.name) {
576
+ // A caller that moved a controlled questionnaire itself still expects
577
+ // focus to follow, or a screen reader stays on a question that is gone.
578
+ if (untrack(controlled) && changed) {
579
+ pendingFocus = null;
580
+ now.item?.focus();
581
+ }
582
+ return;
583
+ }
584
+
585
+ if (pending.target === "invalid") now.item?.focusInvalid();
586
+ else now.item?.focus();
587
+ pendingFocus = null;
588
+ },
589
+ );
590
+
591
+ const goPrevious = (): void => {
592
+ const index = currentIndex();
593
+ const previous = names()[index - 1];
594
+ if (index <= 0 || previous === undefined) return;
595
+ setItem(previous);
596
+ };
597
+
598
+ const goNext = (): void => {
599
+ const item = activeItem();
600
+ const next = names()[currentIndex() + 1];
601
+ if (item === null || next === undefined) return;
602
+ if (!item.validate()) {
603
+ item.focusInvalid();
604
+ return;
605
+ }
606
+ setItem(next);
607
+ };
608
+
609
+ const confirmCurrent = (): void => {
610
+ const item = activeItem();
611
+ if (item === null) return;
612
+ if (!item.validate()) {
613
+ item.focusInvalid();
614
+ return;
615
+ }
616
+ if (last()) {
617
+ form?.requestSubmit();
618
+ return;
619
+ }
620
+ const next = names()[currentIndex() + 1];
621
+ if (next !== undefined) setItem(next);
622
+ };
623
+
624
+ const skipCurrent = (): void => {
625
+ const item = activeItem();
626
+ if (item === null || item.required()) return;
627
+ const wasLast = last();
628
+ const next = names()[currentIndex() + 1];
629
+ item.skip();
630
+ if (!wasLast) {
631
+ if (next !== undefined) setItem(next);
632
+ return;
633
+ }
634
+ // The skip takes the `name` off the question's inputs, and the form has to
635
+ // be read after that has reached the document.
636
+ flush();
637
+ form?.requestSubmit();
638
+ };
639
+
640
+ const onReset = (event: Event): void => {
641
+ options.onReset?.(event);
642
+ if (event.defaultPrevented) return;
643
+ for (const handle of handles()) handle.reset();
644
+
645
+ const declared = collection();
646
+ const wanted = props.defaultItem;
647
+ const name =
648
+ declared === null
649
+ ? (runtimeItems()
650
+ .find((handle) => handle.name() === wanted)
651
+ ?.name() ?? runtimeItems()[0]?.name())
652
+ : initialItemName(declared, wanted);
653
+ if (name !== undefined && name !== null) setItem(name);
654
+ };
655
+
656
+ const onSubmit = (event: SubmitEvent): void => {
657
+ const declared = collection();
658
+ const ordered =
659
+ declared === null
660
+ ? runtimeItems()
661
+ : declared.enabled.flatMap((definition) => {
662
+ const handle = runtimeItems().find((each) => each.name() === definition.name);
663
+ return handle === undefined ? [] : [handle];
664
+ });
665
+ const invalid = ordered.find((handle) => !handle.validate());
666
+
667
+ if (invalid === undefined) {
668
+ options.onSubmit?.(event);
669
+ return;
670
+ }
671
+
672
+ event.preventDefault();
673
+ const wasActive = invalid.name() === activeName();
674
+ setItem(invalid.name(), "invalid");
675
+ if (wasActive) {
676
+ invalid.focusInvalid();
677
+ pendingFocus = null;
678
+ }
679
+ };
680
+
681
+ const onKeyDown = (event: KeyboardEvent): void => {
682
+ const item = activeItem();
683
+ const target = event.target;
684
+ if (
685
+ event.defaultPrevented ||
686
+ event.isComposing ||
687
+ event.keyCode === 229 ||
688
+ item === null ||
689
+ !(target instanceof Element)
690
+ ) {
691
+ return;
692
+ }
693
+
694
+ if (
695
+ event.key === "Enter" &&
696
+ (event.metaKey || event.ctrlKey) &&
697
+ !event.altKey &&
698
+ !event.shiftKey
699
+ ) {
700
+ event.preventDefault();
701
+ if (!event.repeat) confirmCurrent();
702
+ return;
703
+ }
704
+
705
+ if (event.metaKey || event.ctrlKey || event.altKey) return;
706
+
707
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
708
+ if (item.moveAnswerFocus(target, event.key === "ArrowDown" ? "next" : "previous")) {
709
+ event.preventDefault();
710
+ return;
711
+ }
712
+ }
713
+
714
+ if (
715
+ (event.key === "ArrowLeft" || event.key === "ArrowRight") &&
716
+ !isTextEntryTarget(target) &&
717
+ !isRadioTarget(target)
718
+ ) {
719
+ event.preventDefault();
720
+ if (event.repeat) return;
721
+ if (event.key === backKey()) goPrevious();
722
+ else if (item.status() !== "unanswered") goNext();
723
+ return;
724
+ }
725
+
726
+ if (event.key === "Enter") {
727
+ const answer = item.answerByElement(target);
728
+ if (answer === null) return;
729
+ // Always taken from an answer, chosen or not: the browser's own Enter
730
+ // submits the form, which here would skip every question after this one.
731
+ event.preventDefault();
732
+ if (!event.repeat && isAnswerFilled(answer)) confirmCurrent();
733
+ return;
734
+ }
735
+
736
+ const mode = shortcuts();
737
+ if (mode === null || isTextEntryTarget(target)) return;
738
+ const shortcut = shortcutFromKey(event.key, mode);
739
+ const answer = shortcut === null ? null : item.answerByShortcut(shortcut);
740
+ if (answer === null) return;
741
+
742
+ event.preventDefault();
743
+ if (event.repeat) return;
744
+ answer.element.focus();
745
+ if (answer.type === "choice") answer.element.click();
746
+ };
747
+
748
+ const attach = (element: HTMLFormElement | null): void => {
749
+ form = element;
750
+ setDomVersion((version) => version + 1);
751
+ if (element === null || isServer || typeof MutationObserver === "undefined") return;
752
+ observer?.disconnect();
753
+ observer = new MutationObserver(() => setDomVersion((version) => version + 1));
754
+ observer.observe(element, { childList: true, subtree: true });
755
+ };
756
+ onCleanup(() => observer?.disconnect());
757
+
758
+ const value: RootValue = {
759
+ activeName,
760
+ activeRequired,
761
+ activeStatus,
762
+ current,
763
+ total,
764
+ first,
765
+ last,
766
+ declared: () => collection() !== null,
767
+ definition: (name) => collection()?.byName.get(name),
768
+ domVersion,
769
+ nativeValidation: () => !noValidate(),
770
+ shortcuts,
771
+ backKey,
772
+ forwardKey,
773
+ register: (handle) => register(handle, (other) => other.name() === handle.name()),
774
+ goNext,
775
+ goPrevious,
776
+ skipCurrent,
777
+ };
778
+
779
+ const owner = getOwner();
780
+ if (owner !== null) install(owner, RootContext, () => value);
781
+
782
+ const formProps = mergeProps(
783
+ filterDOMProps(options, { global: true, labelable: true, propNames: FORM_PROPS }),
784
+ styleProps(cells(props)),
785
+ {
786
+ noValidate,
787
+ "data-shortcuts": () => shortcuts() ?? undefined,
788
+ "data-current": () => String(current()),
789
+ "data-total": () => String(total()),
790
+ "data-first": () => present(first()),
791
+ "data-last": () => present(last()),
792
+ // After the caller's own, which may have dealt with the key already.
793
+ onKeyDown: (event: KeyboardEvent): void => {
794
+ options.onKeyDown?.(event);
795
+ onKeyDown(event);
796
+ },
797
+ onReset,
798
+ onSubmit,
799
+ },
800
+ );
801
+
802
+ return (
803
+ <form {...formProps} ref={mergeRefs(attach, props.ref)}>
804
+ {props.children}
805
+ </form>
806
+ );
807
+ }
808
+
809
+ // ---------------------------------------------------------------------------
810
+ // Progress
811
+ // ---------------------------------------------------------------------------
812
+
813
+ export interface QuestionnaireProgressProps extends StyleProps {
814
+ /** @default "Question 1 of 3" */
815
+ children?: Child;
816
+ "aria-label"?: string;
817
+ ref?: RefTarget<HTMLDivElement>;
818
+ render?: RenderPart<QuestionnaireProgressState>;
819
+ }
820
+
821
+ export function QuestionnaireProgress(props: QuestionnaireProgressProps) {
822
+ const root = useRoot();
823
+ const options = fromProps(cells(props));
824
+ const known = (): boolean => root.total() > 0;
825
+ const label = (): string | undefined =>
826
+ known() ? `Question ${String(root.current())} of ${String(root.total())}` : undefined;
827
+
828
+ const elementProps = mergeProps(
829
+ {
830
+ role: "progressbar",
831
+ "aria-label": "Questionnaire progress",
832
+ "aria-live": "polite",
833
+ "aria-valuemin": () => (known() ? 1 : undefined),
834
+ "aria-valuemax": () => (known() ? root.total() : undefined),
835
+ "aria-valuenow": () => (known() ? root.current() : undefined),
836
+ "aria-valuetext": label,
837
+ "data-current": () => String(root.current()),
838
+ "data-total": () => String(root.total()),
839
+ "data-first": () => present(root.first()),
840
+ "data-last": () => present(root.last()),
841
+ },
842
+ filterDOMProps(options, { global: true, labelable: true }),
843
+ styleProps(cells(props)),
844
+ );
845
+
846
+ const render = props.render;
847
+ if (render !== undefined) {
848
+ const state: QuestionnaireProgressState = {
849
+ current: root.current,
850
+ first: root.first,
851
+ last: root.last,
852
+ total: root.total,
853
+ };
854
+ return render(partRender({ ...elementProps, ref: props.ref }), state) as JSXElement;
855
+ }
856
+
857
+ return (
858
+ <div {...elementProps} ref={mergeRefs(props.ref)}>
859
+ {props.children === undefined ? () => label() : props.children}
860
+ </div>
861
+ );
862
+ }
863
+
864
+ // ---------------------------------------------------------------------------
865
+ // Item
866
+ // ---------------------------------------------------------------------------
867
+
868
+ export interface QuestionnaireItemProps extends StyleProps {
869
+ children?: Child;
870
+ /** The form field name its answers are submitted under. */
871
+ name: string;
872
+ required?: boolean;
873
+ /** Checkboxes rather than radios. */
874
+ multiple?: boolean;
875
+ /** An error the caller found, on top of the questionnaire's own rule. */
876
+ invalid?: boolean;
877
+ disabled?: boolean;
878
+ onStatusChange?: (status: QuestionnaireItemStatus) => void;
879
+ "aria-describedby"?: string;
880
+ "aria-keyshortcuts"?: string;
881
+ ref?: RefTarget<HTMLFieldSetElement>;
882
+ }
883
+
884
+ export function QuestionnaireItem(props: QuestionnaireItemProps) {
885
+ const root = useRoot();
886
+ const options = fromProps(cells(props));
887
+
888
+ const name = (): string => props.name;
889
+ const disabled = (): boolean => props.disabled ?? false;
890
+ const required = (): boolean => props.required ?? false;
891
+ const multiple = (): boolean => props.multiple ?? false;
892
+ const externallyInvalid = (): boolean => props.invalid ?? false;
893
+
894
+ // Each of these is written by a child while this question is being built: a
895
+ // choice that starts checked, a description announcing its id.
896
+ const building = { ownedWrite: true } as const;
897
+ const [controls, registerAnswer] = registry<Answer>();
898
+ const [descriptionIds, registerDescription] = registry<string>();
899
+ const [errorIds, registerError] = registry<string>();
900
+ const [selectedIds, setSelectedIds] = createSignal<readonly string[]>([], building);
901
+ const [skipped, setSkipped] = createSignal(false, building);
902
+ const [attempted, setAttempted] = createSignal(false);
903
+ const [resetVersion, setResetVersion] = createSignal(0);
904
+ let defaults: string[] = [];
905
+ let element: HTMLFieldSetElement | null = null;
906
+
907
+ const active = (): boolean => !disabled() && root.activeName() === name();
908
+ const answers = createMemo(() => {
909
+ root.domVersion();
910
+ return inDocumentOrder(controls(), element, "input", (answer) => answer.element).filter(
911
+ (answer) => !answer.disabled(),
912
+ );
913
+ });
914
+ const status = createMemo((): QuestionnaireItemStatus => {
915
+ if (skipped()) return "skipped";
916
+ const selected = selectedIds();
917
+ return answers().some((answer) => selected.includes(answer.id)) ? "answered" : "unanswered";
918
+ });
919
+ const intentionallySkipped = (): boolean => status() === "skipped" && !required();
920
+ const valid = (): boolean =>
921
+ disabled() || intentionallySkipped() || (!externallyInvalid() && status() === "answered");
922
+ const invalid = (): boolean =>
923
+ !disabled() && !intentionallySkipped() && (externallyInvalid() || (attempted() && !valid()));
924
+ const hasInputAnswer = (): boolean => answers().some((answer) => answer.type === "input");
925
+
926
+ const declaredShortcuts = createMemo(() =>
927
+ root.declared() ? shortcutsByChoiceValue(root.definition(name()), root.shortcuts()) : null,
928
+ );
929
+ const positionalShortcuts = createMemo(() => {
930
+ const out = new Map<string, string>();
931
+ if (declaredShortcuts() !== null) return out;
932
+ const keys = shortcutKeys(root.shortcuts());
933
+ const choices = answers().filter((answer) => answer.type === "choice");
934
+ for (const [index, answer] of choices.slice(0, keys.length).entries()) {
935
+ out.set(answer.id, keys[index] as string);
936
+ }
937
+ return out;
938
+ });
939
+
940
+ const select = (answerId: string, selected: boolean): void => {
941
+ setSelectedIds((current) => {
942
+ if (!selected) return current.filter((id) => id !== answerId);
943
+ if (!untrack(multiple)) return [answerId];
944
+ return current.includes(answerId) ? current : [...current, answerId];
945
+ });
946
+ };
947
+
948
+ createEffect(status, (now, previous) => {
949
+ if (previous !== undefined && previous !== now) options.onStatusChange?.(now);
950
+ });
951
+
952
+ createEffect(multiple, (now, previous) => {
953
+ if (previous !== true || now) return;
954
+ const kept = untrack(answers).find((answer) => untrack(selectedIds).includes(answer.id));
955
+ setSelectedIds(kept === undefined ? [] : [kept.id]);
956
+ });
957
+
958
+ const focusInvalid = (): void => {
959
+ const filled = element?.querySelector<HTMLElement>("input[data-filled][name]:not(:disabled)");
960
+ const control = element?.querySelector<HTMLElement>(
961
+ "input:not([type=hidden]):not(:disabled), textarea:not(:disabled)",
962
+ );
963
+ (filled ?? control ?? element)?.focus();
964
+ };
965
+
966
+ const validate = (): boolean => {
967
+ setAttempted(true);
968
+ if (!valid()) return false;
969
+ if (!root.nativeValidation()) return true;
970
+
971
+ const malformed = answers().find(
972
+ (answer) =>
973
+ isAnswerFilled(answer) && answer.element.willValidate && !answer.element.validity.valid,
974
+ );
975
+ if (malformed === undefined) return true;
976
+ malformed.element.focus();
977
+ malformed.element.reportValidity();
978
+ return false;
979
+ };
980
+
981
+ const moveAnswerFocus = (from: Element, direction: "next" | "previous"): boolean => {
982
+ const all = answers();
983
+ const index = all.findIndex((answer) => answer.element === from);
984
+ const at = index < 0 ? null : (all[index] ?? null);
985
+
986
+ if (
987
+ all.length === 0 ||
988
+ (isTextEntryTarget(from) && !isEmptyNavigableInput(at)) ||
989
+ (index < 0 && from !== element)
990
+ ) {
991
+ return false;
992
+ }
993
+
994
+ const next =
995
+ index < 0
996
+ ? (all.find(isAnswerFilled) ?? (direction === "next" ? all[0] : all.at(-1)))
997
+ : all[(index + (direction === "next" ? 1 : -1) + all.length) % all.length];
998
+
999
+ if (next === undefined || next.element === from) return false;
1000
+ // Between two radios the browser already moves and selects.
1001
+ if (index >= 0 && isRadioTarget(from) && isRadioTarget(next.element)) return false;
1002
+
1003
+ next.element.focus();
1004
+ if (next.type === "choice" && isRadioTarget(next.element)) next.element.click();
1005
+ return true;
1006
+ };
1007
+
1008
+ const handleFor = (node: HTMLFieldSetElement): ItemHandle => ({
1009
+ element: node,
1010
+ name,
1011
+ disabled,
1012
+ required,
1013
+ status,
1014
+ focus: () => node.focus(),
1015
+ focusInvalid,
1016
+ validate,
1017
+ reset: () => {
1018
+ setAttempted(false);
1019
+ setSkipped(false);
1020
+ setSelectedIds(untrack(multiple) ? [...defaults] : defaults.slice(0, 1));
1021
+ setResetVersion((version) => version + 1);
1022
+ },
1023
+ skip: () => {
1024
+ if (untrack(required)) return;
1025
+ setSelectedIds([]);
1026
+ setSkipped(true);
1027
+ },
1028
+ answerByElement: (target) => answers().find((answer) => answer.element === target) ?? null,
1029
+ answerByShortcut: (shortcut) => {
1030
+ const declared = declaredShortcuts();
1031
+ if (declared !== null) {
1032
+ const wanted = [...declared].find(([, key]) => key === shortcut)?.[0];
1033
+ return (
1034
+ answers().find((answer) => answer.type === "choice" && answer.value() === wanted) ?? null
1035
+ );
1036
+ }
1037
+ const wanted = [...positionalShortcuts()].find(([, key]) => key === shortcut)?.[0];
1038
+ return answers().find((answer) => answer.id === wanted) ?? null;
1039
+ },
1040
+ moveAnswerFocus,
1041
+ });
1042
+
1043
+ let unregister: (() => void) | undefined;
1044
+ const attach = (node: HTMLFieldSetElement | null): void => {
1045
+ unregister?.();
1046
+ unregister = undefined;
1047
+ element = node;
1048
+ if (node !== null) unregister = root.register(handleFor(node));
1049
+ };
1050
+ onCleanup(() => unregister?.());
1051
+
1052
+ const value: ItemValue = {
1053
+ name,
1054
+ disabled,
1055
+ required,
1056
+ multiple,
1057
+ invalid,
1058
+ status,
1059
+ hasInputAnswer,
1060
+ resetVersion,
1061
+ shortcuts: root.shortcuts,
1062
+ isSelected: (answerId) => selectedIds().includes(answerId),
1063
+ shortcutFor: (answerId, choiceValue) =>
1064
+ (choiceValue === undefined ? undefined : declaredShortcuts()?.get(choiceValue)) ??
1065
+ positionalShortcuts().get(answerId) ??
1066
+ null,
1067
+ registerAnswer: (answer) => registerAnswer(answer, (other) => other.id === answer.id),
1068
+ registerSelection: (answerId, selected) => {
1069
+ if (selected) {
1070
+ defaults = [...defaults.filter((id) => id !== answerId), answerId];
1071
+ setSelectedIds((current) => {
1072
+ if (!untrack(multiple)) return current.length > 0 ? current : [answerId];
1073
+ return current.includes(answerId) ? current : [...current, answerId];
1074
+ });
1075
+ }
1076
+ return () => {
1077
+ defaults = defaults.filter((id) => id !== answerId);
1078
+ setSelectedIds((current) => current.filter((id) => id !== answerId));
1079
+ };
1080
+ },
1081
+ setDefault: (answerId, selected) => {
1082
+ defaults = defaults.filter((id) => id !== answerId);
1083
+ if (selected) defaults.push(answerId);
1084
+ },
1085
+ selectFromInteraction: (answerId, selected) => {
1086
+ setSkipped(false);
1087
+ select(answerId, selected);
1088
+ },
1089
+ syncControlled: (answerId, selected) => {
1090
+ if (selected) setSkipped(false);
1091
+ select(answerId, selected);
1092
+ },
1093
+ repair: () => {
1094
+ for (const answer of untrack(controls)) {
1095
+ if (answer.type === "choice") answer.element.checked = untrack(answer.checked);
1096
+ }
1097
+ },
1098
+ registerDescription,
1099
+ registerError,
1100
+ };
1101
+
1102
+ const owner = getOwner();
1103
+ if (owner !== null) install(owner, ItemContext, () => value);
1104
+
1105
+ const describedBy = (): string | undefined => {
1106
+ const ids = [
1107
+ ...descriptionIds(),
1108
+ ...(invalid() ? errorIds() : []),
1109
+ props["aria-describedby"],
1110
+ ].filter((id) => id !== undefined && id !== "");
1111
+ return ids.length === 0 ? undefined : ids.join(" ");
1112
+ };
1113
+
1114
+ const fieldsetProps = mergeProps(
1115
+ filterDOMProps(options, { global: true }),
1116
+ styleProps(cells(props)),
1117
+ {
1118
+ "aria-describedby": describedBy,
1119
+ "aria-invalid": () => (invalid() ? true : undefined),
1120
+ "aria-keyshortcuts": () =>
1121
+ keyShortcuts(
1122
+ props["aria-keyshortcuts"],
1123
+ active() && "Meta+Enter Control+Enter",
1124
+ active() && answers().length > 0 && "ArrowUp ArrowDown",
1125
+ active() && !root.first() && root.backKey(),
1126
+ active() && !root.last() && status() !== "unanswered" && root.forwardKey(),
1127
+ ),
1128
+ disabled,
1129
+ hidden: () => !active(),
1130
+ inert: () => !active(),
1131
+ tabIndex: -1,
1132
+ "data-active": () => present(active()),
1133
+ "data-disabled": () => present(disabled()),
1134
+ "data-invalid": () => present(invalid()),
1135
+ "data-multiple": () => present(multiple()),
1136
+ "data-required": () => present(required()),
1137
+ "data-status": status,
1138
+ },
1139
+ );
1140
+
1141
+ return (
1142
+ <fieldset {...fieldsetProps} ref={mergeRefs(attach, props.ref)}>
1143
+ {props.children}
1144
+ </fieldset>
1145
+ );
1146
+ }
1147
+
1148
+ // ---------------------------------------------------------------------------
1149
+ // Title, description, error
1150
+ // ---------------------------------------------------------------------------
1151
+
1152
+ export interface QuestionnairePartProps extends StyleProps {
1153
+ children?: Child;
1154
+ render?: RenderPart;
1155
+ }
1156
+
1157
+ /** The question itself: a `<legend>`, so it names the group. */
1158
+ export function QuestionnaireTitle(props: QuestionnairePartProps) {
1159
+ useItem();
1160
+ const elementProps = mergeProps(
1161
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1162
+ styleProps(cells(props)),
1163
+ );
1164
+ const render = props.render;
1165
+ if (render !== undefined) return render(partRender(elementProps)) as JSXElement;
1166
+ return <legend {...elementProps}>{props.children}</legend>;
1167
+ }
1168
+
1169
+ export function QuestionnaireDescription(props: QuestionnairePartProps) {
1170
+ const item = useItem();
1171
+ const generated = createUniqueId();
1172
+ const descriptionId = (): string => props.id ?? generated;
1173
+ onCleanup(item.registerDescription(untrack(descriptionId)));
1174
+
1175
+ const elementProps = mergeProps(
1176
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1177
+ styleProps(cells(props)),
1178
+ { id: descriptionId },
1179
+ );
1180
+ const render = props.render;
1181
+ if (render !== undefined) return render(partRender(elementProps)) as JSXElement;
1182
+ return <p {...elementProps}>{props.children}</p>;
1183
+ }
1184
+
1185
+ export interface QuestionnaireErrorProps extends StyleProps {
1186
+ /** @default a sentence saying an answer is needed, or that it may be skipped */
1187
+ children?: Child;
1188
+ render?: RenderPart<Pick<QuestionnaireItemState, "invalid">>;
1189
+ }
1190
+
1191
+ /** Shown, and announced, only while the question is invalid. */
1192
+ export function QuestionnaireError(props: QuestionnaireErrorProps) {
1193
+ const item = useItem();
1194
+ const generated = createUniqueId();
1195
+ const errorId = (): string => props.id ?? generated;
1196
+ onCleanup(item.registerError(untrack(errorId)));
1197
+
1198
+ const message = (): string =>
1199
+ item.required() ? "Choose an answer to continue." : "Choose an answer or skip this question.";
1200
+
1201
+ const elementProps = mergeProps(
1202
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1203
+ styleProps(cells(props)),
1204
+ {
1205
+ id: errorId,
1206
+ hidden: () => !item.invalid(),
1207
+ role: () => (item.invalid() ? "alert" : undefined),
1208
+ "data-invalid": () => present(item.invalid()),
1209
+ },
1210
+ );
1211
+ const render = props.render;
1212
+ if (render !== undefined) {
1213
+ return render(partRender(elementProps), { invalid: item.invalid }) as JSXElement;
1214
+ }
1215
+ return <p {...elementProps}>{props.children === undefined ? () => message() : props.children}</p>;
1216
+ }
1217
+
1218
+ // ---------------------------------------------------------------------------
1219
+ // Choices
1220
+ // ---------------------------------------------------------------------------
1221
+
1222
+ export interface QuestionnaireChoicesProps extends StyleProps {
1223
+ children?: Child;
1224
+ render?: RenderPart<QuestionnaireChoicesState>;
1225
+ }
1226
+
1227
+ export function QuestionnaireChoices(props: QuestionnaireChoicesProps) {
1228
+ const item = useItem();
1229
+ const elementProps = mergeProps(
1230
+ filterDOMProps(fromProps(cells(props)), { global: true, labelable: true }),
1231
+ styleProps(cells(props)),
1232
+ { "data-shortcuts": () => item.shortcuts() ?? undefined },
1233
+ );
1234
+ const render = props.render;
1235
+ if (render !== undefined) {
1236
+ return render(partRender(elementProps), { shortcuts: item.shortcuts }) as JSXElement;
1237
+ }
1238
+ return <div {...elementProps}>{props.children}</div>;
1239
+ }
1240
+
1241
+ export interface QuestionnaireChoiceProps extends StyleProps {
1242
+ children?: Child;
1243
+ /** What is submitted when this choice is the answer. */
1244
+ value: string;
1245
+ checked?: boolean;
1246
+ defaultChecked?: boolean;
1247
+ disabled?: boolean;
1248
+ onChange?: (event: Event) => void;
1249
+ render?: RenderPart<QuestionnaireChoiceState>;
1250
+ }
1251
+
1252
+ /**
1253
+ * One fixed answer: a `<label>` around its input, so the whole row is the
1254
+ * target.
1255
+ */
1256
+ export function QuestionnaireChoice(props: QuestionnaireChoiceProps) {
1257
+ const item = useItem();
1258
+ const options = fromProps(cells(props));
1259
+ const answerId = createUniqueId();
1260
+
1261
+ const value = (): string => props.value;
1262
+ const ownDisabled = (): boolean => props.disabled ?? false;
1263
+ const disabled = (): boolean => item.disabled() || ownDisabled();
1264
+ const controlledChecked = (): boolean | undefined => props.checked;
1265
+ const checked = (): boolean => {
1266
+ const controlled = controlledChecked();
1267
+ if (controlled === undefined) return item.isSelected(answerId);
1268
+ return item.status() === "skipped" ? false : controlled;
1269
+ };
1270
+ const type = (): "checkbox" | "radio" => (item.multiple() ? "checkbox" : "radio");
1271
+ const shortcut = (): string | null => (disabled() ? null : item.shortcutFor(answerId, value()));
1272
+
1273
+ onCleanup(
1274
+ item.registerSelection(
1275
+ answerId,
1276
+ untrack(() => props.defaultChecked ?? false),
1277
+ ),
1278
+ );
1279
+ const initial = untrack(controlledChecked);
1280
+ if (initial !== undefined) item.syncControlled(answerId, initial);
1281
+
1282
+ let input: HTMLInputElement | null = null;
1283
+ let unregister: (() => void) | undefined;
1284
+ const attach = (node: HTMLInputElement | null): void => {
1285
+ unregister?.();
1286
+ unregister = undefined;
1287
+ input = node;
1288
+ if (node === null) return;
1289
+ unregister = item.registerAnswer({
1290
+ id: answerId,
1291
+ type: "choice",
1292
+ element: node,
1293
+ disabled,
1294
+ value,
1295
+ checked,
1296
+ });
1297
+ };
1298
+ onCleanup(() => unregister?.());
1299
+
1300
+ createEffect(
1301
+ () => props.defaultChecked ?? false,
1302
+ (now) => item.setDefault(answerId, now),
1303
+ );
1304
+
1305
+ createEffect(
1306
+ () => ({ controlled: controlledChecked(), version: item.resetVersion() }),
1307
+ (now) => {
1308
+ if (now.controlled !== undefined) item.syncControlled(answerId, now.controlled);
1309
+ },
1310
+ );
1311
+
1312
+ // `defaultChecked` is what a native reset restores, and the state's own
1313
+ // reset has to agree with it or the two disagree until the next click.
1314
+ createEffect(
1315
+ () => ({
1316
+ checked: checked(),
1317
+ fallback: controlledChecked() ?? props.defaultChecked ?? false,
1318
+ version: item.resetVersion(),
1319
+ }),
1320
+ (now) => {
1321
+ if (input === null) return;
1322
+ input.defaultChecked = now.fallback;
1323
+ if (now.version > 0) input.checked = now.checked;
1324
+ },
1325
+ );
1326
+
1327
+ const onChange = (event: Event): void => {
1328
+ options.onChange?.(event);
1329
+ const target = event.currentTarget as HTMLInputElement;
1330
+ const controlled = untrack(controlledChecked);
1331
+ if (controlled === undefined) {
1332
+ item.selectFromInteraction(answerId, target.checked);
1333
+ } else if (untrack(item.status) === "skipped" && controlled === target.checked) {
1334
+ item.selectFromInteraction(answerId, controlled);
1335
+ }
1336
+ // The browser has already moved the mark, on this input and on the radio
1337
+ // it unchecked to do so. Where the state disagrees, the state is right.
1338
+ flush();
1339
+ item.repair();
1340
+ };
1341
+
1342
+ const stateProps: DOMProps = {
1343
+ "data-checked": () => present(checked()),
1344
+ "data-unchecked": () => present(!checked()),
1345
+ "data-disabled": () => present(disabled()),
1346
+ "data-invalid": () => present(item.invalid()),
1347
+ "data-shortcut": () => shortcut() ?? undefined,
1348
+ "data-type": type,
1349
+ };
1350
+
1351
+ const state: QuestionnaireChoiceState = {
1352
+ checked,
1353
+ disabled,
1354
+ invalid: item.invalid,
1355
+ shortcut,
1356
+ type,
1357
+ };
1358
+
1359
+ const choice: ChoiceValue = {
1360
+ state,
1361
+ stateProps,
1362
+ inputProps: {
1363
+ id: answerId,
1364
+ type,
1365
+ value,
1366
+ checked,
1367
+ disabled,
1368
+ name: () => (item.status() === "skipped" ? undefined : item.name()),
1369
+ required: () => item.required() && !item.multiple() && !item.hasInputAnswer(),
1370
+ "aria-invalid": () => (item.invalid() ? true : undefined),
1371
+ "aria-keyshortcuts": () => keyShortcuts(shortcut(), !disabled() && checked() && "Enter"),
1372
+ onChange,
1373
+ ref: attach,
1374
+ },
1375
+ };
1376
+
1377
+ const owner = getOwner();
1378
+ if (owner !== null) install(owner, ChoiceContext, () => choice);
1379
+
1380
+ const labelProps = mergeProps(
1381
+ // NOT `id`: it belongs on the input, which is the labelable element.
1382
+ filterDOMProps(options, { global: true, id: false }),
1383
+ styleProps(cells(props)),
1384
+ stateProps,
1385
+ );
1386
+
1387
+ const render = props.render;
1388
+ if (render !== undefined) return render(partRender(labelProps), state) as JSXElement;
1389
+ return <label {...labelProps}>{props.children}</label>;
1390
+ }
1391
+
1392
+ export interface QuestionnaireChoiceInputProps extends StyleProps {
1393
+ "aria-label"?: string;
1394
+ "aria-labelledby"?: string;
1395
+ "aria-describedby"?: string;
1396
+ ref?: RefTarget<HTMLInputElement>;
1397
+ render?: RenderPart<QuestionnaireChoiceState>;
1398
+ }
1399
+
1400
+ /** The radio or checkbox itself, which is what holds focus and is submitted. */
1401
+ export function QuestionnaireChoiceInput(props: QuestionnaireChoiceInputProps) {
1402
+ const choice = useChoice();
1403
+ const { ref: attach, ...inputProps } = choice.inputProps;
1404
+ const elementProps = mergeProps(
1405
+ filterDOMProps(fromProps(cells(props)), { global: true, labelable: true, id: false }),
1406
+ styleProps(cells(props)),
1407
+ choice.stateProps,
1408
+ inputProps,
1409
+ );
1410
+ const ref = mergeRefs(attach as RefTarget<HTMLInputElement>, props.ref);
1411
+ const render = props.render;
1412
+ if (render !== undefined) {
1413
+ return render(partRender({ ...elementProps, ref }), choice.state) as JSXElement;
1414
+ }
1415
+ return <input {...elementProps} ref={ref} />;
1416
+ }
1417
+
1418
+ export function QuestionnaireChoiceLabel(props: QuestionnairePartProps) {
1419
+ useChoice();
1420
+ const elementProps = mergeProps(
1421
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1422
+ styleProps(cells(props)),
1423
+ );
1424
+ const render = props.render;
1425
+ if (render !== undefined) return render(partRender(elementProps)) as JSXElement;
1426
+ return <span {...elementProps}>{props.children}</span>;
1427
+ }
1428
+
1429
+ export interface QuestionnaireChoiceShortcutProps extends StyleProps {
1430
+ /** @default the key assigned to the choice */
1431
+ children?: Child;
1432
+ render?: RenderPart<QuestionnaireChoiceShortcutState>;
1433
+ }
1434
+
1435
+ /**
1436
+ * The key that selects the choice, for sighted readers.
1437
+ *
1438
+ * `aria-hidden`, because the input already carries it in `aria-keyshortcuts`
1439
+ * and reading it twice is noise.
1440
+ */
1441
+ export function QuestionnaireChoiceShortcut(props: QuestionnaireChoiceShortcutProps) {
1442
+ const choice = useChoice();
1443
+ const elementProps = mergeProps(
1444
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1445
+ styleProps(cells(props)),
1446
+ {
1447
+ "aria-hidden": true,
1448
+ hidden: () => choice.state.shortcut() === null,
1449
+ "data-shortcut": () => choice.state.shortcut() ?? undefined,
1450
+ },
1451
+ );
1452
+ const render = props.render;
1453
+ if (render !== undefined) {
1454
+ return render(partRender(elementProps), { shortcut: choice.state.shortcut }) as JSXElement;
1455
+ }
1456
+ return (
1457
+ <span {...elementProps}>
1458
+ {props.children === undefined ? () => choice.state.shortcut() : props.children}
1459
+ </span>
1460
+ );
1461
+ }
1462
+
1463
+ // ---------------------------------------------------------------------------
1464
+ // Input
1465
+ // ---------------------------------------------------------------------------
1466
+
1467
+ export interface QuestionnaireInputProps extends StyleProps {
1468
+ /** @default "text" */
1469
+ type?: QuestionnaireInputType;
1470
+ value?: string | number;
1471
+ defaultValue?: string | number;
1472
+ disabled?: boolean;
1473
+ placeholder?: string;
1474
+ autoComplete?: string;
1475
+ inputMode?: string;
1476
+ maxLength?: number;
1477
+ minLength?: number;
1478
+ min?: number | string;
1479
+ max?: number | string;
1480
+ step?: number | string;
1481
+ pattern?: string;
1482
+ readOnly?: boolean;
1483
+ onInput?: (event: InputEvent) => void;
1484
+ onChange?: (event: Event) => void;
1485
+ onKeyDown?: (event: KeyboardEvent) => void;
1486
+ "aria-label"?: string;
1487
+ "aria-labelledby"?: string;
1488
+ "aria-describedby"?: string;
1489
+ ref?: RefTarget<HTMLInputElement>;
1490
+ render?: RenderPart<QuestionnaireInputState>;
1491
+ }
1492
+
1493
+ /** A typed answer, on its own or beside the choices. */
1494
+ export function QuestionnaireInput(props: QuestionnaireInputProps) {
1495
+ const item = useItem();
1496
+ const options = fromProps(cells(props));
1497
+ const answerId = createUniqueId();
1498
+
1499
+ const controlledValue = (): string | number | undefined => props.value;
1500
+ const defaultFilled = (): boolean => hasInputValue(props.defaultValue);
1501
+ const [typed, setTyped] = createSignal(untrack(defaultFilled));
1502
+ const disabled = (): boolean => item.disabled() || (props.disabled ?? false);
1503
+ const filled = (): boolean => {
1504
+ const controlled = controlledValue();
1505
+ return controlled === undefined ? typed() : hasInputValue(controlled);
1506
+ };
1507
+ const selected = (): boolean => item.isSelected(answerId);
1508
+
1509
+ onCleanup(item.registerSelection(answerId, untrack(defaultFilled)));
1510
+ const initial = untrack(controlledValue);
1511
+ if (initial !== undefined) item.syncControlled(answerId, hasInputValue(initial));
1512
+
1513
+ let input: HTMLInputElement | null = null;
1514
+ let unregister: (() => void) | undefined;
1515
+ const attach = (node: HTMLInputElement | null): void => {
1516
+ unregister?.();
1517
+ unregister = undefined;
1518
+ input = node;
1519
+ if (node === null) return;
1520
+ const start = untrack(() => props.defaultValue);
1521
+ // The content attribute, so a native reset has something to restore.
1522
+ if (untrack(controlledValue) === undefined && start !== undefined) {
1523
+ node.defaultValue = String(start);
1524
+ }
1525
+ unregister = item.registerAnswer({
1526
+ id: answerId,
1527
+ type: "input",
1528
+ element: node,
1529
+ disabled,
1530
+ value: () => "",
1531
+ checked: () => false,
1532
+ });
1533
+ };
1534
+ onCleanup(() => unregister?.());
1535
+
1536
+ createEffect(defaultFilled, (now) => item.setDefault(answerId, now));
1537
+
1538
+ createEffect(
1539
+ () => ({ controlled: controlledValue(), version: item.resetVersion() }),
1540
+ (now, previous) => {
1541
+ if (now.controlled !== undefined) {
1542
+ item.syncControlled(answerId, hasInputValue(now.controlled));
1543
+ if (input !== null) input.defaultValue = String(now.controlled);
1544
+ return;
1545
+ }
1546
+ if (previous !== undefined && now.version !== previous.version) {
1547
+ setTyped(untrack(defaultFilled));
1548
+ }
1549
+ },
1550
+ );
1551
+
1552
+ const onInput = (event: Event): void => {
1553
+ if (untrack(controlledValue) !== undefined) return;
1554
+ const next = (event.currentTarget as HTMLInputElement).value.trim().length > 0;
1555
+ setTyped(next);
1556
+ item.selectFromInteraction(answerId, next);
1557
+ };
1558
+
1559
+ const inputProps = mergeProps(
1560
+ filterDOMProps(options, {
1561
+ global: true,
1562
+ labelable: true,
1563
+ id: false,
1564
+ propNames: INPUT_PROPS,
1565
+ }),
1566
+ styleProps(cells(props)),
1567
+ {
1568
+ id: answerId,
1569
+ type: () => props.type ?? "text",
1570
+ disabled,
1571
+ // Outside the form until it is the answer, so an abandoned draft is
1572
+ // neither submitted nor validated.
1573
+ form: () => (selected() ? undefined : ""),
1574
+ name: () => (selected() ? item.name() : undefined),
1575
+ "aria-invalid": () => (item.invalid() ? true : undefined),
1576
+ "aria-keyshortcuts": () => keyShortcuts(!disabled() && filled() && selected() && "Enter"),
1577
+ "data-disabled": () => present(disabled()),
1578
+ "data-invalid": () => present(item.invalid()),
1579
+ "data-filled": () => present(filled()),
1580
+ "data-empty": () => present(!filled()),
1581
+ onInput,
1582
+ },
1583
+ props.value === undefined ? null : { value: () => String(controlledValue() ?? "") },
1584
+ );
1585
+
1586
+ const ref = mergeRefs(attach, props.ref);
1587
+ const render = props.render;
1588
+ if (render !== undefined) {
1589
+ const state: QuestionnaireInputState = { disabled, filled, invalid: item.invalid };
1590
+ return render(partRender({ ...inputProps, ref }), state) as JSXElement;
1591
+ }
1592
+ return <input {...inputProps} ref={ref} />;
1593
+ }
1594
+
1595
+ // ---------------------------------------------------------------------------
1596
+ // Navigation
1597
+ // ---------------------------------------------------------------------------
1598
+
1599
+ export interface QuestionnaireButtonProps extends StyleProps {
1600
+ children?: Child;
1601
+ disabled?: boolean;
1602
+ type?: "button" | "submit" | "reset";
1603
+ "aria-label"?: string;
1604
+ "aria-labelledby"?: string;
1605
+ "aria-describedby"?: string;
1606
+ ref?: RefTarget<HTMLButtonElement>;
1607
+ render?: RenderPart<QuestionnaireNavigationState>;
1608
+ }
1609
+
1610
+ interface NavigationOptions {
1611
+ visible: Accessor<boolean>;
1612
+ label: string;
1613
+ type: "button" | "submit";
1614
+ /** Whether Enter on a chosen answer does what this button does. */
1615
+ confirms: boolean;
1616
+ action?: () => void;
1617
+ }
1618
+
1619
+ /**
1620
+ * A button that is in the document for every question and shown for some.
1621
+ *
1622
+ * Hidden rather than removed, so the row of actions keeps its columns and a
1623
+ * layout does not jump when the last question swaps Next for Submit.
1624
+ */
1625
+ function navigationButton(
1626
+ props: Incoming<QuestionnaireButtonProps>,
1627
+ navigation: NavigationOptions,
1628
+ ) {
1629
+ const root = useRoot();
1630
+ const options = fromProps(props);
1631
+ const disabled = (): boolean => props.disabled?.() ?? false;
1632
+ const shortcut = (): "Enter" | null =>
1633
+ navigation.confirms && navigation.visible() && !disabled() ? "Enter" : null;
1634
+
1635
+ const buttonProps = mergeProps(
1636
+ filterDOMProps(options, { global: true, labelable: true, propNames: BUTTON_PROPS }),
1637
+ styleProps(props),
1638
+ {
1639
+ type: () => props.type?.() ?? navigation.type,
1640
+ disabled,
1641
+ hidden: () => !navigation.visible(),
1642
+ inert: () => !navigation.visible(),
1643
+ "aria-hidden": () => (navigation.visible() ? undefined : true),
1644
+ "aria-keyshortcuts": () => shortcut() ?? undefined,
1645
+ tabIndex: () => (navigation.visible() ? props.tabIndex?.() : -1),
1646
+ "data-visible": () => present(navigation.visible()),
1647
+ "data-hidden": () => present(!navigation.visible()),
1648
+ "data-disabled": () => present(disabled()),
1649
+ "data-shortcut": () => shortcut() ?? undefined,
1650
+ "data-status": () => root.activeStatus() ?? undefined,
1651
+ // Chained after the caller's `onClick`, which can cancel the move.
1652
+ onClick: (event: MouseEvent): void => {
1653
+ if (!event.defaultPrevented) navigation.action?.();
1654
+ },
1655
+ },
1656
+ );
1657
+
1658
+ const render = props.render?.();
1659
+ if (render !== undefined) {
1660
+ const state: QuestionnaireNavigationState = {
1661
+ disabled,
1662
+ shortcut,
1663
+ status: root.activeStatus,
1664
+ visible: navigation.visible,
1665
+ };
1666
+ return render(partRender({ ...buttonProps, ref: props.ref?.() }), state) as JSXElement;
1667
+ }
1668
+
1669
+ return (
1670
+ <button {...buttonProps} ref={mergeRefs(props.ref?.())}>
1671
+ {props.children === undefined ? navigation.label : props.children}
1672
+ </button>
1673
+ );
1674
+ }
1675
+
1676
+ export function QuestionnairePrevious(props: Incoming<QuestionnaireButtonProps>) {
1677
+ const root = useRoot();
1678
+ return navigationButton(props, {
1679
+ visible: () => root.total() > 1 && !root.first(),
1680
+ label: "Previous",
1681
+ type: "button",
1682
+ confirms: false,
1683
+ action: root.goPrevious,
1684
+ });
1685
+ }
1686
+
1687
+ export function QuestionnaireSkip(props: Incoming<QuestionnaireButtonProps>) {
1688
+ const root = useRoot();
1689
+ return navigationButton(props, {
1690
+ visible: () => root.activeRequired() === false,
1691
+ label: "Skip",
1692
+ type: "button",
1693
+ confirms: false,
1694
+ action: root.skipCurrent,
1695
+ });
1696
+ }
1697
+
1698
+ export function QuestionnaireNext(props: Incoming<QuestionnaireButtonProps>) {
1699
+ const root = useRoot();
1700
+ return navigationButton(props, {
1701
+ visible: () => root.total() > 1 && !root.last(),
1702
+ label: "Next",
1703
+ type: "button",
1704
+ confirms: true,
1705
+ action: root.goNext,
1706
+ });
1707
+ }
1708
+
1709
+ export function QuestionnaireSubmit(props: Incoming<QuestionnaireButtonProps>) {
1710
+ const root = useRoot();
1711
+ return navigationButton(props, {
1712
+ visible: () => root.total() > 0 && root.last(),
1713
+ label: "Submit",
1714
+ type: "submit",
1715
+ confirms: true,
1716
+ });
1717
+ }