@link-foundation/ui-devmode 0.0.0-stage → 0.1.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,170 @@
1
+ import {
2
+ defaultVocabulary,
3
+ parseLinks,
4
+ valueMatches,
5
+ } from '@link-foundation/ui-core';
6
+
7
+ const TYPES = ['color', 'dimension', 'duration', 'number', 'boolean'];
8
+
9
+ /** Build the target and ancestor index from the trusted site's schema. */
10
+ function schemaIndex(schema) {
11
+ const document = schema?.document ?? schema;
12
+ const vocabulary = schema?.vocabulary ?? defaultVocabulary();
13
+ const parents = new Map();
14
+ const nodes = new Map();
15
+ const walk = (node, parent = null) => {
16
+ nodes.set(node.id, node);
17
+ parents.set(node.id, parent);
18
+ node.children?.forEach((child) => walk(child, node.id));
19
+ };
20
+ document?.roots?.forEach((node) => walk(node));
21
+ return { nodes, parents, vocabulary };
22
+ }
23
+
24
+ function isOverrides(roots) {
25
+ if (roots.length !== 1) {
26
+ return false;
27
+ }
28
+ const [root] = roots;
29
+ return root && !Array.isArray(root) && root.values?.[0] === 'overrides';
30
+ }
31
+
32
+ function metadataReason(link, seen, nodes) {
33
+ const [command, id] = link;
34
+ if (seen.has(command) || link.length !== 2 || typeof id !== 'string') {
35
+ return `Invalid ${command}`;
36
+ }
37
+ if (command === 'layer' && !['user', 'session'].includes(id)) {
38
+ return 'Invalid layer';
39
+ }
40
+ if (command === 'base' && !nodes.has(id)) {
41
+ return 'Invalid base';
42
+ }
43
+ seen.add(command);
44
+ return null;
45
+ }
46
+
47
+ /** Validate untrusted links; only the returned links may be previewed. */
48
+ export function validateOverrides(text, { schema, policy = {} } = {}) {
49
+ let roots;
50
+ try {
51
+ roots = parseLinks(text, { maxInputSize: 65536, maxDepth: 16 });
52
+ } catch (error) {
53
+ return { links: [], rejected: [{ link: null, reason: error.message }] };
54
+ }
55
+ if (!isOverrides(roots)) {
56
+ return {
57
+ links: [],
58
+ rejected: [
59
+ {
60
+ link: roots[0] ?? null,
61
+ reason: 'Expected exactly one overrides link',
62
+ },
63
+ ],
64
+ };
65
+ }
66
+ const index = schemaIndex(schema);
67
+ const safe = ['overrides'];
68
+ const rejected = [];
69
+ const seen = new Set();
70
+ for (const link of roots[0].values.slice(1)) {
71
+ let reason;
72
+ if (!Array.isArray(link)) {
73
+ reason = 'Expected a layer, base or set child';
74
+ } else if (['layer', 'base'].includes(link[0])) {
75
+ reason = metadataReason(link, seen, index.nodes);
76
+ } else {
77
+ reason = validateSet(link, index, policy);
78
+ }
79
+ if (reason) {
80
+ rejected.push({ link, reason });
81
+ } else {
82
+ safe.push(link);
83
+ }
84
+ }
85
+ return { links: [{ id: roots[0].id, values: safe }], rejected };
86
+ }
87
+
88
+ function protectionReason(id, name, rest, parents, policy) {
89
+ for (let ancestor = id; ancestor; ancestor = parents.get(ancestor)) {
90
+ if (policy.lockedElements?.has(ancestor)) {
91
+ return 'Locked element';
92
+ }
93
+ }
94
+ const comfort = policy.comfortKeys ?? new Set();
95
+ if (comfort.has(name) || comfort.has(`${id}.${name}`)) {
96
+ return 'Comfort key';
97
+ }
98
+ if (name === 'token' && comfort.has(rest[0])) {
99
+ return 'Comfort key';
100
+ }
101
+ return null;
102
+ }
103
+
104
+ function propertyType(element, name, rest, vocabulary) {
105
+ const kind = vocabulary.kinds.get(element.kind);
106
+ const property = kind?.properties.get(
107
+ name === element.kind ? kind.positional[0] : name
108
+ );
109
+ if (
110
+ !property ||
111
+ property.type === 'action' ||
112
+ ['bind', 'machine'].includes(name)
113
+ ) {
114
+ return { reason: 'Unknown or non-data property' };
115
+ }
116
+ if (name !== 'token') {
117
+ return { type: property.type, values: rest };
118
+ }
119
+ const [key, ...values] = rest;
120
+ const token = element.properties.find(
121
+ (p) => p.name === 'token' && p.values[0] === key
122
+ );
123
+ if (!token) {
124
+ return { reason: 'Unknown token' };
125
+ }
126
+ // The dialect declares tokens as any; use the existing scalar's type.
127
+ const type = TYPES.find((t) => valueMatches(t, token.values[1])) ?? 'string';
128
+ return { type, values };
129
+ }
130
+
131
+ function scalarReason(type, values) {
132
+ if (
133
+ values.length !== 1 ||
134
+ typeof values[0] !== 'string' ||
135
+ type === 'any' ||
136
+ !valueMatches(type, values[0])
137
+ ) {
138
+ return 'Wrong value type';
139
+ }
140
+ const unsafe = ['javascript:', 'data:', 'vbscript:'];
141
+ if (
142
+ ['url', 'element-ref-or-url'].includes(type) &&
143
+ unsafe.some((scheme) => values[0].trim().toLowerCase().startsWith(scheme))
144
+ ) {
145
+ return 'Unsafe URL';
146
+ }
147
+ return null;
148
+ }
149
+
150
+ function validateSet(link, { nodes, parents, vocabulary }, policy) {
151
+ const [command, id, name, ...rest] = link;
152
+ if (command !== 'set' || name === 'on') {
153
+ return 'Only data set links are allowed; actions are forbidden';
154
+ }
155
+ const element = nodes.get(id);
156
+ if (!element) {
157
+ return 'Unknown element';
158
+ }
159
+ const protectedKey = protectionReason(id, name, rest, parents, policy);
160
+ if (protectedKey) {
161
+ return protectedKey;
162
+ }
163
+ const { type, values, reason } = propertyType(
164
+ element,
165
+ name,
166
+ rest,
167
+ vocabulary
168
+ );
169
+ return reason ?? scalarReason(type, values);
170
+ }
package/src/views.js ADDED
@@ -0,0 +1,328 @@
1
+ /**
2
+ * The views of the inspector tabs, built with DOM APIs into the tab panels
3
+ * of the layout: the outline (a WAI-ARIA tree), the property grid and the
4
+ * read-only Styles, Tokens, Animations and Source views. Values reach the
5
+ * DOM as text only.
6
+ */
7
+
8
+ import { createEditor } from './editors.js';
9
+ import { flattenOutline } from './model.js';
10
+
11
+ const el = (doc, tag, attributes = {}, textContent) => {
12
+ const node = doc.createElement(tag);
13
+ for (const [name, value] of Object.entries(attributes)) {
14
+ node.setAttribute(name, value);
15
+ }
16
+ if (textContent !== undefined) {
17
+ node.textContent = textContent;
18
+ }
19
+ return node;
20
+ };
21
+
22
+ const note = (doc, text) => el(doc, 'p', { class: 'note' }, text);
23
+
24
+ /**
25
+ * The outline: a WAI-ARIA tree of the document, one treeitem per element
26
+ * (`id` and kind), selection following the focus.
27
+ * @param {HTMLElement} panel
28
+ * @param {import('./model.js').OutlineNode[]} outline
29
+ * @param {{ t: Function, onSelect: (id: string) => void }} options
30
+ * @returns {{ select: (id: string|null) => void }}
31
+ */
32
+ export function renderOutline(panel, outline, { t, onSelect }) {
33
+ const doc = panel.ownerDocument;
34
+ panel.replaceChildren();
35
+ const tree = el(doc, 'ul', {
36
+ role: 'tree',
37
+ 'aria-label': t('outline.label'),
38
+ });
39
+ const items = new Map();
40
+ const build = (node, level, into) => {
41
+ const item = el(doc, 'li', {
42
+ role: 'treeitem',
43
+ 'aria-level': String(level),
44
+ 'aria-selected': 'false',
45
+ tabindex: '-1',
46
+ 'data-id': node.id,
47
+ });
48
+ const row = el(doc, 'span', { class: 'row' });
49
+ const toggle = el(doc, 'span', { class: 'toggle', 'aria-hidden': 'true' });
50
+ row.append(
51
+ toggle,
52
+ el(doc, 'span', { class: 'id' }, node.id),
53
+ el(doc, 'span', { class: 'kind' }, node.type)
54
+ );
55
+ item.append(row);
56
+ if (node.children.length > 0) {
57
+ item.setAttribute('aria-expanded', 'true');
58
+ toggle.textContent = '▾';
59
+ const group = el(doc, 'ul', { role: 'group' });
60
+ node.children.forEach((child) => build(child, level + 1, group));
61
+ item.append(group);
62
+ }
63
+ items.set(node.id, item);
64
+ into.append(item);
65
+ };
66
+ outline.forEach((node) => build(node, 1, tree));
67
+ panel.append(tree);
68
+ const first = tree.querySelector('[role="treeitem"]');
69
+ if (first) {
70
+ first.tabIndex = 0;
71
+ }
72
+
73
+ const visible = () =>
74
+ flattenOutline(outline)
75
+ .map(({ node }) => items.get(node.id))
76
+ .filter((item) => !item.parentElement.closest('[aria-expanded="false"]'));
77
+ const setExpanded = (item, expanded) => {
78
+ item.setAttribute('aria-expanded', String(expanded));
79
+ item.querySelector('.toggle').textContent = expanded ? '▾' : '▸';
80
+ item.querySelector('[role="group"]').hidden = !expanded;
81
+ };
82
+ const focusItem = (item) => {
83
+ onSelect(item.dataset.id);
84
+ item.focus();
85
+ };
86
+ tree.addEventListener('click', (event) => {
87
+ const item = event.target.closest('[role="treeitem"]');
88
+ if (!item) {
89
+ return;
90
+ }
91
+ if (event.target.closest('.toggle') && item.hasAttribute('aria-expanded')) {
92
+ setExpanded(item, item.getAttribute('aria-expanded') !== 'true');
93
+ }
94
+ focusItem(item);
95
+ });
96
+ tree.addEventListener('keydown', (event) => {
97
+ const item = event.target.closest('[role="treeitem"]');
98
+ const list = visible();
99
+ const at = list.indexOf(item);
100
+ if (at < 0) {
101
+ return;
102
+ }
103
+ const expandable = item.hasAttribute('aria-expanded');
104
+ const expanded = item.getAttribute('aria-expanded') === 'true';
105
+ const parent = item.parentElement.closest('[role="treeitem"]');
106
+ const moves = {
107
+ ArrowDown: () => list[at + 1],
108
+ ArrowUp: () => list[at - 1],
109
+ Home: () => list[0],
110
+ End: () => list.at(-1),
111
+ ArrowRight: () =>
112
+ expandable && !expanded
113
+ ? setExpanded(item, true)
114
+ : expanded
115
+ ? list[at + 1]
116
+ : undefined,
117
+ ArrowLeft: () =>
118
+ expandable && expanded ? setExpanded(item, false) : parent,
119
+ };
120
+ if (!(event.key in moves)) {
121
+ return;
122
+ }
123
+ event.preventDefault();
124
+ const next = moves[event.key]();
125
+ if (next) {
126
+ focusItem(next);
127
+ }
128
+ });
129
+
130
+ return {
131
+ select(id) {
132
+ for (const [itemId, item] of items) {
133
+ const on = itemId === id;
134
+ item.setAttribute('aria-selected', String(on));
135
+ item.tabIndex = on ? 0 : -1;
136
+ }
137
+ if (!items.has(id) && first) {
138
+ first.tabIndex = 0;
139
+ }
140
+ },
141
+ };
142
+ }
143
+
144
+ /**
145
+ * The property grid of one element: `name | editor | resolved value |
146
+ * source layer | reset`. Rows whose value comes from `user` or `session`
147
+ * have the class `is-changed`.
148
+ * @param {HTMLElement} panel
149
+ * @param {{ id: string, rows: import('./model.js').PropertyRow[],
150
+ * locked: boolean, writable: boolean, tokenPaths: readonly string[] }} data
151
+ * @param {{ t: Function, onEdit: (row: object, value: unknown) => string|null,
152
+ * onReset: (row: object) => void }} options
153
+ * @returns {{ update: (rows: import('./model.js').PropertyRow[]) => void }}
154
+ */
155
+ export function renderProperties(panel, data, { t, onEdit, onReset }) {
156
+ const doc = panel.ownerDocument;
157
+ panel.replaceChildren();
158
+ if (data.locked) {
159
+ panel.append(note(doc, t('properties.locked', { id: data.id })));
160
+ } else if (!data.writable) {
161
+ panel.append(note(doc, t('properties.readOnly')));
162
+ }
163
+ const table = el(doc, 'table', { 'data-element': data.id });
164
+ table.append(
165
+ el(doc, 'caption', {}, t('properties.caption', { id: data.id }))
166
+ );
167
+ const head = el(doc, 'tr');
168
+ for (const key of ['name', 'editor', 'value', 'layer', 'reset']) {
169
+ head.append(el(doc, 'th', { scope: 'col' }, t(`properties.${key}`)));
170
+ }
171
+ table.append(el(doc, 'thead'));
172
+ table.tHead.append(head);
173
+ const body = el(doc, 'tbody');
174
+ table.append(body);
175
+ const cells = new Map();
176
+ const rowKey = (row) => `${row.name}\u0000${row.key ?? ''}`;
177
+ for (const row of data.rows) {
178
+ const tr = el(doc, 'tr', { 'data-name': row.label });
179
+ const editor = createEditor(doc, row, {
180
+ t,
181
+ tokenPaths: data.tokenPaths,
182
+ onEdit: (value) => onEdit(row, value),
183
+ });
184
+ const resolved = el(doc, 'td', { class: 'resolved' });
185
+ const layer = el(doc, 'span', { class: 'layer' });
186
+ const reset = el(
187
+ doc,
188
+ 'button',
189
+ {
190
+ type: 'button',
191
+ 'aria-label': t('properties.resetLabel', { name: row.label }),
192
+ },
193
+ t('properties.reset')
194
+ );
195
+ reset.addEventListener('click', () => onReset(row));
196
+ const editorCell = el(doc, 'td');
197
+ editorCell.append(editor.node);
198
+ const layerCell = el(doc, 'td');
199
+ layerCell.append(layer);
200
+ const resetCell = el(doc, 'td');
201
+ resetCell.append(reset);
202
+ tr.append(el(doc, 'th', { scope: 'row' }, row.label));
203
+ tr.append(editorCell, resolved, layerCell, resetCell);
204
+ body.append(tr);
205
+ cells.set(rowKey(row), { tr, editor, resolved, layer, reset });
206
+ }
207
+ panel.append(table);
208
+
209
+ const update = (rows) => {
210
+ for (const row of rows) {
211
+ const cell = cells.get(rowKey(row));
212
+ if (!cell) {
213
+ continue;
214
+ }
215
+ cell.editor.update(row);
216
+ cell.resolved.textContent = row.text === '' ? '—' : row.text;
217
+ cell.layer.textContent = row.layer;
218
+ cell.tr.dataset.layer = row.layer;
219
+ cell.tr.classList.toggle('is-changed', row.changed);
220
+ cell.tr.classList.toggle('is-locked', row.locked);
221
+ cell.reset.disabled = !row.writable || !row.changed;
222
+ }
223
+ };
224
+ update(data.rows);
225
+ return { update };
226
+ }
227
+
228
+ /** The matching style rules of the element, base rule first. */
229
+ export function renderStyles(panel, { id, styles }, { t }) {
230
+ const doc = panel.ownerDocument;
231
+ panel.replaceChildren();
232
+ if (styles.length === 0) {
233
+ panel.append(note(doc, t('styles.none', { id })));
234
+ return;
235
+ }
236
+ for (const style of styles) {
237
+ const when = [...style.states, ...style.at];
238
+ panel.append(
239
+ el(
240
+ doc,
241
+ 'h3',
242
+ {},
243
+ `${style.rule} (${when.length > 0 ? when.join(', ') : t('styles.base')})`
244
+ )
245
+ );
246
+ const list = el(doc, 'dl');
247
+ for (const decl of style.declarations) {
248
+ list.append(
249
+ el(doc, 'dt', {}, decl.property),
250
+ el(doc, 'dd', {}, decl.text)
251
+ );
252
+ }
253
+ panel.append(list);
254
+ }
255
+ }
256
+
257
+ /** The tokens the element uses: path, resolved value, layer, users. */
258
+ export function renderTokens(panel, { id, tokens }, { t }) {
259
+ const doc = panel.ownerDocument;
260
+ panel.replaceChildren();
261
+ if (tokens.length === 0) {
262
+ panel.append(note(doc, t('tokens.none', { id })));
263
+ return;
264
+ }
265
+ const table = el(doc, 'table');
266
+ table.append(el(doc, 'caption', {}, t('tokens.caption', { id })));
267
+ const head = el(doc, 'tr');
268
+ for (const key of ['token', 'value', 'layer', 'usedBy']) {
269
+ head.append(el(doc, 'th', { scope: 'col' }, t(`tokens.${key}`)));
270
+ }
271
+ table.append(el(doc, 'thead'));
272
+ table.tHead.append(head);
273
+ const body = el(doc, 'tbody');
274
+ for (const token of tokens) {
275
+ const value = el(doc, 'td', { class: 'resolved' });
276
+ if (token.css) {
277
+ const swatch = el(doc, 'span', {
278
+ class: 'swatch',
279
+ 'aria-hidden': 'true',
280
+ });
281
+ swatch.style.background = token.css;
282
+ value.append(swatch);
283
+ }
284
+ value.append(token.text);
285
+ const tr = el(doc, 'tr', { 'data-token': token.path });
286
+ tr.append(
287
+ el(doc, 'th', { scope: 'row' }, token.path),
288
+ value,
289
+ el(doc, 'td', {}, token.layer),
290
+ el(doc, 'td', {}, token.usedBy.join(', '))
291
+ );
292
+ body.append(tr);
293
+ }
294
+ table.append(body);
295
+ panel.append(table);
296
+ }
297
+
298
+ /** The animations that target the element, read-only. */
299
+ export function renderAnimations(panel, { id, animations }, { t }) {
300
+ const doc = panel.ownerDocument;
301
+ panel.replaceChildren();
302
+ if (animations.length === 0) {
303
+ panel.append(note(doc, t('animations.none', { id })));
304
+ return;
305
+ }
306
+ panel.append(note(doc, t('animations.readOnly')));
307
+ for (const animation of animations) {
308
+ panel.append(el(doc, 'h3', {}, animation.id));
309
+ const list = el(doc, 'dl');
310
+ for (const { name, text } of animation.properties) {
311
+ list.append(el(doc, 'dt', {}, name), el(doc, 'dd', {}, text));
312
+ }
313
+ panel.append(list);
314
+ }
315
+ }
316
+
317
+ /** The Links Notation source of the element, read-only. */
318
+ export function renderSource(panel, { id, source }, { t }) {
319
+ const doc = panel.ownerDocument;
320
+ panel.replaceChildren(
321
+ el(doc, 'pre', { 'aria-label': t('source.label', { id }) }, source)
322
+ );
323
+ }
324
+
325
+ /** The empty state of a view without a selection. */
326
+ export function renderEmpty(panel, { t }) {
327
+ panel.replaceChildren(note(panel.ownerDocument, t('empty.selection')));
328
+ }