@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
package/src/details.js ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * The read-only tabs of the inspector, without a DOM: the style rules that
3
+ * match an element, the design tokens it uses, the animations that target
4
+ * it and its Links Notation source. Every function here is pure.
5
+ */
6
+
7
+ import { format, values as uiValues } from '@link-foundation/ui-core';
8
+ import { flatten, matches } from '@link-foundation/ui-style';
9
+ import { formatValues, tokenPath } from './model.js';
10
+
11
+ /** A typed value (ui-core `values`) as text; a colour as CSS (`#6750A4`). */
12
+ export function formatTyped(value) {
13
+ if (value?.type === 'color') {
14
+ return uiValues.colorCss(value);
15
+ }
16
+ return uiValues.formatValue(value);
17
+ }
18
+
19
+ const formatAt = ({ kind, conditions }) =>
20
+ `${kind} ${conditions
21
+ .map((c) => `(${c.feature} ${formatTyped(c.value)})`)
22
+ .join(' ')}`;
23
+
24
+ /**
25
+ * The ancestors of an element, from the root to its parent.
26
+ * @param {string} id
27
+ * @param {{ get: (id: string) => object|undefined,
28
+ * parentOf: (id: string) => string|null }} tree a ui-store store
29
+ */
30
+ export function ancestorsOf(id, tree) {
31
+ const out = [];
32
+ for (let at = tree.parentOf(id); at; at = tree.parentOf(at)) {
33
+ out.unshift(tree.get(at));
34
+ }
35
+ return out;
36
+ }
37
+
38
+ /**
39
+ * @typedef {object} StyleMatch
40
+ * @property {string} rule the id of the style rule
41
+ * @property {readonly string[]} states `hover`, `pressed`, …
42
+ * @property {readonly string[]} at media and container conditions
43
+ * @property {{ property: string, text: string, token: string|null }[]} declarations
44
+ */
45
+
46
+ /**
47
+ * The style entries (base rule, states, media blocks) that match an
48
+ * element, in cascade order.
49
+ * @param {object} element a ui-core node or ui-store view
50
+ * @param {readonly object[]} ancestors from the root to the parent
51
+ * @param {readonly object[]} rules ui-style `readStyles(…).rules`
52
+ * @returns {StyleMatch[]}
53
+ */
54
+ export function matchingStyles(element, ancestors, rules) {
55
+ return flatten(rules ?? [])
56
+ .filter((entry) => matches(entry.selector, element, ancestors))
57
+ .map((entry) => ({
58
+ rule: entry.id,
59
+ states: entry.states,
60
+ at: entry.at.map(formatAt),
61
+ declarations: entry.declarations.map(({ property, value }) => ({
62
+ property,
63
+ text: formatTyped(value),
64
+ token: value.type === 'token-ref' ? value.path : null,
65
+ })),
66
+ }));
67
+ }
68
+
69
+ /**
70
+ * The animations that target an element: `(target id)`.
71
+ * @param {string} id
72
+ * @param {readonly object[]} nodes ui-core nodes (any kind; the
73
+ * `animation` ones are read)
74
+ * @returns {{ id: string, source: string,
75
+ * properties: { name: string, text: string, token: string|null }[] }[]}
76
+ */
77
+ export function animationsOf(id, nodes) {
78
+ const target = (node) =>
79
+ node.properties.find((p) => p.name === 'target')?.values[0];
80
+ return (nodes ?? [])
81
+ .filter((node) => node.kind === 'animation' && target(node) === id)
82
+ .map((node) => ({
83
+ id: node.id,
84
+ properties: node.properties.map(({ name, values }) => ({
85
+ name,
86
+ text: formatValues(values),
87
+ token: tokenPath(values),
88
+ })),
89
+ source: sourceOf(node),
90
+ }));
91
+ }
92
+
93
+ /**
94
+ * The Links Notation source of one element (with its children), written by
95
+ * ui-core `format` in the nested form.
96
+ * @param {object} node a ui-core node
97
+ */
98
+ export const sourceOf = (node) =>
99
+ format({ roots: [node], unknown: [] }).trimEnd();
100
+
101
+ /**
102
+ * The tokens an element uses: the token references of its properties, of
103
+ * the style rules that match it and of the animations that target it.
104
+ * @param {{ rows: readonly { label: string, value?: readonly unknown[] }[],
105
+ * styles: readonly StyleMatch[],
106
+ * animations: readonly { id: string,
107
+ * properties: { name: string, token: string|null }[] }[] }} uses
108
+ * @param {Map<string, { value: object, set: string }>|undefined} tokens
109
+ * ui-tokens `resolveTokens(…)`
110
+ * @param {(path: string) => { value: readonly unknown[], layer: string }|undefined} [resolveOverride]
111
+ * the value of a token in the configuration, when a layer overrides it
112
+ * @returns {{ path: string, usedBy: string[], text: string, css: string|null, layer: string }[]}
113
+ */
114
+ export function tokensUsed(uses, tokens, resolveOverride) {
115
+ const found = new Map();
116
+ const use = (path, by) => {
117
+ if (path === null) {
118
+ return;
119
+ }
120
+ const list = found.get(path) ?? [];
121
+ if (!list.includes(by)) {
122
+ list.push(by);
123
+ }
124
+ found.set(path, list);
125
+ };
126
+ for (const row of uses.rows) {
127
+ use(tokenPath(row.value), row.label);
128
+ }
129
+ for (const style of uses.styles) {
130
+ for (const decl of style.declarations) {
131
+ use(decl.token, `${style.rule} ${decl.property}`);
132
+ }
133
+ }
134
+ for (const animation of uses.animations) {
135
+ for (const { name, token } of animation.properties) {
136
+ use(token, `${animation.id} ${name}`);
137
+ }
138
+ }
139
+ return [...found].map(([path, usedBy]) => {
140
+ const override = resolveOverride?.(path);
141
+ const token = tokens?.get(path);
142
+ const text = override
143
+ ? formatValues(override.value)
144
+ : token
145
+ ? formatTyped(token.value)
146
+ : '';
147
+ const css =
148
+ !override && token?.value?.type === 'color'
149
+ ? uiValues.colorCss(token.value)
150
+ : null;
151
+ return {
152
+ path,
153
+ usedBy,
154
+ text,
155
+ css,
156
+ layer: override?.layer ?? (token ? 'theme' : 'defaults'),
157
+ };
158
+ });
159
+ }
package/src/editors.js ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * The typed editors of the property grid, built from native form controls:
3
+ * a text field, a number field, a number with a unit, a colour picker, a
4
+ * select for an enum, a switch for a boolean and a token reference field.
5
+ * Every editor writes through `onEdit(value)`, which applies the value to
6
+ * the session layer at once.
7
+ */
8
+
9
+ import { values as uiValues } from '@link-foundation/ui-core';
10
+ import { tokenPath } from './model.js';
11
+
12
+ /** The single atom of a value, or `undefined`. */
13
+ const atomOf = (values) =>
14
+ Array.isArray(values) && values.length === 1 && typeof values[0] === 'string'
15
+ ? values[0]
16
+ : undefined;
17
+
18
+ /** `#rrggbb` for an `<input type=color>`, or `undefined`. */
19
+ function hexOf(text) {
20
+ const parsed = text === undefined ? null : uiValues.parseColor(text);
21
+ return parsed ? uiValues.toHex(parsed).slice(0, 7).toLowerCase() : undefined;
22
+ }
23
+
24
+ const el = (doc, tag, attributes = {}) => {
25
+ const node = doc.createElement(tag);
26
+ for (const [name, value] of Object.entries(attributes)) {
27
+ node.setAttribute(name, value);
28
+ }
29
+ return node;
30
+ };
31
+
32
+ /** Whether a control has the focus (then it is not overwritten). */
33
+ const focused = (node) => node.getRootNode().activeElement === node;
34
+
35
+ /** Set a control's value unless the user is typing in it. */
36
+ function setValue(control, value) {
37
+ if (!focused(control) && control.value !== value) {
38
+ control.value = value;
39
+ }
40
+ }
41
+
42
+ /** The number of token lists made, for unique `datalist` ids. */
43
+ let lists = 0;
44
+
45
+ const BUILDERS = {
46
+ string(doc) {
47
+ const input = el(doc, 'input', { type: 'text' });
48
+ return {
49
+ controls: [input],
50
+ read: () => input.value,
51
+ write: (r) => setValue(input, atomOf(r.value) ?? r.text),
52
+ events: [[input, 'input']],
53
+ skip: () => input.value === '',
54
+ };
55
+ },
56
+ number(doc) {
57
+ const input = el(doc, 'input', { type: 'number', step: 'any' });
58
+ return {
59
+ controls: [input],
60
+ read: () => input.value,
61
+ write: (r) => setValue(input, atomOf(r.value) ?? ''),
62
+ events: [[input, 'input']],
63
+ skip: () => input.value === '',
64
+ };
65
+ },
66
+ dimension(doc, row, t) {
67
+ const input = el(doc, 'input', { type: 'number', step: 'any' });
68
+ const unit = el(doc, 'select', {
69
+ 'aria-label': t('properties.unitLabel', { name: row.label }),
70
+ });
71
+ for (const name of row.units) {
72
+ const option = el(doc, 'option', { value: name });
73
+ option.textContent = name;
74
+ unit.append(option);
75
+ }
76
+ return {
77
+ controls: [input, unit],
78
+ read: () => `${input.value}${unit.value}`,
79
+ write(r) {
80
+ const quantity = uiValues.splitQuantity(atomOf(r.value) ?? '', r.units);
81
+ setValue(input, quantity ? String(quantity.value) : '');
82
+ setValue(unit, quantity?.unit ?? r.units[0]);
83
+ },
84
+ events: [
85
+ [input, 'input'],
86
+ [unit, 'change'],
87
+ ],
88
+ skip: () => input.value === '',
89
+ };
90
+ },
91
+ color(doc) {
92
+ const input = el(doc, 'input', { type: 'color' });
93
+ return {
94
+ controls: [input],
95
+ read: () => input.value,
96
+ write: (r) => setValue(input, hexOf(atomOf(r.value)) ?? '#000000'),
97
+ events: [[input, 'input']],
98
+ };
99
+ },
100
+ enum(doc, row, t) {
101
+ const select = el(doc, 'select');
102
+ const unset = el(doc, 'option', { value: '', disabled: '' });
103
+ unset.textContent = t('properties.unset');
104
+ select.append(unset);
105
+ for (const name of row.options) {
106
+ const option = el(doc, 'option', { value: name });
107
+ option.textContent = name;
108
+ select.append(option);
109
+ }
110
+ return {
111
+ controls: [select],
112
+ read: () => select.value,
113
+ write: (r) => setValue(select, atomOf(r.value) ?? ''),
114
+ events: [[select, 'change']],
115
+ skip: () => select.value === '',
116
+ };
117
+ },
118
+ boolean(doc) {
119
+ const input = el(doc, 'input', { type: 'checkbox', role: 'switch' });
120
+ return {
121
+ controls: [input],
122
+ read: () => String(input.checked),
123
+ write(r) {
124
+ input.checked = atomOf(r.value) === 'true';
125
+ },
126
+ events: [[input, 'change']],
127
+ };
128
+ },
129
+ token(doc, row, t, tokenPaths) {
130
+ const input = el(doc, 'input', { type: 'text' });
131
+ const controls = [input];
132
+ if (tokenPaths.length > 0) {
133
+ lists += 1;
134
+ const list = el(doc, 'datalist', { id: `devmode-token-paths-${lists}` });
135
+ for (const path of tokenPaths) {
136
+ list.append(el(doc, 'option', { value: path }));
137
+ }
138
+ input.setAttribute('list', list.id);
139
+ controls.push(list);
140
+ }
141
+ return {
142
+ controls,
143
+ read: () => ({ token: input.value }),
144
+ write: (r) => setValue(input, tokenPath(r.value) ?? ''),
145
+ events: [[input, 'input']],
146
+ skip: () => input.value === '',
147
+ };
148
+ },
149
+ };
150
+
151
+ /**
152
+ * The editor of a property row.
153
+ * @param {Document} doc
154
+ * @param {import('./model.js').PropertyRow} row
155
+ * @param {{ t: (key: string, params?: object) => string,
156
+ * onEdit: (value: unknown) => string|null,
157
+ * tokenPaths?: readonly string[] }} options `onEdit` returns an error
158
+ * message, or `null` when the value was applied
159
+ * @returns {{ node: HTMLElement, update: (row: import('./model.js').PropertyRow) => void }}
160
+ */
161
+ export function createEditor(doc, row, { t, onEdit, tokenPaths = [] }) {
162
+ const node = el(doc, 'div', { class: 'editor' });
163
+ if (row.editor === 'readonly') {
164
+ node.textContent = '—';
165
+ return { node, update() {} };
166
+ }
167
+ const editor = BUILDERS[row.editor](doc, row, t, tokenPaths);
168
+ const [main] = editor.controls;
169
+ main.setAttribute('aria-label', row.label);
170
+ node.append(...editor.controls);
171
+ const commit = () => {
172
+ if (editor.skip?.()) {
173
+ return;
174
+ }
175
+ const error = onEdit(editor.read());
176
+ main.setAttribute('aria-invalid', String(error !== null));
177
+ if (error === null) {
178
+ main.removeAttribute('title');
179
+ } else {
180
+ main.title = error;
181
+ }
182
+ };
183
+ for (const [control, type] of editor.events) {
184
+ control.addEventListener(type, commit);
185
+ }
186
+ const update = (next) => {
187
+ editor.write(next);
188
+ for (const control of editor.controls) {
189
+ control.disabled = !next.writable;
190
+ }
191
+ };
192
+ update(row);
193
+ return { node, update };
194
+ }
package/src/export.js ADDED
@@ -0,0 +1,50 @@
1
+ import { formatLinks, parseLinks } from '@link-foundation/ui-core';
2
+ import { readPatch } from '@link-foundation/ui-config';
3
+
4
+ /** Export only writable-layer changes relative to site, in stable ID/property order. */
5
+ export function exportOverrides(
6
+ config,
7
+ { id = 'user-overrides', base, layers = ['user', 'session'] } = {}
8
+ ) {
9
+ if (layers.some((layer) => !['user', 'session'].includes(layer))) {
10
+ throw new Error('Only user and session overrides can be exported');
11
+ }
12
+ const exported = config.exportPatch({ layers, against: 'site', base });
13
+ const patch = readPatch(exported, {
14
+ maxSize: exported.length * 3,
15
+ maxOps: Number.MAX_SAFE_INTEGER,
16
+ });
17
+ if (patch.diagnostics.some((d) => d.severity === 'error')) {
18
+ throw new Error(patch.diagnostics.map((d) => d.message).join('; '));
19
+ }
20
+ const compare = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
21
+ patch.ops.sort(
22
+ (a, b) =>
23
+ compare(a.id, b.id) ||
24
+ compare(a.name, b.name) ||
25
+ compare(a.key ?? '', b.key ?? '')
26
+ );
27
+ const links = [
28
+ {
29
+ id,
30
+ values: [
31
+ 'overrides',
32
+ ['layer', 'user'],
33
+ ...(patch.base ? [['base', patch.base]] : []),
34
+ ...patch.ops.map((op) => [
35
+ 'set',
36
+ op.id,
37
+ op.name,
38
+ ...(op.key === null ? [] : [op.key]),
39
+ ...op.values,
40
+ ]),
41
+ ],
42
+ },
43
+ ];
44
+ const text = formatLinks(links);
45
+ return {
46
+ text,
47
+ links: parseLinks(text, { maxInputSize: text.length }),
48
+ count: patch.ops.length,
49
+ };
50
+ }
@@ -0,0 +1,166 @@
1
+ import { observeDom, restoreOverrides, treeView } from './runtime.js';
2
+ import { baseDocument, foreignRows, updateOriginals } from './properties.js';
3
+ import { createConfig } from '@link-foundation/ui-config';
4
+ import { importDom as defaultImportDom } from '@link-foundation/ui-convert/browser';
5
+ import { exportOverrides } from '../export.js';
6
+ import { DevModeError } from '../model.js';
7
+ import {
8
+ applyProperty,
9
+ checkProperty,
10
+ readProperty,
11
+ restoreProperty,
12
+ } from './apply.js';
13
+
14
+ /** The shared inspector adapter. It never writes mapping attributes to the page. */
15
+ export function createForeignAdapter({
16
+ root = globalThis.document.body,
17
+ importDom = defaultImportDom,
18
+ ignore = () => false,
19
+ delay = 200,
20
+ } = {}) {
21
+ const listeners = new Set();
22
+ const originals = new Map();
23
+ let imported;
24
+ let reverse;
25
+ let config;
26
+ let syncing = false;
27
+ const notify = () => listeners.forEach((callback) => callback());
28
+ const nameOf = (op) =>
29
+ op.key === null || op.key === undefined ? op.name : `${op.name} ${op.key}`;
30
+ const allOps = () =>
31
+ ['user', 'session'].flatMap((layer) => config?.overrides(layer) ?? []);
32
+ const keyOf = (id, name) => JSON.stringify([id, name]);
33
+ const remember = (id, name, node) => {
34
+ const key = keyOf(id, name);
35
+ if (!originals.has(key)) {
36
+ originals.set(key, {
37
+ id,
38
+ name,
39
+ node,
40
+ value: readProperty(node, name),
41
+ priority: name.startsWith('style ')
42
+ ? node.style.getPropertyPriority(name.slice(6))
43
+ : '',
44
+ });
45
+ }
46
+ };
47
+ const reconcile = () => {
48
+ if (syncing) {
49
+ return;
50
+ }
51
+ const effective = new Map(
52
+ allOps().map((op) => [keyOf(op.id, nameOf(op)), op])
53
+ );
54
+ for (const [key, original] of originals) {
55
+ const node = imported.nodeMap.get(original.id);
56
+ if (!node) {
57
+ continue;
58
+ }
59
+ const op = effective.get(key);
60
+ try {
61
+ if (op) {
62
+ checkProperty(node, original.name, op.values[0]);
63
+ if (readProperty(node, original.name) !== op.values[0]) {
64
+ applyProperty(node, original.name, op.values[0]);
65
+ }
66
+ } else if (
67
+ node === original.node &&
68
+ readProperty(node, original.name) !== original.value
69
+ ) {
70
+ restoreProperty(
71
+ node,
72
+ original.name,
73
+ original.value,
74
+ original.priority
75
+ );
76
+ }
77
+ } catch {
78
+ /* The page may have replaced a leaf with a container. */
79
+ }
80
+ }
81
+ notify();
82
+ };
83
+ const refresh = () => {
84
+ const saved = ['user', 'session'].map((layer) => [
85
+ layer,
86
+ config?.overrides(layer) ?? [],
87
+ ]);
88
+ imported = importDom(root, { ignore });
89
+ updateOriginals(originals, imported.nodeMap);
90
+ reverse = new WeakMap(
91
+ [...imported.nodeMap].map(([id, node]) => [node, id])
92
+ );
93
+ config = createConfig({
94
+ document: { roots: baseDocument(imported.nodeMap, originals) },
95
+ keyedProps: ['attr', 'style'],
96
+ });
97
+ syncing = true;
98
+ for (const [layer, ops] of saved) {
99
+ for (const op of ops) {
100
+ if (imported.nodeMap.has(op.id)) {
101
+ config.set(layer, op.id, op.name, op.values, op.key ?? undefined);
102
+ }
103
+ }
104
+ }
105
+ syncing = false;
106
+ config.subscribe(reconcile);
107
+ reconcile();
108
+ };
109
+ refresh();
110
+ // A stable proxy keeps the inspector subscribed while the live tree changes.
111
+ const configuration = new Proxy(
112
+ {},
113
+ {
114
+ get: (_, key) =>
115
+ key === 'subscribe'
116
+ ? (callback) => {
117
+ listeners.add(callback);
118
+ return () => listeners.delete(callback);
119
+ }
120
+ : config[key],
121
+ }
122
+ );
123
+ const tree = treeView(() => imported.tree, configuration.subscribe);
124
+ const adapter = {
125
+ config: configuration,
126
+ tree: () => tree,
127
+ nodeFor: (id) => imported.nodeMap.get(id) ?? null,
128
+ idFor(node) {
129
+ for (let at = node; at && root.contains(at); at = at.parentNode) {
130
+ const id = reverse.get(at);
131
+ if (id) {
132
+ return id;
133
+ }
134
+ }
135
+ return null;
136
+ },
137
+ applyProperty(id, name, value) {
138
+ name = typeof name === 'object' ? (name.label ?? nameOf(name)) : name;
139
+ const node = adapter.nodeFor(id);
140
+ checkProperty(node, name, value);
141
+ remember(id, name, node);
142
+ const [kind, key] = name.split(' ');
143
+ applyProperty(node, name, value);
144
+ config.set('session', id, kind, [value], key);
145
+ return { layer: 'session' };
146
+ },
147
+ rows: (id) => foreignRows(adapter, config, allOps, id),
148
+ observe: configuration.subscribe,
149
+ exportOverrides: () => exportOverrides(configuration),
150
+ subtree(id) {
151
+ const node = adapter.nodeFor(id);
152
+ if (!node) {
153
+ throw new DevModeError('unknown-element', 'Select an element first');
154
+ }
155
+ return importDom(node, { ignore }).text;
156
+ },
157
+ restore: (text) => restoreOverrides(adapter, text),
158
+ refresh,
159
+ destroy() {
160
+ observer();
161
+ listeners.clear();
162
+ },
163
+ };
164
+ const observer = observeDom(root, ignore, refresh, delay);
165
+ return adapter;
166
+ }
@@ -0,0 +1,89 @@
1
+ import { DevModeError } from '../model.js';
2
+
3
+ const refuse = (message) => {
4
+ throw new DevModeError('bad-value', message);
5
+ };
6
+ const scriptUrl = (value) =>
7
+ /(?:javascript|vbscript):/i.test(
8
+ [...value].filter((c) => c.charCodeAt(0) > 32).join('')
9
+ );
10
+
11
+ /** Validate a foreign edit before writing anything to the page. */
12
+ export function checkProperty(node, name, value) {
13
+ if (typeof value !== 'string') {
14
+ refuse('Foreign properties need text values');
15
+ }
16
+ if (!node || ![1, 3].includes(node.nodeType)) {
17
+ refuse('Unknown DOM node');
18
+ }
19
+ if (name === 'text') {
20
+ if (
21
+ node.nodeType === 1 &&
22
+ (node.children.length || ['script', 'style'].includes(node.localName))
23
+ ) {
24
+ refuse('Only leaf element text is editable');
25
+ }
26
+ return;
27
+ }
28
+ if (node.nodeType !== 1) {
29
+ refuse('Only elements have attributes and styles');
30
+ }
31
+ const [kind, key, ...extra] = name.split(' ');
32
+ if (!key || extra.length || !['attr', 'style'].includes(kind)) {
33
+ refuse('Expected text, attr <name> or style <property>');
34
+ }
35
+ if (scriptUrl(value)) {
36
+ refuse('Script URLs are not editable');
37
+ }
38
+ checkDeclaration(kind, key, value);
39
+ }
40
+
41
+ /** Text, a single attribute, or a single inline CSS declaration. */
42
+ export function applyProperty(node, name, value) {
43
+ checkProperty(node, name, value);
44
+ if (name === 'text') {
45
+ node.textContent = value;
46
+ } else if (name.startsWith('attr ')) {
47
+ node.setAttribute(name.slice(5), value);
48
+ } else {
49
+ node.style.setProperty(name.slice(6), value);
50
+ }
51
+ }
52
+
53
+ export function readProperty(node, name) {
54
+ if (name === 'text') {
55
+ return node.textContent;
56
+ }
57
+ if (name.startsWith('attr ')) {
58
+ return node.getAttribute(name.slice(5));
59
+ }
60
+ return node.style.getPropertyValue(name.slice(6));
61
+ }
62
+
63
+ /** Restore absence as well as values when discarding or resetting edits. */
64
+ export function restoreProperty(node, name, value, priority = '') {
65
+ if (name.startsWith('attr ') && value === null) {
66
+ node.removeAttribute(name.slice(5));
67
+ } else if (name.startsWith('style ')) {
68
+ if (value) {
69
+ node.style.setProperty(name.slice(6), value, priority);
70
+ } else {
71
+ node.style.removeProperty(name.slice(6));
72
+ }
73
+ } else {
74
+ applyProperty(node, name, value ?? '');
75
+ }
76
+ }
77
+
78
+ function checkDeclaration(kind, key, value) {
79
+ if (kind === 'attr') {
80
+ if (/^on/i.test(key) || ['srcdoc', 'style'].includes(key.toLowerCase())) {
81
+ refuse('Executable attributes are not editable');
82
+ }
83
+ } else if (
84
+ !/^(?:--[\w-]+|[a-z][a-z-]*)$/.test(key) ||
85
+ /expression\s*\(|-moz-binding/i.test(value)
86
+ ) {
87
+ refuse('Unsafe style declaration');
88
+ }
89
+ }