@link-foundation/ui-devmode 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +353 -2
  3. package/package.json +78 -4
  4. package/src/activation.js +235 -0
  5. package/src/adapter.js +92 -0
  6. package/src/agent-instruction.d.ts +6 -0
  7. package/src/agent-instruction.js +17 -0
  8. package/src/agent-instruction.txt +8 -0
  9. package/src/apply-shared.js +135 -0
  10. package/src/comments/commands.js +77 -0
  11. package/src/comments/geometry.js +65 -0
  12. package/src/comments/index.d.ts +93 -0
  13. package/src/comments/index.js +205 -0
  14. package/src/comments/model.js +359 -0
  15. package/src/comments/picking.js +154 -0
  16. package/src/comments/style.js +36 -0
  17. package/src/comments/view.js +250 -0
  18. package/src/comments/voice.js +64 -0
  19. package/src/defaults-dialog.js +120 -0
  20. package/src/details.js +159 -0
  21. package/src/editors.js +194 -0
  22. package/src/export.js +50 -0
  23. package/src/foreign/adapter.js +166 -0
  24. package/src/foreign/apply.js +89 -0
  25. package/src/foreign/entry.js +173 -0
  26. package/src/foreign/index.d.ts +32 -0
  27. package/src/foreign/injected.js +6 -0
  28. package/src/foreign/persist.js +54 -0
  29. package/src/foreign/properties.js +126 -0
  30. package/src/foreign/runtime.js +67 -0
  31. package/src/index.d.ts +204 -0
  32. package/src/index.js +201 -0
  33. package/src/inspector-css.js +106 -0
  34. package/src/inspector.js +342 -0
  35. package/src/inspector.lino +50 -0
  36. package/src/messages.js +113 -0
  37. package/src/model.d.ts +101 -0
  38. package/src/model.js +473 -0
  39. package/src/overlay.js +91 -0
  40. package/src/policy.js +222 -0
  41. package/src/read-asset.browser.js +8 -0
  42. package/src/read-asset.js +10 -0
  43. package/src/session.js +555 -0
  44. package/src/share.js +23 -0
  45. package/src/validate.js +170 -0
  46. package/src/views.js +328 -0
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Every text the dev mode UI shows, by key. A page passes its own table
3
+ * (`mountDevMode({ messages })`) to translate dev mode; the
4
+ * keys it leaves out fall back to these English texts.
5
+ */
6
+
7
+ /** The English texts. `{name}` is replaced by the parameter `name`. */
8
+ export const MESSAGES = Object.freeze({
9
+ 'inspector.title': 'Dev mode',
10
+ 'inspector.label': 'Dev mode inspector',
11
+ 'resize.label': 'Resize the inspector',
12
+ 'toolbar.comments': 'Comment on UI',
13
+ 'toolbar.defaults': 'Make these the defaults',
14
+ 'defaults.title': 'Make these the defaults',
15
+ 'defaults.count': '{count} changes',
16
+ 'defaults.overrides': 'Overrides as LiNo',
17
+ 'defaults.share': 'Share link',
18
+ 'defaults.instruction': 'Agent instruction',
19
+ 'defaults.copy': 'Copy',
20
+ 'defaults.copyLabel': 'Copy {name}',
21
+ 'defaults.copied': 'Copied.',
22
+ 'defaults.select': 'Text selected. Copy it with your keyboard.',
23
+ 'defaults.tooLong':
24
+ 'Share link exceeds 8,192 characters. Copy the LiNo text instead.',
25
+ 'defaults.issue': 'Open as GitHub issue',
26
+ 'defaults.close': 'Close dialog',
27
+ 'shared.title': 'Shared UI changes are previewed.',
28
+ 'shared.keep': 'Keep',
29
+ 'shared.discard': 'Discard',
30
+ 'toolbar.label': 'Dev mode actions',
31
+ 'toolbar.pick': 'Pick element',
32
+ 'toolbar.save': 'Save',
33
+ 'toolbar.discard': 'Discard',
34
+ 'toolbar.close': 'Close',
35
+ 'tabs.label': 'Inspector views',
36
+ 'tab.outline': 'Outline',
37
+ 'tab.properties': 'Properties',
38
+ 'tab.styles': 'Styles',
39
+ 'tab.tokens': 'Tokens',
40
+ 'tab.animations': 'Animations',
41
+ 'tab.source': 'Source',
42
+ 'selection.none': 'No element selected',
43
+ 'selection.current': 'Selected: {id} ({type})',
44
+ 'selection.picking': 'Pick mode: click an element, Escape to stop',
45
+ 'empty.selection': 'Select an element in the page or in the outline.',
46
+ 'outline.label': 'Document outline',
47
+ 'properties.caption': 'Properties of {id}',
48
+ 'properties.name': 'Property',
49
+ 'properties.editor': 'Edit',
50
+ 'properties.value': 'Resolved value',
51
+ 'properties.layer': 'Layer',
52
+ 'properties.reset': 'Reset',
53
+ 'properties.resetLabel': 'Reset {name}',
54
+ 'properties.unitLabel': '{name} unit',
55
+ 'properties.unset': 'not set',
56
+ 'properties.locked': '{id} is locked by the site policy; it is read-only.',
57
+ 'properties.readOnly': 'The site policy lets dev mode write no layer.',
58
+ 'styles.none': 'No style rule matches {id}.',
59
+ 'styles.base': 'base',
60
+ 'tokens.caption': 'Tokens used by {id}',
61
+ 'tokens.none': '{id} uses no design token.',
62
+ 'tokens.token': 'Token',
63
+ 'tokens.value': 'Resolved value',
64
+ 'tokens.layer': 'Layer',
65
+ 'tokens.usedBy': 'Used by',
66
+ 'animations.none': 'No animation targets {id}.',
67
+ 'animations.readOnly': 'Animations are read-only here.',
68
+ 'source.label': 'Links Notation source of {id}',
69
+ 'status.saved': 'Saved {count} change(s) to the user layer.',
70
+ 'status.discarded': 'Discarded {count} session change(s).',
71
+ 'status.reset': 'Reset {name}: the {layer} value was removed.',
72
+ 'status.nothing': 'Nothing to reset for {name}.',
73
+ 'status.error': '{message}',
74
+ 'overlay.label': '{id}: {type}',
75
+ });
76
+
77
+ /**
78
+ * A message with its parameters filled in.
79
+ * @param {Readonly<Record<string, string>>} table
80
+ * @param {string} key
81
+ * @param {Record<string, string|number>} [params]
82
+ * @returns {string}
83
+ */
84
+ export function message(table, key, params = {}) {
85
+ const text = table[key] ?? MESSAGES[key] ?? key;
86
+ let out = '';
87
+ let at = 0;
88
+ while (at < text.length) {
89
+ const open = text.indexOf('{', at);
90
+ const close = open < 0 ? -1 : text.indexOf('}', open);
91
+ if (close < 0) {
92
+ out += text.slice(at);
93
+ break;
94
+ }
95
+ const name = text.slice(open + 1, close);
96
+ out +=
97
+ text.slice(at, open) +
98
+ (Object.hasOwn(params, name)
99
+ ? String(params[name])
100
+ : text.slice(open, close + 1));
101
+ at = close + 1;
102
+ }
103
+ return out;
104
+ }
105
+
106
+ /**
107
+ * A translator over a page's table: `t(key, params)`.
108
+ * @param {Readonly<Record<string, string>>} [table]
109
+ */
110
+ export const translator =
111
+ (table = {}) =>
112
+ (key, params) =>
113
+ message(table, key, params);
package/src/model.d.ts ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Type declarations of `@link-foundation/ui-devmode/model`: the pure model
3
+ * of the inspector (outline, property rows, edits).
4
+ */
5
+
6
+ // Resolve declarations through package exports in TypeScript and Deno alike.
7
+ import type { DevModePolicy, WritableLayer } from '@link-foundation/ui-devmode';
8
+
9
+ export const READ_ONLY_LAYERS: readonly ['defaults', 'theme', 'site'];
10
+
11
+ export class DevModeError extends Error {
12
+ /** `read-only-layer`, `locked-element`, `bad-value`, `not-editable` or
13
+ * `unknown-element`. */
14
+ code: string;
15
+ constructor(code: string, message: string);
16
+ }
17
+
18
+ export interface OutlineNode {
19
+ id: string;
20
+ type: string;
21
+ children: OutlineNode[];
22
+ }
23
+
24
+ export function buildOutline(tree: object): OutlineNode[];
25
+ export function flattenOutline(
26
+ outline: readonly OutlineNode[]
27
+ ): { node: OutlineNode; level: number; parent: string | null }[];
28
+ export function isLocked(
29
+ policy: DevModePolicy,
30
+ id: string,
31
+ parentOf?: (id: string) => string | null
32
+ ): boolean;
33
+ export function topWritableLayer(policy: DevModePolicy): WritableLayer | null;
34
+ export function editorFor(
35
+ type: string | readonly string[] | undefined,
36
+ values: readonly unknown[] | undefined
37
+ ): { editor: string; options?: readonly string[]; units?: readonly string[] };
38
+ export function formatValues(values: readonly unknown[] | undefined): string;
39
+
40
+ export interface PropertyRow {
41
+ name: string;
42
+ key: string | null;
43
+ label: string;
44
+ type: string | readonly string[] | undefined;
45
+ editor: string;
46
+ options?: readonly string[];
47
+ units?: readonly string[];
48
+ value: readonly unknown[] | undefined;
49
+ text: string;
50
+ layer: string;
51
+ changed: boolean;
52
+ locked: boolean;
53
+ writable: boolean;
54
+ }
55
+
56
+ export function propertyRows(
57
+ element: { id: string; kind: string; positional?: readonly unknown[] },
58
+ config: object,
59
+ options?: object
60
+ ): PropertyRow[];
61
+ export function editValues(value: unknown): readonly unknown[];
62
+
63
+ export interface EditOptions {
64
+ policy: DevModePolicy;
65
+ vocabulary?: object;
66
+ parentOf?: (id: string) => string | null;
67
+ document?: object;
68
+ getElement?: (id: string) => object | undefined;
69
+ }
70
+
71
+ /** Write one property to a writable layer (the top one by default). */
72
+ export function applyEdit(
73
+ config: object,
74
+ edit: {
75
+ id: string;
76
+ name: string;
77
+ value: unknown;
78
+ key?: string | null;
79
+ layer?: string;
80
+ },
81
+ options: EditOptions
82
+ ): {
83
+ id: string;
84
+ name: string;
85
+ key: string | null;
86
+ layer: WritableLayer;
87
+ values: readonly unknown[];
88
+ };
89
+ export function resetProperty(
90
+ config: object,
91
+ target: { id: string; name: string; key?: string | null },
92
+ options: {
93
+ policy: DevModePolicy;
94
+ parentOf?: (id: string) => string | null;
95
+ }
96
+ ): WritableLayer | null;
97
+ export function saveSession(
98
+ config: object,
99
+ options: { policy: DevModePolicy }
100
+ ): number;
101
+ export function discardSession(config: object): number;
package/src/model.js ADDED
@@ -0,0 +1,473 @@
1
+ /**
2
+ * The data of the inspector, without a DOM: the outline of the document,
3
+ * the rows of the property grid and the checks of an edit. Every function
4
+ * here is pure apart from the ones that write the configuration
5
+ * (`applyEdit`, `resetProperty`, `saveSession`, `discardSession`), and those
6
+ * only call ui-config.
7
+ */
8
+
9
+ import {
10
+ defaultVocabulary,
11
+ formatLinks,
12
+ valueMatches,
13
+ values as uiValues,
14
+ } from '@link-foundation/ui-core';
15
+
16
+ /** The layers below `user`: dev mode reads them and never writes them. */
17
+ export const READ_ONLY_LAYERS = Object.freeze(['defaults', 'theme', 'site']);
18
+
19
+ /** The layers whose values count as a change made in dev mode. */
20
+ const CHANGED_LAYERS = new Set(['user', 'session']);
21
+
22
+ /** Properties a page never edits in the grid (multi-valued or opaque). */
23
+ const HIDDEN_TYPES = new Set(['any', 'action']);
24
+
25
+ /** An error of an edit dev mode refuses. */
26
+ export class DevModeError extends Error {
27
+ /**
28
+ * @param {string} code `read-only-layer`, `locked-element`, `bad-value`,
29
+ * `not-editable` or `unknown-element`
30
+ * @param {string} message
31
+ */
32
+ constructor(code, message) {
33
+ super(message);
34
+ this.name = 'DevModeError';
35
+ this.code = code;
36
+ }
37
+ }
38
+
39
+ const fail = (code, message) => {
40
+ throw new DevModeError(code, message);
41
+ };
42
+
43
+ /**
44
+ * @typedef {object} OutlineNode
45
+ * @property {string} id
46
+ * @property {string} type the kind of the element
47
+ * @property {OutlineNode[]} children
48
+ */
49
+
50
+ /**
51
+ * The outline of a document: `{ id, type, children }` for every element.
52
+ * `tree` is a ui-store store (`roots()`, `get(id)`, `children(id)`) or a
53
+ * ui-core document (`{ roots }` of nodes with `children`).
54
+ * @param {object} tree
55
+ * @returns {OutlineNode[]}
56
+ */
57
+ export function buildOutline(tree) {
58
+ if (typeof tree?.roots === 'function') {
59
+ const visit = (id) => ({
60
+ id,
61
+ type: tree.get(id)?.kind ?? '',
62
+ children: tree.children(id).map(visit),
63
+ });
64
+ return tree.roots().map(visit);
65
+ }
66
+ const visit = (node) => ({
67
+ id: node.id,
68
+ type: node.kind ?? '',
69
+ children: (node.children ?? []).map(visit),
70
+ });
71
+ return (tree?.roots ?? []).map(visit);
72
+ }
73
+
74
+ /**
75
+ * The outline nodes in document order, each with its `level` (1 for a root)
76
+ * and the id of its parent.
77
+ * @param {OutlineNode[]} outline
78
+ * @returns {{ node: OutlineNode, level: number, parent: string|null }[]}
79
+ */
80
+ export function flattenOutline(outline) {
81
+ const out = [];
82
+ const visit = (node, level, parent) => {
83
+ out.push({ node, level, parent });
84
+ node.children.forEach((child) => visit(child, level + 1, node.id));
85
+ };
86
+ outline.forEach((node) => visit(node, 1, null));
87
+ return out;
88
+ }
89
+
90
+ /**
91
+ * Whether an element is locked by the policy: it, or one of its ancestors,
92
+ * is in `(locked-elements …)`.
93
+ * @param {{ lockedElements: ReadonlySet<string> }} policy
94
+ * @param {string} id
95
+ * @param {(id: string) => string|null|undefined} [parentOf]
96
+ */
97
+ export function isLocked(policy, id, parentOf) {
98
+ const seen = new Set();
99
+ for (let at = id; at && !seen.has(at); at = parentOf?.(at) ?? null) {
100
+ if (policy.lockedElements.has(at)) {
101
+ return true;
102
+ }
103
+ seen.add(at);
104
+ }
105
+ return false;
106
+ }
107
+
108
+ /** The highest layer the policy lets dev mode write, or `null`. */
109
+ export const topWritableLayer = (policy) => policy.writeLayers.at(-1) ?? null;
110
+
111
+ /** Whether the values are one token reference `(token path)`. */
112
+ export const tokenPath = (values) =>
113
+ Array.isArray(values) &&
114
+ values.length === 1 &&
115
+ Array.isArray(values[0]) &&
116
+ values[0].length === 2 &&
117
+ values[0][0] === 'token' &&
118
+ typeof values[0][1] === 'string'
119
+ ? values[0][1]
120
+ : null;
121
+
122
+ /** The editor of each named property type. */
123
+ const EDITORS = Object.freeze({
124
+ string: { editor: 'string' },
125
+ 'element-ref': { editor: 'string' },
126
+ 'element-ref-or-url': { editor: 'string' },
127
+ url: { editor: 'string' },
128
+ number: { editor: 'number' },
129
+ boolean: { editor: 'boolean' },
130
+ color: { editor: 'color' },
131
+ dimension: { editor: 'dimension', units: uiValues.DIMENSION_UNITS },
132
+ duration: { editor: 'dimension', units: uiValues.DURATION_UNITS },
133
+ });
134
+
135
+ /**
136
+ * The editor of a property type: `string`, `number`, `dimension` (a number
137
+ * with a unit), `color`, `enum`, `boolean`, `token` or `readonly`.
138
+ * @param {string|readonly string[]|undefined} type
139
+ * @param {readonly unknown[]|undefined} values the current values
140
+ * @returns {{ editor: string, options?: readonly string[], units?: readonly string[] }}
141
+ */
142
+ export function editorFor(type, values) {
143
+ if (tokenPath(values) !== null) {
144
+ return { editor: 'token' };
145
+ }
146
+ if (Array.isArray(type) && type[0] === 'enum') {
147
+ const options = type.slice(1);
148
+ return options.length === 2 &&
149
+ options.includes('true') &&
150
+ options.includes('false')
151
+ ? { editor: 'boolean' }
152
+ : { editor: 'enum', options };
153
+ }
154
+ return typeof type === 'string' && Object.hasOwn(EDITORS, type)
155
+ ? { ...EDITORS[type] }
156
+ : { editor: 'readonly' };
157
+ }
158
+
159
+ /**
160
+ * Raw values as Links Notation text, the way they are written after a
161
+ * property name (`'Hello, links'`, `(token space.medium)`). The text is
162
+ * edited in a one-line field, so it is the inline form of the values. It is
163
+ * written by ui-core `formatLinks`, so all quoting is done by
164
+ * `links-notation`.
165
+ * @param {readonly unknown[]|undefined} values
166
+ */
167
+ export function formatValues(values) {
168
+ if (!Array.isArray(values) || values.length === 0) {
169
+ return '';
170
+ }
171
+ return formatLinks([/** @type {any} */ (values)], { style: 'inline' })
172
+ .trim()
173
+ .slice(1, -1);
174
+ }
175
+
176
+ /** The vocabulary entry of a kind, or an empty one. */
177
+ function kindInfo(vocabulary, kind) {
178
+ return (
179
+ vocabulary.kinds.get(kind) ?? {
180
+ positional: [],
181
+ properties: new Map(),
182
+ children: 'any',
183
+ }
184
+ );
185
+ }
186
+
187
+ /**
188
+ * The row of the positional values of an element: they stand for the
189
+ * first positional property (`(greeting: text 'Hello')` is the `value` of
190
+ * the text). `null` without positional values.
191
+ */
192
+ function positionalTarget(element, info) {
193
+ if ((element.positional ?? []).length === 0) {
194
+ return null;
195
+ }
196
+ const first = info.positional[0];
197
+ return {
198
+ label: first ?? element.kind,
199
+ type: info.properties.get(first)?.type ?? 'string',
200
+ };
201
+ }
202
+
203
+ /**
204
+ * The properties an element shows in the grid, in order: its positional
205
+ * values (named by its kind, as ui-config addresses them), then the
206
+ * single-valued properties of its kind, then any other property it has.
207
+ */
208
+ function rowTargets(element, info, keyedProps) {
209
+ const targets = [];
210
+ const seen = new Set();
211
+ const add = (name, key, type, label = key ? `${name} ${key}` : name) => {
212
+ const k = `${name}\u0000${key ?? ''}`;
213
+ if (!seen.has(k)) {
214
+ seen.add(k);
215
+ targets.push({ name, key, type, label });
216
+ }
217
+ };
218
+ const first = positionalTarget(element, info);
219
+ if (first) {
220
+ add(element.kind, null, first.type, first.label);
221
+ }
222
+ for (const [name, prop] of info.properties) {
223
+ if (name !== first?.label && !prop.multi && !HIDDEN_TYPES.has(prop.type)) {
224
+ add(name, null, prop.type);
225
+ }
226
+ }
227
+ for (const { name, values } of element.properties ?? []) {
228
+ const keyed = keyedProps.includes(name) && typeof values[0] === 'string';
229
+ add(name, keyed ? values[0] : null, info.properties.get(name)?.type);
230
+ }
231
+ return targets;
232
+ }
233
+
234
+ /**
235
+ * @typedef {object} PropertyRow
236
+ * @property {string} name the property name (the kind for positional values)
237
+ * @property {string|null} key the key of a keyed property (`token`, `state`)
238
+ * @property {string} label the name shown in the grid (`value` for the
239
+ * positional values of a text)
240
+ * @property {string|readonly string[]|undefined} type the vocabulary type
241
+ * @property {string} editor see {@link editorFor}
242
+ * @property {readonly string[]} [options] the values of an `enum` editor
243
+ * @property {readonly string[]} [units] the units of a `dimension` editor
244
+ * @property {readonly unknown[]|undefined} value the resolved raw values
245
+ * @property {string} text the resolved values as Links Notation
246
+ * @property {string} layer the layer the value comes from (`defaults` when
247
+ * no layer sets it)
248
+ * @property {boolean} changed true for a value of the `user` or `session` layer
249
+ * @property {boolean} locked the policy locks the element
250
+ * @property {boolean} writable the row can be edited and reset
251
+ */
252
+
253
+ /**
254
+ * The rows of the property grid of one element.
255
+ * @param {{ id: string, kind: string, positional?: readonly unknown[],
256
+ * properties?: readonly { name: string, values: readonly unknown[] }[] }} element
257
+ * a ui-core node or a ui-store view
258
+ * @param {object} config a ui-config configuration
259
+ * @param {{ policy?: { writeLayers: readonly string[],
260
+ * lockedElements: ReadonlySet<string> },
261
+ * vocabulary?: object, parentOf?: (id: string) => string|null }} [options]
262
+ * @returns {PropertyRow[]}
263
+ */
264
+ export function propertyRows(element, config, options = {}) {
265
+ const vocabulary = options.vocabulary ?? defaultVocabulary();
266
+ const policy = options.policy;
267
+ const info = kindInfo(vocabulary, element.kind);
268
+ const locked = policy
269
+ ? isLocked(policy, element.id, options.parentOf)
270
+ : false;
271
+ const canWrite = !locked && (policy ? policy.writeLayers.length > 0 : true);
272
+ const keyedProps = config.keyedProps ?? [];
273
+ return rowTargets(element, info, keyedProps).map((target) => {
274
+ const { name, key, type } = target;
275
+ const resolved = config.resolve(element.id, name, key ?? undefined);
276
+ const value = resolved?.value;
277
+ const layer = resolved?.layer ?? 'defaults';
278
+ const editor = editorFor(type, value);
279
+ return Object.freeze({
280
+ name,
281
+ key,
282
+ label: target.label,
283
+ type,
284
+ ...editor,
285
+ value,
286
+ text: formatValues(value),
287
+ layer,
288
+ changed: CHANGED_LAYERS.has(layer),
289
+ locked,
290
+ writable: canWrite && editor.editor !== 'readonly',
291
+ });
292
+ });
293
+ }
294
+
295
+ /**
296
+ * The raw values of an edit: a string is one atom, a number or a boolean
297
+ * its text, `{ token: path }` a token reference and an array the values
298
+ * themselves.
299
+ */
300
+ export function editValues(value) {
301
+ if (Array.isArray(value)) {
302
+ return value;
303
+ }
304
+ if (value && typeof value === 'object' && typeof value.token === 'string') {
305
+ return [['token', value.token]];
306
+ }
307
+ if (typeof value === 'number' && Number.isFinite(value)) {
308
+ return [String(value)];
309
+ }
310
+ if (typeof value === 'boolean') {
311
+ return [String(value)];
312
+ }
313
+ if (typeof value === 'string') {
314
+ return [value];
315
+ }
316
+ return fail('bad-value', `Cannot edit a property with ${String(value)}`);
317
+ }
318
+
319
+ /** The vocabulary type of `(id, name)`, `undefined` for an unknown one. */
320
+ function typeOf(vocabulary, element, name) {
321
+ const info = kindInfo(vocabulary, element.kind);
322
+ if (name === element.kind) {
323
+ return info.properties.get(info.positional[0])?.type ?? 'string';
324
+ }
325
+ return info.properties.get(name)?.type;
326
+ }
327
+
328
+ /** Check the values of an edit against the type of the property. */
329
+ function checkValues(type, values, positional) {
330
+ if (values.length === 0 || values.some((v) => v === '')) {
331
+ fail('bad-value', 'A property needs a value; use Reset to remove it');
332
+ }
333
+ if (positional && values.some((v) => typeof v !== 'string')) {
334
+ fail('bad-value', 'Positional values are atoms');
335
+ }
336
+ if (type === 'action' || (type === undefined && positional)) {
337
+ fail('not-editable', 'Actions are not edited in dev mode');
338
+ }
339
+ if (type === undefined || type === 'any') {
340
+ return;
341
+ }
342
+ if (values.length !== 1 || !valueMatches(type, values[0])) {
343
+ const expected = Array.isArray(type) ? type.slice(1).join(', ') : type;
344
+ fail(
345
+ 'bad-value',
346
+ `${formatValues(values)} is not a valid value (expected ${expected})`
347
+ );
348
+ }
349
+ }
350
+
351
+ /**
352
+ * The layer an edit writes, checked against the policy: `site`, `theme`
353
+ * and `defaults` are never written, and `user`/`session` only when the
354
+ * policy lists them.
355
+ */
356
+ function writableLayer(policy, layer) {
357
+ const target = layer ?? topWritableLayer(policy);
358
+ if (READ_ONLY_LAYERS.includes(target)) {
359
+ fail(
360
+ 'read-only-layer',
361
+ `Dev mode never writes the ${target} layer; edit user or session`
362
+ );
363
+ }
364
+ if (!target || !policy.writeLayers.includes(target)) {
365
+ fail(
366
+ 'read-only-layer',
367
+ `The site policy does not let dev mode write the ${target ?? 'any'} layer`
368
+ );
369
+ }
370
+ return target;
371
+ }
372
+
373
+ /**
374
+ * The element of an edit: `options.getElement(id)`, else the element of
375
+ * `options.document` (a ui-store store or a ui-core document).
376
+ */
377
+ function elementOf(options, id) {
378
+ const { getElement, document } = options;
379
+ const element =
380
+ getElement?.(id) ??
381
+ (typeof document?.get === 'function'
382
+ ? document.get(id)
383
+ : document?.byId?.get(id)) ??
384
+ null;
385
+ if (!element) {
386
+ fail('unknown-element', `The document has no element "${id}"`);
387
+ }
388
+ return element;
389
+ }
390
+
391
+ /**
392
+ * Write one property in a writable layer, after checking the layer against
393
+ * the policy, the element against `(locked-elements …)` and the value
394
+ * against the vocabulary type of the property.
395
+ * @param {object} config a ui-config configuration
396
+ * @param {{ id: string, name: string, key?: string|null, value: unknown,
397
+ * layer?: string }} edit
398
+ * @param {{ policy: import('./policy.js').DevModePolicy, vocabulary?: object,
399
+ * parentOf?: (id: string) => string|null,
400
+ * document?: object,
401
+ * getElement?: (id: string) => object|undefined }} options the element
402
+ * is looked up with `getElement` or in `document` (a ui-store store or a
403
+ * ui-core document)
404
+ * @returns {{ id: string, name: string, key: string|null, layer: string,
405
+ * values: readonly unknown[] }}
406
+ * @throws {DevModeError}
407
+ */
408
+ export function applyEdit(config, edit, options) {
409
+ const { policy } = options;
410
+ const layer = writableLayer(policy, edit.layer);
411
+ const { id, name } = edit;
412
+ const element = elementOf(options, id);
413
+ if (isLocked(policy, id, options.parentOf)) {
414
+ fail('locked-element', `"${id}" is locked by the site policy`);
415
+ }
416
+ const vocabulary = options.vocabulary ?? defaultVocabulary();
417
+ const values = editValues(edit.value);
418
+ checkValues(typeOf(vocabulary, element, name), values, name === element.kind);
419
+ const key = edit.key ?? null;
420
+ config.set(layer, id, name, values, key ?? undefined);
421
+ return Object.freeze({ id, name, key, layer, values });
422
+ }
423
+
424
+ /**
425
+ * Reset a property: remove it from the highest writable layer that holds
426
+ * it, so the value of the layer below shows again. The element is locked
427
+ * when it or an ancestor (`parentOf`) is in `(locked-elements …)`.
428
+ * @param {object} config a ui-config configuration
429
+ * @param {{ id: string, name: string, key?: string|null }} target
430
+ * @param {{ policy: import('./policy.js').DevModePolicy,
431
+ * parentOf?: (id: string) => string|null }} options
432
+ * @returns {string|null} the layer the value was removed from
433
+ */
434
+ export function resetProperty(
435
+ config,
436
+ { id, name, key = null },
437
+ { policy, parentOf }
438
+ ) {
439
+ if (isLocked(policy, id, parentOf)) {
440
+ fail('locked-element', `"${id}" is locked by the site policy`);
441
+ }
442
+ for (const layer of [...policy.writeLayers].reverse()) {
443
+ if (config.valueIn(layer, id, name, key ?? undefined) !== undefined) {
444
+ config.unset(layer, id, name, key ?? undefined);
445
+ return layer;
446
+ }
447
+ }
448
+ return null;
449
+ }
450
+
451
+ /**
452
+ * Save: move every session override to the user layer (which ui-config
453
+ * persists), then clear the session.
454
+ * @returns {number} the number of overrides moved
455
+ */
456
+ export function saveSession(config, { policy }) {
457
+ if (!policy.writeLayers.includes('user')) {
458
+ fail('read-only-layer', 'The site policy does not allow saving');
459
+ }
460
+ const moved = config.overrides('session');
461
+ for (const o of moved) {
462
+ config.set('user', o.id, o.name, o.values, o.key ?? undefined);
463
+ }
464
+ config.clear('session');
465
+ return moved.length;
466
+ }
467
+
468
+ /** Discard: clear the session layer. */
469
+ export function discardSession(config) {
470
+ const count = config.overrides('session').length;
471
+ config.clear('session');
472
+ return count;
473
+ }