@orangecharts/wrun-chart-host 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +72 -0
  2. package/dist/constants/governed-exchanges.constants.d.ts +11 -0
  3. package/dist/constants/governed-exchanges.constants.js +11 -0
  4. package/dist/constants/indicator-sets.constants.d.ts +8 -0
  5. package/dist/constants/indicator-sets.constants.js +8 -0
  6. package/dist/constants/interval.constants.d.ts +34 -0
  7. package/dist/constants/interval.constants.js +121 -0
  8. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.d.ts +28 -0
  9. package/dist/constants/scriptEditor/technicalIndicatorScriptKeys.constants.js +65 -0
  10. package/dist/constants/tpo-color-schemes.constants.d.ts +30 -0
  11. package/dist/constants/tpo-color-schemes.constants.js +32 -0
  12. package/dist/host-env.d.ts +102 -0
  13. package/dist/host-env.js +26 -0
  14. package/dist/index.d.ts +93 -0
  15. package/dist/index.js +96 -0
  16. package/dist/indicators/controls/tpo-letter.util.d.ts +2 -0
  17. package/dist/indicators/controls/tpo-letter.util.js +13 -0
  18. package/dist/indicators/controls/tpo-session.util.d.ts +99 -0
  19. package/dist/indicators/controls/tpo-session.util.js +389 -0
  20. package/dist/interfaces/kscript-diagnostics.interface.d.ts +64 -0
  21. package/dist/interfaces/kscript-diagnostics.interface.js +1 -0
  22. package/dist/interfaces/om-panel-data.interface.d.ts +103 -0
  23. package/dist/interfaces/om-panel-data.interface.js +7 -0
  24. package/dist/interfaces/wrun-runtime.interface.d.ts +2659 -0
  25. package/dist/interfaces/wrun-runtime.interface.js +55 -0
  26. package/dist/utility/chart/calendar-interval.util.d.ts +24 -0
  27. package/dist/utility/chart/calendar-interval.util.js +81 -0
  28. package/dist/utility/chart/candle-bar-end.util.d.ts +15 -0
  29. package/dist/utility/chart/candle-bar-end.util.js +23 -0
  30. package/dist/utility/chart/cme-realtime.util.d.ts +24 -0
  31. package/dist/utility/chart/cme-realtime.util.js +53 -0
  32. package/dist/utility/chart/interval-ladder.util.d.ts +27 -0
  33. package/dist/utility/chart/interval-ladder.util.js +92 -0
  34. package/dist/utility/chart/kscript-drawing-prep.util.d.ts +40 -0
  35. package/dist/utility/chart/kscript-drawing-prep.util.js +184 -0
  36. package/dist/utility/chart/kscript-drawing-safe-area.util.d.ts +95 -0
  37. package/dist/utility/chart/kscript-drawing-safe-area.util.js +805 -0
  38. package/dist/utility/chart/kscript-legend-entries.util.d.ts +166 -0
  39. package/dist/utility/chart/kscript-legend-entries.util.js +538 -0
  40. package/dist/utility/chart/kscript-output-role.util.d.ts +32 -0
  41. package/dist/utility/chart/kscript-output-role.util.js +215 -0
  42. package/dist/utility/chart/kscript-provenance-keys.util.d.ts +22 -0
  43. package/dist/utility/chart/kscript-provenance-keys.util.js +56 -0
  44. package/dist/utility/chart/kscript-run-result-normalize.util.d.ts +53 -0
  45. package/dist/utility/chart/kscript-run-result-normalize.util.js +476 -0
  46. package/dist/utility/chart/kscript-run-result-shape.util.d.ts +14 -0
  47. package/dist/utility/chart/kscript-run-result-shape.util.js +66 -0
  48. package/dist/utility/chart/kscript-titancharts-container.util.d.ts +29 -0
  49. package/dist/utility/chart/kscript-titancharts-container.util.js +151 -0
  50. package/dist/utility/chart/kscript-viewport-overlays.util.d.ts +83 -0
  51. package/dist/utility/chart/kscript-viewport-overlays.util.js +443 -0
  52. package/dist/utility/chart/om-panel-push-style.util.d.ts +78 -0
  53. package/dist/utility/chart/om-panel-push-style.util.js +301 -0
  54. package/dist/utility/chart/om-panel.util.d.ts +166 -0
  55. package/dist/utility/chart/om-panel.util.js +815 -0
  56. package/dist/utility/chart/om-series.util.d.ts +42 -0
  57. package/dist/utility/chart/om-series.util.js +330 -0
  58. package/dist/utility/chart/om-target.util.d.ts +11 -0
  59. package/dist/utility/chart/om-target.util.js +24 -0
  60. package/dist/utility/chart/om-widget.util.d.ts +148 -0
  61. package/dist/utility/chart/om-widget.util.js +413 -0
  62. package/dist/utility/chart/overlay-output-budget.util.d.ts +16 -0
  63. package/dist/utility/chart/overlay-output-budget.util.js +109 -0
  64. package/dist/utility/chart/overlay-paint-flags.util.d.ts +24 -0
  65. package/dist/utility/chart/overlay-paint-flags.util.js +55 -0
  66. package/dist/utility/chart/profile-row-height.util.d.ts +21 -0
  67. package/dist/utility/chart/profile-row-height.util.js +110 -0
  68. package/dist/utility/chart/session-interval.util.d.ts +1 -0
  69. package/dist/utility/chart/session-interval.util.js +35 -0
  70. package/dist/utility/chart/technical-script-legend-value.util.d.ts +18 -0
  71. package/dist/utility/chart/technical-script-legend-value.util.js +53 -0
  72. package/dist/utility/chart/trading-day.util.d.ts +70 -0
  73. package/dist/utility/chart/trading-day.util.js +238 -0
  74. package/dist/utility/chart/wrun-legend-name.util.d.ts +25 -0
  75. package/dist/utility/chart/wrun-legend-name.util.js +87 -0
  76. package/dist/utility/chart/wrun-run-result.util.d.ts +977 -0
  77. package/dist/utility/chart/wrun-run-result.util.js +5179 -0
  78. package/dist/utility/chart/wrun-visibility-chart.util.d.ts +25 -0
  79. package/dist/utility/chart/wrun-visibility-chart.util.js +22 -0
  80. package/dist/utility/indicators/heatmap-sensitivity.util.d.ts +62 -0
  81. package/dist/utility/indicators/heatmap-sensitivity.util.js +82 -0
  82. package/dist/utility/number-format.util.d.ts +68 -0
  83. package/dist/utility/number-format.util.js +188 -0
  84. package/dist/utility/v2/opra-governed.util.d.ts +1 -0
  85. package/dist/utility/v2/opra-governed.util.js +13 -0
  86. package/dist/utility/wrun/wrun-auto-row.util.d.ts +54 -0
  87. package/dist/utility/wrun/wrun-auto-row.util.js +96 -0
  88. package/dist/utility/wrun/wrun-batched-marks.util.d.ts +341 -0
  89. package/dist/utility/wrun/wrun-batched-marks.util.js +938 -0
  90. package/dist/utility/wrun/wrun-batched-readout.util.d.ts +75 -0
  91. package/dist/utility/wrun/wrun-batched-readout.util.js +171 -0
  92. package/dist/utility/wrun/wrun-box-segment.util.d.ts +185 -0
  93. package/dist/utility/wrun/wrun-box-segment.util.js +570 -0
  94. package/dist/utility/wrun/wrun-build-memo.util.d.ts +133 -0
  95. package/dist/utility/wrun/wrun-build-memo.util.js +301 -0
  96. package/dist/utility/wrun/wrun-builtin-twin-ports.util.d.ts +25 -0
  97. package/dist/utility/wrun/wrun-builtin-twin-ports.util.js +75 -0
  98. package/dist/utility/wrun/wrun-builtin-twin.util.d.ts +9 -0
  99. package/dist/utility/wrun/wrun-builtin-twin.util.js +40 -0
  100. package/dist/utility/wrun/wrun-canvas-cache.util.d.ts +28 -0
  101. package/dist/utility/wrun/wrun-canvas-cache.util.js +56 -0
  102. package/dist/utility/wrun/wrun-canvas-readout.util.d.ts +69 -0
  103. package/dist/utility/wrun/wrun-canvas-readout.util.js +53 -0
  104. package/dist/utility/wrun/wrun-canvases.util.d.ts +295 -0
  105. package/dist/utility/wrun/wrun-canvases.util.js +1432 -0
  106. package/dist/utility/wrun/wrun-cap-notice.util.d.ts +77 -0
  107. package/dist/utility/wrun/wrun-cap-notice.util.js +296 -0
  108. package/dist/utility/wrun/wrun-card-style.util.d.ts +154 -0
  109. package/dist/utility/wrun/wrun-card-style.util.js +539 -0
  110. package/dist/utility/wrun/wrun-chart-context.util.d.ts +89 -0
  111. package/dist/utility/wrun/wrun-chart-context.util.js +213 -0
  112. package/dist/utility/wrun/wrun-chart-names.util.d.ts +23 -0
  113. package/dist/utility/wrun/wrun-chart-names.util.js +33 -0
  114. package/dist/utility/wrun/wrun-chart-time.util.d.ts +12 -0
  115. package/dist/utility/wrun/wrun-chart-time.util.js +23 -0
  116. package/dist/utility/wrun/wrun-child-overlay-id.util.d.ts +13 -0
  117. package/dist/utility/wrun/wrun-child-overlay-id.util.js +44 -0
  118. package/dist/utility/wrun/wrun-color-facts.util.d.ts +40 -0
  119. package/dist/utility/wrun/wrun-color-facts.util.js +88 -0
  120. package/dist/utility/wrun/wrun-color-settings.lazy.d.ts +26 -0
  121. package/dist/utility/wrun/wrun-color-settings.lazy.js +9 -0
  122. package/dist/utility/wrun/wrun-color-settings.util.d.ts +351 -0
  123. package/dist/utility/wrun/wrun-color-settings.util.js +1363 -0
  124. package/dist/utility/wrun/wrun-footprint-modes.util.d.ts +23 -0
  125. package/dist/utility/wrun/wrun-footprint-modes.util.js +24 -0
  126. package/dist/utility/wrun/wrun-frames.d.ts +217 -0
  127. package/dist/utility/wrun/wrun-frames.js +1021 -0
  128. package/dist/utility/wrun/wrun-handles.util.d.ts +792 -0
  129. package/dist/utility/wrun/wrun-handles.util.js +2050 -0
  130. package/dist/utility/wrun/wrun-heatmap-cell-budget.util.d.ts +156 -0
  131. package/dist/utility/wrun/wrun-heatmap-cell-budget.util.js +342 -0
  132. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +218 -0
  133. package/dist/utility/wrun/wrun-hosted-wire-caps.js +667 -0
  134. package/dist/utility/wrun/wrun-hosted-wire.util.d.ts +40 -0
  135. package/dist/utility/wrun/wrun-hosted-wire.util.js +27 -0
  136. package/dist/utility/wrun/wrun-hover.util.d.ts +182 -0
  137. package/dist/utility/wrun/wrun-hover.util.js +534 -0
  138. package/dist/utility/wrun/wrun-hud-looks.util.d.ts +246 -0
  139. package/dist/utility/wrun/wrun-hud-looks.util.js +587 -0
  140. package/dist/utility/wrun/wrun-integration-budget.util.d.ts +47 -0
  141. package/dist/utility/wrun/wrun-integration-budget.util.js +122 -0
  142. package/dist/utility/wrun/wrun-latest-snapshot.d.ts +19 -0
  143. package/dist/utility/wrun/wrun-latest-snapshot.js +7 -0
  144. package/dist/utility/wrun/wrun-levels-child.util.d.ts +131 -0
  145. package/dist/utility/wrun/wrun-levels-child.util.js +514 -0
  146. package/dist/utility/wrun/wrun-lifecycle.contract.d.ts +75 -0
  147. package/dist/utility/wrun/wrun-lifecycle.contract.js +9 -0
  148. package/dist/utility/wrun/wrun-market-facts.util.d.ts +116 -0
  149. package/dist/utility/wrun/wrun-market-facts.util.js +238 -0
  150. package/dist/utility/wrun/wrun-output-style.util.d.ts +344 -0
  151. package/dist/utility/wrun/wrun-output-style.util.js +1239 -0
  152. package/dist/utility/wrun/wrun-overlay-identity.util.d.ts +84 -0
  153. package/dist/utility/wrun/wrun-overlay-identity.util.js +142 -0
  154. package/dist/utility/wrun/wrun-overlay-result.util.d.ts +120 -0
  155. package/dist/utility/wrun/wrun-overlay-result.util.js +219 -0
  156. package/dist/utility/wrun/wrun-pack.util.d.ts +70 -0
  157. package/dist/utility/wrun/wrun-pack.util.js +301 -0
  158. package/dist/utility/wrun/wrun-pane-format.util.d.ts +180 -0
  159. package/dist/utility/wrun/wrun-pane-format.util.js +299 -0
  160. package/dist/utility/wrun/wrun-panel-style.lazy.d.ts +25 -0
  161. package/dist/utility/wrun/wrun-panel-style.lazy.js +15 -0
  162. package/dist/utility/wrun/wrun-panel-style.util.d.ts +174 -0
  163. package/dist/utility/wrun/wrun-panel-style.util.js +726 -0
  164. package/dist/utility/wrun/wrun-param-values.util.d.ts +69 -0
  165. package/dist/utility/wrun/wrun-param-values.util.js +230 -0
  166. package/dist/utility/wrun/wrun-refusal.util.d.ts +263 -0
  167. package/dist/utility/wrun/wrun-refusal.util.js +1259 -0
  168. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +199 -0
  169. package/dist/utility/wrun/wrun-registry-errors.util.js +257 -0
  170. package/dist/utility/wrun/wrun-render-select.util.d.ts +336 -0
  171. package/dist/utility/wrun/wrun-render-select.util.js +1157 -0
  172. package/dist/utility/wrun/wrun-script-inputs.util.d.ts +434 -0
  173. package/dist/utility/wrun/wrun-script-inputs.util.js +1971 -0
  174. package/dist/utility/wrun/wrun-setting-words.lazy.d.ts +20 -0
  175. package/dist/utility/wrun/wrun-setting-words.lazy.js +9 -0
  176. package/dist/utility/wrun/wrun-setting-words.util.d.ts +79 -0
  177. package/dist/utility/wrun/wrun-setting-words.util.js +176 -0
  178. package/dist/utility/wrun/wrun-socket-row-store.d.ts +98 -0
  179. package/dist/utility/wrun/wrun-socket-row-store.js +417 -0
  180. package/dist/utility/wrun/wrun-style-flags.util.d.ts +18 -0
  181. package/dist/utility/wrun/wrun-style-flags.util.js +21 -0
  182. package/dist/utility/wrun/wrun-style-words.util.d.ts +148 -0
  183. package/dist/utility/wrun/wrun-style-words.util.js +439 -0
  184. package/dist/utility/wrun/wrun-table-look.util.d.ts +125 -0
  185. package/dist/utility/wrun/wrun-table-look.util.js +225 -0
  186. package/dist/utility/wrun/wrun-text-look.util.d.ts +51 -0
  187. package/dist/utility/wrun/wrun-text-look.util.js +227 -0
  188. package/dist/utility/wrun/wrun-text-params.util.d.ts +106 -0
  189. package/dist/utility/wrun/wrun-text-params.util.js +171 -0
  190. package/dist/utility/wrun/wrun-tpo-rows.util.d.ts +71 -0
  191. package/dist/utility/wrun/wrun-tpo-rows.util.js +438 -0
  192. package/dist/utility/wrun/wrun-twin-compute-inputs.util.d.ts +14 -0
  193. package/dist/utility/wrun/wrun-twin-compute-inputs.util.js +58 -0
  194. package/dist/utility/wrun/wrun-visibility-table.d.ts +437 -0
  195. package/dist/utility/wrun/wrun-visibility-table.js +237 -0
  196. package/dist/utility/wrun/wrun-volume-profile.util.d.ts +37 -0
  197. package/dist/utility/wrun/wrun-volume-profile.util.js +278 -0
  198. package/package.json +38 -0
@@ -0,0 +1,1432 @@
1
+ /**
2
+ * The price canvases of WRUN-STYLE g6 (PT-heatmap, PT-footprint, PT-tpo,
3
+ * MX-price-matrix, MX-side-panel; DL-time-anchored's volume profile is
4
+ * wrun-volume-profile.util's, delegated to from here): every canvas is a
5
+ * CHILD overlay of the wrun indicator, shaped here from the sheet words and
6
+ * mounted through the child seam (wrun-panel-mount.util).
7
+ *
8
+ * - Celled canvases (a heatmap over book or volume_profile cells, the
9
+ * footprint, the TPO letters) are drawn by the host from the run's own
10
+ * source rows (`WrunCellRows`, handed by wrun-overlay-run.util and the live
11
+ * tick), the rows shared with the run (a fresh outer array only). A grid
12
+ * heatmap rides N data-only outputs (`out.grid`); a matrix a wrun-4 frame.
13
+ * - Sheet words map to engine keys here; colour WORDS stay unresolved on the
14
+ * child (`theme.*` tokens included) and resolve at the mount door
15
+ * (`wrunCanvasChildConfig`, with the chart's theme), so a theme switch
16
+ * re-resolves a child without a rerun (X13). Font words resolve to CSS
17
+ * stacks before the engine (X14). A matrix cell's palette fill is a mix of
18
+ * two stops, which a token cannot express, so the matrix child carries its
19
+ * inputs beside its rows and the config hands back the rows resolved
20
+ * against the theme (`data`); the child's own rows are resolved against the
21
+ * default dark palette for a mount that ignores `data`.
22
+ * - Numbers print through formatWrunNumber (conventions 8); a heatmap or
23
+ * matrix with a `tooltip` registers a hover readout the profile-cell
24
+ * inspector renders from the template.
25
+ * - A heatmap whose bounds come from the quantile carries its scale words
26
+ * (`scale`), and the mount door re-picks its bounds for the viewer's
27
+ * Sensitivity (`heatmap:<name>:sensitivity` on the parent): the run keeps
28
+ * the author's bounds, like it keeps colour words unresolved.
29
+ * - The Style rows of a heatmap or profile (C1 `heatmap:<name>`,
30
+ * `profile:<name>`) reach this file as the sheet the settings seam painted
31
+ * (wrun-color-settings.util): `visible: false` builds no child, and the
32
+ * colour rows are the declared `palette` / buy and sell colours read below.
33
+ */
34
+ import { DEFAULT_TPO_COLOR_SCHEMES } from '../../constants/tpo-color-schemes.constants.js';
35
+ import { profileRowMultiplier, tpoPeriodWord } from '../chart/profile-row-height.util.js';
36
+ import { getTradingDayAnchor } from '../chart/trading-day.util.js';
37
+ import { wrunLegendName } from '../chart/wrun-legend-name.util.js';
38
+ import { heatmapSensitivityForQuantile, heatmapSensitivityQuantile } from '../indicators/heatmap-sensitivity.util.js';
39
+ import { isWrunStyleTargetHidden } from './wrun-color-settings.util.js';
40
+ import { WRUN_MAX_ROWS_PER_PERIOD, WRUN_ROW_CAP_MAX_DOUBLINGS, wrunAutoRowUnit } from './wrun-auto-row.util.js';
41
+ import { WRUN_FOOTPRINT_CELL_METRIC_DEFAULT, WRUN_FOOTPRINT_MODE_DEFAULT } from './wrun-footprint-modes.util.js';
42
+ import { formatWrunNumber, resolveWrunColorWord, wrunFontFamilyCss, } from './wrun-style-words.util.js';
43
+ import { buildWrunTpoRows, WRUN_TPO_MAX_ROWS_PER_BAR, } from './wrun-tpo-rows.util.js';
44
+ import { wrunVolumeProfileChild } from './wrun-volume-profile.util.js';
45
+ import { invalidWrunFrame, parseWrunMatrixFrame } from './wrun-frames.js';
46
+ import { forgetWrunCanvasReadout, rememberWrunCanvasReadout } from './wrun-canvas-readout.util.js';
47
+ /** The engine's plot of each child kind. */
48
+ const CHILD_PLOT = {
49
+ heatmap: 'heatmapCells',
50
+ profile: 'profile',
51
+ matrix: 'priceMatrix',
52
+ };
53
+ /** The default dark palette (wrun-style-words.util 2.3): what a child's own
54
+ * rows resolve against before the mount hands the chart's theme over. */
55
+ export const WRUN_CANVAS_FALLBACK_THEME = Object.freeze({
56
+ up: '#26a69a',
57
+ down: '#ef5350',
58
+ text: '#d1d4dc',
59
+ muted: 'rgba(209, 212, 220, 0.55)',
60
+ bg: '#131722',
61
+ grid: '#2a2e39',
62
+ accent: '#ff4608',
63
+ });
64
+ /** The colour-scale defaults (PT-heatmap): the sequential ramp, the
65
+ * diverging ramp around a centre, the quantile of the auto bounds. */
66
+ export const WRUN_HEATMAP_DEFAULT_PALETTE = Object.freeze([
67
+ 'theme.bg',
68
+ '#2563eb',
69
+ '#22d3ee',
70
+ '#facc15',
71
+ ]);
72
+ export const WRUN_HEATMAP_DIVERGING_PALETTE = Object.freeze(['theme.down', 'theme.bg', 'theme.up']);
73
+ export const WRUN_CANVAS_DEFAULT_QUANTILE = 0.98;
74
+ /** The deterministic stride sample's cap over a run's cells. */
75
+ export const WRUN_CANVAS_SCALE_SAMPLE_CELLS = 65_536;
76
+ /** The side strip's default panel width (MX-side-panel). */
77
+ export const WRUN_SIDE_PANEL_DEFAULT_WIDTH_PX = 280;
78
+ const DEFAULT_TPO_SCHEME = 'Kiyotaka';
79
+ // ── Small readers ───────────────────────────────────────────────────────────
80
+ function finite(value) {
81
+ return typeof value === 'number' && Number.isFinite(value);
82
+ }
83
+ function isRecord(value) {
84
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
85
+ }
86
+ /** The sheet name read as words, the legend's own rule ("book_heat" -> "Book heat", "gex_board" -> "GEX board"). */
87
+ export function wrunCanvasNameWords(name) {
88
+ return wrunLegendName(name);
89
+ }
90
+ export function wrunCanvasChildId(overlayId, kind, name) {
91
+ return `${overlayId}::${kind}:${name}`;
92
+ }
93
+ /** The number format a canvas prints with (rule 8): `format` defaults to "auto". */
94
+ function numberFormatOf(words) {
95
+ return {
96
+ format: words.format ?? 'auto',
97
+ ...(words.decimals !== undefined ? { decimals: words.decimals } : {}),
98
+ ...(words.signed !== undefined ? { signed: words.signed } : {}),
99
+ ...(words.unit !== undefined ? { unit: words.unit } : {}),
100
+ };
101
+ }
102
+ function utf8Bytes(text) {
103
+ return new TextEncoder().encode(text).length;
104
+ }
105
+ function parseCssColor(color) {
106
+ const text = color.trim();
107
+ const hex = /^#([0-9a-f]{3,8})$/i.exec(text);
108
+ if (hex) {
109
+ const h = hex[1];
110
+ if (h.length === 3 || h.length === 4) {
111
+ const r = parseInt(h[0] + h[0], 16);
112
+ const g = parseInt(h[1] + h[1], 16);
113
+ const b = parseInt(h[2] + h[2], 16);
114
+ const a = h.length === 4 ? parseInt(h[3] + h[3], 16) / 255 : 1;
115
+ return [r, g, b, a];
116
+ }
117
+ if (h.length === 6 || h.length === 8) {
118
+ const r = parseInt(h.slice(0, 2), 16);
119
+ const g = parseInt(h.slice(2, 4), 16);
120
+ const b = parseInt(h.slice(4, 6), 16);
121
+ const a = h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1;
122
+ return [r, g, b, a];
123
+ }
124
+ return null;
125
+ }
126
+ const fn = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*(?:,\s*([\d.]+)\s*)?\)$/i.exec(text);
127
+ if (!fn)
128
+ return null;
129
+ const a = fn[4] === undefined ? 1 : Number(fn[4]);
130
+ return [Number(fn[1]), Number(fn[2]), Number(fn[3]), Number.isFinite(a) ? a : 1];
131
+ }
132
+ function hex2(value) {
133
+ return Math.round(Math.min(255, Math.max(0, value)))
134
+ .toString(16)
135
+ .padStart(2, '0');
136
+ }
137
+ /** '#rrggbb' when opaque, else 'rgba(r, g, b, a)' (the foundation's form). */
138
+ function cssColor([r, g, b, a]) {
139
+ const alpha = Math.min(1, Math.max(0, a));
140
+ if (alpha >= 0.9995)
141
+ return `#${hex2(r)}${hex2(g)}${hex2(b)}`;
142
+ return `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${Number(alpha.toFixed(3))})`;
143
+ }
144
+ /** A colour's own alpha times `factor` (conventions 3); an unparseable colour passes unchanged. */
145
+ export function wrunCanvasMultiplyAlpha(color, factor) {
146
+ if (!finite(factor) || factor >= 1)
147
+ return color;
148
+ const parsed = parseCssColor(color);
149
+ if (parsed === null)
150
+ return color;
151
+ return cssColor([parsed[0], parsed[1], parsed[2], parsed[3] * Math.max(0, factor)]);
152
+ }
153
+ function mixColors(a, b, t) {
154
+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3] + (b[3] - a[3]) * t];
155
+ }
156
+ /** The colour at position `t` (0..1) along resolved palette stops. */
157
+ export function wrunCanvasPaletteColor(stops, t) {
158
+ const parsed = stops.map(parseCssColor);
159
+ if (parsed.length === 0 || parsed.some((stop) => stop === null))
160
+ return undefined;
161
+ const colors = parsed;
162
+ if (colors.length === 1)
163
+ return cssColor(colors[0]);
164
+ const position = Math.min(1, Math.max(0, finite(t) ? t : 0)) * (colors.length - 1);
165
+ const at = Math.min(colors.length - 2, Math.floor(position));
166
+ return cssColor(mixColors(colors[at], colors[at + 1], position - at));
167
+ }
168
+ /** The nearest rank of quantile `q` among `count` ascending values (count > 0). */
169
+ function quantileRank(count, q) {
170
+ const at = Math.round((count - 1) * Math.min(1, Math.max(0, q)));
171
+ return Math.min(count - 1, Math.max(0, at));
172
+ }
173
+ /**
174
+ * The `k`-th smallest of `values[0..count)` (0-based), reordering them in
175
+ * place: an iterative quickselect with a median-of-three pivot and a HOARE
176
+ * partition (both scans stop on a value equal to the pivot and swap it), so
177
+ * a duplicate-heavy book, thousands of equal sizes, still splits in half
178
+ * where a Lomuto partition goes quadratic. Every value equal to the pick is
179
+ * bit-identical to it except a signed zero, which the caller resolves.
180
+ */
181
+ function selectKth(values, count, k) {
182
+ let lo = 0;
183
+ let hi = count - 1;
184
+ while (hi > lo) {
185
+ // The pivot: the median of the first, middle and last values.
186
+ const first = values[lo];
187
+ const middle = values[(lo + hi) >>> 1];
188
+ const last = values[hi];
189
+ let pivot;
190
+ if (first < middle)
191
+ pivot = middle < last ? middle : first < last ? last : first;
192
+ else
193
+ pivot = first < last ? first : middle < last ? last : middle;
194
+ let i = lo;
195
+ let j = hi;
196
+ while (i <= j) {
197
+ while (values[i] < pivot)
198
+ i += 1;
199
+ while (values[j] > pivot)
200
+ j -= 1;
201
+ if (i <= j) {
202
+ const swap = values[i];
203
+ values[i] = values[j];
204
+ values[j] = swap;
205
+ i += 1;
206
+ j -= 1;
207
+ }
208
+ }
209
+ // [lo, j] <= pivot, [i, hi] >= pivot, anything between them equals it.
210
+ if (k <= j)
211
+ hi = j;
212
+ else if (k >= i)
213
+ lo = i;
214
+ else
215
+ return values[k];
216
+ }
217
+ return values[k];
218
+ }
219
+ /** The `index`-th zero (0-based) of `values` in their order, its sign as written. */
220
+ function nthZeroOf(values, index) {
221
+ let seen = 0;
222
+ for (let at = 0; at < values.length; at += 1) {
223
+ const value = values[at];
224
+ if (value !== 0)
225
+ continue;
226
+ if (seen === index)
227
+ return value;
228
+ seen += 1;
229
+ }
230
+ return 0;
231
+ }
232
+ /**
233
+ * The colour-scale bounds (PT-heatmap `min` / `max` / `center` /
234
+ * `auto_quantile`): declared bounds win; the rest comes from the sample of
235
+ * the run's cells (a deterministic stride sample of at most 65,536 cells).
236
+ * Sequential: [0 (`zeroFloor`, the size and volume words) else the (1 - q)
237
+ * quantile, the q quantile]; diverging (a declared centre, or a signed /
238
+ * delta word): centre +- the q quantile of |value - centre|.
239
+ *
240
+ * A bound is the value at the nearest rank of the finite values, picked by
241
+ * selection on a copy (no sort): exactly the value an ascending stable sort
242
+ * held at that rank. The one tie a selection can break differently is +0
243
+ * against -0 (they compare equal); the sort kept them in sample order, so a
244
+ * zero pick re-reads the zero at its rank in that order.
245
+ */
246
+ export function wrunCanvasScaleOf(words, values, options) {
247
+ const q = finite(words.auto_quantile) ? words.auto_quantile : WRUN_CANVAS_DEFAULT_QUANTILE;
248
+ const scale = words.scale ?? 'linear';
249
+ const diverging = options.diverging || finite(words.center);
250
+ if (diverging) {
251
+ const center = finite(words.center) ? words.center : 0;
252
+ // Deviations are never -0 (an absolute value); one that overflows to
253
+ // Infinity stays in the sample, as it always did.
254
+ const deviations = new Float64Array(values.length);
255
+ let count = 0;
256
+ for (let at = 0; at < values.length; at += 1) {
257
+ const value = values[at];
258
+ if (finite(value))
259
+ deviations[count++] = Math.abs(value - center);
260
+ }
261
+ let reach = count === 0 ? 0 : selectKth(deviations, count, quantileRank(count, q));
262
+ if (!(reach > 0))
263
+ reach = 1;
264
+ const min = finite(words.min) ? words.min : center - reach;
265
+ const max = finite(words.max) ? words.max : center + reach;
266
+ return { min, max: max > min ? max : min + 1, center, scale };
267
+ }
268
+ const work = new Float64Array(values.length);
269
+ let count = 0;
270
+ let negatives = 0;
271
+ let negativeZero = false;
272
+ for (let at = 0; at < values.length; at += 1) {
273
+ const value = values[at];
274
+ if (!finite(value))
275
+ continue;
276
+ work[count++] = value;
277
+ if (value < 0)
278
+ negatives += 1;
279
+ else if (Object.is(value, -0))
280
+ negativeZero = true;
281
+ }
282
+ const pick = (quantile) => {
283
+ const rank = quantileRank(count, quantile);
284
+ const value = selectKth(work, count, rank);
285
+ // The sorted sample held every value below zero first, then the zeros in
286
+ // sample order: the zero at this rank is the (rank - negatives)-th.
287
+ return value === 0 && negativeZero ? nthZeroOf(values, rank - negatives) : value;
288
+ };
289
+ const min = finite(words.min) ? words.min : options.zeroFloor ? 0 : count === 0 ? 0 : pick(1 - q);
290
+ const max = finite(words.max) ? words.max : count === 0 ? min + 1 : pick(q);
291
+ return { min, max: max > min ? max : min + 1, scale };
292
+ }
293
+ /** A value's position (0..1) on the scale: the diverging ramp sits its
294
+ * centre at 0.5, `sqrt` lifts the small values, `log` (sequential only)
295
+ * spreads a long tail. */
296
+ export function wrunCanvasScalePosition(value, scale) {
297
+ const curve = (u) => {
298
+ const clamped = Math.min(1, Math.max(0, u));
299
+ if (scale.scale === 'sqrt')
300
+ return Math.sqrt(clamped);
301
+ if (scale.scale === 'log')
302
+ return Math.log10(1 + 9 * clamped);
303
+ return clamped;
304
+ };
305
+ if (scale.center !== undefined) {
306
+ const center = scale.center;
307
+ if (value >= center) {
308
+ const span = scale.max - center;
309
+ return 0.5 + 0.5 * curve(span > 0 ? (value - center) / span : 1);
310
+ }
311
+ const span = center - scale.min;
312
+ return 0.5 - 0.5 * curve(span > 0 ? (center - value) / span : 1);
313
+ }
314
+ const span = scale.max - scale.min;
315
+ return curve(span > 0 ? (value - scale.min) / span : 0);
316
+ }
317
+ /** A deterministic stride over `total` cells: the indexes a sample keeps. */
318
+ function sampleStride(total) {
319
+ return total <= WRUN_CANVAS_SCALE_SAMPLE_CELLS ? 1 : Math.ceil(total / WRUN_CANVAS_SCALE_SAMPLE_CELLS);
320
+ }
321
+ /** A profile row's buckets: nested `[ts, [low, high, buy, sell], ...]` (the
322
+ * FE lane) or flat quads `[ts, low, high, buy, sell, ...]`. */
323
+ function profileBuckets(row) {
324
+ if (!Array.isArray(row))
325
+ return [];
326
+ const buckets = [];
327
+ if (row.length > 1 && Array.isArray(row[1])) {
328
+ for (let at = 1; at < row.length; at += 1) {
329
+ const bucket = row[at];
330
+ if (!Array.isArray(bucket) || bucket.length < 4)
331
+ continue;
332
+ const [low, high, buy, sell] = bucket;
333
+ if (finite(low) && finite(high))
334
+ buckets.push([low, high, finite(buy) ? buy : 0, finite(sell) ? sell : 0]);
335
+ }
336
+ return buckets;
337
+ }
338
+ for (let at = 1; at + 3 < row.length; at += 4) {
339
+ const [low, high, buy, sell] = row.slice(at, at + 4);
340
+ if (finite(low) && finite(high))
341
+ buckets.push([low, high, finite(buy) ? buy : 0, finite(sell) ? sell : 0]);
342
+ }
343
+ return buckets;
344
+ }
345
+ /** A profile bucket's cell under the value word (a missing buy or sell
346
+ * reads 0); NaN when its low or high is not finite (no cell). A cell is
347
+ * never NaN itself: only a sum or difference overflowing to Infinity
348
+ * escapes the finite range. */
349
+ function bucketCellValue(field, low, high, buyCell, sellCell) {
350
+ if (!finite(low) || !finite(high))
351
+ return Number.NaN;
352
+ const buy = finite(buyCell) ? buyCell : 0;
353
+ const sell = finite(sellCell) ? sellCell : 0;
354
+ if (field === 'buy')
355
+ return buy;
356
+ if (field === 'sell')
357
+ return sell;
358
+ return field === 'delta' ? buy - sell : buy + sell;
359
+ }
360
+ /**
361
+ * The scale sample over a run's rows: every cell when they fit the cap,
362
+ * else every stride-th cell in row order (the same cells on every run), as
363
+ * typed numbers in row order. A cell is every value the layout's word reads
364
+ * off a row (a cell the word skips, a bid under 'ask', is none): book pairs
365
+ * with a finite price and size, profile buckets with a finite low and high,
366
+ * grid values that are finite. The stride counts every cell; only a finite
367
+ * one is kept (a profile sum can overflow to Infinity).
368
+ *
369
+ * This walks the whole window on every live tick, so it reads the rows in
370
+ * place: no array per row, no division per cell (`skip` counts down to the
371
+ * next sampled cell, the old `seen % stride === 0`). `total`, the stride's
372
+ * count, keeps its rule (an empty row counts -1, a flat profile quad 4, a
373
+ * grid row its low and step), so the same cells are picked as ever; the
374
+ * buffer is sized from the positive terms, which never under-count the
375
+ * cells a row yields.
376
+ */
377
+ function sampleCellValues(layout, field, rows) {
378
+ let total = 0;
379
+ let capacity = 0;
380
+ for (const row of rows) {
381
+ if (!Array.isArray(row))
382
+ continue;
383
+ const term = layout === 'book' ? (row.length - 1) >> 1 : row.length - 1;
384
+ total += term;
385
+ if (term > 0)
386
+ capacity += term;
387
+ }
388
+ const stride = sampleStride(total);
389
+ const sample = new Float64Array(Math.ceil(capacity / stride));
390
+ let kept = 0;
391
+ let skip = 0;
392
+ for (const row of rows) {
393
+ if (!Array.isArray(row))
394
+ continue;
395
+ if (layout === 'book') {
396
+ // A book cell is finite under every word (its size is).
397
+ for (let at = 1; at + 1 < row.length; at += 2) {
398
+ const size = row[at + 1];
399
+ if (!finite(row[at]) || !finite(size))
400
+ continue;
401
+ let value;
402
+ if (field === 'bid') {
403
+ if (size < 0)
404
+ continue;
405
+ value = size;
406
+ }
407
+ else if (field === 'ask') {
408
+ if (size >= 0)
409
+ continue;
410
+ value = -size;
411
+ }
412
+ else
413
+ value = field === 'signed' ? size : Math.abs(size);
414
+ if (skip > 0)
415
+ skip -= 1;
416
+ else {
417
+ sample[kept++] = value;
418
+ skip = stride - 1;
419
+ }
420
+ }
421
+ }
422
+ else if (layout === 'profile' && row.length > 1 && Array.isArray(row[1])) {
423
+ // Nested `[ts, [low, high, buy, sell], ...]` (a short or non-array bucket is no cell).
424
+ for (let at = 1; at < row.length; at += 1) {
425
+ const bucket = row[at];
426
+ if (!Array.isArray(bucket) || bucket.length < 4)
427
+ continue;
428
+ const value = bucketCellValue(field, bucket[0], bucket[1], bucket[2], bucket[3]);
429
+ if (Number.isNaN(value))
430
+ continue;
431
+ if (skip > 0)
432
+ skip -= 1;
433
+ else {
434
+ if (finite(value))
435
+ sample[kept++] = value;
436
+ skip = stride - 1;
437
+ }
438
+ }
439
+ }
440
+ else if (layout === 'profile') {
441
+ // Flat quads `[ts, low, high, buy, sell, ...]`.
442
+ for (let at = 1; at + 3 < row.length; at += 4) {
443
+ const value = bucketCellValue(field, row[at], row[at + 1], row[at + 2], row[at + 3]);
444
+ if (Number.isNaN(value))
445
+ continue;
446
+ if (skip > 0)
447
+ skip -= 1;
448
+ else {
449
+ if (finite(value))
450
+ sample[kept++] = value;
451
+ skip = stride - 1;
452
+ }
453
+ }
454
+ }
455
+ else {
456
+ for (let at = 3; at < row.length; at += 1) {
457
+ const value = row[at];
458
+ if (!finite(value))
459
+ continue;
460
+ if (skip > 0)
461
+ skip -= 1;
462
+ else {
463
+ sample[kept++] = value;
464
+ skip = stride - 1;
465
+ }
466
+ }
467
+ }
468
+ }
469
+ return sample.subarray(0, kept);
470
+ }
471
+ /** The book's own grouping: the smallest positive gap between adjacent
472
+ * prices of the newest row holding two or more levels. */
473
+ function bookGroupingOf(rows) {
474
+ for (let at = rows.length - 1; at >= 0; at -= 1) {
475
+ const row = rows[at];
476
+ if (!Array.isArray(row) || row.length < 5)
477
+ continue;
478
+ let smallest = Number.POSITIVE_INFINITY;
479
+ for (let cell = 1; cell + 2 < row.length; cell += 2) {
480
+ const gap = Math.abs(Number(row[cell + 2]) - Number(row[cell]));
481
+ if (gap > 0 && gap < smallest)
482
+ smallest = gap;
483
+ }
484
+ if (Number.isFinite(smallest))
485
+ return smallest;
486
+ }
487
+ return undefined;
488
+ }
489
+ /** The profile buckets' width: the smallest positive `high - low` of the
490
+ * newest row holding buckets. */
491
+ function bucketWidthOf(rows) {
492
+ for (let at = rows.length - 1; at >= 0; at -= 1) {
493
+ const buckets = profileBuckets(rows[at]);
494
+ if (buckets.length === 0)
495
+ continue;
496
+ let smallest = Number.POSITIVE_INFINITY;
497
+ for (const [low, high] of buckets) {
498
+ const width = high - low;
499
+ if (width > 0 && width < smallest)
500
+ smallest = width;
501
+ }
502
+ if (Number.isFinite(smallest))
503
+ return smallest;
504
+ }
505
+ return undefined;
506
+ }
507
+ /** The widest high-low span among the candle rows (0 without a usable bar). */
508
+ function widestBarSpan(bars) {
509
+ let widest = 0;
510
+ for (const bar of bars) {
511
+ if (!Array.isArray(bar) || !finite(bar[2]) || !finite(bar[3]))
512
+ continue;
513
+ widest = Math.max(widest, bar[2] - bar[3]);
514
+ }
515
+ return widest;
516
+ }
517
+ /** The smallest positive ts gap of candle rows (an intrabar leg's bar interval when the plan is absent). */
518
+ function rowsIntervalMs(rows) {
519
+ let smallest = Number.POSITIVE_INFINITY;
520
+ for (let at = 1; at < rows.length; at += 1) {
521
+ const prev = rows[at - 1];
522
+ const next = rows[at];
523
+ if (!Array.isArray(prev) || !Array.isArray(next) || !finite(prev[0]) || !finite(next[0]))
524
+ continue;
525
+ const gap = next[0] - prev[0];
526
+ if (gap > 0 && gap < smallest)
527
+ smallest = gap;
528
+ }
529
+ return Number.isFinite(smallest) ? smallest : undefined;
530
+ }
531
+ function inputSourceClass(sheet, name) {
532
+ if (name === undefined)
533
+ return undefined;
534
+ return sheet.inputSources?.[name]?.source;
535
+ }
536
+ // ── The run's cell rows (handed by the run and tick routes) ─────────────────
537
+ /**
538
+ * The `WrunCellRows` of a run from its source rows: the book and volume
539
+ * profile lanes, the chart candles, and every intrabar leg keyed by the
540
+ * input that reads it (`legs`: the run's planned legs, `inputIndexes` by
541
+ * leg). Rows are shared, never copied.
542
+ */
543
+ export function wrunCellRowsOf(metadata, sourceRows, legs = []) {
544
+ const cellRows = {};
545
+ if (sourceRows.bookRows !== undefined)
546
+ cellRows.bookRows = sourceRows.bookRows;
547
+ if (sourceRows.volumeProfileRows !== undefined)
548
+ cellRows.volumeProfileRows = sourceRows.volumeProfileRows;
549
+ if (sourceRows.ohlcvRows !== undefined)
550
+ cellRows.ohlcvRows = sourceRows.ohlcvRows;
551
+ const byInput = {};
552
+ const intervalByInput = {};
553
+ let first;
554
+ for (const leg of legs) {
555
+ if (leg.kind !== 'intrabar')
556
+ continue;
557
+ const rows = sourceRows.intrabarRows?.[leg.fetchKey];
558
+ if (rows === undefined)
559
+ continue;
560
+ for (const index of leg.inputIndexes) {
561
+ const name = metadata.inputs.find((input) => input.index === index)?.name;
562
+ if (name === undefined)
563
+ continue;
564
+ byInput[name] = rows;
565
+ intervalByInput[name] = leg.legMs;
566
+ if (first === undefined || index < first.index)
567
+ first = { index, rows };
568
+ }
569
+ }
570
+ if (first !== undefined) {
571
+ cellRows.intrabarRows = first.rows;
572
+ cellRows.intrabarRowsByInput = byInput;
573
+ cellRows.intrabarIntervalMsByInput = intervalByInput;
574
+ }
575
+ return cellRows;
576
+ }
577
+ // ── PT-heatmap ──────────────────────────────────────────────────────────────
578
+ /** The grid heatmap's rows `[tsMs, priceLow, priceStep, v0 .. v(rows-1)]`
579
+ * from the `out.grid` outputs (a ready row with a finite low and a step
580
+ * above 0; NaN cells stay NaN = empty). */
581
+ function gridRowsOf(sheet, heatmap, outputRows) {
582
+ const gridOutputs = sheet.outputs.filter((output) => output.grid === heatmap.grid).sort((a, b) => a.index - b.index);
583
+ const lowOutput = sheet.outputs.find((output) => output.name === heatmap.price_low);
584
+ const stepOutput = typeof heatmap.price_step === 'string'
585
+ ? sheet.outputs.find((output) => output.name === heatmap.price_step)
586
+ : undefined;
587
+ if (gridOutputs.length === 0 || lowOutput === undefined)
588
+ return [];
589
+ if (typeof heatmap.price_step === 'string' && stepOutput === undefined)
590
+ return [];
591
+ const rows = [];
592
+ for (const row of outputRows) {
593
+ const outputs = row.outputs;
594
+ if (outputs === null)
595
+ continue;
596
+ const low = outputs[lowOutput.index];
597
+ const step = stepOutput !== undefined ? outputs[stepOutput.index] : heatmap.price_step;
598
+ if (!finite(low) || !finite(step) || step <= 0)
599
+ continue;
600
+ const cells = gridOutputs.map((output) => {
601
+ const value = outputs[output.index];
602
+ return finite(value) ? value : Number.NaN;
603
+ });
604
+ rows.push([row.ts, low, step, ...cells]);
605
+ }
606
+ return rows;
607
+ }
608
+ /** A heatmap's scale rule (PT-heatmap): the cell layout its cells or grid
609
+ * name, the value word (book `size`, volume_profile `total` by default; a
610
+ * grid's own values), diverging around a centre (declared, or a signed or
611
+ * delta word) and the zero floor of the sequential size and volume words.
612
+ * Null when the cells name no book or volume_profile input. */
613
+ function heatmapScaleRule(sheet, heatmap) {
614
+ let layout;
615
+ let valueField;
616
+ if (heatmap.grid !== undefined) {
617
+ layout = 'grid';
618
+ valueField = 'total';
619
+ }
620
+ else {
621
+ const source = inputSourceClass(sheet, heatmap.cells);
622
+ if (source === 'book') {
623
+ layout = 'book';
624
+ valueField = heatmap.value ?? 'size';
625
+ }
626
+ else if (source === 'volume_profile') {
627
+ layout = 'profile';
628
+ valueField = heatmap.value ?? 'total';
629
+ }
630
+ else
631
+ return null;
632
+ }
633
+ const diverging = heatmap.center !== undefined || valueField === 'signed' || valueField === 'delta';
634
+ return { layout, valueField, diverging, zeroFloor: layout !== 'grid' && !diverging };
635
+ }
636
+ /** True when a param already moves the heatmap's quantile: a `style_targets`
637
+ * path `["heatmaps", <its index or name>, "auto_quantile"]`. That param's
638
+ * own row is the control. */
639
+ function quantileBoundByParam(sheet, heatmap, index) {
640
+ return (sheet.params ?? []).some((param) => {
641
+ const targets = param.style_targets;
642
+ return (Array.isArray(targets) &&
643
+ targets.some((target) => {
644
+ const path = isRecord(target) ? target.path : undefined;
645
+ return (Array.isArray(path) &&
646
+ path.length === 3 &&
647
+ path[0] === 'heatmaps' &&
648
+ (path[1] === index || path[1] === heatmap.name) &&
649
+ path[2] === 'auto_quantile');
650
+ }));
651
+ });
652
+ }
653
+ /**
654
+ * The Sensitivity row rule, one rule for the row, the child's scale words
655
+ * and the mount's re-pick: the heatmap's cells resolve (book,
656
+ * volume_profile or a grid), a bound comes from the quantile (`max` left to
657
+ * the sample, or `min` left to it where it has no zero floor), and no param
658
+ * binds its `auto_quantile`. So both bounds declared shows no row, nor does a
659
+ * size, bid, ask or volume word with `max` declared (its min is 0); one bound
660
+ * declared on a diverging or grid heatmap shows one. Null when no row shows.
661
+ */
662
+ function heatmapSensitivityRule(sheet, heatmap, index) {
663
+ const rule = heatmapScaleRule(sheet, heatmap);
664
+ if (rule === null)
665
+ return null;
666
+ const fromQuantile = !finite(heatmap.max) || (!finite(heatmap.min) && !rule.zeroFloor);
667
+ return fromQuantile && !quantileBoundByParam(sheet, heatmap, index) ? rule : null;
668
+ }
669
+ /** The author's scale words as declared (absent words stay absent). */
670
+ function heatmapScaleWords(heatmap) {
671
+ return {
672
+ ...(heatmap.min !== undefined ? { min: heatmap.min } : {}),
673
+ ...(heatmap.max !== undefined ? { max: heatmap.max } : {}),
674
+ ...(heatmap.center !== undefined ? { center: heatmap.center } : {}),
675
+ ...(heatmap.auto_quantile !== undefined ? { auto_quantile: heatmap.auto_quantile } : {}),
676
+ ...(heatmap.scale !== undefined ? { scale: heatmap.scale } : {}),
677
+ };
678
+ }
679
+ /** The scale sample a heatmap child was built with, kept beside it (keyed by
680
+ * the child's own rows array, a fresh array per child): a Sensitivity re-pick
681
+ * needs only a new selection, never another walk of the window. */
682
+ const heatmapSamples = new WeakMap();
683
+ /**
684
+ * A windowed landing (wrun-panel-mount.util: a pan-back page or a prefix run landed inside its history
685
+ * window) keeps the colour scale its heatmap was drawn with; only a full run samples again. The rows it lands
686
+ * take the sample the mounted rows' bounds were picked from, so a Sensitivity re-pick afterwards reads that
687
+ * sample instead of walking the landed rows into another basis. A child with no kept sample (one that
688
+ * crossed a copy or a trim) still walks its rows on the next re-pick, as before.
689
+ */
690
+ export function keepWrunHeatmapScaleSample(from, to) {
691
+ const sample = heatmapSamples.get(from);
692
+ if (sample !== undefined && from !== to)
693
+ heatmapSamples.set(to, sample);
694
+ }
695
+ /** The newest `tailRows` rows of a source (a live tick's tail), else all of them. */
696
+ function newestRows(rows, tailRows) {
697
+ return tailRows === undefined ? rows : rows.slice(Math.max(0, rows.length - tailRows));
698
+ }
699
+ /** A canvas row as the engine reads it: a plain array. The live book lane
700
+ * hands typed rows (`Float64Array`, wrunLiveBookRows) the worker run wants,
701
+ * which the engine's row readers and live merge skip, so the bars fed live
702
+ * (the forming bar, a just-closed bar until history serves it) would draw no
703
+ * column. Plain rows pass through shared; only the few typed ones are copied. */
704
+ export function wrunPlainCanvasRow(row) {
705
+ if (Array.isArray(row) || !ArrayBuffer.isView(row))
706
+ return row;
707
+ return Array.from(row);
708
+ }
709
+ function heatmapChild(sheet, heatmap, index, cellRows, outputRows, tailRows) {
710
+ const rule = heatmapScaleRule(sheet, heatmap);
711
+ if (rule === null)
712
+ return null;
713
+ const { layout, valueField, diverging, zeroFloor } = rule;
714
+ let data;
715
+ if (layout === 'grid')
716
+ data = gridRowsOf(sheet, heatmap, newestRows(outputRows, tailRows));
717
+ else
718
+ data = newestRows((layout === 'book' ? cellRows?.bookRows : cellRows?.volumeProfileRows) ?? [], tailRows).map(wrunPlainCanvasRow);
719
+ // A tick's tail samples no scale and keeps no Sensitivity inputs: its rows
720
+ // only merge into a mounted canvas, which keeps the bounds (and the sample a
721
+ // Sensitivity re-pick reads) of the full run that mounted it.
722
+ let scale;
723
+ let sensitivity = null;
724
+ if (tailRows === undefined) {
725
+ const sample = sampleCellValues(layout, valueField, data);
726
+ scale = wrunCanvasScaleOf(heatmap, sample, { diverging, zeroFloor });
727
+ sensitivity = heatmapSensitivityRule(sheet, heatmap, index);
728
+ if (sensitivity !== null)
729
+ heatmapSamples.set(data, sample);
730
+ }
731
+ const format = numberFormatOf(heatmap);
732
+ const rowHeight = heatmap.row_height ?? (layout === 'book' ? bookGroupingOf(data) : undefined);
733
+ const settings = {
734
+ cellLayout: layout,
735
+ valueField,
736
+ ...(rowHeight !== undefined ? { rowHeight } : {}),
737
+ palette: [...(heatmap.palette ?? (diverging ? WRUN_HEATMAP_DIVERGING_PALETTE : WRUN_HEATMAP_DEFAULT_PALETTE))],
738
+ ...(scale !== undefined
739
+ ? {
740
+ min: scale.min,
741
+ max: scale.max,
742
+ ...(scale.center !== undefined ? { center: scale.center } : {}),
743
+ scale: scale.scale,
744
+ }
745
+ : {}),
746
+ floor: heatmap.floor ?? 0,
747
+ opacity: heatmap.opacity ?? 0.85,
748
+ behindCandles: heatmap.behind_candles ?? true,
749
+ cellGapPx: heatmap.cell_gap ?? 0,
750
+ labels: heatmap.labels ?? false,
751
+ fontSize: heatmap.font_size ?? 10,
752
+ fontWeight: heatmap.font_weight ?? 'normal',
753
+ fontFamily: wrunFontFamilyCss(heatmap.font_family ?? 'ui'),
754
+ textColor: heatmap.text_color ?? 'theme.text',
755
+ // The cell label format rides as a spec (data): the mount door builds the
756
+ // engine's `formatValue` from it (wrunCanvasChildConfig), so the child
757
+ // never carries a function into the run result.
758
+ valueFormat: format,
759
+ hoverReadout: heatmap.tooltip !== undefined,
760
+ };
761
+ const readout = heatmap.tooltip !== undefined
762
+ ? { kind: 'heatmap', label: heatmap.label ?? wrunCanvasNameWords(heatmap.name), tooltip: heatmap.tooltip, format }
763
+ : undefined;
764
+ return {
765
+ kind: 'heatmap',
766
+ name: heatmap.name,
767
+ data,
768
+ settings,
769
+ ...(readout !== undefined ? { readout } : {}),
770
+ ...(sensitivity !== null ? { scale: { ...sensitivity, words: heatmapScaleWords(heatmap) } } : {}),
771
+ ...(tailRows !== undefined ? { tailOnly: true } : {}),
772
+ };
773
+ }
774
+ /** One child per `heatmaps[]` entry (PT-heatmap): book cells ride the book
775
+ * rows (`cellLayout: 'book'`), volume_profile cells the profile rows
776
+ * (`'profile'`), a grid the rows built from its outputs (`'grid'`).
777
+ * `tailRows` (a live tick) builds each child from the newest that many
778
+ * output rows (grid) or cell rows (book, profile) only, samples no colour
779
+ * scale and marks it `tailOnly`; the rows before the tail are never read. */
780
+ export function wrunHeatmapChildren(sheet, cellRows, outputRows, options) {
781
+ const children = [];
782
+ (sheet.heatmaps ?? []).forEach((heatmap, index) => {
783
+ // A heatmap its Style row switched off (C1 `heatmap:<name>` Visible) builds no child.
784
+ if (isWrunStyleTargetHidden(heatmap))
785
+ return;
786
+ const child = heatmapChild(sheet, heatmap, index, cellRows, outputRows, options?.tailRows);
787
+ if (child !== null)
788
+ children.push(child);
789
+ });
790
+ return children;
791
+ }
792
+ /** One row per heatmap the row rule admits (heatmapSensitivityRule), in sheet order. */
793
+ export function wrunHeatmapSensitivityRows(sheet) {
794
+ if (sheet === undefined)
795
+ return [];
796
+ const rows = [];
797
+ (sheet.heatmaps ?? []).forEach((heatmap, index) => {
798
+ if (heatmapSensitivityRule(sheet, heatmap, index) === null)
799
+ return;
800
+ const quantile = finite(heatmap.auto_quantile) ? heatmap.auto_quantile : WRUN_CANVAS_DEFAULT_QUANTILE;
801
+ rows.push({
802
+ name: heatmap.name,
803
+ label: heatmap.label ?? wrunCanvasNameWords(heatmap.name),
804
+ defaultPosition: heatmapSensitivityForQuantile(quantile),
805
+ });
806
+ });
807
+ return rows;
808
+ }
809
+ /**
810
+ * A heatmap child's colour bounds under the viewer's Sensitivity (0..100):
811
+ * re-picked from the child's own scale sample at the position's quantile
812
+ * (the options heatmap's map); the child's own bounds, the author's exactly,
813
+ * when no position is set or the child carries no scale words. The centre
814
+ * never depends on the quantile, so only `min` and `max` move.
815
+ */
816
+ export function wrunHeatmapSensitivityBounds(child, sensitivity) {
817
+ const own = { min: child.settings.min, max: child.settings.max };
818
+ const inputs = child.scale;
819
+ if (child.kind !== 'heatmap' || inputs === undefined || !finite(sensitivity))
820
+ return own;
821
+ let sample = heatmapSamples.get(child.data);
822
+ if (sample === undefined) {
823
+ // A child that crossed a copy (no kept sample) walks its rows again.
824
+ sample = sampleCellValues(inputs.layout, inputs.valueField, child.data);
825
+ heatmapSamples.set(child.data, sample);
826
+ }
827
+ const scale = wrunCanvasScaleOf({ ...inputs.words, auto_quantile: heatmapSensitivityQuantile(sensitivity) }, sample, {
828
+ diverging: inputs.diverging,
829
+ zeroFloor: inputs.zeroFloor,
830
+ });
831
+ return { min: scale.min, max: scale.max };
832
+ }
833
+ // ── PT-footprint and PT-tpo ─────────────────────────────────────────────────
834
+ const FOOTPRINT_DISPLAY_MODES = {
835
+ cluster: 'cluster',
836
+ split_bar: 'split-bar',
837
+ stacked_bar: 'stacked-bar',
838
+ ladder: 'ladder',
839
+ imbalance_only: 'imbalance-only',
840
+ };
841
+ const TPO_BLOCK_DISPLAYS = {
842
+ letters: 'letters-only',
843
+ blocks: 'blocks-only',
844
+ both: 'blocks+letters',
845
+ };
846
+ /** The text words every profile kind shares (X14: the family resolves to a CSS stack). */
847
+ function profileTextSettings(profile) {
848
+ const fontFamily = wrunFontFamilyCss(profile.font_family);
849
+ return {
850
+ ...(fontFamily !== undefined ? { fontFamily } : {}),
851
+ ...(profile.font_weight !== undefined ? { fontWeight: profile.font_weight } : {}),
852
+ };
853
+ }
854
+ function footprintChild(profile, cellRows, ctx) {
855
+ const data = [...(cellRows?.volumeProfileRows ?? [])];
856
+ const bucketWidth = bucketWidthOf(data) ?? ctx.priceTick;
857
+ let barHeight;
858
+ let minimumBarHeight;
859
+ if (typeof profile.row_height === 'number' && profile.row_height > 0) {
860
+ barHeight = profile.row_height;
861
+ minimumBarHeight = profile.row_height;
862
+ }
863
+ else if (bucketWidth !== undefined) {
864
+ barHeight = bucketWidth * profileRowMultiplier('footprint', ctx.intervalMs);
865
+ minimumBarHeight = bucketWidth;
866
+ }
867
+ const cellHover = profile.cell_hover ?? true;
868
+ const settings = {
869
+ variant: 'session',
870
+ session: ctx.intervalMs,
871
+ sessionType: 'Footprint',
872
+ stickToLeft: true,
873
+ skipZeroValues: true,
874
+ trimZeroTails: true,
875
+ hideLegendValues: true,
876
+ displayMode: FOOTPRINT_DISPLAY_MODES[profile.mode ?? WRUN_FOOTPRINT_MODE_DEFAULT],
877
+ colors: [profile.buy_color ?? 'theme.up', profile.sell_color ?? 'theme.down'],
878
+ ...(barHeight !== undefined ? { barHeight } : {}),
879
+ ...(minimumBarHeight !== undefined ? { minimumBarHeight } : {}),
880
+ barWidth: 0.7,
881
+ showValue: profile.labels ?? true,
882
+ hideZeroText: profile.hide_zero ?? false,
883
+ ...(profile.text_color !== undefined ? { cellTextColor: profile.text_color } : {}),
884
+ imbalance: profile.imbalance ?? false,
885
+ imbalanceRatio: profile.imbalance_ratio ?? 3,
886
+ imbalanceBuyColor: profile.imbalance_buy_color ?? 'theme.up',
887
+ imbalanceSellColor: profile.imbalance_sell_color ?? 'theme.down',
888
+ stackedImbalances: profile.stacked_imbalances ?? 3,
889
+ showPOC: profile.poc ?? true,
890
+ pocColor: profile.poc_color ?? 'theme.text',
891
+ pocThickness: profile.poc_width ?? 1,
892
+ valueArea: profile.value_area ?? 0.7,
893
+ showValueArea: true,
894
+ showVAH: profile.vah ?? true,
895
+ showVAL: profile.val ?? true,
896
+ vahColor: profile.vah_color ?? 'theme.text',
897
+ valColor: profile.val_color ?? 'theme.text',
898
+ clusterCellMetric: profile.cell_metric ?? WRUN_FOOTPRINT_CELL_METRIC_DEFAULT,
899
+ volumeColor: profile.volume_color ?? '#4a90e2',
900
+ scaleAndGrading: profile.grading ?? 'candle',
901
+ ...profileTextSettings(profile),
902
+ cellHover,
903
+ showHoverInspector: cellHover,
904
+ };
905
+ return { kind: 'profile', name: profile.name, data, settings };
906
+ }
907
+ /**
908
+ * The TPO child (PT-tpo): period rows built from the bars or the
909
+ * volume_profile rows, the sheet words mapped to the engine's TPO keys. The
910
+ * declared `palette` (the C1 `profile:<name>` colours row) rides ONE titan
911
+ * ramp: `colors`, the sequential ramp of the period, count and volume modes
912
+ * and of the legend swatch, or in `color_mode: "delta"` `deltaColors` only,
913
+ * titan's diverging sell / neutral / buy ramp, so a delta palette never lands
914
+ * in the sequential slot. The mount door resolves its colour words either way
915
+ * and fills a missing `colors` from the user's TPO scheme (a delta TPO, a
916
+ * TPO without a palette); a delta TPO without a palette keeps titan's default
917
+ * delta ramp.
918
+ */
919
+ function tpoChild(sheet, profile, cellRows, ctx) {
920
+ const source = inputSourceClass(sheet, profile.cells);
921
+ const period = profile.period ?? 'day';
922
+ const letterMinutes = profile.letter_minutes ?? 30;
923
+ let bars;
924
+ let profileRows;
925
+ let barIntervalMs = ctx.intervalMs;
926
+ if (source === 'volume_profile') {
927
+ profileRows = cellRows?.volumeProfileRows ?? [];
928
+ }
929
+ else if (source === 'intrabar' && profile.cells !== undefined) {
930
+ bars = cellRows?.intrabarRowsByInput?.[profile.cells] ?? cellRows?.intrabarRows ?? [];
931
+ barIntervalMs = cellRows?.intrabarIntervalMsByInput?.[profile.cells] ?? rowsIntervalMs(bars) ?? ctx.intervalMs;
932
+ }
933
+ else {
934
+ bars = cellRows?.ohlcvRows ?? [];
935
+ }
936
+ const explicit = typeof profile.row_height === 'number' && profile.row_height > 0 ? profile.row_height : undefined;
937
+ const asked = explicit !== undefined
938
+ ? { rowHeight: explicit, minimumBarHeight: explicit }
939
+ : tpoAutoRow(ctx, period, cellRows, bars, profileRows);
940
+ // The overlay's row cache key (the fold memoizes closed periods behind it)
941
+ // rides a spread typed here, so the input compiles whether or not the
942
+ // builder's own input declares it yet.
943
+ const cacheKey = ctx.overlayId !== undefined ? { cacheKey: `${ctx.overlayId}::tpo:${profile.name}` } : {};
944
+ const input = {
945
+ name: profile.name,
946
+ period,
947
+ letterMinutes,
948
+ rowHeight: asked.rowHeight,
949
+ barIntervalMs,
950
+ ...(bars !== undefined ? { bars: bars } : {}),
951
+ ...(profileRows !== undefined ? { profileRows: profileRows } : {}),
952
+ ...(ctx.exchange !== undefined ? { exchange: ctx.exchange } : {}),
953
+ ...cacheKey,
954
+ };
955
+ const { data, rowHeight, minimumBarHeight, doublings } = foldTpoRowsUnderCap(input, asked.minimumBarHeight);
956
+ const notices = doublings > 0
957
+ ? [tpoCoarsenedNotice(profile.name, period, explicit === undefined, asked.rowHeight, rowHeight)]
958
+ : undefined;
959
+ const tradingDayAnchor = getTradingDayAnchor(ctx.exchange);
960
+ const cellHover = profile.cell_hover ?? true;
961
+ // The palette's titan ramp: delta rows paint from `deltaColors`, every other mode from `colors`.
962
+ const paletteKey = profile.color_mode === 'delta' ? 'deltaColors' : 'colors';
963
+ const settings = {
964
+ variant: 'tpo',
965
+ ...(tradingDayAnchor !== undefined ? { tradingDayAnchor } : {}),
966
+ expandAll: false,
967
+ mergedPeriodsMap: {},
968
+ expandedPeriodsMap: {},
969
+ hideLegendValues: true,
970
+ sessionType: tpoPeriodWord(period),
971
+ tpoBlockSizeMinutes: letterMinutes,
972
+ barHeight: rowHeight,
973
+ minimumBarHeight,
974
+ blockDisplay: TPO_BLOCK_DISPLAYS[profile.display ?? 'both'],
975
+ showLetters: (profile.display ?? 'both') !== 'blocks',
976
+ ...(profile.palette !== undefined ? { [paletteKey]: [...profile.palette] } : {}),
977
+ blockColorMode: profile.color_mode ?? 'period',
978
+ valueAreaPercentage: (profile.value_area ?? 0.7) * 100,
979
+ showPOC: profile.poc ?? true,
980
+ showVAH: profile.vah ?? true,
981
+ showVAL: profile.val ?? true,
982
+ pocColor: profile.poc_color ?? 'theme.text',
983
+ vahColor: profile.vah_color ?? 'theme.muted',
984
+ valColor: profile.val_color ?? 'theme.muted',
985
+ outsideVAOpacity: profile.outside_va_opacity ?? 0.3,
986
+ showOutsideVAColors: true,
987
+ showIBR: profile.initial_balance ?? true,
988
+ ibrColor: profile.ib_color ?? 'theme.text',
989
+ showSinglePrints: profile.single_prints ?? false,
990
+ singlePrintsColor: profile.single_prints_color ?? '#cc0033',
991
+ showPoorHighs: profile.poor_extremes ?? false,
992
+ showPoorLows: profile.poor_extremes ?? false,
993
+ poorHighsColor: profile.poor_extremes_color ?? '#ffd966',
994
+ poorLowsColor: profile.poor_extremes_color ?? '#ffd966',
995
+ showTPOCounts: profile.counts ?? false,
996
+ showVolumeProfile: profile.volume_profile ?? false,
997
+ ...profileTextSettings(profile),
998
+ cellHover,
999
+ showHoverInspector: cellHover,
1000
+ };
1001
+ return { kind: 'profile', name: profile.name, data, settings, ...(notices !== undefined ? { notices } : {}) };
1002
+ }
1003
+ /**
1004
+ * The TPO's auto row (G1): the resolver's unit (wrun-auto-row.util: the
1005
+ * volume_profile bucket width, the served TPO block or the CME engine tick,
1006
+ * the snapped median positive candle range / 4, 1 when no bar moved) times the
1007
+ * native row table, except a bar-range unit, which is the row as is (it
1008
+ * already scales with the interval, the table would count the interval
1009
+ * twice). The unit floors only where the widest feeding bar expands into
1010
+ * half the builder's per-bar cap, so the builder's refusal never fires on
1011
+ * auto (a liquid venue's bars sit far above the floor); never at the axis step.
1012
+ */
1013
+ function tpoAutoRow(ctx, period, cellRows, bars, profileRows) {
1014
+ const resolved = wrunAutoRowUnit({
1015
+ kind: 'tpo',
1016
+ bucketWidth: profileRows !== undefined ? bucketWidthOf(profileRows) : undefined,
1017
+ // The served block, else the CME engine tick: venue facts, both times the table.
1018
+ blockSize: ctx.tpoBlockSize ?? ctx.priceTick,
1019
+ // The chart's own candles size the fallback, like the native table keys
1020
+ // on the chart interval (an intrabar leg's finer bars would shrink it).
1021
+ bars: (cellRows?.ohlcvRows ?? bars),
1022
+ });
1023
+ const multiplier = resolved.source === 'bar-range' ? 1 : profileRowMultiplier('tpo', ctx.intervalMs, tpoPeriodWord(period));
1024
+ const unit = Math.max(resolved.unit, widestBarSpan(bars ?? []) / ((WRUN_TPO_MAX_ROWS_PER_BAR / 2) * multiplier));
1025
+ return { rowHeight: trimmedRowHeight(unit * multiplier), minimumBarHeight: unit };
1026
+ }
1027
+ /** A row height trimmed of float noise (the builder's rowPrice rule). */
1028
+ function trimmedRowHeight(value) {
1029
+ return Number(value.toPrecision(12));
1030
+ }
1031
+ /** The most levels any period row holds (a row is `[startMs, ...levels, metrics]`). */
1032
+ function mostLevelsPerPeriod(rows) {
1033
+ let most = 0;
1034
+ for (const row of rows)
1035
+ most = Math.max(most, row.length - 2);
1036
+ return most;
1037
+ }
1038
+ /**
1039
+ * The fold under the rows-per-period cap (G1): while a period row holds
1040
+ * more than WRUN_MAX_ROWS_PER_PERIOD levels, the row height and the minimum
1041
+ * bar height double and the bars fold again, at most
1042
+ * WRUN_ROW_CAP_MAX_DOUBLINGS times; the last fold is accepted. Each fold
1043
+ * walks about half the rows of the one before, so every retry together
1044
+ * costs less than the first fold.
1045
+ */
1046
+ function foldTpoRowsUnderCap(input, minimumBarHeight) {
1047
+ let rowHeight = input.rowHeight;
1048
+ let minimum = minimumBarHeight;
1049
+ let data = buildWrunTpoRows(input);
1050
+ let doublings = 0;
1051
+ while (doublings < WRUN_ROW_CAP_MAX_DOUBLINGS && mostLevelsPerPeriod(data) > WRUN_MAX_ROWS_PER_PERIOD) {
1052
+ doublings += 1;
1053
+ rowHeight *= 2;
1054
+ minimum *= 2;
1055
+ const coarser = { ...input, rowHeight };
1056
+ data = buildWrunTpoRows(coarser);
1057
+ }
1058
+ return { data, rowHeight, minimumBarHeight: minimum, doublings };
1059
+ }
1060
+ /** The author's line when the cap coarsened a TPO's rows: the declaration,
1061
+ * both row heights and the period the limit counts over. */
1062
+ function tpoCoarsenedNotice(name, period, auto, from, to) {
1063
+ const limit = `${WRUN_MAX_ROWS_PER_PERIOD} rows per ${period} is the chart's limit`;
1064
+ const asked = String(trimmedRowHeight(from));
1065
+ const drawn = String(trimmedRowHeight(to));
1066
+ return auto
1067
+ ? `tpo '${name}': row_height auto coarsened from ${asked} to ${drawn} (${limit})`
1068
+ : `tpo '${name}': row_height ${asked} coarsened to ${drawn} (${limit})`;
1069
+ }
1070
+ /** The runtime row code of a canvas notice: a warning, the canvas still draws. */
1071
+ export const WRUN_CANVAS_NOTICE_CODE = 'WRUN_CANVAS_NOTICE';
1072
+ /** The rows a run seam owns for its canvas notices: replaced by every full
1073
+ * run (drafts and registry Indicators alike, a viewer of a published script
1074
+ * sees them too), cleared by a run with none. */
1075
+ export const WRUN_CANVAS_NOTICE_ROW_CODES = new Set([WRUN_CANVAS_NOTICE_CODE]);
1076
+ /**
1077
+ * One warning row per notice (`wrunRunNoticesOf(runResult)`), the shape the
1078
+ * chart store's diagnostics take: the editor console's Problems tab lists
1079
+ * each line with warning severity, and the indicator's legend chip shows the
1080
+ * warning glyph with the lines on hover (runtime-diagnostics.util
1081
+ * `buildLegendErrorMessage`; a warning never toasts and never fails the run
1082
+ * entry). The rows name no source line: the cap depends on the chart's
1083
+ * prices, which only the running chart knows.
1084
+ */
1085
+ export function wrunCanvasNoticeDiagnostics(notices) {
1086
+ return notices.map((message) => ({
1087
+ stage: 'render',
1088
+ severity: 'warning',
1089
+ code: WRUN_CANVAS_NOTICE_CODE,
1090
+ type: 'execution',
1091
+ message,
1092
+ }));
1093
+ }
1094
+ /** One child per `profiles[]` entry: a footprint column per bar from the
1095
+ * volume_profile rows (PT-footprint), TPO period rows built from the bars
1096
+ * (PT-tpo), and the time-anchored volume profile wrun-volume-profile.util
1097
+ * builds (DL-time-anchored, X31). */
1098
+ export function wrunProfileChildren(sheet, cellRows, ctx) {
1099
+ const children = [];
1100
+ for (const profile of sheet.profiles ?? []) {
1101
+ // A profile its Style row switched off (C1 `profile:<name>` Visible) builds no child.
1102
+ if (isWrunStyleTargetHidden(profile))
1103
+ continue;
1104
+ const child = profileChild(sheet, profile, cellRows, ctx);
1105
+ if (child !== null)
1106
+ children.push(child);
1107
+ }
1108
+ return children;
1109
+ }
1110
+ function profileChild(sheet, profile, cellRows, ctx) {
1111
+ switch (profile.kind) {
1112
+ case 'footprint':
1113
+ return footprintChild(profile, cellRows, ctx);
1114
+ case 'tpo':
1115
+ return tpoChild(sheet, profile, cellRows, ctx);
1116
+ case 'volume':
1117
+ // A range profile resolves its `start` / `end` output names through
1118
+ // the sheet's output declarations; without them it mounts nothing.
1119
+ return wrunVolumeProfileChild(profile, cellRows, { ...ctx, outputs: sheet.outputs });
1120
+ default:
1121
+ return null;
1122
+ }
1123
+ }
1124
+ function matrixCellValue(cell) {
1125
+ if (finite(cell))
1126
+ return cell;
1127
+ if (isRecord(cell) && finite(cell.value))
1128
+ return cell.value;
1129
+ return null;
1130
+ }
1131
+ function matrixColumnsOf(matrix, frame) {
1132
+ if (matrix.columns !== undefined)
1133
+ return [...matrix.columns];
1134
+ if (frame.cols !== undefined)
1135
+ return [...frame.cols];
1136
+ const width = frame.cells[0]?.length ?? 0;
1137
+ return Array.from({ length: width }, (_, at) => String(at + 1));
1138
+ }
1139
+ /** The matrix rows `[price, ...cells]` with every cell resolved against
1140
+ * `theme`: the cell's text (its own, else the formatted number), its fill
1141
+ * (its colour, else the palette at the value over the bounds, times the
1142
+ * opacity), its ink and weight. */
1143
+ export function wrunMatrixRows(matrix, frame, theme) {
1144
+ const shape = frame;
1145
+ const format = numberFormatOf(matrix);
1146
+ const opacity = matrix.opacity ?? 1;
1147
+ const numbers = [];
1148
+ for (const row of shape.cells)
1149
+ for (const cell of row) {
1150
+ const value = matrixCellValue(cell);
1151
+ if (value !== null)
1152
+ numbers.push(value);
1153
+ }
1154
+ const scale = wrunCanvasScaleOf({
1155
+ min: shape.range?.min ?? matrix.min,
1156
+ max: shape.range?.max ?? matrix.max,
1157
+ center: matrix.center,
1158
+ auto_quantile: matrix.auto_quantile,
1159
+ scale: matrix.scale,
1160
+ }, numbers, { diverging: matrix.center !== undefined, zeroFloor: false });
1161
+ const palette = matrix.palette?.map((word) => resolveWrunColorWord(word, theme));
1162
+ const ink = resolveWrunColorWord(matrix.text_color ?? 'theme.text', theme);
1163
+ const weight = matrix.font_weight ?? 'normal';
1164
+ return shape.prices.map((price, rowAt) => {
1165
+ const cells = (shape.cells[rowAt] ?? []).map((cell) => {
1166
+ const value = matrixCellValue(cell);
1167
+ const object = isRecord(cell) ? cell : undefined;
1168
+ const text = typeof cell === 'string'
1169
+ ? cell
1170
+ : typeof object?.text === 'string'
1171
+ ? object.text
1172
+ : value !== null
1173
+ ? formatWrunNumber(value, format)
1174
+ : '';
1175
+ let fill;
1176
+ if (typeof object?.color === 'string')
1177
+ fill = resolveWrunColorWord(object.color, theme);
1178
+ else if (palette !== undefined && value !== null) {
1179
+ fill = wrunCanvasPaletteColor(palette, wrunCanvasScalePosition(value, scale));
1180
+ }
1181
+ if (fill !== undefined)
1182
+ fill = wrunCanvasMultiplyAlpha(fill, opacity);
1183
+ return {
1184
+ text,
1185
+ ...(fill !== undefined ? { fill } : {}),
1186
+ ink: typeof object?.text_color === 'string' ? resolveWrunColorWord(object.text_color, theme) : ink,
1187
+ weight: typeof object?.font_weight === 'string' ? object.font_weight : weight,
1188
+ value,
1189
+ };
1190
+ });
1191
+ return [price, ...cells];
1192
+ });
1193
+ }
1194
+ function matrixSettings(matrix, frame, columns) {
1195
+ const dock = matrix.dock ?? 'right';
1196
+ const columnWidthPx = matrix.column_width ?? 56;
1197
+ const priceColumn = matrix.price_column ?? false;
1198
+ return {
1199
+ dock,
1200
+ columns,
1201
+ columnWidthPx,
1202
+ rowMaxPx: matrix.row_max_px ?? 24,
1203
+ priceColumn,
1204
+ header: matrix.header ?? true,
1205
+ ...(frame.title !== undefined ? { title: frame.title } : {}),
1206
+ ...(frame.highlight !== undefined ? { highlight: { ...frame.highlight } } : {}),
1207
+ highlightColor: matrix.highlight_color ?? 'theme.accent',
1208
+ fontSize: matrix.font_size ?? 10,
1209
+ fontWeight: matrix.font_weight ?? 'normal',
1210
+ fontFamily: wrunFontFamilyCss(matrix.font_family ?? 'ui'),
1211
+ align: matrix.align ?? 'right',
1212
+ textColor: matrix.text_color ?? 'theme.text',
1213
+ headerTextColor: matrix.header_text_color ?? 'theme.muted',
1214
+ headerBackgroundColor: matrix.header_background_color ?? 'theme.bg',
1215
+ backgroundColor: matrix.background_color ?? 'theme.bg',
1216
+ backgroundOpacity: matrix.background_opacity ?? 0.85,
1217
+ gridColor: matrix.grid_color ?? 'theme.grid',
1218
+ gridWidth: matrix.grid_width ?? 1,
1219
+ gridStyle: matrix.grid_style ?? 'solid',
1220
+ gridLines: matrix.grid_lines ?? 'all',
1221
+ borderColor: matrix.border_color ?? 'theme.grid',
1222
+ borderWidth: matrix.border_width ?? 0,
1223
+ borderStyle: matrix.border_style ?? 'solid',
1224
+ cellPaddingPx: matrix.cell_padding ?? 4,
1225
+ hoverReadout: matrix.tooltip !== undefined,
1226
+ ...(dock === 'side'
1227
+ ? { sideDock: true, sideDockWidthPx: (columns.length + (priceColumn ? 1 : 0)) * columnWidthPx }
1228
+ : {}),
1229
+ };
1230
+ }
1231
+ /** The matrix child of a selected matrix (MX-price-matrix): rows
1232
+ * `[price, ...cells]` and the docked settings; `dock: "side"` places it in
1233
+ * the side strip (MX-side-panel). Null without a written frame. */
1234
+ export function wrunMatrixChild(matrix, frame) {
1235
+ if (frame === null)
1236
+ return null;
1237
+ const shape = frame;
1238
+ const columns = matrixColumnsOf(matrix, shape);
1239
+ const format = numberFormatOf(matrix);
1240
+ const readout = matrix.tooltip !== undefined
1241
+ ? {
1242
+ kind: 'matrix',
1243
+ label: matrix.label ?? wrunCanvasNameWords(matrix.name),
1244
+ tooltip: matrix.tooltip,
1245
+ format,
1246
+ columns,
1247
+ }
1248
+ : undefined;
1249
+ return {
1250
+ kind: 'matrix',
1251
+ name: matrix.name,
1252
+ data: wrunMatrixRows(matrix, frame, WRUN_CANVAS_FALLBACK_THEME),
1253
+ settings: matrixSettings(matrix, shape, columns),
1254
+ matrix: { declaration: matrix, frame },
1255
+ ...(readout !== undefined ? { readout } : {}),
1256
+ };
1257
+ }
1258
+ /** The budget charge of a parsed frame: 16 per cell, 8 per number, the
1259
+ * strings' UTF-8 bytes (the om runtime's rule). */
1260
+ export function wrunMatrixFrameBytes(frame) {
1261
+ const shape = frame;
1262
+ let cells = 0;
1263
+ let numbers = shape.prices.length;
1264
+ let strings = 0;
1265
+ for (const row of shape.cells) {
1266
+ for (const cell of row) {
1267
+ cells += 1;
1268
+ if (finite(cell))
1269
+ numbers += 1;
1270
+ else if (typeof cell === 'string')
1271
+ strings += utf8Bytes(cell);
1272
+ else if (isRecord(cell)) {
1273
+ if (finite(cell.value))
1274
+ numbers += 1;
1275
+ for (const key of ['text', 'color', 'text_color', 'font_weight']) {
1276
+ const text = cell[key];
1277
+ if (typeof text === 'string')
1278
+ strings += utf8Bytes(text);
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+ for (const col of shape.cols ?? [])
1284
+ strings += utf8Bytes(col);
1285
+ if (shape.title !== undefined)
1286
+ strings += utf8Bytes(shape.title);
1287
+ if (finite(shape.highlight?.price))
1288
+ numbers += 1;
1289
+ if (finite(shape.highlight?.col))
1290
+ numbers += 1;
1291
+ if (finite(shape.range?.min))
1292
+ numbers += 1;
1293
+ if (finite(shape.range?.max))
1294
+ numbers += 1;
1295
+ return 16 * cells + 8 * numbers + strings;
1296
+ }
1297
+ /**
1298
+ * The matrix selection step (render select, MX-price-matrix): parse the
1299
+ * written frame through the frame host (a refusal is `wrun_frame_invalid`),
1300
+ * refuse a frame whose column count differs from the declared `columns`,
1301
+ * and charge the frame on the shared budget. No frame = null, nothing charged.
1302
+ */
1303
+ export function selectWrunMatrix(matrix, rawFrame, slot) {
1304
+ if (rawFrame === undefined)
1305
+ return { frame: null, bytes: 0 };
1306
+ const frame = parseWrunMatrixFrame(rawFrame, slot, matrix);
1307
+ const width = frame.cells[0]?.length ?? 0;
1308
+ if (matrix.columns !== undefined && matrix.columns.length !== width) {
1309
+ return invalidWrunFrame(slot, `cells: the frame holds ${width} columns, the declaration's columns names ${matrix.columns.length}`);
1310
+ }
1311
+ return { frame, bytes: wrunMatrixFrameBytes(frame) };
1312
+ }
1313
+ // ── MX-side-panel ───────────────────────────────────────────────────────────
1314
+ /** The side-strip settings of a panel with `place: "side"` (MX-side-panel):
1315
+ * `sideDock`, the declared width (default 280 px) and height; null for a
1316
+ * panel below the chart. */
1317
+ export function wrunSidePanelSettings(panel) {
1318
+ if (panel.place !== 'side')
1319
+ return null;
1320
+ return {
1321
+ sideDock: true,
1322
+ sideDockWidthPx: panel.width_px ?? WRUN_SIDE_PANEL_DEFAULT_WIDTH_PX,
1323
+ ...(panel.height_px !== undefined ? { sideDockHeightPx: panel.height_px } : {}),
1324
+ };
1325
+ }
1326
+ // ── The mount door ──────────────────────────────────────────────────────────
1327
+ /** The native profile extractor (session volume profile, TPO): x = the row
1328
+ * index, no candle extent, the row itself as data, so processData never
1329
+ * index-slices rows that do not line up with the candles. */
1330
+ const PROFILE_EXTRACTORS = Object.freeze({
1331
+ getX1: (_point, index) => index,
1332
+ getX2: (_point, index) => index,
1333
+ getHigh: () => Number.NaN,
1334
+ getLow: () => Number.NaN,
1335
+ getData: (point) => point,
1336
+ });
1337
+ /** The live merge of a row-backed canvas (titan `mergeLiveDataPoint`): the
1338
+ * incoming row replaces the forming row (same first cell) or appends a
1339
+ * newer one; anything that is not a row keeps the last row. */
1340
+ export function wrunCanvasMergeLive(lastDataPoint, newPoint) {
1341
+ if (Array.isArray(newPoint) && finite(newPoint[0]))
1342
+ return newPoint;
1343
+ return lastDataPoint;
1344
+ }
1345
+ /** Every string (and string array) of the settings through the colour word
1346
+ * resolver: tokens become the theme's colours, anything else passes. */
1347
+ function resolveSettingsColors(settings, theme) {
1348
+ const resolved = {};
1349
+ for (const [key, value] of Object.entries(settings)) {
1350
+ if (typeof value === 'string')
1351
+ resolved[key] = resolveWrunColorWord(value, theme);
1352
+ else if (Array.isArray(value) && value.every((entry) => typeof entry === 'string')) {
1353
+ resolved[key] = value.map((entry) => resolveWrunColorWord(entry, theme));
1354
+ }
1355
+ else
1356
+ resolved[key] = value;
1357
+ }
1358
+ return resolved;
1359
+ }
1360
+ /** Equal format words: the same keys, each value the same (`Object.is`, so a
1361
+ * callback among them is equal only to itself). */
1362
+ function sameFormatWords(kept, next) {
1363
+ const keys = Object.keys(kept);
1364
+ if (keys.length !== Object.keys(next).length)
1365
+ return false;
1366
+ return keys.every((key) => Object.prototype.hasOwnProperty.call(next, key) && Object.is(kept[key], next[key]));
1367
+ }
1368
+ /** The label formatter of child `id` for `words`: the kept one while its frozen
1369
+ * words equal these, else a new one over a frozen copy (so the run's object
1370
+ * moving later never reaches it), kept for the next build. */
1371
+ function wrunCanvasLabelFormatter(id, words, formatters) {
1372
+ const kept = formatters?.get(id);
1373
+ if (kept !== undefined && sameFormatWords(kept.words, words))
1374
+ return kept.formatValue;
1375
+ const frozen = Object.freeze({ ...words });
1376
+ const formatValue = (value) => formatWrunNumber(value, frozen);
1377
+ formatters?.set(id, { words: frozen, formatValue });
1378
+ return formatValue;
1379
+ }
1380
+ /**
1381
+ * The engine config of a canvas child at mount (and at every retranslate,
1382
+ * X13): the child id, the plot, the settings with every colour word
1383
+ * resolved against the chart's theme (and a heatmap's bounds at the viewer's
1384
+ * Sensitivity), the profile extractor and the live merge for row-backed
1385
+ * kinds, and (matrices) the rows re-resolved against the theme. A child with
1386
+ * a readout registers it for the hover inspector; a tick's heatmap tail
1387
+ * carries `tailOnly` over, so the mount knows its rows are not the canvas's.
1388
+ */
1389
+ export function wrunCanvasChildConfig(child, ctx) {
1390
+ const id = wrunCanvasChildId(ctx.overlayId, child.kind, child.name);
1391
+ const settings = resolveSettingsColors(child.settings, ctx.theme);
1392
+ // The viewer's Sensitivity: a heatmap with scale words takes the bounds
1393
+ // re-picked at its quantile; the run's own stay the author's.
1394
+ if (child.scale !== undefined && finite(ctx.heatmapSensitivity)) {
1395
+ const bounds = wrunHeatmapSensitivityBounds(child, ctx.heatmapSensitivity);
1396
+ settings.min = bounds.min;
1397
+ settings.max = bounds.max;
1398
+ }
1399
+ // A heatmap's cell label format: the child carries the spec, the engine
1400
+ // reads a function; it is attached here, at the door, after the run result
1401
+ // was validated (an app-created function never rides the run result). The
1402
+ // mount's kept function is reused while the words are equal.
1403
+ if ('valueFormat' in settings) {
1404
+ const valueFormat = settings.valueFormat;
1405
+ delete settings.valueFormat;
1406
+ settings.formatValue = wrunCanvasLabelFormatter(id, valueFormat, ctx.formatters);
1407
+ }
1408
+ if (child.kind === 'profile' && child.settings.variant === 'tpo' && child.settings.colors === undefined) {
1409
+ const schemes = DEFAULT_TPO_COLOR_SCHEMES;
1410
+ settings.colors = [...(schemes[ctx.themeMode ?? DEFAULT_TPO_SCHEME] ?? schemes[DEFAULT_TPO_SCHEME])];
1411
+ }
1412
+ if (child.readout !== undefined)
1413
+ rememberWrunCanvasReadout(id, child.readout);
1414
+ else
1415
+ forgetWrunCanvasReadout(id);
1416
+ const config = { id, plot: CHILD_PLOT[child.kind], type: 'onchart', settings };
1417
+ if (child.kind === 'profile')
1418
+ config.extractors = PROFILE_EXTRACTORS;
1419
+ if (child.kind !== 'matrix')
1420
+ config.mergeLiveDataPoint = wrunCanvasMergeLive;
1421
+ if (child.tailOnly === true)
1422
+ config.tailOnly = true;
1423
+ if (child.kind === 'matrix' && child.matrix !== undefined) {
1424
+ config.data = wrunMatrixRows(child.matrix.declaration, child.matrix.frame, ctx.theme);
1425
+ }
1426
+ return config;
1427
+ }
1428
+ // ── The hover readout (heatmap and matrix cells) ────────────────────────────
1429
+ //
1430
+ // The registry and the tooltip text live in wrun-canvas-readout.util (a thin fact the boot-path
1431
+ // hover inspector reads); the mount above and the panel mount write it through these names.
1432
+ export { __resetWrunCanvasReadoutsForTests, forgetWrunCanvasReadout, rememberWrunCanvasReadout, wrunCanvasReadoutOf, wrunCanvasReadoutText, } from './wrun-canvas-readout.util.js';