gloomberb 0.20.13 → 0.20.16

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 (275) hide show
  1. package/package.json +2 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +22 -4
  3. package/src/account/auth-dialog.tsx +22 -4
  4. package/src/account/auth-form.tsx +6 -1
  5. package/src/account/checkout-handoff.tsx +7 -14
  6. package/src/account/device-signin-dialog.tsx +35 -24
  7. package/src/api-client/crypto-markets.ts +10 -0
  8. package/src/api-client/errors.ts +3 -1
  9. package/src/api-client/index.ts +54 -0
  10. package/src/api-client/install-experiments.ts +8 -7
  11. package/src/api-client/money-markets.ts +7 -0
  12. package/src/api-client/paths.ts +2 -1
  13. package/src/api-client/product-waitlist.ts +63 -0
  14. package/src/api-client/request.ts +16 -4
  15. package/src/api-client/types/billing.ts +45 -0
  16. package/src/api-client/yearly-plan.ts +132 -0
  17. package/src/app/global-shortcuts.ts +5 -3
  18. package/src/app/pane-runtime/index.tsx +2 -2
  19. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  20. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  21. package/src/app/since-last-visit/keys.ts +26 -0
  22. package/src/app/since-last-visit/model.ts +266 -0
  23. package/src/app/since-last-visit/strip.tsx +193 -0
  24. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  25. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  26. package/src/app.tsx +15 -0
  27. package/src/architecture/floating-promise-allowlist.json +0 -1
  28. package/src/brokers/signed-in/sign-in-dialog.tsx +38 -38
  29. package/src/cli/commands/market.ts +103 -27
  30. package/src/cli/commands/overview.ts +18 -4
  31. package/src/cli/commands/system.ts +29 -1
  32. package/src/cli/commands/ticker.ts +12 -5
  33. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  34. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  35. package/src/cli/desktop-pane-shot-view.ts +3 -7
  36. package/src/cli/desktop-pane-shot.ts +26 -28
  37. package/src/cli/errors.ts +3 -1
  38. package/src/cli/freshness.ts +7 -2
  39. package/src/cli/glossary.ts +10 -5
  40. package/src/cli/help.ts +1 -0
  41. package/src/cli/helpers.ts +8 -16
  42. package/src/cli/history-export.ts +4 -0
  43. package/src/cli/history-rows.ts +24 -0
  44. package/src/cli/index.ts +4 -0
  45. package/src/cli/known-gaps.ts +2 -2
  46. package/src/cli/listing-arg.ts +79 -11
  47. package/src/cli/not-a-ticker.ts +4 -0
  48. package/src/cli/options.ts +29 -1
  49. package/src/cli/pane-functions/catalog.ts +70 -12
  50. package/src/cli/pane-functions/function-help.ts +1 -1
  51. package/src/cli/pane-functions/headless.ts +68 -3
  52. package/src/cli/pane-functions/index.ts +2 -2
  53. package/src/cli/pane-functions/options.ts +7 -0
  54. package/src/cli/pane-functions/resolver.ts +104 -15
  55. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  56. package/src/cli/report-tables.ts +20 -5
  57. package/src/cli/result.ts +22 -4
  58. package/src/cli/shot-temp-dir.ts +30 -0
  59. package/src/cli/suffixed-listing-rows.ts +11 -0
  60. package/src/cli/symbol-args.ts +5 -3
  61. package/src/cli/symbol-list.ts +23 -10
  62. package/src/cli/symbol-rows.ts +135 -3
  63. package/src/cli/treasury-yields.ts +15 -1
  64. package/src/components/chart/composite/composite-chart.tsx +3 -3
  65. package/src/components/chart/composite/format.ts +2 -1
  66. package/src/components/chart/composite/panel-surface/axis-markers.ts +133 -0
  67. package/src/components/chart/composite/panel-surface/level-labels.tsx +78 -0
  68. package/src/components/chart/composite/panel-surface/overlays.ts +108 -0
  69. package/src/components/chart/composite/panel-surface/pan-coast.ts +54 -0
  70. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +138 -0
  71. package/src/components/chart/composite/panel-surface/panel-levels.ts +47 -0
  72. package/src/components/chart/composite/panel-surface/plot-gestures.ts +403 -0
  73. package/src/components/chart/composite/panel-surface/plot-pointer.ts +65 -0
  74. package/src/components/chart/composite/panel-surface/plot-wheel.ts +102 -0
  75. package/src/components/chart/composite/panel-surface/pointer.ts +12 -0
  76. package/src/components/chart/composite/panel-surface/props.ts +79 -0
  77. package/src/components/chart/composite/panel-surface/tool-readout.ts +151 -0
  78. package/src/components/chart/composite/panel-surface/value-axis-gestures.ts +152 -0
  79. package/src/components/chart/composite/panel-surface.tsx +81 -1177
  80. package/src/components/command-bar/commands/collection-list.ts +1 -0
  81. package/src/components/command-bar/commands/direct/index.ts +31 -8
  82. package/src/components/command-bar/commands/registry.ts +7 -0
  83. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  84. package/src/components/command-bar/routes/root/results.ts +19 -2
  85. package/src/components/command-bar/routes/root/runtime.ts +3 -2
  86. package/src/components/command-bar/routes/root/selection.ts +3 -2
  87. package/src/components/command-bar/routes/root/shortcuts.ts +15 -0
  88. package/src/components/company-logo.tsx +10 -3
  89. package/src/components/data-table/sections.ts +6 -1
  90. package/src/components/layout/pane/title.ts +16 -6
  91. package/src/components/layout/shell/index.tsx +5 -1
  92. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  93. package/src/components/pane-settings-dialog/tui.tsx +6 -3
  94. package/src/components/pane-settings-dialog.tsx +2 -1
  95. package/src/components/pane-template-wizard.tsx +2 -0
  96. package/src/components/ticker/badge/format.ts +12 -3
  97. package/src/components/ticker/badge/index.tsx +9 -3
  98. package/src/components/ticker/list-table-view.tsx +119 -17
  99. package/src/components/ui/choice-dialog.tsx +1 -1
  100. package/src/components/ui/confirm-dialog.tsx +3 -2
  101. package/src/components/ui/data-table/display-columns.ts +16 -0
  102. package/src/components/ui/data-table/index.tsx +40 -9
  103. package/src/components/ui/data-table/types.ts +14 -0
  104. package/src/components/ui/frame.tsx +7 -3
  105. package/src/components/ui/icon.tsx +4 -2
  106. package/src/components/ui/list-view.tsx +8 -0
  107. package/src/components/ui/number-prompt-dialog.tsx +2 -1
  108. package/src/components/use-pane-notice-footer.tsx +3 -1
  109. package/src/core/state/app/layout-reducer.ts +3 -1
  110. package/src/core/state/app/layout.ts +2 -2
  111. package/src/data/config/layout.ts +14 -0
  112. package/src/data/config/store/normalize.ts +11 -1
  113. package/src/docs/snapshot.json +2 -2
  114. package/src/i18n/es.ts +39 -0
  115. package/src/i18n/ja.ts +39 -0
  116. package/src/i18n/ko.ts +39 -0
  117. package/src/i18n/zh-cn.ts +39 -0
  118. package/src/i18n/zh-tw.ts +39 -0
  119. package/src/layout/pane-follow.ts +141 -4
  120. package/src/layout/pane-layout-move.ts +10 -7
  121. package/src/layout/ticker-navigation.ts +13 -19
  122. package/src/layout/ticker-retarget.ts +3 -2
  123. package/src/market-data/market/format.ts +35 -1
  124. package/src/market-data/market/index-level.ts +19 -0
  125. package/src/market-data/quotes/contributions.ts +13 -0
  126. package/src/market-data/quotes/export-identity.ts +36 -1
  127. package/src/market-data/quotes/resolution.ts +16 -0
  128. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  129. package/src/plugins/builtin/account-management/model.ts +2 -0
  130. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  131. package/src/plugins/builtin/account-management/password-dialog.tsx +2 -2
  132. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  133. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  134. package/src/plugins/builtin/analytics/risk-client.ts +12 -2
  135. package/src/plugins/builtin/analytics/risk-headless.ts +66 -6
  136. package/src/plugins/builtin/analytics/risk-math.ts +23 -6
  137. package/src/plugins/builtin/analytics/risk-model.ts +20 -9
  138. package/src/plugins/builtin/analytics/risk-pane.tsx +2 -2
  139. package/src/plugins/builtin/awards/pane.tsx +6 -8
  140. package/src/plugins/builtin/changelog/index.tsx +6 -44
  141. package/src/plugins/builtin/changelog/versions.ts +17 -68
  142. package/src/plugins/builtin/chart-composer/catalog-inventory.ts +5 -2
  143. package/src/plugins/builtin/chart-composer/editor.tsx +1 -0
  144. package/src/plugins/builtin/chart-composer/pane.tsx +1 -1
  145. package/src/plugins/builtin/chart-composer/quick-add.tsx +4 -1
  146. package/src/plugins/builtin/chart-composer/series-catalog.ts +17 -1
  147. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  148. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  149. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  150. package/src/plugins/builtin/cloud/thesis/module.tsx +2 -0
  151. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +6 -2
  152. package/src/plugins/builtin/cpi/headless.ts +6 -1
  153. package/src/plugins/builtin/cpi/model.ts +17 -0
  154. package/src/plugins/builtin/cpi/pane.tsx +4 -2
  155. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  156. package/src/plugins/builtin/crypto-board/headless.ts +10 -2
  157. package/src/plugins/builtin/crypto-board/model.ts +89 -11
  158. package/src/plugins/builtin/crypto-board/pane.tsx +20 -5
  159. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  160. package/src/plugins/builtin/dividend-yield/client.ts +24 -2
  161. package/src/plugins/builtin/dividend-yield/headless.ts +4 -2
  162. package/src/plugins/builtin/dividend-yield/ranking.ts +2 -1
  163. package/src/plugins/builtin/dividend-yield/view.ts +5 -1
  164. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  165. package/src/plugins/builtin/earnings/board.tsx +36 -16
  166. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  167. package/src/plugins/builtin/earnings/history-table.ts +9 -1
  168. package/src/plugins/builtin/earnings/index.tsx +1 -1
  169. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  170. package/src/plugins/builtin/earnings-ripple/index.tsx +2 -0
  171. package/src/plugins/builtin/econ/calendar-model.ts +17 -1
  172. package/src/plugins/builtin/econ/fred-catalog.ts +33 -4
  173. package/src/plugins/builtin/econ-statistics/headless.ts +21 -0
  174. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  175. package/src/plugins/builtin/exposure/index.tsx +1 -1
  176. package/src/plugins/builtin/macro-day/headless.ts +21 -10
  177. package/src/plugins/builtin/macro-day/model.ts +42 -3
  178. package/src/plugins/builtin/macro-day/pane.tsx +26 -8
  179. package/src/plugins/builtin/macro-day/releases.ts +24 -1
  180. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  181. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  182. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  183. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  184. package/src/plugins/builtin/money-markets/client.ts +4 -1
  185. package/src/plugins/builtin/money-markets/headless.ts +15 -4
  186. package/src/plugins/builtin/money-markets/index.tsx +1 -1
  187. package/src/plugins/builtin/money-markets/pane.tsx +7 -1
  188. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  189. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  190. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -2
  191. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +61 -11
  192. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +11 -3
  193. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  194. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +178 -17
  195. package/src/plugins/builtin/portfolio-list/headless.ts +33 -6
  196. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  197. package/src/plugins/builtin/portfolio-list/pane/index.tsx +95 -18
  198. package/src/plugins/builtin/portfolio-list/pane/period-pnl.ts +24 -6
  199. package/src/plugins/builtin/portfolio-list/period-pnl.ts +16 -1
  200. package/src/plugins/builtin/portfolio-list/summary/index.tsx +4 -1
  201. package/src/plugins/builtin/portfolio-list/summary/totals.ts +6 -4
  202. package/src/plugins/builtin/portfolio-list/table.tsx +38 -16
  203. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  204. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  205. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  206. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  207. package/src/plugins/builtin/shared/cloud-upgrade.ts +4 -2
  208. package/src/plugins/builtin/shared/cpi-year-gap.ts +67 -0
  209. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  210. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  211. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  212. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +45 -2
  213. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  214. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  215. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  216. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  217. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  218. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  219. package/src/plugins/builtin/ticker-detail/headless.ts +280 -35
  220. package/src/plugins/builtin/ticker-detail/overview/components.tsx +4 -5
  221. package/src/plugins/builtin/ticker-detail/overview/model.ts +9 -2
  222. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +10 -2
  223. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  224. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  225. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  226. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  227. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  228. package/src/portfolio/collection-name.ts +2 -1
  229. package/src/portfolio/column-values.ts +34 -12
  230. package/src/portfolio/listed-symbol.ts +4 -2
  231. package/src/portfolio/period-pnl.ts +51 -1
  232. package/src/portfolio/suffixed-listings.ts +3 -1
  233. package/src/portfolio/watchlist-groups.ts +212 -0
  234. package/src/react/ticker-source.ts +3 -1
  235. package/src/renderers/dom/dialog-host.tsx +5 -5
  236. package/src/renderers/dom/styles.css +7 -0
  237. package/src/renderers/electrobun/view/remote/capability-invoker.ts +1 -1
  238. package/src/renderers/opentui/dialog-host.tsx +3 -4
  239. package/src/sources/gloomberb-cloud/normalizers.ts +5 -0
  240. package/src/sources/provider-router/history.ts +5 -2
  241. package/src/state/app/bootstrap.ts +11 -0
  242. package/src/state/app/context/index.tsx +6 -0
  243. package/src/sync/collections-contributor.ts +5 -2
  244. package/src/sync/config-merge.ts +10 -2
  245. package/src/sync/sanitize.ts +28 -0
  246. package/src/telemetry/usage-counts.ts +17 -0
  247. package/src/test-support/plugin-persistence.ts +12 -0
  248. package/src/tickers/company-name-listing.ts +4 -3
  249. package/src/tickers/company-name.ts +19 -1
  250. package/src/tickers/instrument-coverage.ts +27 -0
  251. package/src/tickers/search/home-listing.ts +38 -1
  252. package/src/tickers/search/index.ts +3 -2
  253. package/src/tickers/search/ranking.ts +21 -2
  254. package/src/time-series/base-series.ts +4 -0
  255. package/src/time-series/chart-seed.ts +1 -1
  256. package/src/time-series/financial-period-coverage.ts +4 -12
  257. package/src/time-series/parsed-history-cache.ts +1 -1
  258. package/src/time-series/resolve.ts +1 -1
  259. package/src/time-series/types.ts +5 -2
  260. package/src/time-series/use-chart-resolution.ts +6 -1
  261. package/src/types/config.ts +32 -0
  262. package/src/types/financials.ts +13 -0
  263. package/src/types/headless.ts +7 -0
  264. package/src/types/plugin-context.ts +5 -0
  265. package/src/types/ticker.ts +14 -0
  266. package/src/ui/ascii-font.ts +1 -4
  267. package/src/ui/dialog-stack.ts +17 -0
  268. package/src/ui/dialog.tsx +6 -2
  269. package/src/utils/async-deadline.ts +2 -2
  270. package/src/utils/crypto-pair.ts +9 -0
  271. package/src/utils/csv.ts +44 -5
  272. package/src/utils/exchanges.ts +13 -0
  273. package/src/utils/financial-statements.ts +60 -3
  274. package/src/utils/futures-generic.ts +17 -0
  275. package/src/utils/trailing-dividend.ts +13 -3
@@ -1,176 +1,33 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode, type RefObject } from "react";
1
+ import { useRef, useState } from "react";
2
2
  import {
3
3
  Box,
4
- ChartSurface,
5
4
  Text,
6
5
  useNativeRenderer,
7
6
  useUiCapabilities,
8
7
  type BoxRenderable,
9
- type ChartSurfaceProps,
10
8
  } from "../../../ui";
11
- import { colors as themeColors } from "../../../theme/colors";
12
- import { consumeChartMouseEvent, getGlobalMouseX, getLocalPlotPointer, type ChartMouseEvent } from "../core/pointer";
13
9
  import { Button } from "../../ui/button";
14
- import { clamp } from "../../../utils/math";
15
- import { panValueRange, resolveAxisDragSpanFactor, zoomValueRange, type CompositeValueRange } from "./value-scale";
16
10
  import { useStaticChartBitmapSize } from "./bitmap";
17
11
  import { useMeasuredCells } from "../../../ui/measured-cells";
18
- import { PriceAxisLabels, placeAxisTicks } from "./price-axis-labels";
19
- import { layoutLevelLabels, levelLabelStyle, levelLabelText } from "./level-labels";
20
- import { compositeAxisTagFormatter, formatCompositeCursorValue, type CompositeAxisValueFormatter } from "./format";
21
- import {
22
- compositeViewportPositions,
23
- resolveCompositeWheelPan,
24
- resolveCompositeWheelZoom,
25
- type CompositeNavigationFrame,
26
- type CompositeViewportRange,
27
- } from "./interactions";
28
- import {
29
- fitAxisLabels,
30
- hitTestLevel,
31
- levelGrabRatio,
32
- levelVectors,
33
- paintLevels,
34
- projectLevels,
35
- roundLevelValue,
36
- writeLevelText,
37
- type CompositeChartLevels,
38
- type ProjectedLevel,
39
- } from "./levels";
40
- import {
41
- buildChartToolVectors,
42
- countMeasureBars,
43
- drawChartToolOverlay,
44
- resolveChartToolKind,
45
- resolveMeasureAxisDomain,
46
- resolveMeasureDirection,
47
- hitTestDrawings,
48
- isDrawingTool,
49
- resolveDrawingFromDrag,
50
- resolveZoomBoxRange,
51
- shiftDrawing,
52
- summarizeMeasure,
53
- summarizeZoomRange,
54
- summarizeZoomSelection,
55
- type ChartDrawing,
56
- type ChartToolDrag,
57
- type ChartToolKind,
58
- type ChartToolSpan,
59
- } from "./tools";
60
- import { compositeRightOffsetRatio, unprojectCompositeTimestamp } from "./time-scale";
61
- import { resolveCompositeCursorDate, unprojectCompositeValue } from "./scene";
62
- import { compositeAxisTickLabels, renderCompositeAxisText, renderCompositePanelText } from "./text-renderer";
63
- import type { CompositeAxisSide, CompositeChartColors, CompositeChartScene, CompositePanelScene } from "./types";
12
+ import type { ChartToolDrag } from "./tools";
13
+ import { compositeRightOffsetRatio } from "./time-scale";
14
+ import type { CompositeAxisSide } from "./types";
64
15
  import { useCompositePanelBitmap } from "./panel-bitmap";
65
- import { nextDrawingId, nextLevelId } from "./drawing-store";
66
- import {
67
- AXIS_DOUBLE_PRESS_MS,
68
- PLOT_DOUBLE_CLICK_MS,
69
- COMPOSITE_PANEL_ROLE,
70
- isVerticalWheelDirection,
71
- manualValueAxes,
72
- PAN_COAST_START_SPEED,
73
- PAN_COAST_STOP_SPEED,
74
- panCoastStep,
75
- panReleaseVelocity,
76
- startPanGesture,
77
- releaseEditableFocus,
78
- type PanGesture,
79
- type PanSample,
80
- type PendingAxisWheel,
81
- type PendingWheel,
82
- type ValueAxisStart,
83
- } from "./panel-gestures";
84
- import { resolvePanelCrosshair, axisLabelRows, cursorAxisLabel, resolveSeriesCursorYRatio, resolveSeriesAxisTags } from "./panel-labels";
85
- import type { KeyboardToolDrag } from "./use-composite-chart-keyboard";
86
- import { createValueStore, useCursorScene, useValueStore, type CompositeCursorSource, type ValueStore } from "./cursor-source";
87
-
88
- const webFrame = globalThis as typeof globalThis & {
89
- requestAnimationFrame?: (callback: () => void) => number;
90
- cancelAnimationFrame?: (handle: number) => void;
91
- };
92
-
93
- const NO_LEVELS: readonly ProjectedLevel[] = [];
94
-
95
- /** The pointer's height in rows, to a fraction of one where the host reports it. */
96
- function pointerRow(event: ChartMouseEvent): number {
97
- return typeof event.preciseY === "number" ? event.preciseY : event.y;
98
- }
99
-
100
- interface CompositePanelSurfaceProps {
101
- panel: CompositePanelScene;
102
- /** The chart's scene, without its cursor: the crosshair comes from `cursor`. */
103
- scene: CompositeChartScene;
104
- cursor: CompositeCursorSource;
105
- plotWidth: number;
106
- leftAxisWidth: number;
107
- rightAxisWidth: number;
108
- axisGap: number;
109
- colors: CompositeChartColors;
110
- interactive: boolean;
111
- /** False keeps the hover cursor but removes pan, zoom, and the tools. */
112
- navigable: boolean;
113
- formatAxisValue?: CompositeAxisValueFormatter;
114
- remoteKind?: string;
115
- viewport: CompositeViewportRange;
116
- frame: CompositeNavigationFrame;
117
- armedTool: ChartToolKind | null;
118
- drawings: readonly ChartDrawing[];
119
- selectedDrawingId: string | null;
120
- drawColor: string;
121
- onDraw: (drawing: ChartDrawing) => void;
122
- onEditDrawing: (id: string, update: (drawing: ChartDrawing) => ChartDrawing) => void;
123
- onSelectDrawing: (id: string | null) => void;
124
- onActivate?: () => void;
125
- onCursorDateChange: (date: Date | null) => void;
126
- /** The cursor shown is another chart's, so the pointer's level is not part of it. */
127
- sharedCursor: boolean;
128
- /** Positive positions move toward older observations. A gesture supplies the frame and origin it started from. */
129
- onPanViewport: (
130
- deltaPositions: number,
131
- gesture?: { frame: CompositeNavigationFrame; from: CompositeViewportRange },
132
- ) => void;
133
- onZoomViewport: (zoomFactor: number, anchorRatio: number) => void;
134
- onSetViewport: (range: CompositeViewportRange) => void;
135
- onToolSpanChange: (span: ChartToolSpan | null) => void;
136
- /** A press on the plot started (true) or stopped (false) dragging: a pan, a tool, a drawing or a level. */
137
- onDragActiveChange?: (dragging: boolean) => void;
138
- /** The tool being placed from the keyboard, when it lives in this panel. */
139
- keyboardToolDrag: KeyboardToolDrag | null;
140
- /** A press on the plot: the pointer takes over from a keyboard placement. */
141
- onPointerPress: () => void;
142
- showTextFallback: boolean;
143
- /** Set while the owner is picking a bar: a press picks instead of panning. */
144
- onPickTime?: (date: Date) => void;
145
- /** Set while the owner is picking a price on the levels' series: a press picks the one under it. */
146
- onPickPrice?: (value: number) => void;
147
- /** The chart's levels when they draw on this panel. */
148
- levels: CompositeChartLevels | null;
149
- selectedLevelId: string | null;
150
- onSelectLevel: (id: string | null) => void;
151
- /** The value axes stretch and squeeze under a drag or the wheel, and a double click fits them again. */
152
- valueScalable: boolean;
153
- onSetValueScale: (panelId: string, side: CompositeAxisSide, key: string, range: CompositeValueRange) => void;
154
- onResetValueScale: (panelId: string) => void;
155
- /** A hairline on the line above this panel (desktop and web), as the chart's `panelRules` asks. */
156
- ruleAbove?: boolean;
157
- /** The line above this panel, which a drag moves (desktop and web): null for the top panel. */
158
- dividerAbove?: { active: boolean; gestures: PanelDividerGestures } | null;
159
- /** A double click on bare plot gives this panel the whole chart, or gives the others back. */
160
- onToggleMaximized?: () => void;
161
- }
162
-
163
- interface PanelDividerGestures {
164
- onMouseDown: (event: ChartMouseEvent) => void;
165
- onMouseDrag: (event: ChartMouseEvent) => void;
166
- onMouseUp: (event: ChartMouseEvent) => void;
167
- onMouseDragEnd: (event: ChartMouseEvent) => void;
168
- }
16
+ import { COMPOSITE_PANEL_ROLE } from "./panel-gestures";
17
+ import { createValueStore } from "./cursor-source";
18
+ import type { CompositePanelSurfaceProps } from "./panel-surface/props";
19
+ import { usePanelToolReadout } from "./panel-surface/tool-readout";
20
+ import { usePanelLevels } from "./panel-surface/panel-levels";
21
+ import { usePanelOverlays } from "./panel-surface/overlays";
22
+ import { usePanelAxisMarkers } from "./panel-surface/axis-markers";
23
+ import { usePlotPointer } from "./panel-surface/plot-pointer";
24
+ import { usePanCoast } from "./panel-surface/pan-coast";
25
+ import { usePlotGestures } from "./panel-surface/plot-gestures";
26
+ import { usePlotWheel } from "./panel-surface/plot-wheel";
27
+ import { useValueAxisGestures } from "./panel-surface/value-axis-gestures";
28
+ import { DESKTOP_PLOT_PICK_STYLE, DESKTOP_PLOT_STYLE, PanelPlotSurface, PanelValueAxis } from "./panel-surface/panel-cursor";
29
+ import { PanelLevelLabels } from "./panel-surface/level-labels";
169
30
 
170
- const DESKTOP_PLOT_STYLE = { flex: "1 1 0px", width: "auto", minWidth: 0, height: "auto", alignSelf: "stretch" } as const;
171
- /** Over a level that drags, or while one does: it moves up and down only. */
172
- const DESKTOP_PLOT_LEVEL_STYLE = { ...DESKTOP_PLOT_STYLE, cursor: "ns-resize" } as const;
173
- const DESKTOP_PLOT_PICK_STYLE = { ...DESKTOP_PLOT_STYLE, cursor: "crosshair" } as const;
174
31
  /** The grab strip over the line between two panels: the line and a few pixels either side of it. */
175
32
  const PANEL_DIVIDER_STYLE = {
176
33
  left: 0,
@@ -190,6 +47,12 @@ const PANEL_RULE_STYLE = {
190
47
  pointerEvents: "none",
191
48
  } as const;
192
49
 
50
+ /**
51
+ * One panel of a composite chart: its plot between its value axes, and what
52
+ * draws over them. The hooks in `panel-surface/` own its parts: the tool's
53
+ * readout, the levels, the overlays, the axis labels and tags, and the
54
+ * pointer's gestures on the plot and on the axes.
55
+ */
193
56
  export function CompositePanelSurface({
194
57
  panel,
195
58
  scene,
@@ -249,21 +112,6 @@ export function CompositePanelSurface({
249
112
  const keyboardDrag = toolDrag ? null : keyboardToolDrag;
250
113
  const activeDrag = toolDrag ?? keyboardDrag?.drag ?? null;
251
114
  const cursorView = { panel, cursor, pointerY, keyboardDrag, sharedCursor };
252
- // The last press on bare plot, for a double press where the host does not count clicks.
253
- const lastPlotPressRef = useRef<{ at: number; x: number; y: number } | null>(null);
254
- const dragRef = useRef<
255
- | PanGesture
256
- | {
257
- kind: "edit";
258
- drawingId: string;
259
- pointIndex: number | null;
260
- lastXRatio: number;
261
- lastYRatio: number;
262
- }
263
- | { kind: "level-move"; id: string }
264
- | ChartToolDrag
265
- | null
266
- >(null);
267
115
  // The plot's box as the browser lays it out: on the desktop a chart that
268
116
  // fills its box has it a fraction of a cell past its columns and rows. The
269
117
  // bitmap is drawn at that size, so it is 1:1 at rest, and the pointer is
@@ -276,846 +124,46 @@ export function CompositePanelSurface({
276
124
  const plotSpanFactor = 1 + compositeRightOffsetRatio(scene.timeScale);
277
125
  const bitmapSize = useStaticChartBitmapSize(plotSize.width, plotSize.height);
278
126
  const bitmap = useCompositePanelBitmap({ panel, bitmapSize, colors, isDesktopWeb, revealed: plotSize.revealed === true });
279
- const measureDomain = useMemo(() => resolveMeasureAxisDomain(panel), [panel]);
280
- const toolReadout = useMemo(() => {
281
- if (!activeDrag) return null;
282
- // A keyboard placement knows its data points exactly, even off screen; a
283
- // pointer drag reads them back from the plot.
284
- const startTime = keyboardDrag?.start.time
285
- ?? unprojectCompositeTimestamp(scene.timeScale, activeDrag.startXRatio);
286
- const endTime = keyboardDrag?.end.time
287
- ?? unprojectCompositeTimestamp(scene.timeScale, activeDrag.endXRatio);
288
- if (activeDrag.kind === "zoom") {
289
- return {
290
- direction: "up" as const,
291
- summary: keyboardDrag
292
- ? summarizeZoomRange(scene, startTime, endTime)
293
- : summarizeZoomSelection(scene, activeDrag),
294
- startTime,
295
- startValueLabel: null,
296
- endValueLabel: null,
297
- };
298
- }
299
- const startValue = keyboardDrag
300
- ? keyboardDrag.start.value
301
- : measureDomain ? unprojectCompositeValue(activeDrag.startYRatio, measureDomain) : null;
302
- const endValue = keyboardDrag
303
- ? keyboardDrag.end.value
304
- : measureDomain ? unprojectCompositeValue(activeDrag.endYRatio, measureDomain) : null;
305
- return {
306
- direction: resolveMeasureDirection(startValue, endValue),
307
- summary: summarizeMeasure({
308
- startValue,
309
- endValue,
310
- startTime,
311
- endTime,
312
- // Cross-market cursor stops include every listing's observations;
313
- // measured bars still follow the primary market's session scale.
314
- bars: countMeasureBars(scene.timeScale.kind === "market"
315
- ? scene.timeScale.anchors.map(({ timestamp }) => new Date(timestamp))
316
- : scene.dates, startTime, endTime),
317
- domain: measureDomain,
318
- }),
319
- startTime,
320
- startValueLabel: measureDomain && startValue !== null
321
- ? formatCompositeCursorValue(startValue, measureDomain)
322
- : null,
323
- endValueLabel: measureDomain && endValue !== null
324
- ? formatCompositeCursorValue(endValue, measureDomain)
325
- : null,
326
- };
327
- }, [activeDrag, keyboardDrag, measureDomain, scene]);
328
- const toolSummary = toolReadout?.summary ?? null;
329
- const toolStartTime = toolReadout?.startTime ?? null;
330
- const toolSpan = useMemo(() => {
331
- if (!activeDrag || !toolSummary || toolStartTime === null) return null;
332
- return {
333
- startXRatio: activeDrag.startXRatio,
334
- endXRatio: activeDrag.endXRatio,
335
- startTime: toolStartTime,
336
- color: activeDrag.kind === "zoom"
337
- ? colors.crosshair
338
- : toolReadout?.direction === "down" ? colors.negative : themeColors.positive,
339
- };
340
- }, [activeDrag, colors.crosshair, colors.negative, toolReadout?.direction, toolStartTime, toolSummary]);
341
- useEffect(() => {
342
- onToolSpanChange(toolSpan);
343
- }, [onToolSpanChange, toolSpan]);
344
- const panelDrawings = useMemo(
345
- () => drawings.filter((drawing) => drawing.panelId === panel.id),
346
- [drawings, panel.id],
347
- );
348
- // A dragged level moves here and is saved once, when the pointer lets go.
349
- const [levelDraft, setLevelDraft] = useState<{ id: string; value: number } | null>(null);
350
- const levelDraftRef = useRef(levelDraft);
351
- levelDraftRef.current = levelDraft;
352
- const levelDomain = useMemo(() => {
353
- const series = levels ? panel.series.find((entry) => entry.source.id === levels.seriesId) : undefined;
354
- return series ? panel.axes[series.source.axis] ?? null : null;
355
- }, [levels, panel]);
356
- const projectedLevels = useMemo(
357
- () => levels && levelDomain ? projectLevels(levels.items, levelDomain, levelDraft) : NO_LEVELS,
358
- [levelDomain, levelDraft, levels],
359
- );
360
- // Over a line a plain drag moves, and while one moves, the pointer says it
361
- // goes up and down. Where the pointer is, the plot reads (see `PanelPlotSurface`).
362
- const levelGrab = useMemo<LevelGrab>(() => {
363
- if (levelDraft) return true;
364
- if (!levels?.onEdit || onPickTime || onPickPrice || (armedTool && armedTool !== "level")) return false;
365
- return (cursorYRatio) => {
366
- const hit = hitTestLevel(projectedLevels, cursorYRatio, levelGrabRatio(panel.height));
367
- return !!hit?.editable && !!hit.draggable;
368
- };
369
- }, [armedTool, levelDraft, levels?.onEdit, onPickPrice, onPickTime, panel.height, projectedLevels]);
370
- // Drawings project through the time scale alone: the crosshair moving,
371
- // here or on a linked chart, must not repaint the plot, which the terminal's
372
- // kitty surface would upload whole again.
373
- const drawingProjection = useMemo(() => ({ timeScale: scene.timeScale }), [scene.timeScale]);
374
- const bitmapLayers = useMemo(() => {
375
- if (!bitmap) return null;
376
- // The desktop composites overlays as vectors, so the plot raster stays put
377
- // while a tool drags. Copying and reblending it per frame is what made the
378
- // ruler feel heavy.
379
- if (isDesktopWeb) return [bitmap];
380
- const base = !activeDrag && panelDrawings.length === 0 ? bitmap : drawChartToolOverlay(
381
- bitmap,
382
- activeDrag,
383
- {
384
- positive: themeColors.positive,
385
- negative: colors.negative,
386
- zoom: colors.crosshair,
387
- draw: drawColor,
388
- },
389
- toolReadout?.direction ?? "up",
390
- { scene: drawingProjection, panel, items: panelDrawings, selectedId: selectedDrawingId },
391
- );
392
- return [projectedLevels.length > 0 ? paintLevels(base, projectedLevels, selectedLevelId) : base];
393
- }, [
394
- activeDrag,
395
- bitmap,
396
- colors.crosshair,
397
- colors.negative,
398
- drawColor,
399
- drawingProjection,
400
- isDesktopWeb,
401
- panel,
402
- panelDrawings,
403
- projectedLevels,
404
- selectedDrawingId,
405
- selectedLevelId,
406
- toolReadout?.direction,
407
- ]);
408
- const vectors = useMemo<ChartSurfaceProps["vectors"]>(() => {
409
- if (!isDesktopWeb) return null;
410
- const shapes = [...levelVectors(projectedLevels, selectedLevelId), ...buildChartToolVectors({
411
- scene,
412
- panel,
413
- drawings: panelDrawings,
414
- selectedId: selectedDrawingId,
415
- drag: activeDrag,
416
- colors: {
417
- positive: themeColors.positive,
418
- negative: colors.negative,
419
- zoom: colors.crosshair,
420
- draw: drawColor,
421
- },
422
- direction: toolReadout?.direction ?? "up",
423
- })];
424
- return shapes.length > 0 ? shapes : null;
425
- }, [
426
- activeDrag,
427
- colors.crosshair,
428
- colors.negative,
429
- drawColor,
430
- isDesktopWeb,
431
- panel,
432
- panelDrawings,
433
- projectedLevels,
434
- scene,
435
- selectedDrawingId,
436
- selectedLevelId,
437
- toolReadout?.direction,
438
- ]);
439
- const leftAxisLabels = useMemo(
440
- () => axisLabelRows(
441
- renderCompositeAxisText(panel.axes.left, panel.height, leftAxisWidth, "left", formatAxisValue),
442
- ),
443
- [formatAxisValue, leftAxisWidth, panel],
444
- );
445
- const rightAxisLabels = useMemo(
446
- () => axisLabelRows(
447
- renderCompositeAxisText(panel.axes.right, panel.height, rightAxisWidth, "right", formatAxisValue),
448
- ),
449
- [formatAxisValue, panel, rightAxisWidth],
450
- );
451
- const leftAxisTicks = useMemo(
452
- () => compositeAxisTickLabels(panel.axes.left, leftAxisWidth, formatAxisValue),
453
- [formatAxisValue, leftAxisWidth, panel],
454
- );
455
- const rightAxisTicks = useMemo(
456
- () => compositeAxisTickLabels(panel.axes.right, rightAxisWidth, formatAxisValue),
457
- [formatAxisValue, panel, rightAxisWidth],
458
- );
459
- const measureReadout = useMemo(() => {
460
- if (!activeDrag || !toolReadout?.summary) return null;
461
- const text = toolReadout.summary;
462
- const centreX = (activeDrag.startXRatio + activeDrag.endXRatio) / 2;
463
- const centreY = activeDrag.kind === "zoom"
464
- ? 0.5
465
- : (activeDrag.startYRatio + activeDrag.endYRatio) / 2;
466
- const width = Math.min([...text].length, plotWidth);
467
- return {
468
- text,
469
- width,
470
- color: activeDrag.kind === "zoom"
471
- ? colors.text
472
- : toolReadout.direction === "down" ? colors.negative : themeColors.positive,
473
- left: leftAxisWidth + (leftAxisWidth ? axisGap : 0)
474
- + Math.max(0, Math.min(plotWidth - width, Math.round(centreX * plotWidth - width / 2))),
475
- top: Math.max(0, Math.min(panel.height - 1, Math.round(centreY * (panel.height - 1)))),
476
- };
477
- }, [
478
- activeDrag,
479
- axisGap,
480
- colors.negative,
481
- colors.text,
482
- leftAxisWidth,
483
- panel.height,
484
- plotWidth,
485
- toolReadout,
486
- ]);
487
- const axisMarkers = useMemo(() => {
488
- // The crosshair already marks the moving end, so the axes only need the
489
- // anchor the drag started from.
490
- if (!activeDrag || activeDrag.kind === "zoom" || !toolReadout?.startValueLabel) return null;
491
- return {
492
- side: null,
493
- // A keyboard anchor can leave the value range once the view moves.
494
- yRatio: Math.max(0, Math.min(1, activeDrag.startYRatio)),
495
- label: toolReadout.startValueLabel,
496
- color: toolReadout.direction === "down" ? colors.negative : themeColors.positive,
497
- };
498
- }, [activeDrag, colors.negative, toolReadout]);
499
- const lastPriceMarker = useMemo(() => {
500
- const marker = panel.lastPrice;
501
- const domain = marker ? panel.axes[marker.axis] : undefined;
502
- if (!marker || !domain) return null;
503
- return {
504
- side: marker.axis,
505
- yRatio: marker.yRatio,
506
- label: compositeAxisTagFormatter(formatAxisValue)(marker.value, domain),
507
- color: marker.color,
508
- };
509
- }, [formatAxisValue, panel]);
510
- const priorCloseMarker = useMemo(() => {
511
- const marker = panel.priorClose;
512
- const domain = marker ? panel.axes[marker.axis] : undefined;
513
- if (!marker || !domain) return null;
514
- return {
515
- side: marker.axis,
516
- yRatio: marker.yRatio,
517
- label: compositeAxisTagFormatter(formatAxisValue)(marker.value, domain),
518
- color: colors.textDim,
519
- };
520
- }, [colors.textDim, formatAxisValue, panel]);
521
- const levelMarkers = useMemo(() => levelDomain ? [...projectedLevels]
522
- // The picked level's label first, then alerts', when they compete for room.
523
- .sort((left, right) => Number(right.level.id === selectedLevelId) - Number(left.level.id === selectedLevelId)
524
- || Number(left.level.editable) - Number(right.level.editable))
525
- .map(({ level, yRatio }) => ({
526
- id: level.id,
527
- side: levelDomain.side,
528
- yRatio,
529
- label: level.axisLabel ?? compositeAxisTagFormatter(formatAxisValue)(level.value, levelDomain),
530
- color: level.color,
531
- prioritizeAxisLabel: level.prioritizeAxisLabel,
532
- })) : [], [formatAxisValue, levelDomain, projectedLevels, selectedLevelId]);
533
- const buildAxisMarkers = (side: "left" | "right") => {
534
- if (!panel.axes[side]) return undefined;
535
- const toAxisMarker = (marker: { id?: string; yRatio: number; label: string; color: string }) => ({
536
- id: marker.id,
537
- row: Math.round(marker.yRatio * Math.max(panel.height - 1, 0)),
538
- pixelY: marker.yRatio * Math.max(panel.height * cellHeightPx - 1, 0),
539
- label: marker.label,
540
- color: marker.color,
541
- });
542
- const onSide = <T extends { side: string | null }>(marker: T | null): marker is T => (
543
- !!marker && (marker.side === null || marker.side === side)
544
- );
545
- const fixed = [lastPriceMarker, axisMarkers].filter(onSide).map(toAxisMarker);
546
- // The prior close's label yields to every level's.
547
- const referenceLabels = levelMarkers.filter((marker) => marker.prioritizeAxisLabel && onSide(marker)).map(toAxisMarker);
548
- const levelLabels = [...levelMarkers.filter((marker) => !marker.prioritizeAxisLabel), priorCloseMarker].filter(onSide).map(toAxisMarker);
549
- // A label is a row tall, so close levels would stack into an unreadable
550
- // pile and hide the last price: each keeps its line, and only the labels
551
- // with a row to themselves show. Desktop badges sit between rows.
552
- const grid = fractionalViewport
553
- ? placeAxisTicks({ ticks: side === "left" ? leftAxisTicks : rightAxisTicks, height: panel.height, cellHeightPx }).map((tick) => ({
554
- ...toAxisMarker({ yRatio: tick.ratio, label: tick.label, color: colors.textDim }),
555
- pixelY: tick.topPercent / 100 * Math.max(panel.height * cellHeightPx - 1, 1),
556
- }))
557
- : [...(side === "left" ? leftAxisLabels : rightAxisLabels)].map(([row, label]) => ({ id: undefined, row, pixelY: row * cellHeightPx, label, color: colors.textDim }));
558
- const rowOf = (marker: ReturnType<typeof toAxisMarker>) => fractionalViewport ? marker.pixelY / cellHeightPx : marker.row;
559
- // Named guides are part of the chart's readout: ordinary ticks yield to
560
- // them, while a live price or cursor still keeps its place.
561
- const references = fitAxisLabels(referenceLabels, fixed, rowOf);
562
- const markers = [
563
- ...references,
564
- ...fitAxisLabels(levelLabels, [...references, ...fixed, ...grid], rowOf),
565
- ...fixed,
566
- ];
567
- return markers.length > 0 ? markers : undefined;
568
- };
569
- const leftAxisMarkers = buildAxisMarkers("left");
570
- const rightAxisMarkers = buildAxisMarkers("right");
571
-
572
- /** Where the pointer is over the plot, in the scene's columns and rows. */
573
- const plotPointer = useCallback((event: ChartMouseEvent) => {
574
- const pointer = getLocalPlotPointer(event, plotRef.current as unknown as Parameters<typeof getLocalPlotPointer>[1], renderer);
575
- if (!pointer || (plotSize.width === plotWidth && plotSize.height === panel.height)) return pointer;
576
- return {
577
- ...pointer,
578
- cellX: plotSize.width > 0 ? pointer.cellX * (plotWidth / plotSize.width) : pointer.cellX,
579
- cellY: plotSize.height > 0 ? pointer.cellY * (panel.height / plotSize.height) : pointer.cellY,
580
- };
581
- }, [panel.height, plotSize.height, plotSize.width, plotWidth, renderer]);
582
- const pointerRatios = useCallback((event: ChartMouseEvent) => {
583
- const pointer = plotPointer(event);
584
- if (!pointer) return null;
585
- return {
586
- xRatio: plotWidth <= 1 ? 0 : Math.max(0, Math.min(1, pointer.cellX / (plotWidth - 1))),
587
- yRatio: panel.height <= 1 ? 0.5 : Math.max(0, Math.min(1, pointer.cellY / (panel.height - 1))),
588
- };
589
- }, [panel.height, plotPointer, plotWidth]);
590
- const updateCursor = useCallback((event: ChartMouseEvent): boolean => {
591
- const pointer = plotPointer(event);
592
- if (!pointer) return false;
593
- const nextDate = resolveCompositeCursorDate(scene, pointer.cellX);
594
- if (!nextDate) return false;
595
- const nextYRatio = panel.height <= 1
596
- ? 0.5
597
- : Math.max(0, Math.min(1, pointer.cellY / (panel.height - 1)));
598
- pointerY.set(nextYRatio);
599
- onCursorDateChange(nextDate);
600
- consumeChartMouseEvent(event);
601
- return true;
602
- }, [onCursorDateChange, panel.height, plotPointer, pointerY, scene]);
603
- const clearCursor = useCallback(() => {
604
- pointerY.set(null);
605
- onCursorDateChange(null);
606
- }, [onCursorDateChange, pointerY]);
607
- const startDrag = useCallback((event: ChartMouseEvent) => {
608
- onActivate?.();
609
- onPointerPress();
610
- // The plot consumes the press, so the browser never moves focus off a text
611
- // field for us. Hand it back, but only for a press that truly landed here:
612
- // a dialog over the plot must keep the focus it just took.
613
- if (isDesktopWeb) releaseEditableFocus(event);
614
- consumeChartMouseEvent(event);
615
- if (onPickTime) {
616
- const pointer = plotPointer(event);
617
- const date = pointer ? resolveCompositeCursorDate(scene, pointer.cellX) : null;
618
- if (date) onPickTime(date);
619
- return;
620
- }
621
- if (onPickPrice) {
622
- // Only the levels' own panel has their prices; a press elsewhere picks nothing.
623
- const ratios = pointerRatios(event);
624
- const value = ratios && levelDomain ? unprojectCompositeValue(ratios.yRatio, levelDomain) : null;
625
- if (value !== null && levelDomain) onPickPrice(roundLevelValue(value, levelDomain));
626
- return;
627
- }
628
- // A keyboard-armed tool covers terminals that never forward modifier drags.
629
- const tool = resolveChartToolKind(event.modifiers) ?? armedTool;
630
- if (tool === "level" && levels?.onEdit && levelDomain) {
631
- const ratios = pointerRatios(event);
632
- if (!ratios) return;
633
- const hit = hitTestLevel(projectedLevels, ratios.yRatio, levelGrabRatio(panel.height));
634
- if (hit) {
635
- onSelectLevel(hit.id);
636
- if (hit.editable) dragRef.current = { kind: "level-move", id: hit.id };
637
- } else {
638
- const value = unprojectCompositeValue(ratios.yRatio, levelDomain);
639
- if (value !== null) {
640
- const id = nextLevelId();
641
- levels.onEdit({ kind: "add", id, value: roundLevelValue(value, levelDomain) });
642
- onSelectLevel(id);
643
- }
644
- }
645
- updateCursor(event);
646
- return;
647
- }
648
- if (tool) {
649
- const ratios = pointerRatios(event);
650
- if (!ratios) return;
651
- // With a drawing tool in hand, grabbing an existing shape edits it
652
- // instead of starting a new one on top of it.
653
- const hit = isDrawingTool(tool)
654
- ? hitTestDrawings(drawings, scene, panel, ratios, plotAspect)
655
- : null;
656
- if (hit) {
657
- onSelectDrawing(hit.drawing.id);
658
- dragRef.current = {
659
- kind: "edit",
660
- drawingId: hit.drawing.id,
661
- pointIndex: hit.pointIndex,
662
- lastXRatio: ratios.xRatio,
663
- lastYRatio: ratios.yRatio,
664
- };
665
- updateCursor(event);
666
- return;
667
- }
668
- const started: ChartToolDrag = {
669
- kind: tool,
670
- startXRatio: ratios.xRatio,
671
- startYRatio: ratios.yRatio,
672
- endXRatio: ratios.xRatio,
673
- endYRatio: ratios.yRatio,
674
- path: [{ xRatio: ratios.xRatio, yRatio: ratios.yRatio }],
675
- };
676
- if (isDrawingTool(tool)) onSelectDrawing(null);
677
- dragRef.current = { ...started, path: [...started.path] };
678
- setToolDrag(started);
679
- updateCursor(event);
680
- return;
681
- }
682
- // With no tool in hand, a press on a drawing or a level picks it so Backspace
683
- // or Delete can remove it; the press still pans, and one on bare plot lets go.
684
- const ratios = pointerRatios(event);
685
- let bare = true;
686
- if (ratios) {
687
- const drawingHit = drawings.length > 0 ? hitTestDrawings(drawings, scene, panel, ratios, plotAspect) : null;
688
- const levelHit = !drawingHit && levels?.onEdit && levelDomain
689
- ? hitTestLevel(projectedLevels, ratios.yRatio, levelGrabRatio(panel.height))
690
- : null;
691
- onSelectDrawing(drawingHit ? drawingHit.drawing.id : null);
692
- onSelectLevel(levelHit?.editable ? levelHit.id : null);
693
- bare = !drawingHit && !levelHit;
694
- // An order's line drags without the level tool; other levels keep the press for panning.
695
- if (levelHit?.editable && levelHit.draggable) {
696
- dragRef.current = { kind: "level-move", id: levelHit.id };
697
- lastPlotPressRef.current = null;
698
- updateCursor(event);
699
- return;
700
- }
701
- }
702
- // A double click on bare plot gives the panel the whole chart, or the
703
- // others back (the terminal counts two presses on one spot). Its first
704
- // press must have landed here too: a double click on a button that goes
705
- // away under it (All panels) ends on this plot, and is not one of its.
706
- if (!bare) lastPlotPressRef.current = null;
707
- if (onToggleMaximized && bare) {
708
- const now = Date.now();
709
- const last = lastPlotPressRef.current;
710
- const double = typeof event.detail === "number"
711
- ? event.detail >= 2 && !!last && now - last.at < PLOT_DOUBLE_CLICK_MS
712
- : !!last && now - last.at < AXIS_DOUBLE_PRESS_MS && Math.abs(last.x - event.x) <= 1 && Math.abs(last.y - event.y) <= 1;
713
- lastPlotPressRef.current = double ? null : { at: now, x: event.x, y: event.y };
714
- if (double) {
715
- dragRef.current = null;
716
- onToggleMaximized();
717
- return;
718
- }
719
- }
720
- if (!updateCursor(event)) return;
721
- const values = manualValueAxes(panel);
722
- panSamplesRef.current = [{ at: performance.now(), x: getGlobalMouseX(event, renderer) }];
723
- dragRef.current = {
724
- ...startPanGesture(
725
- frame,
726
- viewport,
727
- plotSize.width,
728
- getGlobalMouseX(event, renderer),
729
- plotSpanFactor,
730
- ),
731
- // A panel scaled by hand moves up and down with the drag as well.
732
- ...(values.length > 0 ? { startCellY: pointerRow(event), values } : {}),
733
- };
734
- }, [
735
- armedTool,
736
- drawings,
737
- frame,
738
- levelDomain,
739
- levels,
740
- onActivate,
741
- onPickTime,
742
- onPickPrice,
743
- onPointerPress,
744
- onSelectDrawing,
745
- onSelectLevel,
746
- panel,
747
- plotAspect,
748
- projectedLevels,
749
- plotPointer,
750
- plotSize.width,
751
- plotSpanFactor,
752
- plotWidth,
753
- pointerRatios,
754
- renderer,
755
- scene,
756
- updateCursor,
757
- viewport,
758
- onToggleMaximized,
759
- ]);
760
- const pressCursor = useCallback((event: ChartMouseEvent) => {
761
- onActivate?.();
762
- updateCursor(event);
763
- }, [onActivate, updateCursor]);
764
- const dragViewport = useCallback((event: ChartMouseEvent) => {
765
- const drag = dragRef.current;
766
- if (!drag) return;
767
- consumeChartMouseEvent(event);
768
- updateCursor(event);
769
- if (drag.kind === "level-move") {
770
- const ratios = pointerRatios(event);
771
- const value = ratios && levelDomain ? unprojectCompositeValue(ratios.yRatio, levelDomain) : null;
772
- if (value === null || !levelDomain) return;
773
- const draft = { id: drag.id, value: roundLevelValue(value, levelDomain) };
774
- // The release reads the ref, and a quick drag lets go before the next render.
775
- levelDraftRef.current = draft;
776
- setLevelDraft(draft);
777
- return;
778
- }
779
- if (drag.kind === "edit") {
780
- const ratios = pointerRatios(event);
781
- if (!ratios) return;
782
- // Read the deltas before advancing the ref: the state updater runs later,
783
- // and a mutable capture would hand it a zero move every time.
784
- const deltaXRatio = ratios.xRatio - drag.lastXRatio;
785
- const deltaYRatio = ratios.yRatio - drag.lastYRatio;
786
- const { drawingId, pointIndex } = drag;
787
- drag.lastXRatio = ratios.xRatio;
788
- drag.lastYRatio = ratios.yRatio;
789
- onEditDrawing(
790
- drawingId,
791
- (drawing) => shiftDrawing(drawing, scene, panel, deltaXRatio, deltaYRatio, pointIndex),
792
- );
793
- return;
794
- }
795
- if (drag.kind !== "pan") {
796
- const ratios = pointerRatios(event);
797
- if (!ratios) return;
798
- drag.endXRatio = ratios.xRatio;
799
- drag.endYRatio = ratios.yRatio;
800
- if (drag.kind === "pencil") drag.path.push({ xRatio: ratios.xRatio, yRatio: ratios.yRatio });
801
- setToolDrag({ ...drag, path: [...drag.path] });
802
- return;
803
- }
804
- const globalX = getGlobalMouseX(event, renderer);
805
- panSamplesRef.current.push({ at: performance.now(), x: globalX });
806
- if (panSamplesRef.current.length > 12) panSamplesRef.current.shift();
807
- if (drag.frame !== frame) {
808
- // Data refreshed mid-drag. The new frame maps positions differently, so
809
- // continue from where the plot is now instead of replaying the drag.
810
- Object.assign(drag, startPanGesture(frame, viewport, plotSize.width, globalX, plotSpanFactor));
811
- }
812
- onPanViewport(
813
- (globalX - drag.startGlobalX) * drag.positionsPerCell,
814
- { frame: drag.frame, from: drag.startViewport },
815
- );
816
- if (drag.values && drag.startCellY !== undefined) {
817
- const deltaRatio = (pointerRow(event) - drag.startCellY) / Math.max(plotSize.height, 1);
818
- for (const axis of drag.values) {
819
- onSetValueScale(panel.id, axis.side, axis.key, panValueRange(axis.start, axis.scale, deltaRatio));
820
- }
821
- }
822
- }, [
823
- frame,
824
- levelDomain,
825
- onEditDrawing,
826
- onPanViewport,
827
- onSetValueScale,
828
- plotSize.height,
829
- panel,
830
- plotSize.width,
831
- plotSpanFactor,
832
- plotWidth,
833
- pointerRatios,
834
- renderer,
835
- scene,
836
- updateCursor,
837
- viewport,
838
- ]);
839
- // A pan let go while still moving keeps going and slows down, on the
840
- // desktop and web only: in a terminal every frame would upload the plot again.
841
- const panSamplesRef = useRef<PanSample[]>([]);
842
- const coastFrameRef = useRef<number | null>(null);
843
- const coastPanRef = useRef(onPanViewport);
844
- coastPanRef.current = onPanViewport;
845
- const stopCoast = useCallback(() => {
846
- if (coastFrameRef.current === null) return;
847
- webFrame.cancelAnimationFrame?.(coastFrameRef.current);
848
- coastFrameRef.current = null;
849
- globalThis.removeEventListener?.("pointerdown", stopCoast, true);
850
- globalThis.removeEventListener?.("keydown", stopCoast, true);
851
- }, []);
852
- const startCoast = useCallback((velocity: number, positionsPerCell: number) => {
853
- stopCoast();
854
- const requestFrame = webFrame.requestAnimationFrame;
855
- const widthCells = Math.max(plotSize.width, 1);
856
- const plotWidthsPerSecond = (speed: number) => Math.abs(speed) * 1000 / widthCells;
857
- if (!isDesktopWeb || !requestFrame || plotWidthsPerSecond(velocity) < PAN_COAST_START_SPEED) return;
858
- if (globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
859
- let speed = velocity;
860
- let last = performance.now();
861
- const step = () => {
862
- const now = performance.now();
863
- const next = panCoastStep(speed, now - last);
864
- last = now;
865
- speed = next.velocity;
866
- coastPanRef.current(next.cells * positionsPerCell);
867
- if (plotWidthsPerSecond(speed) < PAN_COAST_STOP_SPEED) stopCoast();
868
- else coastFrameRef.current = requestFrame(step);
869
- };
870
- coastFrameRef.current = requestFrame(step);
871
- // Any press or key anywhere, a range button or a reset, takes the view back from the coast.
872
- globalThis.addEventListener?.("pointerdown", stopCoast, true);
873
- globalThis.addEventListener?.("keydown", stopCoast, true);
874
- }, [isDesktopWeb, plotSize.width, stopCoast]);
875
- useEffect(() => stopCoast, [stopCoast]);
876
- const finishToolDrag = useCallback(() => {
877
- const drag = dragRef.current;
878
- if (!drag || drag.kind === "pan") return;
879
- dragRef.current = null;
880
- if (drag.kind === "edit") return;
881
- if (drag.kind === "level-move") {
882
- const draft = levelDraftRef.current;
883
- setLevelDraft(null);
884
- if (draft) levels?.onEdit?.({ kind: "move", id: draft.id, value: draft.value });
885
- return;
886
- }
887
- setToolDrag(null);
888
- if (isDrawingTool(drag.kind)) {
889
- const drawing = resolveDrawingFromDrag(scene, panel, drag, drawColor, nextDrawingId());
890
- if (drawing) onDraw(drawing);
891
- return;
892
- }
893
- if (drag.kind !== "zoom") return;
894
- const range = resolveZoomBoxRange(scene, drag, frame.minimumSpanMs);
895
- if (range) onSetViewport(range);
896
- }, [drawColor, frame.minimumSpanMs, levels, onDraw, onSetViewport, panel, scene]);
897
- const resetDrag = useCallback(() => {
898
- const drag = dragRef.current;
899
- if (drag?.kind === "pan") {
900
- dragRef.current = null;
901
- startCoast(panReleaseVelocity(panSamplesRef.current, performance.now()), drag.positionsPerCell);
902
- return;
903
- }
904
- finishToolDrag();
905
- }, [finishToolDrag, startCoast]);
906
- // Said once per change, so a pointer move costs the chart nothing.
907
- const reportedDragRef = useRef(false);
908
- const reportDrag = useCallback((dragging: boolean) => {
909
- if (reportedDragRef.current === dragging) return;
910
- reportedDragRef.current = dragging;
911
- onDragActiveChange?.(dragging);
912
- }, [onDragActiveChange]);
913
- const pressPlot = useCallback((event: ChartMouseEvent) => {
914
- stopCoast();
915
- const before = dragRef.current;
916
- startDrag(event);
917
- if (dragRef.current !== null && dragRef.current !== before) reportDrag(true);
918
- }, [reportDrag, startDrag, stopCoast]);
919
- const releasePlot = useCallback(() => {
920
- resetDrag();
921
- reportDrag(false);
922
- }, [reportDrag, resetDrag]);
923
- const handleMouseMove = useCallback((event: ChartMouseEvent) => {
924
- // A release over a neighbouring pane never reaches this surface, so treat a
925
- // plain move, which only fires with no button held, as the missing release.
926
- finishToolDrag();
927
- reportDrag(false);
928
- updateCursor(event);
929
- }, [finishToolDrag, reportDrag, updateCursor]);
930
- // Trackpads fire wheel events faster than the plot can paint, so one frame
931
- // absorbs every event that arrived since the last one.
932
- const pendingWheelRef = useRef<PendingWheel | null>(null);
933
- const wheelFrameRef = useRef<number | null>(null);
934
- const latestWheelStateRef = useRef({ frame, viewport, onPanViewport, onZoomViewport, plotSpanFactor });
935
- latestWheelStateRef.current = { frame, viewport, onPanViewport, onZoomViewport, plotSpanFactor };
936
- const flushWheel = useCallback(() => {
937
- wheelFrameRef.current = null;
938
- const pending = pendingWheelRef.current;
939
- pendingWheelRef.current = null;
940
- if (!pending) return;
941
- const latest = latestWheelStateRef.current;
942
- if (pending.panRatio !== 0) {
943
- const positions = compositeViewportPositions(latest.frame, latest.viewport);
944
- const span = positions ? Math.max(positions.end - positions.start, Number.EPSILON) : 0;
945
- latest.onPanViewport(pending.panRatio * span * latest.plotSpanFactor);
946
- }
947
- if (pending.zoomLog !== 0) {
948
- latest.onZoomViewport(Math.exp(pending.zoomLog), pending.anchorRatio);
949
- }
950
- }, []);
951
- useEffect(() => () => {
952
- pendingWheelRef.current = null;
953
- if (wheelFrameRef.current !== null) {
954
- webFrame.cancelAnimationFrame?.(wheelFrameRef.current);
955
- wheelFrameRef.current = null;
956
- }
957
- }, []);
958
- const panFromWheel = useCallback((event: ChartMouseEvent) => {
959
- const scroll = event.scroll;
960
- if (!scroll) return;
961
- stopCoast();
962
- onActivate?.();
963
- consumeChartMouseEvent(event);
964
- const pointer = plotPointer(event);
965
- updateCursor(event);
966
- const pending = pendingWheelRef.current ?? { panRatio: 0, zoomLog: 0, anchorRatio: 0.5 };
967
- if (event.modifiers.ctrl && pointer && isVerticalWheelDirection(scroll.direction)) {
968
- pending.zoomLog += Math.log(resolveCompositeWheelZoom(scroll));
969
- // The anchor is a fraction of the viewport, so a pointer over the empty
970
- // right offset anchors on the newest observation instead of past it.
971
- pending.anchorRatio = Math.min(
972
- 1,
973
- pointer.cellX / Math.max(plotWidth - 1, 1) * plotSpanFactor,
974
- );
975
- } else {
976
- pending.panRatio += resolveCompositeWheelPan(scroll, plotSize.width * cellWidthPx);
977
- }
978
- pendingWheelRef.current = pending;
979
- if (!isDesktopWeb || typeof webFrame.requestAnimationFrame !== "function") {
980
- flushWheel();
981
- return;
982
- }
983
- if (wheelFrameRef.current === null) {
984
- wheelFrameRef.current = webFrame.requestAnimationFrame(flushWheel);
985
- }
986
- }, [
987
- cellWidthPx,
988
- flushWheel,
989
- isDesktopWeb,
990
- onActivate,
991
- plotPointer,
992
- plotSize.width,
993
- plotSpanFactor,
994
- plotWidth,
995
- updateCursor,
996
- ]);
997
-
998
- // A value axis under the pointer: a drag stretches (up) or squeezes (down)
999
- // it around its middle, the wheel around the pointer, and a double click
1000
- // fits it to the data again. Read through refs, so the handlers stay put.
1001
- const axisGestureRef = useRef<(ValueAxisStart & { startRow: number; moved: boolean }) | null>(null);
1002
- const lastAxisPressRef = useRef<{ side: CompositeAxisSide; at: number } | null>(null);
1003
- const latestAxesRef = useRef({ panel, onSetValueScale, onResetValueScale, onActivate });
1004
- latestAxesRef.current = { panel, onSetValueScale, onResetValueScale, onActivate };
1005
- /** The pointer's height down the panel, 0 at the top and 1 at the bottom. */
1006
- const axisPointerRatio = useCallback((event: ChartMouseEvent): number => {
1007
- const plot = plotRef.current as unknown as { absoluteY?: number; y?: number; height?: number } | null;
1008
- const top = plot?.absoluteY ?? plot?.y;
1009
- const height = plot?.height ?? 0;
1010
- if (top === undefined || height <= 1) return 0.5;
1011
- return clamp((pointerRow(event) - top) / (fractionalViewport ? height : height - 1), 0, 1);
1012
- }, [fractionalViewport]);
1013
- const pressAxis = useCallback((side: CompositeAxisSide, event: ChartMouseEvent) => {
1014
- const latest = latestAxesRef.current;
1015
- const domain = latest.panel.axes[side];
1016
- if (!domain?.scaleKey) return;
1017
- latest.onActivate?.();
1018
- consumeChartMouseEvent(event);
1019
- // The desktop counts clicks; the terminal has two presses close together.
1020
- const now = Date.now();
1021
- const last = lastAxisPressRef.current;
1022
- const double = typeof event.detail === "number"
1023
- ? event.detail >= 2
1024
- : !!last && last.side === side && now - last.at < AXIS_DOUBLE_PRESS_MS;
1025
- if (double) {
1026
- lastAxisPressRef.current = null;
1027
- axisGestureRef.current = null;
1028
- latest.onResetValueScale(latest.panel.id);
1029
- return;
1030
- }
1031
- lastAxisPressRef.current = { side, at: now };
1032
- axisGestureRef.current = {
1033
- side,
1034
- key: domain.scaleKey,
1035
- scale: domain.scale,
1036
- start: { min: domain.min, max: domain.max },
1037
- startRow: pointerRow(event),
1038
- moved: false,
1039
- };
1040
- }, []);
1041
- const dragAxis = useCallback((event: ChartMouseEvent) => {
1042
- const gesture = axisGestureRef.current;
1043
- if (!gesture) return;
1044
- consumeChartMouseEvent(event);
1045
- const deltaPx = (pointerRow(event) - gesture.startRow) * cellHeightPx;
1046
- if (!gesture.moved && Math.abs(deltaPx) < 1) return;
1047
- // A drag is not the first half of a double click.
1048
- gesture.moved = true;
1049
- lastAxisPressRef.current = null;
1050
- const latest = latestAxesRef.current;
1051
- latest.onSetValueScale(
1052
- latest.panel.id,
1053
- gesture.side,
1054
- gesture.key,
1055
- zoomValueRange(gesture.start, gesture.scale, resolveAxisDragSpanFactor(deltaPx), 0.5),
1056
- );
1057
- }, [cellHeightPx]);
1058
- const releaseAxis = useCallback(() => {
1059
- axisGestureRef.current = null;
1060
- }, []);
1061
- const pendingAxisWheelRef = useRef<PendingAxisWheel | null>(null);
1062
- const axisWheelFrameRef = useRef<number | null>(null);
1063
- const flushAxisWheel = useCallback(() => {
1064
- axisWheelFrameRef.current = null;
1065
- const pending = pendingAxisWheelRef.current;
1066
- pendingAxisWheelRef.current = null;
1067
- const latest = latestAxesRef.current;
1068
- const domain = pending ? latest.panel.axes[pending.side] : undefined;
1069
- if (!pending || !domain?.scaleKey || pending.spanLog === 0) return;
1070
- latest.onSetValueScale(
1071
- latest.panel.id,
1072
- pending.side,
1073
- domain.scaleKey,
1074
- zoomValueRange({ min: domain.min, max: domain.max }, domain.scale, Math.exp(pending.spanLog), pending.anchorRatio),
1075
- );
1076
- }, []);
1077
- useEffect(() => () => {
1078
- pendingAxisWheelRef.current = null;
1079
- if (axisWheelFrameRef.current !== null) {
1080
- webFrame.cancelAnimationFrame?.(axisWheelFrameRef.current);
1081
- axisWheelFrameRef.current = null;
1082
- }
1083
- }, []);
1084
- const wheelAxis = useCallback((side: CompositeAxisSide, event: ChartMouseEvent) => {
1085
- const scroll = event.scroll;
1086
- if (!scroll || !latestAxesRef.current.panel.axes[side]?.scaleKey) return;
1087
- latestAxesRef.current.onActivate?.();
1088
- consumeChartMouseEvent(event);
1089
- if (!isVerticalWheelDirection(scroll.direction)) return;
1090
- const pending = pendingAxisWheelRef.current?.side === side
1091
- ? pendingAxisWheelRef.current
1092
- : { side, spanLog: 0, anchorRatio: 0.5 };
1093
- // Up stretches, as Ctrl and the wheel zoom the plot in.
1094
- pending.spanLog -= Math.log(resolveCompositeWheelZoom(scroll));
1095
- pending.anchorRatio = axisPointerRatio(event);
1096
- pendingAxisWheelRef.current = pending;
1097
- if (!isDesktopWeb || typeof webFrame.requestAnimationFrame !== "function") {
1098
- flushAxisWheel();
1099
- return;
1100
- }
1101
- if (axisWheelFrameRef.current === null) {
1102
- axisWheelFrameRef.current = webFrame.requestAnimationFrame(flushAxisWheel);
1103
- }
1104
- }, [axisPointerRatio, flushAxisWheel, isDesktopWeb]);
1105
- const leftAxisGestures = useMemo(() => valueScalable ? {
1106
- onMouseDown: (event: ChartMouseEvent) => pressAxis("left", event),
1107
- onMouseDrag: dragAxis,
1108
- onMouseUp: releaseAxis,
1109
- onMouseDragEnd: releaseAxis,
1110
- onMouseScroll: (event: ChartMouseEvent) => wheelAxis("left", event),
1111
- } : undefined, [dragAxis, pressAxis, releaseAxis, valueScalable, wheelAxis]);
1112
- const rightAxisGestures = useMemo(() => valueScalable ? {
1113
- onMouseDown: (event: ChartMouseEvent) => pressAxis("right", event),
1114
- onMouseDrag: dragAxis,
1115
- onMouseUp: releaseAxis,
1116
- onMouseDragEnd: releaseAxis,
1117
- onMouseScroll: (event: ChartMouseEvent) => wheelAxis("right", event),
1118
- } : undefined, [dragAxis, pressAxis, releaseAxis, valueScalable, wheelAxis]);
127
+ const { toolDirection, measureReadout, anchorMarker } = usePanelToolReadout({
128
+ panel, scene, colors, activeDrag, keyboardDrag, onToolSpanChange, plotWidth, leftAxisWidth, axisGap,
129
+ });
130
+ const { levelDraftRef, setLevelDraft, levelDomain, projectedLevels, levelGrab } = usePanelLevels({
131
+ panel, levels, armedTool, onPickTime, onPickPrice,
132
+ });
133
+ const { bitmapLayers, vectors } = usePanelOverlays({
134
+ bitmap, isDesktopWeb, panel, scene, colors, drawings, selectedDrawingId, drawColor, selectedLevelId,
135
+ activeDrag, toolDirection, projectedLevels,
136
+ });
137
+ const {
138
+ leftAxisLabels,
139
+ rightAxisLabels,
140
+ leftAxisTicks,
141
+ rightAxisTicks,
142
+ leftAxisMarkers,
143
+ rightAxisMarkers,
144
+ } = usePanelAxisMarkers({
145
+ panel, colors, formatAxisValue, leftAxisWidth, rightAxisWidth, selectedLevelId, levelDomain, projectedLevels,
146
+ anchorMarker, cellHeightPx, fractionalViewport,
147
+ });
148
+ const { plotPointer, pointerRatios, updateCursor, clearCursor } = usePlotPointer({
149
+ plotRef, renderer, plotSize, plotWidth, panelHeight: panel.height, scene, pointerY, onCursorDateChange,
150
+ });
151
+ const { stopCoast, startCoast } = usePanCoast({ isDesktopWeb, plotWidth: plotSize.width, onPanViewport });
152
+ const { pressPlot, pressCursor, dragViewport, releasePlot, handleMouseMove } = usePlotGestures({
153
+ panel, scene, frame, viewport, armedTool, drawings, drawColor, levels, plotWidth,
154
+ onActivate, onPointerPress, onPickTime, onPickPrice, onSelectDrawing, onEditDrawing, onDraw, onSelectLevel,
155
+ onPanViewport, onSetViewport, onSetValueScale, onDragActiveChange, onToggleMaximized,
156
+ isDesktopWeb, renderer, plotSize, plotAspect, plotSpanFactor, setToolDrag,
157
+ levelDomain, projectedLevels, levelDraftRef, setLevelDraft,
158
+ plotPointer, pointerRatios, updateCursor, stopCoast, startCoast,
159
+ });
160
+ const panFromWheel = usePlotWheel({
161
+ frame, viewport, onPanViewport, onZoomViewport, onActivate, plotWidth, plotSpanFactor,
162
+ measuredPlotWidth: plotSize.width, cellWidthPx, isDesktopWeb, stopCoast, plotPointer, updateCursor,
163
+ });
164
+ const { leftAxisGestures, rightAxisGestures } = useValueAxisGestures({
165
+ plotRef, panel, valueScalable, onSetValueScale, onResetValueScale, onActivate, isDesktopWeb, cellHeightPx, fractionalViewport,
166
+ });
1119
167
  // While the panel is scaled by hand, the foot of the axis scaled says so
1120
168
  // and is the way back.
1121
169
  const manuallyScaled = !!panel.axes.left?.manual || !!panel.axes.right?.manual;
@@ -1242,34 +290,23 @@ export function CompositePanelSurface({
1242
290
  data-gloom-value-scale={manuallyScaled ? "manual" : undefined}
1243
291
  />
1244
292
  {projectedLevels.length > 0 ? (
1245
- // A level's label leaves its value to the axis, unless the cursor's covers it there.
1246
- <PanelLevelLabels view={cursorView}>
1247
- {(activeCursorYRatio, cursorValues) => (isDesktopWeb
1248
- ? layoutLevelLabels(projectedLevels, plotSize.height * cellHeightPx, cellHeightPx)
1249
- : fitAxisLabels(projectedLevels.filter((entry) => entry.level.label), [], (entry) => entry.yRatio * Math.max(1, panel.height - 1))
1250
- ).map((entry) => {
1251
- const { level, yRatio } = entry;
1252
- const axisWidth = levelDomain?.side === "left" ? leftAxisWidth : rightAxisWidth;
1253
- const axisMarkers = levelDomain?.side === "left" ? leftAxisMarkers : rightAxisMarkers;
1254
- const cursorCovers = activeCursorYRatio !== null && Math.abs(activeCursorYRatio - yRatio) * panel.height < 1;
1255
- const axisVisible = !cursorCovers && (level.axisLabel?.length ?? 0) <= axisWidth && !!axisMarkers?.some((marker) => marker.id === level.id);
1256
- // A cursor on a bar at the level's own value (RETURN's on its best
1257
- // day) reads that value on the axis already: the label does not repeat it.
1258
- const cursorReadsLevel = cursorCovers && !!levels
1259
- && cursorValues.some((entry) => entry.seriesId === levels.seriesId && entry.value === level.value);
1260
- const label = levelLabelText(level, axisVisible || cursorReadsLevel);
1261
- const labelStyle = isDesktopWeb ? {
1262
- ...levelLabelStyle(entry, colors.background), left: "auto", right: (rightAxisWidth + (rightAxisWidth ? axisGap : 0) + 1) * cellWidthPx,
1263
- maxWidth: Math.max(1, plotWidth - 2) * cellWidthPx,
1264
- } : undefined;
1265
- const labelWidth = Math.min(plotWidth - 2, label.length + 2);
1266
- return <Box key={`annotation:${level.id}`} position="absolute" left={leftAxisWidth + (leftAxisWidth ? axisGap : 0) + plotWidth - labelWidth - 1} top={yRatio * Math.max(0, panel.height - 1)} height={1}
1267
- width={labelWidth} flexDirection="row" justifyContent="flex-end" backgroundColor={colors.background} zIndex={20}
1268
- style={labelStyle} data-gloom-role="chart-level-label">
1269
- <Text fg={labelStyle?.color ?? level.color} wrapMode="none" style={isDesktopWeb ? { lineHeight: 1 } : undefined}>{label}</Text>
1270
- </Box>;
1271
- })}
1272
- </PanelLevelLabels>
293
+ <PanelLevelLabels
294
+ view={cursorView}
295
+ projectedLevels={projectedLevels}
296
+ levels={levels}
297
+ levelDomain={levelDomain}
298
+ plotWidth={plotWidth}
299
+ leftAxisWidth={leftAxisWidth}
300
+ rightAxisWidth={rightAxisWidth}
301
+ axisGap={axisGap}
302
+ leftAxisMarkers={leftAxisMarkers}
303
+ rightAxisMarkers={rightAxisMarkers}
304
+ measuredPixelHeight={plotSize.height * cellHeightPx}
305
+ background={colors.background}
306
+ isDesktopWeb={isDesktopWeb}
307
+ cellHeightPx={cellHeightPx}
308
+ cellWidthPx={cellWidthPx}
309
+ />
1273
310
  ) : null}
1274
311
  {rightAxisWidth > 0 ? (
1275
312
  <>
@@ -1329,136 +366,3 @@ export function CompositePanelSurface({
1329
366
  </Box>
1330
367
  );
1331
368
  }
1332
-
1333
- /** Over a level a drag moves: always while one moves, never, or at the pointer's height. */
1334
- type LevelGrab = boolean | ((cursorYRatio: number) => boolean);
1335
-
1336
- /** What a panel's crosshair is read from: everything else in the panel holds still while it moves. */
1337
- interface PanelCursorView {
1338
- panel: CompositePanelScene;
1339
- cursor: CompositeCursorSource;
1340
- pointerY: ValueStore<number | null>;
1341
- keyboardDrag: KeyboardToolDrag | null;
1342
- sharedCursor: boolean;
1343
- }
1344
-
1345
- /** The crosshair over a panel, read by the parts that draw it, so a pointer move renders only them. */
1346
- function usePanelCursor({ panel, cursor, pointerY, keyboardDrag, sharedCursor }: PanelCursorView) {
1347
- const scene = useCursorScene(cursor);
1348
- const cursorYRatio = useValueStore(pointerY);
1349
- // A keyboard placement's end sits at the level the user put it, so it
1350
- // draws a level line where otherwise only the pointer would.
1351
- const heldCursorYRatio = keyboardDrag ? keyboardDrag.drag.endYRatio : sharedCursor ? null : cursorYRatio;
1352
- const seriesCursorYRatio = useMemo(
1353
- () => resolveSeriesCursorYRatio(panel, scene),
1354
- [panel, scene],
1355
- );
1356
- return {
1357
- scene,
1358
- cursorYRatio,
1359
- activeCursorYRatio: scene.cursorXRatio === null ? null : heldCursorYRatio ?? seriesCursorYRatio,
1360
- // The chart under the pointer draws both lines: the level line follows the
1361
- // pointer, and its value sits on the axes, beside each series' own tag on
1362
- // the desktop and the web. A keyboard or shared cursor knows its column
1363
- // only, so a chart following another chart's cursor draws the time line
1364
- // alone. A tool placed from the keyboard is the exception: its end is a level.
1365
- pointerCursorYRatio: scene.cursorXRatio === null ? null : heldCursorYRatio,
1366
- };
1367
- }
1368
-
1369
- /** The plot, with the crosshair over it and, in a terminal without graphics, the text that draws both. */
1370
- function PanelPlotSurface({
1371
- view,
1372
- plotRef,
1373
- bitmap,
1374
- crosshairColor,
1375
- textColor,
1376
- textFallback,
1377
- plotWidth,
1378
- projectedLevels,
1379
- selectedLevelId,
1380
- levelGrab,
1381
- ...surface
1382
- }: Omit<ComponentProps<typeof ChartSurface>, "ref" | "crosshair" | "children"> & {
1383
- view: PanelCursorView;
1384
- plotRef: RefObject<BoxRenderable | null>;
1385
- bitmap: ReturnType<typeof useCompositePanelBitmap>;
1386
- crosshairColor: string;
1387
- textColor: string;
1388
- textFallback: boolean;
1389
- plotWidth: number;
1390
- projectedLevels: readonly ProjectedLevel[];
1391
- selectedLevelId: string | null;
1392
- levelGrab: LevelGrab;
1393
- }) {
1394
- const { panel } = view;
1395
- const { scene, cursorYRatio, pointerCursorYRatio } = usePanelCursor(view);
1396
- const crosshair = useMemo(
1397
- () => resolvePanelCrosshair(panel, bitmap, scene, pointerCursorYRatio, crosshairColor),
1398
- [bitmap, crosshairColor, panel, pointerCursorYRatio, scene],
1399
- );
1400
- const textLines = useMemo(
1401
- () => textFallback
1402
- ? writeLevelText(
1403
- renderCompositePanelText(panel, plotWidth, scene.cursorXRatio, pointerCursorYRatio),
1404
- projectedLevels,
1405
- selectedLevelId,
1406
- )
1407
- : [],
1408
- [panel, plotWidth, pointerCursorYRatio, projectedLevels, scene.cursorXRatio, selectedLevelId, textFallback],
1409
- );
1410
- const grab = typeof levelGrab === "function" ? cursorYRatio !== null && levelGrab(cursorYRatio) : levelGrab;
1411
- return (
1412
- <ChartSurface
1413
- ref={plotRef}
1414
- {...surface}
1415
- style={grab && surface.style ? DESKTOP_PLOT_LEVEL_STYLE : surface.style}
1416
- cursor={grab && surface.cursor ? "ns-resize" : surface.cursor}
1417
- crosshair={crosshair}
1418
- >
1419
- {textLines.map((line, index) => <Text key={index} fg={textColor}>{line}</Text>)}
1420
- </ChartSurface>
1421
- );
1422
- }
1423
-
1424
- /** A value axis, with the cursor's value on it and, on the desktop, each series' value at the cursor. */
1425
- function PanelValueAxis({
1426
- view,
1427
- formatAxisValue,
1428
- side,
1429
- ...axis
1430
- }: Omit<ComponentProps<typeof PriceAxisLabels>, "cursorRow" | "cursorPixelY" | "cursorLabel" | "seriesTags" | "side"> & {
1431
- view: PanelCursorView;
1432
- formatAxisValue?: CompositeAxisValueFormatter;
1433
- side: CompositeAxisSide;
1434
- }) {
1435
- const { panel } = view;
1436
- const isDesktopWeb = useUiCapabilities().nativePaneChrome === true;
1437
- const { cellHeightPx = 18 } = useUiCapabilities();
1438
- const { scene, activeCursorYRatio, pointerCursorYRatio } = usePanelCursor(view);
1439
- // The pointer's value on the axes follows the level line it belongs to.
1440
- const axisCursorYRatio = isDesktopWeb ? pointerCursorYRatio : activeCursorYRatio;
1441
- const seriesTags = useMemo(
1442
- () => isDesktopWeb ? resolveSeriesAxisTags(panel, scene, formatAxisValue).filter((tag) => tag.side === side) : undefined,
1443
- [formatAxisValue, isDesktopWeb, panel, scene, side],
1444
- );
1445
- return (
1446
- <PriceAxisLabels
1447
- {...axis}
1448
- side={side}
1449
- cursorRow={activeCursorYRatio === null ? null : Math.round(activeCursorYRatio * Math.max(panel.height - 1, 0))}
1450
- cursorPixelY={activeCursorYRatio === null ? null : activeCursorYRatio * Math.max(panel.height * cellHeightPx - 1, 0)}
1451
- cursorLabel={cursorAxisLabel(panel, side, axisCursorYRatio, formatAxisValue)}
1452
- seriesTags={seriesTags}
1453
- />
1454
- );
1455
- }
1456
-
1457
- /** A panel's level labels, which step aside where the cursor's label covers theirs on the axis. */
1458
- function PanelLevelLabels({ view, children }: {
1459
- view: PanelCursorView;
1460
- children: (activeCursorYRatio: number | null, cursorValues: CompositeChartScene["cursorValues"]) => ReactNode;
1461
- }) {
1462
- const { activeCursorYRatio, scene } = usePanelCursor(view);
1463
- return <>{children(activeCursorYRatio, scene.cursorValues)}</>;
1464
- }