cornfield 0.46.1 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/explorer/capped.js +3 -2
  2. package/explorer/engine/feedback.js +49 -0
  3. package/explorer/engine/flow-ui.js +39 -0
  4. package/explorer/engine/fly.js +54 -0
  5. package/explorer/engine/hint.js +98 -0
  6. package/explorer/engine/keyboard.js +156 -0
  7. package/explorer/engine/layers.js +280 -0
  8. package/explorer/engine/layout.js +378 -0
  9. package/explorer/engine/map-style.js +552 -0
  10. package/explorer/engine/piece.js +142 -0
  11. package/explorer/engine/render.js +331 -0
  12. package/explorer/engine/search-status.js +59 -0
  13. package/explorer/engine/selection.js +42 -0
  14. package/explorer/engine/sheets.js +417 -0
  15. package/explorer/engine/strings.js +63 -0
  16. package/explorer/feedback.js +11 -45
  17. package/explorer/flow-build.js +88 -0
  18. package/explorer/flow-style.js +28 -0
  19. package/explorer/flows.js +11 -132
  20. package/explorer/fly.js +11 -43
  21. package/explorer/hint.js +15 -88
  22. package/explorer/index.html +40 -82
  23. package/explorer/input.js +197 -177
  24. package/explorer/instance-state.js +172 -0
  25. package/explorer/instance.js +267 -0
  26. package/explorer/keyboard.js +14 -206
  27. package/explorer/labels.js +3 -3
  28. package/explorer/layers.js +34 -445
  29. package/explorer/layout.js +14 -372
  30. package/explorer/main.js +4 -226
  31. package/explorer/map-style.js +27 -525
  32. package/explorer/mockups-model.js +3 -3
  33. package/explorer/page-pieces.js +66 -0
  34. package/explorer/page.js +223 -0
  35. package/explorer/panels.js +29 -409
  36. package/explorer/pieces/adopt-tokens.js +38 -0
  37. package/explorer/pieces/layers.js +325 -0
  38. package/explorer/pieces/map-stage.css +14 -0
  39. package/explorer/pieces/map.js +332 -0
  40. package/explorer/pieces/node-panel.js +536 -0
  41. package/explorer/pieces/search.js +454 -0
  42. package/explorer/proposal-model.js +1 -1
  43. package/explorer/proposal.js +1 -0
  44. package/explorer/render.js +37 -267
  45. package/explorer/renderer-canvas2d.js +4 -4
  46. package/explorer/renderer-webgl.js +21 -8
  47. package/explorer/renderer.js +12 -9
  48. package/explorer/scene.js +3 -2
  49. package/explorer/search-status.js +8 -47
  50. package/explorer/search.js +26 -324
  51. package/explorer/selection-view.js +17 -19
  52. package/explorer/sheets.js +31 -379
  53. package/explorer/state.js +38 -173
  54. package/explorer/strings.js +17 -60
  55. package/explorer/view.js +4 -5
  56. package/package.json +1 -1
@@ -1,274 +1,44 @@
1
1
  /**
2
2
  * @module explorer/render
3
3
  *
4
- * The thin module the rest of the explorer calls: the camera (fit, zoom, screen to world), the
5
- * scene cache and the loop that animates flow packets. What is drawn is decided by scene.js
6
- * (buildScene); how it is drawn is the renderer's (renderer-canvas2d.js today). This module only
7
- * hands the one to the other: `render()` draws the cached scene with the current camera and time.
4
+ * A bridge (spec 0011 D2, step 1): the map's camera, scene cache and frame loop now live in engine/render.js, one per instance
5
+ * (`createMap(inst)`). This file keeps the old names for the modules that are not yet on an instance, bound to the page's instance, so
6
+ * `import { render, fitGraphToViewport } from './render.js'` works as it did. The page's map is made by page.js (or, for a module driven
7
+ * on its own in a test, on first use here). A module that is converted takes `inst` and calls `inst.map.render()` instead.
8
8
  */
9
9
 
10
- import { state, viewEdges } from './state.js';
11
- import { flowReduceMotion } from './flows.js';
12
- import { buildScene, createSceneCache, getActiveSubgraph as activeSubgraph, isNodeVisible as nodeVisible } from './scene.js';
13
- import { createCanvas2dRenderer } from './renderer-canvas2d.js';
14
- import { createSpatialCache } from './spatial.js';
15
- import { createFrameScheduler, packetsOnScreen } from './frame.js';
16
- import { createLabelLayer } from './labels.js';
10
+ import { pageInstance } from './state.js';
11
+ import { createMap } from './engine/render.js';
17
12
  import { measureCovered } from './sheets.js';
18
- import { ZOOM_MIN, ZOOM_FLOOR } from './camera.js';
19
13
 
20
- // ---------------------------------------------------------------------------
21
- // Visibility and focus (decided in scene.js, kept here under their old names)
22
- // ---------------------------------------------------------------------------
23
- export const isNodeVisible = (node) => nodeVisible(state, node);
24
- /** 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) */
25
- export const isNodeVisibleToViewer = (node) => nodeVisible(state, node, { viewer: true });
26
-
27
- /** The focus subgraph: the selected node and every node one edge away (selection-model.js); the switch and the kind come from the state */
28
- export const getActiveSubgraph = (selected, edges = viewEdges(), opts = { throughChildren: !!state.throughChildren, kind: state.selectedKind || null }) => activeSubgraph(selected, edges, opts);
29
-
30
- // ---------------------------------------------------------------------------
31
- // Scene and renderer
32
- // ---------------------------------------------------------------------------
33
- const sceneCache = createSceneCache((st) => buildScene(st, { reduceMotion: flowReduceMotion }));
34
-
35
- /** The scene for the current state, rebuilt only when `state.sceneVersion` changed */
36
- export const getScene = () => sceneCache.get(state);
37
- /** How many times the scene has been built so far (for tests and the bench) */
38
- export const sceneBuilds = () => sceneCache.builds;
39
-
40
- const spatialCache = createSpatialCache();
41
- /** The grid over the current scene's nodes (spatial.js), rebuilt only when the scene is: for hover, click and drag */
42
- export const getSpatialIndex = () => spatialCache.get(getScene());
43
- /** How many times the grid was built so far (for tests and the bench) */
44
- export const spatialBuilds = () => spatialCache.builds;
45
-
46
- let renderer = null;
47
- let rendererCanvas = null;
48
-
49
- const dpr = () => (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
50
-
51
- /** The renderer drawing `state.canvas`: Canvas 2D unless another was handed to setRenderer */
52
- export function getRenderer() {
53
- if (!renderer || rendererCanvas !== state.canvas) {
54
- if (renderer) renderer.destroy();
55
- renderer = createCanvas2dRenderer(state.canvas);
56
- rendererCanvas = state.canvas;
57
- if (state.width) renderer.resize(state.width, state.height, dpr());
58
- }
59
- return renderer;
60
- }
61
-
62
- let labelLayer = null;
63
- let labelLayerCanvas = null;
64
-
65
- /** The label layer on `state.labelCanvas` (labels.js), or null when the page has none */
66
- function getLabelLayer() {
67
- if (!state.labelCanvas) return null;
68
- if (!labelLayer || labelLayerCanvas !== state.labelCanvas) {
69
- if (labelLayer) labelLayer.destroy();
70
- labelLayer = createLabelLayer(state.labelCanvas);
71
- labelLayerCanvas = state.labelCanvas;
72
- if (state.width) labelLayer.resize(state.width, state.height, dpr());
73
- }
74
- return labelLayer;
75
- }
76
-
77
- /** Swaps the renderer (see scene.js for the contract) and draws with it */
78
- export function setRenderer(next) {
79
- if (renderer && renderer !== next) renderer.destroy();
80
- renderer = next;
81
- rendererCanvas = state.canvas;
82
- if (state.width) renderer.resize(state.width, state.height, dpr());
83
- render();
84
- }
85
-
86
- // ---------------------------------------------------------------------------
87
- // Camera
88
- // ---------------------------------------------------------------------------
89
- export function resize() {
90
- const { canvas } = state;
91
- state.width = canvas.parentElement.clientWidth;
92
- state.height = canvas.parentElement.clientHeight;
93
- getRenderer().resize(state.width, state.height, dpr());
94
- const labels = getLabelLayer();
95
- if (labels) labels.resize(state.width, state.height, dpr());
96
- render();
97
- }
98
-
99
- /** The box the fit shows (world px) and the zoom that makes it fill the screen, before any limit; null with nothing to show */
100
- function fitTarget(padding, only = null) {
101
- const { nodes, width, height } = state;
102
- let visible = nodes.filter(isNodeVisible);
103
- if (only) {
104
- const part = visible.filter((n) => only.has(n.id));
105
- if (part.length) visible = part;
106
- }
107
- if (visible.length === 0) return null;
108
- // The phone's sheets hide the bottom of the map (sheets.js): fit into the part they leave
109
- const mapHeight = Math.max(160, height - measureCovered());
110
-
111
- let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
112
- visible.forEach((n) => {
113
- const r = n.r || 18;
114
- minX = Math.min(minX, n.x - r - 25);
115
- maxX = Math.max(maxX, n.x + r + 25);
116
- minY = Math.min(minY, n.y - r - 25);
117
- maxY = Math.max(maxY, n.y + r + 35); // room for the label below
118
- });
119
- if (state.view === 'dataflow' && state.flow) minY = Math.min(minY, state.flow.top - 10); // and the tier titles above
120
- 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)
121
-
122
- const availWidth = Math.max(160, width - padding * 2);
123
- const availHeight = Math.max(160, mapHeight - padding * 2);
124
- const raw = Math.min(availWidth / (maxX - minX), availHeight / (maxY - minY));
125
- return { minX, maxX, minY, maxY, mapHeight, raw };
126
- }
127
-
128
- let minZoomKey = '';
129
- let minZoomValue = ZOOM_MIN;
130
-
131
- /**
132
- * 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
133
- * map keeps its limit). Hand zoom (wheel, pinch, keys) and Fit share it.
134
- */
135
- export function getMinZoom() {
136
- const key = `${state.sceneVersion}|${state.width}|${state.height}|${state.view}|${measureCovered()}`;
137
- if (key !== minZoomKey) {
138
- minZoomKey = key;
139
- const t = fitTarget(fitPadding());
140
- minZoomValue = t && t.raw > 0 && Number.isFinite(t.raw) ? Math.max(ZOOM_FLOOR, Math.min(ZOOM_MIN, t.raw)) : ZOOM_MIN;
141
- }
142
- return minZoomValue;
143
- }
144
-
145
- /** 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 */
146
- export function fitGraphToViewport(padding = 40, only = null) {
147
- const { width, camera } = state;
148
- const t = fitTarget(padding, only);
149
- if (!t) return;
150
- const { minX, maxX, minY, maxY, mapHeight } = t;
151
- const targetZoom = Math.min(1.0, Math.max(ZOOM_FLOOR, t.raw));
152
-
153
- camera.zoom = targetZoom;
154
- camera.x = width / 2 - ((minX + maxX) / 2) * targetZoom;
155
- camera.y = mapHeight / 2 - ((minY + maxY) / 2) * targetZoom;
156
- render();
157
- }
158
-
159
- export const fitPadding = () => (state.width < 640 ? 24 : 48);
160
-
161
- export function screenToWorld(sx, sy) {
162
- return { x: (sx - state.camera.x) / state.camera.zoom, y: (sy - state.camera.y) / state.camera.zoom };
163
- }
164
-
165
- // ---------------------------------------------------------------------------
166
- // When to draw (frame.js has the rules): on demand, not on a timer
167
- // ---------------------------------------------------------------------------
168
- let drawnVersion = -1;
169
-
170
- function paint() {
171
- if (!state.canvas) return;
172
- const scene = getScene();
173
- drawnVersion = scene.version;
174
- getRenderer().draw(scene, state.camera, performance.now());
175
- // The labels repaint only when the camera, the scene or the size changed, never on a packet frame
176
- const labels = getLabelLayer();
177
- if (labels) labels.draw(scene, state.camera, { hover: state.hoverNodeId });
178
- paintHooks.forEach((fn) => fn(scene, state.camera));
179
- }
180
-
181
- /** The node whose label is drawn under a screen point, or null (labels.js `hit`): a cluster's title frames the cluster */
182
- export function labelNodeAt(x, y) {
183
- const labels = getLabelLayer();
184
- return labels ? labels.hit(x, y) : null;
185
- }
186
-
187
- /**
188
- * 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
189
- * draws again (the map has nothing new to show), so moving across the map costs one small redraw per node entered.
190
- */
191
- export function setHoverNode(id) {
192
- const next = id || null;
193
- if (state.hoverNodeId === next) return;
194
- state.hoverNodeId = next;
195
- const labels = getLabelLayer();
196
- if (labels && state.canvas && state.width) labels.draw(getScene(), state.camera, { hover: next });
197
- }
198
-
199
- /** 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 */
200
- const paintHooks = new Set();
201
- export function onPaint(fn) {
202
- paintHooks.add(fn);
203
- return () => paintHooks.delete(fn);
204
- }
205
-
206
- const scheduler = createFrameScheduler({
207
- draw: paint,
208
- packetsVisible: () => !!state.canvas && packetsOnScreen(getScene(), state.camera, state.width, state.height),
209
- isHidden: () => typeof document !== 'undefined' && document.hidden,
210
- tickClients: (t) => { let more = false; frameClients.forEach((c) => { c.tick(t); if (c.wants()) more = true; }); return more; },
211
- clientsWant: () => [...frameClients].some((c) => c.wants()),
212
- reduceMotion: () => flowReduceMotion,
213
- extraDirty: () => state.sceneVersion !== drawnVersion,
214
- now: () => performance.now(),
215
- raf: (cb) => requestAnimationFrame(cb),
216
- caf: (id) => cancelAnimationFrame(id),
217
- });
218
-
219
- /** Something changed (the camera, the scene, the size): draw it in the next animation frame, once however often this is called */
220
- export function render() {
221
- if (!state.canvas) return;
222
- scheduler.markDirty();
223
- }
224
-
225
- /** Draws right now, for a caller that needs the pixels this instant (a test, a screenshot) */
226
- export function renderNow() {
227
- if (!state.canvas) return;
228
- scheduler.drawNow();
229
- }
230
-
231
- // Other things that need frames (the scenario player and its camera glide): `{ tick(nowMs), wants() }`.
232
- // `tick` runs on every frame of the loop; the loop keeps going while any client `wants()` frames, even
233
- // under reduced motion (the packets stay still; the steps still change). frame.js runs them (`tickClients`).
234
- const frameClients = new Set();
235
-
236
- /** Registers a frame client (see above) and returns how to remove it */
237
- export function addFrameClient(client) {
238
- frameClients.add(client);
239
- return () => frameClients.delete(client);
240
- }
241
-
242
- /** 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 */
243
- export const queueFrameWork = (job, opts) => scheduler.queue(job, opts);
244
-
245
- /** How many frames ran and how many of them drew (for tests and the bench) */
246
- export const frameStats = () => ({ frames: scheduler.frames, draws: scheduler.draws });
247
-
248
- /** Stops (`true`) or resumes (`false`) every frame the page asks for itself, so a bench's scripted draws (`renderNow`) are the only ones */
249
- export const holdFrames = (on) => scheduler.hold(on);
250
-
251
- /** Forgets the frame that is waiting, if any (for tests that fake the clock) */
252
- export const cancelFrame = () => scheduler.cancel();
253
-
254
- // ---------------------------------------------------------------------------
255
- // The packet loop: frames are asked for only while packets are on screen (frame.js)
256
- // ---------------------------------------------------------------------------
257
-
258
- /** 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 */
259
- export function ensureFlowLoop() {
260
- scheduler.wake();
261
- }
262
-
263
- // Any pointer, wheel, touch or key event counts as the visitor being there: after 30 s without one the
264
- // packets stop, and the next one starts them again. Passive listeners on the window, so no handler is slowed.
265
- if (typeof window !== 'undefined') {
266
- const onInput = () => scheduler.noteInput();
267
- for (const type of ['pointerdown', 'pointermove', 'mousedown', 'mousemove', 'wheel', 'touchstart', 'touchmove', 'keydown']) {
268
- window.addEventListener(type, onInput, { passive: true, capture: true });
269
- }
270
- }
271
-
272
- if (typeof document !== 'undefined') {
273
- document.addEventListener('visibilitychange', () => { if (!document.hidden) scheduler.shown(); });
274
- }
14
+ /** The page instance's map: made on first use when page.js has not made it */
15
+ export const pageMap = () => {
16
+ const inst = pageInstance();
17
+ return inst.map || createMap(inst, { measureCovered });
18
+ };
19
+
20
+ export const isNodeVisible = (node) => pageMap().isNodeVisible(node);
21
+ export const isNodeVisibleToViewer = (node) => pageMap().isNodeVisibleToViewer(node);
22
+ export const getActiveSubgraph = (...args) => pageMap().getActiveSubgraph(...args);
23
+ export const getScene = () => pageMap().getScene();
24
+ export const sceneBuilds = () => pageMap().sceneBuilds();
25
+ export const getSpatialIndex = () => pageMap().getSpatialIndex();
26
+ export const spatialBuilds = () => pageMap().spatialBuilds();
27
+ export const getRenderer = () => pageMap().getRenderer();
28
+ export const setRenderer = (next) => pageMap().setRenderer(next);
29
+ export const resize = () => pageMap().resize();
30
+ export const getMinZoom = () => pageMap().getMinZoom();
31
+ export const fitGraphToViewport = (padding, only) => pageMap().fitGraphToViewport(padding, only);
32
+ export const fitPadding = () => pageMap().fitPadding();
33
+ export const screenToWorld = (x, y) => pageMap().screenToWorld(x, y);
34
+ export const labelNodeAt = (x, y) => pageMap().labelNodeAt(x, y);
35
+ export const setHoverNode = (id) => pageMap().setHoverNode(id);
36
+ export const onPaint = (fn) => pageMap().onPaint(fn);
37
+ export const render = () => pageMap().render();
38
+ export const renderNow = () => pageMap().renderNow();
39
+ export const addFrameClient = (client) => pageMap().addFrameClient(client);
40
+ export const queueFrameWork = (job, opts) => pageMap().queueFrameWork(job, opts);
41
+ export const frameStats = () => pageMap().frameStats();
42
+ export const holdFrames = (on) => pageMap().holdFrames(on);
43
+ export const cancelFrame = () => pageMap().cancelFrame();
44
+ export const ensureFlowLoop = () => pageMap().ensureFlowLoop();
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
  import { CORE_RATIO, ARROW, END_SHAPES, SHAPE_SIZES, EDGE_STRIKE, MARK_MIN_PX, edgePoint, looksFor, packetPoint } from './scene.js';
12
- import { GLYPH_TOKEN, ICON_RATIO, getMapStyle, looksWith, styledScene } from './map-style.js';
12
+ import { GLYPH_TOKEN, ICON_RATIO, PLAIN_STYLE, looksWith, styledScene } from './engine/map-style.js';
13
13
  import { LETTER_RATIO, letterImage, showsLetters } from './kind-letters.js';
14
14
  import { GLYPH_RATIO, glyphImage, glyphInk, showsGlyph } from './glyphs.js';
15
15
 
@@ -374,11 +374,11 @@ function drawNode(ctx, node, zoom, looks, style) {
374
374
 
375
375
  /**
376
376
  * @param {HTMLCanvasElement} canvas the canvas to draw on
377
- * @param {{mapStyle?: () => import('./map-style.js').MapStyle, layerMinEdges?: number}} [opts] `mapStyle`: where the theme's map tokens come from (default: the page's, map-style.js `getMapStyle`); `layerMinEdges`: how many drawn lines make the layer worth it (default LAYER_MIN_EDGES)
377
+ * @param {{mapStyle?: () => import('./map-style.js').MapStyle, layerMinEdges?: number}} [opts] `mapStyle`: where the theme's map tokens come from (the instance's: `mapStyleOf(inst).get`; none: no theme); `layerMinEdges`: how many drawn lines make the layer worth it (default LAYER_MIN_EDGES)
378
378
  * @returns {import('./scene.js').Renderer}
379
379
  */
380
380
  export function createCanvas2dRenderer(canvas, opts = {}) {
381
- const styleOf = opts.mapStyle || getMapStyle;
381
+ const styleOf = opts.mapStyle || (() => PLAIN_STYLE);
382
382
  const ctx = canvas.getContext('2d');
383
383
  let width = 0;
384
384
  let height = 0;
@@ -394,7 +394,7 @@ export function createCanvas2dRenderer(canvas, opts = {}) {
394
394
  if (layer) return layer;
395
395
  try {
396
396
  layer = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(canvas.width || 1, canvas.height || 1)
397
- : typeof document !== 'undefined' ? document.createElement('canvas') : null;
397
+ : canvas.ownerDocument ? canvas.ownerDocument.createElement('canvas') : null;
398
398
  layerCtx = layer && layer.getContext ? layer.getContext('2d') : null;
399
399
  } catch { layerCtx = null; }
400
400
  if (!layerCtx) layer = null;
@@ -25,7 +25,7 @@
25
25
  */
26
26
 
27
27
  import { ARROW, CORE_RATIO, EDGE_STRIKE, END_SHAPES, SHAPE_SIZES, MARK_MIN_PX, edgePoint, looksFor, parseColor } from './scene.js';
28
- import { GLYPH_TOKEN, ICON_RATIO, getMapStyle, looksWith, styledScene } from './map-style.js';
28
+ import { GLYPH_TOKEN, ICON_RATIO, PLAIN_STYLE, looksWith, styledScene } from './engine/map-style.js';
29
29
  import { LETTER_MIN_PX, LETTER_RATIO, isLetterKey, letterImage, letterKey, lettersOfKey } from './kind-letters.js';
30
30
  import { GLYPH_MIN_PX, GLYPH_RATIO, glyphImage, glyphInk, glyphKey, glyphOfKey, isGlyphKey } from './glyphs.js';
31
31
  import { SHAPES } from '../core/schema.js';
@@ -441,7 +441,7 @@ function destroyGpu(gl, gpu) {
441
441
  /**
442
442
  * @param {HTMLCanvasElement} canvas the canvas to draw on (it must not have given a 2d context)
443
443
  * @param {{gl?: WebGL2RenderingContext, mapStyle?: () => import('./map-style.js').MapStyle}} [opts] `gl`: a context already taken from the canvas.
444
- * `mapStyle`: where the theme's map tokens and icons come from (default: the page's, map-style.js `getMapStyle`)
444
+ * `mapStyle`: where the theme's map tokens and icons come from: the instance's (`mapStyleOf(inst).get`); none: no theme
445
445
  * @returns {import('./scene.js').Renderer & {stats: {uploads: number, draws: number}}}
446
446
  * @throws {Error} when there is no WebGL2 context or a shader fails to compile or link
447
447
  */
@@ -449,7 +449,7 @@ export function createWebglRenderer(canvas, opts = {}) {
449
449
  const gl = opts.gl || canvas.getContext('webgl2', CONTEXT_ATTRS);
450
450
  if (!gl) throw new Error('WebGL2 is not available');
451
451
 
452
- const styleOf = opts.mapStyle || getMapStyle;
452
+ const styleOf = opts.mapStyle || (() => PLAIN_STYLE);
453
453
  const stats = { uploads: 0, draws: 0 };
454
454
  let gpu = buildGpu(gl);
455
455
  let lost = false;
@@ -626,11 +626,24 @@ export function createWebglRenderer(canvas, opts = {}) {
626
626
 
627
627
  draw,
628
628
 
629
- destroy() {
630
- canvas.removeEventListener('webglcontextlost', onLost);
631
- canvas.removeEventListener('webglcontextrestored', onRestored);
632
- if (gpu && !lost) destroyGpu(gl, gpu);
633
- gpu = null;
629
+ /** Frees what this renderer made on the GPU. The canvas keeps its context: a canvas hands out one WebGL context for its life, so a renderer
630
+ * made after this one on the same canvas (a renderer switch) draws with that same context, which must still be alive */
631
+ destroy,
632
+
633
+ /** destroy(), then gives the context back: a browser keeps only a handful of live ones. Only for the end of the canvas's map (engine/render.js
634
+ * `map.destroy()`): a context lost on purpose cannot be had again from that canvas */
635
+ release() {
636
+ const wasLost = lost;
637
+ destroy();
638
+ try { const lose = !wasLost && gl.getExtension ? gl.getExtension('WEBGL_lose_context') : null; if (lose) lose.loseContext(); } catch { /* already gone */ }
634
639
  },
635
640
  };
641
+
642
+ function destroy() {
643
+ canvas.removeEventListener('webglcontextlost', onLost);
644
+ canvas.removeEventListener('webglcontextrestored', onRestored);
645
+ if (gpu && !lost) destroyGpu(gl, gpu);
646
+ gpu = null;
647
+ lost = true; // draws nothing more
648
+ }
636
649
  }
@@ -2,8 +2,8 @@
2
2
  * @module explorer/renderer
3
3
  *
4
4
  * Chooses the renderer for the map canvas (spec 0012 A2): WebGL2 when the canvas gives a WebGL2
5
- * context and the address does not say `?renderer=canvas2d`, otherwise the Canvas 2D reference
6
- * renderer. main.js hands the result to render.js `setRenderer`.
5
+ * context and the caller does not ask for `canvas2d` (cornfield's page reads `?renderer=canvas2d` from its address, page.js; this module
6
+ * never reads the address), otherwise the Canvas 2D reference renderer. The page shell hands the result to the map's `setRenderer`.
7
7
  *
8
8
  * HOW THE MAP IS LAYERED
9
9
  *
@@ -42,6 +42,7 @@ function addStandIn(canvas) {
42
42
  const standIn = canvas.ownerDocument.createElement('canvas');
43
43
  standIn.className = 'hx-overlay';
44
44
  standIn.setAttribute('data-corn', 'map-overlay');
45
+ standIn.setAttribute('part', 'map-overlay'); // a host styles it from outside a shadow root: every hook is a part too
45
46
  standIn.setAttribute('aria-hidden', 'true');
46
47
  canvas.after(standIn);
47
48
  return standIn;
@@ -49,24 +50,26 @@ function addStandIn(canvas) {
49
50
 
50
51
  /**
51
52
  * @param {HTMLCanvasElement} canvas the map canvas; it must not have a 2d context yet
52
- * @param {{prefer?: 'canvas2d'|'webgl2'|null, makeStandIn?: (canvas: HTMLCanvasElement) => HTMLCanvasElement}} [opts]
53
- * `prefer`: default from the page's query string. `makeStandIn`: for tests.
53
+ * @param {{prefer?: 'canvas2d'|'webgl2'|null, makeStandIn?: (canvas: HTMLCanvasElement) => HTMLCanvasElement, mapStyle?: () => import('./engine/map-style.js').MapStyle}} [opts]
54
+ * `prefer`: what the caller was asked for (`rendererPreference(search)`); none means WebGL2 when there is one. `makeStandIn`: for tests.
55
+ * `mapStyle`: where the theme's map tokens come from, the instance's (`mapStyleOf(inst).get`).
54
56
  * @returns {import('./scene.js').Renderer}
55
57
  */
56
58
  export function createRenderer(canvas, opts = {}) {
57
- const prefer = opts.prefer !== undefined ? opts.prefer : rendererPreference(globalThis.location && globalThis.location.search);
58
- if (prefer === 'canvas2d') return createCanvas2dRenderer(canvas);
59
+ const prefer = opts.prefer || null;
60
+ const style = opts.mapStyle ? { mapStyle: opts.mapStyle } : {};
61
+ if (prefer === 'canvas2d') return createCanvas2dRenderer(canvas, style);
59
62
 
60
63
  let gl = null;
61
64
  try { gl = canvas.getContext('webgl2', CONTEXT_ATTRS); } catch { /* treated as no WebGL2 */ }
62
- if (!gl) return createCanvas2dRenderer(canvas);
65
+ if (!gl) return createCanvas2dRenderer(canvas, style);
63
66
 
64
67
  try {
65
- return createWebglRenderer(canvas, { gl });
68
+ return createWebglRenderer(canvas, { gl, ...style });
66
69
  } catch (err) {
67
70
  console.warn(`WebGL2 renderer unavailable, drawing with Canvas 2D: ${err.message}`);
68
71
  const standIn = (opts.makeStandIn || addStandIn)(canvas);
69
- const full = createCanvas2dRenderer(standIn);
72
+ const full = createCanvas2dRenderer(standIn, style);
70
73
  return { ...full, destroy() { full.destroy(); standIn.remove(); } };
71
74
  }
72
75
  }
package/explorer/scene.js CHANGED
@@ -163,10 +163,11 @@
163
163
  * `performance.now()`; it alone moves the packets, so an animated frame needs no new scene.
164
164
  * @property {(width: number, height: number, dpr: number) => void} resize
165
165
  * CSS px size of the viewport and the device pixel ratio; the renderer sizes its surface.
166
- * @property {() => void} destroy releases what it holds
166
+ * @property {() => void} destroy releases what it holds, but not the canvas's context: another renderer may be made on the same canvas
167
+ * @property {() => void} [release] destroy(), and the canvas's GPU context with it (WebGL): only when the canvas's map ends
167
168
  */
168
169
 
169
- import { flowStyleOf } from './flows.js';
170
+ import { flowStyleOf } from './flow-style.js';
170
171
  import { beforeOf, markIn, showsEdge, showsNode, touchedIds } from './proposal-model.js';
171
172
  import { decorateHouseScene, houseEdgeStyle, houseShowsNode, houseViewEdges } from './house-model.js';
172
173
  import { paintVerdict } from './check-model.js';
@@ -1,52 +1,13 @@
1
1
  /**
2
2
  * @module explorer/search-status
3
3
  *
4
- * The polite live region by each search field (F24): what a screen reader hears of a search. Once the typing pauses it says the count ("7 matches")
5
- * or "No match for “xyz”" (search.js, spec 0008); a match chosen or "Framed 7 matches" is said by the map's announcer (keyboard.js), once. The region is out of
6
- * sight: the count in the field and the list under it say it on the screen. The no-match words are the `searchNoMatch` string; the query
7
- * goes in as text, never as HTML.
4
+ * A bridge (spec 0011 D2, step 4): the search's live region now lives in engine/search-status.js, one per instance. This file keeps the old
5
+ * names for the page's instance. It goes when no module that is not on an instance (and no test) calls it.
8
6
  */
7
+ import { pageInstance } from './state.js';
8
+ import * as S from './engine/search-status.js';
9
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
- /** "No match for “query”" */
16
- export const noMatchText = (query) => `${t('searchNoMatch')} “${query}”`;
17
-
18
- /** Writes `text` into the region(s) at once; '' clears them */
19
- function write(text) {
20
- for (const id of IDS) {
21
- const el = document.getElementById(id);
22
- if (el) el.textContent = text;
23
- }
24
- }
25
-
26
- /** 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 */
27
- export const NO_MATCH_DELAY_MS = 400;
28
- let pending = null;
29
-
30
- /** Shows `text` by the search field(s) at once, ending any wait for what the typing found; '' clears it */
31
- export function showSearchStatus(text) {
32
- clearTimeout(pending);
33
- pending = null;
34
- write(text);
35
- }
36
-
37
- /**
38
- * 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
39
- * count (`count`, "7 matches") for a query that found something, or "No match for …" for one that found nothing; so a screen reader
40
- * says it once per pause, not for every letter.
41
- * @param {string} query the trimmed query
42
- * @param {boolean} found whether a node matched
43
- * @param {string} [count] what to say when one did (nothing is said without it)
44
- */
45
- export function updateSearchStatus(query, found, count = '') {
46
- clearTimeout(pending);
47
- pending = null;
48
- write('');
49
- const text = !query ? '' : found ? count : noMatchText(query);
50
- if (!text) return;
51
- pending = setTimeout(() => { pending = null; write(text); }, NO_MATCH_DELAY_MS);
52
- }
10
+ export { NO_MATCH_DELAY_MS } from './engine/search-status.js';
11
+ export const noMatchText = (query) => S.noMatchText(pageInstance(), query);
12
+ export const showSearchStatus = (text) => S.showSearchStatus(pageInstance(), text);
13
+ export const updateSearchStatus = (query, found, count) => S.updateSearchStatus(pageInstance(), query, found, count);