@zeyos/zx 5.6.0 → 5.7.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 (227) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/README.md +73 -7
  3. package/bin/zx-css.js +328 -0
  4. package/dist/types/components/account-menu/account-menu.d.ts +4 -2
  5. package/dist/types/components/activity-list/activity-list.d.ts +14 -8
  6. package/dist/types/components/agent-thread/ag-ui.d.ts +340 -0
  7. package/dist/types/components/agent-thread/agent-thread.d.ts +142 -14
  8. package/dist/types/components/agent-thread/ui-message-stream.d.ts +401 -0
  9. package/dist/types/components/app-sidebar/app-sidebar.d.ts +14 -8
  10. package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
  11. package/dist/types/components/calendar/calendar-model.d.ts +9 -2
  12. package/dist/types/components/calendar/calendar.d.ts +12 -4
  13. package/dist/types/components/chart/chart.d.ts +25 -13
  14. package/dist/types/components/checklist/checklist.d.ts +29 -0
  15. package/dist/types/components/code-editor/code-editor.d.ts +7 -2
  16. package/dist/types/components/composer/composer.d.ts +206 -4
  17. package/dist/types/components/composer/queue.d.ts +76 -0
  18. package/dist/types/components/copy/copy-button.d.ts +6 -4
  19. package/dist/types/components/copy/copy-input.d.ts +10 -6
  20. package/dist/types/components/datebox/date-range-box.d.ts +33 -0
  21. package/dist/types/components/datebox/placeholder.d.ts +7 -0
  22. package/dist/types/components/dialog/dialog.d.ts +2 -2
  23. package/dist/types/components/dock/dock.d.ts +12 -3
  24. package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
  25. package/dist/types/components/field-upload/field-upload.d.ts +3 -2
  26. package/dist/types/components/file-item/file-item.d.ts +3 -2
  27. package/dist/types/components/file-list/file-list.d.ts +14 -8
  28. package/dist/types/components/filter/filter-model.d.ts +31 -1
  29. package/dist/types/components/filter/filter.d.ts +20 -2
  30. package/dist/types/components/finder/finder.d.ts +14 -6
  31. package/dist/types/components/flag/flag.d.ts +99 -0
  32. package/dist/types/components/grid/grid.d.ts +1 -1
  33. package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
  34. package/dist/types/components/launcher/launcher.d.ts +2 -0
  35. package/dist/types/components/modal/modal.d.ts +34 -8
  36. package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
  37. package/dist/types/components/number-field/number-field.d.ts +41 -7
  38. package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
  39. package/dist/types/components/prose/prose.d.ts +9 -6
  40. package/dist/types/components/questionnaire/conditions.d.ts +270 -0
  41. package/dist/types/components/questionnaire/items.d.ts +52 -30
  42. package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
  43. package/dist/types/components/rating/rating.d.ts +5 -3
  44. package/dist/types/components/select/country.d.ts +106 -0
  45. package/dist/types/components/select/field-adapter.d.ts +2 -1
  46. package/dist/types/components/select/locale.d.ts +102 -0
  47. package/dist/types/components/select/select.d.ts +41 -2
  48. package/dist/types/components/sheet/sheet.d.ts +2 -2
  49. package/dist/types/components/slider/slider.d.ts +1 -0
  50. package/dist/types/components/sort-control/sort-control.d.ts +7 -3
  51. package/dist/types/components/source-list/source-list.d.ts +7 -5
  52. package/dist/types/components/split-view/split-view.d.ts +5 -3
  53. package/dist/types/components/surface/catalog.d.ts +260 -0
  54. package/dist/types/components/surface/elicit.d.ts +81 -0
  55. package/dist/types/components/surface/mcp.d.ts +165 -0
  56. package/dist/types/components/surface/schema.d.ts +314 -0
  57. package/dist/types/components/surface/stream.d.ts +118 -0
  58. package/dist/types/components/surface/surface.d.ts +718 -0
  59. package/dist/types/components/surface/text.d.ts +277 -0
  60. package/dist/types/components/surface/validate.d.ts +339 -0
  61. package/dist/types/components/table/table.d.ts +55 -3
  62. package/dist/types/components/table/window.d.ts +203 -0
  63. package/dist/types/components/toolbar/toolbar.d.ts +10 -6
  64. package/dist/types/components/tooltip/tooltip.d.ts +2 -2
  65. package/dist/types/components/tree/tree.d.ts +20 -13
  66. package/dist/types/core/component.d.ts +10 -0
  67. package/dist/types/core/date.d.ts +8 -1
  68. package/dist/types/core/dom.d.ts +15 -0
  69. package/dist/types/core/http.d.ts +10 -0
  70. package/dist/types/core/i18n.d.ts +38 -0
  71. package/dist/types/core/messages.d.ts +344 -1
  72. package/dist/types/core/storage.d.ts +7 -2
  73. package/dist/types/elements/define.d.ts +21 -46
  74. package/dist/types/elements/definitions.d.ts +147 -0
  75. package/dist/types/elements/kit.d.ts +7 -0
  76. package/dist/types/elements/reflect.d.ts +6 -3
  77. package/dist/types/index.d.ts +10 -1
  78. package/dist/types/internal/date-locale.d.ts +7 -0
  79. package/dist/types/internal/json-patch.d.ts +146 -0
  80. package/dist/types/locales/de.d.ts +13 -0
  81. package/dist/types/locales/en.d.ts +2 -0
  82. package/dist/types/locales/index.d.ts +823 -0
  83. package/dist/types/zeyos/view.d.ts +8 -1
  84. package/dist/zx-zeyos.esm.js +16852 -15131
  85. package/dist/zx-zeyos.esm.min.js +5 -5
  86. package/dist/zx.core.css +1276 -0
  87. package/dist/zx.core.min.css +1 -0
  88. package/dist/zx.css +520 -143
  89. package/dist/zx.esm.js +40940 -29684
  90. package/dist/zx.esm.min.js +36 -23
  91. package/dist/zx.global.js +40940 -29684
  92. package/dist/zx.global.min.js +36 -23
  93. package/dist/zx.layered.css +17315 -0
  94. package/dist/zx.layered.min.css +1 -0
  95. package/dist/zx.min.css +1 -1
  96. package/docs/agent-catalog.json +12501 -0
  97. package/docs/agent-surfaces.md +340 -0
  98. package/docs/api.json +909 -137
  99. package/docs/llms.md +1046 -80
  100. package/docs/llms.txt +30 -9
  101. package/package.json +29 -6
  102. package/src/components/account-menu/account-menu.js +6 -3
  103. package/src/components/activity-item/activity-item.js +2 -1
  104. package/src/components/activity-list/activity-list.js +16 -10
  105. package/src/components/agent-thread/ag-ui.js +1439 -0
  106. package/src/components/agent-thread/agent-thread.js +359 -54
  107. package/src/components/agent-thread/ui-message-stream.js +1281 -0
  108. package/src/components/app-sidebar/app-sidebar.js +18 -8
  109. package/src/components/approval-card/approval-card.js +3 -2
  110. package/src/components/block-view/block-view.js +7 -6
  111. package/src/components/breadcrumb/breadcrumb.js +8 -5
  112. package/src/components/button/button.css +24 -11
  113. package/src/components/calendar/calendar-model.js +8 -2
  114. package/src/components/calendar/calendar.js +53 -18
  115. package/src/components/chart/chart.js +54 -23
  116. package/src/components/checklist/checklist.css +9 -1
  117. package/src/components/checklist/checklist.js +59 -3
  118. package/src/components/checklist/field-adapter.js +2 -11
  119. package/src/components/code-editor/code-editor.js +45 -8
  120. package/src/components/code-editor/field-adapter.js +1 -1
  121. package/src/components/composer/composer.css +80 -1
  122. package/src/components/composer/composer.js +390 -16
  123. package/src/components/composer/queue.js +78 -0
  124. package/src/components/context-menu/context-menu.js +12 -1
  125. package/src/components/copy/copy-button.js +9 -7
  126. package/src/components/copy/copy-input.js +10 -6
  127. package/src/components/date-picker/date-picker.js +2 -1
  128. package/src/components/date-picker/date-range-picker.js +8 -7
  129. package/src/components/datebox/date-range-box.js +3 -9
  130. package/src/components/datebox/datebox.js +18 -21
  131. package/src/components/datebox/placeholder.js +18 -0
  132. package/src/components/dialog/dialog.js +4 -5
  133. package/src/components/dock/dock.js +34 -13
  134. package/src/components/entity-ref/entity-ref.js +16 -5
  135. package/src/components/field-upload/field-upload.js +81 -38
  136. package/src/components/file-item/file-item.js +70 -40
  137. package/src/components/file-list/file-list.js +15 -9
  138. package/src/components/filter/filter-model.js +46 -8
  139. package/src/components/filter/filter.css +3 -3
  140. package/src/components/filter/filter.js +29 -10
  141. package/src/components/filter-panel/filter-panel.js +13 -5
  142. package/src/components/finder/finder.js +50 -26
  143. package/src/components/flag/flag.css +40 -0
  144. package/src/components/flag/flag.js +177 -0
  145. package/src/components/form/form.js +1 -1
  146. package/src/components/grid/grid.js +22 -8
  147. package/src/components/kanban-view/kanban-view.js +51 -81
  148. package/src/components/launcher/launcher.js +17 -2
  149. package/src/components/list-toolbar/list-toolbar.js +2 -1
  150. package/src/components/master-panel/master-panel.js +1 -1
  151. package/src/components/menu-button/menu-button.js +4 -0
  152. package/src/components/message/message.js +3 -0
  153. package/src/components/modal/modal.js +62 -8
  154. package/src/components/multi-value-editor/multi-value-editor.js +10 -9
  155. package/src/components/navigation-bar/navigation-bar.js +3 -3
  156. package/src/components/number-field/number-field.js +98 -29
  157. package/src/components/prompt-starters/prompt-starters.css +91 -0
  158. package/src/components/prompt-starters/prompt-starters.js +206 -0
  159. package/src/components/prose/prose.js +14 -10
  160. package/src/components/questionnaire/conditions.js +666 -0
  161. package/src/components/questionnaire/items.js +150 -41
  162. package/src/components/questionnaire/questionnaire.js +126 -32
  163. package/src/components/rating/rating.js +5 -4
  164. package/src/components/run-status/run-status.js +2 -2
  165. package/src/components/select/country.js +136 -0
  166. package/src/components/select/field-adapter.js +7 -2
  167. package/src/components/select/locale.js +219 -0
  168. package/src/components/select/select.css +20 -22
  169. package/src/components/select/select.js +94 -12
  170. package/src/components/sheet/sheet-stack.js +10 -1
  171. package/src/components/sheet/sheet.js +12 -5
  172. package/src/components/slider/slider.js +7 -2
  173. package/src/components/sort-control/sort-control.js +15 -5
  174. package/src/components/source-list/source-list.js +7 -4
  175. package/src/components/split-view/split-view.js +5 -3
  176. package/src/components/surface/catalog.js +1334 -0
  177. package/src/components/surface/elicit.js +107 -0
  178. package/src/components/surface/mcp.js +243 -0
  179. package/src/components/surface/schema.js +644 -0
  180. package/src/components/surface/stream.js +245 -0
  181. package/src/components/surface/surface.css +308 -0
  182. package/src/components/surface/surface.js +2291 -0
  183. package/src/components/surface/text.js +513 -0
  184. package/src/components/surface/validate.js +2218 -0
  185. package/src/components/tabbox/tabbox.js +9 -0
  186. package/src/components/table/table.css +63 -3
  187. package/src/components/table/table.js +167 -28
  188. package/src/components/table/window.js +317 -0
  189. package/src/components/toolbar/toolbar.js +12 -7
  190. package/src/components/tooltip/tooltip.css +2 -3
  191. package/src/components/tooltip/tooltip.js +32 -5
  192. package/src/components/tree/tree.js +53 -23
  193. package/src/core/component.js +25 -1
  194. package/src/core/date.js +62 -16
  195. package/src/core/dom.js +67 -4
  196. package/src/core/format.js +15 -13
  197. package/src/core/http.js +29 -20
  198. package/src/core/i18n.js +83 -10
  199. package/src/core/icons.js +13 -2
  200. package/src/core/keyboard.js +79 -8
  201. package/src/core/messages.js +376 -2
  202. package/src/core/overlay-host.js +1 -0
  203. package/src/core/position.js +3 -2
  204. package/src/core/storage.js +59 -6
  205. package/src/elements/define.js +178 -130
  206. package/src/elements/definitions.js +229 -0
  207. package/src/elements/kit.js +444 -0
  208. package/src/elements/reflect.js +8 -3
  209. package/src/index.js +10 -1
  210. package/src/internal/date-locale.js +11 -0
  211. package/src/internal/json-patch.js +405 -0
  212. package/src/locales/de.js +911 -0
  213. package/src/locales/en.js +2 -0
  214. package/src/locales/index.js +7 -0
  215. package/src/zeyos/calendar.js +2 -1
  216. package/src/zeyos/form.js +2 -1
  217. package/src/zeyos/launcher.js +7 -6
  218. package/src/zeyos/module-bar.js +2 -1
  219. package/src/zeyos/schema.js +37 -23
  220. package/src/zeyos/select.js +4 -3
  221. package/src/zeyos/table.js +2 -13
  222. package/src/zeyos/view.js +57 -17
  223. package/styles/core.css +11 -0
  224. package/styles/tokens/semantic.css +1 -0
  225. package/styles/zeyos.css +2 -0
  226. package/styles/zx.css +4 -8
  227. package/styles/zx.layered.css +1 -0
@@ -5,6 +5,17 @@
5
5
  * are testable in Node.
6
6
  * @module questionnaire/items
7
7
  */
8
+ import { translate } from '../../core/i18n.js';
9
+ import {
10
+ NEXT_REVIEW, NEXT_SUBMIT, checkCondition, checkNext, checkRuleList, evaluate, isEmptyAnswer,
11
+ resolveNext as resolveTarget
12
+ } from './conditions.js';
13
+
14
+ export { isEmptyAnswer };
15
+
16
+ /** @typedef {import('./conditions.js').Condition} Condition */
17
+ /** @typedef {import('./conditions.js').NextTarget} NextTarget */
18
+ /** @typedef {import('./conditions.js').ValidationRule} ValidationRule */
8
19
 
9
20
  /**
10
21
  * @typedef {Object} QuestionnaireChoice
@@ -38,11 +49,18 @@
38
49
  * @property {QuestionnaireChoice[]} [choices=[]] Fixed answers.
39
50
  * @property {QuestionnaireInput|null} [input=null] Freeform answer offered beside the choices.
40
51
  * @property {Object|null} [field=null] Any registered Zx `Field` type used as the answer control.
41
- * @property {((answers: Record<string, unknown>) => boolean)|null} [when=null] Visibility predicate.
42
- * @property {string|((answer: unknown, answers: Record<string, unknown>) => string|null)|null} [next=null]
43
- * Branch target: an item name, or a function returning one.
44
- * @property {((answer: unknown, answers: Record<string, unknown>) => string|null|Promise<string|null>)|null} [validate=null]
45
- * Extra validation returning an error message, or null when the answer is acceptable.
52
+ * @property {Condition|((answers: Record<string, unknown>) => boolean)|null} [when=null] Visibility:
53
+ * a declarative condition, or a predicate. Either sees only the answers of visible items declared
54
+ * before this one, and a declarative condition may only name those items. Anything else, such as
55
+ * `false` or `{}`, reads as absent.
56
+ * @property {NextTarget|((answer: unknown, answers: Record<string, unknown>) => string|null)|null} [next=null]
57
+ * Branch target: an item name, `$review`, `$submit`, a list of `{if, goto}` branches whose first
58
+ * match wins, or a function returning a name. A branch condition may name this item and the
59
+ * items declared before it. An item named `$review` or `$submit` takes the name's place; anything
60
+ * else, such as `false` or `[]`, reads as absent.
61
+ * @property {ValidationRule[]|((answer: unknown, answers: Record<string, unknown>) => string|null|Promise<string|null>)|null} [validate=null]
62
+ * Extra validation: a list of declarative rules, or a function returning an error message, or
63
+ * null when the answer is acceptable. Anything else, such as `false` or `[]`, reads as absent.
46
64
  */
47
65
 
48
66
  /**
@@ -57,9 +75,11 @@
57
75
  * @property {NormalizedChoice[]} choices Fixed answers with shortcut keys assigned.
58
76
  * @property {Required<QuestionnaireInput>|null} input Freeform answer, or null.
59
77
  * @property {Object|null} field Field options, or null.
60
- * @property {((answers: Record<string, unknown>) => boolean)|null} when Visibility predicate.
61
- * @property {string|((answer: unknown, answers: Record<string, unknown>) => string|null)|null} next Branch target.
62
- * @property {((answer: unknown, answers: Record<string, unknown>) => string|null|Promise<string|null>)|null} validate Extra validation.
78
+ * @property {Condition|((answers: Record<string, unknown>) => boolean)|null} when Visibility
79
+ * condition or predicate.
80
+ * @property {NextTarget|((answer: unknown, answers: Record<string, unknown>) => string|null)|null} next Branch target.
81
+ * @property {ValidationRule[]|((answer: unknown, answers: Record<string, unknown>) => string|null|Promise<string|null>)|null} validate
82
+ * Extra validation.
63
83
  */
64
84
 
65
85
  /**
@@ -94,12 +114,26 @@
94
114
  const SHORTCUT_KEYS = '123456789abcdefghijklmnopqrstuvwxyz';
95
115
 
96
116
  /**
97
- * Normalizes and validates a list of item definitions. Never mutates its input.
117
+ * Normalizes and validates a list of item definitions. Never mutates its input; declarative
118
+ * `when`, `next` and `validate` forms are copied.
98
119
  * @param {QuestionnaireItem[]} list Item definitions.
99
120
  * @returns {NormalizedItem[]}
100
- * @throws {TypeError} When the list, an item, or a name is malformed, or a name repeats.
121
+ * @throws {TypeError} When the list, an item, or a name is malformed, a name repeats, or a
122
+ * declarative condition, branch list or rule list is malformed — including a condition naming
123
+ * an item that is not declared before it. A `when`, `next` or `validate` that is neither
124
+ * declarative nor a function does not throw: it reads as absent.
101
125
  */
102
126
  export function normalizeItems(list) {
127
+ return normalizeItemList(list, translate);
128
+ }
129
+
130
+ /**
131
+ * {@link normalizeItems} with the messages of a component.
132
+ * @param {QuestionnaireItem[]} list Item definitions.
133
+ * @param {(key: string) => string} text Resolves the default label of a free-form input.
134
+ * @returns {NormalizedItem[]}
135
+ */
136
+ export function normalizeItemList(list, text) {
103
137
  if (!Array.isArray(list)) throw new TypeError('Questionnaire items must be an array');
104
138
  /** @type {Set<string>} */
105
139
  const seen = new Set();
@@ -112,11 +146,14 @@ export function normalizeItems(list) {
112
146
  }
113
147
  const name = item.name;
114
148
  if (seen.has(name)) throw new TypeError(`Item already exists: ${name}`);
149
+ // Conditions may name only what comes before; `next` branches may also name the item itself.
150
+ const before = [...seen];
115
151
  seen.add(name);
116
152
 
153
+ const validate = normalizeValidate(item.validate, name);
117
154
  const choices = normalizeChoices(item.choices ?? [], name);
118
155
  const field = item.field && typeof item.field === 'object' ? { ...item.field } : null;
119
- const input = normalizeInput(item.input);
156
+ const input = normalizeInput(item.input, text);
120
157
  if (choices.length === 0 && !field && !input) {
121
158
  throw new TypeError(`Item "${name}" needs choices, an input, or a field`);
122
159
  }
@@ -125,15 +162,16 @@ export function normalizeItems(list) {
125
162
  prompt: String(item.prompt ?? name),
126
163
  description: item.description == null || item.description === '' ? null : String(item.description),
127
164
  section: item.section == null ? '' : String(item.section),
128
- required: Boolean(item.required),
165
+ // A declarative required rule marks the control too, so `required` and `aria-required` show.
166
+ required: Boolean(item.required) || (Array.isArray(validate) && validate.some((rule) => rule.required === true)),
129
167
  multiple: Boolean(item.multiple),
130
168
  skippable: Boolean(item.skippable),
131
169
  choices,
132
170
  input,
133
171
  field,
134
- when: typeof item.when === 'function' ? item.when : null,
135
- next: typeof item.next === 'function' || (typeof item.next === 'string' && item.next) ? item.next : null,
136
- validate: typeof item.validate === 'function' ? item.validate : null
172
+ when: normalizeWhen(item.when, name, before),
173
+ next: normalizeNext(item.next, name, [...before, name]),
174
+ validate
137
175
  };
138
176
  });
139
177
  }
@@ -187,16 +225,17 @@ export function normalizeChoices(list, itemName = '') {
187
225
  }
188
226
 
189
227
  /**
190
- * Reports whether an item's `when` predicate passes for a given set of answers. An item without
191
- * one is always visible, and a predicate that throws hides nothing — a broken condition must not
192
- * strand the reader mid-questionnaire.
228
+ * Reports whether an item's `when` condition or predicate passes for a given set of answers. An
229
+ * item without one is always visible, and a condition that throws hides nothing — a broken
230
+ * condition must not strand the reader mid-questionnaire.
193
231
  * @param {NormalizedItem} item Item to test.
194
232
  * @param {Record<string, unknown>} answers Answers visible to the predicate.
195
233
  * @returns {boolean}
196
234
  */
197
235
  export function isVisible(item, answers) {
198
- if (typeof item.when !== 'function') return true;
236
+ if (item.when == null) return true;
199
237
  try {
238
+ if (typeof item.when !== 'function') return evaluate(item.when, answers);
200
239
  return item.when(answers) !== false;
201
240
  } catch {
202
241
  return true;
@@ -243,25 +282,24 @@ export function visibleItems(items, raw) {
243
282
  /**
244
283
  * Resolves which item follows the given one.
245
284
  *
246
- * A `next` of `null` falls through to the next visible item in declaration order. A string, or a
247
- * function returning a string, names a target: when that target is currently hidden the walk
248
- * continues forward from it rather than stranding the reader on an invisible question.
285
+ * A `next` of `null`, or a branch list where nothing matches, falls through to the next visible
286
+ * item in declaration order. A string, a matching branch, or a function returning a string names a
287
+ * target: when that target is currently hidden the walk continues forward from it rather than
288
+ * stranding the reader on an invisible question. `$review` and `$submit` are returned as they are,
289
+ * for the caller to open the review screen or submit, unless an item bears that name.
249
290
  * @param {NormalizedItem[]} items All items.
250
291
  * @param {NormalizedItem} item Item being left.
251
292
  * @param {Record<string, unknown>} raw Every answer given.
252
- * @returns {string|null} Name of the next item, or null at the end of the questionnaire.
293
+ * @returns {string|null} Name of the next item, `$review`, `$submit`, or null at the end of the
294
+ * questionnaire.
253
295
  * @throws {RangeError} When `next` names an item that does not exist.
254
296
  */
255
297
  export function resolveNext(items, item, raw) {
256
298
  const { answers, visible } = resolveFlow(items, raw);
257
299
  const shown = new Set(visible.map((candidate) => candidate.name));
258
300
 
259
- let target = null;
260
- if (typeof item.next === 'string') target = item.next;
261
- else if (typeof item.next === 'function') {
262
- const resolved = item.next(answers[item.name], answers);
263
- target = resolved == null || resolved === '' ? null : String(resolved);
264
- }
301
+ const target = resolveTarget(item.next, answers[item.name], answers);
302
+ if (endsFlow(items, target)) return target;
265
303
 
266
304
  let from = items.indexOf(item);
267
305
  if (target !== null) {
@@ -279,16 +317,14 @@ export function resolveNext(items, item, raw) {
279
317
  }
280
318
 
281
319
  /**
282
- * Reports whether an answer counts as absent. An empty string, an empty array, null, and undefined
283
- * are all "no answer"; `false` and `0` are answers.
284
- * @param {unknown} value Answer value.
320
+ * Reports whether a resolved target ends the walk rather than naming an item: `$review` or
321
+ * `$submit`, unless an item bears that name, which then goes first.
322
+ * @param {NormalizedItem[]} items All items.
323
+ * @param {string|null} target What `resolveNext()` returned.
285
324
  * @returns {boolean}
286
325
  */
287
- export function isEmptyAnswer(value) {
288
- if (value == null) return true;
289
- if (typeof value === 'string') return value.trim() === '';
290
- if (Array.isArray(value)) return value.every((entry) => isEmptyAnswer(entry));
291
- return false;
326
+ export function endsFlow(items, target) {
327
+ return (target === NEXT_REVIEW || target === NEXT_SUBMIT) && !items.some((item) => item.name === target);
292
328
  }
293
329
 
294
330
  /**
@@ -345,7 +381,9 @@ export function progressOf(items, raw, path) {
345
381
 
346
382
  const seen = new Set(walked);
347
383
  const from = active ? visible.indexOf(active) : -1;
348
- const remaining = visible.slice(from + 1).filter((item) => !seen.has(item.name)).length;
384
+ // An active item that leads to `$review` or `$submit` ends the path, whatever is declared after.
385
+ const remaining = active && endsHere(items, active, raw) ? 0
386
+ : visible.slice(from + 1).filter((item) => !seen.has(item.name)).length;
349
387
 
350
388
  const total = walked.length + remaining;
351
389
  return {
@@ -357,14 +395,85 @@ export function progressOf(items, raw, path) {
357
395
  };
358
396
  }
359
397
 
360
- /** @param {unknown} input @returns {Required<QuestionnaireInput>|null} */
361
- function normalizeInput(input) {
398
+ /** @param {unknown} input @param {(key: string) => string} text @returns {Required<QuestionnaireInput>|null} */
399
+ function normalizeInput(input, text) {
362
400
  if (!input) return null;
363
401
  const source = typeof input === 'object' && !Array.isArray(input) ? /** @type {QuestionnaireInput} */ (input) : {};
364
402
  return {
365
- label: String(source.label ?? 'Other'),
403
+ label: String(source.label ?? text('questionnaire.other')),
366
404
  placeholder: String(source.placeholder ?? ''),
367
405
  multiline: Boolean(source.multiline),
368
406
  maxLength: Math.max(0, Number(source.maxLength) || 0)
369
407
  };
370
408
  }
409
+
410
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
411
+ function isRecord(value) {
412
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
413
+ }
414
+
415
+ /**
416
+ * The shape of a declarative `next` or `validate`. Anything else was never one of those forms, and
417
+ * reads as absent the way it always has; only a list that means to be one is held to the rules.
418
+ * @param {unknown} value
419
+ * @returns {value is Record<string, unknown>[]}
420
+ */
421
+ function isRecordList(value) {
422
+ return Array.isArray(value) && value.length > 0 && value.every(isRecord);
423
+ }
424
+
425
+ /**
426
+ * @param {unknown} when @param {string} name @param {string[]} before
427
+ * @returns {NormalizedItem['when']}
428
+ */
429
+ function normalizeWhen(when, name, before) {
430
+ if (typeof when === 'function') return /** @type {NormalizedItem['when']} */ (when);
431
+ if (!isRecord(when) || Object.keys(when).length === 0) return null;
432
+ failOn(checkCondition(when, { fields: before }), name, 'when');
433
+ return structuredClone(/** @type {Condition} */ (when));
434
+ }
435
+
436
+ /**
437
+ * @param {unknown} next @param {string} name @param {string[]} fields
438
+ * @returns {NormalizedItem['next']}
439
+ */
440
+ function normalizeNext(next, name, fields) {
441
+ if (typeof next === 'function') return /** @type {NormalizedItem['next']} */ (next);
442
+ if (typeof next === 'string') return next || null;
443
+ if (!isRecordList(next)) return null;
444
+ failOn(checkNext(next, { fields }), name, 'next');
445
+ return structuredClone(/** @type {NextTarget} */ (next));
446
+ }
447
+
448
+ /**
449
+ * @param {unknown} validate @param {string} name
450
+ * @returns {NormalizedItem['validate']}
451
+ */
452
+ function normalizeValidate(validate, name) {
453
+ if (typeof validate === 'function') return /** @type {NormalizedItem['validate']} */ (validate);
454
+ if (!isRecordList(validate)) return null;
455
+ failOn(checkRuleList(validate), name, 'validate');
456
+ return structuredClone(/** @type {ValidationRule[]} */ (validate));
457
+ }
458
+
459
+ /**
460
+ * @param {import('./conditions.js').ConditionProblem[]} problems @param {string} name @param {string} key
461
+ * @returns {void}
462
+ */
463
+ function failOn(problems, name, key) {
464
+ if (problems.length === 0) return;
465
+ const [first] = problems;
466
+ throw new TypeError(`Item "${name}" ${key}${first.path}: ${first.message}`);
467
+ }
468
+
469
+ /**
470
+ * @param {NormalizedItem[]} items @param {NormalizedItem} item @param {Record<string, unknown>} raw
471
+ * @returns {boolean} Whether the item currently leads to `$review` or `$submit`.
472
+ */
473
+ function endsHere(items, item, raw) {
474
+ try {
475
+ return endsFlow(items, resolveNext(items, item, raw));
476
+ } catch {
477
+ return false;
478
+ }
479
+ }
@@ -7,10 +7,44 @@ import { button } from '../button/button.js';
7
7
  import { Field } from '../field/field.js';
8
8
  import { kbd } from '../kbd/kbd.js';
9
9
  import { ProgressBar } from '../loading/progress-bar.js';
10
+ import { NEXT_REVIEW, checkRules, ruleMessage } from './conditions.js';
10
11
  import {
11
- applyExclusive, isEmptyAnswer, normalizeItems, progressOf, resolveFlow, resolveNext, validateAnswer
12
+ applyExclusive, endsFlow, isEmptyAnswer, normalizeItemList, progressOf, resolveFlow, resolveNext, validateAnswer
12
13
  } from './items.js';
13
14
 
15
+ /**
16
+ * The message key of each declarative rule's default text, as `checkRules()` names the rule.
17
+ * `required` is absent: an item words it itself (`questionnaire.required`,
18
+ * `questionnaire.requiredInput`).
19
+ */
20
+ export const RULE_MESSAGE_KEYS = Object.freeze({
21
+ minLength: 'questionnaire.rule.minLength',
22
+ maxLength: 'questionnaire.rule.maxLength',
23
+ minItems: 'questionnaire.rule.minItems',
24
+ maxItems: 'questionnaire.rule.maxItems',
25
+ minimum: 'questionnaire.rule.minimum',
26
+ maximum: 'questionnaire.rule.maximum',
27
+ oneOf: 'questionnaire.rule.oneOf',
28
+ date: 'questionnaire.rule.date',
29
+ 'date-time': 'questionnaire.rule.dateTime',
30
+ time: 'questionnaire.rule.time',
31
+ email: 'questionnaire.rule.email',
32
+ uri: 'questionnaire.rule.uri'
33
+ });
34
+
35
+ /**
36
+ * A rule's default message through a component's `msg()`: its catalogue key when it has one, the
37
+ * English of `ruleMessage()` otherwise.
38
+ * @param {(key: string, ...args: unknown[]) => string} msg The component's message lookup.
39
+ * @param {string} key The rule key `checkRules()` reports.
40
+ * @param {...unknown} args Its interpolation values.
41
+ * @returns {string}
42
+ */
43
+ export function ruleText(msg, key, ...args) {
44
+ const catalogueKey = /** @type {Record<string, string>} */ (RULE_MESSAGE_KEYS)[key];
45
+ return catalogueKey ? msg(catalogueKey, ...args) : ruleMessage(key, ...args);
46
+ }
47
+
14
48
  /** @typedef {import('./items.js').QuestionnaireItem} QuestionnaireItem */
15
49
  /** @typedef {import('./items.js').QuestionnaireChoice} QuestionnaireChoice */
16
50
  /** @typedef {import('./items.js').NormalizedItem} NormalizedItem */
@@ -83,14 +117,18 @@ function keyHint(key) {
83
117
  * persistence and transport.
84
118
  *
85
119
  * Three things separate it from a `Form` with one `Fieldset` per question. It **branches**: an item
86
- * carries a `when` predicate and a `next` target, conditions cascade, and Back retraces the path
120
+ * carries a `when` condition and a `next` target, conditions cascade, and Back retraces the path
87
121
  * actually walked rather than an array index. Its answer control is **any registered Zx `Field`
88
122
  * type**, so a question can ask for a date, a number, a rating or an upload instead of a choice.
89
123
  * And its `validate` may be asynchronous, which is what lets a question be gated on a server check.
90
124
  *
91
- * The root is a real `<form>` and choices are native radios and checkboxes carrying the item name,
92
- * so `new FormData(questionnaire.toElement())` reads the answers, arrow-key navigation inside a
93
- * choice group is the browser's rather than ours, and nothing depends on JavaScript for semantics.
125
+ * `when`, `next` and `validate` each take a function or the same logic written as plain JSON (see
126
+ * `conditions.js`), so a whole questionnaire can be stored, sent, or composed by an agent.
127
+ *
128
+ * A created root is a real `<form>`; an enhanced non-form target contains one. Choices are native
129
+ * radios and checkboxes carrying the item name,
130
+ * and arrow-key navigation inside a choice group is the browser's. Form data includes every
131
+ * applicable answer, including answers from earlier steps.
94
132
  *
95
133
  * @fires Questionnaire#change
96
134
  * @fires Questionnaire#navigate
@@ -152,6 +190,7 @@ export class Questionnaire extends Component {
152
190
  this._status = 'asking';
153
191
  this._returnToReview = false;
154
192
  this._busy = false;
193
+ this._revision = 0;
155
194
  this._error = '';
156
195
  this._advanceTimer = 0;
157
196
  this._uid = uid('zx-questionnaire');
@@ -187,12 +226,20 @@ export class Questionnaire extends Component {
187
226
  this._form.replaceChildren(this._progressHost, this._itemHost, this._reviewHost, this._actionsHost);
188
227
  if (this._form !== root) root.replaceChildren(this._form);
189
228
 
229
+ this.listen(this._form, 'formdata', (event) => {
230
+ const data = /** @type {FormDataEvent} */ (event).formData;
231
+ for (const name of new Set([...data.keys()])) data.delete(name);
232
+ for (const [name, value] of this.toFormData()) data.append(name, value);
233
+ });
190
234
  this.listen(this._form, 'submit', (event) => {
191
235
  event.preventDefault();
192
236
  void this.next();
193
237
  });
194
238
  this.listen(this._itemHost, 'change', (event) => this._onControlChange(event));
195
- this.listen(this._itemHost, 'input', (event) => this._onFreeformInput(event));
239
+ this.listen(this._itemHost, 'input', (event) => {
240
+ this._revision += 1;
241
+ this._onFreeformInput(event);
242
+ });
196
243
  this.listen(this._actionsHost, 'click', (event) => this._onActionClick(event));
197
244
  this.listen(this._reviewHost, 'click', (event) => this._onReviewClick(event));
198
245
  this.listen(root, 'keydown', (event) => this._onKeydown(/** @type {KeyboardEvent} */ (event)));
@@ -220,19 +267,27 @@ export class Questionnaire extends Component {
220
267
  */
221
268
  setItems(list) {
222
269
  const previous = this.getActive();
223
- const items = normalizeItems(list);
270
+ const items = normalizeItemList(list, (key) => this.msg(key));
224
271
  const names = new Set(items.map((item) => item.name));
272
+ const oldItems = this._items;
273
+ const savedFields = new Map();
274
+ for (const [name, field] of this._fields) {
275
+ if (oldItems.find((item) => item.name === name)?.field && items.find((item) => item.name === name)?.field) {
276
+ savedFields.set(name, field.getValue());
277
+ }
278
+ field.destroy();
279
+ }
280
+ this._fields.clear();
225
281
  this._items = items;
282
+ this._revision += 1;
283
+ for (const [name, value] of savedFields) {
284
+ const item = items.find((candidate) => candidate.name === name);
285
+ if (item) this._field(item).setValue(value, { silent: true });
286
+ }
226
287
 
227
288
  for (const map of [this._selected, this._freeform]) {
228
289
  for (const name of [...map.keys()]) if (!names.has(name)) map.delete(name);
229
290
  }
230
- for (const [name, field] of [...this._fields]) {
231
- if (names.has(name)) continue;
232
- field.destroy();
233
- this._fields.delete(name);
234
- }
235
-
236
291
  const visible = resolveFlow(items, this._rawAnswers()).visible;
237
292
  const kept = this._path.filter((name) => visible.some((item) => item.name === name));
238
293
  if (previous && kept[kept.length - 1] === previous) this._path = kept;
@@ -287,8 +342,9 @@ export class Questionnaire extends Component {
287
342
  async next() {
288
343
  if (this._busy || this._status === 'complete') return false;
289
344
  if (this._status === 'review') return this.submit();
345
+ const revision = this._revision;
290
346
  if (!await this._validateActive()) return false;
291
- if (this._destroyed) return false;
347
+ if (this._destroyed || revision !== this._revision) return false;
292
348
 
293
349
  if (this._returnToReview) {
294
350
  this._returnToReview = false;
@@ -296,9 +352,8 @@ export class Questionnaire extends Component {
296
352
  }
297
353
  const item = this._activeItem();
298
354
  const target = item ? resolveNext(this._items, item, this._rawAnswers()) : null;
299
- if (target) return this._navigate(target, 'next');
300
- if (this.options.review) return this._enterReview();
301
- return this.submit();
355
+ if (this._destroyed || revision !== this._revision) return false;
356
+ return this._leave(target, 'next');
302
357
  }
303
358
 
304
359
  /**
@@ -314,6 +369,7 @@ export class Questionnaire extends Component {
314
369
  if (!last) return false;
315
370
  const event = this.emit('navigate', { from: null, to: last, reason: 'previous' });
316
371
  if (event.defaultPrevented) return false;
372
+ this._revision += 1;
317
373
  this._status = 'asking';
318
374
  // The last question leads back into review on its own, so nothing needs to be remembered.
319
375
  this._returnToReview = false;
@@ -327,6 +383,7 @@ export class Questionnaire extends Component {
327
383
  const to = this._path[this._path.length - 2];
328
384
  const event = this.emit('navigate', { from, to, reason: 'previous' });
329
385
  if (event.defaultPrevented) return false;
386
+ this._revision += 1;
330
387
  this._path.pop();
331
388
  this._returnToReview = false;
332
389
  this._error = '';
@@ -346,15 +403,16 @@ export class Questionnaire extends Component {
346
403
  const item = this._activeItem();
347
404
  if (!item || !item.skippable || this._busy) return false;
348
405
  this.setAnswer(item.name, null, { silent: true });
406
+ const revision = this._revision;
349
407
  this.emit('skip', { name: item.name });
408
+ if (this._destroyed || revision !== this._revision || this._activeItem() !== item) return false;
350
409
  if (this._returnToReview) {
351
410
  this._returnToReview = false;
352
411
  return this._enterReview();
353
412
  }
354
413
  const target = resolveNext(this._items, item, this._rawAnswers());
355
- if (target) return this._navigate(target, 'skip');
356
- if (this.options.review) return this._enterReview();
357
- return this.submit();
414
+ if (this._destroyed || revision !== this._revision || this._activeItem() !== item) return false;
415
+ return this._leave(target, 'skip');
358
416
  }
359
417
 
360
418
  /**
@@ -365,11 +423,18 @@ export class Questionnaire extends Component {
365
423
  */
366
424
  async submit() {
367
425
  if (this._busy || this._status === 'complete') return false;
426
+ const revision = this._revision;
368
427
  if (this._status !== 'review' && !await this._validateActive()) return false;
369
- if (this._destroyed) return false;
428
+ if (this._destroyed || revision !== this._revision) return false;
429
+
430
+ return this._finishSubmit();
431
+ }
370
432
 
433
+ /** @returns {boolean} */
434
+ _finishSubmit() {
435
+ const revision = this._revision;
371
436
  const detail = { answers: this.getAnswers(), path: this.getPath() };
372
- if (this.emit('submit', detail).defaultPrevented) return false;
437
+ if (this.emit('submit', detail).defaultPrevented || this._destroyed || revision !== this._revision) return false;
373
438
  this._status = 'complete';
374
439
  this._paint();
375
440
  this.emit('complete', { answers: detail.answers, path: detail.path });
@@ -430,6 +495,7 @@ export class Questionnaire extends Component {
430
495
  setAnswer(name, value, { silent = false } = {}) {
431
496
  const item = this._items.find((candidate) => candidate.name === name);
432
497
  if (!item) throw new RangeError(`Unknown questionnaire item: ${name}`);
498
+ this._revision += 1;
433
499
 
434
500
  if (item.field) {
435
501
  this._field(item).setValue(value === undefined ? null : value, { silent: true });
@@ -507,6 +573,7 @@ export class Questionnaire extends Component {
507
573
  * @returns {this}
508
574
  */
509
575
  reset() {
576
+ this._revision += 1;
510
577
  this._selected.clear();
511
578
  this._freeform.clear();
512
579
  for (const [name, field] of this._fields) {
@@ -595,6 +662,7 @@ export class Questionnaire extends Component {
595
662
  // The legend already asks the question; repeating it above the control would say it twice.
596
663
  if (options.label == null) field.el.setAttribute('data-hide-label', '');
597
664
  field.on('change', () => {
665
+ this._revision += 1;
598
666
  this._error = '';
599
667
  this._paintError(item);
600
668
  this._emitChange(item);
@@ -609,8 +677,11 @@ export class Questionnaire extends Component {
609
677
  _navigate(name, reason) {
610
678
  const from = this.getActive();
611
679
  if (from === name && this._status === 'asking') return false;
612
- if (this.emit('navigate', { from, to: name, reason }).defaultPrevented) return false;
680
+ const revision = this._revision;
681
+ if (this.emit('navigate', { from, to: name, reason }).defaultPrevented
682
+ || this._destroyed || revision !== this._revision) return false;
613
683
 
684
+ this._revision += 1;
614
685
  const index = this._path.indexOf(name);
615
686
  if (index >= 0) this._path = this._path.slice(0, index + 1);
616
687
  else this._path.push(name);
@@ -621,11 +692,25 @@ export class Questionnaire extends Component {
621
692
  return true;
622
693
  }
623
694
 
695
+ /**
696
+ * Follows a resolved branch target: an item, the review screen, or submission.
697
+ * @param {string|null} target @param {'next'|'skip'} reason @returns {Promise<boolean>|boolean}
698
+ */
699
+ _leave(target, reason) {
700
+ if (endsFlow(this._items, target)) return target === NEXT_REVIEW ? this._enterReview() : this._finishSubmit();
701
+ if (target) return this._navigate(target, reason);
702
+ if (this.options.review) return this._enterReview();
703
+ return this._finishSubmit();
704
+ }
705
+
624
706
  /** @returns {boolean} */
625
707
  _enterReview() {
626
- if (this.emit('navigate', { from: this.getActive(), to: null, reason: 'review' }).defaultPrevented) {
708
+ const revision = this._revision;
709
+ if (this.emit('navigate', { from: this.getActive(), to: null, reason: 'review' }).defaultPrevented
710
+ || this._destroyed || revision !== this._revision) {
627
711
  return false;
628
712
  }
713
+ this._revision += 1;
629
714
  this._status = 'review';
630
715
  this._error = '';
631
716
  this._paint();
@@ -637,10 +722,18 @@ export class Questionnaire extends Component {
637
722
  async _validateActive() {
638
723
  const item = this._activeItem();
639
724
  if (!item) return true;
725
+ const revision = this._revision;
640
726
  const answer = this._answerOf(item);
641
727
  let message = validateAnswer(item, answer, (key) => this.msg(key));
642
728
 
643
- if (!message && typeof item.validate === 'function') {
729
+ if (!message && Array.isArray(item.validate)) {
730
+ // The required rule says what an empty item already says; the others read their English.
731
+ message = checkRules(item.validate, answer, (key, ...args) => (key === 'required'
732
+ ? this.msg(item.choices.length > 0 ? 'questionnaire.required' : 'questionnaire.requiredInput')
733
+ : ruleText((ruleKey, ...values) => ruleKey === 'questionnaire.rule.minLength'
734
+ ? this.msgPlural(ruleKey, Number(values[0]), ...values)
735
+ : this.msg(ruleKey, ...values), key, ...args)));
736
+ } else if (!message && typeof item.validate === 'function') {
644
737
  this._setBusy(true);
645
738
  try {
646
739
  message = await item.validate(answer, this.getAnswers());
@@ -650,7 +743,7 @@ export class Questionnaire extends Component {
650
743
  if (!this._destroyed) this._setBusy(false);
651
744
  }
652
745
  }
653
- if (this._destroyed) return false;
746
+ if (this._destroyed || revision !== this._revision || this._activeItem() !== item) return false;
654
747
 
655
748
  this._error = message ? String(message) : '';
656
749
  this._paintError(item);
@@ -834,13 +927,14 @@ export class Questionnaire extends Component {
834
927
  const review = this._status === 'review';
835
928
  const complete = this._status === 'complete';
836
929
  // `next()` lets a bad branch target throw; painting must not, or one typo blanks the UI.
837
- let hasNext = false;
930
+ let target = null;
838
931
  try {
839
- hasNext = Boolean(item) && resolveNext(this._items, /** @type {NormalizedItem} */ (item),
840
- this._rawAnswers()) !== null;
932
+ target = item ? resolveNext(this._items, /** @type {NormalizedItem} */ (item), this._rawAnswers()) : null;
841
933
  } catch {
842
- hasNext = false;
934
+ target = null;
843
935
  }
936
+ const ending = endsFlow(this._items, target) ? (target === NEXT_REVIEW ? 'review' : 'submit')
937
+ : target === null ? (this.options.review ? 'review' : 'submit') : null;
844
938
 
845
939
  this._back.hidden = complete || (!review && (!this.options.allowBack || this._path.length <= 1));
846
940
  this._back.disabled = this._busy;
@@ -849,8 +943,7 @@ export class Questionnaire extends Component {
849
943
  this._forward.hidden = complete;
850
944
  this._forward.disabled = this._busy || (!item && !review);
851
945
 
852
- const role = review ? 'submit' : this._returnToReview || (!hasNext && this.options.review) ? 'review'
853
- : hasNext ? 'next' : 'submit';
946
+ const role = review ? 'submit' : this._returnToReview ? 'review' : ending ?? 'next';
854
947
  if (this._forward.dataset.role !== role) {
855
948
  this._forward.dataset.role = role;
856
949
  const glyph = role === 'next' ? 'chevron-right' : role === 'review' ? 'list' : 'check';
@@ -879,6 +972,7 @@ export class Questionnaire extends Component {
879
972
  if (!item) return;
880
973
  const choice = item.choices[Number(control.dataset.index)];
881
974
  if (!choice) return;
975
+ this._revision += 1;
882
976
 
883
977
  if (item.multiple) {
884
978
  const checked = [...this._itemHost.querySelectorAll('.zx-questionnaire__control')]