@orangecharts/wrun-chart-host 0.2.0 → 0.4.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 (342) hide show
  1. package/README.md +22 -8
  2. package/dist/constants/common.constants.d.ts +15 -0
  3. package/dist/constants/common.constants.js +23 -0
  4. package/dist/constants/data-source.constants.d.ts +1 -0
  5. package/dist/constants/data-source.constants.js +1 -0
  6. package/dist/constants/economic.constants.d.ts +39 -0
  7. package/dist/constants/economic.constants.js +77 -0
  8. package/dist/constants/etf-covered-coins.constants.d.ts +1 -0
  9. package/dist/constants/etf-covered-coins.constants.js +9 -0
  10. package/dist/constants/feature-flags.constants.d.ts +60 -0
  11. package/dist/constants/feature-flags.constants.js +308 -0
  12. package/dist/constants/feature-limits.constants.d.ts +134 -0
  13. package/dist/constants/feature-limits.constants.js +155 -0
  14. package/dist/constants/marketCapabilities.constants.d.ts +87 -0
  15. package/dist/constants/marketCapabilities.constants.js +213 -0
  16. package/dist/constants/option-venues.constants.d.ts +100 -0
  17. package/dist/constants/option-venues.constants.js +167 -0
  18. package/dist/constants/overlay-data.constants.d.ts +53 -0
  19. package/dist/constants/overlay-data.constants.js +80 -0
  20. package/dist/constants/pane-grid.constants.d.ts +15 -0
  21. package/dist/constants/pane-grid.constants.js +17 -0
  22. package/dist/constants/scriptEditor/builtin-script-snippets.d.ts +133 -0
  23. package/dist/constants/scriptEditor/builtin-script-snippets.js +451 -0
  24. package/dist/constants/venue-presets.constants.d.ts +10 -0
  25. package/dist/constants/venue-presets.constants.js +22 -0
  26. package/dist/enums/chart.enum.d.ts +68 -0
  27. package/dist/enums/chart.enum.js +70 -0
  28. package/dist/helpers/data.helpers.d.ts +2 -0
  29. package/dist/helpers/data.helpers.js +14 -0
  30. package/dist/host-env.d.ts +163 -5
  31. package/dist/host-ports.types.d.ts +431 -0
  32. package/dist/host-ports.types.js +1 -0
  33. package/dist/index.d.ts +138 -0
  34. package/dist/index.js +138 -0
  35. package/dist/indicators/controls/technical-script/technical-script-input-rendering.d.ts +86 -0
  36. package/dist/indicators/controls/technical-script/technical-script-input-rendering.js +179 -0
  37. package/dist/interfaces/asset-venue.interface.d.ts +91 -0
  38. package/dist/interfaces/asset-venue.interface.js +1 -0
  39. package/dist/interfaces/cancel-reason.interface.d.ts +24 -0
  40. package/dist/interfaces/cancel-reason.interface.js +2 -0
  41. package/dist/interfaces/catalog-display.interface.d.ts +3 -0
  42. package/dist/interfaces/catalog-display.interface.js +1 -0
  43. package/dist/interfaces/cme-realtime.interface.d.ts +251 -0
  44. package/dist/interfaces/cme-realtime.interface.js +46 -0
  45. package/dist/interfaces/feed.interface.d.ts +80 -0
  46. package/dist/interfaces/feed.interface.js +7 -0
  47. package/dist/interfaces/market-kind.interface.d.ts +8 -0
  48. package/dist/interfaces/market-kind.interface.js +1 -0
  49. package/dist/interfaces/opra-realtime.interface.d.ts +224 -0
  50. package/dist/interfaces/opra-realtime.interface.js +105 -0
  51. package/dist/interfaces/option-instrument.interface.d.ts +32 -0
  52. package/dist/interfaces/option-instrument.interface.js +1 -0
  53. package/dist/interfaces/options-chain-scope.interface.d.ts +29 -0
  54. package/dist/interfaces/options-chain-scope.interface.js +7 -0
  55. package/dist/interfaces/prediction-market.interface.d.ts +88 -0
  56. package/dist/interfaces/prediction-market.interface.js +8 -0
  57. package/dist/interfaces/wrun-runtime.interface.d.ts +5 -0
  58. package/dist/kscript-data/controls/live-trades-merge.util.d.ts +185 -0
  59. package/dist/kscript-data/controls/live-trades-merge.util.js +357 -0
  60. package/dist/settings-templates/frvp-fields.d.ts +27 -0
  61. package/dist/settings-templates/frvp-fields.js +108 -0
  62. package/dist/settings-templates/index.d.ts +119 -0
  63. package/dist/settings-templates/index.js +442 -0
  64. package/dist/settings-templates/indicator-fields.d.ts +56 -0
  65. package/dist/settings-templates/indicator-fields.js +793 -0
  66. package/dist/settings-templates/tool-rules.d.ts +59 -0
  67. package/dist/settings-templates/tool-rules.js +49 -0
  68. package/dist/settings-templates/tool-tables.generated.d.ts +2 -0
  69. package/dist/settings-templates/tool-tables.generated.js +1668 -0
  70. package/dist/utility/blk-market.util.d.ts +5 -0
  71. package/dist/utility/blk-market.util.js +12 -0
  72. package/dist/utility/chart/chart-load-phase.util.d.ts +32 -0
  73. package/dist/utility/chart/chart-load-phase.util.js +78 -0
  74. package/dist/utility/chart/cme-cache-context.util.d.ts +108 -0
  75. package/dist/utility/chart/cme-cache-context.util.js +166 -0
  76. package/dist/utility/chart/cme-session-bucket.util.d.ts +82 -0
  77. package/dist/utility/chart/cme-session-bucket.util.js +343 -0
  78. package/dist/utility/chart/cme-trade-calendar.util.d.ts +26 -0
  79. package/dist/utility/chart/cme-trade-calendar.util.js +147 -0
  80. package/dist/utility/chart/continuous-contracts.util.d.ts +138 -0
  81. package/dist/utility/chart/continuous-contracts.util.js +374 -0
  82. package/dist/utility/chart/date-labelled-interval.leaf.d.ts +15 -0
  83. package/dist/utility/chart/date-labelled-interval.leaf.js +19 -0
  84. package/dist/utility/chart/feed-interval.util.d.ts +119 -0
  85. package/dist/utility/chart/feed-interval.util.js +321 -0
  86. package/dist/utility/chart/fetch-dedupe-policy.util.d.ts +110 -0
  87. package/dist/utility/chart/fetch-dedupe-policy.util.js +407 -0
  88. package/dist/utility/chart/footprint-band.util.d.ts +76 -0
  89. package/dist/utility/chart/footprint-band.util.js +205 -0
  90. package/dist/utility/chart/footprint-cell-identity.util.d.ts +82 -0
  91. package/dist/utility/chart/footprint-cell-identity.util.js +346 -0
  92. package/dist/utility/chart/formula-calendar.util.d.ts +27 -0
  93. package/dist/utility/chart/formula-calendar.util.js +59 -0
  94. package/dist/utility/chart/history-wall.util.d.ts +67 -0
  95. package/dist/utility/chart/history-wall.util.js +87 -0
  96. package/dist/utility/chart/index-mode.util.d.ts +66 -0
  97. package/dist/utility/chart/index-mode.util.js +360 -0
  98. package/dist/utility/chart/indicator-coverage-planner.util.d.ts +217 -0
  99. package/dist/utility/chart/indicator-coverage-planner.util.js +443 -0
  100. package/dist/utility/chart/indicator-coverage-state.util.d.ts +33 -0
  101. package/dist/utility/chart/indicator-coverage-state.util.js +110 -0
  102. package/dist/utility/chart/indicator-gap-detector.util.d.ts +127 -0
  103. package/dist/utility/chart/indicator-gap-detector.util.js +260 -0
  104. package/dist/utility/chart/indicator-gap-repair.util.d.ts +88 -0
  105. package/dist/utility/chart/indicator-gap-repair.util.js +177 -0
  106. package/dist/utility/chart/indicator-inflight-registry.util.d.ts +26 -0
  107. package/dist/utility/chart/indicator-inflight-registry.util.js +254 -0
  108. package/dist/utility/chart/indicator-run-interval.util.d.ts +130 -0
  109. package/dist/utility/chart/indicator-run-interval.util.js +268 -0
  110. package/dist/utility/chart/interval-registry.util.d.ts +23 -0
  111. package/dist/utility/chart/interval-registry.util.js +83 -0
  112. package/dist/utility/chart/kscript-main-grid-stages.util.d.ts +21 -0
  113. package/dist/utility/chart/kscript-main-grid-stages.util.js +332 -0
  114. package/dist/utility/chart/legacy-exchange.leaf.d.ts +11 -0
  115. package/dist/utility/chart/legacy-exchange.leaf.js +43 -0
  116. package/dist/utility/chart/live-bucket.util.d.ts +66 -0
  117. package/dist/utility/chart/live-bucket.util.js +165 -0
  118. package/dist/utility/chart/market-session-schedule.util.d.ts +91 -0
  119. package/dist/utility/chart/market-session-schedule.util.js +337 -0
  120. package/dist/utility/chart/marketKind.util.d.ts +181 -0
  121. package/dist/utility/chart/marketKind.util.js +371 -0
  122. package/dist/utility/chart/opra-read-access.leaf.d.ts +26 -0
  123. package/dist/utility/chart/opra-read-access.leaf.js +25 -0
  124. package/dist/utility/chart/prediction-identity.util.d.ts +159 -0
  125. package/dist/utility/chart/prediction-identity.util.js +236 -0
  126. package/dist/utility/chart/rth-session.util.d.ts +352 -0
  127. package/dist/utility/chart/rth-session.util.js +926 -0
  128. package/dist/utility/chart/titan-constants.pin.d.ts +43 -0
  129. package/dist/utility/chart/titan-constants.pin.js +50 -0
  130. package/dist/utility/chart/us-equities-session.util.d.ts +127 -0
  131. package/dist/utility/chart/us-equities-session.util.js +251 -0
  132. package/dist/utility/chart/window-geometry.leaf.d.ts +119 -0
  133. package/dist/utility/chart/window-geometry.leaf.js +391 -0
  134. package/dist/utility/chart/window-owner.leaf.d.ts +19 -0
  135. package/dist/utility/chart/window-owner.leaf.js +24 -0
  136. package/dist/utility/chart/wrun-bar-session-facts.util.d.ts +100 -0
  137. package/dist/utility/chart/wrun-bar-session-facts.util.js +354 -0
  138. package/dist/utility/chart/wrun-wire-ref.util.d.ts +23 -0
  139. package/dist/utility/chart/wrun-wire-ref.util.js +16 -0
  140. package/dist/utility/common/safe-math-eval.d.ts +18 -0
  141. package/dist/utility/common/safe-math-eval.js +160 -0
  142. package/dist/utility/common/time.util.d.ts +134 -0
  143. package/dist/utility/common/time.util.js +428 -0
  144. package/dist/utility/common/transformations.util.d.ts +126 -0
  145. package/dist/utility/common/transformations.util.js +711 -0
  146. package/dist/utility/common/visible-timeout.util.d.ts +17 -0
  147. package/dist/utility/common/visible-timeout.util.js +75 -0
  148. package/dist/utility/exchange-normalization.util.d.ts +8 -0
  149. package/dist/utility/exchange-normalization.util.js +32 -0
  150. package/dist/utility/html-escape.leaf.d.ts +11 -0
  151. package/dist/utility/html-escape.leaf.js +20 -0
  152. package/dist/utility/intl-locale.util.d.ts +2 -0
  153. package/dist/utility/intl-locale.util.js +28 -0
  154. package/dist/utility/number-format.util.d.ts +14 -1
  155. package/dist/utility/number-format.util.js +50 -19
  156. package/dist/utility/options/option-symbol.util.d.ts +28 -0
  157. package/dist/utility/options/option-symbol.util.js +176 -0
  158. package/dist/utility/options/option-trade-units.util.d.ts +190 -0
  159. package/dist/utility/options/option-trade-units.util.js +283 -0
  160. package/dist/utility/options/option-venue.util.d.ts +75 -0
  161. package/dist/utility/options/option-venue.util.js +85 -0
  162. package/dist/utility/pool-symbol.leaf.d.ts +34 -0
  163. package/dist/utility/pool-symbol.leaf.js +95 -0
  164. package/dist/utility/scriptEditor/wrun-runtime-diagnostics.leaf.d.ts +109 -0
  165. package/dist/utility/scriptEditor/wrun-runtime-diagnostics.leaf.js +302 -0
  166. package/dist/utility/symbol-selection/contract-expiry.util.d.ts +39 -0
  167. package/dist/utility/symbol-selection/contract-expiry.util.js +111 -0
  168. package/dist/utility/v2/gate-plane.util.d.ts +58 -0
  169. package/dist/utility/v2/gate-plane.util.js +99 -0
  170. package/dist/utility/v2/gate-session-latch.util.d.ts +22 -0
  171. package/dist/utility/v2/gate-session-latch.util.js +34 -0
  172. package/dist/utility/watchlist/import/tradingview-symbols.leaf.d.ts +76 -0
  173. package/dist/utility/watchlist/import/tradingview-symbols.leaf.js +221 -0
  174. package/dist/utility/wrun/sources/host-grid-landing.d.ts +15 -0
  175. package/dist/utility/wrun/sources/host-grid-landing.js +26 -0
  176. package/dist/utility/wrun/sources/lanes/bitfinex_funding.d.ts +27 -0
  177. package/dist/utility/wrun/sources/lanes/bitfinex_funding.js +85 -0
  178. package/dist/utility/wrun/sources/lanes/economic.d.ts +27 -0
  179. package/dist/utility/wrun/sources/lanes/economic.js +79 -0
  180. package/dist/utility/wrun/sources/lanes/etf_holdings.d.ts +35 -0
  181. package/dist/utility/wrun/sources/lanes/etf_holdings.js +165 -0
  182. package/dist/utility/wrun/sources/lanes/etf_premium.d.ts +19 -0
  183. package/dist/utility/wrun/sources/lanes/etf_premium.js +114 -0
  184. package/dist/utility/wrun/sources/lanes/ethena_positions.d.ts +30 -0
  185. package/dist/utility/wrun/sources/lanes/ethena_positions.js +51 -0
  186. package/dist/utility/wrun/sources/lanes/index.d.ts +2 -0
  187. package/dist/utility/wrun/sources/lanes/index.js +32 -0
  188. package/dist/utility/wrun/sources/lanes/long_short_ratio.d.ts +17 -0
  189. package/dist/utility/wrun/sources/lanes/long_short_ratio.js +47 -0
  190. package/dist/utility/wrun/sources/lanes/option_daily.d.ts +58 -0
  191. package/dist/utility/wrun/sources/lanes/option_daily.js +111 -0
  192. package/dist/utility/wrun/sources/lanes/option_stats_10m.d.ts +27 -0
  193. package/dist/utility/wrun/sources/lanes/option_stats_10m.js +21 -0
  194. package/dist/utility/wrun/sources/lanes/options_flow.d.ts +50 -0
  195. package/dist/utility/wrun/sources/lanes/options_flow.js +155 -0
  196. package/dist/utility/wrun/sources/lanes/options_oi.d.ts +29 -0
  197. package/dist/utility/wrun/sources/lanes/options_oi.js +59 -0
  198. package/dist/utility/wrun/sources/lanes/options_volume.d.ts +38 -0
  199. package/dist/utility/wrun/sources/lanes/options_volume.js +63 -0
  200. package/dist/utility/wrun/sources/lanes/series.d.ts +67 -0
  201. package/dist/utility/wrun/sources/lanes/series.js +321 -0
  202. package/dist/utility/wrun/sources/lanes/token_supply.d.ts +30 -0
  203. package/dist/utility/wrun/sources/lanes/token_supply.js +145 -0
  204. package/dist/utility/wrun/sources/lanes/treasury_balance.d.ts +25 -0
  205. package/dist/utility/wrun/sources/lanes/treasury_balance.js +47 -0
  206. package/dist/utility/wrun/sources/lanes/volatility_index.d.ts +21 -0
  207. package/dist/utility/wrun/sources/lanes/volatility_index.js +11 -0
  208. package/dist/utility/wrun/sources/opra-option-lanes.util.d.ts +215 -0
  209. package/dist/utility/wrun/sources/opra-option-lanes.util.js +477 -0
  210. package/dist/utility/wrun/sources/registry.d.ts +21 -0
  211. package/dist/utility/wrun/sources/registry.js +237 -0
  212. package/dist/utility/wrun/sources/row-lane-registry.d.ts +28 -0
  213. package/dist/utility/wrun/sources/row-lane-registry.js +230 -0
  214. package/dist/utility/wrun/sources/row-lanes/index.d.ts +2 -0
  215. package/dist/utility/wrun/sources/row-lanes/index.js +12 -0
  216. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.d.ts +2 -0
  217. package/dist/utility/wrun/sources/row-lanes/option_contract_flow.js +38 -0
  218. package/dist/utility/wrun/sources/row-lanes/option_contract_state.d.ts +55 -0
  219. package/dist/utility/wrun/sources/row-lanes/option_contract_state.js +126 -0
  220. package/dist/utility/wrun/sources/row-lanes/option_prints.d.ts +4 -0
  221. package/dist/utility/wrun/sources/row-lanes/option_prints.js +191 -0
  222. package/dist/utility/wrun/sources/row-lanes/option_strikes.d.ts +62 -0
  223. package/dist/utility/wrun/sources/row-lanes/option_strikes.js +147 -0
  224. package/dist/utility/wrun/sources/row-lanes/option_surface.d.ts +70 -0
  225. package/dist/utility/wrun/sources/row-lanes/option_surface.js +144 -0
  226. package/dist/utility/wrun/sources/wrun-poll-lane.types.d.ts +309 -0
  227. package/dist/utility/wrun/sources/wrun-poll-lane.types.js +26 -0
  228. package/dist/utility/wrun/sources/wrun-poll-lanes.util.d.ts +350 -0
  229. package/dist/utility/wrun/sources/wrun-poll-lanes.util.js +576 -0
  230. package/dist/utility/wrun/sources/wrun-row-lane.types.d.ts +275 -0
  231. package/dist/utility/wrun/sources/wrun-row-lane.types.js +16 -0
  232. package/dist/utility/wrun/sources/wrun-row-lanes.util.d.ts +207 -0
  233. package/dist/utility/wrun/sources/wrun-row-lanes.util.js +450 -0
  234. package/dist/utility/wrun/wrun-browser-sources.leaf.d.ts +28 -0
  235. package/dist/utility/wrun/wrun-browser-sources.leaf.js +66 -0
  236. package/dist/utility/wrun/wrun-cloud-record.util.d.ts +65 -0
  237. package/dist/utility/wrun/wrun-cloud-record.util.js +121 -0
  238. package/dist/utility/wrun/wrun-daily-lane.util.d.ts +95 -0
  239. package/dist/utility/wrun/wrun-daily-lane.util.js +297 -0
  240. package/dist/utility/wrun/wrun-deadline.util.d.ts +52 -0
  241. package/dist/utility/wrun/wrun-deadline.util.js +82 -0
  242. package/dist/utility/wrun/wrun-etf-flow-lane.util.d.ts +94 -0
  243. package/dist/utility/wrun/wrun-etf-flow-lane.util.js +224 -0
  244. package/dist/utility/wrun/wrun-etf-funds.util.d.ts +82 -0
  245. package/dist/utility/wrun/wrun-etf-funds.util.js +242 -0
  246. package/dist/utility/wrun/wrun-frames.d.ts +20 -1
  247. package/dist/utility/wrun/wrun-frames.js +103 -49
  248. package/dist/utility/wrun/wrun-hosted-wire-caps.d.ts +2 -2
  249. package/dist/utility/wrun/wrun-hosted-wire-caps.js +27 -0
  250. package/dist/utility/wrun/wrun-lane-refusal.leaf.d.ts +22 -0
  251. package/dist/utility/wrun/wrun-lane-refusal.leaf.js +32 -0
  252. package/dist/utility/wrun/wrun-lane-warmup.util.d.ts +18 -0
  253. package/dist/utility/wrun/wrun-lane-warmup.util.js +112 -0
  254. package/dist/utility/wrun/wrun-leg-close.util.d.ts +57 -0
  255. package/dist/utility/wrun/wrun-leg-close.util.js +187 -0
  256. package/dist/utility/wrun/wrun-leg-fetch.util.d.ts +144 -0
  257. package/dist/utility/wrun/wrun-leg-fetch.util.js +212 -0
  258. package/dist/utility/wrun/wrun-leg-stream-classes.d.ts +73 -0
  259. package/dist/utility/wrun/wrun-leg-stream-classes.js +86 -0
  260. package/dist/utility/wrun/wrun-levels-child.util.d.ts +101 -6
  261. package/dist/utility/wrun/wrun-levels-child.util.js +335 -157
  262. package/dist/utility/wrun/wrun-memory-clamp.util.d.ts +33 -0
  263. package/dist/utility/wrun/wrun-memory-clamp.util.js +146 -0
  264. package/dist/utility/wrun/wrun-odds-template-market.util.d.ts +51 -0
  265. package/dist/utility/wrun/wrun-odds-template-market.util.js +251 -0
  266. package/dist/utility/wrun/wrun-opra-flow.leaf.d.ts +65 -0
  267. package/dist/utility/wrun/wrun-opra-flow.leaf.js +94 -0
  268. package/dist/utility/wrun/wrun-opra-lane.util.d.ts +47 -0
  269. package/dist/utility/wrun/wrun-opra-lane.util.js +58 -0
  270. package/dist/utility/wrun/wrun-opra-stats.leaf.d.ts +49 -0
  271. package/dist/utility/wrun/wrun-opra-stats.leaf.js +115 -0
  272. package/dist/utility/wrun/wrun-opra-underlying.util.d.ts +12 -0
  273. package/dist/utility/wrun/wrun-opra-underlying.util.js +1 -0
  274. package/dist/utility/wrun/wrun-option-contract-flow.util.d.ts +142 -0
  275. package/dist/utility/wrun/wrun-option-contract-flow.util.js +451 -0
  276. package/dist/utility/wrun/wrun-option-knobs.util.d.ts +43 -0
  277. package/dist/utility/wrun/wrun-option-knobs.util.js +81 -0
  278. package/dist/utility/wrun/wrun-option-prints.util.d.ts +144 -0
  279. package/dist/utility/wrun/wrun-option-prints.util.js +356 -0
  280. package/dist/utility/wrun/wrun-option-summary-lane.util.d.ts +102 -0
  281. package/dist/utility/wrun/wrun-option-summary-lane.util.js +143 -0
  282. package/dist/utility/wrun/wrun-options-chain.util.d.ts +308 -0
  283. package/dist/utility/wrun/wrun-options-chain.util.js +502 -0
  284. package/dist/utility/wrun/wrun-overlay-identity.util.d.ts +9 -4
  285. package/dist/utility/wrun/wrun-overlay-identity.util.js +16 -6
  286. package/dist/utility/wrun/wrun-panel-mount.lazy.d.ts +10 -0
  287. package/dist/utility/wrun/wrun-panel-mount.lazy.js +68 -0
  288. package/dist/utility/wrun/wrun-panel-mount.util.d.ts +377 -0
  289. package/dist/utility/wrun/wrun-panel-mount.util.js +2251 -0
  290. package/dist/utility/wrun/wrun-param-map.util.d.ts +298 -0
  291. package/dist/utility/wrun/wrun-param-map.util.js +581 -0
  292. package/dist/utility/wrun/wrun-pause-dim.util.d.ts +52 -0
  293. package/dist/utility/wrun/wrun-pause-dim.util.js +153 -0
  294. package/dist/utility/wrun/wrun-pin-spelling.util.d.ts +149 -0
  295. package/dist/utility/wrun/wrun-pin-spelling.util.js +523 -0
  296. package/dist/utility/wrun/wrun-pin-venues.util.d.ts +116 -0
  297. package/dist/utility/wrun/wrun-pin-venues.util.js +320 -0
  298. package/dist/utility/wrun/wrun-pinned-interval.util.d.ts +20 -0
  299. package/dist/utility/wrun/wrun-pinned-interval.util.js +47 -0
  300. package/dist/utility/wrun/wrun-plot-gate.types.d.ts +23 -0
  301. package/dist/utility/wrun/wrun-plot-gate.types.js +7 -0
  302. package/dist/utility/wrun/wrun-present-bits.util.d.ts +37 -0
  303. package/dist/utility/wrun/wrun-present-bits.util.js +73 -0
  304. package/dist/utility/wrun/wrun-protocol-pending.util.d.ts +33 -0
  305. package/dist/utility/wrun/wrun-protocol-pending.util.js +57 -0
  306. package/dist/utility/wrun/wrun-refusal.util.d.ts +41 -1
  307. package/dist/utility/wrun/wrun-refusal.util.js +69 -2
  308. package/dist/utility/wrun/wrun-registry-errors.util.d.ts +1 -14
  309. package/dist/utility/wrun/wrun-registry-errors.util.js +0 -16
  310. package/dist/utility/wrun/wrun-row-source.d.ts +158 -0
  311. package/dist/utility/wrun/wrun-row-source.js +75 -0
  312. package/dist/utility/wrun/wrun-run-health.util.d.ts +155 -0
  313. package/dist/utility/wrun/wrun-run-health.util.js +273 -0
  314. package/dist/utility/wrun/wrun-run-interval-projection.types.d.ts +14 -0
  315. package/dist/utility/wrun/wrun-run-interval-projection.types.js +1 -0
  316. package/dist/utility/wrun/wrun-socket-row-source.d.ts +439 -0
  317. package/dist/utility/wrun/wrun-socket-row-source.js +1689 -0
  318. package/dist/utility/wrun/wrun-socket-session-losses.util.d.ts +18 -0
  319. package/dist/utility/wrun/wrun-socket-session-losses.util.js +25 -0
  320. package/dist/utility/wrun/wrun-source-rows.util.d.ts +911 -0
  321. package/dist/utility/wrun/wrun-source-rows.util.js +2597 -0
  322. package/dist/utility/wrun/wrun-tape-source.util.d.ts +82 -0
  323. package/dist/utility/wrun/wrun-tape-source.util.js +151 -0
  324. package/dist/utility/wrun/wrun-tier-grid.util.d.ts +137 -0
  325. package/dist/utility/wrun/wrun-tier-grid.util.js +279 -0
  326. package/dist/utility/wrun/wrun-trades-lane.util.d.ts +52 -0
  327. package/dist/utility/wrun/wrun-trades-lane.util.js +58 -0
  328. package/dist/utility/wrun/wrun-volume-profile-lane.util.d.ts +41 -0
  329. package/dist/utility/wrun/wrun-volume-profile-lane.util.js +66 -0
  330. package/dist/utility/wrun-display-name.util.d.ts +33 -0
  331. package/dist/utility/wrun-display-name.util.js +64 -0
  332. package/dist/workers/constants/kscript-transport-codes.d.ts +15 -0
  333. package/dist/workers/constants/kscript-transport-codes.js +15 -0
  334. package/dist/workers/constants/socket-slots.d.ts +574 -0
  335. package/dist/workers/constants/socket-slots.js +539 -0
  336. package/dist/workers/utils/number.worker.util.d.ts +5 -0
  337. package/dist/workers/utils/number.worker.util.js +10 -0
  338. package/dist/workers/utils/time.worker.util.d.ts +12 -0
  339. package/dist/workers/utils/time.worker.util.js +24 -0
  340. package/dist/workers/utils/volume-profile.worker.util.d.ts +200 -0
  341. package/dist/workers/utils/volume-profile.worker.util.js +631 -0
  342. package/package.json +10 -4
@@ -0,0 +1,2251 @@
1
+ /**
2
+ * The child-overlay mount of a browser-run Indicator (wrun): every panel,
3
+ * docked level, inset, price canvas (heatmap, profile, matrix) and lower pane
4
+ * a run result declares becomes an engine overlay owned by the parent
5
+ * Indicator, mounted here and torn down with it.
6
+ *
7
+ * The mount door (WRUN-STYLE 2.5, 3.5.4): colour WORDS ride the run result
8
+ * unresolved (`theme.*` tokens included) and resolve here against the chart's
9
+ * palette (`wrunColorThemeOf`), so a theme switch or a display-timezone
10
+ * change re-resolves every mounted child without a rerun
11
+ * (`retranslateWrunChildOverlays`, X13). Each mounted child keeps its last
12
+ * unresolved input beside its engine config for exactly that.
13
+ *
14
+ * Panels (g1): the frame translates through om-panel.util with the context
15
+ * this file builds (theme, the chart's price digits, the display timezone);
16
+ * the pane's name, caption, maximize button, stats row, formatter hooks and
17
+ * height share are set here (SC08 SC09 SC10 SC17 SC37); `place: "side"`
18
+ * mounts below the chart like every panel (the window is a side panel's
19
+ * opened form, Kyle 2026-10-04; the engine's side strip stays for `dock:
20
+ * "side"` canvases). Docked levels (g2) take
21
+ * their settings and rows from wrun-levels-child.util's mount helpers and
22
+ * keep their hover rows under the child id (DL-hover). Price canvases (g6)
23
+ * take their config from wrun-canvases.util: heatmap and profile children
24
+ * are row-backed on ticks (the newest row through `liveUpdateData`, every
25
+ * row since the bar they last painted on a tick that added bars; a
26
+ * windowed run's heatmap merges its rows inside the run's history window,
27
+ * a prefix run's through a landing prepared ahead and committed with no
28
+ * await: prepareWrunHeatmapWindowLanding),
29
+ * matrices frame-backed like levels; a heatmap takes the viewer's
30
+ * Sensitivity at this door (`rescaleWrunHeatmapChildren` re-picks the mounted
31
+ * bounds with no run). Batched marks (WRUN-BATCHED-MARKS: marks, spans and
32
+ * rays children) are row-backed like heatmaps: a tick merges every row it
33
+ * re-evaluated, row by row; a windowed run lands inside its window; the engine
34
+ * gate refuses a kind the chart cannot draw by name; their own cell budget
35
+ * charges every seam (wrun-batched-marks.util). The series child (the lower pane, or a
36
+ * pane pinned over the candles, g5 OT08 OT20 OT24) rides the shared kScript
37
+ * adapter and prints its legend through the legend helpers (OT27 OT28 OT29
38
+ * OT32). Every child's eye follows the parent's, except where the reader
39
+ * moved a child's own eye (an inset's): that flip stands (syncChildVisibility).
40
+ */
41
+ import { wrunChartHostEnv } from '../../host-env.js';
42
+ import { isDateLabelledBarInterval } from '../chart/date-labelled-interval.leaf.js';
43
+ import { KSCRIPT_LEGEND_VALUE_INK, kScriptLegendEntries, kScriptLegendLineFormat, kScriptLegendLineFormatOptions, kScriptLegendLines, kScriptLegendLineSwatchAt, kScriptLegendLineValueAt, kScriptLegendSlotCells, padKScriptLegendSlots, } from '../chart/kscript-legend-entries.util.js';
44
+ import { panelGridHeight, refreshPanelOverlayInPlace, samePanelPane, translatePanelToEngine, } from '../chart/om-panel.util.js';
45
+ import { isWrunWindowOwner } from '../chart/window-owner.leaf.js';
46
+ import { planWindowWeights, reconcileWindowOwnerGeometry, savedWindowSplit, tableRowCountOf, } from '../chart/window-geometry.leaf.js';
47
+ import { wrunLegendName } from '../chart/wrun-legend-name.util.js';
48
+ import { wrunResultLegendColors, wrunSeriesChildId, } from '../chart/wrun-run-result.util.js';
49
+ import { escapeHtml } from '../html-escape.leaf.js';
50
+ import { budgetWrunBatchedRetained, budgetWrunBatchedRows, commitWrunBatchedPlan, currentWrunBatchedPlan, forgetWrunBatchedCells, isWrunBatchedMarksKind, noteWrunBatchedRowsCut, planWrunBatchedMerged, restoreWrunBatchedLedger, snapshotWrunBatchedLedger, wrunBatchedChargeOf, wrunBatchedChildConfig, wrunBatchedChildrenOverShare, wrunBatchedSiblingsToRebalance, } from './wrun-batched-marks.util.js';
51
+ import { forgetWrunCanvasReadout, keepWrunHeatmapScaleSample, rememberWrunCanvasReadout, wrunCanvasChildConfig, wrunHeatmapSensitivityBounds, wrunPlainCanvasRow, } from './wrun-canvases.util.js';
52
+ import { wrunChildHiddenRowKey } from './wrun-child-overlay-id.util.js';
53
+ import { wrunHeatmapSensitivitySetting, wrunHeatmapSensitivityValue } from './wrun-color-settings.util.js';
54
+ import { budgetWrunHeatmapRetained, budgetWrunHeatmapRows, commitWrunHeatmapPlan, currentWrunHeatmapPlan, planWrunHeatmapMerged, restoreWrunHeatmapLedger, snapshotWrunHeatmapLedger, wrunHeatmapCellLayoutOf, wrunHeatmapChildrenOverShare, wrunHeatmapSiblingsToRebalance, } from './wrun-heatmap-cell-budget.util.js';
55
+ import { wrunChildOverlayParentId } from './wrun-child-overlay-id.util.js';
56
+ import { forgetWrunLevelsHoverRows, rememberWrunLevelsHoverRows, wrunLevelsChildId, wrunLevelsMountData, wrunLevelsMountSettings, } from './wrun-levels-child.util.js';
57
+ import { wrunPaneChildMountSettings } from './wrun-output-style.util.js';
58
+ import { formatWrunLegendValue, WRUN_PANE_DEFAULT_DIGITS, wrunBuiltinTwin, wrunBuiltinTwinYLabel, wrunPaneYLabel, } from './wrun-pane-format.util.js';
59
+ import { wrunPanelChrome } from './wrun-panel-style.util.js';
60
+ import { reapplyWrunPauseDim } from './wrun-pause-dim.util.js';
61
+ import { resolveWrunColorWord, wrunColorThemeOf } from './wrun-style-words.util.js';
62
+ import { bindWrunPanelMountRuntime } from './wrun-panel-mount.lazy.js';
63
+ const chartChildren = new WeakMap();
64
+ /** The legend controls a child pane's own row hides: the eye (the parent's
65
+ * eye governs its panes, syncChildVisibility) and the pane moves, which
66
+ * belong to the parent. The gear and the close button stay, so the row
67
+ * offers what the owner's row does: the store routes a child id's settings
68
+ * to the owning Indicator's dialog (`openIndicatorSettings`, the gear, a
69
+ * double-click and the "..." menu's Settings alike) and its removal to the
70
+ * owning Indicator (wrun-child-overlay-id.util, `wrunChildOverlayParentId`).
71
+ * QA 200: Absorption's lower pane had no gear and no Settings in its menu. */
72
+ const CHILD_LEGEND_CONTROLS = {
73
+ hideVisibilityBtn: true,
74
+ hideMergePaneBtn: true,
75
+ hidePinToChartBtn: true,
76
+ };
77
+ /**
78
+ * Every child kind and its legend row, decided here once (the legend guard in
79
+ * the mount spec mounts one of each kind listed). The `own` kinds are the
80
+ * allowlist that keeps a row by design: a panel (a side panel too) and a
81
+ * series pane own a pane, a title and controls, and an inset's row carries its
82
+ * latest value. Every other kind folds into the parent's row: `childConfig`
83
+ * sends it `hideLegend: true`, so the engine builds no row, the parent's row
84
+ * carries the Indicator and the parent's eye still governs the child
85
+ * (`syncChildVisibility`). A kind missing here gets no row either, and the
86
+ * typecheck refuses the table until it is decided. Each kind used to opt out
87
+ * on its own, and the levels child that forgot printed a second row titled
88
+ * "gex_by_strike".
89
+ */
90
+ export const WRUN_CHILD_LEGEND_ROW = {
91
+ panel: 'own',
92
+ series: 'own',
93
+ inset: 'own',
94
+ levels: 'parent',
95
+ heatmap: 'parent',
96
+ profile: 'parent',
97
+ matrix: 'parent',
98
+ marks: 'parent',
99
+ spans: 'parent',
100
+ rays: 'parent',
101
+ };
102
+ /** The pane height panels and the series lower pane share below the chart. */
103
+ const CHILD_PANE_GRID_HEIGHT = 0.22;
104
+ /** The pane words a series child carries at the meta level (OT24: the
105
+ * pinned onchart flags), apart from its settings. */
106
+ const SERIES_META_KEYS = new Set([
107
+ 'isPinnedToChart',
108
+ 'showIndependentYAxis',
109
+ 'isIndependentSubsetRange',
110
+ 'hidePriceScale',
111
+ 'shouldAdjustMainGridRange',
112
+ ]);
113
+ /** The child kinds a tick carries: insets and the lower pane take the tick's
114
+ * rows in place, heatmaps and profiles the newest row, batched marks every
115
+ * row the tick re-evaluated; panels, levels and matrices are frame-backed
116
+ * and wait for a tick that carries frames. */
117
+ const ROW_BACKED_KINDS = new Set([
118
+ 'inset',
119
+ 'series',
120
+ 'heatmap',
121
+ 'profile',
122
+ 'marks',
123
+ 'spans',
124
+ 'rays',
125
+ ]);
126
+ function overlayPresent(tc, id) {
127
+ return tc.metadata.some((meta) => meta.id === id);
128
+ }
129
+ /** The price canvases (g6: heatmap, profile and matrix children) and the
130
+ * batched marks drawn over the price pane like them (marks, spans, rays):
131
+ * no price marker, a readout registered when the config is built. */
132
+ function isCanvasChild(child) {
133
+ return child.kind === 'heatmap' || child.kind === 'profile' || child.kind === 'matrix' || isBatchedChild(child);
134
+ }
135
+ /** A batched child (WRUN-BATCHED-MARKS): marks, spans or rays. */
136
+ function isBatchedChild(child) {
137
+ return isWrunBatchedMarksKind(child.kind);
138
+ }
139
+ /** The engine keeps the config's `settings` object as the meta's and rewrites
140
+ * `gridHeight` to the fraction it carved, so the mounted set keeps the intent
141
+ * and the engine gets its own copy: the next run's same-pane check and the
142
+ * in-place settings diff both read what was asked, never what was carved. */
143
+ function addChild(tc, config) {
144
+ wrunChartHostEnv().chart.registerLoadedPacks(tc);
145
+ tc.addOverlay({ ...config, settings: { ...config.settings } });
146
+ }
147
+ /** Mount a child and register what the hover surfaces read off it: a levels
148
+ * child's hover rows (DL-hover, colour words resolved against the palette),
149
+ * or none when the child keeps none (a replacement that turned hover off
150
+ * leaves no rows of its predecessor behind); a canvas readout is
151
+ * registered by its config builder. */
152
+ function installChild(tc, child, theme) {
153
+ addChild(tc, child.config);
154
+ if (child.input.kind !== 'levels')
155
+ return;
156
+ if (child.input.hover !== undefined)
157
+ rememberWrunLevelsHoverRows(child.config.id, child.input.hover, theme);
158
+ else
159
+ forgetWrunLevelsHoverRows(child.config.id);
160
+ }
161
+ function removeChild(tc, id) {
162
+ if (overlayPresent(tc, id))
163
+ tc.removeOverlay(id);
164
+ }
165
+ /** Drop what a child registered for the hover surfaces (the symmetric
166
+ * retract of installChild and the canvas config builder). */
167
+ function forgetChildExtras(id, kind) {
168
+ if (kind === 'levels')
169
+ forgetWrunLevelsHoverRows(id);
170
+ if (kind === 'heatmap' || kind === 'profile' || kind === 'matrix' || isWrunBatchedMarksKind(kind)) {
171
+ forgetWrunCanvasReadout(id);
172
+ }
173
+ }
174
+ /** A canvas config registers its hover readout when it is BUILT, before the
175
+ * pack preflight settles and before the engine took the child: after a run
176
+ * that failed part way, point the registry back at what is mounted (the
177
+ * readout of every mounted canvas, none for a built one that never
178
+ * mounted). A batched child's readout carries its record text on the input
179
+ * (wrun-batched-marks.util), so this restores its hover card whole. */
180
+ function syncCanvasReadouts(mounted, built) {
181
+ for (const { input, config } of built) {
182
+ if (isCanvasChild(input) && !mounted.has(config.id))
183
+ forgetWrunCanvasReadout(config.id);
184
+ }
185
+ for (const [id, { input }] of mounted) {
186
+ if (!isCanvasChild(input))
187
+ continue;
188
+ if (input.readout !== undefined)
189
+ rememberWrunCanvasReadout(id, input.readout);
190
+ else
191
+ forgetWrunCanvasReadout(id);
192
+ }
193
+ }
194
+ /** Remove a child from the chart; its registrations go with it unless the
195
+ * same id is about to be mounted again (a replaced child keeps the rows and
196
+ * readout its new config already registered). */
197
+ function retireChild(tc, id, kind, replaced) {
198
+ if (!tc.isDestroyed)
199
+ removeChild(tc, id);
200
+ if (replaced)
201
+ return;
202
+ forgetChildExtras(id, kind);
203
+ // A batched child's cells leave its Indicator's ledger with it (the "Cells capped" row follows).
204
+ const overlayId = isWrunBatchedMarksKind(kind) ? wrunChildOverlayParentId(id) : null;
205
+ if (overlayId !== null)
206
+ forgetWrunBatchedCells(tc, overlayId, id);
207
+ }
208
+ /** The child pane's close button removes the OWNING Indicator (the store
209
+ * maps the child id to its parent), so its tooltip names the Indicator. */
210
+ function childLegendControls(parentName) {
211
+ return parentName ? { ...CHILD_LEGEND_CONTROLS, legendRemoveLabel: `Remove ${parentName}` } : CHILD_LEGEND_CONTROLS;
212
+ }
213
+ /** Every colour word in a settings bag (strings and string lists) resolved
214
+ * against the palette; anything that is not a token passes unchanged. */
215
+ function resolveSettingsColorWords(settings, theme) {
216
+ const resolved = {};
217
+ for (const [key, value] of Object.entries(settings)) {
218
+ if (typeof value === 'string')
219
+ resolved[key] = resolveWrunColorWord(value, theme);
220
+ else if (Array.isArray(value) && value.every((entry) => typeof entry === 'string')) {
221
+ resolved[key] = value.map((entry) => resolveWrunColorWord(entry, theme));
222
+ }
223
+ else
224
+ resolved[key] = value;
225
+ }
226
+ return resolved;
227
+ }
228
+ /** The chart's display timezone offset for the panel translation (SC37).
229
+ * A chart mounted before the user store exists (a bare test chart, a boot
230
+ * path) reads as UTC, the engine's own default. */
231
+ function displayTimezoneOffsetMs() {
232
+ try {
233
+ return wrunChartHostEnv().user.chartDisplayTimezoneOffsetMs();
234
+ }
235
+ catch {
236
+ return 0;
237
+ }
238
+ }
239
+ /** The user's theme name, the key of the TPO letter scheme a profile child
240
+ * without its own palette takes (PT-tpo, as the native TPO control reads
241
+ * it). A chart mounted before the user store exists reads the default
242
+ * scheme. */
243
+ function userThemeMode() {
244
+ try {
245
+ const mode = wrunChartHostEnv().user.themeMode();
246
+ return typeof mode === 'string' && mode !== '' ? mode : undefined;
247
+ }
248
+ catch {
249
+ return undefined;
250
+ }
251
+ }
252
+ /** A panel child's config (g1): the frame translated with the chart's
253
+ * theme, price digits and display timezone (SC08 SC16 SC37); the run's
254
+ * title and caption on the legend through escapeHtml (SC17); the maximize
255
+ * button and stats row (SC10); the declared height share (SC09); every
256
+ * panel below the chart at its carved height, `place: "side"` included (a
257
+ * side panel's right-side home is the window, never a strip that narrows
258
+ * the candles; `width_px` / `height_px` therefore size nothing here). */
259
+ function panelChildConfig(child, ctx) {
260
+ const translateContext = {
261
+ theme: ctx.theme,
262
+ ...(ctx.priceDigits !== undefined ? { priceDigits: ctx.priceDigits() } : {}),
263
+ timezoneOffsetMs: ctx.timezoneOffsetMs,
264
+ };
265
+ const translated = translatePanelToEngine(child.frame, translateContext);
266
+ const { panel, rows, chrome } = child.frame;
267
+ const caption = chrome?.caption;
268
+ const id = `${ctx.overlayId}::panel:${child.name}`;
269
+ // A table owns no value axis and a rich line (every chrome but box: the
270
+ // numeric curve, or grid / none on a time, category or stacked line) draws
271
+ // its own left axis (C4): neither pane echoes the chart's prices in its
272
+ // scale cell. A box line and every other kind keep it (every panel mounts
273
+ // below, `place: "side"` included).
274
+ const ownAxis = panel.kind === 'table' || (panel.kind === 'line' && wrunPanelChrome(panel) !== 'box');
275
+ return {
276
+ id,
277
+ name: escapeHtml(translated.name),
278
+ plot: translated.plot,
279
+ type: 'offchart',
280
+ interval: ctx.interval,
281
+ data: translated.rows,
282
+ ...(ownAxis ? { hidePriceScale: true } : {}),
283
+ ...translated.hooks,
284
+ settings: {
285
+ ...translated.settings,
286
+ ...childLegendControls(ctx.parentName),
287
+ // The pane this one lands right above (C6): a settings key the engine
288
+ // reads once at addOverlay, like keepAtBottom (alpha.1018 and up; an
289
+ // older engine, an anchor not mounted yet or an onchart one appends).
290
+ // A pane-layout key for the in-place refresh (PANEL_PANE_LAYOUT_KEYS),
291
+ // so a later run's anchor never churns a mounted pane.
292
+ ...(ctx.anchorPaneId !== undefined ? { insertBeforePaneId: ctx.anchorPaneId } : {}),
293
+ ...(panel.maximize === true ? { showMaximizeBtn: true } : {}),
294
+ ...(panel.stats_row === true ? { showStatsRow: true } : {}),
295
+ // The function form skips the engine's $token expansion of a title.
296
+ ...(caption !== undefined ? { customTitle: () => ` · ${escapeHtml(caption)}` } : {}),
297
+ // A pane below the chart takes the declared share, else the table's row
298
+ // height or the shared weight; on a window the plan's weight.
299
+ gridHeight: ctx.planned?.get(id) ?? panelGridHeight(panel, rows.length, ctx.chartHeightPx),
300
+ },
301
+ };
302
+ }
303
+ /** The lower pane (or a pane pinned over the candles, OT24): an offchart
304
+ * kScript container the shared adapter fills from the child's result
305
+ * (nested plots, styled rows, drawings, the engine-native legend), mounted
306
+ * ONCE and re-integrated in place on every run, so its pane, scale and
307
+ * legend survive ticks and reruns. */
308
+ function seriesChildConfig(child, ctx) {
309
+ const { tc, overlayId } = ctx;
310
+ const id = wrunSeriesChildId(overlayId, child.name);
311
+ // The pane's legend palette (its collapsed chip): its own result's
312
+ // legend-line colours, the way the parent mounts
313
+ // with the sheet's (wrunSheetOverlayPalette); empty mounts none.
314
+ const palette = wrunResultLegendColors(child.result.outputs);
315
+ const parentSettings = tc.metadata.find((meta) => meta.id === overlayId)?.settings;
316
+ // A proven twin's lower pane (the parent's `builtinTwinOf`) reads like
317
+ // its built-in: the built-in's axis label (none but a volume-based one's)
318
+ // and its legend rule, never the wrun pane's.
319
+ const builtinTwin = wrunBuiltinTwin(parentSettings);
320
+ const getYLabel = builtinTwin === undefined ? wrunPaneYLabel(() => tc, id) : wrunBuiltinTwinYLabel(builtinTwin);
321
+ // The pane words (OT20 OT24): the pinned onchart flags live on the meta,
322
+ // the height share in the settings.
323
+ const paneWords = wrunPaneChildMountSettings(child.result.pane);
324
+ const metaWords = {};
325
+ const settingWords = {};
326
+ for (const [key, value] of Object.entries(paneWords)) {
327
+ if (SERIES_META_KEYS.has(key))
328
+ metaWords[key] = value;
329
+ else
330
+ settingWords[key] = value;
331
+ }
332
+ const onPrice = child.result.pane?.place === 'price';
333
+ return {
334
+ id,
335
+ name: child.result.define.title,
336
+ plot: 'spline',
337
+ type: onPrice ? 'onchart' : 'offchart',
338
+ interval: ctx.interval,
339
+ data: [],
340
+ isIndependentSubsetRange: true,
341
+ showIndependentYAxis: true,
342
+ ...metaWords,
343
+ // The pane's axis: K/M/B from 1K, its own digits below (the
344
+ // volume-based technical scripts' path), never the main precision.
345
+ ...(getYLabel !== undefined ? { getYLabel } : {}),
346
+ initLegendText: () => wrunSeriesChildLegendSlots(palette),
347
+ getLegendText: wrunSeriesChildLegendText(builtinTwin, ctx.priceDigits),
348
+ settings: {
349
+ ...childLegendControls(ctx.parentName),
350
+ // Below the chart: the shared weight, or on a window the plan's.
351
+ ...(onPrice ? {} : { gridHeight: ctx.planned?.get(id) ?? CHILD_PANE_GRID_HEIGHT }),
352
+ ...settingWords,
353
+ ...(palette.length > 0 ? { colors: palette } : {}),
354
+ ...seriesChildChartSettings(parentSettings),
355
+ },
356
+ };
357
+ }
358
+ /** The chart switches the settings dialog keeps on a package overlay: Plot settings (Hide weekends,
359
+ * Interpolation) and Price marker (Price line, Axis label, Name label). The parent's container takes
360
+ * them through its save, but a series child is a container of its own, so it carries a copy, from its
361
+ * mount and after every save; without one its pane's plots ignored every switch. */
362
+ const SERIES_CHILD_CHART_KEYS = [
363
+ 'hideWeekends',
364
+ 'preventGapInterpolation',
365
+ 'showLastValueLine',
366
+ 'showYAxisPriceLabel',
367
+ 'showYAxisNameLabel',
368
+ ];
369
+ function seriesChildChartSettings(settings) {
370
+ const chartSettings = {};
371
+ for (const key of SERIES_CHILD_CHART_KEYS) {
372
+ if (typeof settings?.[key] === 'boolean')
373
+ chartSettings[key] = settings[key];
374
+ }
375
+ return chartSettings;
376
+ }
377
+ /** A save of the package overlay: every mounted series child takes the chart switches it carries,
378
+ * its container through the engine's settings door and its plots' price markers through the
379
+ * adapter's own stamp (the one the parent's plots take). */
380
+ export function syncWrunSeriesChildChartSettings(tc, overlayId, settings) {
381
+ const chartSettings = seriesChildChartSettings(settings);
382
+ if (Object.keys(chartSettings).length === 0)
383
+ return;
384
+ for (const meta of tc.metadata) {
385
+ if (!isSeriesChildId(meta.id) || !meta.id.startsWith(`${overlayId}::`))
386
+ continue;
387
+ tc.updateSettings?.(meta.id, chartSettings);
388
+ wrunChartHostEnv().chart.syncPriceMarkers({ metadata: [...tc.metadata], renderService: tc.renderService }, meta.id, chartSettings);
389
+ }
390
+ }
391
+ /** A docked levels child (g2): the door settings and rows with every colour
392
+ * word resolved, `beside` and `panel: "lower"` mapped to engine ids
393
+ * (wrun-levels-child.util's mount helpers). The engine's docked door keeps
394
+ * only the sender fields and its boolean legend flags, and warns about
395
+ * anything else: the control keys stay unsent. `hideLegend` is one of those
396
+ * flags from the titan release that adds it to `DOCKED_LEGEND_FLAGS` (an
397
+ * older door drops it and warns once per overlay); `childConfig` sends it,
398
+ * as it does for every kind outside the legend allowlist (WRUN_CHILD_LEGEND_ROW).
399
+ * The name, read as words, titles the child wherever the engine still lists
400
+ * it. */
401
+ function levelsChildConfig(child, ctx) {
402
+ return {
403
+ id: wrunLevelsChildId(ctx.overlayId, child.name),
404
+ // The legend row reads the level's name in words; the id keeps the name.
405
+ name: wrunLegendName(child.name),
406
+ plot: 'levels',
407
+ type: 'onchart',
408
+ interval: ctx.interval,
409
+ data: wrunLevelsMountData(child, ctx.theme),
410
+ settings: wrunLevelsMountSettings(child, ctx.theme, {
411
+ overlayId: ctx.overlayId,
412
+ parentOffchart: ctx.parentOffchart,
413
+ }),
414
+ };
415
+ }
416
+ /** A price canvas child (g6): the config wrun-canvases.util builds (the
417
+ * child id, the engine plot, settings resolved against the theme, a
418
+ * heatmap's bounds at the viewer's Sensitivity, a TPO's default letter
419
+ * scheme from the user's theme name, the profile extractor, the live merge,
420
+ * a matrix's rows re-resolved). */
421
+ function canvasChildConfig(child, ctx) {
422
+ const sensitivity = child.kind === 'heatmap' ? ctx.heatmapSensitivity(child.name) : undefined;
423
+ const config = wrunCanvasChildConfig(child, {
424
+ overlayId: ctx.overlayId,
425
+ theme: ctx.theme,
426
+ ...(ctx.themeMode !== undefined ? { themeMode: ctx.themeMode } : {}),
427
+ ...(sensitivity !== undefined ? { heatmapSensitivity: sensitivity } : {}),
428
+ formatters: ctx.formatters,
429
+ });
430
+ return {
431
+ id: config.id,
432
+ name: child.name,
433
+ plot: config.plot,
434
+ type: config.type,
435
+ interval: ctx.interval,
436
+ // The engine wire rows (book, profile, grid and matrix rows are arrays).
437
+ data: (config.data ?? child.data),
438
+ ...(config.extractors !== undefined ? { extractors: config.extractors } : {}),
439
+ ...(config.mergeLiveDataPoint !== undefined ? { mergeLiveDataPoint: config.mergeLiveDataPoint } : {}),
440
+ ...(config.tailOnly === true ? { tailOnly: true } : {}),
441
+ settings: config.settings,
442
+ };
443
+ }
444
+ /** A batched child (WRUN-BATCHED-MARKS): the config wrun-batched-marks.util
445
+ * builds (the id, the kind as the engine plot, the section look with every
446
+ * colour resolved against the theme, the live merge), its rows the engine
447
+ * wire `[ts, ...fields]`. Its rows are its own subset of the bars (budget
448
+ * trims, live appends), so it mounts as an independent subset: without the
449
+ * flag titan's band and sliver narrowing and its drawn-rows pass read the
450
+ * main series' rows for it, and a partial pass redrew the whole window. */
451
+ function batchedChildConfig(child, ctx) {
452
+ // A timed record's `{{start}}` and `{{end}}` print in the display timezone the time axis labels the chart's bars in.
453
+ const config = wrunBatchedChildConfig(child, {
454
+ overlayId: ctx.overlayId,
455
+ theme: ctx.theme,
456
+ timeOffsetMs: isDateLabelledBarInterval(ctx.interval) ? 0 : ctx.timezoneOffsetMs,
457
+ });
458
+ return {
459
+ id: config.id,
460
+ name: child.name,
461
+ plot: config.plot,
462
+ type: config.type,
463
+ interval: ctx.interval,
464
+ data: child.data,
465
+ isIndependentSubsetRange: true,
466
+ mergeLiveDataPoint: config.mergeLiveDataPoint,
467
+ ...(config.tailOnly === true ? { tailOnly: true } : {}),
468
+ settings: config.settings,
469
+ };
470
+ }
471
+ /** True only for the kinds the legend allowlist marks `own`
472
+ * (WRUN_CHILD_LEGEND_ROW): any other kind, an unlisted one included,
473
+ * builds no legend row. */
474
+ function keepsOwnLegendRow(kind) {
475
+ return WRUN_CHILD_LEGEND_ROW[kind] === 'own';
476
+ }
477
+ /** A price canvas (heatmap, profile, matrix) is no series with a last value:
478
+ * titan tags every onchart overlay on the price axis unless its settings say
479
+ * false, which printed the first bucket price of a heatmap's last row as an
480
+ * amber tag (B37 B43). No axis tag, no name riding it, no last-value line. */
481
+ const CANVAS_PRICE_MARKERS_OFF = {
482
+ showYAxisPriceLabel: false,
483
+ showYAxisNameLabel: false,
484
+ showLastValueLine: false,
485
+ };
486
+ /** The engine config of a child, the one door every config passes before
487
+ * the engine takes it (a mount, the restore after a failed run, a
488
+ * retranslate): the kind's own config, `hideLegend: true` for every kind
489
+ * outside the legend allowlist (WRUN_CHILD_LEGEND_ROW), so no kind needs
490
+ * to remember it, and the price markers off on a price canvas
491
+ * (CANVAS_PRICE_MARKERS_OFF). */
492
+ function childConfig(child, ctx) {
493
+ const config = childKindConfig(child, ctx);
494
+ if (keepsOwnLegendRow(child.kind))
495
+ return config;
496
+ return {
497
+ ...config,
498
+ settings: { ...config.settings, hideLegend: true, ...(isCanvasChild(child) ? CANVAS_PRICE_MARKERS_OFF : {}) },
499
+ };
500
+ }
501
+ /** A child's config by its kind: colour words resolved at this door, the
502
+ * mount's own keys set (the unresolved input stays on the mounted record
503
+ * for a retranslate). */
504
+ function childKindConfig(child, ctx) {
505
+ switch (child.kind) {
506
+ case 'panel':
507
+ return panelChildConfig(child, ctx);
508
+ case 'series':
509
+ return seriesChildConfig(child, ctx);
510
+ case 'levels':
511
+ return levelsChildConfig(child, ctx);
512
+ case 'heatmap':
513
+ case 'profile':
514
+ case 'matrix':
515
+ return canvasChildConfig(child, ctx);
516
+ case 'marks':
517
+ case 'spans':
518
+ case 'rays':
519
+ return batchedChildConfig(child, ctx);
520
+ case 'inset':
521
+ // The docked door keeps the inset sender fields only (a colour word
522
+ // among them resolves here); no legend-control keys, so its row keeps
523
+ // the door's own eye, gear and X (the gear opens the owner's dialog, the
524
+ // eye the reader moves stands: syncChildVisibility). Its legend row
525
+ // stays (it carries the latest value), titled with the name in words,
526
+ // and is never rebuilt while the strip stays the same strip (sameInset).
527
+ return {
528
+ id: `${ctx.overlayId}::inset:${child.name}`,
529
+ name: wrunLegendName(child.name),
530
+ plot: 'inset',
531
+ type: 'onchart',
532
+ interval: ctx.interval,
533
+ data: child.data.map((row) => [...row]),
534
+ settings: resolveSettingsColorWords(child.settings, ctx.theme),
535
+ };
536
+ }
537
+ }
538
+ /** The legend's own O / H / L / C markers (OT28), read per call so a
539
+ * locale switch prints the new words. */
540
+ function legendOhlcLabels() {
541
+ const { t } = wrunChartHostEnv();
542
+ return {
543
+ open: t('chart.legend.open'),
544
+ high: t('chart.legend.high'),
545
+ low: t('chart.legend.low'),
546
+ close: t('chart.legend.close'),
547
+ };
548
+ }
549
+ /** The lower pane's legend readout, the parent's own rule brought to its
550
+ * child: every value line of the pane's nested plots at the hovered bar,
551
+ * named by its output's `labels` column (kScriptLegendEntries, the same
552
+ * entries the technical-script control prints for the parent) and printed
553
+ * by its output's declared `format` word and companions (OT32), else by the
554
+ * lower-pane legend rule (K/M/B from 1K, the built-in legend decimals below,
555
+ * never the axis step: formatWrunLegendValue); "price" prints at the chart's
556
+ * price digits (OT29, the provider). A candle group reads its four values
557
+ * after the legend's O / H / L / C markers (OT28); every dot shows the
558
+ * colour the hovered bar is drawn in (OT27). A single line keeps the
559
+ * unlabelled single-slot readout, like the parent. An output with
560
+ * `legend: false` is never a line (kScriptLegendLines). A proven twin's pane
561
+ * (`builtinTwin`) prints by its built-in's legend rule instead. */
562
+ export function wrunSeriesChildLegendText(builtinTwin, priceDigits) {
563
+ return (point, meta) => {
564
+ const placement = {
565
+ onPrice: false,
566
+ priceDigits: priceDigits?.() ?? WRUN_PANE_DEFAULT_DIGITS,
567
+ builtinTwin,
568
+ };
569
+ const format = (value, line) => formatWrunLegendValue(value, placement, kScriptLegendLineFormat(meta, line), kScriptLegendLineFormatOptions(meta, line));
570
+ const entries = kScriptLegendEntries(point, meta, format, { ohlcLabels: legendOhlcLabels() });
571
+ if (entries.length > 1)
572
+ return padKScriptLegendSlots(entries);
573
+ const [line] = kScriptLegendLines(meta);
574
+ if (line === undefined)
575
+ return padKScriptLegendSlots([]);
576
+ const ts = Array.isArray(point) && typeof point[0] === 'number' ? point[0] : undefined;
577
+ const value = kScriptLegendLineValueAt(line, ts, { meta });
578
+ return padKScriptLegendSlots([
579
+ {
580
+ id: 'value',
581
+ text: value === undefined ? '-' : format(value, line),
582
+ label: '',
583
+ color: KSCRIPT_LEGEND_VALUE_INK,
584
+ swatch: kScriptLegendLineSwatchAt(meta, line, ts),
585
+ },
586
+ ]);
587
+ };
588
+ }
589
+ /** The lower pane's static legend: the slot pool the dynamic readout
590
+ * addresses (one labelled span per slot, born empty, the parent's rule:
591
+ * titan creates legend spans only from this list and drops updates for ids
592
+ * it never created). The palette now rides each update's swatch, so the
593
+ * slots start in the value ink; the argument stays for the callers. */
594
+ export function wrunSeriesChildLegendSlots(_palette) {
595
+ return kScriptLegendSlotCells();
596
+ }
597
+ /** The series child's overlay id (`<parent>::series:<name>`), defined by the
598
+ * adapter (the visibility apply reads it there) and re-exported here. */
599
+ export { wrunSeriesChildId };
600
+ function isSeriesChildId(id) {
601
+ return id.includes('::series:');
602
+ }
603
+ /** True while the reader keeps a child hidden from its own legend row: the
604
+ * visibility door keeps that eye on the owner's settings
605
+ * (wrunChildHiddenRowKey), so it survives remounts and reloads. */
606
+ function hiddenByReader(parent, childId) {
607
+ const key = wrunChildHiddenRowKey(childId);
608
+ return key !== null && parent.settings?.[key] === true;
609
+ }
610
+ /** The parent's eye onto its children. When it moved, every child follows: a
611
+ * hidden Indicator leaves no pane, dock or canvas behind, and shown again
612
+ * each child shows unless the reader hid it on its own row. Otherwise only
613
+ * the children this pass added to the engine (`added`: back through
614
+ * addOverlay visible) take it; a child that stayed keeps the eye it has, so
615
+ * the flip a reader made on its row (titan toggles the child itself) stands
616
+ * through live blocks, reruns and the parent's other updates (QA 214). */
617
+ function syncChildVisibility(tc, parent, state, added = []) {
618
+ if (tc.isDestroyed || typeof tc.changeVisibilityOverlay !== 'function')
619
+ return;
620
+ const ownerVisible = parent.isHidden !== true;
621
+ const moved = state.ownerVisible !== ownerVisible;
622
+ state.ownerVisible = ownerVisible;
623
+ for (const id of moved ? [...state.children.keys()] : added) {
624
+ const child = tc.metadata.find((meta) => meta.id === id);
625
+ const visible = ownerVisible && !hiddenByReader(parent, id);
626
+ if (child && (child.isHidden === true) === visible)
627
+ tc.changeVisibilityOverlay(id, visible);
628
+ }
629
+ }
630
+ /** Apply a series child's result to its mounted container through the shared
631
+ * adapter: the mounted-row refresh on a tick (the kScript live ladder's
632
+ * first rung), the full metadata apply on a run, on a fresh mount, or when
633
+ * the refresh could not apply. A parent that ran at another interval hands
634
+ * its projection (the run's stamp, the chart and its venue), so the lower
635
+ * pane lands on the chart's bars like the parent's rows. Throws the
636
+ * adapter's diagnostics, so a failed child apply fails the run exactly like
637
+ * a failed pack. */
638
+ function integrateSeriesChild(tc, childId, result, mode, projection) {
639
+ const meta = tc.metadata.find((candidate) => candidate.id === childId);
640
+ if (!meta)
641
+ throw new Error(`wrun series child '${childId}' is not mounted`);
642
+ if (mode === 'tick') {
643
+ const refresh = wrunChartHostEnv().chart.refreshMountedRows({
644
+ tc: tc,
645
+ indicatorId: childId,
646
+ meta: meta,
647
+ runResult: result,
648
+ ...projection,
649
+ });
650
+ if (refresh.ok && refresh.applied)
651
+ return;
652
+ }
653
+ const integration = wrunChartHostEnv().chart.integrate({
654
+ tc: tc,
655
+ indicatorId: childId,
656
+ runResult: result,
657
+ mode: 'metadata',
658
+ meta: meta,
659
+ ...projection,
660
+ });
661
+ if (!integration.ok) {
662
+ throw new Error(`wrun lower pane integration failed: ${integration.diagnostics.map((d) => `${d.code}: ${d.message}`).join('; ')}`);
663
+ }
664
+ }
665
+ /** The same pane, the shared rule (om-panel.util), for a panel and for the
666
+ * series child alike: side, species, axis ownership, chrome and the carved
667
+ * height the child was mounted with. On a window the height is the plan's
668
+ * and moves in place (reconcileWindowOwnerGeometry at the end of the
669
+ * mount), so only the other fields decide there: a plan that shifts when a
670
+ * sibling arrives never re-mounts the panes that stay. */
671
+ function samePane(mounted, next, windowCell = false) {
672
+ if (mounted.type !== next.type)
673
+ return false;
674
+ const shape = (config) => ({
675
+ plot: config.plot,
676
+ hidePriceScale: config.hidePriceScale,
677
+ gridHeight: windowCell ? 0 : Number(config.settings.gridHeight ?? CHILD_PANE_GRID_HEIGHT),
678
+ ...(typeof config.settings.chromeStyle === 'string' ? { chromeStyle: config.settings.chromeStyle } : {}),
679
+ });
680
+ return samePanelPane(shape(mounted), shape(next));
681
+ }
682
+ /** The panes a window mount lays out, for the planner: the owner's own pane
683
+ * when it is mounted offchart (a lower-only package), the run's panel
684
+ * children (side panels included: they stack in the window) and series
685
+ * children that mount below the chart (a pane pinned over the candles
686
+ * carves nothing), and the mounted children a frameless tick keeps. */
687
+ function windowPanesOfMount(parent, overlayId, children, kept) {
688
+ const panes = [];
689
+ if (parent.type === 'offchart' && parent.isPaneHidden !== true)
690
+ panes.push({ id: overlayId, kind: 'time' });
691
+ const seen = new Set();
692
+ for (const child of children) {
693
+ if (child.kind === 'panel') {
694
+ const id = `${overlayId}::panel:${child.name}`;
695
+ seen.add(id);
696
+ panes.push(child.frame.panel.kind === 'table'
697
+ ? { id, kind: 'table', rows: child.frame.rows.length }
698
+ : { id, kind: 'chart' });
699
+ }
700
+ else if (child.kind === 'series') {
701
+ if (child.result.pane?.place === 'price')
702
+ continue;
703
+ const id = wrunSeriesChildId(overlayId, child.name);
704
+ seen.add(id);
705
+ panes.push({ id, kind: 'time' });
706
+ }
707
+ }
708
+ for (const config of kept) {
709
+ if (seen.has(config.id) || config.type !== 'offchart')
710
+ continue;
711
+ if (isSeriesChildId(config.id))
712
+ panes.push({ id: config.id, kind: 'time' });
713
+ else if (config.plot === 'table')
714
+ panes.push({ id: config.id, kind: 'table', rows: tableRowCountOf(config) });
715
+ else
716
+ panes.push({ id: config.id, kind: 'chart' });
717
+ }
718
+ return panes;
719
+ }
720
+ /** A row-backed canvas keeps its overlay across runs while it stays the
721
+ * same canvas: the same engine plot over the same cell layout (a heatmap's
722
+ * `cellLayout`, a profile's `variant`) and, on a batched child, the same row
723
+ * geometry (`slots` and `stride`: a row of another width is another canvas). */
724
+ function sameCanvas(mounted, next) {
725
+ const layout = (config) => [
726
+ config.plot,
727
+ config.settings.cellLayout ?? '',
728
+ config.settings.variant ?? '',
729
+ config.settings.slots ?? '',
730
+ config.settings.stride ?? '',
731
+ ]
732
+ .map(String)
733
+ .join('|');
734
+ return layout(mounted) === layout(next);
735
+ }
736
+ /** The inset keys the docked door lays a strip out by. */
737
+ const INSET_STRIP_KEYS = ['dock', 'height_px', 'shape'];
738
+ /** An inset keeps its overlay across ticks and runs while it stays the same
739
+ * strip (the same dock, height and shape): its rows and colours move in
740
+ * place, so its legend row (the latest value, the eye, the gear, the X) is
741
+ * never rebuilt under the reader's cursor (QA 214: an inset re-added on
742
+ * every live block ate the clicks on its row). Another strip mounts again. */
743
+ function sameInset(mounted, next) {
744
+ return INSET_STRIP_KEYS.every((key) => Object.is(mounted.settings[key], next.settings[key]));
745
+ }
746
+ /** Refresh a mounted panel child from the new run through the shared
747
+ * in-place path (om-panel.util): the pane keeps its place in the stack; the
748
+ * run's title and formatter hooks follow (R13: a bag without a hook
749
+ * deletes the mounted one). */
750
+ function refreshPanelChild(tc, mounted, next) {
751
+ const hooks = {
752
+ ...(next.formatDomainValue !== undefined ? { formatDomainValue: next.formatDomainValue } : {}),
753
+ ...(next.getYLabel !== undefined ? { getYLabel: next.getYLabel } : {}),
754
+ };
755
+ refreshPanelOverlayInPlace(tc, next.id, { data: next.data, settings: next.settings, name: next.name, hooks }, mounted.settings);
756
+ }
757
+ /** Refresh a mounted row-backed child in place (a canvas that stays the same
758
+ * canvas on a full run or a moved window, an inset that stays the same
759
+ * strip on any pass): the settings move onto the engine's meta (the keys the
760
+ * mount set and the run dropped go), then the rows swap through the engine's
761
+ * own update path; the overlay keeps its place, its GL cells and its legend
762
+ * row. */
763
+ function refreshChildInPlace(tc, mounted, next) {
764
+ const meta = tc.metadata.find((candidate) => candidate.id === next.id);
765
+ if (!meta)
766
+ throw new Error(`wrun child '${next.id}' is not mounted`);
767
+ const settings = (meta.settings ??= {});
768
+ for (const key of Object.keys(mounted.settings)) {
769
+ if (!(key in next.settings))
770
+ delete settings[key];
771
+ }
772
+ Object.assign(settings, next.settings);
773
+ if (typeof tc.updateData === 'function') {
774
+ tc.updateData(next.id, next.data, { shouldResetRange: false });
775
+ return;
776
+ }
777
+ meta.rawData = next.data;
778
+ meta.data = next.data;
779
+ }
780
+ /** A tick's rows for a mounted row-backed canvas through the engine's live
781
+ * merge (the forming row replaced, a newer one appended): the newest row, or,
782
+ * on a tick that added bars (`fromTs`, the bar the canvases last painted),
783
+ * every row from the one holding that bar on, oldest first
784
+ * (`liveCanvasRows`), so each bar keeps its column, a roll's closed bar its
785
+ * final row included. An engine
786
+ * without the merge takes the rows whole, unless they are a heatmap tail: a
787
+ * tail would replace the canvas's history. A heatmap's record then follows
788
+ * the rows the engine holds (`adoptMergedHeatmapRows`, or the rows handed
789
+ * whole) and its retained rows answer to the cell budget
790
+ * (`budgetLiveHeatmap`). */
791
+ function liveUpdateCanvasChild(tc, config, fromTs) {
792
+ if (config.data[config.data.length - 1] === undefined)
793
+ return;
794
+ if (typeof tc.liveUpdateData === 'function') {
795
+ for (const row of liveCanvasRows(config.data, fromTs))
796
+ tc.liveUpdateData(config.id, row);
797
+ adoptMergedHeatmapRows(tc, config.id);
798
+ }
799
+ else if (config.tailOnly !== true) {
800
+ tc.updateData?.(config.id, config.data, { shouldResetRange: false });
801
+ const record = mountedHeatmapRecord(tc, config.id);
802
+ if (record !== undefined)
803
+ keepHeatmapRows(record, config.data);
804
+ }
805
+ budgetLiveHeatmap(tc, config);
806
+ }
807
+ /** The rows a live merge hands a canvas, oldest first: the newest alone, or (`fromTs`) the row holding that bar
808
+ * (the newest at or before it: the bar's own row, or a profile's period) and every row after it, so a period the
809
+ * tick closed lands too. Rows come in time order; the newest is always among them. */
810
+ function liveCanvasRows(rows, fromTs) {
811
+ let from = rows.length - 1;
812
+ if (fromTs !== undefined) {
813
+ while (from > 0 && (rowTs(rows[from]) ?? Number.NEGATIVE_INFINITY) > fromTs)
814
+ from -= 1;
815
+ }
816
+ return rows.slice(from);
817
+ }
818
+ /**
819
+ * A mounted heatmap's record holds the rows the mount last meant the engine to hold (its intended
820
+ * input: what a retranslate rebuilds from and what a trim is cut from), never the engine's rows read
821
+ * right after an `updateData`: titan queues an overlay's replacement while a gesture is live and
822
+ * keeps its own array when an update proves identical, so its rows then are not the ones asked for.
823
+ * The record of the child `childId` names, when it is a heatmap.
824
+ */
825
+ function mountedHeatmapRecord(tc, childId) {
826
+ const overlayId = wrunChildOverlayParentId(childId);
827
+ const record = overlayId === null ? undefined : chartChildren.get(tc)?.get(overlayId)?.children.get(childId);
828
+ return record?.input.kind === 'heatmap' ? record : undefined;
829
+ }
830
+ /** A heatmap (or batched) record takes `rows` as its intended input, its config and its unresolved
831
+ * input alike. */
832
+ function keepHeatmapRows(record, rows) {
833
+ if (record.config.data === rows)
834
+ return;
835
+ record.config = { ...record.config, data: rows };
836
+ if (record.input.kind === 'heatmap')
837
+ record.input = { ...record.input, data: rows };
838
+ else if (isBatchedChild(record.input))
839
+ record.input = { ...record.input, data: rows };
840
+ }
841
+ /** After an actual live merge the engine's rows are the ones it adopted: titan lands every
842
+ * replacement it queued for the overlay before it merges. The heatmap's record points at them on
843
+ * every merge, a merge that trims nothing included, so the ticks after it land in the record's own
844
+ * array and a retranslate rebuilds what the engine draws. */
845
+ function adoptMergedHeatmapRows(tc, childId) {
846
+ const record = mountedHeatmapRecord(tc, childId);
847
+ if (record === undefined)
848
+ return;
849
+ const meta = tc.metadata.find((candidate) => candidate.id === childId);
850
+ const adopted = meta?.rawData ?? meta?.data;
851
+ if (Array.isArray(adopted))
852
+ keepHeatmapRows(record, adopted);
853
+ }
854
+ /**
855
+ * The cell budget at a seam that hands a heatmap child its rows in full (the first install, the
856
+ * full run's replace, the retranslation; WRUN-COST-GUARD U4): over the child's share of the
857
+ * Indicator's cell cap the oldest bars are dropped before the engine takes the rows, and the
858
+ * child's record (the unresolved input a retranslate rebuilds from, and the config) points at the
859
+ * rows the engine holds, so the live merges land in the record's own array as before. A mounted
860
+ * sibling the new demand pushed over its share drops its oldest bars too. Any other child passes.
861
+ * A retranslation (`rebuild`) hands back the record's rows, which are what the allowance left and
862
+ * never what the child asked for: they are counted as retained rows with no growth, so the ledger
863
+ * keeps the child's demand and the "Cells capped" row its numbers (they are trimmed again only when
864
+ * the allowance shrank meanwhile). A history-window merge budgets through its own landing
865
+ * (`landHeatmapWindow`).
866
+ */
867
+ function budgetHeatmapChild(tc, overlayId, child, seam = 'run') {
868
+ if (child.input.kind !== 'heatmap' || child.config.tailOnly === true)
869
+ return;
870
+ const held = heldByMount(tc, overlayId);
871
+ const layout = wrunHeatmapCellLayoutOf(child.config.settings);
872
+ const id = child.config.id;
873
+ const rows = seam === 'rebuild'
874
+ ? (budgetWrunHeatmapRetained(tc, overlayId, id, layout, child.config.data, held) ?? child.config.data)
875
+ : budgetWrunHeatmapRows(tc, overlayId, id, layout, child.config.data, held);
876
+ if (rows !== child.config.data) {
877
+ child.config.data = rows;
878
+ child.input = { ...child.input, data: rows };
879
+ }
880
+ for (const sibling of wrunHeatmapChildrenOverShare(tc, overlayId, child.config.id, held)) {
881
+ budgetMountedHeatmap(tc, overlayId, sibling);
882
+ }
883
+ }
884
+ /** The children the Indicator's mount holds a record for (a child about to be installed is one). */
885
+ function heldByMount(tc, overlayId) {
886
+ return (childId) => chartChildren.get(tc)?.get(overlayId)?.children.has(childId) === true;
887
+ }
888
+ /** The cell budget after a live merge into a mounted heatmap (the engine's history plus the bar a
889
+ * tick appended). The append's growth shrinks its siblings' shares (the water-filling the full
890
+ * seams apply): while the Indicator's mounted cells pass the cap, a sibling now over its share
891
+ * drops its oldest bars too, also one this tick already merged. */
892
+ function budgetLiveHeatmap(tc, config) {
893
+ const overlayId = wrunChildOverlayParentId(config.id);
894
+ if (config.plot !== 'heatmapCells' || overlayId === null)
895
+ return;
896
+ budgetMountedHeatmap(tc, overlayId, config.id);
897
+ for (const sibling of wrunHeatmapSiblingsToRebalance(tc, overlayId, config.id, heldByMount(tc, overlayId))) {
898
+ budgetMountedHeatmap(tc, overlayId, sibling);
899
+ }
900
+ }
901
+ /**
902
+ * A mounted heatmap's retained rows counted again: past its share the oldest bars are dropped
903
+ * through the engine's row swap (titan's `updateData` keeps the shorter array as its history). The
904
+ * rows counted are the child's record, the intended input (`mountedHeatmapRecord`), never the
905
+ * engine's own: a replacement handed earlier may still wait in titan's queue. The record then holds
906
+ * the trimmed rows, so the next trim and a retranslate start from them.
907
+ */
908
+ function budgetMountedHeatmap(tc, overlayId, childId) {
909
+ const record = mountedHeatmapRecord(tc, childId);
910
+ if (record === undefined || !overlayPresent(tc, childId))
911
+ return;
912
+ const layout = wrunHeatmapCellLayoutOf(record.config.settings);
913
+ const retained = record.config.data;
914
+ const rows = budgetWrunHeatmapRetained(tc, overlayId, childId, layout, retained, heldByMount(tc, overlayId));
915
+ if (rows === null)
916
+ return;
917
+ tc.updateData?.(childId, rows, { shouldResetRange: false });
918
+ keepHeatmapRows(record, rows);
919
+ }
920
+ function isBatchedRecord(record) {
921
+ return record !== undefined && isBatchedChild(record.input);
922
+ }
923
+ /** The record of the batched child `childId` names, when it is one. */
924
+ function mountedBatchedRecord(tc, childId) {
925
+ const overlayId = wrunChildOverlayParentId(childId);
926
+ const record = overlayId === null ? undefined : chartChildren.get(tc)?.get(overlayId)?.children.get(childId);
927
+ return isBatchedRecord(record) ? record : undefined;
928
+ }
929
+ /**
930
+ * The cell budget at a seam that hands a batched child its rows in full (WRUN-BATCHED-MARKS): the
931
+ * first install and a full run's replace charge the rows the build kept under its share (a replace
932
+ * keeps the hard allowance: the old copy goes at the swap and is never charged), and a
933
+ * retranslation's rebuild counts the record's rows as retained with no growth (it removes the old
934
+ * copy before it adds the new one). The child's record and config point at the rows the engine is
935
+ * handed; a sibling the demand pushed over its share drops its oldest bars too. Any other child
936
+ * passes. A history-window merge budgets through its own landing (`landHeatmapWindow`).
937
+ */
938
+ function budgetBatchedChild(tc, overlayId, child, seam = 'run') {
939
+ if (!isBatchedChild(child.input) || child.config.tailOnly === true)
940
+ return;
941
+ const held = heldByMount(tc, overlayId);
942
+ const charge = wrunBatchedChargeOf(child.config.settings);
943
+ const id = child.config.id;
944
+ const rows = seam === 'rebuild'
945
+ ? (budgetWrunBatchedRetained(tc, overlayId, id, child.config.data, charge, held) ?? child.config.data)
946
+ : budgetWrunBatchedRows(tc, overlayId, id, child.config.data, charge, {
947
+ ...(child.input.budget !== undefined ? { built: child.input.budget } : {}),
948
+ isMounted: held,
949
+ });
950
+ if (rows !== child.config.data) {
951
+ child.config.data = rows;
952
+ child.input = { ...child.input, data: rows };
953
+ }
954
+ for (const sibling of wrunBatchedChildrenOverShare(tc, overlayId, id, held)) {
955
+ budgetMountedBatched(tc, overlayId, sibling);
956
+ }
957
+ }
958
+ /** A mounted batched child's retained rows counted again (its record, the rows the mount means the
959
+ * engine to hold): past its share the oldest bars are dropped through the engine's row swap down to
960
+ * the watermark, and the record holds the trimmed rows. */
961
+ function budgetMountedBatched(tc, overlayId, childId) {
962
+ const record = mountedBatchedRecord(tc, childId);
963
+ if (record === undefined || !overlayPresent(tc, childId))
964
+ return;
965
+ const charge = wrunBatchedChargeOf(record.config.settings);
966
+ const held = heldByMount(tc, overlayId);
967
+ const rows = budgetWrunBatchedRetained(tc, overlayId, childId, record.config.data, charge, held);
968
+ if (rows === null)
969
+ return;
970
+ tc.updateData?.(childId, rows, { shouldResetRange: false });
971
+ keepHeatmapRows(record, rows);
972
+ }
973
+ /** The cell budget after a live merge into a mounted batched child: the child counted again, and
974
+ * while the Indicator's batched cells pass the cap, a sibling now over its share trimmed too. */
975
+ function budgetLiveBatched(tc, childId) {
976
+ const overlayId = wrunChildOverlayParentId(childId);
977
+ if (overlayId === null)
978
+ return;
979
+ budgetMountedBatched(tc, overlayId, childId);
980
+ for (const sibling of wrunBatchedSiblingsToRebalance(tc, overlayId, childId, heldByMount(tc, overlayId))) {
981
+ budgetMountedBatched(tc, overlayId, sibling);
982
+ }
983
+ }
984
+ /**
985
+ * The changed tail of a pass merged into a mounted batched child, row by row (the live tick's
986
+ * contract): every row of the pass at or after the newest row the child's record holds (the bar the
987
+ * engine holds as its forming bar), found walking back from the pass's newest row, so a tick costs
988
+ * its tail and never the history. Each row goes through the engine's live merge in timestamp order:
989
+ * the first replaces the bar the engine holds as its newest (the previous forming bar on a roll),
990
+ * each newer one appends; an all-NaN row clears its bar's records. The record then follows the rows
991
+ * the engine adopted (an engine without the live merge takes the merged rows whole) and the cell
992
+ * budget counts them again. A child holding no rows takes none (the engine merges no live row into an
993
+ * empty overlay): the tick asks a whole window for it instead (wrun-live-tick.util).
994
+ */
995
+ function mergeBatchedChangedRows(tc, record, config) {
996
+ const held = record.config.data;
997
+ const newestTs = rowTs(held[held.length - 1]);
998
+ if (newestTs === undefined)
999
+ return;
1000
+ const pass = config.data;
1001
+ let from = pass.length;
1002
+ while (from > 0) {
1003
+ const ts = rowTs(pass[from - 1]);
1004
+ if (ts === undefined || ts < newestTs)
1005
+ break;
1006
+ from -= 1;
1007
+ }
1008
+ if (from === pass.length)
1009
+ return;
1010
+ if (typeof tc.liveUpdateData === 'function') {
1011
+ for (let at = from; at < pass.length; at += 1)
1012
+ tc.liveUpdateData(config.id, pass[at]);
1013
+ const meta = tc.metadata.find((candidate) => candidate.id === config.id);
1014
+ const adopted = meta?.rawData ?? meta?.data;
1015
+ if (Array.isArray(adopted))
1016
+ keepHeatmapRows(record, adopted);
1017
+ }
1018
+ else {
1019
+ const firstTs = rowTs(pass[from]);
1020
+ let keep = held.length;
1021
+ while (keep > 0 && (rowTs(held[keep - 1]) ?? Number.NEGATIVE_INFINITY) >= firstTs)
1022
+ keep -= 1;
1023
+ const merged = [...held.slice(0, keep), ...pass.slice(from)];
1024
+ tc.updateData?.(config.id, merged, { shouldResetRange: false });
1025
+ keepHeatmapRows(record, merged);
1026
+ }
1027
+ budgetLiveBatched(tc, config.id);
1028
+ }
1029
+ /** Why the engine gate refuses a batched child, null when the chart draws it: its pack failed to
1030
+ * load or to register on this chart (`pack-failed`), or after the pack settled the engine has no
1031
+ * renderer for the kind (`old-engine`: titan's `hasPlotRenderer` is also false for a known type no
1032
+ * pack registered, so it is read only after the await and the registration). */
1033
+ function batchedGateCause(tc, plot, packs) {
1034
+ if (packs !== undefined && packs.failed.length > 0)
1035
+ return 'pack-failed';
1036
+ wrunChartHostEnv().chart.registerLoadedPacks(tc);
1037
+ if (packs !== undefined &&
1038
+ typeof tc.hasFeaturePack === 'function' &&
1039
+ packs.loaded.some((name) => tc.hasFeaturePack?.(name) !== true)) {
1040
+ return 'pack-failed';
1041
+ }
1042
+ return typeof tc.hasPlotRenderer === 'function' && tc.hasPlotRenderer(plot) ? null : 'old-engine';
1043
+ }
1044
+ /**
1045
+ * True while the engine gate refuses the batched child `childId` of `overlayId` (the last pass that
1046
+ * judged it): a child the chart cannot draw is never mounted, so the live tick leaves it out of its
1047
+ * changed-tail decision (wrun-live-tick.util) instead of rebuilding every section's whole window on
1048
+ * every tick for as long as the refusal holds. A tick still carries its tail and the gate judges it
1049
+ * again: one the chart draws again stops reading as refused, and the next tick mounts it. A layout
1050
+ * refusal (a section or a retained record newer than this chart) is not the tail's to lift: it holds
1051
+ * until a full build (a run, a reseed, a whole-window tick) judges the child again.
1052
+ */
1053
+ export function isWrunBatchedChildRefused(tc, overlayId, childId) {
1054
+ return chartChildren.get(tc)?.get(overlayId)?.gateRefused?.has(childId) === true;
1055
+ }
1056
+ /** A row's time (its first cell), undefined for anything else. */
1057
+ function rowTs(row) {
1058
+ return Array.isArray(row) && typeof row[0] === 'number' && Number.isFinite(row[0]) ? row[0] : undefined;
1059
+ }
1060
+ /** True when a tick's canvas rows overlap the mounted rows (the tick's oldest
1061
+ * row is no newer than the mounted newest), so the newest row is the only
1062
+ * change; a sliding lane buffer that drops its oldest row still overlaps. A
1063
+ * window that rolled past every mounted row (a developing profile's session
1064
+ * changed) or that cannot be read takes the full row swap instead. */
1065
+ function sameDataWindow(mounted, next) {
1066
+ const mountedNewest = rowTs(mounted.data[mounted.data.length - 1]);
1067
+ const nextOldest = rowTs(next.data[0]);
1068
+ return mountedNewest !== undefined && nextOldest !== undefined && nextOldest <= mountedNewest;
1069
+ }
1070
+ /**
1071
+ * A mounted heatmap's rows with a windowed run's rows landed inside `window`: the mounted rows outside
1072
+ * the inclusive window stay, the pass's rows replace the window's contents (a mounted timestamp the
1073
+ * pass lacks there is deleted, an empty pass empties the window, a pass row at a mounted timestamp
1074
+ * wins), in timestamp order. A row with no finite timestamp has no place and is dropped. The rows that
1075
+ * stay are the mounted row objects themselves, never copies (C3: the suffix a prefix lands in front of is
1076
+ * untouched). Mounted rows and pass rows that each come in timestamp order (the engine's rows, a run's
1077
+ * rows) merge in one pass; anything else is sorted, stably, into the same order the merge gives.
1078
+ */
1079
+ function heatmapRowsWithWindow(mounted, pass, window) {
1080
+ const passRows = [];
1081
+ const passTs = [];
1082
+ const passTimes = new Set();
1083
+ let passOrdered = true;
1084
+ for (const row of pass) {
1085
+ const ts = rowTs(row);
1086
+ if (ts === undefined)
1087
+ continue;
1088
+ if (passTs.length > 0 && ts < passTs[passTs.length - 1])
1089
+ passOrdered = false;
1090
+ passRows.push(row);
1091
+ passTs.push(ts);
1092
+ passTimes.add(ts);
1093
+ }
1094
+ const keptRows = [];
1095
+ const keptTs = [];
1096
+ let keptOrdered = true;
1097
+ for (const row of mounted) {
1098
+ const ts = rowTs(row);
1099
+ if (ts === undefined || !(ts < window.fromMs || ts > window.toMs) || passTimes.has(ts))
1100
+ continue;
1101
+ if (keptTs.length > 0 && ts < keptTs[keptTs.length - 1])
1102
+ keptOrdered = false;
1103
+ keptRows.push(row);
1104
+ keptTs.push(ts);
1105
+ }
1106
+ const total = keptRows.length + passRows.length;
1107
+ const rows = [];
1108
+ const fromPass = new Uint8Array(total);
1109
+ if (passOrdered && keptOrdered) {
1110
+ // A kept row and a pass row never share a timestamp, so taking the older head each step is the
1111
+ // order a stable sort of the kept rows followed by the pass rows gives.
1112
+ let kept = 0;
1113
+ let landed = 0;
1114
+ while (rows.length < total) {
1115
+ if (landed < passRows.length && (kept >= keptRows.length || passTs[landed] < keptTs[kept])) {
1116
+ fromPass[rows.length] = 1;
1117
+ rows.push(passRows[landed++]);
1118
+ }
1119
+ else
1120
+ rows.push(keptRows[kept++]);
1121
+ }
1122
+ return { rows, fromPass, passRows: passRows.length };
1123
+ }
1124
+ const order = Array.from({ length: total }, (_, at) => at);
1125
+ const tsAt = (at) => (at < keptRows.length ? keptTs[at] : passTs[at - keptRows.length]);
1126
+ order.sort((a, b) => tsAt(a) - tsAt(b));
1127
+ for (const at of order) {
1128
+ if (at >= keptRows.length)
1129
+ fromPass[rows.length] = 1;
1130
+ rows.push(at < keptRows.length ? keptRows[at] : passRows[at - keptRows.length]);
1131
+ }
1132
+ return { rows, fromPass, passRows: passRows.length };
1133
+ }
1134
+ function isHeatmapRecord(record) {
1135
+ return record?.input.kind === 'heatmap';
1136
+ }
1137
+ function isWindowRecord(record) {
1138
+ return isHeatmapRecord(record) || isBatchedRecord(record);
1139
+ }
1140
+ /** The merge of a pass into a mounted heatmap's or batched child's window and its budget, planned from the
1141
+ * record's rows (the rows the mount means the engine to hold, a trim titan still queues included), writing
1142
+ * nothing. */
1143
+ function planHeatmapWindow(tc, overlayId, record, pass, window) {
1144
+ const base = record.config.data;
1145
+ const merged = heatmapRowsWithWindow(base, pass, window);
1146
+ const childId = record.config.id;
1147
+ const held = heldByMount(tc, overlayId);
1148
+ const budget = isBatchedRecord(record)
1149
+ ? {
1150
+ family: 'batched',
1151
+ plan: planWrunBatchedMerged(tc, overlayId, childId, merged.rows, wrunBatchedChargeOf(record.config.settings), held),
1152
+ }
1153
+ : {
1154
+ family: 'heatmap',
1155
+ plan: planWrunHeatmapMerged(tc, overlayId, childId, wrunHeatmapCellLayoutOf(record.config.settings), merged.rows, held),
1156
+ };
1157
+ return {
1158
+ childId,
1159
+ pass,
1160
+ window,
1161
+ base,
1162
+ baseLength: base.length,
1163
+ baseNewest: base[base.length - 1],
1164
+ merged,
1165
+ budget,
1166
+ };
1167
+ }
1168
+ /** The rows a window budget hands the engine. */
1169
+ function windowBudgetRows(budget) {
1170
+ return budget.plan.rows;
1171
+ }
1172
+ /** The record still holds exactly the rows a plan merged into: the same array, neither grown nor its newest
1173
+ * row replaced since. */
1174
+ function holdsPlannedRows(record, plan) {
1175
+ const rows = record.config.data;
1176
+ return rows === plan.base && rows.length === plan.baseLength && rows[rows.length - 1] === plan.baseNewest;
1177
+ }
1178
+ /** No sibling waits on a landing of its own (a mount pass lands one child at a time). */
1179
+ const NO_DEFERRED_SIBLINGS = new Set();
1180
+ /**
1181
+ * Land a planned window into its mounted heatmap, synchronously: the budget planned again when a sibling's
1182
+ * landing moved the ledger since, the kept rows through the engine's own row swap with the record's settings
1183
+ * (a windowed landing keeps the colour scale the canvas was drawn with, its Sensitivity sample too; only a full
1184
+ * run samples again), then the record and the ledger, then a sibling the growth pushed over its share trimmed,
1185
+ * unless it is `deferred`: a sibling whose own landing of the same run is still to commit is cut to its share
1186
+ * by that commit, from its merged rows (cut here, it would lose bars its landing could not bring back).
1187
+ * Nothing is recorded when the engine refuses the rows. Returns the record now held.
1188
+ */
1189
+ function landHeatmapWindow(tc, overlayId, state, record, plan, deferred = NO_DEFERRED_SIBLINGS) {
1190
+ const held = heldByMount(tc, overlayId);
1191
+ plan.budget =
1192
+ plan.budget.family === 'batched'
1193
+ ? { family: 'batched', plan: currentWrunBatchedPlan(tc, plan.budget.plan, held) }
1194
+ : { family: 'heatmap', plan: currentWrunHeatmapPlan(tc, plan.budget.plan, held) };
1195
+ const rows = windowBudgetRows(plan.budget);
1196
+ const landed = {
1197
+ input: { ...record.input, data: rows },
1198
+ config: { ...record.config, data: rows },
1199
+ };
1200
+ refreshChildInPlace(tc, record.config, landed.config);
1201
+ state.children.set(plan.childId, landed);
1202
+ if (plan.budget.family === 'batched') {
1203
+ commitWrunBatchedPlan(tc, plan.budget.plan, held);
1204
+ for (const sibling of wrunBatchedChildrenOverShare(tc, overlayId, plan.childId, held)) {
1205
+ if (!deferred.has(sibling))
1206
+ budgetMountedBatched(tc, overlayId, sibling);
1207
+ }
1208
+ return landed;
1209
+ }
1210
+ commitWrunHeatmapPlan(tc, plan.budget.plan, held);
1211
+ keepWrunHeatmapScaleSample(record.input.data, rows);
1212
+ for (const sibling of wrunHeatmapChildrenOverShare(tc, overlayId, plan.childId, held)) {
1213
+ if (!deferred.has(sibling))
1214
+ budgetMountedHeatmap(tc, overlayId, sibling);
1215
+ }
1216
+ return landed;
1217
+ }
1218
+ /** What a planned window lands (`PreparedWrunWindowLanding`): the budget drops the oldest merged rows, so the
1219
+ * pass rows among them are the ones that do not land. */
1220
+ function windowLandingCounts(plan) {
1221
+ const { rows, fromPass, passRows } = plan.merged;
1222
+ const kept = windowBudgetRows(plan.budget).length;
1223
+ const trimmedRows = rows.length - kept;
1224
+ let trimmedPass = 0;
1225
+ for (let at = 0; at < trimmedRows; at += 1)
1226
+ trimmedPass += fromPass[at];
1227
+ const landedRows = passRows - trimmedPass;
1228
+ return { landedRows, keptRows: kept - landedRows, trimmedRows };
1229
+ }
1230
+ /** A prepared heatmap landing that can no longer land (C6): nothing of it is applied. */
1231
+ export class WrunStaleLandingError extends Error {
1232
+ childId;
1233
+ reason;
1234
+ constructor(childId, reason) {
1235
+ super(`wrun heatmap landing for '${childId}' is stale (${reason})`);
1236
+ this.name = 'WrunStaleLandingError';
1237
+ this.childId = childId;
1238
+ this.reason = reason;
1239
+ }
1240
+ }
1241
+ /** The mount a landing for `childId` lands into: the chart's mount of the Indicator, its parent overlay
1242
+ * still the one mounted, and the child a mounted heatmap holding rows (an empty one kept no colour scale to
1243
+ * keep: a full run lands it). Throws `WrunStaleLandingError` otherwise. */
1244
+ function windowLandingTarget(tc, overlayId, childId) {
1245
+ if (!tc || tc.isDestroyed)
1246
+ throw new WrunStaleLandingError(childId, 'chart');
1247
+ const state = chartChildren.get(tc)?.get(overlayId);
1248
+ if (!state)
1249
+ throw new WrunStaleLandingError(childId, 'mount');
1250
+ if (tc.metadata.find((meta) => meta.id === overlayId) !== state.parent) {
1251
+ throw new WrunStaleLandingError(childId, 'parent');
1252
+ }
1253
+ const record = state.children.get(childId);
1254
+ if (!isWindowRecord(record) || record.config.data.length === 0 || !overlayPresent(tc, childId)) {
1255
+ throw new WrunStaleLandingError(childId, 'child');
1256
+ }
1257
+ return { tc, state, record };
1258
+ }
1259
+ const landingGroups = new WeakMap();
1260
+ /** The transaction a landing prepared now joins: the open one of the same mount, else a new one. */
1261
+ function joinLandingGroup(tc, overlayId, state, member) {
1262
+ const open = landingGroups.get(state);
1263
+ if (open !== undefined && open.token === state.token && open.pending.size > 0 && !open.rolledBack) {
1264
+ open.pending.add(member);
1265
+ return open;
1266
+ }
1267
+ const group = {
1268
+ tc,
1269
+ overlayId,
1270
+ state,
1271
+ token: state.token,
1272
+ pending: new Set([member]),
1273
+ landed: 0,
1274
+ rolledBack: false,
1275
+ };
1276
+ landingGroups.set(state, group);
1277
+ return group;
1278
+ }
1279
+ function snapshotLandingGroup(group) {
1280
+ if (group.snapshot !== undefined)
1281
+ return;
1282
+ const children = [];
1283
+ for (const [id, record] of group.state.children) {
1284
+ if (isWindowRecord(record))
1285
+ children.push({ id, record, config: record.config, input: record.input });
1286
+ }
1287
+ group.snapshot = {
1288
+ children,
1289
+ ledger: snapshotWrunHeatmapLedger(group.tc, group.overlayId),
1290
+ batchedLedger: snapshotWrunBatchedLedger(group.tc, group.overlayId),
1291
+ };
1292
+ }
1293
+ /**
1294
+ * Put back what a transaction's landings changed (their rows, the records and the ledger, a sibling's trim
1295
+ * included), once. Only on the mount the landings went into: after another pass (a tick, a run) the picture is
1296
+ * that pass's, and the full run a rejected prefix queues repaints it. A restore the engine refuses is skipped:
1297
+ * the rest still goes back.
1298
+ */
1299
+ function rollBackLandingGroup(group) {
1300
+ if (group.rolledBack)
1301
+ return;
1302
+ group.rolledBack = true;
1303
+ const snapshot = group.snapshot;
1304
+ group.snapshot = undefined;
1305
+ const { tc, overlayId, state } = group;
1306
+ if (snapshot === undefined || group.landed === 0)
1307
+ return;
1308
+ if (tc.isDestroyed || chartChildren.get(tc)?.get(overlayId) !== state || state.token !== group.token)
1309
+ return;
1310
+ for (const { id, record, config, input } of snapshot.children) {
1311
+ // Read before the record is put back: a trim reassigned the config of the very record the snapshot holds.
1312
+ const held = state.children.get(id)?.config;
1313
+ record.config = config;
1314
+ record.input = input;
1315
+ state.children.set(id, record);
1316
+ if (held === undefined || held.data === config.data || !overlayPresent(tc, id))
1317
+ continue;
1318
+ try {
1319
+ refreshChildInPlace(tc, held, config);
1320
+ }
1321
+ catch {
1322
+ // The engine refused the old rows: the record still says what was meant, and the next run lands it.
1323
+ }
1324
+ }
1325
+ restoreWrunHeatmapLedger(tc, overlayId, snapshot.ledger);
1326
+ restoreWrunBatchedLedger(tc, overlayId, snapshot.batchedLedger);
1327
+ paintAfterMount(tc);
1328
+ }
1329
+ /**
1330
+ * Prepare a mounted heatmap child's landing of `rows` inside `historyWindow` (both ends inclusive, epoch ms):
1331
+ * the C6 seam a prefix run lands its heatmap children through, as an asynchronous prepare and a synchronous
1332
+ * commit under the run's own lock. Every await is here: the chart the index names, the child's packs, the
1333
+ * pause lookup. Then, with no await, the rows merge into the rows the mount record holds (the rows outside the
1334
+ * window kept by identity, C3), the cell budget is planned from the merged rows and the ledger as it stands
1335
+ * (no whole-run skip: the budget only cuts the oldest bars), and the mounted scale is kept: a windowed landing
1336
+ * never samples colour bounds, a full run does. Rejects with `WrunStaleLandingError` when the mount holds no
1337
+ * such child to land into, and with the pack error when a pack failed.
1338
+ *
1339
+ * A batched child (WRUN-BATCHED-MARKS: marks, spans, rays) lands through the same seam (round-2 fold 10:
1340
+ * the row-backed canvas kinds prepend rows): its merged rows are budgeted on the batched ledger, each pass
1341
+ * row that replaces a mounted bar charged its old copy too, and the ring logs `wrun-batched-prefix-landed`;
1342
+ * a run's heatmap and batched landings commit as one transaction. `prepareWrunChildWindowLanding` names
1343
+ * the generalized seam.
1344
+ */
1345
+ export async function prepareWrunHeatmapWindowLanding(input) {
1346
+ const { chartIndex, indicatorId, childId } = input;
1347
+ const span = { fromMs: input.historyWindow.fromTs, toMs: input.historyWindow.toTs };
1348
+ // A typed row (the live book lane's) would draw no column: the engine reads plain rows only.
1349
+ const pass = input.rows.map(wrunPlainCanvasRow);
1350
+ const { getTC } = await wrunChartHostEnv().chart.loadTitanCharts();
1351
+ const chartAt = () => getTC(chartIndex);
1352
+ const { record: before } = windowLandingTarget(chartAt(), indicatorId, childId);
1353
+ const packs = await wrunChartHostEnv().chart.ensurePacks({ plotTypes: [before.config.plot] });
1354
+ if (packs.failed.length > 0)
1355
+ throw new Error(`wrun child overlay packs unavailable: ${packs.failed.join(', ')}`);
1356
+ const paused = await wrunMountPauseReader();
1357
+ // The awaits are done: the plan reads the mount as it stands now, and the commit holds it to that.
1358
+ const { tc, state, record } = windowLandingTarget(chartAt(), indicatorId, childId);
1359
+ const token = state.token;
1360
+ const parent = state.parent;
1361
+ let plan = planHeatmapWindow(tc, indicatorId, record, pass, span);
1362
+ let counts = windowLandingCounts(plan);
1363
+ let settled;
1364
+ const member = { childId };
1365
+ const group = joinLandingGroup(tc, indicatorId, state, member);
1366
+ // Checks the landing against the mount it was prepared on, then lands it (merged again from the rows the
1367
+ // child holds now when they moved since the plan). Throws before any change when a check fails.
1368
+ const land = (landing) => {
1369
+ if (group.rolledBack)
1370
+ throw new WrunStaleLandingError(childId, 'rolled-back');
1371
+ if (chartAt() !== tc || tc.isDestroyed)
1372
+ throw new WrunStaleLandingError(childId, 'chart');
1373
+ if (chartChildren.get(tc)?.get(indicatorId) !== state || state.token !== token) {
1374
+ throw new WrunStaleLandingError(childId, 'mount');
1375
+ }
1376
+ if (state.parent !== parent || tc.metadata.find((meta) => meta.id === indicatorId) !== parent) {
1377
+ throw new WrunStaleLandingError(childId, 'parent');
1378
+ }
1379
+ const current = state.children.get(childId);
1380
+ if (!isWindowRecord(current) || !overlayPresent(tc, childId))
1381
+ throw new WrunStaleLandingError(childId, 'child');
1382
+ if (paused(chartIndex, indicatorId))
1383
+ throw new WrunStaleLandingError(childId, 'paused');
1384
+ const fresh = holdsPlannedRows(current, landing)
1385
+ ? landing
1386
+ : planHeatmapWindow(tc, indicatorId, current, landing.pass, landing.window);
1387
+ snapshotLandingGroup(group);
1388
+ const deferred = new Set([...group.pending].map((other) => other.childId));
1389
+ landHeatmapWindow(tc, indicatorId, state, current, fresh, deferred);
1390
+ return fresh;
1391
+ };
1392
+ return {
1393
+ childId,
1394
+ get landedRows() {
1395
+ return counts.landedRows;
1396
+ },
1397
+ get keptRows() {
1398
+ return counts.keptRows;
1399
+ },
1400
+ get trimmedRows() {
1401
+ return counts.trimmedRows;
1402
+ },
1403
+ commit() {
1404
+ const landing = plan;
1405
+ if (landing === undefined || settled !== undefined)
1406
+ throw new WrunStaleLandingError(childId, 'spent');
1407
+ plan = undefined;
1408
+ group.pending.delete(member);
1409
+ let landed;
1410
+ try {
1411
+ landed = land(landing);
1412
+ }
1413
+ catch (error) {
1414
+ settled = 'failed';
1415
+ rollBackLandingGroup(group);
1416
+ throw error;
1417
+ }
1418
+ settled = 'landed';
1419
+ group.landed += 1;
1420
+ // Every landing of the run is in: nothing is left to roll back.
1421
+ if (group.pending.size === 0)
1422
+ group.snapshot = undefined;
1423
+ counts = windowLandingCounts(landed);
1424
+ paintAfterMount(tc);
1425
+ if (wrunChartHostEnv().diagnostics.debugEnabled()) {
1426
+ const event = isWrunBatchedMarksKind(before.input.kind)
1427
+ ? 'wrun-batched-prefix-landed'
1428
+ : 'wrun-heatmap-prefix-landed';
1429
+ wrunChartHostEnv().diagnostics.debug(event, { chartIndex, indicatorId, childId, ...counts });
1430
+ }
1431
+ },
1432
+ discard() {
1433
+ if (plan === undefined || settled !== undefined)
1434
+ return;
1435
+ plan = undefined;
1436
+ settled = 'dropped';
1437
+ group.pending.delete(member);
1438
+ // A landing dropped while another of its run landed leaves the run partial: roll the landed ones back.
1439
+ if (group.landed > 0)
1440
+ rollBackLandingGroup(group);
1441
+ else if (group.pending.size === 0)
1442
+ group.snapshot = undefined;
1443
+ },
1444
+ };
1445
+ }
1446
+ /** The window landing of any row-backed canvas child (a heatmap or a batched child), the generalized name. */
1447
+ export const prepareWrunChildWindowLanding = prepareWrunHeatmapWindowLanding;
1448
+ /** True when a tick's canvas moved its row grid: the TPO's rows-per-period
1449
+ * cap coarsened (or relaxed) the row height on this tick, or the auto unit
1450
+ * under it moved. The engine reads the mounted `barHeight` and
1451
+ * `minimumBarHeight` for every period, so the newest row alone would draw
1452
+ * a forming period on the new grid beside closed periods on the old one,
1453
+ * under the old height: the tick takes the full rows and settings instead. */
1454
+ function canvasGridMoved(mounted, next) {
1455
+ return (mounted.settings.barHeight !== next.settings.barHeight ||
1456
+ mounted.settings.minimumBarHeight !== next.settings.minimumBarHeight);
1457
+ }
1458
+ /**
1459
+ * The same-frame signature of a frame child's engine config (levels, matrix, inset): its rows and
1460
+ * its settings as text, compared part by part, so an in-place refresh hands the engine only the
1461
+ * part that changed (refreshInsetChild). A mount signs every frame config it built before any of
1462
+ * them reaches the engine (applyChildren): titan keeps the row arrays it is handed and mutates them
1463
+ * in place, so a signature taken from a mounted config after the hand-off would read the engine's
1464
+ * rows, and a next input equal to those would wrongly read as unchanged. A config never signed
1465
+ * before its hand-off (a retranslate's rebuild, a restore after a failed run) reads as changed,
1466
+ * and so do settings holding a function (text cannot compare one).
1467
+ */
1468
+ function sameFrameSignature(config) {
1469
+ const seen = { fn: false };
1470
+ const settings = JSON.stringify(config.settings, (_key, value) => {
1471
+ if (typeof value === 'function')
1472
+ seen.fn = true;
1473
+ return value;
1474
+ });
1475
+ return { rows: JSON.stringify(config.data), settings: seen.fn ? undefined : settings };
1476
+ }
1477
+ /** The signature of every mounted frame config, taken before its hand-off (sameFrameSignature). */
1478
+ const frameSignatures = new WeakMap();
1479
+ /**
1480
+ * Refresh a mounted frame child in place from the config this run built: while it stays the same
1481
+ * engine overlay (kind, side, plot, interval, name) it never leaves the engine, and only the part
1482
+ * that changed reaches it, through the engine's own doors: `updateSettings` (it bumps the docked
1483
+ * revision the renderers re-read; the keys the mounted config set and this one dropped leave the
1484
+ * engine's settings first, as in the canvas refresh) and `updateData` (it swaps the rows; the
1485
+ * engine's own row diff decides how much to repaint). An unchanged frame costs the engine
1486
+ * nothing. The inset is the bare case (it draws on its own pane); levels and matrices add their
1487
+ * pane rule and extras on top (refreshLevelsChild, refreshMatrixChild). False when the child
1488
+ * cannot stay (another overlay, an engine without both doors, a child the engine no longer
1489
+ * holds): the caller retires and re-adds it, as before.
1490
+ */
1491
+ function refreshInsetChild(tc, mounted, next) {
1492
+ const was = mounted.config;
1493
+ const is = next.config;
1494
+ if (next.input.kind !== mounted.input.kind ||
1495
+ is.type !== was.type ||
1496
+ is.plot !== was.plot ||
1497
+ is.interval !== was.interval ||
1498
+ is.name !== was.name) {
1499
+ return false;
1500
+ }
1501
+ if (typeof tc.updateData !== 'function' || typeof tc.updateSettings !== 'function')
1502
+ return false;
1503
+ const meta = tc.metadata.find((candidate) => candidate.id === is.id);
1504
+ if (!meta)
1505
+ return false;
1506
+ const before = frameSignatures.get(was);
1507
+ const after = frameSignatures.get(is);
1508
+ const same = (part) => {
1509
+ const signed = before?.[part];
1510
+ return signed !== undefined && signed === after?.[part];
1511
+ };
1512
+ if (!same('settings')) {
1513
+ const settings = (meta.settings ??= {});
1514
+ for (const key of Object.keys(was.settings)) {
1515
+ if (!(key in is.settings))
1516
+ delete settings[key];
1517
+ }
1518
+ void tc.updateSettings(is.id, { ...is.settings });
1519
+ }
1520
+ if (!same('rows'))
1521
+ tc.updateData(is.id, is.data, { shouldResetRange: false });
1522
+ return true;
1523
+ }
1524
+ /** A mounted levels child refreshed in place (refreshInsetChild) while it docks on the same pane:
1525
+ * the one `pane_id` names (a lower pane, DL-lower-pane), else the price pane; one that moved pane
1526
+ * is retired and re-added. Its hover rows follow this run's, resolved against the palette the way
1527
+ * installChild registers them (none once the run turned hover off). */
1528
+ function refreshLevelsChild(tc, mounted, next, theme) {
1529
+ if (next.input.kind !== 'levels' || next.config.settings.pane_id !== mounted.config.settings.pane_id)
1530
+ return false;
1531
+ if (!refreshInsetChild(tc, mounted, next))
1532
+ return false;
1533
+ if (next.input.hover !== undefined)
1534
+ rememberWrunLevelsHoverRows(next.config.id, next.input.hover, theme);
1535
+ else
1536
+ forgetWrunLevelsHoverRows(next.config.id);
1537
+ return true;
1538
+ }
1539
+ /** A mounted matrix refreshed in place (refreshInsetChild) while it stays on the same surface: the
1540
+ * price pane, or the side strip the engine plans apart (`dock: "side"`, MX-side-panel); one moving
1541
+ * between them is retired and re-added. Its hover readout was registered when its config was
1542
+ * built (wrunCanvasChildConfig). */
1543
+ function refreshMatrixChild(tc, mounted, next) {
1544
+ const sideStrip = ({ settings }) => settings.dock === 'side' || settings.sideDock === true;
1545
+ if (next.input.kind !== 'matrix' || sideStrip(next.config) !== sideStrip(mounted.config))
1546
+ return false;
1547
+ return refreshInsetChild(tc, mounted, next);
1548
+ }
1549
+ /** The owner's first time pane (C6): the parent itself when it homes
1550
+ * offchart (a lower-only package), else the first series child that mounts
1551
+ * below the chart (a pane pinned over the candles carves nothing); undefined
1552
+ * when the Indicator has none. */
1553
+ function ownerTimePaneId(parent, overlayId, children) {
1554
+ if (parent.type === 'offchart')
1555
+ return overlayId;
1556
+ const lower = children.find((child) => child.kind === 'series' && child.result.pane?.place !== 'price');
1557
+ return lower === undefined ? undefined : wrunSeriesChildId(overlayId, lower.name);
1558
+ }
1559
+ /** The run's children in mount order (C6): the panels first, then today's
1560
+ * order (series, levels, canvases, insets), each group as the run listed
1561
+ * it. Decided here, never in the run result, so the run golden's
1562
+ * `childOverlays` keeps its order. */
1563
+ function panelsFirst(children) {
1564
+ return [...children.filter((child) => child.kind === 'panel'), ...children.filter((child) => child.kind !== 'panel')];
1565
+ }
1566
+ /** The Sensitivity a heatmap draws with: the drag value a slider holds, else
1567
+ * the saved row on the parent's engine settings (read like the window's
1568
+ * saved split); undefined draws the author's bounds. */
1569
+ function heatmapSensitivityOf(previews, parent, name) {
1570
+ return wrunHeatmapSensitivityValue(previews?.get(name)) ?? wrunHeatmapSensitivitySetting(parent.settings, name);
1571
+ }
1572
+ /** The context every child config of one Indicator is built from: the
1573
+ * chart's palette, the user's theme name and the display timezone read
1574
+ * now, so a retranslate builds against the current ones; the owner's time
1575
+ * pane from the run's (or the mounted) children; each heatmap's Sensitivity
1576
+ * (a held drag value, else the parent's saved row) read when its config is
1577
+ * built; the Indicator's kept label formatters. */
1578
+ function mountContext(tc, overlayId, parent, children, priceDigits, chartHeightPx, windowCell, planned, previews, formatters) {
1579
+ return {
1580
+ tc,
1581
+ overlayId,
1582
+ interval: parent.interval ?? tc.metadata[0]?.interval ?? 1,
1583
+ chartHeightPx,
1584
+ parentName: parent.name,
1585
+ parentOffchart: parent.type === 'offchart',
1586
+ priceDigits,
1587
+ theme: wrunColorThemeOf(tc),
1588
+ themeMode: userThemeMode(),
1589
+ timezoneOffsetMs: displayTimezoneOffsetMs(),
1590
+ windowCell,
1591
+ planned,
1592
+ anchorPaneId: ownerTimePaneId(parent, overlayId, children),
1593
+ heatmapSensitivity: (name) => heatmapSensitivityOf(previews(), parent, name),
1594
+ formatters,
1595
+ };
1596
+ }
1597
+ /** Mount a run snapshot after every required pack has settled.
1598
+ * The parent remains the canonical numeric-output container. A panel child
1599
+ * the run still declares in the same pane takes the new rows in place; one
1600
+ * whose pane changed (side, species, axis, chrome, carved height) or that
1601
+ * the run dropped is replaced or removed. A heatmap or profile that stays
1602
+ * the same canvas, and an inset that stays the same strip (sameInset), takes
1603
+ * the run's rows in place too; a levels or matrix child in the same pane
1604
+ * and kind refreshes in place when its frame signature changed (one that
1605
+ * moved pane or kind is replaced). A tick
1606
+ * without frames touches only the row-backed kinds: an inset takes its rows
1607
+ * in place (a moved strip is replaced, one the tick dropped removed),
1608
+ * heatmaps and profiles their newest row (every row from `canvasRowsFromTs`
1609
+ * on when the tick added bars; all their rows and settings when
1610
+ * the row grid moved), and the series child is refreshed in place; a series
1611
+ * child is never removed while the run still declares it in the same pane (a
1612
+ * pane moved onto the price or given another height is re-carved). Every
1613
+ * child mounts with the parent's eye, a child the reader hid on its own row
1614
+ * hidden (syncChildVisibility). `priceDigits` is the chart's price
1615
+ * precision (OT29, X7): the panels' formatters and the lower pane's legend
1616
+ * print "price" values with it. A tick's heatmap tail (`tailOnly`) only
1617
+ * ever merges its rows into a mounted canvas. */
1618
+ export function mountWrunChildOverlays({ tc, overlayId, runResult, replaceFrames = true, swapCanvasRows, canvasRowsFromTs, historyWindow, projection, cell, priceDigits, onMainThreadMs, chartIndex, }) {
1619
+ if (runResult.failureReason !== undefined)
1620
+ return Promise.reject(new Error(runResult.failureReason));
1621
+ if (tc.isDestroyed)
1622
+ return Promise.resolve(false);
1623
+ const parent = tc.metadata.find((meta) => meta.id === overlayId);
1624
+ if (!parent)
1625
+ return Promise.resolve(false);
1626
+ let owners = chartChildren.get(tc);
1627
+ let state = owners?.get(overlayId);
1628
+ if (state && state.parent !== parent) {
1629
+ unmountWrunChildOverlays(tc, overlayId);
1630
+ state = undefined;
1631
+ }
1632
+ const children = (runResult.childOverlays ?? []).filter((child) => replaceFrames || ROW_BACKED_KINDS.has(child.kind));
1633
+ if (!state && children.length === 0)
1634
+ return Promise.resolve(true);
1635
+ if (!replaceFrames &&
1636
+ children.length === 0 &&
1637
+ ![...state.children.values()].some((child) => child.input.kind === 'inset'))
1638
+ return Promise.resolve(true);
1639
+ if (!owners) {
1640
+ owners = new Map();
1641
+ chartChildren.set(tc, owners);
1642
+ }
1643
+ if (!state) {
1644
+ state = { parent, token: Symbol(overlayId), children: new Map(), formatters: new Map() };
1645
+ owners.set(overlayId, state);
1646
+ state.unsubscribe = tc.on?.('objects', (event) => {
1647
+ // A `reset` names no overlay (titan's pane regroup, swap and order events carry no refs).
1648
+ if (!event.refs?.some((ref) => ref.id === overlayId))
1649
+ return;
1650
+ if (event.type === 'removed') {
1651
+ unmountWrunChildOverlays(tc, overlayId);
1652
+ return;
1653
+ }
1654
+ // The parent's eye (titan emits `updated` for the toggled overlay):
1655
+ // every child follows it, so a hidden Indicator leaves nothing behind.
1656
+ // An update that left the eye where it was (a settings save) moves no
1657
+ // child, so an eye the reader moved on a child's row stands.
1658
+ if (event.type !== 'updated')
1659
+ return;
1660
+ const live = chartChildren.get(tc)?.get(overlayId);
1661
+ if (live)
1662
+ syncChildVisibility(tc, parent, live);
1663
+ });
1664
+ }
1665
+ const current = state;
1666
+ const token = Symbol(overlayId);
1667
+ current.token = token;
1668
+ current.priceDigits = priceDigits;
1669
+ // A window (the parent carries the owner flag in its engine settings, or the
1670
+ // caller says so): the children mount at the plan's weights and the plan is
1671
+ // reconciled onto the mounted panes when the mount settles. A cell without
1672
+ // a flagged owner never enters that path: its configs are today's.
1673
+ const windowCell = cell?.window ?? isWrunWindowOwner(parent);
1674
+ current.chartHeightPx = cell?.canvasHeightPx ?? tc.canvasChartController?.canvasElement?.clientHeight;
1675
+ let planned;
1676
+ if (windowCell) {
1677
+ planned = cell?.planned;
1678
+ if (!planned) {
1679
+ const panes = windowPanesOfMount(parent, overlayId, children, replaceFrames ? [] : [...current.children.values()].map((mounted) => mounted.config));
1680
+ // The reader's saved split (the parent's settings carry it,
1681
+ // window-geometry.util) is the first paint when it names exactly these
1682
+ // panes: a reload mounts the children at the split with no flash of
1683
+ // the plan. Else the plan.
1684
+ const weights = savedWindowSplit(parent.settings, panes) ?? planWindowWeights(panes, current.chartHeightPx);
1685
+ planned = new Map(weights.map(({ id, gridHeight }) => [id, gridHeight]));
1686
+ }
1687
+ }
1688
+ current.windowCell = windowCell;
1689
+ current.planned = planned;
1690
+ const ctx = mountContext(tc, overlayId, parent, children, priceDigits, current.chartHeightPx, windowCell, planned, () => current.previews, current.formatters);
1691
+ // Panels mount ahead of the Indicator's time panes (C6), so a first mount
1692
+ // stacks them above the lower pane by order alone; the anchor keeps a
1693
+ // later or re-carved panel there.
1694
+ const entries = panelsFirst(children).map((child) => ({
1695
+ input: child,
1696
+ config: childConfig(child, ctx),
1697
+ }));
1698
+ const seriesResults = new Map(children.flatMap((child) => child.kind === 'series' ? [[wrunSeriesChildId(overlayId, child.name), child.result]] : []));
1699
+ const active = () => !tc.isDestroyed &&
1700
+ chartChildren.get(tc)?.get(overlayId) === current &&
1701
+ current.token === token &&
1702
+ tc.metadata.find((meta) => meta.id === overlayId) === parent;
1703
+ // A series child paints its result's plot kinds (markers, ranges, fills
1704
+ // and the rest ride packs the parent's mount usually already loaded).
1705
+ const plotTypesFor = (config) => {
1706
+ const result = seriesResults.get(config.id);
1707
+ const nested = result ? Object.values(result.outputs).map((output) => output.plotType) : [];
1708
+ return [
1709
+ config.plot,
1710
+ ...nested.filter((plotType, at) => plotType !== config.plot && nested.indexOf(plotType) === at),
1711
+ ];
1712
+ };
1713
+ // The children's application once their packs load: synchronous, the mount's own main-thread
1714
+ // work (the wait before it is not), timed whole inside this mount's continuation
1715
+ // (onMainThreadMs).
1716
+ let appliedMs;
1717
+ const applyChildren = (packs) => {
1718
+ if (!active())
1719
+ return false;
1720
+ // A batched child's pack is the engine gate's to judge (below): its failure refuses that child by
1721
+ // name and never the rest of the mount.
1722
+ const failed = [
1723
+ ...new Set(packs.flatMap((result, at) => (isBatchedChild(entries[at].input) ? [] : result.failed))),
1724
+ ];
1725
+ if (failed.length > 0) {
1726
+ syncCanvasReadouts(current.children, entries);
1727
+ throw new Error(`wrun child overlay packs unavailable: ${failed.join(', ')}`);
1728
+ }
1729
+ // The engine gate (WRUN-BATCHED-MARKS): every batched child is judged after its pack settled, and one
1730
+ // the chart cannot draw is refused by name (never silently: the Indicator's notice row names it, one
1731
+ // word for a pack that failed to load, another for an engine that needs a newer chart) and never
1732
+ // mounted; a mounted one of the same id leaves. The rest of the mount goes on. A child whose section
1733
+ // names a layout newer than this chart (`newer`: the build's gate over its declaration, or a record's
1734
+ // meta, WRUN-MARKS-CONTRACT F2) needs a newer chart whatever the engine holds.
1735
+ const refusals = [];
1736
+ const refused = new Map();
1737
+ entries.forEach((entry, at) => {
1738
+ if (!isBatchedChild(entry.input))
1739
+ return;
1740
+ // A layout refusal (its `reason`: the section's declaration, or a record in the retained history whose
1741
+ // meta packs a field this chart does not read) stands until a full build judges the child again
1742
+ // (WRUN-MARKS-CONTRACT F2, finding 5). A tick's tail copies only the rows the tick re-evaluated, so a
1743
+ // clean tail says nothing of the records before it: lifting the refusal there left the child neither
1744
+ // refused nor mounted, and the next tick rebuilt the whole history to refuse it again (a full copy
1745
+ // every other tick, the row flickering). The held refusal is the one published, so its row stays as is;
1746
+ // the tail mounts nothing (a tail never does). An engine gate refusal is judged again as before.
1747
+ const held = entry.config.tailOnly === true ? current.gateRefused?.get(entry.config.id) : undefined;
1748
+ if (held?.reason !== undefined) {
1749
+ refused.set(entry.config.id, held);
1750
+ refusals.push(held);
1751
+ forgetWrunCanvasReadout(entry.config.id);
1752
+ return;
1753
+ }
1754
+ const newer = entry.input.newer;
1755
+ const cause = newer !== undefined ? 'old-engine' : batchedGateCause(tc, entry.config.plot, packs[at]);
1756
+ if (cause === null)
1757
+ return;
1758
+ const refusal = {
1759
+ kind: entry.input.kind,
1760
+ name: entry.input.name,
1761
+ cause,
1762
+ ...(newer !== undefined ? { reason: newer } : {}),
1763
+ };
1764
+ refused.set(entry.config.id, refusal);
1765
+ refusals.push(refusal);
1766
+ forgetWrunCanvasReadout(entry.config.id);
1767
+ if (newer !== undefined && wrunChartHostEnv().diagnostics.debugEnabled()) {
1768
+ wrunChartHostEnv().diagnostics.debug('wrun-batched-layout-refused', {
1769
+ chartIndex,
1770
+ overlayId,
1771
+ childId: entry.config.id,
1772
+ reason: newer,
1773
+ });
1774
+ }
1775
+ });
1776
+ const applying = refused.size === 0 ? entries : entries.filter((entry) => !refused.has(entry.config.id));
1777
+ // Preserve the previous complete snapshot until all pack imports succeed.
1778
+ // An unmount or newer run during an import must not resurrect children.
1779
+ // A series child the run still declares in the same pane is preserved
1780
+ // in place (its result is re-applied below, never re-added); one the run
1781
+ // dropped goes with the frames.
1782
+ const previous = current.children;
1783
+ const nextById = new Map(applying.map((entry) => [entry.config.id, entry]));
1784
+ // Every frame config this run built is signed before any of it reaches the
1785
+ // engine (sameFrameSignature): the refresh below and the next run compare
1786
+ // against what was handed over, never against what the engine made of it.
1787
+ for (const { input, config } of applying) {
1788
+ if (input.kind === 'levels' || input.kind === 'matrix' || input.kind === 'inset') {
1789
+ frameSignatures.set(config, sameFrameSignature(config));
1790
+ }
1791
+ }
1792
+ const preserved = new Map([...previous].flatMap(([id, mounted]) => {
1793
+ const next = nextById.get(id);
1794
+ // An inset stays while the pass (a tick's or a run's) still declares
1795
+ // the same strip, and takes its rows in place below.
1796
+ if (mounted.input.kind === 'inset') {
1797
+ return next !== undefined && overlayPresent(tc, id) && sameInset(mounted.config, next.config)
1798
+ ? [[id, mounted]]
1799
+ : [];
1800
+ }
1801
+ // A tick: frame-backed children (panels, levels, matrices) stay as
1802
+ // mounted, row-backed canvases stay and take the tick's rows, the
1803
+ // series child is re-applied (insets were decided above).
1804
+ // A batched child the engine gate refused leaves, on a tick too.
1805
+ if (refused.has(id))
1806
+ return [];
1807
+ if (!replaceFrames)
1808
+ return [[id, mounted]];
1809
+ if (next === undefined || !overlayPresent(tc, id))
1810
+ return [];
1811
+ switch (mounted.input.kind) {
1812
+ case 'series':
1813
+ case 'panel':
1814
+ return samePane(mounted.config, next.config, windowCell) ? [[id, mounted]] : [];
1815
+ case 'heatmap':
1816
+ case 'profile':
1817
+ case 'marks':
1818
+ case 'spans':
1819
+ case 'rays':
1820
+ return sameCanvas(mounted.config, next.config) ? [[id, mounted]] : [];
1821
+ // A frame that stays on its pane is refreshed in place right here and
1822
+ // kept as this run's child (the engine keeps one overlay throughout);
1823
+ // one that moved pane or kind is retired and re-added below.
1824
+ case 'levels':
1825
+ return refreshLevelsChild(tc, mounted, next, ctx.theme) ? [[id, next]] : [];
1826
+ case 'matrix':
1827
+ return refreshMatrixChild(tc, mounted, next) ? [[id, next]] : [];
1828
+ }
1829
+ }));
1830
+ current.children = new Map(preserved);
1831
+ // The configs were built before the pack await: a heatmap about to be
1832
+ // installed or refreshed re-picks its bounds from the Sensitivity it holds
1833
+ // NOW (a drag or a save during the await), never the one it was built with.
1834
+ const repickHeatmapBounds = ({ input, config }) => {
1835
+ if (input.kind !== 'heatmap' || input.scale === undefined)
1836
+ return;
1837
+ const bounds = wrunHeatmapSensitivityBounds(input, heatmapSensitivityOf(current.previews, parent, input.name));
1838
+ config.settings.min = bounds.min;
1839
+ config.settings.max = bounds.max;
1840
+ };
1841
+ // The children this pass adds to the engine (each comes back visible).
1842
+ const installed = [];
1843
+ try {
1844
+ for (const [id, mounted] of previous) {
1845
+ if (!preserved.has(id))
1846
+ retireChild(tc, id, mounted.input.kind, nextById.has(id));
1847
+ }
1848
+ for (const entry of applying) {
1849
+ if (!active())
1850
+ return false;
1851
+ const { config, input } = entry;
1852
+ const id = config.id;
1853
+ const mounted = preserved.has(id) && overlayPresent(tc, id);
1854
+ if (config.tailOnly === true) {
1855
+ // A tick's heatmap tail (the newest rows, no colour scale): its
1856
+ // newest row (every row from `canvasRowsFromTs` on, a tick that
1857
+ // added bars) merges into a mounted canvas, on a tick with frames
1858
+ // too, and that is all. It never mounts a canvas or swaps rows in
1859
+ // (a tail would replace the history), and the full run's record
1860
+ // stays, so a retranslate or a Sensitivity re-pick works from the
1861
+ // full rows, bounds and sample (the engine keeps that record's row
1862
+ // array and merges live rows into it). An unmounted one waits for
1863
+ // the next full run. A batched child's tail (every row the tick
1864
+ // re-evaluated) merges row by row the same way (mergeBatchedChangedRows).
1865
+ const stayed = mounted ? preserved.get(id) : undefined;
1866
+ if (isBatchedRecord(stayed))
1867
+ mergeBatchedChangedRows(tc, stayed, config);
1868
+ else if (mounted)
1869
+ liveUpdateCanvasChild(tc, config, canvasRowsFromTs);
1870
+ else
1871
+ forgetWrunCanvasReadout(id);
1872
+ }
1873
+ else if (!mounted) {
1874
+ repickHeatmapBounds(entry);
1875
+ current.children.set(id, entry);
1876
+ budgetHeatmapChild(tc, overlayId, entry);
1877
+ budgetBatchedChild(tc, overlayId, entry);
1878
+ installChild(tc, entry, ctx.theme);
1879
+ installed.push(id);
1880
+ }
1881
+ else if (isBatchedChild(input)) {
1882
+ // A batched child that stayed the same canvas: a windowed run lands inside its history window
1883
+ // (the rows outside it kept, the budget planned over the merged rows); a run (or the hosted
1884
+ // swap, or a pass whose rows no longer overlap the mounted ones) replaces its rows in place,
1885
+ // under the hard allowance; a frameless pass that built the whole window (a tick while a
1886
+ // sibling held no rows) merges only the rows it changed, row by row.
1887
+ const stayed = preserved.get(id);
1888
+ const mountedConfig = stayed.config;
1889
+ if (historyWindow !== undefined &&
1890
+ swapCanvasRows !== true &&
1891
+ isBatchedRecord(stayed) &&
1892
+ mountedConfig.data.length > 0) {
1893
+ landHeatmapWindow(tc, overlayId, current, stayed, planHeatmapWindow(tc, overlayId, stayed, config.data, historyWindow));
1894
+ }
1895
+ else if (replaceFrames || swapCanvasRows === true || !sameDataWindow(mountedConfig, config)) {
1896
+ budgetBatchedChild(tc, overlayId, entry);
1897
+ refreshChildInPlace(tc, mountedConfig, config);
1898
+ current.children.set(id, entry);
1899
+ }
1900
+ else if (isBatchedRecord(stayed)) {
1901
+ mergeBatchedChangedRows(tc, stayed, config);
1902
+ keepHeatmapRows(entry, stayed.config.data);
1903
+ current.children.set(id, entry);
1904
+ }
1905
+ }
1906
+ else if (input.kind === 'panel') {
1907
+ if (replaceFrames) {
1908
+ refreshPanelChild(tc, preserved.get(id).config, config);
1909
+ current.children.set(id, entry);
1910
+ }
1911
+ }
1912
+ else if (input.kind === 'heatmap' || input.kind === 'profile') {
1913
+ // A tick hands a canvas its newest row (every row from
1914
+ // `canvasRowsFromTs` on, a tick that added bars), unless its
1915
+ // dataset window moved (a developing profile's session rolled: the
1916
+ // builder returns the new session's rows only, and a merge would
1917
+ // leave the old session's rows under the new profile) or its row
1918
+ // grid moved (canvasGridMoved): then the rows and the settings swap.
1919
+ // A windowed run's heatmap merges inside its history window instead.
1920
+ const stayed = preserved.get(id);
1921
+ const mountedConfig = stayed.config;
1922
+ if (historyWindow !== undefined &&
1923
+ swapCanvasRows !== true &&
1924
+ isHeatmapRecord(stayed) &&
1925
+ mountedConfig.data.length > 0) {
1926
+ landHeatmapWindow(tc, overlayId, current, stayed, planHeatmapWindow(tc, overlayId, stayed, config.data, historyWindow));
1927
+ }
1928
+ else if (replaceFrames ||
1929
+ swapCanvasRows === true ||
1930
+ !sameDataWindow(mountedConfig, config) ||
1931
+ canvasGridMoved(mountedConfig, config)) {
1932
+ repickHeatmapBounds(entry);
1933
+ budgetHeatmapChild(tc, overlayId, entry);
1934
+ refreshChildInPlace(tc, mountedConfig, config);
1935
+ current.children.set(id, entry);
1936
+ }
1937
+ else {
1938
+ liveUpdateCanvasChild(tc, config, canvasRowsFromTs);
1939
+ // The entry stored holds the rows the engine holds after the merge (and any trim), never
1940
+ // the pass's own: the engine took only the rows it merged.
1941
+ const held = mountedHeatmapRecord(tc, id);
1942
+ if (held !== undefined)
1943
+ keepHeatmapRows(entry, held.config.data);
1944
+ current.children.set(id, entry);
1945
+ }
1946
+ }
1947
+ else if (input.kind === 'inset') {
1948
+ // A strip that stayed takes the pass's rows and colours in place: by
1949
+ // signature (rows only when they changed, settings only when they
1950
+ // moved), else the whole-config refresh.
1951
+ const stayed = preserved.get(id);
1952
+ if (!refreshInsetChild(tc, stayed, entry))
1953
+ refreshChildInPlace(tc, stayed.config, config);
1954
+ current.children.set(id, entry);
1955
+ }
1956
+ const seriesResult = seriesResults.get(id);
1957
+ if (seriesResult !== undefined) {
1958
+ integrateSeriesChild(tc, id, seriesResult, mounted && !replaceFrames ? 'tick' : 'run', projection);
1959
+ }
1960
+ if (!active())
1961
+ return false;
1962
+ }
1963
+ }
1964
+ catch (error) {
1965
+ for (const [id, mounted] of current.children) {
1966
+ if (!preserved.has(id))
1967
+ retireChild(tc, id, mounted.input.kind, previous.has(id));
1968
+ }
1969
+ // A preserved child keeps the record of what the engine holds: the
1970
+ // run's input when this run already refreshed it in place.
1971
+ current.children = new Map([...current.children].filter(([id]) => preserved.has(id)));
1972
+ if (active()) {
1973
+ // The previous children come back through the door (their hover
1974
+ // rows and readouts with them), resolved against the current theme.
1975
+ for (const [id, mounted] of previous) {
1976
+ if (preserved.has(id))
1977
+ continue;
1978
+ const restored = { input: mounted.input, config: childConfig(mounted.input, ctx) };
1979
+ current.children.set(id, restored);
1980
+ installChild(tc, restored, ctx.theme);
1981
+ }
1982
+ syncCanvasReadouts(current.children, entries);
1983
+ }
1984
+ throw error;
1985
+ }
1986
+ // A kept label formatter goes with its child: one mounted again starts afresh.
1987
+ for (const id of current.formatters.keys()) {
1988
+ if (!current.children.has(id))
1989
+ current.formatters.delete(id);
1990
+ }
1991
+ // The engine gate's notice, on every pass that judged a batched child, and on a run after a pass that
1992
+ // refused one (a run that carries none clears its rows; a tick carrying none leaves them as they are;
1993
+ // an Indicator without batched children never publishes). Reconciled against the Indicator's rows in
1994
+ // the store on every such pass, never against a memo of the last publish (publishWrunPlotGateNotice
1995
+ // writes only when they differ): a clear of the Indicator's diagnostics (Resume, the editor's Clear
1996
+ // console) takes the rows off while the refusal holds, and the next pass puts them back.
1997
+ const judged = entries.some((entry) => isBatchedChild(entry.input));
1998
+ if (judged || (replaceFrames && (current.gateRefused?.size ?? 0) > 0)) {
1999
+ current.gateRefused = refused;
2000
+ wrunChartHostEnv().diagnostics.publishPlotGateNotice(tc, overlayId, refusals);
2001
+ }
2002
+ // The window's weights onto the panes that are mounted now (the engine
2003
+ // carves at addOverlay only and, with main hidden, splits evenly): the
2004
+ // one reconciliation the window host also runs, idempotent, and silent
2005
+ // while the candle pane is still visible.
2006
+ if (windowCell)
2007
+ reconcileWindowOwnerGeometry(tc, overlayId, current.chartHeightPx);
2008
+ // A child mounted while the Indicator is hidden starts hidden too, and so
2009
+ // does one the reader hid on its own row; a child that stayed keeps its eye.
2010
+ syncChildVisibility(tc, parent, current, installed);
2011
+ // One engine pass for the whole mount, after it (paintAfterMount).
2012
+ paintAfterMount(tc);
2013
+ return true;
2014
+ };
2015
+ current.pending = (async () => {
2016
+ const packs = await Promise.all(entries.map((entry) => wrunChartHostEnv().chart.ensurePacks({ plotTypes: plotTypesFor(entry.config) })));
2017
+ // The pack wait is an await: a pause that landed meanwhile holds this mount (the async commit
2018
+ // gate of the pause semantics); the retained children stay as they are.
2019
+ if (chartIndex !== undefined && (await wrunMountParentPaused(chartIndex, overlayId)))
2020
+ return false;
2021
+ const applyingSince = mountClockMs();
2022
+ try {
2023
+ return applyChildren(packs);
2024
+ }
2025
+ finally {
2026
+ // Stopped here, before this mount settles: a sibling mount that waited on the same packs
2027
+ // applies in its own continuation and never lands in this one's time.
2028
+ appliedMs = mountClockMs() - applyingSince;
2029
+ }
2030
+ })();
2031
+ if (onMainThreadMs !== undefined) {
2032
+ const report = () => {
2033
+ if (appliedMs !== undefined)
2034
+ onMainThreadMs(appliedMs);
2035
+ };
2036
+ void current.pending.then(report, report);
2037
+ }
2038
+ return current.pending;
2039
+ }
2040
+ /** One engine pass after a mount applied: a chart that can defer gets one request, folded with every
2041
+ * other this task makes on it, and the engine runs it on its frame (scheduleKScriptChartPaint). A chart
2042
+ * with neither deferred method keeps the synchronous pair inside the mount. */
2043
+ function paintAfterMount(tc) {
2044
+ const paint = tc;
2045
+ if (typeof paint.requestLiveRecompute === 'function' || typeof paint.requestProcessAndRender === 'function') {
2046
+ wrunChartHostEnv().chart.schedulePaint(paint);
2047
+ }
2048
+ else {
2049
+ tc.processData?.();
2050
+ tc.renderService?.renderOnce?.();
2051
+ }
2052
+ }
2053
+ /** The store is read through a dynamic import (the run util's pattern): this module is imported by
2054
+ * the store's own lanes, so a static import would close a cycle. A store that fails to load, or to
2055
+ * answer, reads as not paused. */
2056
+ async function wrunMountPauseReader() {
2057
+ try {
2058
+ const { useChartStore } = await wrunChartHostEnv().chart.loadChartStore();
2059
+ return (chartIndex, overlayId) => {
2060
+ try {
2061
+ return useChartStore().isKScriptOverlayPaused?.(chartIndex, overlayId) === true;
2062
+ }
2063
+ catch {
2064
+ return false;
2065
+ }
2066
+ };
2067
+ }
2068
+ catch {
2069
+ return () => false;
2070
+ }
2071
+ }
2072
+ async function wrunMountParentPaused(chartIndex, overlayId) {
2073
+ return (await wrunMountPauseReader())(chartIndex, overlayId);
2074
+ }
2075
+ function mountClockMs() {
2076
+ return typeof performance !== 'undefined' ? performance.now() : Date.now();
2077
+ }
2078
+ /** Re-resolve every mounted child of every Indicator on the chart against
2079
+ * the chart's current palette, theme name and display timezone, without a
2080
+ * rerun (X13; hosted runs follow too): a panel takes its retranslated rows
2081
+ * and settings in place (its pane keeps its place in the stack and the
2082
+ * height the run carved it at), a levels, inset or canvas child is rebuilt
2083
+ * from its unresolved input under the same id, in the chart's own order so
2084
+ * the rebuilt ones keep their stacking. The series child's colours ride
2085
+ * the adapter's own theme reguard. Called by the theme rerun when a packed
2086
+ * colour moved and by the timezone sync per chart. */
2087
+ export function retranslateWrunChildOverlays(tc) {
2088
+ const owners = chartChildren.get(tc);
2089
+ if (!owners || tc.isDestroyed)
2090
+ return;
2091
+ const ownerOf = new Map();
2092
+ for (const [overlayId, state] of owners) {
2093
+ const parent = tc.metadata.find((meta) => meta.id === overlayId);
2094
+ if (!parent || state.parent !== parent)
2095
+ continue;
2096
+ const owner = {
2097
+ state,
2098
+ ctx: mountContext(tc, overlayId, parent, [...state.children.values()].map((mounted) => mounted.input), state.priceDigits, state.chartHeightPx, state.windowCell ?? false, state.planned, () => state.previews, state.formatters),
2099
+ };
2100
+ for (const [id, mounted] of state.children) {
2101
+ if (mounted.input.kind !== 'series')
2102
+ ownerOf.set(id, owner);
2103
+ }
2104
+ }
2105
+ let moved = false;
2106
+ const rebuilt = new Map();
2107
+ for (const { id } of [...tc.metadata]) {
2108
+ const owner = ownerOf.get(id);
2109
+ const mounted = owner?.state.children.get(id);
2110
+ if (owner === undefined || mounted === undefined)
2111
+ continue;
2112
+ const next = { input: mounted.input, config: childConfig(mounted.input, owner.ctx) };
2113
+ if (mounted.input.kind === 'panel' && samePane(mounted.config, next.config, owner.state.windowCell ?? false)) {
2114
+ refreshPanelChild(tc, mounted.config, next.config);
2115
+ }
2116
+ else {
2117
+ removeChild(tc, id);
2118
+ budgetHeatmapChild(tc, owner.ctx.overlayId, next, 'rebuild');
2119
+ budgetBatchedChild(tc, owner.ctx.overlayId, next, 'rebuild');
2120
+ installChild(tc, next, owner.ctx.theme);
2121
+ rebuilt.set(owner.state, [...(rebuilt.get(owner.state) ?? []), id]);
2122
+ }
2123
+ owner.state.children.set(id, next);
2124
+ moved = true;
2125
+ }
2126
+ if (!moved)
2127
+ return;
2128
+ // A rebuilt child comes back through addOverlay visible: it takes its
2129
+ // Indicator's eye again (a hidden Indicator leaves nothing behind on a
2130
+ // theme or timezone switch either), hidden too when the reader hid it.
2131
+ // It also comes back with its own opacity and painting: a paused
2132
+ // Indicator's rebuilt heatmaps take the pause dim again, and a paint-cost
2133
+ // pause's suspension reaches its rebuilt canvases (once per owner, after
2134
+ // its rebuild).
2135
+ for (const { state, ctx } of new Set(ownerOf.values())) {
2136
+ syncChildVisibility(tc, state.parent, state, rebuilt.get(state) ?? []);
2137
+ if (rebuilt.has(state)) {
2138
+ reapplyWrunPauseDim(tc, ctx.overlayId);
2139
+ wrunChartHostEnv().chart.reapplyPausedOverlayPaint(tc, ctx.overlayId);
2140
+ }
2141
+ }
2142
+ tc.processData?.();
2143
+ tc.renderService?.renderOnce?.();
2144
+ }
2145
+ /**
2146
+ * Re-pick the colour bounds of an Indicator's mounted heatmaps for the
2147
+ * viewer's Sensitivity, with no run. With `preview` the named heatmap holds
2148
+ * the slider's drag value (ahead of the saved row, for every mount until a
2149
+ * commit); without one the call commits: held values drop and every heatmap
2150
+ * takes its saved row (`heatmap:<name>:sensitivity` on the parent's engine
2151
+ * settings; none draws the author's bounds). Only `min` and `max` move on the
2152
+ * engine meta: titan reads meta.settings on every draw and keys its colour
2153
+ * table on the bounds, so there is no row swap and no remount. The bounds go
2154
+ * through the engine's settings door (`updateSettings`), which also commits a
2155
+ * content mutation, so the 2D strip cache of the canvas fallback never blits
2156
+ * pixels drawn with the old bounds back on a live-edge sliver. The mounted
2157
+ * record keeps the config with the bounds it now holds, so the next run
2158
+ * diffs against them. Returns whether a bound moved.
2159
+ */
2160
+ export function rescaleWrunHeatmapChildren(tc, overlayId, preview) {
2161
+ const state = chartChildren.get(tc)?.get(overlayId);
2162
+ if (!state || tc.isDestroyed)
2163
+ return false;
2164
+ if (preview !== undefined)
2165
+ (state.previews ??= new Map()).set(preview.name, preview.value);
2166
+ else
2167
+ state.previews = undefined;
2168
+ const parent = tc.metadata.find((meta) => meta.id === overlayId);
2169
+ if (!parent || state.parent !== parent)
2170
+ return false;
2171
+ let moved = false;
2172
+ for (const [id, mounted] of state.children) {
2173
+ const input = mounted.input;
2174
+ if (input.kind !== 'heatmap' || input.scale === undefined)
2175
+ continue;
2176
+ if (preview !== undefined && input.name !== preview.name)
2177
+ continue;
2178
+ const meta = tc.metadata.find((candidate) => candidate.id === id);
2179
+ if (!meta)
2180
+ continue;
2181
+ const { min, max } = wrunHeatmapSensitivityBounds(input, heatmapSensitivityOf(state.previews, parent, input.name));
2182
+ const settings = (meta.settings ??= {});
2183
+ if (!Object.is(settings.min, min) || !Object.is(settings.max, max)) {
2184
+ moved = true;
2185
+ if (typeof tc.updateSettings === 'function')
2186
+ void tc.updateSettings(id, { min, max });
2187
+ else {
2188
+ settings.min = min;
2189
+ settings.max = max;
2190
+ }
2191
+ }
2192
+ state.children.set(id, {
2193
+ input,
2194
+ config: { ...mounted.config, settings: { ...mounted.config.settings, min, max } },
2195
+ });
2196
+ }
2197
+ // The settings door schedules its own paint; a chart without it repaints here.
2198
+ if (moved && typeof tc.updateSettings !== 'function')
2199
+ tc.renderService?.renderOnce?.();
2200
+ return moved;
2201
+ }
2202
+ /**
2203
+ * A replay cut of an Indicator's batched children (WRUN-BATCHED-MARKS, round-2 fold 9), synchronous with
2204
+ * the cut of the engine rows (wrun-replay-rows.util, which also tells the engine the rows moved in place so
2205
+ * a pack's cached geometry is read again): each mounted batched child's record (the input a retranslate
2206
+ * rebuilds from and the config) keeps the rows inside [fromTs, toTs] (fromTs NaN keeps every row through
2207
+ * toTs) and its cell ledger follows. A theme or timezone switch while the replay holds its reseed then
2208
+ * rebuilds the cut rows, never the rows the step took away. Returns the child ids whose records were cut.
2209
+ */
2210
+ export function cutWrunBatchedChildRecords(tc, overlayId, fromTs, toTs) {
2211
+ const state = chartChildren.get(tc)?.get(overlayId);
2212
+ if (!state || tc.isDestroyed)
2213
+ return [];
2214
+ const cut = [];
2215
+ for (const [id, record] of state.children) {
2216
+ if (!isBatchedRecord(record))
2217
+ continue;
2218
+ const rows = record.config.data;
2219
+ const kept = rows.filter((row) => {
2220
+ const ts = rowTs(row);
2221
+ return ts !== undefined && (!Number.isFinite(fromTs) || ts >= fromTs) && ts <= toTs;
2222
+ });
2223
+ if (kept.length === rows.length)
2224
+ continue;
2225
+ keepHeatmapRows(record, kept);
2226
+ noteWrunBatchedRowsCut(tc, overlayId, id, kept, wrunBatchedChargeOf(record.config.settings));
2227
+ cut.push(id);
2228
+ }
2229
+ return cut;
2230
+ }
2231
+ /** Full compute runs await the async work started by the synchronous
2232
+ * integration seam. A failed pack never becomes a successful full run. */
2233
+ export function awaitWrunChildOverlays(tc, overlayId) {
2234
+ return (chartChildren.get(tc)?.get(overlayId)?.pending ?? Promise.resolve(!tc.isDestroyed && overlayPresent(tc, overlayId)));
2235
+ }
2236
+ /** Explicit teardown is also used by the engine's post-removal object event. */
2237
+ export function unmountWrunChildOverlays(tc, overlayId) {
2238
+ const owners = chartChildren.get(tc);
2239
+ const state = owners?.get(overlayId);
2240
+ if (!state)
2241
+ return;
2242
+ owners?.delete(overlayId);
2243
+ state.token = Symbol(overlayId);
2244
+ state.unsubscribe?.();
2245
+ for (const [id, mounted] of state.children)
2246
+ retireChild(tc, id, mounted.input.kind, false);
2247
+ state.children.clear();
2248
+ }
2249
+ // The boot graph's door (wrun-panel-mount.lazy.ts): bound as this module evaluates, since it owns
2250
+ // the mounted children, so the timezone sync reaches them in its own turn whenever any exist.
2251
+ bindWrunPanelMountRuntime({ retranslateWrunChildOverlays, cutWrunBatchedChildRecords });