@fieldia/viewer 0.10.0 → 0.11.0

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 (70) hide show
  1. package/README.md +126 -1
  2. package/bundle/fieldia.ar.js +2 -2
  3. package/bundle/fieldia.ar.js.map +2 -2
  4. package/bundle/fieldia.de.js +2 -2
  5. package/bundle/fieldia.de.js.map +2 -2
  6. package/bundle/fieldia.fr.js +2 -2
  7. package/bundle/fieldia.fr.js.map +2 -2
  8. package/bundle/fieldia.js +4 -4
  9. package/bundle/fieldia.js.map +4 -4
  10. package/package.json +3 -3
  11. package/src/lib/dialog.d.mts +29 -2
  12. package/src/lib/dialog.d.ts +29 -2
  13. package/src/lib/dialog.js +94 -27
  14. package/src/lib/dialog.js.map +1 -1
  15. package/src/lib/dialog.mjs +92 -27
  16. package/src/lib/dialog.mjs.map +1 -1
  17. package/src/lib/labels.d.mts +14 -0
  18. package/src/lib/labels.d.ts +14 -0
  19. package/src/lib/labels.js +6 -0
  20. package/src/lib/labels.js.map +1 -1
  21. package/src/lib/labels.mjs +6 -0
  22. package/src/lib/labels.mjs.map +1 -1
  23. package/src/lib/list.d.mts +3 -2
  24. package/src/lib/list.d.ts +3 -2
  25. package/src/lib/list.js +5 -5
  26. package/src/lib/list.js.map +1 -1
  27. package/src/lib/list.mjs +5 -5
  28. package/src/lib/list.mjs.map +1 -1
  29. package/src/lib/locales/ar.js +6 -0
  30. package/src/lib/locales/ar.js.map +1 -1
  31. package/src/lib/locales/ar.mjs +6 -0
  32. package/src/lib/locales/ar.mjs.map +1 -1
  33. package/src/lib/locales/de.js +6 -0
  34. package/src/lib/locales/de.js.map +1 -1
  35. package/src/lib/locales/de.mjs +6 -0
  36. package/src/lib/locales/de.mjs.map +1 -1
  37. package/src/lib/locales/fr.js +6 -0
  38. package/src/lib/locales/fr.js.map +1 -1
  39. package/src/lib/locales/fr.mjs +6 -0
  40. package/src/lib/locales/fr.mjs.map +1 -1
  41. package/src/lib/look.d.mts +7 -3
  42. package/src/lib/look.d.ts +7 -3
  43. package/src/lib/look.js +72 -15
  44. package/src/lib/look.js.map +1 -1
  45. package/src/lib/look.mjs +72 -15
  46. package/src/lib/look.mjs.map +1 -1
  47. package/src/lib/open.d.mts +24 -0
  48. package/src/lib/open.d.ts +24 -0
  49. package/src/lib/open.js +81 -0
  50. package/src/lib/open.js.map +1 -0
  51. package/src/lib/open.mjs +78 -0
  52. package/src/lib/open.mjs.map +1 -0
  53. package/src/lib/related.d.mts +19 -0
  54. package/src/lib/related.d.ts +19 -0
  55. package/src/lib/related.js +15 -2
  56. package/src/lib/related.js.map +1 -1
  57. package/src/lib/related.mjs +14 -2
  58. package/src/lib/related.mjs.map +1 -1
  59. package/src/lib/say.d.mts +9 -0
  60. package/src/lib/say.d.ts +9 -0
  61. package/src/lib/say.js +45 -0
  62. package/src/lib/say.js.map +1 -0
  63. package/src/lib/say.mjs +42 -0
  64. package/src/lib/say.mjs.map +1 -0
  65. package/src/lib/viewer.d.mts +33 -5
  66. package/src/lib/viewer.d.ts +33 -5
  67. package/src/lib/viewer.js +464 -279
  68. package/src/lib/viewer.js.map +1 -1
  69. package/src/lib/viewer.mjs +465 -280
  70. package/src/lib/viewer.mjs.map +1 -1
package/src/lib/viewer.js CHANGED
@@ -9,6 +9,8 @@ const list_1 = require("./list");
9
9
  const look_1 = require("./look");
10
10
  const place_1 = require("./place");
11
11
  const dom_1 = require("./dom");
12
+ const open_1 = require("./open");
13
+ const say_1 = require("./say");
12
14
  const labels_1 = require("./labels");
13
15
  const focus_trap_1 = require("./focus-trap");
14
16
  var labels_2 = require("./labels");
@@ -31,18 +33,40 @@ function mountViewer(host, options) {
31
33
  const tag = options.locale ?? checked.page.language;
32
34
  const localized = tag ? (0, core_1.localizePage)(checked.page, tag) : checked.page;
33
35
  const page = options.translate ? (0, core_1.translatePage)(localized, options.translate) : localized;
36
+ /** Another page as this one is shown: in its language, through the app's translator. */
37
+ const shownAs = (other) => {
38
+ const own = tag ? (0, core_1.localizePage)(other, tag) : other;
39
+ return options.translate ? (0, core_1.translatePage)(own, options.translate) : own;
40
+ };
34
41
  const locale = (0, labels_1.ownLocale)(tag);
35
42
  const preferences = options.preferences ?? (0, widgets_1.browserPreferences)();
36
43
  const dialogs = (0, related_1.pageDialogs)(options);
37
44
  const ownsForm = !options.form;
38
- const form = options.form ?? (0, core_1.createForm)({ ...options, page, messages: options.messages ?? core_1.MESSAGES[locale] });
39
45
  const labels = { ...labels_1.VIEWER_LABELS[locale], ...options.labels };
46
+ /**
47
+ * What the page's steps ask of the screen: a page opened, words said, a
48
+ * question asked, a tab shown — the viewer's own, under the app's. A form
49
+ * made elsewhere (`form`) keeps the host it was made with.
50
+ */
51
+ const actionHost = {
52
+ open: (request) => (0, open_1.openPage)({ options, place: host, root, title: (other) => shownAs(other).title || other.id, back: labels.back, missing: (id) => fill(labels.pageMissing, { page: id }) }, request),
53
+ say: (message, tone) => say(message, tone),
54
+ ask: (message) => confirm(message),
55
+ show: (target) => {
56
+ const show = tabs.get(target);
57
+ if (!show?.())
58
+ throw new Error(`No tab "${target}" can be shown here`);
59
+ },
60
+ ...options.host,
61
+ };
62
+ const form = options.form ?? (0, core_1.createForm)({ ...options, page, host: actionHost, messages: options.messages ?? core_1.MESSAGES[locale] });
40
63
  const widgetLabels = widgets_1.WIDGET_LABELS[locale];
41
64
  const dir = options.dir ?? (tag && (0, core_1.isRightToLeft)(tag) ? 'rtl' : undefined);
42
65
  const prefix = `fd${++mounts}`;
43
66
  const updaters = [];
44
67
  const cleanups = [];
45
- const uid = (id) => `${prefix}-${id.replace(/[^A-Za-z0-9_-]/g, '_')}`;
68
+ const ownUid = (id) => `${prefix}-${id.replace(/[^A-Za-z0-9_-]/g, '_')}`;
69
+ const uid = ownUid;
46
70
  const fill = (template, values) => template.replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? ''));
47
71
  (0, widgets_1.installStyles)(doc);
48
72
  function el(tag, attrs = {}, ...children) {
@@ -66,287 +90,421 @@ function mountViewer(host, options) {
66
90
  const root = el('form', { class: 'fd-form', novalidate: '', 'data-fd-skin': options.skin ?? 'underline', dir, lang: tag, 'data-max-width': page.maxWidth });
67
91
  (0, look_1.applyLook)(root, page.look);
68
92
  const confirm = options.confirm ?? dialogConfirm;
69
- // ---- the parts -------------------------------------------------------
70
- /** A field with its label, help and messages. `labels` is where labels sit where it is put; the title's own fields take none. */
71
- function fieldItem(node, labels) {
72
- const def = page.fields[node.field];
73
- const id = uid(node.id);
74
- const labelsAt = (0, place_1.labelPlace)(node, def.type, labels);
75
- const wrapper = el('div', { class: 'fd-field', 'data-node': node.id, 'data-field': node.field, 'data-type': def.type, 'data-labels': labelsAt });
76
- if (node.colspan)
77
- wrapper.style.setProperty('--fd-span', String(node.colspan));
78
- const labelText = node.label ?? def.label;
79
- const label = el('label', { class: 'fd-label', id: `${id}-label`, for: id }, labelText);
80
- // The ✓ of a field filled in right; never on a yes/no box, a table or a file, where it would say nothing.
81
- const mark = options.showValid && !NO_VALID_MARK.has(def.type) ? (0, widgets_1.drawIcon)(doc, 'check') : null;
82
- if (mark) {
83
- mark.classList.add('fd-valid-mark');
84
- label.append(mark);
85
- }
86
- const widget = (0, widgets_1.createWidget)({ form, name: node.field, field: def, node, id, document: doc, labels: widgetLabels, preferences, locale, dialogs }, options.widgets);
87
- // A label kept out of sight still names the box; the empty box shows it instead, unless the page gives it words of its own.
88
- if (labelsAt === 'hidden' && !node.placeholder) {
89
- const box = widget.element.matches(TEXT_BOX) ? widget.element : widget.element.querySelector(TEXT_BOX);
90
- box?.setAttribute('placeholder', labelText);
91
- }
92
- if (!['INPUT', 'SELECT', 'TEXTAREA'].includes(widget.element.tagName)) {
93
- // `for` stays: a custom field that puts the id on its own input is
94
- // labelled natively. Only a wrapper with a role (a radio group, say) may
95
- // carry a name; ARIA forbids naming a plain div or span.
96
- // A group inside a box of its own (a radio group with "Clear selection" under it) is named too.
97
- const named = widget.element.getAttribute('role') ? widget.element : widget.element.querySelector(`[id="${id}"][role]`);
98
- named?.setAttribute('aria-labelledby', label.id);
99
- label.addEventListener('click', () => widget.focus());
100
- }
101
- const helpText = node.help ?? def.help;
102
- const help = helpText ? el('div', { class: 'fd-help', id: `${id}-help` }, helpText) : null;
103
- // Not an alert of its own: a refused save is announced once, naming every field to look at.
104
- const error = el('div', { class: 'fd-error', id: `${id}-error`, hidden: '' });
105
- // A warning from an answer rule, and one from the data source's onchange beside the field whose change brought it.
106
- const warning = el('div', { class: 'fd-warning', id: `${id}-warning`, role: 'status', hidden: '' });
107
- wrapper.append(...(labelsAt === 'after' ? [widget.element, label] : [label, widget.element]), ...(help ? [help] : []), error, warning);
108
- if (widget.destroy)
109
- cleanups.push(() => widget.destroy?.());
110
- // An answer rule's warning waits until the person leaves the field: no advice
111
- // mid-word. One already shown stays while they put it right, and goes once they have.
112
- let typing = false;
113
- let advice = '';
114
- wrapper.addEventListener('focusin', () => (typing = true));
115
- wrapper.addEventListener('focusout', (event) => {
116
- if (wrapper.contains(event.relatedTarget))
117
- return;
118
- typing = false;
119
- // Not at once: focus also leaves when a redraw removes the focused part
120
- // (a deleted line's button), and that redraw must finish first.
121
- queueMicrotask(() => update(form.getState()));
122
- });
123
- const update = (state) => {
124
- const shown = form.node(node.id);
125
- (0, dom_1.setHidden)(wrapper, shown.invisible);
126
- wrapper.classList.toggle('fd-required', shown.required);
127
- const message = state.errors[node.field];
128
- (0, dom_1.setHidden)(error, !message);
129
- (0, dom_1.setText)(error, message ?? '');
130
- const now = state.warnings[node.field] ?? '';
131
- if (!typing || !now)
132
- advice = now;
133
- // An error shown says enough: the rule's warning gives way to it.
134
- const warned = [message ? '' : advice, state.warning && state.warningField === node.field ? state.warning : ''].filter(Boolean).join(' ');
135
- (0, dom_1.setHidden)(warning, !warned);
136
- (0, dom_1.setText)(warning, warned);
137
- if (mark) {
138
- const value = state.values[node.field];
139
- const filled = value !== null && value !== undefined && value !== '' && !(Array.isArray(value) && !value.length);
140
- const valid = !shown.readonly && !message && filled && state.dirty.includes(node.field) && form.problem(node.field) === null;
141
- wrapper.classList.toggle('fd-valid', valid);
142
- mark.toggleAttribute('hidden', !valid);
93
+ const say = (0, say_1.sayer)(root, el, labels.dismiss);
94
+ /** The tabs a step can show, by id: each shows its tab, false when it is hidden. */
95
+ const tabs = new Map();
96
+ /**
97
+ * A press runs its steps one run at a time: the button busy meanwhile, and
98
+ * not pressed again. A check or a save that stops it takes the focus to the
99
+ * first problem, and says which fields, as Save does.
100
+ */
101
+ async function press(button, run) {
102
+ if (button.hasAttribute('aria-busy'))
103
+ return;
104
+ button.setAttribute('aria-busy', 'true');
105
+ button.setAttribute('aria-disabled', 'true');
106
+ try {
107
+ const { reason } = await run();
108
+ if (reason === 'check' || reason === 'save') {
109
+ if (!form.getState().saveProblem)
110
+ announce(checkText(form.getState()));
111
+ focusFirstProblem();
143
112
  }
144
- widget.update({
145
- value: state.values[node.field],
146
- values: state.values,
147
- readonly: shown.readonly || locked,
148
- required: shown.required,
149
- invalid: !!message,
150
- describedBy: [help?.id, message ? error.id : undefined, warned ? warning.id : undefined].filter(Boolean).join(' ') || undefined,
151
- });
152
- };
153
- updaters.push(update);
154
- return wrapper;
155
- }
156
- function hideWhen(element, id) {
157
- updaters.push(() => (0, dom_1.setHidden)(element, form.node(id).invisible));
158
- }
159
- function buttonItem(node) {
160
- const button = el('button', { type: 'button', class: `fd-button fd-button-${node.style ?? 'secondary'}`, 'data-node': node.id }, ...withIcon(node.icon, node.label));
161
- spans(button, node.colspan);
162
- button.addEventListener('click', async () => {
163
- if (node.confirm && !(await confirm(node.confirm)))
164
- return;
165
- await form.runAction(node.id);
166
- });
167
- hideWhen(button, node.id);
168
- return button;
169
- }
170
- function textItem(node) {
171
- const style = node.style ?? 'paragraph';
172
- const element = el(style === 'heading' ? 'h3' : 'p', { class: `fd-text-${style}`, 'data-node': node.id }, node.text);
173
- spans(element, node.colspan);
174
- hideWhen(element, node.id);
175
- return element;
176
- }
177
- function slotItem(node) {
178
- const element = el('div', { class: 'fd-slot', 'data-slot': node.name, 'data-node': node.id });
179
- const cleanup = options.slots?.[node.name]?.(element, { form, name: node.name });
180
- if (cleanup)
181
- cleanups.push(cleanup);
182
- hideWhen(element, node.id);
183
- return element;
113
+ }
114
+ finally {
115
+ button.removeAttribute('aria-busy');
116
+ button.removeAttribute('aria-disabled');
117
+ }
184
118
  }
119
+ // ---- the parts -------------------------------------------------------
120
+ /** Folded sections, and how to open each: a problem inside one has to be seen. */
121
+ const folds = new Map();
122
+ /** Every part drawn again from the state of the page shown. */
123
+ const renderNow = () => render(form.getState());
124
+ /** Set once the viewer is on the page; set again when it is taken away. */
125
+ let mounted = false;
126
+ let gone = false;
185
127
  /** The columns a part spans in the grid it sits in; the stylesheet keeps it within the columns there at each width. */
186
128
  function spans(element, colspan) {
187
129
  if (colspan)
188
130
  element.style.setProperty('--fd-span', String(colspan));
189
131
  }
132
+ /** Where the parts of a page, a tab or a step sit: one column, the page's labels. */
133
+ const top = (onPage) => ({ columns: 1, onPage, labels: page.look?.labels });
190
134
  /**
191
- * A grid of parts. With `columns` null, it has none of its own: it lays its
192
- * parts on the columns of the grid round it (an arrangement on its tracks).
135
+ * The parts of one page, drawn with its own form: the page shown, or a saved
136
+ * form placed in it. Inside, `form` and `page` are the scope's.
193
137
  */
194
- function grid(children, columns, place) {
195
- const box = el('div', { class: 'fd-grid' });
196
- if (columns !== null) {
197
- box.style.setProperty('--fd-columns', String((0, core_1.wideColumns)(columns)));
198
- // Counts given for the narrower widths replace the skin's own stacking there.
199
- if (typeof columns === 'object') {
200
- for (const width of ['medium', 'narrow']) {
201
- const count = columns[width];
202
- if (count === undefined)
203
- continue;
204
- box.setAttribute(`data-columns-${width}`, String(count));
205
- box.style.setProperty(`--fd-columns-${width}`, String(count));
138
+ function drawer(scope) {
139
+ const { form, page } = scope;
140
+ const uid = (id) => ownUid(scope.prefix + id);
141
+ /** A part's updater, handed the state of the part's own form. */
142
+ const watch = (update) => updaters.push(scope.root ? update : () => update(form.getState()));
143
+ /** A field with its label, help and messages. `labels` is where labels sit where it is put; the title's own fields take none. */
144
+ function fieldItem(node, labels) {
145
+ const def = page.fields[node.field];
146
+ const id = uid(node.id);
147
+ const labelsAt = (0, place_1.labelPlace)(node, def.type, labels);
148
+ const wrapper = el('div', { class: 'fd-field', 'data-node': node.id, 'data-field': node.field, 'data-path': scope.path + node.field, 'data-type': def.type, 'data-labels': labelsAt });
149
+ if (node.colspan)
150
+ wrapper.style.setProperty('--fd-span', String(node.colspan));
151
+ const labelText = node.label ?? def.label;
152
+ const label = el('label', { class: 'fd-label', id: `${id}-label`, for: id }, labelText);
153
+ // The ✓ of a field filled in right; never on a yes/no box, a table or a file, where it would say nothing.
154
+ const mark = options.showValid && !NO_VALID_MARK.has(def.type) ? (0, widgets_1.drawIcon)(doc, 'check') : null;
155
+ if (mark) {
156
+ mark.classList.add('fd-valid-mark');
157
+ label.append(mark);
158
+ }
159
+ const widget = (0, widgets_1.createWidget)({ form, name: node.field, field: def, node, id, document: doc, labels: widgetLabels, preferences, locale, dialogs }, options.widgets);
160
+ // A label kept out of sight still names the box; the empty box shows it instead, unless the page gives it words of its own.
161
+ if (labelsAt === 'hidden' && !node.placeholder) {
162
+ const box = widget.element.matches(TEXT_BOX) ? widget.element : widget.element.querySelector(TEXT_BOX);
163
+ box?.setAttribute('placeholder', labelText);
164
+ }
165
+ if (!['INPUT', 'SELECT', 'TEXTAREA'].includes(widget.element.tagName)) {
166
+ // `for` stays: a custom field that puts the id on its own input is
167
+ // labelled natively. Only a wrapper with a role (a radio group, say) may
168
+ // carry a name; ARIA forbids naming a plain div or span.
169
+ // A group inside a box of its own (a radio group with "Clear selection" under it) is named too.
170
+ const named = widget.element.getAttribute('role') ? widget.element : widget.element.querySelector(`[id="${id}"][role]`);
171
+ named?.setAttribute('aria-labelledby', label.id);
172
+ label.addEventListener('click', () => widget.focus());
173
+ }
174
+ const helpText = node.help ?? def.help;
175
+ const help = helpText ? el('div', { class: 'fd-help', id: `${id}-help` }, helpText) : null;
176
+ // Not an alert of its own: a refused save is announced once, naming every field to look at.
177
+ const error = el('div', { class: 'fd-error', id: `${id}-error`, hidden: '' });
178
+ // A warning from an answer rule, and one from the data source's onchange beside the field whose change brought it.
179
+ const warning = el('div', { class: 'fd-warning', id: `${id}-warning`, role: 'status', hidden: '' });
180
+ wrapper.append(...(labelsAt === 'after' ? [widget.element, label] : [label, widget.element]), ...(help ? [help] : []), error, warning);
181
+ if (widget.destroy)
182
+ cleanups.push(() => widget.destroy?.());
183
+ // An answer rule's warning waits until the person leaves the field: no advice
184
+ // mid-word. One already shown stays while they put it right, and goes once they have.
185
+ let typing = false;
186
+ let advice = '';
187
+ wrapper.addEventListener('focusin', () => (typing = true));
188
+ wrapper.addEventListener('focusout', (event) => {
189
+ if (wrapper.contains(event.relatedTarget))
190
+ return;
191
+ typing = false;
192
+ // Not at once: focus also leaves when a redraw removes the focused part
193
+ // (a deleted line's button), and that redraw must finish first.
194
+ queueMicrotask(() => update(form.getState()));
195
+ });
196
+ const update = (state) => {
197
+ const shown = form.node(node.id);
198
+ (0, dom_1.setHidden)(wrapper, shown.invisible);
199
+ wrapper.classList.toggle('fd-required', shown.required);
200
+ const message = state.errors[node.field];
201
+ (0, dom_1.setHidden)(error, !message);
202
+ (0, dom_1.setText)(error, message ?? '');
203
+ const now = state.warnings[node.field] ?? '';
204
+ if (!typing || !now)
205
+ advice = now;
206
+ // An error shown says enough: the rule's warning gives way to it.
207
+ const warned = [message ? '' : advice, state.warning && state.warningField === node.field ? state.warning : ''].filter(Boolean).join(' ');
208
+ (0, dom_1.setHidden)(warning, !warned);
209
+ (0, dom_1.setText)(warning, warned);
210
+ if (mark) {
211
+ const value = state.values[node.field];
212
+ const filled = value !== null && value !== undefined && value !== '' && !(Array.isArray(value) && !value.length);
213
+ const valid = !shown.readonly && !message && filled && state.dirty.includes(node.field) && form.problem(node.field) === null;
214
+ wrapper.classList.toggle('fd-valid', valid);
215
+ mark.toggleAttribute('hidden', !valid);
216
+ }
217
+ widget.update({
218
+ value: state.values[node.field],
219
+ values: state.values,
220
+ readonly: shown.readonly || locked || scope.locked(),
221
+ required: shown.required,
222
+ invalid: !!message,
223
+ describedBy: [help?.id, message ? error.id : undefined, warned ? warning.id : undefined].filter(Boolean).join(' ') || undefined,
224
+ });
225
+ };
226
+ watch(update);
227
+ return wrapper;
228
+ }
229
+ function hideWhen(element, id) {
230
+ watch(() => (0, dom_1.setHidden)(element, form.node(id).invisible));
231
+ }
232
+ function buttonItem(node) {
233
+ const button = el('button', { type: 'button', class: `fd-button fd-button-${node.style ?? 'secondary'}`, 'data-node': node.id }, ...withIcon(node.icon, node.label));
234
+ spans(button, node.colspan);
235
+ // Its confirmation, then its steps: the form asks, through the viewer.
236
+ button.addEventListener('click', () => void press(button, () => form.runAction(node.id)));
237
+ hideWhen(button, node.id);
238
+ return button;
239
+ }
240
+ function textItem(node) {
241
+ const style = node.style ?? 'paragraph';
242
+ const element = el(style === 'heading' ? 'h3' : 'p', { class: `fd-text-${style}`, 'data-node': node.id }, node.text);
243
+ spans(element, node.colspan);
244
+ hideWhen(element, node.id);
245
+ return element;
246
+ }
247
+ function slotItem(node) {
248
+ const element = el('div', { class: 'fd-slot', 'data-slot': node.name, 'data-node': node.id });
249
+ const cleanup = options.slots?.[node.name]?.(element, { form, name: node.name });
250
+ if (cleanup)
251
+ cleanups.push(cleanup);
252
+ hideWhen(element, node.id);
253
+ return element;
254
+ }
255
+ /**
256
+ * A grid of parts. With `columns` null, it has none of its own: it lays its
257
+ * parts on the columns of the grid round it (an arrangement on its tracks).
258
+ */
259
+ function grid(children, columns, place) {
260
+ const box = el('div', { class: 'fd-grid' });
261
+ if (columns !== null) {
262
+ box.style.setProperty('--fd-columns', String((0, core_1.wideColumns)(columns)));
263
+ // Counts given for the narrower widths replace the skin's own stacking there.
264
+ if (typeof columns === 'object') {
265
+ for (const width of ['medium', 'narrow']) {
266
+ const count = columns[width];
267
+ if (count === undefined)
268
+ continue;
269
+ box.setAttribute(`data-columns-${width}`, String(count));
270
+ box.style.setProperty(`--fd-columns-${width}`, String(count));
271
+ }
206
272
  }
207
273
  }
274
+ box.append(...children.map((child) => item(child, place)));
275
+ return box;
208
276
  }
209
- box.append(...children.map((child) => item(child, place)));
210
- return box;
211
- }
212
- /** Where the parts of a page, a tab or a step sit: one column, the page's labels. */
213
- const top = (onPage) => ({ columns: 1, onPage, labels: page.look?.labels });
214
- /** Folded sections, and how to open each: a problem inside one has to be seen. */
215
- const folds = new Map();
216
- function sectionItem(node, place) {
217
- const plan = (0, place_1.planSection)(node, place);
218
- // An arrangement is no group to name, and a fieldset cannot lay its parts on the columns round it.
219
- const section = el(plan.arrangement ? 'div' : 'fieldset', {
220
- class: 'fd-section',
221
- 'data-node': node.id,
222
- 'data-style': plan.style,
223
- 'data-place': plan.at,
224
- 'data-on-page': plan.style === 'card' && place.onPage ? '' : undefined,
225
- });
226
- spans(section, node.colspan);
227
- if (node.labelWidth)
228
- section.style.setProperty('--fd-label-width', `${node.labelWidth}px`);
229
- const description = node.description ? el('p', { class: 'fd-section-description' }, node.description) : null;
230
- const content = grid(node.children, plan.at === 'tracks' ? null : node.columns, plan.inner);
231
- if (node.title && node.collapsible) {
232
- content.id = uid(`${node.id}-content`);
233
- const toggle = el('button', { type: 'button', class: 'fd-section-toggle', 'aria-controls': content.id }, el('span', { class: 'fd-section-chevron', 'aria-hidden': 'true' }), ...withIcon(node.icon, node.title));
234
- let open = node.collapsed !== true;
235
- const show = (next) => {
236
- open = next;
237
- toggle.setAttribute('aria-expanded', String(open));
238
- content.hidden = !open;
239
- if (description)
240
- description.hidden = !open;
241
- section.classList.toggle('fd-section-folded', !open);
277
+ function sectionItem(node, place) {
278
+ const plan = (0, place_1.planSection)(node, place);
279
+ // An arrangement is no group to name, and a fieldset cannot lay its parts on the columns round it.
280
+ const section = el(plan.arrangement ? 'div' : 'fieldset', {
281
+ class: 'fd-section',
282
+ 'data-node': node.id,
283
+ 'data-style': plan.style,
284
+ 'data-place': plan.at,
285
+ 'data-on-page': plan.style === 'card' && place.onPage ? '' : undefined,
286
+ });
287
+ spans(section, node.colspan);
288
+ if (node.labelWidth)
289
+ section.style.setProperty('--fd-label-width', `${node.labelWidth}px`);
290
+ const description = node.description ? el('p', { class: 'fd-section-description' }, node.description) : null;
291
+ const content = grid(node.children, plan.at === 'tracks' ? null : node.columns, plan.inner);
292
+ if (node.title && node.collapsible) {
293
+ content.id = uid(`${node.id}-content`);
294
+ const toggle = el('button', { type: 'button', class: 'fd-section-toggle', 'aria-controls': content.id }, el('span', { class: 'fd-section-chevron', 'aria-hidden': 'true' }), ...withIcon(node.icon, node.title));
295
+ let open = node.collapsed !== true;
296
+ const show = (next) => {
297
+ open = next;
298
+ toggle.setAttribute('aria-expanded', String(open));
299
+ content.hidden = !open;
300
+ if (description)
301
+ description.hidden = !open;
302
+ section.classList.toggle('fd-section-folded', !open);
303
+ };
304
+ toggle.addEventListener('click', () => show(!open));
305
+ folds.set(section, () => show(true));
306
+ show(open);
307
+ section.append(el('legend', { class: 'fd-section-title' }, toggle));
308
+ }
309
+ else if (node.title) {
310
+ section.append(el('legend', { class: 'fd-section-title' }, ...withIcon(node.icon, node.title)));
311
+ }
312
+ if (description)
313
+ section.append(description);
314
+ section.append(content);
315
+ hideWhen(section, node.id);
316
+ return section;
317
+ }
318
+ function tabsItem(node, place) {
319
+ const box = el('div', { class: 'fd-tabs', 'data-node': node.id });
320
+ spans(box, node.colspan);
321
+ const list = el('div', { class: 'fd-tablist', role: 'tablist' });
322
+ // The tab someone picked. Until they pick, the first visible tab is open —
323
+ // a tab hidden while the record loads must not leave its neighbour open.
324
+ let picked = null;
325
+ let active = node.children[0].id;
326
+ /** A tab shown, by a person or a step: the page's steps for it run. */
327
+ const show = (tab) => {
328
+ picked = active = tab;
329
+ renderNow();
330
+ form.shown(tab);
242
331
  };
243
- toggle.addEventListener('click', () => show(!open));
244
- folds.set(section, () => show(true));
245
- show(open);
246
- section.append(el('legend', { class: 'fd-section-title' }, toggle));
247
- }
248
- else if (node.title) {
249
- section.append(el('legend', { class: 'fd-section-title' }, ...withIcon(node.icon, node.title)));
250
- }
251
- if (description)
252
- section.append(description);
253
- section.append(content);
254
- hideWhen(section, node.id);
255
- return section;
256
- }
257
- function tabsItem(node, place) {
258
- const box = el('div', { class: 'fd-tabs', 'data-node': node.id });
259
- spans(box, node.colspan);
260
- const list = el('div', { class: 'fd-tablist', role: 'tablist' });
261
- // The tab someone picked. Until they pick, the first visible tab is open —
262
- // a tab hidden while the record loads must not leave its neighbour open.
263
- let picked = null;
264
- let active = node.children[0].id;
265
- const parts = node.children.map((tab) => {
266
- const tabId = uid(`${tab.id}-tab`);
267
- const panelId = uid(`${tab.id}-panel`);
268
- const button = el('button', { type: 'button', class: 'fd-tab', role: 'tab', id: tabId, 'aria-controls': panelId, 'data-node': tab.id }, ...withIcon(tab.icon, tab.label));
269
- // A tab's parts sit where the tabs do: on the page, or in the box round them.
270
- const panel = el('div', { class: 'fd-tabpanel', role: 'tabpanel', id: panelId, 'aria-labelledby': tabId }, grid(tab.children, 1, { columns: 1, onPage: place.onPage, labels: place.labels }));
271
- button.addEventListener('click', () => {
272
- picked = active = tab.id;
273
- render(form.getState());
332
+ const parts = node.children.map((tab) => {
333
+ const tabId = uid(`${tab.id}-tab`);
334
+ const panelId = uid(`${tab.id}-panel`);
335
+ const button = el('button', { type: 'button', class: 'fd-tab', role: 'tab', id: tabId, 'aria-controls': panelId, 'data-node': tab.id }, ...withIcon(tab.icon, tab.label));
336
+ // A tab's parts sit where the tabs do: on the page, or in the box round them.
337
+ const panel = el('div', { class: 'fd-tabpanel', role: 'tabpanel', id: panelId, 'aria-labelledby': tabId }, grid(tab.children, 1, { columns: 1, onPage: place.onPage, labels: place.labels }));
338
+ button.addEventListener('click', () => show(tab.id));
339
+ if (!tabs.has(tab.id))
340
+ tabs.set(tab.id, () => !form.node(tab.id).invisible && (show(tab.id), true));
341
+ list.append(button);
342
+ return { tab, button, panel };
274
343
  });
275
- list.append(button);
276
- return { tab, button, panel };
277
- });
278
- list.addEventListener('keydown', (event) => {
279
- const shown = parts.filter((p) => !p.button.hidden);
280
- const at = shown.findIndex((p) => p.tab.id === active);
281
- const move = { ArrowRight: 1, ArrowLeft: -1, Home: -at, End: shown.length - 1 - at }[event.key];
282
- if (move === undefined || at === -1)
283
- return;
284
- event.preventDefault();
285
- const rtl = root.getAttribute('dir') === 'rtl' && (event.key === 'ArrowRight' || event.key === 'ArrowLeft');
286
- const next = shown[(at + (rtl ? -move : move) + shown.length) % shown.length];
287
- picked = active = next.tab.id;
288
- render(form.getState());
289
- next.button.focus();
290
- });
291
- box.append(list, ...parts.map((p) => p.panel));
292
- updaters.push(() => {
293
- box.hidden = form.node(node.id).invisible;
294
- const shown = parts.filter((p) => !form.node(p.tab.id).invisible);
295
- const keep = picked !== null && shown.some((p) => p.tab.id === picked);
296
- if (keep)
297
- active = picked;
298
- else if (shown.length)
299
- active = shown[0].tab.id;
300
- for (const p of parts) {
301
- const selected = p.tab.id === active;
302
- p.button.hidden = !shown.includes(p);
303
- p.button.setAttribute('aria-selected', String(selected));
304
- p.button.tabIndex = selected ? 0 : -1;
305
- p.panel.hidden = !selected;
344
+ list.addEventListener('keydown', (event) => {
345
+ const shown = parts.filter((p) => !p.button.hidden);
346
+ const at = shown.findIndex((p) => p.tab.id === active);
347
+ const move = { ArrowRight: 1, ArrowLeft: -1, Home: -at, End: shown.length - 1 - at }[event.key];
348
+ if (move === undefined || at === -1)
349
+ return;
350
+ event.preventDefault();
351
+ const rtl = root.getAttribute('dir') === 'rtl' && (event.key === 'ArrowRight' || event.key === 'ArrowLeft');
352
+ const next = shown[(at + (rtl ? -move : move) + shown.length) % shown.length];
353
+ show(next.tab.id);
354
+ next.button.focus();
355
+ });
356
+ box.append(list, ...parts.map((p) => p.panel));
357
+ watch(() => {
358
+ box.hidden = form.node(node.id).invisible;
359
+ const shown = parts.filter((p) => !form.node(p.tab.id).invisible);
360
+ const keep = picked !== null && shown.some((p) => p.tab.id === picked);
361
+ if (keep)
362
+ active = picked;
363
+ else if (shown.length)
364
+ active = shown[0].tab.id;
365
+ for (const p of parts) {
366
+ const selected = p.tab.id === active;
367
+ p.button.hidden = !shown.includes(p);
368
+ p.button.setAttribute('aria-selected', String(selected));
369
+ p.button.tabIndex = selected ? 0 : -1;
370
+ p.panel.hidden = !selected;
371
+ }
372
+ });
373
+ return box;
374
+ }
375
+ function item(node, place) {
376
+ switch (node.type) {
377
+ case 'field':
378
+ return fieldItem(node, place.labels);
379
+ case 'button':
380
+ return buttonItem(node);
381
+ case 'text':
382
+ return textItem(node);
383
+ case 'slot':
384
+ return slotItem(node);
385
+ case 'section':
386
+ return sectionItem(node, place);
387
+ case 'tabs':
388
+ return tabsItem(node, place);
389
+ case 'divider':
390
+ case 'spacer':
391
+ case 'image':
392
+ return blockItem(node);
393
+ case 'form':
394
+ return formItem(node, place);
306
395
  }
307
- });
308
- return box;
309
- }
310
- function item(node, place) {
311
- switch (node.type) {
312
- case 'field':
313
- return fieldItem(node, place.labels);
314
- case 'button':
315
- return buttonItem(node);
316
- case 'text':
317
- return textItem(node);
318
- case 'slot':
319
- return slotItem(node);
320
- case 'section':
321
- return sectionItem(node, place);
322
- case 'tabs':
323
- return tabsItem(node, place);
324
- case 'divider':
325
- case 'spacer':
326
- case 'image':
327
- return blockItem(node);
328
396
  }
397
+ /** A line across the row, empty room, or a picture: shown and hidden by its rule like any part. */
398
+ function blockItem(node) {
399
+ const element = node.type === 'divider' ? el('hr', { class: 'fd-divider', 'data-node': node.id })
400
+ : node.type === 'spacer' ? el('div', { class: 'fd-block fd-spacer', 'aria-hidden': 'true', 'data-node': node.id })
401
+ : figure(node);
402
+ if (node.type !== 'divider' && node.colspan)
403
+ element.style.setProperty('--fd-span', String(node.colspan));
404
+ hideWhen(element, node.id);
405
+ return element;
406
+ }
407
+ /** A picture as wide and where its page says, opening its link in a new tab — a web or mail address only — its caption under it. */
408
+ function figure(node) {
409
+ const image = el('img', { class: 'fd-image', src: node.src, alt: node.alt, loading: 'lazy' });
410
+ const href = node.href && /^(https?:\/\/|mailto:)/i.test(node.href) ? node.href : undefined;
411
+ const element = el('figure', { class: 'fd-block fd-figure', 'data-node': node.id, 'data-align': node.align }, href ? el('a', { href, target: '_blank', rel: 'noopener noreferrer' }, image) : image, ...(node.caption ? [el('figcaption', { class: 'fd-caption' }, node.caption)] : []));
412
+ const width = typeof node.width === 'number' ? `${node.width}px` : node.width && { small: '160px', medium: '320px', large: '480px', full: '100%' }[node.width];
413
+ if (width)
414
+ element.style.setProperty('--fd-image-width', width);
415
+ return element;
416
+ }
417
+ /**
418
+ * A saved form placed here, drawn from the page the app gives for its id
419
+ * with a form of its own inside this one. A quiet placeholder while the
420
+ * page comes; words in its place when it cannot be found, would hold
421
+ * itself, or cannot sit in a form.
422
+ */
423
+ function formItem(node, place) {
424
+ const box = el('fieldset', {
425
+ class: 'fd-section fd-form-part',
426
+ 'data-node': node.id,
427
+ 'data-style': 'card',
428
+ 'data-on-page': place.onPage ? '' : undefined,
429
+ 'aria-busy': 'true',
430
+ });
431
+ spans(box, node.colspan);
432
+ const note = el('p', { class: 'fd-form-part-note' }, labels.loading);
433
+ box.append(note);
434
+ hideWhen(box, node.id);
435
+ const refuse = (words) => {
436
+ box.removeAttribute('aria-busy');
437
+ note.textContent = words;
438
+ note.classList.add('fd-form-part-problem');
439
+ };
440
+ const draw = (found) => {
441
+ if (gone)
442
+ return;
443
+ if (!found)
444
+ return refuse(fill(labels.formMissing, { page: node.page }));
445
+ const saved = shownAs(found);
446
+ const name = saved.title || found.id;
447
+ const at = scope.chain.findIndex((p) => p.id === found.id);
448
+ if (at !== -1)
449
+ return refuse(fill(labels.formInItself, { page: name, chain: [...scope.chain.slice(at).map((p) => p.title), name].join(' → ') }));
450
+ if (found.layout.type !== 'sections' && found.layout.type !== 'tabs')
451
+ return refuse(fill(labels.formNotPlaceable, { page: name }));
452
+ const checked = (0, core_1.checkPage)(saved);
453
+ let inner;
454
+ try {
455
+ if (!checked.ok)
456
+ throw new Error(checked.issues.map((i) => `${i.path}: ${i.message}`).join('; '));
457
+ inner = form.embed(node.id, saved);
458
+ }
459
+ catch (error) {
460
+ console.warn(`Fieldia: the saved form "${found.id}" cannot be shown: ${error.message}`);
461
+ return refuse(fill(labels.formBroken, { page: name }));
462
+ }
463
+ const title = node.title ?? saved.title ?? '';
464
+ box.setAttribute('data-title', title);
465
+ if (title)
466
+ box.prepend(el('legend', { class: 'fd-section-title' }, ...withIcon(undefined, title)));
467
+ const own = drawer({
468
+ root: false,
469
+ form: inner,
470
+ page: saved,
471
+ prefix: `${scope.prefix}${node.id}-`,
472
+ chain: [...scope.chain, { id: found.id, title: name }],
473
+ locked: () => scope.locked() || form.node(node.id).readonly,
474
+ path: `${scope.path}${node.name}.`,
475
+ });
476
+ const layout = saved.layout;
477
+ // Its parts sit in the part's box: a card there draws none of its own.
478
+ note.replaceWith(own.grid(layout.type === 'tabs' ? [layout] : layout.children, 1, { columns: 1, onPage: false, labels: place.labels }));
479
+ box.removeAttribute('aria-busy');
480
+ cleanups.push(inner.subscribe(renderNow));
481
+ if (mounted)
482
+ renderNow();
483
+ };
484
+ let asked;
485
+ try {
486
+ asked = (0, related_1.findPage)(options, node.version === undefined ? { id: node.page } : { id: node.page, version: node.version });
487
+ }
488
+ catch {
489
+ asked = null;
490
+ }
491
+ if (asked instanceof Promise)
492
+ asked.then(draw, () => draw(null));
493
+ else
494
+ draw(asked);
495
+ return box;
496
+ }
497
+ return { item, grid, fieldItem, buttonItem, hideWhen, slotItem };
329
498
  }
330
- /** A line across the row, empty room, or a picture: shown and hidden by its rule like any part. */
331
- function blockItem(node) {
332
- const element = node.type === 'divider' ? el('hr', { class: 'fd-divider', 'data-node': node.id })
333
- : node.type === 'spacer' ? el('div', { class: 'fd-block fd-spacer', 'aria-hidden': 'true', 'data-node': node.id })
334
- : figure(node);
335
- if (node.type !== 'divider' && node.colspan)
336
- element.style.setProperty('--fd-span', String(node.colspan));
337
- hideWhen(element, node.id);
338
- return element;
339
- }
340
- /** A picture as wide and where its page says, opening its link in a new tab — a web or mail address only — its caption under it. */
341
- function figure(node) {
342
- const image = el('img', { class: 'fd-image', src: node.src, alt: node.alt, loading: 'lazy' });
343
- const href = node.href && /^(https?:\/\/|mailto:)/i.test(node.href) ? node.href : undefined;
344
- const element = el('figure', { class: 'fd-block fd-figure', 'data-node': node.id, 'data-align': node.align }, href ? el('a', { href, target: '_blank', rel: 'noopener noreferrer' }, image) : image, ...(node.caption ? [el('figcaption', { class: 'fd-caption' }, node.caption)] : []));
345
- const width = typeof node.width === 'number' ? `${node.width}px` : node.width && { small: '160px', medium: '320px', large: '480px', full: '100%' }[node.width];
346
- if (width)
347
- element.style.setProperty('--fd-image-width', width);
348
- return element;
349
- }
499
+ const { item, grid, fieldItem, buttonItem, hideWhen, slotItem } = drawer({
500
+ root: true,
501
+ form,
502
+ page,
503
+ prefix: '',
504
+ chain: [{ id: page.id, title: page.title || page.id }],
505
+ locked: () => false,
506
+ path: '',
507
+ });
350
508
  // ---- shared chrome ----------------------------------------------------------
351
509
  /** The whole form locked: every field read-only, no Save; buttons still run. */
352
510
  let locked = options.readonly === true;
@@ -383,18 +541,27 @@ function mountViewer(host, options) {
383
541
  retry.addEventListener('click', () => void submitOrSave());
384
542
  const status = el('div', { class: 'fd-status-box' }, statusText, retry);
385
543
  const notDone = () => (page.data.kind === 'responses' ? labels.notSent : labels.notSaved);
386
- /** "Not saved. Check: Email, Phone": the fields with a problem, in the order they show. */
544
+ /**
545
+ * "Not saved. Check: Email, Phone": the fields with a problem, in the order
546
+ * they show; one inside a saved form with that form's title, "Street (Home address)".
547
+ */
387
548
  function checkText(state) {
388
- const names = [];
549
+ const fieldsShown = [...root.querySelectorAll('.fd-field[data-path]')];
550
+ const found = [];
389
551
  for (const key of Object.keys(state.errors)) {
390
- const field = key.split('.')[0];
391
- const shown = root.querySelector(`.fd-field[data-field="${field}"]:not([hidden]) > .fd-label`);
392
- const name = shown?.firstChild?.textContent ?? page.fields[field]?.label ?? field;
393
- if (!names.includes(name))
394
- names.push(name);
395
- }
396
- const inOrder = [...root.querySelectorAll('.fd-field[data-field] > .fd-label')].map((label) => label.firstChild?.textContent ?? '');
397
- names.sort((a, b) => (inOrder.indexOf(a) + 1 || Infinity) - (inOrder.indexOf(b) + 1 || Infinity));
552
+ // The field itself, or — for a line's — the table it is in.
553
+ let shown;
554
+ for (let path = key; path && !shown; path = path.slice(0, Math.max(0, path.lastIndexOf('.')))) {
555
+ shown = fieldsShown.find((field) => field.getAttribute('data-path') === path && !field.hidden);
556
+ }
557
+ const first = key.split('.')[0];
558
+ const label = shown?.querySelector(':scope > .fd-label')?.firstChild?.textContent ?? page.fields[first]?.label ?? first;
559
+ const within = shown?.closest('.fd-form-part')?.getAttribute('data-title');
560
+ const name = within ? `${label} (${within})` : label;
561
+ if (!found.some((f) => f.name === name))
562
+ found.push({ name, at: shown ? fieldsShown.indexOf(shown) : Infinity });
563
+ }
564
+ const names = found.sort((a, b) => a.at - b.at).map((f) => f.name);
398
565
  return names.length ? fill(labels.checkFields, { what: notDone(), fields: names.join(', ') }) : notDone();
399
566
  }
400
567
  let quietTimer;
@@ -659,7 +826,7 @@ function mountViewer(host, options) {
659
826
  const icon = (0, widgets_1.drawIcon)(doc, stat.icon, options.icons);
660
827
  const words = el('span', { class: 'fd-stat-words' }, value, el('span', { class: 'fd-stat-label' }, stat.label));
661
828
  const button = el('button', { type: 'button', class: 'fd-stat', 'data-node': stat.id }, ...(icon ? [icon, words] : [words]));
662
- button.addEventListener('click', () => void form.runAction(stat.id));
829
+ button.addEventListener('click', () => void press(button, () => form.runAction(stat.id)));
663
830
  updaters.push((state) => {
664
831
  button.hidden = form.node(stat.id).invisible;
665
832
  const count = stat.field ? state.values[stat.field] : null;
@@ -765,7 +932,7 @@ function mountViewer(host, options) {
765
932
  labels,
766
933
  locale,
767
934
  fill,
768
- confirm,
935
+ press,
769
936
  withIcon,
770
937
  uid,
771
938
  icons: options.icons,
@@ -874,9 +1041,13 @@ function mountViewer(host, options) {
874
1041
  };
875
1042
  cancel.addEventListener('click', () => close(false));
876
1043
  ok.addEventListener('click', () => close(true));
1044
+ // Its keys are its own: Escape answers No here, and closes no dialog or panel under it.
877
1045
  backdrop.addEventListener('keydown', (event) => {
878
- if (event.key === 'Escape')
1046
+ event.stopPropagation();
1047
+ if (event.key === 'Escape') {
1048
+ event.preventDefault();
879
1049
  close(false);
1050
+ }
880
1051
  else
881
1052
  (0, focus_trap_1.keepTabIn)(dialog, event);
882
1053
  });
@@ -891,7 +1062,13 @@ function mountViewer(host, options) {
891
1062
  }
892
1063
  host.append(root);
893
1064
  const unsubscribe = form.subscribe(render);
1065
+ // A run that could not go on says why: a step that cannot run here, or what the app threw. A stop with words the form says itself.
1066
+ cleanups.push(form.on('run', ({ result }) => {
1067
+ if (result.reason === 'cannot' || (result.reason === 'app' && result.error !== undefined))
1068
+ actionHost.say(result.message ?? '', result.reason === 'app' ? 'danger' : 'warning');
1069
+ }));
894
1070
  render(form.getState());
1071
+ mounted = true;
895
1072
  if (form.getState().status === 'idle')
896
1073
  void form.load();
897
1074
  return {
@@ -918,7 +1095,15 @@ function mountViewer(host, options) {
918
1095
  render(form.getState());
919
1096
  },
920
1097
  isReadonly: () => locked,
1098
+ on: (event, listener) => {
1099
+ const off = form.on(event, listener);
1100
+ cleanups.push(off);
1101
+ return off;
1102
+ },
1103
+ setValues: (values) => form.setValues(values),
1104
+ run: (steps, context) => form.run(steps, context),
921
1105
  destroy() {
1106
+ gone = true;
922
1107
  unsubscribe();
923
1108
  for (const cleanup of cleanups)
924
1109
  cleanup();