@fieldia/viewer 0.10.0 → 0.12.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 (110) 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 +6 -4
  9. package/bundle/fieldia.js.map +4 -4
  10. package/package.json +3 -3
  11. package/src/lib/attachment-preview.d.mts +27 -0
  12. package/src/lib/attachment-preview.d.ts +27 -0
  13. package/src/lib/attachment-preview.js +89 -0
  14. package/src/lib/attachment-preview.js.map +1 -0
  15. package/src/lib/attachment-preview.mjs +86 -0
  16. package/src/lib/attachment-preview.mjs.map +1 -0
  17. package/src/lib/dialog.d.mts +31 -2
  18. package/src/lib/dialog.d.ts +31 -2
  19. package/src/lib/dialog.js +158 -30
  20. package/src/lib/dialog.js.map +1 -1
  21. package/src/lib/dialog.mjs +155 -30
  22. package/src/lib/dialog.mjs.map +1 -1
  23. package/src/lib/hotkeys.d.mts +11 -0
  24. package/src/lib/hotkeys.d.ts +11 -0
  25. package/src/lib/hotkeys.js +34 -0
  26. package/src/lib/hotkeys.js.map +1 -0
  27. package/src/lib/hotkeys.mjs +30 -0
  28. package/src/lib/hotkeys.mjs.map +1 -0
  29. package/src/lib/labels.d.mts +39 -0
  30. package/src/lib/labels.d.ts +39 -0
  31. package/src/lib/labels.js +23 -0
  32. package/src/lib/labels.js.map +1 -1
  33. package/src/lib/labels.mjs +23 -0
  34. package/src/lib/labels.mjs.map +1 -1
  35. package/src/lib/list.d.mts +5 -2
  36. package/src/lib/list.d.ts +5 -2
  37. package/src/lib/list.js +6 -6
  38. package/src/lib/list.js.map +1 -1
  39. package/src/lib/list.mjs +6 -6
  40. package/src/lib/list.mjs.map +1 -1
  41. package/src/lib/locales/ar.js +23 -0
  42. package/src/lib/locales/ar.js.map +1 -1
  43. package/src/lib/locales/ar.mjs +23 -0
  44. package/src/lib/locales/ar.mjs.map +1 -1
  45. package/src/lib/locales/de.js +23 -0
  46. package/src/lib/locales/de.js.map +1 -1
  47. package/src/lib/locales/de.mjs +23 -0
  48. package/src/lib/locales/de.mjs.map +1 -1
  49. package/src/lib/locales/fr.js +23 -0
  50. package/src/lib/locales/fr.js.map +1 -1
  51. package/src/lib/locales/fr.mjs +23 -0
  52. package/src/lib/locales/fr.mjs.map +1 -1
  53. package/src/lib/look.d.mts +7 -3
  54. package/src/lib/look.d.ts +7 -3
  55. package/src/lib/look.js +72 -15
  56. package/src/lib/look.js.map +1 -1
  57. package/src/lib/look.mjs +72 -15
  58. package/src/lib/look.mjs.map +1 -1
  59. package/src/lib/open.d.mts +30 -0
  60. package/src/lib/open.d.ts +30 -0
  61. package/src/lib/open.js +92 -0
  62. package/src/lib/open.js.map +1 -0
  63. package/src/lib/open.mjs +89 -0
  64. package/src/lib/open.mjs.map +1 -0
  65. package/src/lib/place.d.mts +2 -0
  66. package/src/lib/place.d.ts +2 -0
  67. package/src/lib/place.js.map +1 -1
  68. package/src/lib/place.mjs.map +1 -1
  69. package/src/lib/record-bar.d.mts +56 -0
  70. package/src/lib/record-bar.d.ts +56 -0
  71. package/src/lib/record-bar.js +237 -0
  72. package/src/lib/record-bar.js.map +1 -0
  73. package/src/lib/record-bar.mjs +234 -0
  74. package/src/lib/record-bar.mjs.map +1 -0
  75. package/src/lib/record-styles.d.mts +9 -0
  76. package/src/lib/record-styles.d.ts +9 -0
  77. package/src/lib/record-styles.js +83 -0
  78. package/src/lib/record-styles.js.map +1 -0
  79. package/src/lib/record-styles.mjs +79 -0
  80. package/src/lib/record-styles.mjs.map +1 -0
  81. package/src/lib/related.d.mts +26 -3
  82. package/src/lib/related.d.ts +26 -3
  83. package/src/lib/related.js +37 -10
  84. package/src/lib/related.js.map +1 -1
  85. package/src/lib/related.mjs +36 -10
  86. package/src/lib/related.mjs.map +1 -1
  87. package/src/lib/say.d.mts +11 -0
  88. package/src/lib/say.d.ts +11 -0
  89. package/src/lib/say.js +61 -0
  90. package/src/lib/say.js.map +1 -0
  91. package/src/lib/say.mjs +58 -0
  92. package/src/lib/say.mjs.map +1 -0
  93. package/src/lib/tab-strip.d.mts +17 -0
  94. package/src/lib/tab-strip.d.ts +17 -0
  95. package/src/lib/tab-strip.js +51 -0
  96. package/src/lib/tab-strip.js.map +1 -0
  97. package/src/lib/tab-strip.mjs +48 -0
  98. package/src/lib/tab-strip.mjs.map +1 -0
  99. package/src/lib/value-words.d.mts +10 -0
  100. package/src/lib/value-words.d.ts +10 -0
  101. package/src/lib/value-words.js +38 -0
  102. package/src/lib/value-words.js.map +1 -0
  103. package/src/lib/value-words.mjs +35 -0
  104. package/src/lib/value-words.mjs.map +1 -0
  105. package/src/lib/viewer.d.mts +54 -5
  106. package/src/lib/viewer.d.ts +54 -5
  107. package/src/lib/viewer.js +924 -297
  108. package/src/lib/viewer.js.map +1 -1
  109. package/src/lib/viewer.mjs +926 -299
  110. package/src/lib/viewer.mjs.map +1 -1
@@ -1,10 +1,18 @@
1
1
  import { createForm, checkPage, isRightToLeft, localizePage, translatePage, wideColumns, MESSAGES, } from '@fieldia/core';
2
- import { browserPreferences, createWidget, drawIcon, installStyles, WIDGET_LABELS } from '@fieldia/widgets';
3
- import { pageDialogs } from './related.mjs';
2
+ import { browserPreferences, createWidget, displayValue, drawIcon, installStyles, readsAsText, readText, WIDGET_LABELS } from '@fieldia/widgets';
3
+ import { findPage, pageDialogs } from './related.mjs';
4
4
  import { listView } from './list.mjs';
5
5
  import { applyLook } from './look.mjs';
6
6
  import { labelPlace, planSection } from './place.mjs';
7
7
  import { setAttr, setHidden, setText } from './dom.mjs';
8
+ import { openPage } from './open.mjs';
9
+ import { sayer } from './say.mjs';
10
+ import { tabStrip } from './tab-strip.mjs';
11
+ import { valueWords } from './value-words.mjs';
12
+ import { hotkeyOf, hotkeyOn } from './hotkeys.mjs';
13
+ import { recordBar } from './record-bar.mjs';
14
+ import { attachmentPreview } from './attachment-preview.mjs';
15
+ import { installRecordStyles } from './record-styles.mjs';
8
16
  import { ownLocale, VIEWER_LABELS } from './labels.mjs';
9
17
  import { keepTabIn } from './focus-trap.mjs';
10
18
  export { VIEWER_LABELS, DEFAULT_LABELS } from './labels.mjs';
@@ -17,7 +25,8 @@ let mounts = 0;
17
25
  export function mountViewer(host, options) {
18
26
  const doc = host.ownerDocument;
19
27
  // The quick check of names and conditions: the full one, with its validation library, belongs where pages are made.
20
- const checked = checkPage(options.page);
28
+ // A line's own form reads the record the line is on as parent.
29
+ const checked = checkPage(options.page, options.parent ? { parent: options.parent.fields } : {});
21
30
  if (!checked.ok) {
22
31
  throw new Error(`This page cannot be shown:\n${checked.issues.map((i) => ` ${i.path}: ${i.message}`).join('\n')}`);
23
32
  }
@@ -25,20 +34,60 @@ export function mountViewer(host, options) {
25
34
  const tag = options.locale ?? checked.page.language;
26
35
  const localized = tag ? localizePage(checked.page, tag) : checked.page;
27
36
  const page = options.translate ? translatePage(localized, options.translate) : localized;
37
+ /** Another page as this one is shown: in its language, through the app's translator. */
38
+ const shownAs = (other) => {
39
+ const own = tag ? localizePage(other, tag) : other;
40
+ return options.translate ? translatePage(own, options.translate) : own;
41
+ };
28
42
  const locale = ownLocale(tag);
29
43
  const preferences = options.preferences ?? browserPreferences();
30
- const dialogs = pageDialogs(options);
44
+ const dialogs = pageDialogs(options, (message, tone) => actionHost.say(message, tone));
31
45
  const ownsForm = !options.form;
32
- const form = options.form ?? createForm({ ...options, page, messages: options.messages ?? MESSAGES[locale] });
33
46
  const labels = { ...VIEWER_LABELS[locale], ...options.labels };
47
+ /**
48
+ * What the page's steps ask of the screen: a page opened, words said, a
49
+ * question asked, a tab shown — the viewer's own, under the app's. A form
50
+ * made elsewhere (`form`) keeps the host it was made with.
51
+ */
52
+ const actionHost = {
53
+ open: (request) => openPage({
54
+ options,
55
+ place: host,
56
+ root,
57
+ title: (other) => shownAs(other).title || other.id,
58
+ back: labels.back,
59
+ missing: (id) => fill(labels.pageMissing, { page: id }),
60
+ say: (message, tone) => actionHost.say(message, tone),
61
+ post: (message) => form.post(message),
62
+ name: () => recordName() || labels.newRecord,
63
+ }, request),
64
+ say: (message, tone) => say(message, tone),
65
+ ask: (message) => confirm(message),
66
+ show: (target) => {
67
+ const show = tabs.get(target);
68
+ if (!show?.())
69
+ throw new Error(`No tab "${target}" can be shown here`);
70
+ },
71
+ // A new tab opened apart from this page, or this one sent there.
72
+ openUrl: (url, newTab) => (newTab ? doc.defaultView?.open(url, '_blank', 'noopener,noreferrer') : doc.defaultView?.location.assign(url)),
73
+ ...options.host,
74
+ };
75
+ const form = options.form ?? createForm({ ...options, page, host: actionHost, messages: options.messages ?? MESSAGES[locale] });
34
76
  const widgetLabels = WIDGET_LABELS[locale];
35
77
  const dir = options.dir ?? (tag && isRightToLeft(tag) ? 'rtl' : undefined);
36
78
  const prefix = `fd${++mounts}`;
37
79
  const updaters = [];
80
+ /**
81
+ * Where a part's updater goes as it is drawn: the form's own list, or the list
82
+ * of the tab it is drawn in, which runs only while that tab is shown.
83
+ */
84
+ let sink = updaters;
38
85
  const cleanups = [];
39
- const uid = (id) => `${prefix}-${id.replace(/[^A-Za-z0-9_-]/g, '_')}`;
86
+ const ownUid = (id) => `${prefix}-${id.replace(/[^A-Za-z0-9_-]/g, '_')}`;
87
+ const uid = ownUid;
40
88
  const fill = (template, values) => template.replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? ''));
41
89
  installStyles(doc);
90
+ installRecordStyles(doc);
42
91
  function el(tag, attrs = {}, ...children) {
43
92
  const node = doc.createElement(tag);
44
93
  for (const [name, value] of Object.entries(attrs))
@@ -60,287 +109,609 @@ export function mountViewer(host, options) {
60
109
  const root = el('form', { class: 'fd-form', novalidate: '', 'data-fd-skin': options.skin ?? 'underline', dir, lang: tag, 'data-max-width': page.maxWidth });
61
110
  applyLook(root, page.look);
62
111
  const confirm = options.confirm ?? dialogConfirm;
63
- // ---- the parts -------------------------------------------------------
64
- /** A field with its label, help and messages. `labels` is where labels sit where it is put; the title's own fields take none. */
65
- function fieldItem(node, labels) {
66
- const def = page.fields[node.field];
67
- const id = uid(node.id);
68
- const labelsAt = labelPlace(node, def.type, labels);
69
- const wrapper = el('div', { class: 'fd-field', 'data-node': node.id, 'data-field': node.field, 'data-type': def.type, 'data-labels': labelsAt });
70
- if (node.colspan)
71
- wrapper.style.setProperty('--fd-span', String(node.colspan));
72
- const labelText = node.label ?? def.label;
73
- const label = el('label', { class: 'fd-label', id: `${id}-label`, for: id }, labelText);
74
- // The ✓ of a field filled in right; never on a yes/no box, a table or a file, where it would say nothing.
75
- const mark = options.showValid && !NO_VALID_MARK.has(def.type) ? drawIcon(doc, 'check') : null;
76
- if (mark) {
77
- mark.classList.add('fd-valid-mark');
78
- label.append(mark);
79
- }
80
- const widget = createWidget({ form, name: node.field, field: def, node, id, document: doc, labels: widgetLabels, preferences, locale, dialogs }, options.widgets);
81
- // 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.
82
- if (labelsAt === 'hidden' && !node.placeholder) {
83
- const box = widget.element.matches(TEXT_BOX) ? widget.element : widget.element.querySelector(TEXT_BOX);
84
- box?.setAttribute('placeholder', labelText);
85
- }
86
- if (!['INPUT', 'SELECT', 'TEXTAREA'].includes(widget.element.tagName)) {
87
- // `for` stays: a custom field that puts the id on its own input is
88
- // labelled natively. Only a wrapper with a role (a radio group, say) may
89
- // carry a name; ARIA forbids naming a plain div or span.
90
- // A group inside a box of its own (a radio group with "Clear selection" under it) is named too.
91
- const named = widget.element.getAttribute('role') ? widget.element : widget.element.querySelector(`[id="${id}"][role]`);
92
- named?.setAttribute('aria-labelledby', label.id);
93
- label.addEventListener('click', () => widget.focus());
94
- }
95
- const helpText = node.help ?? def.help;
96
- const help = helpText ? el('div', { class: 'fd-help', id: `${id}-help` }, helpText) : null;
97
- // Not an alert of its own: a refused save is announced once, naming every field to look at.
98
- const error = el('div', { class: 'fd-error', id: `${id}-error`, hidden: '' });
99
- // A warning from an answer rule, and one from the data source's onchange beside the field whose change brought it.
100
- const warning = el('div', { class: 'fd-warning', id: `${id}-warning`, role: 'status', hidden: '' });
101
- wrapper.append(...(labelsAt === 'after' ? [widget.element, label] : [label, widget.element]), ...(help ? [help] : []), error, warning);
102
- if (widget.destroy)
103
- cleanups.push(() => widget.destroy?.());
104
- // An answer rule's warning waits until the person leaves the field: no advice
105
- // mid-word. One already shown stays while they put it right, and goes once they have.
106
- let typing = false;
107
- let advice = '';
108
- wrapper.addEventListener('focusin', () => (typing = true));
109
- wrapper.addEventListener('focusout', (event) => {
110
- if (wrapper.contains(event.relatedTarget))
111
- return;
112
- typing = false;
113
- // Not at once: focus also leaves when a redraw removes the focused part
114
- // (a deleted line's button), and that redraw must finish first.
115
- queueMicrotask(() => update(form.getState()));
116
- });
117
- const update = (state) => {
118
- const shown = form.node(node.id);
119
- setHidden(wrapper, shown.invisible);
120
- wrapper.classList.toggle('fd-required', shown.required);
121
- const message = state.errors[node.field];
122
- setHidden(error, !message);
123
- setText(error, message ?? '');
124
- const now = state.warnings[node.field] ?? '';
125
- if (!typing || !now)
126
- advice = now;
127
- // An error shown says enough: the rule's warning gives way to it.
128
- const warned = [message ? '' : advice, state.warning && state.warningField === node.field ? state.warning : ''].filter(Boolean).join(' ');
129
- setHidden(warning, !warned);
130
- setText(warning, warned);
131
- if (mark) {
132
- const value = state.values[node.field];
133
- const filled = value !== null && value !== undefined && value !== '' && !(Array.isArray(value) && !value.length);
134
- const valid = !shown.readonly && !message && filled && state.dirty.includes(node.field) && form.problem(node.field) === null;
135
- wrapper.classList.toggle('fd-valid', valid);
136
- mark.toggleAttribute('hidden', !valid);
112
+ const say = sayer(root, el, labels.dismiss);
113
+ /** The tabs a step can show, by id: each shows its tab, false when it is hidden. */
114
+ const tabs = new Map();
115
+ /** For each field in a tab, how to show its tab: a problem there is shown before the focus goes to it. */
116
+ const problemTabs = new Map();
117
+ /**
118
+ * A press runs its steps one run at a time: the button busy meanwhile, and
119
+ * not pressed again. A check or a save that stops it takes the focus to the
120
+ * first problem, and says which fields, as Save does.
121
+ */
122
+ async function press(button, run) {
123
+ if (button.hasAttribute('aria-busy'))
124
+ return;
125
+ button.setAttribute('aria-busy', 'true');
126
+ button.setAttribute('aria-disabled', 'true');
127
+ try {
128
+ const { reason } = await run();
129
+ if (reason === 'check' || reason === 'save') {
130
+ if (!form.getState().saveProblem)
131
+ announce(checkText(form.getState()));
132
+ focusFirstProblem();
137
133
  }
138
- widget.update({
139
- value: state.values[node.field],
140
- values: state.values,
141
- readonly: shown.readonly || locked,
142
- required: shown.required,
143
- invalid: !!message,
144
- describedBy: [help?.id, message ? error.id : undefined, warned ? warning.id : undefined].filter(Boolean).join(' ') || undefined,
145
- });
146
- };
147
- updaters.push(update);
148
- return wrapper;
149
- }
150
- function hideWhen(element, id) {
151
- updaters.push(() => setHidden(element, form.node(id).invisible));
152
- }
153
- function buttonItem(node) {
154
- const button = el('button', { type: 'button', class: `fd-button fd-button-${node.style ?? 'secondary'}`, 'data-node': node.id }, ...withIcon(node.icon, node.label));
155
- spans(button, node.colspan);
156
- button.addEventListener('click', async () => {
157
- if (node.confirm && !(await confirm(node.confirm)))
158
- return;
159
- await form.runAction(node.id);
160
- });
161
- hideWhen(button, node.id);
162
- return button;
163
- }
164
- function textItem(node) {
165
- const style = node.style ?? 'paragraph';
166
- const element = el(style === 'heading' ? 'h3' : 'p', { class: `fd-text-${style}`, 'data-node': node.id }, node.text);
167
- spans(element, node.colspan);
168
- hideWhen(element, node.id);
169
- return element;
170
- }
171
- function slotItem(node) {
172
- const element = el('div', { class: 'fd-slot', 'data-slot': node.name, 'data-node': node.id });
173
- const cleanup = options.slots?.[node.name]?.(element, { form, name: node.name });
174
- if (cleanup)
175
- cleanups.push(cleanup);
176
- hideWhen(element, node.id);
177
- return element;
134
+ }
135
+ finally {
136
+ button.removeAttribute('aria-busy');
137
+ button.removeAttribute('aria-disabled');
138
+ }
178
139
  }
140
+ // ---- the parts -------------------------------------------------------
141
+ /** The fields that take the focus as the record opens, in the order they are drawn. */
142
+ const focusers = [];
143
+ /** Folded sections, and how to open each: a problem inside one has to be seen. */
144
+ const folds = new Map();
145
+ /** Every part drawn again from the state of the page shown. */
146
+ const renderNow = () => render(form.getState());
147
+ /** Set once the viewer is on the page; set again when it is taken away. */
148
+ let mounted = false;
149
+ let gone = false;
179
150
  /** The columns a part spans in the grid it sits in; the stylesheet keeps it within the columns there at each width. */
180
151
  function spans(element, colspan) {
181
152
  if (colspan)
182
153
  element.style.setProperty('--fd-span', String(colspan));
183
154
  }
155
+ /** Where the parts of a page, a tab or a step sit: one column, the page's labels. */
156
+ const top = (onPage) => ({ columns: 1, onPage, labels: page.look?.labels });
184
157
  /**
185
- * A grid of parts. With `columns` null, it has none of its own: it lays its
186
- * parts on the columns of the grid round it (an arrangement on its tracks).
158
+ * The parts of one page, drawn with its own form: the page shown, or a saved
159
+ * form placed in it. Inside, `form` and `page` are the scope's.
187
160
  */
188
- function grid(children, columns, place) {
189
- const box = el('div', { class: 'fd-grid' });
190
- if (columns !== null) {
191
- box.style.setProperty('--fd-columns', String(wideColumns(columns)));
192
- // Counts given for the narrower widths replace the skin's own stacking there.
193
- if (typeof columns === 'object') {
194
- for (const width of ['medium', 'narrow']) {
195
- const count = columns[width];
196
- if (count === undefined)
197
- continue;
198
- box.setAttribute(`data-columns-${width}`, String(count));
199
- box.style.setProperty(`--fd-columns-${width}`, String(count));
161
+ function drawer(scope) {
162
+ const { form, page } = scope;
163
+ const uid = (id) => ownUid(scope.prefix + id);
164
+ /** A part's updater, handed the state of the part's own form. */
165
+ const watch = (update) => sink.push(scope.root ? update : () => update(form.getState()));
166
+ /** A field with its label, help and messages. `place` is where labels sit where it is put; the title's own fields take none. */
167
+ function fieldItem(node, place) {
168
+ const def = page.fields[node.field];
169
+ const id = uid(node.id);
170
+ const labelsAt = labelPlace(node, def.type, place);
171
+ 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, 'data-focus': node.focus && scope.root ? '' : undefined });
172
+ if (node.colspan)
173
+ wrapper.style.setProperty('--fd-span', String(node.colspan));
174
+ const labelText = node.label ?? def.label;
175
+ const label = el('label', { class: 'fd-label', id: `${id}-label`, for: id }, labelText);
176
+ // The ✓ of a field filled in right; never on a yes/no box, a table or a file, where it would say nothing.
177
+ const mark = options.showValid && !NO_VALID_MARK.has(def.type) ? drawIcon(doc, 'check') : null;
178
+ if (mark) {
179
+ mark.classList.add('fd-valid-mark');
180
+ label.append(mark);
181
+ }
182
+ const widget = createWidget({ form, name: node.field, field: def, node, id, document: doc, labels: widgetLabels, preferences, locale, dialogs }, options.widgets);
183
+ // The field that takes the focus as the record opens (Flectra's default_focus): the page's own, not a saved form's inside it.
184
+ if (node.focus && scope.root)
185
+ focusers.push({ wrapper, focus: () => widget.focus() });
186
+ // 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.
187
+ const textBox = widget.element.matches(TEXT_BOX) ? widget.element : widget.element.querySelector(TEXT_BOX);
188
+ if (labelsAt === 'hidden' && !node.placeholder)
189
+ textBox?.setAttribute('placeholder', labelText);
190
+ // Words chosen by a condition (placeholderWhen), else what the box showed as it was drawn.
191
+ const drawnPlaceholder = textBox?.getAttribute('placeholder') ?? null;
192
+ const chosenPlaceholder = node.placeholderWhen?.length ? textBox : null;
193
+ if (!['INPUT', 'SELECT', 'TEXTAREA'].includes(widget.element.tagName)) {
194
+ // `for` stays: a custom field that puts the id on its own input is
195
+ // labelled natively. Only a wrapper with a role (a radio group, say) may
196
+ // carry a name; ARIA forbids naming a plain div or span.
197
+ // A group inside a box of its own (a radio group with "Clear selection" under it) is named too.
198
+ const named = widget.element.getAttribute('role') ? widget.element : widget.element.querySelector(`[id="${id}"][role]`);
199
+ named?.setAttribute('aria-labelledby', label.id);
200
+ label.addEventListener('click', () => widget.focus());
201
+ }
202
+ const helpText = node.help ?? def.help;
203
+ // Under the field, behind a (?) by its label, or both: the field's own way, else the page's.
204
+ const helpWay = node.helpShown ?? page.look?.helpShown ?? 'below';
205
+ const help = helpText && helpWay !== 'tooltip' ? el('div', { class: 'fd-help', id: `${id}-help` }, helpText) : null;
206
+ const tip = helpText && helpWay !== 'below' ? helpTip(`${id}-tip`, helpText, fill(labels.helpFor, { label: labelText })) : null;
207
+ // In the label, as Flectra's: a press on it does not move into the box. A label out of sight keeps it after the box.
208
+ if (tip && labelsAt === 'hidden')
209
+ widget.element.after(tip.element);
210
+ else if (tip)
211
+ label.append(tip.element);
212
+ // Not an alert of its own: a refused save is announced once, naming every field to look at.
213
+ const error = el('div', { class: 'fd-error', id: `${id}-error`, hidden: '' });
214
+ // A warning from an answer rule, and one from the data source's onchange beside the field whose change brought it.
215
+ const warning = el('div', { class: 'fd-warning', id: `${id}-warning`, role: 'status', hidden: '' });
216
+ wrapper.append(...(labelsAt === 'after' ? [widget.element, label] : [label, widget.element]), ...(help ? [help] : []), error, warning);
217
+ // Read-only, as words in place of the box, when the page draws them so.
218
+ const asText = page.look?.readonlyShown === 'text' && readsAsText(def, node) ? readText({ document: doc, field: def, node, id, locale, labels: widgetLabels, dialogs }) : null;
219
+ if (asText)
220
+ widget.element.after(asText.element);
221
+ if (widget.destroy)
222
+ cleanups.push(() => widget.destroy?.());
223
+ // An answer rule's warning waits until the person leaves the field: no advice
224
+ // mid-word. One already shown stays while they put it right, and goes once they have.
225
+ let typing = false;
226
+ let advice = '';
227
+ wrapper.addEventListener('focusin', () => (typing = true));
228
+ wrapper.addEventListener('focusout', (event) => {
229
+ if (wrapper.contains(event.relatedTarget))
230
+ return;
231
+ typing = false;
232
+ // Not at once: focus also leaves when a redraw removes the focused part
233
+ // (a deleted line's button), and that redraw must finish first.
234
+ queueMicrotask(() => update(form.getState()));
235
+ });
236
+ const toned = node.tones !== undefined || node.bold !== undefined;
237
+ const update = (state) => {
238
+ const shown = form.node(node.id);
239
+ setHidden(wrapper, shown.invisible);
240
+ wrapper.classList.toggle('fd-required', shown.required);
241
+ // Its value's tone and bold while a condition holds: Flectra's decoration-* on a field.
242
+ if (toned) {
243
+ const look = form.fieldTone(node.id);
244
+ setAttr(wrapper, 'data-tone', look.tone);
245
+ wrapper.classList.toggle('fd-value-bold', look.bold);
246
+ }
247
+ if (chosenPlaceholder)
248
+ setAttr(chosenPlaceholder, 'placeholder', form.placeholder(node.id) ?? drawnPlaceholder);
249
+ const message = state.errors[node.field];
250
+ setHidden(error, !message);
251
+ setText(error, message ?? '');
252
+ const now = state.warnings[node.field] ?? '';
253
+ if (!typing || !now)
254
+ advice = now;
255
+ // An error shown says enough: the rule's warning gives way to it.
256
+ const warned = [message ? '' : advice, state.warning && state.warningField === node.field ? state.warning : ''].filter(Boolean).join(' ');
257
+ setHidden(warning, !warned);
258
+ setText(warning, warned);
259
+ if (mark) {
260
+ const value = state.values[node.field];
261
+ const filled = value !== null && value !== undefined && value !== '' && !(Array.isArray(value) && !value.length);
262
+ const valid = !shown.readonly && !message && filled && state.dirty.includes(node.field) && form.problem(node.field) === null;
263
+ wrapper.classList.toggle('fd-valid', valid);
264
+ mark.toggleAttribute('hidden', !valid);
265
+ }
266
+ const readonly = shown.readonly || locked || scope.locked();
267
+ if (asText) {
268
+ setHidden(widget.element, readonly);
269
+ setHidden(asText.element, !readonly);
270
+ setAttr(wrapper, 'data-read-text', readonly ? '' : null);
271
+ if (readonly)
272
+ asText.update(state.values[node.field], state.values);
273
+ }
274
+ widget.update({
275
+ value: state.values[node.field],
276
+ values: state.values,
277
+ readonly,
278
+ required: shown.required,
279
+ invalid: !!message,
280
+ describedBy: [help?.id ?? tip?.bubble.id, message ? error.id : undefined, warned ? warning.id : undefined].filter(Boolean).join(' ') || undefined,
281
+ });
282
+ };
283
+ watch(update);
284
+ return wrapper;
285
+ }
286
+ /** A (?) that shows a field's help in a bubble: on hover, on focus, or kept open by a press — a tap — and gone with Escape. */
287
+ function helpTip(bubbleId, text, name) {
288
+ const bubble = el('span', { class: 'fd-help-bubble', role: 'tooltip', id: bubbleId, hidden: '' }, text);
289
+ const button = el('button', { type: 'button', class: 'fd-help-tip', 'aria-label': name, 'aria-expanded': 'false', 'aria-controls': bubbleId }, '?');
290
+ let kept = false;
291
+ const show = (open) => {
292
+ bubble.hidden = !open;
293
+ button.setAttribute('aria-expanded', String(open));
294
+ };
295
+ button.addEventListener('mouseenter', () => show(true));
296
+ button.addEventListener('mouseleave', () => show(kept));
297
+ button.addEventListener('focus', () => show(true));
298
+ button.addEventListener('blur', () => ((kept = false), show(false)));
299
+ button.addEventListener('click', (event) => {
300
+ event.preventDefault();
301
+ kept = !kept;
302
+ show(kept);
303
+ });
304
+ button.addEventListener('keydown', (event) => {
305
+ if (event.key !== 'Escape' || bubble.hidden)
306
+ return;
307
+ // Escape closes the bubble, not the dialog the form is in.
308
+ event.stopPropagation();
309
+ kept = false;
310
+ show(false);
311
+ });
312
+ return { element: el('span', { class: 'fd-help-tip-wrap' }, button, bubble), bubble };
313
+ }
314
+ function hideWhen(element, id) {
315
+ watch(() => setHidden(element, form.node(id).invisible));
316
+ }
317
+ function buttonItem(node) {
318
+ const button = el('button', { type: 'button', class: `fd-button fd-button-${node.style ?? 'secondary'}`, 'data-node': node.id }, ...withIcon(node.icon, node.label));
319
+ if (node.hotkey)
320
+ hotkeyOn(button, node.hotkey, node.label);
321
+ spans(button, node.colspan);
322
+ // Its confirmation, then its steps: the form asks, through the viewer.
323
+ button.addEventListener('click', () => void press(button, () => form.runAction(node.id)));
324
+ hideWhen(button, node.id);
325
+ // A header's button is drawn here too, never through item(): hidden at its widths the same way.
326
+ return hiddenOn(node, button);
327
+ }
328
+ function textItem(node, inline = false) {
329
+ const style = node.style ?? 'paragraph';
330
+ // Its words, with the values of the fields they name.
331
+ const words = valueWords(doc, page.fields, node.text, locale);
332
+ const element = inline
333
+ ? el('span', { class: `fd-oneline-words fd-text-${style}`, 'data-node': node.id }, ...words.nodes)
334
+ : style === 'alert'
335
+ ? el('div', { class: `fd-alert fd-text-alert fd-tone-${node.tone ?? 'info'}`, role: 'status', 'data-node': node.id }, el('span', { class: 'fd-alert-message' }, ...words.nodes))
336
+ : el(style === 'heading' ? 'h3' : 'p', { class: `fd-text-${style}`, 'data-node': node.id }, ...words.nodes);
337
+ spans(element, node.colspan);
338
+ hideWhen(element, node.id);
339
+ watch((state) => words.update(state.values));
340
+ return element;
341
+ }
342
+ function slotItem(node) {
343
+ const element = el('div', { class: 'fd-slot', 'data-slot': node.name, 'data-node': node.id });
344
+ const cleanup = options.slots?.[node.name]?.(element, { form, name: node.name });
345
+ if (cleanup)
346
+ cleanups.push(cleanup);
347
+ hideWhen(element, node.id);
348
+ return element;
349
+ }
350
+ /**
351
+ * A grid of parts. With `columns` null, it has none of its own: it lays its
352
+ * parts on the columns of the grid round it (an arrangement on its tracks).
353
+ */
354
+ function grid(children, columns, place) {
355
+ const box = el('div', { class: 'fd-grid' });
356
+ if (columns !== null) {
357
+ box.style.setProperty('--fd-columns', String(wideColumns(columns)));
358
+ // Twelfths: eleven gaps between them, which shrink in a narrow column rather than push past it.
359
+ if (wideColumns(columns) === 12)
360
+ box.setAttribute('data-twelfths', '');
361
+ // Counts given for the narrower widths replace the skin's own stacking there.
362
+ if (typeof columns === 'object') {
363
+ for (const width of ['medium', 'narrow']) {
364
+ const count = columns[width];
365
+ if (count === undefined)
366
+ continue;
367
+ box.setAttribute(`data-columns-${width}`, String(count));
368
+ box.style.setProperty(`--fd-columns-${width}`, String(count));
369
+ }
200
370
  }
201
371
  }
372
+ box.append(...children.map((child) => item(child, place)));
373
+ return box;
202
374
  }
203
- box.append(...children.map((child) => item(child, place)));
204
- return box;
205
- }
206
- /** Where the parts of a page, a tab or a step sit: one column, the page's labels. */
207
- const top = (onPage) => ({ columns: 1, onPage, labels: page.look?.labels });
208
- /** Folded sections, and how to open each: a problem inside one has to be seen. */
209
- const folds = new Map();
210
- function sectionItem(node, place) {
211
- const plan = planSection(node, place);
212
- // An arrangement is no group to name, and a fieldset cannot lay its parts on the columns round it.
213
- const section = el(plan.arrangement ? 'div' : 'fieldset', {
214
- class: 'fd-section',
215
- 'data-node': node.id,
216
- 'data-style': plan.style,
217
- 'data-place': plan.at,
218
- 'data-on-page': plan.style === 'card' && place.onPage ? '' : undefined,
219
- });
220
- spans(section, node.colspan);
221
- if (node.labelWidth)
222
- section.style.setProperty('--fd-label-width', `${node.labelWidth}px`);
223
- const description = node.description ? el('p', { class: 'fd-section-description' }, node.description) : null;
224
- const content = grid(node.children, plan.at === 'tracks' ? null : node.columns, plan.inner);
225
- if (node.title && node.collapsible) {
226
- content.id = uid(`${node.id}-content`);
227
- 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));
228
- let open = node.collapsed !== true;
229
- const show = (next) => {
230
- open = next;
231
- toggle.setAttribute('aria-expanded', String(open));
232
- content.hidden = !open;
233
- if (description)
234
- description.hidden = !open;
235
- section.classList.toggle('fd-section-folded', !open);
375
+ /**
376
+ * A row of twelfths led by a field whose label sits beside it, as Flectra's
377
+ * `<label/><div class="o_row">`: that label goes with the labels round it,
378
+ * and the parts share the room their values have.
379
+ */
380
+ function labelledRow(node, plan) {
381
+ const [first] = node.children;
382
+ if (!plan.arrangement || plan.at === 'tracks' || wideColumns(node.columns) !== 12 || node.children.length < 2 || first?.type !== 'field')
383
+ return null;
384
+ // One line of them: parts running past twelve twelfths are a column of fields, each with its own label.
385
+ if (node.children.reduce((sum, child) => sum + (child.colspan ?? 1), 0) > 12)
386
+ return null;
387
+ const type = page.fields[first.field]?.type;
388
+ const where = type ? labelPlace(first, type, plan.inner.labels) : 'hidden';
389
+ // The skin's place: beside in the underline skin, above in the outlined one, as the stylesheet says.
390
+ return where === undefined ? 'skin' : where === 'beside' ? 'beside' : null;
391
+ }
392
+ /**
393
+ * A line of parts, as Flectra's `<label/><div class="o_row">`: its title as
394
+ * the line's label, where the labels round it sit, and its parts after it,
395
+ * each as wide as it needs, its fields named for a screen reader.
396
+ */
397
+ function inlineItem(node, place) {
398
+ const line = el('div', { class: 'fd-field fd-oneline', 'data-node': node.id, 'data-style': 'inline', 'data-labels': place.labels });
399
+ spans(line, node.colspan);
400
+ const row = el('div', { class: 'fd-oneline-row', role: 'group' }, ...node.children.map((child) => item(child, { columns: 1, onPage: false, inline: true })));
401
+ if (node.title) {
402
+ const title = el('span', { class: 'fd-label', id: uid(`${node.id}-label`) }, node.title);
403
+ row.setAttribute('aria-labelledby', title.id);
404
+ line.append(title);
405
+ }
406
+ line.append(row);
407
+ hideWhen(line, node.id);
408
+ return line;
409
+ }
410
+ function sectionItem(node, place) {
411
+ if (node.style === 'inline')
412
+ return inlineItem(node, place);
413
+ const plan = planSection(node, place);
414
+ // An arrangement is no group to name, and a fieldset cannot lay its parts on the columns round it.
415
+ const section = el(plan.arrangement ? 'div' : 'fieldset', {
416
+ class: 'fd-section',
417
+ 'data-node': node.id,
418
+ 'data-style': plan.style,
419
+ 'data-place': plan.at,
420
+ 'data-on-page': plan.style === 'card' && place.onPage ? '' : undefined,
421
+ });
422
+ spans(section, node.colspan);
423
+ const row = labelledRow(node, plan);
424
+ if (row)
425
+ section.setAttribute('data-row', row);
426
+ if (node.labelWidth)
427
+ section.style.setProperty('--fd-label-width', `${node.labelWidth}px`);
428
+ const description = node.description ? el('p', { class: 'fd-section-description' }, node.description) : null;
429
+ const content = grid(node.children, plan.at === 'tracks' ? null : node.columns, plan.inner);
430
+ if (node.title && node.collapsible) {
431
+ content.id = uid(`${node.id}-content`);
432
+ 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));
433
+ let open = node.collapsed !== true;
434
+ const show = (next) => {
435
+ open = next;
436
+ toggle.setAttribute('aria-expanded', String(open));
437
+ content.hidden = !open;
438
+ if (description)
439
+ description.hidden = !open;
440
+ section.classList.toggle('fd-section-folded', !open);
441
+ };
442
+ toggle.addEventListener('click', () => show(!open));
443
+ folds.set(section, () => show(true));
444
+ show(open);
445
+ section.append(el('legend', { class: 'fd-section-title' }, toggle));
446
+ }
447
+ else if (node.title) {
448
+ section.append(el('legend', { class: 'fd-section-title' }, ...withIcon(node.icon, node.title)));
449
+ }
450
+ if (description)
451
+ section.append(description);
452
+ section.append(content);
453
+ hideWhen(section, node.id);
454
+ return section;
455
+ }
456
+ function tabsItem(node, place) {
457
+ const box = el('div', { class: 'fd-tabs', 'data-node': node.id });
458
+ spans(box, node.colspan);
459
+ const list = el('div', { class: 'fd-tablist', role: 'tablist' });
460
+ // The tab someone picked. Until they pick, the first visible tab is open —
461
+ // a tab hidden while the record loads must not leave its neighbour open.
462
+ let picked = null;
463
+ let active = node.children[0].id;
464
+ /** A tab shown, by a person or a step: the page's steps for it run. */
465
+ const show = (tab) => {
466
+ picked = active = tab;
467
+ renderNow();
468
+ form.shown(tab);
236
469
  };
237
- toggle.addEventListener('click', () => show(!open));
238
- folds.set(section, () => show(true));
239
- show(open);
240
- section.append(el('legend', { class: 'fd-section-title' }, toggle));
241
- }
242
- else if (node.title) {
243
- section.append(el('legend', { class: 'fd-section-title' }, ...withIcon(node.icon, node.title)));
244
- }
245
- if (description)
246
- section.append(description);
247
- section.append(content);
248
- hideWhen(section, node.id);
249
- return section;
250
- }
251
- function tabsItem(node, place) {
252
- const box = el('div', { class: 'fd-tabs', 'data-node': node.id });
253
- spans(box, node.colspan);
254
- const list = el('div', { class: 'fd-tablist', role: 'tablist' });
255
- // The tab someone picked. Until they pick, the first visible tab is open —
256
- // a tab hidden while the record loads must not leave its neighbour open.
257
- let picked = null;
258
- let active = node.children[0].id;
259
- const parts = node.children.map((tab) => {
260
- const tabId = uid(`${tab.id}-tab`);
261
- const panelId = uid(`${tab.id}-panel`);
262
- 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));
263
- // A tab's parts sit where the tabs do: on the page, or in the box round them.
264
- 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 }));
265
- button.addEventListener('click', () => {
266
- picked = active = tab.id;
267
- render(form.getState());
470
+ const parts = node.children.map((tab) => {
471
+ const tabId = uid(`${tab.id}-tab`);
472
+ const panelId = uid(`${tab.id}-panel`);
473
+ 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));
474
+ const panel = el('div', { class: 'fd-tabpanel', role: 'tabpanel', id: panelId, 'aria-labelledby': tabId });
475
+ /**
476
+ * A tab's parts are drawn when it is first shown, and kept up to date
477
+ * only while it is shown: a page of many tabs costs one tab's work.
478
+ */
479
+ const own = [];
480
+ let built = false;
481
+ const build = () => {
482
+ if (built)
483
+ return;
484
+ built = true;
485
+ const outer = sink;
486
+ sink = own;
487
+ try {
488
+ // A tab's parts sit where the tabs do: on the page, or in the box round them.
489
+ panel.append(grid(tab.children, 1, { columns: 1, onPage: place.onPage, labels: place.labels }));
490
+ }
491
+ finally {
492
+ sink = outer;
493
+ }
494
+ };
495
+ const open = () => !form.node(tab.id).invisible && (show(tab.id), true);
496
+ button.addEventListener('click', () => show(tab.id));
497
+ if (!tabs.has(tab.id))
498
+ tabs.set(tab.id, open);
499
+ // The fields it holds, to mark it while one has a problem and to open it at one.
500
+ const fields = fieldsIn(tab.children);
501
+ if (scope.root)
502
+ for (const name of fields)
503
+ if (!problemTabs.has(name))
504
+ problemTabs.set(name, open);
505
+ list.append(button);
506
+ return { tab, button, panel, own, build, fields };
268
507
  });
269
- list.append(button);
270
- return { tab, button, panel };
271
- });
272
- list.addEventListener('keydown', (event) => {
273
- const shown = parts.filter((p) => !p.button.hidden);
274
- const at = shown.findIndex((p) => p.tab.id === active);
275
- const move = { ArrowRight: 1, ArrowLeft: -1, Home: -at, End: shown.length - 1 - at }[event.key];
276
- if (move === undefined || at === -1)
277
- return;
278
- event.preventDefault();
279
- const rtl = root.getAttribute('dir') === 'rtl' && (event.key === 'ArrowRight' || event.key === 'ArrowLeft');
280
- const next = shown[(at + (rtl ? -move : move) + shown.length) % shown.length];
281
- picked = active = next.tab.id;
282
- render(form.getState());
283
- next.button.focus();
284
- });
285
- box.append(list, ...parts.map((p) => p.panel));
286
- updaters.push(() => {
287
- box.hidden = form.node(node.id).invisible;
288
- const shown = parts.filter((p) => !form.node(p.tab.id).invisible);
289
- const keep = picked !== null && shown.some((p) => p.tab.id === picked);
290
- if (keep)
291
- active = picked;
292
- else if (shown.length)
293
- active = shown[0].tab.id;
294
- for (const p of parts) {
295
- const selected = p.tab.id === active;
296
- p.button.hidden = !shown.includes(p);
297
- p.button.setAttribute('aria-selected', String(selected));
298
- p.button.tabIndex = selected ? 0 : -1;
299
- p.panel.hidden = !selected;
508
+ list.addEventListener('keydown', (event) => {
509
+ const shown = parts.filter((p) => !p.button.hidden);
510
+ const at = shown.findIndex((p) => p.tab.id === active);
511
+ const move = { ArrowRight: 1, ArrowLeft: -1, Home: -at, End: shown.length - 1 - at }[event.key];
512
+ if (move === undefined || at === -1)
513
+ return;
514
+ event.preventDefault();
515
+ const rtl = root.getAttribute('dir') === 'rtl' && (event.key === 'ArrowRight' || event.key === 'ArrowLeft');
516
+ const next = shown[(at + (rtl ? -move : move) + shown.length) % shown.length];
517
+ show(next.tab.id);
518
+ next.button.focus();
519
+ });
520
+ // Too long for its room, the strip scrolls; the tab chosen, however, comes into sight in it.
521
+ const strip = tabStrip(list, el);
522
+ cleanups.push(strip.destroy);
523
+ box.append(strip.element, ...parts.map((p) => p.panel));
524
+ let shownKey = '';
525
+ let revealed = '';
526
+ watch((state) => {
527
+ const tabsHidden = form.node(node.id).invisible;
528
+ setHidden(box, tabsHidden);
529
+ const shown = parts.filter((p) => !form.node(p.tab.id).invisible);
530
+ const keep = picked !== null && shown.some((p) => p.tab.id === picked);
531
+ if (keep)
532
+ active = picked;
533
+ else if (shown.length)
534
+ active = shown[0].tab.id;
535
+ const errors = form.getState().errors;
536
+ for (const p of parts) {
537
+ const selected = p.tab.id === active;
538
+ setHidden(p.button, !shown.includes(p));
539
+ setAttr(p.button, 'aria-selected', String(selected));
540
+ if (p.button.tabIndex !== (selected ? 0 : -1))
541
+ p.button.tabIndex = selected ? 0 : -1;
542
+ setAttr(p.button, 'data-problem', p.fields.some((name) => errors[name]) ? '' : null);
543
+ setHidden(p.panel, !selected);
544
+ // The tab shown: drawn if it is new, and brought up to date — it was left alone while out of sight.
545
+ if (selected && !tabsHidden) {
546
+ p.build();
547
+ for (const update of p.own)
548
+ update(state);
549
+ }
550
+ }
551
+ // Measured only when it can have changed: the strip's tabs, or the one chosen.
552
+ const key = shown.map((p) => p.tab.id).join(' ');
553
+ if (key !== shownKey) {
554
+ shownKey = key;
555
+ strip.measure();
556
+ }
557
+ if (active !== revealed && list.clientWidth) {
558
+ revealed = active;
559
+ const chosen = parts.find((p) => p.tab.id === active);
560
+ if (chosen)
561
+ strip.reveal(chosen.button);
562
+ }
563
+ });
564
+ return box;
565
+ }
566
+ /** The fields a tab holds, in its sections and tabs inside it; a saved form placed in it keeps its own. */
567
+ function fieldsIn(children) {
568
+ return children.flatMap((child) => child.type === 'field' ? [child.field]
569
+ : child.type === 'section' ? fieldsIn(child.children)
570
+ : child.type === 'tabs' ? child.children.flatMap((tab) => fieldsIn(tab.children))
571
+ : []);
572
+ }
573
+ function item(node, place) {
574
+ return hiddenOn(node, partItem(node, place));
575
+ }
576
+ /** A part hidden at some widths of the form (`hideOn`), as a phone's: the stylesheet hides it there. */
577
+ function hiddenOn(node, element) {
578
+ if (node.hideOn?.length)
579
+ element.dataset['hideOn'] = node.hideOn.join(' ');
580
+ return element;
581
+ }
582
+ function partItem(node, place) {
583
+ switch (node.type) {
584
+ case 'field':
585
+ return fieldItem(node, place.labels);
586
+ case 'button':
587
+ return buttonItem(node);
588
+ case 'text':
589
+ return textItem(node, place.inline);
590
+ case 'slot':
591
+ return slotItem(node);
592
+ case 'section':
593
+ return sectionItem(node, place);
594
+ case 'tabs':
595
+ return tabsItem(node, place);
596
+ case 'divider':
597
+ case 'spacer':
598
+ case 'image':
599
+ return blockItem(node);
600
+ case 'form':
601
+ return formItem(node, place);
300
602
  }
301
- });
302
- return box;
303
- }
304
- function item(node, place) {
305
- switch (node.type) {
306
- case 'field':
307
- return fieldItem(node, place.labels);
308
- case 'button':
309
- return buttonItem(node);
310
- case 'text':
311
- return textItem(node);
312
- case 'slot':
313
- return slotItem(node);
314
- case 'section':
315
- return sectionItem(node, place);
316
- case 'tabs':
317
- return tabsItem(node, place);
318
- case 'divider':
319
- case 'spacer':
320
- case 'image':
321
- return blockItem(node);
322
603
  }
604
+ /** A line across the row, empty room, or a picture: shown and hidden by its rule like any part. */
605
+ function blockItem(node) {
606
+ const element = node.type === 'divider' ? el('hr', { class: 'fd-divider', 'data-node': node.id })
607
+ : node.type === 'spacer' ? el('div', { class: 'fd-block fd-spacer', 'aria-hidden': 'true', 'data-node': node.id })
608
+ : figure(node);
609
+ if (node.type !== 'divider' && node.colspan)
610
+ element.style.setProperty('--fd-span', String(node.colspan));
611
+ hideWhen(element, node.id);
612
+ return element;
613
+ }
614
+ /** 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. */
615
+ function figure(node) {
616
+ const image = el('img', { class: 'fd-image', src: node.src, alt: node.alt, loading: 'lazy' });
617
+ const href = node.href && /^(https?:\/\/|mailto:)/i.test(node.href) ? node.href : undefined;
618
+ 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)] : []));
619
+ const width = typeof node.width === 'number' ? `${node.width}px` : node.width && { small: '160px', medium: '320px', large: '480px', full: '100%' }[node.width];
620
+ if (width)
621
+ element.style.setProperty('--fd-image-width', width);
622
+ return element;
623
+ }
624
+ /**
625
+ * A saved form placed here, drawn from the page the app gives for its id
626
+ * with a form of its own inside this one. A quiet placeholder while the
627
+ * page comes; words in its place when it cannot be found, would hold
628
+ * itself, or cannot sit in a form.
629
+ */
630
+ function formItem(node, place) {
631
+ const box = el('fieldset', {
632
+ class: 'fd-section fd-form-part',
633
+ 'data-node': node.id,
634
+ 'data-style': 'card',
635
+ 'data-on-page': place.onPage ? '' : undefined,
636
+ 'aria-busy': 'true',
637
+ });
638
+ spans(box, node.colspan);
639
+ const note = el('p', { class: 'fd-form-part-note' }, labels.loading);
640
+ box.append(note);
641
+ hideWhen(box, node.id);
642
+ const refuse = (words) => {
643
+ box.removeAttribute('aria-busy');
644
+ note.textContent = words;
645
+ note.classList.add('fd-form-part-problem');
646
+ };
647
+ const draw = (found) => {
648
+ if (gone)
649
+ return;
650
+ if (!found)
651
+ return refuse(fill(labels.formMissing, { page: node.page }));
652
+ const saved = shownAs(found);
653
+ const name = saved.title || found.id;
654
+ const at = scope.chain.findIndex((p) => p.id === found.id);
655
+ if (at !== -1)
656
+ return refuse(fill(labels.formInItself, { page: name, chain: [...scope.chain.slice(at).map((p) => p.title), name].join(' → ') }));
657
+ if (found.layout.type !== 'sections' && found.layout.type !== 'tabs')
658
+ return refuse(fill(labels.formNotPlaceable, { page: name }));
659
+ const checked = checkPage(saved);
660
+ let inner;
661
+ try {
662
+ if (!checked.ok)
663
+ throw new Error(checked.issues.map((i) => `${i.path}: ${i.message}`).join('; '));
664
+ inner = form.embed(node.id, saved);
665
+ }
666
+ catch (error) {
667
+ console.warn(`Fieldia: the saved form "${found.id}" cannot be shown: ${error.message}`);
668
+ return refuse(fill(labels.formBroken, { page: name }));
669
+ }
670
+ const title = node.title ?? saved.title ?? '';
671
+ box.setAttribute('data-title', title);
672
+ if (title)
673
+ box.prepend(el('legend', { class: 'fd-section-title' }, ...withIcon(undefined, title)));
674
+ const own = drawer({
675
+ root: false,
676
+ form: inner,
677
+ page: saved,
678
+ prefix: `${scope.prefix}${node.id}-`,
679
+ chain: [...scope.chain, { id: found.id, title: name }],
680
+ locked: () => scope.locked() || form.node(node.id).readonly,
681
+ path: `${scope.path}${node.name}.`,
682
+ });
683
+ const layout = saved.layout;
684
+ // Its parts sit in the part's box: a card there draws none of its own.
685
+ note.replaceWith(own.grid(layout.type === 'tabs' ? [layout] : layout.children, 1, { columns: 1, onPage: false, labels: place.labels }));
686
+ box.removeAttribute('aria-busy');
687
+ cleanups.push(inner.subscribe(renderNow));
688
+ if (mounted)
689
+ renderNow();
690
+ };
691
+ let asked;
692
+ try {
693
+ asked = findPage(options, node.version === undefined ? { id: node.page } : { id: node.page, version: node.version });
694
+ }
695
+ catch {
696
+ asked = null;
697
+ }
698
+ if (asked instanceof Promise)
699
+ asked.then(draw, () => draw(null));
700
+ else
701
+ draw(asked);
702
+ return box;
703
+ }
704
+ return { item, grid, fieldItem, buttonItem, hideWhen, slotItem };
323
705
  }
324
- /** A line across the row, empty room, or a picture: shown and hidden by its rule like any part. */
325
- function blockItem(node) {
326
- const element = node.type === 'divider' ? el('hr', { class: 'fd-divider', 'data-node': node.id })
327
- : node.type === 'spacer' ? el('div', { class: 'fd-block fd-spacer', 'aria-hidden': 'true', 'data-node': node.id })
328
- : figure(node);
329
- if (node.type !== 'divider' && node.colspan)
330
- element.style.setProperty('--fd-span', String(node.colspan));
331
- hideWhen(element, node.id);
332
- return element;
333
- }
334
- /** 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. */
335
- function figure(node) {
336
- const image = el('img', { class: 'fd-image', src: node.src, alt: node.alt, loading: 'lazy' });
337
- const href = node.href && /^(https?:\/\/|mailto:)/i.test(node.href) ? node.href : undefined;
338
- 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)] : []));
339
- const width = typeof node.width === 'number' ? `${node.width}px` : node.width && { small: '160px', medium: '320px', large: '480px', full: '100%' }[node.width];
340
- if (width)
341
- element.style.setProperty('--fd-image-width', width);
342
- return element;
343
- }
706
+ const { item, grid, fieldItem, buttonItem, hideWhen, slotItem } = drawer({
707
+ root: true,
708
+ form,
709
+ page,
710
+ prefix: '',
711
+ chain: [{ id: page.id, title: page.title || page.id }],
712
+ locked: () => false,
713
+ path: '',
714
+ });
344
715
  // ---- shared chrome ----------------------------------------------------------
345
716
  /** The whole form locked: every field read-only, no Save; buttons still run. */
346
717
  let locked = options.readonly === true;
@@ -362,9 +733,12 @@ export function mountViewer(host, options) {
362
733
  else
363
734
  locked = false;
364
735
  root.toggleAttribute('data-readonly', locked);
736
+ // Conditions read `editing`: parts for editing only, or reading only, follow.
737
+ form.setEditing(!locked);
365
738
  render(form.getState());
366
739
  });
367
740
  root.toggleAttribute('data-readonly', locked);
741
+ form.setEditing(!locked);
368
742
  updaters.push(() => {
369
743
  if (!editSwitch)
370
744
  return;
@@ -377,18 +751,27 @@ export function mountViewer(host, options) {
377
751
  retry.addEventListener('click', () => void submitOrSave());
378
752
  const status = el('div', { class: 'fd-status-box' }, statusText, retry);
379
753
  const notDone = () => (page.data.kind === 'responses' ? labels.notSent : labels.notSaved);
380
- /** "Not saved. Check: Email, Phone": the fields with a problem, in the order they show. */
754
+ /**
755
+ * "Not saved. Check: Email, Phone": the fields with a problem, in the order
756
+ * they show; one inside a saved form with that form's title, "Street (Home address)".
757
+ */
381
758
  function checkText(state) {
382
- const names = [];
759
+ const fieldsShown = [...root.querySelectorAll('.fd-field[data-path]')];
760
+ const found = [];
383
761
  for (const key of Object.keys(state.errors)) {
384
- const field = key.split('.')[0];
385
- const shown = root.querySelector(`.fd-field[data-field="${field}"]:not([hidden]) > .fd-label`);
386
- const name = shown?.firstChild?.textContent ?? page.fields[field]?.label ?? field;
387
- if (!names.includes(name))
388
- names.push(name);
389
- }
390
- const inOrder = [...root.querySelectorAll('.fd-field[data-field] > .fd-label')].map((label) => label.firstChild?.textContent ?? '');
391
- names.sort((a, b) => (inOrder.indexOf(a) + 1 || Infinity) - (inOrder.indexOf(b) + 1 || Infinity));
762
+ // The field itself, or — for a line's — the table it is in.
763
+ let shown;
764
+ for (let path = key; path && !shown; path = path.slice(0, Math.max(0, path.lastIndexOf('.')))) {
765
+ shown = fieldsShown.find((field) => field.getAttribute('data-path') === path && !field.hidden);
766
+ }
767
+ const first = key.split('.')[0];
768
+ const label = shown?.querySelector(':scope > .fd-label')?.firstChild?.textContent ?? page.fields[first]?.label ?? first;
769
+ const within = shown?.closest('.fd-form-part')?.getAttribute('data-title');
770
+ const name = within ? `${label} (${within})` : label;
771
+ if (!found.some((f) => f.name === name))
772
+ found.push({ name, at: shown ? fieldsShown.indexOf(shown) : Infinity });
773
+ }
774
+ const names = found.sort((a, b) => a.at - b.at).map((f) => f.name);
392
775
  return names.length ? fill(labels.checkFields, { what: notDone(), fields: names.join(', ') }) : notDone();
393
776
  }
394
777
  let quietTimer;
@@ -453,7 +836,15 @@ export function mountViewer(host, options) {
453
836
  draftText.textContent = fill(labels.draftFound, { time: new Date(state.draft.savedAt).toLocaleString() });
454
837
  });
455
838
  function focusFirstProblem() {
456
- const invalid = root.querySelector('[aria-invalid="true"]');
839
+ // A problem in a tab out of sight, or not drawn yet: its tab shown first, the first such in the page's order.
840
+ const seen = [...root.querySelectorAll('[aria-invalid="true"]')].find((e) => !e.closest('.fd-tabpanel[hidden]'));
841
+ if (!seen) {
842
+ const errors = form.getState().errors;
843
+ const first = [...problemTabs.keys()].find((name) => errors[name]);
844
+ if (first)
845
+ problemTabs.get(first)?.();
846
+ }
847
+ const invalid = [...root.querySelectorAll('[aria-invalid="true"]')].find((e) => !e.closest('.fd-tabpanel[hidden]')) ?? null;
457
848
  if (!invalid)
458
849
  return;
459
850
  for (let folded = invalid.closest('.fd-section-folded'); folded; folded = folded.parentElement?.closest('.fd-section-folded') ?? null) {
@@ -488,6 +879,52 @@ export function mountViewer(host, options) {
488
879
  content.hidden = false;
489
880
  done.hidden = true;
490
881
  });
882
+ /** The record's name, as the last of its breadcrumbs says it: its sheet's title field, else the page's title; empty for a new one. */
883
+ function recordName() {
884
+ const state = form.getState();
885
+ if (state.recordId == null)
886
+ return '';
887
+ const field = page.layout.type === 'sheet' ? page.layout.title?.field : undefined;
888
+ const name = field ? displayValue(page.fields[field], state.values[field], state.values, locale) : '';
889
+ return name || page.title || '';
890
+ }
891
+ /** The bar over a record — its breadcrumbs, its gear menu, its pager — or null when it would hold nothing. */
892
+ function topBar(toolbar) {
893
+ if (page.data.kind !== 'record')
894
+ return null;
895
+ const bar = recordBar({
896
+ doc,
897
+ el,
898
+ form,
899
+ toolbar,
900
+ records: options.records,
901
+ breadcrumbs: options.breadcrumbs,
902
+ labels,
903
+ icons: options.icons,
904
+ uid,
905
+ fill,
906
+ withIcon,
907
+ press,
908
+ name: recordName,
909
+ render: renderNow,
910
+ async leave() {
911
+ if (!form.getState().dirty.length)
912
+ return true;
913
+ const saved = await form.save();
914
+ if (!saved) {
915
+ if (!form.getState().saveProblem)
916
+ announce(checkText(form.getState()));
917
+ focusFirstProblem();
918
+ }
919
+ return saved;
920
+ },
921
+ });
922
+ if (!bar)
923
+ return null;
924
+ updaters.push(bar.update);
925
+ cleanups.push(bar.destroy);
926
+ return bar.element;
927
+ }
491
928
  function pageHead() {
492
929
  if (!page.title && !page.description)
493
930
  return null;
@@ -499,8 +936,20 @@ export function mountViewer(host, options) {
499
936
  return head;
500
937
  }
501
938
  // ---- the four page layouts ---------------------------------------------------
939
+ /**
940
+ * A page's own buttons at its foot, as a wizard's, in place of its Save and
941
+ * Discard; null when it has none, or when a dialog round it draws them.
942
+ */
943
+ function pageFooter(footer) {
944
+ if (!footer?.length || options.showActions === false)
945
+ return null;
946
+ return el('div', { class: 'fd-actions fd-actions-end fd-page-footer' }, status, ...footer.map(buttonItem));
947
+ }
502
948
  function sectionsLayout(node) {
503
949
  const box = el('div', { class: 'fd-sections', 'data-node': node.id }, ...node.children.map((child) => item(child, top(true))));
950
+ const own = pageFooter(node.footer);
951
+ if (own)
952
+ return el('div', {}, box, own);
504
953
  const action = el('button', { type: 'submit', class: 'fd-button fd-button-primary' }, page.data.kind === 'responses' ? labels.submit : labels.save);
505
954
  const actions = el('div', { class: 'fd-actions fd-actions-end' }, status, action);
506
955
  if (page.data.kind === 'record') {
@@ -619,7 +1068,8 @@ export function mountViewer(host, options) {
619
1068
  // Save and Discard lead the header bar, or close the sheet when the page puts them at its foot.
620
1069
  const atFoot = page.actionsPosition === 'bottom';
621
1070
  const foot = el('div', { class: 'fd-actions fd-actions-end fd-sheet-foot' });
622
- if (options.showActions === false)
1071
+ const own = pageFooter(node.footer);
1072
+ if (options.showActions === false || own)
623
1073
  actions.append(...(node.buttons ?? []).map(buttonItem));
624
1074
  else if (atFoot) {
625
1075
  actions.append(...(node.buttons ?? []).map(buttonItem));
@@ -640,31 +1090,89 @@ export function mountViewer(host, options) {
640
1090
  if (node.statusbar && !underTitle)
641
1091
  header.append(statusbar(node.statusbar));
642
1092
  const card = el('div', { class: 'fd-card' });
643
- if (node.ribbon) {
644
- const ribbon = el('div', { class: `fd-ribbon fd-tone-${node.ribbon.tone ?? 'muted'}`, 'data-node': node.ribbon.id }, node.ribbon.label);
645
- hideWhen(ribbon, node.ribbon.id);
646
- // The ribbon is clipped to the card's corner by its own frame, so the card itself never clips: lists open past it.
647
- card.append(el('div', { class: 'fd-ribbon-frame' }, ribbon));
1093
+ const ribbons = [...(node.ribbon ? [node.ribbon] : []), ...(node.ribbons ?? [])];
1094
+ if (ribbons.length) {
1095
+ // The ribbons are clipped to the card's corner by their own frame, so the card itself never clips: lists open past it.
1096
+ const frame = el('div', { class: 'fd-ribbon-frame' });
1097
+ const drawn = ribbons.map((ribbon) => {
1098
+ const element = el('div', { class: `fd-ribbon fd-tone-${ribbon.tone ?? 'muted'}`, 'data-node': ribbon.id, title: ribbon.tooltip }, ribbon.label);
1099
+ frame.append(element);
1100
+ return { ribbon, element };
1101
+ });
1102
+ // One corner, one ribbon: the first whose condition holds; its words from a field when the field holds any.
1103
+ updaters.push((state) => {
1104
+ let shown = false;
1105
+ for (const { ribbon, element } of drawn) {
1106
+ const show = !shown && !form.node(ribbon.id).invisible;
1107
+ shown ||= show;
1108
+ setHidden(element, !show);
1109
+ if (!show)
1110
+ continue;
1111
+ const from = ribbon.labelField ? displayValue(page.fields[ribbon.labelField], state.values[ribbon.labelField], state.values, locale) : '';
1112
+ setText(element, from || ribbon.label);
1113
+ }
1114
+ });
1115
+ card.append(frame);
648
1116
  }
649
1117
  if (node.statButtons?.length) {
650
1118
  const stats = el('div', { class: 'fd-stats' });
1119
+ /** A field's value as the field shows it: money with its currency, a date, a count grouped. */
1120
+ const shownValue = (name, values) => name && page.fields[name] ? displayValue(page.fields[name], values[name], values, locale) : '';
651
1121
  for (const stat of node.statButtons) {
652
1122
  const value = el('span', { class: 'fd-stat-value' });
1123
+ const label = el('span', { class: 'fd-stat-label' }, stat.label);
1124
+ // A second value with words of its own: the two one over the other, each after its words.
1125
+ const second = stat.secondField && stat.secondLabel !== undefined ? { value: el('span', { class: 'fd-stat-value' }), label: el('span', { class: 'fd-stat-label' }, stat.secondLabel) } : null;
653
1126
  const icon = drawIcon(doc, stat.icon, options.icons);
654
- const words = el('span', { class: 'fd-stat-words' }, value, el('span', { class: 'fd-stat-label' }, stat.label));
655
- const button = el('button', { type: 'button', class: 'fd-stat', 'data-node': stat.id }, ...(icon ? [icon, words] : [words]));
656
- button.addEventListener('click', () => void form.runAction(stat.id));
1127
+ const words = second
1128
+ ? el('span', { class: 'fd-stat-words fd-stat-pair' }, el('span', { class: 'fd-stat-row' }, label, value), el('span', { class: 'fd-stat-row' }, second.label, second.value))
1129
+ : el('span', { class: 'fd-stat-words' }, value, label);
1130
+ // Its help, as Flectra's help=: its tooltip, and its description for a screen reader — never its name.
1131
+ const helpId = stat.help ? uid(`${stat.id}-help`) : undefined;
1132
+ const button = el('button', { type: 'button', class: 'fd-stat', 'data-node': stat.id, title: stat.help || undefined, 'aria-describedby': helpId }, ...(icon ? [icon, words] : [words]));
1133
+ if (helpId)
1134
+ stats.append(el('span', { class: 'fd-sr-only', id: helpId }, stat.help));
1135
+ button.addEventListener('click', () => void press(button, () => form.runAction(stat.id)));
657
1136
  updaters.push((state) => {
658
1137
  button.hidden = form.node(stat.id).invisible;
659
- const count = stat.field ? state.values[stat.field] : null;
660
- value.textContent = count === null || count === undefined ? '' : String(count);
1138
+ const values = state.values;
1139
+ const unit = shownValue(stat.unitField, values) || stat.unit || '';
1140
+ const first = shownValue(stat.field, values);
1141
+ const other = shownValue(stat.secondField, values);
1142
+ if (second) {
1143
+ setText(value, first);
1144
+ setText(second.value, [other, unit].filter(Boolean).join(' '));
1145
+ }
1146
+ else
1147
+ setText(value, [[first, other].filter(Boolean).join(' / '), first || other ? unit : ''].filter(Boolean).join(' '));
1148
+ setText(label, shownValue(stat.labelField, values) || stat.label);
661
1149
  });
662
1150
  stats.append(button);
663
1151
  }
1152
+ // No empty row while every button is hidden, as with the badges.
1153
+ updaters.push(() => {
1154
+ stats.hidden = [...stats.querySelectorAll(':scope > .fd-stat')].every((stat) => stat.hidden);
1155
+ });
664
1156
  card.append(stats);
665
1157
  }
666
1158
  for (const alert of node.alerts ?? []) {
667
- const box = el('div', { class: `fd-alert fd-tone-${alert.tone ?? 'info'}`, role: 'status', 'data-node': alert.id }, el('span', { class: 'fd-alert-message' }, alert.message));
1159
+ // Its words with the values they name, or a field's words while it holds any; its buttons after them, as links unless styled.
1160
+ const words = valueWords(doc, page.fields, alert.message, locale);
1161
+ const message = el('span', { class: 'fd-alert-message' }, ...words.nodes);
1162
+ let fromField = false;
1163
+ const box = el('div', { class: `fd-alert fd-tone-${alert.tone ?? 'info'}`, role: 'status', 'data-node': alert.id }, message);
1164
+ if (alert.buttons?.length)
1165
+ box.append(el('span', { class: 'fd-alert-actions' }, ...alert.buttons.map((button) => buttonItem({ ...button, style: button.style ?? 'link' }))));
1166
+ updaters.push((state) => {
1167
+ words.update(state.values);
1168
+ const from = alert.messageField ? state.values[alert.messageField] : null;
1169
+ const said = typeof from === 'string' ? from.trim() : '';
1170
+ if (said)
1171
+ setText(message, said);
1172
+ else if (fromField)
1173
+ message.replaceChildren(...words.nodes);
1174
+ fromField = !!said;
1175
+ });
668
1176
  if (alert.dismissible) {
669
1177
  // Closed, it stays closed while the page is open, whatever its condition does.
670
1178
  let dismissed = false;
@@ -696,9 +1204,26 @@ export function mountViewer(host, options) {
696
1204
  }
697
1205
  if (node.title) {
698
1206
  const title = el('div', { class: 'fd-title' });
1207
+ // Words over the title, as Flectra's "Product Name" over its h1, naming its box.
1208
+ if (node.title.label)
1209
+ title.append(el('label', { class: 'fd-title-label', for: uid('#title') }, node.title.label));
699
1210
  if (node.title.above?.length)
700
1211
  title.append(el('div', { class: 'fd-title-above' }, ...node.title.above.map((part) => fieldItem(part))));
701
- title.append(fieldItem({ type: 'field', id: '#title', field: node.title.field, placeholder: node.title.placeholder }));
1212
+ const name = fieldItem({ type: 'field', id: '#title', field: node.title.field, placeholder: node.title.placeholder, ...(node.title.placeholderWhen ? { placeholderWhen: node.title.placeholderWhen } : {}), ...(node.title.focus ? { focus: true } : {}) });
1213
+ // Fields on the title's line, before and after it: a priority star, a state's dot (Flectra's <h1>).
1214
+ const before = node.title.before ?? [];
1215
+ const after = node.title.after ?? [];
1216
+ if (before.length || after.length) {
1217
+ name.classList.add('fd-title-name');
1218
+ const side = (part) => {
1219
+ const item = fieldItem(part);
1220
+ item.classList.add('fd-title-side');
1221
+ return item;
1222
+ };
1223
+ title.append(el('div', { class: 'fd-title-line' }, ...before.map(side), name, ...after.map(side)));
1224
+ }
1225
+ else
1226
+ title.append(name);
702
1227
  if (node.title.subtitleField)
703
1228
  title.append(fieldItem({ type: 'field', id: '#subtitle', field: node.title.subtitleField }));
704
1229
  if (node.title.below?.length)
@@ -714,6 +1239,8 @@ export function mountViewer(host, options) {
714
1239
  if (node.statusbar && underTitle)
715
1240
  card.append(el('div', { class: 'fd-title-statusbar' }, statusbar(node.statusbar)));
716
1241
  card.append(grid(node.children, 1, top(false)));
1242
+ if (own)
1243
+ card.append(own);
717
1244
  if (atFoot && options.showActions !== false) {
718
1245
  card.append(foot);
719
1246
  updaters.push((state) => {
@@ -721,11 +1248,22 @@ export function mountViewer(host, options) {
721
1248
  });
722
1249
  }
723
1250
  const layout = el('div', { class: 'fd-sheet-layout' }, card);
1251
+ if (node.attachmentPreview) {
1252
+ // Beside the sheet on a wide form, the side panel then under the sheet; under the sheet on a narrow one.
1253
+ const preview = attachmentPreview({ doc, el, form, page, node: node.attachmentPreview, dataSource: options.dataSource, labels, fill });
1254
+ layout.classList.add('fd-has-preview');
1255
+ layout.append(preview.element);
1256
+ updaters.push(preview.update);
1257
+ cleanups.push(preview.destroy);
1258
+ }
724
1259
  if (node.sidePanel) {
725
1260
  layout.classList.add('fd-has-side');
1261
+ if (node.sidePanelBeside)
1262
+ layout.setAttribute('data-side-beside', node.sidePanelBeside);
726
1263
  layout.append(el('aside', { class: 'fd-side' }, slotItem(node.sidePanel)));
727
1264
  }
728
- pageBox.append(header, layout);
1265
+ const bar = topBar(node.toolbar);
1266
+ pageBox.append(...(bar ? [bar] : []), header, layout);
729
1267
  return pageBox;
730
1268
  }
731
1269
  /** The sheet header's statusbar: the same widget a form can place anywhere. */
@@ -734,9 +1272,18 @@ export function mountViewer(host, options) {
734
1272
  const barOptions = { clickable: config.clickable === true };
735
1273
  if (config.visibleStates)
736
1274
  barOptions['visibleStates'] = config.visibleStates;
1275
+ for (const key of ['durationsField', 'fold', 'saves'])
1276
+ if (config[key] !== undefined)
1277
+ barOptions[key] = config[key];
737
1278
  const node = { type: 'field', id: '#statusbar', field: config.field, widget: 'statusbar', options: barOptions };
738
1279
  const widget = createWidget({ form, name: config.field, field: def, node, id: uid('statusbar'), document: doc, labels: widgetLabels, preferences, locale, dialogs }, options.widgets);
739
- updaters.push((state) => widget.update({ value: state.values[config.field], values: state.values, readonly: form.node('#statusbar').readonly || locked, required: false, invalid: false }));
1280
+ if (widget.destroy)
1281
+ cleanups.push(() => widget.destroy?.());
1282
+ updaters.push((state) => {
1283
+ // Hidden while its own condition holds, or from people outside its roles.
1284
+ setHidden(widget.element, form.node('#statusbar').invisible);
1285
+ widget.update({ value: state.values[config.field], values: state.values, readonly: form.node('#statusbar').readonly || locked, required: false, invalid: false });
1286
+ });
740
1287
  return widget.element;
741
1288
  }
742
1289
  let wizardForward = null;
@@ -759,12 +1306,13 @@ export function mountViewer(host, options) {
759
1306
  labels,
760
1307
  locale,
761
1308
  fill,
762
- confirm,
1309
+ press,
763
1310
  withIcon,
764
1311
  uid,
765
1312
  icons: options.icons,
766
1313
  preferences,
767
1314
  onOpenRecord: options.onOpenRecord,
1315
+ ...(options.listFilter ? { fixedFilter: options.listFilter } : {}),
768
1316
  });
769
1317
  cleanups.push(list.destroy);
770
1318
  body = list.element;
@@ -772,7 +1320,9 @@ export function mountViewer(host, options) {
772
1320
  else
773
1321
  body = sectionsLayout(layout);
774
1322
  const head = layout.type === 'sheet' ? null : pageHead();
775
- content.append(...(head ? [head] : []), banner, draft, body);
1323
+ // A record of sections or tabs has the bar the app fills — its breadcrumbs and pager — over its title.
1324
+ const bar = layout.type === 'sections' || layout.type === 'tabs' ? topBar(undefined) : null;
1325
+ content.append(...(bar ? [bar] : []), ...(head ? [head] : []), banner, draft, body);
776
1326
  root.append(content, done, announcer);
777
1327
  // The status leaves its place beside Save when the page wants it in a corner or across the top.
778
1328
  if (options.saveStatus === 'toast') {
@@ -847,6 +1397,46 @@ export function mountViewer(host, options) {
847
1397
  event.preventDefault();
848
1398
  nextField(from)?.focus();
849
1399
  });
1400
+ // ---- a button's key, with Alt -------------------------------------------------
1401
+ /**
1402
+ * Whether a key pressed with Alt is this form's: pressed in it (not in a
1403
+ * form inside it, such as a dialog's), or — pressed outside any form — this
1404
+ * is the first form on the page, or in the question or dialog on top of it.
1405
+ */
1406
+ function hotkeysHere(target) {
1407
+ const inner = target instanceof Element ? target.closest('.fd-form') : null;
1408
+ if (inner)
1409
+ return inner === root && !root.querySelector(':scope > .fd-dialog-backdrop');
1410
+ const modals = [...doc.querySelectorAll('[aria-modal="true"]')].filter((modal) => !modal.closest('[hidden]'));
1411
+ const top = modals[modals.length - 1];
1412
+ return (top ?? doc).querySelector('.fd-form') === root;
1413
+ }
1414
+ const onHotkey = (event) => {
1415
+ if (event.key === 'Alt') {
1416
+ if (hotkeysHere(event.target))
1417
+ root.setAttribute('data-hotkeys', '');
1418
+ return;
1419
+ }
1420
+ const key = hotkeyOf(event);
1421
+ if (!key || !hotkeysHere(event.target))
1422
+ return;
1423
+ const button = [...root.querySelectorAll(`button[data-hotkey="${key}"]`)].find((b) => b.closest('.fd-form') === root && !b.closest('[hidden]') && !b.disabled && !b.hasAttribute('aria-busy'));
1424
+ if (!button)
1425
+ return;
1426
+ event.preventDefault();
1427
+ root.removeAttribute('data-hotkeys');
1428
+ button.click();
1429
+ };
1430
+ const offHotkeys = () => root.removeAttribute('data-hotkeys');
1431
+ const altUp = (event) => event.key === 'Alt' && offHotkeys();
1432
+ doc.addEventListener('keydown', onHotkey);
1433
+ doc.addEventListener('keyup', altUp);
1434
+ doc.defaultView?.addEventListener('blur', offHotkeys);
1435
+ cleanups.push(() => {
1436
+ doc.removeEventListener('keydown', onHotkey);
1437
+ doc.removeEventListener('keyup', altUp);
1438
+ doc.defaultView?.removeEventListener('blur', offHotkeys);
1439
+ });
850
1440
  // ---- confirmation dialog -----------------------------------------------------
851
1441
  /** A question with Cancel and OK, or with `withCancel` false a notice with OK alone. */
852
1442
  function dialogConfirm(message, withCancel = true) {
@@ -868,9 +1458,13 @@ export function mountViewer(host, options) {
868
1458
  };
869
1459
  cancel.addEventListener('click', () => close(false));
870
1460
  ok.addEventListener('click', () => close(true));
1461
+ // Its keys are its own: Escape answers No here, and closes no dialog or panel under it.
871
1462
  backdrop.addEventListener('keydown', (event) => {
872
- if (event.key === 'Escape')
1463
+ event.stopPropagation();
1464
+ if (event.key === 'Escape') {
1465
+ event.preventDefault();
873
1466
  close(false);
1467
+ }
874
1468
  else
875
1469
  keepTabIn(dialog, event);
876
1470
  });
@@ -885,7 +1479,31 @@ export function mountViewer(host, options) {
885
1479
  }
886
1480
  host.append(root);
887
1481
  const unsubscribe = form.subscribe(render);
1482
+ // 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.
1483
+ cleanups.push(form.on('run', ({ result }) => {
1484
+ if (result.reason === 'cannot' || (result.reason === 'app' && result.error !== undefined))
1485
+ actionHost.say(result.message ?? '', result.reason === 'app' ? 'danger' : 'warning');
1486
+ }));
888
1487
  render(form.getState());
1488
+ mounted = true;
1489
+ // As the record opens, its focused field takes the focus — the first shown — unless the person is busy elsewhere:
1490
+ // only while nothing has the focus, or, the first time, while it is in this form (a dialog's first box).
1491
+ let opened = false;
1492
+ if (focusers.length) {
1493
+ cleanups.push(form.on('open', () => {
1494
+ const first = !opened;
1495
+ opened = true;
1496
+ queueMicrotask(() => {
1497
+ if (gone || !root.isConnected || root.closest('[hidden]') || (typeof root.checkVisibility === 'function' && !root.checkVisibility()))
1498
+ return;
1499
+ const active = doc.activeElement;
1500
+ const free = !active || active === doc.body || active === doc.documentElement;
1501
+ if (!free && !(first && root.contains(active)))
1502
+ return;
1503
+ focusers.find((one) => !one.wrapper.closest('[hidden]'))?.focus();
1504
+ });
1505
+ }));
1506
+ }
889
1507
  if (form.getState().status === 'idle')
890
1508
  void form.load();
891
1509
  return {
@@ -909,10 +1527,19 @@ export function mountViewer(host, options) {
909
1527
  setReadonly(readonly) {
910
1528
  locked = readonly;
911
1529
  root.toggleAttribute('data-readonly', locked);
1530
+ form.setEditing(!locked);
912
1531
  render(form.getState());
913
1532
  },
914
1533
  isReadonly: () => locked,
1534
+ on: (event, listener) => {
1535
+ const off = form.on(event, listener);
1536
+ cleanups.push(off);
1537
+ return off;
1538
+ },
1539
+ setValues: (values) => form.setValues(values),
1540
+ run: (steps, context) => form.run(steps, context),
915
1541
  destroy() {
1542
+ gone = true;
916
1543
  unsubscribe();
917
1544
  for (const cleanup of cleanups)
918
1545
  cleanup();