cornfield 0.39.0 → 0.41.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);
@@ -0,0 +1,59 @@
1
+ /**
2
+ * @module explorer/layer-model
3
+ *
4
+ * Which layer a node is in, as the Layers menu and the map read it (spec 0009 D3), from the state alone: no DOM, no drawing.
5
+ *
6
+ * - `projectLayerKey(state, node)`: the first project layer (`state.projectLayers`, from the config's `layers.add`) whose match the node
7
+ * meets, or null. A project layer takes its nodes from their starting layer, so a node is in exactly one row.
8
+ * - `rowKeyOf(state, node)`: the row a node is under: that layer, else its starting layer. The root has none (null).
9
+ * - `shownByProposal(state, node)`: a node the open proposal touches is always drawn, whatever its layer says, so a review never hides its
10
+ * own change.
11
+ *
12
+ * The matching itself is core/layers.js (data only); this file only hands it the map's ownership line.
13
+ */
14
+
15
+ import { kindLetters, layerKeyOf, parentIndex, projectLayerOf } from '../core/layers.js';
16
+ import { touchedIds } from './proposal-model.js';
17
+
18
+ /** Asks the ownership line of the map the state holds, only when a layer matches by `parent` */
19
+ const parentFn = (state) => ((state.projectLayers || []).some((l) => l.match && l.match.parent !== undefined) ? (n) => parentIndex(state.edges || []).get(n.id) : undefined);
20
+
21
+ /** The key of the project layer that takes `node`, or null */
22
+ export function projectLayerKey(state, node) {
23
+ const add = state.projectLayers;
24
+ if (!add || !add.length) return null;
25
+ return projectLayerOf(add, node, parentFn(state));
26
+ }
27
+
28
+ /** The key of the row `node` is under (null for the root) */
29
+ export const rowKeyOf = (state, node) => layerKeyOf(state.projectLayers || [], node, parentFn(state));
30
+
31
+ const touchedMemo = new WeakMap();
32
+ /** The ids of the nodes the open proposal touches: a node it marks, and both ends of an edge it marks (what Diff keeps bright) */
33
+ function touchedBy(state) {
34
+ const edges = state.edges || [];
35
+ const hit = touchedMemo.get(state.nodes);
36
+ if (hit && hit.edges === edges && hit.n === state.nodes.length && hit.e === edges.length) return hit.touched;
37
+ const touched = touchedIds(state.nodes, edges).touched;
38
+ touchedMemo.set(state.nodes, { edges, n: state.nodes.length, e: edges.length, touched });
39
+ return touched;
40
+ }
41
+
42
+ /** Whether the open proposal touches `node` (false with no proposal open) */
43
+ export const shownByProposal = (state, node) => !!state.proposal && touchedBy(state).has(node.id);
44
+
45
+ const lettersMemo = new WeakMap();
46
+ /**
47
+ * The letters of the node's finer kind (core/layers.js `kindLetters`, over the whole map so two kinds of a type never share one), or ''.
48
+ * An outside node's kind is its layer (cloud or web), not a finer one.
49
+ */
50
+ export function lettersOf(state, node) {
51
+ if (typeof node.kind !== 'string' || !node.kind || node.type === 'external') return '';
52
+ let hit = lettersMemo.get(state.nodes);
53
+ if (!hit || hit.n !== state.nodes.length) {
54
+ hit = { n: state.nodes.length, map: kindLetters(state.nodes) };
55
+ lettersMemo.set(state.nodes, hit);
56
+ }
57
+ const t = hit.map.get(node.type);
58
+ return (t && t.get(node.kind)) || '';
59
+ }