@tidal-ts/chart 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1154 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useRef, useCallback, Fragment, memo, useEffect, useMemo, useState, } from 'react';
3
+ import { AreaChart, BandChart, BarChart, Candlestick, ChartContainer, ChartRow, Layers, LineChart, Marker, Region, TimeAxis, YAxis, YAxisIndicator, } from '@pond-ts/charts';
4
+ import { segmentDiscontinuity, weekendSkip } from '@pond-ts/financial';
5
+ import { resolveTimeZone, aggregateColumn, hasPairOp, inferBarMs, liveWindowMs, ohlcWindow, readNumericColumn, sessionOpenLine, exactSessionSegments, sessionSegments, shiftKeys, WINDOW_MS, autoBarWindow, opOutputs, outputMark, } from '@tidal-ts/core';
6
+ import { candleStyleForColor, candleStyleForPair } from './candleStyle.js';
7
+ import { useMeasuredWidth } from './useMeasuredWidth.js';
8
+ import { DEFAULT_CHART_SETTINGS } from './chartSettings.js';
9
+ import { configAxisId, seriesDrawn, DASH_PATTERN, effectiveSplit, seriesAxisId, seriesLineDashArray, seriesLineWidth, sharedAxisId, axisFormat, bandColumns, outputKey, configColumns, } from './series.js';
10
+ /** The schema-erased series type every layer reads. Rows carry heterogeneous
11
+ * sources (vol `%`, price `$`), so the chart works in the erased schema and each
12
+ * config names its `column`. Callers build the {@link TimeSeriesChartProps.sources} map
13
+ * in this type — cast their specific `TimeSeries` in (schema erasure, like
14
+ * `@tidal-ts/core`'s aggregate output). */
15
+ /** Fallback for a series too short to infer sessions from (< 2 points): collapse
16
+ * weekends and nothing else. Built once — the container rebuilds the scale if the
17
+ * reference changes. */
18
+ const WEEKEND_SKIP = weekendSkip();
19
+ /** Stable empty default: a fresh `[]` per render would re-run the sessions memo
20
+ * (and rebuild the container's scale) on every frame. */
21
+ const EMPTY_DAYS = [];
22
+ /** Dash ladders for a multi-output study's 2nd..Nth line. Distinguishable at a
23
+ * glance and ordered so a longer dash reads as "further from the main output".
24
+ * Cycles past the end — a 12-output ribbon (`guppy`) wants a colour ramp
25
+ * rather than twelve dashes, which is a named TDL-STUDYDRAW case. */
26
+ const OUTPUT_DASHES = [
27
+ [6, 3],
28
+ [2, 2],
29
+ [9, 3, 2, 3],
30
+ [1, 3],
31
+ ];
32
+ const EMPTY_ANNOTATIONS = [];
33
+ const EMPTY_SOURCES = [];
34
+ /**
35
+ * Is this mark within the data's span?
36
+ *
37
+ * Clips on the mark's **own extent**, not on its line position — which is the bug
38
+ * this exists to prevent. A session-spanning annotation puts its line through the
39
+ * middle of the day (`at + 12h`), so at daily grain, where the last bar's key IS a
40
+ * UTC midnight, an event on the last in-view session sat half a day past the upper
41
+ * bound and the whole mark — band included — was filtered out. That silently
42
+ * dropped the MOST RECENT earnings, the one most worth seeing.
43
+ *
44
+ * The test is **overlap, not containment**: a band straddling either edge is still
45
+ * partly on screen, and should draw the part that is.
46
+ *
47
+ * Exported for its own test. Nothing about the failure is visible in a screenshot —
48
+ * a dropped annotation looks exactly like a quarter with no earnings.
49
+ */
50
+ export function annotationInView(a, lo, hi) {
51
+ // A band is HALF-OPEN — `[day, day + 1d]`, where the upper bound is the NEXT
52
+ // day's midnight and belongs to that day, not this one. So a band merely
53
+ // touching `lo` at its end covers only time before the first visible bar, and is
54
+ // outside. Hence the strict `>` here and the inclusive `>=` for a bare rule,
55
+ // which is a point and is visible when it lands exactly on the edge.
56
+ if (!a.band)
57
+ return a.at >= lo && a.at <= hi;
58
+ return a.band[1] > lo && a.band[0] <= hi;
59
+ }
60
+ /** Zoom-in floor when the drawn grain isn't known yet (no data): five days, the
61
+ * value this was hardcoded to for every grain. See {@link MIN_VIEW_BARS}. */
62
+ const MIN_VIEW_MS = 5 * 86_400_000;
63
+ /** Zoom-in floor, counted in **marks of the grain being drawn** rather than in
64
+ * calendar time.
65
+ *
66
+ * This was a flat five calendar days, with a comment reasoning about daily bars
67
+ * — and on daily bars five days *is* five bars, which is why it read as a
68
+ * sensible constant for as long as every series was daily. On 1-minute data the
69
+ * same number is 1,950 bars: at maximum zoom the plot holds about **half a pixel
70
+ * per bar**, so a minute candle can never be a pixel wide, let alone be read.
71
+ * The rule was always bars; only the units were wrong.
72
+ *
73
+ * Five marks of the **finest** drawn grain — finest because that is the series
74
+ * being zoomed in to read. A coarser companion series draws one wide body across
75
+ * the view at that zoom, which is what it should do. */
76
+ const MIN_VIEW_BARS = 5;
77
+ /** How often draw stats may reach React. A diagnostics line does not need 60 Hz,
78
+ * and a pan fires a frame per row per repaint. */
79
+ const STATS_MS = 250;
80
+ /** A bar of a count-like column (volume) sums over its window; a level (a vol or
81
+ * price) averages. */
82
+ const reducerFor = (c) => (c.column === 'volume' ? 'sum' : 'avg');
83
+ /** #rgb / #rrggbb → `[r, g, b]`, or null for any other colour form. */
84
+ function parseHex(hex) {
85
+ let h = hex.trim().replace(/^#/, '');
86
+ if (h.length === 3)
87
+ h = h
88
+ .split('')
89
+ .map((c) => c + c)
90
+ .join('');
91
+ const m = /^([\da-f]{6})$/i.exec(h);
92
+ if (!m)
93
+ return null;
94
+ const n = parseInt(m[1], 16);
95
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
96
+ }
97
+ /** How far a hovered axis's ink shifts toward the theme's extreme. */
98
+ const HOVER_LIFT = 0.42;
99
+ /** The default {@link TimeSeriesChartProps.resolveColor}: the config's colour is
100
+ * already a CSS colour. Module-level so its identity never churns the theme. */
101
+ const sameColor = (color) => color;
102
+ /**
103
+ * A hovered y-axis gutter's ink: the axis's own colour lifted toward **white
104
+ * in dark mode / black in light** — the affordance that says the gutter is
105
+ * clickable (it opens the axis panel). `<YAxis>` takes no cursor or hover
106
+ * props, so its `color` is the one presentation channel available; the shift
107
+ * is deliberately small (the axis must not read as selected). Non-hex colours
108
+ * pass through unchanged — hover simply no-ops rather than guessing.
109
+ */
110
+ function hoverInk(color, scheme) {
111
+ if (!color)
112
+ return undefined;
113
+ const rgb = parseHex(color);
114
+ if (!rgb)
115
+ return color;
116
+ const target = scheme === 'dark' ? 255 : 0;
117
+ const [r, g, b] = rgb.map((v) => Math.round(v + (target - v) * HOVER_LIFT));
118
+ return `rgb(${r}, ${g}, ${b})`;
119
+ }
120
+ /** #rgb / #rrggbb → rgba() with the given alpha (for dimming a series). Falls
121
+ * back to the input unchanged for any other color form (dim just no-ops). */
122
+ function withAlpha(hex, alpha) {
123
+ let h = hex.trim().replace(/^#/, '');
124
+ if (h.length === 3)
125
+ h = h
126
+ .split('')
127
+ .map((c) => c + c)
128
+ .join('');
129
+ const m = /^([\da-f]{6})$/i.exec(h);
130
+ if (!m)
131
+ return hex;
132
+ const n = parseInt(m[1], 16);
133
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
134
+ }
135
+ /** A row's per-side SHARED axis id — unique across the container so each row
136
+ * scales independently. Now the exported `sharedAxisId` (series.ts): the
137
+ * machine keys range state and the host builds the panel model with the same
138
+ * vocabulary. An unlinked config's OWN axis appends its id (`seriesAxisId`). */
139
+ /** The series' native bar interval, cached per series object so a re-render does
140
+ * not re-scan the key column. Weakly keyed: a new fetch drops the old entry. */
141
+ /** Sorted times with duplicates removed — a union of symbols repeats every shared
142
+ * bar, and exact adjacency must see each instant once. */
143
+ function dedupe(sorted) {
144
+ const out = [];
145
+ for (const t of sorted)
146
+ if (out[out.length - 1] !== t)
147
+ out.push(t);
148
+ return out;
149
+ }
150
+ /**
151
+ * Whether the series sits on a **regular grid** — every gap a whole number of
152
+ * intervals.
153
+ *
154
+ * Precisely what it checks, and no more. It does NOT verify that no bar is missing:
155
+ * a skipped minute leaves a 2-interval gap, which is a whole multiple and passes.
156
+ * That is fine, because a skipped bar splits the run under the OLD threshold rule
157
+ * too (a 2-minute gap clears a 1.5-minute threshold), so exact adjacency is no
158
+ * worse there — it is simply not better.
159
+ *
160
+ * What it does catch is a series whose keys are *off* the grid — an irregular or
161
+ * unaligned cadence, where exact adjacency would find no two bars adjacent and cut
162
+ * the axis into one segment per bar. That series wants the threshold's tolerance
163
+ * instead, so it falls back.
164
+ *
165
+ * Cheap: one pass of integer arithmetic, run once per fetch rather than per frame.
166
+ */
167
+ function isOnGrid(sorted, intervalMs) {
168
+ if (!(intervalMs > 0))
169
+ return false;
170
+ for (let i = 1; i < sorted.length; i += 1) {
171
+ const gap = sorted[i] - sorted[i - 1];
172
+ if (gap === 0)
173
+ continue; // a duplicate from the union, not a hole
174
+ if (gap % intervalMs !== 0)
175
+ return false;
176
+ }
177
+ return true;
178
+ }
179
+ /**
180
+ * Source bars inside the visible window — the input the bar-density chooser needs,
181
+ * and the reason it can be exact rather than estimated.
182
+ *
183
+ * Binary search on the key column, which is sorted; an O(n) scan here would run on
184
+ * every resize of a 250k-row intraday series. `null`/absent view ⇒ everything,
185
+ * which is what an unfitted chart shows.
186
+ */
187
+ function barsInView(series, view) {
188
+ const n = series.length;
189
+ if (!view || n === 0)
190
+ return n;
191
+ const key = series.keyColumn();
192
+ // First index at or after `t`.
193
+ const lowerBound = (t) => {
194
+ let lo = 0;
195
+ let hi = n;
196
+ while (lo < hi) {
197
+ const mid = (lo + hi) >>> 1;
198
+ if ((key.at(mid) ?? Infinity) < t)
199
+ lo = mid + 1;
200
+ else
201
+ hi = mid;
202
+ }
203
+ return lo;
204
+ };
205
+ return Math.max(0, lowerBound(view[1] + 1) - lowerBound(view[0]));
206
+ }
207
+ const nativeMsCache = new WeakMap();
208
+ function nativeMs(series) {
209
+ if (nativeMsCache.has(series))
210
+ return nativeMsCache.get(series);
211
+ const key = series.keyColumn();
212
+ // A prefix is enough to find the median interval, and bounds the cost on a
213
+ // 250k-row intraday series.
214
+ const take = Math.min(series.length, 512);
215
+ const times = [];
216
+ for (let i = 0; i < take; i += 1) {
217
+ const t = key.at(i);
218
+ if (t !== undefined)
219
+ times.push(t);
220
+ }
221
+ const ms = inferBarMs(times);
222
+ nativeMsCache.set(series, ms);
223
+ return ms;
224
+ }
225
+ /**
226
+ * Per-bar colours for a study histogram, by the SIGN of each bar.
227
+ *
228
+ * A MACD's histogram is the line minus its signal, so what a reader takes off it
229
+ * is which side of zero it sits on — not whether it rose since the last bar,
230
+ * which is what {@link splitBarColumns} answers for a volume row. Different
231
+ * question, different split.
232
+ *
233
+ * Uses `<BarChart binColors>` rather than splitting the column into two layers:
234
+ * the split-column trick exists because the library's bar layer had one fill per
235
+ * series (F-charts-12), and `binColors` is the fix that shipped for it. One
236
+ * layer, one pass, and the hover readout keeps the bar's own colour.
237
+ * `undefined` falls back to the theme fill, which is what a zero or a gap wants.
238
+ */
239
+ function signColors(series, column, rise, fall) {
240
+ const col = readNumericColumn(series, column);
241
+ const n = col?.length ?? 0;
242
+ const out = new Array(n);
243
+ for (let i = 0; i < n; i += 1) {
244
+ const v = col.read(i);
245
+ if (v == null || !Number.isFinite(v) || v === 0)
246
+ continue; // theme fill
247
+ out[i] = v > 0 ? rise : fall;
248
+ }
249
+ return out;
250
+ }
251
+ const rowAxis = sharedAxisId;
252
+ /**
253
+ * Split an aggregated bar column into `<col>__up` / `<col>__dn` halves by each
254
+ * window's **direction**, so a rise/fall bar draws as two single-series layers
255
+ * (the library's bar layer has one fill per series — F-charts-12; the stacked
256
+ * path would cost the crosshair readout). Exactly one half carries each bar, so
257
+ * the pixels match a per-bar-colored single layer.
258
+ *
259
+ * Direction: an OHLC source uses the window's own `close >= open` (matching the
260
+ * candle convention) from an {@link ohlcWindow} roll-up over the SAME bucket
261
+ * grid as the aggregate — **every** window, `'1d'` included. `sessions` must be
262
+ * the same grid the aggregate used, or the two fall out of alignment silently.
263
+ * Never index the raw source rows: the aggregate emits a bucket per window (empty
264
+ * weekends included), so on trading-day data raw-row indexes drift by two per
265
+ * weekend and the colors go wrong (caught in the PR #117 review). Two aggregates
266
+ * over one grid are index-aligned by construction. A non-OHLC source rises when the value
267
+ * is ≥ the previous window's (first bar reads as a rise).
268
+ *
269
+ * Exported for tests (the weekend-gap regression); not part of the public API.
270
+ */
271
+ export function splitBarColumns(agg, col, src, hasOhlc, window, sessions) {
272
+ // Columnar reads throughout (`series.column(name)`) rather than `toObjects()` —
273
+ // no object per bar just to look at one or two fields (pond 0.52's "columns, not
274
+ // events" guidance, applied to our own fold).
275
+ const source = readNumericColumn(agg, col);
276
+ const n = source?.length ?? 0;
277
+ const vals = new Array(n);
278
+ for (let i = 0; i < n; i += 1) {
279
+ const v = source.read(i);
280
+ if (v != null && Number.isFinite(v))
281
+ vals[i] = v;
282
+ }
283
+ let rising;
284
+ if (hasOhlc) {
285
+ const oc = ohlcWindow(src, window, sessions);
286
+ const open = readNumericColumn(oc, 'open');
287
+ const close = readNumericColumn(oc, 'close');
288
+ rising = (i) => {
289
+ const o = open?.read(i);
290
+ const c = close?.read(i);
291
+ // An empty bucket (weekend/holiday window) has no open/close — its bar
292
+ // value is 0/absent anyway, so the defaulted direction never draws.
293
+ return o != null && c != null ? c >= o : true;
294
+ };
295
+ }
296
+ else {
297
+ // Last defined value wins as "previous", so a gap doesn't flip direction.
298
+ const prev = [];
299
+ let last;
300
+ for (const v of vals) {
301
+ prev.push(last);
302
+ if (v != null)
303
+ last = v;
304
+ }
305
+ rising = (i) => prev[i] == null || (vals[i] ?? 0) >= prev[i];
306
+ }
307
+ const up = vals.map((v, i) => (v != null && rising(i) ? v : undefined));
308
+ const dn = vals.map((v, i) => (v != null && !rising(i) ? v : undefined));
309
+ return agg.withColumn(`${col}__up`, up).withColumn(`${col}__dn`, dn);
310
+ }
311
+ /**
312
+ * The time-series chart: N stacked viewport **rows** sharing one time axis, each
313
+ * row a set of series on its own dual L/R axes. A config names its data `source`
314
+ * (`vol` / `price`, from {@link TimeSeriesChartProps.sources}) and its `column`; rows are
315
+ * viewports, sources a separate axis — so a row can hold any source and a source
316
+ * can appear in any row. Per-series color (and dimming for non-selected series) is
317
+ * baked into a generated `ChartTheme` overlaid on the host-supplied base
318
+ * {@link TimeSeriesChartProps.theme}; the chart itself reads no CSS token.
319
+ *
320
+ * (Historic: every visible series used to draw TWICE when a compare series was
321
+ * supplied — solid primary, dashed counterpart. That blanket render retired
322
+ * 2026-08-18: a comparison is now a PAIR you ask for per metric, so the only
323
+ * dashed lines are compare-bound legs, styled by `settings.comparisons`.)
324
+ * the primary as-is and a **dashed counterpart** (`<id>__cmp`, same color + axis) —
325
+ * texture encodes primary-vs-compare, color encodes the series.
326
+ *
327
+ * Cursor is the crosshair (synced line + per-series dots + on-axis value pills +
328
+ * x-axis time pill); hover values ALSO surface via {@link onTracker} so the legend
329
+ * chips can track the hovered point. Memoized — the caller's hover state re-renders
330
+ * chips, not the canvas (keep prop identities stable).
331
+ */
332
+ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays = EMPTY_DAYS, annotations = EMPTY_ANNOTATIONS, coarseSources = EMPTY_SOURCES, dimmed = [], splitters, onTracker, onStats, pricePill, collapseWeekends, settings = DEFAULT_CHART_SETTINGS, timeZone, theme: base, resolveColor = sameColor, colorScheme = 'dark', viewRange, onViewRangeChange, axisOptions, onAxisClick, onAxisBounds, }) {
333
+ const [ref, width] = useMeasuredWidth();
334
+ // Which y-axis gutter the pointer is over (the hover affordance). Axis
335
+ // chrome is DOM, so this repaints the gutter only — never the canvas.
336
+ const [hoverAxis, setHoverAxis] = useState(null);
337
+ const allConfigs = useMemo(() => rows.flatMap((r) => r.configs), [rows]);
338
+ const ohlc = useMemo(() => new Set(ohlcSources), [ohlcSources]);
339
+ const dimKey = dimmed.join(',');
340
+ // The category styles + split defaults shape the theme too — one compact key
341
+ // for all of it, so a settings change repaints and a hover doesn't.
342
+ const settingsSig = JSON.stringify(settings);
343
+ // Keyed by a signature of the theme-shaping fields (id / color / split mode +
344
+ // pair / style / stroke width) + the dim set + the settings — NOT the rows
345
+ // identity — so a height-only splitter drag doesn't rebuild the theme (or,
346
+ // below, the aggregated series). Effective values (`seriesLineWidth`,
347
+ // `effectiveSplit`), not raw fields, so a change lands even when it moves a
348
+ // series off its default.
349
+ const themeSig = allConfigs
350
+ .map((c) => {
351
+ const sp = effectiveSplit(c, settings);
352
+ return `${c.id}:${c.color}:${sp.mode}:${sp.rise}:${sp.fall}:${c.style}:${seriesLineWidth(c, settings)}`;
353
+ })
354
+ .join('|') +
355
+ '#' +
356
+ dimKey +
357
+ '#' +
358
+ settingsSig;
359
+ // Only the (role, colour) pairs shape the theme, so the signature collapses the
360
+ // many marks of a kind to one entry. Without this the memo would rebuild on
361
+ // every fetch — `annotations` is a fresh array each time and 298 marks long.
362
+ const annotationSig = [...new Set(annotations.map((a) => `${a.role}:${a.color}`))]
363
+ .sort()
364
+ .join('|');
365
+ const theme = useMemo(() => {
366
+ const dim = new Set(dimmed);
367
+ // One entry per series per draw kind — the canvas can't read the host's
368
+ // colour tokens, so each style's color is baked in from the resolved stroke.
369
+ // A series only draws in one style at a time, but seeding every map keeps
370
+ // `as={id}` valid whatever style the config picks.
371
+ const line = { ...base.line };
372
+ const area = { ...base.area };
373
+ const bar = { ...base.bar };
374
+ const candle = { ...base.candle };
375
+ const band = { ...base.band };
376
+ for (const c of allConfigs) {
377
+ const stroke = resolveColor(c.color);
378
+ const isDim = dim.has(c.id);
379
+ const color = isDim ? withAlpha(stroke, 0.22) : stroke;
380
+ const width = seriesLineWidth(c, settings);
381
+ const dash = seriesLineDashArray(c, settings);
382
+ line[c.id] = { color, width, ...(dash ? { dash: [...dash] } : {}) };
383
+ // The comparison counterpart shares the color + axis but takes the
384
+ // `comparisons` category's own weight + texture (dashed by default —
385
+ // texture encodes primary-vs-compare). Dims with its primary.
386
+ line[`${c.id}__cmp`] = {
387
+ color,
388
+ width: settings.comparisons.weight,
389
+ ...(settings.comparisons.dash === 'dashed' ? { dash: [...DASH_PATTERN] } : {}),
390
+ };
391
+ // Area fill wants a solid hex for its gradient, so dim via fillOpacity (not
392
+ // an rgba fill); the outline still carries the dim.
393
+ area[c.id] = {
394
+ ...base.area.default,
395
+ color,
396
+ width,
397
+ fill: stroke,
398
+ fillOpacity: isDim ? 0.04 : 0.14,
399
+ };
400
+ // A band is a WASH, not a fill under a line: it carries no outline of its
401
+ // own (the middle band draws that, as an ordinary line under the same
402
+ // id), so it wants to read as a tinted region and nothing else. 0.16 sits
403
+ // where the earnings band landed — unmistakably a region, still quiet
404
+ // enough that a line crossing it stays the brighter thing.
405
+ band[c.id] = { fill: stroke, opacity: isDim ? 0.04 : 0.16 };
406
+ // A multi-output study's N lines: ONE colour, N textures. A study's
407
+ // outputs are one series (a MACD is one study), so spending N palette
408
+ // colours on them would fight "colour = series" and make three studies
409
+ // look like nine. The first output is the study's own line; each later one
410
+ // takes a longer dash and a hair less weight, so the stack reads as
411
+ // primary-and-derived rather than as peers. Same shape as `__cmp`.
412
+ if (c.style === 'lines' && c.derive) {
413
+ const op = c.derive.op;
414
+ opOutputs(op).forEach((suffix, i) => {
415
+ const key = outputKey(c.id, i);
416
+ if (outputMark(op, suffix) === 'bar') {
417
+ // A histogram in the STUDY's colour, not a rise/fall pair: green and
418
+ // red are reserved for market data (P&L, bid/ask), never for an
419
+ // indicator. The sign is legible from which side of zero the bar
420
+ // sits on, which is the reading anyway.
421
+ bar[key] = { ...base.bar.default, fill: color, highlight: color };
422
+ return;
423
+ }
424
+ line[key] = {
425
+ color,
426
+ width: i === 0 ? width : Math.max(1, width - 0.5),
427
+ ...(i === 0 ? {} : { dash: [...OUTPUT_DASHES[(i - 1) % OUTPUT_DASHES.length]] }),
428
+ };
429
+ });
430
+ }
431
+ // Direction-capable marks: a split bar draws its rise fill under `c.id` and
432
+ // its fall fill under `` `${c.id}__down` `` (the render splits the column in
433
+ // two — the library's bar layer has one fill per series; F-charts-12). A
434
+ // split candle gets a per-id rise/fall pair + `colorBy='direction'`.
435
+ const sp = effectiveSplit(c, settings);
436
+ if (sp.mode === 'split') {
437
+ const rise = resolveColor(sp.rise);
438
+ const fall = resolveColor(sp.fall);
439
+ const riseC = isDim ? withAlpha(rise, 0.22) : rise;
440
+ const fallC = isDim ? withAlpha(fall, 0.22) : fall;
441
+ bar[c.id] = { ...base.bar.default, fill: riseC, highlight: riseC };
442
+ bar[`${c.id}__down`] = { ...base.bar.default, fill: fallC, highlight: fallC };
443
+ if (c.style === 'candle')
444
+ candle[c.id] = candleStyleForPair(riseC, fallC);
445
+ }
446
+ else {
447
+ bar[c.id] = { ...base.bar.default, fill: color, highlight: color };
448
+ // A single-color candle takes the series' one colour (a per-id style) so
449
+ // it doesn't fight the "colour = series" encoding.
450
+ if (c.style === 'candle')
451
+ candle[c.id] = candleStyleForColor(color);
452
+ }
453
+ }
454
+ // The theme is the ONLY styling channel for a mark — `<Marker>` takes no
455
+ // colour prop, deliberately ("colour is a theme concern") — so a user-picked
456
+ // annotation colour reaches the canvas by redefining its ROLE here. Keyed by
457
+ // role, so N marks of one kind cost one entry, and the theme's own per-role
458
+ // `dash` survives: hue is the user's, texture stays ours (it is what tells
459
+ // the two kinds apart).
460
+ const annotation = base.annotation
461
+ ? {
462
+ ...base.annotation,
463
+ roles: annotations.reduce((acc, a) => ({
464
+ ...acc,
465
+ [a.role]: { ...acc?.[a.role], color: resolveColor(a.color) },
466
+ }), base.annotation.roles ?? {}),
467
+ }
468
+ : base.annotation;
469
+ return {
470
+ ...base,
471
+ line: line,
472
+ area: area,
473
+ bar: bar,
474
+ candle: candle,
475
+ band: band,
476
+ annotation,
477
+ };
478
+ // eslint-disable-next-line react-hooks/exhaustive-deps
479
+ }, [base, resolveColor, themeSig, annotationSig]);
480
+ // The trading sessions on this axis, derived from the data rather than from a
481
+ // calendar. ONE session model with TWO consumers — the axis (which collapses
482
+ // everything between sessions) and the roll-up grid below (whose buckets must
483
+ // be those same sessions). When they disagree, a candle's slot covers time the
484
+ // axis has excised: the body stretches across the collapsed seam, and its
485
+ // midpoint — where the crosshair anchors its readout — falls in dead time and
486
+ // clamps onto the session open, so the reticle lands on the candle's edge.
487
+ //
488
+ // The UNION of every series on the axis. Deriving from one source is wrong the
489
+ // moment two symbols are on screen: they do not print in the same minutes
490
+ // (AAPL and SPY differ in ~2,600 minutes over a year), so a minute the primary
491
+ // missed would be excised while the other symbol has a point in it. The axis
492
+ // is shared, so its live spans must be too.
493
+ //
494
+ // `sources` IS that union now: a comparison is no longer a parallel map, it is
495
+ // `cmp_`-prefixed columns joined onto the primary (`@tidal-ts/core`'s
496
+ // `joinUnderPrefix`). One caveat rides along — that join is a left EXACT-KEY
497
+ // join, so a minute only the comparison printed is dropped there, before this
498
+ // ever sees it. Aligned daily grids (a fixture + a daily feed) match exactly;
499
+ // an intraday feed does not, and the fix (gap-cap, then `align` both series to
500
+ // the grain, then join) is stated at the join itself. It lands here too when it
501
+ // does: `align` creates rows, so this union — which is what a SESSION means —
502
+ // must keep coming from real timestamps, not a cadence grid (`TDL-CMPGAP`).
503
+ //
504
+ // Keyed on the sources' identity, so it is rebuilt on a fetch and not on a
505
+ // hover or a splitter drag; the container rebuilds its scale when the
506
+ // discontinuity reference changes, so a stable identity matters.
507
+ // Clipped to the data's own span, exactly like `calendarDays`: a marker outside
508
+ // it says "before this instrument listed", which is not an annotation of
509
+ // anything on screen. Cheap (tens of entries), so it recomputes with the data.
510
+ const shownAnnotations = useMemo(() => {
511
+ if (annotations.length === 0)
512
+ return EMPTY_ANNOTATIONS;
513
+ let lo = Infinity;
514
+ let hi = -Infinity;
515
+ for (const ser of Object.values(sources ?? {})) {
516
+ const key = ser.keyColumn();
517
+ const first = key.at(0);
518
+ const last = key.at(ser.length - 1);
519
+ if (first !== undefined && first < lo)
520
+ lo = first;
521
+ if (last !== undefined && last > hi)
522
+ hi = last;
523
+ }
524
+ if (!Number.isFinite(lo) || !Number.isFinite(hi))
525
+ return EMPTY_ANNOTATIONS;
526
+ return annotations.filter((a) => annotationInView(a, lo, hi));
527
+ }, [annotations, sources]);
528
+ const sessions = useMemo(() => {
529
+ const times = [];
530
+ const collect = (map) => {
531
+ for (const s of Object.values(map ?? {})) {
532
+ // Columnar key read — the raw number, no event materialised
533
+ // (ARCHITECTURE.md).
534
+ const key = s.keyColumn();
535
+ for (let i = 0; i < s.length; i += 1) {
536
+ const t = key.at(i);
537
+ if (t !== undefined)
538
+ times.push(t);
539
+ }
540
+ }
541
+ };
542
+ collect(sources);
543
+ if (times.length < 2)
544
+ return [];
545
+ times.sort((a, b) => a - b);
546
+ // A CALENDAR beats both inference paths at daily grain: it can say a session
547
+ // existed that the data has no bar for, which no amount of looking at bars can.
548
+ // Clipped to the data's span — outside it the answer would be "this instrument
549
+ // did not exist yet", which is not a gap.
550
+ const bar0 = inferBarMs(times);
551
+ if (calendarDays.length > 0 && bar0 !== undefined && bar0 >= WINDOW_MS['1d']) {
552
+ const lo = times[0];
553
+ const hi = times[times.length - 1];
554
+ const span = calendarDays.filter((d) => d >= lo && d <= hi);
555
+ if (span.length > 0)
556
+ return exactSessionSegments(span, WINDOW_MS['1d']);
557
+ }
558
+ // Dense data gets EXACT adjacency; only a sparse series needs the threshold.
559
+ //
560
+ // `sessionSegments` compares each gap against the median gap in view, which is
561
+ // right only while the median is representative. Measured on daily bars
562
+ // spanning Thanksgiving 2025: at `1M` and wider the median is 1 day and the
563
+ // holiday collapses correctly, but at `5D` half the gaps are weekends, the
564
+ // median is 2 days, and a 1-day holiday gap stops clearing the 3-day threshold
565
+ // — so 27 November ended up INSIDE a live span and the axis reserved width for
566
+ // a day with no bar. The same closure rendered differently depending on how far
567
+ // you were zoomed out, which is wrong: a market holiday is a property of the
568
+ // market, not of the viewport.
569
+ //
570
+ // Exact adjacency has no median to distort. It needs keys on a regular grid,
571
+ // which both of our shapes satisfy — a trading day either printed or was not a
572
+ // session, and the 1-minute archive is gap-free in session. An off-grid series
573
+ // would find no two bars adjacent, so it keeps the threshold.
574
+ const bar = bar0;
575
+ const onGrid = bar !== undefined && isOnGrid(times, bar);
576
+ return onGrid ? exactSessionSegments(dedupe(times), bar) : sessionSegments(times);
577
+ }, [sources, calendarDays]);
578
+ // Aggregated series behind the binning styles (pond does the windowing). Bars
579
+ // reduce one column into windows; candles roll a source's OHLCV into a coarser
580
+ /**
581
+ * The window a bar series is actually drawn at.
582
+ *
583
+ * `c.window` unset means **Auto**, and Auto is chosen from the pixels: a bar
584
+ * narrower than {@link MIN_BAR_PX} cannot be drawn, and because a rise/fall bar
585
+ * is two layers with fall on top, sub-pixel bars do not merely blur — the upper
586
+ * layer wins every shared pixel column and the chart reports bar density as
587
+ * market direction. AAPL's full history rendered 82% red against 47.5% down days
588
+ * until this existed (`autoBarWindow` carries the measurements).
589
+ *
590
+ * An EXPLICIT window is returned untouched, overdraw and all. The Window control
591
+ * names it, and a control that reads `1D` over a canvas of monthly bars is a
592
+ * worse failure than the one being fixed — so the coarsening only happens in the
593
+ * mode that is honestly labelled "Auto".
594
+ */
595
+ const windowFor = useCallback((c, src) => c.window ??
596
+ autoBarWindow({
597
+ bars: barsInView(src, viewRange),
598
+ nativeMs: nativeMs(src) ?? WINDOW_MS['1d'],
599
+ widthPx: width,
600
+ }), [viewRange, width]);
601
+ // window. Keyed by a signature of the fields that change the data (source /
602
+ // style / window / column / visibility / split mode) — colors/dim only touch
603
+ // the theme, but flipping split on/off changes the derived columns.
604
+ //
605
+ // The window in the signature is the RESOLVED one, not `c.window` — an Auto
606
+ // series' window is a function of the plot width and the view, so keying on the
607
+ // raw field would leave the aggregate stale across a resize. Keying on the
608
+ // resolved value also means a resize that does NOT change the choice (most of
609
+ // them) re-uses the memo instead of re-aggregating every frame of the drag.
610
+ const aggSig = allConfigs
611
+ .map((c) => {
612
+ const src = c.source ? sources[c.source] : undefined;
613
+ const w = src && c.style === 'bar' ? windowFor(c, src) : (c.window ?? '1d');
614
+ return `${c.id}:${c.source ?? ''}:${c.style}:${w}:${c.column}:${seriesDrawn(c)}:${effectiveSplit(c, settings).mode}`;
615
+ })
616
+ .join('|');
617
+ // Buckets follow the SESSIONS for intraday data and the CALENDAR for daily. Not a
618
+ // preference — on daily bars the session segments are whole *weeks* (a weekend gap
619
+ // is the only gap wide enough to split them), so bucketing a `'1d'` window on them
620
+ // would roll five days into one mark.
621
+ const sessionsFor = useCallback((src) => {
622
+ const native = nativeMs(src);
623
+ return native !== undefined && native < WINDOW_MS['1d'] ? sessions : undefined;
624
+ }, [sessions]);
625
+ const derived = useMemo(() => {
626
+ const bar = new Map();
627
+ const candle = new Map();
628
+ for (const c of allConfigs) {
629
+ if (!seriesDrawn(c) || !c.source)
630
+ continue;
631
+ const src = sources[c.source];
632
+ if (!src)
633
+ continue;
634
+ if (c.style === 'bar') {
635
+ const col = c.column;
636
+ const window = windowFor(c, src);
637
+ const grid = sessionsFor(src);
638
+ let agg = aggregateColumn(src, col, window, reducerFor(c), grid);
639
+ // A split bar needs per-bar direction the library's bar layer can't paint
640
+ // (one fill per series; F-charts-12) — split the column into `__up`/`__dn`
641
+ // halves and draw them as two layers. Same grid, or the halves misalign.
642
+ if (effectiveSplit(c, settings).mode === 'split')
643
+ agg = splitBarColumns(agg, col, src, ohlc.has(c.source), window, grid);
644
+ bar.set(c.id, agg);
645
+ }
646
+ // A candle at the data's NATIVE interval feeds the raw point-keyed series
647
+ // straight to <Candlestick> (neighbour-derived slot); anything coarser needs
648
+ // an OHLC roll-up, and only a source that actually carries OHLC can candle.
649
+ //
650
+ // The comparison is against the data, not against the token `'1d'`. That
651
+ // shortcut held while every source was daily and silently broke on intraday:
652
+ // a "1 day" candle over 1-minute bars drew one candle per MINUTE, because
653
+ // `'1d'` was read as "native" rather than as a day.
654
+ if (c.style === 'candle' && ohlc.has(c.source)) {
655
+ const window = c.window ?? '1d';
656
+ const native = nativeMs(src);
657
+ // 1.5× so a jittery interval does not roll a series up against itself.
658
+ if (native === undefined || WINDOW_MS[window] > native * 1.5)
659
+ candle.set(c.id, ohlcWindow(src, window, sessionsFor(src)));
660
+ }
661
+ }
662
+ return { bar, candle };
663
+ // eslint-disable-next-line react-hooks/exhaustive-deps
664
+ }, [sources, ohlc, sessionsFor, aggSig]);
665
+ // A line through `close` belongs at the bar's END, not its start.
666
+ //
667
+ // The archive stamps a bar by its OPEN — the row stamped 13:30 covers 13:30–13:31
668
+ // — so its close is the price at ~13:31. Plotting that close at 13:30 draws every
669
+ // intraday close one bar early: uniform, invisible mid-series, and exactly
670
+ // visible at a session seam, where the day's last close lands at 21:59 instead of
671
+ // 22:00 and the first close of the next session sits on the open rather than a
672
+ // minute after it.
673
+ //
674
+ // Only the line-ish styles want this. A candle spans `[open, close]` and draws
675
+ // from the open, so the same row wants a different x per style — which is why the
676
+ // shift lives here, per layer, rather than in the fetch.
677
+ //
678
+ // DAILY IS NOT EXEMPT, though I first thought it should be. The objection was
679
+ // that shifting would put Friday's close on Saturday — but a daily stamp is a
680
+ // UTC-midnight **boundary**, not the session it describes, so the shift is what
681
+ // gets the date RIGHT rather than wrong: the bar stamped 27 Apr is Monday's
682
+ // session, and its close plotted at 28 Apr 00:00Z is 27 Apr 20:00 in New York —
683
+ // the correct NY day. Unshifted it sits at 27 Apr 00:00Z, which is *Sunday*
684
+ // evening in New York, a day before the session it reports.
685
+ //
686
+ // Leaving daily out also cost a fifth of every week: the segment runs one bar
687
+ // past its last key, so Fri 00:00Z → Sat 00:00Z was live axis with no line on it.
688
+ const shifted = useMemo(() => {
689
+ const out = new Map();
690
+ for (const [key, src] of Object.entries(sources ?? {})) {
691
+ const native = nativeMs(src);
692
+ if (native === undefined)
693
+ continue;
694
+ out.set(key, shiftKeys(src, native));
695
+ }
696
+ return out;
697
+ }, [sources]);
698
+ // …and where the source carries an OPEN, the line can start at the session open
699
+ // instead of a minute inside it. `sessionOpenLine` emits one column named `close`
700
+ // and `bars + 1` points per session — the opening print, then every close — so
701
+ // the line spans the whole live segment rather than beginning after it.
702
+ //
703
+ // Price only. A vol series has no open to start from, so its line keeps the
704
+ // shifted closes and legitimately begins one bar in.
705
+ const openLine = useMemo(() => {
706
+ const out = new Map();
707
+ for (const key of ohlc) {
708
+ const src = sources?.[key];
709
+ if (!src)
710
+ continue;
711
+ const native = nativeMs(src);
712
+ if (native === undefined)
713
+ continue;
714
+ out.set(key, sessionOpenLine(src, native, { open: 'open', close: 'close' }));
715
+ }
716
+ return out;
717
+ }, [sources, ohlc]);
718
+ // The zoom-in floor in the grain actually on screen (see MIN_VIEW_BARS). Mirrors
719
+ // how `derived` decides what a mark is: a bar always bins to its window, a candle
720
+ // only when the window is coarser than native, everything else draws raw.
721
+ const minDuration = useMemo(() => {
722
+ let finest;
723
+ for (const c of allConfigs) {
724
+ if (!c.visible || !c.source)
725
+ continue;
726
+ const src = sources[c.source];
727
+ if (!src)
728
+ continue;
729
+ const native = nativeMs(src);
730
+ if (native === undefined)
731
+ continue;
732
+ const window = c.window ?? '1d';
733
+ // A binned mark spans its window in LIVE time (`liveWindowMs`); an unbinned
734
+ // one spans its native interval, which is already live — a minute inside a
735
+ // session is a live minute.
736
+ const binned = c.style === 'bar' || (c.style === 'candle' && WINDOW_MS[window] > native * 1.5);
737
+ const mark = binned ? (liveWindowMs(window, sessionsFor(src)) ?? WINDOW_MS[window]) : native;
738
+ if (finest === undefined || mark < finest)
739
+ finest = mark;
740
+ }
741
+ return finest === undefined ? MIN_VIEW_MS : MIN_VIEW_BARS * finest;
742
+ // eslint-disable-next-line react-hooks/exhaustive-deps
743
+ }, [sources, sessionsFor, aggSig]);
744
+ // The trading-time axis, from the sessions above. `weekendSkip()` collapses
745
+ // weekends ONLY, which is adequate for daily bars and badly wrong intraday: a
746
+ // year of 1-minute data carries ~190 overnight gaps of ~8h, so each session
747
+ // occupies about a quarter of its day's width and the chart draws a comb of
748
+ // hairlines. Sessions derived from the data collapse overnight, weekends,
749
+ // holidays and half-days with one rule.
750
+ //
751
+ // Too short to infer a bar interval from ⇒ fall back rather than excise
752
+ // everything.
753
+ /**
754
+ * Whether the bars are **intraday**, which is the only grain a session break
755
+ * means anything at.
756
+ *
757
+ * A break exists to show live time a series could not fill *inside* a session's
758
+ * continuum — an intraday line starts one bar after the open, so the space
759
+ * before its first point is real. At daily grain each point IS a session, so
760
+ * consecutive sessions are contiguous and Friday→Monday is a join, not a jump:
761
+ * the axis has already collapsed the weekend, and breaking the line as well
762
+ * states the same fact twice and reads as missing data.
763
+ *
764
+ * That is what it looked like, too. With the calendar axis feeding
765
+ * `exactSessionSegments`, every weekend is a segment boundary, so a daily vol
766
+ * line came out chopped into five-point weekly fragments — reported as "why does
767
+ * ATM vol have gaps?", and the data has none: every gap in the archive is a real
768
+ * closure (2026-06-19 Juneteenth, 2026-07-03 for July 4th), and `iv21` is
769
+ * non-null throughout.
770
+ */
771
+ const coarse = useMemo(() => new Set(coarseSources), [coarseSources]);
772
+ const intraday = useMemo(() => {
773
+ // A short prefix of ONE source is enough to tell intraday from daily, and
774
+ // avoids a second full walk of what can be 99k points (the sessions memo
775
+ // already does one). `inferBarMs` takes the modal gap, so a handful of bars
776
+ // settles it even if the first pair straddles a seam.
777
+ const first = Object.values(sources ?? {})[0];
778
+ if (!first)
779
+ return false;
780
+ const key = first.keyColumn();
781
+ const probe = [];
782
+ for (let i = 0; i < Math.min(first.length, 64); i += 1) {
783
+ const t = key.at(i);
784
+ if (t !== undefined)
785
+ probe.push(t);
786
+ }
787
+ const bar = probe.length >= 2 ? inferBarMs(probe) : undefined;
788
+ return bar !== undefined && bar < WINDOW_MS['1d'];
789
+ }, [sources]);
790
+ const discontinuities = useMemo(() => !collapseWeekends
791
+ ? undefined
792
+ : sessions.length
793
+ ? segmentDiscontinuity(sessions)
794
+ : WEEKEND_SKIP, [collapseWeekends, sessions]);
795
+ // One series → one or more draw layers, picked by `style`. The compare ticker is
796
+ // always a dashed line whatever the primary style (texture = compare).
797
+ // `candleable` is true only for a source that carries the OHLC a candle needs.
798
+ //
799
+ // Returns a FLAT ARRAY, never a Fragment: `<Layers>` injects each **direct**
800
+ // child's JSX position as its z-index (`cloneElement(child, { index })`), and a
801
+ // Fragment would swallow that prop — leaving every layer at the default index
802
+ // (draw order then followed mount order, so reordering did nothing). Arrays are
803
+ // flattened by `Children.map`, so each layer stays a direct child and keeps its
804
+ // own z slot. Keys are explicit for the same reason.
805
+ const layer = (c, panelSeries, axis, candleable) => {
806
+ const col = c.column;
807
+ // A line/area draws CLOSES, which belong at their bar's end — see `shifted`.
808
+ // For the price column of an OHLC source it can do better still and start at
809
+ // the session's open (`openLine`). Both fall back to the raw series when there
810
+ // is nothing to shift, which is daily data.
811
+ const closeSeries = (c.source && col === 'close' ? openLine.get(c.source) : undefined) ??
812
+ (c.source ? shifted.get(c.source) : undefined) ??
813
+ panelSeries;
814
+ switch (c.style) {
815
+ case 'area':
816
+ return [
817
+ // No `sessionBreaks` on `<AreaChart>` — the prop is LineChart-only, so
818
+ // an area still bridges the seam. Logged as F-charts-20.
819
+ _jsx(AreaChart, { series: closeSeries, column: col, as: c.id, axis: axis }, c.id),
820
+ ];
821
+ case 'bar': {
822
+ const s = derived.bar.get(c.id);
823
+ if (!s)
824
+ return [];
825
+ // A split bar draws its two direction halves as two single-series layers
826
+ // (see splitBarColumns) — the rise under the series' own id, the fall
827
+ // under `<id>__down` (its theme fill; the host normalizes tracker labels).
828
+ return effectiveSplit(c, settings).mode === 'split'
829
+ ? [
830
+ _jsx(BarChart, { series: s, column: `${col}__up`, as: c.id, axis: axis }, c.id),
831
+ _jsx(BarChart, { series: s, column: `${col}__dn`, as: `${c.id}__down`, axis: axis }, `${c.id}__down`),
832
+ ]
833
+ : [_jsx(BarChart, { series: s, column: col, as: c.id, axis: axis }, c.id)];
834
+ }
835
+ case 'candle':
836
+ // Only an OHLC source can candle; elsewhere fall back to a line. A daily
837
+ // candle draws the raw series; a windowed one draws its OHLC roll-up.
838
+ // Split mode paints by direction (the per-id rise/fall pair baked into
839
+ // the theme); single mode takes the series' one colour. Tracker keys on
840
+ // `as`.
841
+ return candleable
842
+ ? [
843
+ _jsx(Candlestick, { series: derived.candle.get(c.id) ?? panelSeries, as: c.id, axis: axis, variant: c.candleVariant ?? 'candle', colorBy: effectiveSplit(c, settings).mode === 'split' ? 'direction' : 'series',
844
+ // The full O/H/L/C quote, so the reticle can snap to a wick
845
+ // extreme instead of riding the close: hover the top of a bar and
846
+ // the axis pill reads that bar's HIGH. Charts leaves this off by
847
+ // default for a compact legend, which is the wrong default for a
848
+ // terminal — the four values ARE the mark. The host folds the
849
+ // four labels back to one chip (`hoverValues`).
850
+ showOHLC: true }, c.id),
851
+ ]
852
+ : [
853
+ _jsx(LineChart, { series: panelSeries, column: col, as: c.id, axis: axis, sessionBreaks: intraday && settings.sessions.breaks && !coarse.has(c.source ?? '') }, c.id),
854
+ ];
855
+ case 'band': {
856
+ // A band is TWO layers for ONE config — the wash between the edges, and
857
+ // the middle band drawn as an ordinary line. Both take `as={c.id}`: the
858
+ // registers are separate maps (`theme.band` vs `theme.line`), so one id
859
+ // styles both halves and they cannot drift apart.
860
+ //
861
+ // The wash goes FIRST so the centre line draws over it — `<Layers>`
862
+ // z-orders by JSX position, and this array is flattened into it.
863
+ //
864
+ // `col` is the SPEC ID here, not a column: a multi-output op names its
865
+ // three columns off it (`bandColumns`). Reading `col` itself would find
866
+ // nothing.
867
+ const b = bandColumns(col);
868
+ return [
869
+ _jsx(BandChart, { series: panelSeries, lower: b.lower, upper: b.upper, as: c.id, axis: axis }, `${c.id}__band`),
870
+ _jsx(LineChart, { series: panelSeries, column: b.middle, as: c.id, axis: axis, sessionBreaks: intraday && settings.sessions.breaks && !coarse.has(c.source ?? '') }, c.id),
871
+ ];
872
+ }
873
+ case 'lines': {
874
+ // N layers for ONE config — one per declared output, each on its own
875
+ // theme key so the textures above apply. `col` is the SPEC ID, so every
876
+ // column is named off it by suffix; reading `col` itself finds nothing,
877
+ // exactly as for a band.
878
+ if (!c.derive)
879
+ return [];
880
+ const op = c.derive.op;
881
+ const histSplit = effectiveSplit(c, settings);
882
+ const layers = opOutputs(op).map((suffix, i) => ({
883
+ mark: outputMark(op, suffix),
884
+ node: outputMark(op, suffix) === 'bar' ? (_jsx(BarChart, { series: panelSeries, column: `${col}${suffix}`, as: outputKey(c.id, i), axis: axis, ...(histSplit.mode === 'split'
885
+ ? {
886
+ binColors: signColors(panelSeries, `${col}${suffix}`, resolveColor(histSplit.rise), resolveColor(histSplit.fall)),
887
+ }
888
+ : {}) }, `${c.id}__o${i}`)) : (_jsx(LineChart, { series: panelSeries, column: `${col}${suffix}`, as: outputKey(c.id, i), axis: axis, sessionBreaks: intraday && settings.sessions.breaks && !coarse.has(c.source ?? '') }, `${c.id}__o${i}`)),
889
+ }));
890
+ // Bars UNDER lines. `<Layers>` z-orders by position, and a MACD's
891
+ // histogram is context for its two lines — drawn over them it would
892
+ // hide the crossing that the histogram exists to mark.
893
+ return [
894
+ ...layers.filter((l) => l.mark === 'bar').map((l) => l.node),
895
+ ...layers.filter((l) => l.mark !== 'bar').map((l) => l.node),
896
+ ];
897
+ }
898
+ default:
899
+ return [
900
+ _jsx(LineChart, { series: closeSeries, column: col, as: c.id, axis: axis, sessionBreaks: intraday && settings.sessions.breaks && !coarse.has(c.source ?? '') }, c.id),
901
+ ];
902
+ }
903
+ };
904
+ // Render a row if it has a visible series — but always keep the first row, so
905
+ // hiding every series in it leaves the chart frame (not an empty container).
906
+ // Splitters index by the *rendered*-row gap (`splitters[i]` below rendered row
907
+ // i). For today's two rows this is exactly the old vol|price behavior.
908
+ // Any change to which gutters exist drops the hover. A gutter removed from
909
+ // under a stationary pointer fires NO mouseout (verified in Chrome), so a
910
+ // swap / preset / row change would otherwise strand an axis in hover ink
911
+ // with the pointer nowhere near it (PR #135 review, LOW). Re-hovering costs
912
+ // one pointer move; a stuck highlight costs trust in the affordance.
913
+ const gutterSig = rows
914
+ .map((r) => `${r.id}:${r.configs.map((c) => `${c.id}${c.axis}${c.axisGroup ?? ''}${seriesDrawn(c) ? '' : 'h'}`).join(',')}`)
915
+ .join('|');
916
+ useEffect(() => setHoverAxis(null), [gutterSig]);
917
+ const renderedRows = rows.filter((r, i) => i === 0 || r.configs.some(seriesDrawn));
918
+ const gapSplitter = renderedRows.length > 1 && !!splitters?.length;
919
+ // The live pill rides the first visible config on its named source (that config
920
+ // decides the row + side). Null when no such series is on the terminal. The
921
+ // config must also CARRY its column — a `—` chip config would anchor the
922
+ // pill to an axis that doesn't render (PR #133 review, LOW).
923
+ const pillCfg = pricePill
924
+ ? allConfigs.find((c) => {
925
+ if (!seriesDrawn(c) || c.source !== pricePill.sourceKey)
926
+ return false;
927
+ const s = sources[c.source];
928
+ const col = c.column;
929
+ return !!s && s.schema.some((sc) => sc.name === col);
930
+ })
931
+ : undefined;
932
+ // Draw stats arrive once per ROW repaint, inside the draw frame — so they land
933
+ // in a ref and are published on a time gate. Doing React state work per frame
934
+ // would make the diagnostics line the most expensive thing on the canvas, and
935
+ // during a pan it fires every frame.
936
+ const drawRef = useRef(new Map());
937
+ const flushedAt = useRef(0);
938
+ const pending = useRef(null);
939
+ const publish = useCallback(() => {
940
+ pending.current = null;
941
+ flushedAt.current = performance.now();
942
+ let points = 0;
943
+ let drawMs = 0;
944
+ for (const row of drawRef.current.values()) {
945
+ points += row.points;
946
+ drawMs += row.drawMs;
947
+ }
948
+ onStats?.({ points, drawMs });
949
+ }, [onStats]);
950
+ const handleDrawStats = useCallback((frame) => {
951
+ let points = 0;
952
+ let drawMs = 0;
953
+ for (const l of frame.layers) {
954
+ // `sourceCount` is undefined for a layer that reports no counts; its
955
+ // `drawMs` still counts, so the cost stays honest even when the point
956
+ // total can't see that layer.
957
+ points += l.sourceCount ?? 0;
958
+ drawMs += l.drawMs;
959
+ }
960
+ drawRef.current.set(frame.rowKey, { points, drawMs });
961
+ // Leading AND trailing edge. Rows repaint independently, so the first frame
962
+ // of a batch is usually the EMPTY row: a leading-only throttle published
963
+ // that zero and then sat on every real number until the next repaint, which
964
+ // on a static chart never comes. Reading `points 0` under a drawn chart was
965
+ // this, not a measurement.
966
+ const wait = STATS_MS - (performance.now() - flushedAt.current);
967
+ if (wait <= 0)
968
+ publish();
969
+ else if (pending.current === null)
970
+ pending.current = setTimeout(publish, wait);
971
+ }, [publish]);
972
+ useEffect(() => {
973
+ // The timer holds a closure over `onStats`; firing it after unmount would
974
+ // call setState on a dead component.
975
+ return () => {
976
+ if (pending.current !== null)
977
+ clearTimeout(pending.current);
978
+ pending.current = null;
979
+ };
980
+ }, []);
981
+ // A removed row never reports again, so its last frame would keep contributing
982
+ // its points and its draw cost to the totals forever. Rows are identified by an
983
+ // opaque key we can't enumerate, so drop the lot whenever the row set changes
984
+ // and let the next repaint refill it — one stale tick is cheaper than a total
985
+ // that counts a row that isn't there.
986
+ useEffect(() => {
987
+ drawRef.current.clear();
988
+ }, [gutterSig]);
989
+ return (_jsx("div", { ref: ref, style: S.wrap, "data-testid": "time-series-chart", children: width > 0 && (_jsxs(ChartContainer, { width: width, theme: theme,
990
+ // THE ZONE. Omitting it means the VIEWER's, which made the axis the one
991
+ // place in Tidal that did not read in UTC — every stamp behind it does
992
+ // (the daily bar's UTC-midnight date, the calendar's open days, the
993
+ // earnings sessions, the aggregate's day/week/month buckets, the range
994
+ // picker). Read from Madrid the axis placed its day boundary two hours
995
+ // from where the bar started. pond's rule for 0.69 is that this and
996
+ // `Sequence.calendar` take the SAME zone or a bucket edge and the tick
997
+ // labelling it are different instants — so they read one constant.
998
+ timeZone: resolveTimeZone(timeZone),
999
+ // Controlled pan/zoom: the view round-trips through the host (range ⇄
1000
+ // onTimeRangeChange), so pill state and persistence stay in sync and a
1001
+ // pill click can reset the viewport (uncontrolled mode ignores later
1002
+ // `range` changes once the user pans). No view ⇒ auto-fit the data.
1003
+ panZoom: true,
1004
+ // …and the y GUTTERS take their own gesture: drag one to PAN that axis
1005
+ // alone, wheel to zoom it (0.64 aligned the drag with the x strip —
1006
+ // before that a drag scaled). Deliberately `'y'` — the x strip would
1007
+ // duplicate the plot's own pan/zoom, and the range pills are the x reset.
1008
+ axisPanZoom: onAxisBounds ? 'y' : 'none', range: viewRange ?? undefined, onTimeRangeChange: onViewRangeChange, minDuration: minDuration, cursor: "crosshair", onTrackerChanged: onTracker,
1009
+ // Omitting it makes charts skip per-layer timing entirely, so an app that
1010
+ // doesn't show the diagnostics line pays nothing for them.
1011
+ onDrawStats: onStats ? handleDrawStats : undefined, discontinuities: discontinuities, sessionDividers: settings.sessions.dividers, rowGap: gapSplitter ? 0 : 8, showAxis: false, children: [renderedRows.map((row, i) => {
1012
+ const visible = row.configs.filter(seriesDrawn);
1013
+ // Visible AND its column actually folded — the drawable set. A `—`
1014
+ // chip config (a skipped derived spec) is visible but carries no
1015
+ // column: it draws nothing, and it must not mount an EMPTY own
1016
+ // axis (charts' [0,1] fallback gutter) either (PR #133 review).
1017
+ //
1018
+ // `configColumns`, exactly as the layer guard below does: a BAND's
1019
+ // `column` is a spec id naming three columns and is in no schema, so
1020
+ // testing it directly kept every band OUT of `drawable` — and
1021
+ // `drawable` is what the axes are built from. The band's layers then
1022
+ // named a `<YAxis>` that was never mounted (visible the moment the
1023
+ // band is unlinked onto its own axis, or its parent metric hidden),
1024
+ // and the band was silently absent from the axis-colour vote.
1025
+ const drawable = visible.filter((c) => {
1026
+ const s = c.source ? sources[c.source] : undefined;
1027
+ if (!s)
1028
+ return false;
1029
+ return configColumns(c).every((col) => s.schema.some((sc) => sc.name === col));
1030
+ });
1031
+ // The axes a side carries: its SHARED axis (when any drawable linked
1032
+ // config sits there) plus one OWN axis per unlinked config — pond
1033
+ // stacks same-side axes natively. No axis label — the legend
1034
+ // carries series identity + units; a side with nothing on it
1035
+ // renders no gutter at all. The colour rule: a single-member axis
1036
+ // takes its series' colour (shared-with-one included), a truly
1037
+ // shared axis stays neutral. A click anywhere on a gutter reports
1038
+ // row + side (+ the exact axis) for the anchored axis panel.
1039
+ const axesFor = (side) => {
1040
+ const sideCfgs = drawable.filter((c) => side === 'R' ? c.axis === 'R' : c.axis !== 'R');
1041
+ const shared = sideCfgs.filter((c) => !c.axisGroup);
1042
+ // Non-shared axes GROUPED by key, in first-appearance order —
1043
+ // members naming the same group share one scale.
1044
+ const grouped = new Map();
1045
+ for (const c of sideCfgs)
1046
+ if (c.axisGroup)
1047
+ grouped.set(c.axisGroup, [...(grouped.get(c.axisGroup) ?? []), c]);
1048
+ // One handler per axis: a click opens the panel; enter/leave
1049
+ // drive the hover affordance (the gutter is clickable, and
1050
+ // nothing else says so). `cursor` can't be set on the axis, so
1051
+ // hover speaks through the one presentation channel `<YAxis>`
1052
+ // has — its `color`, lifted toward the text colour (brighter in
1053
+ // dark, darker in light — the tokens already invert).
1054
+ const mouse = onAxisClick
1055
+ ? (axisId) => (e) => {
1056
+ if (e.event.type === 'click')
1057
+ onAxisClick({
1058
+ rowId: row.id,
1059
+ side,
1060
+ axisId,
1061
+ clientX: e.event.clientX,
1062
+ clientY: e.event.clientY,
1063
+ detail: e.event.detail,
1064
+ });
1065
+ else if (e.event.type === 'mouseenter')
1066
+ setHoverAxis(axisId);
1067
+ else if (e.event.type === 'mouseleave')
1068
+ setHoverAxis((cur) => (cur === axisId ? null : cur));
1069
+ }
1070
+ : () => undefined;
1071
+ const axis = (id, cfgs) => {
1072
+ // An axis takes its members' colour when they AGREE on one —
1073
+ // not just when there is exactly one of them. Two legs of a
1074
+ // pair, or a metric and its study, are one reading in one ink,
1075
+ // and the scale they share should say so; a genuinely MIXED
1076
+ // axis stays neutral, because no single colour is true of it
1077
+ // (Peter, 2026-08-18).
1078
+ const only = new Set(cfgs.map((c) => c.color));
1079
+ const own = only.size === 1 ? resolveColor(cfgs[0].color) : null;
1080
+ return (_jsx(YAxis, { id: id, side: side === 'R' ? 'right' : 'left', label: "",
1081
+ // The unit decides the shape, the axis's precision decides
1082
+ // the decimals (`axisFormat`); absent, every unit formats
1083
+ // exactly as it always did.
1084
+ format: axisFormat(cfgs[0].unit, axisOptions?.[id]?.precision), scale: axisOptions?.[id]?.scaleType ?? 'linear', color: hoverAxis === id
1085
+ ? hoverInk(own ?? base.axis.label, colorScheme)
1086
+ : (own ?? undefined),
1087
+ // Each bound resolves on its own (a hard lock, else a manual
1088
+ // pin, else the library's fit — `effectiveAxisBounds`), so a
1089
+ // bar axis can run a nailed-down `0` floor under a free,
1090
+ // auto-fitting top. An omitted bound is the auto one.
1091
+ min: axisOptions?.[id]?.min, max: axisOptions?.[id]?.max, onMouseEvent: mouse(id), onBoundsChange: onAxisBounds ? (bounds) => onAxisBounds(id, bounds) : undefined }, id));
1092
+ };
1093
+ return [
1094
+ ...(shared.length > 0 ? [axis(rowAxis(row.id, side), shared)] : []),
1095
+ ...[...grouped].map(([g, cfgs]) => axis(seriesAxisId(row.id, side, g), cfgs)),
1096
+ ];
1097
+ };
1098
+ const showPill = !!pillCfg && row.configs.some((c) => c.id === pillCfg.id);
1099
+ return (_jsxs(Fragment, { children: [_jsxs(ChartRow, { height: row.height, children: [axesFor('L'), _jsxs(Layers, { children: [shownAnnotations.map((a) => a.band ? (_jsx(Region, { id: `${a.id}:band`, from: a.band[0], to: a.band[1],
1100
+ // No chip from the band — the marker inside it carries
1101
+ // the label, and the region's auto-label would print a
1102
+ // raw date range beside it.
1103
+ label: false,
1104
+ // Fill only: side rules at both edges would put three
1105
+ // verticals where the point is one.
1106
+ edges: false, role: a.role, selectable: false }, `${a.id}:band`)) : null), shownAnnotations.map((a) => (_jsx(Marker, { id: a.id, at: a.at,
1107
+ // No chips, for either kind (Peter, 2026-08-24): a shaded
1108
+ // day-band and a dashed rule are each distinct enough to
1109
+ // read unaided, and the captions were the whole of the
1110
+ // density problem — 16 across the top at 1Y, two of them
1111
+ // behind our own legend. `false` (not omitted) is required:
1112
+ // omitting it auto-labels with the axis formatter.
1113
+ label: false, role: a.role, selectable: false }, a.id))), [...visible].reverse().flatMap((c) => {
1114
+ const src = c.source ? sources[c.source] : undefined;
1115
+ // Column-level "show only what the data carries": a config
1116
+ // whose column is absent from its (folded) series draws
1117
+ // nothing rather than crashing pond's layer — the render
1118
+ // half of `applyDerived`'s skip contract. First earned by
1119
+ // cross-entity pairs: `ratio(iv21,cmp_iv21)` can't fold on
1120
+ // the COMPARE series (no cmp_ columns there), so only its
1121
+ // dashed counterpart must drop; and with compare off the
1122
+ // primary fold skips too, so the spread gaps gracefully.
1123
+ //
1124
+ // Asked of `configColumns`, not of `c.column`: a BAND's
1125
+ // `column` is a spec id naming three columns and is not
1126
+ // itself in any schema, so testing it directly dropped
1127
+ // every band before it could draw — the layer built fine
1128
+ // and was never reached.
1129
+ const cols = configColumns(c);
1130
+ const carries = (s) => !!s && cols.every((col) => s.schema.some((sc) => sc.name === col));
1131
+ if (!carries(src))
1132
+ return [];
1133
+ // A PAIR states its own symbols, one per leg, so the
1134
+ // blanket counterpart is not "the same thing on the other
1135
+ // ticker" — it is a DIFFERENT pair, which the grammar says
1136
+ // to ask for as one. Same for a study built on a spread
1137
+ // (Peter, 2026-08-18). This is the first bite out of the
1138
+ // blanket `__cmp` render; the rest goes with the leg group.
1139
+ // No blanket counterpart for a PAIR — joined (the spec
1140
+ // is a pair op) or split (a leg group member). A pair
1141
+ // names a symbol per leg either way, so a dashed twin is
1142
+ // a different pair, not the same thing on another ticker.
1143
+ // Gating both keeps fn() honest: `None` draws TWO lines,
1144
+ // not four (Peter, 2026-08-18).
1145
+ return layer(c, src, configAxisId(row.id, c), !!c.source && ohlc.has(c.source));
1146
+ }), showPill && pricePill && (_jsx(YAxisIndicator, { source: pricePill.source, axis: configAxisId(row.id, pillCfg), color: resolveColor(pricePill.color), format: (v) => `$${v.toFixed(2)}`, line: true }))] }), axesFor('R')] }), i < renderedRows.length - 1 && splitters?.[i]] }, row.id));
1147
+ }), _jsx(TimeAxis, { dateStyle: "flat", align: "right" })] })) }));
1148
+ }
1149
+ /** Memoized export — hover state in the terminal re-renders the chips, not the
1150
+ * canvas. */
1151
+ export const TimeSeriesChart = memo(TimeSeriesChartInner);
1152
+ const S = {
1153
+ wrap: { width: '100%', minHeight: 1 },
1154
+ };