@popcorn245/cornfield 0.48.0 → 0.50.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.
- package/core/strings.js +14 -0
- package/explorer/check.js +7 -227
- package/explorer/connection.js +3 -3
- package/explorer/css/review.css +49 -0
- package/explorer/decision-model.js +6 -0
- package/explorer/engine/checks.js +252 -0
- package/explorer/engine/connection.js +36 -0
- package/explorer/engine/layers.js +1 -0
- package/explorer/engine/layout.js +8 -3
- package/explorer/engine/player.js +489 -0
- package/explorer/engine/proposal.js +373 -0
- package/explorer/engine/render.js +1 -0
- package/explorer/engine/sheets.js +40 -7
- package/explorer/engine/source.js +315 -0
- package/explorer/engine/theme-sheet.js +444 -0
- package/explorer/engine/topology.js +126 -0
- package/explorer/index.html +6 -59
- package/explorer/instance.js +87 -7
- package/explorer/page-address.js +59 -0
- package/explorer/page-pieces.js +33 -5
- package/explorer/page.js +20 -20
- package/explorer/panels.js +1 -3
- package/explorer/pieces/changes.js +495 -0
- package/explorer/pieces/decision.js +664 -0
- package/explorer/pieces/layers.js +4 -0
- package/explorer/pieces/map.js +117 -25
- package/explorer/pieces/node-panel.js +34 -1
- package/explorer/pieces/proposal.js +488 -0
- package/explorer/pieces/review.js +280 -0
- package/explorer/pieces/scope-link.js +50 -0
- package/explorer/pieces/scope.js +247 -0
- package/explorer/pieces/status.css +24 -0
- package/explorer/pieces/status.js +144 -0
- package/explorer/plugins.js +0 -10
- package/explorer/proposal.js +64 -697
- package/explorer/review-column.js +24 -439
- package/explorer/review.js +27 -673
- package/explorer/scenario-ui.js +32 -478
- package/explorer/sheets.js +8 -7
- package/explorer/view.js +12 -64
- package/explorer/waiting-line.js +7 -50
- package/package.json +1 -1
|
@@ -59,6 +59,9 @@ export function labelWidth(inst, node) {
|
|
|
59
59
|
const DATA_TYPES = ['store', 'table', 'rom'];
|
|
60
60
|
const CHILD_TYPE_ORDER = ['core', 'atom', 'molecule', 'token', 'page', 'service', 'external', 'stack', 'table', 'store', 'tool', 'app', 'pkg'];
|
|
61
61
|
|
|
62
|
+
/** How deep packTree nests a cluster's own clusters (a real map nests a few levels) */
|
|
63
|
+
const PACK_DEPTH = 64;
|
|
64
|
+
|
|
62
65
|
/** Concentric rings of `items` around (0, 0): returns the offsets and the radii used */
|
|
63
66
|
function ringPack(items, { first = 110, gap = 76, spacing = 90 } = {}) {
|
|
64
67
|
const offsets = [];
|
|
@@ -90,14 +93,16 @@ function ringPack(items, { first = 110, gap = 76, spacing = 90 } = {}) {
|
|
|
90
93
|
* `kidsOf(node)` says who hangs under a node. Returns `{ children, offsets, radii, subs, extent }`: `subs[i]` is the
|
|
91
94
|
* child i's own pack (or null), `extent` how far the whole thing reaches from the centre.
|
|
92
95
|
*/
|
|
93
|
-
function packTree(children, kidsOf, spacingOf, byOrder, seen = new Set()) {
|
|
96
|
+
function packTree(children, kidsOf, spacingOf, byOrder, seen = new Set(), depth = 0) {
|
|
94
97
|
const withSub = [];
|
|
95
98
|
const plain = [];
|
|
96
99
|
children.forEach((c) => {
|
|
97
|
-
|
|
100
|
+
// Deeper than PACK_DEPTH a child is packed as a leaf, and its own children are placed around it after (the last pass of layoutOrbit): a map
|
|
101
|
+
// nested thousands deep is laid out, never a stack overflow
|
|
102
|
+
const kids = seen.has(c.id) || depth >= PACK_DEPTH ? [] : kidsOf(c);
|
|
98
103
|
if (!kids.length) { plain.push(c); return; }
|
|
99
104
|
seen.add(c.id);
|
|
100
|
-
const sub = packTree(kids.sort(byOrder), kidsOf, spacingOf, byOrder, seen);
|
|
105
|
+
const sub = packTree(kids.sort(byOrder), kidsOf, spacingOf, byOrder, seen, depth + 1);
|
|
101
106
|
withSub.push({ c, sub, fp: sub.extent });
|
|
102
107
|
});
|
|
103
108
|
withSub.sort((a, b) => b.fp - a.fp);
|
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module explorer/engine/player
|
|
3
|
+
*
|
|
4
|
+
* The browser half of the scenario player on an instance (spec 0012 B3, TOPO-10; the pure core is scenario.js). `play(scenario)` puts a player on the
|
|
5
|
+
* map: it keeps the player's snapshot in `state.scenario` (scene.js lights it), shows a compact bar (title, "2 of 5 · text", previous, play or pause, next,
|
|
6
|
+
* close), answers the keyboard (space, left and right arrows), and glides the camera to the current step when that is off screen. The ROM simulation plays
|
|
7
|
+
* through here too. The bar also holds the viewer's speed: a small menu of how long a step plays (2 s, 5 s, 10 s, or Manual, which moves only on Next), kept
|
|
8
|
+
* in the viewer's browser storage and applied to the running player.
|
|
9
|
+
*
|
|
10
|
+
* Frames: the player is a frame client of the instance's map loop (`inst.map.addFrameClient`), not a timer of its own. It asks for frames only while
|
|
11
|
+
* playing or while the camera glides, so a paused or finished scenario costs nothing, a hidden tab stops the loop, and under prefers-reduced-motion the
|
|
12
|
+
* steps still change but the packet does not travel and the camera jumps.
|
|
13
|
+
*
|
|
14
|
+
* The scenario list is the review column's (pieces/changes.js): this module plays what it hands over and tells it where the player is (`onChange`, and
|
|
15
|
+
* the instance's `scenario:player` event), so the list can follow. On a phone (engine/sheets.js, TOPO-18) the bar is a bottom sheet in `#sheet-dock`: a peek
|
|
16
|
+
* (title, step counter and text) until expanded, and the camera follows a step into the part of the map the sheets leave free.
|
|
17
|
+
*
|
|
18
|
+
* The instance's events from here: `scenario:player` { id, index, total, done, playing, checks } on each change of step, play state or answer, and null when
|
|
19
|
+
* the player closes. It hears `scenario:clear` (a selection ends a playing scenario).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { escapeHtml as escHtml } from '../../core/text.js';
|
|
23
|
+
import { createPlayer, cameraFor, parseSpeed, SPEED_CHOICES, SPEED_KEY } from '../scenario.js';
|
|
24
|
+
import { blastRadius, outageLayers, outageScenario } from '../outage-model.js';
|
|
25
|
+
import { setLayer, clearStepLayers, LAYER_DEFS } from './layers.js';
|
|
26
|
+
import { externalLayer } from '../cloud-model.js';
|
|
27
|
+
import { layerOn, layersOf, projectLayerKey, shownByProposal } from '../layer-model.js';
|
|
28
|
+
import { registerSheet, unregisterSheet, collapseAllSheets, visibleMapRect, onCoveredChange } from './sheets.js';
|
|
29
|
+
import { announce } from './keyboard.js';
|
|
30
|
+
import { t } from './strings.js';
|
|
31
|
+
import { currentStepSentence } from '../scenario-list-model.js';
|
|
32
|
+
import { personaFor, personaLabel } from '../check-model.js';
|
|
33
|
+
import { addParts } from './piece.js';
|
|
34
|
+
|
|
35
|
+
/** A frame that arrives later than this (a tab that was hidden) counts as this long */
|
|
36
|
+
const MAX_FRAME_MS = 250;
|
|
37
|
+
/** How quickly the camera closes on its target: the time for it to cover about 63% of the way */
|
|
38
|
+
const GLIDE_MS = 140;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The Layers keys that hide a node, or [] when no layer does (#212). Only what Layers decides: the Flow and House views and
|
|
42
|
+
* Before or After draw their own sets, and a layer would not change them.
|
|
43
|
+
*/
|
|
44
|
+
export function layersHiding(inst, node) {
|
|
45
|
+
const { state } = inst;
|
|
46
|
+
if (!node || state.view === 'dataflow' || state.view === 'house') return [];
|
|
47
|
+
const layers = layersOf(state); // what is drawn: the viewer's layers, or the review's (layer-model.js)
|
|
48
|
+
const on = (key) => layers[key] !== false;
|
|
49
|
+
const type = node.type;
|
|
50
|
+
if (type === 'root' || shownByProposal(state, node)) return []; // a proposal's own nodes are drawn whatever their layer says (spec 0009 D3)
|
|
51
|
+
const project = projectLayerKey(state, node); // a project layer that takes the node decides alone (spec 0009 D3), as scene.js layerShows has it
|
|
52
|
+
if (project) return on(project) ? [] : [project];
|
|
53
|
+
if (type === 'core') return [...(on('core') ? [] : ['core']), ...(layers.pkg || layers.atom ? [] : ['pkg'])];
|
|
54
|
+
if (type === 'store') return ['flow', 'store'].filter((k) => !on(k));
|
|
55
|
+
if (type === 'rom') return ['rom', 'flow'].filter((k) => !on(k));
|
|
56
|
+
if (type === 'floor' || type === 'room') return on('house') ? [] : ['house'];
|
|
57
|
+
const key = type === 'external' ? externalLayer(node) : type;
|
|
58
|
+
return on(key) ? [] : [key];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The nodes a scenario's steps name: a node step's node, both ends of an edge step */
|
|
62
|
+
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] : []));
|
|
63
|
+
|
|
64
|
+
const TYPING = 'input, textarea, select, [contenteditable=""], [contenteditable="true"]';
|
|
65
|
+
const typingIn = (target) => !!(target && target.closest && target.closest(TYPING));
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The demo scenario, walked over what the loaded topology really has: from the node with the most links that are not ownership, along such links for up
|
|
69
|
+
* to three hops, never back to a node it has been at. Fewer than two steps (a map with no links) means no demo (null).
|
|
70
|
+
*/
|
|
71
|
+
export function demoScenario(nodes, edges) {
|
|
72
|
+
const ids = new Set(nodes.map((n) => n.id));
|
|
73
|
+
const label = (id) => (nodes.find((n) => n.id === id) || { label: id }).label;
|
|
74
|
+
const links = edges.filter((e) => (e.kind || e.dashed) && ids.has(e.from) && ids.has(e.to) && e.from !== e.to);
|
|
75
|
+
if (!links.length) return null;
|
|
76
|
+
const out = new Map();
|
|
77
|
+
for (const e of links) { if (!out.has(e.from)) out.set(e.from, []); out.get(e.from).push(e); }
|
|
78
|
+
const start = [...out.keys()].sort((x, y) => out.get(y).length - out.get(x).length || x.localeCompare(y))[0];
|
|
79
|
+
const steps = [{ node: start, text: `It starts at ${label(start)}.` }];
|
|
80
|
+
const seen = new Set([start]);
|
|
81
|
+
let at = start;
|
|
82
|
+
for (let hop = 0; hop < 3; hop++) {
|
|
83
|
+
const next = (out.get(at) || []).find((e) => !seen.has(e.to));
|
|
84
|
+
if (!next) break;
|
|
85
|
+
const edge = { from: next.from, to: next.to, ...(next.kind ? { kind: next.kind } : {}), ...(next.kind === 'flow' ? { flow: next.flow } : {}) };
|
|
86
|
+
steps.push({ edge, text: `${label(next.from)} ${next.label || next.kind || 'uses'} ${label(next.to)}.` });
|
|
87
|
+
steps.push({ node: next.to, text: `Now at ${label(next.to)}.` });
|
|
88
|
+
seen.add(next.to);
|
|
89
|
+
at = next.to;
|
|
90
|
+
}
|
|
91
|
+
return steps.length < 2 ? null : { id: 'demo', title: 'A walk over the map', steps };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The player of an instance.
|
|
96
|
+
* @param {ReturnType<import('../instance.js').createInstance>} inst
|
|
97
|
+
* @param {ReturnType<typeof import('./piece.js').scopeOf>} scope the piece's own end: every listener, observer and the frame client go with it
|
|
98
|
+
* @param {ReturnType<typeof import('./checks.js').createChecks>} checks
|
|
99
|
+
*/
|
|
100
|
+
export function createScenarioPlayer(inst, scope, checks) {
|
|
101
|
+
const { state } = inst;
|
|
102
|
+
let player = null;
|
|
103
|
+
let bar = null;
|
|
104
|
+
let signature = '';
|
|
105
|
+
let glide = null; // { to: {x, y, zoom}, last: nowMs|null }
|
|
106
|
+
let held = false; // the viewer took hold of the map since the step began: the camera is theirs until the next step
|
|
107
|
+
let framedFor = -1; // the player bar's height when the camera last followed the step
|
|
108
|
+
let barWatch = null; // a ResizeObserver on the bar: when it grows (a check's line arrives), the step is followed again
|
|
109
|
+
let lastFill = -1;
|
|
110
|
+
/** What had the focus when a scenario started, to give it back when the scenario closes (a control of another panel, say) */
|
|
111
|
+
let returnTo = null;
|
|
112
|
+
/** Who knows where the focus goes when the player closes: the review column's step list gives the step the player was on */
|
|
113
|
+
let closeFocus = null;
|
|
114
|
+
/** Who keeps a closed scenario's checks: the review column, while its steps are open in the list (their verdicts stay there) */
|
|
115
|
+
let keepChecksOnClose = null;
|
|
116
|
+
/** Who knows the scenario after this one, in the order the list reads: `fn(scenarioId)` gives the scenario or null */
|
|
117
|
+
let nextScenarioOf = null;
|
|
118
|
+
const listeners = new Set();
|
|
119
|
+
/** Takes the listeners off the bar's own controls when it goes */
|
|
120
|
+
let barOffs = [];
|
|
121
|
+
const notify = (snap) => { for (const fn of [...listeners]) fn(snap); inst.emit('scenario:player', snap); };
|
|
122
|
+
|
|
123
|
+
const stage = () => (state.canvas ? state.canvas.parentElement : null);
|
|
124
|
+
const render = () => inst.map.render();
|
|
125
|
+
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
// Playing
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
|
|
130
|
+
/** What had the focus when a scenario started: not the player, not the review column, not the map */
|
|
131
|
+
function openerOf() {
|
|
132
|
+
const active = inst.active();
|
|
133
|
+
if (active && active !== inst.doc.body && !active.closest?.('.hx-player') && !active.closest?.('#review-column') && active !== state.canvas) return active;
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Whether the focus is on the page's controls (not on nothing, and not in a field): a scenario started by a script from outside takes none */
|
|
138
|
+
function isKeyboardish() {
|
|
139
|
+
const active = inst.active();
|
|
140
|
+
return !!active && active !== inst.doc.body && !typingIn(active);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** 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 */
|
|
144
|
+
function giveFocusBack() {
|
|
145
|
+
const to = returnTo;
|
|
146
|
+
returnTo = null;
|
|
147
|
+
const took = (el) => {
|
|
148
|
+
if (!el || !el.isConnected || el.hidden || el.disabled || el.closest('[hidden]')) return false;
|
|
149
|
+
el.focus();
|
|
150
|
+
return inst.active() === el; // a control the stylesheet hides takes no focus
|
|
151
|
+
};
|
|
152
|
+
if (took(closeFocus && closeFocus()) || took(to)) return;
|
|
153
|
+
took(state.canvas);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* An outage scenario (spec 0031 section 8) turns on the layers its blast radius is drawn on (containers and machines start off), as a scenario that
|
|
158
|
+
* names a persona turns the People layer on (checks.js).
|
|
159
|
+
*/
|
|
160
|
+
function showOutageLayers(scenario) {
|
|
161
|
+
if (!scenario || !Array.isArray(scenario.down) || !scenario.down.length) return;
|
|
162
|
+
outageLayers(blastRadius(scenario.down, state.nodes, state.edges), state.nodes)
|
|
163
|
+
.forEach((key) => { if (!layerOn(state, key)) setLayer(inst, key, true, { scenario: true }); });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 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
|
|
168
|
+
* its steps are drawn on, as an outage turns on what it hits, and says which.
|
|
169
|
+
*/
|
|
170
|
+
function showStepLayers(scenario) {
|
|
171
|
+
const byId = new Map(state.nodes.map((n) => [n.id, n]));
|
|
172
|
+
const keys = [];
|
|
173
|
+
for (const id of stepNodeIds(scenario)) for (const key of layersHiding(inst, byId.get(id))) if (!keys.includes(key)) keys.push(key);
|
|
174
|
+
if (!keys.length) return;
|
|
175
|
+
for (const key of keys) setLayer(inst, key, true, { scenario: true }); // on, for the review too (state.review.step): stopping the scenario takes it off again
|
|
176
|
+
const names = keys.map((key) => (LAYER_DEFS.find((l) => l.key === key) || (state.projectLayers || []).find((l) => l.key === key) || { label: key }).label);
|
|
177
|
+
announce(inst, `Turned on ${names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` : names[0]} to show this scenario's steps.`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Plays a scenario on the map, replacing any that is playing.
|
|
182
|
+
* @param {object} scenario
|
|
183
|
+
* @param {{ autoplay?: boolean, stepMs?: number | 'manual', step?: number, focus?: boolean }} [opts] `autoplay` false opens it paused on the first step;
|
|
184
|
+
* `step` opens it on that step (paused); `stepMs` is a speed for this scenario in place of the viewer's saved one;
|
|
185
|
+
* `focus` false leaves the keyboard focus where it is (the review column's step list keeps it)
|
|
186
|
+
* @returns {ReturnType<typeof createPlayer>} the player, for a caller that wants to drive it
|
|
187
|
+
*/
|
|
188
|
+
function play(scenario, opts = {}) {
|
|
189
|
+
const opener = openerOf();
|
|
190
|
+
const takeFocus = isKeyboardish() && opts.focus !== false; // checked now: whatever was pressed may go with the markup
|
|
191
|
+
clear({ keepChecks: true });
|
|
192
|
+
returnTo = opener;
|
|
193
|
+
const speed = opts.stepMs ?? readSpeed();
|
|
194
|
+
player = createPlayer(scenario, { stepMs: speed, maxFrameMs: MAX_FRAME_MS });
|
|
195
|
+
if (Number.isFinite(opts.step) && opts.step > 0) player.goTo(opts.step);
|
|
196
|
+
showBar(speed);
|
|
197
|
+
checks.open(scenario, () => { sync(); render(); }); // PHY-10: one batch of permission checks for the scenario (checks.js); the same scenario already open in the list keeps its answers
|
|
198
|
+
showOutageLayers(scenario);
|
|
199
|
+
showStepLayers(scenario);
|
|
200
|
+
if (opts.autoplay !== false && !(opts.step > 0)) player.play();
|
|
201
|
+
sync(true);
|
|
202
|
+
render();
|
|
203
|
+
inst.map.ensureFlowLoop();
|
|
204
|
+
// Whatever started it may be gone: focus goes to the player's play and pause button, the first control of what opened
|
|
205
|
+
if (takeFocus && bar) {
|
|
206
|
+
const toggle = bar.querySelector('[data-action=scenario-toggle]');
|
|
207
|
+
if (toggle && !toggle.disabled) toggle.focus(); else bar.querySelector('[data-action=scenario-next]')?.focus();
|
|
208
|
+
}
|
|
209
|
+
return player;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** The cloud panel's Play button (CLOUD-07): plays "X is down" for a cloud node, generated from the map (outage-model.js) */
|
|
213
|
+
function playOutage(id) {
|
|
214
|
+
const node = state.nodes.find((n) => n.id === id);
|
|
215
|
+
if (!node || node.type !== 'external' || node.kind !== 'cloud') return null;
|
|
216
|
+
return play(outageScenario(node, state.nodes, state.edges));
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** 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 */
|
|
220
|
+
function clear({ keepChecks = false, closing = false } = {}) {
|
|
221
|
+
const had = !!player || !!state.scenario;
|
|
222
|
+
if (had) clearStepLayers(inst); // the layers this scenario turned on for a review go off with it: the focused view comes back
|
|
223
|
+
player = null;
|
|
224
|
+
glide = null;
|
|
225
|
+
signature = '';
|
|
226
|
+
state.scenario = null;
|
|
227
|
+
if (!keepChecks) checks.close();
|
|
228
|
+
if (barWatch) { barWatch.disconnect(); barWatch = null; }
|
|
229
|
+
if (bar) { unregisterSheet(inst, 'player'); barOffs.forEach((off) => off()); barOffs = []; checks.unmount(); bar.remove(); bar = null; }
|
|
230
|
+
if (had && (!keepChecks || closing)) notify(null);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Ends the scenario and redraws the map without it */
|
|
234
|
+
function stop() {
|
|
235
|
+
if (!player && !state.scenario) return;
|
|
236
|
+
const active = inst.active();
|
|
237
|
+
const hadFocus = (!!bar && bar.contains(active)) || !!active?.closest?.('#review-column'); // in the player, or in the list that follows it
|
|
238
|
+
const keep = !!player && !!keepChecksOnClose && keepChecksOnClose(player.scenario().id); // the list still shows its steps: their verdicts stay
|
|
239
|
+
clear({ keepChecks: keep, closing: true });
|
|
240
|
+
inst.touchScene();
|
|
241
|
+
render();
|
|
242
|
+
const now = inst.active();
|
|
243
|
+
if (hadFocus || !now || now === inst.doc.body) giveFocusBack(); // focus was in the player, which is gone: it goes to the step the player was on
|
|
244
|
+
else returnTo = null;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Brings `state.scenario` up to date with the player; when a step, the play state or the step start moved, rebuilds the scene and follows the step with the camera */
|
|
248
|
+
function sync(force = false) {
|
|
249
|
+
if (!player) return false;
|
|
250
|
+
const snap = checks.decorate(player.snapshot(), player.scenario());
|
|
251
|
+
state.scenario = snap;
|
|
252
|
+
const next = `${snap.index}|${snap.playing}|${snap.done}|${snap.stepStartMs}|${snap.stepMs}|${snap.manual}|${checks.version()}`;
|
|
253
|
+
const changed = force || next !== signature;
|
|
254
|
+
if (changed) {
|
|
255
|
+
const stepChanged = force || next.split('|')[0] !== signature.split('|')[0];
|
|
256
|
+
signature = next;
|
|
257
|
+
inst.touchScene();
|
|
258
|
+
if (stepChanged) { held = false; followStep(snap); }
|
|
259
|
+
}
|
|
260
|
+
updateBar(snap);
|
|
261
|
+
if (changed) notify({ id: snap.id, index: snap.index, total: snap.total, done: snap.done, playing: snap.playing, checks: checks.version() });
|
|
262
|
+
return changed;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ---------------------------------------------------------------------------
|
|
266
|
+
// The camera follows the step
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
function followStep(snap) {
|
|
269
|
+
const visible = new Map();
|
|
270
|
+
state.nodes.forEach((n) => { if (inst.map.isNodeVisible(n)) visible.set(n.id, n); });
|
|
271
|
+
// 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
|
|
272
|
+
const rect = visibleMapRect(inst);
|
|
273
|
+
framedFor = bar ? bar.offsetHeight : 0;
|
|
274
|
+
const target = cameraFor({ node: snap.current.node, edge: snap.current.edge, at: snap.current.at, text: snap.current.text }, state.camera, rect, visible, 60, inst.map.getMinZoom());
|
|
275
|
+
if (!target) return;
|
|
276
|
+
if (inst.reducedMotion) { Object.assign(state.camera, target); glide = null; render(); return; } // reduced motion: jump, do not fly
|
|
277
|
+
glide = { to: target, last: null };
|
|
278
|
+
inst.map.ensureFlowLoop();
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function stepGlide(now) {
|
|
282
|
+
if (!glide) return;
|
|
283
|
+
const dt = glide.last === null ? 16 : Math.min(now - glide.last, 100);
|
|
284
|
+
glide.last = now;
|
|
285
|
+
const k = 1 - Math.exp(-dt / GLIDE_MS);
|
|
286
|
+
const cam = state.camera;
|
|
287
|
+
cam.x += (glide.to.x - cam.x) * k;
|
|
288
|
+
cam.y += (glide.to.y - cam.y) * k;
|
|
289
|
+
cam.zoom += (glide.to.zoom - cam.zoom) * k;
|
|
290
|
+
if (Math.abs(glide.to.x - cam.x) < 0.5 && Math.abs(glide.to.y - cam.y) < 0.5 && Math.abs(glide.to.zoom - cam.zoom) < 0.002) {
|
|
291
|
+
Object.assign(cam, glide.to);
|
|
292
|
+
glide = null;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Whether the player needs frames: while it plays or the camera glides; never when paused, done or closed */
|
|
297
|
+
const wantsFrames = () => !!player && (player.isPlaying() || !!glide);
|
|
298
|
+
|
|
299
|
+
/** What the frame loop calls every frame with its clock (exported so a test can be the loop) */
|
|
300
|
+
function tick(now) {
|
|
301
|
+
if (!player) return;
|
|
302
|
+
player.tick(now);
|
|
303
|
+
sync();
|
|
304
|
+
stepGlide(now);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
scope.own(inst.map.addFrameClient({ wants: wantsFrames, tick }));
|
|
308
|
+
|
|
309
|
+
// ---------------------------------------------------------------------------
|
|
310
|
+
// The bar
|
|
311
|
+
// ---------------------------------------------------------------------------
|
|
312
|
+
function showBar(speed) {
|
|
313
|
+
const area = stage();
|
|
314
|
+
if (!area) return;
|
|
315
|
+
bar = inst.doc.createElement('div');
|
|
316
|
+
bar.className = 'hx-player glass';
|
|
317
|
+
bar.dataset.corn = 'scenario-player';
|
|
318
|
+
bar.setAttribute('part', 'scenario-player');
|
|
319
|
+
bar.setAttribute('role', 'region');
|
|
320
|
+
bar.setAttribute('aria-label', 'Scenario player');
|
|
321
|
+
// One bar (spec 0006 D6): Previous, Pause or Play, Next; "2 of 4 · As Adult · the step's text · Allowed"; the speed and Close.
|
|
322
|
+
// 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.
|
|
323
|
+
bar.innerHTML = `
|
|
324
|
+
<span class="hx-player-title hx-sr-only"></span>
|
|
325
|
+
<div class="hx-player-controls" role="group">
|
|
326
|
+
<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>
|
|
327
|
+
<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>
|
|
328
|
+
<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>
|
|
329
|
+
<button data-corn-kind="secondary" type="button" class="hx-btn hx-player-next-scenario" data-action="scenario-next-scenario" data-peek-ok hidden></button>
|
|
330
|
+
</div>
|
|
331
|
+
<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>
|
|
332
|
+
<span class="hx-player-says hx-sr-only" role="status" aria-live="polite"></span>
|
|
333
|
+
<div class="hx-player-side">
|
|
334
|
+
<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="${escHtml(String(c.value))}">${escHtml(c.label)}</option>`).join('')}</select>
|
|
335
|
+
<button type="button" class="hx-close" data-action="scenario-close" aria-label="Close the scenario" data-corn-kind="icon">✕</button>
|
|
336
|
+
</div>
|
|
337
|
+
<div class="hx-player-track" data-corn="scenario-track" aria-hidden="true"><span class="hx-player-fill" data-corn="scenario-fill"></span></div>`;
|
|
338
|
+
addParts(bar);
|
|
339
|
+
bar.querySelector('.hx-player-controls').setAttribute('aria-label', t(inst, 'steps'));
|
|
340
|
+
bar.querySelector('.hx-player-prev .hx-player-label').textContent = t(inst, 'previousStep');
|
|
341
|
+
bar.querySelector('.hx-player-next .hx-player-label').textContent = t(inst, 'nextStep');
|
|
342
|
+
bar.querySelector('.hx-player-next-scenario').textContent = t(inst, 'nextScenario');
|
|
343
|
+
const onBarClick = (e) => {
|
|
344
|
+
const button = e.target.closest('[data-action]');
|
|
345
|
+
if (button) act(button.dataset.action);
|
|
346
|
+
};
|
|
347
|
+
const menu = bar.querySelector('.hx-player-speed');
|
|
348
|
+
const onSpeed = (e) => chooseSpeed(e.target.value);
|
|
349
|
+
const here = bar;
|
|
350
|
+
here.addEventListener('click', onBarClick);
|
|
351
|
+
menu.value = String(speed);
|
|
352
|
+
menu.addEventListener('change', onSpeed);
|
|
353
|
+
barOffs.push(() => { here.removeEventListener('click', onBarClick); menu.removeEventListener('change', onSpeed); });
|
|
354
|
+
// 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
|
|
355
|
+
const dock = inst.el('sheet-dock');
|
|
356
|
+
const drawer = inst.el('spec-drawer');
|
|
357
|
+
if (dock && drawer && drawer.parentElement === dock) dock.insertBefore(bar, drawer);
|
|
358
|
+
else (dock || area).appendChild(bar);
|
|
359
|
+
registerSheet(inst, 'player', bar);
|
|
360
|
+
collapseAllSheets(inst);
|
|
361
|
+
// 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
|
|
362
|
+
const RO = inst.win && inst.win.ResizeObserver;
|
|
363
|
+
if (typeof RO === 'function') {
|
|
364
|
+
barWatch = new RO(() => { if (bar && player && state.scenario && !held && bar.offsetHeight !== framedFor) followStep(player.snapshot()); });
|
|
365
|
+
barWatch.observe(bar);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// The viewer's speed: a setting of theirs, kept for the next scenario and the next visit
|
|
370
|
+
const readSpeed = () => parseSpeed(inst.store.get(SPEED_KEY));
|
|
371
|
+
|
|
372
|
+
function chooseSpeed(value) {
|
|
373
|
+
const speed = parseSpeed(value);
|
|
374
|
+
inst.store.set(SPEED_KEY, String(speed));
|
|
375
|
+
if (!player) return;
|
|
376
|
+
player.setSpeed(speed);
|
|
377
|
+
sync();
|
|
378
|
+
render();
|
|
379
|
+
inst.map.ensureFlowLoop();
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** One place for what the bar's buttons and the keys do */
|
|
383
|
+
function act(action) {
|
|
384
|
+
if (!player) return;
|
|
385
|
+
if (action === 'scenario-close') return stop();
|
|
386
|
+
if (action === 'scenario-next-scenario') {
|
|
387
|
+
// 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
|
|
388
|
+
const next = nextScenarioOf ? nextScenarioOf(player.scenario().id) : null;
|
|
389
|
+
if (next) play(next);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (action === 'scenario-toggle') {
|
|
393
|
+
const s = player.snapshot();
|
|
394
|
+
if (s.playing) player.pause(); else player.play();
|
|
395
|
+
announce(inst, s.playing ? 'Paused' : s.done ? 'Playing again' : s.index > 0 || s.progress > 0 ? 'Resumed' : 'Playing');
|
|
396
|
+
} else if (action === 'scenario-prev') player.prev();
|
|
397
|
+
else if (action === 'scenario-next') player.next();
|
|
398
|
+
else return;
|
|
399
|
+
sync();
|
|
400
|
+
render();
|
|
401
|
+
inst.map.ensureFlowLoop();
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function updateBar(snap) {
|
|
405
|
+
if (!bar) return;
|
|
406
|
+
const q = (cls) => bar.querySelector(cls);
|
|
407
|
+
// this runs every frame: a live region is written only when its words change, so a step is said once, not once a frame
|
|
408
|
+
const put = (cls, text) => { const el = q(cls); if (el.textContent !== text) el.textContent = text; };
|
|
409
|
+
put('.hx-player-title', snap.title);
|
|
410
|
+
bar.setAttribute('aria-label', `Scenario player: ${snap.title}`);
|
|
411
|
+
put('.hx-player-count', `${Math.min(snap.index + 1, Math.max(snap.total, 1))} of ${snap.total}`);
|
|
412
|
+
const actor = snap.current.actor ? personaLabel(personaFor(state.nodes, snap.current.actor)) || snap.current.actor : '';
|
|
413
|
+
put('.hx-player-who', actor && !snap.done ? `As ${actor} · ` : '');
|
|
414
|
+
put('.hx-player-step', snap.done ? 'Played to the end' : snap.current.text);
|
|
415
|
+
bar.dataset.done = String(!!snap.done);
|
|
416
|
+
const toggle = q('[data-action=scenario-toggle]');
|
|
417
|
+
const label = snap.playing ? t(inst, 'pause') : snap.done ? t(inst, 'playAgain') : t(inst, 'play');
|
|
418
|
+
put('[data-action=scenario-toggle] .hx-player-label', label);
|
|
419
|
+
toggle.dataset.state = snap.playing ? 'playing' : snap.done ? 'done' : 'paused';
|
|
420
|
+
toggle.disabled = snap.total === 0 || snap.manual;
|
|
421
|
+
toggle.title = snap.manual ? 'The time for each step is Manual: use Next' : '';
|
|
422
|
+
q('[data-action=scenario-prev]').disabled = snap.index === 0 && !snap.done;
|
|
423
|
+
const next = q('[data-action=scenario-next]');
|
|
424
|
+
next.disabled = snap.done || snap.total === 0;
|
|
425
|
+
// at the end: Play again and Next scenario (the next one in the list's order); nothing carries on by itself
|
|
426
|
+
const following = snap.done && nextScenarioOf ? nextScenarioOf(snap.id) : null;
|
|
427
|
+
q('[data-action=scenario-next-scenario]').hidden = !following;
|
|
428
|
+
next.hidden = !!following;
|
|
429
|
+
// the one polite line: a step as the list says it ("Step 2 of 3, as Adult: checkout page, Added. You pay. Allowed.")
|
|
430
|
+
put('.hx-player-says', snap.done ? `${snap.title}: played to the end.` : currentStepSentence({ snap, nodes: state.nodes, edges: state.edges, words: { notChecked: t(inst, 'notChecked') } }));
|
|
431
|
+
const fill = snap.total ? Math.round(((snap.done ? snap.total : snap.index + snap.progress) / snap.total) * 1000) / 10 : 0;
|
|
432
|
+
if (fill !== lastFill) { lastFill = fill; q('.hx-player-fill').style.width = `${fill}%`; }
|
|
433
|
+
checks.paint(bar, snap);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// ---------------------------------------------------------------------------
|
|
437
|
+
// Keyboard: space plays and pauses, left and right step; never while typing
|
|
438
|
+
// ---------------------------------------------------------------------------
|
|
439
|
+
/** A menu or dialog that has its own Escape: the layers menu, the toolbar's ⋯ menu, a dialog */
|
|
440
|
+
function otherPopupOpen() {
|
|
441
|
+
return !!inst.root.querySelector('#legend-dropdown:not([hidden]), #proposal-more-menu:not([hidden]), [data-corn="dialog-scrim"]:not([hidden]), .hx-mockup-dialog');
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
scope.listen(inst.root, 'keydown', (e) => {
|
|
445
|
+
if (e.key === 'Escape' && !e.defaultPrevented && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
|
446
|
+
if (player && !typingIn(e.target) && !otherPopupOpen()) { e.preventDefault(); stop(); return; } // Escape closes the scenario; focus goes back to Play
|
|
447
|
+
}
|
|
448
|
+
if (!player || e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey || typingIn(e.target)) return;
|
|
449
|
+
if ((e.key === ' ' || e.code === 'Space') && e.target.closest?.('#review-column')) return; // Space on a step or a row presses it
|
|
450
|
+
const action = e.key === ' ' || e.code === 'Space' ? 'scenario-toggle' : e.key === 'ArrowLeft' ? 'scenario-prev' : e.key === 'ArrowRight' ? 'scenario-next' : null;
|
|
451
|
+
if (!action) return;
|
|
452
|
+
e.preventDefault(); // space on a focused button would press it as well
|
|
453
|
+
act(action);
|
|
454
|
+
});
|
|
455
|
+
// Some browsers press a focused button on the key's release, so a space the player took must not reach it
|
|
456
|
+
scope.listen(inst.root, 'keyup', (e) => {
|
|
457
|
+
if (player && (e.key === ' ' || e.code === 'Space') && !typingIn(e.target)) e.preventDefault();
|
|
458
|
+
});
|
|
459
|
+
// A sheet that opened or closed changes what the map shows: keep the step in view
|
|
460
|
+
scope.own(onCoveredChange(inst, () => { if (player && state.scenario) followStep(player.snapshot()); }));
|
|
461
|
+
// Taking hold of the map (a drag, the wheel, a pinch) ends the camera's glide: the camera is theirs
|
|
462
|
+
for (const type of ['pointerdown', 'wheel', 'touchstart', 'mousedown']) scope.listen(inst.root, type, (e) => { if (e.target === state.canvas) { glide = null; held = true; } }, { passive: true, capture: true });
|
|
463
|
+
scope.on('scenario:clear', () => clear());
|
|
464
|
+
scope.own(() => { clear({ keepChecks: false }); listeners.clear(); });
|
|
465
|
+
|
|
466
|
+
return {
|
|
467
|
+
play,
|
|
468
|
+
stop,
|
|
469
|
+
clear,
|
|
470
|
+
tick,
|
|
471
|
+
playOutage,
|
|
472
|
+
getPlayer: () => player,
|
|
473
|
+
bar: () => bar,
|
|
474
|
+
wantsFrames,
|
|
475
|
+
/** Calls `fn(snapshot)` on each change of the player: the step it is on (null when closed), whether it reached the end. Returns how to stop. */
|
|
476
|
+
onChange(fn) { listeners.add(fn); return () => listeners.delete(fn); },
|
|
477
|
+
setCloseFocus(fn) { closeFocus = typeof fn === 'function' ? fn : null; },
|
|
478
|
+
setNextScenario(fn) { nextScenarioOf = typeof fn === 'function' ? fn : null; },
|
|
479
|
+
setKeepChecksOnClose(fn) { keepChecksOnClose = typeof fn === 'function' ? fn : null; },
|
|
480
|
+
/** Starts the demo when the page was opened with `?scenario-demo=1` (the page says so: `asked`; call it once the topology is loaded) */
|
|
481
|
+
demo(asked = true) {
|
|
482
|
+
if (!asked) return false;
|
|
483
|
+
const scenario = demoScenario(state.nodes, state.edges);
|
|
484
|
+
if (!scenario) { console.warn('scenario-demo: the map has none of the nodes the demo walks over'); return false; }
|
|
485
|
+
play(scenario);
|
|
486
|
+
return true;
|
|
487
|
+
},
|
|
488
|
+
};
|
|
489
|
+
}
|