@tidal-ts/chart 0.17.0 → 0.21.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/README.md CHANGED
@@ -20,8 +20,8 @@ version number.
20
20
  ## Install
21
21
 
22
22
  ```bash
23
- npm install --save-exact @tidal-ts/core @tidal-ts/chart @pond-ts/process@0.75.0
24
- npm install pond-ts@~0.75.0 @pond-ts/financial@~0.75.0 @pond-ts/charts@~0.75.0 @pond-ts/react@~0.75.0
23
+ npm install --save-exact @tidal-ts/core @tidal-ts/chart @pond-ts/process@0.78.0
24
+ npm install pond-ts@~0.78.0 @pond-ts/financial@~0.78.0 @pond-ts/charts@~0.78.0 @pond-ts/react@~0.78.0
25
25
  ```
26
26
 
27
27
  React 18 or 19. The pond packages are peer dependencies: install them once, on
@@ -2,6 +2,7 @@ import { type ReactNode } from 'react';
2
2
  import type { ChartSeries } from './types.js';
3
3
  import type { ChartContainerProps, ChartTheme, LiveValue, TrackerInfo } from '@pond-ts/charts';
4
4
  import { aggregateColumn, type Segment } from '@tidal-ts/core';
5
+ import { type ChartLevel } from './levels.js';
5
6
  import { type ChartSettings } from './chartSettings.js';
6
7
  import { type SeriesAxis, type SeriesConfig } from './series.js';
7
8
  /** One time marker. */
@@ -78,6 +79,13 @@ export interface TimeSeriesChartRow {
78
79
  id: string;
79
80
  height: number;
80
81
  configs: SeriesConfig[];
82
+ /**
83
+ * Host levels: a value (or a low and a high) drawn across the plot on the
84
+ * axis of one of this row's series, in an ink the host chooses. Beside the
85
+ * study guides, never instead of them. They do not move the axis, and they
86
+ * hide with the series they ride on. See {@link ChartLevel}.
87
+ */
88
+ levels?: readonly ChartLevel[];
81
89
  }
82
90
  export interface TimeSeriesChartProps {
83
91
  /** The stacked rows (top → bottom), each with a resolved px `height` + configs.
@@ -197,6 +205,20 @@ export interface TimeSeriesChartProps {
197
205
  * Keep the identity stable (module-level or memoised): it keys the theme memo.
198
206
  */
199
207
  resolveColor?: (color: string) => string;
208
+ /**
209
+ * The **BEFORE ink** of a comparison: a concrete canvas colour that the
210
+ * compared side ({@link isCompareSide} — a series whose every leaf is on the
211
+ * comparison symbol) draws in, in place of its own. The reference keeps its
212
+ * own colour, so the answer is always the solid line in its own ink and the
213
+ * thing compared is the muted, dashed one ("before / after").
214
+ *
215
+ * The canvas only: the config keeps its colour, so an axis still takes its
216
+ * members' colour when they agree (a mirror and its primary share one), and
217
+ * a host's legend and swatches are untouched. A joined pair reads both
218
+ * symbols and keeps its colour. Absent (the default), colour = series, as
219
+ * before.
220
+ */
221
+ compareInk?: string;
200
222
  /**
201
223
  * Which way a hovered axis's ink lifts: toward white on a dark surface, toward
202
224
  * black on a light one. The one presentation fact the theme object does not
@@ -358,7 +380,7 @@ export declare function splitBarColumns(agg: ChartSeries, col: string, src: Char
358
380
  * chips can track the hovered point. Memoized — the caller's hover state re-renders
359
381
  * chips, not the canvas (keep prop identities stable).
360
382
  */
361
- declare function TimeSeriesChartInner({ rows, sources, ohlcSources, calendarDays, annotations, coarseSources, dimmed, splitters, onTracker, onStats, pricePill, collapseWeekends, settings, timeZone, theme: base, resolveColor, colorScheme, viewRange, onViewRangeChange, panZoom, axisOptions, onAxisClick, onAxisBounds, onBarSeries, }: TimeSeriesChartProps): import("react").JSX.Element;
383
+ declare function TimeSeriesChartInner({ rows, sources, ohlcSources, calendarDays, annotations, coarseSources, dimmed, splitters, onTracker, onStats, pricePill, collapseWeekends, settings, timeZone, theme: base, resolveColor, compareInk, colorScheme, viewRange, onViewRangeChange, panZoom, axisOptions, onAxisClick, onAxisBounds, onBarSeries, }: TimeSeriesChartProps): import("react").JSX.Element;
362
384
  /** Memoized export — hover state in the terminal re-renders the chips, not the
363
385
  * canvas. */
364
386
  export declare const TimeSeriesChart: import("react").MemoExoticComponent<typeof TimeSeriesChartInner>;
@@ -1,13 +1,14 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useRef, useCallback, Fragment, memo, useEffect, useMemo, useState, } from 'react';
3
- import { AreaChart, BandChart, BarChart, Candlestick, ChartContainer, ChartRow, CrosshairCursor, Layers, LineChart, Baseline, Marker, Region, TimeAxis, YAxis, YAxisIndicator, } from '@pond-ts/charts';
3
+ import { AreaChart, BandChart, BarChart, Candlestick, ChartContainer, ChartRow, CrosshairCursor, Layers, LineChart, Baseline, Marker, Region, TimeAxis, YAxis, YAxisIndicator, Zone, } from '@pond-ts/charts';
4
4
  import { segmentDiscontinuity, weekendSkip } from '@pond-ts/financial';
5
5
  import { resolveTimeZone, aggregateColumn, hasPairOp, inferBarMs, liveWindowMs, ohlcWindow, readNumericColumn, sessionOpenLine, exactSessionSegments, sessionSegments, shiftKeys, WINDOW_MS, autoBarWindow, } from '@tidal-ts/core';
6
6
  import { candleStyleForColor, candleStyleForPair } from './candleStyle.js';
7
7
  import { useMeasuredWidth } from './useMeasuredWidth.js';
8
8
  import { withAlpha } from './withAlpha.js';
9
+ import { levelRoles, levelsSig, rowLevelMarks } from './levels.js';
9
10
  import { DEFAULT_CHART_SETTINGS } from './chartSettings.js';
10
- import { configAxisId, guideLevels, seriesDrawn, configBand, configOutputs, dashPattern, outputLook, effectiveSplit, seriesAxisId, seriesLineDashArray, seriesLineWidth, sharedAxisId, axisFormat, fractionTicks, outputKey, configColumns, } from './series.js';
11
+ import { configAxisId, guideLevels, seriesDrawn, configBand, configOutputs, dashPattern, outputLook, effectiveSplit, seriesAxisId, seriesLineDashArray, seriesLineWidth, isCompareSide, readsCompare, sharedAxisId, axisFormat, fractionTicks, outputKey, configColumns, } from './series.js';
11
12
  /** The schema-erased series type every layer reads. Rows carry heterogeneous
12
13
  * sources (vol `%`, price `$`), so the chart works in the erased schema and each
13
14
  * config names its `column`. Callers build the {@link TimeSeriesChartProps.sources} map
@@ -310,7 +311,7 @@ export function splitBarColumns(agg, col, src, hasOhlc, window, sessions) {
310
311
  * chips can track the hovered point. Memoized — the caller's hover state re-renders
311
312
  * chips, not the canvas (keep prop identities stable).
312
313
  */
313
- function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, 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, panZoom = true, axisOptions, onAxisClick, onAxisBounds, onBarSeries, }) {
314
+ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, calendarDays = EMPTY_DAYS, annotations = EMPTY_ANNOTATIONS, coarseSources = EMPTY_SOURCES, dimmed = [], splitters, onTracker, onStats, pricePill, collapseWeekends, settings = DEFAULT_CHART_SETTINGS, timeZone, theme: base, resolveColor = sameColor, compareInk, colorScheme = 'dark', viewRange, onViewRangeChange, panZoom = true, axisOptions, onAxisClick, onAxisBounds, onBarSeries, }) {
314
315
  const [ref, width] = useMeasuredWidth();
315
316
  // Which y-axis gutter the pointer is over (the hover affordance). Axis
316
317
  // chrome is DOM, so this repaints the gutter only — never the canvas.
@@ -342,7 +343,11 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, cale
342
343
  const marks = configOutputs(c)
343
344
  .map((o) => o.mark[0])
344
345
  .join('');
345
- return `${c.id}:${c.color}:${sp.mode}:${sp.rise}:${sp.fall}:${c.style}:${seriesLineWidth(c, settings)}:${c.lineDash ?? ''}:${c.opacity ?? ''}:${c.fan?.join(',') ?? ''}:${marks}:${c.outputStyles ? JSON.stringify(c.outputStyles) : ''}`;
346
+ // Which SIDE of a comparison it reads: the dash (`readsCompare`) and
347
+ // the before ink (`isCompareSide`) both turn on the column and spec,
348
+ // which a study re-pointed at the other symbol changes under one id.
349
+ const side = `${readsCompare(c) ? 'c' : ''}${isCompareSide(c) ? 's' : ''}`;
350
+ return `${c.id}:${side}:${c.color}:${sp.mode}:${sp.rise}:${sp.fall}:${c.style}:${seriesLineWidth(c, settings)}:${c.lineDash ?? ''}:${c.opacity ?? ''}:${c.fan?.join(',') ?? ''}:${marks}:${c.outputStyles ? JSON.stringify(c.outputStyles) : ''}`;
346
351
  })
347
352
  .join('|') +
348
353
  '#' +
@@ -355,6 +360,9 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, cale
355
360
  const annotationSig = [...new Set(annotations.map((a) => `${a.role}:${a.color}`))]
356
361
  .sort()
357
362
  .join('|');
363
+ // Each host level's ink is a theme role (the library's only channel for a
364
+ // mark's colour), so its style fields key the theme too.
365
+ const levelSig = levelsSig(rows);
358
366
  const theme = useMemo(() => {
359
367
  const dim = new Set(dimmed);
360
368
  // One entry per series per draw kind — the canvas can't read the host's
@@ -367,7 +375,12 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, cale
367
375
  const candle = { ...base.candle };
368
376
  const band = { ...base.band };
369
377
  for (const c of allConfigs) {
370
- const stroke = resolveColor(c.color);
378
+ // The compared side draws in the host's BEFORE ink (`compareInk`); every
379
+ // other series in its own. Its outputs follow it, so a study on the
380
+ // compared leg is "before" too.
381
+ const before = compareInk !== undefined && isCompareSide(c);
382
+ const inkOf = (color) => (before ? compareInk : resolveColor(color));
383
+ const stroke = inkOf(c.color);
371
384
  const isDim = dim.has(c.id);
372
385
  // The user's opacity and the chart's dimming compose: a half-opaque line
373
386
  // that is also dimmed is fainter still, never back to full strength.
@@ -388,12 +401,19 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, cale
388
401
  };
389
402
  // Area fill wants a solid hex for its gradient, so dim via fillOpacity (not
390
403
  // an rgba fill); the outline still carries the dim.
404
+ //
405
+ // The outline takes the series' dash exactly as a line does (charts
406
+ // 0.78 `AreaStyle.dash` dashes the top edge, never the fill). That is
407
+ // what lets a comparison keep an area as an area: the compared side is
408
+ // the same shape with a dashed rim, the "before" of before / after. A
409
+ // user-picked texture on an area reaches the canvas by the same road.
391
410
  area[c.id] = {
392
411
  ...base.area.default,
393
412
  color,
394
413
  width,
395
414
  fill: stroke,
396
415
  fillOpacity: (isDim ? 0.04 : 0.14) * own,
416
+ ...(dash ? { dash: [...dash] } : {}),
397
417
  };
398
418
  // A band is a WASH, not a fill under a line: it carries no outline of its
399
419
  // own (the middle band draws that, as an ordinary line under the same
@@ -411,7 +431,7 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, cale
411
431
  c.style === 'band') {
412
432
  configOutputs(c).forEach((out, i) => {
413
433
  const look = outputLook(c, i, settings);
414
- const ink = withAlpha(resolveColor(look.color), opacityOf(look.opacity) * (isDim ? 0.22 : 1));
434
+ const ink = withAlpha(inkOf(look.color), opacityOf(look.opacity) * (isDim ? 0.22 : 1));
415
435
  const style = {
416
436
  color: ink,
417
437
  width: look.width,
@@ -463,15 +483,24 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, cale
463
483
  // role, so N marks of one kind cost one entry, and the theme's own per-role
464
484
  // `dash` survives: hue is the user's, texture stays ours (it is what tells
465
485
  // the two kinds apart).
466
- const annotation = base.annotation
486
+ // Host levels (`TimeSeriesChartRow.levels`) take the same route, one role
487
+ // per level. A base theme with no register gets one holding only those
488
+ // roles: charts fills every field it leaves out from `defaultAnnotation`,
489
+ // the ink every other mark already draws in there.
490
+ const levelRoleMap = levelRoles(rows, resolveColor, dim);
491
+ const register = base.annotation ?? (Object.keys(levelRoleMap).length > 0 ? {} : undefined);
492
+ const annotation = register
467
493
  ? {
468
- ...base.annotation,
469
- roles: annotations.reduce((acc, a) => ({
470
- ...acc,
471
- [a.role]: { ...acc?.[a.role], color: resolveColor(a.color) },
472
- }), base.annotation.roles ?? {}),
494
+ ...register,
495
+ roles: {
496
+ ...annotations.reduce((acc, a) => ({
497
+ ...acc,
498
+ [a.role]: { ...acc?.[a.role], color: resolveColor(a.color) },
499
+ }), register.roles ?? {}),
500
+ ...levelRoleMap,
501
+ },
473
502
  }
474
- : base.annotation;
503
+ : register;
475
504
  return {
476
505
  ...base,
477
506
  line: line,
@@ -482,7 +511,7 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, cale
482
511
  annotation,
483
512
  };
484
513
  // eslint-disable-next-line react-hooks/exhaustive-deps
485
- }, [base, resolveColor, themeSig, annotationSig]);
514
+ }, [base, resolveColor, compareInk, themeSig, annotationSig, levelSig]);
486
515
  // The trading sessions on this axis, derived from the data rather than from a
487
516
  // calendar. ONE session model with TWO consumers — the axis (which collapses
488
517
  // everything between sessions) and the roll-up grid below (whose buckets must
@@ -1212,7 +1241,13 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = EMPTY_SOURCES, cale
1212
1241
  // density problem — 16 across the top at 1Y, two of them
1213
1242
  // behind our own legend. `false` (not omitted) is required:
1214
1243
  // omitting it auto-labels with the axis formatter.
1215
- label: false, role: a.role, selectable: false }, a.id))), guideLevels(drawable, row.id, (a) => axisOptions?.[a]?.scaleType === 'log').map((g) => (_jsx(Baseline, { id: g.key, value: g.value, axis: g.axis, label: false, selectable: false, role: "guide" }, g.key))), [...visible].reverse().flatMap((c) => {
1244
+ label: false, role: a.role, selectable: false }, a.id))), guideLevels(drawable, row.id, (a) => axisOptions?.[a]?.scaleType === 'log').map((g) => (_jsx(Baseline, { id: g.key, value: g.value, axis: g.axis, label: false, selectable: false, role: "guide" }, g.key))), (() => {
1245
+ const marks = rowLevelMarks(row.levels, drawable, row.id, (a) => axisOptions?.[a]?.scaleType === 'log');
1246
+ return [
1247
+ ...marks.washes.map((w) => (_jsx(Zone, { id: w.key, from: w.from, to: w.to, axis: w.axis, role: w.role }, w.key))),
1248
+ ...marks.lines.map((l) => (_jsx(Baseline, { id: l.key, value: l.value, axis: l.axis, label: l.label, selectable: false, role: l.role }, l.key))),
1249
+ ];
1250
+ })(), [...visible].reverse().flatMap((c) => {
1216
1251
  const src = c.source ? sources[c.source] : undefined;
1217
1252
  // Column-level "show only what the data carries": a config
1218
1253
  // whose column is absent from its (folded) series draws
package/dist/index.d.ts CHANGED
@@ -13,7 +13,8 @@
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, seriesCategoryStyle, seriesLineDashArray, seriesLineWidth, sharedAxisId, type AxisRange, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, fractionTicks, bandColumns, configBand, configColumns, configOutputs, configSpecs, dashPattern, fanIsBand, LINE_DASHES, OUTPUT_DASHES, outputKey, outputLook, publishedColumns, type ConfigOutput, type OutputLook, type OutputStyle, hasBarOutput, offersOutputBars, 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, readsFrom, sourcesOf, } from './series.js';
16
+ export { levelRole, levelRoles, rowLevelMarks, type ChartLevel, type ChartLevelLine, type ChartLevelRange, type ChartLevelStyle, type LevelLineMark, type LevelRoleStyle, type LevelWashMark, } from './levels.js';
17
+ export { configAxisId, effectiveSplit, formatSeriesValue, isStudySeries, LINE_WIDTHS, PAIR_JOINS, PAIR_LENSES, seriesAxisId, readsCompare, isCompareSide, seriesDrawn, seriesCategoryStyle, seriesLineDashArray, seriesLineWidth, sharedAxisId, type AxisRange, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, fractionTicks, bandColumns, configBand, configColumns, configOutputs, configSpecs, dashPattern, fanIsBand, LINE_DASHES, OUTPUT_DASHES, outputKey, outputLook, publishedColumns, type ConfigOutput, type OutputLook, type OutputStyle, hasBarOutput, offersOutputBars, 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, readsFrom, sourcesOf, } from './series.js';
17
18
  export { DEFAULT_CHART_SETTINGS, mergeChartSettings, type AnnotationOverride, type ChartSettings, type CategoryLineStyle, type SessionDividers, type SplitColorDefault, type LineDash, } from './chartSettings.js';
18
19
  export { useMeasuredWidth, useMeasuredSize } from './useMeasuredWidth.js';
19
20
  export { assembleRows, carries, foldKey, foldSources, foldSourcesReport, type SourceFoldReport, prepareChart, sourceFacts, type ConfigRow, type PreparedRow, type SourceFacts, type SourceHold, type SourceInput, type SourceInputs, } from './prepare.js';
package/dist/index.js CHANGED
@@ -12,7 +12,8 @@
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, seriesCategoryStyle, seriesLineDashArray, seriesLineWidth, sharedAxisId, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, fractionTicks, bandColumns, configBand, configColumns, configOutputs, configSpecs, dashPattern, fanIsBand, LINE_DASHES, OUTPUT_DASHES, outputKey, outputLook, publishedColumns, hasBarOutput, offersOutputBars, logAllowed, AXIS_PRECISIONS, readsFrom, sourcesOf, } from './series.js';
15
+ export { levelRole, levelRoles, rowLevelMarks, } from './levels.js';
16
+ export { configAxisId, effectiveSplit, formatSeriesValue, isStudySeries, LINE_WIDTHS, PAIR_JOINS, PAIR_LENSES, seriesAxisId, readsCompare, isCompareSide, seriesDrawn, seriesCategoryStyle, seriesLineDashArray, seriesLineWidth, sharedAxisId, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, fractionTicks, bandColumns, configBand, configColumns, configOutputs, configSpecs, dashPattern, fanIsBand, LINE_DASHES, OUTPUT_DASHES, outputKey, outputLook, publishedColumns, hasBarOutput, offersOutputBars, logAllowed, AXIS_PRECISIONS, readsFrom, sourcesOf, } from './series.js';
16
17
  export { DEFAULT_CHART_SETTINGS, mergeChartSettings, } from './chartSettings.js';
17
18
  export { useMeasuredWidth, useMeasuredSize } from './useMeasuredWidth.js';
18
19
  export { assembleRows, carries, foldKey, foldSources, foldSourcesReport, prepareChart, sourceFacts, } from './prepare.js';
@@ -0,0 +1,147 @@
1
+ /**
2
+ * **Host levels** — horizontal lines a host places on a row, beside the
3
+ * study-catalog guides (`guideLevels`). A level is a value the host already
4
+ * holds, such as the last value of a series or the low and high of a window,
5
+ * drawn across the plot on the axis of a series in that row.
6
+ *
7
+ * Drawn with `@pond-ts/charts`' `<Baseline>` (a level, each edge of a range)
8
+ * and `<Zone>` (a range's wash). Like the guides, they never move an axis:
9
+ * the marks read the axis's scale and do not feed its extent, so the line of a
10
+ * level outside the window is off the plot. A level that should be on screen
11
+ * is the host's to frame (`axisOptions`).
12
+ *
13
+ * How it meets charts' annotation register:
14
+ *
15
+ * - **Ink by role.** `<Baseline>` / `<Zone>` take colour from
16
+ * `theme.annotation.roles[role]` ("colour is a theme concern"), so each level
17
+ * gets its own role ({@link levelRole}), folded into the theme by
18
+ * {@link levelRoles}, the same route `ChartAnnotation.color` takes. The role
19
+ * carries the level's dash, `lineWidth` and wash too.
20
+ * - **`opacity` is the line's opacity.** An inert mark paints at its role's
21
+ * `depth[2]`, so each level's role sets its depth to `[1, 1, 1]`: the line
22
+ * reads at the level's own `opacity`, not at that times the register's
23
+ * resting depth (0.4 in charts' themes) as it did before charts 0.76.
24
+ * - **A chip stays in its row.** Since charts 0.77 `<Baseline>` hides a line
25
+ * and its chip when the value is off the visible y-range, and keeps a chip
26
+ * near the edge inside the row.
27
+ * - **A bare theme keeps its ink.** A theme with no `annotation` gets one
28
+ * holding only the level roles; charts fills the rest from its
29
+ * `defaultAnnotation`, which is what it drew in anyway.
30
+ *
31
+ * Still open upstream: no per-mark colour prop, so a level is one theme role.
32
+ *
33
+ * @module
34
+ */
35
+ import { type SeriesConfig } from './series.js';
36
+ import type { LineDash } from './chartSettings.js';
37
+ /** How a level draws. Every field but `color` is optional. */
38
+ export interface ChartLevelStyle {
39
+ /** A palette key (resolved by the chart's `resolveColor`) or raw CSS. */
40
+ color: string;
41
+ /** Texture. Omitted ⇒ `solid`, whatever the theme's register dash is. */
42
+ lineDash?: LineDash;
43
+ /** `0..1`, folded into the colour: the line's own opacity (see the module
44
+ * note). Composes with the series' dimming. Omitted ⇒ `1`. */
45
+ opacity?: number;
46
+ /** Stroke width in px, for the line (or both edges of a range). Omitted ⇒
47
+ * the theme's annotation `lineWidth`, else `1`. */
48
+ lineWidth?: number;
49
+ }
50
+ /** Shared by both kinds. */
51
+ interface ChartLevelBase extends ChartLevelStyle {
52
+ /** Unique within its row. */
53
+ id: string;
54
+ /**
55
+ * The id of the config in THIS row whose axis the level rides on. It scales
56
+ * with that series, and is hidden while that series is not drawn (hidden, or
57
+ * its column absent). A config in another row draws nothing.
58
+ */
59
+ series: string;
60
+ }
61
+ /** One value: a horizontal line across the plot. */
62
+ export interface ChartLevelLine extends ChartLevelBase {
63
+ kind: 'level';
64
+ value: number;
65
+ /** A chip at the line's left end. Omitted ⇒ no chip. */
66
+ label?: string;
67
+ }
68
+ /** A low and a high: two lines, optionally with a wash between them. */
69
+ export interface ChartLevelRange extends ChartLevelBase {
70
+ kind: 'range';
71
+ low: number;
72
+ high: number;
73
+ /** A chip on each edge. Omitted ⇒ none. */
74
+ labels?: {
75
+ low?: string;
76
+ high?: string;
77
+ };
78
+ /**
79
+ * Opacity (`0..1`) of a wash between the two lines, in the level's colour.
80
+ * Omitted (or `0`) ⇒ the two lines alone. Keep it light: the wash paints
81
+ * over the data, like every annotation. `0.1` is the register's own fill.
82
+ * The level's `opacity` scales it too; the register's depth does not.
83
+ */
84
+ fill?: number;
85
+ }
86
+ /** A host level on a row: one value, or a range. */
87
+ export type ChartLevel = ChartLevelLine | ChartLevelRange;
88
+ /** The theme role a level draws in. Unique per (row, level id). */
89
+ export declare const levelRole: (rowId: string, levelId: string) => string;
90
+ /** One `<Baseline>` to draw. */
91
+ export interface LevelLineMark {
92
+ key: string;
93
+ role: string;
94
+ axis: string;
95
+ value: number;
96
+ /** `false` ⇒ no chip. */
97
+ label: string | false;
98
+ }
99
+ /** One `<Zone>` (a range's wash) to draw. */
100
+ export interface LevelWashMark {
101
+ key: string;
102
+ role: string;
103
+ axis: string;
104
+ from: number;
105
+ to: number;
106
+ }
107
+ /**
108
+ * What a row's host levels draw: one line per level, two per range, and a
109
+ * wash per range with a `fill`. Only levels whose `series` is in `drawn` (the
110
+ * row's drawn configs); each on that config's axis ({@link configAxisId}).
111
+ *
112
+ * A non-finite value draws nothing. On a log axis a value at or below zero
113
+ * draws nothing (as the guides skip theirs), and a range with such an edge
114
+ * keeps its other line but loses its wash.
115
+ */
116
+ export declare function rowLevelMarks(levels: readonly ChartLevel[] | undefined, drawn: readonly SeriesConfig[], rowId: string, isLog?: (axisId: string) => boolean): {
117
+ lines: LevelLineMark[];
118
+ washes: LevelWashMark[];
119
+ };
120
+ /** A role entry, as `theme.annotation.roles` takes it. */
121
+ export interface LevelRoleStyle {
122
+ color: string;
123
+ dash: readonly number[];
124
+ /** Always `[1, 1, 1]`: an inert mark paints at `depth[2]`, and a level's
125
+ * strength is its `opacity`, already in `color`. */
126
+ depth: readonly [number, number, number];
127
+ lineWidth?: number;
128
+ fillOpacity?: number;
129
+ }
130
+ /**
131
+ * The theme roles every host level draws in, keyed by {@link levelRole}. Its
132
+ * colour is resolved and carries the level's `opacity` (and the chart's
133
+ * dimming, when the series it rides on is dimmed, at the same `0.22` a series
134
+ * takes). `dash` is always stated, so a `solid` level stays solid on a theme
135
+ * whose register is dashed, and `depth` is always `[1, 1, 1]`, so the line
136
+ * reads at that colour. `lineWidth` is set only when the level gives one.
137
+ */
138
+ export declare function levelRoles(rows: readonly {
139
+ id: string;
140
+ levels?: readonly ChartLevel[];
141
+ }[], resolveColor: (color: string) => string, dimmed?: ReadonlySet<string>): Record<string, LevelRoleStyle>;
142
+ /** The theme-shaping fields of every row's levels, as one memo key. */
143
+ export declare function levelsSig(rows: readonly {
144
+ id: string;
145
+ levels?: readonly ChartLevel[];
146
+ }[]): string;
147
+ export {};
package/dist/levels.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * **Host levels** — horizontal lines a host places on a row, beside the
3
+ * study-catalog guides (`guideLevels`). A level is a value the host already
4
+ * holds, such as the last value of a series or the low and high of a window,
5
+ * drawn across the plot on the axis of a series in that row.
6
+ *
7
+ * Drawn with `@pond-ts/charts`' `<Baseline>` (a level, each edge of a range)
8
+ * and `<Zone>` (a range's wash). Like the guides, they never move an axis:
9
+ * the marks read the axis's scale and do not feed its extent, so the line of a
10
+ * level outside the window is off the plot. A level that should be on screen
11
+ * is the host's to frame (`axisOptions`).
12
+ *
13
+ * How it meets charts' annotation register:
14
+ *
15
+ * - **Ink by role.** `<Baseline>` / `<Zone>` take colour from
16
+ * `theme.annotation.roles[role]` ("colour is a theme concern"), so each level
17
+ * gets its own role ({@link levelRole}), folded into the theme by
18
+ * {@link levelRoles}, the same route `ChartAnnotation.color` takes. The role
19
+ * carries the level's dash, `lineWidth` and wash too.
20
+ * - **`opacity` is the line's opacity.** An inert mark paints at its role's
21
+ * `depth[2]`, so each level's role sets its depth to `[1, 1, 1]`: the line
22
+ * reads at the level's own `opacity`, not at that times the register's
23
+ * resting depth (0.4 in charts' themes) as it did before charts 0.76.
24
+ * - **A chip stays in its row.** Since charts 0.77 `<Baseline>` hides a line
25
+ * and its chip when the value is off the visible y-range, and keeps a chip
26
+ * near the edge inside the row.
27
+ * - **A bare theme keeps its ink.** A theme with no `annotation` gets one
28
+ * holding only the level roles; charts fills the rest from its
29
+ * `defaultAnnotation`, which is what it drew in anyway.
30
+ *
31
+ * Still open upstream: no per-mark colour prop, so a level is one theme role.
32
+ *
33
+ * @module
34
+ */
35
+ import { configAxisId, dashPattern } from './series.js';
36
+ import { withAlpha } from './withAlpha.js';
37
+ /** The theme role a level draws in. Unique per (row, level id). */
38
+ export const levelRole = (rowId, levelId) => `level\u0000${rowId}\u0000${levelId}`;
39
+ /**
40
+ * What a row's host levels draw: one line per level, two per range, and a
41
+ * wash per range with a `fill`. Only levels whose `series` is in `drawn` (the
42
+ * row's drawn configs); each on that config's axis ({@link configAxisId}).
43
+ *
44
+ * A non-finite value draws nothing. On a log axis a value at or below zero
45
+ * draws nothing (as the guides skip theirs), and a range with such an edge
46
+ * keeps its other line but loses its wash.
47
+ */
48
+ export function rowLevelMarks(levels, drawn, rowId, isLog = () => false) {
49
+ const lines = [];
50
+ const washes = [];
51
+ if (!levels || levels.length === 0)
52
+ return { lines, washes };
53
+ const byId = new Map(drawn.map((c) => [c.id, c]));
54
+ for (const l of levels) {
55
+ const c = byId.get(l.series);
56
+ if (!c)
57
+ continue;
58
+ const axis = configAxisId(rowId, c);
59
+ const log = isLog(axis);
60
+ const ok = (v) => Number.isFinite(v) && !(log && v <= 0);
61
+ const role = levelRole(rowId, l.id);
62
+ // The role doubles as the key: NUL-separated, so no row or level id can
63
+ // collide with another's, nor with a host's own annotation role or id.
64
+ const key = role;
65
+ if (l.kind === 'level') {
66
+ if (ok(l.value))
67
+ lines.push({ key, role, axis, value: l.value, label: l.label || false });
68
+ continue;
69
+ }
70
+ if (ok(l.low))
71
+ lines.push({
72
+ key: `${key}\u0000low`,
73
+ role,
74
+ axis,
75
+ value: l.low,
76
+ label: l.labels?.low || false,
77
+ });
78
+ if (ok(l.high))
79
+ lines.push({
80
+ key: `${key}\u0000high`,
81
+ role,
82
+ axis,
83
+ value: l.high,
84
+ label: l.labels?.high || false,
85
+ });
86
+ if (l.fill !== undefined && l.fill > 0 && ok(l.low) && ok(l.high)) {
87
+ washes.push({ key: `${key}\u0000fill`, role, axis, from: l.low, to: l.high });
88
+ }
89
+ }
90
+ return { lines, washes };
91
+ }
92
+ /** A level's depth ramp: every level at full strength, so `opacity` rules. */
93
+ const LEVEL_DEPTH = [1, 1, 1];
94
+ const unit = (o) => typeof o === 'number' && Number.isFinite(o) ? Math.min(1, Math.max(0, o)) : 1;
95
+ /**
96
+ * The theme roles every host level draws in, keyed by {@link levelRole}. Its
97
+ * colour is resolved and carries the level's `opacity` (and the chart's
98
+ * dimming, when the series it rides on is dimmed, at the same `0.22` a series
99
+ * takes). `dash` is always stated, so a `solid` level stays solid on a theme
100
+ * whose register is dashed, and `depth` is always `[1, 1, 1]`, so the line
101
+ * reads at that colour. `lineWidth` is set only when the level gives one.
102
+ */
103
+ export function levelRoles(rows, resolveColor, dimmed = new Set()) {
104
+ const out = {};
105
+ for (const r of rows) {
106
+ for (const l of r.levels ?? []) {
107
+ const alpha = unit(l.opacity) * (dimmed.has(l.series) ? 0.22 : 1);
108
+ const dash = dashPattern(l.lineDash);
109
+ out[levelRole(r.id, l.id)] = {
110
+ color: withAlpha(resolveColor(l.color), alpha),
111
+ dash: dash ? [...dash] : [],
112
+ depth: LEVEL_DEPTH,
113
+ ...(typeof l.lineWidth === 'number' && Number.isFinite(l.lineWidth) && l.lineWidth > 0
114
+ ? { lineWidth: l.lineWidth }
115
+ : {}),
116
+ ...(l.kind === 'range' && l.fill !== undefined && l.fill > 0
117
+ ? { fillOpacity: unit(l.fill) }
118
+ : {}),
119
+ };
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+ /** The theme-shaping fields of every row's levels, as one memo key. */
125
+ export function levelsSig(rows) {
126
+ return rows
127
+ .flatMap((r) => (r.levels ?? []).map((l) => `${r.id}\u0000${l.id}\u0000${l.series}\u0000${l.color}\u0000${l.lineDash ?? ''}\u0000${l.opacity ?? ''}\u0000${l.lineWidth ?? ''}\u0000${l.kind === 'range' ? (l.fill ?? '') : ''}`))
128
+ .join('|');
129
+ }
package/dist/series.d.ts CHANGED
@@ -610,6 +610,15 @@ export declare function isStudySeries(s: SeriesConfig): boolean;
610
610
  /** True if a series reads the COMPARISON symbol — a spec whose leaves are
611
611
  * `cmp_`-prefixed, or (an unjoined pair's leg) a raw `cmp_` column. */
612
612
  export declare function readsCompare(s: Pick<SeriesConfig, 'derive' | 'column'>): boolean;
613
+ /**
614
+ * True if a series is the **compared side** of a comparison: every leaf it
615
+ * reads is on the comparison symbol (a raw `cmp_` column, or a study whose
616
+ * inputs are all `cmp_`). Narrower than {@link readsCompare}: a joined pair
617
+ * such as `ratio(iv21, cmp_iv21)` reads both symbols, so it is the ANSWER of
618
+ * the comparison, not its "before" — it is dashed (it reads the compare) but
619
+ * keeps its own colour under {@link TimeSeriesChartProps.compareInk}.
620
+ */
621
+ export declare function isCompareSide(s: Pick<SeriesConfig, 'derive' | 'column'>): boolean;
613
622
  /** The style category a series' line defaults come from. A comparison-reading
614
623
  * series takes the `comparisons` category (dashed) whatever else it is — the
615
624
  * texture encodes the SYMBOL, so a study of a compare leg is dashed too. */
package/dist/series.js CHANGED
@@ -151,7 +151,7 @@ export function configColumns(c) {
151
151
  // `@tidal-ts/core` (where the windowing + derive seam live) — imported for
152
152
  // `SeriesConfig` below and re-exported so UI code has one import site for the
153
153
  // series vocabulary.
154
- import { BAND_OUTPUTS, BAR_PRICE_COLUMNS, COMPARE_PREFIX, deriveId, inputNames, isPairOp, isStudyOp, opOutputs, opParams, outputMark, studyLevels, usesCompare, withFanOutput, } from '@tidal-ts/core';
154
+ import { BAND_OUTPUTS, BAR_PRICE_COLUMNS, COMPARE_PREFIX, deriveId, inputNames, isPairOp, isPickedInput, isStudyOp, opOutputs, opParams, outputMark, studyLevels, usesCompare, withFanOutput, } from '@tidal-ts/core';
155
155
  // The app-wide presentation defaults the category resolvers below read.
156
156
  import { DEFAULT_CHART_SETTINGS, } from './chartSettings.js';
157
157
  /** The textures in display order. */
@@ -416,6 +416,29 @@ export function isStudySeries(s) {
416
416
  export function readsCompare(s) {
417
417
  return s.derive ? usesCompare(s.derive) : s.column.startsWith(COMPARE_PREFIX);
418
418
  }
419
+ /**
420
+ * True if a series is the **compared side** of a comparison: every leaf it
421
+ * reads is on the comparison symbol (a raw `cmp_` column, or a study whose
422
+ * inputs are all `cmp_`). Narrower than {@link readsCompare}: a joined pair
423
+ * such as `ratio(iv21, cmp_iv21)` reads both symbols, so it is the ANSWER of
424
+ * the comparison, not its "before" — it is dashed (it reads the compare) but
425
+ * keeps its own colour under {@link TimeSeriesChartProps.compareInk}.
426
+ */
427
+ export function isCompareSide(s) {
428
+ return s.derive ? onlyCompare(s.derive) : s.column.startsWith(COMPARE_PREFIX);
429
+ }
430
+ /** Every leaf of a spec is on the comparison symbol (and it has one) — the
431
+ * "all" twin of core's `usesCompare`, walked the same way. */
432
+ function onlyCompare(spec) {
433
+ // Safe on any persisted shape, as `usesCompare` is.
434
+ if (!spec || typeof spec !== 'object')
435
+ return false;
436
+ const leaves = (spec.inputs ?? []).filter((i) => typeof i === 'string' || (typeof i === 'object' && i !== null));
437
+ return (leaves.length > 0 &&
438
+ leaves.every((i) => typeof i === 'string'
439
+ ? i.startsWith(COMPARE_PREFIX)
440
+ : onlyCompare(isPickedInput(i) ? i.from : i)));
441
+ }
419
442
  /** The style category a series' line defaults come from. A comparison-reading
420
443
  * series takes the `comparisons` category (dashed) whatever else it is — the
421
444
  * texture encodes the SYMBOL, so a study of a compare leg is dashed too. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/chart",
3
- "version": "0.17.0",
3
+ "version": "0.21.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",
@@ -31,20 +31,20 @@
31
31
  "access": "public"
32
32
  },
33
33
  "peerDependencies": {
34
- "@pond-ts/charts": "^0.75.0",
35
- "@pond-ts/financial": "^0.75.0",
36
- "@pond-ts/react": "^0.75.0",
37
- "pond-ts": "^0.75.0",
34
+ "@pond-ts/charts": "^0.78.0",
35
+ "@pond-ts/financial": "^0.78.0",
36
+ "@pond-ts/react": "^0.78.0",
37
+ "pond-ts": "^0.78.0",
38
38
  "react": "^18.2.0 || ^19.0.0"
39
39
  },
40
40
  "dependencies": {
41
- "@tidal-ts/core": "0.17.0"
41
+ "@tidal-ts/core": "0.21.0"
42
42
  },
43
43
  "devDependencies": {
44
- "@pond-ts/charts": "^0.75.0",
45
- "@pond-ts/financial": "^0.75.0",
46
- "@pond-ts/process": "0.75.0",
47
- "@pond-ts/react": "^0.75.0",
44
+ "@pond-ts/charts": "^0.78.0",
45
+ "@pond-ts/financial": "^0.78.0",
46
+ "@pond-ts/process": "0.78.0",
47
+ "@pond-ts/react": "^0.78.0",
48
48
  "@storybook/addon-essentials": "^8.5.0",
49
49
  "@storybook/react": "^8.5.0",
50
50
  "@storybook/react-vite": "^8.5.0",
@@ -52,7 +52,7 @@
52
52
  "@types/react-dom": "^18.3.5",
53
53
  "@types/react-test-renderer": "^18.3.1",
54
54
  "@vitejs/plugin-react": "^4.3.4",
55
- "pond-ts": "^0.75.0",
55
+ "pond-ts": "^0.78.0",
56
56
  "react": "^18.3.1",
57
57
  "react-dom": "^18.3.1",
58
58
  "react-test-renderer": "^18.3.1",