@ai-gui/plugin-bigscreen 0.36.3 → 0.37.1

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.
@@ -0,0 +1,1621 @@
1
+ //#region src/palette.ts
2
+ /**
3
+ * Two palettes, one per theme.
4
+ *
5
+ * The dark one is the data-wall look — deep navy, cyan accent, a little glow; the light one is
6
+ * the same screen on a white page. The accent can be overridden per screen, and the series
7
+ * colours start from it so a screen reads as one thing rather than a collage.
8
+ */
9
+ function palette(definition) {
10
+ const accent = definition.accent ?? (definition.theme === "dark" ? "#22d3ee" : "#0369a1");
11
+ return definition.theme === "dark" ? {
12
+ accent,
13
+ text: "#e2e8f0",
14
+ muted: "#94a3b8",
15
+ good: "#34d399",
16
+ bad: "#fb7185",
17
+ warn: "#fbbf24",
18
+ track: "rgba(148,163,184,0.18)",
19
+ series: [
20
+ accent,
21
+ "#a78bfa",
22
+ "#34d399",
23
+ "#fbbf24",
24
+ "#fb7185",
25
+ "#60a5fa",
26
+ "#f472b6",
27
+ "#2dd4bf"
28
+ ],
29
+ gridLine: "rgba(148,163,184,0.16)"
30
+ } : {
31
+ accent,
32
+ text: "#1e293b",
33
+ muted: "#64748b",
34
+ good: "#059669",
35
+ bad: "#e11d48",
36
+ warn: "#d97706",
37
+ track: "rgba(100,116,139,0.16)",
38
+ series: [
39
+ accent,
40
+ "#7c3aed",
41
+ "#059669",
42
+ "#d97706",
43
+ "#e11d48",
44
+ "#2563eb",
45
+ "#db2777",
46
+ "#0d9488"
47
+ ],
48
+ gridLine: "rgba(100,116,139,0.2)"
49
+ };
50
+ }
51
+ /** `#rrggbb` with an alpha, for glows and fills. */
52
+ function withAlpha(hex, alpha) {
53
+ const h = hex.replace("#", "");
54
+ const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
55
+ const n = Number.parseInt(full, 16);
56
+ return `rgba(${n >> 16 & 255},${n >> 8 & 255},${n & 255},${alpha})`;
57
+ }
58
+
59
+ //#endregion
60
+ //#region src/options.ts
61
+ /**
62
+ * ECharts options built from panels.
63
+ *
64
+ * Pure functions of the panel and the palette, so they can be tested without a canvas and so
65
+ * the same panel draws the same chart on every screen.
66
+ */
67
+ /** The one font every panel writes in, exported so the panels in their own files share it. */
68
+ const FONT = "ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, 'PingFang SC', 'Noto Sans CJK SC', sans-serif";
69
+ /** Format a number for a label: thousands grouped, up to `decimals` places. */
70
+ function formatNumber(value, decimals = 0) {
71
+ return value.toLocaleString("en-US", {
72
+ minimumFractionDigits: decimals,
73
+ maximumFractionDigits: decimals
74
+ });
75
+ }
76
+ /** The colour a gauge shows at `fraction` of its range. */
77
+ function gaugeColour(fraction, thresholds, c) {
78
+ if (!thresholds) return c.accent;
79
+ if (fraction >= thresholds[1]) return c.bad;
80
+ if (fraction >= thresholds[0]) return c.warn;
81
+ return c.good;
82
+ }
83
+ function gaugeOption(panel, c, animate) {
84
+ const max = panel.max ?? 100;
85
+ const fraction = Math.max(0, Math.min(1, panel.value / max));
86
+ const colour = gaugeColour(fraction, panel.thresholds, c);
87
+ const ring = panel.style === "ring";
88
+ return {
89
+ animation: animate,
90
+ animationDuration: 1400,
91
+ animationEasing: "cubicOut",
92
+ series: [{
93
+ type: "gauge",
94
+ startAngle: ring ? 90 : 210,
95
+ endAngle: ring ? -270 : -30,
96
+ min: 0,
97
+ max,
98
+ radius: "92%",
99
+ center: ["50%", ring ? "50%" : "58%"],
100
+ progress: {
101
+ show: true,
102
+ width: ring ? 14 : 16,
103
+ roundCap: true,
104
+ itemStyle: {
105
+ color: colour,
106
+ shadowBlur: 12,
107
+ shadowColor: withAlpha(colour, .5)
108
+ }
109
+ },
110
+ pointer: {
111
+ show: !ring,
112
+ length: "60%",
113
+ width: 4,
114
+ itemStyle: { color: colour }
115
+ },
116
+ axisLine: { lineStyle: {
117
+ width: ring ? 14 : 16,
118
+ color: [[1, c.track]]
119
+ } },
120
+ axisTick: { show: false },
121
+ splitLine: {
122
+ show: !ring,
123
+ length: 8,
124
+ lineStyle: {
125
+ color: c.muted,
126
+ width: 1
127
+ }
128
+ },
129
+ axisLabel: {
130
+ show: !ring,
131
+ color: c.muted,
132
+ fontSize: 10,
133
+ distance: 18,
134
+ fontFamily: FONT
135
+ },
136
+ anchor: {
137
+ show: !ring,
138
+ size: 10,
139
+ itemStyle: { color: colour }
140
+ },
141
+ title: { show: false },
142
+ detail: {
143
+ valueAnimation: animate,
144
+ offsetCenter: [0, ring ? 0 : "28%"],
145
+ fontSize: ring ? 28 : 24,
146
+ fontWeight: 700,
147
+ fontFamily: FONT,
148
+ color: c.text,
149
+ formatter: (value) => `${formatNumber(value, Number.isInteger(panel.value) ? 0 : 1)}${panel.unit ?? ""}`
150
+ },
151
+ data: [{ value: panel.value }]
152
+ }]
153
+ };
154
+ }
155
+ /**
156
+ * The screen's palette laid over whatever the model wrote.
157
+ *
158
+ * The model's option wins on anything it sets; this only fills in the colours, the font, the
159
+ * transparent background and the entrance animation a screen wants, so a plain `bar` series
160
+ * still looks like it belongs.
161
+ */
162
+ function chartOption(panel, c, animate) {
163
+ const axisStyle = {
164
+ axisLine: { lineStyle: { color: c.gridLine } },
165
+ axisLabel: {
166
+ color: c.muted,
167
+ fontFamily: FONT
168
+ },
169
+ splitLine: { lineStyle: { color: c.gridLine } }
170
+ };
171
+ const withAxisDefaults = (axis) => {
172
+ if (Array.isArray(axis)) return axis.map((a) => ({
173
+ ...axisStyle,
174
+ ...a
175
+ }));
176
+ if (axis && typeof axis === "object") return {
177
+ ...axisStyle,
178
+ ...axis
179
+ };
180
+ return axis;
181
+ };
182
+ const option = panel.option;
183
+ return {
184
+ backgroundColor: "transparent",
185
+ color: c.series,
186
+ textStyle: {
187
+ color: c.text,
188
+ fontFamily: FONT
189
+ },
190
+ animation: animate,
191
+ animationDuration: 1200,
192
+ animationEasing: "cubicOut",
193
+ grid: {
194
+ left: 40,
195
+ right: 16,
196
+ top: 28,
197
+ bottom: 28,
198
+ containLabel: true
199
+ },
200
+ legend: { textStyle: { color: c.muted } },
201
+ tooltip: { trigger: "axis" },
202
+ ...option,
203
+ ...option.xAxis !== void 0 ? { xAxis: withAxisDefaults(option.xAxis) } : {},
204
+ ...option.yAxis !== void 0 ? { yAxis: withAxisDefaults(option.yAxis) } : {}
205
+ };
206
+ }
207
+ function chart3dOption(panel, c, animate) {
208
+ const values = panel.data.map((p) => p[2]);
209
+ const max = Math.max(...values);
210
+ const min = Math.min(...values);
211
+ const axis = (categories, name) => ({
212
+ type: categories ? "category" : "value",
213
+ data: categories,
214
+ name: "",
215
+ axisLine: { lineStyle: { color: c.gridLine } },
216
+ axisLabel: {
217
+ color: c.muted,
218
+ fontFamily: FONT
219
+ },
220
+ splitLine: { lineStyle: { color: c.gridLine } },
221
+ axisPointer: { show: false },
222
+ nameTextStyle: { color: c.muted },
223
+ id: name
224
+ });
225
+ const series = {
226
+ type: panel.type,
227
+ data: panel.data,
228
+ shading: "lambert",
229
+ emphasis: { itemStyle: { color: c.text } }
230
+ };
231
+ if (panel.type === "bar3D") series.bevelSize = .2;
232
+ if (panel.type === "scatter3D") series.symbolSize = 9;
233
+ if (panel.type === "line3D") series.lineStyle = {
234
+ width: 3,
235
+ color: c.accent
236
+ };
237
+ if (panel.type === "surface") series.wireframe = {
238
+ show: true,
239
+ lineStyle: { color: withAlpha(c.accent, .35) }
240
+ };
241
+ return {
242
+ backgroundColor: "transparent",
243
+ textStyle: { fontFamily: FONT },
244
+ tooltip: {},
245
+ visualMap: {
246
+ show: false,
247
+ min,
248
+ max,
249
+ dimension: 2,
250
+ inRange: { color: [
251
+ withAlpha(c.accent, .55),
252
+ c.accent,
253
+ c.series[1]
254
+ ] }
255
+ },
256
+ xAxis3D: axis(panel.xAxis, "x"),
257
+ yAxis3D: axis(panel.yAxis, "y"),
258
+ zAxis3D: {
259
+ type: "value",
260
+ name: "",
261
+ axisLine: { lineStyle: { color: c.gridLine } },
262
+ axisLabel: {
263
+ color: c.muted,
264
+ fontFamily: FONT
265
+ },
266
+ splitLine: { lineStyle: { color: c.gridLine } }
267
+ },
268
+ grid3D: {
269
+ boxWidth: 100,
270
+ boxDepth: 80,
271
+ boxHeight: 60,
272
+ axisPointer: { show: false },
273
+ light: {
274
+ main: {
275
+ intensity: 1.3,
276
+ shadow: false,
277
+ alpha: 40,
278
+ beta: 30
279
+ },
280
+ ambient: { intensity: .5 }
281
+ },
282
+ viewControl: {
283
+ autoRotate: animate && panel.rotate !== false,
284
+ autoRotateSpeed: 8,
285
+ distance: 190,
286
+ alpha: 24,
287
+ beta: 35,
288
+ projection: "perspective"
289
+ },
290
+ environment: "none"
291
+ },
292
+ series: [series]
293
+ };
294
+ }
295
+ /**
296
+ * A globe without a satellite photograph.
297
+ *
298
+ * ECharts' globe wants a texture, and the usual one is an image fetched from somewhere — which a
299
+ * page must not do on a model's say-so. So the texture is painted here: a deep sphere with a
300
+ * graticule, which is what a data wall's globe looks like anyway. A host that wants a real earth
301
+ * says so in `BigscreenOptions.globe` and `earth.ts` takes over; this stays the fallback.
302
+ */
303
+ function globeTexture(c, theme) {
304
+ if (typeof document === "undefined") return void 0;
305
+ const canvas = document.createElement("canvas");
306
+ canvas.width = 1024;
307
+ canvas.height = 512;
308
+ const ctx = canvas.getContext("2d");
309
+ if (!ctx) return void 0;
310
+ ctx.fillStyle = theme === "dark" ? "#0b1a33" : "#dbe7f5";
311
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
312
+ ctx.strokeStyle = withAlpha(c.accent, theme === "dark" ? .28 : .35);
313
+ ctx.lineWidth = 1.2;
314
+ for (let lng = 0; lng < 360; lng += 15) {
315
+ const x = lng / 360 * canvas.width;
316
+ ctx.beginPath();
317
+ ctx.moveTo(x, 0);
318
+ ctx.lineTo(x, canvas.height);
319
+ ctx.stroke();
320
+ }
321
+ for (let lat = 15; lat < 180; lat += 15) {
322
+ const y = lat / 180 * canvas.height;
323
+ ctx.beginPath();
324
+ ctx.moveTo(0, y);
325
+ ctx.lineTo(canvas.width, y);
326
+ ctx.stroke();
327
+ }
328
+ ctx.strokeStyle = withAlpha(c.accent, .6);
329
+ ctx.lineWidth = 2;
330
+ ctx.beginPath();
331
+ ctx.moveTo(0, canvas.height / 2);
332
+ ctx.lineTo(canvas.width, canvas.height / 2);
333
+ ctx.stroke();
334
+ return canvas.toDataURL("image/png");
335
+ }
336
+ /** How many of a globe's points carry a written label; the rest are on the tooltip. */
337
+ const GLOBE_LABELS = 8;
338
+ /**
339
+ * The sphere itself, with and without a host-supplied earth.
340
+ *
341
+ * Without one, everything below the `skin` branch is the globe this plugin has always drawn: a
342
+ * flat-lit ball with a graticule on it, every point labelled. A wire grid needs no sun — there is
343
+ * nothing on it a shadow would tell you about — and `shading: "color"` with the light turned down
344
+ * is what keeps it evenly readable while it turns.
345
+ *
346
+ * With one, the ball is a planet: lambert (or the host's choice) so the terminator falls where the
347
+ * sun actually is, an atmosphere at the rim, and labels only on the points worth reading from
348
+ * across a room. `postEffect` stays off — bloom and depth of field on one of six panels is a
349
+ * frame budget spent on the wrong thing.
350
+ */
351
+ function globeOption(panel, c, animate, texture, skin) {
352
+ const arcs = (panel.arcs ?? []).map((arc) => ({
353
+ coords: [arc.from, arc.to],
354
+ name: arc.label
355
+ }));
356
+ const points = (panel.points ?? []).map((point) => ({
357
+ name: point.label,
358
+ value: [
359
+ point.coord[0],
360
+ point.coord[1],
361
+ 0,
362
+ point.value ?? 1
363
+ ]
364
+ }));
365
+ const maxValue = Math.max(1, ...points.map((p) => p.value[3]));
366
+ const shading = skin ? skin.shading ?? "lambert" : "color";
367
+ const globe = {
368
+ baseTexture: texture,
369
+ shading,
370
+ environment: "none",
371
+ globeRadius: 78,
372
+ atmosphere: {
373
+ show: skin ? skin.atmosphere !== false : true,
374
+ color: c.accent,
375
+ glowPower: 5,
376
+ innerGlowPower: 2,
377
+ offset: 4
378
+ },
379
+ light: skin ? {
380
+ ambient: { intensity: skin.light?.ambient ?? .5 },
381
+ main: {
382
+ intensity: skin.light?.intensity ?? 1.1,
383
+ shadow: false,
384
+ time: skin.light?.time ?? new Date()
385
+ }
386
+ } : {
387
+ ambient: { intensity: 1 },
388
+ main: { intensity: .2 }
389
+ },
390
+ viewControl: {
391
+ autoRotate: animate && panel.rotate !== false,
392
+ autoRotateSpeed: 3,
393
+ distance: 150,
394
+ targetCoord: arcs[0]?.coords[0] ?? points[0]?.value.slice(0, 2)
395
+ }
396
+ };
397
+ if (skin) {
398
+ globe.postEffect = { enable: false };
399
+ if (skin.heightTexture) globe.heightTexture = skin.heightTexture;
400
+ if (shading === "realistic") globe.realisticMaterial = {
401
+ roughness: .85,
402
+ metalness: 0
403
+ };
404
+ }
405
+ const named = new Set([...points].sort((a, b) => b.value[3] - a.value[3]).slice(0, GLOBE_LABELS).map((p) => p.name));
406
+ return {
407
+ backgroundColor: "transparent",
408
+ ...skin ? { tooltip: {
409
+ trigger: "item",
410
+ confine: true,
411
+ formatter: "{b}"
412
+ } } : {},
413
+ globe,
414
+ series: [{
415
+ type: "lines3D",
416
+ coordinateSystem: "globe",
417
+ blendMode: "lighter",
418
+ lineStyle: {
419
+ width: 2.5,
420
+ color: c.series[1],
421
+ opacity: .9
422
+ },
423
+ effect: {
424
+ show: animate,
425
+ period: 3,
426
+ trailWidth: 4,
427
+ trailLength: .3,
428
+ trailOpacity: 1,
429
+ trailColor: "#ffffff"
430
+ },
431
+ data: arcs
432
+ }, {
433
+ type: "scatter3D",
434
+ coordinateSystem: "globe",
435
+ symbolSize: (value) => 6 + 10 * Math.sqrt((value[3] ?? 1) / maxValue),
436
+ itemStyle: {
437
+ color: c.series[1],
438
+ opacity: .9
439
+ },
440
+ label: {
441
+ show: true,
442
+ formatter: skin ? (params) => params.name && named.has(params.name) ? params.name : "" : "{b}",
443
+ color: c.text,
444
+ fontSize: 11,
445
+ fontFamily: FONT,
446
+ backgroundColor: "transparent",
447
+ distance: 6
448
+ },
449
+ data: points
450
+ }]
451
+ };
452
+ }
453
+
454
+ //#endregion
455
+ //#region src/earth.ts
456
+ /**
457
+ * The planet a globe panel is drawn on.
458
+ *
459
+ * echarts-gl's globe samples one equirectangular image: 2:1, longitude -180..180 left to right,
460
+ * latitude 90..-90 top to bottom. A host that has a satellite photograph hands it over as
461
+ * `baseTexture` and this file does nothing; a host that has only country outlines hands over
462
+ * GeoJSON and this file paints them, because a page must not fetch a map on a model's say-so and
463
+ * because the same outlines have to come out in two palettes.
464
+ *
465
+ * The canvas is 2048x1024 rather than the graticule's 1024x512: a border is one pixel wide, and
466
+ * at half this width the coastline of anywhere smaller than France stops being a shape.
467
+ */
468
+ const WIDTH = 2048;
469
+ const HEIGHT = 1024;
470
+ function earthColours(c, theme, skin) {
471
+ const dark = theme === "dark";
472
+ return {
473
+ ocean: skin?.ocean ?? (dark ? "#0b1a33" : "#dbe7f5"),
474
+ land: skin?.land ?? (dark ? "#334155" : "#f8fafc"),
475
+ border: skin?.border ?? withAlpha(c.accent, dark ? .55 : .75)
476
+ };
477
+ }
478
+ /** The rings of a geometry, as a list of polygons; anything that is not a polygon is skipped. */
479
+ function polygonsOf(geometry) {
480
+ if (!geometry || !Array.isArray(geometry.coordinates)) return [];
481
+ if (geometry.type === "Polygon") return [geometry.coordinates];
482
+ if (geometry.type === "MultiPolygon") return geometry.coordinates;
483
+ return [];
484
+ }
485
+ /**
486
+ * One ring, in canvas pixels, shifted by whole worlds.
487
+ *
488
+ * Longitude is unwrapped as it goes: a step of more than half the world is the antimeridian, not
489
+ * a country, and drawing it literally paints a bar all the way across the Pacific — which is how
490
+ * Russia and Fiji ruin an otherwise correct map. Carrying an offset instead keeps the ring
491
+ * continuous past ±180, and the caller draws it three times, one world left and one right, so the
492
+ * part that has left the canvas comes back on the other side.
493
+ */
494
+ function traceRing(ctx, ring, shift) {
495
+ if (ring.length < 2) return;
496
+ let offset = 0;
497
+ let previous = ring[0][0];
498
+ ring.forEach((point, index) => {
499
+ const lon = point[0];
500
+ const step = lon - previous;
501
+ if (step > 180) offset -= 360;
502
+ else if (step < -180) offset += 360;
503
+ previous = lon;
504
+ const x = (lon + offset + 180) / 360 * WIDTH + shift;
505
+ const y = (90 - point[1]) / 180 * HEIGHT;
506
+ if (index === 0) ctx.moveTo(x, y);
507
+ else ctx.lineTo(x, y);
508
+ });
509
+ ctx.closePath();
510
+ }
511
+ /**
512
+ * Rasterise a world onto a 2:1 canvas and hand it over as a data URL.
513
+ *
514
+ * A data URL rather than the canvas element: that is the path echarts-gl treats as an image to
515
+ * decode, and it involves no request. A canvas element handed to `baseTexture` is a white ball.
516
+ *
517
+ * Rings are filled even-odd so that a country drawn as an outer ring plus holes — Lesotho inside
518
+ * South Africa, the lakes inside Canada — comes out with the holes in it whichever way round the
519
+ * source wound them.
520
+ */
521
+ function countriesTexture(countries, colours) {
522
+ if (typeof document === "undefined") return void 0;
523
+ const canvas = document.createElement("canvas");
524
+ canvas.width = WIDTH;
525
+ canvas.height = HEIGHT;
526
+ const ctx = canvas.getContext("2d");
527
+ if (!ctx) return void 0;
528
+ ctx.fillStyle = colours.ocean;
529
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
530
+ ctx.fillStyle = colours.land;
531
+ ctx.strokeStyle = colours.border;
532
+ ctx.lineWidth = 1;
533
+ ctx.lineJoin = "round";
534
+ for (const feature of countries.features ?? []) for (const polygon of polygonsOf(feature?.geometry)) for (const shift of [
535
+ -WIDTH,
536
+ 0,
537
+ WIDTH
538
+ ]) {
539
+ ctx.beginPath();
540
+ for (const ring of polygon) traceRing(ctx, ring, shift);
541
+ ctx.fill("evenodd");
542
+ ctx.stroke();
543
+ }
544
+ return canvas.toDataURL("image/png");
545
+ }
546
+ /**
547
+ * The texture a globe panel wears, by the host's precedence.
548
+ *
549
+ * `baseTexture` wins because a host that has a photograph has already decided; `countries` is
550
+ * next because outlines a host bundled are still the host's map; and with neither there is the
551
+ * graticule, which is what this plugin has always drawn and what every consumer that never heard
552
+ * of a `globe` option keeps getting.
553
+ */
554
+ function earthTexture(c, theme, skin) {
555
+ if (skin?.baseTexture) return skin.baseTexture;
556
+ if (skin?.countries) return countriesTexture(skin.countries, earthColours(c, theme, skin)) ?? globeTexture(c, theme);
557
+ return globeTexture(c, theme);
558
+ }
559
+
560
+ //#endregion
561
+ //#region src/timeline.ts
562
+ /**
563
+ * A timeline of claims, one lane per source.
564
+ *
565
+ * The panel exists for the line nobody else draws: two outlets said things that cannot both be
566
+ * true, and the red segment between their two points is the whole point of the picture. So the
567
+ * lanes stay in the order they were given (a reader compares row against row, and a chart that
568
+ * reorders them silently answers a different question), time runs across, and every claim is one
569
+ * point that can be clicked back to the page it came from.
570
+ *
571
+ * Pure: the option is a function of the panel and the palette, so it can be tested without a
572
+ * canvas and so the same claims draw the same picture on every screen.
573
+ */
574
+ /** How many claims carry a written label; the rest are on the tooltip. */
575
+ const TIMELINE_LABELS = 12;
576
+ /** The default point, in pixels, for a claim with no `value`. */
577
+ const DEFAULT_SYMBOL = 12;
578
+ const HOUR = 60 * 60 * 1e3;
579
+ /** How far into the window a claim has to be before its label is written on the other side. */
580
+ const LABEL_FLIPS_AT = .62;
581
+ const escapeHtml$1 = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
582
+ /**
583
+ * The window drawn, in epoch milliseconds.
584
+ *
585
+ * The panel's own `from` and `to` win where they are given. Otherwise it is the claims' own range
586
+ * with 5% on each side, because a point exactly on the axis reads as clipped rather than as first.
587
+ * A single claim has no range to take a fraction of, so it gets an hour either way — enough for
588
+ * the point to sit somewhere rather than in the middle of nothing.
589
+ */
590
+ function timelineWindow(panel) {
591
+ const times = panel.items.map((item) => Date.parse(item.at));
592
+ const low = panel.from === void 0 ? void 0 : Date.parse(panel.from);
593
+ const high = panel.to === void 0 ? void 0 : Date.parse(panel.to);
594
+ if (low !== void 0 && high !== void 0) return [low, high];
595
+ const min = Math.min(...times);
596
+ const max = Math.max(...times);
597
+ const pad = (max - min) * .05 || HOUR;
598
+ return [low ?? min - pad, high ?? max + pad];
599
+ }
600
+ /**
601
+ * Which claims have room for a label, as indexes into `panel.items`.
602
+ *
603
+ * A label is drawn beside its point, on its own lane, so what decides whether it can be read is
604
+ * the empty time on either side of it within that lane — not how important the claim is and not
605
+ * what order it was written in. Twelve labels on a wall panel is about where a reader stops
606
+ * reading them anyway, and the rest are one hover away.
607
+ */
608
+ function spacedItems(panel, max = TIMELINE_LABELS) {
609
+ const byLane = new Map();
610
+ panel.items.forEach((item, index) => {
611
+ const lane = byLane.get(item.lane) ?? [];
612
+ lane.push({
613
+ index,
614
+ at: Date.parse(item.at)
615
+ });
616
+ byLane.set(item.lane, lane);
617
+ });
618
+ const room = new Map();
619
+ for (const lane of byLane.values()) {
620
+ const sorted = [...lane].sort((a, b) => a.at - b.at);
621
+ sorted.forEach((entry, i) => {
622
+ const before = i > 0 ? entry.at - sorted[i - 1].at : Number.POSITIVE_INFINITY;
623
+ const after = i < sorted.length - 1 ? sorted[i + 1].at - entry.at : Number.POSITIVE_INFINITY;
624
+ room.set(entry.index, Math.min(before, after));
625
+ });
626
+ }
627
+ return new Set([...room.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0]).slice(0, max).map(([index]) => index));
628
+ }
629
+ /**
630
+ * How tall a timeline of this many lanes has to be.
631
+ *
632
+ * 320 is the default panel, and it holds a handful of lanes comfortably. Past that the lanes get
633
+ * a floor of 28 pixels each: below that the points of two neighbouring outlets touch, and a
634
+ * contradiction drawn between them stops being a line between two rows.
635
+ */
636
+ function timelineHeight(lanes) {
637
+ return Math.min(900, Math.max(320, 60 + lanes * 28));
638
+ }
639
+ /** How a link of each kind is drawn. `follows` is what an untyped link gets. */
640
+ const LINK_KINDS = {
641
+ contradicts: {
642
+ danger: true,
643
+ dotted: false,
644
+ arrow: false,
645
+ width: 2,
646
+ opacity: .95
647
+ },
648
+ follows: {
649
+ danger: false,
650
+ dotted: false,
651
+ arrow: true,
652
+ width: 1.4,
653
+ opacity: .6
654
+ },
655
+ same: {
656
+ danger: false,
657
+ dotted: true,
658
+ arrow: false,
659
+ width: 1.4,
660
+ opacity: .6
661
+ }
662
+ };
663
+ /** When a claim was made, written the way a wall is read: minutes, UTC, no locale surprises. */
664
+ function when(at) {
665
+ return `${new Date(at).toISOString().slice(0, 16).replace("T", " ")} UTC`;
666
+ }
667
+ function timelineOption(panel, c, animate) {
668
+ const [from, to] = timelineWindow(panel);
669
+ const laneName = new Map(panel.lanes.map((lane) => [lane.id, lane.name]));
670
+ const labelled = spacedItems(panel);
671
+ const maxValue = Math.max(0, ...panel.items.map((item) => item.value ?? 0));
672
+ const symbolSize = (value) => {
673
+ const raw = typeof value[2] === "number" ? value[2] : 0;
674
+ return raw > 0 && maxValue > 0 ? 8 + 12 * Math.sqrt(raw / maxValue) : DEFAULT_SYMBOL;
675
+ };
676
+ const series = panel.lanes.map((lane, laneIndex) => {
677
+ const colour = lane.color ?? c.series[laneIndex % c.series.length];
678
+ const data = panel.items.map((item, index) => ({
679
+ item,
680
+ index
681
+ })).filter(({ item }) => item.lane === lane.id).map(({ item, index }) => {
682
+ const at = Date.parse(item.at);
683
+ return {
684
+ name: item.label,
685
+ value: [
686
+ at,
687
+ lane.name,
688
+ item.value ?? 0
689
+ ],
690
+ item,
691
+ label: {
692
+ show: labelled.has(index),
693
+ position: (at - from) / (to - from) > LABEL_FLIPS_AT ? "left" : "right"
694
+ }
695
+ };
696
+ });
697
+ return {
698
+ name: lane.name,
699
+ type: "scatter",
700
+ symbolSize,
701
+ itemStyle: {
702
+ color: colour,
703
+ borderColor: withAlpha(colour, .35),
704
+ borderWidth: 4
705
+ },
706
+ label: {
707
+ show: false,
708
+ position: "right",
709
+ distance: 8,
710
+ color: c.text,
711
+ fontSize: 11,
712
+ fontFamily: FONT,
713
+ formatter: "{b}"
714
+ },
715
+ emphasis: {
716
+ scale: 1.35,
717
+ label: { show: true }
718
+ },
719
+ animationDelay: (index) => index * 30,
720
+ data
721
+ };
722
+ });
723
+ const byId = new Map(panel.items.filter((item) => item.id !== void 0).map((item) => [item.id, item]));
724
+ const coord = (id) => {
725
+ const item = byId.get(id);
726
+ const name = item && laneName.get(item.lane);
727
+ return item && name !== void 0 ? [Date.parse(item.at), name] : void 0;
728
+ };
729
+ const links = (panel.links ?? []).flatMap((link) => {
730
+ const a = coord(link.from);
731
+ const b = coord(link.to);
732
+ if (!a || !b) return [];
733
+ const kind = link.kind ?? "follows";
734
+ const style = LINK_KINDS[kind];
735
+ return [{
736
+ coords: [a, b],
737
+ name: kind,
738
+ symbol: style.arrow ? ["none", "arrow"] : ["none", "none"],
739
+ symbolSize: 7,
740
+ lineStyle: {
741
+ color: style.danger ? c.bad : c.muted,
742
+ width: style.width,
743
+ type: style.dotted ? "dotted" : "solid",
744
+ opacity: style.opacity,
745
+ curveness: .15
746
+ }
747
+ }];
748
+ });
749
+ if (links.length) series.push({
750
+ name: "links",
751
+ type: "lines",
752
+ coordinateSystem: "cartesian2d",
753
+ z: 1,
754
+ polyline: false,
755
+ animationDuration: 1400,
756
+ data: links
757
+ });
758
+ const axisLine = { lineStyle: { color: c.gridLine } };
759
+ return {
760
+ backgroundColor: "transparent",
761
+ textStyle: {
762
+ color: c.text,
763
+ fontFamily: FONT
764
+ },
765
+ animation: animate,
766
+ animationDuration: 1200,
767
+ animationEasing: "cubicOut",
768
+ grid: {
769
+ left: 8,
770
+ right: 28,
771
+ top: 18,
772
+ bottom: 24,
773
+ containLabel: true
774
+ },
775
+ tooltip: {
776
+ trigger: "item",
777
+ confine: true,
778
+ formatter: (params) => {
779
+ const data = params.data;
780
+ const item = data?.item;
781
+ if (!item) return escapeHtml$1(String(params.seriesName ?? ""));
782
+ const rows = [`<span style="opacity:.7">${escapeHtml$1(params.seriesName ?? "")} · ${when(Date.parse(item.at))}</span>`, `<b>${escapeHtml$1(item.label)}</b>`];
783
+ if (item.detail) rows.push(`<span style="opacity:.85">${escapeHtml$1(item.detail)}</span>`);
784
+ return rows.join("<br/>");
785
+ }
786
+ },
787
+ xAxis: {
788
+ type: "time",
789
+ min: from,
790
+ max: to,
791
+ axisLine,
792
+ axisTick: { show: false },
793
+ axisLabel: {
794
+ color: c.muted,
795
+ fontFamily: FONT,
796
+ fontSize: 10,
797
+ hideOverlap: true
798
+ },
799
+ splitLine: {
800
+ show: true,
801
+ lineStyle: {
802
+ color: c.gridLine,
803
+ type: "dashed"
804
+ }
805
+ }
806
+ },
807
+ yAxis: {
808
+ type: "category",
809
+ data: panel.lanes.map((lane) => lane.name),
810
+ inverse: true,
811
+ axisLine,
812
+ axisTick: { show: false },
813
+ axisLabel: {
814
+ color: c.text,
815
+ fontFamily: FONT,
816
+ fontSize: 11
817
+ },
818
+ splitLine: {
819
+ show: true,
820
+ lineStyle: { color: c.gridLine }
821
+ },
822
+ splitArea: {
823
+ show: true,
824
+ areaStyle: { color: [withAlpha(c.muted, .06), "transparent"] }
825
+ }
826
+ },
827
+ series
828
+ };
829
+ }
830
+
831
+ //#endregion
832
+ //#region src/layout3d.ts
833
+ /**
834
+ * A spring–electrical layout in three dimensions.
835
+ *
836
+ * Fruchterman–Reingold's forces, one dimension further: every pair of entities pushes apart with
837
+ * `k²/d`, every edge pulls its ends together with `d²/k`, a weak spring holds the whole thing to
838
+ * the origin, and a falling temperature caps how far a node may move in one step so the graph
839
+ * cools into a shape instead of oscillating around one.
840
+ *
841
+ * Written here rather than taken from a dependency for two reasons. The panel needs positions in
842
+ * three dimensions and echarts-gl's own layouts are two-dimensional; and the layout has to be
843
+ * *steppable* — a few steps per animation frame — so the reader watches the graph pull itself
844
+ * apart rather than being handed a settled picture. A library that runs to convergence behind a
845
+ * promise cannot do that.
846
+ *
847
+ * Deterministic on purpose: the starting positions are a hash of the node ids on a sphere, so the
848
+ * same knowledge graph draws the same picture twice running, and a screenshot test means
849
+ * something. Nothing here calls `Math.random`.
850
+ *
851
+ * Complexity is O(n²) per step, which is why `layoutSteps` spends fewer steps on a bigger graph.
852
+ */
853
+ /** The distance an edge settles at: the unit everything else here is measured in. */
854
+ const LAYOUT_SPRING = 1;
855
+ /**
856
+ * The pull to the origin, per unit of distance from it.
857
+ *
858
+ * Without it a knowledge graph with two unconnected components is unbounded: nothing attracts
859
+ * them to each other, the repulsion between them is never opposed, and one of them leaves the
860
+ * panel and keeps going.
861
+ */
862
+ const LAYOUT_GRAVITY = .08;
863
+ /** How far a node may move in the first step, as a fraction of the graph's own radius. */
864
+ const HEAT = .12;
865
+ /** Below this the repulsion between two nodes in the same place would be infinite. */
866
+ const MIN_DISTANCE = .001;
867
+ const FNV_OFFSET = 2166136261;
868
+ const FNV_PRIME = 16777619;
869
+ /**
870
+ * FNV-1a.
871
+ *
872
+ * The one hash in this package: the same function that decides a type's colour decides where a
873
+ * node starts, so both are a function of the name and of nothing else.
874
+ */
875
+ function hash(value) {
876
+ let h = FNV_OFFSET;
877
+ for (let i = 0; i < value.length; i++) {
878
+ h ^= value.charCodeAt(i);
879
+ h = Math.imul(h, FNV_PRIME);
880
+ }
881
+ return h >>> 0;
882
+ }
883
+ /**
884
+ * How many steps a graph of `n` entities is given.
885
+ *
886
+ * Each step is O(n²), so the count falls as the graph grows: three hundred steps at fifty
887
+ * entities (a small graph settles properly and still inside a second), a hundred and twenty at
888
+ * five hundred, forty at two thousand — the panel's own limit, where a single step already costs
889
+ * a frame. Interpolated on a log scale between those three measured points, and flat outside
890
+ * them, so there is no size at which the number jumps.
891
+ */
892
+ const STEP_ANCHORS = [
893
+ [50, 300],
894
+ [500, 120],
895
+ [2e3, 40]
896
+ ];
897
+ function layoutSteps(n) {
898
+ const size = Math.max(1, n);
899
+ if (size <= STEP_ANCHORS[0][0]) return STEP_ANCHORS[0][1];
900
+ for (let i = 1; i < STEP_ANCHORS.length; i++) {
901
+ const [lowN, lowSteps] = STEP_ANCHORS[i - 1];
902
+ const [highN, highSteps] = STEP_ANCHORS[i];
903
+ if (size > highN) continue;
904
+ const t = (Math.log(size) - Math.log(lowN)) / (Math.log(highN) - Math.log(lowN));
905
+ return Math.round(lowSteps + (highSteps - lowSteps) * t);
906
+ }
907
+ return STEP_ANCHORS[STEP_ANCHORS.length - 1][1];
908
+ }
909
+ /**
910
+ * How many steps are spent per animation frame while the graph settles in front of the reader.
911
+ *
912
+ * Small enough to leave the frame time for drawing, and large enough that a six-entity graph —
913
+ * which is given three hundred steps — is finished in well under a second rather than in five.
914
+ * At a few hundred entities a single step already costs most of a frame, so it drops to one and
915
+ * the graph settles at whatever pace the machine can manage.
916
+ */
917
+ function layoutChunk(n) {
918
+ return Math.max(1, Math.min(8, Math.round(600 / Math.max(1, n))));
919
+ }
920
+ /**
921
+ * The radius a graph of `n` entities settles inside, which is also where it is started.
922
+ *
923
+ * A cube root, not a square root. Inside a ball of charge the repulsion at radius `r` comes only
924
+ * from what is enclosed — `n(r/R)³` of it, over `r²` — so balancing it against a gravity of `g·r`
925
+ * gives `R = k·∛(n/g)`. Guessing `sqrt` instead put a two-thousand-entity graph's starting sphere
926
+ * five times too wide, and the first half of its forty steps went on collapsing rather than on
927
+ * laying anything out.
928
+ */
929
+ function layoutRadius(n) {
930
+ return LAYOUT_SPRING * Math.cbrt(Math.max(1, n) / LAYOUT_GRAVITY);
931
+ }
932
+ /**
933
+ * Where every node starts, as `[x, y, z]` per node in the order the ids were given.
934
+ *
935
+ * A node the caller remembers keeps exactly the position it had, which is what stops a graph that
936
+ * gained three entities from reshuffling the twenty that were already there. Everything else is
937
+ * placed on a sphere by the hash of its id — a Fibonacci-like spiral from two independent hashes,
938
+ * so ids that are one character apart do not end up next to each other — scaled to the cloud the
939
+ * remembered nodes already occupy, or to the graph's own settling radius when there is nothing to
940
+ * remember.
941
+ */
942
+ function seedPositions(ids, seed) {
943
+ const out = new Float32Array(ids.length * 3);
944
+ let remembered = 0;
945
+ let rememberedRadius = 0;
946
+ for (const id of ids) {
947
+ const previous = seed?.get(id);
948
+ if (!previous) continue;
949
+ remembered++;
950
+ rememberedRadius += Math.hypot(previous[0], previous[1], previous[2]);
951
+ }
952
+ const radius = remembered > 0 ? Math.max(rememberedRadius / remembered, MIN_DISTANCE) : layoutRadius(ids.length);
953
+ for (const [index, id] of ids.entries()) {
954
+ const previous = seed?.get(id);
955
+ if (previous) {
956
+ out[index * 3] = previous[0];
957
+ out[index * 3 + 1] = previous[1];
958
+ out[index * 3 + 2] = previous[2];
959
+ continue;
960
+ }
961
+ const h = hash(id);
962
+ const z = h % 2048 / 2048 * 2 - 1;
963
+ const theta = hash(`${id}`) % 4096 * (Math.PI * 2 / 4096);
964
+ const ring = Math.sqrt(Math.max(0, 1 - z * z));
965
+ out[index * 3] = radius * ring * Math.cos(theta);
966
+ out[index * 3 + 1] = radius * ring * Math.sin(theta);
967
+ out[index * 3 + 2] = radius * z;
968
+ }
969
+ return out;
970
+ }
971
+ /**
972
+ * A layout over `nodes` and `edges`, ready to be stepped.
973
+ *
974
+ * `seed` is the positions the same graph settled into last time, by node id; the ids it does not
975
+ * mention are placed by their hash. An edge naming a node that is not there is skipped rather
976
+ * than refused — the parser has already rejected those, and a layout is not the place to raise.
977
+ */
978
+ function createLayout(nodes, edges, seed) {
979
+ const ids = nodes.map((node) => node.id);
980
+ const index = new Map(ids.map((id, i) => [id, i]));
981
+ const position = seedPositions(ids, seed);
982
+ const displacement = new Float64Array(position.length);
983
+ const count = nodes.length;
984
+ const steps = layoutSteps(count);
985
+ const links = [];
986
+ for (const edge of edges) {
987
+ const from = index.get(edge.from);
988
+ const to = index.get(edge.to);
989
+ if (from === void 0 || to === void 0 || from === to) continue;
990
+ links.push(from, to);
991
+ }
992
+ const k = LAYOUT_SPRING;
993
+ const kSquared = k * k;
994
+ const heat = layoutRadius(count) * HEAT;
995
+ let taken = 0;
996
+ const one = () => {
997
+ displacement.fill(0);
998
+ for (let i = 0; i < count; i++) {
999
+ const xi = position[i * 3];
1000
+ const yi = position[i * 3 + 1];
1001
+ const zi = position[i * 3 + 2];
1002
+ for (let j = i + 1; j < count; j++) {
1003
+ const dx = xi - position[j * 3];
1004
+ const dy = yi - position[j * 3 + 1];
1005
+ const dz = zi - position[j * 3 + 2];
1006
+ const squared = Math.max(dx * dx + dy * dy + dz * dz, MIN_DISTANCE * MIN_DISTANCE);
1007
+ const force = kSquared / squared;
1008
+ displacement[i * 3] += dx * force;
1009
+ displacement[i * 3 + 1] += dy * force;
1010
+ displacement[i * 3 + 2] += dz * force;
1011
+ displacement[j * 3] -= dx * force;
1012
+ displacement[j * 3 + 1] -= dy * force;
1013
+ displacement[j * 3 + 2] -= dz * force;
1014
+ }
1015
+ }
1016
+ for (let e = 0; e < links.length; e += 2) {
1017
+ const a = links[e];
1018
+ const b = links[e + 1];
1019
+ const dx = position[a * 3] - position[b * 3];
1020
+ const dy = position[a * 3 + 1] - position[b * 3 + 1];
1021
+ const dz = position[a * 3 + 2] - position[b * 3 + 2];
1022
+ const distance = Math.max(Math.hypot(dx, dy, dz), MIN_DISTANCE);
1023
+ const force = distance / k;
1024
+ displacement[a * 3] -= dx * force;
1025
+ displacement[a * 3 + 1] -= dy * force;
1026
+ displacement[a * 3 + 2] -= dz * force;
1027
+ displacement[b * 3] += dx * force;
1028
+ displacement[b * 3 + 1] += dy * force;
1029
+ displacement[b * 3 + 2] += dz * force;
1030
+ }
1031
+ const temperature = Math.max(heat * (1 - taken / steps), heat * .01);
1032
+ for (let i = 0; i < count; i++) {
1033
+ const dx = displacement[i * 3] - position[i * 3] * LAYOUT_GRAVITY;
1034
+ const dy = displacement[i * 3 + 1] - position[i * 3 + 1] * LAYOUT_GRAVITY;
1035
+ const dz = displacement[i * 3 + 2] - position[i * 3 + 2] * LAYOUT_GRAVITY;
1036
+ const length = Math.hypot(dx, dy, dz);
1037
+ if (length < MIN_DISTANCE) continue;
1038
+ const scale = Math.min(length, temperature) / length;
1039
+ position[i * 3] += dx * scale;
1040
+ position[i * 3 + 1] += dy * scale;
1041
+ position[i * 3 + 2] += dz * scale;
1042
+ }
1043
+ taken++;
1044
+ };
1045
+ return {
1046
+ step(request = 1) {
1047
+ for (let i = 0; i < request && taken < steps; i++) one();
1048
+ },
1049
+ positions: () => position,
1050
+ get done() {
1051
+ return taken >= steps;
1052
+ },
1053
+ steps,
1054
+ get taken() {
1055
+ return taken;
1056
+ }
1057
+ };
1058
+ }
1059
+
1060
+ //#endregion
1061
+ //#region src/graph3d.ts
1062
+ /**
1063
+ * The vocabulary every knowledge graph panel is drawn in, and the flat mode's own option.
1064
+ *
1065
+ * A type's colour, a node's degree, the legend in the corner and the tooltip are the same in both
1066
+ * modes and live here. `orbit.ts` — the default — turns the entities into a model in space;
1067
+ * `graph3dOption` below is `flat`, echarts-gl's `graphGL`: force-atlas2 on the GPU, drawn on a
1068
+ * plane with an orthographic camera. It draws more nodes at once than the model does, which is
1069
+ * the reason it is still here.
1070
+ *
1071
+ * Pure: the option is a function of the panel and the palette.
1072
+ */
1073
+ /** How many entities carry a written label. The rest are one hover away. */
1074
+ const GRAPH_LABELS = 20;
1075
+ /**
1076
+ * How the layout is run.
1077
+ *
1078
+ * `steps` is iterations per frame and `maxSteps` is where the layout stops. Settling takes
1079
+ * `maxSteps / steps` frames — 125 of them, a shade over two seconds at sixty frames a second,
1080
+ * which is long enough to watch a graph of five hundred entities pull itself apart and short
1081
+ * enough that nobody waits for it. When nothing is meant to move, the same thousand iterations
1082
+ * are spent four frames deep and the reader gets the settled graph instead of the settling.
1083
+ *
1084
+ * (echarts-gl 2.x bounds the layout with `maxSteps`; there is no convergence threshold to set.)
1085
+ */
1086
+ const GRAPH_SETTLE_STEPS = 8;
1087
+ const GRAPH_INSTANT_STEPS = 250;
1088
+ const GRAPH_MAX_STEPS = 1e3;
1089
+ /** How many types the corner legend lists before it would start covering the graph. */
1090
+ const GRAPH_LEGEND_ROWS = 12;
1091
+ /** How many of the palette's series colours a type may be hashed onto. */
1092
+ const GRAPH_COLOURS = 7;
1093
+ /**
1094
+ * Where the graph starts, and where it is pulled to.
1095
+ *
1096
+ * echarts-gl scatters the first positions at random inside the panel and fits the camera to them
1097
+ * once — `_updateCamera` refits only when the graph has left the frame entirely — so a random
1098
+ * start is why a settled graph sits wherever its first throw of the dice happened to land. Seeding
1099
+ * the nodes on a ring instead fixes the frame, and makes the same entities draw the same picture
1100
+ * twice running.
1101
+ *
1102
+ * The frame it fits is not centred on that ring: it pads the left by a fifth of the padded width,
1103
+ * which leaves the ring's own centre 0.16 of a radius right of the middle. So the layout's
1104
+ * `gravityCenter` is moved the same distance the other way, and the settled graph comes out in
1105
+ * the middle of the panel.
1106
+ */
1107
+ const SEED_RADIUS = 45;
1108
+ const SEED_OFFSET = .16;
1109
+ /**
1110
+ * The colour of a type.
1111
+ *
1112
+ * Hashed rather than handed out in order of appearance, because two graph panels on one wall must
1113
+ * colour `outlet` the same way, and the order the types happen to appear in is different in each
1114
+ * of them. A hash means two types can land on the same colour, which is what the legend in the
1115
+ * corner is for; a panel that cares says so in `types`.
1116
+ *
1117
+ * Only the first seven series colours are in the ring. The eighth is a second cyan a shade off
1118
+ * the accent, and two types a reader cannot tell apart is worse than two types sharing a colour
1119
+ * the legend admits to sharing.
1120
+ *
1121
+ * A node with no type gets the muted colour: it is not a category, so it does not get one of the
1122
+ * colours the categories are being told apart by.
1123
+ */
1124
+ function typeColour(type, c, overrides) {
1125
+ if (type === void 0) return c.muted;
1126
+ const ring = c.series.slice(0, GRAPH_COLOURS);
1127
+ return overrides?.[type] ?? ring[hash(type) % ring.length];
1128
+ }
1129
+ /** How many edges touch each node. Both ends count, so a self-edge counts twice. */
1130
+ function degrees(panel) {
1131
+ const count = new Map(panel.nodes.map((node) => [node.id, 0]));
1132
+ for (const edge of panel.edges) for (const id of [edge.from, edge.to]) {
1133
+ const current = count.get(id);
1134
+ if (current !== void 0) count.set(id, current + 1);
1135
+ }
1136
+ return count;
1137
+ }
1138
+ /**
1139
+ * The key drawn in the panel's corner: every type that appears, once, in its own colour.
1140
+ *
1141
+ * Nodes first, then edges, each in the order it first appears — which is the order the model
1142
+ * wrote them in, and therefore the order it was thinking in. An untyped graph gets no legend at
1143
+ * all rather than an empty box.
1144
+ */
1145
+ function graphLegend(panel, c) {
1146
+ const entries = [];
1147
+ const seen = new Set();
1148
+ const add = (shape, type) => {
1149
+ if (type === void 0) return;
1150
+ const key = `${shape}:${type}`;
1151
+ if (seen.has(key)) return;
1152
+ seen.add(key);
1153
+ entries.push({
1154
+ label: type,
1155
+ colour: typeColour(type, c, panel.types),
1156
+ shape
1157
+ });
1158
+ };
1159
+ for (const node of panel.nodes) add("node", node.type);
1160
+ for (const edge of panel.edges) add("edge", edge.type);
1161
+ return entries.slice(0, GRAPH_LEGEND_ROWS);
1162
+ }
1163
+ const escapeHtml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1164
+ /**
1165
+ * What an entity or an edge says on hover, in both modes.
1166
+ *
1167
+ * Escaped by hand: ECharts renders a formatter's return as HTML and every name here was written
1168
+ * by a model. An edge is told apart by `dataType` in the flat series and by carrying its own
1169
+ * `coords` in the orbit one, which is the only thing the two series disagree about.
1170
+ */
1171
+ function graphTooltip(params) {
1172
+ const data = params.data ?? {};
1173
+ if (params.dataType === "edge" || data.coords !== void 0) return escapeHtml(data.edgeType ?? "linked to");
1174
+ const rows = [`<b>${escapeHtml(data.name ?? "")}</b>`];
1175
+ if (data.nodeType) rows.push(`<span style="opacity:.7">${escapeHtml(data.nodeType)}</span>`);
1176
+ rows.push(`<span style="opacity:.7">${data.degree ?? 0} connections</span>`);
1177
+ return rows.join("<br/>");
1178
+ }
1179
+ /**
1180
+ * The `flat` mode: `graphGL`, laid out by force-atlas2 on the GPU.
1181
+ *
1182
+ * Unchanged since it was written, byte for byte, and pinned by a test that says so — a panel that
1183
+ * asked for this mode asked for exactly this picture. The 3D model is `graphOrbitOption`, which
1184
+ * takes positions rather than computing them, because it is stepped in front of the reader.
1185
+ */
1186
+ function graph3dOption(panel, c, animate) {
1187
+ const degree = degrees(panel);
1188
+ const weight = (node) => node.value ?? degree.get(node.id) ?? 0;
1189
+ const maxWeight = Math.max(1, ...panel.nodes.map(weight));
1190
+ const named = new Set([...panel.nodes].sort((a, b) => (degree.get(b.id) ?? 0) - (degree.get(a.id) ?? 0)).slice(0, GRAPH_LABELS).map((node) => node.id));
1191
+ if (panel.focus !== void 0) named.add(panel.focus);
1192
+ const radius = SEED_RADIUS * Math.sqrt(panel.nodes.length) + 60;
1193
+ const nodes = panel.nodes.map((node, index) => {
1194
+ const focused = node.id === panel.focus;
1195
+ const symbolSize = (focused ? 6 : 0) + 6 + 16 * Math.sqrt(weight(node) / maxWeight);
1196
+ const angle = index / panel.nodes.length * Math.PI * 2;
1197
+ return {
1198
+ id: node.id,
1199
+ name: node.name,
1200
+ x: radius * Math.cos(angle),
1201
+ y: radius * Math.sin(angle),
1202
+ nodeType: node.type,
1203
+ degree: degree.get(node.id) ?? 0,
1204
+ node,
1205
+ symbolSize,
1206
+ itemStyle: {
1207
+ color: focused ? c.accent : typeColour(node.type, c, panel.types),
1208
+ opacity: .95
1209
+ },
1210
+ label: focused ? {
1211
+ show: true,
1212
+ fontSize: 13,
1213
+ fontWeight: "bold",
1214
+ color: c.accent
1215
+ } : { show: named.has(node.id) }
1216
+ };
1217
+ });
1218
+ const edges = panel.edges.map((edge) => ({
1219
+ source: edge.from,
1220
+ target: edge.to,
1221
+ edgeType: edge.type,
1222
+ lineStyle: {
1223
+ color: typeColour(edge.type, c, panel.types),
1224
+ opacity: .55,
1225
+ width: 1.5
1226
+ }
1227
+ }));
1228
+ const settling = animate && panel.rotate !== false;
1229
+ return {
1230
+ backgroundColor: "transparent",
1231
+ textStyle: {
1232
+ color: c.text,
1233
+ fontFamily: FONT
1234
+ },
1235
+ tooltip: {
1236
+ trigger: "item",
1237
+ confine: true,
1238
+ formatter: graphTooltip
1239
+ },
1240
+ series: [{
1241
+ type: "graphGL",
1242
+ layout: "forceAtlas2",
1243
+ forceAtlas2: {
1244
+ GPU: true,
1245
+ steps: settling ? GRAPH_SETTLE_STEPS : GRAPH_INSTANT_STEPS,
1246
+ maxSteps: GRAPH_MAX_STEPS,
1247
+ gravity: .6,
1248
+ scaling: 5,
1249
+ gravityCenter: [-SEED_OFFSET * radius, 0],
1250
+ edgeWeightInfluence: 0,
1251
+ repulsionByDegree: true,
1252
+ preventOverlap: true
1253
+ },
1254
+ roam: true,
1255
+ focusNodeAdjacency: true,
1256
+ zoom: 1,
1257
+ label: {
1258
+ show: false,
1259
+ position: "right",
1260
+ distance: 4,
1261
+ color: c.text,
1262
+ fontSize: 11,
1263
+ fontFamily: FONT,
1264
+ formatter: "{b}"
1265
+ },
1266
+ emphasis: { label: { show: true } },
1267
+ lineStyle: {
1268
+ color: c.gridLine,
1269
+ width: 1,
1270
+ opacity: .35
1271
+ },
1272
+ nodes,
1273
+ edges
1274
+ }]
1275
+ };
1276
+ }
1277
+
1278
+ //#endregion
1279
+ //#region src/orbit.ts
1280
+ /**
1281
+ * The knowledge graph as a model you look at, rather than a picture you look down on.
1282
+ *
1283
+ * `layout3d.ts` puts the entities in space; this puts a camera in there with them. A `grid3D`
1284
+ * holds the coordinate system, a `scatter3D` draws the entities and a `line3D` draws the edges,
1285
+ * and the box the three of them share is deliberately invisible: a knowledge graph has no axes
1286
+ * to read, and the only thing an axis would add is furniture.
1287
+ *
1288
+ * Pure: the option is a function of the panel, the palette and the positions. The positions come
1289
+ * from outside because the layout is stepped — the mount loop hands the same builder a slightly
1290
+ * different set of coordinates every frame while the graph settles.
1291
+ */
1292
+ /**
1293
+ * The half-width of the space the graph is drawn in, in the box's own units.
1294
+ *
1295
+ * Everything about the camera — the distance it sits at, how big a node reads at that distance —
1296
+ * is a constant, so the graph has to be scaled to it rather than the other way round. The layout
1297
+ * works in units of its own spring length and a graph of two thousand is naturally four times
1298
+ * wider than a graph of six; `orbitScale` divides that difference out, and this is what is left.
1299
+ */
1300
+ const ORBIT_EXTENT = 50;
1301
+ /** The cube the coordinate system is drawn in. Equal on all three sides, or the shape is a lie. */
1302
+ const ORBIT_BOX = 140;
1303
+ /** How solid an edge is drawn. */
1304
+ const EDGE_OPACITY = .6;
1305
+ /**
1306
+ * The camera: how far out it sits, how fast it goes round, and the field of view it does it with.
1307
+ *
1308
+ * The distance is not a matter of taste. The graph is fitted to the box, so its furthest entity
1309
+ * sits half a box from the middle — and as the camera turns, that entity comes round to the near
1310
+ * side, where the perspective divide is over a distance of `ORBIT_DISTANCE - ORBIT_BOX / 2`
1311
+ * rather than `ORBIT_DISTANCE`. A camera framed for the middle therefore crops the graph twice a
1312
+ * revolution, which is exactly what it did at 180: an entity and its edge walked off the bottom
1313
+ * of the panel and back. So the distance is set from the near face, with room left over for the
1314
+ * labels, which stick out further than the entities they belong to.
1315
+ *
1316
+ * echarts-gl's grid3D camera has a vertical field of view of 50 degrees and is not configurable
1317
+ * through `viewControl`, so it is written down here rather than passed.
1318
+ */
1319
+ const ORBIT_FOV = 50;
1320
+ const ORBIT_DISTANCE = 260;
1321
+ const ORBIT_SPEED = 6;
1322
+ /**
1323
+ * The graph's own bounding box, as the transform that puts it in the middle of the panel.
1324
+ *
1325
+ * Its box, not its bounding sphere, and its centre, not the origin. A settled graph is rarely a
1326
+ * ball: the eight-entity example comes out about 72 units wide, 26 tall and 40 deep, centred six
1327
+ * units left of where it started. Scaling that by its largest radius left it filling a fifth of
1328
+ * the panel and sitting off to one side — correct, and unreadable. Fitting the longest of the
1329
+ * three spans instead fills the frame in whichever direction the graph is actually long, and
1330
+ * because every other span is shorter by definition, nothing lands outside the box.
1331
+ */
1332
+ function orbitFrame(positions) {
1333
+ if (positions.length < 3) return {
1334
+ centre: [
1335
+ 0,
1336
+ 0,
1337
+ 0
1338
+ ],
1339
+ scale: 1
1340
+ };
1341
+ const low = [
1342
+ Infinity,
1343
+ Infinity,
1344
+ Infinity
1345
+ ];
1346
+ const high = [
1347
+ -Infinity,
1348
+ -Infinity,
1349
+ -Infinity
1350
+ ];
1351
+ for (let i = 0; i < positions.length; i += 3) for (let axis = 0; axis < 3; axis++) {
1352
+ low[axis] = Math.min(low[axis], positions[i + axis]);
1353
+ high[axis] = Math.max(high[axis], positions[i + axis]);
1354
+ }
1355
+ const centre = [
1356
+ (low[0] + high[0]) / 2,
1357
+ (low[1] + high[1]) / 2,
1358
+ (low[2] + high[2]) / 2
1359
+ ];
1360
+ const half = Math.max((high[0] - low[0]) / 2, (high[1] - low[1]) / 2, (high[2] - low[2]) / 2);
1361
+ return {
1362
+ centre,
1363
+ scale: half > 0 ? ORBIT_EXTENT / half : 1
1364
+ };
1365
+ }
1366
+ /** How many vertices one edge contributes to that polyline. */
1367
+ const EDGE_VERTICES = 4;
1368
+ /**
1369
+ * The two series' data, from the panel and wherever the layout has got to.
1370
+ *
1371
+ * Built as one thing because the edges have to agree with the nodes: an edge is drawn between two
1372
+ * points, not between two ids, so a frame that moved the nodes and left the edges behind would
1373
+ * detach every line from both its ends.
1374
+ */
1375
+ function graphOrbitData(panel, c, positions) {
1376
+ const degree = degrees(panel);
1377
+ const weight = (node) => node.value ?? degree.get(node.id) ?? 0;
1378
+ const maxWeight = Math.max(1, ...panel.nodes.map(weight));
1379
+ const named = new Set([...panel.nodes].sort((a, b) => (degree.get(b.id) ?? 0) - (degree.get(a.id) ?? 0)).slice(0, GRAPH_LABELS).map((node) => node.id));
1380
+ if (panel.focus !== void 0) named.add(panel.focus);
1381
+ const { centre, scale } = orbitFrame(positions);
1382
+ const at = (index) => [
1383
+ (positions[index * 3] - centre[0]) * scale,
1384
+ (positions[index * 3 + 1] - centre[1]) * scale,
1385
+ (positions[index * 3 + 2] - centre[2]) * scale
1386
+ ];
1387
+ const place = new Map();
1388
+ const nodes = panel.nodes.map((node, index) => {
1389
+ const focused = node.id === panel.focus;
1390
+ const [x, y, z] = at(index);
1391
+ place.set(node.id, [
1392
+ x,
1393
+ y,
1394
+ z
1395
+ ]);
1396
+ return {
1397
+ id: node.id,
1398
+ name: node.name,
1399
+ value: [
1400
+ x,
1401
+ y,
1402
+ z,
1403
+ (focused ? 6 : 0) + 6 + 16 * Math.sqrt(weight(node) / maxWeight)
1404
+ ],
1405
+ itemStyle: {
1406
+ color: focused ? c.accent : typeColour(node.type, c, panel.types),
1407
+ opacity: .95
1408
+ },
1409
+ labelled: named.has(node.id),
1410
+ nodeType: node.type,
1411
+ degree: degree.get(node.id) ?? 0,
1412
+ node
1413
+ };
1414
+ });
1415
+ const origin = [
1416
+ 0,
1417
+ 0,
1418
+ 0
1419
+ ];
1420
+ const edges = [];
1421
+ for (const edge of panel.edges) {
1422
+ const from = place.get(edge.from) ?? origin;
1423
+ const to = place.get(edge.to) ?? origin;
1424
+ const color = typeColour(edge.type, c, panel.types);
1425
+ for (const [value, opacity] of [
1426
+ [from, 0],
1427
+ [from, EDGE_OPACITY],
1428
+ [to, EDGE_OPACITY],
1429
+ [to, 0]
1430
+ ]) edges.push({
1431
+ value,
1432
+ lineStyle: {
1433
+ color,
1434
+ opacity
1435
+ }
1436
+ });
1437
+ }
1438
+ return {
1439
+ nodes,
1440
+ edges
1441
+ };
1442
+ }
1443
+ /**
1444
+ * An axis that exists to hold coordinates and to show nothing.
1445
+ *
1446
+ * Note what is *not* here: `axisLine: { show: false }`. echarts-gl records the axis line's two
1447
+ * endpoints only while it is drawing that line, and the camera-change handler then reads them to
1448
+ * decide which way the labels face — so an axis with its line switched off throws
1449
+ * `Cannot read properties of null` out of `_updateAxisLabelAlign` on every frame the camera
1450
+ * moves, which on an auto-rotating panel is all of them. The box is hidden with `grid3D.show`
1451
+ * instead, which takes the whole thing — faces, axes, labels — out of the scene and skips that
1452
+ * handler entirely.
1453
+ */
1454
+ function hiddenAxis() {
1455
+ return {
1456
+ type: "value",
1457
+ name: "",
1458
+ min: -ORBIT_EXTENT,
1459
+ max: ORBIT_EXTENT,
1460
+ axisPointer: { show: false }
1461
+ };
1462
+ }
1463
+ /**
1464
+ * The whole scene.
1465
+ *
1466
+ * `animate` is the host's word and `panel.rotate` is the fence's; either one saying no stops the
1467
+ * camera. ECharts' own animation is off throughout — on each series as well as at the root,
1468
+ * because echarts-gl's vertex animation asks the *series* whether it may animate and does not
1469
+ * fall back to the screen's answer. While the graph settles this option's data is replaced every
1470
+ * frame, and an animated transition would spend that frame interpolating towards positions the
1471
+ * next frame has already superseded.
1472
+ */
1473
+ function graphOrbitOption(panel, c, animate, positions) {
1474
+ const data = graphOrbitData(panel, c, positions);
1475
+ const name = (params) => params.data?.name ?? "";
1476
+ return {
1477
+ backgroundColor: "transparent",
1478
+ textStyle: {
1479
+ color: c.text,
1480
+ fontFamily: FONT
1481
+ },
1482
+ animation: false,
1483
+ tooltip: {
1484
+ trigger: "item",
1485
+ confine: true,
1486
+ formatter: graphTooltip
1487
+ },
1488
+ xAxis3D: hiddenAxis(),
1489
+ yAxis3D: hiddenAxis(),
1490
+ zAxis3D: hiddenAxis(),
1491
+ grid3D: {
1492
+ show: false,
1493
+ boxWidth: ORBIT_BOX,
1494
+ boxHeight: ORBIT_BOX,
1495
+ boxDepth: ORBIT_BOX,
1496
+ environment: "none",
1497
+ axisPointer: { show: false },
1498
+ light: {
1499
+ main: {
1500
+ intensity: 1.2,
1501
+ shadow: false,
1502
+ alpha: 30,
1503
+ beta: 40
1504
+ },
1505
+ ambient: { intensity: .6 }
1506
+ },
1507
+ viewControl: {
1508
+ projection: "perspective",
1509
+ autoRotate: animate && panel.rotate !== false,
1510
+ autoRotateSpeed: ORBIT_SPEED,
1511
+ autoRotateAfterStill: 4,
1512
+ distance: ORBIT_DISTANCE,
1513
+ alpha: 18,
1514
+ beta: 25,
1515
+ damping: .85
1516
+ }
1517
+ },
1518
+ series: [{
1519
+ type: "line3D",
1520
+ coordinateSystem: "cartesian3D",
1521
+ animation: false,
1522
+ lineStyle: { width: 1.6 },
1523
+ silent: true,
1524
+ data: data.edges
1525
+ }, {
1526
+ type: "scatter3D",
1527
+ coordinateSystem: "cartesian3D",
1528
+ animation: false,
1529
+ symbolSize: (value) => value[3],
1530
+ itemStyle: { opacity: .95 },
1531
+ label: {
1532
+ show: true,
1533
+ formatter: (params) => params.data?.labelled ? params.data.name ?? "" : "",
1534
+ color: c.text,
1535
+ fontSize: 11,
1536
+ fontFamily: FONT,
1537
+ distance: 4,
1538
+ backgroundColor: "transparent"
1539
+ },
1540
+ emphasis: {
1541
+ label: {
1542
+ show: true,
1543
+ formatter: name
1544
+ },
1545
+ itemStyle: { opacity: 1 }
1546
+ },
1547
+ data: data.nodes
1548
+ }]
1549
+ };
1550
+ }
1551
+
1552
+ //#endregion
1553
+ //#region src/positions.ts
1554
+ /**
1555
+ * Where each graph settled last time it was drawn.
1556
+ *
1557
+ * A streamed answer re-renders the same fence as the model writes it: a graph of twenty entities
1558
+ * becomes the same graph of twenty-three, and the reconciler tears the panel down and mounts a
1559
+ * new one. Without a memory the new layout starts from the hash again, every node lands somewhere
1560
+ * else, and the reader — who was reading it — watches the picture they had just understood
1561
+ * dissolve because three names arrived.
1562
+ *
1563
+ * So the positions are kept by node id, under a key that deliberately does *not* depend on the
1564
+ * node set: the ids that are still there resume exactly where they were, and only the new ones
1565
+ * have to find a place. It is module-level state, which is what makes it survive the remount; it
1566
+ * is bounded so a long conversation full of graphs cannot grow it without limit, and it is
1567
+ * forgettable so tests do not leak into each other.
1568
+ */
1569
+ /** How many graphs are remembered at once. Beyond this the least recently used one is dropped. */
1570
+ const REMEMBERED_GRAPHS = 8;
1571
+ /** Insertion order is the recency order: `Map` iterates oldest first, which is the whole trick. */
1572
+ const settled = new Map();
1573
+ /**
1574
+ * What identifies a graph across a re-render.
1575
+ *
1576
+ * The title, because that is the one thing a model rewriting its own fence keeps stable while the
1577
+ * entities underneath it change. A panel with no title falls back to its first entity, which is
1578
+ * the next most stable thing there is — a graph usually keeps the entity it was drawn around.
1579
+ * The prefix keeps a panel titled `kyiv` from colliding with an untitled one whose first node is
1580
+ * `kyiv`.
1581
+ */
1582
+ function graphKey(panel) {
1583
+ return panel.title !== void 0 ? `title:${panel.title}` : `node:${panel.nodes[0]?.id ?? ""}`;
1584
+ }
1585
+ /** The positions this graph settled into last time, by node id, or nothing. */
1586
+ function recallPositions(key) {
1587
+ const found = settled.get(key);
1588
+ if (!found) return void 0;
1589
+ settled.delete(key);
1590
+ settled.set(key, found);
1591
+ return found;
1592
+ }
1593
+ /**
1594
+ * Remember where a graph settled.
1595
+ *
1596
+ * The positions are copied out of the buffer rather than kept by reference: `Layout.positions()`
1597
+ * hands back the live array, and a layout that is still running would otherwise have this
1598
+ * remember whatever it became several frames later.
1599
+ */
1600
+ function rememberPositions(key, ids, positions) {
1601
+ const map = new Map();
1602
+ for (const [index, id] of ids.entries()) map.set(id, [
1603
+ positions[index * 3],
1604
+ positions[index * 3 + 1],
1605
+ positions[index * 3 + 2]
1606
+ ]);
1607
+ settled.delete(key);
1608
+ settled.set(key, map);
1609
+ while (settled.size > REMEMBERED_GRAPHS) {
1610
+ const oldest = settled.keys().next();
1611
+ if (oldest.done) break;
1612
+ settled.delete(oldest.value);
1613
+ }
1614
+ }
1615
+ /** Drop every remembered graph. For tests, and for a host tearing a page down. */
1616
+ function forgetPositions() {
1617
+ settled.clear();
1618
+ }
1619
+
1620
+ //#endregion
1621
+ export { EDGE_VERTICES, GRAPH_LABELS, GRAPH_LEGEND_ROWS, GRAPH_MAX_STEPS, GRAPH_SETTLE_STEPS, LAYOUT_GRAVITY, LAYOUT_SPRING, ORBIT_BOX, ORBIT_DISTANCE, ORBIT_EXTENT, ORBIT_FOV, REMEMBERED_GRAPHS, TIMELINE_LABELS, chart3dOption, chartOption, countriesTexture, createLayout, degrees, earthColours, earthTexture, forgetPositions, formatNumber, gaugeColour, gaugeOption, globeOption, globeTexture, graph3dOption, graphKey, graphLegend, graphOrbitData, graphOrbitOption, graphTooltip, hash, layoutChunk, layoutRadius, layoutSteps, orbitFrame, palette, recallPositions, rememberPositions, seedPositions, spacedItems, timelineHeight, timelineOption, timelineWindow, typeColour, withAlpha };