@popcorn245/cornfield 0.46.0 → 0.46.2

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 (62) 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 +97 -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 +547 -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-style.js +28 -0
  18. package/explorer/flows.js +10 -51
  19. package/explorer/fly.js +11 -43
  20. package/explorer/hint.js +15 -88
  21. package/explorer/index.html +38 -75
  22. package/explorer/input.js +190 -177
  23. package/explorer/instance-state.js +172 -0
  24. package/explorer/instance.js +267 -0
  25. package/explorer/keyboard.js +14 -206
  26. package/explorer/labels.js +3 -3
  27. package/explorer/layers.js +34 -445
  28. package/explorer/layout.js +14 -372
  29. package/explorer/main.js +4 -226
  30. package/explorer/map-style.js +27 -525
  31. package/explorer/mockups-model.js +3 -3
  32. package/explorer/page-pieces.js +61 -0
  33. package/explorer/page.js +232 -0
  34. package/explorer/panels.js +29 -409
  35. package/explorer/pieces/layers.js +325 -0
  36. package/explorer/pieces/node-panel.js +536 -0
  37. package/explorer/pieces/search.js +454 -0
  38. package/explorer/proposal-model.js +1 -1
  39. package/explorer/proposal.js +1 -0
  40. package/explorer/render.js +37 -267
  41. package/explorer/renderer-canvas2d.js +4 -4
  42. package/explorer/renderer-webgl.js +21 -8
  43. package/explorer/renderer.js +11 -9
  44. package/explorer/scene.js +3 -2
  45. package/explorer/search-status.js +8 -47
  46. package/explorer/search.js +26 -324
  47. package/explorer/selection-view.js +17 -19
  48. package/explorer/sheets.js +31 -379
  49. package/explorer/state.js +38 -173
  50. package/explorer/strings.js +17 -60
  51. package/explorer/view.js +4 -5
  52. package/package.json +1 -1
  53. package/server/agent-api.js +13 -6
  54. package/server/agent-runs.js +2 -1
  55. package/server/auth.js +1 -1
  56. package/server/forge-actions.js +34 -24
  57. package/server/forge-routes.js +3 -3
  58. package/server/lander.js +3 -2
  59. package/server/proposals.js +11 -3
  60. package/server/review-api.js +13 -8
  61. package/server/server.js +5 -4
  62. package/server/throttle.js +27 -0
@@ -0,0 +1,267 @@
1
+ /**
2
+ * @module explorer/instance
3
+ *
4
+ * The engine as something a page can make more than one of (spec 0011 D2). `createInstance` returns the object that holds what
5
+ * `state.js` held when the explorer was one program per document, and the things a piece of the explorer may reach:
6
+ *
7
+ * inst.root where the instance's elements are: a Document (cornfield's page), or an element or shadow root (a component)
8
+ * inst.state the explorer's state (instance-state.js): the topology, the layers, the camera, the selection, the view
9
+ * inst.base the address of the cornfield server the instance talks to ('' = the page's own origin)
10
+ * inst.fetch `fetch` bound to that base; inst.url(path) is a served path made absolute against it
11
+ * inst.strings the words the host overrides (key -> text), read with engine/strings.js `t(inst, key)`: two instances speak in two voices
12
+ * inst.touchScene / onSceneTouch a change the picture is built from, and who follows it
13
+ * inst.on / emit what a piece tells its neighbours, per instance: `emit(name, detail)` calls every `on(name, fn)`, and `on` returns how to stop.
14
+ * inst.ask what a piece asks of a neighbour that may or may not be there: the first answer other than `undefined` from the
15
+ * handlers of `on(name, ...)`, else `undefined`. A piece that finds no answer does without (the Work panel is not part of every page)
16
+ * inst.setSelection(node, edge, { source, quiet }) the one way the converted pieces change what is selected (explorer/engine/selection.js);
17
+ * returns the change, whose `announce()` says it when `quiet` held it back (the caller touches the scene first)
18
+ * inst.active() the element that has the focus inside the root's tree (a shadow root's own, not the host)
19
+ * inst.el an element of the instance by id, found inside its root and never by document id
20
+ * inst.listen a listener that `destroy()` removes; inst.own: any other clean-up `destroy()` runs; inst.release(fn): takes one back that its owner ran itself
21
+ * inst.slot what a module keeps for this instance (its map style), made on first use
22
+ * inst.map the map (engine/render.js createMap sets it)
23
+ * inst.destroy() runs every clean-up, so nothing the instance set up outlives it
24
+ *
25
+ * The events of an instance (name: detail). Every one is per instance; a name that is not listed here is not part of the contract.
26
+ *
27
+ * What happened (`on` them):
28
+ * selection { node, edge, previous: { node, edge }, source } THE selection changed: another node (by id), another edge, or none. `source` says
29
+ * who: 'tap' (the map or the panel's Close), 'keyboard', 'search', 'link' (a link or a list row in the panel), 'api' (a program calling
30
+ * engine/selection.js), or 'state' (an assignment to `state.selectedNode` or `state.selectedEdge`: an edge picked on the map is one).
31
+ * `node: null` is a clear. Said once per change, in order, and `previous` is what the listeners last heard: not when the same node
32
+ * is chosen again or nothing was selected and nothing is; a change a listener makes while it is said is said after every
33
+ * listener has heard the first
34
+ * scene (none) touchScene(): what the picture is built from changed (`onSceneTouch`)
35
+ * layers (none) a layer went on or off, or the layers were set (engine/layers.js): live.js starts or stops the live layer, a search moves its matches
36
+ * search { query, current } the search's query or its current match changed (pieces/search.js)
37
+ * node:painted { node } the node panel was filled for this node (pieces/node-panel.js)
38
+ * announce text what a screen reader is told (engine/keyboard.js `announce`, which also writes it in the root's `#map-announcer`, if it has one)
39
+ *
40
+ * What a piece is asked to do (`emit`ted to it):
41
+ * node:show { node, frame } show this node in the panel (engine/selection.js `selectNode`, once the scene is up to date); node:close: close it;
42
+ * node:focus: the focus goes into the open panel (Enter on the map)
43
+ * layers:redraw (none) draw the Layers menu again (engine/layers.js: a layer, the nodes or a review changed)
44
+ * theme (none) light or dark changed: the Layers menu draws its dots again (the host says so; theme.js does on the page)
45
+ * view view the view changed ('orbit', 'dataflow', 'house'): the Layers chip dims while the data-flow view is on (view.js on the page)
46
+ *
47
+ * What a piece asks of a neighbour that may not be there (`ask`: the first answer that is not `undefined`; nobody answering is a no):
48
+ * search:active (none) is a search with matches on? -> boolean (the map's N and P step through its matches then)
49
+ * search:step by step to the next (+1) or previous (-1) match -> boolean, whether there was one
50
+ * live:section node the live layer's block for the node panel -> HTML, put in the panel as it is: whoever answers escapes what it shows
51
+ * (live.js does); live:hydrate (emit) el: its photos
52
+ * forge:can-start (none) can a run be started from here? -> boolean; forge:start (emit) { slug, returnTo }: open the Start dialog
53
+ * scenario:clear (none) (emit) a selection ends a playing scenario
54
+ *
55
+ * What input.js asks of the page (requests, not news of a change; the page decides what each means):
56
+ * select node a tap on a node; `background`: a tap on the bare map; `grab`: a hand took the camera
57
+ *
58
+ * A module that is "on the instance" takes `inst` and reads nothing global: no shared state, no `document.getElementById`, no
59
+ * listener on `document` or `window`, no `location`, no `history`, no fetch of a literal path (test/explorer/instance-tripwires.test.js).
60
+ * Light and dark, and the viewer's reduced-motion setting, are read through the instance too (`inst.tokenReader()`, `inst.reducedMotion`).
61
+ */
62
+
63
+ import { createState } from './instance-state.js';
64
+
65
+ const ABSOLUTE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
66
+
67
+ /**
68
+ * @param {object} [opts]
69
+ * @param {Document|Element|ShadowRoot|null} [opts.root] where the instance's elements are; null for an instance with no page (a test, a worker)
70
+ * @param {string} [opts.base] the cornfield server's address; '' is the document's own origin
71
+ * @param {typeof fetch} [opts.fetch] default: the global `fetch`, looked up at each call
72
+ * @param {Record<string, string>} [opts.strings] the host's own words
73
+ * @param {object} [opts.state] a state object to adopt instead of a new one (state.js hands the page's to the page instance)
74
+ */
75
+ export function createInstance({ root = null, base = '', fetch: fetchOpt, strings = {}, state } = {}) {
76
+ const doc = root ? (root.nodeType === 9 ? /** @type {Document} */ (root) : root.ownerDocument) : null;
77
+ const win = doc ? doc.defaultView : null;
78
+ const events = new Map();
79
+ const cleanups = [];
80
+ const slots = new Map();
81
+ let destroyed = false;
82
+ const fetchImpl = fetchOpt;
83
+
84
+ const on = (name, fn) => {
85
+ let set = events.get(name);
86
+ if (!set) events.set(name, (set = new Set()));
87
+ set.add(fn);
88
+ return () => set.delete(fn);
89
+ };
90
+
91
+ /** A served path made absolute against the base; anything already absolute (or no base) is returned as it was */
92
+ const url = (path) => {
93
+ const p = String(path);
94
+ if (!base || ABSOLUTE.test(p)) return p;
95
+ return new URL(p, base).href;
96
+ };
97
+
98
+ /** The element whose computed style holds the tokens: the document's own for a page, else the root itself (a shadow root's host) */
99
+ const tokenElement = () => {
100
+ if (!root) return null;
101
+ if (root.nodeType === 9) return /** @type {Document} */ (root).documentElement;
102
+ return root.nodeType === 11 ? /** @type {ShadowRoot} */ (root).host : /** @type {Element} */ (root);
103
+ };
104
+
105
+ // What is selected: a node and an edge, kept behind accessors on the state so that every way of changing them, an assignment included, is heard
106
+ const theState = state || createState();
107
+ let selNode = theState.selectedNode || null;
108
+ let selEdge = theState.selectedEdge || null;
109
+ // The `selection` event says each change once, against what its listeners last heard (`heard`), in order: a change made while it is
110
+ // being said (a listener that selects) is said after every listener has heard the first, and a quiet change a later one overtook says nothing
111
+ let heard = { node: selNode, edge: selEdge };
112
+ const queue = [];
113
+ let saying = false;
114
+ const differs = (a, b) => (a.node ? a.node.id : null) !== (b.node ? b.node.id : null) || a.edge !== b.edge;
115
+ const say = (source) => {
116
+ queue.push(source);
117
+ if (saying) return;
118
+ saying = true;
119
+ try {
120
+ while (queue.length) {
121
+ const why = queue.shift();
122
+ const now = { node: selNode, edge: selEdge };
123
+ if (destroyed || !differs(heard, now)) continue;
124
+ const previous = heard;
125
+ heard = now;
126
+ inst.emit('selection', { ...now, previous, source: why });
127
+ }
128
+ } finally { saying = false; }
129
+ };
130
+ const commit = (nextNode, nextEdge, source, quiet) => {
131
+ const previous = { node: selNode, edge: selEdge };
132
+ selNode = nextNode || null;
133
+ selEdge = nextEdge || null;
134
+ const changed = differs(previous, { node: selNode, edge: selEdge });
135
+ let said = false;
136
+ const announce = () => { if (said) return; said = true; if (changed) say(source); };
137
+ if (!quiet) announce();
138
+ return { changed, previous, announce };
139
+ };
140
+ Object.defineProperty(theState, 'selectedNode', { enumerable: true, configurable: true, get: () => selNode, set: (v) => { commit(v, selEdge, 'state', false); } });
141
+ Object.defineProperty(theState, 'selectedEdge', { enumerable: true, configurable: true, get: () => selEdge, set: (v) => { commit(selNode, v, 'state', false); } });
142
+
143
+ const inst = {
144
+ root,
145
+ doc,
146
+ win,
147
+ base,
148
+ /** The host's own words (key -> text); nothing on the map reads them yet (the pieces of step 4 will) */
149
+ strings: { ...strings },
150
+ state: theState,
151
+
152
+ url,
153
+ fetch(input, init) {
154
+ const f = fetchImpl || globalThis.fetch;
155
+ return f(typeof input === 'string' ? url(input) : input, init);
156
+ },
157
+
158
+ // -- what changed -----------------------------------------------------------------------------------------------------------
159
+ /** Call after changing anything a picture is built from: the topology or its layout, the layers, the selection, the search, the view, a playing scenario, a proposal. Not for the camera, and not for time. */
160
+ touchScene() {
161
+ inst.state.sceneVersion++;
162
+ const set = events.get('scene');
163
+ if (set) set.forEach((fn) => fn());
164
+ },
165
+ /** Calls `fn` after every touchScene(): for UI that follows what the scene is built from. Returns how to stop. */
166
+ onSceneTouch: (fn) => on('scene', fn),
167
+ on,
168
+ emit(name, detail) {
169
+ const set = events.get(name);
170
+ if (set) [...set].forEach((fn) => fn(detail));
171
+ },
172
+ ask(name, detail) {
173
+ const set = events.get(name);
174
+ if (!set) return undefined;
175
+ for (const fn of [...set]) {
176
+ const answer = fn(detail);
177
+ if (answer !== undefined) return answer;
178
+ }
179
+ return undefined;
180
+ },
181
+ /**
182
+ * Sets what is selected (a node, an edge, or neither). Fires `selection` once if the node (by id) or the edge changed, unless `quiet`:
183
+ * then the returned change's `announce()` says it later. Plain assignments to `state.selectedNode` / `state.selectedEdge` fire it too.
184
+ */
185
+ setSelection: (node, edge = null, { source = 'api', quiet = false } = {}) => commit(node, edge, source, quiet),
186
+
187
+ // -- the instance's own elements ----------------------------------------------------------------------------------------------
188
+ /** The element with this id inside the root, or null (ids are only unique inside one root) */
189
+ el: (id) => (root ? root.querySelector(`[id="${String(id).replace(/["\\]/g, '\\$&')}"]`) : null),
190
+ /** The element with the focus in the root's own tree: a Document's or a shadow root's `activeElement`, or the document's when it is inside the root; else null */
191
+ active: () => {
192
+ if (!root || !doc) return null;
193
+ if (root.nodeType !== 1) return root.activeElement || null; // a Document or a shadow root
194
+ return doc.activeElement && root.contains(doc.activeElement) ? doc.activeElement : null;
195
+ },
196
+
197
+ // -- what the viewer prefers --------------------------------------------------------------------------------------------------
198
+ /** A reader of the computed custom properties at the root (`(name) => value`), or null where there is no page */
199
+ tokenReader() {
200
+ const el = tokenElement();
201
+ if (!el || !win || !win.getComputedStyle) return null;
202
+ const style = win.getComputedStyle(el);
203
+ return (name) => style.getPropertyValue(name);
204
+ },
205
+ /** The element tokens are read from (attributes on it, `data-theme`, say, change them) */
206
+ tokenElement,
207
+ /** prefers-reduced-motion, as it was when the instance was made */
208
+ reducedMotion: !!(win && win.matchMedia && win.matchMedia('(prefers-reduced-motion: reduce)').matches),
209
+ /** The device pixel ratio now */
210
+ dpr: () => (win && win.devicePixelRatio) || 1,
211
+ /** Whether the tab is hidden */
212
+ hidden: () => !!(doc && doc.hidden),
213
+ /** Calls `fn` when the tab is shown again; the one document-level fact an instance needs. Removed by destroy(). */
214
+ onShown(fn) {
215
+ if (!doc) return () => {};
216
+ return inst.listen(doc, 'visibilitychange', () => { if (!doc.hidden) fn(); });
217
+ },
218
+ /** A small key-value store (the browser's localStorage, which may be blocked): what a viewer's own choices are kept in */
219
+ store: {
220
+ get(key) { try { return win && win.localStorage ? win.localStorage.getItem(key) : null; } catch { return null; } },
221
+ set(key, value) { try { if (win && win.localStorage) win.localStorage.setItem(key, value); } catch { /* blocked: holds for this visit */ } },
222
+ remove(key) { try { if (win && win.localStorage) win.localStorage.removeItem(key); } catch { /* nothing to clear */ } },
223
+ },
224
+
225
+ // -- an end to everything -----------------------------------------------------------------------------------------------------
226
+ /** Adds `listener` to `target`; destroy() removes it. Returns how to remove it now. */
227
+ listen(target, type, listener, options) {
228
+ target.addEventListener(type, listener, options);
229
+ const off = () => {
230
+ target.removeEventListener(type, listener, options);
231
+ inst.release(off);
232
+ };
233
+ cleanups.push(off);
234
+ return off;
235
+ },
236
+ /** Runs `fn` when the instance is destroyed (an observer's disconnect, a timer's clear, a renderer's release); returns `fn` */
237
+ own(fn) {
238
+ cleanups.push(fn);
239
+ return fn;
240
+ },
241
+ /** Takes back a clean-up given to `own` (or the one `listen` returned) that its owner has run itself: a piece that ends before the instance does */
242
+ release(fn) {
243
+ const at = cleanups.lastIndexOf(fn);
244
+ if (at >= 0) cleanups.splice(at, 1);
245
+ },
246
+ /** What a module keeps for this instance: `make(inst)` the first time, the same value after */
247
+ slot(key, make) {
248
+ if (!slots.has(key)) slots.set(key, make(inst));
249
+ return slots.get(key);
250
+ },
251
+ /** Removes every listener, observer and timer the instance's modules set up and releases the renderer's GPU context. Safe to call twice. */
252
+ destroy() {
253
+ if (destroyed) return;
254
+ destroyed = true;
255
+ while (cleanups.length) {
256
+ try { cleanups.pop()(); } catch (err) { console.error('An instance clean-up failed', err); }
257
+ }
258
+ events.clear();
259
+ slots.clear();
260
+ },
261
+
262
+ // -- the map as the state holds it ----------------------------------------------------------------------------------------------
263
+ /** The edges the current view draws and the selection walks */
264
+ viewEdges: () => (inst.state.view === 'dataflow' && inst.state.flow ? inst.state.flow.edges : inst.state.edges),
265
+ };
266
+ return inst;
267
+ }
@@ -1,215 +1,23 @@
1
1
  /**
2
2
  * @module explorer/keyboard
3
3
  *
4
- * The map by keyboard, and what a screen reader hears (MAP-02). keyboard-model.js decides what a key means and
5
- * the words; this module does it on the page:
6
- *
7
- * - the map canvas is focusable (`tabindex="0"`, `role="application"`, its keys in `#map-keys-help`): the arrow
8
- * keys pan, + and - zoom about the middle, 0 fits, N and P (or ] and [) step through the visible nodes in
9
- * reading order and select each, centred, Home and End the first and the last, Enter goes into the panel,
10
- * Escape closes it, and in Freeform Alt+arrow moves the selected node;
11
- * - `#map-announcer` (a polite live region) says where the keyboard landed: the node, its type, its
12
- * connections, its place; the zoom; a search's hit;
13
- * - Enter in the search box selects the best match and goes on to the next (search.js); with a search on, N and P step through its matches;
14
- * - the panel: Escape inside it closes it and gives the focus back to the map; it is `inert` while closed
15
- * (panels.js), so its buttons are never tabbed to off screen;
16
- * - the Layers menu says whether it is open (`aria-expanded`), and Escape closes it, back on its button;
17
- * - `/` goes to the search (anywhere but in a field): the box on a desktop, the search bar on a phone.
4
+ * A bridge (spec 0011 D2, step 4): the map by keyboard and the screen reader's announcer now live in engine/keyboard.js, one per instance; the
5
+ * keys of the node panel, the Layers menu and the search belong to those pieces. This file keeps the old names for the modules that are not
6
+ * yet on an instance (they call `announce`), bound to the page's instance. It goes when the last of them is converted.
18
7
  */
19
8
 
20
- import { state, touchScene } from './state.js';
21
- import { render, fitGraphToViewport, fitPadding, isNodeVisible, getMinZoom } from './render.js';
22
- import { zoomAbout } from './camera.js';
23
- import { selectNode, closeDrawer } from './panels.js';
24
- import { saveFreeformPositions } from './layout.js';
25
- import { closeLegendMenu } from './layers.js';
26
- import * as K from './keyboard-model.js';
27
- import { searchActive, stepMatch } from './search.js';
28
- import { frameSelection, litNodes } from './selection-view.js';
29
-
30
- const $ = (id) => document.getElementById(id);
31
- let wired = false;
32
- let announceTimer = null;
33
-
34
- /** Tells a screen reader `text` (politely: after what it is reading). The same words twice are said twice. */
35
- export function announce(text) {
36
- const el = $('map-announcer');
37
- if (!el) return;
38
- el.textContent = '';
39
- clearTimeout(announceTimer);
40
- // a fresh text node a moment later is what makes a live region speak again
41
- announceTimer = setTimeout(() => { el.textContent = text; }, 30);
42
- }
43
-
44
- /** The visible nodes, in the order the keys step through them */
45
- const stepOrder = () => K.readingOrder(state.nodes.filter((n) => isNodeVisible(n)));
46
-
47
- /** The camera that puts `node` in the middle of the part of the map not under the panels or a phone's sheets, at `zoom` (the current one by default) */
48
- export function centreTarget(node, zoom = state.camera.zoom) {
49
- const { width, height } = state;
50
- const visibleHeight = Math.max(160, height - (state.coveredBottom || 0));
51
- const panel = $('spec-drawer');
52
- const visibleWidth = width >= 768 && panel && panel.classList.contains('drawer-open') ? Math.max(160, width - (panel.offsetWidth || 480)) : width;
53
- // The issues and PRs panel slides in from the left (forge-panel.js)
54
- const forge = $('forge-panel');
55
- const left = width >= 768 && forge && forge.classList.contains('forge-open') ? Math.min(forge.offsetWidth || 400, visibleWidth - 160) : 0;
56
- return { x: left + (visibleWidth - left) / 2 - node.x * zoom, y: visibleHeight / 2 - node.y * zoom, zoom };
57
- }
58
-
59
- /** Moves the camera so `node` is in the middle of the part of the map not under the panels or a phone's sheets */
60
- export function centreOn(node) {
61
- Object.assign(state.camera, centreTarget(node));
62
- render();
63
- }
64
-
65
- function land(node, order) {
66
- if (!node) { announce('No nodes are shown. Turn a layer on in the Layers menu.'); return; }
67
- selectNode(node, { frame: true }); // the keyboard's selection frames the node and what it lights (spec 0008 D6)
68
- announce(K.describeNode(node, order.length, order.indexOf(node)));
69
- }
70
-
71
- /** "Frame them" and the `F` key: the camera goes to the selected node and what it lights, and a screen reader is told how many that is */
72
- export function frameThem() {
73
- if (!state.selectedNode) return;
74
- const target = frameSelection();
75
- if (!target) return;
76
- const connected = Math.max(0, litNodes().length - 1);
77
- announce(target.framed ? `Framed ${state.selectedNode.label} and ${connected} connected` : `${state.selectedNode.label} centred: ${connected} connected, too spread out to frame together`);
78
- }
79
-
80
- /** Into the open panel: its title takes the focus, so a screen reader starts there and Tab goes on into it */
81
- function focusPanel() {
82
- const title = $('drawer-title');
83
- if (!title) return;
84
- title.setAttribute('tabindex', '-1');
85
- title.focus();
86
- }
87
-
88
- function moveSelected(dx, dy) {
89
- const node = state.selectedNode;
90
- if (!node) return;
91
- node.x += dx;
92
- node.y += dy;
93
- state.freeformPositions[node.id] = { x: node.x, y: node.y };
94
- touchScene();
95
- saveFreeformPositions();
96
- render();
97
- announce(`Moved ${node.label}`);
98
- }
99
-
100
- function onMapKey(e) {
101
- if (e.target !== state.canvas || e.defaultPrevented) return;
102
- const action = K.mapKeyAction(e.key, {
103
- shift: e.shiftKey, alt: e.altKey, ctrl: e.ctrlKey, meta: e.metaKey,
104
- scenario: !!state.scenario, freeform: state.isFreeform && state.view === 'orbit', selected: !!state.selectedNode,
105
- });
106
- if (!action) return;
107
- e.preventDefault();
108
- const { camera, width, height } = state;
109
- switch (action.type) {
110
- case 'pan':
111
- camera.x += action.dx;
112
- camera.y += action.dy;
113
- render();
114
- break;
115
- case 'zoom':
116
- Object.assign(camera, zoomAbout(camera, action.factor, width / 2, height / 2, getMinZoom()));
117
- render();
118
- announce(K.zoomWords(camera.zoom));
119
- break;
120
- case 'fit':
121
- fitGraphToViewport(fitPadding());
122
- announce(`The whole map. ${K.zoomWords(camera.zoom)}`);
123
- break;
124
- case 'step': {
125
- if (searchActive() && stepMatch(action.by)) break; // with a search on, N and P walk its matches (search.js)
126
- const order = stepOrder();
127
- land(K.stepFrom(order, state.selectedNode && state.selectedNode.id, action.by), order);
128
- break;
129
- }
130
- case 'first': case 'last': {
131
- const order = stepOrder();
132
- land(action.type === 'first' ? order[0] : order[order.length - 1], order);
133
- break;
134
- }
135
- case 'frame':
136
- frameThem();
137
- break;
138
- case 'open':
139
- focusPanel();
140
- break;
141
- case 'close':
142
- closeDrawer();
143
- announce('Panel closed');
144
- break;
145
- case 'move':
146
- moveSelected(action.dx, action.dy);
147
- break;
148
- default:
149
- }
150
- }
151
-
152
- /** Escape anywhere in the panel closes it, and the map has the focus again */
153
- function onPanelKey(e) {
154
- if (e.key !== 'Escape' || e.defaultPrevented) return;
155
- if (e.target.closest && e.target.closest('select, input, textarea')) return; // a field's own Escape first
156
- e.preventDefault();
157
- closeDrawer();
158
- if (state.canvas) state.canvas.focus();
159
- announce('Panel closed');
160
- }
161
-
162
- /** The panel's ✕: the focus would be left on a hidden button, so it goes back to the map */
163
- function onPanelClick(e) {
164
- const close = e.target.closest && e.target.closest('[data-action="close-drawer"]');
165
- if (close && state.canvas) setTimeout(() => state.canvas.focus(), 0);
166
- }
9
+ import { pageInstance } from './state.js';
10
+ import { ensurePagePieces } from './page-pieces.js';
11
+ import * as K from './engine/keyboard.js';
167
12
 
168
- /** Whether the key went to something that takes typing */
169
- const typing = (el) => !!el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName));
170
-
171
- /** `/` goes to the search box, or to the phone's search bar where the box is not shown (opening the bar if it is shut) */
172
- function goToSearch() {
173
- const input = $('node-search');
174
- const shown = input && input.closest('.hx-search') && window.getComputedStyle(input.closest('.hx-search')).display !== 'none';
175
- if (shown) { input.focus(); input.select(); return; }
176
- const bar = $('mobile-search-bar');
177
- if (bar && !bar.hidden) { $('mobile-node-search').focus(); return; }
178
- const open = $('mobile-search-toggle');
179
- if (open) open.click();
180
- }
181
-
182
- /** Escape with the Layers menu open closes it, and its button has the focus again */
183
- function onDocumentKey(e) {
184
- if (e.key === '/' && !e.ctrlKey && !e.metaKey && !e.altKey && !typing(e.target) && !document.querySelector('[data-corn="dialog-scrim"]:not([hidden]), .hx-mockup-dialog')) {
185
- e.preventDefault();
186
- goToSearch();
187
- return;
188
- }
189
- if (e.key !== 'Escape') return;
190
- const menu = $('legend-dropdown');
191
- if (!menu || menu.hidden) return;
192
- closeLegendMenu();
193
- const btn = $('legend-toggle-btn');
194
- if (btn) btn.focus();
195
- }
196
-
197
- /** Wires the keys (main.js, once the canvas is on `state`) */
13
+ export const announce = (text) => K.announce(pageInstance(), text);
14
+ export const centreTarget = (node, zoom) => K.centreTarget(pageInstance(), node, zoom);
15
+ export const centreOn = (node) => K.centreOn(pageInstance(), node);
16
+ export const frameThem = () => K.frameThem(pageInstance());
17
+ /** Wires the map's keys on the page, and the pieces' (the panel's Escape, the Layers menu's, the search's `/`) where the page has them */
198
18
  export function initKeyboard() {
199
- if (wired || !state.canvas) return;
200
- wired = true;
201
- state.canvas.addEventListener('keydown', onMapKey);
202
- const drawer = $('spec-drawer');
203
- if (drawer) {
204
- drawer.addEventListener('keydown', onPanelKey);
205
- drawer.addEventListener('click', onPanelClick);
206
- }
207
- document.addEventListener('keydown', onDocumentKey);
19
+ ensurePagePieces();
20
+ K.initKeyboard(pageInstance());
208
21
  }
209
-
210
22
  /** For tests: wire again on a fresh page */
211
- export function resetKeyboardForTests() {
212
- if (wired && state.canvas) state.canvas.removeEventListener('keydown', onMapKey);
213
- document.removeEventListener('keydown', onDocumentKey);
214
- wired = false;
215
- }
23
+ export const resetKeyboardForTests = () => K.resetKeyboard(pageInstance());
@@ -45,7 +45,7 @@
45
45
  */
46
46
 
47
47
  import { FONT_EDGE, FONT_NODE, HUB_LABEL_EXTRA_PX, LABEL_MIN_FLOOR, LABEL_MIN_PX, LANDMARK_TYPES, looksFor } from './scene.js';
48
- import { getMapStyle, styledScene } from './map-style.js';
48
+ import { PLAIN_STYLE, styledScene } from './engine/map-style.js';
49
49
 
50
50
  /** At most this many node labels in view at a time (lane text and selection edge labels are extra); the placing itself never needs it */
51
51
  export const MAX_LABELS = 400;
@@ -314,14 +314,14 @@ export function labelHit(placed, camera, x, y) {
314
314
  /**
315
315
  * A transparent 2D canvas that draws the chosen labels over the map
316
316
  * @param {HTMLCanvasElement} canvas
317
- * @param {{mapStyle?: () => import('./map-style.js').MapStyle}} [opts] `mapStyle`: where the theme's map tokens come from (default: the page's, map-style.js `getMapStyle`);
317
+ * @param {{mapStyle?: () => import('./map-style.js').MapStyle}} [opts] `mapStyle`: where the theme's map tokens come from (the instance's: `mapStyleOf(inst).get`; none: no theme);
318
318
  * a node's label colour is the theme's `--corn-map-label`, and the outline under every label its `--corn-map-label-halo`, when it sets them
319
319
  * @returns {{hit: (x: number, y: number) => string|null, draw: (scene: import('./scene.js').Scene, camera: import('./scene.js').Camera, extras?: {hover?: string|null}) => boolean, resize: (width: number, height: number, dpr: number) => void, destroy: () => void}}
320
320
  * `draw` returns whether it painted: false when the camera, the scene, the size and the hovered node were unchanged; `extras.hover` is the
321
321
  * node the pointer is on (named by a chip when it has no label)
322
322
  */
323
323
  export function createLabelLayer(canvas, opts = {}) {
324
- const styleOf = opts.mapStyle || getMapStyle;
324
+ const styleOf = opts.mapStyle || (() => PLAIN_STYLE);
325
325
  const ctx = canvas.getContext('2d');
326
326
  let width = 0, height = 0, dpr = 1;
327
327
  let lastScene = null, lastVersion, lastX, lastY, lastZoom, lastStyle, lastHover;