@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
@@ -0,0 +1,142 @@
1
+ /**
2
+ * @module explorer/engine/piece
3
+ *
4
+ * What every piece of the explorer (explorer/pieces/) does the same way (spec 0011 D3):
5
+ *
6
+ * scopeOf(inst) the piece's own end: `listen`, `on`, `timer`, `own` as the instance's, and `destroy()` which takes back every one of them
7
+ * (the instance's own `destroy()` runs it too, if the piece is still there)
8
+ * place(inst, root, html, slots, slot) makes the piece's elements from `html` and puts them where the host says: before the node `slots[slot]` if
9
+ * it is given (cornfield's page leaves a marker comment where each goes), else at the end of `root`; returns the
10
+ * elements, which the piece removes on `destroy`. A stand-in the host's markup keeps before the marker for the
11
+ * first paint (`<!--corn-placeholder:NAME/SLOT-->` and the piece's markup without ids) goes when the piece comes.
12
+ * The markup speaks in the instance's words (`inst.strings`) from the start
13
+ * withParts(html) every hook of the markup also gets a `part` of the same name, so a host's stylesheet can reach it
14
+ * from outside a shadow root (`::part(row)`)
15
+ */
16
+
17
+ import { applyStrings } from './strings.js';
18
+
19
+ const HOOK = new RegExp('\\sdata-corn=\\"([^\\"]+)\\"');
20
+ /** An element's data-corn hook is also its part, of the same name (and an element that has a part already keeps it) */
21
+ export function withParts(html) {
22
+ return String(html).replace(/<[a-zA-Z][^<>]*>/g, (tag) => (/\spart=/.test(tag) ? tag : tag.replace(HOOK, (_all, hook) => ` data-corn=\"${hook}\" part=\"${hook}\"`)));
23
+ }
24
+
25
+ /** Gives every element under `el` that has a hook and no part the part of the same name */
26
+ export function addParts(el) {
27
+ for (const x of el.querySelectorAll('[data-corn]:not([part])')) x.setAttribute('part', x.getAttribute('data-corn'));
28
+ }
29
+
30
+ /**
31
+ * A piece's own end.
32
+ * @param {ReturnType<import('../instance.js').createInstance>} inst
33
+ */
34
+ export function scopeOf(inst) {
35
+ const offs = [];
36
+ let done = false;
37
+ const scope = {
38
+ /** Adds a listener; `destroy()` removes it */
39
+ listen(target, type, listener, options) {
40
+ const off = inst.listen(target, type, listener, options);
41
+ offs.push(off);
42
+ return off;
43
+ },
44
+ /** Hears an event of the instance; `destroy()` stops it */
45
+ on(name, fn) {
46
+ const off = inst.on(name, fn);
47
+ offs.push(off);
48
+ return off;
49
+ },
50
+ /** Runs `fn` when the piece ends (a timer's clear, an observer's disconnect); returns `fn` */
51
+ own(fn) {
52
+ offs.push(fn);
53
+ return fn;
54
+ },
55
+ /** A timeout that does not outlive the piece: `destroy()` clears it */
56
+ timeout(fn, ms) {
57
+ const id = setTimeout(() => { fn(); }, ms);
58
+ offs.push(() => clearTimeout(id));
59
+ return id;
60
+ },
61
+ /** Keeps the parts right in `els` as markup is put in them later (the panel's sections, a legend another module fills): a hook gets its part */
62
+ keepParts(...els) {
63
+ const MO = inst.win && inst.win.MutationObserver;
64
+ if (!MO) return;
65
+ const mo = new MO((list) => {
66
+ for (const m of list) {
67
+ for (const n of m.addedNodes) {
68
+ if (n.nodeType !== 1) continue;
69
+ if (n.hasAttribute('data-corn') && !n.hasAttribute('part')) n.setAttribute('part', n.getAttribute('data-corn'));
70
+ addParts(n);
71
+ }
72
+ }
73
+ });
74
+ for (const el of els) mo.observe(el, { childList: true, subtree: true });
75
+ offs.push(() => mo.disconnect());
76
+ },
77
+ /** Ends the piece's part of the instance: runs every clean-up, last first. Safe to call twice. */
78
+ destroy() {
79
+ if (done) return;
80
+ done = true;
81
+ inst.release(scope.destroy);
82
+ while (offs.length) {
83
+ try { offs.pop()(); } catch (err) { console.error('A piece clean-up failed', err); }
84
+ }
85
+ },
86
+ };
87
+ inst.own(scope.destroy);
88
+ return scope;
89
+ }
90
+
91
+ /**
92
+ * Makes elements from `html` and puts them in place. Returns them (the piece removes each on `destroy`).
93
+ * @param {{ doc: Document | null }} inst
94
+ * @param {ParentNode} root where the elements go when the host names no place
95
+ * @param {string} html the markup (it gets its parts)
96
+ * @param {Record<string, Node | null | undefined> | undefined} slots the host's places by name: the node an element goes before
97
+ * @param {string} [slot] this markup's place
98
+ */
99
+ export function place(inst, root, html, slots, slot) {
100
+ const template = inst.doc.createElement('template');
101
+ template.innerHTML = withParts(html);
102
+ applyStrings(inst, template.content); // the instance's own words, where its host overrides one (`data-corn-string`): a host need not apply them after
103
+ const made = [...template.content.children];
104
+ const marker = slots && slot ? slots[slot] : null;
105
+ if (marker && marker.parentNode) {
106
+ const stand = standInBefore(marker);
107
+ marker.parentNode.insertBefore(template.content, marker);
108
+ if (stand) takeOver(inst, stand, made);
109
+ } else root.append(template.content);
110
+ return made;
111
+ }
112
+
113
+ /**
114
+ * The stand-in a host's static markup may hold for a piece, so the first paint has it before any script runs (cornfield's header: the
115
+ * Layers chip and the search field). It is the piece's markup without ids, between `<!--corn-placeholder:NAME/SLOT-->` and the piece's
116
+ * own marker, and goes when the piece comes. Returns its nodes, or null when there is none.
117
+ * @param {Node} marker
118
+ */
119
+ function standInBefore(marker) {
120
+ const nodes = [];
121
+ const open = `corn-placeholder:${String(marker.data || '').replace(/^corn-piece:/, '')}`;
122
+ for (let n = marker.previousSibling; n; n = n.previousSibling) {
123
+ nodes.push(n);
124
+ if (n.nodeType === 8 && n.data === open) return nodes;
125
+ }
126
+ return null;
127
+ }
128
+
129
+ /** The piece takes the stand-in's place: what was typed in it and the focus carry over to the same control of the piece, and the stand-in goes */
130
+ function takeOver(inst, stand, made) {
131
+ const controls = (els) => els.flatMap((el) => (el.nodeType === 1 ? [...(el.matches('button, input') ? [el] : []), ...el.querySelectorAll('button, input')] : []));
132
+ const before = controls(stand.slice().reverse());
133
+ const after = controls(made);
134
+ const active = inst.active();
135
+ before.forEach((el, i) => {
136
+ const next = after[i];
137
+ if (!next || next.tagName !== el.tagName) return;
138
+ if (el.tagName === 'INPUT' && el.value) next.value = el.value;
139
+ if (el === active) next.focus();
140
+ });
141
+ stand.forEach((n) => n.remove());
142
+ }
@@ -0,0 +1,331 @@
1
+ /**
2
+ * @module explorer/engine/render
3
+ *
4
+ * The map of one instance (spec 0011 D2): the camera (fit, zoom, screen to world), the scene cache and the loop that animates flow
5
+ * packets. What is drawn is decided by scene.js (buildScene); how it is drawn is the renderer's (renderer-webgl.js or
6
+ * renderer-canvas2d.js). `createMap(inst)` hands the one to the other: `map.render()` draws the cached scene with the current camera
7
+ * and time. Everything that used to be a module-level singleton (the renderer, the label layer, the frame loop, the frame clients, the
8
+ * caches) is made here, once per instance, and released by `map.destroy()` (also run by `inst.destroy()`).
9
+ *
10
+ * It reads the instance and nothing global: the state is `inst.state`, the canvas is `inst.state.canvas` (the page shell finds it
11
+ * inside the instance's root), activity is watched on the root, and the size by a ResizeObserver on the canvas's box.
12
+ */
13
+
14
+ import { buildScene, createSceneCache, getActiveSubgraph as activeSubgraph, isNodeVisible as nodeVisible } from '../scene.js';
15
+ import { createCanvas2dRenderer } from '../renderer-canvas2d.js';
16
+ import { createSpatialCache } from '../spatial.js';
17
+ import { createFrameScheduler, packetsOnScreen } from '../frame.js';
18
+ import { createLabelLayer } from '../labels.js';
19
+ import { mapStyleOf } from './map-style.js';
20
+ import { ZOOM_MIN, ZOOM_FLOOR } from '../camera.js';
21
+
22
+ /** What keeps a visitor "there": after 30 s without one of these the packets stop (frame.js) */
23
+ const ACTIVITY = ['pointerdown', 'pointermove', 'mousedown', 'mousemove', 'wheel', 'touchstart', 'touchmove', 'keydown'];
24
+
25
+ /**
26
+ * @param {ReturnType<typeof import('../instance.js').createInstance>} inst
27
+ * @param {{ measureCovered?: () => number }} [opts] (used by the call that makes the map) `measureCovered`: the height of the bottom of the map the phone's sheets cover (sheets.js); default what `state.coveredBottom` holds
28
+ */
29
+ export function createMap(inst, opts = {}) {
30
+ // One map per instance: a module that is not yet converted registers with it as it loads (fly.js adds its frame client), before the page shell
31
+ // runs, so a second call finds the map the first made
32
+ if (inst.map) return inst.map;
33
+ const { state } = inst;
34
+ const measureCovered = opts.measureCovered || (() => state.coveredBottom || 0);
35
+ const mapStyle = mapStyleOf(inst).get; // looked up once: a renderer and the labels call it on every draw
36
+ /** The map has ended (destroy): nothing draws, nothing asks for a frame, no renderer is made again, whoever calls */
37
+ let ended = false;
38
+
39
+ // -------------------------------------------------------------------------
40
+ // Visibility and focus (decided in scene.js)
41
+ // -------------------------------------------------------------------------
42
+ const isNodeVisible = (node) => nodeVisible(state, node);
43
+ /** Whether the viewer's own layers show the node, whatever a review has hidden (what-if's list of the other end of an edge) */
44
+ const isNodeVisibleToViewer = (node) => nodeVisible(state, node, { viewer: true });
45
+
46
+ /** The focus subgraph: the selected node and every node one edge away (selection-model.js); the switch and the kind come from the state */
47
+ const getActiveSubgraph = (selected, edges = inst.viewEdges(), o = { throughChildren: !!state.throughChildren, kind: state.selectedKind || null }) => activeSubgraph(selected, edges, o);
48
+
49
+ // -------------------------------------------------------------------------
50
+ // Scene and renderer
51
+ // -------------------------------------------------------------------------
52
+ const sceneCache = createSceneCache((st) => buildScene(st, { reduceMotion: inst.reducedMotion }));
53
+ /** The scene for the current state, rebuilt only when `state.sceneVersion` changed */
54
+ const getScene = () => sceneCache.get(state);
55
+ /** How many times the scene has been built so far (for tests and the bench) */
56
+ const sceneBuilds = () => sceneCache.builds;
57
+
58
+ const spatialCache = createSpatialCache();
59
+ /** The grid over the current scene's nodes (spatial.js), rebuilt only when the scene is: for hover, click and drag */
60
+ const getSpatialIndex = () => spatialCache.get(getScene());
61
+ /** How many times the grid was built so far (for tests and the bench) */
62
+ const spatialBuilds = () => spatialCache.builds;
63
+
64
+ let renderer = null;
65
+ let rendererCanvas = null;
66
+
67
+ /** The renderer drawing `state.canvas`: Canvas 2D unless another was handed to setRenderer */
68
+ function getRenderer() {
69
+ if (!renderer || rendererCanvas !== state.canvas) {
70
+ if (renderer) renderer.destroy();
71
+ renderer = createCanvas2dRenderer(state.canvas, { mapStyle });
72
+ rendererCanvas = state.canvas;
73
+ if (state.width) renderer.resize(state.width, state.height, inst.dpr());
74
+ }
75
+ return renderer;
76
+ }
77
+
78
+ let labelLayer = null;
79
+ let labelLayerCanvas = null;
80
+
81
+ /** The label layer on `state.labelCanvas` (labels.js), or null when the page has none */
82
+ function getLabelLayer() {
83
+ if (!state.labelCanvas) return null;
84
+ if (!labelLayer || labelLayerCanvas !== state.labelCanvas) {
85
+ if (labelLayer) labelLayer.destroy();
86
+ labelLayer = createLabelLayer(state.labelCanvas, { mapStyle });
87
+ labelLayerCanvas = state.labelCanvas;
88
+ if (state.width) labelLayer.resize(state.width, state.height, inst.dpr());
89
+ }
90
+ return labelLayer;
91
+ }
92
+
93
+ /** Swaps the renderer (see scene.js for the contract) and draws with it */
94
+ function setRenderer(next) {
95
+ if (renderer && renderer !== next) renderer.destroy();
96
+ renderer = next;
97
+ rendererCanvas = state.canvas;
98
+ if (state.width) renderer.resize(state.width, state.height, inst.dpr());
99
+ render();
100
+ }
101
+
102
+ // -------------------------------------------------------------------------
103
+ // Camera
104
+ // -------------------------------------------------------------------------
105
+ function resize() {
106
+ const { canvas } = state;
107
+ state.width = canvas.parentElement.clientWidth;
108
+ state.height = canvas.parentElement.clientHeight;
109
+ getRenderer().resize(state.width, state.height, inst.dpr());
110
+ const labels = getLabelLayer();
111
+ if (labels) labels.resize(state.width, state.height, inst.dpr());
112
+ render();
113
+ }
114
+
115
+ /**
116
+ * Draws again when the map's box changes size (in place of a listener on the window): a ResizeObserver on the canvas's parent. The first
117
+ * report, which every observer makes on `observe`, is skipped when the size is already the one the map has.
118
+ */
119
+ function watchSize() {
120
+ const box = state.canvas && state.canvas.parentElement;
121
+ const Observer = inst.win && inst.win.ResizeObserver;
122
+ if (!box || !Observer) return () => {};
123
+ const ro = new Observer(() => {
124
+ if (!state.canvas) return;
125
+ if (box.clientWidth === state.width && box.clientHeight === state.height) return;
126
+ resize();
127
+ });
128
+ ro.observe(box);
129
+ const stop = () => ro.disconnect();
130
+ inst.own(stop);
131
+ return stop;
132
+ }
133
+
134
+ /** The box the fit shows (world px) and the zoom that makes it fill the screen, before any limit; null with nothing to show */
135
+ function fitTarget(padding, only = null) {
136
+ const { nodes, width, height } = state;
137
+ let visible = nodes.filter(isNodeVisible);
138
+ if (only) {
139
+ const part = visible.filter((n) => only.has(n.id));
140
+ if (part.length) visible = part;
141
+ }
142
+ if (visible.length === 0) return null;
143
+ // The phone's sheets hide the bottom of the map (sheets.js): fit into the part they leave
144
+ const mapHeight = Math.max(160, height - measureCovered());
145
+
146
+ let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
147
+ visible.forEach((n) => {
148
+ const r = n.r || 18;
149
+ minX = Math.min(minX, n.x - r - 25);
150
+ maxX = Math.max(maxX, n.x + r + 25);
151
+ minY = Math.min(minY, n.y - r - 25);
152
+ maxY = Math.max(maxY, n.y + r + 35); // room for the label below
153
+ });
154
+ if (state.view === 'dataflow' && state.flow) minY = Math.min(minY, state.flow.top - 10); // and the tier titles above
155
+ if (state.view === 'house' && state.house && state.house.fit && !only) ({ minX, maxX, minY, maxY } = state.house.fit); // the House view fits its plan and bands (house-model.js)
156
+
157
+ const availWidth = Math.max(160, width - padding * 2);
158
+ const availHeight = Math.max(160, mapHeight - padding * 2);
159
+ const raw = Math.min(availWidth / (maxX - minX), availHeight / (maxY - minY));
160
+ return { minX, maxX, minY, maxY, mapHeight, raw };
161
+ }
162
+
163
+ let minZoomKey = '';
164
+ let minZoomValue = ZOOM_MIN;
165
+
166
+ /**
167
+ * The lowest zoom for this map on this screen: low enough that Fit shows all of it (at most the default floor, so a small
168
+ * map keeps its limit). Hand zoom (wheel, pinch, keys) and Fit share it.
169
+ */
170
+ function getMinZoom() {
171
+ const key = `${state.sceneVersion}|${state.width}|${state.height}|${state.view}|${measureCovered()}`;
172
+ if (key !== minZoomKey) {
173
+ minZoomKey = key;
174
+ const t = fitTarget(fitPadding());
175
+ minZoomValue = t && t.raw > 0 && Number.isFinite(t.raw) ? Math.max(ZOOM_FLOOR, Math.min(ZOOM_MIN, t.raw)) : ZOOM_MIN;
176
+ }
177
+ return minZoomValue;
178
+ }
179
+
180
+ /** Zoom and pan so every visible node (and its label) is on screen; `only` (a Set of ids) narrows it to those, when any are visible */
181
+ function fitGraphToViewport(padding = 40, only = null) {
182
+ const { width, camera } = state;
183
+ const t = fitTarget(padding, only);
184
+ if (!t) return;
185
+ const { minX, maxX, minY, maxY, mapHeight } = t;
186
+ const targetZoom = Math.min(1.0, Math.max(ZOOM_FLOOR, t.raw));
187
+
188
+ camera.zoom = targetZoom;
189
+ camera.x = width / 2 - ((minX + maxX) / 2) * targetZoom;
190
+ camera.y = mapHeight / 2 - ((minY + maxY) / 2) * targetZoom;
191
+ render();
192
+ }
193
+
194
+ const fitPadding = () => (state.width < 640 ? 24 : 48);
195
+
196
+ const screenToWorld = (sx, sy) => ({ x: (sx - state.camera.x) / state.camera.zoom, y: (sy - state.camera.y) / state.camera.zoom });
197
+
198
+ // -------------------------------------------------------------------------
199
+ // When to draw (frame.js has the rules): on demand, not on a timer
200
+ // -------------------------------------------------------------------------
201
+ let drawnVersion = -1;
202
+
203
+ function paint() {
204
+ if (!state.canvas) return;
205
+ const scene = getScene();
206
+ drawnVersion = scene.version;
207
+ getRenderer().draw(scene, state.camera, performance.now());
208
+ // The labels repaint only when the camera, the scene or the size changed, never on a packet frame
209
+ const labels = getLabelLayer();
210
+ if (labels) labels.draw(scene, state.camera, { hover: state.hoverNodeId });
211
+ paintHooks.forEach((fn) => fn(scene, state.camera));
212
+ }
213
+
214
+ /** The node whose label is drawn under a screen point, or null (labels.js `hit`): a cluster's title frames the cluster */
215
+ function labelNodeAt(x, y) {
216
+ const labels = getLabelLayer();
217
+ return labels ? labels.hit(x, y) : null;
218
+ }
219
+
220
+ /**
221
+ * The node the pointer is on (or null): a node with no label is named by a chip over the map while it is. Only the label layer
222
+ * draws again (the map has nothing new to show), so moving across the map costs one small redraw per node entered.
223
+ */
224
+ function setHoverNode(id) {
225
+ const next = id || null;
226
+ if (state.hoverNodeId === next) return;
227
+ state.hoverNodeId = next;
228
+ const labels = getLabelLayer();
229
+ if (labels && state.canvas && state.width) labels.draw(getScene(), state.camera, { hover: next });
230
+ }
231
+
232
+ /** Things drawn over the map by the page itself (the runs' marks, explorer/runs-map.js): called after each draw with the scene and the camera */
233
+ const paintHooks = new Set();
234
+ const onPaint = (fn) => {
235
+ paintHooks.add(fn);
236
+ return () => paintHooks.delete(fn);
237
+ };
238
+
239
+ // Other things that need frames (the scenario player and its camera glide): `{ tick(nowMs), wants() }`.
240
+ // `tick` runs on every frame of the loop; the loop keeps going while any client `wants()` frames, even
241
+ // under reduced motion (the packets stay still; the steps still change). frame.js runs them (`tickClients`).
242
+ const frameClients = new Set();
243
+
244
+ const scheduler = createFrameScheduler({
245
+ draw: paint,
246
+ packetsVisible: () => !!state.canvas && packetsOnScreen(getScene(), state.camera, state.width, state.height),
247
+ isHidden: () => inst.hidden(),
248
+ tickClients: (t) => { let more = false; frameClients.forEach((c) => { c.tick(t); if (c.wants()) more = true; }); return more; },
249
+ clientsWant: () => [...frameClients].some((c) => c.wants()),
250
+ reduceMotion: () => inst.reducedMotion,
251
+ extraDirty: () => state.sceneVersion !== drawnVersion,
252
+ now: () => performance.now(),
253
+ raf: (cb) => requestAnimationFrame(cb),
254
+ caf: (id) => cancelAnimationFrame(id),
255
+ });
256
+
257
+ /** Something changed (the camera, the scene, the size): draw it in the next animation frame, once however often this is called */
258
+ function render() {
259
+ if (ended || !state.canvas) return;
260
+ scheduler.markDirty();
261
+ }
262
+
263
+ /** Draws right now, for a caller that needs the pixels this instant (a test, a screenshot) */
264
+ function renderNow() {
265
+ if (ended || !state.canvas) return;
266
+ scheduler.drawNow();
267
+ }
268
+
269
+ /** Registers a frame client (see above) and returns how to remove it */
270
+ function addFrameClient(client) {
271
+ frameClients.add(client);
272
+ return () => frameClients.delete(client);
273
+ }
274
+
275
+ // Any pointer, wheel, touch or key event counts as the visitor being there: after 30 s without one the
276
+ // packets stop, and the next one starts them again. Passive listeners on the root (captured, so no handler hides one), so no handler is slowed.
277
+ if (inst.root) {
278
+ const onInput = () => scheduler.noteInput();
279
+ for (const type of ACTIVITY) inst.listen(inst.root, type, onInput, { passive: true, capture: true });
280
+ }
281
+ inst.onShown(() => scheduler.shown());
282
+
283
+ /** Ends the map: no frame is waiting, the renderer's GPU context and the label layer are released, nothing is called again */
284
+ function destroy() {
285
+ ended = true;
286
+ scheduler.cancel();
287
+ // the end of this map: the renderer gives its WebGL context back too (`release`); a swap (setRenderer) only destroys, so the next renderer on the canvas has a live one
288
+ if (renderer) { if (renderer.release) renderer.release(); else renderer.destroy(); renderer = null; rendererCanvas = null; }
289
+ if (labelLayer) { labelLayer.destroy(); labelLayer = null; labelLayerCanvas = null; }
290
+ paintHooks.clear();
291
+ frameClients.clear();
292
+ }
293
+
294
+ const map = {
295
+ isNodeVisible,
296
+ isNodeVisibleToViewer,
297
+ getActiveSubgraph,
298
+ getScene,
299
+ sceneBuilds,
300
+ getSpatialIndex,
301
+ spatialBuilds,
302
+ getRenderer,
303
+ setRenderer,
304
+ resize,
305
+ watchSize,
306
+ getMinZoom,
307
+ fitGraphToViewport,
308
+ fitPadding,
309
+ screenToWorld,
310
+ labelNodeAt,
311
+ setHoverNode,
312
+ onPaint,
313
+ render,
314
+ renderNow,
315
+ addFrameClient,
316
+ /** Runs `job` at the start of the next frame, once however often it is queued, then draws (unless `{ draw: false }`): input.js coalesces pointer events with it */
317
+ queueFrameWork: (job, o) => { if (!ended) scheduler.queue(job, o); },
318
+ /** How many frames ran and how many of them drew (for tests and the bench) */
319
+ frameStats: () => ({ frames: scheduler.frames, draws: scheduler.draws }),
320
+ /** Stops (`true`) or resumes (`false`) every frame the page asks for itself, so a bench's scripted draws (`renderNow`) are the only ones */
321
+ holdFrames: (on) => { if (!ended) scheduler.hold(on); },
322
+ /** Forgets the frame that is waiting, if any (for tests that fake the clock) */
323
+ cancelFrame: () => scheduler.cancel(),
324
+ /** Start animating if allowed: asks for a frame, which draws and goes on only while a packet is on screen, motion is allowed and the visitor is active */
325
+ ensureFlowLoop: () => { if (!ended) scheduler.wake(); },
326
+ destroy,
327
+ };
328
+ inst.map = map;
329
+ inst.own(destroy);
330
+ return map;
331
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @module explorer/engine/search-status
3
+ *
4
+ * The polite live region by each search field (F24), on an instance: what a screen reader hears of a search. Once the typing pauses it says the
5
+ * count ("7 matches") or "No match for “xyz”" (pieces/search.js, spec 0008); a match chosen or "Framed 7 matches" is said by the map's
6
+ * announcer (engine/keyboard.js), once. The region is out of sight: the count in the field and the list under it say it on the screen. The
7
+ * no-match words are the `searchNoMatch` string; the query goes in as text, never as HTML. explorer/search-status.js keeps the old names for the page.
8
+ */
9
+
10
+ import { t } from './strings.js';
11
+
12
+ /** The two fields' status lines: the desktop box and the phone's bar */
13
+ const IDS = ['search-status', 'mobile-search-status'];
14
+
15
+ /** How long the typing must pause before what a search found is said: a live region that changed on every key would be read out on every key */
16
+ export const NO_MATCH_DELAY_MS = 400;
17
+
18
+ /** "No match for “query”" */
19
+ export const noMatchText = (inst, query) => `${t(inst, 'searchNoMatch')} “${query}”`;
20
+
21
+ const pendingOf = (inst) => inst.slot('search-status', () => {
22
+ const m = { pending: null };
23
+ inst.own(() => clearTimeout(m.pending));
24
+ return m;
25
+ });
26
+
27
+ /** Writes `text` into the region(s) at once; '' clears them */
28
+ function write(inst, text) {
29
+ for (const id of IDS) {
30
+ const el = inst.el(id);
31
+ if (el) el.textContent = text;
32
+ }
33
+ }
34
+
35
+ /** Shows `text` by the search field(s) at once, ending any wait for what the typing found; '' clears it */
36
+ export function showSearchStatus(inst, text) {
37
+ const m = pendingOf(inst);
38
+ clearTimeout(m.pending);
39
+ m.pending = null;
40
+ write(inst, text);
41
+ }
42
+
43
+ /**
44
+ * Sets the status for a search as it is typed: cleared at once (an empty query clears it for good), then, once the typing pauses, the
45
+ * count (`count`, "7 matches") for a query that found something, or "No match for …" for one that found nothing; so a screen reader
46
+ * says it once per pause, not for every letter.
47
+ * @param {string} query the trimmed query
48
+ * @param {boolean} found whether a node matched
49
+ * @param {string} [count] what to say when one did (nothing is said without it)
50
+ */
51
+ export function updateSearchStatus(inst, query, found, count = '') {
52
+ const m = pendingOf(inst);
53
+ clearTimeout(m.pending);
54
+ m.pending = null;
55
+ write(inst, '');
56
+ const text = !query ? '' : found ? count : noMatchText(inst, query);
57
+ if (!text) return;
58
+ m.pending = setTimeout(() => { m.pending = null; write(inst, text); }, NO_MATCH_DELAY_MS);
59
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * @module explorer/engine/selection
3
+ *
4
+ * Choosing a node, and choosing none, on an instance (spec 0008 D5 and D6; the rules of what a selection lights are in selection-model.js).
5
+ * Every way of changing the selection goes through here or through `state.selectedNode` / `state.selectedEdge` (a plain assignment), and the
6
+ * instance tells it once: the `selection` event (instance.js). The node panel (pieces/node-panel.js) follows `node:show` and `node:close`.
7
+ *
8
+ * selectNode(inst, node, { frame, source }) lights what is one edge from `node`, tells the panel, and when `frame` is set (a search, a list, a
9
+ * link, the keyboard: not a click on the map) flies the camera to the node and what it lights
10
+ * clearSelection(inst, { source }) no node, no edge; the panel closes
11
+ */
12
+ import { dismissHint } from './hint.js';
13
+ import { frameSelection } from '../selection-view.js';
14
+
15
+ /**
16
+ * Selects a node: lights what is one edge from it on the map and has the panel show it. `frame` is for a selection that did not come
17
+ * from a click on the map: the camera then flies to the node and what it lights (selection-model.js); a click leaves the camera where it is
18
+ * (spec 0008 D6). `source` says who chose, for the `selection` event ('tap', 'keyboard', 'search', 'link', 'api').
19
+ */
20
+ export function selectNode(inst, node, { frame = false, source = 'api' } = {}) {
21
+ if (!node) return;
22
+ const { state } = inst;
23
+ inst.emit('scenario:clear'); // a playing scenario ends (scenario-ui.js)
24
+ dismissHint(inst); // a node has been picked: the hint's job is done for this session
25
+ if (!state.selectedNode || state.selectedNode.id !== node.id) state.selectedKind = null; // a kind chosen for one node means nothing for the next
26
+ const change = inst.setSelection(node, null, { source, quiet: true });
27
+ inst.touchScene();
28
+ inst.map.render();
29
+ change.announce(); // the scene is up to date when the instance is told
30
+ inst.emit('node:show', { node, frame }); // the panel fills and opens, so what it covers is known below
31
+ if (frame) frameSelection(inst);
32
+ }
33
+
34
+ /** Ends the selection: no node, no edge, the panel closes */
35
+ export function clearSelection(inst, { source = 'api' } = {}) {
36
+ inst.emit('scenario:clear');
37
+ const change = inst.setSelection(null, null, { source, quiet: true });
38
+ inst.touchScene();
39
+ inst.map.render();
40
+ inst.emit('node:close');
41
+ change.announce();
42
+ }