@tidal-ts/chart 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,11 @@
1
+ import type { CandleStyle } from '@pond-ts/charts';
2
+ /** A single-colour {@link CandleStyle} for `colorBy='series'` — every candle
3
+ * draws in one resolved `color` (rising === falling === neutral; only `rising`
4
+ * is read under `colorBy='series'`). Used in the vol terminal so a price candle
5
+ * beside colour-coded vol lines takes the series' colour, not market green/red
6
+ * — the theme's `candle.default` keeps green/red for a standalone price candle. */
7
+ export declare function candleStyleForColor(color: string): CandleStyle;
8
+ /** A two-colour {@link CandleStyle} for `colorBy='direction'` with the user's
9
+ * own rise/fall picks (already **resolved** to concrete colors). `neutral` is
10
+ * omitted, so a doji falls back to the rising colour. */
11
+ export declare function candleStyleForPair(rise: string, fall: string): CandleStyle;
@@ -0,0 +1,20 @@
1
+ /** A single-colour {@link CandleStyle} for `colorBy='series'` — every candle
2
+ * draws in one resolved `color` (rising === falling === neutral; only `rising`
3
+ * is read under `colorBy='series'`). Used in the vol terminal so a price candle
4
+ * beside colour-coded vol lines takes the series' colour, not market green/red
5
+ * — the theme's `candle.default` keeps green/red for a standalone price candle. */
6
+ export function candleStyleForColor(color) {
7
+ const pair = { body: color, wick: color };
8
+ return { rising: pair, falling: pair, neutral: pair, bodyWidth: 0.7, wickWidth: 1 };
9
+ }
10
+ /** A two-colour {@link CandleStyle} for `colorBy='direction'` with the user's
11
+ * own rise/fall picks (already **resolved** to concrete colors). `neutral` is
12
+ * omitted, so a doji falls back to the rising colour. */
13
+ export function candleStyleForPair(rise, fall) {
14
+ return {
15
+ rising: { body: rise, wick: rise },
16
+ falling: { body: fall, wick: fall },
17
+ bodyWidth: 0.7,
18
+ wickWidth: 1,
19
+ };
20
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * App-wide **chart settings** — the user's default presentation preferences,
3
+ * distinct from per-series overrides (which live on each `SeriesConfig`) and
4
+ * from presets (which capture a terminal's configuration). Settings are the
5
+ * *defaults* a fresh series starts from: what a bar/candle's rise/fall split
6
+ * looks like, and how heavy/dashed each category of line draws.
7
+ *
8
+ * This module is the **vocabulary**: the types, the shipped defaults and the
9
+ * forward-compatible merge — what the chart reads (`<TimeSeriesChart settings>`)
10
+ * and what any host persists. Who OWNS the value is the host's affair: Tidal's
11
+ * `ChartSettingsProvider` (context + localStorage, edited in the settings
12
+ * dialog) lives outside the chart entry, and a library consumer can hold the
13
+ * settings however it likes. Presentational components receive them as
14
+ * **props** (props in, events out).
15
+ */
16
+ export type LineDash = 'solid' | 'dashed';
17
+ /** One line category's presentation default: stroke style + weight (px). */
18
+ export interface CategoryLineStyle {
19
+ dash: LineDash;
20
+ weight: number;
21
+ }
22
+ /** Default coloring for a direction-capable mark (bar / candle): split rise/fall
23
+ * (market convention) vs the series' own single color. `rise`/`fall` are color
24
+ * keys — palette keys, the market `positive`/`negative` tokens, or raw CSS. */
25
+ export interface SplitColorDefault {
26
+ split: boolean;
27
+ rise: string;
28
+ fall: string;
29
+ }
30
+ /** Where a trading-time axis marks its collapse seams (a session/day open). */
31
+ export type SessionDividers = 'labeled' | 'all' | 'none';
32
+ export interface ChartSettings {
33
+ /**
34
+ * How a session boundary reads on a collapsed axis.
35
+ *
36
+ * `dividers` draws the vertical at each seam — `'labeled'` only where the axis
37
+ * also labels, `'all'` at every seam in view (crowds when zoomed out). We
38
+ * default it ON, against charts' `'none'`, because an intraday price line steps
39
+ * VERTICALLY at a seam: the overnight move has no horizontal room once the gap
40
+ * is collapsed, so without a divider that step reads as a price move inside the
41
+ * session rather than the boundary it is.
42
+ *
43
+ * `breaks` ends the line at the close and restarts it at the open instead of
44
+ * connecting across. It does visible work only where a series has live time it
45
+ * cannot fill: a price line starts at the session's open, so its seam is
46
+ * zero-width and there is nothing to break — a vol line has no open, starts one
47
+ * bar in, and breaks there.
48
+ */
49
+ sessions: {
50
+ dividers: SessionDividers;
51
+ breaks: boolean;
52
+ };
53
+ /** Bar-styled series (volume …): split rise/fall by direction, or single. */
54
+ bars: SplitColorDefault;
55
+ /** Candle-styled series: split rise/fall by direction, or single. */
56
+ candles: SplitColorDefault;
57
+ /** Raw metric lines (vol curves, price, derived catalog metrics). */
58
+ metrics: CategoryLineStyle;
59
+ /** Windowed studies (SMA / EMA overlays). */
60
+ derived: CategoryLineStyle;
61
+ /** The comparison ticker's counterpart lines. */
62
+ comparisons: CategoryLineStyle;
63
+ /**
64
+ * Per-annotation overrides (earnings, expirations …), keyed by the annotation's
65
+ * catalog id.
66
+ *
67
+ * **Every field is optional and absence means "as shipped"** — the catalog owns
68
+ * each default and this records only what the user changed. That is what keeps a
69
+ * new annotation kind from needing a settings migration: it appears at its own
70
+ * default, and a stored blob written before it existed stays valid.
71
+ *
72
+ * Deliberately an open map rather than a named pair. The other sections here are
73
+ * fixed presentation categories, but *which annotations exist* is the app's
74
+ * catalog to decide, and this package cannot import it (dependency direction).
75
+ * The dialog is handed the options as a prop for the same reason.
76
+ */
77
+ annotations: Record<string, AnnotationOverride>;
78
+ }
79
+ /** What a user can change about one annotation. Both optional — see
80
+ * {@link ChartSettings.annotations}. */
81
+ export interface AnnotationOverride {
82
+ /** Drawn or not. Absent ⇒ the catalog's `default`. */
83
+ on?: boolean;
84
+ /** Palette key (or raw CSS). Absent ⇒ the catalog's `defaultColor`. */
85
+ color?: string;
86
+ }
87
+ /** The shipped defaults (settings dialog spec): split green/red marks; solid
88
+ * 1.5 metrics, solid 0.5 studies, dashed 1.0 comparisons. */
89
+ export declare const DEFAULT_CHART_SETTINGS: ChartSettings;
90
+ /** Merge a stored (possibly partial / stale-shaped) value over the defaults —
91
+ * section by section, so a settings shape that grows stays forward-compatible
92
+ * with older persisted blobs. Unknown sections/fields are dropped. */
93
+ export declare function mergeChartSettings(stored: unknown): ChartSettings;
@@ -0,0 +1,107 @@
1
+ /**
2
+ * App-wide **chart settings** — the user's default presentation preferences,
3
+ * distinct from per-series overrides (which live on each `SeriesConfig`) and
4
+ * from presets (which capture a terminal's configuration). Settings are the
5
+ * *defaults* a fresh series starts from: what a bar/candle's rise/fall split
6
+ * looks like, and how heavy/dashed each category of line draws.
7
+ *
8
+ * This module is the **vocabulary**: the types, the shipped defaults and the
9
+ * forward-compatible merge — what the chart reads (`<TimeSeriesChart settings>`)
10
+ * and what any host persists. Who OWNS the value is the host's affair: Tidal's
11
+ * `ChartSettingsProvider` (context + localStorage, edited in the settings
12
+ * dialog) lives outside the chart entry, and a library consumer can hold the
13
+ * settings however it likes. Presentational components receive them as
14
+ * **props** (props in, events out).
15
+ */
16
+ /** The shipped defaults (settings dialog spec): split green/red marks; solid
17
+ * 1.5 metrics, solid 0.5 studies, dashed 1.0 comparisons. */
18
+ export const DEFAULT_CHART_SETTINGS = {
19
+ bars: { split: true, rise: 'positive', fall: 'negative' },
20
+ candles: { split: true, rise: 'positive', fall: 'negative' },
21
+ metrics: { dash: 'solid', weight: 1.5 },
22
+ derived: { dash: 'solid', weight: 0.5 },
23
+ comparisons: { dash: 'dashed', weight: 1 },
24
+ sessions: { dividers: 'labeled', breaks: true },
25
+ // Empty on purpose — every annotation starts at its catalog default until the
26
+ // user says otherwise. See `ChartSettings.annotations`.
27
+ annotations: {},
28
+ };
29
+ /** Merge a stored (possibly partial / stale-shaped) value over the defaults —
30
+ * section by section, so a settings shape that grows stays forward-compatible
31
+ * with older persisted blobs. Unknown sections/fields are dropped. */
32
+ export function mergeChartSettings(stored) {
33
+ const d = DEFAULT_CHART_SETTINGS;
34
+ if (typeof stored !== 'object' || stored === null)
35
+ return d;
36
+ const s = stored;
37
+ const split = (v, base) => {
38
+ const o = (typeof v === 'object' && v !== null ? v : {});
39
+ return {
40
+ split: typeof o.split === 'boolean' ? o.split : base.split,
41
+ rise: typeof o.rise === 'string' ? o.rise : base.rise,
42
+ fall: typeof o.fall === 'string' ? o.fall : base.fall,
43
+ };
44
+ };
45
+ const lineStyle = (v, base) => {
46
+ const o = (typeof v === 'object' && v !== null ? v : {});
47
+ // Weight must be a sane stroke (a stored 0/negative would draw nothing and
48
+ // read as a data bug) — out-of-range falls back to the default.
49
+ const w = o.weight;
50
+ return {
51
+ dash: o.dash === 'solid' || o.dash === 'dashed' ? o.dash : base.dash,
52
+ weight: typeof w === 'number' && Number.isFinite(w) && w > 0 && w <= 8 ? w : base.weight,
53
+ };
54
+ };
55
+ const sessions = (v, base) => {
56
+ const o = (typeof v === 'object' && v !== null ? v : {});
57
+ return {
58
+ dividers: o.dividers === 'labeled' || o.dividers === 'all' || o.dividers === 'none'
59
+ ? o.dividers
60
+ : base.dividers,
61
+ breaks: typeof o.breaks === 'boolean' ? o.breaks : base.breaks,
62
+ };
63
+ };
64
+ // The keys are the app's, so this cannot validate them against a list — but it
65
+ // can validate the VALUES, and must: consumers resolve with
66
+ // `override?.on ?? entry.default`, so a stored `"false"` would bypass the
67
+ // default and then read as truthy.
68
+ //
69
+ // A **bare boolean is accepted** and read as `{ on }`. That was the shape this
70
+ // section shipped with before colours existed, so a dev's stored blob (or an
71
+ // early user's) still carries it; migrating on read costs two lines and means
72
+ // nobody's toggle silently resets.
73
+ const annotations = (v) => {
74
+ if (typeof v !== 'object' || v === null)
75
+ return {};
76
+ const out = {};
77
+ for (const [k, val] of Object.entries(v)) {
78
+ if (typeof val === 'boolean') {
79
+ out[k] = { on: val };
80
+ continue;
81
+ }
82
+ if (typeof val !== 'object' || val === null)
83
+ continue;
84
+ const o = val;
85
+ const entry = {};
86
+ if (typeof o.on === 'boolean')
87
+ entry.on = o.on;
88
+ // A colour is a palette key or raw CSS — both are strings here, and the
89
+ // renderer resolves either. Empty string is not a colour.
90
+ if (typeof o.color === 'string' && o.color !== '')
91
+ entry.color = o.color;
92
+ // Drop an entry that overrides nothing, so `{}` does not accumulate.
93
+ if (entry.on !== undefined || entry.color !== undefined)
94
+ out[k] = entry;
95
+ }
96
+ return out;
97
+ };
98
+ return {
99
+ bars: split(s.bars, d.bars),
100
+ candles: split(s.candles, d.candles),
101
+ metrics: lineStyle(s.metrics, d.metrics),
102
+ derived: lineStyle(s.derived, d.derived),
103
+ comparisons: lineStyle(s.comparisons, d.comparisons),
104
+ sessions: sessions(s.sessions, d.sessions),
105
+ annotations: annotations(s.annotations),
106
+ };
107
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The **chart entry** — the surface that becomes `@tidal-ts/chart` (TDL-LIB).
3
+ *
4
+ * Rules, enforced by `boundary.test.ts`: this folder imports only `@tidal-ts/core`,
5
+ * the pond family, React and itself. No CSS, no provider, no token names, no
6
+ * control-panel or shell code. A host hands the chart its theme, its colour
7
+ * resolver and its settings as props; this entry decides nothing about where
8
+ * they come from.
9
+ *
10
+ * Exports are chosen, not inherited: what a second host needs to render a chart
11
+ * and prepare its data. Internals (`splitBarColumns`, `columnNames`, the candle
12
+ * style builders) stay internal until a consumer asks.
13
+ */
14
+ export { TimeSeriesChart, annotationInView, type ChartAnnotation, type ChartStats, type TimeSeriesChartProps, type TimeSeriesChartRow, } from './TimeSeriesChart.js';
15
+ export type { ChartSeries } from './types.js';
16
+ export { configAxisId, effectiveSplit, formatSeriesValue, isStudySeries, LINE_WIDTHS, PAIR_JOINS, PAIR_LENSES, seriesAxisId, readsCompare, seriesDrawn, seriesLineDashArray, seriesLineWidth, sharedAxisId, type AxisRange, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, bandColumns, configColumns, logAllowed, AXIS_PRECISIONS, type PairJoinOp, type PairLensOp, type SeriesGroup, type PairPartView, type PairView, type SeriesBinding, type SeriesConfig, type SeriesAxis, type SeriesStyle, type SeriesWindow, type CandleVariant, type ColorBy, } from './series.js';
17
+ export { DEFAULT_CHART_SETTINGS, mergeChartSettings, type AnnotationOverride, type ChartSettings, type CategoryLineStyle, type SessionDividers, type SplitColorDefault, type LineDash, } from './chartSettings.js';
18
+ export { useMeasuredWidth, useMeasuredSize } from './useMeasuredWidth.js';
19
+ export { assembleRows, carries, foldKey, foldSources, prepareChart, sourceFacts, type ConfigRow, type PreparedRow, type SourceFacts, type SourceInput, type SourceInputs, } from './prepare.js';
20
+ export { finiteColumns, firstLast, lastRow } from './seriesFacts.js';
21
+ export { createLiveValue } from '@pond-ts/charts';
22
+ export type { TrackerInfo, TrackerSample, LiveValue } from '@pond-ts/charts';
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The **chart entry** — the surface that becomes `@tidal-ts/chart` (TDL-LIB).
3
+ *
4
+ * Rules, enforced by `boundary.test.ts`: this folder imports only `@tidal-ts/core`,
5
+ * the pond family, React and itself. No CSS, no provider, no token names, no
6
+ * control-panel or shell code. A host hands the chart its theme, its colour
7
+ * resolver and its settings as props; this entry decides nothing about where
8
+ * they come from.
9
+ *
10
+ * Exports are chosen, not inherited: what a second host needs to render a chart
11
+ * and prepare its data. Internals (`splitBarColumns`, `columnNames`, the candle
12
+ * style builders) stay internal until a consumer asks.
13
+ */
14
+ export { TimeSeriesChart, annotationInView, } from './TimeSeriesChart.js';
15
+ export { configAxisId, effectiveSplit, formatSeriesValue, isStudySeries, LINE_WIDTHS, PAIR_JOINS, PAIR_LENSES, seriesAxisId, readsCompare, seriesDrawn, seriesLineDashArray, seriesLineWidth, sharedAxisId, effectiveAxisBounds, clampBoundsToLocks, barZeroLock, centerOnZero, axisRangeIsEmpty, axisFormat, bandColumns, configColumns, logAllowed, AXIS_PRECISIONS, } from './series.js';
16
+ export { DEFAULT_CHART_SETTINGS, mergeChartSettings, } from './chartSettings.js';
17
+ export { useMeasuredWidth, useMeasuredSize } from './useMeasuredWidth.js';
18
+ export { assembleRows, carries, foldKey, foldSources, prepareChart, sourceFacts, } from './prepare.js';
19
+ export { finiteColumns, firstLast, lastRow } from './seriesFacts.js';
20
+ // Re-exported so a host wires the live pill / tracker without a second import
21
+ // site for the library the chart is built on.
22
+ export { createLiveValue } from '@pond-ts/charts';
@@ -0,0 +1,111 @@
1
+ import { type SeriesConfig } from './series.js';
2
+ import type { ChartSeries } from './types.js';
3
+ /**
4
+ * The **prepare step**: from the host's raw series and its seated configs to
5
+ * what the chart eats. Pure functions, so a host memoises each at the grain it
6
+ * needs — the fold is the expensive one and must not re-run on a recolour; the
7
+ * row assembly is cheap and re-runs whenever the configs do.
8
+ *
9
+ * Three moves, in order:
10
+ *
11
+ * 1. {@link foldSources} — join the comparison series under the compare prefix
12
+ * where a config asks for it, then fold every study spec onto its source so
13
+ * the derived columns exist before the chart reads them.
14
+ * 2. {@link sourceFacts} — read, columnar, which columns actually carry data
15
+ * and what the latest bar holds.
16
+ * 3. {@link assembleRows} — per row, the configs the data can honour (plus the
17
+ * ones that must stay listed even when it cannot), each stamped with its
18
+ * latest value.
19
+ *
20
+ * {@link prepareChart} is the three in one call for a host that does not need
21
+ * the memo split.
22
+ */
23
+ /** One keyed source as the host holds it: the primary series, and the
24
+ * comparison entity's series when a comparison is on. */
25
+ export interface SourceInput {
26
+ series: ChartSeries;
27
+ compare?: ChartSeries | null;
28
+ }
29
+ export type SourceInputs = Record<string, SourceInput>;
30
+ /** A row of seated configs — the shape the terminal machine holds. */
31
+ export interface ConfigRow {
32
+ id: string;
33
+ configs: readonly SeriesConfig[];
34
+ }
35
+ /** A prepared row: the configs the chart and the chips should see, valued. */
36
+ export interface PreparedRow {
37
+ id: string;
38
+ configs: SeriesConfig[];
39
+ }
40
+ /** What the folded sources carry, read columnar (never `toObjects()`). */
41
+ export interface SourceFacts {
42
+ /** Per source: the columns with at least one finite value. */
43
+ columns: Record<string, ReadonlySet<string>>;
44
+ /** Per source: the last bar, as a plain row. Absent for an empty series. */
45
+ last: Record<string, Readonly<Record<string, number>>>;
46
+ }
47
+ /**
48
+ * A stable string of everything {@link foldSources} depends on in the configs —
49
+ * the specs per source and the raw-compare set — so a host can key its fold
50
+ * memo on this rather than on the configs' identity, and a recolour, a
51
+ * reorder, a visibility toggle never re-fold. Two config lists that differ only
52
+ * in presentation or order yield the same key: the fold is dependency-ordered
53
+ * inside the engine, so the order the specs arrive in cannot change its result,
54
+ * and the key sorts them (by content) so a reorder cannot change the key either.
55
+ */
56
+ export declare function foldKey(configs: readonly SeriesConfig[]): string;
57
+ /**
58
+ * The fold: each source, joined with its comparison under the compare prefix
59
+ * when any config on it asks (a compare-bound spec, or a raw compare leg), then
60
+ * every study spec on it applied so the derived columns exist. A spec whose
61
+ * inputs are missing is skipped by the engine and simply yields no column — the
62
+ * chart's column-absence handling is the render half of that contract, and
63
+ * {@link assembleRows} keeps the config listed so the user can still remove it.
64
+ *
65
+ * Only sources present in `inputs` are produced; a config naming an absent
66
+ * source is the caller's affair (it will not be carried).
67
+ */
68
+ export declare function foldSources(inputs: SourceInputs, configs: readonly SeriesConfig[]): Record<string, ChartSeries>;
69
+ /** Per-source data facts, read columnar: which columns carry real (finite)
70
+ * values ("show only what the data carries") and the latest bar (the chip /
71
+ * controls value readout). One `toObjects()` pass per source here was the
72
+ * single largest cost of a range change at intraday scale (`seriesFacts.ts`
73
+ * has the measurements). */
74
+ export declare function sourceFacts(sources: Record<string, ChartSeries>): SourceFacts;
75
+ /** Whether a config's columns exist in its folded source — the "this config
76
+ * draws" predicate. A derived spec that did not fold is CONFIGURED but not
77
+ * CARRIED: anything reading "what is on the canvas" (dimming, the price pill,
78
+ * an axis panel's drawn set) tests this, not mere visibility.
79
+ *
80
+ * `configColumns`, not `c.column`: a multi-output config's column is a spec id
81
+ * naming NONE of its own columns, so testing it directly said "not carried" for
82
+ * every band and every multi-output study — a MACD's chip sat blank while the
83
+ * hover readout, which reads the series itself, showed a value. `every`,
84
+ * because one op's fold either produces all its outputs or none. */
85
+ export declare function carries(facts: SourceFacts, c: Pick<SeriesConfig, 'source' | 'column' | 'style' | 'derive'>): boolean;
86
+ /**
87
+ * Per row, the configs to show, each stamped with its latest value (or `null`).
88
+ *
89
+ * A raw metric is kept only when the data carries its column — a feed lacking
90
+ * a column hides the series rather than drawing nothing. A DERIVED config is
91
+ * kept even when its spec did not fold (compare off, a leg's column gone): its
92
+ * value reads `—` and the chart just does not draw it. Silently dropping it was
93
+ * the "ghost spread" debt — a seated series with no visible trace that nothing
94
+ * could remove. A LEG-GROUP member is kept for the same reason even when raw:
95
+ * it is half of a pair the user built, so it stays listed (dimmed, by the
96
+ * host) rather than vanishing.
97
+ *
98
+ * The raw-metric test is {@link carries} (every declared output), where the
99
+ * terminal used to test the bare `column`. Equivalent for every reachable
100
+ * config — a band or multi-output study always carries `derive`, which keeps
101
+ * it listed regardless — and one predicate rather than two for "does the data
102
+ * carry this", so the chip and the canvas cannot disagree.
103
+ */
104
+ export declare function assembleRows(rows: readonly ConfigRow[], facts: SourceFacts): PreparedRow[];
105
+ /** The whole prepare step in one call, for a host that does not need the memo
106
+ * split: fold, read the facts, assemble the rows. */
107
+ export declare function prepareChart(inputs: SourceInputs, rows: readonly ConfigRow[]): {
108
+ sources: Record<string, ChartSeries>;
109
+ facts: SourceFacts;
110
+ rows: PreparedRow[];
111
+ };
@@ -0,0 +1,139 @@
1
+ import { applyDerived, COMPARE_PREFIX, joinUnderPrefix, usesCompare } from '@tidal-ts/core';
2
+ import { configColumns } from './series.js';
3
+ import { finiteColumns, lastRow } from './seriesFacts.js';
4
+ const specsBySource = (configs) => {
5
+ const m = {};
6
+ for (const c of configs)
7
+ if (c.derive && c.source)
8
+ (m[c.source] ??= []).push(c.derive);
9
+ return m;
10
+ };
11
+ /** Sources with a config reading a RAW compare column — a split pair's leg,
12
+ * which carries no spec at all but needs the compare join exactly as a
13
+ * compare-bound spec does. (Asking only the specs left such a leg reading a
14
+ * column nothing ever joined on: it drew nothing and, having no `derive`, was
15
+ * filtered out of the panel too — an invisible, unremovable leg.) */
16
+ const rawCompareSources = (configs) => [
17
+ ...new Set(configs
18
+ .filter((c) => c.source && !c.derive && c.column.startsWith(COMPARE_PREFIX))
19
+ .map((c) => c.source)),
20
+ ].sort();
21
+ /**
22
+ * A stable string of everything {@link foldSources} depends on in the configs —
23
+ * the specs per source and the raw-compare set — so a host can key its fold
24
+ * memo on this rather than on the configs' identity, and a recolour, a
25
+ * reorder, a visibility toggle never re-fold. Two config lists that differ only
26
+ * in presentation or order yield the same key: the fold is dependency-ordered
27
+ * inside the engine, so the order the specs arrive in cannot change its result,
28
+ * and the key sorts them (by content) so a reorder cannot change the key either.
29
+ */
30
+ export function foldKey(configs) {
31
+ const bySource = specsBySource(configs);
32
+ const sorted = Object.fromEntries(Object.keys(bySource)
33
+ .sort()
34
+ .map((source) => [source, bySource[source].map((spec) => JSON.stringify(spec)).sort()]));
35
+ return JSON.stringify([sorted, rawCompareSources(configs)]);
36
+ }
37
+ /**
38
+ * The fold: each source, joined with its comparison under the compare prefix
39
+ * when any config on it asks (a compare-bound spec, or a raw compare leg), then
40
+ * every study spec on it applied so the derived columns exist. A spec whose
41
+ * inputs are missing is skipped by the engine and simply yields no column — the
42
+ * chart's column-absence handling is the render half of that contract, and
43
+ * {@link assembleRows} keeps the config listed so the user can still remove it.
44
+ *
45
+ * Only sources present in `inputs` are produced; a config naming an absent
46
+ * source is the caller's affair (it will not be carried).
47
+ */
48
+ export function foldSources(inputs, configs) {
49
+ const specs = specsBySource(configs);
50
+ const rawCompare = new Set(rawCompareSources(configs));
51
+ const out = {};
52
+ for (const [key, input] of Object.entries(inputs)) {
53
+ const mine = specs[key] ?? [];
54
+ let series = input.series;
55
+ // A compare-bound leg needs the compare entity's columns on the PRIMARY
56
+ // series before the fold — a left exact-key join, every conflicting column
57
+ // prefixed. Only when asked and the compare series exists; otherwise the
58
+ // fold's own skip leaves the spread as a gap (compare off ⇒ not drawn).
59
+ // Rename-then-join lives in core (`joinUnderPrefix`; F-charts-14 for why
60
+ // not the library's `onConflict: 'prefix'`).
61
+ if (input.compare && (rawCompare.has(key) || mine.some(usesCompare)))
62
+ series = joinUnderPrefix(series, input.compare);
63
+ out[key] = applyDerived(series, mine);
64
+ }
65
+ return out;
66
+ }
67
+ /** Per-source data facts, read columnar: which columns carry real (finite)
68
+ * values ("show only what the data carries") and the latest bar (the chip /
69
+ * controls value readout). One `toObjects()` pass per source here was the
70
+ * single largest cost of a range change at intraday scale (`seriesFacts.ts`
71
+ * has the measurements). */
72
+ export function sourceFacts(sources) {
73
+ const columns = {};
74
+ const last = {};
75
+ for (const [key, series] of Object.entries(sources)) {
76
+ columns[key] = finiteColumns(series);
77
+ const row = lastRow(series);
78
+ if (row)
79
+ last[key] = row;
80
+ }
81
+ return { columns, last };
82
+ }
83
+ /** Whether a config's columns exist in its folded source — the "this config
84
+ * draws" predicate. A derived spec that did not fold is CONFIGURED but not
85
+ * CARRIED: anything reading "what is on the canvas" (dimming, the price pill,
86
+ * an axis panel's drawn set) tests this, not mere visibility.
87
+ *
88
+ * `configColumns`, not `c.column`: a multi-output config's column is a spec id
89
+ * naming NONE of its own columns, so testing it directly said "not carried" for
90
+ * every band and every multi-output study — a MACD's chip sat blank while the
91
+ * hover readout, which reads the series itself, showed a value. `every`,
92
+ * because one op's fold either produces all its outputs or none. */
93
+ export function carries(facts, c) {
94
+ const cols = c.source ? facts.columns[c.source] : undefined;
95
+ if (!cols)
96
+ return false;
97
+ return configColumns(c).every((col) => cols.has(col));
98
+ }
99
+ /**
100
+ * Per row, the configs to show, each stamped with its latest value (or `null`).
101
+ *
102
+ * A raw metric is kept only when the data carries its column — a feed lacking
103
+ * a column hides the series rather than drawing nothing. A DERIVED config is
104
+ * kept even when its spec did not fold (compare off, a leg's column gone): its
105
+ * value reads `—` and the chart just does not draw it. Silently dropping it was
106
+ * the "ghost spread" debt — a seated series with no visible trace that nothing
107
+ * could remove. A LEG-GROUP member is kept for the same reason even when raw:
108
+ * it is half of a pair the user built, so it stays listed (dimmed, by the
109
+ * host) rather than vanishing.
110
+ *
111
+ * The raw-metric test is {@link carries} (every declared output), where the
112
+ * terminal used to test the bare `column`. Equivalent for every reachable
113
+ * config — a band or multi-output study always carries `derive`, which keeps
114
+ * it listed regardless — and one predicate rather than two for "does the data
115
+ * carry this", so the chip and the canvas cannot disagree.
116
+ */
117
+ export function assembleRows(rows, facts) {
118
+ return rows.map((row) => ({
119
+ id: row.id,
120
+ configs: row.configs
121
+ .filter((c) => carries(facts, c) || !!c.derive || !!c.group)
122
+ .map((c) => ({
123
+ ...c,
124
+ // The PRIMARY output's column, not `c.column`: a multi-output config's
125
+ // column is a spec id naming none of its columns, so reading it directly
126
+ // left the chip blank. `configColumns` returns the declared outputs in
127
+ // order, so `[0]` is the reading the study is named for (a band's
128
+ // centre, a MACD's line).
129
+ value: (c.source ? facts.last[c.source] : undefined)?.[configColumns(c)[0] ?? c.column] ?? null,
130
+ })),
131
+ }));
132
+ }
133
+ /** The whole prepare step in one call, for a host that does not need the memo
134
+ * split: fold, read the facts, assemble the rows. */
135
+ export function prepareChart(inputs, rows) {
136
+ const sources = foldSources(inputs, rows.flatMap((r) => r.configs));
137
+ const facts = sourceFacts(sources);
138
+ return { sources, facts, rows: assembleRows(rows, facts) };
139
+ }