@tidal-ts/terminal 0.8.0 → 0.11.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/dist/context.d.ts CHANGED
@@ -39,7 +39,7 @@ export declare function useActiveSlot(): number | null;
39
39
  export declare function useAxisRanges(): Record<string, AxisRange>;
40
40
  export declare function useAddSeries(): (catalogId: string, rowId?: string) => void;
41
41
  /** Add a study (`sma`/`ema` …) of a target series, layered on its row. */
42
- export declare function useAddStudy(): (targetId: string, op: DeriveOp, period: number) => void;
42
+ export declare function useAddStudy(): (targetId: string, op: DeriveOp, period: number, outputs?: readonly string[]) => void;
43
43
  /** Add a pair (A vs B spread — diff/ratio/logRatio) of two metrics, on `rowId`
44
44
  * when given (the per-row `+Pair`), else in front of leg A. */
45
45
  export declare function useAddPair(): (a: PairLegInput, b: PairLegInput, op: PairLensOp, rowId?: string) => void;
@@ -51,6 +51,9 @@ export declare function useSetStudyParam(): (id: string, name: string, value: nu
51
51
  /** Switch which output of a multi-output source a study reads (the output
52
52
  * picker). Pair it with `outputAllowed` to render refused choices disabled. */
53
53
  export declare function useSetStudyOutput(): (id: string, output: string) => void;
54
+ /** Which outputs of its multi-output source a study runs on — one, several, or
55
+ * all (`series.setStudyOutputs`). */
56
+ export declare function useSetStudyOutputs(): (id: string, outputs: readonly string[]) => void;
54
57
  /** Step a series' draw order within its row (`front`/`up`/`down`/`back`; the
55
58
  * list is front→back, so `up` moves toward the top of the canvas stack). */
56
59
  export declare function useOrderSeries(): (id: string, to: 'front' | 'up' | 'down' | 'back') => void;
package/dist/context.js CHANGED
@@ -67,7 +67,7 @@ export function useAddSeries() {
67
67
  /** Add a study (`sma`/`ema` …) of a target series, layered on its row. */
68
68
  export function useAddStudy() {
69
69
  const ref = TerminalContext.useActorRef();
70
- return useCallback((targetId, op, period) => ref.send({ type: 'series.addStudy', targetId, op, period }), [ref]);
70
+ return useCallback((targetId, op, period, outputs) => ref.send({ type: 'series.addStudy', targetId, op, period, ...(outputs ? { outputs } : {}) }), [ref]);
71
71
  }
72
72
  /** Add a pair (A vs B spread — diff/ratio/logRatio) of two metrics, on `rowId`
73
73
  * when given (the per-row `+Pair`), else in front of leg A. */
@@ -92,6 +92,12 @@ export function useSetStudyOutput() {
92
92
  const ref = TerminalContext.useActorRef();
93
93
  return useCallback((id, output) => ref.send({ type: 'series.setStudyOutput', id, output }), [ref]);
94
94
  }
95
+ /** Which outputs of its multi-output source a study runs on — one, several, or
96
+ * all (`series.setStudyOutputs`). */
97
+ export function useSetStudyOutputs() {
98
+ const ref = TerminalContext.useActorRef();
99
+ return useCallback((id, outputs) => ref.send({ type: 'series.setStudyOutputs', id, outputs }), [ref]);
100
+ }
95
101
  /** Step a series' draw order within its row (`front`/`up`/`down`/`back`; the
96
102
  * list is front→back, so `up` moves toward the top of the canvas stack). */
97
103
  export function useOrderSeries() {
package/dist/index.d.ts CHANGED
@@ -5,6 +5,6 @@
5
5
  * union — the pre-paid bus contract. The actor context + machine internals stay
6
6
  * private to the module.
7
7
  */
8
- export { TerminalProvider, useRows, useSelectedSeries, useExpandedSeries, useControlsOpen, usePresetSaved, useActiveSlot, useAddSeries, useAddPair, useCompareAll, useAddStudy, useSetStudyParam, useSetStudyOutput, useOrderSeries, useReindexSeries, useMoveSeriesToRow, useMoveToAxis, useRemoveSeries, usePatchSeries, useToggleVisible, useToggleGroupVisible, useRemoveGroup, useSelectSeries, useExpandSeries, useSetControlsOpen, useSelectPreset, useSavePreset, useSetRowHeights, useAddRow, useRemoveRow, useAxisRanges, useToggleAxisLink, useSwapAxisSide, useSetAxisRange, useSetAxisAuto, useSetAxisLocks, useSetAxisAutoOpts, useSetAxisFormat, useTerminalHotkeys, type TerminalProviderProps, } from './context.js';
9
- export { PRESET_SLOTS, MAX_ROWS, activeSlot, canonRows, columnLabel, columnUnits, entryColumn, groupMembers, mintId, axisMoveAllowed, linkToggleAllowed, respecAllowed, outputAllowed, studyChainTail, studyOfferable, SOURCE_COLUMNS, swapAllowed, type EditScope, type RowState, type TerminalPreset, type MetricEntry, type PairLegInput, type PresetStorage, type TerminalEvent, type TerminalInput, } from './terminalMachine.js';
8
+ export { TerminalProvider, useRows, useSelectedSeries, useExpandedSeries, useControlsOpen, usePresetSaved, useActiveSlot, useAddSeries, useAddPair, useCompareAll, useAddStudy, useSetStudyParam, useSetStudyOutput, useSetStudyOutputs, useOrderSeries, useReindexSeries, useMoveSeriesToRow, useMoveToAxis, useRemoveSeries, usePatchSeries, useToggleVisible, useToggleGroupVisible, useRemoveGroup, useSelectSeries, useExpandSeries, useSetControlsOpen, useSelectPreset, useSavePreset, useSetRowHeights, useAddRow, useRemoveRow, useAxisRanges, useToggleAxisLink, useSwapAxisSide, useSetAxisRange, useSetAxisAuto, useSetAxisLocks, useSetAxisAutoOpts, useSetAxisFormat, useTerminalHotkeys, type TerminalProviderProps, } from './context.js';
9
+ export { PRESET_SLOTS, MAX_ROWS, activeSlot, canonRows, columnLabel, columnUnits, entryColumn, groupMembers, mintId, axisMoveAllowed, linkToggleAllowed, respecAllowed, outputAllowed, outputsAllowed, studyOutputChoices, studyOutputsOf, studyOutputsRead, defaultStudyOutputs, studyChainTail, studyOfferable, SOURCE_COLUMNS, swapAllowed, type EditScope, type RowState, type TerminalPreset, type MetricEntry, type PairLegInput, type PresetStorage, type TerminalEvent, type TerminalInput, } from './terminalMachine.js';
10
10
  export { axisBindings, allowedAxes, canAddUnit, axisForAdd, type AxisMember, } from './axisPolicy.js';
package/dist/index.js CHANGED
@@ -5,8 +5,8 @@
5
5
  * union — the pre-paid bus contract. The actor context + machine internals stay
6
6
  * private to the module.
7
7
  */
8
- export { TerminalProvider, useRows, useSelectedSeries, useExpandedSeries, useControlsOpen, usePresetSaved, useActiveSlot, useAddSeries, useAddPair, useCompareAll, useAddStudy, useSetStudyParam, useSetStudyOutput, useOrderSeries, useReindexSeries, useMoveSeriesToRow, useMoveToAxis, useRemoveSeries, usePatchSeries, useToggleVisible, useToggleGroupVisible, useRemoveGroup, useSelectSeries, useExpandSeries, useSetControlsOpen, useSelectPreset, useSavePreset, useSetRowHeights, useAddRow, useRemoveRow, useAxisRanges, useToggleAxisLink, useSwapAxisSide, useSetAxisRange, useSetAxisAuto, useSetAxisLocks, useSetAxisAutoOpts, useSetAxisFormat, useTerminalHotkeys, } from './context.js';
9
- export { PRESET_SLOTS, MAX_ROWS, activeSlot, canonRows, columnLabel, columnUnits, entryColumn, groupMembers, mintId, axisMoveAllowed, linkToggleAllowed, respecAllowed, outputAllowed, studyChainTail, studyOfferable, SOURCE_COLUMNS, swapAllowed, } from './terminalMachine.js';
8
+ export { TerminalProvider, useRows, useSelectedSeries, useExpandedSeries, useControlsOpen, usePresetSaved, useActiveSlot, useAddSeries, useAddPair, useCompareAll, useAddStudy, useSetStudyParam, useSetStudyOutput, useSetStudyOutputs, useOrderSeries, useReindexSeries, useMoveSeriesToRow, useMoveToAxis, useRemoveSeries, usePatchSeries, useToggleVisible, useToggleGroupVisible, useRemoveGroup, useSelectSeries, useExpandSeries, useSetControlsOpen, useSelectPreset, useSavePreset, useSetRowHeights, useAddRow, useRemoveRow, useAxisRanges, useToggleAxisLink, useSwapAxisSide, useSetAxisRange, useSetAxisAuto, useSetAxisLocks, useSetAxisAutoOpts, useSetAxisFormat, useTerminalHotkeys, } from './context.js';
9
+ export { PRESET_SLOTS, MAX_ROWS, activeSlot, canonRows, columnLabel, columnUnits, entryColumn, groupMembers, mintId, axisMoveAllowed, linkToggleAllowed, respecAllowed, outputAllowed, outputsAllowed, studyOutputChoices, studyOutputsOf, studyOutputsRead, defaultStudyOutputs, studyChainTail, studyOfferable, SOURCE_COLUMNS, swapAllowed, } from './terminalMachine.js';
10
10
  // The axis policy a host's MENUS gate on — the same predicates the machine's
11
11
  // guards enforce, exported so the two cannot disagree (0.1.0 left them internal;
12
12
  // a host had to keep its own copy).
@@ -119,11 +119,17 @@ export type TerminalEvent = {
119
119
  type: 'series.add';
120
120
  catalogId: string;
121
121
  rowId?: string;
122
- } | {
122
+ }
123
+ /** Add a study of `targetId`. `outputs` names which outputs of a
124
+ * MULTI-OUTPUT target it runs on ({@link studyOutputsOf}); several make one
125
+ * study FANNED over them (`SeriesConfig.fan`). Omitted ⇒ the target's
126
+ * default ({@link defaultStudyOutputs}). Ignored for a single-output target. */
127
+ | {
123
128
  type: 'series.addStudy';
124
129
  targetId: string;
125
130
  op: DeriveOp;
126
131
  period: number;
132
+ outputs?: readonly string[];
127
133
  }
128
134
  /** Add an A-vs-B spread. `rowId` names the row to seat it on — the per-row
129
135
  * `+Pair` affordance, and an EXPLICIT choice, so it wins over the default
@@ -158,6 +164,14 @@ export type TerminalEvent = {
158
164
  id: string;
159
165
  output: string;
160
166
  }
167
+ /** Which outputs of its multi-output source a study runs on — one, several
168
+ * (a FAN: one study drawing a line per output), or all. Generalises
169
+ * `series.setStudyOutput`, and reaches a study of a fanned study too. */
170
+ | {
171
+ type: 'series.setStudyOutputs';
172
+ id: string;
173
+ outputs: readonly string[];
174
+ }
161
175
  /** Draw-order (z) within the series' own row. The row's config list is
162
176
  * **front→back** — index 0 paints on top (the render reverses for
163
177
  * `<Layers>`), so `up` moves toward the front. */
@@ -347,6 +361,23 @@ export declare function studyChainTail(configs: readonly SeriesConfig[], rootId:
347
361
  * entry IS its computation — so its id doubles as its column name when it
348
362
  * doesn't name one (`iv21`), and a derived entry names its folded output. */
349
363
  export declare const entryColumn: (e: Pick<MetricEntry, "id" | "column">) => string;
364
+ /**
365
+ * The outputs a study of `target` may run on — the choices the add-study
366
+ * picker and the properties' "Reads" control offer.
367
+ *
368
+ * A MULTI-OUTPUT study offers its declared outputs (a MACD's Line, Signal,
369
+ * Hist); a FANNED study offers the outputs it runs on, because a study of it
370
+ * continues each of its lines (an EMA of a smoothed band's edges). Anything
371
+ * else offers none: it is one line, and a study of it reads that.
372
+ */
373
+ export declare function studyOutputsOf(target: Pick<SeriesConfig, 'derive' | 'fan'>): string[];
374
+ /**
375
+ * What a study of `target` runs on when nothing says otherwise: a fanned
376
+ * study's every line (so smoothing a smoothed band gives a band), else a
377
+ * multi-output study's PRIMARY (`primaryOutput`) — the one reading it was
378
+ * named for. Empty for a single-output target.
379
+ */
380
+ export declare function defaultStudyOutputs(target: Pick<SeriesConfig, 'derive' | 'fan'>): string[];
350
381
  /** One side of a pair as the PICKER states it (the two-sided grammar, TDL-PAIR
351
382
  * stage 2): a metric, the workspace ROLE the leg reads — `'primary'` (default)
352
383
  * or `'compare'`, re-resolving when the ticker bar changes, which is what
@@ -438,6 +469,25 @@ export declare function respecAllowed(scope: EditScope, id: string, name: string
438
469
  * Total: it runs in a guard, where a throw kills the actor.
439
470
  */
440
471
  export declare function outputAllowed(scope: EditScope, id: string, output: string): boolean;
472
+ /**
473
+ * The outputs a study can be set to run on — its PARENT's
474
+ * ({@link studyOutputsOf}), or, with no seated parent, every output its chain's
475
+ * multi-output source declares. Empty when it reads no multi-output source.
476
+ */
477
+ export declare function studyOutputChoices(scope: EditScope, id: string): string[];
478
+ /** The outputs a study runs on now: its fan, else the one its chain picks. */
479
+ export declare function studyOutputsRead(study: Pick<SeriesConfig, 'derive' | 'fan'>): string[];
480
+ /**
481
+ * Whether a study can be set to run on `outputs` — shared by the guard and the
482
+ * host, so a refused set renders disabled. Beyond {@link respecOutputs}'s own
483
+ * refusals: nothing may change while the SAME set is asked for; a study with a
484
+ * study built on it may only move between single outputs (its child reads one
485
+ * of its lines, and a fan change would leave it reading a line no longer
486
+ * drawn); and the result must stay coherent like any retune.
487
+ *
488
+ * Total: it runs in a guard.
489
+ */
490
+ export declare function outputsAllowed(scope: EditScope, id: string, outputs: readonly string[]): boolean;
441
491
  export declare const groupMembers: (configs: readonly SeriesConfig[], groupId: string) => SeriesConfig[];
442
492
  /**
443
493
  * Whether `id` can move onto the axis keyed by `axisGroup` (undefined = the
@@ -494,6 +544,7 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
494
544
  targetId: string;
495
545
  op: DeriveOp;
496
546
  period: number;
547
+ outputs?: readonly string[];
497
548
  } | {
498
549
  type: "series.addPair";
499
550
  a: PairLegInput;
@@ -511,6 +562,10 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
511
562
  type: "series.setStudyOutput";
512
563
  id: string;
513
564
  output: string;
565
+ } | {
566
+ type: "series.setStudyOutputs";
567
+ id: string;
568
+ outputs: readonly string[];
514
569
  } | {
515
570
  type: "series.order";
516
571
  id: string;
@@ -609,6 +664,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
609
664
  } | {
610
665
  type: "setStudyOutput";
611
666
  params: import("xstate").NonReducibleUnknown;
667
+ } | {
668
+ type: "setStudyOutputs";
669
+ params: import("xstate").NonReducibleUnknown;
612
670
  } | {
613
671
  type: "setStudyParam";
614
672
  params: import("xstate").NonReducibleUnknown;
@@ -702,6 +760,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
702
760
  } | {
703
761
  type: "canSetStudyOutput";
704
762
  params: unknown;
763
+ } | {
764
+ type: "canSetStudyOutputs";
765
+ params: unknown;
705
766
  } | {
706
767
  type: "canSetStudyParam";
707
768
  params: unknown;
@@ -1,5 +1,5 @@
1
1
  import { assign, enqueueActions, setup } from 'xstate';
2
- import { COMPARE_PREFIX, hasPairOp, usesCompare, deriveId, opParams, opInputs, opNeedsColumns, opIsBand, opIsMulti, outputMark, opOutputs, TARGET_ROLES, opSharesSourceAxis, studyTag, inputNames, isPickedInput, isPairOp, isValidSpec, partStudyLabel, readPairParts, specUnit, studyInputOf, studyPick, substituteInput, withStudyOutput, } from '@tidal-ts/core';
2
+ import { COMPARE_PREFIX, hasPairOp, usesCompare, deriveId, opParams, opInputs, opNeedsColumns, opIsBand, opIsMulti, outputMark, opOutputs, TARGET_ROLES, opSharesSourceAxis, studyTag, inputNames, isPickedInput, isPairOp, isValidSpec, partStudyLabel, readPairParts, specUnit, studyInputOf, studyPick, substituteInput, withStudyOutput, fanPick, primaryOutput, withFanOutput, } from '@tidal-ts/core';
3
3
  /**
4
4
  * The bar columns each data SOURCE carries — the one fact that decides whether a
5
5
  * multi-column study is offerable on a series. Only the price series has bars;
@@ -31,7 +31,7 @@ function hidesPointer(context, toggledId, pointer) {
31
31
  : new Set([toggledId]);
32
32
  return cascade.has(pointer);
33
33
  }
34
- import { axisRangeIsEmpty, logAllowed, isStudySeries, readsFrom, sourcesOf, } from '@tidal-ts/chart';
34
+ import { axisRangeIsEmpty, logAllowed, isStudySeries, readsFrom, sourcesOf, fanIsBand, publishedColumns, } from '@tidal-ts/chart';
35
35
  import { configAxisId, seriesAxisId, sharedAxisId, } from '@tidal-ts/chart';
36
36
  import { axisForAdd, canAddUnit } from './axisPolicy.js';
37
37
  export const PRESET_SLOTS = 5;
@@ -422,6 +422,51 @@ function toConfig(e, id, axis = e.axis) {
422
422
  derive: e.derive,
423
423
  };
424
424
  }
425
+ /**
426
+ * The outputs a study of `target` may run on — the choices the add-study
427
+ * picker and the properties' "Reads" control offer.
428
+ *
429
+ * A MULTI-OUTPUT study offers its declared outputs (a MACD's Line, Signal,
430
+ * Hist); a FANNED study offers the outputs it runs on, because a study of it
431
+ * continues each of its lines (an EMA of a smoothed band's edges). Anything
432
+ * else offers none: it is one line, and a study of it reads that.
433
+ */
434
+ export function studyOutputsOf(target) {
435
+ if (target.fan && target.fan.length > 0)
436
+ return [...target.fan];
437
+ if (target.derive && opOutputs(target.derive.op).length > 1)
438
+ return opOutputs(target.derive.op);
439
+ return [];
440
+ }
441
+ /**
442
+ * What a study of `target` runs on when nothing says otherwise: a fanned
443
+ * study's every line (so smoothing a smoothed band gives a band), else a
444
+ * multi-output study's PRIMARY (`primaryOutput`) — the one reading it was
445
+ * named for. Empty for a single-output target.
446
+ */
447
+ export function defaultStudyOutputs(target) {
448
+ if (target.fan && target.fan.length > 0)
449
+ return [...target.fan];
450
+ const primary = target.derive ? primaryOutput(target.derive.op) : undefined;
451
+ return primary ? [primary] : [];
452
+ }
453
+ /** `outputs` in the order `offered` lists them, duplicates dropped — so a fan's
454
+ * first output (the one `derive` reads) does not depend on click order. */
455
+ const inOfferedOrder = (offered, outputs) => offered.filter((o) => outputs.includes(o));
456
+ /**
457
+ * The input a study of `target` reads for one of its outputs: the target's own
458
+ * column or spec, a PICK of one output of a multi-output target, or — for a
459
+ * fanned target — the chain that computes that one of its lines.
460
+ */
461
+ function studyInputFor(target, output) {
462
+ if (output !== undefined && target.derive) {
463
+ if (target.fan && target.fan.includes(output))
464
+ return withFanOutput(target.derive, output);
465
+ if (opOutputs(target.derive.op).includes(output))
466
+ return { from: target.derive, output };
467
+ }
468
+ return studyInputOf(target.derive ?? target.column);
469
+ }
425
470
  /** The spec a study of `target` at `(op, period)` induces — reads the target's
426
471
  * DATA column, or **nests** the target's own spec when the target is derived
427
472
  * (the engine reads a string input as a raw column, so composition nests;
@@ -429,7 +474,7 @@ function toConfig(e, id, axis = e.axis) {
429
474
  * MULTI-OUTPUT target is nested as one PICKED output, its primary
430
475
  * (`studyInputOf`) — never bare, which would read whichever output it happens
431
476
  * to declare first (TDL-STUDYCHAIN). */
432
- const studySpec = (target, op, period) => {
477
+ const studySpec = (target, op, period, output) => {
433
478
  // Params come from the REGISTRY, not from a list here: an op is tuned by
434
479
  // exactly what it declares, so a two-param study (a band's `period` +
435
480
  // `stdDev`) is complete on arrival without this function knowing it exists.
@@ -456,7 +501,7 @@ const studySpec = (target, op, period) => {
456
501
  // and `deriveId` dedupes them. That is correct — ATR(14) of the bars is one
457
502
  // series — and it is why the picker has to refuse the op where its columns
458
503
  // are absent (`opNeedsColumns`) rather than let the fold skip it silently.
459
- const self = studyInputOf(target.derive ?? target.column);
504
+ const self = studyInputFor(target, output);
460
505
  const inputs = opInputs(op).map((r) =>
461
506
  // A target role takes the target; a bar role takes its own column. No
462
507
  // default and not a target role should be unreachable (a benchmark role is
@@ -476,8 +521,12 @@ const studySpec = (target, op, period) => {
476
521
  * source's params) with the op·period appended — e.g. `Price · SMA · 20`,
477
522
  * `ATM Vol · 21D · SMA · 20` — so the lineage is legible. Warm default colour so
478
523
  * it reads over its source; the user recolours. */
479
- function studyConfig(target, op, period, id, unitOf) {
480
- const derive = studySpec(target, op, period);
524
+ function studyConfig(target, op, period, id, unitOf, requested) {
525
+ const outputs = chosenOutputs(target, requested);
526
+ const derive = studySpec(target, op, period, outputs[0]);
527
+ // Several outputs make one study FANNED over them: `derive` reads the first,
528
+ // and each other line is the same chain with its pick swapped.
529
+ const fan = outputs.length > 1 ? outputs : undefined;
481
530
  // Only an `inherit` op may share its source's scale (pond's rule, shipped
482
531
  // with the catalog's `unit`). An RSI is bounded 0..100 and a vol reading is
483
532
  // ~20, so sharing stretches the axis five times and squashes the very series
@@ -489,9 +538,11 @@ function studyConfig(target, op, period, id, unitOf) {
489
538
  // (a bar's high/low read as its close) — the SAME resolution a re-spec uses,
490
539
  // so adding a study and retuning it can never disagree about its unit.
491
540
  const own = specUnit(derive, (col) => col === target.column ? (target.unit ?? '') : unitOf(col));
492
- // Which output of a multi-output target this study reads, named in the label
493
- // (`Price · DONCHIAN(20) · Middle · SMA(10)`) so the choice is never silent.
494
- const picked = derive.inputs.find(isPickedInput);
541
+ // Which output(s) of a multi-output target this study reads, named in the
542
+ // label (`Price · DONCHIAN(20) · Middle · SMA(10)`) so the choice is never
543
+ // silent — except where it says nothing new: a study of a fanned study run
544
+ // on every one of its lines reads exactly what its parent's label says.
545
+ const segment = outputsSegment(target, outputs);
495
546
  return {
496
547
  id,
497
548
  // Sharing means sharing the SOURCE's scale — which is the source's own axis
@@ -499,7 +550,7 @@ function studyConfig(target, op, period, id, unitOf) {
499
550
  // group landed on the row's shared axis instead, a line near zero drawn on
500
551
  // the price's scale.
501
552
  ...(shares ? (target.axisGroup ? { axisGroup: target.axisGroup } : {}) : { axisGroup: id }),
502
- label: `${target.label}${picked ? ` · ${picked.output}` : ''} · ${studyTag(derive)}`, // legend chip
553
+ label: `${target.label}${segment ? ` · ${segment}` : ''} · ${studyTag(derive)}`, // legend chip
503
554
  family: target.family ?? target.label, // main line = the source's name
504
555
  tenor: target.tenor, // carry the source's tenor into the params sub-line
505
556
  // A study is the same reading, smoothed — so it takes its metric's COLOUR
@@ -514,19 +565,24 @@ function studyConfig(target, op, period, id, unitOf) {
514
565
  // anything else is N lines off one spec, one per declared output. A
515
566
  // single-output study whose one output is a histogram (an Awesome
516
567
  // Oscillator) opens as bars; the user can still restyle it.
517
- style: opIsBand(op)
518
- ? 'band'
519
- : opIsMulti(op)
520
- ? 'lines'
521
- : outputMark(op, '') === 'bar'
522
- ? 'bar'
523
- : 'line',
568
+ style: fan
569
+ ? fanIsBand(fan)
570
+ ? 'band'
571
+ : 'lines'
572
+ : opIsBand(op)
573
+ ? 'band'
574
+ : opIsMulti(op)
575
+ ? 'lines'
576
+ : outputMark(op, '') === 'bar'
577
+ ? 'bar'
578
+ : 'line',
524
579
  visible: true,
525
580
  source: target.source,
526
581
  column: deriveId(derive),
527
582
  value: null,
528
583
  unit: shares ? target.unit : own,
529
584
  derive,
585
+ ...(fan ? { fan } : {}),
530
586
  // WHICH config this study is on — recorded now, because this is the one
531
587
  // moment it is known for certain: the user pressed THIS config's button.
532
588
  // The spec above names the target by column, which is the data; this
@@ -538,6 +594,27 @@ function studyConfig(target, op, period, id, unitOf) {
538
594
  ...recordParents(derive, [target]),
539
595
  };
540
596
  }
597
+ /** The outputs a new study of `target` runs on: what was asked for, in the
598
+ * target's own order and limited to what it offers, else its default. Empty
599
+ * for a single-output target. */
600
+ function chosenOutputs(target, requested) {
601
+ const offered = studyOutputsOf(target);
602
+ if (offered.length === 0)
603
+ return [];
604
+ const asked = requested ? inOfferedOrder(offered, requested) : [];
605
+ return asked.length > 0 ? asked : defaultStudyOutputs(target);
606
+ }
607
+ /** The label segment naming which outputs a study of `parent` reads, or
608
+ * `undefined` when there is nothing to say: a single-output parent, or a
609
+ * fanned parent continued on every one of its lines. */
610
+ function outputsSegment(parent, outputs) {
611
+ if (outputs.length === 0)
612
+ return undefined;
613
+ const fan = parent?.fan;
614
+ if (fan && fan.length === outputs.length && fan.every((o) => outputs.includes(o)))
615
+ return undefined;
616
+ return outputs.join(', ');
617
+ }
541
618
  /** Legend label per pair op — the spread reads as its construction. */
542
619
  const PAIR_LABEL = {
543
620
  diff: (a, b) => `${a} \u2212 ${b}`,
@@ -574,6 +651,9 @@ function legSeat(context, metricId) {
574
651
  */
575
652
  const resolveLeg = (context, id) => {
576
653
  const cfg = legSeat(context, id);
654
+ // A FANNED study is several lines, like a multi-output one: no single leg.
655
+ if (cfg?.fan && cfg.fan.length > 0)
656
+ return null;
577
657
  if (cfg)
578
658
  return {
579
659
  seatId: cfg.id,
@@ -729,7 +809,9 @@ palette = [], taken = [], spreadColor) {
729
809
  * carries no empty array.
730
810
  */
731
811
  function recordParents(derive, seats) {
732
- const parentIds = inputNames(derive).map((name) => seats.find((s) => s.column === name)?.id);
812
+ // `publishedColumns`: a study of ONE line of a fanned study reads that
813
+ // line's column, which is not the column the fanned config is named by.
814
+ const parentIds = inputNames(derive).map((name) => seats.find((s) => s.column === name || (!!s.fan && publishedColumns(s).includes(name)))?.id);
733
815
  return parentIds.some((id) => id != null) ? { parentIds } : {};
734
816
  }
735
817
  /**
@@ -874,6 +956,10 @@ export function outputAllowed(scope, id, output) {
874
956
  const target = configs.find((c) => c.id === id);
875
957
  if (!target?.derive)
876
958
  return false;
959
+ // A fanned study moves its outputs with `series.setStudyOutputs`, which
960
+ // keeps the fan and the spec in step; this event would move only the spec.
961
+ if (target.fan && target.fan.length > 0)
962
+ return false;
877
963
  const pick = studyPick(target.derive);
878
964
  if (!pick || !opOutputs(pick.from.op).includes(output))
879
965
  return false;
@@ -891,6 +977,112 @@ export function outputAllowed(scope, id, output) {
891
977
  return false;
892
978
  }
893
979
  }
980
+ /**
981
+ * The outputs a study can be set to run on — its PARENT's
982
+ * ({@link studyOutputsOf}), or, with no seated parent, every output its chain's
983
+ * multi-output source declares. Empty when it reads no multi-output source.
984
+ */
985
+ export function studyOutputChoices(scope, id) {
986
+ const configs = flatConfigs(scope.rows);
987
+ const study = configs.find((c) => c.id === id);
988
+ if (!study?.derive)
989
+ return [];
990
+ const pick = fanPick(study.derive);
991
+ if (!pick)
992
+ return [];
993
+ const parent = sourcesOf(configs, study)[0];
994
+ const offered = parent ? studyOutputsOf(parent) : [];
995
+ return offered.length > 0 ? offered : opOutputs(pick.from.op);
996
+ }
997
+ /** The outputs a study runs on now: its fan, else the one its chain picks. */
998
+ export function studyOutputsRead(study) {
999
+ if (study.fan && study.fan.length > 0)
1000
+ return [...study.fan];
1001
+ const pick = study.derive ? fanPick(study.derive) : undefined;
1002
+ return pick ? [pick.output] : [];
1003
+ }
1004
+ /**
1005
+ * A study re-pointed to run on `outputs` — its spec, fan, style and label;
1006
+ * `null` when the set is not one it can take.
1007
+ *
1008
+ * The identity stands, as for every retune. The spec reads the FIRST output
1009
+ * (so `column` and every one-spec reader keep working); more than one makes it
1010
+ * a fan, drawn as a band over a band's two edges and as lines otherwise. Going
1011
+ * back to one output gives back a single line — unless the study was already
1012
+ * drawing as something single-column the user chose (an area), which it keeps.
1013
+ */
1014
+ function respecOutputs(scope, study, outputs) {
1015
+ if (!study.derive)
1016
+ return null;
1017
+ const offered = studyOutputChoices(scope, study.id);
1018
+ if (offered.length === 0 || outputs.length === 0)
1019
+ return null;
1020
+ if (!outputs.every((o) => offered.includes(o)))
1021
+ return null;
1022
+ const next = inOfferedOrder(offered, outputs);
1023
+ // A fan runs a SINGLE-output study once per output (see `canAddStudy`).
1024
+ if (next.length > 1 && opOutputs(study.derive.op).length > 1)
1025
+ return null;
1026
+ const derive = withFanOutput(study.derive, next[0]);
1027
+ const fan = next.length > 1 ? next : undefined;
1028
+ const configs = flatConfigs(scope.rows);
1029
+ const parent = sourcesOf(configs, study)[0];
1030
+ // Swap the label's output segment, keeping whatever precedes it.
1031
+ const tag = ` · ${studyTag(study.derive)}`;
1032
+ const was = outputsSegment(parent, studyOutputsRead(study));
1033
+ const label = typeof study.label === 'string' ? study.label : '';
1034
+ const named = was ? ` · ${was}${tag}` : tag;
1035
+ const base = label.endsWith(named)
1036
+ ? label.slice(0, -named.length)
1037
+ : label.endsWith(tag)
1038
+ ? label.slice(0, -tag.length)
1039
+ : (study.family ?? label);
1040
+ const segment = outputsSegment(parent, next);
1041
+ const single = study.style === 'band' || study.style === 'lines' ? 'line' : study.style;
1042
+ return {
1043
+ ...study,
1044
+ derive,
1045
+ column: deriveId(derive),
1046
+ fan,
1047
+ style: fan ? (fanIsBand(fan) ? 'band' : 'lines') : opIsBand(study.derive.op) ? 'band' : single,
1048
+ label: `${base}${segment ? ` · ${segment}` : ''}${tag}`,
1049
+ };
1050
+ }
1051
+ /**
1052
+ * Whether a study can be set to run on `outputs` — shared by the guard and the
1053
+ * host, so a refused set renders disabled. Beyond {@link respecOutputs}'s own
1054
+ * refusals: nothing may change while the SAME set is asked for; a study with a
1055
+ * study built on it may only move between single outputs (its child reads one
1056
+ * of its lines, and a fan change would leave it reading a line no longer
1057
+ * drawn); and the result must stay coherent like any retune.
1058
+ *
1059
+ * Total: it runs in a guard.
1060
+ */
1061
+ export function outputsAllowed(scope, id, outputs) {
1062
+ try {
1063
+ const configs = flatConfigs(scope.rows);
1064
+ const study = configs.find((c) => c.id === id);
1065
+ if (!study?.derive)
1066
+ return false;
1067
+ const now = studyOutputsRead(study);
1068
+ const next = respecOutputs(scope, study, outputs);
1069
+ if (!next)
1070
+ return false;
1071
+ const want = studyOutputsRead(next);
1072
+ if (want.length === now.length && want.every((o, i) => o === now[i]))
1073
+ return false;
1074
+ if (hasStudyChild(configs, study) && (want.length > 1 || now.length > 1))
1075
+ return false;
1076
+ const re = propagateRespec(configs, id, next, unitOfColumn(scope));
1077
+ if (re === null || !unitsStayCoherent(scope.rows, re))
1078
+ return false;
1079
+ const borrowed = study.axisGroup != null && study.axisGroup !== study.id;
1080
+ return !(borrowed && re.get(id).unit !== (study.unit ?? ''));
1081
+ }
1082
+ catch {
1083
+ return false;
1084
+ }
1085
+ }
894
1086
  // --- fn() = None: the LEG GROUP ----------------------------------------------
895
1087
  // With no transform a pair has no single line and therefore no single ink, so
896
1088
  // it stops being one config and becomes TWO — each an ordinary series with its
@@ -1159,7 +1351,15 @@ function propagateRespec(configs, rootId, root, unitOf) {
1159
1351
  // line the user never touched computes.
1160
1352
  if (!readsFrom(configs, c, dep))
1161
1353
  continue;
1162
- spec = substituteInput(spec, dep.column, moved.derive);
1354
+ // A FANNED source publishes one column per line, and a dependent
1355
+ // may read any of them: re-point each at the same line of the
1356
+ // retuned chain. Its fan itself does not move with a retune.
1357
+ if (dep.fan && dep.fan.length > 0 && dep.derive) {
1358
+ for (const o of dep.fan)
1359
+ spec = substituteInput(spec, deriveId(withFanOutput(dep.derive, o)), withFanOutput(moved.derive, o));
1360
+ }
1361
+ else
1362
+ spec = substituteInput(spec, dep.column, moved.derive);
1163
1363
  }
1164
1364
  if (spec === before)
1165
1365
  continue;
@@ -1392,6 +1592,8 @@ function comparableMetric(c) {
1392
1592
  // which reads as the button silently skipping things.
1393
1593
  if (c.derive && opIsMulti(c.derive.op))
1394
1594
  return false;
1595
+ if (c.fan && c.fan.length > 0)
1596
+ return false; // a fan is several lines too
1395
1597
  return !c.column.startsWith(COMPARE_PREFIX);
1396
1598
  }
1397
1599
  export function canonRows(rows) {
@@ -1438,6 +1640,16 @@ export function canonRows(rows) {
1438
1640
  // a different preset from the same two joined, or from two unrelated
1439
1641
  // metrics that happen to be seated together.
1440
1642
  c.group ? [groupSlot(c.group.id), c.group.side, c.group.hidden ?? false] : null,
1643
+ c.lineDash ?? null,
1644
+ c.opacity ?? null,
1645
+ // Per-output ink, key-sorted so two equal maps written in different
1646
+ // orders hash alike. A fan is composition: which lines a study draws.
1647
+ c.outputStyles
1648
+ ? Object.keys(c.outputStyles)
1649
+ .sort()
1650
+ .map((k) => [k, c.outputStyles[k]])
1651
+ : null,
1652
+ c.fan ?? null,
1441
1653
  ]),
1442
1654
  ];
1443
1655
  }));
@@ -1525,7 +1737,19 @@ export const terminalMachine = setup({
1525
1737
  // (out-of-range period, malformed nested input), and a guard that throws
1526
1738
  // errors the whole actor (PR #130 review, HIGH). The machine is
1527
1739
  // host-driven — this guard IS the validation.
1528
- const spec = studySpec(target, event.op, event.period);
1740
+ // A requested output set must be one the target offers, and a FAN —
1741
+ // more than one — runs a single-output study once per output: fanning a
1742
+ // multi-output study (a MACD of each band edge) would draw a grid of
1743
+ // lines nothing can key, so it is refused rather than guessed at.
1744
+ const outputs = chosenOutputs(target, event.outputs);
1745
+ const offered = studyOutputsOf(target);
1746
+ if (offered.length > 0 && event.outputs && event.outputs.length > 0) {
1747
+ if (!event.outputs.every((o) => offered.includes(o)))
1748
+ return false;
1749
+ }
1750
+ if (outputs.length > 1 && opOutputs(event.op).length > 1)
1751
+ return false;
1752
+ const spec = studySpec(target, event.op, event.period, outputs[0]);
1529
1753
  // The same study may sit on two configs — an SMA on the price in each of
1530
1754
  // two rows, each copy then growing its own chain. That was refused
1531
1755
  // because every walk resolved by column and could not tell the two
@@ -1599,6 +1823,7 @@ export const terminalMachine = setup({
1599
1823
  // the actor-killing hazard `canAddStudy` guards (a throwing guard kills the
1600
1824
  // actor, and the `>= 2` pre-check does not cover the registry's max).
1601
1825
  canSetStudyOutput: ({ context, event }) => event.type === 'series.setStudyOutput' && outputAllowed(context, event.id, event.output),
1826
+ canSetStudyOutputs: ({ context, event }) => event.type === 'series.setStudyOutputs' && outputsAllowed(context, event.id, event.outputs),
1602
1827
  canSetStudyParam: ({ context, event }) => event.type === 'series.setStudyParam' &&
1603
1828
  respecAllowed(context, event.id, event.name, event.value),
1604
1829
  // The chain toggle — delegated to the shared pure helper so the panel's
@@ -1655,7 +1880,7 @@ export const terminalMachine = setup({
1655
1880
  // Every assigner in this `assign` sees the SAME pre-update context, so
1656
1881
  // the id minted here and the one `expanded`/`cfgSeq` compute below all
1657
1882
  // agree without threading a value between them.
1658
- const cfg = studyConfig(target, event.op, event.period, mintId(context.cfgSeq), unitOfColumn(context));
1883
+ const cfg = studyConfig(target, event.op, event.period, mintId(context.cfgSeq), unitOfColumn(context), event.outputs);
1659
1884
  // A study in its OWN units (an RSI, a MACD, an ATR) opens on a row of
1660
1885
  // its own, directly under its target's row (TDL-OSCROW). On the target's
1661
1886
  // row it drew over the price on a second scale, which is what the
@@ -1801,6 +2026,27 @@ export const terminalMachine = setup({
1801
2026
  return applyRespec(context, event.id, respecOutput(target, event.output));
1802
2027
  },
1803
2028
  }),
2029
+ setStudyOutputs: assign({
2030
+ rows: ({ context, event }) => {
2031
+ if (event.type !== 'series.setStudyOutputs')
2032
+ return context.rows;
2033
+ const study = flatConfigs(context.rows).find((c) => c.id === event.id);
2034
+ if (!study)
2035
+ return context.rows;
2036
+ const next = respecOutputs(context, study, event.outputs);
2037
+ if (!next)
2038
+ return context.rows;
2039
+ const rows = applyRespec(context, event.id, next);
2040
+ if (rows === context.rows)
2041
+ return rows; // refused: never half-apply
2042
+ // The spec moved through the one apply path; the fan and the style are
2043
+ // this edit's own and are written beside it.
2044
+ return rows.map((r) => ({
2045
+ ...r,
2046
+ configs: r.configs.map((c) => c.id === event.id ? { ...c, fan: next.fan, style: next.style } : c),
2047
+ }));
2048
+ },
2049
+ }),
1804
2050
  setStudyParam: assign({
1805
2051
  rows: ({ context, event }) => {
1806
2052
  if (event.type !== 'series.setStudyParam')
@@ -2022,16 +2268,52 @@ export const terminalMachine = setup({
2022
2268
  },
2023
2269
  }),
2024
2270
  patchSeries: assign({
2025
- rows: ({ context, event }) => event.type === 'series.patch'
2026
- ? context.rows.map((r) => ({
2271
+ rows: ({ context, event }) => {
2272
+ if (event.type !== 'series.patch')
2273
+ return context.rows;
2274
+ // A study's colour is its parent's until the user says otherwise
2275
+ // (Peter, 2026-10-11): recolouring a series recolours every study built
2276
+ // on it that still wears the colour it had — and leaves alone one that
2277
+ // was given its own. Matching on the OLD colour is what tells the two
2278
+ // apart without a second field to keep in step.
2279
+ // The walk goes study by study down from the recoloured series and
2280
+ // stops at a link that does not follow, so a grandchild under a study
2281
+ // given its own colour keeps its colour even if it matches the root's.
2282
+ // A pair is never a study of one leg, so it never follows.
2283
+ const follow = new Set();
2284
+ const configs = flatConfigs(context.rows);
2285
+ const target = configs.find((c) => c.id === event.id);
2286
+ const color = event.patch.color;
2287
+ if (target && typeof color === 'string' && color !== target.color) {
2288
+ const catalog = isCatalogColumn(context);
2289
+ const reached = [target];
2290
+ while (reached.length > 0) {
2291
+ const from = reached.pop();
2292
+ for (const c of configs) {
2293
+ if (c.id === target.id || follow.has(c.id) || !c.derive)
2294
+ continue;
2295
+ if (catalog(c.column) || readPairParts(c.derive) !== null)
2296
+ continue;
2297
+ if (c.color !== target.color || !readsFrom(configs, c, from))
2298
+ continue;
2299
+ follow.add(c.id);
2300
+ reached.push(c);
2301
+ }
2302
+ }
2303
+ }
2304
+ return context.rows.map((r) => ({
2027
2305
  ...r,
2028
2306
  configs: r.configs.map((c) =>
2029
2307
  // `parentIds` is the graph, not a presentation field: a patch
2030
2308
  // may not rewrite which config a study is on (an untyped host
2031
2309
  // could still send one).
2032
- c.id === event.id ? { ...c, ...event.patch, parentIds: c.parentIds } : c),
2033
- }))
2034
- : context.rows,
2310
+ c.id === event.id
2311
+ ? { ...c, ...event.patch, parentIds: c.parentIds }
2312
+ : follow.has(c.id)
2313
+ ? { ...c, color: color }
2314
+ : c),
2315
+ }));
2316
+ },
2035
2317
  }),
2036
2318
  toggleVisible: assign({
2037
2319
  rows: ({ context, event }) => {
@@ -2441,6 +2723,7 @@ export const terminalMachine = setup({
2441
2723
  },
2442
2724
  'series.setStudyParam': { guard: 'canSetStudyParam', actions: 'setStudyParam' },
2443
2725
  'series.setStudyOutput': { guard: 'canSetStudyOutput', actions: 'setStudyOutput' },
2726
+ 'series.setStudyOutputs': { guard: 'canSetStudyOutputs', actions: 'setStudyOutputs' },
2444
2727
  'series.order': { actions: 'orderSeries' },
2445
2728
  'series.reindex': { actions: 'orderSeries' },
2446
2729
  'series.moveToRow': { guard: 'canMoveToRow', actions: 'moveSeriesToRow' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/terminal",
3
- "version": "0.8.0",
3
+ "version": "0.11.0",
4
4
  "private": false,
5
5
  "description": "The terminal machine — an XState v5 statechart that owns a chart's configuration (rows, series, studies, pairs, axes, presets) and never its data.",
6
6
  "license": "MIT",
@@ -36,17 +36,17 @@
36
36
  "xstate": "^5.28.0"
37
37
  },
38
38
  "dependencies": {
39
- "@tidal-ts/chart": "0.8.0",
40
- "@tidal-ts/core": "0.8.0"
39
+ "@tidal-ts/chart": "0.11.0",
40
+ "@tidal-ts/core": "0.11.0"
41
41
  },
42
42
  "devDependencies": {
43
- "@pond-ts/charts": "^0.72.0",
44
- "@pond-ts/financial": "^0.72.0",
45
- "@pond-ts/process": "0.72.0",
46
- "@pond-ts/react": "^0.72.0",
43
+ "@pond-ts/charts": "^0.73.0",
44
+ "@pond-ts/financial": "^0.73.0",
45
+ "@pond-ts/process": "0.73.0",
46
+ "@pond-ts/react": "^0.73.0",
47
47
  "@types/react": "^18.3.18",
48
48
  "@xstate/react": "^6.1.0",
49
- "pond-ts": "^0.72.0",
49
+ "pond-ts": "^0.73.0",
50
50
  "react": "^18.3.1",
51
51
  "typescript": "^5.7.2",
52
52
  "vitest": "^2.1.8",