@zeyos/zx 5.6.0 → 5.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +188 -0
- package/README.md +73 -7
- package/bin/zx-css.js +328 -0
- package/dist/types/components/account-menu/account-menu.d.ts +4 -2
- package/dist/types/components/activity-list/activity-list.d.ts +14 -8
- package/dist/types/components/agent-thread/ag-ui.d.ts +340 -0
- package/dist/types/components/agent-thread/agent-thread.d.ts +142 -14
- package/dist/types/components/agent-thread/ui-message-stream.d.ts +401 -0
- package/dist/types/components/app-sidebar/app-sidebar.d.ts +14 -8
- package/dist/types/components/breadcrumb/breadcrumb.d.ts +3 -3
- package/dist/types/components/calendar/calendar-model.d.ts +9 -2
- package/dist/types/components/calendar/calendar.d.ts +12 -4
- package/dist/types/components/chart/chart.d.ts +25 -13
- package/dist/types/components/checklist/checklist.d.ts +29 -0
- package/dist/types/components/code-editor/code-editor.d.ts +7 -2
- package/dist/types/components/composer/composer.d.ts +206 -4
- package/dist/types/components/composer/queue.d.ts +76 -0
- package/dist/types/components/copy/copy-button.d.ts +6 -4
- package/dist/types/components/copy/copy-input.d.ts +10 -6
- package/dist/types/components/datebox/date-range-box.d.ts +33 -0
- package/dist/types/components/datebox/placeholder.d.ts +7 -0
- package/dist/types/components/dialog/dialog.d.ts +2 -2
- package/dist/types/components/dock/dock.d.ts +12 -3
- package/dist/types/components/entity-ref/entity-ref.d.ts +5 -3
- package/dist/types/components/field-upload/field-upload.d.ts +3 -2
- package/dist/types/components/file-item/file-item.d.ts +3 -2
- package/dist/types/components/file-list/file-list.d.ts +14 -8
- package/dist/types/components/filter/filter-model.d.ts +31 -1
- package/dist/types/components/filter/filter.d.ts +20 -2
- package/dist/types/components/finder/finder.d.ts +14 -6
- package/dist/types/components/flag/flag.d.ts +99 -0
- package/dist/types/components/grid/grid.d.ts +1 -1
- package/dist/types/components/kanban-view/kanban-view.d.ts +8 -66
- package/dist/types/components/launcher/launcher.d.ts +2 -0
- package/dist/types/components/modal/modal.d.ts +34 -8
- package/dist/types/components/multi-value-editor/multi-value-editor.d.ts +3 -2
- package/dist/types/components/number-field/number-field.d.ts +41 -7
- package/dist/types/components/prompt-starters/prompt-starters.d.ts +107 -0
- package/dist/types/components/prose/prose.d.ts +9 -6
- package/dist/types/components/questionnaire/conditions.d.ts +270 -0
- package/dist/types/components/questionnaire/items.d.ts +52 -30
- package/dist/types/components/questionnaire/questionnaire.d.ts +44 -4
- package/dist/types/components/rating/rating.d.ts +5 -3
- package/dist/types/components/select/country.d.ts +106 -0
- package/dist/types/components/select/field-adapter.d.ts +2 -1
- package/dist/types/components/select/locale.d.ts +102 -0
- package/dist/types/components/select/select.d.ts +41 -2
- package/dist/types/components/sheet/sheet.d.ts +2 -2
- package/dist/types/components/slider/slider.d.ts +1 -0
- package/dist/types/components/sort-control/sort-control.d.ts +7 -3
- package/dist/types/components/source-list/source-list.d.ts +7 -5
- package/dist/types/components/split-view/split-view.d.ts +5 -3
- package/dist/types/components/surface/catalog.d.ts +260 -0
- package/dist/types/components/surface/elicit.d.ts +81 -0
- package/dist/types/components/surface/mcp.d.ts +165 -0
- package/dist/types/components/surface/schema.d.ts +314 -0
- package/dist/types/components/surface/stream.d.ts +118 -0
- package/dist/types/components/surface/surface.d.ts +718 -0
- package/dist/types/components/surface/text.d.ts +277 -0
- package/dist/types/components/surface/validate.d.ts +339 -0
- package/dist/types/components/table/table.d.ts +55 -3
- package/dist/types/components/table/window.d.ts +203 -0
- package/dist/types/components/toolbar/toolbar.d.ts +10 -6
- package/dist/types/components/tooltip/tooltip.d.ts +2 -2
- package/dist/types/components/tree/tree.d.ts +20 -13
- package/dist/types/core/component.d.ts +10 -0
- package/dist/types/core/date.d.ts +8 -1
- package/dist/types/core/dom.d.ts +15 -0
- package/dist/types/core/http.d.ts +10 -0
- package/dist/types/core/i18n.d.ts +38 -0
- package/dist/types/core/messages.d.ts +344 -1
- package/dist/types/core/storage.d.ts +7 -2
- package/dist/types/elements/define.d.ts +21 -46
- package/dist/types/elements/definitions.d.ts +147 -0
- package/dist/types/elements/kit.d.ts +7 -0
- package/dist/types/elements/reflect.d.ts +6 -3
- package/dist/types/index.d.ts +10 -1
- package/dist/types/internal/date-locale.d.ts +7 -0
- package/dist/types/internal/json-patch.d.ts +146 -0
- package/dist/types/locales/de.d.ts +13 -0
- package/dist/types/locales/en.d.ts +2 -0
- package/dist/types/locales/index.d.ts +823 -0
- package/dist/types/zeyos/view.d.ts +8 -1
- package/dist/zx-zeyos.esm.js +16852 -15131
- package/dist/zx-zeyos.esm.min.js +5 -5
- package/dist/zx.core.css +1276 -0
- package/dist/zx.core.min.css +1 -0
- package/dist/zx.css +520 -143
- package/dist/zx.esm.js +40940 -29684
- package/dist/zx.esm.min.js +36 -23
- package/dist/zx.global.js +40940 -29684
- package/dist/zx.global.min.js +36 -23
- package/dist/zx.layered.css +17315 -0
- package/dist/zx.layered.min.css +1 -0
- package/dist/zx.min.css +1 -1
- package/docs/agent-catalog.json +12501 -0
- package/docs/agent-surfaces.md +340 -0
- package/docs/api.json +909 -137
- package/docs/llms.md +1046 -80
- package/docs/llms.txt +30 -9
- package/package.json +29 -6
- package/src/components/account-menu/account-menu.js +6 -3
- package/src/components/activity-item/activity-item.js +2 -1
- package/src/components/activity-list/activity-list.js +16 -10
- package/src/components/agent-thread/ag-ui.js +1439 -0
- package/src/components/agent-thread/agent-thread.js +359 -54
- package/src/components/agent-thread/ui-message-stream.js +1281 -0
- package/src/components/app-sidebar/app-sidebar.js +18 -8
- package/src/components/approval-card/approval-card.js +3 -2
- package/src/components/block-view/block-view.js +7 -6
- package/src/components/breadcrumb/breadcrumb.js +8 -5
- package/src/components/button/button.css +24 -11
- package/src/components/calendar/calendar-model.js +8 -2
- package/src/components/calendar/calendar.js +53 -18
- package/src/components/chart/chart.js +54 -23
- package/src/components/checklist/checklist.css +9 -1
- package/src/components/checklist/checklist.js +59 -3
- package/src/components/checklist/field-adapter.js +2 -11
- package/src/components/code-editor/code-editor.js +45 -8
- package/src/components/code-editor/field-adapter.js +1 -1
- package/src/components/composer/composer.css +80 -1
- package/src/components/composer/composer.js +390 -16
- package/src/components/composer/queue.js +78 -0
- package/src/components/context-menu/context-menu.js +12 -1
- package/src/components/copy/copy-button.js +9 -7
- package/src/components/copy/copy-input.js +10 -6
- package/src/components/date-picker/date-picker.js +2 -1
- package/src/components/date-picker/date-range-picker.js +8 -7
- package/src/components/datebox/date-range-box.js +3 -9
- package/src/components/datebox/datebox.js +18 -21
- package/src/components/datebox/placeholder.js +18 -0
- package/src/components/dialog/dialog.js +4 -5
- package/src/components/dock/dock.js +34 -13
- package/src/components/entity-ref/entity-ref.js +16 -5
- package/src/components/field-upload/field-upload.js +81 -38
- package/src/components/file-item/file-item.js +70 -40
- package/src/components/file-list/file-list.js +15 -9
- package/src/components/filter/filter-model.js +46 -8
- package/src/components/filter/filter.css +3 -3
- package/src/components/filter/filter.js +29 -10
- package/src/components/filter-panel/filter-panel.js +13 -5
- package/src/components/finder/finder.js +50 -26
- package/src/components/flag/flag.css +40 -0
- package/src/components/flag/flag.js +177 -0
- package/src/components/form/form.js +1 -1
- package/src/components/grid/grid.js +22 -8
- package/src/components/kanban-view/kanban-view.js +51 -81
- package/src/components/launcher/launcher.js +17 -2
- package/src/components/list-toolbar/list-toolbar.js +2 -1
- package/src/components/master-panel/master-panel.js +1 -1
- package/src/components/menu-button/menu-button.js +4 -0
- package/src/components/message/message.js +3 -0
- package/src/components/modal/modal.js +62 -8
- package/src/components/multi-value-editor/multi-value-editor.js +10 -9
- package/src/components/navigation-bar/navigation-bar.js +3 -3
- package/src/components/number-field/number-field.js +98 -29
- package/src/components/prompt-starters/prompt-starters.css +91 -0
- package/src/components/prompt-starters/prompt-starters.js +206 -0
- package/src/components/prose/prose.js +14 -10
- package/src/components/questionnaire/conditions.js +666 -0
- package/src/components/questionnaire/items.js +150 -41
- package/src/components/questionnaire/questionnaire.js +126 -32
- package/src/components/rating/rating.js +5 -4
- package/src/components/run-status/run-status.js +2 -2
- package/src/components/select/country.js +136 -0
- package/src/components/select/field-adapter.js +7 -2
- package/src/components/select/locale.js +219 -0
- package/src/components/select/select.css +20 -22
- package/src/components/select/select.js +94 -12
- package/src/components/sheet/sheet-stack.js +10 -1
- package/src/components/sheet/sheet.js +12 -5
- package/src/components/slider/slider.js +7 -2
- package/src/components/sort-control/sort-control.js +15 -5
- package/src/components/source-list/source-list.js +7 -4
- package/src/components/split-view/split-view.js +5 -3
- package/src/components/surface/catalog.js +1334 -0
- package/src/components/surface/elicit.js +107 -0
- package/src/components/surface/mcp.js +243 -0
- package/src/components/surface/schema.js +644 -0
- package/src/components/surface/stream.js +245 -0
- package/src/components/surface/surface.css +308 -0
- package/src/components/surface/surface.js +2291 -0
- package/src/components/surface/text.js +513 -0
- package/src/components/surface/validate.js +2218 -0
- package/src/components/tabbox/tabbox.js +9 -0
- package/src/components/table/table.css +63 -3
- package/src/components/table/table.js +167 -28
- package/src/components/table/window.js +317 -0
- package/src/components/toolbar/toolbar.js +12 -7
- package/src/components/tooltip/tooltip.css +2 -3
- package/src/components/tooltip/tooltip.js +32 -5
- package/src/components/tree/tree.js +53 -23
- package/src/core/component.js +25 -1
- package/src/core/date.js +62 -16
- package/src/core/dom.js +67 -4
- package/src/core/format.js +15 -13
- package/src/core/http.js +29 -20
- package/src/core/i18n.js +83 -10
- package/src/core/icons.js +13 -2
- package/src/core/keyboard.js +79 -8
- package/src/core/messages.js +376 -2
- package/src/core/overlay-host.js +1 -0
- package/src/core/position.js +3 -2
- package/src/core/storage.js +59 -6
- package/src/elements/define.js +178 -130
- package/src/elements/definitions.js +229 -0
- package/src/elements/kit.js +444 -0
- package/src/elements/reflect.js +8 -3
- package/src/index.js +10 -1
- package/src/internal/date-locale.js +11 -0
- package/src/internal/json-patch.js +405 -0
- package/src/locales/de.js +911 -0
- package/src/locales/en.js +2 -0
- package/src/locales/index.js +7 -0
- package/src/zeyos/calendar.js +2 -1
- package/src/zeyos/form.js +2 -1
- package/src/zeyos/launcher.js +7 -6
- package/src/zeyos/module-bar.js +2 -1
- package/src/zeyos/schema.js +37 -23
- package/src/zeyos/select.js +4 -3
- package/src/zeyos/table.js +2 -13
- package/src/zeyos/view.js +57 -17
- package/styles/core.css +11 -0
- package/styles/tokens/semantic.css +1 -0
- package/styles/zeyos.css +2 -0
- package/styles/zx.css +4 -8
- package/styles/zx.layered.css +1 -0
|
@@ -0,0 +1,2291 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import { Component } from '../../core/component.js';
|
|
3
|
+
import { h, restoreTarget, safeHref, snapshotTarget } from '../../core/dom.js';
|
|
4
|
+
import { icon } from '../../core/icons.js';
|
|
5
|
+
import { uid } from '../../core/util.js';
|
|
6
|
+
import { isEmptyAnswer } from '../questionnaire/conditions.js';
|
|
7
|
+
import { badge } from '../badge/badge.js';
|
|
8
|
+
import { renderBlocks } from '../block-view/block-view.js';
|
|
9
|
+
import { button } from '../button/button.js';
|
|
10
|
+
import { Chart } from '../chart/chart.js';
|
|
11
|
+
import { registerChecklistFieldAdapter } from '../checklist/field-adapter.js';
|
|
12
|
+
import { registerDateboxFieldAdapters } from '../datebox/field-adapter.js';
|
|
13
|
+
import { Dialog } from '../dialog/dialog.js';
|
|
14
|
+
import { emptyState } from '../empty-state/empty-state.js';
|
|
15
|
+
import { EntityRef } from '../entity-ref/entity-ref.js';
|
|
16
|
+
import { Field } from '../field/field.js';
|
|
17
|
+
import { Fieldset } from '../fieldset/fieldset.js';
|
|
18
|
+
import { Groupbox } from '../groupbox/groupbox.js';
|
|
19
|
+
import { grid, stack } from '../layout/layout.js';
|
|
20
|
+
import { registerNumberFieldAdapter } from '../number-field/field-adapter.js';
|
|
21
|
+
import { Questionnaire, ruleText } from '../questionnaire/questionnaire.js';
|
|
22
|
+
import { registerRatingFieldAdapter } from '../rating/field-adapter.js';
|
|
23
|
+
import { registerSelectFieldAdapter } from '../select/field-adapter.js';
|
|
24
|
+
import { Sheet } from '../sheet/sheet.js';
|
|
25
|
+
import { skeletonText } from '../skeleton/skeleton.js';
|
|
26
|
+
import { registerSliderFieldAdapter } from '../slider/field-adapter.js';
|
|
27
|
+
import { StatTile } from '../stat-tile/stat-tile.js';
|
|
28
|
+
import { Table } from '../table/table.js';
|
|
29
|
+
import { registerTagPickerFieldAdapter } from '../tag-picker/field-adapter.js';
|
|
30
|
+
import { registerToggleFieldAdapter } from '../toggle/field-adapter.js';
|
|
31
|
+
import { assertCatalog, CATALOG, ID_PATTERN, LIMITS, REPLY_VERSION, SURFACE_VERSION } from './catalog.js';
|
|
32
|
+
import { checkValue, schemaToFields, toJsonValue } from './schema.js';
|
|
33
|
+
import { lineSplitter } from './stream.js';
|
|
34
|
+
import {
|
|
35
|
+
CLOSING_ACTIONS, createReply, inputNames, localDateTime, readProp, surfaceVisibility, verdictText, visibleSteps
|
|
36
|
+
} from './text.js';
|
|
37
|
+
import {
|
|
38
|
+
cellLimitMessage, createValidationState, describeValue, tableCells, validateDocument, validateOp, validateValue
|
|
39
|
+
} from './validate.js';
|
|
40
|
+
import { dateLocale } from '../../internal/date-locale.js';
|
|
41
|
+
|
|
42
|
+
/** @typedef {import('./catalog.js').SurfaceCatalog} SurfaceCatalog */
|
|
43
|
+
/** @typedef {import('./catalog.js').SurfaceIntent} SurfaceIntent */
|
|
44
|
+
/** @typedef {import('./catalog.js').SurfacePlacement} SurfacePlacement */
|
|
45
|
+
/** @typedef {import('./validate.js').SurfaceDocument} SurfaceDocument */
|
|
46
|
+
/** @typedef {import('./validate.js').SurfaceNode} SurfaceNode */
|
|
47
|
+
/** @typedef {import('./validate.js').SurfaceOp} SurfaceOp */
|
|
48
|
+
/** @typedef {import('./validate.js').SurfaceAction} SurfaceAction */
|
|
49
|
+
/** @typedef {import('./validate.js').SurfaceError} SurfaceError */
|
|
50
|
+
/** @typedef {import('./validate.js').SurfaceSource} SurfaceSource */
|
|
51
|
+
/** @typedef {import('./text.js').SurfaceReply} SurfaceReply */
|
|
52
|
+
/** @typedef {import('./text.js').ReplyReason} ReplyReason */
|
|
53
|
+
/** @typedef {import('../chart/chart.js').ChartAdapter} ChartAdapter */
|
|
54
|
+
/** @typedef {import('../entity-ref/entity-ref.js').EntityRefOptions} EntityRefOptions */
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* How an action must be confirmed before it replies: not at all, by a click in a confirmation
|
|
58
|
+
* dialog, by typing a text, or not at all because it is removed.
|
|
59
|
+
* @typedef {'allow'|'confirm'|'type-to-confirm'|'deny'} PolicyLevel
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* What a policy returns: a level, or a level with the text to type and the dialog's message.
|
|
64
|
+
* @typedef {PolicyLevel|{level: PolicyLevel, confirmText?: string, message?: string}} PolicyDecision
|
|
65
|
+
*/
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The application's say over each action. It receives a copy of the action — its `id`, `label`,
|
|
69
|
+
* `kind`, `tool` and `description` — and the surface as it stands, and decides what the action
|
|
70
|
+
* needs. It is asked for every action except the built-in Cancel, which only closes. It answers
|
|
71
|
+
* synchronously: nothing waits for it, so a Promise denies the action, as a policy that throws
|
|
72
|
+
* does. Anything else it returns that is not a decision counts as `confirm`.
|
|
73
|
+
* @typedef {(action: SurfaceAction, surface: SurfaceDocument) => PolicyDecision} SurfacePolicy
|
|
74
|
+
*/
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* How the application resolves what a surface may only name.
|
|
78
|
+
* @typedef {Object} SurfaceResolve
|
|
79
|
+
* @property {(ref: {$ref: string, id: string}) => EntityRefOptions|null|undefined} [ref] A record
|
|
80
|
+
* to the options of the EntityRef that draws it; `null` draws its id as text.
|
|
81
|
+
* @property {(href: string, context: {text: string}) => string|boolean|null|undefined} [link] A
|
|
82
|
+
* link's address to the address to open: `false` or `null` refuses it, and the text is shown
|
|
83
|
+
* without a link; `true` or nothing keeps it.
|
|
84
|
+
* @property {(asset: {$asset: string}) => string|null} [asset] An asset name to an image address
|
|
85
|
+
* the application serves. No node of the current catalog shows one; reserved.
|
|
86
|
+
* @property {Iterable<string>|null} [entities] The record entities `{"$ref": …}` may name; without
|
|
87
|
+
* them every record is refused.
|
|
88
|
+
*/
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @typedef {Object} SurfaceOptions
|
|
92
|
+
* @property {SurfaceDocument|Record<string, unknown>|null} [document=null] A whole surface, as the
|
|
93
|
+
* `show_surface` and `ask_user` tools take it. Leave it out to stream with `apply()` or `write()`.
|
|
94
|
+
* @property {SurfacePolicy|null} [policy=null] What each action needs before it replies; every
|
|
95
|
+
* action is allowed when null. Nothing in a surface can lower what it decides.
|
|
96
|
+
* @property {SurfaceResolve} [resolve={}] How records, links and assets are resolved.
|
|
97
|
+
* @property {Record<string, {name: string}>} [authors={}] Who may compose a surface, by the key
|
|
98
|
+
* its `author` names; the byline shows the name, or the key when it is not listed.
|
|
99
|
+
* @property {boolean} [userInitiated=false] Whether the surface answers the person's latest
|
|
100
|
+
* message; only then may `openSurface()` honour a request for a sheet or a dialog.
|
|
101
|
+
* @property {2|3|4|5} [headingLevel=3] The element level of the surface's title; its `heading`
|
|
102
|
+
* nodes go one and two deeper.
|
|
103
|
+
* @property {string} [locale] Locale for numbers and times.
|
|
104
|
+
* @property {SurfaceCatalog} [catalog=CATALOG] A catalog narrowed with `narrowCatalog()`; the full
|
|
105
|
+
* one by default. What lies outside it is refused as unknown.
|
|
106
|
+
* @property {string|null} [token=null] The application's opaque string, at most 512 characters,
|
|
107
|
+
* copied unchanged into every reply. A surface cannot set it.
|
|
108
|
+
* @property {SurfaceReply|null} [reply=null] A reply the surface already gave, for a surface
|
|
109
|
+
* restored from a stored conversation: it starts as its receipt and replies no more.
|
|
110
|
+
* @property {string|null} [labelledBy=null] The id of an element that already shows the title,
|
|
111
|
+
* such as a Dialog's; the surface then draws no title of its own and is labelled by it.
|
|
112
|
+
* @property {ChartAdapter|null} [chartAdapter=null] The engine that draws `chart` nodes; without
|
|
113
|
+
* one a chart shows its data table.
|
|
114
|
+
* @property {Record<string, string>|Record<string, Record<string, string>>} [msg] Localized messages.
|
|
115
|
+
* @property {(event: CustomEvent<{reply: SurfaceReply}>) => void} [onreply] Reply listener.
|
|
116
|
+
* @property {(event: CustomEvent<{errors: SurfaceError[]}>) => void} [onerror] Error listener.
|
|
117
|
+
* @property {(event: CustomEvent<{name: string, value: unknown}>) => void} [onchange] Input listener.
|
|
118
|
+
* @property {(event: CustomEvent<Record<string, never>>) => void} [onready] First-render listener.
|
|
119
|
+
* @property {(event: CustomEvent<Record<string, never>>) => void} [onend] End-of-surface listener.
|
|
120
|
+
*/
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @typedef {Object} SurfaceModel
|
|
124
|
+
* @property {boolean} began
|
|
125
|
+
* @property {boolean} ended
|
|
126
|
+
* @property {string} surface
|
|
127
|
+
* @property {SurfaceIntent|null} intent
|
|
128
|
+
* @property {string} [title]
|
|
129
|
+
* @property {string} [author]
|
|
130
|
+
* @property {SurfacePlacement} [placement]
|
|
131
|
+
* @property {string} [description]
|
|
132
|
+
* @property {string[]} root
|
|
133
|
+
* @property {Map<string, SurfaceNode>} nodes
|
|
134
|
+
* @property {Map<string, number>} order
|
|
135
|
+
* @property {Record<string, unknown>} data
|
|
136
|
+
* @property {SurfaceAction[]|null} actions
|
|
137
|
+
* @property {SurfaceSource[]|null} sources
|
|
138
|
+
*/
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* @typedef {Object} NodeView
|
|
142
|
+
* @property {HTMLElement} el
|
|
143
|
+
* @property {Component[]} owned
|
|
144
|
+
* @property {'node'|'placeholder'|'fallback'|'receipt'} kind
|
|
145
|
+
* @property {HTMLElement|null} [container] Where a layout node's children go.
|
|
146
|
+
* @property {Fieldset} [fieldset]
|
|
147
|
+
* @property {Record<string, any>} [schema]
|
|
148
|
+
* @property {Table} [table]
|
|
149
|
+
* @property {string} [rowId]
|
|
150
|
+
* @property {Questionnaire} [questionnaire]
|
|
151
|
+
* @property {HTMLFieldSetElement} [choice]
|
|
152
|
+
* @property {HTMLElement} [choiceError]
|
|
153
|
+
* @property {boolean} [overBudget] A table left out for the cell budget.
|
|
154
|
+
*/
|
|
155
|
+
|
|
156
|
+
/** @typedef {SurfaceAction & {builtin?: boolean}} DrawnAction */
|
|
157
|
+
|
|
158
|
+
const ASKING_INTENTS = new Set(['ask', 'choose', 'review']);
|
|
159
|
+
const CANCEL_INTENTS = new Set(['ask', 'choose', 'confirm', 'questionnaire']);
|
|
160
|
+
const VALUELESS = new Set(['reject', 'cancel', 'dismiss']);
|
|
161
|
+
const LEVELS = new Set(['allow', 'confirm', 'type-to-confirm', 'deny']);
|
|
162
|
+
const BLOCK_TYPES = new Set(['text', 'heading', 'list', 'quote', 'code', 'callout', 'figures']);
|
|
163
|
+
const GAPS = Object.freeze({ sm: 2, md: 4, lg: 6 });
|
|
164
|
+
const MAX_TOKEN = 512;
|
|
165
|
+
const SURFACE_ID = new RegExp(ID_PATTERN);
|
|
166
|
+
/** The defaults that answer: they check the inputs and send their values. */
|
|
167
|
+
const ANSWERING = new Set(['submit', 'confirm', 'approve']);
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* A surface an agent composed as JSON — a rich answer, or a dialog asking the person something —
|
|
171
|
+
* drawn with the library's own components from validated values only. It arrives whole as a
|
|
172
|
+
* `document`, or as operation lines through `apply()` and `write()`, drawing what it has as it
|
|
173
|
+
* arrives: a child that has not arrived is a skeleton line, and every action but Cancel waits for
|
|
174
|
+
* the surface's `end`.
|
|
175
|
+
*
|
|
176
|
+
* Every surface ends in exactly one `reply`: an action, Submit, Cancel, Escape, being superseded
|
|
177
|
+
* and being destroyed unanswered all reply, and a second answer is ignored. Answered, it freezes
|
|
178
|
+
* into a read-only receipt (`data-state="answered"`). Whether an action needs a confirmation is
|
|
179
|
+
* the application's `policy`, never the surface's. An input surface is a `<form>` labelled by its
|
|
180
|
+
* title; any other is a labelled region.
|
|
181
|
+
*
|
|
182
|
+
* @fires Surface#reply
|
|
183
|
+
* @fires Surface#error
|
|
184
|
+
* @fires Surface#change
|
|
185
|
+
* @fires Surface#ready
|
|
186
|
+
* @fires Surface#end
|
|
187
|
+
* @extends {Component<SurfaceOptions>}
|
|
188
|
+
*/
|
|
189
|
+
export class Surface extends Component {
|
|
190
|
+
static cssName = 'surface';
|
|
191
|
+
|
|
192
|
+
/** @type {Readonly<SurfaceOptions>} */
|
|
193
|
+
static defaults = {
|
|
194
|
+
document: null,
|
|
195
|
+
policy: null,
|
|
196
|
+
resolve: {},
|
|
197
|
+
authors: {},
|
|
198
|
+
userInitiated: false,
|
|
199
|
+
headingLevel: 3,
|
|
200
|
+
catalog: CATALOG,
|
|
201
|
+
token: null,
|
|
202
|
+
reply: null,
|
|
203
|
+
labelledBy: null,
|
|
204
|
+
chartAdapter: null
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/** @returns {HTMLElement} */
|
|
208
|
+
render() {
|
|
209
|
+
const token = this.options.token ?? null;
|
|
210
|
+
if (token !== null && (typeof token !== 'string' || token.length > MAX_TOKEN)) {
|
|
211
|
+
throw new TypeError(`A surface token is a string of at most ${MAX_TOKEN} characters`);
|
|
212
|
+
}
|
|
213
|
+
assertCatalog(this.options.catalog);
|
|
214
|
+
registerFields();
|
|
215
|
+
const created = !this.el;
|
|
216
|
+
const root = /** @type {HTMLElement} */ (this.el ?? h('section'));
|
|
217
|
+
this.el = root;
|
|
218
|
+
this._original = created ? null : snapshotTarget(root);
|
|
219
|
+
if (!created) root.replaceChildren();
|
|
220
|
+
this._token = token;
|
|
221
|
+
this._catalog = /** @type {SurfaceCatalog} */ (this.options.catalog);
|
|
222
|
+
this._uid = uid('zx-surface');
|
|
223
|
+
const resolve = this.options.resolve ?? {};
|
|
224
|
+
this._entities = resolve.entities == null ? null : [...resolve.entities].filter((entity) => typeof entity === 'string');
|
|
225
|
+
this._state = createValidationState({ entities: this._entities });
|
|
226
|
+
/** @type {SurfaceModel} */
|
|
227
|
+
this._model = {
|
|
228
|
+
began: false, ended: false, surface: '', intent: null, root: [], nodes: new Map(), order: new Map(),
|
|
229
|
+
data: {}, actions: null, sources: null
|
|
230
|
+
};
|
|
231
|
+
/** @type {SurfaceError[]} */
|
|
232
|
+
this._errors = [];
|
|
233
|
+
this._reported = new Set();
|
|
234
|
+
/** @type {Map<string, NodeView>} */
|
|
235
|
+
this._views = new Map();
|
|
236
|
+
/** @type {Set<string>} */
|
|
237
|
+
this._dirty = new Set();
|
|
238
|
+
/** @type {Map<string, Map<string, unknown>>} Bound properties resolved and checked, by node. */
|
|
239
|
+
this._bound = new Map();
|
|
240
|
+
/** Table cells drawn so far in this pass. */
|
|
241
|
+
this._cells = 0;
|
|
242
|
+
/** @type {Record<string, unknown>} Raw input values by name, kept while an input is hidden. */
|
|
243
|
+
this._raw = {};
|
|
244
|
+
/** @type {Record<string, string>} JSON of the last reported value of each input. */
|
|
245
|
+
this._reportedValues = {};
|
|
246
|
+
/** @type {import('./text.js').SurfaceVisibility|null} */
|
|
247
|
+
this._visibility = null;
|
|
248
|
+
/** @type {SurfaceReply|null} */
|
|
249
|
+
this._reply = null;
|
|
250
|
+
/** @type {DrawnAction[]} */
|
|
251
|
+
this._actions = [];
|
|
252
|
+
/** @type {Map<string, {level: PolicyLevel, confirmText?: string, message?: string}>} */
|
|
253
|
+
this._decisions = new Map();
|
|
254
|
+
/** @type {string[]} */
|
|
255
|
+
this._removed = [];
|
|
256
|
+
this._actionsDirty = true;
|
|
257
|
+
this._busy = false;
|
|
258
|
+
/** @type {Dialog|null} */
|
|
259
|
+
this._confirm = null;
|
|
260
|
+
this._ready = false;
|
|
261
|
+
this._destroyed = false;
|
|
262
|
+
/** @type {ReturnType<typeof lineSplitter>|null} */
|
|
263
|
+
this._splitter = null;
|
|
264
|
+
this._documentMode = false;
|
|
265
|
+
/** @type {HTMLElement|null} */
|
|
266
|
+
this._frame = null;
|
|
267
|
+
this._asking = false;
|
|
268
|
+
/** @type {HTMLElement|null} */
|
|
269
|
+
this._body = null;
|
|
270
|
+
/** @type {HTMLElement|null} */
|
|
271
|
+
this._actionsEl = null;
|
|
272
|
+
/** @type {HTMLElement|null} */
|
|
273
|
+
this._verdict = null;
|
|
274
|
+
this._frozen = false;
|
|
275
|
+
this._endEmitted = false;
|
|
276
|
+
/** @type {string|null} The surface id an operation or the document named, before any began. */
|
|
277
|
+
this._named = null;
|
|
278
|
+
|
|
279
|
+
root.setAttribute('aria-busy', 'true');
|
|
280
|
+
this._waiting = skeletonText({ lines: 2 });
|
|
281
|
+
root.append(this._waiting);
|
|
282
|
+
|
|
283
|
+
this.listen(root, 'keydown', (event) => this._onKeydown(/** @type {KeyboardEvent} */ (event)));
|
|
284
|
+
this.listen(root, 'input', () => this._inputChanged());
|
|
285
|
+
this.listen(root, 'change', () => this._inputChanged());
|
|
286
|
+
// Inner components announce their own edits; the surface reports one `change` per input.
|
|
287
|
+
this.listen(root, 'zx-change', (event) => {
|
|
288
|
+
if (event.target === root) return;
|
|
289
|
+
event.stopPropagation();
|
|
290
|
+
this._inputChanged();
|
|
291
|
+
});
|
|
292
|
+
this.listen(root, 'zx-submit', (event) => {
|
|
293
|
+
if (event.target !== root) event.stopPropagation();
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
const document = this.options.document;
|
|
297
|
+
if (document != null) this._load(document);
|
|
298
|
+
return root;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/* ------------------------------------------------------------------ public API -- */
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Applies one operation, as parsed from its line. It is validated against the catalog first:
|
|
305
|
+
* what is invalid is dropped and reported through `error`, and only the valid rest is drawn.
|
|
306
|
+
* Operations for another surface, and any after the surface was answered, are ignored.
|
|
307
|
+
* @param {unknown} op
|
|
308
|
+
* @returns {this}
|
|
309
|
+
* @fires Surface#error
|
|
310
|
+
*/
|
|
311
|
+
apply(op) {
|
|
312
|
+
if (this._reply || this._destroyed) return this;
|
|
313
|
+
if (this._documentMode || this._model.ended) {
|
|
314
|
+
this._report([{ code: 'ended', message: 'The surface has ended', surface: this._model.surface || undefined }]);
|
|
315
|
+
return this;
|
|
316
|
+
}
|
|
317
|
+
const surface = op && typeof op === 'object' ? /** @type {Record<string, unknown>} */ (op).surface : undefined;
|
|
318
|
+
if (this._model.began && surface !== this._model.surface) {
|
|
319
|
+
this._report([{
|
|
320
|
+
code: 'not-allowed',
|
|
321
|
+
message: `This surface is "${this._model.surface}"; an operation for ${describeValue(surface)} was refused`,
|
|
322
|
+
path: '/surface'
|
|
323
|
+
}]);
|
|
324
|
+
return this;
|
|
325
|
+
}
|
|
326
|
+
if (!this._model.began && !this._named && typeof surface === 'string' && SURFACE_ID.test(surface)) this._named = surface;
|
|
327
|
+
const result = validateOp(op, this._state, this._catalog);
|
|
328
|
+
for (const valid of result.ops) this._applyValid(valid);
|
|
329
|
+
this._draw();
|
|
330
|
+
this._report(result.errors);
|
|
331
|
+
return this;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Takes a chunk of operation lines, as streamed: every complete line is parsed and applied.
|
|
336
|
+
* @param {string} chunk
|
|
337
|
+
* @returns {this}
|
|
338
|
+
* @fires Surface#error
|
|
339
|
+
*/
|
|
340
|
+
write(chunk) {
|
|
341
|
+
this._lines().write(String(chunk ?? ''));
|
|
342
|
+
return this;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Ends the stream: applies a last line without a line break. A surface whose `end` never
|
|
347
|
+
* arrived is reported and keeps its actions disabled; Cancel still replies.
|
|
348
|
+
* @returns {this}
|
|
349
|
+
* @fires Surface#error
|
|
350
|
+
*/
|
|
351
|
+
end() {
|
|
352
|
+
this._lines().end();
|
|
353
|
+
if (this._model.began && !this._model.ended && !this._reply && !this._documentMode) {
|
|
354
|
+
this._report([{
|
|
355
|
+
code: 'missing', surface: this._model.surface, path: '/op',
|
|
356
|
+
message: 'The stream ended before the surface\'s "end"; its actions stay disabled'
|
|
357
|
+
}]);
|
|
358
|
+
}
|
|
359
|
+
return this;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* The values of the visible inputs by name, as a reply would carry them: JSON, hidden inputs
|
|
364
|
+
* left out. A questionnaire's are `{answers, path}`.
|
|
365
|
+
* @returns {Record<string, unknown>}
|
|
366
|
+
*/
|
|
367
|
+
getValues() {
|
|
368
|
+
if (this._reply) return structuredClone(this._reply.values);
|
|
369
|
+
if (this._model.intent === 'questionnaire') {
|
|
370
|
+
const view = this._questionnaireView();
|
|
371
|
+
return view?.questionnaire ? { answers: view.questionnaire.getAnswers(), path: view.questionnaire.getPath() } : {};
|
|
372
|
+
}
|
|
373
|
+
const values = this._jsonValues();
|
|
374
|
+
const visibility = this._visibilityFor(values);
|
|
375
|
+
/** @type {Record<string, unknown>} */
|
|
376
|
+
const out = {};
|
|
377
|
+
for (const name of visibility.names) if (Object.hasOwn(values, name)) out[name] = values[name];
|
|
378
|
+
return out;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Every problem collected so far, in a shape an application can return to the model.
|
|
383
|
+
* @returns {SurfaceError[]}
|
|
384
|
+
*/
|
|
385
|
+
getErrors() {
|
|
386
|
+
return structuredClone(this._errors);
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Closes the surface unanswered: replies `cancel` (`dismiss` for a `show` surface).
|
|
391
|
+
* @param {ReplyReason} [reason='cancelled'] Why, carried in the reply's `reason`.
|
|
392
|
+
* @returns {this}
|
|
393
|
+
* @fires Surface#reply
|
|
394
|
+
*/
|
|
395
|
+
cancel(reason = 'cancelled') {
|
|
396
|
+
this._close(this._model.intent === 'show' ? 'dismiss' : 'cancel', reason || 'cancelled');
|
|
397
|
+
return this;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* Ends the surface because a newer one takes its place: replies `dismiss` with the reason
|
|
402
|
+
* `superseded`.
|
|
403
|
+
* @returns {this}
|
|
404
|
+
* @fires Surface#reply
|
|
405
|
+
*/
|
|
406
|
+
supersede() {
|
|
407
|
+
this._close('dismiss', 'superseded');
|
|
408
|
+
return this;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Moves focus to the first control: the first input, else the first enabled action.
|
|
413
|
+
* @returns {this}
|
|
414
|
+
*/
|
|
415
|
+
focus() {
|
|
416
|
+
const body = this._body;
|
|
417
|
+
const selector = 'input:not([type="hidden"]):not([disabled]), select:not([disabled]), textarea:not([disabled]), [role="grid"][tabindex], button:not([disabled]), [tabindex="0"]';
|
|
418
|
+
const visible = (/** @type {Element} */ element) => !element.closest('[hidden]') && /** @type {HTMLElement} */ (element).getClientRects().length > 0;
|
|
419
|
+
const first = [...(body?.querySelectorAll(selector) ?? [])].find(visible)
|
|
420
|
+
?? [...(this._actionsEl?.querySelectorAll('button:not([disabled])') ?? [])].find(visible)
|
|
421
|
+
?? null;
|
|
422
|
+
if (first) /** @type {HTMLElement} */ (first).focus();
|
|
423
|
+
else /** @type {HTMLElement} */ (this._verdict ?? this.el).focus?.();
|
|
424
|
+
return this;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* The surface as it stands, as a document: what was validated, repairs applied and invalid
|
|
429
|
+
* parts dropped. `null` before it began.
|
|
430
|
+
* @returns {SurfaceDocument|null}
|
|
431
|
+
*/
|
|
432
|
+
toDocument() {
|
|
433
|
+
const model = this._model;
|
|
434
|
+
if (!model.began) return null;
|
|
435
|
+
/** @type {Record<string, unknown>} */
|
|
436
|
+
const out = { zx: SURFACE_VERSION, surface: model.surface, intent: model.intent };
|
|
437
|
+
if (model.title !== undefined) out.title = model.title;
|
|
438
|
+
if (model.author !== undefined) out.author = model.author;
|
|
439
|
+
out.root = [...model.root];
|
|
440
|
+
if (model.placement !== undefined) out.placement = model.placement;
|
|
441
|
+
if (model.description !== undefined) out.description = model.description;
|
|
442
|
+
out.nodes = [...model.nodes.values()]
|
|
443
|
+
.sort((a, b) => (model.order.get(a.id) ?? 0) - (model.order.get(b.id) ?? 0))
|
|
444
|
+
.map((node) => structuredClone(node));
|
|
445
|
+
if (Object.keys(model.data).length) out.data = structuredClone(model.data);
|
|
446
|
+
if (model.actions) out.actions = structuredClone(model.actions);
|
|
447
|
+
if (model.sources) out.sources = structuredClone(model.sources);
|
|
448
|
+
return /** @type {SurfaceDocument} */ (out);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* The reply the surface gave, or `null` while it waits.
|
|
453
|
+
* @returns {SurfaceReply|null}
|
|
454
|
+
*/
|
|
455
|
+
getReply() {
|
|
456
|
+
return this._reply ? structuredClone(this._reply) : null;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Destroys the surface. An unanswered surface replies `dismiss` first, with the reason
|
|
461
|
+
* `destroyed`, so a waiting agent never hangs.
|
|
462
|
+
* @returns {void}
|
|
463
|
+
* @fires Surface#reply
|
|
464
|
+
*/
|
|
465
|
+
destroy() {
|
|
466
|
+
if (this._destroyed) return;
|
|
467
|
+
this._close('dismiss', 'destroyed');
|
|
468
|
+
this._destroyed = true;
|
|
469
|
+
this._confirm?.close(false);
|
|
470
|
+
this._confirm = null;
|
|
471
|
+
for (const view of this._views.values()) for (const component of view.owned) component.destroy();
|
|
472
|
+
this._views.clear();
|
|
473
|
+
super.destroy();
|
|
474
|
+
if (this._original) restoreTarget(this.el, this._original);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/* ------------------------------------------------------------------ model -- */
|
|
478
|
+
|
|
479
|
+
/** @private @returns {ReturnType<typeof lineSplitter>} */
|
|
480
|
+
_lines() {
|
|
481
|
+
if (!this._splitter) {
|
|
482
|
+
this._splitter = lineSplitter((line) => {
|
|
483
|
+
if (!line.trim()) return;
|
|
484
|
+
let op;
|
|
485
|
+
try {
|
|
486
|
+
op = JSON.parse(line);
|
|
487
|
+
} catch {
|
|
488
|
+
this._report([{ code: 'invalid-op', message: 'A line is not complete JSON; it was dropped' }]);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
this.apply(op);
|
|
492
|
+
}, {
|
|
493
|
+
onerror: (error) => this._report([{ code: 'limit', message: error.message }])
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
return this._splitter;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Draws a whole document.
|
|
501
|
+
* @private
|
|
502
|
+
* @param {unknown} document
|
|
503
|
+
* @returns {void}
|
|
504
|
+
*/
|
|
505
|
+
_load(document) {
|
|
506
|
+
const { document: valid, errors } = validateDocument(document, this._catalog, { entities: this._entities });
|
|
507
|
+
this._documentMode = true;
|
|
508
|
+
const named = document && typeof document === 'object' ? /** @type {Record<string, unknown>} */ (document).surface : undefined;
|
|
509
|
+
if (typeof named === 'string' && SURFACE_ID.test(named)) this._named = named;
|
|
510
|
+
if (valid) {
|
|
511
|
+
const { nodes, data, actions, sources, ...begin } = valid;
|
|
512
|
+
this._applyValid(/** @type {SurfaceOp} */ ({ ...begin, op: 'begin' }));
|
|
513
|
+
if (data) this._model.data = structuredClone(data);
|
|
514
|
+
for (const node of nodes) this._applyValid(/** @type {SurfaceOp} */ ({ op: 'node', surface: valid.surface, ...node }));
|
|
515
|
+
if (actions) this._applyValid(/** @type {SurfaceOp} */ ({ op: 'actions', surface: valid.surface, items: actions }));
|
|
516
|
+
this._applyValid(/** @type {SurfaceOp} */ ({ op: 'end', surface: valid.surface, ...(sources ? { sources } : {}) }));
|
|
517
|
+
}
|
|
518
|
+
const given = this.options.reply;
|
|
519
|
+
if (valid && given && typeof given === 'object' && given.surface === valid.surface) {
|
|
520
|
+
this._reply = structuredClone(given);
|
|
521
|
+
}
|
|
522
|
+
this._draw();
|
|
523
|
+
this._report(errors);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Records one validated operation in the model.
|
|
528
|
+
* @private
|
|
529
|
+
* @param {SurfaceOp} op
|
|
530
|
+
* @returns {void}
|
|
531
|
+
*/
|
|
532
|
+
_applyValid(op) {
|
|
533
|
+
const model = this._model;
|
|
534
|
+
switch (op.op) {
|
|
535
|
+
case 'begin':
|
|
536
|
+
model.began = true;
|
|
537
|
+
model.surface = op.surface;
|
|
538
|
+
model.intent = op.intent ?? null;
|
|
539
|
+
model.root = [...op.root];
|
|
540
|
+
for (const key of /** @type {const} */ (['title', 'author', 'placement', 'description'])) {
|
|
541
|
+
if (op[key] !== undefined) /** @type {any} */ (model)[key] = op[key];
|
|
542
|
+
}
|
|
543
|
+
this._buildFrame();
|
|
544
|
+
break;
|
|
545
|
+
case 'node': {
|
|
546
|
+
const { op: _op, surface: _surface, ...node } = /** @type {any} */ (op);
|
|
547
|
+
if (!model.order.has(node.id)) model.order.set(node.id, model.order.size);
|
|
548
|
+
model.nodes.set(node.id, /** @type {SurfaceNode} */ (node));
|
|
549
|
+
this._bound.delete(node.id);
|
|
550
|
+
this._dirty.add(node.id);
|
|
551
|
+
break;
|
|
552
|
+
}
|
|
553
|
+
case 'patch': {
|
|
554
|
+
const node = model.nodes.get(op.id);
|
|
555
|
+
if (!node) break;
|
|
556
|
+
for (const [key, value] of Object.entries(op.props)) {
|
|
557
|
+
if (value === null) delete node[key];
|
|
558
|
+
else node[key] = structuredClone(value);
|
|
559
|
+
}
|
|
560
|
+
this._bound.delete(op.id);
|
|
561
|
+
this._dirty.add(op.id);
|
|
562
|
+
break;
|
|
563
|
+
}
|
|
564
|
+
case 'append': {
|
|
565
|
+
const node = model.nodes.get(op.id);
|
|
566
|
+
if (!node) break;
|
|
567
|
+
node.text = (typeof node.text === 'string' ? node.text : '') + op.text;
|
|
568
|
+
this._dirty.add(op.id);
|
|
569
|
+
break;
|
|
570
|
+
}
|
|
571
|
+
case 'remove':
|
|
572
|
+
model.nodes.delete(op.id);
|
|
573
|
+
this._bound.delete(op.id);
|
|
574
|
+
model.root = model.root.filter((id) => id !== op.id);
|
|
575
|
+
for (const node of model.nodes.values()) {
|
|
576
|
+
if (Array.isArray(node.children) && node.children.includes(op.id)) {
|
|
577
|
+
node.children = node.children.filter((id) => id !== op.id);
|
|
578
|
+
this._dirty.add(node.id);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
break;
|
|
582
|
+
case 'data':
|
|
583
|
+
// Validation stored it: the surface reads that data, and redraws only what is bound to it.
|
|
584
|
+
model.data = this._state.surfaces.get(op.surface)?.data ?? model.data;
|
|
585
|
+
for (const node of model.nodes.values()) {
|
|
586
|
+
if (!boundPointers(node).some((pointer) => touches(pointer, op.path))) continue;
|
|
587
|
+
this._bound.delete(node.id);
|
|
588
|
+
this._dirty.add(node.id);
|
|
589
|
+
}
|
|
590
|
+
break;
|
|
591
|
+
case 'actions':
|
|
592
|
+
model.actions = structuredClone(op.items);
|
|
593
|
+
this._actionsDirty = true;
|
|
594
|
+
break;
|
|
595
|
+
case 'end':
|
|
596
|
+
model.ended = true;
|
|
597
|
+
if (op.sources) model.sources = structuredClone(op.sources);
|
|
598
|
+
for (const [id, view] of this._views) if (view.kind !== 'node') this._dirty.add(id);
|
|
599
|
+
this._actionsDirty = true;
|
|
600
|
+
break;
|
|
601
|
+
default:
|
|
602
|
+
break;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/* ------------------------------------------------------------------ drawing -- */
|
|
607
|
+
|
|
608
|
+
/**
|
|
609
|
+
* Builds the frame once the intent is known: a `<form>` for a surface that asks, a region for
|
|
610
|
+
* any other, labelled by the title.
|
|
611
|
+
* @private
|
|
612
|
+
* @returns {void}
|
|
613
|
+
*/
|
|
614
|
+
_buildFrame() {
|
|
615
|
+
if (this._frame) return;
|
|
616
|
+
const model = this._model;
|
|
617
|
+
const asking = model.intent !== null && ASKING_INTENTS.has(model.intent);
|
|
618
|
+
const labelledBy = typeof this.options.labelledBy === 'string' && this.options.labelledBy ? this.options.labelledBy : null;
|
|
619
|
+
const titleId = `${this._uid}-title`;
|
|
620
|
+
const level = headingLevel(this.options.headingLevel);
|
|
621
|
+
const frame = /** @type {HTMLElement} */ (h(asking ? 'form' : 'div', {
|
|
622
|
+
class: 'zx-surface__frame',
|
|
623
|
+
role: asking ? null : 'region',
|
|
624
|
+
'aria-labelledby': labelledBy ?? (model.title ? titleId : null),
|
|
625
|
+
'aria-label': labelledBy || model.title ? null : this.msg('surface.byline', this._authorName()),
|
|
626
|
+
novalidate: asking ? true : null
|
|
627
|
+
}));
|
|
628
|
+
this._frame = frame;
|
|
629
|
+
this._asking = asking;
|
|
630
|
+
const header = h('header', { class: 'zx-surface__header' });
|
|
631
|
+
if (!labelledBy && model.title) header.append(h(`h${level}`, { class: 'zx-surface__title', id: titleId }, model.title));
|
|
632
|
+
if (model.description) header.append(h('p', { class: 'zx-surface__description' }, model.description));
|
|
633
|
+
header.append(h('p', { class: 'zx-surface__byline' }, this.msg('surface.byline', this._authorName())));
|
|
634
|
+
this._body = h('div', { class: 'zx-surface__body' });
|
|
635
|
+
this._actionsEl = h('div', { class: 'zx-surface__actions' });
|
|
636
|
+
this._verdict = null;
|
|
637
|
+
frame.append(header, this._body, this._actionsEl);
|
|
638
|
+
const root = /** @type {HTMLElement} */ (this.el);
|
|
639
|
+
root.dataset.intent = model.intent ?? 'none';
|
|
640
|
+
root.dataset.state = 'open';
|
|
641
|
+
this._waiting?.remove();
|
|
642
|
+
this.el.append(frame);
|
|
643
|
+
if (asking) {
|
|
644
|
+
this.listen(frame, 'submit', (event) => {
|
|
645
|
+
event.preventDefault();
|
|
646
|
+
if (event.target !== frame) return;
|
|
647
|
+
// The button pressed answers; Enter in a field presses the first primary action.
|
|
648
|
+
const pressed = /** @type {SubmitEvent} */ (event).submitter?.getAttribute('data-surface-action');
|
|
649
|
+
const id = pressed ?? this._actions.find((action) => action.kind === 'primary' && !action.builtin)?.id;
|
|
650
|
+
if (id) void this._run(id);
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
this.listen(this._actionsEl, 'click', (event) => {
|
|
654
|
+
const target = /** @type {Element} */ (event.target).closest?.('button[data-surface-action]');
|
|
655
|
+
if (!target || /** @type {HTMLButtonElement} */ (target).type === 'submit') return;
|
|
656
|
+
void this._run(String(/** @type {HTMLElement} */ (target).dataset.surfaceAction));
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Draws what changed: the node tree from `root`, the visibility of every node and field, and
|
|
662
|
+
* the actions, or the receipt once the surface is answered.
|
|
663
|
+
* @private
|
|
664
|
+
* @returns {void}
|
|
665
|
+
*/
|
|
666
|
+
_draw() {
|
|
667
|
+
if (!this._model.began || this._destroyed || !this._body) return;
|
|
668
|
+
try {
|
|
669
|
+
this._paint();
|
|
670
|
+
} catch (error) {
|
|
671
|
+
this._drawFailed(error);
|
|
672
|
+
}
|
|
673
|
+
this.el.removeAttribute('aria-busy');
|
|
674
|
+
if (!this._ready) {
|
|
675
|
+
this._ready = true;
|
|
676
|
+
this.emit('ready');
|
|
677
|
+
}
|
|
678
|
+
if (this._model.ended && !this._endEmitted) {
|
|
679
|
+
this._endEmitted = true;
|
|
680
|
+
this.emit('end');
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/**
|
|
685
|
+
* @private
|
|
686
|
+
* @returns {void}
|
|
687
|
+
*/
|
|
688
|
+
_paint() {
|
|
689
|
+
if (this._reply && !this._frozen) this._freeze();
|
|
690
|
+
/** @type {Set<string>} */
|
|
691
|
+
const used = new Set();
|
|
692
|
+
this._cells = 0;
|
|
693
|
+
syncChildren(this._body, this._model.root.map((id) => this._viewOf(id, used, 1)));
|
|
694
|
+
for (const [id, view] of [...this._views]) {
|
|
695
|
+
if (used.has(id)) continue;
|
|
696
|
+
for (const component of view.owned) component.destroy();
|
|
697
|
+
view.el.remove();
|
|
698
|
+
this._views.delete(id);
|
|
699
|
+
}
|
|
700
|
+
this._dirty.clear();
|
|
701
|
+
this._syncVisibility();
|
|
702
|
+
if (!this._reply) this._drawActions();
|
|
703
|
+
const busy = !this._model.ended && !this._reply;
|
|
704
|
+
if (this._frame) setFormAttribute(this._frame, 'aria-busy', busy ? 'true' : null);
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* What goes wrong while drawing costs the part that failed and is reported; never the rest of
|
|
709
|
+
* the surface, and never its reply.
|
|
710
|
+
* @private
|
|
711
|
+
* @param {unknown} error @param {string} [id] The node that failed.
|
|
712
|
+
* @returns {void}
|
|
713
|
+
*/
|
|
714
|
+
_drawFailed(error, id) {
|
|
715
|
+
this._report([{
|
|
716
|
+
code: 'draw-failed', surface: this._model.surface || undefined, ...(id === undefined ? {} : { id }),
|
|
717
|
+
message: `${id === undefined ? 'The surface' : `The node "${id}"`} could not be drawn: ${error instanceof Error ? error.message : String(error)}`
|
|
718
|
+
}]);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* The element for a node id: its view, built or rebuilt when it changed, with a layout node's
|
|
723
|
+
* children synced inside it.
|
|
724
|
+
* @private
|
|
725
|
+
* @param {string} id @param {Set<string>} used @param {number} depth
|
|
726
|
+
* @returns {HTMLElement}
|
|
727
|
+
*/
|
|
728
|
+
_viewOf(id, used, depth) {
|
|
729
|
+
if (used.has(id) || depth > LIMITS.depth) return h('span', { hidden: true });
|
|
730
|
+
used.add(id);
|
|
731
|
+
let view = this._views.get(id);
|
|
732
|
+
const overBudget = this._overBudget(id);
|
|
733
|
+
if (!view || this._dirty.has(id) || Boolean(view.overBudget) !== overBudget) {
|
|
734
|
+
const next = overBudget ? { ...this._fallback(), overBudget } : this._safeBuild(id);
|
|
735
|
+
if (view) {
|
|
736
|
+
const hadFocus = view.el.contains(document.activeElement);
|
|
737
|
+
view.el.replaceWith(next.el);
|
|
738
|
+
for (const component of view.owned) component.destroy();
|
|
739
|
+
if (hadFocus) this._refocus(next);
|
|
740
|
+
}
|
|
741
|
+
view = next;
|
|
742
|
+
this._views.set(id, view);
|
|
743
|
+
}
|
|
744
|
+
view.el.dataset.surfaceNode = id;
|
|
745
|
+
const node = this._model.nodes.get(id);
|
|
746
|
+
if (view.container && node && Array.isArray(node.children)) {
|
|
747
|
+
syncChildren(view.container, node.children.map((child) => this._viewOf(child, used, depth + 1)));
|
|
748
|
+
}
|
|
749
|
+
return view.el;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* Counts a table against the cell budget as it is drawn, so the budget also holds for a stream
|
|
754
|
+
* that never ends.
|
|
755
|
+
* @private
|
|
756
|
+
* @param {string} id
|
|
757
|
+
* @returns {boolean} Whether it is left out.
|
|
758
|
+
*/
|
|
759
|
+
_overBudget(id) {
|
|
760
|
+
const node = this._model.nodes.get(id);
|
|
761
|
+
const cells = node ? tableCells(node, this._model.data) : 0;
|
|
762
|
+
if (this._cells + cells <= LIMITS.cells) {
|
|
763
|
+
this._cells += cells;
|
|
764
|
+
return false;
|
|
765
|
+
}
|
|
766
|
+
this._report([{ code: 'limit', surface: this._model.surface, id, path: `/nodes/${id}/rows`, message: cellLimitMessage(id) }]);
|
|
767
|
+
return true;
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/**
|
|
771
|
+
* @private
|
|
772
|
+
* @param {string} id
|
|
773
|
+
* @returns {NodeView}
|
|
774
|
+
*/
|
|
775
|
+
_safeBuild(id) {
|
|
776
|
+
try {
|
|
777
|
+
return this._build(id);
|
|
778
|
+
} catch (error) {
|
|
779
|
+
this._drawFailed(error, id);
|
|
780
|
+
return this._fallback();
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/**
|
|
785
|
+
* Builds one node's view: the component it maps to, a skeleton while what it needs has not
|
|
786
|
+
* arrived, a quiet fallback for what cannot be shown, or, once answered, the receipt.
|
|
787
|
+
* @private
|
|
788
|
+
* @param {string} id
|
|
789
|
+
* @returns {NodeView}
|
|
790
|
+
*/
|
|
791
|
+
_build(id) {
|
|
792
|
+
const node = this._model.nodes.get(id);
|
|
793
|
+
const ended = this._model.ended;
|
|
794
|
+
if (!node) return ended ? this._fallback() : this._placeholder();
|
|
795
|
+
const entry = this._entry(node.type);
|
|
796
|
+
if (!entry || (entry.input && !this._model.intent)) return this._fallback();
|
|
797
|
+
/** @type {Record<string, any>} */
|
|
798
|
+
const props = {};
|
|
799
|
+
for (const [name, member] of Object.entries(entry.props)) {
|
|
800
|
+
const value = this._prop(node, name);
|
|
801
|
+
if (value !== undefined) props[name] = value;
|
|
802
|
+
else if (member.required) return ended ? this._fallback() : this._placeholder();
|
|
803
|
+
}
|
|
804
|
+
if (this._reply && entry.input) return this._receipt(node, props);
|
|
805
|
+
/** @type {NodeView} */
|
|
806
|
+
const view = { el: h('div'), owned: [], kind: 'node' };
|
|
807
|
+
const level = headingLevel(this.options.headingLevel);
|
|
808
|
+
if (BLOCK_TYPES.has(node.type)) {
|
|
809
|
+
view.el = h('div', { class: 'zx-surface__blocks zx-prose', dataset: { size: 'sm' } },
|
|
810
|
+
renderBlocks([toBlock(node.type, props)], { headingLevel: /** @type {any} */ (Math.min(5, level + 1)), msg: (key, ...args) => this.msg(key, ...args) }));
|
|
811
|
+
if (node.type === 'heading') settleHeading(view.el, Math.min(6, level + (props.level === 3 ? 2 : 1)));
|
|
812
|
+
return view;
|
|
813
|
+
}
|
|
814
|
+
switch (node.type) {
|
|
815
|
+
case 'table':
|
|
816
|
+
return this._table(view, props);
|
|
817
|
+
case 'stat': {
|
|
818
|
+
const tile = new StatTile(null, {
|
|
819
|
+
label: props.label, value: props.value, format: props.format ?? 'number', currency: props.currency ?? null,
|
|
820
|
+
delta: props.delta ?? null, caption: props.caption ?? '', variant: 'plain', locale: this.options.locale
|
|
821
|
+
});
|
|
822
|
+
view.owned.push(tile);
|
|
823
|
+
view.el = h('div', { class: 'zx-surface__stat' }, tile.toElement());
|
|
824
|
+
return view;
|
|
825
|
+
}
|
|
826
|
+
case 'badge':
|
|
827
|
+
view.el = h('div', { class: 'zx-surface__badge' }, badge({ label: props.label, kind: props.kind ?? 'neutral' }));
|
|
828
|
+
return view;
|
|
829
|
+
case 'ref':
|
|
830
|
+
view.el = h('div', { class: 'zx-surface__ref' }, this._ref(props.ref, view));
|
|
831
|
+
return view;
|
|
832
|
+
case 'link':
|
|
833
|
+
view.el = h('p', { class: 'zx-surface__link' }, ...this._link(props.text, props.href));
|
|
834
|
+
return view;
|
|
835
|
+
case 'chart':
|
|
836
|
+
return this._chart(view, props);
|
|
837
|
+
case 'empty':
|
|
838
|
+
view.el = h('div', { class: 'zx-surface__empty' },
|
|
839
|
+
emptyState({ icon: null, title: props.title, description: props.description ?? '', size: 'sm', align: 'start' }));
|
|
840
|
+
return view;
|
|
841
|
+
case 'stack':
|
|
842
|
+
view.el = stack({ gap: GAPS[/** @type {keyof typeof GAPS} */ (props.gap)] ?? GAPS.md, class: 'zx-surface__stack' });
|
|
843
|
+
view.container = view.el;
|
|
844
|
+
return view;
|
|
845
|
+
case 'columns':
|
|
846
|
+
view.el = grid({ columns: props.count ?? 2, min: '12rem', class: 'zx-surface__columns' });
|
|
847
|
+
view.container = view.el;
|
|
848
|
+
return view;
|
|
849
|
+
case 'group': {
|
|
850
|
+
const box = new Groupbox(null, { title: props.title, open: true });
|
|
851
|
+
const container = stack({ gap: GAPS.md });
|
|
852
|
+
box.setContent(container);
|
|
853
|
+
view.owned.push(box);
|
|
854
|
+
view.el = h('div', { class: 'zx-surface__group' }, box.toElement());
|
|
855
|
+
view.container = container;
|
|
856
|
+
return view;
|
|
857
|
+
}
|
|
858
|
+
case 'fields':
|
|
859
|
+
return this._fields(view, props);
|
|
860
|
+
case 'choice':
|
|
861
|
+
return this._choice(view, node, props);
|
|
862
|
+
case 'diff':
|
|
863
|
+
return this._diff(view, props);
|
|
864
|
+
case 'questionnaire':
|
|
865
|
+
return this._questionnaire(view, props);
|
|
866
|
+
default:
|
|
867
|
+
return this._fallback();
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/**
|
|
872
|
+
* The catalog's own entry for a type: a node of any other type, whatever it is called, has none.
|
|
873
|
+
* @private
|
|
874
|
+
* @param {string} type
|
|
875
|
+
* @returns {import('./catalog.js').CatalogNode|undefined}
|
|
876
|
+
*/
|
|
877
|
+
_entry(type) {
|
|
878
|
+
return Object.hasOwn(this._catalog.nodes, type) ? this._catalog.nodes[type] : undefined;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* A property's value, a `$data` binding resolved and checked as if it had been written in.
|
|
883
|
+
* @private
|
|
884
|
+
* @param {SurfaceNode} node @param {string} name
|
|
885
|
+
* @returns {any}
|
|
886
|
+
*/
|
|
887
|
+
_prop(node, name) {
|
|
888
|
+
const raw = node[name];
|
|
889
|
+
if (!isBinding(raw)) return raw === null ? undefined : raw;
|
|
890
|
+
const known = this._bound.get(node.id);
|
|
891
|
+
if (known?.has(name)) return known.get(name);
|
|
892
|
+
const value = readProp(node, name, this._model.data);
|
|
893
|
+
const { value: checked, errors } = value === undefined ? { value: undefined, errors: [] }
|
|
894
|
+
: validateValue(node.type, name, value, { entities: this._entities, node });
|
|
895
|
+
this._report(errors.map((error) => ({
|
|
896
|
+
...error, surface: this._model.surface, id: node.id,
|
|
897
|
+
path: `/nodes/${node.id}/${name}${error.path}`
|
|
898
|
+
})));
|
|
899
|
+
if (known) known.set(name, checked);
|
|
900
|
+
else this._bound.set(node.id, new Map([[name, checked]]));
|
|
901
|
+
return checked;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/** @private @returns {NodeView} */
|
|
905
|
+
_placeholder() {
|
|
906
|
+
return { el: h('div', { class: 'zx-surface__placeholder' }, skeletonText({ lines: 1 })), owned: [], kind: 'placeholder' };
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** @private @returns {NodeView} */
|
|
910
|
+
_fallback() {
|
|
911
|
+
return {
|
|
912
|
+
el: h('p', { class: 'zx-surface__fallback' },
|
|
913
|
+
h('span', { class: 'zx-surface__fallback-icon', 'aria-hidden': 'true' }, icon('info', { size: 14 })),
|
|
914
|
+
h('span', {}, this.msg('surface.fallback'))),
|
|
915
|
+
owned: [],
|
|
916
|
+
kind: 'fallback'
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
/**
|
|
921
|
+
* @private
|
|
922
|
+
* @param {NodeView} view @param {Record<string, any>} props
|
|
923
|
+
* @returns {NodeView}
|
|
924
|
+
*/
|
|
925
|
+
_table(view, props) {
|
|
926
|
+
const rows = /** @type {Record<string, unknown>[]} */ (props.rows);
|
|
927
|
+
const selectable = props.selectable && props.name ? props.selectable : false;
|
|
928
|
+
const table = new Table(null, {
|
|
929
|
+
columns: /** @type {any} */ (this._columns(props.columns, rows, view)),
|
|
930
|
+
data: drawnRows(rows, props.columns),
|
|
931
|
+
rowId: drawnRowId(props.rowId),
|
|
932
|
+
selectable,
|
|
933
|
+
label: props.label ?? null,
|
|
934
|
+
stickyHeader: false
|
|
935
|
+
});
|
|
936
|
+
view.owned.push(table);
|
|
937
|
+
view.table = table;
|
|
938
|
+
view.rowId = props.rowId;
|
|
939
|
+
if (selectable) {
|
|
940
|
+
const saved = this._raw[props.name];
|
|
941
|
+
if (saved != null) table.setSelection(Array.isArray(saved) ? saved : [saved]);
|
|
942
|
+
table.on('selectionchange', () => this._inputChanged());
|
|
943
|
+
}
|
|
944
|
+
view.el = h('div', { class: 'zx-surface__table' }, table.toElement());
|
|
945
|
+
return view;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* Table columns: formats mapped, record cells drawn through `resolve.ref`.
|
|
950
|
+
* @private
|
|
951
|
+
* @param {Array<Record<string, any>>} columns @param {Record<string, unknown>[]} rows @param {NodeView} view
|
|
952
|
+
* @returns {Array<Record<string, unknown>>}
|
|
953
|
+
*/
|
|
954
|
+
_columns(columns, rows, view) {
|
|
955
|
+
return columns.map((column) => {
|
|
956
|
+
/** @type {Record<string, unknown>} */
|
|
957
|
+
const out = { id: column.id, label: column.label, align: column.align ?? 'start' };
|
|
958
|
+
if (column.format === 'number' || column.format === 'percent') out.type = column.format;
|
|
959
|
+
if (column.format === 'currency') {
|
|
960
|
+
if (column.currency) Object.assign(out, { type: 'currency', currency: column.currency });
|
|
961
|
+
else out.type = 'number';
|
|
962
|
+
}
|
|
963
|
+
if (this.options.locale) out.locale = this.options.locale;
|
|
964
|
+
if (rows.some((row) => isRef(row[column.id]))) {
|
|
965
|
+
out.render = (/** @type {Record<string, unknown>} */ row) => {
|
|
966
|
+
const cell = row[column.id];
|
|
967
|
+
return isRef(cell) ? this._ref(cell, view) : cell == null ? '' : String(cell);
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
return out;
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* A record drawn as an EntityRef through `resolve.ref`, or its id as text.
|
|
976
|
+
* @private
|
|
977
|
+
* @param {{$ref: string, id: string}} ref @param {NodeView} view
|
|
978
|
+
* @returns {Node}
|
|
979
|
+
*/
|
|
980
|
+
_ref(ref, view) {
|
|
981
|
+
const resolver = this.options.resolve?.ref;
|
|
982
|
+
let options = null;
|
|
983
|
+
if (typeof resolver === 'function') {
|
|
984
|
+
try {
|
|
985
|
+
options = resolver({ $ref: ref.$ref, id: ref.id });
|
|
986
|
+
} catch {
|
|
987
|
+
options = null;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
if (!options || typeof options !== 'object') return h('span', { class: 'zx-surface__ref-id' }, ref.id);
|
|
991
|
+
const entity = new EntityRef(null, { size: 'sm', ...options });
|
|
992
|
+
view.owned.push(entity);
|
|
993
|
+
return entity.toElement();
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/**
|
|
997
|
+
* A link: the text, opening in a new tab when `resolve.link` keeps it, and the host beside it.
|
|
998
|
+
* @private
|
|
999
|
+
* @param {string} text @param {string} href
|
|
1000
|
+
* @returns {Node[]}
|
|
1001
|
+
*/
|
|
1002
|
+
_link(text, href) {
|
|
1003
|
+
let host = '';
|
|
1004
|
+
try {
|
|
1005
|
+
host = new URL(href).host;
|
|
1006
|
+
} catch {
|
|
1007
|
+
host = '';
|
|
1008
|
+
}
|
|
1009
|
+
/** @type {string|null} */
|
|
1010
|
+
let target = href;
|
|
1011
|
+
const resolver = this.options.resolve?.link;
|
|
1012
|
+
if (typeof resolver === 'function') {
|
|
1013
|
+
let answer;
|
|
1014
|
+
try {
|
|
1015
|
+
answer = resolver(href, { text });
|
|
1016
|
+
} catch {
|
|
1017
|
+
answer = false;
|
|
1018
|
+
}
|
|
1019
|
+
if (answer === false || answer === null) target = null;
|
|
1020
|
+
else if (typeof answer === 'string') target = safeHref(answer) ? answer : null;
|
|
1021
|
+
}
|
|
1022
|
+
const label = target
|
|
1023
|
+
? h('a', { class: 'zx-surface__link-text', href: target, target: '_blank', rel: 'noopener noreferrer' }, text)
|
|
1024
|
+
: h('span', { class: 'zx-surface__link-text' }, text);
|
|
1025
|
+
return [label, host ? h('span', { class: 'zx-surface__host' }, ` (${host})`) : document.createTextNode('')];
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
/**
|
|
1029
|
+
* A chart; its data table is shown when there is no engine, and offered behind a toggle when
|
|
1030
|
+
* there is.
|
|
1031
|
+
* @private
|
|
1032
|
+
* @param {NodeView} view @param {Record<string, any>} props
|
|
1033
|
+
* @returns {NodeView}
|
|
1034
|
+
*/
|
|
1035
|
+
_chart(view, props) {
|
|
1036
|
+
const adapter = this.options.chartAdapter ?? null;
|
|
1037
|
+
const chart = new Chart(null, {
|
|
1038
|
+
adapter, type: props.kind, data: props.data, label: props.label, description: props.description ?? '',
|
|
1039
|
+
summary: adapter ? 'hidden' : 'visible'
|
|
1040
|
+
});
|
|
1041
|
+
view.owned.push(chart);
|
|
1042
|
+
view.el = h('div', { class: 'zx-surface__chart' }, chart.toElement());
|
|
1043
|
+
const summary = /** @type {HTMLElement|null} */ (chart.toElement().querySelector('.zx-chart__summary'));
|
|
1044
|
+
if (adapter && summary) {
|
|
1045
|
+
summary.id = uid(`${this._uid}-data`);
|
|
1046
|
+
const toggle = /** @type {HTMLButtonElement} */ (button({ label: this.msg('surface.dataTable'), kind: 'ghost', size: 'sm', icon: 'table' }));
|
|
1047
|
+
toggle.setAttribute('aria-expanded', 'false');
|
|
1048
|
+
toggle.setAttribute('aria-controls', summary.id);
|
|
1049
|
+
toggle.classList.add('zx-surface__data-toggle');
|
|
1050
|
+
this.listen(toggle, 'click', () => {
|
|
1051
|
+
const open = toggle.getAttribute('aria-expanded') !== 'true';
|
|
1052
|
+
toggle.setAttribute('aria-expanded', String(open));
|
|
1053
|
+
summary.dataset.summary = open ? 'visible' : 'hidden';
|
|
1054
|
+
});
|
|
1055
|
+
view.el.append(toggle);
|
|
1056
|
+
}
|
|
1057
|
+
return view;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/**
|
|
1061
|
+
* A schema drawn as a Fieldset; what was typed survives a redraw.
|
|
1062
|
+
* @private
|
|
1063
|
+
* @param {NodeView} view @param {Record<string, any>} props
|
|
1064
|
+
* @returns {NodeView}
|
|
1065
|
+
*/
|
|
1066
|
+
_fields(view, props) {
|
|
1067
|
+
const schema = props.schema;
|
|
1068
|
+
let fields;
|
|
1069
|
+
try {
|
|
1070
|
+
fields = schemaToFields(schema);
|
|
1071
|
+
} catch {
|
|
1072
|
+
return this._fallback();
|
|
1073
|
+
}
|
|
1074
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
1075
|
+
const property = schema.properties[name];
|
|
1076
|
+
if (typeof field.value === 'string' && property.type === 'string' && (property.format === 'date' || property.format === 'date-time')) {
|
|
1077
|
+
const date = parseLocal(field.value);
|
|
1078
|
+
if (date) field.value = date;
|
|
1079
|
+
else delete field.value;
|
|
1080
|
+
}
|
|
1081
|
+
// A native select's empty first option is a choice still to make: it says so.
|
|
1082
|
+
if (field.type === 'select' && field.options && Object.hasOwn(field.options, '') && !field.options['']) {
|
|
1083
|
+
field.options = { ...field.options, '': this.msg('surface.choose') };
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
const fieldset = new Fieldset(null, { title: props.title ?? '', fields: /** @type {any} */ (fields), idPrefix: `${this._uid}-${uid('f')}` });
|
|
1087
|
+
// A radio group is named by its field's label, as its radios are by their own.
|
|
1088
|
+
for (const field of Object.values(fieldset.getFields())) {
|
|
1089
|
+
const group = field.el.querySelector('[role="radiogroup"]');
|
|
1090
|
+
const label = field.el.querySelector(`[id="${CSS.escape(`${field.controlId}-label`)}"]`);
|
|
1091
|
+
if (group && label && !group.hasAttribute('aria-labelledby') && !group.hasAttribute('aria-label')) {
|
|
1092
|
+
group.setAttribute('aria-labelledby', label.id);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
/** @type {Record<string, unknown>} */
|
|
1096
|
+
const saved = {};
|
|
1097
|
+
for (const name of Object.keys(fields)) if (Object.hasOwn(this._raw, name)) saved[name] = this._raw[name];
|
|
1098
|
+
if (Object.keys(saved).length) fieldset.setValues(saved, { silent: true });
|
|
1099
|
+
view.owned.push(fieldset);
|
|
1100
|
+
view.fieldset = fieldset;
|
|
1101
|
+
view.schema = schema;
|
|
1102
|
+
view.el = h('div', { class: 'zx-surface__fields' }, fieldset.toElement());
|
|
1103
|
+
return view;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/**
|
|
1107
|
+
* Options to pick from, as a native group of radios or checkboxes.
|
|
1108
|
+
* @private
|
|
1109
|
+
* @param {NodeView} view @param {SurfaceNode} node @param {Record<string, any>} props
|
|
1110
|
+
* @returns {NodeView}
|
|
1111
|
+
*/
|
|
1112
|
+
_choice(view, node, props) {
|
|
1113
|
+
const name = String(node.name);
|
|
1114
|
+
const multiple = Boolean(props.multiple);
|
|
1115
|
+
const groupName = `${this._uid}-${name}`;
|
|
1116
|
+
const saved = this._raw[name];
|
|
1117
|
+
const picked = new Set(Array.isArray(saved) ? saved : saved == null ? [] : [saved]);
|
|
1118
|
+
const errorId = `${groupName}-error`;
|
|
1119
|
+
const error = h('p', { class: 'zx-surface__choice-error', id: errorId, role: 'alert', hidden: true });
|
|
1120
|
+
const set = /** @type {HTMLFieldSetElement} */ (h('fieldset', { class: 'zx-surface__choice', dataset: { name } },
|
|
1121
|
+
h('legend', { class: 'zx-surface__choice-legend' }, props.label),
|
|
1122
|
+
h('div', { class: 'zx-surface__choice-list' }, props.choices.map((/** @type {any} */ choice, /** @type {number} */ index) => {
|
|
1123
|
+
const id = `${groupName}-${index}`;
|
|
1124
|
+
const descriptionId = choice.description ? `${id}-description` : null;
|
|
1125
|
+
return h('div', { class: 'zx-surface__option' },
|
|
1126
|
+
h('input', {
|
|
1127
|
+
type: multiple ? 'checkbox' : 'radio', id, name: groupName, value: choice.value,
|
|
1128
|
+
checked: picked.has(choice.value), 'aria-describedby': descriptionId
|
|
1129
|
+
}),
|
|
1130
|
+
h('label', { for: id, class: 'zx-surface__option-label' },
|
|
1131
|
+
choice.icon ? h('span', { class: 'zx-surface__option-icon', 'aria-hidden': 'true' }, icon(choice.icon, { size: 16 })) : null,
|
|
1132
|
+
h('span', { class: 'zx-surface__option-text' }, choice.label,
|
|
1133
|
+
descriptionId ? h('span', { class: 'zx-surface__option-description', id: descriptionId }, choice.description) : null)));
|
|
1134
|
+
})),
|
|
1135
|
+
error));
|
|
1136
|
+
view.choice = set;
|
|
1137
|
+
view.choiceError = error;
|
|
1138
|
+
view.el = h('div', { class: 'zx-surface__choice-host' }, set);
|
|
1139
|
+
return view;
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
/**
|
|
1143
|
+
* Proposed changes as a table whose selected rows are the accepted ones.
|
|
1144
|
+
* @private
|
|
1145
|
+
* @param {NodeView} view @param {Record<string, any>} props
|
|
1146
|
+
* @returns {NodeView}
|
|
1147
|
+
*/
|
|
1148
|
+
_diff(view, props) {
|
|
1149
|
+
const rows = /** @type {Array<Record<string, any>>} */ (props.rows);
|
|
1150
|
+
const table = new Table(null, {
|
|
1151
|
+
columns: /** @type {any} */ (this._diffColumns(rows, view)),
|
|
1152
|
+
data: rows.map((row) => ({ ...row })),
|
|
1153
|
+
rowId: 'id',
|
|
1154
|
+
selectable: 'multi',
|
|
1155
|
+
label: props.label ?? null,
|
|
1156
|
+
stickyHeader: false
|
|
1157
|
+
});
|
|
1158
|
+
const saved = this._raw[/** @type {string} */ (props.name)];
|
|
1159
|
+
if (Array.isArray(saved)) table.setSelection(saved);
|
|
1160
|
+
table.on('selectionchange', () => this._inputChanged());
|
|
1161
|
+
view.owned.push(table);
|
|
1162
|
+
view.table = table;
|
|
1163
|
+
view.rowId = 'id';
|
|
1164
|
+
view.el = h('div', { class: 'zx-surface__diff' }, table.toElement());
|
|
1165
|
+
return view;
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
/**
|
|
1169
|
+
* @private
|
|
1170
|
+
* @param {Array<Record<string, any>>} rows @param {NodeView} view
|
|
1171
|
+
* @returns {Array<Record<string, unknown>>}
|
|
1172
|
+
*/
|
|
1173
|
+
_diffColumns(rows, view) {
|
|
1174
|
+
const cell = (/** @type {unknown} */ value) => (value === true ? this.msg('surface.yes') : value === false ? this.msg('surface.no')
|
|
1175
|
+
: value == null || value === '' ? h('span', { class: 'zx-surface__none' }, this.msg('surface.noAnswer')) : String(value));
|
|
1176
|
+
return [
|
|
1177
|
+
{
|
|
1178
|
+
id: 'label', label: this.msg('surface.field'),
|
|
1179
|
+
render: (/** @type {Record<string, any>} */ row) => (row.ref
|
|
1180
|
+
? h('span', { class: 'zx-surface__diff-label' }, String(row.label), this._ref(row.ref, view))
|
|
1181
|
+
: String(row.label))
|
|
1182
|
+
},
|
|
1183
|
+
{ id: 'before', label: this.msg('surface.before'), render: (/** @type {Record<string, any>} */ row) => cell(row.before) },
|
|
1184
|
+
{ id: 'after', label: this.msg('surface.after'), render: (/** @type {Record<string, any>} */ row) => cell(row.after) }
|
|
1185
|
+
];
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
/**
|
|
1189
|
+
* Steps asked one at a time; the Questionnaire's own submit answers the surface.
|
|
1190
|
+
* @private
|
|
1191
|
+
* @param {NodeView} view @param {Record<string, any>} props
|
|
1192
|
+
* @returns {NodeView}
|
|
1193
|
+
*/
|
|
1194
|
+
_questionnaire(view, props) {
|
|
1195
|
+
let questionnaire;
|
|
1196
|
+
try {
|
|
1197
|
+
questionnaire = new Questionnaire(null, {
|
|
1198
|
+
items: structuredClone(props.steps), review: Boolean(props.review), progress: props.steps.length > 1,
|
|
1199
|
+
msg: this.options.msg
|
|
1200
|
+
});
|
|
1201
|
+
} catch {
|
|
1202
|
+
return this._fallback();
|
|
1203
|
+
}
|
|
1204
|
+
const labelledBy = this._frame?.getAttribute('aria-labelledby');
|
|
1205
|
+
if (labelledBy) setFormAttribute(questionnaire.toElement(), 'aria-labelledby', labelledBy);
|
|
1206
|
+
questionnaire.on('submit', (event) => {
|
|
1207
|
+
event.preventDefault();
|
|
1208
|
+
void this._run('submit');
|
|
1209
|
+
});
|
|
1210
|
+
view.owned.push(questionnaire);
|
|
1211
|
+
view.questionnaire = questionnaire;
|
|
1212
|
+
view.el = h('div', { class: 'zx-surface__questionnaire' }, questionnaire.toElement());
|
|
1213
|
+
return view;
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* An input as the read-only record of what was answered.
|
|
1218
|
+
* @private
|
|
1219
|
+
* @param {SurfaceNode} node @param {Record<string, any>} props
|
|
1220
|
+
* @returns {NodeView}
|
|
1221
|
+
*/
|
|
1222
|
+
_receipt(node, props) {
|
|
1223
|
+
/** @type {NodeView} */
|
|
1224
|
+
const view = { el: h('div', { class: 'zx-surface__receipt' }), owned: [], kind: 'receipt' };
|
|
1225
|
+
const reply = /** @type {SurfaceReply} */ (this._reply);
|
|
1226
|
+
const values = reply.values ?? {};
|
|
1227
|
+
const answered = !VALUELESS.has(reply.action) && Object.keys(values).length > 0;
|
|
1228
|
+
// A table stays drawn whatever the answer; only what was picked in it is marked.
|
|
1229
|
+
if (!answered && node.type !== 'table' && node.type !== 'diff') {
|
|
1230
|
+
view.el.hidden = true;
|
|
1231
|
+
return view;
|
|
1232
|
+
}
|
|
1233
|
+
const none = () => h('span', { class: 'zx-surface__none' }, this.msg('surface.noAnswer'));
|
|
1234
|
+
/** @type {Array<[string, Node|string]>} */
|
|
1235
|
+
const pairs = [];
|
|
1236
|
+
switch (node.type) {
|
|
1237
|
+
case 'fields':
|
|
1238
|
+
for (const [name, property] of Object.entries(/** @type {Record<string, any>} */ (props.schema.properties))) {
|
|
1239
|
+
if (!Object.hasOwn(values, name) && this._hiddenAt(reply, node.id, name)) continue;
|
|
1240
|
+
const choices = choiceLabels(property);
|
|
1241
|
+
pairs.push([property.title || name, Object.hasOwn(values, name) ? this._display(values[name], choices) : none()]);
|
|
1242
|
+
}
|
|
1243
|
+
break;
|
|
1244
|
+
case 'choice': {
|
|
1245
|
+
if (!Object.hasOwn(values, String(node.name))) break;
|
|
1246
|
+
const choices = new Map(props.choices.map((/** @type {any} */ choice) => [choice.value, choice.label]));
|
|
1247
|
+
pairs.push([props.label, this._display(values[String(node.name)], choices)]);
|
|
1248
|
+
break;
|
|
1249
|
+
}
|
|
1250
|
+
case 'questionnaire': {
|
|
1251
|
+
const given = /** @type {Record<string, unknown>} */ (values.answers ?? {});
|
|
1252
|
+
const { answers, path } = visibleSteps(props.steps, given, /** @type {string[]} */ (Array.isArray(values.path) ? values.path : Object.keys(given)));
|
|
1253
|
+
for (const name of path) {
|
|
1254
|
+
const step = props.steps.find((/** @type {any} */ entry) => entry.name === name);
|
|
1255
|
+
if (!step || !Object.hasOwn(answers, name)) continue;
|
|
1256
|
+
const choices = new Map((step.choices ?? []).map((/** @type {any} */ choice) => [choice.value, choice.label]));
|
|
1257
|
+
pairs.push([step.prompt, this._display(answers[name], choices)]);
|
|
1258
|
+
}
|
|
1259
|
+
break;
|
|
1260
|
+
}
|
|
1261
|
+
case 'table':
|
|
1262
|
+
case 'diff': {
|
|
1263
|
+
const name = String(node.name ?? props.name ?? '');
|
|
1264
|
+
if (node.type === 'table' && !props.selectable) {
|
|
1265
|
+
view.kind = 'node';
|
|
1266
|
+
return this._table(view, props);
|
|
1267
|
+
}
|
|
1268
|
+
const selected = new Set(Array.isArray(values[name]) ? values[name] : values[name] == null ? [] : [values[name]]);
|
|
1269
|
+
const rowId = node.type === 'diff' ? 'id' : props.rowId;
|
|
1270
|
+
const rows = /** @type {Array<Record<string, any>>} */ (props.rows);
|
|
1271
|
+
const columns = node.type === 'diff' ? this._diffColumns(rows, view) : this._columns(props.columns, rows, view);
|
|
1272
|
+
const table = new Table(null, {
|
|
1273
|
+
columns: [{
|
|
1274
|
+
id: '__selected', label: '', ariaLabel: this.msg('surface.selected'), width: '2.5rem',
|
|
1275
|
+
render: (/** @type {Record<string, any>} */ row) => (selected.has(ownValue(row, rowId))
|
|
1276
|
+
? h('span', { class: 'zx-surface__mark' }, icon('check', { size: 14 }), h('span', { class: 'zx-surface__sr' }, this.msg('surface.selected')))
|
|
1277
|
+
: '')
|
|
1278
|
+
}, ...columns].map((column) => /** @type {any} */ (column)),
|
|
1279
|
+
data: node.type === 'diff' ? rows.map((row) => ({ ...row })) : drawnRows(rows, props.columns),
|
|
1280
|
+
rowId: node.type === 'diff' ? rowId : drawnRowId(rowId),
|
|
1281
|
+
label: props.label ?? null,
|
|
1282
|
+
stickyHeader: false
|
|
1283
|
+
});
|
|
1284
|
+
view.owned.push(table);
|
|
1285
|
+
view.el.append(table.toElement());
|
|
1286
|
+
for (const row of view.el.querySelectorAll('tbody tr')) {
|
|
1287
|
+
if (row.querySelector('.zx-surface__mark')) /** @type {HTMLElement} */ (row).dataset.selected = 'true';
|
|
1288
|
+
}
|
|
1289
|
+
return view;
|
|
1290
|
+
}
|
|
1291
|
+
default:
|
|
1292
|
+
break;
|
|
1293
|
+
}
|
|
1294
|
+
if (!pairs.length) {
|
|
1295
|
+
view.el.hidden = true;
|
|
1296
|
+
return view;
|
|
1297
|
+
}
|
|
1298
|
+
view.el.append(h('dl', { class: 'zx-surface__answers' }, pairs.map(([label, value]) => h('div', { class: 'zx-surface__answer' },
|
|
1299
|
+
h('dt', {}, label), h('dd', {}, value)))));
|
|
1300
|
+
return view;
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
/** @private @param {SurfaceReply} reply @param {string} id @param {string} name @returns {boolean} */
|
|
1304
|
+
_hiddenAt(reply, id, name) {
|
|
1305
|
+
const visibility = surfaceVisibility(this._docLike(), reply.values ?? {});
|
|
1306
|
+
return visibility.hiddenNodes.has(id) || Boolean(visibility.hiddenFields.get(id)?.has(name));
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/** @private @param {unknown} value @param {Map<unknown, string>} choices @returns {string} */
|
|
1310
|
+
_display(value, choices) {
|
|
1311
|
+
const one = (/** @type {unknown} */ entry) => (choices.has(entry) ? String(choices.get(entry))
|
|
1312
|
+
: entry === true ? this.msg('surface.yes') : entry === false ? this.msg('surface.no') : String(entry));
|
|
1313
|
+
if (Array.isArray(value)) return value.length ? value.map(one).join(', ') : this.msg('surface.noAnswer');
|
|
1314
|
+
return one(value);
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
/* ------------------------------------------------------------------ inputs -- */
|
|
1318
|
+
|
|
1319
|
+
/**
|
|
1320
|
+
* Reads every input's raw value — what its control holds, hidden inputs included.
|
|
1321
|
+
* @private
|
|
1322
|
+
* @returns {Record<string, unknown>}
|
|
1323
|
+
*/
|
|
1324
|
+
_collectRaw() {
|
|
1325
|
+
/** @type {Record<string, unknown>} */
|
|
1326
|
+
const raw = {};
|
|
1327
|
+
for (const [id, view] of this._views) {
|
|
1328
|
+
const node = this._model.nodes.get(id);
|
|
1329
|
+
if (!node || view.kind !== 'node') continue;
|
|
1330
|
+
if (view.fieldset) Object.assign(raw, view.fieldset.getValues());
|
|
1331
|
+
else if (view.choice) {
|
|
1332
|
+
const checked = [...view.choice.querySelectorAll('input:checked')].map((input) => /** @type {HTMLInputElement} */ (input).value);
|
|
1333
|
+
const multiple = view.choice.querySelector('input[type="checkbox"]') !== null;
|
|
1334
|
+
raw[String(node.name)] = multiple ? checked : checked[0] ?? null;
|
|
1335
|
+
} else if (view.table && typeof node.name === 'string' && (node.type === 'diff' || this._prop(node, 'selectable'))) {
|
|
1336
|
+
const key = /** @type {string} */ (view.rowId);
|
|
1337
|
+
const ids = view.table.getSelection().map((row) => ownValue(row, key)).filter((id) => id !== null);
|
|
1338
|
+
raw[node.name] = node.type === 'table' && this._prop(node, 'selectable') === 'single' ? ids[0] ?? null : ids;
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
return raw;
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/**
|
|
1345
|
+
* The inputs' values as JSON, empty ones left out; hidden ones included.
|
|
1346
|
+
* @private
|
|
1347
|
+
* @returns {Record<string, unknown>}
|
|
1348
|
+
*/
|
|
1349
|
+
_jsonValues() {
|
|
1350
|
+
const raw = { ...this._raw, ...this._collectRaw() };
|
|
1351
|
+
/** @type {Record<string, unknown>} */
|
|
1352
|
+
const out = {};
|
|
1353
|
+
for (const [id, node] of this._model.nodes) {
|
|
1354
|
+
const view = this._views.get(id);
|
|
1355
|
+
if (node.type === 'fields') {
|
|
1356
|
+
const schema = view?.schema ?? this._prop(node, 'schema');
|
|
1357
|
+
if (!schema?.properties) continue;
|
|
1358
|
+
for (const [name, property] of Object.entries(/** @type {Record<string, any>} */ (schema.properties))) {
|
|
1359
|
+
if (!Object.hasOwn(raw, name)) continue;
|
|
1360
|
+
const value = toJsonValue(property, raw[name]);
|
|
1361
|
+
const empty = isEmptyAnswer(value) || (property.type === 'boolean' && typeof value !== 'boolean');
|
|
1362
|
+
if (!empty) out[name] = value;
|
|
1363
|
+
}
|
|
1364
|
+
} else {
|
|
1365
|
+
for (const name of inputNames(node, this._model.data)) {
|
|
1366
|
+
if (Object.hasOwn(raw, name) && raw[name] !== null && raw[name] !== undefined) out[name] = structuredClone(raw[name]);
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
return out;
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
/** @private @returns {any} The model as `surfaceVisibility()` and `createReply()` read it. */
|
|
1374
|
+
_docLike() {
|
|
1375
|
+
const model = this._model;
|
|
1376
|
+
/** @type {Map<string, SurfaceNode>} */
|
|
1377
|
+
const nodes = new Map();
|
|
1378
|
+
for (const [id, node] of model.nodes) {
|
|
1379
|
+
if (!hasBinding(node)) {
|
|
1380
|
+
nodes.set(id, node);
|
|
1381
|
+
continue;
|
|
1382
|
+
}
|
|
1383
|
+
const resolved = { ...node };
|
|
1384
|
+
for (const key of Object.keys(node)) if (isBinding(node[key])) resolved[key] = this._prop(node, key);
|
|
1385
|
+
nodes.set(id, resolved);
|
|
1386
|
+
}
|
|
1387
|
+
return { zx: SURFACE_VERSION, surface: model.surface, intent: model.intent, root: model.root, nodes, data: model.data, actions: model.actions ?? [] };
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
/** @private @param {Record<string, unknown>} values @returns {import('./text.js').SurfaceVisibility} */
|
|
1391
|
+
_visibilityFor(values) {
|
|
1392
|
+
return surfaceVisibility(this._docLike(), values);
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/**
|
|
1396
|
+
* Something was typed, picked or selected: reports each input whose value changed, and shows
|
|
1397
|
+
* and hides what depends on it.
|
|
1398
|
+
* @private
|
|
1399
|
+
* @returns {void}
|
|
1400
|
+
*/
|
|
1401
|
+
_inputChanged() {
|
|
1402
|
+
if (this._reply || !this._model.began) return;
|
|
1403
|
+
Object.assign(this._raw, this._collectRaw());
|
|
1404
|
+
const values = this._jsonValues();
|
|
1405
|
+
/** @type {string[]} */
|
|
1406
|
+
const changed = [];
|
|
1407
|
+
const names = new Set([...Object.keys(values), ...Object.keys(this._reportedValues)]);
|
|
1408
|
+
for (const name of names) {
|
|
1409
|
+
const json = values[name] === undefined ? '' : JSON.stringify(values[name]);
|
|
1410
|
+
if ((this._reportedValues[name] ?? '') === json) continue;
|
|
1411
|
+
if (json) this._reportedValues[name] = json;
|
|
1412
|
+
else delete this._reportedValues[name];
|
|
1413
|
+
changed.push(name);
|
|
1414
|
+
}
|
|
1415
|
+
if (!changed.length) return;
|
|
1416
|
+
this._syncVisibility(changed);
|
|
1417
|
+
for (const name of changed) {
|
|
1418
|
+
this._clearError(name);
|
|
1419
|
+
this.emit('change', { name, value: values[name] === undefined ? null : structuredClone(values[name]) });
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
/**
|
|
1424
|
+
* Shows and hides nodes and fields for the current values. A node that hides while it holds
|
|
1425
|
+
* the focus hands it to the input whose value hid it.
|
|
1426
|
+
* @private
|
|
1427
|
+
* @param {string[]} [changed=[]] The inputs that just changed.
|
|
1428
|
+
* @returns {void}
|
|
1429
|
+
*/
|
|
1430
|
+
_syncVisibility(changed = []) {
|
|
1431
|
+
// Answered, the surface shows what the reply says, which a restored one has no inputs for.
|
|
1432
|
+
const visibility = this._visibilityFor(this._reply ? this._reply.values ?? {} : this._jsonValues());
|
|
1433
|
+
this._visibility = visibility;
|
|
1434
|
+
const active = document.activeElement;
|
|
1435
|
+
let lost = false;
|
|
1436
|
+
for (const [id, view] of this._views) {
|
|
1437
|
+
const hidden = visibility.hiddenNodes.has(id);
|
|
1438
|
+
if (hidden && !view.el.hidden && active && view.el.contains(active)) lost = true;
|
|
1439
|
+
view.el.hidden = hidden;
|
|
1440
|
+
if (view.fieldset) {
|
|
1441
|
+
const fieldsHidden = visibility.hiddenFields.get(id) ?? new Set();
|
|
1442
|
+
for (const [name, field] of Object.entries(view.fieldset.getFields())) {
|
|
1443
|
+
const hide = fieldsHidden.has(name);
|
|
1444
|
+
const element = /** @type {HTMLElement} */ (field.el);
|
|
1445
|
+
if (hide && !element.hidden && active && element.contains(active)) lost = true;
|
|
1446
|
+
element.hidden = hide;
|
|
1447
|
+
if (hide) field.clearHighlight();
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
if (lost) {
|
|
1452
|
+
const target = changed.find((name) => visibility.names.includes(name));
|
|
1453
|
+
if (target) this._focusInput(target);
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
/**
|
|
1458
|
+
* @private
|
|
1459
|
+
* @param {string} name
|
|
1460
|
+
* @returns {boolean} Whether an input took the focus.
|
|
1461
|
+
*/
|
|
1462
|
+
_focusInput(name) {
|
|
1463
|
+
const owner = this._visibility?.owners.get(name) ?? surfaceVisibility(this._docLike(), {}).owners.get(name);
|
|
1464
|
+
const view = owner ? this._views.get(owner) : null;
|
|
1465
|
+
if (!view) return false;
|
|
1466
|
+
if (view.fieldset) {
|
|
1467
|
+
view.fieldset.focus(name);
|
|
1468
|
+
return true;
|
|
1469
|
+
}
|
|
1470
|
+
if (view.choice) {
|
|
1471
|
+
const input = /** @type {HTMLInputElement|null} */ (view.choice.querySelector('input:checked') ?? view.choice.querySelector('input'));
|
|
1472
|
+
input?.focus();
|
|
1473
|
+
return Boolean(input);
|
|
1474
|
+
}
|
|
1475
|
+
if (view.table) {
|
|
1476
|
+
const target = /** @type {HTMLElement|null} */ (view.table.toElement().querySelector('[tabindex="0"]') ?? view.table.toElement().querySelector('input'));
|
|
1477
|
+
target?.focus();
|
|
1478
|
+
return Boolean(target);
|
|
1479
|
+
}
|
|
1480
|
+
return false;
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
/** @private @param {NodeView} view @returns {void} */
|
|
1484
|
+
_refocus(view) {
|
|
1485
|
+
const target = /** @type {HTMLElement|null} */ (view.el.querySelector('input, select, textarea, button, [tabindex]'));
|
|
1486
|
+
target?.focus();
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
/**
|
|
1490
|
+
* Checks the visible inputs before an action replies: each schema, and a pick for each choice.
|
|
1491
|
+
* Marks what failed and returns the values to send.
|
|
1492
|
+
* @private
|
|
1493
|
+
* @returns {{values: Record<string, unknown>, invalid: string|null}}
|
|
1494
|
+
*/
|
|
1495
|
+
_check() {
|
|
1496
|
+
Object.assign(this._raw, this._collectRaw());
|
|
1497
|
+
const values = this._jsonValues();
|
|
1498
|
+
const visibility = this._visibilityFor(values);
|
|
1499
|
+
/** @type {Record<string, unknown>} */
|
|
1500
|
+
const out = {};
|
|
1501
|
+
/** @type {string|null} */
|
|
1502
|
+
let invalid = null;
|
|
1503
|
+
// The same keys as a questionnaire's rules, so one translation serves both.
|
|
1504
|
+
const msg = (/** @type {string} */ key, /** @type {unknown[]} */ ...args) => this.msg(key, ...args);
|
|
1505
|
+
const message = (/** @type {string} */ key, /** @type {unknown[]} */ ...args) => (key === 'required'
|
|
1506
|
+
? this.msg('questionnaire.requiredInput')
|
|
1507
|
+
: ruleText(msg, key, ...args));
|
|
1508
|
+
for (const name of visibility.names) {
|
|
1509
|
+
const owner = /** @type {string} */ (visibility.owners.get(name));
|
|
1510
|
+
const view = this._views.get(owner);
|
|
1511
|
+
if (view?.fieldset || view?.choice) continue;
|
|
1512
|
+
if (Object.hasOwn(values, name)) out[name] = values[name];
|
|
1513
|
+
}
|
|
1514
|
+
for (const [id, view] of this._views) {
|
|
1515
|
+
if (view.kind !== 'node' || visibility.hiddenNodes.has(id)) continue;
|
|
1516
|
+
if (view.fieldset && view.schema) {
|
|
1517
|
+
const raw = view.fieldset.getValues();
|
|
1518
|
+
const hidden = visibility.hiddenFields.get(id) ?? new Set();
|
|
1519
|
+
const result = checkValue(/** @type {any} */ (view.schema), raw, hidden, message);
|
|
1520
|
+
/** @type {Record<string, string>} */
|
|
1521
|
+
const highlights = {};
|
|
1522
|
+
for (const problem of result.errors) highlights[problem.name] = problem.message;
|
|
1523
|
+
view.fieldset.setHighlights(highlights);
|
|
1524
|
+
if (result.errors.length && !invalid) invalid = result.errors[0].name;
|
|
1525
|
+
Object.assign(out, result.values);
|
|
1526
|
+
} else if (view.choice) {
|
|
1527
|
+
const node = /** @type {SurfaceNode} */ (this._model.nodes.get(id));
|
|
1528
|
+
const name = String(node.name);
|
|
1529
|
+
const value = values[name];
|
|
1530
|
+
const multiple = view.choice.querySelector('input[type="checkbox"]') !== null;
|
|
1531
|
+
const missing = !multiple && isEmptyAnswer(value);
|
|
1532
|
+
this._choiceError(view, missing ? this.msg('surface.choiceRequired') : '');
|
|
1533
|
+
if (missing) {
|
|
1534
|
+
if (!invalid) invalid = name;
|
|
1535
|
+
} else {
|
|
1536
|
+
out[name] = multiple && value == null ? [] : value;
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
return { values: out, invalid };
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
/** @private @param {NodeView} view @param {string} text @returns {void} */
|
|
1544
|
+
_choiceError(view, text) {
|
|
1545
|
+
if (!view.choice || !view.choiceError) return;
|
|
1546
|
+
view.choiceError.textContent = text;
|
|
1547
|
+
view.choiceError.hidden = !text;
|
|
1548
|
+
if (text) {
|
|
1549
|
+
view.choice.setAttribute('aria-invalid', 'true');
|
|
1550
|
+
view.choice.setAttribute('aria-describedby', view.choiceError.id);
|
|
1551
|
+
} else {
|
|
1552
|
+
view.choice.removeAttribute('aria-invalid');
|
|
1553
|
+
view.choice.removeAttribute('aria-describedby');
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
/** @private @param {string} name @returns {void} */
|
|
1558
|
+
_clearError(name) {
|
|
1559
|
+
const owner = this._visibility?.owners.get(name);
|
|
1560
|
+
const view = owner ? this._views.get(owner) : null;
|
|
1561
|
+
if (view?.fieldset) view.fieldset.getField(name)?.clearHighlight();
|
|
1562
|
+
if (view?.choice) this._choiceError(view, '');
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
/** @private @returns {NodeView|null} */
|
|
1566
|
+
_questionnaireView() {
|
|
1567
|
+
for (const view of this._views.values()) if (view.questionnaire) return view;
|
|
1568
|
+
return null;
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
/* ------------------------------------------------------------------ actions -- */
|
|
1572
|
+
|
|
1573
|
+
/**
|
|
1574
|
+
* The actions this surface draws: its own, or the intent's defaults, then Cancel where the
|
|
1575
|
+
* intent has one. Each is put to the policy; a denied one is not drawn.
|
|
1576
|
+
* @private
|
|
1577
|
+
* @returns {void}
|
|
1578
|
+
*/
|
|
1579
|
+
_drawActions() {
|
|
1580
|
+
const host = this._actionsEl;
|
|
1581
|
+
if (!host) return;
|
|
1582
|
+
if (this._actionsDirty) {
|
|
1583
|
+
this._actionsDirty = false;
|
|
1584
|
+
this._actions = this._actionList();
|
|
1585
|
+
this._removed = [];
|
|
1586
|
+
this._decisions.clear();
|
|
1587
|
+
/** @type {SurfaceDocument|null} */
|
|
1588
|
+
let snapshot = null;
|
|
1589
|
+
for (const action of this._actions) {
|
|
1590
|
+
if (action.builtin) continue;
|
|
1591
|
+
snapshot ??= deepFreeze(/** @type {SurfaceDocument} */ (this.toDocument()));
|
|
1592
|
+
const decision = decide(this.options.policy, action, snapshot);
|
|
1593
|
+
if (decision.level === 'deny') this._removed.push(action.id);
|
|
1594
|
+
this._decisions.set(action.id, decision);
|
|
1595
|
+
}
|
|
1596
|
+
if (this._model.intent === 'questionnaire') {
|
|
1597
|
+
// The questionnaire answers through its own Submit, which the policy decides up front too.
|
|
1598
|
+
snapshot ??= deepFreeze(/** @type {SurfaceDocument} */ (this.toDocument()));
|
|
1599
|
+
const decision = decide(this.options.policy, { id: 'submit', label: this.msg('surface.submit') }, snapshot);
|
|
1600
|
+
this._decisions.set('submit', decision);
|
|
1601
|
+
if (decision.level === 'deny') this._removed.push('submit');
|
|
1602
|
+
if (decision.level === 'deny') /** @type {HTMLElement} */ (this.el).dataset.submit = 'denied';
|
|
1603
|
+
else delete /** @type {HTMLElement} */ (this.el).dataset.submit;
|
|
1604
|
+
}
|
|
1605
|
+
this._actions = this._actions.filter((action) => !this._removed.includes(action.id));
|
|
1606
|
+
// A review's Reject is its way out; without one, it gets the Cancel the others have.
|
|
1607
|
+
if (this._model.intent === 'review' && !this._actions.some((action) => action.id === 'reject')) this._actions.push(this._cancelAction());
|
|
1608
|
+
host.replaceChildren(...this._actions.map((action) => {
|
|
1609
|
+
const element = /** @type {HTMLButtonElement} */ (button({
|
|
1610
|
+
label: action.label,
|
|
1611
|
+
kind: action.kind === 'danger' ? 'danger' : action.kind === 'primary' ? 'primary' : 'default'
|
|
1612
|
+
}));
|
|
1613
|
+
element.dataset.surfaceAction = action.id;
|
|
1614
|
+
if (action.builtin) element.dataset.surfaceBuiltin = 'cancel';
|
|
1615
|
+
if (action.kind === 'primary' && !action.builtin && this._asking) element.type = 'submit';
|
|
1616
|
+
if (action.description) element.title = action.description;
|
|
1617
|
+
return element;
|
|
1618
|
+
}));
|
|
1619
|
+
host.hidden = this._actions.length === 0;
|
|
1620
|
+
}
|
|
1621
|
+
for (const element of host.querySelectorAll('button[data-surface-action]')) {
|
|
1622
|
+
const builtin = /** @type {HTMLElement} */ (element).dataset.surfaceBuiltin === 'cancel';
|
|
1623
|
+
/** @type {HTMLButtonElement} */ (element).disabled = this._busy || (!builtin && !this._model.ended);
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
/** @private @returns {DrawnAction[]} */
|
|
1628
|
+
_actionList() {
|
|
1629
|
+
const intent = this._model.intent;
|
|
1630
|
+
if (!intent) return [];
|
|
1631
|
+
/** @type {DrawnAction[]} */
|
|
1632
|
+
const list = [];
|
|
1633
|
+
const own = this._model.actions ?? [];
|
|
1634
|
+
if (own.length) list.push(...own);
|
|
1635
|
+
else if (intent === 'ask' || intent === 'choose') list.push({ id: 'submit', label: this.msg('surface.submit'), kind: 'primary' });
|
|
1636
|
+
else if (intent === 'confirm') list.push({ id: 'confirm', label: this.msg('surface.confirm'), kind: 'primary' });
|
|
1637
|
+
else if (intent === 'review') {
|
|
1638
|
+
list.push({ id: 'approve', label: this.msg('surface.approve'), kind: 'primary' }, { id: 'reject', label: this.msg('surface.reject') });
|
|
1639
|
+
}
|
|
1640
|
+
if (CANCEL_INTENTS.has(intent)) list.push(this._cancelAction());
|
|
1641
|
+
return list;
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
/** @private @returns {DrawnAction} */
|
|
1645
|
+
_cancelAction() {
|
|
1646
|
+
return { id: 'cancel', label: this.msg('surface.cancel'), builtin: true };
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
/**
|
|
1650
|
+
* Runs an action: checks the inputs, asks the confirmation the policy wants, and replies.
|
|
1651
|
+
* @private
|
|
1652
|
+
* @param {string} id
|
|
1653
|
+
* @returns {Promise<void>}
|
|
1654
|
+
*/
|
|
1655
|
+
async _run(id) {
|
|
1656
|
+
if (this._reply || this._busy || this._destroyed) return;
|
|
1657
|
+
const action = this._actions.find((entry) => entry.id === id);
|
|
1658
|
+
const intent = this._model.intent;
|
|
1659
|
+
if (id === 'submit' && intent === 'questionnaire' && !action) {
|
|
1660
|
+
// The questionnaire's own submit: the default action of its intent.
|
|
1661
|
+
return this._answer({ id: 'submit', label: this.msg('surface.submit') });
|
|
1662
|
+
}
|
|
1663
|
+
if (!action) return;
|
|
1664
|
+
if (action.builtin) {
|
|
1665
|
+
this.cancel('cancelled');
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
return this._answer(action);
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
/**
|
|
1672
|
+
* @private
|
|
1673
|
+
* @param {SurfaceAction} action
|
|
1674
|
+
* @returns {Promise<void>}
|
|
1675
|
+
*/
|
|
1676
|
+
async _answer(action) {
|
|
1677
|
+
if (!this._model.ended) return;
|
|
1678
|
+
const intent = this._model.intent;
|
|
1679
|
+
let decision = this._decisions.get(action.id);
|
|
1680
|
+
if (!decision) {
|
|
1681
|
+
decision = decide(this.options.policy, action, deepFreeze(/** @type {SurfaceDocument} */ (this.toDocument())));
|
|
1682
|
+
this._decisions.set(action.id, decision);
|
|
1683
|
+
}
|
|
1684
|
+
if (decision.level === 'deny') return;
|
|
1685
|
+
/** @type {Record<string, unknown>} */
|
|
1686
|
+
let values = {};
|
|
1687
|
+
if (intent === 'questionnaire') {
|
|
1688
|
+
const view = this._questionnaireView();
|
|
1689
|
+
values = view?.questionnaire ? { answers: view.questionnaire.getAnswers(), path: view.questionnaire.getPath() } : {};
|
|
1690
|
+
} else if (this._answers(action) && intent !== 'show' && intent !== 'confirm') {
|
|
1691
|
+
const checked = this._check();
|
|
1692
|
+
if (checked.invalid) {
|
|
1693
|
+
this._focusInput(checked.invalid);
|
|
1694
|
+
return;
|
|
1695
|
+
}
|
|
1696
|
+
values = checked.values;
|
|
1697
|
+
}
|
|
1698
|
+
/** @type {import('./text.js').ReplyConfirmation} */
|
|
1699
|
+
let confirmation = null;
|
|
1700
|
+
if (decision.level === 'confirm' || decision.level === 'type-to-confirm') {
|
|
1701
|
+
const typed = decision.level === 'type-to-confirm';
|
|
1702
|
+
this._busy = true;
|
|
1703
|
+
this._drawActions();
|
|
1704
|
+
const doc = this.el.ownerDocument;
|
|
1705
|
+
const before = new Set(doc.querySelectorAll('dialog'));
|
|
1706
|
+
let confirmed = false;
|
|
1707
|
+
try {
|
|
1708
|
+
const answer = Dialog.confirm({
|
|
1709
|
+
title: this._model.title ?? action.label,
|
|
1710
|
+
message: decision.message ?? action.description ?? '',
|
|
1711
|
+
okLabel: action.label,
|
|
1712
|
+
cancelLabel: this.msg('surface.cancel'),
|
|
1713
|
+
danger: typed || action.kind === 'danger',
|
|
1714
|
+
// The phrase to type is the application's, never the model's.
|
|
1715
|
+
confirmText: typed ? decision.confirmText || this.msg('surface.typeToConfirm') : null
|
|
1716
|
+
});
|
|
1717
|
+
const opened = [...doc.querySelectorAll('dialog')].find((element) => !before.has(element));
|
|
1718
|
+
this._confirm = opened ? /** @type {Dialog|null} */ (Dialog.from(opened)) : null;
|
|
1719
|
+
confirmed = await answer;
|
|
1720
|
+
} finally {
|
|
1721
|
+
this._busy = false;
|
|
1722
|
+
this._confirm = null;
|
|
1723
|
+
}
|
|
1724
|
+
if (this._reply || this._destroyed) return;
|
|
1725
|
+
this._drawActions();
|
|
1726
|
+
if (!confirmed) return;
|
|
1727
|
+
confirmation = typed ? 'typed' : 'clicked';
|
|
1728
|
+
}
|
|
1729
|
+
this._finish(createReply(this._docLike(), {
|
|
1730
|
+
action: action.id, values, confirmation, token: this._token, removed: this._removed
|
|
1731
|
+
}));
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
/**
|
|
1735
|
+
* Replies with a closing action, unless the surface already replied.
|
|
1736
|
+
* @private
|
|
1737
|
+
* @param {'cancel'|'dismiss'} action @param {ReplyReason} reason
|
|
1738
|
+
* @returns {void}
|
|
1739
|
+
*/
|
|
1740
|
+
_close(action, reason) {
|
|
1741
|
+
if (this._reply || this._destroyed) return;
|
|
1742
|
+
/** @type {SurfaceReply|null} */
|
|
1743
|
+
let reply = null;
|
|
1744
|
+
if (this._model.began) {
|
|
1745
|
+
try {
|
|
1746
|
+
reply = createReply(this._docLike(), { action, reason, token: this._token, removed: this._removed });
|
|
1747
|
+
} catch (error) {
|
|
1748
|
+
this._drawFailed(error);
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
this._finish(reply ?? this._bareReply(action, reason));
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
/**
|
|
1755
|
+
* The closing reply when no fuller one can be built: nothing valid began, say. It is owed all
|
|
1756
|
+
* the same.
|
|
1757
|
+
* @private
|
|
1758
|
+
* @param {'cancel'|'dismiss'} action @param {ReplyReason} reason
|
|
1759
|
+
* @returns {SurfaceReply}
|
|
1760
|
+
*/
|
|
1761
|
+
_bareReply(action, reason) {
|
|
1762
|
+
const surface = this._model.surface || this._named;
|
|
1763
|
+
/** @type {SurfaceReply} */
|
|
1764
|
+
const reply = {
|
|
1765
|
+
zx: /** @type {'reply/1'} */ (REPLY_VERSION), surface, action, key: `${surface ?? ''}#${action}`,
|
|
1766
|
+
values: {}, confirmation: null, at: localDateTime(new Date())
|
|
1767
|
+
};
|
|
1768
|
+
if (this._token !== null) reply.token = this._token;
|
|
1769
|
+
if (reason) reply.reason = reason;
|
|
1770
|
+
return reply;
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
/**
|
|
1774
|
+
* Whether an action answers: checks the inputs and sends their values. The intent's answering
|
|
1775
|
+
* defaults do, and so does an action of the surface's own with `kind: 'primary'`; any other
|
|
1776
|
+
* replies with no values.
|
|
1777
|
+
* @private
|
|
1778
|
+
* @param {SurfaceAction} action
|
|
1779
|
+
* @returns {boolean}
|
|
1780
|
+
*/
|
|
1781
|
+
_answers(action) {
|
|
1782
|
+
const own = (this._model.actions ?? []).some((entry) => entry.id === action.id);
|
|
1783
|
+
return own ? action.kind === 'primary' : ANSWERING.has(action.id);
|
|
1784
|
+
}
|
|
1785
|
+
|
|
1786
|
+
/**
|
|
1787
|
+
* Records the one reply, freezes the surface into its receipt, and reports it.
|
|
1788
|
+
* @private
|
|
1789
|
+
* @param {SurfaceReply} reply
|
|
1790
|
+
* @returns {void}
|
|
1791
|
+
*/
|
|
1792
|
+
_finish(reply) {
|
|
1793
|
+
if (this._reply) return;
|
|
1794
|
+
this._reply = reply;
|
|
1795
|
+
// The reply is owed whatever happens to the receipt.
|
|
1796
|
+
try {
|
|
1797
|
+
this._confirm?.close(false);
|
|
1798
|
+
if (!this._model.began) {
|
|
1799
|
+
this._waiting?.remove();
|
|
1800
|
+
this.el.removeAttribute('aria-busy');
|
|
1801
|
+
/** @type {HTMLElement} */ (this.el).dataset.state = 'answered';
|
|
1802
|
+
}
|
|
1803
|
+
const hadFocus = this.el.contains(document.activeElement);
|
|
1804
|
+
if (!this._destroyed) {
|
|
1805
|
+
this._draw();
|
|
1806
|
+
if (hadFocus && this._verdict) this._verdict.focus({ preventScroll: true });
|
|
1807
|
+
}
|
|
1808
|
+
} catch (error) {
|
|
1809
|
+
this._drawFailed(error);
|
|
1810
|
+
}
|
|
1811
|
+
this.emit('reply', { reply: structuredClone(reply) });
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
/**
|
|
1815
|
+
* Turns the surface into the record of its answer: inputs redrawn as what was answered, and the
|
|
1816
|
+
* actions replaced by the verdict.
|
|
1817
|
+
* @private
|
|
1818
|
+
* @returns {void}
|
|
1819
|
+
*/
|
|
1820
|
+
_freeze() {
|
|
1821
|
+
const reply = /** @type {SurfaceReply} */ (this._reply);
|
|
1822
|
+
this._frozen = true;
|
|
1823
|
+
/** @type {HTMLElement} */ (this.el).dataset.state = 'answered';
|
|
1824
|
+
for (const [id, node] of this._model.nodes) if (this._entry(node.type)?.input) this._dirty.add(id);
|
|
1825
|
+
const time = formatTime(reply.at, this.options.locale);
|
|
1826
|
+
const verdict = verdictText(reply.action, this._model.actions ?? [], (key, ...args) => this.msg(key, ...args));
|
|
1827
|
+
this._verdict = h('p', { class: 'zx-surface__verdict', tabIndex: -1, dataset: { action: reply.action } },
|
|
1828
|
+
h('span', { class: 'zx-surface__verdict-icon', 'aria-hidden': 'true' },
|
|
1829
|
+
icon(CLOSING_ACTIONS.includes(reply.action) || reply.action === 'reject' ? 'x' : 'check', { size: 14 })),
|
|
1830
|
+
h('span', {}, time ? this.msg('surface.verdictAt', verdict, time) : verdict));
|
|
1831
|
+
this._actionsEl?.replaceWith(this._verdict);
|
|
1832
|
+
this._actionsEl = null;
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
/** @private @param {KeyboardEvent} event @returns {void} */
|
|
1836
|
+
_onKeydown(event) {
|
|
1837
|
+
if (event.key !== 'Escape' || event.defaultPrevented || event.isComposing || this._reply || this._busy) return;
|
|
1838
|
+
if (!this._waits()) return;
|
|
1839
|
+
// An Escape that closes something nested — an open popover, an expanded list — is not ours.
|
|
1840
|
+
if (this._escapeIsNested(event)) return;
|
|
1841
|
+
// Decide once every other handler had its turn: one that handled the key prevents it.
|
|
1842
|
+
setTimeout(() => {
|
|
1843
|
+
if (event.defaultPrevented || this._reply || this._busy || this._destroyed) return;
|
|
1844
|
+
this.cancel('escape');
|
|
1845
|
+
}, 0);
|
|
1846
|
+
}
|
|
1847
|
+
|
|
1848
|
+
/**
|
|
1849
|
+
* @private
|
|
1850
|
+
* @returns {boolean} Whether someone is expected to answer: every intent that asks, and a `show`
|
|
1851
|
+
* surface with actions of its own. One without any has nothing to close.
|
|
1852
|
+
*/
|
|
1853
|
+
_waits() {
|
|
1854
|
+
const intent = this._model.intent;
|
|
1855
|
+
return intent !== null && (intent !== 'show' || this._actions.length > 0);
|
|
1856
|
+
}
|
|
1857
|
+
|
|
1858
|
+
/**
|
|
1859
|
+
* @private
|
|
1860
|
+
* @param {KeyboardEvent} event
|
|
1861
|
+
* @returns {boolean} Whether a nested control owns the Escape.
|
|
1862
|
+
*/
|
|
1863
|
+
_escapeIsNested(event) {
|
|
1864
|
+
const target = /** @type {Element|null} */ (event.target instanceof Element ? event.target : null);
|
|
1865
|
+
if (target?.closest('[aria-expanded="true"]')) return true;
|
|
1866
|
+
if (this.el.querySelector('[aria-expanded="true"]:not(.zx-surface__data-toggle)')) return true;
|
|
1867
|
+
const doc = this.el.ownerDocument;
|
|
1868
|
+
for (const open of doc.querySelectorAll(':popover-open')) {
|
|
1869
|
+
if (!open.contains(this.el)) return true;
|
|
1870
|
+
}
|
|
1871
|
+
// A dialog opened above the surface, not the one that holds it.
|
|
1872
|
+
for (const dialog of doc.querySelectorAll('dialog[open]')) {
|
|
1873
|
+
if (!dialog.contains(this.el) && target && dialog.contains(target)) return true;
|
|
1874
|
+
}
|
|
1875
|
+
return false;
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
/* ------------------------------------------------------------------ helpers -- */
|
|
1879
|
+
|
|
1880
|
+
/**
|
|
1881
|
+
* Adds problems to the list and reports the new ones.
|
|
1882
|
+
* @private
|
|
1883
|
+
* @param {SurfaceError[]} errors
|
|
1884
|
+
* @returns {void}
|
|
1885
|
+
*/
|
|
1886
|
+
_report(errors) {
|
|
1887
|
+
const fresh = [];
|
|
1888
|
+
for (const error of errors) {
|
|
1889
|
+
const key = JSON.stringify([error.code, error.path ?? '', error.id ?? '', error.message]);
|
|
1890
|
+
if (this._reported.has(key)) continue;
|
|
1891
|
+
this._reported.add(key);
|
|
1892
|
+
fresh.push(error);
|
|
1893
|
+
}
|
|
1894
|
+
if (!fresh.length) return;
|
|
1895
|
+
this._errors.push(...fresh);
|
|
1896
|
+
if (!this._destroyed) this.emit('error', { errors: structuredClone(fresh) });
|
|
1897
|
+
}
|
|
1898
|
+
|
|
1899
|
+
/** @private @returns {string} */
|
|
1900
|
+
_authorName() {
|
|
1901
|
+
const key = this._model.author ?? '';
|
|
1902
|
+
const authors = this.options.authors ?? {};
|
|
1903
|
+
const author = Object.hasOwn(authors, key) ? authors[key] : null;
|
|
1904
|
+
return author && typeof author.name === 'string' && author.name ? author.name : key || '—';
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
/**
|
|
1909
|
+
* The one reply, exactly once.
|
|
1910
|
+
* @event Surface#reply
|
|
1911
|
+
* @type {CustomEvent<{reply: SurfaceReply}>}
|
|
1912
|
+
*/
|
|
1913
|
+
/**
|
|
1914
|
+
* New problems, each time some are found.
|
|
1915
|
+
* @event Surface#error
|
|
1916
|
+
* @type {CustomEvent<{errors: SurfaceError[]}>}
|
|
1917
|
+
*/
|
|
1918
|
+
/**
|
|
1919
|
+
* An input's value changed; `value` is JSON, `null` when it was emptied.
|
|
1920
|
+
* @event Surface#change
|
|
1921
|
+
* @type {CustomEvent<{name: string, value: unknown}>}
|
|
1922
|
+
*/
|
|
1923
|
+
/**
|
|
1924
|
+
* The surface has begun and shows its first state.
|
|
1925
|
+
* @event Surface#ready
|
|
1926
|
+
* @type {CustomEvent<Record<string, never>>}
|
|
1927
|
+
*/
|
|
1928
|
+
/**
|
|
1929
|
+
* The surface's `end` arrived: it is complete, and its actions are enabled.
|
|
1930
|
+
* @event Surface#end
|
|
1931
|
+
* @type {CustomEvent<Record<string, never>>}
|
|
1932
|
+
*/
|
|
1933
|
+
|
|
1934
|
+
/**
|
|
1935
|
+
* Options of `openSurface()`: the Surface's own, and where it goes.
|
|
1936
|
+
* @typedef {SurfaceOptions & {
|
|
1937
|
+
* placement?: SurfacePlacement,
|
|
1938
|
+
* target?: Element|string|null,
|
|
1939
|
+
* side?: 'start'|'end'|'top'|'bottom',
|
|
1940
|
+
* onopen?: (surface: Surface) => void,
|
|
1941
|
+
* signal?: AbortSignal|null
|
|
1942
|
+
* }} OpenSurfaceOptions
|
|
1943
|
+
*/
|
|
1944
|
+
|
|
1945
|
+
/**
|
|
1946
|
+
* Shows a surface and waits for its reply. The placement the document asks for is a request:
|
|
1947
|
+
* a sheet or a dialog only when `userInitiated` (the surface answers the person's latest
|
|
1948
|
+
* message), inline into `target` otherwise. An application that passes `placement` itself
|
|
1949
|
+
* decides. Closing the sheet or dialog replies `cancel` (`dismiss` for a `show` surface). The
|
|
1950
|
+
* first control takes the focus. A document that cannot begin at all — not an object, the wrong
|
|
1951
|
+
* version, no usable surface id — rejects with a `TypeError` carrying `errors` before anything
|
|
1952
|
+
* opens; a surface given its `reply` resolves with it at once.
|
|
1953
|
+
*
|
|
1954
|
+
* `signal` withdraws the question: when it aborts, the surface is cancelled with the reason
|
|
1955
|
+
* `stopped` (`cancel`, or `dismiss` for a `show` surface) and the promise resolves with that reply;
|
|
1956
|
+
* a sheet or dialog closes and is destroyed, an inline surface stays as its receipt. A signal
|
|
1957
|
+
* already aborted resolves the same reply without drawing anything. An inline surface whose
|
|
1958
|
+
* `target` the application removes is not noticed: abort the signal, or destroy the surface (it
|
|
1959
|
+
* replies `dismiss`), so the promise settles.
|
|
1960
|
+
* @throws {TypeError} Rejects for a document that cannot begin, or an inline surface without a
|
|
1961
|
+
* `target`.
|
|
1962
|
+
* @param {SurfaceDocument|Record<string, unknown>} document The whole surface.
|
|
1963
|
+
* @param {OpenSurfaceOptions} [options]
|
|
1964
|
+
* @returns {Promise<SurfaceReply>}
|
|
1965
|
+
*/
|
|
1966
|
+
export function openSurface(document, options = {}) {
|
|
1967
|
+
const { placement: chosen, target = null, side = 'end', onopen, signal = null, ...surfaceOptions } = options;
|
|
1968
|
+
const catalog = surfaceOptions.catalog ?? CATALOG;
|
|
1969
|
+
const entities = surfaceOptions.resolve?.entities ?? null;
|
|
1970
|
+
const { document: preview, errors } = validateDocument(document, catalog, { entities });
|
|
1971
|
+
const requested = chosen ?? preview?.placement ?? 'inline';
|
|
1972
|
+
const placement = chosen ? chosen : requested !== 'inline' && !surfaceOptions.userInitiated ? 'inline' : requested;
|
|
1973
|
+
return new Promise((resolve, reject) => {
|
|
1974
|
+
if (!preview) {
|
|
1975
|
+
// Nothing could begin: refuse before anything opens, with the problems to hand back.
|
|
1976
|
+
const error = new TypeError(`The surface cannot be drawn: ${errors.map((entry) => entry.message).join('; ')}`);
|
|
1977
|
+
/** @type {any} */ (error).errors = errors;
|
|
1978
|
+
reject(error);
|
|
1979
|
+
return;
|
|
1980
|
+
}
|
|
1981
|
+
if (signal?.aborted) {
|
|
1982
|
+
// Withdrawn before it was asked: the reply a stopped surface gives, and nothing drawn.
|
|
1983
|
+
const stopped = new Surface(null, { ...surfaceOptions, document });
|
|
1984
|
+
const reply = stopped.getReply() ?? stopped.cancel('stopped').getReply();
|
|
1985
|
+
stopped.destroy();
|
|
1986
|
+
resolve(/** @type {SurfaceReply} */ (reply));
|
|
1987
|
+
return;
|
|
1988
|
+
}
|
|
1989
|
+
/** Cancels the drawn surface when the signal aborts, until it has replied. @param {Surface} surface */
|
|
1990
|
+
const withdrawOn = (surface) => {
|
|
1991
|
+
if (!signal) return;
|
|
1992
|
+
const withdraw = () => surface.cancel('stopped');
|
|
1993
|
+
signal.addEventListener('abort', withdraw, { once: true });
|
|
1994
|
+
surface.on('reply', () => signal.removeEventListener('abort', withdraw));
|
|
1995
|
+
};
|
|
1996
|
+
const given = surfaceOptions.reply;
|
|
1997
|
+
if (given && typeof given === 'object' && /** @type {SurfaceReply} */ (given).surface === preview.surface) {
|
|
1998
|
+
// Already answered: the receipt goes inline when there is a target, and the reply stands.
|
|
1999
|
+
const host = typeof target === 'string' ? globalThis.document.querySelector(target) : target;
|
|
2000
|
+
if (host) {
|
|
2001
|
+
const receipt = new Surface(null, { ...surfaceOptions, document });
|
|
2002
|
+
host.append(receipt.toElement());
|
|
2003
|
+
onopen?.(receipt);
|
|
2004
|
+
}
|
|
2005
|
+
resolve(structuredClone(/** @type {SurfaceReply} */ (given)));
|
|
2006
|
+
return;
|
|
2007
|
+
}
|
|
2008
|
+
if (placement === 'inline') {
|
|
2009
|
+
const host = typeof target === 'string' ? globalThis.document.querySelector(target) : target;
|
|
2010
|
+
if (!host) {
|
|
2011
|
+
reject(new TypeError('An inline surface needs a "target" to be drawn into'));
|
|
2012
|
+
return;
|
|
2013
|
+
}
|
|
2014
|
+
const surface = new Surface(null, { ...surfaceOptions, document });
|
|
2015
|
+
surface.on('reply', (event) => resolve(/** @type {CustomEvent<{reply: SurfaceReply}>} */ (event).detail.reply));
|
|
2016
|
+
withdrawOn(surface);
|
|
2017
|
+
host.append(surface.toElement());
|
|
2018
|
+
onopen?.(surface);
|
|
2019
|
+
if (!surface.getReply()) surface.focus();
|
|
2020
|
+
return;
|
|
2021
|
+
}
|
|
2022
|
+
const Overlay = placement === 'sheet' ? Sheet : Dialog;
|
|
2023
|
+
const overlay = new Overlay(null, /** @type {any} */ ({
|
|
2024
|
+
title: preview?.title ?? '', size: placement === 'sheet' ? null : 'md', closable: true,
|
|
2025
|
+
...(placement === 'sheet' ? { side } : {})
|
|
2026
|
+
}));
|
|
2027
|
+
const titleId = overlay.refs.title?.id ?? null;
|
|
2028
|
+
let surface;
|
|
2029
|
+
try {
|
|
2030
|
+
surface = new Surface(null, { ...surfaceOptions, document, labelledBy: titleId });
|
|
2031
|
+
} catch (error) {
|
|
2032
|
+
overlay.destroy();
|
|
2033
|
+
reject(error);
|
|
2034
|
+
return;
|
|
2035
|
+
}
|
|
2036
|
+
overlay.setContent(surface.toElement());
|
|
2037
|
+
overlay.el.classList.add('zx-surface-host');
|
|
2038
|
+
let settled = false;
|
|
2039
|
+
surface.on('reply', (event) => {
|
|
2040
|
+
settled = true;
|
|
2041
|
+
const { reply } = /** @type {CustomEvent<{reply: SurfaceReply}>} */ (event).detail;
|
|
2042
|
+
if (overlay.isOpen()) overlay.close();
|
|
2043
|
+
resolve(reply);
|
|
2044
|
+
});
|
|
2045
|
+
withdrawOn(surface);
|
|
2046
|
+
overlay.on('close', () => {
|
|
2047
|
+
if (!settled) surface.cancel('closed');
|
|
2048
|
+
queueMicrotask(() => {
|
|
2049
|
+
surface.destroy();
|
|
2050
|
+
overlay.destroy();
|
|
2051
|
+
});
|
|
2052
|
+
});
|
|
2053
|
+
overlay.open();
|
|
2054
|
+
onopen?.(surface);
|
|
2055
|
+
queueMicrotask(() => {
|
|
2056
|
+
if (overlay.isOpen()) surface.focus();
|
|
2057
|
+
});
|
|
2058
|
+
});
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
/* ------------------------------------------------------------------ module helpers -- */
|
|
2062
|
+
|
|
2063
|
+
/** What draws the Field types a schema property may name. */
|
|
2064
|
+
const FIELD_ADAPTERS = Object.freeze([
|
|
2065
|
+
registerSelectFieldAdapter, registerChecklistFieldAdapter, registerDateboxFieldAdapters, registerToggleFieldAdapter,
|
|
2066
|
+
registerNumberFieldAdapter, registerRatingFieldAdapter, registerTagPickerFieldAdapter, registerSliderFieldAdapter
|
|
2067
|
+
]);
|
|
2068
|
+
|
|
2069
|
+
/**
|
|
2070
|
+
* Registers the Field types a schema property may name, where nothing draws them yet. What the
|
|
2071
|
+
* application registered stays. `Field.register` replaces, and one adapter below registers two
|
|
2072
|
+
* types, so the check is made for each type as it is registered.
|
|
2073
|
+
*/
|
|
2074
|
+
function registerFields() {
|
|
2075
|
+
const register = Field.register;
|
|
2076
|
+
Field.register = (type, adapter) => (Field.has(type) ? Field : register.call(Field, type, adapter));
|
|
2077
|
+
try {
|
|
2078
|
+
for (const add of FIELD_ADAPTERS) add();
|
|
2079
|
+
} finally {
|
|
2080
|
+
Field.register = register;
|
|
2081
|
+
}
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
/**
|
|
2085
|
+
* What the policy decided, read strictly: anything but a decision asks for a confirmation, and a
|
|
2086
|
+
* policy that throws or returns a Promise denies.
|
|
2087
|
+
* @param {SurfacePolicy|null|undefined} policy @param {SurfaceAction} action @param {SurfaceDocument} doc
|
|
2088
|
+
* @returns {{level: PolicyLevel, confirmText?: string, message?: string}}
|
|
2089
|
+
*/
|
|
2090
|
+
function decide(policy, action, doc) {
|
|
2091
|
+
if (typeof policy !== 'function') return { level: 'allow' };
|
|
2092
|
+
/** @type {SurfaceAction} */
|
|
2093
|
+
const copy = { id: action.id, label: action.label };
|
|
2094
|
+
for (const key of /** @type {const} */ (['kind', 'tool', 'description'])) if (action[key] !== undefined) /** @type {any} */ (copy)[key] = action[key];
|
|
2095
|
+
let result;
|
|
2096
|
+
try {
|
|
2097
|
+
result = policy(Object.freeze(copy), doc);
|
|
2098
|
+
if (typeof result?.then === 'function') {
|
|
2099
|
+
// Whatever it settles to arrives too late to decide anything, and must not go unhandled.
|
|
2100
|
+
Promise.resolve(result).catch(() => {});
|
|
2101
|
+
return { level: 'deny' };
|
|
2102
|
+
}
|
|
2103
|
+
} catch {
|
|
2104
|
+
return { level: 'deny' };
|
|
2105
|
+
}
|
|
2106
|
+
if (typeof result === 'string') return LEVELS.has(result) ? { level: /** @type {PolicyLevel} */ (result) } : { level: 'confirm' };
|
|
2107
|
+
if (result && typeof result === 'object' && LEVELS.has(/** @type {string} */ (result.level))) {
|
|
2108
|
+
/** @type {{level: PolicyLevel, confirmText?: string, message?: string}} */
|
|
2109
|
+
const out = { level: result.level };
|
|
2110
|
+
if (typeof result.confirmText === 'string' && result.confirmText.trim()) out.confirmText = result.confirmText;
|
|
2111
|
+
if (typeof result.message === 'string') out.message = result.message;
|
|
2112
|
+
return out;
|
|
2113
|
+
}
|
|
2114
|
+
return { level: 'confirm' };
|
|
2115
|
+
}
|
|
2116
|
+
|
|
2117
|
+
/**
|
|
2118
|
+
* The block a display node is drawn as.
|
|
2119
|
+
* @param {string} type @param {Record<string, any>} props
|
|
2120
|
+
* @returns {import('../../internal/agent-model.js').Block}
|
|
2121
|
+
*/
|
|
2122
|
+
function toBlock(type, props) {
|
|
2123
|
+
switch (type) {
|
|
2124
|
+
case 'text': return /** @type {any} */ ({ type: 'p', text: props.text });
|
|
2125
|
+
case 'heading': return /** @type {any} */ ({ type: 'heading', text: props.text, level: props.level ?? 2 });
|
|
2126
|
+
case 'list': return /** @type {any} */ ({ type: 'list', items: props.items, ordered: Boolean(props.ordered) });
|
|
2127
|
+
case 'quote': return /** @type {any} */ ({ type: 'quote', text: props.text });
|
|
2128
|
+
case 'code': return /** @type {any} */ ({ type: 'code', code: props.code, language: props.language ?? '' });
|
|
2129
|
+
case 'callout': return /** @type {any} */ ({ type: 'callout', text: props.text, title: props.title, tone: props.tone ?? 'info' });
|
|
2130
|
+
default: return /** @type {any} */ ({ type: 'figures', rows: props.rows });
|
|
2131
|
+
}
|
|
2132
|
+
}
|
|
2133
|
+
|
|
2134
|
+
/**
|
|
2135
|
+
* Puts a container's children in order, moving only what is out of place, so focus and state
|
|
2136
|
+
* inside the children survive.
|
|
2137
|
+
* @param {Element} container @param {Element[]} children
|
|
2138
|
+
* @returns {void}
|
|
2139
|
+
*/
|
|
2140
|
+
function syncChildren(container, children) {
|
|
2141
|
+
const current = [...container.children];
|
|
2142
|
+
if (current.length === children.length && current.every((child, index) => child === children[index])) return;
|
|
2143
|
+
const keep = new Set(children);
|
|
2144
|
+
for (const child of current) if (!keep.has(child)) child.remove();
|
|
2145
|
+
children.forEach((child, index) => {
|
|
2146
|
+
const at = container.children[index];
|
|
2147
|
+
if (at !== child) container.insertBefore(child, at ?? null);
|
|
2148
|
+
});
|
|
2149
|
+
}
|
|
2150
|
+
|
|
2151
|
+
/**
|
|
2152
|
+
* Sets an attribute of a form, or removes it with `null`, through the prototype: a form's members
|
|
2153
|
+
* answer to its inputs' names, and a surface's inputs are named by the model, so `form.setAttribute`
|
|
2154
|
+
* may be an input. Read nothing else off a form that holds a surface's inputs.
|
|
2155
|
+
* @param {Element} form @param {string} name @param {string|null} value
|
|
2156
|
+
* @returns {void}
|
|
2157
|
+
*/
|
|
2158
|
+
function setFormAttribute(form, name, value) {
|
|
2159
|
+
if (value === null) Element.prototype.removeAttribute.call(form, name);
|
|
2160
|
+
else Element.prototype.setAttribute.call(form, name, value);
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
/**
|
|
2164
|
+
* Gives a drawn heading node its level below the surface's title, up to h6, which the block
|
|
2165
|
+
* renderer alone cannot reach.
|
|
2166
|
+
* @param {HTMLElement} host @param {number} level
|
|
2167
|
+
* @returns {void}
|
|
2168
|
+
*/
|
|
2169
|
+
function settleHeading(host, level) {
|
|
2170
|
+
const drawn = host.querySelector('h1, h2, h3, h4, h5, h6');
|
|
2171
|
+
if (!drawn || drawn.localName === `h${level}`) return;
|
|
2172
|
+
const heading = document.createElement(`h${level}`);
|
|
2173
|
+
for (const attribute of drawn.attributes) heading.setAttribute(attribute.name, attribute.value);
|
|
2174
|
+
heading.append(...drawn.childNodes);
|
|
2175
|
+
drawn.replaceWith(heading);
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
/** @param {unknown} value @returns {2|3|4|5} */
|
|
2179
|
+
function headingLevel(value) {
|
|
2180
|
+
const level = Math.trunc(Number(value) || 3);
|
|
2181
|
+
return /** @type {2|3|4|5} */ (Math.min(5, Math.max(2, level)));
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
/** @param {Record<string, any>} property @returns {Map<unknown, string>} */
|
|
2185
|
+
function choiceLabels(property) {
|
|
2186
|
+
const source = property.type === 'array' ? property.items ?? {} : property;
|
|
2187
|
+
if (Array.isArray(source.enum)) return new Map(source.enum.map((/** @type {string} */ value) => [value, value]));
|
|
2188
|
+
const list = property.type === 'array' ? source.anyOf : property.oneOf;
|
|
2189
|
+
return new Map(Array.isArray(list) ? list.map((/** @type {any} */ choice) => [choice.const, choice.title]) : []);
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2192
|
+
/** @param {string} at @param {string} [locale] @returns {string} */
|
|
2193
|
+
function formatTime(at, locale) {
|
|
2194
|
+
const match = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)/.exec(String(at ?? ''));
|
|
2195
|
+
if (!match) return '';
|
|
2196
|
+
const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]));
|
|
2197
|
+
try {
|
|
2198
|
+
return new Intl.DateTimeFormat(dateLocale(locale), { hour: '2-digit', minute: '2-digit' }).format(date);
|
|
2199
|
+
} catch {
|
|
2200
|
+
return `${match[4]}:${match[5]}`;
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
|
|
2204
|
+
/** @param {string} value @returns {Date|null} */
|
|
2205
|
+
function parseLocal(value) {
|
|
2206
|
+
const match = /^(\d{4})-(\d\d)-(\d\d)(?:T(\d\d):(\d\d)(?::(\d\d))?)?$/.exec(value);
|
|
2207
|
+
if (!match) return null;
|
|
2208
|
+
const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]),
|
|
2209
|
+
Number(match[4] ?? 0), Number(match[5] ?? 0), Number(match[6] ?? 0));
|
|
2210
|
+
return Number.isNaN(date.getTime()) ? null : date;
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
/** @param {unknown} value @returns {value is {$data: string}} */
|
|
2214
|
+
function isBinding(value) {
|
|
2215
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
2216
|
+
&& typeof (/** @type {any} */ (value).$data) === 'string' && Object.keys(value).length === 1;
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2219
|
+
/** @param {SurfaceNode} node @returns {boolean} */
|
|
2220
|
+
function hasBinding(node) {
|
|
2221
|
+
return Object.values(node).some(isBinding);
|
|
2222
|
+
}
|
|
2223
|
+
|
|
2224
|
+
/** @param {SurfaceNode} node @returns {string[]} The pointers the node's properties are bound to. */
|
|
2225
|
+
function boundPointers(node) {
|
|
2226
|
+
return Object.values(node).filter(isBinding).map((value) => value.$data);
|
|
2227
|
+
}
|
|
2228
|
+
|
|
2229
|
+
/**
|
|
2230
|
+
* Whether a change at a path reaches a binding: at the pointer, above it or below it, or, for an
|
|
2231
|
+
* entry of a list, anywhere in that list, as adding or removing one moves the entries after it.
|
|
2232
|
+
* @param {string} pointer @param {string} path
|
|
2233
|
+
* @returns {boolean}
|
|
2234
|
+
*/
|
|
2235
|
+
function touches(pointer, path) {
|
|
2236
|
+
if (pointer === path || pointer.startsWith(`${path}/`) || path.startsWith(`${pointer}/`)) return true;
|
|
2237
|
+
const end = path.lastIndexOf('/');
|
|
2238
|
+
return /^(?:\d+|-)$/.test(path.slice(end + 1)) && pointer.startsWith(`${path.slice(0, end)}/`);
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
/**
|
|
2242
|
+
* Where a drawn row keeps its position, so every row has an id of its own whatever the surface
|
|
2243
|
+
* names as its `rowId`: `#` cannot be part of a column id.
|
|
2244
|
+
*/
|
|
2245
|
+
const ROW_POSITION = '#position';
|
|
2246
|
+
|
|
2247
|
+
/**
|
|
2248
|
+
* The rows as a Table draws them. A column reads what the row itself holds: a column id every
|
|
2249
|
+
* object happens to inherit (`toString`) is an empty cell, not a function.
|
|
2250
|
+
* @param {Array<Record<string, unknown>>} rows @param {Array<{id: string}>} columns
|
|
2251
|
+
* @returns {Array<Record<string, unknown>>}
|
|
2252
|
+
*/
|
|
2253
|
+
function drawnRows(rows, columns) {
|
|
2254
|
+
return rows.map((row, index) => {
|
|
2255
|
+
const copy = { ...row, [ROW_POSITION]: `#${index}` };
|
|
2256
|
+
for (const column of columns) if (!Object.hasOwn(copy, column.id)) copy[column.id] = null;
|
|
2257
|
+
return copy;
|
|
2258
|
+
});
|
|
2259
|
+
}
|
|
2260
|
+
|
|
2261
|
+
/**
|
|
2262
|
+
* A row's id for a Table: what the row holds under the surface's `rowId`, or, when it holds
|
|
2263
|
+
* nothing there, its position. Such a row can be selected but has no id to report.
|
|
2264
|
+
* @param {string} [key] @returns {(row: Record<string, unknown>) => unknown}
|
|
2265
|
+
*/
|
|
2266
|
+
function drawnRowId(key) {
|
|
2267
|
+
return (row) => ownValue(row, key) ?? row[ROW_POSITION];
|
|
2268
|
+
}
|
|
2269
|
+
|
|
2270
|
+
/**
|
|
2271
|
+
* @param {Record<string, unknown>} row @param {string} [key]
|
|
2272
|
+
* @returns {unknown} What the row itself holds under the key, or `null`.
|
|
2273
|
+
*/
|
|
2274
|
+
function ownValue(row, key) {
|
|
2275
|
+
return key !== undefined && Object.hasOwn(row, key) ? row[key] ?? null : null;
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
/** @param {unknown} value @returns {value is {$ref: string, id: string}} */
|
|
2279
|
+
function isRef(value) {
|
|
2280
|
+
return value !== null && typeof value === 'object' && typeof (/** @type {any} */ (value).$ref) === 'string'
|
|
2281
|
+
&& typeof (/** @type {any} */ (value).id) === 'string';
|
|
2282
|
+
}
|
|
2283
|
+
|
|
2284
|
+
/** @template T @param {T} value @returns {T} */
|
|
2285
|
+
function deepFreeze(value) {
|
|
2286
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
2287
|
+
Object.freeze(value);
|
|
2288
|
+
for (const entry of Object.values(value)) deepFreeze(entry);
|
|
2289
|
+
}
|
|
2290
|
+
return value;
|
|
2291
|
+
}
|