@tidal-ts/terminal 0.21.0 → 0.23.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
@@ -1,8 +1,8 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import type { InspectionEvent, Observer } from 'xstate';
3
- import type { DeriveOp } from '@tidal-ts/core';
3
+ import type { DeriveOp, PairOp } from '@tidal-ts/core';
4
4
  import type { AxisRange, PairLensOp, SeriesConfig } from '@tidal-ts/chart';
5
- import { type MetricEntry, type PairLegInput, type PresetStorage, type RowState, type TerminalPreset } from './terminalMachine.js';
5
+ import { type MetricEntry, type PairLegInput, type PresetSet, type PresetStorage, type RowState, type TerminalPreset } from './terminalMachine.js';
6
6
  export interface TerminalProviderProps {
7
7
  initialRows: RowState[];
8
8
  catalog: readonly MetricEntry[];
@@ -15,23 +15,30 @@ export interface TerminalProviderProps {
15
15
  /** What a new SPREAD draws in, when the host reserves a colour for one —
16
16
  * see {@link TerminalInput.spreadColor}. Absent ⇒ the first free palette key. */
17
17
  spreadColor?: string;
18
+ /** The preset set showing at mount — `compare` when the host reloads with a
19
+ * comparison named. Default `plain`. Read once, at mount: changing it later
20
+ * does nothing, so a host that switches sets as its comparison comes and
21
+ * goes sends {@link useSetPresetSet} instead. */
22
+ initialPresetSet?: PresetSet;
18
23
  /** An XState inspector (`@statelyai/inspect`'s `inspect`, or any observer of
19
24
  * inspection events). The host decides whether and when to attach one; the
20
25
  * machine has no opinion and no build-time flag. */
21
26
  inspect?: Observer<InspectionEvent> | ((event: InspectionEvent) => void);
22
27
  children: ReactNode;
23
28
  }
24
- export declare function TerminalProvider({ initialRows, catalog, storage, palette, spreadColor, inspect, children, }: TerminalProviderProps): import("react").JSX.Element;
29
+ export declare function TerminalProvider({ initialRows, catalog, storage, palette, spreadColor, initialPresetSet, inspect, children, }: TerminalProviderProps): import("react").JSX.Element;
25
30
  export declare function useRows(): RowState[];
26
31
  export declare function useSelectedSeries(): string | null;
27
32
  /** The control-panel expansion (the row whose controls are open) — overrides the
28
33
  * app selection for emphasis while set. Null when nothing is expanded. */
29
34
  export declare function useExpandedSeries(): string | null;
30
35
  export declare function useControlsOpen(): boolean;
31
- /** Which preset slots hold a saved preset (length === PRESET_SLOTS). */
36
+ /** The preset set showing (`plain` or `compare`). */
37
+ export declare function usePresetSet(): PresetSet;
38
+ /** Which slots of the showing set hold a saved preset (length === PRESET_SLOTS). */
32
39
  export declare function usePresetSaved(): boolean[];
33
- /** The active slot — the saved slot whose rows deep-equal the live rows — or
34
- * null (a custom state). Derived, not stored. */
40
+ /** The active slot of the showing set — the saved slot whose rows deep-equal
41
+ * the live rows — or null (a custom state). Derived, not stored. */
35
42
  export declare function useActiveSlot(): number | null;
36
43
  /** Per-axis range state, keyed by axis id (`configAxisId`). No entry = an
37
44
  * untouched auto axis; `mode:'auto'` with values = the preserved manual
@@ -47,6 +54,8 @@ export declare function useAddPair(): (a: PairLegInput, b: PairLegInput, op: Pai
47
54
  * comparison, in one gesture. Offer it only when a comparison is named — the
48
55
  * terminal machine cannot see whether one is. */
49
56
  export declare function useCompareAll(): () => void;
57
+ /** Set or clear (`null`) the function a compare applies to a metric. */
58
+ export declare function useSetCompareFn(): (id: string, fn: PairOp | null) => void;
50
59
  export declare function useSetStudyParam(): (id: string, name: string, value: number) => void;
51
60
  /** Switch which output of a multi-output source a study reads (the output
52
61
  * picker). Pair it with `outputAllowed` to render refused choices disabled. */
@@ -83,6 +92,8 @@ export declare function useExpandSeries(): (id: string | null) => void;
83
92
  export declare function useSetControlsOpen(): (open: boolean) => void;
84
93
  export declare function useSelectPreset(): (slot: number) => void;
85
94
  export declare function useSavePreset(): (slot: number) => void;
95
+ /** Show a preset set: `compare` while a comparison is named, else `plain`. */
96
+ export declare function useSetPresetSet(): (set: PresetSet) => void;
86
97
  export declare function useSetRowHeights(): (heights: Record<string, number>) => void;
87
98
  /** Toggle a series' axis membership — the panel's chain icon (unlink to its own
88
99
  * axis / unit-gated re-link into the side's shared axis; `linkToggleAllowed`
package/dist/context.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useCallback, useEffect } from 'react';
2
+ import { useCallback, useEffect, useRef } from 'react';
3
3
  import { createActorContext } from '@xstate/react';
4
4
  import { activeSlot, terminalMachine, } from './terminalMachine.js';
5
5
  /**
@@ -8,7 +8,7 @@ import { activeSlot, terminalMachine, } from './terminalMachine.js';
8
8
  * barrel re-exports these + the event union; the actor + machine stay private.
9
9
  */
10
10
  const TerminalContext = createActorContext(terminalMachine);
11
- export function TerminalProvider({ initialRows, catalog, storage, palette, spreadColor, inspect, children, }) {
11
+ export function TerminalProvider({ initialRows, catalog, storage, palette, spreadColor, initialPresetSet, inspect, children, }) {
12
12
  return (_jsxs(TerminalContext.Provider, { options: {
13
13
  input: {
14
14
  initialRows,
@@ -16,6 +16,7 @@ export function TerminalProvider({ initialRows, catalog, storage, palette, sprea
16
16
  storage,
17
17
  ...(palette ? { palette } : {}),
18
18
  ...(spreadColor ? { spreadColor } : {}),
19
+ ...(initialPresetSet ? { initialPresetSet } : {}),
19
20
  },
20
21
  ...(inspect ? { inspect } : {}),
21
22
  }, children: [_jsx(PersistActive, { storage: storage }), children] }));
@@ -23,10 +24,27 @@ export function TerminalProvider({ initialRows, catalog, storage, palette, sprea
23
24
  /** Persists the derived active-slot pointer so a fresh mount (a reload) can
24
25
  * re-seed from the last applied preset (see `seedTerminalRows`). The machine
25
26
  * owns preset *contents*; this is the only writer of the pointer. Renders
26
- * nothing. */
27
+ * nothing.
28
+ *
29
+ * It writes on a change, never at mount: the state a mount starts in came
30
+ * from what storage already holds, so there is nothing new to save — and a
31
+ * host whose set arrives a moment after mount (a comparison that resolves
32
+ * late) would otherwise overwrite the stored pointer with null first. */
27
33
  function PersistActive({ storage }) {
28
34
  const active = useActiveSlot();
29
- useEffect(() => storage.saveActive(active), [active, storage]);
35
+ const set = usePresetSet();
36
+ const last = useRef(null);
37
+ useEffect(() => {
38
+ const key = active == null ? 'none' : `${set}:${active}`;
39
+ if (last.current === null) {
40
+ last.current = key;
41
+ return;
42
+ }
43
+ if (last.current === key)
44
+ return;
45
+ last.current = key;
46
+ storage.saveActive(active == null ? null : { set, slot: active });
47
+ }, [active, set, storage]);
30
48
  return null;
31
49
  }
32
50
  // --- Read surface ----------------------------------------------------------
@@ -44,14 +62,18 @@ export function useExpandedSeries() {
44
62
  export function useControlsOpen() {
45
63
  return TerminalContext.useSelector((s) => s.context.controlsOpen);
46
64
  }
47
- /** Which preset slots hold a saved preset (length === PRESET_SLOTS). */
65
+ /** The preset set showing (`plain` or `compare`). */
66
+ export function usePresetSet() {
67
+ return TerminalContext.useSelector((s) => s.context.presetSet);
68
+ }
69
+ /** Which slots of the showing set hold a saved preset (length === PRESET_SLOTS). */
48
70
  export function usePresetSaved() {
49
- return TerminalContext.useSelector((s) => s.context.presets.map((p) => p != null));
71
+ return TerminalContext.useSelector((s) => s.context.presets[s.context.presetSet].map((p) => p != null));
50
72
  }
51
- /** The active slot — the saved slot whose rows deep-equal the live rows — or
52
- * null (a custom state). Derived, not stored. */
73
+ /** The active slot of the showing set — the saved slot whose rows deep-equal
74
+ * the live rows — or null (a custom state). Derived, not stored. */
53
75
  export function useActiveSlot() {
54
- return TerminalContext.useSelector((s) => activeSlot(s.context.presets, s.context.rows));
76
+ return TerminalContext.useSelector((s) => activeSlot(s.context.presets[s.context.presetSet], s.context.rows));
55
77
  }
56
78
  /** Per-axis range state, keyed by axis id (`configAxisId`). No entry = an
57
79
  * untouched auto axis; `mode:'auto'` with values = the preserved manual
@@ -82,6 +104,11 @@ export function useCompareAll() {
82
104
  const ref = TerminalContext.useActorRef();
83
105
  return useCallback(() => ref.send({ type: 'series.compareAll' }), [ref]);
84
106
  }
107
+ /** Set or clear (`null`) the function a compare applies to a metric. */
108
+ export function useSetCompareFn() {
109
+ const ref = TerminalContext.useActorRef();
110
+ return useCallback((id, fn) => ref.send({ type: 'series.setCompareFn', id, fn }), [ref]);
111
+ }
85
112
  export function useSetStudyParam() {
86
113
  const ref = TerminalContext.useActorRef();
87
114
  return useCallback((id, name, value) => ref.send({ type: 'series.setStudyParam', id, name, value }), [ref]);
@@ -175,6 +202,11 @@ export function useSavePreset() {
175
202
  const ref = TerminalContext.useActorRef();
176
203
  return useCallback((slot) => ref.send({ type: 'preset.save', slot }), [ref]);
177
204
  }
205
+ /** Show a preset set: `compare` while a comparison is named, else `plain`. */
206
+ export function useSetPresetSet() {
207
+ const ref = TerminalContext.useActorRef();
208
+ return useCallback((set) => ref.send({ type: 'preset.useSet', set }), [ref]);
209
+ }
178
210
  export function useSetRowHeights() {
179
211
  const ref = TerminalContext.useActorRef();
180
212
  return useCallback((heights) => ref.send({ type: 'layout.setRowHeights', heights }), [ref]);
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, useSetStudyInput, useSetDataColumns, 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, inputAllowed, dataColumnsAllowed, 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';
8
+ export { TerminalProvider, useRows, useSelectedSeries, useExpandedSeries, useControlsOpen, usePresetSaved, useActiveSlot, useAddSeries, useAddPair, useCompareAll, useAddStudy, useSetCompareFn, useSetStudyParam, useSetStudyOutput, useSetStudyInput, useSetDataColumns, useSetStudyOutputs, useOrderSeries, useReindexSeries, useMoveSeriesToRow, useMoveToAxis, useRemoveSeries, usePatchSeries, useToggleVisible, useToggleGroupVisible, useRemoveGroup, useSelectSeries, useExpandSeries, useSetControlsOpen, useSelectPreset, useSavePreset, useSetPresetSet, usePresetSet, useSetRowHeights, useAddRow, useRemoveRow, useAxisRanges, useToggleAxisLink, useSwapAxisSide, useSetAxisRange, useSetAxisAuto, useSetAxisLocks, useSetAxisAutoOpts, useSetAxisFormat, useTerminalHotkeys, type TerminalProviderProps, } from './context.js';
9
+ export { PRESET_SLOTS, PRESET_SETS, type PresetSet, type PresetSlot, MAX_ROWS, activeSlot, canonRows, columnLabel, columnUnits, compareFnAllowed, entryColumn, groupMembers, mintId, axisMoveAllowed, linkToggleAllowed, respecAllowed, outputAllowed, inputAllowed, dataColumnsAllowed, 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, useSetStudyInput, useSetDataColumns, 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, inputAllowed, dataColumnsAllowed, outputsAllowed, studyOutputChoices, studyOutputsOf, studyOutputsRead, defaultStudyOutputs, studyChainTail, studyOfferable, SOURCE_COLUMNS, swapAllowed, } from './terminalMachine.js';
8
+ export { TerminalProvider, useRows, useSelectedSeries, useExpandedSeries, useControlsOpen, usePresetSaved, useActiveSlot, useAddSeries, useAddPair, useCompareAll, useAddStudy, useSetCompareFn, useSetStudyParam, useSetStudyOutput, useSetStudyInput, useSetDataColumns, useSetStudyOutputs, useOrderSeries, useReindexSeries, useMoveSeriesToRow, useMoveToAxis, useRemoveSeries, usePatchSeries, useToggleVisible, useToggleGroupVisible, useRemoveGroup, useSelectSeries, useExpandSeries, useSetControlsOpen, useSelectPreset, useSavePreset, useSetPresetSet, usePresetSet, useSetRowHeights, useAddRow, useRemoveRow, useAxisRanges, useToggleAxisLink, useSwapAxisSide, useSetAxisRange, useSetAxisAuto, useSetAxisLocks, useSetAxisAutoOpts, useSetAxisFormat, useTerminalHotkeys, } from './context.js';
9
+ export { PRESET_SLOTS, PRESET_SETS, MAX_ROWS, activeSlot, canonRows, columnLabel, columnUnits, compareFnAllowed, entryColumn, groupMembers, mintId, axisMoveAllowed, linkToggleAllowed, respecAllowed, outputAllowed, inputAllowed, dataColumnsAllowed, 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).
@@ -1,4 +1,4 @@
1
- import { type DeriveOp, type DeriveSpec } from '@tidal-ts/core';
1
+ import { type DeriveOp, type DeriveSpec, type PairOp } from '@tidal-ts/core';
2
2
  /**
3
3
  * The bar columns each data SOURCE carries — the one fact that decides whether a
4
4
  * multi-column study is offerable on a series. Only the price series has bars;
@@ -66,16 +66,30 @@ export interface MetricEntry {
66
66
  * this spec by `applyDerived`, not read from the feed. Absent ⇒ raw. */
67
67
  derive?: DeriveSpec;
68
68
  }
69
+ /**
70
+ * The two **preset sets**: `plain` (P1…) for a chart of one symbol, `compare`
71
+ * (C1…) for a chart with a comparison named. Both store the same shape; the
72
+ * host says which one is showing (`preset.useSet`), since only it knows whether
73
+ * a comparison is named.
74
+ */
75
+ export type PresetSet = 'plain' | 'compare';
76
+ export declare const PRESET_SETS: readonly PresetSet[];
77
+ /** A slot in one set: what the active-preset pointer persists. */
78
+ export interface PresetSlot {
79
+ set: PresetSet;
80
+ slot: number;
81
+ }
69
82
  /** Injectable persistence for the preset slots (default: the app's localStorage
70
83
  * keys). A host brings its own storage, or none. */
71
84
  export interface PresetStorage {
72
- loadPresets(): (TerminalPreset | null)[];
73
- savePresets(presets: (TerminalPreset | null)[]): void;
85
+ loadPresets(set: PresetSet): (TerminalPreset | null)[];
86
+ savePresets(set: PresetSet, presets: (TerminalPreset | null)[]): void;
74
87
  /** The persisted active-slot pointer — only used to seed `initialRows`. */
75
- loadActive(): number | null;
76
- saveActive(index: number | null): void;
88
+ loadActive(): PresetSlot | null;
89
+ saveActive(active: PresetSlot | null): void;
77
90
  }
78
- export declare const PRESET_SLOTS = 5;
91
+ /** Slots in each preset set. */
92
+ export declare const PRESET_SLOTS = 6;
79
93
  /** Max viewport rows (the control-panel spec: 1–3, capped at 3 for now). */
80
94
  export declare const MAX_ROWS = 3;
81
95
  export declare const mintId: (seq: number) => string;
@@ -109,7 +123,11 @@ interface TerminalContext {
109
123
  * on collapse or closing the panel, so emphasis falls back to `selected`. */
110
124
  expanded: string | null;
111
125
  controlsOpen: boolean;
112
- presets: (TerminalPreset | null)[];
126
+ /** Each set's slots, {@link PRESET_SLOTS} long. */
127
+ presets: Record<PresetSet, (TerminalPreset | null)[]>;
128
+ /** The set the host is showing — `compare` while a comparison is named. The
129
+ * slot events and the active slot read this one. */
130
+ presetSet: PresetSet;
113
131
  catalog: readonly MetricEntry[];
114
132
  storage: PresetStorage;
115
133
  }
@@ -218,11 +236,21 @@ export type TerminalEvent = {
218
236
  | {
219
237
  type: 'series.patch';
220
238
  id: string;
221
- patch: Partial<Omit<SeriesConfig, 'axis' | 'axisGroup' | 'parentIds'>>;
239
+ patch: Partial<Omit<SeriesConfig, 'axis' | 'axisGroup' | 'parentIds' | 'compareFn'>>;
222
240
  } | {
223
241
  type: 'series.toggleVisible';
224
242
  id: string;
225
243
  }
244
+ /** Set or clear the function a compare applies to a metric
245
+ * ({@link SeriesConfig.compareFn}) — `null` clears it, so the metric draws
246
+ * once per symbol again. Refused for anything {@link compareFnAllowed}
247
+ * refuses. Allowed with no comparison named: the function sleeps until
248
+ * there is one, and the machine cannot see whether there is. */
249
+ | {
250
+ type: 'series.setCompareFn';
251
+ id: string;
252
+ fn: PairOp | null;
253
+ }
226
254
  /** The PAIR's own eye — hides both legs at once. Each leg keeps its own
227
255
  * `visible`, so unhiding the pair restores what each leg was rather than
228
256
  * switching everything on (Peter, 2026-08-18). */
@@ -250,6 +278,12 @@ export type TerminalEvent = {
250
278
  } | {
251
279
  type: 'preset.save';
252
280
  slot: number;
281
+ }
282
+ /** Show the other preset set: the host sends `compare` when a comparison is
283
+ * named and `plain` when it is cleared. The rows are left alone. */
284
+ | {
285
+ type: 'preset.useSet';
286
+ set: PresetSet;
253
287
  } | {
254
288
  type: 'layout.setRowHeights';
255
289
  heights: Record<string, number>;
@@ -333,6 +367,9 @@ export interface TerminalInput {
333
367
  initialRows: RowState[];
334
368
  catalog: readonly MetricEntry[];
335
369
  storage: PresetStorage;
370
+ /** The preset set showing at start (the host's comparison, on a reload).
371
+ * Default `plain`. */
372
+ initialPresetSet?: PresetSet;
336
373
  /** The colour keys the host hands a new series, in order — see
337
374
  * `TerminalProviderProps.palette`. Default: none (a leg keeps its pair's). */
338
375
  palette?: readonly string[];
@@ -571,6 +608,20 @@ export declare function linkToggleAllowed(configs: readonly SeriesConfig[], id:
571
608
  * gutters.
572
609
  */
573
610
  export declare function swapAllowed(configs: readonly SeriesConfig[], id: string): boolean;
611
+ /**
612
+ * Whether a seated config can carry a compare function
613
+ * ({@link SeriesConfig.compareFn}).
614
+ *
615
+ * Only the ROOT of a chain — a metric, raw or a derived catalog metric, never
616
+ * a study: the function sits straight after the metric and every study on it
617
+ * runs on the joined line, so a study carrying its own would be a second join
618
+ * inside the first. And only something that has one reading per symbol:
619
+ * refused for anything that already states its own symbols (a leg of a leg
620
+ * group, a spread, anything reading the comparison) and for anything that
621
+ * draws several lines (a band, a multi-output metric, a fan), which has no
622
+ * single line to divide by another.
623
+ */
624
+ export declare function compareFnAllowed(c: SeriesConfig): boolean;
574
625
  export declare function canonRows(rows: readonly RowState[]): string;
575
626
  /** The active slot: first saved preset whose rows deep-equal the live rows, else
576
627
  * null (custom). The single derivation behind the filled circle + the seed. */
@@ -632,10 +683,14 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
632
683
  } | {
633
684
  type: "series.patch";
634
685
  id: string;
635
- patch: Partial<Omit<SeriesConfig, "axis" | "axisGroup" | "parentIds">>;
686
+ patch: Partial<Omit<SeriesConfig, "axis" | "axisGroup" | "parentIds" | "compareFn">>;
636
687
  } | {
637
688
  type: "series.toggleVisible";
638
689
  id: string;
690
+ } | {
691
+ type: "series.setCompareFn";
692
+ id: string;
693
+ fn: PairOp | null;
639
694
  } | {
640
695
  type: "group.toggleVisible";
641
696
  groupId: string;
@@ -658,6 +713,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
658
713
  } | {
659
714
  type: "preset.save";
660
715
  slot: number;
716
+ } | {
717
+ type: "preset.useSet";
718
+ set: PresetSet;
661
719
  } | {
662
720
  type: "layout.setRowHeights";
663
721
  heights: Record<string, number>;
@@ -745,6 +803,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
745
803
  } | {
746
804
  type: "moveSeriesToRow";
747
805
  params: import("xstate").NonReducibleUnknown;
806
+ } | {
807
+ type: "setCompareFn";
808
+ params: import("xstate").NonReducibleUnknown;
748
809
  } | {
749
810
  type: "patchSeries";
750
811
  params: import("xstate").NonReducibleUnknown;
@@ -769,6 +830,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
769
830
  } | {
770
831
  type: "savePreset";
771
832
  params: import("xstate").NonReducibleUnknown;
833
+ } | {
834
+ type: "usePresetSet";
835
+ params: import("xstate").NonReducibleUnknown;
772
836
  } | {
773
837
  type: "setRowHeights";
774
838
  params: import("xstate").NonReducibleUnknown;
@@ -823,6 +887,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
823
887
  } | {
824
888
  type: "canSetStudyOutputs";
825
889
  params: unknown;
890
+ } | {
891
+ type: "canSetCompareFn";
892
+ params: unknown;
826
893
  } | {
827
894
  type: "canSetStudyParam";
828
895
  params: unknown;
@@ -34,7 +34,20 @@ function hidesPointer(context, toggledId, pointer) {
34
34
  import { axisRangeIsEmpty, logAllowed, isStudySeries, readsFrom, sourcesOf, fanIsBand, offersOutputBars, publishedColumns, } from '@tidal-ts/chart';
35
35
  import { configAxisId, seriesAxisId, sharedAxisId, } from '@tidal-ts/chart';
36
36
  import { axisForAdd, canAddUnit } from './axisPolicy.js';
37
- export const PRESET_SLOTS = 5;
37
+ export const PRESET_SETS = ['plain', 'compare'];
38
+ /** Slots in each preset set. */
39
+ export const PRESET_SLOTS = 6;
40
+ /** Whatever storage handed back, as exactly {@link PRESET_SLOTS} slots: a
41
+ * shorter list (an older build kept fewer) is padded with empty slots, a
42
+ * longer one is cut, and anything that isn't a list — or an entry that isn't
43
+ * a preset — reads as empty. */
44
+ function toSlots(raw) {
45
+ const list = Array.isArray(raw) ? raw : [];
46
+ return Array.from({ length: PRESET_SLOTS }, (_, i) => {
47
+ const p = list[i];
48
+ return p != null && typeof p === 'object' && Array.isArray(p.rows) ? p : null;
49
+ });
50
+ }
38
51
  /** Max viewport rows (the control-panel spec: 1–3, capped at 3 for now). */
39
52
  export const MAX_ROWS = 3;
40
53
  /**
@@ -1057,6 +1070,12 @@ export function dataColumnsAllowed(scope, id, columns) {
1057
1070
  * presentation field: a patch may not rewrite which config a study is on.
1058
1071
  */
1059
1072
  function coherentPatch(c, patch) {
1073
+ // `compareFn` is set only through `series.setCompareFn` and its guard; a
1074
+ // patch that names it (an untyped caller) is not let around that guard.
1075
+ const { compareFn: _ignored, ...asked } = patch;
1076
+ return keepCompareFnCoherent(drawablePatch(c, asked));
1077
+ }
1078
+ function drawablePatch(c, patch) {
1060
1079
  const next = { ...c, ...patch, parentIds: c.parentIds };
1061
1080
  if (next.derive)
1062
1081
  return next;
@@ -1069,6 +1088,18 @@ function coherentPatch(c, patch) {
1069
1088
  return { ...next, style: c.style === 'band' ? 'line' : c.style };
1070
1089
  return next;
1071
1090
  }
1091
+ /**
1092
+ * A config that has stopped being one a compare function may sit on — it
1093
+ * joined a pair as a leg, took a fan, took a band style — drops the function,
1094
+ * so a saved config never carries one {@link compareFnAllowed} refuses (PR #45
1095
+ * review). Everything else passes through unchanged.
1096
+ */
1097
+ function keepCompareFnCoherent(c) {
1098
+ if (!c.compareFn || compareFnAllowed(c))
1099
+ return c;
1100
+ const { compareFn: _drop, ...rest } = c;
1101
+ return rest;
1102
+ }
1072
1103
  /** Bar price columns in the bar's own order. */
1073
1104
  const barOrder = (columns) => [...columns].sort((a, b) => BAR_PRICE_COLUMNS.indexOf(a) - BAR_PRICE_COLUMNS.indexOf(b));
1074
1105
  /**
@@ -1770,6 +1801,38 @@ function comparableMetric(c) {
1770
1801
  return false; // a fan is several lines too
1771
1802
  return !c.column.startsWith(COMPARE_PREFIX);
1772
1803
  }
1804
+ /**
1805
+ * Whether a seated config can carry a compare function
1806
+ * ({@link SeriesConfig.compareFn}).
1807
+ *
1808
+ * Only the ROOT of a chain — a metric, raw or a derived catalog metric, never
1809
+ * a study: the function sits straight after the metric and every study on it
1810
+ * runs on the joined line, so a study carrying its own would be a second join
1811
+ * inside the first. And only something that has one reading per symbol:
1812
+ * refused for anything that already states its own symbols (a leg of a leg
1813
+ * group, a spread, anything reading the comparison) and for anything that
1814
+ * draws several lines (a band, a multi-output metric, a fan), which has no
1815
+ * single line to divide by another.
1816
+ */
1817
+ export function compareFnAllowed(c) {
1818
+ if (c.group)
1819
+ return false;
1820
+ if (c.column.startsWith(COMPARE_PREFIX))
1821
+ return false;
1822
+ if (c.style === 'band' || c.style === 'lines')
1823
+ return false;
1824
+ if (c.fan && c.fan.length > 0)
1825
+ return false;
1826
+ if (c.derive) {
1827
+ if (isStudyOp(c.derive.op))
1828
+ return false;
1829
+ if (hasPairOp(c.derive) || usesCompare(c.derive))
1830
+ return false;
1831
+ if (opIsMulti(c.derive.op) || opIsBand(c.derive.op))
1832
+ return false;
1833
+ }
1834
+ return true;
1835
+ }
1773
1836
  export function canonRows(rows) {
1774
1837
  return JSON.stringify(rows.map((r) => {
1775
1838
  // Axis membership is preset identity — but `axisGroup` is a MINTED config
@@ -1828,6 +1891,10 @@ export function canonRows(rows) {
1828
1891
  .map((k) => [k, c.outputStyles[k]])
1829
1892
  : null,
1830
1893
  c.fan ?? null,
1894
+ // How the metric reads under a comparison: one joined line or two.
1895
+ // Appended only when set, so a config without one hashes exactly as
1896
+ // it did before the field existed and a saved preset still matches.
1897
+ ...(c.compareFn ? [c.compareFn] : []),
1831
1898
  ]),
1832
1899
  ];
1833
1900
  }));
@@ -2005,6 +2072,16 @@ export const terminalMachine = setup({
2005
2072
  canSetDataColumns: ({ context, event }) => event.type === 'series.setDataColumns' &&
2006
2073
  dataColumnsAllowed(context, event.id, event.columns),
2007
2074
  canSetStudyOutputs: ({ context, event }) => event.type === 'series.setStudyOutputs' && outputsAllowed(context, event.id, event.outputs),
2075
+ canSetCompareFn: ({ context, event }) => {
2076
+ if (event.type !== 'series.setCompareFn')
2077
+ return false;
2078
+ const target = flatConfigs(context.rows).find((c) => c.id === event.id);
2079
+ if (!target)
2080
+ return false;
2081
+ // Clearing is always allowed: a function persisted on something that
2082
+ // can no longer carry one must still be removable.
2083
+ return event.fn === null || (isPairOp(event.fn) && compareFnAllowed(target));
2084
+ },
2008
2085
  canSetStudyParam: ({ context, event }) => event.type === 'series.setStudyParam' &&
2009
2086
  respecAllowed(context, event.id, event.name, event.value),
2010
2087
  // The chain toggle — delegated to the shared pure helper so the panel's
@@ -2148,7 +2225,7 @@ export const terminalMachine = setup({
2148
2225
  ...r,
2149
2226
  configs: (r.id === row.id ? [...plan.create, ...r.configs] : r.configs).map((c) => {
2150
2227
  const group = tag.get(c.id);
2151
- return group ? { ...c, group } : c;
2228
+ return group ? keepCompareFnCoherent({ ...c, group }) : c;
2152
2229
  }),
2153
2230
  }));
2154
2231
  }
@@ -2265,7 +2342,7 @@ export const terminalMachine = setup({
2265
2342
  if (i >= 0 && c.parentIds?.[i] == null)
2266
2343
  orphans.set(c.id, i);
2267
2344
  }
2268
- const next = dataColumnsConfig(node, event.columns);
2345
+ const next = keepCompareFnCoherent(dataColumnsConfig(node, event.columns));
2269
2346
  return context.rows.map((r) => ({
2270
2347
  ...r,
2271
2348
  configs: r.configs.map((c) => {
@@ -2522,6 +2599,25 @@ export const terminalMachine = setup({
2522
2599
  return pruneEmptied(context.rows, mapped);
2523
2600
  },
2524
2601
  }),
2602
+ setCompareFn: assign({
2603
+ rows: ({ context, event }) => {
2604
+ if (event.type !== 'series.setCompareFn')
2605
+ return context.rows;
2606
+ return context.rows.map((r) => r.configs.some((c) => c.id === event.id)
2607
+ ? {
2608
+ ...r,
2609
+ configs: r.configs.map((c) => {
2610
+ if (c.id !== event.id)
2611
+ return c;
2612
+ // Cleared by REMOVING the key, so a cleared config and one
2613
+ // that never had a function persist the same shape.
2614
+ const { compareFn: _drop, ...rest } = c;
2615
+ return event.fn ? { ...rest, compareFn: event.fn } : rest;
2616
+ }),
2617
+ }
2618
+ : r);
2619
+ },
2620
+ }),
2525
2621
  patchSeries: assign({
2526
2622
  rows: ({ context, event }) => {
2527
2623
  if (event.type !== 'series.patch')
@@ -2634,7 +2730,7 @@ export const terminalMachine = setup({
2634
2730
  rows: ({ context, event }) => {
2635
2731
  if (event.type !== 'preset.select')
2636
2732
  return context.rows;
2637
- const p = context.presets[event.slot];
2733
+ const p = context.presets[context.presetSet][event.slot];
2638
2734
  // A preset saved before the invariant existed can carry a stack with no
2639
2735
  // remainder row, which would reproduce the stuck-seam bug on apply.
2640
2736
  return p ? withRemainder(cloneRows(p.rows)) : context.rows;
@@ -2649,11 +2745,11 @@ export const terminalMachine = setup({
2649
2745
  // duplicate row ids collide in `setRowHeights`, in `configAxisId`, and in
2650
2746
  // every find-by-rowId.
2651
2747
  cfgSeq: ({ context, event }) => {
2652
- const p = event.type === 'preset.select' ? context.presets[event.slot] : null;
2748
+ const p = event.type === 'preset.select' ? context.presets[context.presetSet][event.slot] : null;
2653
2749
  return p ? Math.max(context.cfgSeq, cfgSeqAfter(p.rows)) : context.cfgSeq;
2654
2750
  },
2655
2751
  rowSeq: ({ context, event }) => {
2656
- const p = event.type === 'preset.select' ? context.presets[event.slot] : null;
2752
+ const p = event.type === 'preset.select' ? context.presets[context.presetSet][event.slot] : null;
2657
2753
  return p ? Math.max(context.rowSeq, rowSeqAfter(p.rows)) : context.rowSeq;
2658
2754
  },
2659
2755
  // Presets are COMPOSITION; per-axis ranges are ARRANGEMENT and aren't
@@ -2661,18 +2757,26 @@ export const terminalMachine = setup({
2661
2757
  // leak: a manual range pinned under different rows reads as a broken
2662
2758
  // chart with no visible cause. Membership (`axisGroup`) DOES restore — it
2663
2759
  // lives on the configs.
2664
- axisRanges: ({ context, event }) => event.type === 'preset.select' && context.presets[event.slot] ? {} : context.axisRanges,
2760
+ axisRanges: ({ context, event }) => event.type === 'preset.select' && context.presets[context.presetSet][event.slot]
2761
+ ? {}
2762
+ : context.axisRanges,
2665
2763
  }),
2666
2764
  savePreset: assign({
2667
2765
  presets: ({ context, event }) => {
2668
2766
  if (event.type !== 'preset.save')
2669
2767
  return context.presets;
2670
- const next = context.presets.slice();
2768
+ const set = context.presetSet;
2769
+ const next = context.presets[set].slice();
2671
2770
  next[event.slot] = { rows: cloneRows(context.rows) };
2672
- context.storage.savePresets(next);
2673
- return next;
2771
+ context.storage.savePresets(set, next);
2772
+ return { ...context.presets, [set]: next };
2674
2773
  },
2675
2774
  }),
2775
+ usePresetSet: assign({
2776
+ presetSet: ({ context, event }) => event.type === 'preset.useSet' && PRESET_SETS.includes(event.set)
2777
+ ? event.set
2778
+ : context.presetSet,
2779
+ }),
2676
2780
  setRowHeights: assign({
2677
2781
  rows: ({ context, event }) => event.type === 'layout.setRowHeights'
2678
2782
  ? // `withRemainder` because a commit is a full height map: a drag that
@@ -2949,7 +3053,11 @@ export const terminalMachine = setup({
2949
3053
  selected: null,
2950
3054
  expanded: null,
2951
3055
  controlsOpen: false,
2952
- presets: input.storage.loadPresets(),
3056
+ presets: {
3057
+ plain: toSlots(input.storage.loadPresets('plain')),
3058
+ compare: toSlots(input.storage.loadPresets('compare')),
3059
+ },
3060
+ presetSet: input.initialPresetSet ?? 'plain',
2953
3061
  catalog: input.catalog,
2954
3062
  storage: input.storage,
2955
3063
  }),
@@ -2986,6 +3094,7 @@ export const terminalMachine = setup({
2986
3094
  'series.moveToRow': { guard: 'canMoveToRow', actions: 'moveSeriesToRow' },
2987
3095
  'series.remove': { actions: 'removeSeries' },
2988
3096
  'series.patch': { actions: 'patchSeries' },
3097
+ 'series.setCompareFn': { guard: 'canSetCompareFn', actions: 'setCompareFn' },
2989
3098
  'series.toggleVisible': { actions: 'toggleVisible' },
2990
3099
  'group.toggleVisible': { actions: 'toggleGroupVisible' },
2991
3100
  'group.remove': { actions: 'removeGroup' },
@@ -2995,6 +3104,7 @@ export const terminalMachine = setup({
2995
3104
  'controls.close': { actions: 'closeControls' },
2996
3105
  'preset.select': { actions: 'applyPreset' },
2997
3106
  'preset.save': { actions: 'savePreset' },
3107
+ 'preset.useSet': { actions: 'usePresetSet' },
2998
3108
  'layout.setRowHeights': { actions: 'setRowHeights' },
2999
3109
  'row.add': { guard: 'canAddRow', actions: 'addRow' },
3000
3110
  'row.remove': { actions: 'removeRow' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/terminal",
3
- "version": "0.21.0",
3
+ "version": "0.23.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,8 +36,8 @@
36
36
  "xstate": "^5.28.0"
37
37
  },
38
38
  "dependencies": {
39
- "@tidal-ts/chart": "0.21.0",
40
- "@tidal-ts/core": "0.21.0"
39
+ "@tidal-ts/chart": "0.23.0",
40
+ "@tidal-ts/core": "0.23.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@pond-ts/charts": "^0.78.0",