@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 +21 -0
- package/dist/TimeSeriesChart.d.ts +308 -0
- package/dist/TimeSeriesChart.js +1154 -0
- package/dist/candleStyle.d.ts +11 -0
- package/dist/candleStyle.js +20 -0
- package/dist/chartSettings.d.ts +93 -0
- package/dist/chartSettings.js +107 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.js +22 -0
- package/dist/prepare.d.ts +111 -0
- package/dist/prepare.js +139 -0
- package/dist/series.d.ts +474 -0
- package/dist/series.js +355 -0
- package/dist/seriesFacts.d.ts +38 -0
- package/dist/seriesFacts.js +65 -0
- package/dist/types.d.ts +9 -0
- package/dist/types.js +1 -0
- package/dist/useMeasuredWidth.d.ts +21 -0
- package/dist/useMeasuredWidth.js +55 -0
- package/package.json +57 -0
package/dist/series.js
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The three columns a `band` config reads. Its `column` is the SPEC ID, which
|
|
3
|
+
* for a multi-output op is a PREFIX rather than a column of its own — the
|
|
4
|
+
* engine names `${id}Middle` / `Upper` / `Lower` off it. So a band is the one
|
|
5
|
+
* style whose `column` is not directly readable, and everything that scans a
|
|
6
|
+
* config's data (extent, hover, render) goes through here instead.
|
|
7
|
+
*/
|
|
8
|
+
export function bandColumns(column) {
|
|
9
|
+
const [middle, upper, lower] = BAND_OUTPUTS.map((suffix) => `${column}${suffix}`);
|
|
10
|
+
return { middle: middle, upper: upper, lower: lower };
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Whether a config draws a bar-marked output — i.e. whether the rise/fall
|
|
14
|
+
* toggle means anything for it.
|
|
15
|
+
*
|
|
16
|
+
* A `lines` config is a multi-output study, and only some of those carry a
|
|
17
|
+
* histogram among their outputs (a MACD does; a stochastic does not). Offering
|
|
18
|
+
* the toggle on a study with nothing to colour would be a control that does
|
|
19
|
+
* nothing.
|
|
20
|
+
*/
|
|
21
|
+
export function hasBarOutput(c) {
|
|
22
|
+
if (c.style !== 'lines' || !c.derive)
|
|
23
|
+
return false;
|
|
24
|
+
const op = c.derive.op;
|
|
25
|
+
return opOutputs(op).some((suffix) => outputMark(op, suffix) === 'bar');
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The per-output theme key for a `lines` config.
|
|
29
|
+
*
|
|
30
|
+
* One colour, N textures — a study's outputs are ONE series (a MACD is one
|
|
31
|
+
* study), so varying colour across them would fight the "colour = series"
|
|
32
|
+
* encoding. Mirrors the `__cmp` key, which does the same thing for a
|
|
33
|
+
* comparison counterpart.
|
|
34
|
+
*/
|
|
35
|
+
export const outputKey = (id, i) => `${id}__o${i}`;
|
|
36
|
+
/**
|
|
37
|
+
* The columns a config actually reads — one for most styles, three for a
|
|
38
|
+
* `band`, and one per declared output for `lines`.
|
|
39
|
+
*
|
|
40
|
+
* The single place that answers "what data does this config touch?", so a new
|
|
41
|
+
* multi-output study doesn't have to be found in five scanners. A `lines`
|
|
42
|
+
* config needs its `derive` to answer, because the suffixes come from the op's
|
|
43
|
+
* declaration; without one it degrades to its bare column rather than throwing
|
|
44
|
+
* (a persisted config can outlive the op that named it).
|
|
45
|
+
*/
|
|
46
|
+
export function configColumns(c) {
|
|
47
|
+
if (c.style === 'band') {
|
|
48
|
+
const b = bandColumns(c.column);
|
|
49
|
+
return [b.middle, b.upper, b.lower];
|
|
50
|
+
}
|
|
51
|
+
if (c.style === 'lines') {
|
|
52
|
+
if (!c.derive)
|
|
53
|
+
return [c.column];
|
|
54
|
+
return opOutputs(c.derive.op).map((suffix) => `${c.column}${suffix}`);
|
|
55
|
+
}
|
|
56
|
+
return [c.column];
|
|
57
|
+
}
|
|
58
|
+
// The aggregation window for `bar`/`candle` + the study `DeriveSpec` are owned by
|
|
59
|
+
// `@tidal-ts/core` (where the windowing + derive seam live) — imported for
|
|
60
|
+
// `SeriesConfig` below and re-exported so UI code has one import site for the
|
|
61
|
+
// series vocabulary.
|
|
62
|
+
import { BAND_OUTPUTS, COMPARE_PREFIX, opOutputs, opParams, outputMark, usesCompare, } from '@tidal-ts/core';
|
|
63
|
+
// The app-wide presentation defaults the category resolvers below read.
|
|
64
|
+
import { DEFAULT_CHART_SETTINGS, } from './chartSettings.js';
|
|
65
|
+
// --- Axis identity ------------------------------------------------------------
|
|
66
|
+
// One vocabulary for the chart (renders the axes), the machine (keys the range
|
|
67
|
+
// state), and the host (builds the panel model). A row-side's SHARED axis is
|
|
68
|
+
// `rowId:side`; an unlinked series' OWN axis appends its config id. Config ids
|
|
69
|
+
// (engine specIds) contain `:`/parens, so these ids are built here and never
|
|
70
|
+
// parsed — carry `rowId`/`side` alongside wherever they're needed.
|
|
71
|
+
/** A row-side's shared axis id (once the chart's private `rowAxis`). */
|
|
72
|
+
export const sharedAxisId = (rowId, side) => `${rowId}:${side === 'R' ? 'R' : 'L'}`;
|
|
73
|
+
/** A non-shared axis's id on a row side, keyed by its group. */
|
|
74
|
+
export const seriesAxisId = (rowId, side, group) => `${sharedAxisId(rowId, side)}:${group}`;
|
|
75
|
+
/** The axis a config actually scales on: its own when unlinked, else the shared. */
|
|
76
|
+
export const configAxisId = (rowId, c) => c.axisGroup ? seriesAxisId(rowId, c.axis, c.axisGroup) : sharedAxisId(rowId, c.axis);
|
|
77
|
+
/**
|
|
78
|
+
* Whether an axis's entry says nothing — no lock, no pin, no memory, no format
|
|
79
|
+
* or fit choice — and can therefore be dropped rather than accumulate an empty
|
|
80
|
+
* per axis ever touched.
|
|
81
|
+
*
|
|
82
|
+
* **One definition on purpose.** Each writer used to carry its own copy of this
|
|
83
|
+
* test, and two of the three had fallen behind the fields the type had grown:
|
|
84
|
+
* clearing a lock deleted the axis's `precision` and `scaleType` with it, and
|
|
85
|
+
* toggling centre-zero off did the same. A predicate that lives beside the type
|
|
86
|
+
* cannot drift from it that way.
|
|
87
|
+
*/
|
|
88
|
+
export function axisRangeIsEmpty(r) {
|
|
89
|
+
return (r.mode === 'auto' &&
|
|
90
|
+
r.min === undefined &&
|
|
91
|
+
r.max === undefined &&
|
|
92
|
+
r.lockMin === undefined &&
|
|
93
|
+
r.lockMax === undefined &&
|
|
94
|
+
r.autoBasis === undefined &&
|
|
95
|
+
r.centerZero === undefined &&
|
|
96
|
+
r.precision === undefined &&
|
|
97
|
+
r.scaleType === undefined);
|
|
98
|
+
}
|
|
99
|
+
/** The 0–4 precision choices an axis offers. */
|
|
100
|
+
export const AXIS_PRECISIONS = [0, 1, 2, 3, 4];
|
|
101
|
+
/**
|
|
102
|
+
* Whether `log` may be chosen for an axis. A log scale cannot contain zero or
|
|
103
|
+
* anything below it, so any bound the STATE nails at or under `0` — a hard lock
|
|
104
|
+
* or a manual pin — refuses it. The reason is the second element, for the
|
|
105
|
+
* disabled control's tooltip.
|
|
106
|
+
*
|
|
107
|
+
* Only what the range can state is checked. An AUTO fit that happens to span
|
|
108
|
+
* zero is a property of the data, not of this record, so it is the chart's to
|
|
109
|
+
* handle (PR #173 review, LOW: the old test was `=== 0` on the two locks, which
|
|
110
|
+
* let a hand-locked `-5` floor through while the doc claimed the stronger
|
|
111
|
+
* property).
|
|
112
|
+
*/
|
|
113
|
+
export function logAllowed(range) {
|
|
114
|
+
if (!range)
|
|
115
|
+
return [true];
|
|
116
|
+
const nonPositive = (v) => v !== undefined && v <= 0;
|
|
117
|
+
if (nonPositive(range.lockMin) || nonPositive(range.lockMax))
|
|
118
|
+
return [false, 'A log axis cannot reach 0 — unlock the bound pinned there first'];
|
|
119
|
+
if (range.mode === 'manual' && (nonPositive(range.min) || nonPositive(range.max)))
|
|
120
|
+
return [false, 'A log axis cannot reach 0 — raise the manual bounds above it first'];
|
|
121
|
+
return [true];
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* An axis tick formatter: the unit's own format, with `precision` overriding
|
|
125
|
+
* how many decimals it carries.
|
|
126
|
+
*
|
|
127
|
+
* Precision changes the DECIMALS, never the unit's identity — `$` keeps its
|
|
128
|
+
* symbol in front, `%` its sign behind, a count its compact `M`/`K` suffix, and
|
|
129
|
+
* a variance its exponential form (where the precision is the mantissa's).
|
|
130
|
+
* Omitted, every unit formats exactly as it did before this existed.
|
|
131
|
+
*
|
|
132
|
+
* The returned function is MEMOISED on `(unit, precision)`. `<YAxis format>` is
|
|
133
|
+
* the one axis prop the library cannot value-compare (`YAxis.d.ts`: a fresh
|
|
134
|
+
* function reference re-registers the axis every render), and the call site is
|
|
135
|
+
* an inline prop inside a render, so a stable identity has to come from here.
|
|
136
|
+
* The cache is bounded by the unit vocabulary × six precisions.
|
|
137
|
+
*/
|
|
138
|
+
const AXIS_FORMATS = new Map();
|
|
139
|
+
export function axisFormat(unit, precision) {
|
|
140
|
+
const key = `${unit ?? ''}|${precision ?? ''}`;
|
|
141
|
+
const memo = AXIS_FORMATS.get(key);
|
|
142
|
+
if (memo)
|
|
143
|
+
return memo;
|
|
144
|
+
const built = buildAxisFormat(unit, precision);
|
|
145
|
+
AXIS_FORMATS.set(key, built);
|
|
146
|
+
return built;
|
|
147
|
+
}
|
|
148
|
+
function buildAxisFormat(unit, precision) {
|
|
149
|
+
const p = precision;
|
|
150
|
+
// Same accounting convention as the chips: a MACD axis ran `$5 / $0 / $-5`
|
|
151
|
+
// before this, where the tick beside it now reads `($5)`.
|
|
152
|
+
if (unit === '$')
|
|
153
|
+
return (v) => formatCurrency(v, p === undefined ? 0 : p);
|
|
154
|
+
if (unit === '%')
|
|
155
|
+
return (v) => `${v.toFixed(p ?? 1)}%`;
|
|
156
|
+
if (unit === 'variance')
|
|
157
|
+
return (v) => v.toExponential(p ?? 1);
|
|
158
|
+
if (unit === 'count') {
|
|
159
|
+
const fmt = new Intl.NumberFormat('en', {
|
|
160
|
+
notation: 'compact',
|
|
161
|
+
maximumFractionDigits: p ?? 1,
|
|
162
|
+
});
|
|
163
|
+
return (v) => fmt.format(v);
|
|
164
|
+
}
|
|
165
|
+
// The unitless default keeps its "compact above 10k" rule, which is about
|
|
166
|
+
// legibility rather than decimals, so precision tunes only the plain branch.
|
|
167
|
+
const compact = new Intl.NumberFormat('en', {
|
|
168
|
+
notation: 'compact',
|
|
169
|
+
maximumFractionDigits: p ?? 1,
|
|
170
|
+
});
|
|
171
|
+
return (v) => (Math.abs(v) >= 10_000 ? compact.format(v) : v.toFixed(p ?? 1));
|
|
172
|
+
}
|
|
173
|
+
/** Make a fitted extent symmetric about zero — `[-m, +m]`. `null` when there is
|
|
174
|
+
* nothing to centre (no data), so the caller falls back to the library's fit. */
|
|
175
|
+
export function centerOnZero(fit) {
|
|
176
|
+
if (!fit)
|
|
177
|
+
return null;
|
|
178
|
+
const m = Math.max(Math.abs(fit.min), Math.abs(fit.max));
|
|
179
|
+
// An all-zero series has no magnitude to mirror; leave it to the library
|
|
180
|
+
// rather than emitting the degenerate [0, 0] no axis can draw.
|
|
181
|
+
return m > 0 ? { min: -m, max: m } : null;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* What to hand `<YAxis min|max>` for an axis — a lock first, then the manual
|
|
185
|
+
* pin, else `undefined` for the library's auto fit.
|
|
186
|
+
*
|
|
187
|
+
* The two bounds resolve independently, which is the point: a bar axis normally
|
|
188
|
+
* runs with a hard `0` floor and a free, auto-fitting top.
|
|
189
|
+
*/
|
|
190
|
+
export function effectiveAxisBounds(range,
|
|
191
|
+
/** The host's computed AUTO fit for this axis, when its `autoBasis` /
|
|
192
|
+
* `centerZero` ask for one the library would not produce by itself. Consulted
|
|
193
|
+
* only under `mode: 'auto'`, and only where no lock has already spoken. */
|
|
194
|
+
fitted) {
|
|
195
|
+
if (!range)
|
|
196
|
+
return {};
|
|
197
|
+
const manual = range.mode === 'manual';
|
|
198
|
+
const auto = manual ? undefined : (fitted ?? undefined);
|
|
199
|
+
return {
|
|
200
|
+
min: range.lockMin ?? (manual ? range.min : auto?.min),
|
|
201
|
+
max: range.lockMax ?? (manual ? range.max : auto?.max),
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Apply an axis's locks to bounds a GESTURE reported — the enforcement half of
|
|
206
|
+
* "a lock is a hard limit".
|
|
207
|
+
*
|
|
208
|
+
* The axes are controlled: charts reports where a drag or wheel would take the
|
|
209
|
+
* axis and the host decides what to write back. So a locked bound is simply not
|
|
210
|
+
* taken from the gesture, which is what makes the zero floor unpannable rather
|
|
211
|
+
* than merely re-drawn.
|
|
212
|
+
*/
|
|
213
|
+
export function clampBoundsToLocks(range, bounds) {
|
|
214
|
+
return [range?.lockMin ?? bounds[0], range?.lockMax ?? bounds[1]];
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* The DEFAULT locks for an axis, from what it carries — the rule that gives a
|
|
218
|
+
* bar its baseline for free.
|
|
219
|
+
*
|
|
220
|
+
* All-positive bars lock `min` to `0`; all-negative lock `max` to `0`. Any
|
|
221
|
+
* non-bar member removes the lock: a line has no baseline to protect, and it
|
|
222
|
+
* should not inherit a floor it never asked for.
|
|
223
|
+
*
|
|
224
|
+
* **Bars that straddle zero get no lock** (Peter, 2026-08-29). Their baseline
|
|
225
|
+
* sits inside the plot, where neither bound can hold it — locking `min` would
|
|
226
|
+
* pin the wrong thing. Better to leave it free than invent a rule.
|
|
227
|
+
*
|
|
228
|
+
* A derived default, re-seeded when an axis's membership changes, so an axis
|
|
229
|
+
* that returns to all-bars gets its floor back.
|
|
230
|
+
*
|
|
231
|
+
* @param autoMin the axis's auto fit — the sign test. `null` (no data) yields no
|
|
232
|
+
* lock, so an empty axis is never nailed to a floor it cannot justify.
|
|
233
|
+
*/
|
|
234
|
+
export function barZeroLock(cfgs, autoMin, autoMax) {
|
|
235
|
+
if (cfgs.length === 0 || !cfgs.every((c) => c.style === 'bar'))
|
|
236
|
+
return {};
|
|
237
|
+
if (autoMin == null || autoMax == null)
|
|
238
|
+
return {};
|
|
239
|
+
if (autoMin >= 0)
|
|
240
|
+
return { lockMin: 0 };
|
|
241
|
+
if (autoMax <= 0)
|
|
242
|
+
return { lockMax: 0 };
|
|
243
|
+
return {};
|
|
244
|
+
}
|
|
245
|
+
/** The JOINS — what the pair PICKER offers at add time (a pair is built by
|
|
246
|
+
* choosing a transform), and the subset of fn() that yields one line. One
|
|
247
|
+
* list, so the picker and the fn() node can't drift on naming or order. */
|
|
248
|
+
export const PAIR_JOINS = [
|
|
249
|
+
{ op: 'diff', glyph: 'A − B', hint: 'difference' },
|
|
250
|
+
{ op: 'ratio', glyph: 'A / B', hint: 'ratio' },
|
|
251
|
+
{ op: 'logRatio', glyph: 'log(A/B)', hint: 'log ratio' },
|
|
252
|
+
];
|
|
253
|
+
/** Every fn() option, in display order — the joins plus `None`, which leads
|
|
254
|
+
* because it is the least of them: no transform at all. */
|
|
255
|
+
export const PAIR_LENSES = [
|
|
256
|
+
{ op: 'none', glyph: 'None', hint: 'draw both legs, no transform' },
|
|
257
|
+
...PAIR_JOINS,
|
|
258
|
+
];
|
|
259
|
+
/**
|
|
260
|
+
* Whether a series actually DRAWS — its own eye, and every ancestor's.
|
|
261
|
+
*
|
|
262
|
+
* A leg keeps its own `visible` while the pair above it is hidden, so unhiding
|
|
263
|
+
* the pair restores what each leg was rather than switching everything on. The
|
|
264
|
+
* panel therefore shows the leg's OWN eye (dimmed, because something above it
|
|
265
|
+
* is doing the hiding); the chart asks this.
|
|
266
|
+
*/
|
|
267
|
+
export const seriesDrawn = (c) => c.visible && !c.group?.hidden;
|
|
268
|
+
/** The stroke widths offered in the controls + settings (px). */
|
|
269
|
+
export const LINE_WIDTHS = [0.5, 1, 1.5, 2];
|
|
270
|
+
/** The dash pattern a `'dashed'` category draws with (also the compare texture). */
|
|
271
|
+
export const DASH_PATTERN = [6, 4];
|
|
272
|
+
/** Whether a series is a windowed **study** (an SMA/EMA overlay — the "Derived"
|
|
273
|
+
* style category). A pointwise derived metric (the realized-vol line) and every
|
|
274
|
+
* raw column read as **metrics**. */
|
|
275
|
+
export function isStudySeries(s) {
|
|
276
|
+
// Asked of the REGISTRY, not of `params.period`: a period-shaped test answers
|
|
277
|
+
// "is this windowed?", which was the same question only while every tunable
|
|
278
|
+
// op had exactly one param with that name (PR #181 review, MEDIUM).
|
|
279
|
+
return s.derive ? opParams(s.derive.op).length > 0 : false;
|
|
280
|
+
}
|
|
281
|
+
/** True if a series reads the COMPARISON symbol — a spec whose leaves are
|
|
282
|
+
* `cmp_`-prefixed, or (an unjoined pair's leg) a raw `cmp_` column. */
|
|
283
|
+
export function readsCompare(s) {
|
|
284
|
+
return s.derive ? usesCompare(s.derive) : s.column.startsWith(COMPARE_PREFIX);
|
|
285
|
+
}
|
|
286
|
+
/** The style category a series' line defaults come from. A comparison-reading
|
|
287
|
+
* series takes the `comparisons` category (dashed) whatever else it is — the
|
|
288
|
+
* texture encodes the SYMBOL, so a study of a compare leg is dashed too. */
|
|
289
|
+
export function seriesCategoryStyle(s, settings) {
|
|
290
|
+
if (readsCompare(s))
|
|
291
|
+
return settings.comparisons;
|
|
292
|
+
return isStudySeries(s) ? settings.derived : settings.metrics;
|
|
293
|
+
}
|
|
294
|
+
/** A series' stroke width: its explicit `lineWidth` override, else its category
|
|
295
|
+
* default from the settings (metrics vs studies). */
|
|
296
|
+
export function seriesLineWidth(s, settings = DEFAULT_CHART_SETTINGS) {
|
|
297
|
+
return s.lineWidth ?? seriesCategoryStyle(s, settings).weight;
|
|
298
|
+
}
|
|
299
|
+
/** A series' dash pattern (`undefined` = solid) from its category's style. */
|
|
300
|
+
export function seriesLineDashArray(s, settings = DEFAULT_CHART_SETTINGS) {
|
|
301
|
+
return seriesCategoryStyle(s, settings).dash === 'dashed' ? DASH_PATTERN : undefined;
|
|
302
|
+
}
|
|
303
|
+
/** The effective direction-coloring of a `bar`/`candle` series: the per-series
|
|
304
|
+
* override, else the legacy candle `candleColorBy` (old presets), else the
|
|
305
|
+
* settings default for that mark kind. Rise/fall fall back to the settings'
|
|
306
|
+
* colors. Meaningless (single) for a `line`/`area` series. */
|
|
307
|
+
export function effectiveSplit(s, settings = DEFAULT_CHART_SETTINGS) {
|
|
308
|
+
const def = s.style === 'candle' ? settings.candles : settings.bars;
|
|
309
|
+
const legacy = s.style === 'candle' && s.candleColorBy != null
|
|
310
|
+
? s.candleColorBy === 'direction'
|
|
311
|
+
? 'split'
|
|
312
|
+
: 'single'
|
|
313
|
+
: undefined;
|
|
314
|
+
const mode = s.style === 'lines'
|
|
315
|
+
? // A study's histogram is OPT-IN, and never inherits the app's bar
|
|
316
|
+
// default: a MACD keeps the study's own colour until asked otherwise,
|
|
317
|
+
// because green/red is reserved for market data and an indicator is not
|
|
318
|
+
// that. The toggle is the asking.
|
|
319
|
+
(s.colorMode ?? 'single')
|
|
320
|
+
: s.style === 'bar' || s.style === 'candle'
|
|
321
|
+
? (s.colorMode ?? legacy ?? (def.split ? 'split' : 'single'))
|
|
322
|
+
: 'single';
|
|
323
|
+
return { mode, rise: s.riseColor ?? def.rise, fall: s.fallColor ?? def.fall };
|
|
324
|
+
}
|
|
325
|
+
const COMPACT = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 2 });
|
|
326
|
+
/**
|
|
327
|
+
* A negative currency amount in the accounting convention: `($2.75)`, not
|
|
328
|
+
* `$-2.75`.
|
|
329
|
+
*
|
|
330
|
+
* The sign belongs to the AMOUNT, so it wraps the whole thing rather than
|
|
331
|
+
* wedging a minus between the symbol and the digits — which is how every
|
|
332
|
+
* finance surface writes it, and which stopped being a hypothetical the moment
|
|
333
|
+
* a `delta`-unit study (a MACD of a price) put negative dollars on screen.
|
|
334
|
+
* Applies to the axis ticks too, so a chip and the axis beside it agree.
|
|
335
|
+
*/
|
|
336
|
+
export const formatCurrency = (v, digits) => v < 0 ? `($${Math.abs(v).toFixed(digits)})` : `$${v.toFixed(digits)}`;
|
|
337
|
+
/** Format a series value for a chip/row. Currency (`$`) leads the value
|
|
338
|
+
* (`$161.76`), and a negative reads `($2.75)` — see {@link formatCurrency};
|
|
339
|
+
* `count` (volume/shares) compacts to `1.18M` with no suffix;
|
|
340
|
+
* `log` is a SCALE rather than a suffix, so a log-ratio reads `-0.23`, not
|
|
341
|
+
* `-0.23log` (the unit still keeps it off a unitless axis); a percent /
|
|
342
|
+
* unitless suffix trails the value (`22.65%`). */
|
|
343
|
+
export function formatSeriesValue(value, unit = '') {
|
|
344
|
+
if (value == null)
|
|
345
|
+
return '—';
|
|
346
|
+
if (unit === 'count')
|
|
347
|
+
return COMPACT.format(value);
|
|
348
|
+
if (unit === 'variance')
|
|
349
|
+
return value.toExponential(1); // tiny raw decimal
|
|
350
|
+
if (unit === 'log')
|
|
351
|
+
return value.toFixed(2);
|
|
352
|
+
if (unit === '$')
|
|
353
|
+
return formatCurrency(value, 2);
|
|
354
|
+
return `${value.toFixed(2)}${unit}`;
|
|
355
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { readNumericColumn } from '@tidal-ts/core';
|
|
2
|
+
/**
|
|
3
|
+
* The facts the prepare step (and a host's readouts) need from a series, read
|
|
4
|
+
* **columnar**.
|
|
5
|
+
*
|
|
6
|
+
* Both were previously taken from `series.toObjects()`, which materialises one
|
|
7
|
+
* JS object per bar. At the ~250–1,260 daily bars Tidal was built on that is
|
|
8
|
+
* unnoticeable; at a year of 1-minute bars (250,291) it is the dominant cost of
|
|
9
|
+
* every range change — measured at **885 ms for 6M and 1,714 ms for 1Y** of
|
|
10
|
+
* blocked main thread, scaling with row count, while the same interaction on
|
|
11
|
+
* daily data produced no long task at all.
|
|
12
|
+
*
|
|
13
|
+
* It is also the exact trap pond's "columns, not events" guidance names, and one
|
|
14
|
+
* `TimeSeriesChart` already avoids by comment. These readers keep to the packed typed
|
|
15
|
+
* arrays.
|
|
16
|
+
*/
|
|
17
|
+
/** A series as the terminal holds it — schema-erased. */
|
|
18
|
+
type AnySeries = Parameters<typeof readNumericColumn>[0];
|
|
19
|
+
/** Column names, from the first row only. */
|
|
20
|
+
export declare function columnNames(series: AnySeries): string[];
|
|
21
|
+
/**
|
|
22
|
+
* Which columns carry at least one finite number — "show only what the data
|
|
23
|
+
* carries".
|
|
24
|
+
*
|
|
25
|
+
* The early exit is what makes this cheap: a column with data almost always has
|
|
26
|
+
* it in the first row, so this is O(columns) in practice rather than
|
|
27
|
+
* O(rows × columns). Only a genuinely empty column is scanned to the end, and
|
|
28
|
+
* that is the case worth being sure about.
|
|
29
|
+
*/
|
|
30
|
+
export declare function finiteColumns(series: AnySeries): Set<string>;
|
|
31
|
+
/** The last bar, as a plain row — that row only, never the whole series. */
|
|
32
|
+
export declare function lastRow(series: AnySeries): Record<string, number> | undefined;
|
|
33
|
+
/** First and last value of one column, without materialising anything. */
|
|
34
|
+
export declare function firstLast(series: AnySeries, column: string): {
|
|
35
|
+
first: number | null;
|
|
36
|
+
last: number | null;
|
|
37
|
+
};
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { readNumericColumn } from '@tidal-ts/core';
|
|
2
|
+
/** One row, via `at(i)`.
|
|
3
|
+
*
|
|
4
|
+
* pond documents `at` as routing through the store's per-row `eventAt` cache —
|
|
5
|
+
* "O(1) materialization for the requested row" — explicitly *unlike* indexing
|
|
6
|
+
* `series.events`, which forces the whole series to materialise. `toObjects()`
|
|
7
|
+
* is built on `this.events`, so it is exactly that full materialisation; that is
|
|
8
|
+
* what `toEvents()` shows up as in a profile.
|
|
9
|
+
*
|
|
10
|
+
* (A one-row `slice(...).toObjects()` measures fine too — `slice` is
|
|
11
|
+
* column-native — but it builds an intermediate series to read one row, and
|
|
12
|
+
* relies on that staying true. `at` says what it means.) */
|
|
13
|
+
function rowAt(series, index) {
|
|
14
|
+
const s = series;
|
|
15
|
+
if (index < 0 || index >= s.length)
|
|
16
|
+
return undefined;
|
|
17
|
+
return s.at(index)?.data();
|
|
18
|
+
}
|
|
19
|
+
/** Column names, from the first row only. */
|
|
20
|
+
export function columnNames(series) {
|
|
21
|
+
const row = rowAt(series, 0);
|
|
22
|
+
return row ? Object.keys(row) : [];
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Which columns carry at least one finite number — "show only what the data
|
|
26
|
+
* carries".
|
|
27
|
+
*
|
|
28
|
+
* The early exit is what makes this cheap: a column with data almost always has
|
|
29
|
+
* it in the first row, so this is O(columns) in practice rather than
|
|
30
|
+
* O(rows × columns). Only a genuinely empty column is scanned to the end, and
|
|
31
|
+
* that is the case worth being sure about.
|
|
32
|
+
*/
|
|
33
|
+
export function finiteColumns(series) {
|
|
34
|
+
const found = new Set();
|
|
35
|
+
for (const name of columnNames(series)) {
|
|
36
|
+
const col = readNumericColumn(series, name);
|
|
37
|
+
if (!col)
|
|
38
|
+
continue;
|
|
39
|
+
for (let i = 0; i < col.length; i += 1) {
|
|
40
|
+
const v = col.read(i);
|
|
41
|
+
if (typeof v === 'number' && Number.isFinite(v)) {
|
|
42
|
+
found.add(name);
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return found;
|
|
48
|
+
}
|
|
49
|
+
/** The last bar, as a plain row — that row only, never the whole series. */
|
|
50
|
+
export function lastRow(series) {
|
|
51
|
+
const n = series.length;
|
|
52
|
+
return rowAt(series, n - 1);
|
|
53
|
+
}
|
|
54
|
+
/** First and last value of one column, without materialising anything. */
|
|
55
|
+
export function firstLast(series, column) {
|
|
56
|
+
const col = readNumericColumn(series, column);
|
|
57
|
+
if (!col || col.length === 0)
|
|
58
|
+
return { first: null, last: null };
|
|
59
|
+
// `null`, not 0. A zero here used to mean "nothing to report", which is the
|
|
60
|
+
// same conflation the archive makes with a sentinel price of 0 — and it read
|
|
61
|
+
// downstream as a genuine quote of 0.00 for a ticker the dataset simply does
|
|
62
|
+
// not carry (MSFT has daily bars but no minute bars). Absence has to be a
|
|
63
|
+
// different value from a number.
|
|
64
|
+
return { first: col.read(0) ?? null, last: col.read(col.length - 1) ?? null };
|
|
65
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SeriesSchema, TimeSeries } from 'pond-ts';
|
|
2
|
+
/**
|
|
3
|
+
* The series the chart reads: a pond `TimeSeries` in the **erased** schema.
|
|
4
|
+
* Rows are heterogeneous (a vol series in `%`, a price series in `$`), so a
|
|
5
|
+
* host casts its specific schemas to this one at the boundary; a config names
|
|
6
|
+
* its `column` and the chart reads it structurally. One home for the type, so
|
|
7
|
+
* the prepare step and the renderer agree without importing each other.
|
|
8
|
+
*/
|
|
9
|
+
export type ChartSeries = TimeSeries<SeriesSchema>;
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { type RefObject } from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* Track an element's content-box width via `ResizeObserver`. `@pond-ts/charts`'
|
|
4
|
+
* `ChartContainer` needs an explicit pixel width, so a responsive chart wraps a
|
|
5
|
+
* measured element and feeds this width down. Returns `[ref, width]`; width is
|
|
6
|
+
* `0` until the first measurement (callers render a placeholder until > 0).
|
|
7
|
+
*/
|
|
8
|
+
export declare function useMeasuredWidth<T extends HTMLElement = HTMLDivElement>(): [RefObject<T>, number];
|
|
9
|
+
/**
|
|
10
|
+
* Track an element's border-box width AND height via `ResizeObserver`, seeded by
|
|
11
|
+
* a **synchronous** first read (`getBoundingClientRect` in a layout effect) — RO's
|
|
12
|
+
* initial callback isn't guaranteed to fire, and a fill layout that waits on it
|
|
13
|
+
* can mount at zero and never recover. Returns `[ref, { width, height }]`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function useMeasuredSize<T extends HTMLElement = HTMLDivElement>(): [
|
|
16
|
+
RefObject<T>,
|
|
17
|
+
{
|
|
18
|
+
width: number;
|
|
19
|
+
height: number;
|
|
20
|
+
}
|
|
21
|
+
];
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* Track an element's content-box width via `ResizeObserver`. `@pond-ts/charts`'
|
|
4
|
+
* `ChartContainer` needs an explicit pixel width, so a responsive chart wraps a
|
|
5
|
+
* measured element and feeds this width down. Returns `[ref, width]`; width is
|
|
6
|
+
* `0` until the first measurement (callers render a placeholder until > 0).
|
|
7
|
+
*/
|
|
8
|
+
// NOTE (React 18): the ref is typed `RefObject<T>` because that's what the DOM
|
|
9
|
+
// `ref` prop accepts under @types/react@18 (a nullable `RefObject<T | null>` is
|
|
10
|
+
// rejected there). React 19 flips this — revisit to `RefObject<T | null>` on the
|
|
11
|
+
// React 19 bump.
|
|
12
|
+
export function useMeasuredWidth() {
|
|
13
|
+
const ref = useRef(null);
|
|
14
|
+
const [width, setWidth] = useState(0);
|
|
15
|
+
useEffect(() => {
|
|
16
|
+
const el = ref.current;
|
|
17
|
+
if (!el)
|
|
18
|
+
return;
|
|
19
|
+
const observer = new ResizeObserver((entries) => {
|
|
20
|
+
const entry = entries[0];
|
|
21
|
+
if (entry)
|
|
22
|
+
setWidth(entry.contentRect.width);
|
|
23
|
+
});
|
|
24
|
+
observer.observe(el);
|
|
25
|
+
setWidth(el.clientWidth);
|
|
26
|
+
return () => observer.disconnect();
|
|
27
|
+
}, []);
|
|
28
|
+
return [ref, width];
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Track an element's border-box width AND height via `ResizeObserver`, seeded by
|
|
32
|
+
* a **synchronous** first read (`getBoundingClientRect` in a layout effect) — RO's
|
|
33
|
+
* initial callback isn't guaranteed to fire, and a fill layout that waits on it
|
|
34
|
+
* can mount at zero and never recover. Returns `[ref, { width, height }]`.
|
|
35
|
+
*/
|
|
36
|
+
export function useMeasuredSize() {
|
|
37
|
+
const ref = useRef(null);
|
|
38
|
+
const [size, setSize] = useState({ width: 0, height: 0 });
|
|
39
|
+
useLayoutEffect(() => {
|
|
40
|
+
const el = ref.current;
|
|
41
|
+
if (!el)
|
|
42
|
+
return;
|
|
43
|
+
const measure = () => {
|
|
44
|
+
const r = el.getBoundingClientRect();
|
|
45
|
+
const width = Math.round(r.width);
|
|
46
|
+
const height = Math.round(r.height);
|
|
47
|
+
setSize((p) => (p.width === width && p.height === height ? p : { width, height }));
|
|
48
|
+
};
|
|
49
|
+
measure();
|
|
50
|
+
const observer = new ResizeObserver(measure);
|
|
51
|
+
observer.observe(el);
|
|
52
|
+
return () => observer.disconnect();
|
|
53
|
+
}, []);
|
|
54
|
+
return [ref, size];
|
|
55
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tidal-ts/chart",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": false,
|
|
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
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/tidal-app/tidal-ts.git",
|
|
10
|
+
"directory": "packages/chart"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/tidal-app/tidal-ts#readme",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"main": "dist/index.js",
|
|
15
|
+
"types": "dist/index.d.ts",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"sideEffects": false,
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"!dist/**/*.test.*"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=22"
|
|
29
|
+
},
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"@pond-ts/charts": "^0.69.0",
|
|
35
|
+
"@pond-ts/financial": "^0.69.0",
|
|
36
|
+
"pond-ts": "^0.69.0",
|
|
37
|
+
"react": "^18.2.0 || ^19.0.0"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"@tidal-ts/core": "0.1.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@pond-ts/financial": "^0.69.0",
|
|
44
|
+
"@pond-ts/process": "0.69.0",
|
|
45
|
+
"pond-ts": "^0.69.0",
|
|
46
|
+
"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"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
54
|
+
"typecheck": "tsc -p tsconfig.test.json",
|
|
55
|
+
"test": "vitest run"
|
|
56
|
+
}
|
|
57
|
+
}
|