@tidal-ts/chart 0.1.2 → 0.2.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.
@@ -227,6 +227,28 @@ export interface TimeSeriesChartProps {
227
227
  precision?: number;
228
228
  /** `log` never arrives with a `0` bound — the host refuses that pairing. */
229
229
  scaleType?: 'linear' | 'log';
230
+ /**
231
+ * A title over the gutter — the curve's name atop its own column. Drawn
232
+ * at the top of the gutter with headroom padded into the domain so the
233
+ * top tick does not collide with it. One titled axis pads every axis on
234
+ * its side, so their tick rows stay aligned. Absent everywhere ⇒ no title
235
+ * and no pad: the legend carries identity, which is right for a terminal
236
+ * and wrong for a pane whose gutter IS the legend.
237
+ */
238
+ label?: string;
239
+ /**
240
+ * Pin this many ticks at equal FRACTIONS of `[min, max]`. Several
241
+ * own-axes stacked on one side each nice their ticks independently, so
242
+ * their rows land at different heights and the one grid the row draws
243
+ * lines up with exactly one of them; the same fractions on every axis
244
+ * make the rows agree by construction (`fractionTicks`). Honoured only
245
+ * when BOTH bounds are pinned (a free bound has no fraction to pin to)
246
+ * and the scale is linear (equal fractions of a log domain bunch).
247
+ */
248
+ ticks?: number;
249
+ /** The gutter's width in px; absent keeps pond's default. A pane that
250
+ * stacks one column per curve budgets this exactly. */
251
+ width?: number;
230
252
  }>;
231
253
  /**
232
254
  * A y GUTTER GESTURE that moved an axis (`<YAxis onBoundsChange>`): the bounds
@@ -2,11 +2,11 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useRef, useCallback, Fragment, memo, useEffect, useMemo, useState, } from 'react';
3
3
  import { AreaChart, BandChart, BarChart, Candlestick, ChartContainer, ChartRow, Layers, LineChart, Marker, Region, TimeAxis, YAxis, YAxisIndicator, } from '@pond-ts/charts';
4
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';
5
+ import { resolveTimeZone, aggregateColumn, hasPairOp, inferBarMs, liveWindowMs, ohlcWindow, readNumericColumn, sessionOpenLine, exactSessionSegments, sessionSegments, shiftKeys, sliceBySegments, WINDOW_MS, autoBarWindow, opOutputs, outputMark, } from '@tidal-ts/core';
6
6
  import { candleStyleForColor, candleStyleForPair } from './candleStyle.js';
7
7
  import { useMeasuredWidth } from './useMeasuredWidth.js';
8
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';
9
+ import { configAxisId, seriesDrawn, DASH_PATTERN, effectiveSplit, seriesAxisId, seriesLineDashArray, seriesLineWidth, sharedAxisId, axisFormat, fractionTicks, bandColumns, outputKey, configColumns, } from './series.js';
10
10
  /** The schema-erased series type every layer reads. Rows carry heterogeneous
11
11
  * sources (vol `%`, price `$`), so the chart works in the erased schema and each
12
12
  * config names its `column`. Callers build the {@link TimeSeriesChartProps.sources} map
@@ -94,6 +94,9 @@ function parseHex(hex) {
94
94
  const n = parseInt(m[1], 16);
95
95
  return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
96
96
  }
97
+ /** Headroom a TITLED axis adds above its domain, as a fraction of the span, so
98
+ * the top tick clears the title drawn in the same gutter. */
99
+ const AXIS_LABEL_HEADROOM = 0.14;
97
100
  /** How far a hovered axis's ink shifts toward the theme's extreme. */
98
101
  const HOVER_LIFT = 0.42;
99
102
  /** The default {@link TimeSeriesChartProps.resolveColor}: the config's colour is
@@ -787,6 +790,25 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
787
790
  const bar = probe.length >= 2 ? inferBarMs(probe) : undefined;
788
791
  return bar !== undefined && bar < WINDOW_MS['1d'];
789
792
  }, [sources]);
793
+ /** Whether this config's layers break at the session seams. */
794
+ const breaksFor = (c) => intraday && settings.sessions.breaks && !coarse.has(c.source ?? '');
795
+ /** …and whether a FILL has to be split to do so: only when there are seams. */
796
+ const splitsFor = (c) => breaksFor(c) && sessions.length > 1;
797
+ // One sub-series per live segment, for the layers pond gives no `sessionBreaks`
798
+ // (`<BandChart>`, `<AreaChart>`). Lazy and cached on the series object: slicing
799
+ // a 250k-row series into ~250 sessions is real work, and most renders draw no
800
+ // fill at all. The cache resets with the segments.
801
+ const segmentsFor = useMemo(() => {
802
+ const cache = new Map();
803
+ return (series) => {
804
+ let slices = cache.get(series);
805
+ if (!slices) {
806
+ slices = sliceBySegments(series, sessions);
807
+ cache.set(series, slices);
808
+ }
809
+ return slices;
810
+ };
811
+ }, [sessions]);
790
812
  const discontinuities = useMemo(() => !collapseWeekends
791
813
  ? undefined
792
814
  : sessions.length
@@ -812,12 +834,30 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
812
834
  (c.source ? shifted.get(c.source) : undefined) ??
813
835
  panelSeries;
814
836
  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
- ];
837
+ case 'area': {
838
+ // No `sessionBreaks` on `<AreaChart>` — the prop is LineChart-only
839
+ // (F-charts-20), so the break is made here: one layer per live segment,
840
+ // and the fill ends at the close and restarts at the open like the line
841
+ // would. One layer when nothing collapses.
842
+ //
843
+ // Cut the RAW series, then shift each slice — never the reverse. The
844
+ // segments come from unshifted keys, so a shifted session's last close
845
+ // sits exactly on its segment end and the half-open cut would drop it:
846
+ // the fill would stop one bar before the line it is meant to agree with,
847
+ // at every seam.
848
+ if (!splitsFor(c)) {
849
+ return [_jsx(AreaChart, { series: closeSeries, column: col, as: c.id, axis: axis }, c.id)];
850
+ }
851
+ const native = c.source ? nativeMs(sources[c.source]) : undefined;
852
+ const atClose = (slice) => {
853
+ if (native === undefined)
854
+ return slice;
855
+ if (c.source && col === 'close' && ohlc.has(c.source))
856
+ return sessionOpenLine(slice, native, { open: 'open', close: 'close' });
857
+ return shiftKeys(slice, native);
858
+ };
859
+ return segmentsFor(panelSeries).map((slice, i) => (_jsx(AreaChart, { series: atClose(slice), column: col, as: c.id, axis: axis }, `${c.id}__s${i}`)));
860
+ }
821
861
  case 'bar': {
822
862
  const s = derived.bar.get(c.id);
823
863
  if (!s)
@@ -864,10 +904,19 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
864
904
  // `col` is the SPEC ID here, not a column: a multi-output op names its
865
905
  // three columns off it (`bandColumns`). Reading `col` itself would find
866
906
  // nothing.
907
+ //
908
+ // The wash has no `sessionBreaks` either, so on a collapsing axis it is
909
+ // one `<BandChart>` per live segment over that segment's slice — else a
910
+ // filled envelope bridges the overnight gap its own centre line honours.
867
911
  const b = bandColumns(col);
912
+ const washes = splitsFor(c)
913
+ ? segmentsFor(panelSeries).map((slice, i) => (_jsx(BandChart, { series: slice, lower: b.lower, upper: b.upper, as: c.id, axis: axis }, `${c.id}__band${i}`)))
914
+ : [
915
+ _jsx(BandChart, { series: panelSeries, lower: b.lower, upper: b.upper, as: c.id, axis: axis }, `${c.id}__band`),
916
+ ];
868
917
  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),
918
+ ...washes,
919
+ _jsx(LineChart, { series: panelSeries, column: b.middle, as: c.id, axis: axis, sessionBreaks: breaksFor(c) }, c.id),
871
920
  ];
872
921
  }
873
922
  case 'lines': {
@@ -1068,6 +1117,16 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
1068
1117
  setHoverAxis((cur) => (cur === axisId ? null : cur));
1069
1118
  }
1070
1119
  : () => undefined;
1120
+ // A title pads its axis's domain (headroom for the title), and pond
1121
+ // pads BOTH ends. Pad one axis and its tick rows slide against its
1122
+ // neighbours', which undoes what `ticks` is for — so one titled
1123
+ // axis pads every axis on its side. Recorded as a pond ask: a
1124
+ // top-only pad, so a title does not also lift a `min: 0` floor.
1125
+ const sideAxisIds = [
1126
+ ...(shared.length > 0 ? [rowAxis(row.id, side)] : []),
1127
+ ...[...grouped.keys()].map((g) => seriesAxisId(row.id, side, g)),
1128
+ ];
1129
+ const sideTitled = sideAxisIds.some((a) => !!axisOptions?.[a]?.label);
1071
1130
  const axis = (id, cfgs) => {
1072
1131
  // An axis takes its members' colour when they AGREE on one —
1073
1132
  // not just when there is exactly one of them. Two legs of a
@@ -1077,11 +1136,28 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
1077
1136
  // (Peter, 2026-08-18).
1078
1137
  const only = new Set(cfgs.map((c) => c.color));
1079
1138
  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
1139
+ const opts = axisOptions?.[id];
1140
+ // The unit decides the shape, the axis's precision decides the
1141
+ // decimals (`axisFormat`); absent, every unit formats exactly as
1142
+ // it always did.
1143
+ const format = axisFormat(cfgs[0].unit, opts?.precision);
1144
+ // Pinned ticks need pinned bounds (a fraction of a free edge is
1145
+ // not a position) and a linear scale (equal fractions of a log
1146
+ // domain bunch toward the top).
1147
+ const scale = opts?.scaleType ?? 'linear';
1148
+ const ticks = scale === 'linear' &&
1149
+ opts?.ticks !== undefined &&
1150
+ opts.min !== undefined &&
1151
+ opts.max !== undefined
1152
+ ? fractionTicks(opts.min, opts.max, opts.ticks, format)
1153
+ : undefined;
1154
+ return (_jsx(YAxis, { id: id, side: side === 'R' ? 'right' : 'left', label: opts?.label ?? '',
1155
+ // A title sits at the top of its own gutter, exactly where
1156
+ // the top tick label wants to be. Padding the domain pushes
1157
+ // that tick down off the edge and leaves the title a clear
1158
+ // line; the same pad on every titled axis keeps their rows
1159
+ // aligned.
1160
+ labelPlacement: opts?.label ? 'top' : undefined, pad: sideTitled ? AXIS_LABEL_HEADROOM : undefined, width: opts?.width, ticks: ticks, format: format, scale: scale, color: hoverAxis === id
1085
1161
  ? hoverInk(own ?? base.axis.label, colorScheme)
1086
1162
  : (own ?? undefined),
1087
1163
  // Each bound resolves on its own (a hard lock, else a manual
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
  export { TimeSeriesChart, annotationInView, type ChartAnnotation, type ChartStats, type TimeSeriesChartProps, type TimeSeriesChartRow, } from './TimeSeriesChart.js';
15
15
  export type { ChartSeries } from './types.js';
16
- export { configAxisId, effectiveSplit, formatSeriesValue, isStudySeries, LINE_WIDTHS, PAIR_JOINS, PAIR_LENSES, seriesAxisId, readsCompare, seriesDrawn, seriesLineDashArray, seriesLineWidth, sharedAxisId, type AxisRange, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, bandColumns, configColumns, hasBarOutput, logAllowed, AXIS_PRECISIONS, type PairJoinOp, type PairLensOp, type SeriesGroup, type PairPartView, type PairView, type SeriesBinding, type SeriesConfig, type SeriesAxis, type SeriesStyle, type SeriesWindow, type CandleVariant, type ColorBy, } from './series.js';
16
+ export { configAxisId, effectiveSplit, formatSeriesValue, isStudySeries, LINE_WIDTHS, PAIR_JOINS, PAIR_LENSES, seriesAxisId, readsCompare, seriesDrawn, seriesLineDashArray, seriesLineWidth, sharedAxisId, type AxisRange, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, fractionTicks, bandColumns, configColumns, hasBarOutput, logAllowed, AXIS_PRECISIONS, type PairJoinOp, type PairLensOp, type SeriesGroup, type PairPartView, type PairView, type SeriesBinding, type SeriesConfig, type SeriesAxis, type SeriesStyle, type SeriesWindow, type CandleVariant, type ColorBy, } from './series.js';
17
17
  export { DEFAULT_CHART_SETTINGS, mergeChartSettings, type AnnotationOverride, type ChartSettings, type CategoryLineStyle, type SessionDividers, type SplitColorDefault, type LineDash, } from './chartSettings.js';
18
18
  export { useMeasuredWidth, useMeasuredSize } from './useMeasuredWidth.js';
19
19
  export { assembleRows, carries, foldKey, foldSources, prepareChart, sourceFacts, type ConfigRow, type PreparedRow, type SourceFacts, type SourceInput, type SourceInputs, } from './prepare.js';
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@
12
12
  * style builders) stay internal until a consumer asks.
13
13
  */
14
14
  export { TimeSeriesChart, annotationInView, } from './TimeSeriesChart.js';
15
- export { configAxisId, effectiveSplit, formatSeriesValue, isStudySeries, LINE_WIDTHS, PAIR_JOINS, PAIR_LENSES, seriesAxisId, readsCompare, seriesDrawn, seriesLineDashArray, seriesLineWidth, sharedAxisId, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, bandColumns, configColumns, hasBarOutput, logAllowed, AXIS_PRECISIONS, } from './series.js';
15
+ export { configAxisId, effectiveSplit, formatSeriesValue, isStudySeries, LINE_WIDTHS, PAIR_JOINS, PAIR_LENSES, seriesAxisId, readsCompare, seriesDrawn, seriesLineDashArray, seriesLineWidth, sharedAxisId, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, fractionTicks, bandColumns, configColumns, hasBarOutput, logAllowed, AXIS_PRECISIONS, } from './series.js';
16
16
  export { DEFAULT_CHART_SETTINGS, mergeChartSettings, } from './chartSettings.js';
17
17
  export { useMeasuredWidth, useMeasuredSize } from './useMeasuredWidth.js';
18
18
  export { assembleRows, carries, foldKey, foldSources, prepareChart, sourceFacts, } from './prepare.js';
package/dist/series.d.ts CHANGED
@@ -268,6 +268,23 @@ export declare const AXIS_PRECISIONS: readonly [0, 1, 2, 3, 4];
268
268
  * property).
269
269
  */
270
270
  export declare function logAllowed(range: AxisRange | undefined): [boolean, string?];
271
+ /**
272
+ * Ticks at the same FRACTIONS of an axis's own domain — `i / (count - 1)` of the
273
+ * way from `min` to `max`, labelled by `format`.
274
+ *
275
+ * Several own-axes stacked on one side each nice their ticks independently, so
276
+ * their rows land at different heights and the one grid the row draws (from the
277
+ * first axis) lines up with exactly one of them. Pinning every axis to explicit
278
+ * bounds and to these ticks makes the rows agree by construction, and the
279
+ * gridlines then read as every axis's grid. Only meaningful when both bounds are
280
+ * fixed, which is why the chart takes the count through `axisOptions` and
281
+ * ignores it when either bound is free. Fewer than two ticks, or an inverted
282
+ * domain, is nothing to draw.
283
+ */
284
+ export declare function fractionTicks(min: number, max: number, count: number, format: (v: number) => string): Array<{
285
+ at: number;
286
+ label: string;
287
+ }>;
271
288
  export declare function axisFormat(unit: string | undefined, precision?: number): (v: number) => string;
272
289
  /** Make a fitted extent symmetric about zero — `[-m, +m]`. `null` when there is
273
290
  * nothing to centre (no data), so the caller falls back to the library's fit. */
package/dist/series.js CHANGED
@@ -136,6 +136,27 @@ export function logAllowed(range) {
136
136
  * The cache is bounded by the unit vocabulary × six precisions.
137
137
  */
138
138
  const AXIS_FORMATS = new Map();
139
+ /**
140
+ * Ticks at the same FRACTIONS of an axis's own domain — `i / (count - 1)` of the
141
+ * way from `min` to `max`, labelled by `format`.
142
+ *
143
+ * Several own-axes stacked on one side each nice their ticks independently, so
144
+ * their rows land at different heights and the one grid the row draws (from the
145
+ * first axis) lines up with exactly one of them. Pinning every axis to explicit
146
+ * bounds and to these ticks makes the rows agree by construction, and the
147
+ * gridlines then read as every axis's grid. Only meaningful when both bounds are
148
+ * fixed, which is why the chart takes the count through `axisOptions` and
149
+ * ignores it when either bound is free. Fewer than two ticks, or an inverted
150
+ * domain, is nothing to draw.
151
+ */
152
+ export function fractionTicks(min, max, count, format) {
153
+ if (!(count >= 2) || !(max > min))
154
+ return [];
155
+ return Array.from({ length: count }, (_, i) => {
156
+ const at = min + ((max - min) * i) / (count - 1);
157
+ return { at, label: format(at) };
158
+ });
159
+ }
139
160
  export function axisFormat(unit, precision) {
140
161
  const key = `${unit ?? ''}|${precision ?? ''}`;
141
162
  const memo = AXIS_FORMATS.get(key);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/chart",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "description": "TimeSeriesChart — a multi-row time-series chart on @pond-ts/charts, plus the series and settings vocabulary and the prepare step. Theme, colours and settings arrive as props.",
6
6
  "license": "MIT",
@@ -37,21 +37,31 @@
37
37
  "react": "^18.2.0 || ^19.0.0"
38
38
  },
39
39
  "dependencies": {
40
- "@tidal-ts/core": "0.1.2"
40
+ "@tidal-ts/core": "0.2.0"
41
41
  },
42
42
  "devDependencies": {
43
+ "@pond-ts/charts": "^0.69.0",
43
44
  "@pond-ts/financial": "^0.69.0",
44
45
  "@pond-ts/process": "0.69.0",
46
+ "@storybook/addon-essentials": "^8.5.0",
47
+ "@storybook/react": "^8.5.0",
48
+ "@storybook/react-vite": "^8.5.0",
49
+ "@types/react": "^18.3.18",
50
+ "@types/react-dom": "^18.3.5",
51
+ "@vitejs/plugin-react": "^4.3.4",
45
52
  "pond-ts": "^0.69.0",
53
+ "react": "^18.3.1",
54
+ "react-dom": "^18.3.1",
55
+ "storybook": "^8.5.0",
46
56
  "typescript": "^5.7.2",
47
- "vitest": "^2.1.8",
48
- "@pond-ts/charts": "^0.69.0",
49
- "@types/react": "^18.3.18",
50
- "react": "^18.3.1"
57
+ "vite": "^5.4.11",
58
+ "vitest": "^2.1.8"
51
59
  },
52
60
  "scripts": {
53
61
  "build": "rm -rf dist && tsc -p tsconfig.json",
54
62
  "typecheck": "tsc -p tsconfig.test.json",
55
- "test": "vitest run"
63
+ "test": "vitest run",
64
+ "storybook": "storybook dev -p 6009 --no-open",
65
+ "build-storybook": "storybook build"
56
66
  }
57
67
  }