@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/session.js ADDED
@@ -0,0 +1,555 @@
1
+ /**
2
+ * An open dev mode: the overlay, the inspector and the wiring between them,
3
+ * the page and the configuration. `index.js` loads this module with a
4
+ * dynamic `import()` only when dev mode opens, so a page whose policy
5
+ * disables dev mode never downloads it (nor the inspector, the overlay and
6
+ * the model it imports).
7
+ */
8
+
9
+ import { parse } from '@link-foundation/ui-core';
10
+ import { readStyles } from '@link-foundation/ui-style';
11
+ import { readTokens, resolveTokens } from '@link-foundation/ui-tokens';
12
+ import {
13
+ ancestorsOf,
14
+ animationsOf,
15
+ matchingStyles,
16
+ sourceOf,
17
+ tokensUsed,
18
+ } from './details.js';
19
+ import { createUiDomAdapter } from './adapter.js';
20
+ import { createInspector, loadLayout } from './inspector.js';
21
+ import {
22
+ buildOutline,
23
+ DevModeError,
24
+ discardSession,
25
+ isLocked,
26
+ resetProperty,
27
+ saveSession,
28
+ } from './model.js';
29
+ import { openDefaultsDialog } from './defaults-dialog.js';
30
+ import { createOverlay } from './overlay.js';
31
+ import { mountComments } from './comments/index.js';
32
+ import {
33
+ renderAnimations,
34
+ renderEmpty,
35
+ renderOutline,
36
+ renderProperties,
37
+ renderSource,
38
+ renderStyles,
39
+ renderTokens,
40
+ } from './views.js';
41
+
42
+ /** The events pick mode takes from the page (the app never sees them). */
43
+ const PICK_EVENTS = [
44
+ 'pointerdown',
45
+ 'mousedown',
46
+ 'pointerup',
47
+ 'mouseup',
48
+ 'click',
49
+ 'dblclick',
50
+ 'auxclick',
51
+ ];
52
+
53
+ /** The `theme` atom of the first root element, if any. */
54
+ function themeOf(tree) {
55
+ const [first] = tree.roots();
56
+ const property = tree.get(first)?.properties?.find((p) => p.name === 'theme');
57
+ const value = property?.values?.[0];
58
+ return typeof value === 'string' ? value : undefined;
59
+ }
60
+
61
+ /** The resolved tokens: a ui-tokens map, or tokens.lino text. */
62
+ function readTokenMap(tokens, theme) {
63
+ if (tokens instanceof Map) {
64
+ return tokens;
65
+ }
66
+ if (typeof tokens !== 'string') {
67
+ return new Map();
68
+ }
69
+ const { sets } = readTokens(tokens);
70
+ const setId = [theme].find((id) => sets.has(id)) ?? [...sets.keys()][0];
71
+ return setId === undefined ? new Map() : resolveTokens(sets, setId);
72
+ }
73
+
74
+ /** The animation nodes: of the document and of the `animations` option. */
75
+ function animationNodes(tree, animations) {
76
+ const extra =
77
+ typeof animations === 'string'
78
+ ? parse(animations).roots
79
+ : (animations ?? []);
80
+ const own = [];
81
+ const walk = (node) => {
82
+ if (node.kind === 'animation') {
83
+ own.push(node);
84
+ }
85
+ (node.children ?? []).forEach(walk);
86
+ };
87
+ tree.toDocument().roots.forEach(walk);
88
+ return [...own, ...extra];
89
+ }
90
+
91
+ /** The source nodes of the read-only tabs (styles, tokens, animations). */
92
+ function readSources(options, tree) {
93
+ const theme = options.theme ?? themeOf(tree);
94
+ return {
95
+ rules:
96
+ typeof options.styles === 'string'
97
+ ? readStyles(options.styles).rules
98
+ : (options.styles ?? []),
99
+ tokens: readTokenMap(options.tokens, theme),
100
+ animations: () => animationNodes(tree, options.animations),
101
+ };
102
+ }
103
+
104
+ /** The token value of the configuration: a `(token path …)` of a theme. */
105
+ function tokenOverride(config, tree) {
106
+ const themes = [];
107
+ const walk = (id) => {
108
+ if (tree.get(id)?.kind === 'theme') {
109
+ themes.push(id);
110
+ }
111
+ tree.children(id).forEach(walk);
112
+ };
113
+ tree.roots().forEach(walk);
114
+ return (path) => {
115
+ for (const id of themes) {
116
+ const found = config.resolve(id, 'token', path);
117
+ if (found?.value !== undefined) {
118
+ return found;
119
+ }
120
+ }
121
+ return undefined;
122
+ };
123
+ }
124
+
125
+ /** The views of the selection: the property grid and the read-only tabs. */
126
+ function renderDetails(ctx, id) {
127
+ const { tree, inspector, t, sources } = ctx;
128
+ const rows = ctx.renderGrid(id);
129
+ const styles = matchingStyles(
130
+ tree.get(id),
131
+ ancestorsOf(id, tree),
132
+ sources.rules
133
+ );
134
+ const animations = animationsOf(id, sources.animations());
135
+ const tokens = tokensUsed(
136
+ { rows, styles, animations },
137
+ sources.tokens,
138
+ sources.overrideOf
139
+ );
140
+ renderStyles(inspector.panel('styles'), { id, styles }, { t });
141
+ renderTokens(inspector.panel('tokens'), { id, tokens }, { t });
142
+ renderAnimations(inspector.panel('animations'), { id, animations }, { t });
143
+ const node = tree.toDocument().byId.get(id);
144
+ const source = node ? sourceOf(node) : '';
145
+ renderSource(inspector.panel('source'), { id, source }, { t });
146
+ }
147
+
148
+ const DETAIL_VIEWS = ['properties', 'styles', 'tokens', 'animations', 'source'];
149
+
150
+ /** The property grid, rebuilt only when its rows change. */
151
+ function gridRenderer(ctx) {
152
+ let grid = null;
153
+ let gridKey = '';
154
+ const { config, policy, inspector, t } = ctx;
155
+ const edit = (row, value) => {
156
+ try {
157
+ ctx.applyRow(ctx.state.selected, row, value);
158
+ return null;
159
+ } catch (error) {
160
+ if (error instanceof DevModeError) {
161
+ inspector.announce(t('status.error', { message: error.message }));
162
+ return error.message;
163
+ }
164
+ throw error;
165
+ }
166
+ };
167
+ const reset = (row) => {
168
+ const { name, key, label } = row;
169
+ const layer = resetProperty(
170
+ config,
171
+ { id: ctx.state.selected, name, key },
172
+ { policy, parentOf: ctx.parentOf }
173
+ );
174
+ inspector.announce(
175
+ layer
176
+ ? t('status.reset', { name: label, layer })
177
+ : t('status.nothing', { name: label })
178
+ );
179
+ };
180
+ return {
181
+ clear() {
182
+ grid = null;
183
+ gridKey = '';
184
+ },
185
+ render(id) {
186
+ const rows = ctx.rowsOf(id);
187
+ const key = `${id} ${rows.map((r) => `${r.name}/${r.key ?? ''}`).join(' ')}`;
188
+ if (grid && gridKey === key) {
189
+ grid.update(rows);
190
+ return rows;
191
+ }
192
+ gridKey = key;
193
+ grid = renderProperties(
194
+ inspector.panel('properties'),
195
+ {
196
+ id,
197
+ rows,
198
+ locked: isLocked(policy, id, ctx.parentOf),
199
+ writable: policy.writeLayers.length > 0,
200
+ tokenPaths: [...ctx.sources.tokens.keys()],
201
+ },
202
+ { t, onEdit: edit, onReset: reset }
203
+ );
204
+ return rows;
205
+ },
206
+ };
207
+ }
208
+
209
+ /** The outline, the selection and the refresh after a change. */
210
+ function selectionController(ctx) {
211
+ const { tree, inspector, overlay, t, state } = ctx;
212
+ let outlineKey = '';
213
+ let outline = null;
214
+ const grid = gridRenderer(ctx);
215
+ ctx.renderGrid = grid.render;
216
+ const renderViews = () => {
217
+ const id = state.selected;
218
+ if (id === null) {
219
+ grid.clear();
220
+ DETAIL_VIEWS.forEach((view) => renderEmpty(inspector.panel(view), { t }));
221
+ } else {
222
+ renderDetails(ctx, id);
223
+ }
224
+ };
225
+ const renderTree = () => {
226
+ const next = buildOutline(tree);
227
+ const key = JSON.stringify(next);
228
+ if (key !== outlineKey) {
229
+ outlineKey = key;
230
+ outline = renderOutline(inspector.panel('outline'), next, {
231
+ t,
232
+ onSelect: (id) => select(id),
233
+ });
234
+ }
235
+ outline.select(state.selected);
236
+ };
237
+ const showSelection = () => {
238
+ const id = state.selected;
239
+ overlay.show('selected', ctx.target(id));
240
+ inspector.setSelection(
241
+ id === null
242
+ ? t('selection.none')
243
+ : t('selection.current', { id, type: ctx.typeOf(id) })
244
+ );
245
+ };
246
+ function select(id) {
247
+ state.selected =
248
+ id !== null && id !== undefined && tree.get(id) ? id : null;
249
+ outline.select(state.selected);
250
+ showSelection();
251
+ renderViews();
252
+ return state.selected;
253
+ }
254
+ const refresh = () => {
255
+ renderTree();
256
+ if (state.selected !== null && !tree.get(state.selected)) {
257
+ select(null);
258
+ return;
259
+ }
260
+ if (state.selected !== null) {
261
+ renderDetails(ctx, state.selected);
262
+ }
263
+ showSelection();
264
+ overlay.update();
265
+ };
266
+ return { renderTree, select, refresh };
267
+ }
268
+
269
+ /**
270
+ * Pick mode: hovering the page highlights the element under the pointer,
271
+ * a click selects it; the pointer events of a pick never reach the app.
272
+ */
273
+ function installPicking(ctx, listen, select) {
274
+ const { window, inspector, overlay, state } = ctx;
275
+ const own = (event) =>
276
+ inspector.contains(event) ||
277
+ (event.composedPath?.() ?? []).includes(overlay.host);
278
+ const pickedId = (event) => {
279
+ for (const node of event.composedPath?.() ?? [event.target]) {
280
+ if (node?.nodeType) {
281
+ const id = ctx.adapter.idFor(node);
282
+ if (id !== null) {
283
+ return id;
284
+ }
285
+ }
286
+ }
287
+ return null;
288
+ };
289
+ listen(
290
+ window,
291
+ 'pointermove',
292
+ (event) => {
293
+ if (state.picking && !own(event)) {
294
+ const id = pickedId(event);
295
+ overlay.show('hover', ctx.target(id));
296
+ }
297
+ },
298
+ true
299
+ );
300
+ for (const type of PICK_EVENTS) {
301
+ listen(
302
+ window,
303
+ type,
304
+ (event) => {
305
+ const id = state.picking && !own(event) ? pickedId(event) : null;
306
+ const node = id === null ? null : ctx.adapter.nodeFor(id);
307
+ if (node === null) {
308
+ return;
309
+ }
310
+ event.preventDefault();
311
+ event.stopImmediatePropagation();
312
+ if (type === 'click') {
313
+ select(id);
314
+ }
315
+ },
316
+ true
317
+ );
318
+ }
319
+ }
320
+
321
+ /** The shared state and helpers of an open dev mode. */
322
+ async function createContext(options) {
323
+ const { window, config } = options;
324
+ const adapter = options.adapter ?? createUiDomAdapter(options);
325
+ const tree = adapter.tree();
326
+ const parentOf = (id) => tree.parentOf(id);
327
+ const typeOf = (id) => tree.get(id)?.kind ?? '';
328
+ const rowsOf = (id) => adapter.rows(id);
329
+ return {
330
+ ...options,
331
+ adapter,
332
+ layout: options.layout ?? (await loadLayout()),
333
+ tree,
334
+ parentOf,
335
+ typeOf,
336
+ rowsOf,
337
+ sources: {
338
+ ...readSources(options, tree),
339
+ overrideOf: tokenOverride(config, tree),
340
+ },
341
+ state: { selected: null, picking: false, closed: false },
342
+ target(id) {
343
+ const node = id === null ? null : adapter.nodeFor(id);
344
+ return node ? { node, id, type: typeOf(id) } : null;
345
+ },
346
+ /** Write a property of the grid (a row, or a name) to the session. */
347
+ applyRow(id, row, value) {
348
+ return adapter.applyProperty(id, row, value);
349
+ },
350
+ nameRow: (id, name) =>
351
+ rowsOf(id).find((r) => r.label === name || r.name === name) ?? {
352
+ name,
353
+ key: null,
354
+ },
355
+ restoreFocus: window.document.activeElement,
356
+ };
357
+ }
358
+
359
+ /** The toolbar commands. */
360
+ function commandsOf(ctx, close) {
361
+ const { config, policy, inspector, t } = ctx;
362
+ return {
363
+ comments() {
364
+ if (ctx.comments) {
365
+ return;
366
+ }
367
+ ctx.setPicking(false);
368
+ inspector.host.style.visibility = 'hidden';
369
+ ctx.comments = mountComments({
370
+ root: ctx.root,
371
+ tree: ctx.tree,
372
+ nodeFor: (id) => ctx.adapter.nodeFor(id),
373
+ observe: (refresh) => ctx.adapter.observe(refresh),
374
+ container: ctx.container,
375
+ ...ctx.commentOptions,
376
+ onClose() {
377
+ ctx.comments = null;
378
+ inspector.host.style.visibility = '';
379
+ if (!ctx.state.closed) {
380
+ ctx.setPicking(true);
381
+ }
382
+ },
383
+ });
384
+ if (ctx.state.selected) {
385
+ ctx.comments.select([ctx.state.selected]);
386
+ }
387
+ },
388
+ defaults() {
389
+ ctx.setPicking(false);
390
+ ctx.defaultsDialog?.close();
391
+ ctx.defaultsDialog = openDefaultsDialog({
392
+ window: ctx.window,
393
+ config,
394
+ policy,
395
+ t,
396
+ });
397
+ },
398
+ pick: () => ctx.setPicking(!ctx.state.picking),
399
+ save() {
400
+ const count = saveSession(config, { policy });
401
+ inspector.announce(t('status.saved', { count }));
402
+ },
403
+ discard() {
404
+ const count = discardSession(config);
405
+ inspector.announce(t('status.discarded', { count }));
406
+ },
407
+ close,
408
+ };
409
+ }
410
+
411
+ /**
412
+ * Open dev mode over a rendered page.
413
+ * @param {{ window: Window & typeof globalThis, root: Element,
414
+ * config: object, policy: import('./policy.js').DevModePolicy,
415
+ * store?: object, handle?: { nodeFor?: (id: string) => Element|null },
416
+ * styles?: string|object[], tokens?: string|Map<string, object>,
417
+ * theme?: string, animations?: string|object[], vocabulary?: object,
418
+ * layout?: string, t: (key: string, params?: object) => string,
419
+ * adapter?: import('./adapter.js').PageAdapter, container?: Node,
420
+ * onInspector?: (inspector: object) => void,
421
+ * onClose?: () => void }} options
422
+ * @returns {Promise<DevModeSession>}
423
+ *
424
+ * @typedef {object} DevModeSession
425
+ * @property {(id: string|null) => string|null} select
426
+ * @property {() => { id: string, type: string }|null} getSelection
427
+ * @property {(id: string, name: string, value: unknown) => object} setProperty
428
+ * @property {(picking: boolean) => void} setPicking
429
+ * @property {() => boolean} isPicking
430
+ * @property {() => void} close
431
+ */
432
+ export async function openSession(options) {
433
+ const ctx = await createContext(options);
434
+ const { window, policy, t, state } = ctx;
435
+ const cleanups = [];
436
+ const listen = (target, type, listener, capture = false) => {
437
+ target.addEventListener(type, listener, capture);
438
+ cleanups.push(() => target.removeEventListener(type, listener, capture));
439
+ };
440
+ let commands = {};
441
+ ctx.overlay = createOverlay({
442
+ document: window.document,
443
+ container: options.container,
444
+ label: (id, type) => t('overlay.label', { id, type }),
445
+ });
446
+ ctx.inspector = createInspector({
447
+ window,
448
+ container: options.container,
449
+ layout: ctx.layout,
450
+ t,
451
+ onCommand: (command) => commands[command]?.(),
452
+ });
453
+ const { inspector, overlay } = ctx;
454
+ options.onInspector?.(inspector);
455
+ const view = selectionController(ctx);
456
+ ctx.setPicking = (picking) => {
457
+ state.picking = Boolean(picking);
458
+ inspector.setPressed('pick', state.picking);
459
+ if (!state.picking) {
460
+ overlay.show('hover', null);
461
+ }
462
+ inspector.announce(state.picking ? t('selection.picking') : '');
463
+ };
464
+
465
+ // Changes of the store or the configuration, scrolling and resizing are
466
+ // coalesced to one update per frame.
467
+ let frame = null;
468
+ const raf =
469
+ window.requestAnimationFrame?.bind(window) ??
470
+ ((callback) => window.setTimeout(callback, 16));
471
+ const schedule = () => {
472
+ frame ??= raf(() => {
473
+ frame = null;
474
+ if (!state.closed) {
475
+ view.refresh();
476
+ }
477
+ });
478
+ };
479
+ const reposition = () => overlay.update();
480
+
481
+ const close = () => {
482
+ if (state.closed) {
483
+ return;
484
+ }
485
+ state.closed = true;
486
+ ctx.defaultsDialog?.close();
487
+ ctx.comments?.destroy();
488
+ cleanups.splice(0).forEach((cleanup) => cleanup());
489
+ inspector.destroy();
490
+ overlay.destroy();
491
+ if (ctx.restoreFocus?.isConnected) {
492
+ ctx.restoreFocus.focus?.();
493
+ }
494
+ options.onClose?.();
495
+ };
496
+ commands = commandsOf(ctx, close);
497
+ if (!policy.writeLayers.includes('user')) {
498
+ inspector.setDisabled('save', true);
499
+ }
500
+ if (!policy.writeLayers.includes('session')) {
501
+ inspector.setDisabled('discard', true);
502
+ }
503
+
504
+ installPicking(ctx, listen, view.select);
505
+ listen(
506
+ window,
507
+ 'keydown',
508
+ (event) => {
509
+ if (
510
+ event.key === 'Escape' &&
511
+ !event.defaultPrevented &&
512
+ !ctx.defaultsDialog?.host.isConnected &&
513
+ !ctx.comments
514
+ ) {
515
+ event.preventDefault();
516
+ if (state.picking) {
517
+ ctx.setPicking(false);
518
+ } else {
519
+ close();
520
+ }
521
+ }
522
+ },
523
+ true
524
+ );
525
+ listen(window, 'scroll', reposition, true);
526
+ listen(window, 'resize', reposition);
527
+ cleanups.push(ctx.adapter.observe(schedule));
528
+ if (options.store?.subscribe) {
529
+ cleanups.push(options.store.subscribe(schedule));
530
+ }
531
+ if (window.ResizeObserver) {
532
+ const observer = new window.ResizeObserver(reposition);
533
+ observer.observe(ctx.root);
534
+ cleanups.push(() => observer.disconnect());
535
+ }
536
+ cleanups.push(() => frame !== null && window.cancelAnimationFrame?.(frame));
537
+
538
+ view.renderTree();
539
+ inspector.showView('outline');
540
+ view.select(null);
541
+ ctx.setPicking(true);
542
+
543
+ return {
544
+ select: (id) => view.select(id ?? null),
545
+ getSelection: () =>
546
+ state.selected === null
547
+ ? null
548
+ : { id: state.selected, type: ctx.typeOf(state.selected) },
549
+ setProperty: (id, name, value) =>
550
+ ctx.applyRow(id, ctx.nameRow(id, name), value),
551
+ setPicking: ctx.setPicking,
552
+ isPicking: () => state.picking,
553
+ close,
554
+ };
555
+ }
package/src/share.js ADDED
@@ -0,0 +1,23 @@
1
+ export const SHARE_PREFIX = '#ui-overrides=';
2
+ export const URL_BUDGET = 8192;
3
+
4
+ export const encodeShareHash = (text) =>
5
+ SHARE_PREFIX + encodeURIComponent(text);
6
+
7
+ /** Malformed percent escapes are untrusted input, never an exception. */
8
+ export function decodeShareHash(hash) {
9
+ if (typeof hash !== 'string' || !hash.startsWith(SHARE_PREFIX)) {
10
+ return null;
11
+ }
12
+ try {
13
+ return decodeURIComponent(hash.slice(SHARE_PREFIX.length));
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+
19
+ export function shareUrl(location, text) {
20
+ const url =
21
+ String(location.href ?? location).split('#')[0] + encodeShareHash(text);
22
+ return { url, tooLong: url.length > URL_BUDGET };
23
+ }