@popcorn245/cornfield 0.46.1 → 0.47.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 (56) hide show
  1. package/explorer/capped.js +3 -2
  2. package/explorer/engine/feedback.js +49 -0
  3. package/explorer/engine/flow-ui.js +39 -0
  4. package/explorer/engine/fly.js +54 -0
  5. package/explorer/engine/hint.js +98 -0
  6. package/explorer/engine/keyboard.js +156 -0
  7. package/explorer/engine/layers.js +280 -0
  8. package/explorer/engine/layout.js +378 -0
  9. package/explorer/engine/map-style.js +552 -0
  10. package/explorer/engine/piece.js +142 -0
  11. package/explorer/engine/render.js +331 -0
  12. package/explorer/engine/search-status.js +59 -0
  13. package/explorer/engine/selection.js +42 -0
  14. package/explorer/engine/sheets.js +417 -0
  15. package/explorer/engine/strings.js +63 -0
  16. package/explorer/feedback.js +11 -45
  17. package/explorer/flow-build.js +88 -0
  18. package/explorer/flow-style.js +28 -0
  19. package/explorer/flows.js +11 -132
  20. package/explorer/fly.js +11 -43
  21. package/explorer/hint.js +15 -88
  22. package/explorer/index.html +40 -82
  23. package/explorer/input.js +197 -177
  24. package/explorer/instance-state.js +172 -0
  25. package/explorer/instance.js +267 -0
  26. package/explorer/keyboard.js +14 -206
  27. package/explorer/labels.js +3 -3
  28. package/explorer/layers.js +34 -445
  29. package/explorer/layout.js +14 -372
  30. package/explorer/main.js +4 -226
  31. package/explorer/map-style.js +27 -525
  32. package/explorer/mockups-model.js +3 -3
  33. package/explorer/page-pieces.js +66 -0
  34. package/explorer/page.js +223 -0
  35. package/explorer/panels.js +29 -409
  36. package/explorer/pieces/adopt-tokens.js +38 -0
  37. package/explorer/pieces/layers.js +325 -0
  38. package/explorer/pieces/map-stage.css +14 -0
  39. package/explorer/pieces/map.js +332 -0
  40. package/explorer/pieces/node-panel.js +536 -0
  41. package/explorer/pieces/search.js +454 -0
  42. package/explorer/proposal-model.js +1 -1
  43. package/explorer/proposal.js +1 -0
  44. package/explorer/render.js +37 -267
  45. package/explorer/renderer-canvas2d.js +4 -4
  46. package/explorer/renderer-webgl.js +21 -8
  47. package/explorer/renderer.js +12 -9
  48. package/explorer/scene.js +3 -2
  49. package/explorer/search-status.js +8 -47
  50. package/explorer/search.js +26 -324
  51. package/explorer/selection-view.js +17 -19
  52. package/explorer/sheets.js +31 -379
  53. package/explorer/state.js +38 -173
  54. package/explorer/strings.js +17 -60
  55. package/explorer/view.js +4 -5
  56. package/package.json +1 -1
@@ -1,425 +1,45 @@
1
1
  /**
2
2
  * @module explorer/panels
3
3
  *
4
- * The side panel that opens when a node is selected: what the node is, and what the map knows about its data: the flows it is on, the
5
- * tables a page reads and writes, the services behind an endpoint, the stack an app runs on, and for a
6
- * cloud node (spec 0031) its plan, what breaks if it is down and who uses it, by when (cloud-model.js).
4
+ * A bridge (spec 0011 D2 and D3, step 4): the node panel is now a piece (pieces/node-panel.js) and choosing a node is the instance's
5
+ * (engine/selection.js). This file keeps the old names for the modules that are not yet on an instance (forge-panel.js, house.js, proposal.js,
6
+ * review-column.js, page.js), bound to the page's instance, and answers for the unconverted neighbours the piece asks (the live layer's
7
+ * block, the Start dialog, the end of a playing scenario). It goes when the last of those callers is converted.
7
8
  */
8
9
 
9
- import { state, nodeById, nameOf, escHtml, touchScene, viewEdges } from './state.js';
10
- import { render, onPaint } from './render.js';
11
- import { flowSummary } from './flows.js';
10
+ import { pageInstance } from './state.js';
12
11
  import { clearScenario } from './scenario-ui.js';
13
- import { kindOfMark, fieldRows, MARK_WORDS } from './proposal-model.js';
14
- import { nodeMockupsHtml } from './mockups-model.js';
15
- import { collapseSheet, isPhone, measureCovered, onCoveredChange, showSheet } from './sheets.js';
16
- import { panIntoView } from './camera.js';
17
12
  import { liveSection, hydrateLivePhotos } from './live.js';
18
- import { cloudPanelHtml } from './cloud-model.js';
19
- import { t } from './strings.js';
20
- import { markStateAttr, markState } from './corn-state.js';
21
- import { fileUrl } from './file-url.js';
22
- import { capped, toggleCapped } from './capped.js';
23
- import { dismissHint } from './hint.js';
24
13
  import { canStartAgent, openProposalStart } from './forge-panel.js';
25
- import { sayResult, clearResult, showResultIn, RESULT_MS } from './feedback.js';
26
- import { activeSubgraph, connectedLine, farEnds, kindPanelWord, linesByKind } from './selection-model.js';
27
- import { frameSelection, reach } from './selection-view.js';
28
- import { announce } from './keyboard.js';
14
+ import { selectNode as select, clearSelection } from './engine/selection.js';
15
+ import { diffPillWords as pill, LINES_CAP as CAP, copySpec as copy } from './pieces/node-panel.js';
16
+ import { pagePiece } from './page-pieces.js';
29
17
 
30
- const $ = (id) => document.getElementById(id);
18
+ export const LINES_CAP = CAP;
31
19
 
32
- // ---------------------------------------------------------------------------
33
- // Small HTML pieces shared by the sections below
34
- // ---------------------------------------------------------------------------
35
- const code = (s) => `<code class="hx-code">${escHtml(s)}</code>`;
36
- const nm = (id) => `<span class="hx-name">${escHtml(nameOf(id))}</span>`;
37
- const line = (body) => `<div class="hx-line">${body}</div>`;
38
- /** The words a fact goes by in the panel: short nouns, whatever the longer sentence it was built from */
39
- const FACT_KEYS = {
40
- 'Uses design tokens': 'Tokens', 'Loaded by the server per request': 'Loaded by', 'Domains served (Caddyfile → service)': 'Domains', 'Compose file': 'File',
41
- 'Baked pages': 'Baked', 'Reads tables': 'Reads', 'Writes tables': 'Writes', 'Self-hosted': 'Role', 'Pushes to (webhook)': 'Pushes to',
42
- 'Calls outside': 'Calls', 'Client modules': 'Modules', 'Data flows': 'Flows',
43
- };
44
- const FACT_COUNTED = /^(?:Defines )?\d+ (?:CSS )?(variable|service)\(s\)$/;
45
- const factKey = (title) => {
46
- const plain = title.replace(/:$/, '');
47
- const counted = FACT_COUNTED.exec(plain);
48
- if (counted) return counted[1] === 'service' ? 'Services' : plain.startsWith('Defines') ? 'Defines' : 'Variables';
49
- return FACT_KEYS[plain] || plain;
50
- };
51
- /** One fact: its name, and what it says. A fact with nothing in it is not shown. */
52
- const section = (title, rows) => (rows.length ? `<div class="hx-fact" data-corn="section"><div class="hx-fact-k">${escHtml(factKey(title))}</div><div class="hx-fact-v">${capped(rows)}</div></div>` : '');
53
- const varList = (vars) => `<div class="hx-chips">${capped(vars.map((v) => `<code class="hx-var">${escHtml(v)}</code>`))}</div>`;
54
- const edgesOf = (kind, side, id) => state.edges.filter((e) => e.kind === kind && e[side] === id);
20
+ // What the node panel asks of neighbours that are not on an instance yet, answered for the page's instance
21
+ const page = pageInstance();
22
+ page.on('scenario:clear', () => { clearScenario(); });
23
+ page.on('live:section', (node) => liveSection(node));
24
+ page.on('live:hydrate', (el) => { hydrateLivePhotos(el); });
25
+ page.on('forge:can-start', () => canStartAgent());
26
+ page.on('forge:start', ({ slug, returnTo }) => { openProposalStart(slug, returnTo); });
55
27
 
56
- /** Table <-> page data: which keys a page's render reads, which forms write, what ROM re-bakes */
57
- function dataSummary(node) {
58
- const reads = state.edges.filter((e) => e.kind === 'reads');
59
- const writes = state.edges.filter((e) => e.kind === 'writes');
60
- const usesOut = state.edges.filter((e) => e.kind === 'uses' && e.from === node.id);
61
- const extendsOut = state.edges.filter((e) => e.kind === 'extends' && e.from === node.id);
62
- const common = section('Extends:', extendsOut.map((e) => line(nm(e.to))))
63
- + section('Uses design tokens:', usesOut.map((e) => line(`${nm(e.to)} · ${e.vars.length}${varList(e.vars)}`)))
64
- + (node.type !== 'token' && node.vars ? section(`Defines ${node.vars.length} CSS variable(s):`, [varList(node.vars)]) : '');
65
-
66
- if (node.type === 'app') {
67
- const served = node.deployed
68
- ? line(`${/^https?:\/\//.test(node.url) ? `<a data-corn="text-link" class="hx-link" href="${escHtml(node.url)}" target="_blank" rel="noreferrer">${escHtml(node.url)}</a>` : code(node.url)} → ${(node.upstreams || []).map(code).join(' ')}${node.stack ? ` <span class="hx-faint">[${escHtml(node.stack)}]</span>` : ''}`)
69
- : line('Not deployed by any stack in this repo');
70
- const runsOn = state.edges.filter((e) => e.kind === 'runs-on' && e.from === node.id)
71
- .map((e) => line(`${nm(e.to)}${(e.mappings || []).map((m) => `<div class="hx-faint">${code(m.host)} → ${code(m.upstream)}${m.service ? ` = ${code(m.service)}` : ''}</div>`).join('')}`));
72
- return section('Served:', [served])
73
- + section('Runs on:', runsOn)
74
- + section('Loaded by the server per request:', reads.filter((e) => e.to === node.id).map((e) => line(nm(e.from))))
75
- + common;
76
- }
77
- if (node.type === 'token') {
78
- const users = state.edges.filter((e) => e.kind === 'uses' && e.to === node.id);
79
- return section(`${node.vars.length} variable(s):`, [varList(node.vars)])
80
- + section('Used by:', users.map((e) => line(`${nm(e.from)} · ${escHtml(e.vars.join(' '))}`)));
81
- }
82
- if (['atom', 'molecule', 'core'].includes(node.type)) {
83
- const pages = state.edges.filter((e) => e.dashed && e.to === node.id).map((e) => line(nm(e.from)));
84
- return (node.table ? section('Record of:', [line(`${escHtml(node.model)} · table ${code(node.table)}`)]) : '')
85
- + section('Rendered by:', pages) + common;
86
- }
87
- if (node.type === 'stack') {
88
- const served = state.edges.filter((e) => e.kind === 'runs-on' && e.to === node.id);
89
- return section('Domains served (Caddyfile → service):', served.flatMap((e) => (e.mappings || []).map((m) => line(`<span class="hx-name">${escHtml(m.host)}</span> → ${code(m.upstream)}${m.service ? ` = ${code(m.service)}` : ''}`))))
90
- + section(`${(node.services || []).length} service(s):`, (node.services || []).map((s) => line(`<span class="hx-name">${escHtml(s.name)}</span>${s.image ? ` <span class="hx-faint">${escHtml(s.image)}</span>` : ''}${s.ports.length ? `<div>${s.ports.map(code).join(' ')}</div>` : ''}${s.volumes.length ? `<div class="hx-faint">${s.volumes.map(escHtml).join('<br>')}</div>` : ''}`)))
91
- + section('Compose file:', [line(code(node.file))]);
92
- }
93
- if (node.type === 'table') {
94
- const readers = reads.filter((e) => e.from === node.id);
95
- const writers = writes.filter((e) => e.to === node.id);
96
- const baked = readers.filter((e) => (nodeById(e.to) || {}).render?.rom === 'bake');
97
- return (node.model ? section('Model:', [line(escHtml(node.model))]) : '')
98
- + section('Read by:', readers.map((e) => line(`${nm(e.to)} · ${e.keys.map(code).join(' ')}`)))
99
- + section('Written by:', writers.map((e) => line(`${nm(e.from)} · ${escHtml(e.label)}`)))
100
- + (baked.length ? section('Baked pages:', [line(`a write here re-bakes <span class="hx-rom hx-bold">${baked.length}</span> file(s): ${baked.map((e) => escHtml(nameOf(e.to))).join(', ')}`)]) : '');
101
- }
102
- if (node.type === 'service') {
103
- const row = (e, side) => `${nm(e[side])}${e.label && e.label !== 'imports' ? ` · ${escHtml(e.label)}` : ''}`;
104
- // The summary is the first sentence of the description above: shown again only when the description does not hold it
105
- const again = node.summary && !String(node.desc || '').includes(node.summary);
106
- // The kind is in the badge ("Service · timer", typeWords): it has no row of its own
107
- return (again ? section('Summary:', [line(`<span class="hx-faint">${escHtml(node.summary)}</span>`)]) : '')
108
- + section('Started by:', [...(node.triggers || []).map((t) => line(escHtml(t))), ...edgesOf('triggers', 'to', node.id).map((e) => line(row(e, 'from')))])
109
- + section('Jobs:', (node.jobs || []).map((j) => line(`${code(j.name)} · cron ${code(j.cron)}`)))
110
- + section('Runs:', edgesOf('triggers', 'from', node.id).map((e) => line(row(e, 'to'))))
111
- + section('Calls:', edgesOf('calls', 'from', node.id).map((e) => line(row(e, 'to'))))
112
- + section('Called by:', edgesOf('calls', 'to', node.id).map((e) => line(row(e, 'from'))))
113
- + section('Reads tables:', reads.filter((e) => e.to === node.id).map((e) => line(nm(e.from))))
114
- + section('Writes tables:', writes.filter((e) => e.from === node.id).map((e) => line(nm(e.to))))
115
- + section('Mechanisms:', (node.mechanisms || []).map((m) => line(escHtml(m))));
116
- }
117
- if (node.type === 'container' && node.selfHosted) {
118
- // A self-hosted service is the container that runs it (spec 0031 section 3): what the API uses it for, who calls it, its webhook
119
- const row = (e, side) => `${nm(e[side])}${e.label && e.label !== 'calls' ? ` · ${escHtml(e.label)}` : ''}`;
120
- const into = state.edges.filter((e) => e.to === node.id && (e.kind === 'calls' || (e.kind === 'flow' && e.flow === 'api')));
121
- const calledBy = (type) => into.filter((e) => nodeById(e.from)?.type === type).map((e) => line(row(e, 'from')));
122
- const stackmates = new Set(state.nodes.filter((n) => n.type === 'container' && n.stack === node.stack).map((n) => n.id));
123
- return section('Self-hosted:', [line(escHtml(node.summary || ''))])
124
- + section('Called by services:', calledBy('service'))
125
- + section('Called by endpoints:', calledBy('page'))
126
- + section('Called by apps:', calledBy('app'))
127
- + section('Pushes to (webhook):', state.edges.filter((e) => e.kind === 'delivers' && stackmates.has(e.from) && nodeById(e.to)?.type === 'page').map((e) => line(`${nm(e.to)}${e.from === node.id ? '' : ` <span class="hx-faint">from ${escHtml(nameOf(e.from))}</span>`}`)));
128
- }
129
- if (node.type === 'external' && node.kind) { // a cloud node or the public web (spec 0031 section 6)
130
- return cloudPanelHtml(node, state.nodes, state.edges); // its File line is the registry
131
- }
132
- if (node.type === 'external') {
133
- const calledBy = (type) => edgesOf('calls', 'to', node.id).filter((e) => nodeById(e.from)?.type === type);
134
- return section('System:', [line(`${escHtml(node.summary || '')}${node.host ? `<div class="hx-faint">Runs here as ${code(node.host)}</div>` : '<div class="hx-faint">Not run by this stack</div>'}`)])
135
- + section('Client modules:', (node.modules || []).map((m) => line(code(m))))
136
- + section('Called by services:', calledBy('service').map((e) => line(nm(e.from))))
137
- + section('Called by endpoints:', calledBy('page').map((e) => line(nm(e.from))))
138
- + section('Pushes to (webhook):', edgesOf('delivers', 'from', node.id).map((e) => line(nm(e.to))));
139
- }
140
- if (node.type === 'page') {
141
- const r = node.render;
142
- const components = state.edges.filter((e) => e.dashed && e.from === node.id).map((e) => line(nm(e.to)));
143
- return (node.methods ? section('Methods:', [line(node.methods.map(code).join(' '))]) : '')
144
- + (node.render_fn ? section('Rendered by:', [line(`${code(node.render_fn)} · ${escHtml(node.file)}`)]) : '')
145
- + section('Calls outside:', edgesOf('calls', 'from', node.id).map((e) => line(nm(e.to))))
146
- + section('Pushed to by:', edgesOf('delivers', 'to', node.id).map((e) => line(`${nm(e.from)} · ${escHtml(e.label)}`)))
147
- + section('Starts:', edgesOf('triggers', 'from', node.id).map((e) => line(`${nm(e.to)} · ${escHtml(e.label)}`)))
148
- + section('Renders:', components)
149
- + section('Reads:', reads.filter((e) => e.to === node.id).map((e) => line(`${nm(e.from)} · ${e.keys.map(code).join(' ')}`)))
150
- + section('Writes:', writes.filter((e) => e.from === node.id).map((e) => line(`${nm(e.to)} · ${escHtml(e.label)}`)))
151
- + (r ? section('Render:', [line(`today: ${code(r.now)} · ROM: ${r.rom === 'bake' ? '<span class="hx-rom hx-bold">bake</span>' : '<span class="hx-faint">skip (per request)</span>'}${r.note ? `<div class="hx-faint">${escHtml(r.note)}</div>` : ''}`)]) : '');
152
- }
153
- return '';
154
- }
155
-
156
- // ---------------------------------------------------------------------------
157
- // Threads that mention the node
158
- // ---------------------------------------------------------------------------
159
-
160
- /** "Threads": the threads whose text names the node (an idea, or a spec PR's conversation); each opens in the Work panel */
161
- function threadsSection(node) {
162
- const index = state.threadIndex;
163
- if (!index) return '';
164
- const threads = index.for(node.id);
165
- // "Start a thread about this" shows whenever threads are on and a maintainer is signed in (the panel only sets `start` then)
166
- const start = index.start ? `<button data-corn-kind="quiet" type="button" class="hx-btn hx-btn--quiet hx-textact" data-thread-start="${escHtml(node.id)}" aria-label="Start a thread about this: opens the New idea form for ${escHtml(index.forge())}, with this node mentioned">Start a thread about this</button>` : '';
167
- if (!threads || !threads.length) return start;
168
- const rows = threads.map((th) => {
169
- const count = Number(th.comments) || 0;
170
- return `<li><button type="button" class="hx-row hx-thread-open" data-thread-open="${escHtml(th.number)}" data-corn="row" aria-label="Open thread #${escHtml(th.number)}, ${escHtml(th.title)}, ${count} ${count === 1 ? 'comment' : 'comments'}, in the issues and pull requests panel"><span class="hx-row-title">${escHtml(th.title)}</span><span class="hx-row-meta">#${escHtml(th.number)} · ${count}</span></button></li>`;
171
- });
172
- return `<div class="hx-sec-block" data-corn="section"><h3 class="hx-sec-title">Threads</h3><ul class="hx-rows">${rows.join('')}</ul>${start}</div>`;
173
- }
174
-
175
- /** Draws "Threads" again in the open panel (the list was just read, or the map changed); nothing else in the panel moves */
176
- export function repaintThreads() {
177
- const box = $('drawer-threads');
178
- if (!box || !state.selectedNode) return;
179
- box.innerHTML = threadsSection(state.selectedNode);
180
- }
181
-
182
- // ---------------------------------------------------------------------------
183
- // The head: type · host, and what the open proposal does to the node
184
- // ---------------------------------------------------------------------------
185
-
186
- /** "Page", "Cloud", "Public web", "Service · timer": the kind of node, in words, with its finer kind (spec 0009 D5) after a dot. A kind is text, shown as text */
187
- function typeWords(node) {
188
- if (node.type === 'external' && node.kind) return node.kind === 'web' ? 'Public web' : 'Cloud';
189
- const type = node.type.charAt(0).toUpperCase() + node.type.slice(1);
190
- return typeof node.kind === 'string' && node.kind ? `${type} · ${node.kind}` : type;
191
- }
192
-
193
- /** The host a node answers on, when it has one */
194
- function hostOf(node) {
195
- if (node.url) { try { return new URL(node.url).host; } catch { /* not a URL: no host */ } }
196
- return node.host || '';
197
- }
198
-
199
- /** "Added by Checkout": the pill for a node the open proposal touches; '' for one it leaves alone */
200
- export function diffPillWords(node) {
201
- const mark = node && node.mark;
202
- if (!mark || mark === 'none') return '';
203
- if (mark === 'edit') return `${node.editOp === 'removed' ? 'Removed' : 'Added'} by your edit`;
204
- const title = state.proposal && typeof state.proposal.title === 'string' ? state.proposal.title : '';
205
- return title ? `${MARK_WORDS[mark] || mark} by ${title}` : `${MARK_WORDS[mark] || mark} by this proposal`;
206
- }
207
-
208
- /** "In this proposal": the diff for a changed node as key/value rows (id, parent, edges +2; a change shows each field before and after) */
209
- function diffSection(node) {
210
- const kind = kindOfMark(node);
211
- if (!diffPillWords(node)) return '';
212
- const row = (k, v) => `<div class="hx-diff-k">${escHtml(k)}</div><div class="hx-diff-v">${v}</div>`;
213
- const rows = [row('id', escHtml(node.id))];
214
- const parent = state.edges.find((e) => !e.kind && !e.dashed && e.to === node.id);
215
- if (parent) rows.push(row('parent', escHtml(parent.from)));
216
- const touching = state.edges.filter((e) => e.from === node.id || e.to === node.id);
217
- const added = touching.filter((e) => kindOfMark(e) === 'added').length;
218
- const removed = touching.filter((e) => kindOfMark(e) === 'removed').length;
219
- if (added || removed) rows.push(row('edges', escHtml([added ? `+${added}` : '', removed ? `−${removed}` : ''].filter(Boolean).join(' '))));
220
- if (kind === 'changed') {
221
- for (const r of fieldRows(node)) rows.push(row(r.field, `<span class="hx-change-before">${escHtml(r.before) || '<em>nothing</em>'}</span> <span aria-hidden="true">→</span><span class="hx-sr-only"> became </span> <span class="hx-change-after">${escHtml(r.after) || '<em>nothing</em>'}</span>`));
222
- }
223
- return `<div class="hx-sec-block" data-proposal-mark="${escHtml(node.mark)}" data-corn="section"><h3 class="hx-sec-title">In this proposal</h3>${node.why ? `<p class="hx-why">${escHtml(node.why)}</p>` : ''}<div class="hx-diff hx-diff--${escHtml(kind)}" data-corn="diff-block"${markStateAttr(node.mark)}>${rows.join('')}</div></div>`;
224
- }
225
-
226
- // ---------------------------------------------------------------------------
227
- // What the selection lights: the lines by kind, the switch, Frame them (spec 0008 D5 and D6)
228
- // ---------------------------------------------------------------------------
229
-
230
- /** The most rows a kind's list shows before "and N more" */
231
- export const LINES_CAP = 12;
232
-
233
- /** The lit set the panel describes: the same rule the scene lights by (selection-model.js) */
234
- const litNow = () => activeSubgraph(state.selectedNode, viewEdges(), { throughChildren: state.throughChildren, kind: state.selectedKind });
235
-
236
- /** The panel's "Calls 12 · Reads 9" chips, the chosen kind's far ends, the switch, and the line that says how much is on screen, with Frame them */
237
- function linesHtml(node) {
238
- const sub = litNow();
239
- if (!sub || !sub.kinds.size) return '';
240
- const kinds = linesByKind(sub);
241
- const chips = kinds.map(({ kind, count, word }) => `<button type="button" class="hx-lines-kind" data-corn="lines-kind" data-corn-kind="quiet" data-lines-kind="${escHtml(kind)}" data-focus-key="kind:${escHtml(kind)}" aria-pressed="${sub.kind === kind}">${escHtml(word)} <span class="hx-lines-count" data-corn="count">${count}</span></button>`).join('');
242
- const open = sub.kind ? farEnds(sub, sub.kind).map((r) => `<button type="button" class="hx-linkbtn" data-corn="node-link" data-action="select-node" data-id="${escHtml(r.id)}"><span class="hx-sr-only">${r.out ? 'to ' : 'from '}</span><span aria-hidden="true">${r.out ? '→' : '←'}</span> ${escHtml(nameOf(r.id))}</button>`) : [];
243
- const list = open.length ? `<div class="hx-lines-list">${capped(open, LINES_CAP)}</div>` : '';
244
- const hasChildren = activeSubgraph(node, viewEdges(), { throughChildren: false }).childIds.size > 0;
245
- const through = hasChildren ? `<label class="hx-lines-switch"><input type="checkbox" data-corn="lines-switch" data-lines-switch data-focus-key="switch"${state.throughChildren ? ' checked' : ''}> <span>${escHtml(t('throughChildren'))}</span></label>` : '';
246
- const { connected, off } = reach();
247
- return `<div class="hx-sec-block hx-lines" id="drawer-lines" data-corn="lines-by-kind"><h3 class="hx-sec-title">Lines</h3><div class="hx-chips" role="group" aria-label="Lit lines by kind">${chips}</div>${list}${through}<div class="hx-lines-reach"><span data-lines-reach>${escHtml(connectedLine(connected, off))}</span> <button type="button" data-corn="frame-button" data-corn-kind="secondary" class="hx-btn hx-btn--secondary" data-action="frame-selection" data-focus-key="frame">${escHtml(t('frame'))}</button></div></div>`;
248
- }
249
-
250
- /** Draws the lines block again after a switch or a kind was chosen; the focus stays on the control that was used */
251
- function paintLines() {
252
- const box = $('drawer-lines');
253
- if (!box || !state.selectedNode) return;
254
- const key = document.activeElement && box.contains(document.activeElement) ? document.activeElement.dataset.focusKey : '';
255
- const html = linesHtml(state.selectedNode);
256
- const holder = document.createElement('div');
257
- holder.innerHTML = html;
258
- const next = holder.firstElementChild;
259
- if (next) box.replaceWith(next); else box.remove();
260
- if (key) { const again = $('drawer-lines'); const el = again && [...again.querySelectorAll('[data-focus-key]')].find((x) => x.dataset.focusKey === key); if (el) el.focus(); }
261
- }
262
-
263
- /** One step through the panel's lines controls: a kind's chip lights that kind alone (the same chip again lights them all), the switch widens the set */
264
- function onLinesClick(e) {
265
- const chip = e.target.closest && e.target.closest('[data-lines-kind]');
266
- if (!chip || !state.selectedNode) return false;
267
- const kind = chip.dataset.linesKind;
268
- state.selectedKind = state.selectedKind === kind ? null : kind;
269
- touchScene();
270
- render();
271
- paintLines();
272
- const sub = litNow();
273
- announce(sub && sub.kind ? `Showing ${kindPanelWord(sub.kind).toLowerCase()} only: ${sub.edges.length} ${sub.edges.length === 1 ? 'line' : 'lines'}` : 'Showing every kind of line');
274
- return true;
275
- }
276
- function onLinesChange(e) {
277
- const box = e.target.closest && e.target.closest('[data-lines-switch]');
278
- if (!box || !state.selectedNode) return;
279
- state.throughChildren = !!box.checked;
280
- state.selectedKind = null; // the set changed under the chosen kind: it may not be in it
281
- touchScene();
282
- render();
283
- paintLines();
284
- const sub = litNow();
285
- announce(`${state.throughChildren ? 'Including' : 'Not including'} its children's lines: ${sub ? sub.connectedNodeIds.size - 1 : 0} connected`);
286
- }
287
-
288
- /** Keeps "9 connected · 3 off screen" true as the camera moves (after every draw, while a node is selected and its panel is open) */
289
- onPaint(() => {
290
- if (!state.selectedNode) return;
291
- const el = document.querySelector('[data-lines-reach]');
292
- if (!el) return;
293
- const { connected, off } = reach();
294
- const text = connectedLine(connected, off);
295
- if (el.textContent !== text) el.textContent = text;
296
- });
297
-
298
- // ---------------------------------------------------------------------------
299
- // The drawer
300
- // ---------------------------------------------------------------------------
301
- let selectToken = 0;
302
-
303
- /**
304
- * Selects a node: lights what is one edge from it on the map and fills the side panel. `frame` is for a selection that did not come
305
- * from a click on the map (a search, a list, a link, the keyboard): the camera then flies to the node and what it lights (selection-model.js);
306
- * a click leaves the camera where it is (spec 0008 D6).
307
- */
308
- export async function selectNode(node, { frame = false } = {}) {
309
- if (!node) return;
310
- const token = ++selectToken;
311
- clearScenario();
312
- dismissHint(); // a node has been picked: the hint's job is done for this session
313
- if (!state.selectedNode || state.selectedNode.id !== node.id) state.selectedKind = null; // a kind chosen for one node means nothing for the next
314
- state.selectedNode = node;
315
- state.selectedEdge = null;
316
- touchScene();
317
- render();
318
-
319
- const metaList = $('drawer-meta-list');
320
- if (!metaList.dataset.moreBound) {
321
- metaList.dataset.moreBound = '1';
322
- metaList.addEventListener('click', (e) => { if (!onLinesClick(e)) toggleCapped(e.target); });
323
- metaList.addEventListener('change', onLinesChange);
324
- }
325
- const openBtn = $('drawer-open-btn');
326
- const title = $('drawer-title');
327
-
328
- title.textContent = node.tag ? `<${node.tag}>` : node.label;
329
- title.classList.toggle('hx-mono', node.type === 'page' || !!node.tag); // a route or a tag reads as code
330
- $('drawer-badge').textContent = typeWords(node);
331
- const host = hostOf(node);
332
- $('drawer-host').textContent = host ? ` · ${host}` : '';
333
- const pill = diffPillWords(node);
334
- $('drawer-diff').textContent = pill;
335
- $('drawer-diff').hidden = !pill;
336
- const pillState = markState(pill ? node.mark : ''); // added, changed, removed or edit
337
- if (pillState) $('drawer-diff').dataset.cornState = pillState; else delete $('drawer-diff').dataset.cornState;
338
- const lead = $('drawer-description');
339
- lead.textContent = node.desc || '';
340
- lead.hidden = !node.desc;
341
- if (token !== selectToken) return;
342
-
343
- const facts = `${node.file ? section('File', [code(node.file)]) : ''}${flowSummary(node)}${dataSummary(node)}`;
344
- metaList.innerHTML = `${linesHtml(node)}${facts ? `<div class="hx-facts">${facts}</div>` : ''}
345
- <div id="drawer-live">${liveSection(node)}</div>
346
- ${nodeMockupsHtml(node.id)}
347
- <div id="drawer-threads">${threadsSection(node)}</div>
348
- ${diffSection(node)}`;
349
- if (state.threadIndex) state.threadIndex.ensure();
350
- hydrateLivePhotos($('drawer-live'));
351
-
352
- // The actions: Open file (the node's file on the forge) is the primary one; with an address too, Open route is the quiet one.
353
- // The proposal's head branch is not known here (the proposals list does not carry it): the file is at the default branch.
354
- const fileBtn = $('drawer-file-btn');
355
- const file = node.file && state.forge ? fileUrl(state.forge, node.file, state.forge.baseBranch) : null;
356
- fileBtn.hidden = !file;
357
- if (file) fileBtn.href = file; else fileBtn.removeAttribute('href');
358
- const route = !!(node.url && /^https?:\/\//.test(node.url));
359
- if (route) openBtn.href = node.url; else openBtn.removeAttribute('href');
360
- openBtn.hidden = !route;
361
- openBtn.className = file ? 'hx-btn hx-btn--quiet hx-foot-btn' : 'hx-open';
362
- if (file) openBtn.dataset.cornKind = 'quiet'; else openBtn.dataset.cornKind = 'primary'; // the route is the primary action when there is no file
363
- openBtn.textContent = `${t('openRoute')} ↗`;
364
- fileBtn.textContent = `${t('openFile')} ↗`;
365
- const run = $('drawer-run-btn');
366
- run.hidden = !(state.proposalSlug && canStartAgent());
367
-
368
- $('spec-drawer').classList.add('drawer-open');
369
- $('spec-drawer').inert = false; // closed, it waits off screen: inert, so Tab never reaches its buttons (MAP-02)
370
- $('drawer-backdrop').hidden = false;
371
- showSheet('drawer'); // on a phone it takes Work's place (the node sheet and Work take turns), and comes back from away when its node is tapped again
372
- if (frame) frameSelection(); // the panel is open now, so what it covers is known
373
- else keepSelectedInView();
374
- }
375
-
376
- /**
377
- * On a phone the node's sheet covers the bottom of the map (sheets.js): when the selected node is under it, or
378
- * gets covered as the sheet expands, pan the map (never zoom it) so the node is in the part still showing (F32)
379
- */
380
- export function keepSelectedInView() {
381
- const node = state.selectedNode;
382
- if (!node || !state.width || !isPhone()) return;
383
- const covered = measureCovered();
384
- const next = panIntoView(state.camera, node, { left: 0, top: 0, right: state.width, bottom: state.height - covered }, node.r * state.camera.zoom + 16);
385
- if (!next) return;
386
- Object.assign(state.camera, next);
387
- render();
388
- }
389
- onCoveredChange(() => keepSelectedInView());
390
-
391
- /** Start a run: the Start dialog of the Work panel, on the proposal that is open */
392
- export function startRun() {
393
- if (state.proposalSlug) openProposalStart(state.proposalSlug, '#drawer-run-btn');
28
+ /** Selects a node: lights what is one edge from it on the map and fills the side panel. `frame`: the camera follows (a search, a list, a link, the keyboard) */
29
+ export async function selectNode(node, { frame = false, source = frame ? 'link' : 'api' } = {}) {
30
+ pagePiece('node-panel'); // the panel is mounted where the page has its place
31
+ select(pageInstance(), node, { frame, source });
394
32
  }
395
33
 
396
34
  export function closeDrawer() {
397
- selectToken++;
398
- state.selectedEdge = null;
399
- clearScenario();
400
- $('spec-drawer').classList.remove('drawer-open');
401
- $('spec-drawer').inert = true;
402
- $('drawer-backdrop').hidden = true;
403
- collapseSheet('drawer'); // the next node opens as a peek on a phone
404
- state.selectedNode = null;
405
- touchScene();
406
- render();
35
+ pagePiece('node-panel');
36
+ clearSelection(pageInstance(), { source: 'api' });
407
37
  }
408
38
 
409
- let copyTimer = 0;
410
- /** Copies the selected node as JSON; the result is said under the button and to a screen reader, and stays a few seconds */
411
- export async function copySpec(button) {
412
- if (!state.selectedNode) return;
413
- const text = JSON.stringify({ node: state.selectedNode }, null, 2);
414
- clearTimeout(copyTimer);
415
- clearResult('copy-spec');
416
- const where = $('copy-spec-result');
417
- try {
418
- await navigator.clipboard.writeText(text);
419
- sayResult('copy-spec', `Copied the spec of ${state.selectedNode.label || state.selectedNode.id} to the clipboard.`, true);
420
- } catch {
421
- sayResult('copy-spec', 'The browser did not allow copying, so nothing was copied. Allow clipboard access for this page, then press Copy Spec again.', false);
422
- }
423
- showResultIn(where, 'copy-spec');
424
- copyTimer = setTimeout(() => { clearResult('copy-spec'); showResultIn(where, 'copy-spec'); }, RESULT_MS);
425
- }
39
+ /** "Added by Checkout": the pill for a node the open proposal touches; '' for one it leaves alone */
40
+ export const diffPillWords = (node) => pill(node, pageInstance().state.proposal);
41
+ export const repaintThreads = () => { const p = pagePiece('node-panel'); if (p) p.repaintThreads(); };
42
+ export const keepSelectedInView = () => { const p = pagePiece('node-panel'); if (p) p.keepSelectedInView(); };
43
+ export const startRun = () => { const p = pagePiece('node-panel'); if (p) p.startRun(); };
44
+ /** Copies the selected node as JSON (the Copy Spec button); `button` is kept for the old signature */
45
+ export const copySpec = () => copy(pageInstance(), pageInstance().el('copy-spec-result'));
@@ -0,0 +1,38 @@
1
+ /**
2
+ * @module explorer/pieces/adopt-tokens
3
+ *
4
+ * The default `--corn-*` tokens for a page that has no cornfield stylesheet of its own (spec 0011 D7). The package generates the sheet from
5
+ * explorer/tokens.css at build time, with every selector at zero specificity (`:where(...)`), so any ordinary rule of the host's overrides it; the
6
+ * first `corn-*` element to connect hands its text to this, and it is added once to the document (and once to a shadow root the element sits in).
7
+ */
8
+
9
+ /** Marks the sheet this module made, so a second copy of the package on the same page finds it and adds nothing */
10
+ const MARK = Symbol.for('cornfield.default-tokens');
11
+ const ATTR = 'data-corn-default-tokens';
12
+
13
+ /**
14
+ * Adds `css` to the root node the element is in (a document or a shadow root), once. Returns true when it added it.
15
+ * Uses `adoptedStyleSheets`; a browser without it gets a `<style>` placed first in the head (or the shadow root), which loses to every later rule the same way.
16
+ * @param {Document|ShadowRoot} rootNode `element.getRootNode()`
17
+ * @param {string} css the generated default tokens
18
+ */
19
+ export function adoptDefaultTokens(rootNode, css) {
20
+ if (!rootNode || !css) return false;
21
+ const doc = rootNode.nodeType === 9 ? rootNode : rootNode.ownerDocument;
22
+ const sheets = rootNode.adoptedStyleSheets;
23
+ if (Array.isArray(sheets) && doc && doc.defaultView && typeof doc.defaultView.CSSStyleSheet === 'function' && 'replaceSync' in doc.defaultView.CSSStyleSheet.prototype) {
24
+ if (sheets.some((s) => s && s[MARK])) return false;
25
+ const sheet = new doc.defaultView.CSSStyleSheet();
26
+ sheet.replaceSync(css);
27
+ sheet[MARK] = true;
28
+ rootNode.adoptedStyleSheets = [...sheets, sheet];
29
+ return true;
30
+ }
31
+ const holder = rootNode.nodeType === 9 ? rootNode.head : rootNode;
32
+ if (!holder || holder.querySelector(`style[${ATTR}]`)) return false;
33
+ const style = doc.createElement('style');
34
+ style.setAttribute(ATTR, '');
35
+ style.textContent = css;
36
+ holder.prepend(style);
37
+ return true;
38
+ }