cornfield 0.38.0 → 0.40.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.
@@ -14,16 +14,15 @@
14
14
  * scenario costs nothing, a hidden tab stops the loop, and under prefers-reduced-motion the steps
15
15
  * still change but the packet does not travel and the camera jumps.
16
16
  *
17
- * The scenario list: a `Scenarios · N` disclosure that appears whenever `state.proposal.scenarios`
18
- * is not empty (TOPO-09 sets `state.proposal`; this follows it through `onSceneTouch`). It sits as
19
- * a row inside the proposal bar, and at the stage's corner when there is no bar.
17
+ * The scenario list is the review column's (review-column.js): this module plays what it hands over and tells it where the
18
+ * player is (`onPlayerChange`), so the list can follow.
20
19
  *
21
20
  * On a phone (sheets.js, TOPO-18) the bar is a bottom sheet in `#sheet-dock`: a peek (title, step
22
21
  * counter and text) until expanded, and the camera follows a step into the part of the map the
23
22
  * sheets leave free.
24
23
  */
25
24
 
26
- import { state, touchScene, onSceneTouch } from './state.js';
25
+ import { state, touchScene } from './state.js';
27
26
  import { render, ensureFlowLoop, addFrameClient, isNodeVisible, getMinZoom } from './render.js';
28
27
  import { flowReduceMotion } from './flows.js';
29
28
  import { registerSheet, unregisterSheet, collapseAllSheets, visibleMapRect, onCoveredChange } from './sheets.js';
@@ -31,8 +30,13 @@ import { createPlayer, cameraFor, parseSpeed, SPEED_CHOICES, SPEED_KEY } from '.
31
30
  import { edgeKey } from '../core/proposal.js';
32
31
  import { checksVersion, closeChecks, decorateSnapshot, openChecks, paintChecks } from './check.js';
33
32
  import { blastRadius, outageLayers, outageScenario } from './outage-model.js';
34
- import { toggleLayer } from './layers.js';
33
+ import { toggleLayer, LAYER_DEFS } from './layers.js';
34
+ import { externalLayer } from './cloud-model.js';
35
+ import { projectLayerKey, shownByProposal } from './layer-model.js';
35
36
  import { announce } from './keyboard.js';
37
+ import { t } from './strings.js';
38
+ import { currentStepSentence } from './scenario-list-model.js';
39
+ import { personaFor, personaLabel } from './check-model.js';
36
40
 
37
41
  /** A frame that arrives later than this (a tab that was hidden) counts as this long */
38
42
  const MAX_FRAME_MS = 250;
@@ -43,7 +47,9 @@ let player = null;
43
47
  let bar = null;
44
48
  let signature = '';
45
49
  let glide = null; // { to: {x, y, zoom}, last: nowMs|null }
46
- let list = null;
50
+ let held = false; // the viewer took hold of the map since the step began: the camera is theirs until the next step
51
+ let framedFor = -1; // the player bar's height when the camera last followed the step
52
+ let barWatch = null; // a ResizeObserver on the bar: when it grows (a check's line arrives), the step is followed again
47
53
 
48
54
  const $stage = () => (state.canvas ? state.canvas.parentElement : null);
49
55
 
@@ -54,39 +60,40 @@ const $stage = () => (state.canvas ? state.canvas.parentElement : null);
54
60
  /**
55
61
  * Plays a scenario on the map, replacing any that is playing.
56
62
  * @param {import('./scenario.js').Scenario} scenario
57
- * @param {{ autoplay?: boolean, stepMs?: number | 'manual' }} [opts] `autoplay` false opens it paused on the first step;
58
- * `stepMs` is a speed for this scenario in place of the viewer's saved one
63
+ * @param {{ autoplay?: boolean, stepMs?: number | 'manual', step?: number, focus?: boolean }} [opts] `autoplay` false opens it paused on the first step;
64
+ * `step` opens it on that step (paused); `stepMs` is a speed for this scenario in place of the viewer's saved one;
65
+ * `focus` false leaves the keyboard focus where it is (the review column's step list keeps it)
59
66
  * @returns {ReturnType<typeof createPlayer>} the player, for a caller that wants to drive it
60
67
  */
61
68
  export function playScenario(scenario, opts = {}) {
62
69
  const opener = openerOf();
63
- const takeFocus = isKeyboardish(); // checked now: the list row that was pressed goes with the list
64
- clearScenario();
70
+ const takeFocus = isKeyboardish() && opts.focus !== false; // checked now: whatever was pressed may go with the markup
71
+ clearScenario({ keepChecks: true });
65
72
  returnTo = opener;
66
73
  const speed = opts.stepMs ?? readSpeed();
67
74
  player = createPlayer(scenario, { stepMs: speed, maxFrameMs: MAX_FRAME_MS });
75
+ if (Number.isFinite(opts.step) && opts.step > 0) player.goTo(opts.step);
68
76
  showBar(speed);
69
- openChecks(scenario, () => { sync(); render(); }); // PHY-10: one batch of permission checks for the scenario (check.js)
77
+ openChecks(scenario, () => { sync(); render(); }); // PHY-10: one batch of permission checks for the scenario (check.js); the same scenario already open in the list keeps its answers
70
78
  showOutageLayers(scenario);
71
- if (opts.autoplay !== false) player.play();
79
+ showStepLayers(scenario);
80
+ if (opts.autoplay !== false && !(opts.step > 0)) player.play();
72
81
  sync(true);
73
82
  render();
74
83
  ensureFlowLoop();
75
- // Whatever started it (a row of the list, which goes) is gone: focus goes to the player's play and pause button, the first control of what opened
76
- if (opts.focus !== false && bar && takeFocus) {
84
+ // Whatever started it may be gone: focus goes to the player's play and pause button, the first control of what opened
85
+ if (takeFocus && bar) {
77
86
  const toggle = bar.querySelector('[data-action=scenario-toggle]');
78
87
  if (toggle && !toggle.disabled) toggle.focus(); else bar.querySelector('[data-action=scenario-next]')?.focus();
79
88
  }
80
89
  return player;
81
90
  }
82
91
 
83
- /** What had the focus when a scenario started, to give it back when the scenario closes: the toolbar's Play button when the start came from it or its list */
92
+ /** What had the focus when a scenario started, to give it back when the scenario closes (a control of another panel, say) */
84
93
  let returnTo = null;
85
94
  function openerOf() {
86
95
  const active = document.activeElement;
87
- const play = document.getElementById('proposal-play');
88
- if (active && active !== document.body && (active === play || active.closest?.('#proposal-scenarios'))) return play;
89
- if (active && active !== document.body && !active.closest?.('.hx-player') && active !== state.canvas) return active;
96
+ if (active && active !== document.body && !active.closest?.('.hx-player') && !active.closest?.('#review-column') && active !== state.canvas) return active;
90
97
  return null;
91
98
  }
92
99
 
@@ -96,7 +103,19 @@ function isKeyboardish() {
96
103
  return !!active && active !== document.body && !typingIn(active);
97
104
  }
98
105
 
99
- /** Closing the player by the viewer's own act: the focus goes back to what started it (Play), else to Play, else to the map (on a phone Play is folded away in the peek) */
106
+ /** Who knows where the focus goes when the player closes: the review column's step list (review-column.js) gives the step the player was on */
107
+ let closeFocus = null;
108
+ export function setCloseFocus(fn) { closeFocus = typeof fn === 'function' ? fn : null; }
109
+
110
+ /** Who is told when the player moves: `fn(snapshot)` on each change of step, play state or answer, and `fn(null)` when it closes */
111
+ const playerListeners = new Set();
112
+ export function onPlayerChange(fn) {
113
+ playerListeners.add(fn);
114
+ return () => playerListeners.delete(fn);
115
+ }
116
+ const notify = (snap) => { for (const fn of playerListeners) fn(snap); };
117
+
118
+ /** Closing the player by the viewer's own act: the focus goes back to the step it was on in the list, else to what started it, else to the map */
100
119
  function giveFocusBack() {
101
120
  const to = returnTo;
102
121
  returnTo = null;
@@ -105,7 +124,7 @@ function giveFocusBack() {
105
124
  el.focus();
106
125
  return document.activeElement === el; // a control the stylesheet hides takes no focus
107
126
  };
108
- if (took(to) || took(document.getElementById('proposal-play'))) return;
127
+ if (took(closeFocus && closeFocus()) || took(to)) return;
109
128
  took(state.canvas);
110
129
  }
111
130
 
@@ -119,6 +138,42 @@ function showOutageLayers(scenario) {
119
138
  .forEach((key) => { if (state.activeLayers[key] === false) toggleLayer(key); });
120
139
  }
121
140
 
141
+ /**
142
+ * The Layers keys that hide a node, or [] when no layer does (#212). Only what Layers decides: the Flow and House views and
143
+ * Before or After draw their own sets, and a layer would not change them.
144
+ */
145
+ export function layersHiding(node) {
146
+ if (!node || state.view === 'dataflow' || state.view === 'house') return [];
147
+ const on = (key) => state.activeLayers[key] !== false;
148
+ const t = node.type;
149
+ if (t === 'root' || shownByProposal(state, node)) return []; // a proposal's own nodes are drawn whatever their layer says (spec 0009 D3)
150
+ const project = projectLayerKey(state, node); // a project layer that takes the node decides alone (spec 0009 D3), as scene.js layerShows has it
151
+ if (project) return on(project) ? [] : [project];
152
+ if (t === 'core') return [...(on('core') ? [] : ['core']), ...(state.activeLayers.pkg || state.activeLayers.atom ? [] : ['pkg'])];
153
+ if (t === 'store') return ['flow', 'store'].filter((k) => !on(k));
154
+ if (t === 'rom') return ['rom', 'flow'].filter((k) => !on(k));
155
+ if (t === 'floor' || t === 'room') return on('house') ? [] : ['house'];
156
+ const key = t === 'external' ? externalLayer(node) : t;
157
+ return on(key) ? [] : [key];
158
+ }
159
+
160
+ /** The nodes a scenario's steps name: a node step's node, both ends of an edge step */
161
+ const stepNodeIds = (scenario) => (Array.isArray(scenario?.steps) ? scenario.steps : []).flatMap((st) => (st?.edge ? [st.edge.from, st.edge.to] : st && st.node !== undefined ? [st.node] : []));
162
+
163
+ /**
164
+ * A step on a layer that is off cannot be followed: the camera has nothing to go to (#212). Playing a scenario turns on the layers
165
+ * its steps are drawn on, as an outage turns on what it hits, and says which.
166
+ */
167
+ function showStepLayers(scenario) {
168
+ const byId = new Map(state.nodes.map((n) => [n.id, n]));
169
+ const keys = [];
170
+ for (const id of stepNodeIds(scenario)) for (const key of layersHiding(byId.get(id))) if (!keys.includes(key)) keys.push(key);
171
+ if (!keys.length) return;
172
+ for (const key of keys) { if (key === 'pkg') state.activeLayers.pkg = false; toggleLayer(key); }
173
+ const names = keys.map((key) => (LAYER_DEFS.find((l) => l.key === key) || (state.projectLayers || []).find((l) => l.key === key) || { label: key }).label);
174
+ announce(`Turned on ${names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : names[0]} to show this scenario's steps.`);
175
+ }
176
+
122
177
  /** The cloud panel's Play button (CLOUD-07): plays "X is down" for a cloud node, generated from the map (outage-model.js) */
123
178
  export function playOutage(id) {
124
179
  const node = state.nodes.find((n) => n.id === id);
@@ -129,25 +184,32 @@ export function playOutage(id) {
129
184
  /** The player of the scenario on the map, or null */
130
185
  export const getPlayer = () => player;
131
186
 
132
- /** Ends the scenario without touching the picture: for callers that rebuild it themselves (selecting a node, switching view) */
133
- export function clearScenario() {
187
+ /** Ends the scenario without touching the picture: for callers that rebuild it themselves (selecting a node, switching view). `keepChecks` while another scenario is about to start */
188
+ export function clearScenario({ keepChecks = false, closing = false } = {}) {
189
+ const had = !!player || !!state.scenario;
134
190
  player = null;
135
191
  glide = null;
136
192
  signature = '';
137
193
  state.scenario = null;
138
- closeChecks();
194
+ if (!keepChecks) closeChecks();
195
+ if (barWatch) { barWatch.disconnect(); barWatch = null; }
139
196
  if (bar) { unregisterSheet('player'); bar.remove(); bar = null; }
140
- refreshList();
197
+ if (had && (!keepChecks || closing)) notify(null);
141
198
  }
142
199
 
200
+ /** Who keeps a closed scenario's checks: the review column, while its steps are open in the list (their verdicts stay there) */
201
+ let keepChecksOnClose = null;
202
+ export function setKeepChecksOnClose(fn) { keepChecksOnClose = typeof fn === 'function' ? fn : null; }
203
+
143
204
  /** Ends the scenario and redraws the map without it */
144
205
  export function stopScenario() {
145
206
  if (!player && !state.scenario) return;
146
- const hadFocus = !!bar && bar.contains(document.activeElement);
147
- clearScenario();
207
+ const hadFocus = (!!bar && bar.contains(document.activeElement)) || !!document.activeElement?.closest?.('#review-column'); // in the player, or in the list that follows it
208
+ const keep = !!player && !!keepChecksOnClose && keepChecksOnClose(player.scenario().id); // the list still shows its steps: their verdicts stay
209
+ clearScenario({ keepChecks: keep, closing: true });
148
210
  touchScene();
149
211
  render();
150
- if (hadFocus || document.activeElement === document.body) giveFocusBack(); // focus was in the player, which is gone
212
+ if (hadFocus || document.activeElement === document.body) giveFocusBack(); // focus was in the player, which is gone: it goes to the step the player was on
151
213
  else returnTo = null;
152
214
  }
153
215
 
@@ -162,9 +224,10 @@ function sync(force = false) {
162
224
  const stepChanged = force || next.split('|')[0] !== signature.split('|')[0];
163
225
  signature = next;
164
226
  touchScene();
165
- if (stepChanged) followStep(snap);
227
+ if (stepChanged) { held = false; followStep(snap); }
166
228
  }
167
229
  updateBar(snap);
230
+ if (changed) notify({ id: snap.id, index: snap.index, total: snap.total, done: snap.done, playing: snap.playing, checks: checksVersion() });
168
231
  return changed;
169
232
  }
170
233
 
@@ -176,6 +239,7 @@ function followStep(snap) {
176
239
  state.nodes.forEach((n) => { if (isNodeVisible(n)) visible.set(n.id, n); });
177
240
  // The step must be in the part of the map nothing covers: not under the proposal bar, the node panel, the player or (on a phone) the sheets
178
241
  const rect = visibleMapRect();
242
+ framedFor = bar ? bar.offsetHeight : 0;
179
243
  const target = cameraFor({ node: snap.current.node, edge: snap.current.edge, at: snap.current.at, text: snap.current.text }, state.camera, rect, visible, 60, getMinZoom());
180
244
  if (!target) return;
181
245
  if (flowReduceMotion) { Object.assign(state.camera, target); glide = null; render(); return; } // reduced motion: jump, do not fly
@@ -222,19 +286,27 @@ function showBar(speed) {
222
286
  bar.dataset.corn = 'scenario-player';
223
287
  bar.setAttribute('role', 'region');
224
288
  bar.setAttribute('aria-label', 'Scenario player');
289
+ // One bar (spec 0006 D6): Previous, Pause or Play, Next; "2 of 4 · As Adult · the step's text · Allowed"; the speed and Close.
290
+ // The scenario's name is the title (heard, and shown on a phone's open sheet); the list beside the map has it open and the step marked.
225
291
  bar.innerHTML = `
226
- <div class="hx-player-head">
227
- <span class="hx-player-title"></span>
292
+ <span class="hx-player-title hx-sr-only"></span>
293
+ <div class="hx-player-controls" role="group">
294
+ <button data-corn-kind="secondary" type="button" class="hx-btn hx-player-prev" data-action="scenario-prev" data-peek-ok><span class="hx-player-label"></span></button>
295
+ <button type="button" class="hx-btn hx-btn--active hx-player-toggle" data-action="scenario-toggle" data-peek-ok data-corn-kind="primary"><span class="hx-player-label"></span></button>
296
+ <button data-corn-kind="secondary" type="button" class="hx-btn hx-player-next" data-action="scenario-next" data-peek-ok><span class="hx-player-label"></span></button>
297
+ <button data-corn-kind="secondary" type="button" class="hx-btn hx-player-next-scenario" data-action="scenario-next-scenario" data-peek-ok hidden></button>
298
+ </div>
299
+ <p class="hx-player-text"><span class="hx-player-count" data-corn="count"></span><span class="hx-player-sep" aria-hidden="true"> · </span><span class="hx-player-who"></span><span class="hx-player-step"></span></p>
300
+ <span class="hx-player-says hx-sr-only" role="status" aria-live="polite"></span>
301
+ <div class="hx-player-side">
228
302
  <select data-corn="control" class="hx-player-speed" data-action="scenario-speed" aria-label="Time for each step" title="Time for each step">${SPEED_CHOICES.map((c) => `<option value="${c.value}">${c.label}</option>`).join('')}</select>
229
303
  <button type="button" class="hx-close" data-action="scenario-close" aria-label="Close the scenario" data-corn-kind="icon">✕</button>
230
304
  </div>
231
- <p class="hx-player-text" aria-live="polite"><span class="hx-player-count" data-corn="count"></span> · <span class="hx-player-step"></span></p>
232
- <div class="hx-player-controls">
233
- <button data-corn-kind="secondary" type="button" class="hx-btn" data-action="scenario-prev" data-peek-ok>◀ Previous</button>
234
- <button type="button" class="hx-btn hx-btn--active" data-action="scenario-toggle" data-peek-ok data-corn-kind="primary"></button>
235
- <button data-corn-kind="secondary" type="button" class="hx-btn" data-action="scenario-next" data-peek-ok>Next ▶</button>
236
- </div>
237
305
  <div class="hx-player-track" data-corn="scenario-track" aria-hidden="true"><span class="hx-player-fill" data-corn="scenario-fill"></span></div>`;
306
+ bar.querySelector('.hx-player-controls').setAttribute('aria-label', t('steps'));
307
+ bar.querySelector('.hx-player-prev .hx-player-label').textContent = t('previousStep');
308
+ bar.querySelector('.hx-player-next .hx-player-label').textContent = t('nextStep');
309
+ bar.querySelector('.hx-player-next-scenario').textContent = t('nextScenario');
238
310
  bar.addEventListener('click', (e) => {
239
311
  const button = e.target.closest('[data-action]');
240
312
  if (button) act(button.dataset.action);
@@ -242,15 +314,24 @@ function showBar(speed) {
242
314
  const menu = bar.querySelector('.hx-player-speed');
243
315
  menu.value = String(speed);
244
316
  menu.addEventListener('change', (e) => chooseSpeed(e.target.value));
245
- // On a phone the bar is a sheet in the dock, above the node panel; it opens as a peek and the others fold, so the map shows
317
+ // On a phone the bar is a sheet in the dock, above the node panel; it opens as a peek (one row) and the others fold, so the map shows
246
318
  const dock = document.getElementById('sheet-dock');
247
319
  const drawer = document.getElementById('spec-drawer');
248
320
  if (dock && drawer && drawer.parentElement === dock) dock.insertBefore(bar, drawer);
249
321
  else (dock || stage).appendChild(bar);
250
322
  registerSheet('player', bar);
251
323
  collapseAllSheets();
324
+ // The bar grows once it has more to say (a step's check, its As row): the step it framed would now be under it, so it is followed again
325
+ if (typeof ResizeObserver === 'function') {
326
+ barWatch = new ResizeObserver(() => { if (bar && player && state.scenario && !held && bar.offsetHeight !== framedFor) followStep(player.snapshot()); });
327
+ barWatch.observe(bar);
328
+ }
252
329
  }
253
330
 
331
+ /** Who knows the scenario after this one, in the order the list reads (review-column.js): `fn(scenarioId)` gives the scenario or null */
332
+ let nextScenarioOf = null;
333
+ export function setNextScenario(fn) { nextScenarioOf = typeof fn === 'function' ? fn : null; }
334
+
254
335
  // The viewer's speed: a setting of theirs, kept for the next scenario and the next visit
255
336
  function readSpeed() {
256
337
  try { return parseSpeed(window.localStorage.getItem(SPEED_KEY)); } catch { return parseSpeed(null); }
@@ -270,6 +351,12 @@ function chooseSpeed(value) {
270
351
  function act(action) {
271
352
  if (!player) return;
272
353
  if (action === 'scenario-close') return stopScenario();
354
+ if (action === 'scenario-next-scenario') {
355
+ // the end of a scenario: nothing advances by itself; this is the reviewer's choice, and it starts the next one in the list's order
356
+ const next = nextScenarioOf ? nextScenarioOf(player.scenario().id) : null;
357
+ if (next) playScenario(next);
358
+ return;
359
+ }
273
360
  if (action === 'scenario-toggle') {
274
361
  const s = player.snapshot();
275
362
  if (s.playing) player.pause(); else player.play();
@@ -289,14 +376,27 @@ function updateBar(snap) {
289
376
  // this runs every frame: a live region is written only when its words change, so a step is said once, not once a frame
290
377
  const put = (cls, text) => { const el = q(cls); if (el.textContent !== text) el.textContent = text; };
291
378
  put('.hx-player-title', snap.title);
379
+ bar.setAttribute('aria-label', `Scenario player: ${snap.title}`);
292
380
  put('.hx-player-count', `${Math.min(snap.index + 1, Math.max(snap.total, 1))} of ${snap.total}`);
293
- put('.hx-player-step', snap.current.text);
381
+ const actor = snap.current.actor ? personaLabel(personaFor(state.nodes, snap.current.actor)) || snap.current.actor : '';
382
+ put('.hx-player-who', actor && !snap.done ? `As ${actor} · ` : '');
383
+ put('.hx-player-step', snap.done ? 'Played to the end' : snap.current.text);
384
+ bar.dataset.done = String(!!snap.done);
294
385
  const toggle = q('[data-action=scenario-toggle]');
295
- toggle.textContent = snap.playing ? 'Pause' : snap.done ? 'Play again' : 'Play';
386
+ const label = snap.playing ? t('pause') : snap.done ? t('playAgain') : t('play');
387
+ put('[data-action=scenario-toggle] .hx-player-label', label);
388
+ toggle.dataset.state = snap.playing ? 'playing' : snap.done ? 'done' : 'paused';
296
389
  toggle.disabled = snap.total === 0 || snap.manual;
297
390
  toggle.title = snap.manual ? 'The time for each step is Manual: use Next' : '';
298
391
  q('[data-action=scenario-prev]').disabled = snap.index === 0 && !snap.done;
299
- q('[data-action=scenario-next]').disabled = snap.done || snap.total === 0;
392
+ const next = q('[data-action=scenario-next]');
393
+ next.disabled = snap.done || snap.total === 0;
394
+ // at the end: Play again and Next scenario (the next one in the list's order); nothing carries on by itself
395
+ const following = snap.done && nextScenarioOf ? nextScenarioOf(snap.id) : null;
396
+ q('[data-action=scenario-next-scenario]').hidden = !following;
397
+ next.hidden = !!following;
398
+ // the one polite line: a step as the list says it ("Step 2 of 3, as Adult: checkout page, Added. You pay. Allowed.")
399
+ put('.hx-player-says', snap.done ? `${snap.title}: played to the end.` : currentStepSentence({ snap, nodes: state.nodes, edges: state.edges, words: { notChecked: t('notChecked') } }));
300
400
  const fill = snap.total ? Math.round(((snap.done ? snap.total : snap.index + snap.progress) / snap.total) * 1000) / 10 : 0;
301
401
  if (fill !== lastFill) { lastFill = fill; q('.hx-player-fill').style.width = `${fill}%`; }
302
402
  paintChecks(bar, snap);
@@ -314,9 +414,9 @@ function typingIn(target) {
314
414
  function onKeydown(e) {
315
415
  if (e.key === 'Escape' && !e.defaultPrevented && !e.ctrlKey && !e.metaKey && !e.altKey) {
316
416
  if (player && !typingIn(e.target) && !otherPopupOpen()) { e.preventDefault(); stopScenario(); return; } // Escape closes the scenario; focus goes back to Play
317
- if (!player && list && !list.hidden && list.contains(document.activeElement)) { e.preventDefault(); closeList(true); return; }
318
417
  }
319
418
  if (!player || e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey || typingIn(e.target)) return;
419
+ if ((e.key === ' ' || e.code === 'Space') && e.target.closest?.('#review-column')) return; // Space on a step or a row presses it
320
420
  const action = e.key === ' ' || e.code === 'Space' ? 'scenario-toggle' : e.key === 'ArrowLeft' ? 'scenario-prev' : e.key === 'ArrowRight' ? 'scenario-next' : null;
321
421
  if (!action) return;
322
422
  e.preventDefault(); // space on a focused button would press it as well
@@ -333,98 +433,6 @@ function onKeyup(e) {
333
433
  if (player && (e.key === ' ' || e.code === 'Space') && !typingIn(e.target)) e.preventDefault();
334
434
  }
335
435
 
336
- // ---------------------------------------------------------------------------
337
- // The scenario list
338
- // ---------------------------------------------------------------------------
339
- /** The open proposal's scenarios, with the maintainer's what-if edits in (`state.effectiveProposal`) when there are any */
340
- const proposalScenarios = () => {
341
- const p = state.effectiveProposal || state.proposal;
342
- return p && Array.isArray(p.scenarios) ? p.scenarios : [];
343
- };
344
-
345
- /**
346
- * Where the list goes: a row of the open proposal's bar, under its title row, so the list
347
- * opens in the bar's own flow and the bar grows to hold it (as a second box at the stage's corner
348
- * it opened underneath the bar and was covered). Without a bar it is a box at the stage's corner.
349
- */
350
- function mountList() {
351
- const body = document.getElementById('proposal-body');
352
- const stage = $stage();
353
- if (!body) {
354
- if (stage && list.parentElement !== stage) stage.appendChild(list);
355
- } else if (list.parentElement !== body) {
356
- const summary = document.getElementById('proposal-summary');
357
- if (summary && summary.parentElement === body) body.insertBefore(list, summary);
358
- else body.appendChild(list);
359
- }
360
- }
361
-
362
- const wiredPlay = new WeakSet();
363
-
364
- /** The toolbar's Play button: shown while the open proposal has scenarios and none plays; with one it plays it, with several it opens the list */
365
- function paintPlay(show) {
366
- const btn = document.getElementById('proposal-play');
367
- if (!btn) return;
368
- btn.hidden = !show;
369
- // with one scenario Play plays it, so it expands nothing
370
- if (proposalScenarios().length > 1) btn.setAttribute('aria-expanded', String(!!list && !list.hidden)); else btn.removeAttribute('aria-expanded');
371
- if (wiredPlay.has(btn)) return;
372
- wiredPlay.add(btn);
373
- btn.addEventListener('click', () => {
374
- const scenarios = proposalScenarios();
375
- if (scenarios.length === 1) playScenario(scenarios[0]);
376
- else if (list) {
377
- if (list.hidden) { list.hidden = false; btn.setAttribute('aria-expanded', 'true'); list.querySelector('button')?.focus(); } // the first row of what opened
378
- else closeList(false);
379
- }
380
- });
381
- }
382
-
383
- /** Folds the scenario list back onto Play; `refocus` gives Play the focus (Escape from inside the list) */
384
- function closeList(refocus) {
385
- if (list) list.hidden = true;
386
- const btn = document.getElementById('proposal-play');
387
- if (!btn) return;
388
- btn.setAttribute('aria-expanded', 'false');
389
- if (refocus) btn.focus();
390
- }
391
-
392
- /** Shows or hides the Play button and its list to match the open proposal's scenarios (and hides them while one plays: the player is the control then) */
393
- export function refreshList() {
394
- const stage = $stage();
395
- const scenarios = proposalScenarios();
396
- const show = !!stage && scenarios.length > 0 && !player;
397
- if (!show) { if (list) { list.remove(); list = null; } paintPlay(false); return; }
398
- const key = scenarios.map((s) => `${s.id}\u0000${s.title}\u0000${(s.steps || []).length}`).join('\u0001');
399
- if (list && list.dataset.key === key) { mountList(); paintPlay(true); return; }
400
- const wasOpen = !!list && !list.hidden;
401
- if (list) list.remove();
402
- list = document.createElement('div');
403
- list.id = 'proposal-scenarios';
404
- list.className = 'hx-scenarios glass';
405
- list.dataset.corn = 'scenario-list';
406
- list.dataset.key = key;
407
- list.hidden = !!document.getElementById('proposal-play') && (!wasOpen || scenarios.length < 2); // behind Play when the toolbar has one
408
- scenarios.forEach((s) => {
409
- const button = document.createElement('button');
410
- button.type = 'button';
411
- button.className = 'hx-scenarios-item';
412
- button.dataset.corn = 'row';
413
- button.dataset.scenario = s.id;
414
- const steps = (s.steps || []).length;
415
- button.textContent = `${s.title} · ${steps} ${steps === 1 ? 'step' : 'steps'}`;
416
- list.appendChild(button);
417
- });
418
- list.addEventListener('click', (e) => {
419
- const button = e.target.closest('[data-scenario]');
420
- if (!button) return;
421
- const scenario = proposalScenarios().find((s) => s.id === button.dataset.scenario);
422
- if (scenario) playScenario(scenario);
423
- });
424
- mountList();
425
- paintPlay(true);
426
- }
427
-
428
436
  // ---------------------------------------------------------------------------
429
437
  // /?scenario-demo=1: a small scenario over real nodes, for looking at the player before a proposal exists
430
438
  // ---------------------------------------------------------------------------
@@ -474,10 +482,8 @@ export function initScenarioUi() {
474
482
  wired = true;
475
483
  document.addEventListener('keydown', onKeydown);
476
484
  document.addEventListener('keyup', onKeyup);
477
- onSceneTouch(refreshList);
478
485
  // A sheet that opened or closed changes what the map shows: keep the step in view
479
486
  onCoveredChange(() => { if (player && state.scenario) followStep(player.snapshot()); });
480
487
  // Taking hold of the map (a drag, the wheel, a pinch) ends the camera's glide: the camera is theirs
481
- for (const type of ['pointerdown', 'wheel', 'touchstart', 'mousedown']) document.addEventListener(type, (e) => { if (e.target === state.canvas) glide = null; }, { passive: true, capture: true });
482
- refreshList();
488
+ for (const type of ['pointerdown', 'wheel', 'touchstart', 'mousedown']) document.addEventListener(type, (e) => { if (e.target === state.canvas) { glide = null; held = true; } }, { passive: true, capture: true });
483
489
  }
package/explorer/scene.js CHANGED
@@ -163,6 +163,7 @@ import { beforeOf, markIn, showsEdge, showsNode, touchedIds } from './proposal-m
163
163
  import { decorateHouseScene, houseEdgeStyle, houseShowsNode, houseViewEdges } from './house-model.js';
164
164
  import { paintVerdict } from './check-model.js';
165
165
  import { externalLayer, whenDash } from './cloud-model.js';
166
+ import { lettersOf, projectLayerKey, shownByProposal } from './layer-model.js';
166
167
  import { outageFor, paintOutage } from './outage-model.js';
167
168
  import { paintForge } from './forge-panel-model.js';
168
169
  import { lightColor, lightenScene, parseColor } from './theme-model.js';
@@ -238,11 +239,18 @@ export const PROPOSAL_DIM_ALPHA = 0.28;
238
239
  // Visibility and focus (moved unchanged from render.js)
239
240
  // ---------------------------------------------------------------------------
240
241
  export function isNodeVisible(state, node) {
241
- const { activeLayers } = state;
242
242
  if (state.proposal && !showsNode(state.proposalView || 'diff', node)) return false; // Before hides what is added, After what is removed
243
243
  if (state.view === 'dataflow') return !!state.flow && state.flow.ids.has(node.id);
244
244
  if (state.view === 'house') return houseShowsNode(state, node); // the House view (spec 0029, PHY-11) draws its own set: house-model.js
245
245
  if (node.type === 'root') return true;
246
+ return layerShows(state, node) || shownByProposal(state, node); // a proposal's own nodes are drawn whatever their layer says (spec 0009 D3)
247
+ }
248
+
249
+ /** Whether the Layers menu has the node's layer on: a project layer that takes it decides alone, else its starting layer, with the rules each type has */
250
+ export function layerShows(state, node) {
251
+ const { activeLayers } = state;
252
+ const project = projectLayerKey(state, node);
253
+ if (project) return activeLayers[project] !== false;
246
254
  if (node.type === 'core') return (activeLayers.pkg || activeLayers.atom) && activeLayers.core !== false; // its own row in Layers, and Packages or Atoms
247
255
  if (node.type === 'store') return activeLayers.flow !== false && activeLayers.store !== false; // its own row, and Data Flow
248
256
  if (node.type === 'rom') return activeLayers.rom !== false && activeLayers.flow !== false;
@@ -567,9 +575,15 @@ function buildNodes(state, subgraph) {
567
575
  if (focus && !focus.touched.has(node.id)) alpha = Math.min(alpha, PROPOSAL_DIM_ALPHA);
568
576
  if (look) alpha *= gone ? MARK.removed.alpha : look.alpha;
569
577
  const big = shown.type === 'root' || shown.type === 'app';
578
+ // A finer kind (spec 0009): its letters, drawn in the node's core by the renderers (kind-letters.js), and the project layer that takes the node
579
+ const letters = lettersOf(state, shown);
580
+ const layer = projectLayerKey(state, shown);
570
581
 
571
582
  out.push({
572
583
  id: node.id, type: shown.type, group: groupOf(shown),
584
+ ...(typeof shown.kind === 'string' && shown.kind ? { kind: shown.kind } : {}),
585
+ ...(letters ? { letters } : {}),
586
+ ...(layer ? { layer } : {}),
573
587
  x: node.x, y: node.y, r: shown.r, color: shown.color,
574
588
  alpha,
575
589
  glow: connected && alpha >= 0.5 ? (big ? 15 : 9) : 0,
@@ -545,7 +545,7 @@ flat out float v_alpha;
545
545
  void main() {
546
546
  vec2 centre = u_cam.xy + a_geom.xy * u_cam.z;
547
547
  vec2 pos = centre + a_corner * (a_geom.z * 0.5 * u_cam.z);
548
- v_uv = vec2(a_corner.x * 0.5 + 0.5, 0.5 - a_corner.y * 0.5);
548
+ v_uv = vec2(a_corner.x * 0.5 + 0.5, a_corner.y * 0.5 + 0.5); // screen y runs down and an image's first row is its top, so the corner below the centre reads the last row
549
549
  v_alpha = a_geom.w;
550
550
  gl_Position = toClip(pos);
551
551
  }
@@ -202,7 +202,7 @@ export function measureCovered() {
202
202
  /**
203
203
  * The part of the map nothing covers, in the canvas's own CSS px: what the camera should frame a node into.
204
204
  * On a phone the dock's sheets cover the bottom; from 768px the proposal bar covers the top (and the change list it grows to hold),
205
- * the node panel the right, the Work panel the left and the scenario player the bottom. Without a layout (no page) it is the whole canvas.
205
+ * the node panel the right, the Work panel and the review column the left and the scenario player the bottom. Without a layout (no page) it is the whole canvas.
206
206
  * @returns {{ x: number, y: number, width: number, height: number }}
207
207
  */
208
208
  export function visibleMapRect() {
@@ -218,6 +218,9 @@ export function visibleMapRect() {
218
218
  if (shown(drawer) && drawer.classList.contains('drawer-open')) covers.right = drawer.offsetWidth; // its width, not its box: it slides in
219
219
  const forge = $('forge-panel');
220
220
  if (shown(forge) && forge.classList.contains('forge-open')) covers.left = forge.offsetWidth;
221
+ // the review column (review-column.js) is docked on the left under the bar: its right edge is what it covers, past the Work panel's when both are open
222
+ const column = $('review-column');
223
+ if (shown(column)) covers.left = Math.max(covers.left, Math.max(0, column.getBoundingClientRect().right - c.left) + 8);
221
224
  const player = document.querySelector('.hx-player');
222
225
  if (shown(player)) covers.bottom = Math.max(0, c.bottom - player.getBoundingClientRect().top) + 8;
223
226
  }
@@ -263,7 +266,7 @@ export function unregisterSheet(id, redraw = true) {
263
266
  export function expandSheet(id) { syncShown(); if (model.expand(id)) apply(); } // what is open on the page is known first (a bar shown a moment ago)
264
267
  export function collapseSheet(id) { if (model.collapse(id)) apply(); }
265
268
  export function collapseAllSheets() { if (model.collapseAll()) apply(); }
266
- export function toggleSheet(id) { if (model.toggle(id)) apply(); }
269
+ export function toggleSheet(id) { syncShown(); if (model.toggle(id)) apply(); } // the same: a bar shown since the last change is open
267
270
 
268
271
  // ---------------------------------------------------------------------------
269
272
  // Taps and swipes
package/explorer/state.js CHANGED
@@ -54,6 +54,15 @@ export const state = {
54
54
  machine: false, container: false, device: false, house: false, persona: false,
55
55
  },
56
56
 
57
+ /**
58
+ * The project's own layers (spec 0009): `{ key, label, desc?, match }` in `add` order, as the config sent them (core/layers.js); a node is
59
+ * in the first one whose match it meets (explorer/layer-model.js). `layerOrder` is the config's `order`; `layerDefaults` what each layer is
60
+ * when the viewer has not touched it (layers.js `setProjectLayers`). Empty with no `layers` in the config: the menu is then the starting set.
61
+ */
62
+ projectLayers: [],
63
+ layerOrder: [],
64
+ layerDefaults: {},
65
+
57
66
  /**
58
67
  * The map as the last `setMap` (view.js) was handed it, before the live layer is laid in: the base
59
68
  * copies, or a proposal applied over them. `nodes` and `edges` are these plus the live ones.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.38.0",
3
+ "version": "0.40.0",
4
4
  "description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
5
5
  "license": "MIT",
6
6
  "author": "popcorn245 (https://github.com/popcorn245)",
package/server/server.js CHANGED
@@ -57,6 +57,7 @@ import { browserSources, BUILTIN_SOURCES, parseDuration, specPollMs, triggersOf,
57
57
  import { CLOUD_FILE } from '../core/cloud.js';
58
58
  import { BRAND_SVG_CSP, MANIFEST_PATH, appNameOf, brandAssetFile, brandImages, clientBrand, manifestOf } from '../core/brand.js';
59
59
  import { clientStrings } from '../core/strings.js';
60
+ import { clientLayers } from '../core/layers.js';
60
61
  import { MAX_THEME_ASSET_BYTES, MAX_THEME_BYTES, THEME_ASSET_PREFIX, THEME_NAME, THEME_SVG_CSP, clientTheme, cssProblems, cssUrls, fontOrigins, themeAssetFile, themeAssetPath, themeUrlTarget } from '../core/theme.js';
61
62
  import { decodePath, inside, notFound, sendFile } from './files.js';
62
63
  import { serveProposals } from './proposals.js';
@@ -81,7 +82,7 @@ import { compressResponse } from './compress.js';
81
82
  export const CORNFIELD_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
82
83
  const EXPLORER_DIR = path.join(CORNFIELD_DIR, 'explorer');
83
84
  /** The pure core modules the explorer imports (no Node built-ins, no files): the only ones of core/ served */
84
- export const BROWSER_CORE = ['schema.js', 'proposal.js', 'personas.js', 'cloud.js', 'text.js', 'mentions.js', 'color.js', 'strings.js'];
85
+ export const BROWSER_CORE = ['schema.js', 'proposal.js', 'personas.js', 'cloud.js', 'text.js', 'mentions.js', 'color.js', 'strings.js', 'layers.js'];
85
86
  /** The explorer files the sign-in pages load: cornfield's tokens, their own stylesheet and the script that applies Light or Dark. Served without a session. */
86
87
  const SIGN_IN_FILES = new Set(['/explorer/tokens.css', '/explorer/sign-in.css', '/explorer/theme-boot.js']);
87
88
  /** cornfield's own browser sources, by request path */
@@ -252,6 +253,8 @@ export function clientConfig(config, signIn = false) {
252
253
  brand: clientBrand(config.brand, PKG.homepage),
253
254
  // Only the labels the config overrides, as text (core/strings.js); the defaults are in the browser
254
255
  strings: clientStrings(config.strings),
256
+ // The project's own layers, as plain data of the known keys (core/layers.js; docs/config.md#layers)
257
+ layers: clientLayers(config.layers),
255
258
  forge: config.forge ? { type: config.forge.type, url: config.forge.url || (config.forge.type === 'github' ? 'https://github.com' : null), repo: config.forge.repo, mergeMethod: config.forge.mergeMethod || 'merge', ...(config.forge.baseBranch ? { baseBranch: config.forge.baseBranch } : {}), ...(config.approveLands ? { approveLands: true } : {}) } : null,
256
259
  // Threads (docs/threads.md): the idea label, or false when `threads: false` turns the Threads tab off
257
260
  threads: config.threads === false ? false : { label: ideaLabel(config) },