@tidal-ts/terminal 0.21.0 → 0.22.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,6 +1,6 @@
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
5
  import { type MetricEntry, type PairLegInput, type PresetStorage, type RowState, type TerminalPreset } from './terminalMachine.js';
6
6
  export interface TerminalProviderProps {
@@ -47,6 +47,8 @@ export declare function useAddPair(): (a: PairLegInput, b: PairLegInput, op: Pai
47
47
  * comparison, in one gesture. Offer it only when a comparison is named — the
48
48
  * terminal machine cannot see whether one is. */
49
49
  export declare function useCompareAll(): () => void;
50
+ /** Set or clear (`null`) the function a compare applies to a metric. */
51
+ export declare function useSetCompareFn(): (id: string, fn: PairOp | null) => void;
50
52
  export declare function useSetStudyParam(): (id: string, name: string, value: number) => void;
51
53
  /** Switch which output of a multi-output source a study reads (the output
52
54
  * picker). Pair it with `outputAllowed` to render refused choices disabled. */
package/dist/context.js CHANGED
@@ -82,6 +82,11 @@ export function useCompareAll() {
82
82
  const ref = TerminalContext.useActorRef();
83
83
  return useCallback(() => ref.send({ type: 'series.compareAll' }), [ref]);
84
84
  }
85
+ /** Set or clear (`null`) the function a compare applies to a metric. */
86
+ export function useSetCompareFn() {
87
+ const ref = TerminalContext.useActorRef();
88
+ return useCallback((id, fn) => ref.send({ type: 'series.setCompareFn', id, fn }), [ref]);
89
+ }
85
90
  export function useSetStudyParam() {
86
91
  const ref = TerminalContext.useActorRef();
87
92
  return useCallback((id, name, value) => ref.send({ type: 'series.setStudyParam', id, name, value }), [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, 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, 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, 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, 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;
@@ -218,11 +218,21 @@ export type TerminalEvent = {
218
218
  | {
219
219
  type: 'series.patch';
220
220
  id: string;
221
- patch: Partial<Omit<SeriesConfig, 'axis' | 'axisGroup' | 'parentIds'>>;
221
+ patch: Partial<Omit<SeriesConfig, 'axis' | 'axisGroup' | 'parentIds' | 'compareFn'>>;
222
222
  } | {
223
223
  type: 'series.toggleVisible';
224
224
  id: string;
225
225
  }
226
+ /** Set or clear the function a compare applies to a metric
227
+ * ({@link SeriesConfig.compareFn}) — `null` clears it, so the metric draws
228
+ * once per symbol again. Refused for anything {@link compareFnAllowed}
229
+ * refuses. Allowed with no comparison named: the function sleeps until
230
+ * there is one, and the machine cannot see whether there is. */
231
+ | {
232
+ type: 'series.setCompareFn';
233
+ id: string;
234
+ fn: PairOp | null;
235
+ }
226
236
  /** The PAIR's own eye — hides both legs at once. Each leg keeps its own
227
237
  * `visible`, so unhiding the pair restores what each leg was rather than
228
238
  * switching everything on (Peter, 2026-08-18). */
@@ -571,6 +581,20 @@ export declare function linkToggleAllowed(configs: readonly SeriesConfig[], id:
571
581
  * gutters.
572
582
  */
573
583
  export declare function swapAllowed(configs: readonly SeriesConfig[], id: string): boolean;
584
+ /**
585
+ * Whether a seated config can carry a compare function
586
+ * ({@link SeriesConfig.compareFn}).
587
+ *
588
+ * Only the ROOT of a chain — a metric, raw or a derived catalog metric, never
589
+ * a study: the function sits straight after the metric and every study on it
590
+ * runs on the joined line, so a study carrying its own would be a second join
591
+ * inside the first. And only something that has one reading per symbol:
592
+ * refused for anything that already states its own symbols (a leg of a leg
593
+ * group, a spread, anything reading the comparison) and for anything that
594
+ * draws several lines (a band, a multi-output metric, a fan), which has no
595
+ * single line to divide by another.
596
+ */
597
+ export declare function compareFnAllowed(c: SeriesConfig): boolean;
574
598
  export declare function canonRows(rows: readonly RowState[]): string;
575
599
  /** The active slot: first saved preset whose rows deep-equal the live rows, else
576
600
  * null (custom). The single derivation behind the filled circle + the seed. */
@@ -632,10 +656,14 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
632
656
  } | {
633
657
  type: "series.patch";
634
658
  id: string;
635
- patch: Partial<Omit<SeriesConfig, "axis" | "axisGroup" | "parentIds">>;
659
+ patch: Partial<Omit<SeriesConfig, "axis" | "axisGroup" | "parentIds" | "compareFn">>;
636
660
  } | {
637
661
  type: "series.toggleVisible";
638
662
  id: string;
663
+ } | {
664
+ type: "series.setCompareFn";
665
+ id: string;
666
+ fn: PairOp | null;
639
667
  } | {
640
668
  type: "group.toggleVisible";
641
669
  groupId: string;
@@ -745,6 +773,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
745
773
  } | {
746
774
  type: "moveSeriesToRow";
747
775
  params: import("xstate").NonReducibleUnknown;
776
+ } | {
777
+ type: "setCompareFn";
778
+ params: import("xstate").NonReducibleUnknown;
748
779
  } | {
749
780
  type: "patchSeries";
750
781
  params: import("xstate").NonReducibleUnknown;
@@ -823,6 +854,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
823
854
  } | {
824
855
  type: "canSetStudyOutputs";
825
856
  params: unknown;
857
+ } | {
858
+ type: "canSetCompareFn";
859
+ params: unknown;
826
860
  } | {
827
861
  type: "canSetStudyParam";
828
862
  params: unknown;
@@ -1057,6 +1057,12 @@ export function dataColumnsAllowed(scope, id, columns) {
1057
1057
  * presentation field: a patch may not rewrite which config a study is on.
1058
1058
  */
1059
1059
  function coherentPatch(c, patch) {
1060
+ // `compareFn` is set only through `series.setCompareFn` and its guard; a
1061
+ // patch that names it (an untyped caller) is not let around that guard.
1062
+ const { compareFn: _ignored, ...asked } = patch;
1063
+ return keepCompareFnCoherent(drawablePatch(c, asked));
1064
+ }
1065
+ function drawablePatch(c, patch) {
1060
1066
  const next = { ...c, ...patch, parentIds: c.parentIds };
1061
1067
  if (next.derive)
1062
1068
  return next;
@@ -1069,6 +1075,18 @@ function coherentPatch(c, patch) {
1069
1075
  return { ...next, style: c.style === 'band' ? 'line' : c.style };
1070
1076
  return next;
1071
1077
  }
1078
+ /**
1079
+ * A config that has stopped being one a compare function may sit on — it
1080
+ * joined a pair as a leg, took a fan, took a band style — drops the function,
1081
+ * so a saved config never carries one {@link compareFnAllowed} refuses (PR #45
1082
+ * review). Everything else passes through unchanged.
1083
+ */
1084
+ function keepCompareFnCoherent(c) {
1085
+ if (!c.compareFn || compareFnAllowed(c))
1086
+ return c;
1087
+ const { compareFn: _drop, ...rest } = c;
1088
+ return rest;
1089
+ }
1072
1090
  /** Bar price columns in the bar's own order. */
1073
1091
  const barOrder = (columns) => [...columns].sort((a, b) => BAR_PRICE_COLUMNS.indexOf(a) - BAR_PRICE_COLUMNS.indexOf(b));
1074
1092
  /**
@@ -1770,6 +1788,38 @@ function comparableMetric(c) {
1770
1788
  return false; // a fan is several lines too
1771
1789
  return !c.column.startsWith(COMPARE_PREFIX);
1772
1790
  }
1791
+ /**
1792
+ * Whether a seated config can carry a compare function
1793
+ * ({@link SeriesConfig.compareFn}).
1794
+ *
1795
+ * Only the ROOT of a chain — a metric, raw or a derived catalog metric, never
1796
+ * a study: the function sits straight after the metric and every study on it
1797
+ * runs on the joined line, so a study carrying its own would be a second join
1798
+ * inside the first. And only something that has one reading per symbol:
1799
+ * refused for anything that already states its own symbols (a leg of a leg
1800
+ * group, a spread, anything reading the comparison) and for anything that
1801
+ * draws several lines (a band, a multi-output metric, a fan), which has no
1802
+ * single line to divide by another.
1803
+ */
1804
+ export function compareFnAllowed(c) {
1805
+ if (c.group)
1806
+ return false;
1807
+ if (c.column.startsWith(COMPARE_PREFIX))
1808
+ return false;
1809
+ if (c.style === 'band' || c.style === 'lines')
1810
+ return false;
1811
+ if (c.fan && c.fan.length > 0)
1812
+ return false;
1813
+ if (c.derive) {
1814
+ if (isStudyOp(c.derive.op))
1815
+ return false;
1816
+ if (hasPairOp(c.derive) || usesCompare(c.derive))
1817
+ return false;
1818
+ if (opIsMulti(c.derive.op) || opIsBand(c.derive.op))
1819
+ return false;
1820
+ }
1821
+ return true;
1822
+ }
1773
1823
  export function canonRows(rows) {
1774
1824
  return JSON.stringify(rows.map((r) => {
1775
1825
  // Axis membership is preset identity — but `axisGroup` is a MINTED config
@@ -1828,6 +1878,10 @@ export function canonRows(rows) {
1828
1878
  .map((k) => [k, c.outputStyles[k]])
1829
1879
  : null,
1830
1880
  c.fan ?? null,
1881
+ // How the metric reads under a comparison: one joined line or two.
1882
+ // Appended only when set, so a config without one hashes exactly as
1883
+ // it did before the field existed and a saved preset still matches.
1884
+ ...(c.compareFn ? [c.compareFn] : []),
1831
1885
  ]),
1832
1886
  ];
1833
1887
  }));
@@ -2005,6 +2059,16 @@ export const terminalMachine = setup({
2005
2059
  canSetDataColumns: ({ context, event }) => event.type === 'series.setDataColumns' &&
2006
2060
  dataColumnsAllowed(context, event.id, event.columns),
2007
2061
  canSetStudyOutputs: ({ context, event }) => event.type === 'series.setStudyOutputs' && outputsAllowed(context, event.id, event.outputs),
2062
+ canSetCompareFn: ({ context, event }) => {
2063
+ if (event.type !== 'series.setCompareFn')
2064
+ return false;
2065
+ const target = flatConfigs(context.rows).find((c) => c.id === event.id);
2066
+ if (!target)
2067
+ return false;
2068
+ // Clearing is always allowed: a function persisted on something that
2069
+ // can no longer carry one must still be removable.
2070
+ return event.fn === null || (isPairOp(event.fn) && compareFnAllowed(target));
2071
+ },
2008
2072
  canSetStudyParam: ({ context, event }) => event.type === 'series.setStudyParam' &&
2009
2073
  respecAllowed(context, event.id, event.name, event.value),
2010
2074
  // The chain toggle — delegated to the shared pure helper so the panel's
@@ -2148,7 +2212,7 @@ export const terminalMachine = setup({
2148
2212
  ...r,
2149
2213
  configs: (r.id === row.id ? [...plan.create, ...r.configs] : r.configs).map((c) => {
2150
2214
  const group = tag.get(c.id);
2151
- return group ? { ...c, group } : c;
2215
+ return group ? keepCompareFnCoherent({ ...c, group }) : c;
2152
2216
  }),
2153
2217
  }));
2154
2218
  }
@@ -2265,7 +2329,7 @@ export const terminalMachine = setup({
2265
2329
  if (i >= 0 && c.parentIds?.[i] == null)
2266
2330
  orphans.set(c.id, i);
2267
2331
  }
2268
- const next = dataColumnsConfig(node, event.columns);
2332
+ const next = keepCompareFnCoherent(dataColumnsConfig(node, event.columns));
2269
2333
  return context.rows.map((r) => ({
2270
2334
  ...r,
2271
2335
  configs: r.configs.map((c) => {
@@ -2522,6 +2586,25 @@ export const terminalMachine = setup({
2522
2586
  return pruneEmptied(context.rows, mapped);
2523
2587
  },
2524
2588
  }),
2589
+ setCompareFn: assign({
2590
+ rows: ({ context, event }) => {
2591
+ if (event.type !== 'series.setCompareFn')
2592
+ return context.rows;
2593
+ return context.rows.map((r) => r.configs.some((c) => c.id === event.id)
2594
+ ? {
2595
+ ...r,
2596
+ configs: r.configs.map((c) => {
2597
+ if (c.id !== event.id)
2598
+ return c;
2599
+ // Cleared by REMOVING the key, so a cleared config and one
2600
+ // that never had a function persist the same shape.
2601
+ const { compareFn: _drop, ...rest } = c;
2602
+ return event.fn ? { ...rest, compareFn: event.fn } : rest;
2603
+ }),
2604
+ }
2605
+ : r);
2606
+ },
2607
+ }),
2525
2608
  patchSeries: assign({
2526
2609
  rows: ({ context, event }) => {
2527
2610
  if (event.type !== 'series.patch')
@@ -2986,6 +3069,7 @@ export const terminalMachine = setup({
2986
3069
  'series.moveToRow': { guard: 'canMoveToRow', actions: 'moveSeriesToRow' },
2987
3070
  'series.remove': { actions: 'removeSeries' },
2988
3071
  'series.patch': { actions: 'patchSeries' },
3072
+ 'series.setCompareFn': { guard: 'canSetCompareFn', actions: 'setCompareFn' },
2989
3073
  'series.toggleVisible': { actions: 'toggleVisible' },
2990
3074
  'group.toggleVisible': { actions: 'toggleGroupVisible' },
2991
3075
  'group.remove': { actions: 'removeGroup' },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tidal-ts/terminal",
3
- "version": "0.21.0",
3
+ "version": "0.22.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.22.0",
40
+ "@tidal-ts/core": "0.22.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@pond-ts/charts": "^0.78.0",