cornfield 0.40.0 → 0.42.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.
@@ -1,26 +1,33 @@
1
1
  /**
2
2
  * @module explorer/labels
3
3
  *
4
- * The label overlay (spec 0012 A3, TOPO-05): every label the map shows, drawn by one layer on
5
- * a transparent canvas stacked over the map canvas, for either renderer. Two parts:
4
+ * The label overlay (spec 0012 A3, TOPO-05; spec 0008 D2): every label the map shows, drawn by one layer on
5
+ * a transparent canvas stacked over the map canvas, for either renderer. Three parts:
6
6
  *
7
- * chooseLabels(scene, camera, viewport) pure: which text to draw, in world coordinates
8
- * createLabelLayer(canvas) draws that on a 2d canvas, and only when something changed
7
+ * placeLabels(scene, zoom) pure: which node labels fit at this zoom, and where (cached by zoom)
8
+ * chooseLabels(scene, camera, viewport) pure: the text to draw, in world coordinates, for this view
9
+ * createLabelLayer(canvas) draws that on a 2d canvas, and only when something changed
9
10
  *
10
- * chooseLabels applies `labelAt` (scene.js) for the zoom-dependent level of detail and size, drops
11
- * the labels whose box is off screen, and when more than MAX_LABELS node labels remain keeps the
12
- * most useful: the selection and what is connected to it, then search matches, then landmark
13
- * types, then the larger nodes, with ties kept in scene order so a pan never reshuffles them.
14
- * Lane titles, notes and arrows and the selection's edge labels are always included and do not
15
- * count against the cap. The layer redraws only when the camera, the scene or the size changed, so
16
- * a packet frame (the renderer redrawing for animation) costs the labels nothing.
11
+ * The rule (D2). Every visible node is a candidate at every zoom: there is no zoom cut-off. Candidates are tried in a fixed
12
+ * priority order, and a label whose screen box (plus LABEL_PAD px) touches one already placed is skipped, so no two labels
13
+ * ever collide at any zoom. The order: the selection; the current search match, then the other matches; the selection's lit
14
+ * neighbours; the nodes a proposal (or an outage, or a pull request) marks; hubs (the landmark types: a cluster's title);
15
+ * then the rest, the larger disc first, then the more edges, then scene order. It does not depend on the camera, so a pan never
16
+ * reshuffles it: the placement is made for the whole map at a zoom (a box is `zoom` times its world size, offset from the
17
+ * origin, wherever the camera is), cached per scene and zoom, and the view only picks the boxes that reach the screen.
18
+ * A label is never drawn under 11 px (a hub's, 13 px, bold; a theme may raise the 11 with `--corn-map-label-min`): text that
19
+ * would be smaller is not drawn smaller, it competes for room at 11 px. Zoomed in, it grows with the map.
20
+ * A node left without a label is named by a chip over everything else while the pointer is on it (`hover`).
21
+ * Lane titles, notes and arrows and the selection's edge labels are always included and take no part in the placing.
22
+ * The layer redraws only when the camera, the scene, the size or the hover changed, so a packet frame (the renderer
23
+ * redrawing for animation) costs the labels nothing.
17
24
  *
18
25
  * Pure like scene.js apart from the layer's own canvas: it reads a scene, a camera and a size,
19
26
  * never the explorer's state.
20
27
  *
21
28
  * @typedef {object} LabelItem One piece of text to draw
22
- * @property {'node'|'edge'|'lane'} kind
23
- * @property {string} [id] the node, for `kind: 'node'`
29
+ * @property {'node'|'edge'|'lane'|'chip'} kind
30
+ * @property {string} [id] the node, for `kind: 'node'` and `'chip'`
24
31
  * @property {string} text
25
32
  * @property {number} x world coordinates; the text is drawn on this baseline point
26
33
  * @property {number} y
@@ -33,41 +40,132 @@
33
40
  * @property {'center'} align
34
41
  * @property {string} family CSS font-family
35
42
  * @property {boolean} [strike] a line through the text: a node a proposal removes
43
+ * @property {number} [px] a node's label: its size on screen (px)
44
+ * @property {boolean} [screen] a node's label at its minimum size: drawn in screen space at `px`, so the font stays one string while the zoom changes (a changing font string is the slow part of drawing text)
36
45
  */
37
46
 
38
- import { EDGE_LABEL_SIZE, FONT_EDGE, FONT_NODE, labelAt, looksFor } from './scene.js';
47
+ import { EDGE_LABEL_SIZE, FONT_EDGE, FONT_NODE, HUB_LABEL_EXTRA_PX, LABEL_MIN_FLOOR, LABEL_MIN_PX, LANDMARK_TYPES, looksFor } from './scene.js';
39
48
  import { getMapStyle, styledScene } from './map-style.js';
40
49
 
41
- /** At most this many node labels at a time (lane text and selection edge labels are extra) */
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 */
42
51
  export const MAX_LABELS = 400;
43
52
  /** A label this many screen px past the viewport is still kept, so none pops in at the border */
44
53
  export const CULL_MARGIN = 32;
54
+ /** A label whose box, this many px bigger on every side, touches a placed one is skipped: placed labels are at least this far apart */
55
+ export const LABEL_PAD = 2;
56
+ /** A label dimmer than this (a node the focus or a search dims) takes no room: nobody can read it */
57
+ export const MIN_LABEL_ALPHA = 0.15;
45
58
  /** A label's box: this many sizes above its baseline, and this many below */
46
59
  const ASCENT = 1;
47
60
  const DESCENT = 0.3;
48
61
  /** Average glyph width, in sizes, when nothing measures the text */
49
62
  const GLYPH = 0.58;
63
+ /** The gap between a disc and its label (px; at least the 3 world units it was, once zoomed in) */
64
+ const GAP_PX = 3;
65
+ /** The size text is measured at (then scaled): one measurement per string, whatever the zoom */
66
+ const REF = 100;
67
+ /** The grid the placing looks for neighbours in (px) */
68
+ const CELL = 64;
50
69
 
51
- const estimate = (text, size) => text.length * size * GLYPH;
70
+ /** Priority tiers, best first */
71
+ const TIER = { selected: 0, current: 1, match: 2, lit: 3, marked: 4, hub: 5, rest: 6 };
52
72
 
53
- /** Priority tiers, lowest first: the selection and its neighbours, search matches, landmarks, the rest */
54
- const TIER_FOCUS = 0;
55
- const TIER_MATCH = 1;
56
- const TIER_LANDMARK = 2;
57
- const TIER_REST = 3;
73
+ /**
74
+ * The smallest label size on screen (px) for a theme's `--corn-map-label-min` (a number, or null for `auto`): a theme may raise the 11 px,
75
+ * never lower it (spec 0008, open question 3). 9 and 10 px are read but drawn at 11; under 9 px is not read at all (map-style.js), and
76
+ * `validate` warns.
77
+ * @param {number|null|undefined} value
78
+ */
79
+ export const labelMinPx = (value) => (Number.isFinite(value) && value >= LABEL_MIN_FLOOR ? Math.max(LABEL_MIN_PX, value) : LABEL_MIN_PX);
80
+ /** The smallest label size on screen (px) for a scene: the theme's `--corn-map-label-min`, never under 11 */
81
+ export const labelMinOf = (scene) => labelMinPx(scene.labelMin);
82
+
83
+ const isHub = (node) => LANDMARK_TYPES.includes(node.type);
84
+
85
+ const tierOf = (node, focused) => (node.selected ? TIER.selected
86
+ : node.current ? TIER.current
87
+ : node.match ? TIER.match
88
+ : focused && node.connected ? TIER.lit
89
+ : (node.mark && node.mark !== 'none') || (node.labelKeep && !isHub(node)) ? TIER.marked
90
+ : isHub(node) ? TIER.hub : TIER.rest);
91
+
92
+ /**
93
+ * Which node labels fit at `zoom`, and where. The whole map, not the view: a box is in zoom-scaled world coordinates (`x * zoom`, no
94
+ * camera), so the answer is the same wherever the camera is and can be kept for as long as the scene and the zoom stay.
95
+ * @param {import('./scene.js').Scene} scene
96
+ * @param {number} zoom
97
+ * @param {{measure?: (text: string, size: number, bold: boolean) => number}} [opts]
98
+ * `measure`: the width of a text at that font size (px); default: an estimate from its length
99
+ * @returns {{index: number, id: string, rank: number, tier: number, px: number, bold: boolean, size: number, x: number, y: number, node: object, l: number, t: number, r: number, b: number}[]}
100
+ * in priority order: `rank` is the place in it
101
+ */
102
+ export function placeLabels(scene, zoom, opts = {}) {
103
+ const { measure = null } = opts;
104
+ const min = labelMinOf(scene);
105
+ const focused = scene.nodes.some((n) => n.selected || !n.connected);
106
+ const cands = [];
107
+ scene.nodes.forEach((node, index) => {
108
+ if (!node.label || !(node.labelAlpha >= MIN_LABEL_ALPHA)) return;
109
+ cands.push({ node, index, tier: tierOf(node, focused) });
110
+ });
111
+ cands.sort((a, b) => a.tier - b.tier || b.node.r - a.node.r || (b.node.degree || 0) - (a.node.degree || 0) || a.index - b.index);
112
+
113
+ const grid = new Map(); // cell -> the placed boxes that reach it; the key is a number (a string key per cell was most of the time)
114
+ const cellKey = (i, j) => (i + 8192) * 16384 + (j + 8192);
115
+ const placed = [];
116
+ const gap = Math.max(GAP_PX, GAP_PX * zoom);
117
+ for (const { node, index, tier } of cands) {
118
+ const hub = isHub(node);
119
+ const bold = !!node.labelBold || hub;
120
+ const px = Math.max(hub ? min + HUB_LABEL_EXTRA_PX : min, node.labelSize * zoom);
121
+ const w = measure ? (measure(node.label, REF, bold) * px) / REF : node.label.length * px * GLYPH;
122
+ const cx = node.x * zoom;
123
+ const baseline = node.y * zoom + node.r * zoom + gap + px;
124
+ const l = cx - w / 2, r = cx + w / 2, t = baseline - px * ASCENT, b = baseline + px * DESCENT;
125
+ // Touching a placed box, give or take LABEL_PAD: skipped
126
+ const i0 = Math.floor((l - LABEL_PAD) / CELL), i1 = Math.floor((r + LABEL_PAD) / CELL);
127
+ const j0 = Math.floor((t - LABEL_PAD) / CELL), j1 = Math.floor((b + LABEL_PAD) / CELL);
128
+ let hit = false;
129
+ for (let i = i0; i <= i1 && !hit; i++) {
130
+ for (let j = j0; j <= j1 && !hit; j++) {
131
+ const cell = grid.get(cellKey(i, j));
132
+ if (!cell) continue;
133
+ for (let k = 0; k < cell.length; k++) {
134
+ const o = cell[k];
135
+ if (l - LABEL_PAD < o.r && r + LABEL_PAD > o.l && t - LABEL_PAD < o.b && b + LABEL_PAD > o.t) { hit = true; break; }
136
+ }
137
+ }
138
+ }
139
+ if (hit) continue;
140
+ const item = {
141
+ index, id: node.id, rank: placed.length, tier, px, bold, screen: node.labelSize * zoom <= (hub ? min + HUB_LABEL_EXTRA_PX : min), size: px / zoom, x: node.x, y: node.y + node.r + (gap + px) / zoom,
142
+ node, l, t, r, b,
143
+ };
144
+ placed.push(item);
145
+ const ci0 = Math.floor(l / CELL), ci1 = Math.floor(r / CELL), cj0 = Math.floor(t / CELL), cj1 = Math.floor(b / CELL);
146
+ for (let i = ci0; i <= ci1; i++) for (let j = cj0; j <= cj1; j++) {
147
+ const key = cellKey(i, j);
148
+ const cell = grid.get(key);
149
+ if (cell) cell.push(item); else grid.set(key, [item]);
150
+ }
151
+ }
152
+ return placed;
153
+ }
58
154
 
59
155
  /**
60
156
  * The text to draw for `scene` seen through `camera` in a `viewport`
61
157
  * @param {import('./scene.js').Scene} scene
62
158
  * @param {import('./scene.js').Camera} camera
63
159
  * @param {{width:number, height:number}} viewport CSS px
64
- * @param {{max?:number, margin?:number, measure?:(text:string, size:number, bold:boolean) => number}} [opts]
65
- * `max` node labels (default 400); `margin` px past the viewport (default 32); `measure` the
66
- * width in world units of a label (default: an estimate from its length)
67
- * @returns {LabelItem[]} lane text, then edge labels, then node labels in scene order
160
+ * @param {{max?:number, margin?:number, measure?:(text:string, size:number, bold:boolean) => number, hover?:string|null,
161
+ * placed?: ReturnType<typeof placeLabels>}} [opts]
162
+ * `max` node labels in view (default 400); `margin` px past the viewport (default 32); `measure` the width of a text at a font
163
+ * size (default: an estimate from its length); `hover`: the node the pointer is on, named by a chip when it has no label;
164
+ * `placed`: the placing for this scene at this zoom, when the caller has kept it (default: made here)
165
+ * @returns {LabelItem[]} lane text, then edge labels, then node labels in scene order, then the chip
68
166
  */
69
167
  export function chooseLabels(scene, camera, viewport, opts = {}) {
70
- const { max = MAX_LABELS, margin = CULL_MARGIN, measure = null } = opts;
168
+ const { max = MAX_LABELS, margin = CULL_MARGIN, measure = null, hover = null } = opts;
71
169
  const out = [];
72
170
  const outline = scene.labelOutline || looksFor(scene.theme).labelOutline; // the ground's own colour (or the theme's --corn-map-label-halo), under the text
73
171
 
@@ -83,66 +181,93 @@ export function chooseLabels(scene, camera, viewport, opts = {}) {
83
181
  if (l) out.push({ kind: 'edge', text: l.text, x: l.x, y: l.y, size: EDGE_LABEL_SIZE, bold: false, italic: !!l.italic, color: l.color, alpha: edge.alpha, outline: outline.edge, align: 'center', family: scene.labelFont || FONT_EDGE });
84
182
  }
85
183
 
86
- // Node labels: level of detail, then the ones whose box reaches the viewport
184
+ // Node labels: the placing for this zoom, then the boxes that reach the viewport
87
185
  const { zoom } = camera;
88
- const minX = -margin, maxX = viewport.width + margin;
89
- const minY = -margin, maxY = viewport.height + margin;
90
- const focused = scene.nodes.some((n) => n.selected || !n.connected);
91
- const found = [];
92
-
93
- scene.nodes.forEach((node, index) => {
94
- const label = labelAt(node, zoom, scene);
95
- if (!label) return;
96
- const sy = camera.y + label.y * zoom;
97
- if (sy + label.size * DESCENT * zoom < minY || sy - label.size * ASCENT * zoom > maxY) return;
98
- const sx = camera.x + label.x * zoom;
99
- // A label centred inside the viewport is in view whatever its width: text is measured only
100
- // for the ones centred past a side edge, where its half width decides
101
- if (sx < minX || sx > maxX) {
102
- const half = ((measure ? measure(label.text, label.size, label.bold) : estimate(label.text, label.size)) / 2) * zoom;
103
- if (sx + half < minX || sx - half > maxX) return;
104
- }
105
-
106
- const tier = node.selected || (focused && node.connected) ? TIER_FOCUS : node.match ? TIER_MATCH : node.labelKeep ? TIER_LANDMARK : TIER_REST;
107
- found.push({ index, tier, r: node.r, label, id: node.id });
108
- });
109
-
110
- // Over the cap: keep the best `max`. Sorting by (tier, larger radius, scene order) is a total order
111
- // that does not depend on the camera, so the same nodes win while the view pans.
112
- let kept = found;
113
- if (found.length > max) {
114
- kept = found.slice().sort((a, b) => a.tier - b.tier || b.r - a.r || a.index - b.index).slice(0, Math.max(0, max));
115
- kept.sort((a, b) => a.index - b.index); // draw in scene order, as the circles are
186
+ const placed = opts.placed || placeLabels(scene, zoom, { measure });
187
+ const minX = -margin - camera.x, maxX = viewport.width + margin - camera.x;
188
+ const minY = -margin - camera.y, maxY = viewport.height + margin - camera.y;
189
+ let inView = placed.filter((p) => p.r >= minX && p.l <= maxX && p.b >= minY && p.t <= maxY);
190
+ // Over the cap: the best `max` (the placing is in priority order, so the same ones win while the view pans)
191
+ if (inView.length > max) inView = inView.slice(0, Math.max(0, max)); // placed is in priority order
192
+ inView.sort((a, b) => a.index - b.index); // drawn in scene order, as the circles are
193
+ const family = scene.labelFont || FONT_NODE;
194
+ for (const p of inView) {
195
+ const k = Math.max(1, 1 / zoom); // the outline keeps its weight on screen (3.5 px) when zoomed out, and grows with the map when zoomed in
196
+ out.push({ kind: 'node', id: p.id, text: p.node.label, x: p.x, y: p.y, size: p.size, bold: p.bold, italic: false, color: p.node.labelColor, alpha: p.node.labelAlpha, outline: outline.node ? { color: outline.node.color, width: outline.node.width * k } : null, align: 'center', family, strike: !!p.node.labelStrike, px: p.px, screen: p.screen });
116
197
  }
117
198
 
118
- for (const { label, id } of kept) {
119
- out.push({ kind: 'node', id, text: label.text, x: label.x, y: label.y, size: label.size, bold: label.bold, italic: false, color: label.color, alpha: label.alpha, outline: outline.node, align: 'center', family: scene.labelFont || FONT_NODE, strike: !!label.strike });
199
+ // The chip: a node with no label, named while the pointer is on it
200
+ if (hover) {
201
+ const node = scene.nodes.find((n) => n.id === hover);
202
+ if (node && node.label && !placed.some((p) => p.id === hover && inView.includes(p))) {
203
+ const px = labelMinOf(scene);
204
+ const above = camera.y + node.y * zoom - node.r * zoom > 40; // room above it, else below
205
+ const y = above ? node.y - node.r - (GAP_PX + 2) / zoom : node.y + node.r + (GAP_PX + 2 + px) / zoom;
206
+ out.push({ kind: 'chip', id: node.id, text: node.label, x: node.x, y, size: px / zoom, px, screen: true, bold: false, italic: false, color: (scene.nodes.find((n) => n.connected) || node).labelColor, alpha: 1, outline: outline.node, align: 'center', family, strike: false });
207
+ }
120
208
  }
121
209
  return out;
122
210
  }
123
211
 
124
- const fontOf = (t) => `${t.italic ? 'italic ' : ''}${t.bold ? 'bold ' : ''}${t.size}px ${t.family}`;
212
+ const fontOf = (t) => `${t.italic ? 'italic ' : ''}${t.bold ? 'bold ' : ''}${t.screen ? t.px : t.size}px ${t.family}`;
213
+
214
+ /** Where an item goes on the canvas: `ox`, `oy` and `k`, from world to the context (the world pass draws under the camera's transform, so `{0, 0, 1}`; the screen pass under none) */
215
+ const WORLD = { ox: 0, oy: 0, k: 1 };
125
216
 
126
- function drawItem(ctx, t) {
127
- ctx.globalAlpha = t.alpha;
217
+ /** The chip behind a hovered node's name: a rounded box in the label outline's colour, over everything else (drawn in screen space) */
218
+ function drawChip(ctx, t, v) {
128
219
  ctx.font = fontOf(t);
220
+ const pad = 4;
221
+ const w = ctx.measureText(t.text).width + pad * 2;
222
+ const h = t.px * (ASCENT + DESCENT) + pad;
223
+ const tx = v.ox + t.x * v.k, ty = v.oy + t.y * v.k;
224
+ const x = tx - w / 2, y = ty - t.px * ASCENT - pad / 2;
225
+ ctx.globalAlpha = 1;
226
+ ctx.beginPath();
227
+ if (ctx.roundRect) ctx.roundRect(x, y, w, h, 4); else ctx.rect(x, y, w, h);
228
+ ctx.fillStyle = t.outline ? t.outline.color : 'rgba(9, 13, 22, 0.95)';
229
+ ctx.fill();
230
+ ctx.lineWidth = 1;
231
+ ctx.strokeStyle = t.color;
232
+ ctx.stroke();
129
233
  ctx.textAlign = t.align;
234
+ ctx.fillStyle = t.color;
235
+ ctx.fillText(t.text, tx, ty);
236
+ }
237
+
238
+ /**
239
+ * What the context was last set to while one draw runs: setting a font, a width or a colour is not free, and a map of hundreds of
240
+ * labels at one size repeats the same few values. `pen` is reset at the start of every draw (and where the context is saved and restored).
241
+ */
242
+ function newPen() { return { font: '', alpha: -1, fill: '', stroke: '', width: -1, align: '' }; }
243
+
244
+ /** Draws one item at `v` (WORLD under the camera's transform, or the screen's own `{ ox: camera.x, oy: camera.y, k: zoom }` under none) */
245
+ function drawItem(ctx, t, pen, v = WORLD) {
246
+ if (t.kind === 'chip') { drawChip(ctx, t, v); return; }
247
+ if (pen.alpha !== t.alpha) { ctx.globalAlpha = t.alpha; pen.alpha = t.alpha; }
248
+ const font = fontOf(t);
249
+ if (pen.font !== font) { ctx.font = font; pen.font = font; }
250
+ if (pen.align !== t.align) { ctx.textAlign = t.align; pen.align = t.align; }
251
+ const x = v.ox + t.x * v.k, y = v.oy + t.y * v.k;
130
252
  if (t.outline) {
131
253
  ctx.lineJoin = 'round';
132
- ctx.strokeStyle = t.outline.color;
133
- ctx.lineWidth = t.outline.width;
134
- ctx.strokeText(t.text, t.x, t.y);
254
+ const width = t.outline.width * v.k;
255
+ if (pen.stroke !== t.outline.color) { ctx.strokeStyle = t.outline.color; pen.stroke = t.outline.color; }
256
+ if (pen.width !== width) { ctx.lineWidth = width; pen.width = width; }
257
+ ctx.strokeText(t.text, x, y);
135
258
  }
136
- ctx.fillStyle = t.color;
137
- ctx.fillText(t.text, t.x, t.y);
259
+ if (pen.fill !== t.color) { ctx.fillStyle = t.color; pen.fill = t.color; }
260
+ ctx.fillText(t.text, x, y);
138
261
  if (t.strike) {
139
262
  const half = ctx.measureText(t.text).width / 2;
263
+ const size = t.screen ? t.px : t.size * v.k;
140
264
  ctx.beginPath();
141
- ctx.moveTo(t.x - half, t.y - t.size * 0.32);
142
- ctx.lineTo(t.x + half, t.y - t.size * 0.32);
265
+ ctx.moveTo(x - half, y - size * 0.32);
266
+ ctx.lineTo(x + half, y - size * 0.32);
143
267
  ctx.strokeStyle = t.color;
144
268
  ctx.lineWidth = 1.4;
145
269
  ctx.stroke();
270
+ pen.stroke = t.color; pen.width = 1.4; // the strike left its own colour and width on the context
146
271
  }
147
272
  }
148
273
 
@@ -166,19 +291,36 @@ function coverWithNodes(ctx, nodes) {
166
291
  ctx.restore();
167
292
  }
168
293
 
294
+ /**
295
+ * The placed label under a screen point, or null: the one drawn on top (the last in scene order) when two overlap their padding
296
+ * @param {ReturnType<typeof placeLabels>} placed
297
+ * @param {import('./scene.js').Camera} camera
298
+ * @param {number} x screen px
299
+ * @param {number} y
300
+ */
301
+ export function labelHit(placed, camera, x, y) {
302
+ let hit = null;
303
+ for (const p of placed) {
304
+ if (x >= camera.x + p.l && x <= camera.x + p.r && y >= camera.y + p.t && y <= camera.y + p.b && (!hit || p.index > hit.index)) hit = p;
305
+ }
306
+ return hit ? hit.id : null;
307
+ }
308
+
169
309
  /**
170
310
  * A transparent 2D canvas that draws the chosen labels over the map
171
311
  * @param {HTMLCanvasElement} canvas
172
312
  * @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`);
173
313
  * 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
174
- * @returns {{draw: (scene: import('./scene.js').Scene, camera: import('./scene.js').Camera) => boolean, resize: (width: number, height: number, dpr: number) => void, destroy: () => void}}
175
- * `draw` returns whether it painted: false when the camera, the scene and the size were unchanged
314
+ * @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}}
315
+ * `draw` returns whether it painted: false when the camera, the scene, the size and the hovered node were unchanged; `extras.hover` is the
316
+ * node the pointer is on (named by a chip when it has no label)
176
317
  */
177
318
  export function createLabelLayer(canvas, opts = {}) {
178
319
  const styleOf = opts.mapStyle || getMapStyle;
179
320
  const ctx = canvas.getContext('2d');
180
321
  let width = 0, height = 0, dpr = 1;
181
- let lastScene = null, lastVersion, lastX, lastY, lastZoom, lastStyle;
322
+ let lastScene = null, lastVersion, lastX, lastY, lastZoom, lastStyle, lastHover;
323
+ let kept = null; // the placing for the scene and zoom last drawn: a pan reuses it (placeLabels)
182
324
  let dirty = true;
183
325
  let destroyed = false;
184
326
 
@@ -189,6 +331,7 @@ export function createLabelLayer(canvas, opts = {}) {
189
331
  const key = `${bold ? 'b' : 'n'}${size}|${family}|${text}`;
190
332
  let w = widths.get(key);
191
333
  if (w === undefined) {
334
+ if (widths.size > 20000) widths.clear(); // a long session on a big map: start again rather than grow
192
335
  ctx.font = fontOf({ italic: false, bold, size, family });
193
336
  w = ctx.measureText(text).width;
194
337
  widths.set(key, w);
@@ -197,6 +340,11 @@ export function createLabelLayer(canvas, opts = {}) {
197
340
  };
198
341
 
199
342
  return {
343
+ /** The node whose label is drawn under a screen point (a cluster's title: input.js frames the cluster), or null */
344
+ hit(x, y) {
345
+ return kept && lastScene ? labelHit(kept, { x: lastX, y: lastY, zoom: lastZoom }, x, y) : null;
346
+ },
347
+
200
348
  resize(w, h, ratio) {
201
349
  width = w;
202
350
  height = h;
@@ -207,12 +355,14 @@ export function createLabelLayer(canvas, opts = {}) {
207
355
  dirty = true;
208
356
  },
209
357
 
210
- draw(drawn, camera) {
358
+ draw(drawn, camera, extras = {}) {
211
359
  if (destroyed) return false;
212
360
  const style = styleOf();
213
361
  const styleKey = style.plain ? 0 : style.version;
214
- if (!dirty && drawn === lastScene && drawn.version === lastVersion && camera.x === lastX && camera.y === lastY && camera.zoom === lastZoom && styleKey === lastStyle) return false;
215
- lastScene = drawn; lastVersion = drawn.version; lastX = camera.x; lastY = camera.y; lastZoom = camera.zoom; lastStyle = styleKey;
362
+ const hover = extras.hover || null;
363
+ if (!dirty && drawn === lastScene && drawn.version === lastVersion && camera.x === lastX && camera.y === lastY && camera.zoom === lastZoom && styleKey === lastStyle && hover === lastHover) return false;
364
+ const samePlacing = kept && drawn === lastScene && drawn.version === lastVersion && camera.zoom === lastZoom && styleKey === lastStyle && !dirty;
365
+ lastScene = drawn; lastVersion = drawn.version; lastX = camera.x; lastY = camera.y; lastZoom = camera.zoom; lastStyle = styleKey; lastHover = hover;
216
366
  dirty = false;
217
367
  const scene = styledScene(drawn, style); // the label colours and font of the theme (map-style.js)
218
368
  family = scene.labelFont || FONT_NODE;
@@ -222,20 +372,29 @@ export function createLabelLayer(canvas, opts = {}) {
222
372
  ctx.save();
223
373
  ctx.translate(camera.x, camera.y);
224
374
  ctx.scale(camera.zoom, camera.zoom);
225
- const items = chooseLabels(scene, camera, { width, height }, { measure });
226
- let covered = !items.some((t) => t.kind === 'edge');
227
- items.forEach((t) => {
228
- if (!covered && t.kind === 'node') { coverWithNodes(ctx, scene.nodes); covered = true; }
229
- drawItem(ctx, t);
230
- });
231
- if (!covered) coverWithNodes(ctx, scene.nodes);
375
+ // The placing is for the whole map at this zoom: kept while the scene, the zoom and the style stay (a pan, a hover), made again when one changes
376
+ if (!samePlacing) kept = placeLabels(scene, camera.zoom, { measure });
377
+ const items = chooseLabels(scene, camera, { width, height }, { measure, hover, placed: kept });
378
+ // The lane text and the selection's edge labels, then the circles cut out of them (only when there are edge labels), then the node labels
379
+ let pen = newPen();
380
+ let edges = false;
381
+ for (const t of items) { if (t.kind === 'lane' || t.kind === 'edge') { drawItem(ctx, t, pen); if (t.kind === 'edge') edges = true; } }
382
+ if (edges) { coverWithNodes(ctx, scene.nodes); pen = newPen(); }
383
+ for (const t of items) if (t.kind === 'node' && !t.screen) drawItem(ctx, t, pen); // a label that grows with the map: the camera's transform
232
384
  ctx.restore();
385
+ // A label at its minimum size is drawn in screen space at a whole font size, whatever the zoom: the font string does not change as the
386
+ // zoom does, and text is what costs in a frame; then the chip, over everything
387
+ const screen = { ox: camera.x, oy: camera.y, k: camera.zoom };
388
+ pen = newPen();
389
+ for (const t of items) if (t.kind === 'node' && t.screen) drawItem(ctx, t, pen, screen);
390
+ for (const t of items) if (t.kind === 'chip') drawItem(ctx, t, pen, screen);
233
391
  return true;
234
392
  },
235
393
 
236
394
  destroy() {
237
395
  destroyed = true;
238
396
  lastScene = null;
397
+ kept = null;
239
398
  widths.clear();
240
399
  ctx.setTransform(1, 0, 0, 1, 0, 0);
241
400
  ctx.clearRect(0, 0, width, height);
@@ -51,8 +51,8 @@ export function labelWidth(node) {
51
51
  // 1. The data tier (stores, tables, ROM stages) rings the root, grouped by kind.
52
52
  // 2. A hub's children fill concentric rings around it; the spacing along a ring
53
53
  // comes from that cluster's own label widths, so labels never collide.
54
- // 3. Hubs with children share one ring around the core, each taking arc in
55
- // proportion to its cluster's size; the ring is sized so clusters never touch.
54
+ // 3. Hubs with children are packed round the core, largest first (ties by label), each in the free place nearest it,
55
+ // searched from the top clockwise (spec 0008 D1); a cluster's place depends only on the ones placed before it.
56
56
  // 4. Childless hubs (leaf apps, tools, packages) sit on an outer ring.
57
57
  // ---------------------------------------------------------------------------
58
58
  const DATA_TYPES = ['store', 'table', 'rom'];
@@ -145,6 +145,34 @@ function placePack(pack, ox, oy, clusters) {
145
145
  });
146
146
  }
147
147
 
148
+
149
+ /**
150
+ * The free place nearest (0, 0) for a disc of radius `r` among `discs` (`{ x, y, r }`, each already holding its own gap),
151
+ * searched along rays from the top clockwise every STEP degrees: on each ray the nearest point where the disc touches
152
+ * none, and of the rays the nearest of all, the first in the search order winning a tie. Exact and deterministic.
153
+ */
154
+ const PACK_STEP_DEG = 2;
155
+ function nearestFreePlace(discs, r) {
156
+ let best = null;
157
+ for (let deg = 0; deg < 360; deg += PACK_STEP_DEG) {
158
+ const a = -Math.PI / 2 + (deg * Math.PI) / 180;
159
+ const dx = Math.cos(a), dy = Math.sin(a);
160
+ // The stretches of this ray where the disc would touch another (open intervals of the distance along it)
161
+ const blocked = [];
162
+ for (const d of discs) {
163
+ const along = dx * d.x + dy * d.y;
164
+ const reach = d.r + r;
165
+ const disc = along * along - (d.x * d.x + d.y * d.y) + reach * reach;
166
+ if (disc > 0) blocked.push([along - Math.sqrt(disc), along + Math.sqrt(disc)]);
167
+ }
168
+ blocked.sort((p, q) => p[0] - q[0]);
169
+ let at = 0;
170
+ for (const [lo, hi] of blocked) if (lo < at + 1e-9 && hi > at) at = hi;
171
+ if (!best || at < best.at - 1e-6) best = { at, x: dx * at, y: dy * at };
172
+ }
173
+ return best;
174
+ }
175
+
148
176
  export function computeOrbitalLayout() {
149
177
  touchScene(); // positions and rings change
150
178
  const { nodes, edges } = state;
@@ -214,31 +242,31 @@ export function computeOrbitalLayout() {
214
242
  packs.set(hub.id, packTree(children, kidsOf, spacingOf, byTypeThenLabel, new Set([hub.id])));
215
243
  });
216
244
 
217
- // 3. Hubs with children around the core, arc proportional to cluster size
245
+ // 3. Hubs with children, packed (spec 0008 D1): the largest cluster first (ties by label) takes the free place nearest
246
+ // the core, searched from the top clockwise, GAP from every cluster already placed. No physics: the same map
247
+ // always draws the same, and a cluster's place depends only on the ones placed before it.
218
248
  const GAP = 70;
219
- const big = hubs.filter((h) => packs.has(h.id)).sort((a, b) => packs.get(b.id).extent - packs.get(a.id).extent);
220
- const maxExtent = big.length ? Math.max(...big.map((h) => packs.get(h.id).extent)) : 0;
221
- const need = big.reduce((s, h) => s + 2 * packs.get(h.id).extent + GAP, 0);
222
- const hubR = Math.max(coreExtent + maxExtent + GAP, need / (2 * Math.PI));
223
- let angle = -Math.PI / 2;
249
+ const big = hubs.filter((h) => packs.has(h.id))
250
+ .sort((a, b) => packs.get(b.id).extent - packs.get(a.id).extent || String(a.label).localeCompare(String(b.label)));
251
+ const discs = [{ x: 0, y: 0, r: coreExtent }];
252
+ let hubReach = coreExtent; // how far from the centre the packed clusters reach
224
253
  big.forEach((hub) => {
225
254
  const pack = packs.get(hub.id);
226
- const share = ((2 * pack.extent + GAP) / need) * Math.PI * 2;
227
- const a = angle + share / 2;
228
- hub.x = Math.cos(a) * hubR;
229
- hub.y = Math.sin(a) * hubR;
255
+ const at = nearestFreePlace(discs, pack.extent + GAP / 2);
256
+ hub.x = at.x;
257
+ hub.y = at.y;
258
+ discs.push({ x: hub.x, y: hub.y, r: pack.extent + GAP / 2 });
259
+ hubReach = Math.max(hubReach, Math.hypot(hub.x, hub.y) + pack.extent);
230
260
  LAYOUT.clusters.push({ x: hub.x, y: hub.y, radii: pack.radii });
231
261
  placePack(pack, hub.x, hub.y, LAYOUT.clusters);
232
- angle += share;
233
262
  });
234
- if (big.length) LAYOUT.rings.push({ x: 0, y: 0, r: hubR });
235
263
 
236
264
  // 4. Childless hubs on an outer ring, and with them any node that has no parent and is none of the above
237
265
  // (it would otherwise sit on the centre, under whatever else is there)
238
266
  const homeless = nodes.filter((n) => n.id !== 'root' && !parentMap[n.id] && !isData(n) && !hubIds.has(n.id));
239
267
  const leaves = [...hubs.filter((h) => !packs.has(h.id)), ...homeless].sort(byTypeThenLabel);
240
268
  const leafSpacing = Math.max(120, ...leaves.map((n) => labelWidth(n) + 30));
241
- const leafR = Math.max(hubR + maxExtent + 90, (leaves.length * leafSpacing) / (2 * Math.PI));
269
+ const leafR = Math.max(hubReach + 90, (leaves.length * leafSpacing) / (2 * Math.PI));
242
270
  leaves.forEach((n, i) => {
243
271
  const a = -Math.PI / 2 + (i / Math.max(1, leaves.length)) * Math.PI * 2;
244
272
  n.x = Math.cos(a) * leafR;
package/explorer/main.js CHANGED
@@ -17,6 +17,7 @@
17
17
  * scenario.js the player's pure core scenario-ui.js its bar, keys and camera
18
18
  * bench.js /?bench=1 stopwatch and /?fixture=5k (the generated topology, from the server)
19
19
  * keyboard.js the map by keyboard and the screen reader's announcer; keyboard-model.js its pure half
20
+ * search.js search: the count, the list by type and the stepping; search-model.js its pure half (what it reads and the rank)
20
21
  * live.js the live layer: the chip, polling, laying a live source's answer over the map; live-model.js its pure half
21
22
  * review-tokens.js review tokens for the review API, when somebody is signed in: make one (shown once), list, revoke; review-tokens-model.js its pure half
22
23
  * forge-panel.js the issues and PRs panel, when the config names a forge: a PR lights the nodes it changes; forge-panel-model.js its pure half
@@ -24,7 +25,7 @@
24
25
  */
25
26
 
26
27
  import { state, nodeById, touchScene } from './state.js';
27
- import { updateSearchStatus } from './search-status.js';
28
+ import { initSearch, setQuery, stepMatch } from './search.js';
28
29
  import { render, resize, fitGraphToViewport, fitPadding, isNodeVisible, setRenderer, getRenderer, ensureFlowLoop, renderNow, holdFrames } from './render.js';
29
30
  import { createRenderer } from './renderer.js';
30
31
  import { clearFreeformPositions, layoutOrbit, loadFreeformPositions } from './layout.js';
@@ -87,27 +88,6 @@ function resetFreeformPositions() {
87
88
  // ---------------------------------------------------------------------------
88
89
  // Search
89
90
  // ---------------------------------------------------------------------------
90
- function handleSearch(value) {
91
- state.searchQuery = value.trim();
92
- touchScene();
93
- for (const id of ['mobile-node-search', 'node-search']) {
94
- const input = $(id);
95
- if (input && input.value !== value) input.value = value;
96
- }
97
- if (state.searchQuery) {
98
- const q = state.searchQuery.toLowerCase();
99
- const found = state.nodes.find((n) => isNodeVisible(n) && n.label.toLowerCase().includes(q));
100
- if (found) {
101
- state.camera.x = state.width / 2 - found.x * state.camera.zoom;
102
- state.camera.y = state.height / 2 - found.y * state.camera.zoom;
103
- }
104
- updateSearchStatus(state.searchQuery, !!found);
105
- } else {
106
- updateSearchStatus('', false);
107
- }
108
- render();
109
- }
110
-
111
91
  function toggleMobileSearch(open) {
112
92
  const bar = $('mobile-search-bar');
113
93
  const input = $('mobile-node-search');
@@ -142,7 +122,9 @@ const ACTIONS = {
142
122
  },
143
123
  'toggle-mobile-search': () => toggleMobileSearch(),
144
124
  'close-mobile-search': () => toggleMobileSearch(false),
145
- 'clear-search': () => handleSearch(''),
125
+ 'clear-search': () => { setQuery(''); const field = $('node-search'); const bar = $('mobile-search-bar'); (bar && !bar.hidden ? $('mobile-node-search') : field).focus(); },
126
+ 'search-prev': () => stepMatch(-1),
127
+ 'search-next': () => stepMatch(1),
146
128
  'close-drawer': () => closeDrawer(),
147
129
  'copy-spec': (el) => copySpec(el),
148
130
  'start-run': () => startRun(),
@@ -213,8 +195,7 @@ initSheets();
213
195
  initScenarioUi();
214
196
  initReviewColumn(); // the review column: the changes, and the personas with their scenarios (review-column.js)
215
197
  window.addEventListener('resize', resize);
216
- $('node-search').addEventListener('input', (e) => handleSearch(e.target.value));
217
- $('mobile-node-search').addEventListener('input', (e) => handleSearch(e.target.value));
198
+ initSearch(); // the count, the list and the stepping of both search fields (search.js)
218
199
 
219
200
  resize();
220
201
  syncViewUi();