@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Peter Murphy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,308 @@
1
+ import { type ReactNode } from 'react';
2
+ import type { ChartSeries } from './types.js';
3
+ import type { ChartTheme, LiveValue, TrackerInfo } from '@pond-ts/charts';
4
+ import { aggregateColumn, type Segment } from '@tidal-ts/core';
5
+ import { type ChartSettings } from './chartSettings.js';
6
+ import { type SeriesAxis, type SeriesConfig } from './series.js';
7
+ /** One time marker. */
8
+ export interface ChartAnnotation {
9
+ id: string;
10
+ /** Epoch ms on the time axis. */
11
+ at: number;
12
+ /**
13
+ * Which theme annotation role this mark draws in. The charts library takes no
14
+ * per-mark colour prop ("colour is a theme concern"), so a user-chosen colour
15
+ * reaches the canvas by this role being redefined — see {@link ChartAnnotation.color}.
16
+ */
17
+ role: string;
18
+ /**
19
+ * The mark's colour — a palette key (`'amber'`) or raw CSS.
20
+ *
21
+ * Stated per mark and folded into the theme's `annotation.roles` by role, rather
22
+ * than passed to `<Marker>`, because the library has no colour prop. Marks
23
+ * sharing a role must therefore agree on a colour; the last one wins, which is
24
+ * exactly right when the colour is a property of the *kind*.
25
+ */
26
+ color: string;
27
+ /**
28
+ * `[from, to]` in axis units — draws a **shaded band** behind the line, so the
29
+ * mark reads as a property of a *span* rather than an instant.
30
+ *
31
+ * Earnings use it: an announcement belongs to a session, not to a moment inside
32
+ * one, and a bare vertical rule reads as the latter. The band is inert and
33
+ * edgeless (fill only, no side rules) and sits at the back of the depth ramp, so
34
+ * it tints under the data instead of competing with it. Absent ⇒ line only,
35
+ * which is what expirations want — an expiry really is a boundary.
36
+ */
37
+ band?: readonly [number, number];
38
+ }
39
+ /**
40
+ * Is this mark within the data's span?
41
+ *
42
+ * Clips on the mark's **own extent**, not on its line position — which is the bug
43
+ * this exists to prevent. A session-spanning annotation puts its line through the
44
+ * middle of the day (`at + 12h`), so at daily grain, where the last bar's key IS a
45
+ * UTC midnight, an event on the last in-view session sat half a day past the upper
46
+ * bound and the whole mark — band included — was filtered out. That silently
47
+ * dropped the MOST RECENT earnings, the one most worth seeing.
48
+ *
49
+ * The test is **overlap, not containment**: a band straddling either edge is still
50
+ * partly on screen, and should draw the part that is.
51
+ *
52
+ * Exported for its own test. Nothing about the failure is visible in a screenshot —
53
+ * a dropped annotation looks exactly like a quarter with no earnings.
54
+ */
55
+ export declare function annotationInView(a: ChartAnnotation, lo: number, hi: number): boolean;
56
+ /** What the status line reports about the draw. */
57
+ export interface ChartStats {
58
+ /** Points handed to the layers, summed over every layer on screen — the count
59
+ * BEFORE decimation, because decimation is a display mechanism: at a given
60
+ * view we are showing this much data whether or not the renderer chose to
61
+ * stroke every one of them. Charts reports it per layer as `sourceCount`.
62
+ *
63
+ * A layer is the unit, which settles the counting question both ways: a candle
64
+ * reads four columns and draws one mark per bar, so it counts once; two series
65
+ * drawn separately are two layers, so they count twice — including a split
66
+ * bar's rise/fall halves, which really are two draws. */
67
+ points: number;
68
+ /** Wall-clock ms in the layers' `draw` for the most recent repaint, summed
69
+ * across every row that painted. This is the CHART's cost — distinct from the
70
+ * socket readiness figure the status line used to label "render". */
71
+ drawMs: number;
72
+ }
73
+ /** A viewport row as the chart renders it: its **resolved px** `height` and the
74
+ * series configured in it. Structurally matches the app's machine `RowState`
75
+ * (which holds the *committed* height, `0` ⇒ remainder) — the host resolves the
76
+ * remainder math + drag into pixels and hands those over. */
77
+ export interface TimeSeriesChartRow {
78
+ id: string;
79
+ height: number;
80
+ configs: SeriesConfig[];
81
+ }
82
+ export interface TimeSeriesChartProps {
83
+ /** The stacked rows (top → bottom), each with a resolved px `height` + configs.
84
+ * Every config reads `sources[config.source]`, column `config.column`. */
85
+ rows: readonly TimeSeriesChartRow[];
86
+ /** Keyed time-series data — `{ vol, price }` today. A config's `source` selects
87
+ * its series here; a config whose source is absent is skipped (the render-side
88
+ * half of "show only what the data carries"). */
89
+ sources: Record<string, ChartSeries>;
90
+ /** Source keys whose series carry OHLC (candle-capable). A `candle` config on a
91
+ * non-OHLC source falls back to a line. Default: none. */
92
+ ohlcSources?: readonly string[];
93
+ /**
94
+ * The market's trading days (UTC-midnight instants) — the axis's session model at
95
+ * **daily** grain when supplied.
96
+ *
97
+ * Preferred over inferring from the bars because a session is a fact about the
98
+ * market, not about which symbols happen to be loaded: two compared symbols get
99
+ * one grid, and a session the data is MISSING stays visible instead of being
100
+ * collapsed as though the market had been shut. Clipped to the data's own span, so
101
+ * the days before an instrument listed are not drawn as gaps.
102
+ *
103
+ * Omitted or empty ⇒ infer from the bars, which is correct for dense data.
104
+ */
105
+ calendarDays?: readonly number[];
106
+ /**
107
+ * Time **markers** — earnings, expirations. Not series: they claim no axis, they
108
+ * carry no value, and nothing scales them.
109
+ *
110
+ * Drawn on every rendered row (a date is a date, whichever panel you read it
111
+ * against) but **labelled only on the first**, so the chip appears once above a
112
+ * line that runs the full height. Inert by construction — `selectable: false` —
113
+ * because these are context, not something the user placed and can drag.
114
+ *
115
+ * Colour comes from the theme's annotation `role`, never from a prop: two marker
116
+ * kinds on one canvas have to be distinguishable, and that is a palette decision
117
+ * (`theme.annotation.roles`), not a per-call one.
118
+ */
119
+ annotations?: readonly ChartAnnotation[];
120
+ /**
121
+ * Source keys whose data is **coarser than the axis** — a daily vol curve held
122
+ * across an intraday grid (`holdVolAcrossGrid`).
123
+ *
124
+ * These opt out of session breaks. A break marks live time a series could not
125
+ * fill *within its own cadence*; a daily observation has no intraday cadence to
126
+ * fail at, so breaking it at every overnight gap chops one flat daily level into
127
+ * a separate 3px dash per session — 250 of them across a year, which reads as
128
+ * scattered noise rather than as a step function.
129
+ *
130
+ * Cannot be inferred here: the held series is re-keyed onto the fine grid, so its
131
+ * KEYS are minutes and only its values are daily. The service knows, because it
132
+ * did the fallback (the daily history's vol grain).
133
+ */
134
+ coarseSources?: readonly string[];
135
+ /** Series ids to de-emphasize (drawn with reduced alpha) — the chart's "dim the
136
+ * others" for the selected series. */
137
+ dimmed?: readonly string[];
138
+ /** Draggable dividers, one per gap between *rendered* rows (`splitters[i]` sits
139
+ * below the i-th rendered row). The caller owns them + drives the heights from
140
+ * them. When any is present the row gap collapses to 0 so the splitter itself
141
+ * is the gutter. */
142
+ splitters?: readonly ReactNode[];
143
+ /** Hover readout: fires with the cursor time + every series' value there
144
+ * (`TrackerSample.label` = the series id / `<id>__cmp`), and `null` on leave —
145
+ * the caller renders the readout (chip values) outside the chart. */
146
+ onTracker?: (info: TrackerInfo | null) => void;
147
+ /** Draw diagnostics for the status line: how many points are on screen and what
148
+ * the last repaint cost. Coalesced — see `onDrawStats` in the render. */
149
+ onStats?: (stats: ChartStats) => void;
150
+ /** The live value pill (ChartIQ-style): pinned to the axis edge of the source
151
+ * it names (`sourceKey`), on the side of that source's first visible config.
152
+ * `source` is a stable `LiveValue` (see `createLiveValue`) — ticks repaint ONLY
153
+ * the pill, never the chart. `color` is a palette key or raw CSS color. */
154
+ pricePill?: {
155
+ source: LiveValue;
156
+ color: string;
157
+ sourceKey: string;
158
+ } | null;
159
+ /** When true, the shared time axis collapses closed-market gaps (weekends) so
160
+ * bars sit contiguous and ticks stay calendar-aware. Off for the mock fixture,
161
+ * whose bars walk every calendar day and would otherwise clamp onto the removed
162
+ * weekends. Named for the behavior, not the data: the caller maps its
163
+ * data-nature flag to this. */
164
+ collapseWeekends?: boolean;
165
+ /** App-wide presentation defaults (category line weights/dash, bar/candle
166
+ * split colors). Defaults to the shipped {@link DEFAULT_CHART_SETTINGS}. */
167
+ settings?: ChartSettings;
168
+ /**
169
+ * The DISPLAY zone the axis reads in — an IANA id, or `'local'`.
170
+ *
171
+ * Visual only: it never re-buckets anything, which is the split
172
+ * `DATA_TIME_ZONE` documents. It applies at EVERY grain, daily included —
173
+ * measured, because the opposite looked true on paper. A daily stamp is UTC
174
+ * midnight for its trading date, and that instant formatted in New York is
175
+ * the PREVIOUS day, so the axis "should" shift. It does not: the chart runs
176
+ * on a trading-time scale (`discontinuities`) which places a bar by its
177
+ * SESSION, so the date survives the zone. Confirmed by a side-by-side render
178
+ * — identical tick labels in UTC and `America/New_York`.
179
+ */
180
+ timeZone?: string;
181
+ /**
182
+ * The **base** canvas theme — axes, grid, font, cursor, the annotation
183
+ * register, the default marks. The chart overlays one entry per series on top
184
+ * of it (colour, weight, dash, dimming) and never reads a CSS token itself, so
185
+ * the host owns the token vocabulary and the dark/light switch: pass a new
186
+ * object and the canvas repaints. Tidal's host reads it off the `--td-*`
187
+ * tokens with `useTidalChartTheme`; another host builds it however it likes
188
+ * (`@pond-ts/charts`' `cssVarTheme`, or a literal).
189
+ */
190
+ theme: ChartTheme;
191
+ /**
192
+ * Maps a config's `color` (and a split's `riseColor` / `fallColor`, an
193
+ * annotation's `color`, the price pill's) to a **concrete canvas colour**.
194
+ * Tidal's configs carry curated palette KEYS (`'blue'`) that resolve off CSS
195
+ * tokens, so its host passes `resolveSeriesStroke`; a host whose configs
196
+ * already carry CSS colours needs nothing — the default is the identity.
197
+ * Keep the identity stable (module-level or memoised): it keys the theme memo.
198
+ */
199
+ resolveColor?: (color: string) => string;
200
+ /**
201
+ * Which way a hovered axis's ink lifts: toward white on a dark surface, toward
202
+ * black on a light one. The one presentation fact the theme object does not
203
+ * carry. Default `'dark'`.
204
+ */
205
+ colorScheme?: 'dark' | 'light';
206
+ /** The controlled visible time window `[from, to]` (epoch ms) — pass to show a
207
+ * panned/zoomed/custom viewport; null/omitted fits the data. Wire together
208
+ * with {@link onViewRangeChange} (pan + wheel-zoom round-trip through the
209
+ * host, so pill state / persistence can react). */
210
+ viewRange?: readonly [number, number] | null;
211
+ /** Fires on every pan/zoom step with the new window. Wiring it makes the
212
+ * view CONTROLLED (the library keys controlled-ness on this callback);
213
+ * omitting it falls back to the library's uncontrolled internal view, which
214
+ * external `range` changes can then no longer reset. */
215
+ onViewRangeChange?: (view: [number, number]) => void;
216
+ /** Per-axis presentation, keyed by axis id (`configAxisId`/`sharedAxisId`) —
217
+ * what the host has resolved out of the machine's lock / mode / memory /
218
+ * unit model, plus the axis's own format and scale.
219
+ *
220
+ * Each BOUND is independent: present ⇒ that edge is fixed, absent ⇒ it
221
+ * auto-fits, so `{ min: 0 }` is a hard floor under a free top. Axes with
222
+ * nothing to say are omitted. */
223
+ axisOptions?: Record<string, {
224
+ min?: number;
225
+ max?: number;
226
+ /** Decimal places for the tick labels; absent keeps the unit's default. */
227
+ precision?: number;
228
+ /** `log` never arrives with a `0` bound — the host refuses that pairing. */
229
+ scaleType?: 'linear' | 'log';
230
+ }>;
231
+ /**
232
+ * A y GUTTER GESTURE that moved an axis (`<YAxis onBoundsChange>`): the bounds
233
+ * the gesture reached, or `null` when it releases the axis back to auto-fit.
234
+ *
235
+ * Which gesture does what is pond's, and it CHANGED in charts 0.64.0: a drag
236
+ * used to scale the axis; it now **pans** it, and the **wheel** zooms it —
237
+ * matching the x strip (drag pans, wheel zooms). Both still report through
238
+ * here, so nothing in this seam or the host's model changed; only what the
239
+ * hand does. Don't re-document the gesture in terms of scaling.
240
+ *
241
+ * Providing it makes those axes **controlled** — the gesture only reports, and
242
+ * what draws is whatever comes back through `axisOptions`. That is exactly the
243
+ * shape the host already keeps, so a drag and the axis panel's padlock write
244
+ * the same manual pin and can never disagree about which axis is manual.
245
+ */
246
+ onAxisBounds?: (axisId: string, bounds: readonly [number, number] | null) => void;
247
+ /** A CLICK on a y-axis gutter (pond 0.61 `onMouseEvent`), with the row/side
248
+ * it landed on and the viewport point — the axis panel's anchor. Row + side
249
+ * are passed apart because axis ids embed config ids (engine specIds with
250
+ * `:`/parens) and cannot be parsed back. */
251
+ onAxisClick?: (hit: {
252
+ rowId: string;
253
+ side: SeriesAxis;
254
+ axisId: string;
255
+ clientX: number;
256
+ clientY: number;
257
+ /** The native click COUNT — 1 for a single click, 2 for the second click of
258
+ * a double click. Passed on because a double click on the gutter is pond's
259
+ * reset-to-auto gesture, and the host must not treat it as two opens. */
260
+ detail: number;
261
+ }) => void;
262
+ }
263
+ /**
264
+ * Split an aggregated bar column into `<col>__up` / `<col>__dn` halves by each
265
+ * window's **direction**, so a rise/fall bar draws as two single-series layers
266
+ * (the library's bar layer has one fill per series — F-charts-12; the stacked
267
+ * path would cost the crosshair readout). Exactly one half carries each bar, so
268
+ * the pixels match a per-bar-colored single layer.
269
+ *
270
+ * Direction: an OHLC source uses the window's own `close >= open` (matching the
271
+ * candle convention) from an {@link ohlcWindow} roll-up over the SAME bucket
272
+ * grid as the aggregate — **every** window, `'1d'` included. `sessions` must be
273
+ * the same grid the aggregate used, or the two fall out of alignment silently.
274
+ * Never index the raw source rows: the aggregate emits a bucket per window (empty
275
+ * weekends included), so on trading-day data raw-row indexes drift by two per
276
+ * weekend and the colors go wrong (caught in the PR #117 review). Two aggregates
277
+ * over one grid are index-aligned by construction. A non-OHLC source rises when the value
278
+ * is ≥ the previous window's (first bar reads as a rise).
279
+ *
280
+ * Exported for tests (the weekend-gap regression); not part of the public API.
281
+ */
282
+ export declare function splitBarColumns(agg: ChartSeries, col: string, src: ChartSeries, hasOhlc: boolean, window: Parameters<typeof aggregateColumn>[2], sessions?: readonly Segment[]): ChartSeries;
283
+ /**
284
+ * The time-series chart: N stacked viewport **rows** sharing one time axis, each
285
+ * row a set of series on its own dual L/R axes. A config names its data `source`
286
+ * (`vol` / `price`, from {@link TimeSeriesChartProps.sources}) and its `column`; rows are
287
+ * viewports, sources a separate axis — so a row can hold any source and a source
288
+ * can appear in any row. Per-series color (and dimming for non-selected series) is
289
+ * baked into a generated `ChartTheme` overlaid on the host-supplied base
290
+ * {@link TimeSeriesChartProps.theme}; the chart itself reads no CSS token.
291
+ *
292
+ * (Historic: every visible series used to draw TWICE when a compare series was
293
+ * supplied — solid primary, dashed counterpart. That blanket render retired
294
+ * 2026-08-18: a comparison is now a PAIR you ask for per metric, so the only
295
+ * dashed lines are compare-bound legs, styled by `settings.comparisons`.)
296
+ * the primary as-is and a **dashed counterpart** (`<id>__cmp`, same color + axis) —
297
+ * texture encodes primary-vs-compare, color encodes the series.
298
+ *
299
+ * Cursor is the crosshair (synced line + per-series dots + on-axis value pills +
300
+ * x-axis time pill); hover values ALSO surface via {@link onTracker} so the legend
301
+ * chips can track the hovered point. Memoized — the caller's hover state re-renders
302
+ * chips, not the canvas (keep prop identities stable).
303
+ */
304
+ declare function TimeSeriesChartInner({ rows, sources, ohlcSources, calendarDays, annotations, coarseSources, dimmed, splitters, onTracker, onStats, pricePill, collapseWeekends, settings, timeZone, theme: base, resolveColor, colorScheme, viewRange, onViewRangeChange, axisOptions, onAxisClick, onAxisBounds, }: TimeSeriesChartProps): import("react").JSX.Element;
305
+ /** Memoized export — hover state in the terminal re-renders the chips, not the
306
+ * canvas. */
307
+ export declare const TimeSeriesChart: import("react").MemoExoticComponent<typeof TimeSeriesChartInner>;
308
+ export {};