@tidal-ts/chart 0.8.0 → 0.10.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.72.0
24
- npm install pond-ts@~0.72.0 @pond-ts/financial@~0.72.0 @pond-ts/charts@~0.72.0 @pond-ts/react@~0.72.0
23
+ npm install --save-exact @tidal-ts/core @tidal-ts/chart @pond-ts/process@0.73.0
24
+ npm install pond-ts@~0.73.0 @pond-ts/financial@~0.73.0 @pond-ts/charts@~0.73.0 @pond-ts/react@~0.73.0
25
25
  ```
26
26
 
27
27
  React 18 or 19. The pond packages are peer dependencies: install them once, on
@@ -2,11 +2,12 @@ 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, CrosshairCursor, Layers, LineChart, Baseline, 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, sliceBySegments, WINDOW_MS, autoBarWindow, opOutputs, outputMark, } from '@tidal-ts/core';
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
+ import { withAlpha } from './withAlpha.js';
8
9
  import { DEFAULT_CHART_SETTINGS } from './chartSettings.js';
9
- import { configAxisId, guideLevels, seriesDrawn, DASH_PATTERN, effectiveSplit, seriesAxisId, seriesLineDashArray, seriesLineWidth, sharedAxisId, axisFormat, fractionTicks, bandColumns, outputKey, configColumns, } from './series.js';
10
+ import { configAxisId, guideLevels, seriesDrawn, configBand, configOutputs, dashPattern, outputLook, effectiveSplit, seriesAxisId, seriesLineDashArray, seriesLineWidth, sharedAxisId, axisFormat, fractionTicks, outputKey, configColumns, } from './series.js';
10
11
  /** The schema-erased series type every layer reads. Rows carry heterogeneous
11
12
  * sources (vol `%`, price `$`), so the chart works in the erased schema and each
12
13
  * config names its `column`. Callers build the {@link TimeSeriesChartProps.sources} map
@@ -19,16 +20,6 @@ const WEEKEND_SKIP = weekendSkip();
19
20
  /** Stable empty default: a fresh `[]` per render would re-run the sessions memo
20
21
  * (and rebuild the container's scale) on every frame. */
21
22
  const EMPTY_DAYS = [];
22
- /** Dash ladders for a multi-output study's 2nd..Nth line. Distinguishable at a
23
- * glance and ordered so a longer dash reads as "further from the main output".
24
- * Cycles past the end — a 12-output ribbon (`guppy`) wants a colour ramp
25
- * rather than twelve dashes, which is a named TDL-STUDYDRAW case. */
26
- const OUTPUT_DASHES = [
27
- [6, 3],
28
- [2, 2],
29
- [9, 3, 2, 3],
30
- [1, 3],
31
- ];
32
23
  const EMPTY_ANNOTATIONS = [];
33
24
  const EMPTY_SOURCES = [];
34
25
  /**
@@ -120,21 +111,8 @@ function hoverInk(color, scheme) {
120
111
  const [r, g, b] = rgb.map((v) => Math.round(v + (target - v) * HOVER_LIFT));
121
112
  return `rgb(${r}, ${g}, ${b})`;
122
113
  }
123
- /** #rgb / #rrggbb → rgba() with the given alpha (for dimming a series). Falls
124
- * back to the input unchanged for any other color form (dim just no-ops). */
125
- function withAlpha(hex, alpha) {
126
- let h = hex.trim().replace(/^#/, '');
127
- if (h.length === 3)
128
- h = h
129
- .split('')
130
- .map((c) => c + c)
131
- .join('');
132
- const m = /^([\da-f]{6})$/i.exec(h);
133
- if (!m)
134
- return hex;
135
- const n = parseInt(m[1], 16);
136
- return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
137
- }
114
+ /** A config's own opacity, clamped to `0..1` (persisted state is untyped). */
115
+ const opacityOf = (o) => typeof o === 'number' && Number.isFinite(o) ? Math.min(1, Math.max(0, o)) : 1;
138
116
  /** A row's per-side SHARED axis id — unique across the container so each row
139
117
  * scales independently. Now the exported `sharedAxisId` (series.ts): the
140
118
  * machine keys range state and the host builds the panel model with the same
@@ -352,7 +330,9 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
352
330
  const themeSig = allConfigs
353
331
  .map((c) => {
354
332
  const sp = effectiveSplit(c, settings);
355
- return `${c.id}:${c.color}:${sp.mode}:${sp.rise}:${sp.fall}:${c.style}:${seriesLineWidth(c, settings)}`;
333
+ // The per-output ink, texture and opacity too — and the FAN, whose
334
+ // outputs are what the per-output keys are named after.
335
+ return `${c.id}:${c.color}:${sp.mode}:${sp.rise}:${sp.fall}:${c.style}:${seriesLineWidth(c, settings)}:${c.lineDash ?? ''}:${c.opacity ?? ''}:${c.fan?.join(',') ?? ''}:${c.outputStyles ? JSON.stringify(c.outputStyles) : ''}`;
356
336
  })
357
337
  .join('|') +
358
338
  '#' +
@@ -379,17 +359,22 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
379
359
  for (const c of allConfigs) {
380
360
  const stroke = resolveColor(c.color);
381
361
  const isDim = dim.has(c.id);
382
- const color = isDim ? withAlpha(stroke, 0.22) : stroke;
362
+ // The user's opacity and the chart's dimming compose: a half-opaque line
363
+ // that is also dimmed is fainter still, never back to full strength.
364
+ const own = opacityOf(c.opacity);
365
+ const alpha = own * (isDim ? 0.22 : 1);
366
+ const color = withAlpha(stroke, alpha);
383
367
  const width = seriesLineWidth(c, settings);
384
368
  const dash = seriesLineDashArray(c, settings);
385
369
  line[c.id] = { color, width, ...(dash ? { dash: [...dash] } : {}) };
386
370
  // The comparison counterpart shares the color + axis but takes the
387
371
  // `comparisons` category's own weight + texture (dashed by default —
388
372
  // texture encodes primary-vs-compare). Dims with its primary.
373
+ const cmpDash = dashPattern(settings.comparisons.dash);
389
374
  line[`${c.id}__cmp`] = {
390
375
  color,
391
376
  width: settings.comparisons.weight,
392
- ...(settings.comparisons.dash === 'dashed' ? { dash: [...DASH_PATTERN] } : {}),
377
+ ...(cmpDash ? { dash: [...cmpDash] } : {}),
393
378
  };
394
379
  // Area fill wants a solid hex for its gradient, so dim via fillOpacity (not
395
380
  // an rgba fill); the outline still carries the dim.
@@ -398,37 +383,44 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
398
383
  color,
399
384
  width,
400
385
  fill: stroke,
401
- fillOpacity: isDim ? 0.04 : 0.14,
386
+ fillOpacity: (isDim ? 0.04 : 0.14) * own,
402
387
  };
403
388
  // A band is a WASH, not a fill under a line: it carries no outline of its
404
389
  // own (the middle band draws that, as an ordinary line under the same
405
390
  // id), so it wants to read as a tinted region and nothing else. 0.16 sits
406
391
  // where the earnings band landed — unmistakably a region, still quiet
407
392
  // enough that a line crossing it stays the brighter thing.
408
- band[c.id] = { fill: stroke, opacity: isDim ? 0.04 : 0.16 };
409
- // A multi-output study's N lines: ONE colour, N textures. A study's
410
- // outputs are one series (a MACD is one study), so spending N palette
411
- // colours on them would fight "colour = series" and make three studies
412
- // look like nine. The first output is the study's own line; each later one
413
- // takes a longer dash and a hair less weight, so the stack reads as
414
- // primary-and-derived rather than as peers. Same shape as `__cmp`.
415
- if (c.style === 'lines' && c.derive) {
416
- const op = c.derive.op;
417
- opOutputs(op).forEach((suffix, i) => {
393
+ band[c.id] = { fill: stroke, opacity: (isDim ? 0.04 : 0.16) * own };
394
+ // Each output of a multi-output config takes its own ink (`outputLook`):
395
+ // by default ONE colour, N textures — a study's outputs are one series (a
396
+ // MACD is one study), so spending N palette colours on them would fight
397
+ // "colour = series" — and whatever the user has set per output on top.
398
+ // A band's one line (its centre) draws under `c.id`, so its look lands
399
+ // there; a stack's lines each get their own key.
400
+ if ((c.style === 'lines' && c.derive) || c.style === 'band') {
401
+ configOutputs(c).forEach((out, i) => {
402
+ const look = outputLook(c, i, settings);
403
+ const ink = withAlpha(resolveColor(look.color), opacityOf(look.opacity) * (isDim ? 0.22 : 1));
404
+ const style = {
405
+ color: ink,
406
+ width: look.width,
407
+ ...(look.dash ? { dash: [...look.dash] } : {}),
408
+ };
409
+ if (c.style === 'band') {
410
+ if (out.name === 'Middle')
411
+ line[c.id] = style;
412
+ return;
413
+ }
418
414
  const key = outputKey(c.id, i);
419
- if (outputMark(op, suffix) === 'bar') {
415
+ if (out.mark === 'bar') {
420
416
  // A histogram in the STUDY's colour, not a rise/fall pair: green and
421
417
  // red are reserved for market data (P&L, bid/ask), never for an
422
418
  // indicator. The sign is legible from which side of zero the bar
423
419
  // sits on, which is the reading anyway.
424
- bar[key] = { ...base.bar.default, fill: color, highlight: color };
420
+ bar[key] = { ...base.bar.default, fill: ink, highlight: ink };
425
421
  return;
426
422
  }
427
- line[key] = {
428
- color,
429
- width: i === 0 ? width : Math.max(1, width - 0.5),
430
- ...(i === 0 ? {} : { dash: [...OUTPUT_DASHES[(i - 1) % OUTPUT_DASHES.length]] }),
431
- };
423
+ line[key] = style;
432
424
  });
433
425
  }
434
426
  // Direction-capable marks: a split bar draws its rise fill under `c.id` and
@@ -439,8 +431,8 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
439
431
  if (sp.mode === 'split') {
440
432
  const rise = resolveColor(sp.rise);
441
433
  const fall = resolveColor(sp.fall);
442
- const riseC = isDim ? withAlpha(rise, 0.22) : rise;
443
- const fallC = isDim ? withAlpha(fall, 0.22) : fall;
434
+ const riseC = withAlpha(rise, alpha);
435
+ const fallC = withAlpha(fall, alpha);
444
436
  bar[c.id] = { ...base.bar.default, fill: riseC, highlight: riseC };
445
437
  bar[`${c.id}__down`] = { ...base.bar.default, fill: fallC, highlight: fallC };
446
438
  if (c.style === 'candle')
@@ -683,7 +675,7 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
683
675
  //
684
676
  // Only the line-ish styles want this. A candle spans `[open, close]` and draws
685
677
  // from the open, so the same row wants a different x per style — which is why the
686
- // shift lives here, per layer, rather than in the fetch.
678
+ // shift lives on the layer (charts' `xOffset`, 0.73) rather than in the fetch.
687
679
  //
688
680
  // DAILY IS NOT EXEMPT, though I first thought it should be. The objection was
689
681
  // that shifting would put Friday's close on Saturday — but a daily stamp is a
@@ -695,15 +687,26 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
695
687
  //
696
688
  // Leaving daily out also cost a fifth of every week: the segment runs one bar
697
689
  // past its last key, so Fri 00:00Z → Sat 00:00Z was live axis with no line on it.
698
- const shifted = useMemo(() => {
690
+ //
691
+ // A line, area or band takes `xOffset={native}` and moves its own copy of the
692
+ // key. `<BarChart>` has no `xOffset`, so a study's histogram — which must sit
693
+ // under the lines it explains — draws from a moved copy instead: pond's
694
+ // `offsetTime` (via `shiftKeys`), value columns shared. Lazy, because most
695
+ // renders draw no histogram, and cached per source identity.
696
+ const histSeriesFor = useMemo(() => {
699
697
  const out = new Map();
700
- for (const [key, src] of Object.entries(sources ?? {})) {
701
- const native = nativeMs(src);
702
- if (native === undefined)
703
- continue;
704
- out.set(key, shiftKeys(src, native));
705
- }
706
- return out;
698
+ return (key) => {
699
+ const hit = out.get(key);
700
+ if (hit)
701
+ return hit;
702
+ const src = sources?.[key];
703
+ const native = src ? nativeMs(src) : undefined;
704
+ if (!src || native === undefined)
705
+ return undefined;
706
+ const moved = shiftKeys(src, native);
707
+ out.set(key, moved);
708
+ return moved;
709
+ };
707
710
  }, [sources]);
708
711
  // …and where the source carries an OPEN, the line can start at the session open
709
712
  // instead of a minute inside it. `sessionOpenLine` emits one column named `close`
@@ -711,7 +714,8 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
711
714
  // the line spans the whole live segment rather than beginning after it.
712
715
  //
713
716
  // Price only. A vol series has no open to start from, so its line keeps the
714
- // shifted closes and legitimately begins one bar in.
717
+ // end-offset closes and legitimately begins one bar in. This series is already
718
+ // in drawn time, so it takes no `xOffset`.
715
719
  const openLine = useMemo(() => {
716
720
  const out = new Map();
717
721
  for (const key of ohlc) {
@@ -799,43 +803,6 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
799
803
  }, [sources]);
800
804
  /** Whether this config's layers break at the session seams. */
801
805
  const breaksFor = (c) => intraday && settings.sessions.breaks && !coarse.has(c.source ?? '');
802
- /** …and whether a FILL has to be split to do so: only when there are seams. */
803
- const splitsFor = (c) => breaksFor(c) && sessions.length > 1;
804
- // One sub-series per live segment, for the one layer pond gives no
805
- // `sessionBreaks` (`<AreaChart>`; `<BandChart>` got it in charts 0.70.0).
806
- // Lazy and cached on the series object: slicing a 250k-row series into ~250
807
- // sessions is real work, and most renders draw no fill at all. The cache
808
- // resets with the segments.
809
- const { segmentsFor, endSegmentsFor } = useMemo(() => {
810
- const raw = new Map();
811
- const end = new Map();
812
- const segmentsFor = (series) => {
813
- let slices = raw.get(series);
814
- if (!slices) {
815
- slices = sliceBySegments(series, sessions);
816
- raw.set(series, slices);
817
- }
818
- return slices;
819
- };
820
- // The same slices moved to the bar's END — cut first, shifted after, and
821
- // cached like the raw ones: a fill that is re-shifted on every frame of a
822
- // pan hands pond a fresh series identity per slice per frame. Only the area
823
- // still needs these — `<AreaChart>` has no `sessionBreaks` (F-charts-20);
824
- // `<BandChart>` gained it in charts 0.70.0.
825
- const endSegmentsFor = (series) => {
826
- let slices = end.get(series);
827
- if (!slices) {
828
- const native = nativeMs(series);
829
- slices =
830
- native === undefined
831
- ? segmentsFor(series)
832
- : segmentsFor(series).map((slice) => shiftKeys(slice, native));
833
- end.set(series, slices);
834
- }
835
- return slices;
836
- };
837
- return { segmentsFor, endSegmentsFor };
838
- }, [sessions]);
839
806
  const discontinuities = useMemo(() => !collapseWeekends
840
807
  ? undefined
841
808
  : sessions.length
@@ -853,54 +820,35 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
853
820
  // own z slot. Keys are explicit for the same reason.
854
821
  const layer = (c, panelSeries, axis, candleable) => {
855
822
  const col = c.column;
856
- // A line/area draws CLOSES, which belong at their bar's end — see `shifted`,
857
- // and daily is not exempt. For the price column of an OHLC source it can do
858
- // better still and start at the session's open (`openLine`). Both fall back
859
- // to the raw series only when no bar interval can be inferred.
860
- const closeSeries = (c.source && col === 'close' ? openLine.get(c.source) : undefined) ??
861
- (c.source ? shifted.get(c.source) : undefined) ??
862
- panelSeries;
863
- // Every OTHER line-like mark belongs at its bar's end too — a band's edges
864
- // and middle, a study's outputs — or a banded curve leads the plain line
865
- // beside it by one bar, visibly at every seam. Same shift as `closeSeries`,
866
- // minus the open-line case: only a price column has an open to start from.
867
- // Per-segment slices come from `endSegmentsFor`: cut from the RAW series
868
- // and shifted after (shifted first, a session's last close sits on the
869
- // segment end), and cached.
823
+ // Every line-like mark draws at its bar's END — a close, a band's edges and
824
+ // middle, a study's outputs — or a banded curve leads the plain line beside
825
+ // it by one bar, visibly at every seam; daily is not exempt (see
826
+ // `histSeriesFor`). The layer does the move: the source series with
827
+ // `xOffset` one bar. Without an inferable bar interval it draws the panel's
828
+ // series at its keys.
870
829
  const src = c.source ? sources[c.source] : undefined;
871
830
  const native = src ? nativeMs(src) : undefined;
872
- const endSeries = (c.source ? shifted.get(c.source) : undefined) ?? panelSeries;
831
+ const endSeries = native !== undefined ? src : panelSeries;
832
+ // For the price column of an OHLC source the line does better still and
833
+ // starts at the session's open (`openLine`), a series already in drawn time.
834
+ const openSeries = c.source && col === 'close' ? openLine.get(c.source) : undefined;
835
+ const closeSeries = openSeries ?? endSeries;
836
+ const closeOffset = openSeries ? undefined : native;
873
837
  switch (c.style) {
874
- case 'area': {
875
- // No `sessionBreaks` on `<AreaChart>` — the prop is LineChart-only
876
- // (F-charts-20), so the break is made here: one layer per live segment,
877
- // and the fill ends at the close and restarts at the open like the line
878
- // would. One layer when nothing collapses.
838
+ case 'area':
839
+ // Breaks at the session seams like the line drawn over it — the fill
840
+ // ends at the close and restarts at the open (`<AreaChart
841
+ // sessionBreaks>`, charts 0.73; this was one layer per segment before).
879
842
  //
880
- // Cut the RAW series, then shift each slice — never the reverse. The
881
- // segments come from unshifted keys, so a shifted session's last close
882
- // sits exactly on its segment end and the half-open cut would drop it:
883
- // the fill would stop one bar before the line it is meant to agree with,
884
- // at every seam.
885
- if (!splitsFor(c)) {
886
- // `baseline="floor"`: since charts 0.71 an area fills to zero by
887
- // default, and on an axis the library auto-fits (no `min`/`max` from
888
- // the host, or a flat series a host hands back to the fit) that pulls
889
- // 0 into the domain. On a pinned axis the two draw the same, because
890
- // the baseline clamps to the edge. The fill rests on the floor, as
891
- // before, whichever way the host fits.
892
- return [
893
- _jsx(AreaChart, { series: closeSeries, column: col, as: c.id, axis: axis, baseline: "floor" }, c.id),
894
- ];
895
- }
896
- // The price close gets the open-line treatment per slice (one source,
897
- // so uncached is cheap); everything else takes the cached end-shifted
898
- // slices.
899
- const slices = native !== undefined && c.source && col === 'close' && ohlc.has(c.source)
900
- ? segmentsFor(panelSeries).map((slice) => sessionOpenLine(slice, native, { open: 'open', close: 'close' }))
901
- : endSegmentsFor(panelSeries);
902
- return slices.map((slice, i) => (_jsx(AreaChart, { series: slice, column: col, as: c.id, axis: axis, baseline: "floor" }, `${c.id}__s${i}`)));
903
- }
843
+ // No `baseline`: since charts 0.73 the baseline only says where the fill
844
+ // rests and no longer widens an auto-fitted axis. So the fill shades
845
+ // toward zero inside the axis it has: a series wholly above zero rests on
846
+ // the floor, a signed one (a skew, a spread) shades to the zero line, and
847
+ // one wholly below zero hangs from the top edge — zero clamps to the
848
+ // nearest edge.
849
+ return [
850
+ _jsx(AreaChart, { series: closeSeries, column: col, as: c.id, axis: axis, xOffset: closeOffset, sessionBreaks: breaksFor(c) }, c.id),
851
+ ];
904
852
  case 'bar': {
905
853
  const s = derived.bar.get(c.id);
906
854
  if (!s)
@@ -933,7 +881,7 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
933
881
  showOHLC: true }, c.id),
934
882
  ]
935
883
  : [
936
- _jsx(LineChart, { series: closeSeries, column: col, as: c.id, axis: axis, sessionBreaks: intraday && settings.sessions.breaks && !coarse.has(c.source ?? '') }, c.id),
884
+ _jsx(LineChart, { series: closeSeries, column: col, as: c.id, axis: axis, xOffset: closeOffset, sessionBreaks: breaksFor(c) }, c.id),
937
885
  ];
938
886
  case 'band': {
939
887
  // A band is TWO layers for ONE config — the wash between the edges, and
@@ -951,10 +899,16 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
951
899
  // Both break at the session seams together — `<BandChart sessionBreaks>`
952
900
  // arrived in charts 0.70.0 with the same semantics as the line's, which
953
901
  // retired this chart's one-wash-per-segment workaround (0.2.0).
954
- const b = bandColumns(col);
902
+ // A FANNED band (an SMA of a band's two edges) may have no centre: it
903
+ // draws its wash and nothing else.
904
+ const b = configBand(c);
955
905
  return [
956
- _jsx(BandChart, { series: endSeries, lower: b.lower, upper: b.upper, as: c.id, axis: axis, sessionBreaks: breaksFor(c) }, `${c.id}__band`),
957
- _jsx(LineChart, { series: endSeries, column: b.middle, as: c.id, axis: axis, sessionBreaks: breaksFor(c) }, c.id),
906
+ _jsx(BandChart, { series: endSeries, lower: b.lower, upper: b.upper, as: c.id, axis: axis, xOffset: native, sessionBreaks: breaksFor(c) }, `${c.id}__band`),
907
+ ...(b.middle
908
+ ? [
909
+ _jsx(LineChart, { series: endSeries, column: b.middle, as: c.id, axis: axis, xOffset: native, sessionBreaks: breaksFor(c) }, c.id),
910
+ ]
911
+ : []),
958
912
  ];
959
913
  }
960
914
  case 'lines': {
@@ -964,20 +918,22 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
964
918
  // exactly as for a band.
965
919
  if (!c.derive)
966
920
  return [];
967
- const op = c.derive.op;
968
921
  const histSplit = effectiveSplit(c, settings);
969
- const layers = opOutputs(op).map((suffix, i) => ({
970
- mark: outputMark(op, suffix),
971
- node: outputMark(op, suffix) === 'bar' ? (
972
- // On the SAME series as the study's lines: a point-keyed bar is
973
- // centred on its key, so a histogram left on the raw keys would
974
- // put its zero-cross one bar left of the line-cross it exists to
975
- // mark.
976
- _jsx(BarChart, { series: endSeries, column: `${col}${suffix}`, as: outputKey(c.id, i), axis: axis, ...(histSplit.mode === 'split'
922
+ const histSeries = (c.source ? histSeriesFor(c.source) : undefined) ?? panelSeries;
923
+ // One per OUTPUT (`configOutputs`): a multi-output op's declared
924
+ // suffixes, or a fanned study's one line per source output it runs on.
925
+ const layers = configOutputs(c).map((out, i) => ({
926
+ mark: out.mark,
927
+ node: out.mark === 'bar' ? (
928
+ // At the SAME x as the study's lines: a point-keyed bar is centred
929
+ // on its key, so a histogram left on the raw keys would put its
930
+ // zero-cross one bar left of the line-cross it exists to mark.
931
+ // `<BarChart>` has no `xOffset`, hence the moved copy.
932
+ _jsx(BarChart, { series: histSeries, column: out.column, as: outputKey(c.id, i), axis: axis, ...(histSplit.mode === 'split'
977
933
  ? {
978
- binColors: signColors(endSeries, `${col}${suffix}`, resolveColor(histSplit.rise), resolveColor(histSplit.fall)),
934
+ binColors: signColors(histSeries, out.column, resolveColor(histSplit.rise), resolveColor(histSplit.fall)),
979
935
  }
980
- : {}) }, `${c.id}__o${i}`)) : (_jsx(LineChart, { series: endSeries, column: `${col}${suffix}`, as: outputKey(c.id, i), axis: axis, sessionBreaks: intraday && settings.sessions.breaks && !coarse.has(c.source ?? '') }, `${c.id}__o${i}`)),
936
+ : {}) }, `${c.id}__o${i}`)) : (_jsx(LineChart, { series: endSeries, column: out.column, as: outputKey(c.id, i), axis: axis, xOffset: native, sessionBreaks: breaksFor(c) }, `${c.id}__o${i}`)),
981
937
  }));
982
938
  // Bars UNDER lines. `<Layers>` z-orders by position, and a MACD's
983
939
  // histogram is context for its two lines — drawn over them it would
@@ -989,7 +945,7 @@ function TimeSeriesChartInner({ rows, sources, ohlcSources = [], calendarDays =
989
945
  }
990
946
  default:
991
947
  return [
992
- _jsx(LineChart, { series: closeSeries, column: col, as: c.id, axis: axis, sessionBreaks: intraday && settings.sessions.breaks && !coarse.has(c.source ?? '') }, c.id),
948
+ _jsx(LineChart, { series: closeSeries, column: col, as: c.id, axis: axis, xOffset: closeOffset, sessionBreaks: breaksFor(c) }, c.id),
993
949
  ];
994
950
  }
995
951
  };
@@ -13,7 +13,7 @@
13
13
  * settings however it likes. Presentational components receive them as
14
14
  * **props** (props in, events out).
15
15
  */
16
- export type LineDash = 'solid' | 'dashed';
16
+ export type LineDash = 'solid' | 'dashed' | 'dotted';
17
17
  /** One line category's presentation default: stroke style + weight (px). */
18
18
  export interface CategoryLineStyle {
19
19
  dash: LineDash;
@@ -48,7 +48,7 @@ export function mergeChartSettings(stored) {
48
48
  // read as a data bug) — out-of-range falls back to the default.
49
49
  const w = o.weight;
50
50
  return {
51
- dash: o.dash === 'solid' || o.dash === 'dashed' ? o.dash : base.dash,
51
+ dash: o.dash === 'solid' || o.dash === 'dashed' || o.dash === 'dotted' ? o.dash : base.dash,
52
52
  weight: typeof w === 'number' && Number.isFinite(w) && w > 0 && w <= 8 ? w : base.weight,
53
53
  };
54
54
  };
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, 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, readsFrom, sourcesOf, } from './series.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, 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
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 SourceHold, 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, fractionTicks, bandColumns, configColumns, hasBarOutput, logAllowed, AXIS_PRECISIONS, readsFrom, sourcesOf, } from './series.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, logAllowed, AXIS_PRECISIONS, readsFrom, sourcesOf, } 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/prepare.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { applyDerived, COMPARE_PREFIX, holdAcrossGrid, joinUnderPrefix, usesCompare, } from '@tidal-ts/core';
2
- import { configColumns } from './series.js';
2
+ import { configColumns, configSpecs } from './series.js';
3
3
  import { finiteColumns, lastRow } from './seriesFacts.js';
4
4
  /** The series with one row per key, the last of each run: a restatement
5
5
  * replaces the row before it. The key scan is cheap, so a series without
@@ -13,9 +13,10 @@ const lastPerKey = (series) => {
13
13
  };
14
14
  const specsBySource = (configs) => {
15
15
  const m = {};
16
+ // `configSpecs`: a FANNED study folds one spec per output it runs on.
16
17
  for (const c of configs)
17
18
  if (c.derive && c.source)
18
- (m[c.source] ??= []).push(c.derive);
19
+ (m[c.source] ??= []).push(...configSpecs(c));
19
20
  return m;
20
21
  };
21
22
  /** Sources with a config reading a RAW compare column — a split pair's leg,
package/dist/series.d.ts CHANGED
@@ -32,7 +32,7 @@ export declare function bandColumns(column: string): {
32
32
  * the toggle on a study with nothing to colour would be a control that does
33
33
  * nothing.
34
34
  */
35
- export declare function hasBarOutput(c: Pick<SeriesConfig, 'style' | 'derive'>): boolean;
35
+ export declare function hasBarOutput(c: Pick<SeriesConfig, 'style' | 'derive' | 'column' | 'fan'>): boolean;
36
36
  /**
37
37
  * The per-output theme key for a `lines` config.
38
38
  *
@@ -43,25 +43,76 @@ export declare function hasBarOutput(c: Pick<SeriesConfig, 'style' | 'derive'>):
43
43
  */
44
44
  export declare const outputKey: (id: string, i: number) => string;
45
45
  /**
46
- * The columns a config actually reads — one for most styles, three for a
47
- * `band`, and one per declared output for `lines`.
46
+ * One drawn output of a config — its NAME (the declared suffix, or for a
47
+ * fanned study the source output it runs on), the column it reads, and its
48
+ * mark. Index-aligned with {@link outputKey}.
49
+ */
50
+ export interface ConfigOutput {
51
+ /** `''` for a single-output config; `'Upper'`, `'Signal'`, … otherwise. */
52
+ name: string;
53
+ column: string;
54
+ mark: 'line' | 'bar';
55
+ }
56
+ /**
57
+ * The outputs a config draws, in order — the one answer to "what lines does
58
+ * this config put on the canvas, and what is each called?".
59
+ *
60
+ * Three shapes:
61
+ *
62
+ * - **A fanned study** ({@link SeriesConfig.fan}): one output per source output
63
+ * it runs on, each its own spec (`withFanOutput`) and so its own column.
64
+ * - **A multi-output op**: one per declared suffix, named off the spec id.
65
+ * - **Anything else**: its one column, unnamed.
66
+ *
67
+ * A config whose `derive` is gone degrades to its bare column rather than
68
+ * throwing (a persisted config can outlive the op that named it).
69
+ */
70
+ export declare function configOutputs(c: Pick<SeriesConfig, 'column' | 'derive' | 'fan'>): ConfigOutput[];
71
+ /**
72
+ * The columns a `band` config draws between (and its centre line, when it has
73
+ * one). A fanned band — an SMA of a band's `Upper` and `Lower` — may have no
74
+ * centre at all; an op's own band always does (`bandColumns`).
75
+ */
76
+ export declare function configBand(c: Pick<SeriesConfig, 'column' | 'derive' | 'fan'>): {
77
+ middle?: string;
78
+ upper: string;
79
+ lower: string;
80
+ };
81
+ /**
82
+ * Whether a fan over `outputs` draws as a BAND: it runs on a band's two edges.
83
+ * A centre is optional — smoothing a band's bounds is still a band.
84
+ */
85
+ export declare const fanIsBand: (outputs: readonly string[]) => boolean;
86
+ /**
87
+ * The specs a config folds — one, or one per output of a fanned study. The
88
+ * prepare step folds every one of them, so each fanned line has a column.
89
+ */
90
+ export declare function configSpecs(c: Pick<SeriesConfig, 'derive' | 'fan'>): DeriveSpec[];
91
+ /**
92
+ * The columns OTHER configs can be built on — what a study of this one may
93
+ * read. A config's `column`, and for a fanned study each of its lines' too:
94
+ * an EMA of the `Lower` line of a fanned SMA reads that line's column, not
95
+ * the `Upper` one the config is named by.
96
+ */
97
+ export declare function publishedColumns(c: Pick<SeriesConfig, 'column' | 'derive' | 'fan'>): string[];
98
+ /**
99
+ * The columns a config actually reads — one for most styles, two or three for
100
+ * a `band`, and one per output for `lines`.
48
101
  *
49
102
  * The single place that answers "what data does this config touch?", so a new
50
- * multi-output study doesn't have to be found in five scanners. A `lines`
51
- * config needs its `derive` to answer, because the suffixes come from the op's
52
- * declaration; without one it degrades to its bare column rather than throwing
53
- * (a persisted config can outlive the op that named it).
103
+ * multi-output study doesn't have to be found in five scanners.
54
104
  */
55
105
  export declare function configColumns(c: {
56
106
  column: string;
57
107
  style: SeriesStyle;
58
108
  derive?: DeriveSpec;
109
+ fan?: readonly string[];
59
110
  }): string[];
60
111
  import type { DeriveSpec, SeriesWindow } from '@tidal-ts/core';
61
112
  export type { DeriveSpec, SeriesWindow };
62
113
  import type { CandleVariant, ColorBy } from '@pond-ts/charts';
63
114
  export type { CandleVariant, ColorBy };
64
- import { type CategoryLineStyle, type ChartSettings } from './chartSettings.js';
115
+ import { type CategoryLineStyle, type ChartSettings, type LineDash } from './chartSettings.js';
65
116
  /**
66
117
  * One seated series.
67
118
  *
@@ -182,6 +233,47 @@ export interface SeriesConfig {
182
233
  * keys / raw CSS). Omitted ⇒ the chart settings' defaults. */
183
234
  riseColor?: string;
184
235
  fallColor?: string;
236
+ /** The line's texture. Omitted ⇒ the category default from the chart
237
+ * settings (see {@link seriesLineDashArray}). A comparison-reading series
238
+ * keeps its own texture: there, dashing is what says "the other symbol". */
239
+ lineDash?: LineDash;
240
+ /** How opaque the series draws, `0..1`. Omitted ⇒ `1`. Multiplies with the
241
+ * chart's own dimming and with a fill's own translucency, so a half-opaque
242
+ * band is half as strong a wash, not an opaque one. A LINE fades only when
243
+ * its colour resolves to hex or `rgb()`/`rgba()`; another form (`hsl()`, a
244
+ * named colour, `var()`) draws at full strength — resolve to hex to fade. */
245
+ opacity?: number;
246
+ /**
247
+ * Per-OUTPUT ink for a config that draws several lines (a MACD's `Signal`, a
248
+ * band's `Middle`, one line of a fanned study), keyed by the output's name
249
+ * ({@link ConfigOutput.name}). Every field falls back to the config's own,
250
+ * then to the output's default texture — so an empty entry changes nothing,
251
+ * and a study recoloured as a whole still recolours every output it has not
252
+ * been told otherwise about.
253
+ */
254
+ outputStyles?: Readonly<Record<string, OutputStyle>>;
255
+ /**
256
+ * The outputs of its multi-output source this study runs on, when it runs on
257
+ * MORE than one — an SMA of a band's `Upper` and `Lower` is one study drawing
258
+ * two smoothed edges, not two studies.
259
+ *
260
+ * `derive` reads the first of them, so `column` and every single-spec reader
261
+ * (params, labels, the panel) keep working unchanged; each other output's
262
+ * spec is the same chain with the bottom pick swapped (`withFanOutput`), so a
263
+ * retune moves every line together. Absent ⇒ the one output `derive` picks.
264
+ * A fan over a band's two edges draws as a `band`; anything else as `lines`.
265
+ */
266
+ fan?: readonly string[];
267
+ }
268
+ /** The textures in display order. */
269
+ export declare const LINE_DASHES: readonly LineDash[];
270
+ /** Ink for ONE output of a multi-output config — see
271
+ * {@link SeriesConfig.outputStyles}. Every field is an override. */
272
+ export interface OutputStyle {
273
+ color?: string;
274
+ lineWidth?: number;
275
+ lineDash?: LineDash;
276
+ opacity?: number;
185
277
  }
186
278
  /** A row-side's shared axis id (once the chart's private `rowAxis`). */
187
279
  export declare const sharedAxisId: (rowId: string, side: SeriesAxis) => string;
@@ -489,8 +581,42 @@ export declare function seriesCategoryStyle(s: SeriesConfig, settings: ChartSett
489
581
  /** A series' stroke width: its explicit `lineWidth` override, else its category
490
582
  * default from the settings (metrics vs studies). */
491
583
  export declare function seriesLineWidth(s: SeriesConfig, settings?: ChartSettings): number;
492
- /** A series' dash pattern (`undefined` = solid) from its category's style. */
584
+ /** The dash pattern a `'dotted'` line draws with — short enough to read as
585
+ * dots at every weight the panel offers, spaced so it never reads as a dash. */
586
+ export declare const DOT_PATTERN: readonly [number, number];
587
+ /** A texture as a dash pattern — `undefined` for solid. */
588
+ export declare function dashPattern(dash: LineDash | undefined): readonly [number, number] | undefined;
589
+ /** A series' dash pattern (`undefined` = solid): its own `lineDash`, else its
590
+ * category's style. A comparison-reading series always takes its category's:
591
+ * there the texture is not decoration but the symbol it reads. */
493
592
  export declare function seriesLineDashArray(s: SeriesConfig, settings?: ChartSettings): readonly [number, number] | undefined;
593
+ /** Dash ladders for a multi-output config's 2nd..Nth line, by default.
594
+ * Distinguishable at a glance and ordered so a longer dash reads as "further
595
+ * from the main output". Cycles past the end — a 12-output ribbon (`guppy`)
596
+ * wants a colour ramp rather than twelve dashes, which is a named
597
+ * TDL-STUDYDRAW case. Exported so a host's key draws the same textures. */
598
+ export declare const OUTPUT_DASHES: readonly (readonly number[])[];
599
+ /** How one output of a config draws — see {@link outputLook}. */
600
+ export interface OutputLook {
601
+ /** A palette key or raw CSS colour, unresolved — as `SeriesConfig.color`. */
602
+ color: string;
603
+ width: number;
604
+ /** `undefined` = solid. */
605
+ dash?: readonly number[];
606
+ /** `0..1`, before the chart's own dimming. */
607
+ opacity: number;
608
+ }
609
+ /**
610
+ * The ink one output of a config draws with — its {@link OutputStyle}
611
+ * overrides, else the config's own, else the output's default.
612
+ *
613
+ * The defaults are what a multi-output study has always drawn: ONE colour, N
614
+ * textures. The first output is the config's own line; each later one takes a
615
+ * longer dash and a hair less weight, so the stack reads as primary-and-derived
616
+ * rather than as peers. One function for the chart and for any key a host
617
+ * draws, so the two cannot disagree about which line is which.
618
+ */
619
+ export declare function outputLook(c: SeriesConfig, index: number, settings?: ChartSettings): OutputLook;
494
620
  /** The effective direction-coloring of a `bar`/`candle` series: the per-series
495
621
  * override, else the legacy candle `candleColorBy` (old presets), else the
496
622
  * settings default for that mark kind. Rise/fall fall back to the settings'
package/dist/series.js CHANGED
@@ -21,8 +21,7 @@ export function bandColumns(column) {
21
21
  export function hasBarOutput(c) {
22
22
  if (c.style !== 'lines' || !c.derive)
23
23
  return false;
24
- const op = c.derive.op;
25
- return opOutputs(op).some((suffix) => outputMark(op, suffix) === 'bar');
24
+ return configOutputs(c).some((o) => o.mark === 'bar');
26
25
  }
27
26
  /**
28
27
  * The per-output theme key for a `lines` config.
@@ -34,34 +33,103 @@ export function hasBarOutput(c) {
34
33
  */
35
34
  export const outputKey = (id, i) => `${id}__o${i}`;
36
35
  /**
37
- * The columns a config actually reads — one for most styles, three for a
38
- * `band`, and one per declared output for `lines`.
36
+ * The outputs a config draws, in order — the one answer to "what lines does
37
+ * this config put on the canvas, and what is each called?".
38
+ *
39
+ * Three shapes:
40
+ *
41
+ * - **A fanned study** ({@link SeriesConfig.fan}): one output per source output
42
+ * it runs on, each its own spec (`withFanOutput`) and so its own column.
43
+ * - **A multi-output op**: one per declared suffix, named off the spec id.
44
+ * - **Anything else**: its one column, unnamed.
45
+ *
46
+ * A config whose `derive` is gone degrades to its bare column rather than
47
+ * throwing (a persisted config can outlive the op that named it).
48
+ */
49
+ export function configOutputs(c) {
50
+ if (c.derive && c.fan && c.fan.length > 0) {
51
+ const mark = outputMark(c.derive.op, '');
52
+ const derive = c.derive;
53
+ return c.fan.map((name) => ({ name, column: deriveId(withFanOutput(derive, name)), mark }));
54
+ }
55
+ if (c.derive) {
56
+ const op = c.derive.op;
57
+ const outs = opOutputs(op);
58
+ if (outs.length > 1)
59
+ return outs.map((name) => ({
60
+ name,
61
+ column: `${c.column}${name}`,
62
+ mark: outputMark(op, name),
63
+ }));
64
+ }
65
+ return [{ name: '', column: c.column, mark: 'line' }];
66
+ }
67
+ /**
68
+ * The columns a `band` config draws between (and its centre line, when it has
69
+ * one). A fanned band — an SMA of a band's `Upper` and `Lower` — may have no
70
+ * centre at all; an op's own band always does (`bandColumns`).
71
+ */
72
+ export function configBand(c) {
73
+ if (c.derive && c.fan && c.fan.length > 0) {
74
+ const by = new Map(configOutputs(c).map((o) => [o.name, o.column]));
75
+ const middle = by.get('Middle');
76
+ return {
77
+ ...(middle ? { middle } : {}),
78
+ upper: by.get('Upper') ?? c.column,
79
+ lower: by.get('Lower') ?? c.column,
80
+ };
81
+ }
82
+ return bandColumns(c.column);
83
+ }
84
+ /**
85
+ * Whether a fan over `outputs` draws as a BAND: it runs on a band's two edges.
86
+ * A centre is optional — smoothing a band's bounds is still a band.
87
+ */
88
+ export const fanIsBand = (outputs) => outputs.includes('Upper') && outputs.includes('Lower');
89
+ /**
90
+ * The specs a config folds — one, or one per output of a fanned study. The
91
+ * prepare step folds every one of them, so each fanned line has a column.
92
+ */
93
+ export function configSpecs(c) {
94
+ if (!c.derive)
95
+ return [];
96
+ const derive = c.derive;
97
+ return c.fan && c.fan.length > 0 ? c.fan.map((o) => withFanOutput(derive, o)) : [derive];
98
+ }
99
+ /**
100
+ * The columns OTHER configs can be built on — what a study of this one may
101
+ * read. A config's `column`, and for a fanned study each of its lines' too:
102
+ * an EMA of the `Lower` line of a fanned SMA reads that line's column, not
103
+ * the `Upper` one the config is named by.
104
+ */
105
+ export function publishedColumns(c) {
106
+ return c.fan && c.fan.length > 0 ? configOutputs(c).map((o) => o.column) : [c.column];
107
+ }
108
+ /**
109
+ * The columns a config actually reads — one for most styles, two or three for
110
+ * a `band`, and one per output for `lines`.
39
111
  *
40
112
  * 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).
113
+ * multi-output study doesn't have to be found in five scanners.
45
114
  */
46
115
  export function configColumns(c) {
47
116
  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}`);
117
+ const b = configBand(c);
118
+ return [...(b.middle ? [b.middle] : []), b.upper, b.lower];
55
119
  }
120
+ if (c.style === 'lines' || (c.fan && c.fan.length > 0))
121
+ return configOutputs(c).map((o) => o.column);
56
122
  return [c.column];
57
123
  }
58
124
  // The aggregation window for `bar`/`candle` + the study `DeriveSpec` are owned by
59
125
  // `@tidal-ts/core` (where the windowing + derive seam live) — imported for
60
126
  // `SeriesConfig` below and re-exported so UI code has one import site for the
61
127
  // series vocabulary.
62
- import { BAND_OUTPUTS, COMPARE_PREFIX, inputNames, opOutputs, opParams, outputMark, studyLevels, usesCompare, } from '@tidal-ts/core';
128
+ import { BAND_OUTPUTS, COMPARE_PREFIX, deriveId, inputNames, opOutputs, opParams, outputMark, studyLevels, usesCompare, withFanOutput, } from '@tidal-ts/core';
63
129
  // The app-wide presentation defaults the category resolvers below read.
64
130
  import { DEFAULT_CHART_SETTINGS, } from './chartSettings.js';
131
+ /** The textures in display order. */
132
+ export const LINE_DASHES = ['solid', 'dashed', 'dotted'];
65
133
  // --- Axis identity ------------------------------------------------------------
66
134
  // One vocabulary for the chart (renders the axes), the machine (keys the range
67
135
  // state), and the host (builds the panel model). A row-side's SHARED axis is
@@ -337,9 +405,64 @@ export function seriesCategoryStyle(s, settings) {
337
405
  export function seriesLineWidth(s, settings = DEFAULT_CHART_SETTINGS) {
338
406
  return s.lineWidth ?? seriesCategoryStyle(s, settings).weight;
339
407
  }
340
- /** A series' dash pattern (`undefined` = solid) from its category's style. */
408
+ /** The dash pattern a `'dotted'` line draws with — short enough to read as
409
+ * dots at every weight the panel offers, spaced so it never reads as a dash. */
410
+ export const DOT_PATTERN = [1.5, 3];
411
+ /** A texture as a dash pattern — `undefined` for solid. */
412
+ export function dashPattern(dash) {
413
+ return dash === 'dashed' ? DASH_PATTERN : dash === 'dotted' ? DOT_PATTERN : undefined;
414
+ }
415
+ /** A series' dash pattern (`undefined` = solid): its own `lineDash`, else its
416
+ * category's style. A comparison-reading series always takes its category's:
417
+ * there the texture is not decoration but the symbol it reads. */
341
418
  export function seriesLineDashArray(s, settings = DEFAULT_CHART_SETTINGS) {
342
- return seriesCategoryStyle(s, settings).dash === 'dashed' ? DASH_PATTERN : undefined;
419
+ if (s.lineDash && !readsCompare(s))
420
+ return dashPattern(s.lineDash);
421
+ return dashPattern(seriesCategoryStyle(s, settings).dash);
422
+ }
423
+ /** Dash ladders for a multi-output config's 2nd..Nth line, by default.
424
+ * Distinguishable at a glance and ordered so a longer dash reads as "further
425
+ * from the main output". Cycles past the end — a 12-output ribbon (`guppy`)
426
+ * wants a colour ramp rather than twelve dashes, which is a named
427
+ * TDL-STUDYDRAW case. Exported so a host's key draws the same textures. */
428
+ export const OUTPUT_DASHES = [
429
+ [6, 3],
430
+ [2, 2],
431
+ [9, 3, 2, 3],
432
+ [1, 3],
433
+ ];
434
+ /**
435
+ * The ink one output of a config draws with — its {@link OutputStyle}
436
+ * overrides, else the config's own, else the output's default.
437
+ *
438
+ * The defaults are what a multi-output study has always drawn: ONE colour, N
439
+ * textures. The first output is the config's own line; each later one takes a
440
+ * longer dash and a hair less weight, so the stack reads as primary-and-derived
441
+ * rather than as peers. One function for the chart and for any key a host
442
+ * draws, so the two cannot disagree about which line is which.
443
+ */
444
+ export function outputLook(c, index, settings = DEFAULT_CHART_SETTINGS) {
445
+ const name = configOutputs(c)[index]?.name ?? '';
446
+ const own = c.outputStyles?.[name];
447
+ const width = seriesLineWidth(c, settings);
448
+ // A band draws ONE line (its centre) over its wash, so that line is the
449
+ // config's own and takes the config's own texture; the ladder is for stacks.
450
+ const lead = index === 0 || c.style === 'band';
451
+ const dash = own?.lineDash
452
+ ? dashPattern(own.lineDash)
453
+ : c.style === 'band'
454
+ ? seriesLineDashArray(c, settings)
455
+ : index === 0
456
+ ? c.lineDash
457
+ ? dashPattern(c.lineDash)
458
+ : undefined
459
+ : OUTPUT_DASHES[(index - 1) % OUTPUT_DASHES.length];
460
+ return {
461
+ color: own?.color ?? c.color,
462
+ width: own?.lineWidth ?? (lead ? width : Math.max(1, width - 0.5)),
463
+ ...(dash ? { dash } : {}),
464
+ opacity: own?.opacity ?? c.opacity ?? 1,
465
+ };
343
466
  }
344
467
  /** The effective direction-coloring of a `bar`/`candle` series: the per-series
345
468
  * override, else the legacy candle `candleColorBy` (old presets), else the
@@ -431,17 +554,20 @@ export function sourcesOf(configs, c) {
431
554
  const recorded = configs.find((x) => x.id === byId);
432
555
  if (!recorded)
433
556
  return; // its parent is gone — an orphan, not a re-bind
434
- if (recorded.column === name) {
557
+ if (publishes(recorded, name)) {
435
558
  out.push(recorded);
436
559
  return;
437
560
  }
438
561
  // Stale: that config computes something else now. Fall through.
439
562
  }
440
- const src = configs.find((x) => x.id !== c.id && x.column === name);
563
+ const src = configs.find((x) => x.id !== c.id && publishes(x, name));
441
564
  if (src)
442
565
  out.push(src);
443
566
  });
444
567
  return out;
445
568
  }
569
+ /** Whether `c` computes the column `name` — its own, or one of its fanned
570
+ * lines' ({@link publishedColumns}). The cheap test first: a fan is rare. */
571
+ const publishes = (c, name) => c.column === name || (!!c.fan && publishedColumns(c).includes(name));
446
572
  /** Whether `c` is built on `p` — `sourcesOf`, asked the other way round. */
447
573
  export const readsFrom = (configs, c, p) => sourcesOf(configs, c).some((s) => s.id === p.id);
@@ -0,0 +1,4 @@
1
+ /** A colour with its alpha multiplied by `alpha` — `#rgb`, `#rrggbb`,
2
+ * `#rrggbbaa`, `rgb()` and `rgba()`. Any other colour form comes back
3
+ * unchanged (dimming then simply no-ops). `1` is the identity. */
4
+ export declare function withAlpha(color: string, alpha: number): string;
@@ -0,0 +1,26 @@
1
+ // The chart's one colour transform: fading an ink by an opacity.
2
+ /** A colour with its alpha multiplied by `alpha` — `#rgb`, `#rrggbb`,
3
+ * `#rrggbbaa`, `rgb()` and `rgba()`. Any other colour form comes back
4
+ * unchanged (dimming then simply no-ops). `1` is the identity. */
5
+ export function withAlpha(color, alpha) {
6
+ if (alpha >= 1)
7
+ return color;
8
+ const fn = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?\s*\)$/i.exec(color.trim());
9
+ if (fn) {
10
+ const a0 = fn[4] == null ? 1 : fn[4].endsWith('%') ? parseFloat(fn[4]) / 100 : Number(fn[4]);
11
+ return `rgba(${fn[1]}, ${fn[2]}, ${fn[3]}, ${round3(a0 * alpha)})`;
12
+ }
13
+ let h = color.trim().replace(/^#/, '');
14
+ if (h.length === 3)
15
+ h = h
16
+ .split('')
17
+ .map((c) => c + c)
18
+ .join('');
19
+ const m = /^([\da-f]{6})([\da-f]{2})?$/i.exec(h);
20
+ if (!m)
21
+ return color;
22
+ const n = parseInt(m[1], 16);
23
+ const a0 = m[2] ? parseInt(m[2], 16) / 255 : 1;
24
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${round3(a0 * alpha)})`;
25
+ }
26
+ const round3 = (v) => Math.round(v * 1000) / 1000;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/chart",
3
- "version": "0.8.0",
3
+ "version": "0.10.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,27 +31,27 @@
31
31
  "access": "public"
32
32
  },
33
33
  "peerDependencies": {
34
- "@pond-ts/charts": "^0.72.0",
35
- "@pond-ts/financial": "^0.72.0",
36
- "@pond-ts/react": "^0.72.0",
37
- "pond-ts": "^0.72.0",
34
+ "@pond-ts/charts": "^0.73.0",
35
+ "@pond-ts/financial": "^0.73.0",
36
+ "@pond-ts/react": "^0.73.0",
37
+ "pond-ts": "^0.73.0",
38
38
  "react": "^18.2.0 || ^19.0.0"
39
39
  },
40
40
  "dependencies": {
41
- "@tidal-ts/core": "0.8.0"
41
+ "@tidal-ts/core": "0.10.0"
42
42
  },
43
43
  "devDependencies": {
44
- "@pond-ts/charts": "^0.72.0",
45
- "@pond-ts/financial": "^0.72.0",
46
- "@pond-ts/process": "0.72.0",
47
- "@pond-ts/react": "^0.72.0",
44
+ "@pond-ts/charts": "^0.73.0",
45
+ "@pond-ts/financial": "^0.73.0",
46
+ "@pond-ts/process": "0.73.0",
47
+ "@pond-ts/react": "^0.73.0",
48
48
  "@storybook/addon-essentials": "^8.5.0",
49
49
  "@storybook/react": "^8.5.0",
50
50
  "@storybook/react-vite": "^8.5.0",
51
51
  "@types/react": "^18.3.18",
52
52
  "@types/react-dom": "^18.3.5",
53
53
  "@vitejs/plugin-react": "^4.3.4",
54
- "pond-ts": "^0.72.0",
54
+ "pond-ts": "^0.73.0",
55
55
  "react": "^18.3.1",
56
56
  "react-dom": "^18.3.1",
57
57
  "storybook": "^8.5.0",