-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChart.tsx
More file actions
2121 lines (2036 loc) · 80.7 KB
/
Copy pathChart.tsx
File metadata and controls
2121 lines (2036 loc) · 80.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
'use client';
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
import type {
ActiveElement,
Chart as ChartJs,
ChartDataset,
ChartEvent,
LegendItem,
Plugin,
TooltipModel,
} from 'chart.js';
import {
CHART_FETCH_N,
clampRangeWindow,
collectAllValues,
commitDateLabel,
decimateSeries,
DEFAULT_VISIBLE,
escapeHtml,
FETCH_N,
FETCH_TIMEOUT_MS,
firstLine,
formatDisplayValue,
HOVER_DWELL_MS,
HOVER_PREFETCH_PRIORITY,
IDENTITY_UNIT,
INTERACTION_FULL_PRIORITY,
LAZY_HYDRATION_ROOT_MARGIN,
MAX_VISIBLE_POINTS,
normalizeChartPayload,
PAN_THROTTLE_MS,
parsePrNumber,
pickDisplayUnit,
predecessorValue,
rangeTouchesUnloadedHistory,
displaySeriesLabel,
seriesOrder,
seriesPassesFilter,
seriesPassesGroupFilter,
seriesStyle,
shortDate,
shortSha,
throttle,
truncate,
visibleRange,
ZOOM_THROTTLE_MS,
type DisplayUnit,
type NormalizedChartPayload,
} from '@/lib/chart-format';
import { loadChartJs } from '@/lib/chart-js';
import {
abortGroupBundle,
emptyGroupSnapshot,
ensureGroupBundle,
fullHistoryQueue,
getCachedPayload,
getGlobalFilterSnapshot,
getGroupSnapshot,
hydrationQueue,
noteGroupSeries,
subscribeGlobalFilter,
subscribeGroup,
type QueueEntry,
} from '@/lib/chart-store';
import type { ChartResponse } from '@/lib/queries';
/**
* The per-chart client island, the React port of the per-card layer of
* `server/static/chart-init.js`: the card chrome (title, toolbar, tooltip host,
* canvas, range strip, downsample badge) plus the full interactive behavior.
*
* Architecture notes (where the port deviates mechanically from v3; the few
* DELIBERATE behavioral deviations are documented at their sites, e.g.
* `applyY`'s pre-construction recording and the permalink page's title row):
*
* - v3 planted per-chart state on the canvas node (`canvas.__bench_*`); here
* the same fields live in a [`CardState`] owned by a [`ChartController`]
* created once per EFFECT MOUNT (torn down in that effect's cleanup, so
* React StrictMode's dev replay gets a fresh controller), and the v3 free
* functions became its methods. On creation the controller replays the
* group store's current state (group Y), since the store outlives mounts.
* - v3 wired group hydration per group (shard fetches); v4 has no shard route,
* so each island lazily fetches its own `/api/chart/{slug}?n=100` through the
* shared bounded [`hydrationQueue`] on group open (or pointer intent). The
* one-shot `?n=all` upgrade through [`fullHistoryQueue`] is opt-in: it runs
* only on per-chart intent (window-chip click, hover dwell, or pan/zoom into
* the unloaded region), never as an automatic group-open warmup.
* - High-frequency mutations (slider value, badge text, range-strip geometry,
* tooltip markup, `dataset.data` rebuilds) stay imperative on refs, exactly
* as v3 mutated the DOM; React state is reserved for low-frequency bits (the
* Y-button highlight, the loading/error indicators).
* - Group open/close stays native `<details>` behavior; the island listens for
* the `toggle` event of its enclosing disclosure (fired for both user and
* scripted changes, which is how Expand All reaches the islands without a
* shared React tree).
*/
/** A Chart.js line dataset extended with the bench-specific carry-alongs. */
interface BenchDataset extends ChartDataset<'line', (number | null)[]> {
/** The unmodified payload values; the tooltip reads these regardless of
* which indices LTTB kept in `data`. */
rawData: (number | null)[];
/** Engine/format tag used by the global filter's bulk hide/show. */
benchMeta: { engine?: string; format?: string };
}
/** The per-island mutable state, the port of the v3 `canvas.__bench_*` contract. */
interface CardState {
chart: ChartJs | null;
constructing: boolean;
payload: NormalizedChartPayload | null;
ui: { y: 'linear' | 'log'; scope: number | 'all' };
/** Series labels the user has explicitly legend-toggled on this card. Once
* set, the global/group filters no longer drive that label here. */
overrides: Record<string, true>;
displayUnit: DisplayUnit;
/** v3 also tracked `__bench_inline_trimmed`; it was write-only there and is
* dropped here. `payload.history.complete` carries the same information. */
fullLoaded: boolean;
initialFetchEntry: QueueEntry | null;
fullFetchEntry: QueueEntry | null;
fullFetchPending: Promise<void> | null;
/** The in-flight `?n=100` fetch's per-fetch aborter; lets a group close or
* destroy cancel it without aborting the controller-lifetime `aborter`. */
initialFetchController: AbortController | null;
/** The in-flight `?n=all` fetch's per-fetch aborter; same role as above. */
fullFetchController: AbortController | null;
/** True once this card has rendered a bounded window (so the chip is shown);
* a chart born complete never sets it and shows no chip. */
everWindowed: boolean;
/** The most recent full-history fetch failed; the chip offers a retry. */
chipError: boolean;
/** The pointer is currently resting on this card (chip shows the action). */
hovering: boolean;
/** Pending hover-dwell prefetch timer; cleared on `pointerleave`/destroy. */
hoverDwellTimer: ReturnType<typeof setTimeout> | null;
/** A full-history fetch returned 404: there is nothing beyond the window to
* load, so the chip stops offering the action and hovers stop re-fetching. */
fullUnavailable: boolean;
yUserSet: boolean;
stripRender: (() => void) | null;
rebuild: ((chart: ChartJs) => void) | null;
wheelAttached: boolean;
disposed: boolean;
}
/** The DOM handles the controller operates on, resolved from refs at call time. */
interface CardElements {
card: HTMLElement | null;
canvas: HTMLCanvasElement | null;
tooltipHost: HTMLDivElement | null;
slider: HTMLInputElement | null;
badge: HTMLSpanElement | null;
chip: HTMLButtonElement | null;
strip: HTMLDivElement | null;
stripWindow: HTMLDivElement | null;
}
/** React-state setters the controller drives (low-frequency UI bits only). */
interface CardCallbacks {
setY: (y: 'linear' | 'log') => void;
setLoading: (on: boolean) => void;
setError: (msg: string | null) => void;
/** Show/hide the initial-fetch retry control in the error region. */
setRetryable: (on: boolean) => void;
/** Flip once the Chart.js instance exists, so the pre-data placeholder hides. */
setConstructed: (on: boolean) => void;
}
/** Subtle, theme-neutral grid line color (slate-gray at low opacity), matching
* the v2 frontend's faint gridlines a reviewer preferred over the heavier
* Chart.js default. */
const GRID_COLOR = 'rgba(148, 163, 184, 0.14)';
// ---------------------------------------------------------------------------
// Crosshair plugin: draws a vertical line at the chart's active hover index.
// An inline plugin is cheaper than chartjs-plugin-crosshair, which is overkill
// for this one feature.
// ---------------------------------------------------------------------------
const crosshairPlugin: Plugin<'line'> = {
id: 'benchCrosshair',
afterDatasetsDraw(chart) {
const active = chart.tooltip?.getActiveElements ? chart.tooltip.getActiveElements() : [];
if (!active || active.length === 0) {
return;
}
const x = active[0].element.x;
const ya = chart.scales?.y;
if (!ya || !Number.isFinite(x)) {
return;
}
const ctx = chart.ctx;
ctx.save();
// `--muted` from the page theme, read lazily so dark mode picks up the
// right color.
const muted =
getComputedStyle(document.documentElement).getPropertyValue('--muted').trim() || '#9ca3af';
ctx.strokeStyle = muted;
ctx.lineWidth = 1;
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.moveTo(x, ya.top);
ctx.lineTo(x, ya.bottom);
ctx.stroke();
ctx.restore();
},
};
/** Read a chart's datasets with the bench carry-alongs visible to the types. */
function benchDatasets(chart: ChartJs): BenchDataset[] {
return chart.data.datasets as BenchDataset[];
}
/**
* Build the per-series dataset shells. `data` starts as a full-length
* null-padded array; `rebuildVisibleAndUpdate` fills it in based on the current
* visible range. `rawData` holds a reference to the original payload so the
* tooltip can show raw values regardless of LTTB.
*/
function buildDatasets(payload: NormalizedChartPayload): BenchDataset[] {
const raw = payload.series ?? {};
const meta = payload.series_meta ?? {};
const n = payload.commits.length;
const global = getGlobalFilterSnapshot();
return Object.keys(raw)
.sort()
.map((name) => {
const seriesMeta = meta[name] ?? {};
const rawValues = Array.isArray(raw[name]) ? raw[name] : [];
// Tier-based style: the named Vortex/Parquet series get vivid, thicker
// lines; everything else is muted and thin (see `seriesStyle`).
const style = seriesStyle(name, seriesMeta);
// `data` starts null-padded; `rebuildVisibleAndUpdate` fills the current
// visible window with raw or LTTB-kept values. With `spanGaps: true` the
// line connects across nulls, so a series with partial coverage still
// draws as a continuous trend; markers only appear at non-null indices.
const data = new Array<number | null>(n).fill(null);
return {
label: name,
data,
rawData: rawValues,
borderColor: style.color,
backgroundColor: `${style.color}20`,
borderWidth: style.width,
// Layer the hero series on top: Vortex in front ... arrow at the back,
// datafusion ahead of duckdb. Lower `order` renders on top in Chart.js.
order: seriesOrder(name, seriesMeta),
spanGaps: true,
tension: 0,
pointRadius: 2,
pointHoverRadius: 5,
pointHitRadius: 8,
pointStyle: 'cross',
benchMeta: { engine: seriesMeta.engine, format: seriesMeta.format },
hidden: !seriesPassesFilter(seriesMeta, global.active, global.universe),
} satisfies BenchDataset;
});
}
/**
* The external tooltip handler factory, ported verbatim from v3 including the
* flicker fix: the tooltip host is ALWAYS `pointer-events: none` (via CSS); the
* previous v2 implementation flipped it to `auto` when visible and the cursor
* would oscillate between canvas and tooltip at event-loop frequency. Clicks on
* a data point are handled by the chart's `onClick`, so the tooltip itself
* never needs to be interactive.
*/
function externalTooltipHandler(state: CardState, host: HTMLDivElement | null) {
return (context: { chart: ChartJs; tooltip: TooltipModel<'line'> }) => {
const tt = context.tooltip;
if (!host) {
return;
}
if (tt.opacity === 0) {
host.style.opacity = '0';
return;
}
const chart = context.chart;
const firstDp = tt.dataPoints?.[0];
if (!firstDp) {
host.style.opacity = '0';
return;
}
// Snap to a single commit: `mode: "nearest"` means `firstDp.dataIndex` is
// the single closest data point to the cursor (skipping nulls). If the
// cursor falls between two LTTB-kept points, exactly one wins.
const idx = firstDp.dataIndex;
const commit = state.payload?.commits?.[idx] ?? null;
const displayUnit = state.displayUnit ?? IDENTITY_UNIT;
// Build one row per dataset from each series' `rawData` so the tooltip
// shows raw measurements even when LTTB nulled out `dataset.data[idx]`.
// Iterating `chart.data.datasets` directly (instead of `tt.dataPoints`)
// guarantees one row per series at this single commit.
const rowItems = benchDatasets(chart)
.map((ds, dsIndex) => {
const meta = chart.getDatasetMeta(dsIndex);
if (meta?.hidden || ds.hidden) {
return null;
}
const raw = ds.rawData?.[idx];
if (raw === null || raw === undefined || Number.isNaN(raw)) {
return null;
}
// Per-row delta is `(current - previous) / previous`, where "previous"
// is the chronologically preceding commit per the BAN-pinned `idx - 1`
// oldest-first walk in [`predecessorValue`].
const prevRaw = predecessorValue(ds.rawData ?? [], idx);
let deltaHtml = '';
if (prevRaw !== null && prevRaw !== 0) {
const pct = ((raw - prevRaw) / prevRaw) * 100;
const cls =
pct > 0
? 'tt-delta tt-delta--worse'
: pct < 0
? 'tt-delta tt-delta--better'
: 'tt-delta';
const sign = pct > 0 ? '+' : '';
deltaHtml = `<span class="${cls}">${sign}${pct.toFixed(1)}%</span>`;
}
return { label: ds.label ?? '', color: String(ds.borderColor), raw, deltaHtml };
})
.filter((r): r is NonNullable<typeof r> => r !== null);
// Top-to-bottom order matches the visual stack of lines at this x.
rowItems.sort((a, b) => b.raw - a.raw);
const rows = rowItems
.map(
(r) =>
`<div class="tt-row">` +
`<span class="tt-swatch" style="background:${r.color}"></span>` +
`<span class="tt-label">${escapeHtml(displaySeriesLabel(r.label))}</span>` +
`<span class="tt-value">${escapeHtml(formatDisplayValue(r.raw, displayUnit))}</span>` +
r.deltaHtml +
`</div>`,
)
.join('');
// If every series was hidden or had no value at this commit, treat this as
// a no-op hover instead of flashing an empty popup.
if (!rows) {
host.style.opacity = '0';
return;
}
const titleHtml =
`<div class="tt-title">` +
`${escapeHtml(shortSha(commit?.sha))} · ${escapeHtml(shortDate(commit?.timestamp))}` +
`</div>`;
// Short SHA + first-line commit message, truncated. The full URL (or PR
// URL) is wired up via the chart's onClick handler.
const msg = truncate(firstLine(commit?.message ?? ''), 80);
const footerLine = commit?.sha
? msg
? `${escapeHtml(shortSha(commit.sha))} · ${escapeHtml(msg)}`
: escapeHtml(shortSha(commit.sha))
: escapeHtml(msg);
const footerHtml = footerLine
? `<div class="tt-footer"><div class="tt-msg">${footerLine}</div></div>`
: '';
host.innerHTML = `${titleHtml}<div class="tt-rows">${rows}</div>${footerHtml}`;
// Position the tooltip relative to its container, offset 12px from the
// cursor; flip horizontally if it would overflow.
const canvasRect = context.chart.canvas.getBoundingClientRect();
const parent = host.parentNode as HTMLElement;
const hostRect = parent.getBoundingClientRect();
const x = canvasRect.left - hostRect.left + tt.caretX;
const y = canvasRect.top - hostRect.top + tt.caretY;
host.style.opacity = '1';
host.style.left = `${x}px`;
host.style.top = `${y}px`;
// Measure after the content swap so flipping is correct.
const ttWidth = host.offsetWidth || 0;
const containerWidth = parent.clientWidth || 0;
const flip = x + ttWidth + 24 > containerWidth;
host.style.transform = flip ? 'translate(calc(-100% - 12px), 12px)' : 'translate(12px, 12px)';
};
}
/**
* The imperative per-island engine. Created once per MOUNT (not per component
* instance): React StrictMode runs every dev effect as mount, cleanup, remount,
* and `destroy()` is one-way, so the mount effect constructs a fresh controller
* each time it runs and tears the previous one down in its cleanup. Every
* method is a direct port of the corresponding `chart-init.js` function with
* the canvas field-stash replaced by [`CardState`]; the DOM listeners the
* controller attaches (wheel pan, range-strip pointers) are registered with its
* own abort signal so a teardown removes them from the still-mounted nodes
* before the next controller re-binds.
*/
class ChartController {
private readonly state: CardState;
/** Aborted on [`destroy`]; every controller-attached DOM listener uses it. */
private readonly aborter = new AbortController();
/** Failed Chart.js dynamic-import attempts; bounds the error-dismiss retry. */
private loadAttempts = 0;
constructor(
private readonly slug: string,
private readonly groupSlug: string | undefined,
private readonly els: () => CardElements,
private readonly cb: CardCallbacks,
) {
this.state = {
chart: null,
constructing: false,
payload: null,
ui: { y: 'linear', scope: DEFAULT_VISIBLE },
overrides: {},
displayUnit: IDENTITY_UNIT,
fullLoaded: false,
initialFetchEntry: null,
fullFetchEntry: null,
fullFetchPending: null,
initialFetchController: null,
fullFetchController: null,
everWindowed: false,
chipError: false,
hovering: false,
hoverDwellTimer: null,
fullUnavailable: false,
yUserSet: false,
stripRender: null,
rebuild: null,
wheelAttached: false,
disposed: false,
};
}
/** Seed the permalink page's server-fetched payload before any fetch runs. */
seedPayload(payload: ChartResponse): void {
const normalized = normalizeChartPayload(payload);
this.state.payload = normalized;
this.state.fullLoaded = normalized.history.complete;
if (!normalized.history.complete) {
this.state.everWindowed = true;
}
this.syncWindowChip();
if (this.groupSlug) {
noteGroupSeries(this.groupSlug, normalized.series_meta);
}
}
/** Whether the enclosing group disclosure (if any) is open. */
private groupIsOpen(): boolean {
const card = this.els().card;
const group = card?.closest('.group-details');
const details = group?.querySelector('details.group-disclosure');
return !details || (details as HTMLDetailsElement).open;
}
/**
* Ensure this chart's default `?n=100` payload is loaded. Consults the session
* payload cache first (a sibling group-bundle fetch may have already cached
* it), then on the landing page drives one bundle fetch per group, falling
* back to the per-chart [`fetchInitialPayloadDirect`] only when the bundle does
* not cover this slug. The permalink page (no group slug) goes straight to the
* per-chart fetch. `showLoading` mirrors v3: the group-open path shows the
* per-card loading indicator, the pointer-intent prefetch stays silent.
*/
ensureInitialPayload(priority: number, showLoading: boolean): Promise<void> {
const state = this.state;
if (state.payload || state.disposed) {
return Promise.resolve();
}
// Fast path: a sibling group-bundle fetch may have already cached this
// chart's default payload. Seed from it synchronously (the same steps as the
// fetch success path) so no per-chart request is issued.
const cached = getCachedPayload(this.slug);
if (cached) {
this.seedFromCachedPayload(cached);
return Promise.resolve();
}
// On the landing page (a group slug is present), drive one bundle fetch per
// group and hydrate from it. Only fall through to the per-chart fetch when
// the bundle is unavailable (404 / failed / this slug missing).
if (this.groupSlug) {
if (showLoading) {
this.cb.setLoading(true);
this.cb.setRetryable(false);
}
const groupSlug = this.groupSlug;
return ensureGroupBundle(groupSlug, priority).then(() => {
// The group can close while this card awaits the in-flight bundle. The
// close runs `abortInFlightFetches` + `abortGroupBundle` already, so a
// per-chart fallback issued now would never be aborted and would defeat
// the "closing a group frees server capacity" contract. Bail when the
// group is no longer open.
if (state.disposed || state.payload || !this.groupIsOpen()) {
return;
}
const fromBundle = getCachedPayload(this.slug);
if (fromBundle) {
this.seedFromCachedPayload(fromBundle);
return;
}
// Bundle did not cover this chart: fall back to the per-chart fetch.
return this.fetchInitialPayloadDirect(priority, showLoading);
});
}
return this.fetchInitialPayloadDirect(priority, showLoading);
}
/** Seed state from a cached default payload (the bundle/cache hit path),
* mirroring the per-chart fetch's success handler. Does NOT call
* `maybeConstruct`; the caller does after the returned promise resolves. */
private seedFromCachedPayload(raw: ChartResponse): void {
const state = this.state;
// A concurrent full-history upgrade may already have constructed from the
// `?n=all` payload; the late cache seed must not clobber that back to the
// bounded window (same invariant as the per-chart success handler).
if (state.fullLoaded) {
return;
}
const normalized = normalizeChartPayload(raw);
state.payload = normalized;
state.fullLoaded = normalized.history.complete;
if (!normalized.history.complete) {
state.everWindowed = true;
}
this.syncWindowChip();
this.cb.setLoading(false);
if (this.groupSlug) {
noteGroupSeries(this.groupSlug, normalized.series_meta);
}
}
/**
* Queue the initial `?n=100` fetch through the bounded hydration queue (or
* bump its priority if already queued). The per-chart fallback for the bundle
* path and the only path on the permalink page. `showLoading` mirrors v3: the
* group-open path shows the per-card loading indicator, the pointer-intent
* prefetch stays silent.
*/
private fetchInitialPayloadDirect(priority: number, showLoading: boolean): Promise<void> {
const state = this.state;
if (state.initialFetchEntry) {
if (priority > state.initialFetchEntry.priority) {
state.initialFetchEntry.priority = priority;
hydrationQueue.drain();
}
if (showLoading) {
this.cb.setLoading(true);
this.cb.setRetryable(false);
}
return state.initialFetchEntry.promise.then(
() => undefined,
() => undefined,
);
}
if (showLoading) {
this.cb.setLoading(true);
this.cb.setRetryable(false);
}
const url = `/api/chart/${encodeURIComponent(this.slug)}?n=${encodeURIComponent(CHART_FETCH_N)}`;
const fc = new AbortController();
state.initialFetchController = fc;
// Bridge the controller-lifetime aborter to this per-fetch controller so
// `destroy()` cancels the in-flight request. `{ once: true }` self-removes
// the listener after a single abort; the `finally` removes it on the no-abort
// path. Propagate the parent's reason so a destroy reads as `AbortError`.
const onParentAbort = (): void => fc.abort(this.aborter.signal.reason);
this.aborter.signal.addEventListener('abort', onParentAbort, { once: true });
if (this.aborter.signal.aborted) {
fc.abort(this.aborter.signal.reason);
}
const entry = hydrationQueue.schedule(async () => {
// The timeout starts when the task actually runs (not while queued), so it
// measures fetch duration, not queue wait. A `TimeoutError` reason lets the
// catch tell a timeout apart from a close/destroy `AbortError`.
const timer = setTimeout(
() => fc.abort(new DOMException('Fetch timed out', 'TimeoutError')),
FETCH_TIMEOUT_MS,
);
try {
const r = await fetch(url, { headers: { accept: 'application/json' }, signal: fc.signal });
if (!r.ok) {
throw new Error(r.status === 404 ? 'not found' : `HTTP ${r.status}`);
}
return (await r.json()) as ChartResponse;
} finally {
clearTimeout(timer);
this.aborter.signal.removeEventListener('abort', onParentAbort);
}
}, priority);
state.initialFetchEntry = entry;
return entry.promise.then(
(raw) => {
if (state.initialFetchEntry === entry) {
state.initialFetchEntry = null;
}
if (state.initialFetchController === fc) {
state.initialFetchController = null;
}
if (state.disposed) {
return;
}
// A concurrent full-history upgrade (hover dwell or chip click) may have
// already resolved and constructed from the `?n=all` payload while this
// `?n=100` window was still in flight. The late window resolution must
// not clobber that full payload back to the bounded window (which would
// diverge `payload` from the rendered datasets, regress the chip, and
// re-arm a redundant pan-triggered refetch).
if (state.fullLoaded) {
return;
}
const normalized = normalizeChartPayload(raw as ChartResponse);
state.payload = normalized;
state.fullLoaded = normalized.history.complete;
if (!normalized.history.complete) {
state.everWindowed = true;
}
this.syncWindowChip();
this.cb.setLoading(false);
if (this.groupSlug) {
noteGroupSeries(this.groupSlug, normalized.series_meta);
}
void this.maybeConstruct();
},
(err: unknown) => {
if (state.initialFetchEntry === entry) {
state.initialFetchEntry = null;
}
if (state.initialFetchController === fc) {
state.initialFetchController = null;
}
if (state.disposed) {
return;
}
// A close/destroy cancellation aborts with `AbortError`: stay silent and
// do NOT touch the loading state, which may now belong to a fresh fetch
// scheduled after a reopen (clearing it here would extinguish that
// newer fetch's spinner). A timeout (`TimeoutError`) or a genuine
// network/HTTP failure clears loading and surfaces the error indicator.
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
this.cb.setLoading(false);
const message =
err instanceof DOMException && err.name === 'TimeoutError'
? 'timed out'
: err instanceof Error
? err.message
: 'unknown error';
this.cb.setError(`failed to load: ${message}`);
this.cb.setRetryable(true);
},
);
}
/** Re-issue the initial `?n=100` fetch after a failure/timeout. User-initiated
* (the error region's retry control), so it is naturally bounded; clears the
* error first and schedules at the top of the hydration queue.
*/
retryInitialPayload(): void {
if (this.state.disposed || this.state.payload) {
return;
}
this.cb.setError(null);
this.cb.setRetryable(false);
void this.ensureInitialPayload(0, true).then(() => {
if (this.state.disposed) {
return;
}
void this.maybeConstruct();
});
}
/**
* Hydrate this chart's latest-100 window at `priority` and construct. Full
* history is NOT warmed here; it loads only on explicit per-chart intent
* (window-chip click, hover dwell, or pan/zoom into the unloaded region). The
* priority is the negated visual `index`, so top cards drain ahead of lower
* ones (the queue drains highest-priority-first).
*/
onGroupOpen(priority: number): void {
void this.ensureInitialPayload(priority, true).then(() => {
if (this.state.disposed) {
return;
}
void this.maybeConstruct();
});
}
/**
* Queue the one-shot `?n=all` full-history upgrade (or promote the queued
* entry's priority). Triggered only by explicit intent — window-chip click
* (`INTERACTION_FULL_PRIORITY`), hover dwell (`HOVER_PREFETCH_PRIORITY`), or
* pan/zoom touching the unloaded region — never as an automatic warmup.
*/
ensureFullHistory(priority: number): Promise<void> {
const state = this.state;
// `fullUnavailable` is checked here (not only at the chip/hover call sites)
// so every intent path shares one terminal-404 guard, including the pan/zoom
// `rangeTouchesUnloadedHistory` promotion, which must not re-issue a fetch
// that already 404'd.
if (state.fullLoaded || state.fullUnavailable || state.disposed) {
return Promise.resolve();
}
if (state.fullFetchEntry) {
if (priority > state.fullFetchEntry.priority) {
state.fullFetchEntry.priority = priority;
fullHistoryQueue.drain();
}
return state.fullFetchPending ?? Promise.resolve();
}
const url = `/api/chart/${encodeURIComponent(this.slug)}?n=${encodeURIComponent(FETCH_N)}`;
const fc = new AbortController();
state.fullFetchController = fc;
const onParentAbort = (): void => fc.abort(this.aborter.signal.reason);
this.aborter.signal.addEventListener('abort', onParentAbort, { once: true });
if (this.aborter.signal.aborted) {
fc.abort(this.aborter.signal.reason);
}
const entry = fullHistoryQueue.schedule(async () => {
const timer = setTimeout(
() => fc.abort(new DOMException('Fetch timed out', 'TimeoutError')),
FETCH_TIMEOUT_MS,
);
try {
const r = await fetch(url, { headers: { accept: 'application/json' }, signal: fc.signal });
if (r.status === 404) {
return null;
}
if (!r.ok) {
throw new Error(`HTTP ${r.status}`);
}
return (await r.json()) as ChartResponse;
} finally {
clearTimeout(timer);
this.aborter.signal.removeEventListener('abort', onParentAbort);
}
}, priority);
state.fullFetchEntry = entry;
state.fullFetchPending = entry.promise
.then((full) => {
if (state.disposed) {
return;
}
if (full === null) {
state.fullUnavailable = true;
return;
}
this.replaceChartPayload(full as ChartResponse);
state.fullLoaded = true;
if (state.fullFetchController === fc) {
state.fullFetchController = null;
}
state.chipError = false;
this.cb.setLoading(false);
if (!state.chart && this.groupIsOpen()) {
void this.maybeConstruct();
}
})
.catch((err: unknown) => {
if (state.fullFetchController === fc) {
state.fullFetchController = null;
}
// A close/destroy cancellation is silent; a timeout or genuine failure
// leaves the chip's retry affordance (chipError) so the user can re-try.
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
// Quiet: the latest-100 payload is still usable. Surface to the console
// for debugging; the chip exposes the retry affordance.
console.warn('bench: full history fetch failed', err);
state.chipError = true;
})
.then(() => {
if (state.fullFetchEntry === entry) {
state.fullFetchEntry = null;
state.fullFetchController = null;
state.fullFetchPending = null;
}
// Always re-sync the chip so the UI reflects the latest state even when
// the guard above skips the stale entry clears.
this.syncWindowChip();
});
this.syncWindowChip();
return state.fullFetchPending;
}
/**
* Construct the Chart.js instance when the payload is present and the
* enclosing group (if any) is open. Loads Chart.js lazily on first need.
* Idempotent across overlapping calls via the `constructing` latch.
*/
async maybeConstruct(): Promise<void> {
const state = this.state;
if (state.chart || state.constructing || !state.payload || state.disposed) {
return;
}
if (!this.groupIsOpen()) {
return;
}
const { canvas, tooltipHost, card } = this.els();
if (!canvas || !card) {
return;
}
state.constructing = true;
try {
let Chart;
try {
Chart = await loadChartJs();
} catch (err) {
// A failed chunk load (deploy rotated the hashed assets, flaky
// network) surfaces like a fetch failure; the loader has already reset
// its cache, and the error indicator's auto-dismiss retries
// construction (bounded by `shouldRetryConstruct`) so charts whose
// only construction trigger already fired (the permalink page's
// one-shot IntersectionObserver) are not left permanently blank.
this.loadAttempts += 1;
if (!state.disposed) {
const message = err instanceof Error ? err.message : 'unknown error';
this.cb.setError(`failed to load chart library: ${message}`);
}
return;
}
if (state.disposed || state.chart || !state.payload) {
return;
}
// Re-check the disclosure AFTER the await: the group can close while the
// Chart.js chunk loads (a window v3 never had, its library being
// preloaded), and constructing into the display:none grid would render a
// zero-size chart. The next toggle-open re-enters via onGroupOpen.
if (!this.groupIsOpen()) {
return;
}
const payload = state.payload;
// Lock the display unit for the lifetime of this loaded payload; it is
// recomputed only when `replaceChartPayload` swaps in the wider window.
state.displayUnit = pickDisplayUnit(payload.unit_kind, collectAllValues(payload));
const labels = payload.commits.map(commitDateLabel);
const datasets = buildDatasets(payload);
const range = visibleRange(labels.length, state.ui.scope);
const legendPosition = window.matchMedia?.('(max-width: 768px)').matches ? 'top' : 'bottom';
// Throttled rebuild for pan/zoom: both axes mutate `scales.x.min/max`
// continuously during interaction, so the rendered points re-derive at
// most every PAN_THROTTLE_MS and the range strip refreshes in the same
// call so LTTB and the strip never diverge.
const throttledRebuild = throttle((chart: ChartJs) => {
const sx = chart.scales?.x;
if (!sx) {
return;
}
this.rebuildVisibleAndUpdate(chart, sx.min, sx.max, true);
state.stripRender?.();
}, PAN_THROTTLE_MS);
const state_ = state;
const chart = new Chart(canvas, {
type: 'line',
data: { labels, datasets },
plugins: [crosshairPlugin],
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
// Snap to the single nearest commit THAT HAS RENDERED DATA. After
// LTTB most commit indices are null in `dataset.data`; `mode:
// "index"` would pick null indices (empty tooltip) and `mode: "x"`
// would pick multiple closely-packed LTTB columns at once (duplicate
// rows). `intersect: false` keeps the tooltip active anywhere on the
// chart and, combined with `pointer-events: none` on the host, is
// also the flicker fix.
interaction: { mode: 'nearest', intersect: false, axis: 'x' },
onClick: (event: ChartEvent, _active: ActiveElement[], c: ChartJs) => {
const native = event.native;
if (!native) {
return;
}
const points = c.getElementsAtEventForMode(
native,
'nearest',
{ intersect: false, axis: 'x' },
true,
);
if (points.length === 0) {
return;
}
const commit = state_.payload?.commits?.[points[0].index];
if (!commit) {
return;
}
const pr = parsePrNumber(commit.message);
const url = pr ? `https://github.com/vortex-data/vortex/pull/${pr}` : commit.url;
if (url) {
window.open(url, '_blank', 'noopener');
}
},
scales: {
y: {
type: state.ui.y === 'log' ? 'logarithmic' : 'linear',
beginAtZero: state.ui.y !== 'log',
grid: { color: GRID_COLOR },
// The axis title reflects the locked display unit; empty for
// dimensionless kinds so a "1.2x speedup" chart does not get an
// arbitrary label.
title: {
display: state.displayUnit.axisLabel !== '',
text: state.displayUnit.axisLabel,
},
},
x: {
min: range.min,
max: range.max,
grid: { color: GRID_COLOR },
title: { display: false },
// One tick per commit is unreadable on a 5000-commit history;
// Chart.js picks a sensible subset.
ticks: { maxTicksLimit: 12, autoSkip: true },
},
},
plugins: {
legend: {
position: legendPosition,
// Rewrite only the displayed legend text (vortex-file-compressed ->
// vortex); `dataset.label` stays the real key the toggle/filter use.
labels: {
generateLabels: (ci) => {
const items = Chart.defaults.plugins.legend.labels.generateLabels(ci);
for (const item of items) {
if (typeof item.text === 'string') {
item.text = displaySeriesLabel(item.text);
}
}
return items;
},
},
// Wrap the default toggle to record the per-card override and
// keep `dataset.hidden` in sync with the legend's visibility
// flag; the filter passes write to `dataset.hidden`, so they
// need to track each other.
onClick: (_e: ChartEvent, item: LegendItem, legend) => {
const ci = legend.chart;
const ds = ci.data.datasets[item.datasetIndex ?? 0];
const label = ds?.label;
if (label) {
state_.overrides[label] = true;
}
const visible = ci.isDatasetVisible(item.datasetIndex ?? 0);
ci.setDatasetVisibility(item.datasetIndex ?? 0, !visible);
if (ds) {
// Flipped: was visible means now hidden, and vice versa.
ds.hidden = visible;
}
ci.update();
},
},
tooltip: {
enabled: false,
external: externalTooltipHandler(state, tooltipHost),
},
// A mouse drag draws a selection rectangle and zooms to it (the v3
// behavior), never pans. Panning is reserved for the wheel (manual
// listener below) and the range strip, so a plain drag highlights a
// region without sliding the axes. Wheel-zoom is disabled because
// wheel means PAN here.
zoom: {
zoom: {
wheel: { enabled: false },
drag: { enabled: true, backgroundColor: 'rgba(37, 99, 235, 0.10)' },
mode: 'x',
onZoom: (ctx) => throttledRebuild(ctx.chart),
},
// Drag-to-pan is disabled so a drag is a zoom selection, not a pan.
// The plugin's `chart.pan()` API (used by the wheel listener and the
// range strip) is NOT gated by this flag, so wheel/strip panning is
// unaffected; only the built-in drag-pan gesture is removed.
pan: {
enabled: false,
mode: 'x',
},
limits: {
x: { min: 0, max: Math.max(0, labels.length - 1), minRange: 4 },
},
},
},
},
});
state.chart = chart;
this.cb.setConstructed(true);
state.rebuild = throttledRebuild;
this.attachWheelPan(canvas, chart, throttledRebuild);
this.syncSliderBounds(labels.length);
// Initial render: populate the null data for the initial window, then