@tidal-ts/terminal 0.3.0 → 0.4.1

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
@@ -48,6 +48,9 @@ export declare function useAddPair(): (a: PairLegInput, b: PairLegInput, op: Pai
48
48
  * terminal machine cannot see whether one is. */
49
49
  export declare function useCompareAll(): () => void;
50
50
  export declare function useSetStudyParam(): (id: string, name: string, value: number) => void;
51
+ /** Switch which output of a multi-output source a study reads (the output
52
+ * picker). Pair it with `outputAllowed` to render refused choices disabled. */
53
+ export declare function useSetStudyOutput(): (id: string, output: string) => void;
51
54
  /** Step a series' draw order within its row (`front`/`up`/`down`/`back`; the
52
55
  * list is front→back, so `up` moves toward the top of the canvas stack). */
53
56
  export declare function useOrderSeries(): (id: string, to: 'front' | 'up' | 'down' | 'back') => void;
package/dist/context.js CHANGED
@@ -86,6 +86,12 @@ export function useSetStudyParam() {
86
86
  const ref = TerminalContext.useActorRef();
87
87
  return useCallback((id, name, value) => ref.send({ type: 'series.setStudyParam', id, name, value }), [ref]);
88
88
  }
89
+ /** Switch which output of a multi-output source a study reads (the output
90
+ * picker). Pair it with `outputAllowed` to render refused choices disabled. */
91
+ export function useSetStudyOutput() {
92
+ const ref = TerminalContext.useActorRef();
93
+ return useCallback((id, output) => ref.send({ type: 'series.setStudyOutput', id, output }), [ref]);
94
+ }
89
95
  /** Step a series' draw order within its row (`front`/`up`/`down`/`back`; the
90
96
  * list is front→back, so `up` moves toward the top of the canvas stack). */
91
97
  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, 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, 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, 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';
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, 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, studyChainTail, studyOfferable, SOURCE_COLUMNS, swapAllowed, } from './terminalMachine.js';
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';
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).
@@ -151,6 +151,13 @@ export type TerminalEvent = {
151
151
  name: string;
152
152
  value: number;
153
153
  }
154
+ /** Which output of a multi-output source a study reads (`Middle`, `Hist`) —
155
+ * the output picker. `output` is one of the source op's declared suffixes. */
156
+ | {
157
+ type: 'series.setStudyOutput';
158
+ id: string;
159
+ output: string;
160
+ }
154
161
  /** Draw-order (z) within the series' own row. The row's config list is
155
162
  * **front→back** — index 0 paints on top (the render reverses for
156
163
  * `<Layers>`), so `up` moves toward the front. */
@@ -418,6 +425,19 @@ export declare function columnLabel(scope: EditScope, column: string): string;
418
425
  * (PR #140 review, MEDIUM).
419
426
  */
420
427
  export declare function respecAllowed(scope: EditScope, id: string, name: string, value: number): boolean;
428
+ /**
429
+ * Whether a study can switch to reading `output` of its multi-output source —
430
+ * shared by the guard and the host, so a refused choice renders disabled (the
431
+ * {@link respecAllowed} contract). Refused when the study reads no such source
432
+ * (a pair's legs included: see `studyPick`), the source does not declare
433
+ * `output`, it is already the one read, or the rewrite would be incoherent: a
434
+ * spec the registry rejects, a shared axis left holding two units, or a study
435
+ * on its SOURCE's axis changing unit — an SMA of a regression's `R2` is
436
+ * unitless and would be drawn on the regression's `$` scale.
437
+ *
438
+ * Total: it runs in a guard, where a throw kills the actor.
439
+ */
440
+ export declare function outputAllowed(scope: EditScope, id: string, output: string): boolean;
421
441
  export declare const groupMembers: (configs: readonly SeriesConfig[], groupId: string) => SeriesConfig[];
422
442
  /**
423
443
  * Whether `id` can move onto the axis keyed by `axisGroup` (undefined = the
@@ -487,6 +507,10 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
487
507
  id: string;
488
508
  name: string;
489
509
  value: number;
510
+ } | {
511
+ type: "series.setStudyOutput";
512
+ id: string;
513
+ output: string;
490
514
  } | {
491
515
  type: "series.order";
492
516
  id: string;
@@ -582,6 +606,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
582
606
  } | {
583
607
  type: "addPair";
584
608
  params: import("xstate").NonReducibleUnknown;
609
+ } | {
610
+ type: "setStudyOutput";
611
+ params: import("xstate").NonReducibleUnknown;
585
612
  } | {
586
613
  type: "setStudyParam";
587
614
  params: import("xstate").NonReducibleUnknown;
@@ -672,6 +699,9 @@ export declare const terminalMachine: import("xstate").StateMachine<TerminalCont
672
699
  } | {
673
700
  type: "canAddPair";
674
701
  params: unknown;
702
+ } | {
703
+ type: "canSetStudyOutput";
704
+ params: unknown;
675
705
  } | {
676
706
  type: "canSetStudyParam";
677
707
  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, TARGET_ROLES, opSharesSourceAxis, studyTag, inputNames, isPickedInput, isPairOp, isValidSpec, partStudyLabel, readPairParts, specUnit, studyInputOf, substituteInput, } from '@tidal-ts/core';
2
+ import { COMPARE_PREFIX, hasPairOp, usesCompare, deriveId, opParams, opInputs, opNeedsColumns, opIsBand, opIsMulti, opOutputs, TARGET_ROLES, opSharesSourceAxis, studyTag, inputNames, isPickedInput, isPairOp, isValidSpec, partStudyLabel, readPairParts, specUnit, studyInputOf, studyPick, substituteInput, withStudyOutput, } 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;
@@ -443,7 +443,7 @@ const studySpec = (target, op, period) => {
443
443
  * source's params) with the op·period appended — e.g. `Price · SMA · 20`,
444
444
  * `ATM Vol · 21D · SMA · 20` — so the lineage is legible. Warm default colour so
445
445
  * it reads over its source; the user recolours. */
446
- function studyConfig(target, op, period, id) {
446
+ function studyConfig(target, op, period, id, unitOf) {
447
447
  const derive = studySpec(target, op, period);
448
448
  // Only an `inherit` op may share its source's scale (pond's rule, shipped
449
449
  // with the catalog's `unit`). An RSI is bounded 0..100 and a vol reading is
@@ -452,7 +452,10 @@ function studyConfig(target, op, period, id) {
452
452
  // render before this. A study that reads in its own units gets its own axis
453
453
  // group, keyed by its own id, and its own unit for the labels.
454
454
  const shares = opSharesSourceAxis(op);
455
- const own = specUnit(derive, (col) => (col === target.column ? (target.unit ?? '') : ''));
455
+ // The target's own unit for its column, and the scope's for everything else
456
+ // (a bar's high/low read as its close) — the SAME resolution a re-spec uses,
457
+ // so adding a study and retuning it can never disagree about its unit.
458
+ const own = specUnit(derive, (col) => col === target.column ? (target.unit ?? '') : unitOf(col));
456
459
  // Which output of a multi-output target this study reads, named in the label
457
460
  // (`Price · DONCHIAN(20) · Middle · SMA(10)`) so the choice is never silent.
458
461
  const picked = derive.inputs.find(isPickedInput);
@@ -586,11 +589,21 @@ export const columnUnits = (catalog, configs = []) => {
586
589
  units.set(c.column, c.unit ?? '');
587
590
  for (const e of catalog)
588
591
  units.set(entryColumn(e), e.unit);
592
+ // A bar's open/high/low are prices like its close, but no catalog entry
593
+ // names them — they are inputs, never series. Unknown, they read unitless,
594
+ // so every study reading high/low (a Donchian, an ATR band) computed its unit
595
+ // as '' on a RE-spec while it was seated as '$': the unit gate then refused
596
+ // every retune of it, silently (found building the output picker).
597
+ for (const part of BAR_PRICE_PARTS)
598
+ if (!units.has(part))
599
+ units.set(part, units.get('close') ?? '');
589
600
  return (column) => units.get(column) ??
590
601
  (column.startsWith(COMPARE_PREFIX)
591
602
  ? (units.get(column.slice(COMPARE_PREFIX.length)) ?? '')
592
603
  : '');
593
604
  };
605
+ /** The bar columns that read in the same unit as the bar's `close`. */
606
+ const BAR_PRICE_PARTS = ['open', 'high', 'low'];
594
607
  const unitOfColumn = (scope) => columnUnits(scope.catalog, flatConfigs(scope.rows));
595
608
  /** A resolved+bound leg: the graph input the pair spec takes, and the
596
609
  * decorated label the spread reads by. Order matters: the study wraps the
@@ -802,6 +815,41 @@ export function respecAllowed(scope, id, name, value) {
802
815
  // could disagree about the very thing they now both write (PR #141 review).
803
816
  return next !== null && unitsStayCoherent(scope.rows, next);
804
817
  }
818
+ /**
819
+ * Whether a study can switch to reading `output` of its multi-output source —
820
+ * shared by the guard and the host, so a refused choice renders disabled (the
821
+ * {@link respecAllowed} contract). Refused when the study reads no such source
822
+ * (a pair's legs included: see `studyPick`), the source does not declare
823
+ * `output`, it is already the one read, or the rewrite would be incoherent: a
824
+ * spec the registry rejects, a shared axis left holding two units, or a study
825
+ * on its SOURCE's axis changing unit — an SMA of a regression's `R2` is
826
+ * unitless and would be drawn on the regression's `$` scale.
827
+ *
828
+ * Total: it runs in a guard, where a throw kills the actor.
829
+ */
830
+ export function outputAllowed(scope, id, output) {
831
+ try {
832
+ const configs = flatConfigs(scope.rows);
833
+ const target = configs.find((c) => c.id === id);
834
+ if (!target?.derive)
835
+ return false;
836
+ const pick = studyPick(target.derive);
837
+ if (!pick || !opOutputs(pick.from.op).includes(output))
838
+ return false;
839
+ if (pick.explicit && pick.output === output)
840
+ return false;
841
+ if (!isValidSpec(withStudyOutput(target.derive, output)))
842
+ return false;
843
+ const next = propagateRespec(configs, id, respecOutput(target, output), unitOfColumn(scope));
844
+ if (next === null || !unitsStayCoherent(scope.rows, next))
845
+ return false;
846
+ const borrowed = target.axisGroup != null && target.axisGroup !== target.id;
847
+ return !(borrowed && next.get(id).unit !== (target.unit ?? ''));
848
+ }
849
+ catch {
850
+ return false;
851
+ }
852
+ }
805
853
  // --- fn() = None: the LEG GROUP ----------------------------------------------
806
854
  // With no transform a pair has no single line and therefore no single ink, so
807
855
  // it stops being one config and becomes TWO — each an ordinary series with its
@@ -990,6 +1038,25 @@ function respecParam(study, name, value) {
990
1038
  label: `${base} · ${studyTag(derive)}`,
991
1039
  };
992
1040
  }
1041
+ /** Re-spec a study to read another output of its source, **in place** — the
1042
+ * identity stands, like {@link respecParam}. The label's output segment is
1043
+ * swapped (`… · Line · SMA(10)` → `… · Hist · SMA(10)`); a study saved before
1044
+ * its label named one gains it. */
1045
+ function respecOutput(study, output) {
1046
+ const prev = study.derive;
1047
+ const pick = studyPick(prev);
1048
+ const derive = withStudyOutput(prev, output);
1049
+ const tag = ` · ${studyTag(prev)}`;
1050
+ const named = ` · ${pick.output}${tag}`;
1051
+ // `label` is untyped persisted state; a missing one must not throw here.
1052
+ const label = typeof study.label === 'string' ? study.label : '';
1053
+ const base = label.endsWith(named)
1054
+ ? label.slice(0, -named.length)
1055
+ : label.endsWith(tag)
1056
+ ? label.slice(0, -tag.length)
1057
+ : (study.family ?? label);
1058
+ return { ...study, column: deriveId(derive), derive, label: `${base} · ${output}${tag}` };
1059
+ }
993
1060
  function propagateRespec(configs, rootId, root, unitOf) {
994
1061
  const rootCfg = configs.find((c) => c.id === rootId);
995
1062
  if (!rootCfg?.derive || !root.derive)
@@ -1476,6 +1543,7 @@ export const terminalMachine = setup({
1476
1543
  // rewritten spec and returns false rather than throwing — which also covers
1477
1544
  // the actor-killing hazard `canAddStudy` guards (a throwing guard kills the
1478
1545
  // actor, and the `>= 2` pre-check does not cover the registry's max).
1546
+ canSetStudyOutput: ({ context, event }) => event.type === 'series.setStudyOutput' && outputAllowed(context, event.id, event.output),
1479
1547
  canSetStudyParam: ({ context, event }) => event.type === 'series.setStudyParam' &&
1480
1548
  respecAllowed(context, event.id, event.name, event.value),
1481
1549
  // The chain toggle — delegated to the shared pure helper so the panel's
@@ -1532,7 +1600,7 @@ export const terminalMachine = setup({
1532
1600
  // Every assigner in this `assign` sees the SAME pre-update context, so
1533
1601
  // the id minted here and the one `expanded`/`cfgSeq` compute below all
1534
1602
  // agree without threading a value between them.
1535
- const cfg = studyConfig(target, event.op, event.period, mintId(context.cfgSeq));
1603
+ const cfg = studyConfig(target, event.op, event.period, mintId(context.cfgSeq), unitOfColumn(context));
1536
1604
  // Overlay on the target's row (own-row oscillators are a later step),
1537
1605
  // inserted directly IN FRONT of its target — the list is front→back, so
1538
1606
  // that's the target's own index. A study must read over its source (see
@@ -1641,6 +1709,16 @@ export const terminalMachine = setup({
1641
1709
  // no pointer moves: every config keeps its identity, so selection,
1642
1710
  // expansion, ink, axis membership and range pins all survive (they used to
1643
1711
  // be destroyed, and the dependents deleted outright).
1712
+ setStudyOutput: assign({
1713
+ rows: ({ context, event }) => {
1714
+ if (event.type !== 'series.setStudyOutput')
1715
+ return context.rows;
1716
+ const target = flatConfigs(context.rows).find((c) => c.id === event.id);
1717
+ if (!target?.derive)
1718
+ return context.rows;
1719
+ return applyRespec(context, event.id, respecOutput(target, event.output));
1720
+ },
1721
+ }),
1644
1722
  setStudyParam: assign({
1645
1723
  rows: ({ context, event }) => {
1646
1724
  if (event.type !== 'series.setStudyParam')
@@ -2276,6 +2354,7 @@ export const terminalMachine = setup({
2276
2354
  }),
2277
2355
  },
2278
2356
  'series.setStudyParam': { guard: 'canSetStudyParam', actions: 'setStudyParam' },
2357
+ 'series.setStudyOutput': { guard: 'canSetStudyOutput', actions: 'setStudyOutput' },
2279
2358
  'series.order': { actions: 'orderSeries' },
2280
2359
  'series.reindex': { actions: 'orderSeries' },
2281
2360
  '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.3.0",
3
+ "version": "0.4.1",
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.3.0",
40
- "@tidal-ts/core": "0.3.0"
39
+ "@tidal-ts/chart": "0.4.1",
40
+ "@tidal-ts/core": "0.4.1"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@pond-ts/charts": "^0.70.0",