@gloom-sh/terminal 0.20.18 → 0.20.19

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 (204) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/cot.ts +5 -6
  3. package/src/api-client/data.ts +11 -1
  4. package/src/api-client/index.ts +1 -0
  5. package/src/api-client/request.ts +162 -40
  6. package/src/api-client/types/news.ts +45 -0
  7. package/src/api-client/types/world-venues.ts +9 -0
  8. package/src/app.tsx +4 -2
  9. package/src/architecture/floating-promise-allowlist.json +1 -1
  10. package/src/cli/commands/market.ts +53 -17
  11. package/src/cli/commands/ticker.ts +13 -6
  12. package/src/cli/context.ts +8 -0
  13. package/src/cli/desktop-pane-shot-browser.ts +3 -1
  14. package/src/cli/desktop-pane-shot-view.ts +0 -1
  15. package/src/cli/desktop-pane-shot.ts +204 -43
  16. package/src/cli/errors.ts +3 -9
  17. package/src/cli/exit-codes.ts +1 -1
  18. package/src/cli/glossary.ts +1 -1
  19. package/src/cli/help.ts +1 -1
  20. package/src/cli/history-rows.ts +2 -2
  21. package/src/cli/index.ts +1 -1
  22. package/src/cli/listing-arg.ts +87 -23
  23. package/src/cli/pane-functions/catalog-snapshot.json +17 -6
  24. package/src/cli/pane-functions/dom.ts +30 -2
  25. package/src/cli/pane-functions/freshness.ts +23 -4
  26. package/src/cli/pane-functions/function-help.ts +3 -3
  27. package/src/cli/pane-functions/headless.ts +9 -1
  28. package/src/cli/pane-functions/index.ts +77 -10
  29. package/src/cli/pane-functions/report-notices.ts +10 -0
  30. package/src/cli/pane-functions/resolver.ts +3 -2
  31. package/src/cli/pane-functions/screenshot-assessment.ts +10 -5
  32. package/src/cli/pane-functions/screenshot-data-evidence.ts +7 -15
  33. package/src/cli/pane-functions/screenshot-payload.ts +24 -10
  34. package/src/cli/pane-functions/screenshot-render.ts +21 -8
  35. package/src/cli/pane-functions/screenshot-types.ts +9 -0
  36. package/src/cli/quote-answer.ts +1 -1
  37. package/src/cli/result.ts +17 -0
  38. package/src/cli/scroll-truncation.ts +7 -2
  39. package/src/cli/ticker-resolution.ts +1 -1
  40. package/src/cli/unreachable.ts +21 -0
  41. package/src/components/chart/composite/drawing-store.ts +11 -7
  42. package/src/components/chart/composite/format.ts +1 -0
  43. package/src/components/chart/composite/legend.tsx +5 -2
  44. package/src/components/chart/composite/panel-surface/plot-gestures.ts +9 -2
  45. package/src/components/chart/composite/panel-surface.tsx +1 -1
  46. package/src/components/chart/composite/tools.ts +164 -39
  47. package/src/components/chart-table/header.tsx +2 -2
  48. package/src/components/chart-table/layout.ts +5 -6
  49. package/src/components/command-bar/routes/root/runtime.ts +11 -3
  50. package/src/components/command-bar/routes/ticker-search/results.ts +5 -0
  51. package/src/components/command-bar/selection-runtime.ts +29 -5
  52. package/src/components/command-bar/surface/index.tsx +4 -1
  53. package/src/components/command-bar/workflow/alert.ts +13 -5
  54. package/src/components/layout/pane/footer/model.ts +10 -2
  55. package/src/components/layout/pane/status-footer.ts +24 -0
  56. package/src/components/price-performance.tsx +26 -8
  57. package/src/components/reader/article-reader.tsx +12 -5
  58. package/src/components/ui/data-table/opentui/index.tsx +7 -0
  59. package/src/components/ui/table-layout.ts +32 -1
  60. package/src/market-data/ah-pair.ts +19 -0
  61. package/src/market-data/coordinator/entries.ts +6 -4
  62. package/src/market-data/coordinator/index.ts +14 -3
  63. package/src/market-data/futures-board.ts +36 -29
  64. package/src/market-data/futures-contract.ts +37 -1
  65. package/src/market-data/market/change-basis.ts +9 -0
  66. package/src/market-data/market/status.ts +40 -4
  67. package/src/market-data/performance.ts +127 -32
  68. package/src/market-data/quotes/time.ts +5 -2
  69. package/src/news/types.ts +28 -0
  70. package/src/notifications/app-badge.ts +2 -3
  71. package/src/notifications/app-notifier.ts +5 -0
  72. package/src/plugins/builtin/alerts/cli.ts +65 -18
  73. package/src/plugins/builtin/alerts/command.ts +39 -9
  74. package/src/plugins/builtin/alerts/event-rows.ts +9 -3
  75. package/src/plugins/builtin/alerts/events-pane.tsx +16 -10
  76. package/src/plugins/builtin/alerts/headless.ts +12 -6
  77. package/src/plugins/builtin/alerts/index.tsx +60 -8
  78. package/src/plugins/builtin/alerts/option-contract.ts +197 -0
  79. package/src/plugins/builtin/alerts/price.ts +30 -5
  80. package/src/plugins/builtin/alerts/pro-rules.ts +62 -0
  81. package/src/plugins/builtin/alerts/research-builder.ts +5 -10
  82. package/src/plugins/builtin/analytics/account-returns.ts +1 -1
  83. package/src/plugins/builtin/analytics/pane-model.ts +2 -2
  84. package/src/plugins/builtin/analytics/risk-client.ts +1 -1
  85. package/src/plugins/builtin/buildout/company/pane.tsx +4 -14
  86. package/src/plugins/builtin/catalysts/model.ts +2 -1
  87. package/src/plugins/builtin/chart-composer/chart-spec.ts +5 -0
  88. package/src/plugins/builtin/chart-composer/cli-options.ts +5 -3
  89. package/src/plugins/builtin/chart-composer/headless-schema.ts +14 -10
  90. package/src/plugins/builtin/chart-composer/headless.ts +2 -0
  91. package/src/plugins/builtin/chart-composer/index.tsx +17 -5
  92. package/src/plugins/builtin/chart-composer/pane.tsx +14 -4
  93. package/src/plugins/builtin/chart-composer/viewport-labels.ts +2 -17
  94. package/src/plugins/builtin/chat/controller/notifications.ts +1 -0
  95. package/src/plugins/builtin/chat/index.tsx +0 -1
  96. package/src/plugins/builtin/commodities-energy/index.tsx +1 -1
  97. package/src/plugins/builtin/company-kpis/headless.ts +1 -1
  98. package/src/plugins/builtin/company-kpis/model.ts +21 -9
  99. package/src/plugins/builtin/congress-trades/model.ts +9 -5
  100. package/src/plugins/builtin/cot/client.ts +2 -3
  101. package/src/plugins/builtin/cot/headless.ts +16 -16
  102. package/src/plugins/builtin/cot/index.tsx +6 -6
  103. package/src/plugins/builtin/cot/model.ts +25 -5
  104. package/src/plugins/builtin/cot/pane.tsx +11 -6
  105. package/src/plugins/builtin/cot/series.ts +11 -8
  106. package/src/plugins/builtin/cpi/model.ts +15 -4
  107. package/src/plugins/builtin/cpi/pane.tsx +29 -7
  108. package/src/plugins/builtin/doe/model.ts +30 -0
  109. package/src/plugins/builtin/doe/pane.tsx +8 -2
  110. package/src/plugins/builtin/earnings/board-table.ts +9 -4
  111. package/src/plugins/builtin/earnings/headless.ts +10 -3
  112. package/src/plugins/builtin/earnings/history-table.ts +4 -2
  113. package/src/plugins/builtin/earnings-calls/calendar.tsx +4 -3
  114. package/src/plugins/builtin/earnings-ripple/pane.tsx +2 -2
  115. package/src/plugins/builtin/econ/index.tsx +4 -2
  116. package/src/plugins/builtin/futures/model.ts +14 -1
  117. package/src/plugins/builtin/futures/series.ts +1 -8
  118. package/src/plugins/builtin/fx-matrix/index.tsx +2 -2
  119. package/src/plugins/builtin/insider/detail.tsx +36 -7
  120. package/src/plugins/builtin/insider/filing-stories.ts +110 -0
  121. package/src/plugins/builtin/insider/headless.ts +37 -2
  122. package/src/plugins/builtin/insider/index.tsx +79 -10
  123. package/src/plugins/builtin/insider/model.ts +43 -5
  124. package/src/plugins/builtin/ipo-calendar/client.ts +11 -1
  125. package/src/plugins/builtin/ipo-calendar/model.ts +3 -7
  126. package/src/plugins/builtin/jobs/headless.ts +2 -1
  127. package/src/plugins/builtin/jobs/model.ts +6 -0
  128. package/src/plugins/builtin/jobs/pane.tsx +8 -3
  129. package/src/plugins/builtin/news/wire/news/detail-view.tsx +118 -10
  130. package/src/plugins/builtin/news/wire/news/story-evidence.ts +178 -0
  131. package/src/plugins/builtin/options/analytics.ts +1 -1
  132. package/src/plugins/builtin/options/view.tsx +18 -11
  133. package/src/plugins/builtin/options-positioning/model.ts +11 -0
  134. package/src/plugins/builtin/options-positioning/pane.tsx +22 -1
  135. package/src/plugins/builtin/options-scenario/client.ts +49 -8
  136. package/src/plugins/builtin/options-scenario/headless.ts +7 -3
  137. package/src/plugins/builtin/options-scenario/model.ts +33 -2
  138. package/src/plugins/builtin/options-scenario/pane.tsx +3 -4
  139. package/src/plugins/builtin/perps/cascade.ts +4 -3
  140. package/src/plugins/builtin/perps/markets-section.tsx +5 -2
  141. package/src/plugins/builtin/perps/model.ts +4 -3
  142. package/src/plugins/builtin/portfolio-list/table.tsx +3 -2
  143. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -14
  144. package/src/plugins/builtin/research/event-model.ts +12 -6
  145. package/src/plugins/builtin/research-search/index.tsx +3 -1
  146. package/src/plugins/builtin/scanner/denied.tsx +16 -4
  147. package/src/plugins/builtin/scanner/flow-pane.tsx +1 -1
  148. package/src/plugins/builtin/scanner/hilo-pane.tsx +1 -1
  149. package/src/plugins/builtin/sec/filing-display.tsx +14 -2
  150. package/src/plugins/builtin/sec/headless.ts +42 -4
  151. package/src/plugins/builtin/sec/index.tsx +21 -1
  152. package/src/plugins/builtin/sectors/sector-model.ts +1 -1
  153. package/src/plugins/builtin/shared/earnings-report.ts +32 -3
  154. package/src/plugins/builtin/shared/options-pro-copy.ts +34 -0
  155. package/src/plugins/builtin/shared/statement-currency.ts +23 -0
  156. package/src/plugins/builtin/shared/ticker-surface.ts +1 -1
  157. package/src/plugins/builtin/supply-chain/pane.tsx +4 -3
  158. package/src/plugins/builtin/themes/headless.ts +4 -4
  159. package/src/plugins/builtin/themes/model.ts +11 -8
  160. package/src/plugins/builtin/themes/pane.tsx +2 -2
  161. package/src/plugins/builtin/ticker-detail/financials/model.ts +22 -32
  162. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +7 -9
  163. package/src/plugins/builtin/ticker-detail/headless-schema.ts +2 -0
  164. package/src/plugins/builtin/ticker-detail/headless.ts +28 -12
  165. package/src/plugins/builtin/ticker-detail/overview/board-lot.ts +21 -0
  166. package/src/plugins/builtin/ticker-detail/overview/model.ts +11 -1
  167. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -0
  168. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +61 -13
  169. package/src/plugins/builtin/volatility/pane.tsx +3 -3
  170. package/src/plugins/builtin/world-venue-map/headless.ts +4 -2
  171. package/src/plugins/builtin/world-venue-map/model.ts +6 -1
  172. package/src/plugins/builtin/world-venue-map/venue-header.tsx +5 -3
  173. package/src/plugins/catalog-browser.ts +10 -1
  174. package/src/renderers/browser/activity.ts +16 -0
  175. package/src/renderers/browser/app-badge-host.ts +14 -0
  176. package/src/renderers/browser/main.tsx +5 -0
  177. package/src/renderers/browser/notifications.ts +103 -0
  178. package/src/renderers/browser/ui-host.tsx +4 -0
  179. package/src/renderers/dom/data-table/index.tsx +27 -4
  180. package/src/renderers/electrobun/view/http-fetch.ts +3 -2
  181. package/src/sources/gloomberb-cloud/index.ts +8 -6
  182. package/src/sources/gloomberb-cloud/news.ts +35 -0
  183. package/src/sources/provider-errors.ts +34 -7
  184. package/src/sources/provider-router/history.ts +32 -6
  185. package/src/time-series/base-series.ts +39 -6
  186. package/src/time-series/chart-seed.ts +2 -2
  187. package/src/time-series/history-quality.ts +4 -1
  188. package/src/time-series/hooks.ts +2 -0
  189. package/src/time-series/price-comparison.ts +17 -23
  190. package/src/time-series/reporting.ts +1 -1
  191. package/src/time-series/resolution.ts +13 -0
  192. package/src/time-series/resolve-context.ts +6 -0
  193. package/src/time-series/resolve.ts +39 -2
  194. package/src/time-series/types.ts +2 -1
  195. package/src/types/financials.ts +9 -1
  196. package/src/types/headless.ts +1 -0
  197. package/src/types/issuer-listings.ts +2 -0
  198. package/src/types/plugin-notifications.ts +3 -0
  199. package/src/types/price-history.ts +6 -4
  200. package/src/ui/host.tsx +2 -0
  201. package/src/utils/exchange-announcements.ts +7 -2
  202. package/src/utils/fundamentals.ts +40 -0
  203. package/src/utils/network-failure.ts +2 -0
  204. package/src/utils/price-history-integrity.ts +9 -1
@@ -1,9 +1,10 @@
1
1
  import { logFailure } from "../../utils/log-failure";
2
2
  import { apiClient } from "../../api-client";
3
3
  import { loadResolvedHeadlessPaneModel, reportCoverage, reportGaps, type LoadedHeadlessPaneModel } from "./headless";
4
- import { createOutputFolder } from "../output-file";
4
+ import { createOutputFolder, writeOutputFile } from "../output-file";
5
5
  import type { Quote } from "../../types/financials";
6
6
  import { isRecord } from "../../utils/guards";
7
+ import { savedCopyAt, savedCopyShownAt } from "../../data/saved-copies";
7
8
  import {
8
9
  prepareDesktopPaneShotView,
9
10
  renderDesktopPaneScreenshot,
@@ -43,7 +44,7 @@ export function shotHasStatusLine(resolved: Pick<ResolvedPaneFunction, "pane" |
43
44
  }
44
45
 
45
46
  /** The bridge, keeping every quote it serves the page: what a pane that loads its own quotes (WEI) shows. */
46
- function recordBridgedQuotes(bridge: DesktopPaneShotBridge): { bridge: DesktopPaneShotBridge; quotes: Quote[] } {
47
+ function recordBridgedQuotes(bridge: DesktopPaneShotBridge, onSavedCopy?: (savedAt: number) => void): { bridge: DesktopPaneShotBridge; quotes: Quote[] } {
47
48
  const quotes: Quote[] = [];
48
49
  const keep = (value: unknown) => {
49
50
  if (isRecord(value) && typeof value.symbol === "string" && typeof value.price === "number") quotes.push(value as unknown as Quote);
@@ -54,6 +55,9 @@ function recordBridgedQuotes(bridge: DesktopPaneShotBridge): { bridge: DesktopPa
54
55
  ...bridge,
55
56
  async marketData(operation, args) {
56
57
  const result = await bridge.marketData(operation, args);
58
+ // The page gets the answer as JSON, which drops its saved-copy mark: the report keeps when it was saved.
59
+ const savedAt = savedCopyAt(result) ?? savedCopyShownAt(result);
60
+ if (savedAt != null) onSavedCopy?.(savedAt);
57
61
  if (operation === "getQuote") keep(result);
58
62
  if (operation === "getQuotesBatch" && Array.isArray(result)) {
59
63
  for (const entry of result) keep(isRecord(entry) ? entry.quote : null);
@@ -225,6 +229,7 @@ export async function renderDesktopShot({
225
229
  maxHeightCells,
226
230
  options,
227
231
  captureImage = true,
232
+ onlyUsable = false,
228
233
  onStalledReport,
229
234
  onDrawing,
230
235
  }: {
@@ -247,6 +252,7 @@ export async function renderDesktopShot({
247
252
  maxHeightCells?: number;
248
253
  options: Record<string, string | true>;
249
254
  captureImage?: boolean;
255
+ onlyUsable?: boolean;
250
256
  /**
251
257
  * Called when the report behind the status line was still loading at the
252
258
  * wait's end: the load was aborted, but a loader that ignores the signal
@@ -255,13 +261,17 @@ export async function renderDesktopShot({
255
261
  onStalledReport?: () => void;
256
262
  /** Called once the pane's data is read and the page starts to draw it. */
257
263
  onDrawing?: () => void;
258
- }): Promise<PaneScreenshotResult> {
264
+ }): Promise<PaneScreenshotResult & { saved: boolean }> {
259
265
  prepareDesktopPaneShotView();
260
266
  if (captureImage) await createOutputFolder(outputPath);
261
- const apiProxy = resolveDesktopShotApiProxy(context);
267
+ // The copies saved earlier the page drew from, where the data service did not answer.
268
+ const savedCopies: number[] = [];
269
+ const onSavedCopy = (savedAt: number) => { savedCopies.push(savedAt); };
270
+ const apiProxy = { ...resolveDesktopShotApiProxy(context), onSavedCopy };
262
271
  const previousSessionToken = apiClient.getSessionToken();
263
272
  let payload: DesktopPaneShotPayload;
264
273
  let render: DesktopPaneShotRenderResult;
274
+ let image: Uint8Array | undefined;
265
275
  let freshness: ReportFreshness | undefined;
266
276
  let coverage: Promise<ShotReportCoverage | undefined> | undefined;
267
277
  let covered: ShotReportCoverage | undefined;
@@ -307,9 +317,9 @@ export async function renderDesktopShot({
307
317
  const report = payload.statusLine ? reportShotFreshness(resolved, loadModel) : undefined;
308
318
  // The same load says whether the report is complete, with or without a status line.
309
319
  coverage = captureImage ? reportShotCoverage(resolved, loadModel) : undefined;
310
- const recorded = recordBridgedQuotes(createDesktopShotBridge(context));
320
+ const recorded = recordBridgedQuotes(createDesktopShotBridge(context), onSavedCopy);
311
321
  const shotPayload = payload;
312
- render = await renderDesktopPaneScreenshot(payload, outputPath, apiProxy, {
322
+ ({ image, ...render } = await renderDesktopPaneScreenshot(payload, apiProxy, {
313
323
  captureImage,
314
324
  bridge: recorded.bridge,
315
325
  statusLine: async (rendered) => {
@@ -327,7 +337,7 @@ export async function renderDesktopShot({
327
337
  return { variants: unread ? line.variants.map((variant) => `${variant} · ${unread}`) : line.variants, dates: line.dates,
328
338
  dateEvidence: statusDateEvidence(line.freshness) };
329
339
  },
330
- });
340
+ }));
331
341
  covered = coverage && await settledWithin(coverage, SHOT_REPORT_WAIT_MS);
332
342
  } finally {
333
343
  apiClient.setSessionToken(previousSessionToken);
@@ -336,8 +346,11 @@ export async function renderDesktopShot({
336
346
  const renderedInstance = payload.config.layout.instances.find(({ instanceId }) => instanceId === payload.paneId);
337
347
  if (renderedInstance) resolved = { ...resolved, instance: renderedInstance };
338
348
  const assessed = withReportCoverage(assessPaneScreenshot(resolved, payload, render, rawArg, outputPath), covered);
349
+ const save = image && (!onlyUsable || assessed.usable) ? image : undefined;
350
+ if (save) await writeOutputFile(outputPath, save);
339
351
  const unreadRows = payload.unreadRows?.length ? { unreadRows: payload.unreadRows, ...(payload.unreadReasons ? { unreadReasons: payload.unreadReasons } : {}) } : {};
340
- return freshness ? { ...assessed, ...unreadRows, freshness } : { ...assessed, ...unreadRows };
352
+ return { ...assessed, ...unreadRows, saved: save !== undefined, ...(freshness ? { freshness } : {}),
353
+ ...(savedCopies.length > 0 ? { savedCopyAt: Math.min(...savedCopies) } : {}) };
341
354
  }
342
355
 
343
356
  /** "FRC did not load": a list's rows whose read failed, as the capture's status line marks them. */
@@ -5,6 +5,8 @@ import type { PaneScreenshotEvidence } from "./screenshot-evidence";
5
5
  import type { ReportFreshness } from "./freshness";
6
6
  import type { PaneScreenshotFinancialRatioEvidence } from "./financial-ratio-shot";
7
7
 
8
+ export const PANE_SWEEP_EVIDENCE_PATH = "GLOOMBERB_PANE_SWEEP_EVIDENCE_PATH";
9
+
8
10
  export interface PaneScreenshotExpectedSelection {
9
11
  control: "metric" | "statement" | "ratio" | "period";
10
12
  value?: string;
@@ -108,6 +110,7 @@ export type PaneScreenshotDataEvidence =
108
110
  | PaneScreenshotEvidence;
109
111
 
110
112
  export interface PaneScreenshotReadinessSignals {
113
+ confirmedEmpty?: boolean;
111
114
  /**
112
115
  * A surface to operate rather than data to read (Layouts, Brokers): its rows
113
116
  * and an empty-state marker inside it say nothing of whether it rendered.
@@ -145,6 +148,12 @@ export interface PaneScreenshotResult {
145
148
  empty: boolean;
146
149
  complete: boolean;
147
150
  unavailableSymbols: string[];
151
+ /**
152
+ * When the oldest copy the page drew from was saved (ms): a read the data
153
+ * service did not answer was answered from a copy saved earlier, through
154
+ * the market bridge or the API proxy. A report dates its view as saved.
155
+ */
156
+ savedCopyAt?: number;
148
157
  /** Rows of a list whose read failed (refused, timed out): pictured without figures and named on the status line. */
149
158
  unreadRows?: string[];
150
159
  /** Why each of `unreadRows` did not load, as the source answered. */
@@ -303,7 +303,7 @@ async function answerNamedListing(
303
303
  datesChangeBasis: boolean,
304
304
  ): Promise<QuoteAnswer | null> {
305
305
  // A listing on a venue the app cannot read is no answer: the word keeps its own.
306
- const resolved = await resolveCliListing(named.key, null, market).catch((error: unknown) => {
306
+ const resolved = await resolveCliListing(named.key, null, market, { listingAbroad: false }).catch((error: unknown) => {
307
307
  if (error instanceof ListingArgError) return null;
308
308
  throw error;
309
309
  });
package/src/cli/result.ts CHANGED
@@ -20,6 +20,9 @@ import { portableCsv } from "./csv-export";
20
20
  import { logFailure } from "../utils/log-failure";
21
21
  import { formatUtcTime, isEpochMilliseconds, isZonedIsoDateTime } from "../utils/utc-time";
22
22
  import { formatFreshnessLine, withSavedCopy, type ReportFreshness } from "./pane-functions/freshness";
23
+ import { savedCopyShownAt } from "../data/saved-copies";
24
+ import { dataServiceUnreachable } from "../api-client/request";
25
+ import { savedCopyUnreachableWarning } from "./unreachable";
23
26
  import { withSearchHints, type FredSeriesCheck } from "./not-a-ticker";
24
27
  import {
25
28
  exportJsonValue,
@@ -716,6 +719,19 @@ function withHintedCells<T>(result: CliResult<T>, hinted: (text: string) => stri
716
719
  return changed ? { ...result, data: data as T } : result;
717
720
  }
718
721
 
722
+ /**
723
+ * A result shown from saved copies while the data service went unanswered,
724
+ * with the warning that says so (`savedCopyUnreachableWarning`); any other as it is.
725
+ */
726
+ export function withUnreachedSavedCopyWarning<T>(result: CliResult<T>): CliResult<T> {
727
+ if (!dataServiceUnreachable()) return result;
728
+ const cited = result.freshness ?? result.exportFreshness;
729
+ const saved = cited ? withSavedCopy(cited, result.data).savedAt != null : savedCopyShownAt(result.data) != null;
730
+ if (!saved) return result;
731
+ const warning = savedCopyUnreachableWarning();
732
+ return result.warnings?.includes(warning) ? result : { ...result, warnings: [...result.warnings ?? [], warning] };
733
+ }
734
+
719
735
  export function printCliResult<T, Row extends Record<string, unknown> = Record<string, unknown>>(
720
736
  result: CliResult<T>,
721
737
  options: CliGlobalOptions,
@@ -724,6 +740,7 @@ export function printCliResult<T, Row extends Record<string, unknown> = Record<s
724
740
  isFredSeries?: FredSeriesCheck,
725
741
  ): void {
726
742
  if (options.quiet && options.format === "text") return;
743
+ result = withUnreachedSavedCopyWarning(result);
727
744
  // JSON keeps the router's own words; everything else is for a person, so a "Not a ticker" gets its hint.
728
745
  const hinted = (text: string) => options.format === "json" ? text : withSearchHints(text, args, isFredSeries);
729
746
  // A CSV's status cell is where its row says why, so it gets the hint the warning line has: a cell ends in a comma,
@@ -20,7 +20,7 @@ export interface ScrollBoxMetrics {
20
20
  * centred on the money is cut above and below, a list at its top only below.
21
21
  * Self-contained so the screenshot runner can evaluate it in the browser.
22
22
  */
23
- export function scrollTruncationReasons(box: ScrollBoxMetrics): string[] {
23
+ export function scrollTruncationReasons(box: ScrollBoxMetrics, rowsAnnounced = false): string[] {
24
24
  const reasons: string[] = [];
25
25
  const cut = (offset: number, content: number, viewport: number, flagged: boolean, noun: string, sides: readonly [string, string, string, string]) => {
26
26
  if (!flagged && !(content > viewport + 1)) return;
@@ -32,7 +32,12 @@ export function scrollTruncationReasons(box: ScrollBoxMetrics): string[] {
32
32
  ? `${noun} ${before && after ? sides[2] : before ? sides[0] : sides[1]} the rendered viewport are cut`
33
33
  : `${noun} ${sides[3]} the rendered viewport may be cut`);
34
34
  };
35
- cut(box.scrollTop, box.scrollHeight, box.clientHeight, box.scrollbarY, "rows", ["above", "below", "above and below", "above or below"]);
35
+ if (!rowsAnnounced) cut(box.scrollTop, box.scrollHeight, box.clientHeight, box.scrollbarY, "rows", ["above", "below", "above and below", "above or below"]);
36
36
  cut(box.scrollLeft, box.scrollWidth, box.clientWidth, box.scrollbarX, "columns", ["left of", "right of", "left and right of", "left or right of"]);
37
37
  return reasons;
38
38
  }
39
+
40
+ export function rowViewportVisibility(top: number, bottom: number, viewportTop: number, viewportBottom: number): "outside" | "partial" | "whole" {
41
+ if (bottom <= viewportTop + 1 || top >= viewportBottom - 1) return "outside";
42
+ return top >= viewportTop - 1 && bottom <= viewportBottom + 1 ? "whole" : "partial";
43
+ }
@@ -235,7 +235,7 @@ export async function resolveCliTicker(
235
235
  const deps: ListingDeps = { store, dataProvider };
236
236
  // A vendor's suffix is the venue it names (GARAN.IS is GARAN:BIST), so the listing is saved under one key. A word that
237
237
  // names a company is read below, once the lookup says no listing trades as it (`oneWordCompanyName`).
238
- const listing = await resolveCliListing(symbol, exchange, deps, { ownExchangeWins: options.ownExchangeWins, listingSuffix: true, companyWord: false });
238
+ const listing = await resolveCliListing(symbol, exchange, deps, { ownExchangeWins: options.ownExchangeWins, listingSuffix: true, companyWord: false, listingAbroad: false });
239
239
  const read = listingReadNotes(listing);
240
240
  // Looked up beside the search, so saying FB is now META costs no wait.
241
241
  const changes = options.changes === false ? null : startTickerChangeLookup(dataProvider, listing.symbol, listing.exchange);
@@ -0,0 +1,21 @@
1
+ import { DATA_SERVICE_UNREACHABLE_MESSAGE } from "../utils/network-failure";
2
+
3
+ /** What to check when nothing answered: the connection, and the proxy when one is set. */
4
+ export function unreachableHint(): string {
5
+ const env = typeof process === "undefined" ? {} : process.env;
6
+ const proxy = ["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"].find((name) => env[name]?.trim());
7
+ return proxy
8
+ ? `Check the internet connection and the proxy in ${proxy}, then try again.`
9
+ : "Check the internet connection, then try again.";
10
+ }
11
+
12
+ /**
13
+ * What a command that answered from saved copies says when the data service
14
+ * went unanswered: the words a command with nothing to show fails with
15
+ * (`unreachableError`), and that what it printed is the copy its source line
16
+ * dates. Offline, DES printed a saved quote as "15 min delayed" and nothing
17
+ * said the service was never reached.
18
+ */
19
+ export function savedCopyUnreachableWarning(): string {
20
+ return `${DATA_SERVICE_UNREACHABLE_MESSAGE}, so this is the copy saved earlier. ${unreachableHint()}`;
21
+ }
@@ -1,11 +1,12 @@
1
1
  import { useCallback, useEffect, useRef } from "react";
2
2
  import { usePaneSettingValue } from "../../../state/app/context";
3
- import { CHART_DRAWINGS_SETTING_KEY, parseChartDrawings, type ChartDrawing } from "./tools";
3
+ import { CHART_DRAWINGS_SETTING_KEY, readSavedChartDrawings, type ChartDrawing, type SavedChartDrawings } from "./tools";
4
4
 
5
5
  let nextDrawingSequence = 1;
6
6
 
7
+ /** Drawings are saved with the pane, so, like levels, their ids must not repeat across sessions. */
7
8
  export function nextDrawingId(): string {
8
- return `drawing:${nextDrawingSequence++}`;
9
+ return `drawing:${Date.now().toString(36)}-${(nextDrawingSequence++).toString(36)}`;
9
10
  }
10
11
 
11
12
  /** Levels are stored with the account, so their ids must not repeat across sessions. */
@@ -36,19 +37,19 @@ export function ChartDrawingStore({
36
37
  NO_DRAWINGS,
37
38
  paneInstanceId,
38
39
  );
39
- const restoredRef = useRef<readonly ChartDrawing[] | null>(null);
40
+ const restoredRef = useRef<SavedChartDrawings | null>(null);
40
41
  if (restoredRef.current === null) {
41
- restoredRef.current = parseChartDrawings(stored);
42
+ restoredRef.current = readSavedChartDrawings(stored);
42
43
  }
43
44
  // What the settings hold, so removing the last drawing is told even when the
44
45
  // pane opened with none: it is not "nothing to say" but "the stored one is gone".
45
- const writtenRef = useRef<readonly ChartDrawing[]>(restoredRef.current);
46
+ const writtenRef = useRef<readonly ChartDrawing[]>(restoredRef.current.drawings);
46
47
  const pendingRef = useRef<readonly ChartDrawing[] | null>(null);
47
48
  const setStoredRef = useRef(setStored);
48
49
  setStoredRef.current = setStored;
49
50
 
50
51
  useEffect(() => {
51
- const restored = restoredRef.current;
52
+ const restored = restoredRef.current?.drawings;
52
53
  if (restored && restored.length > 0) onRestore(restored);
53
54
  // Restoring once on mount: later writes must not scroll back in time.
54
55
  }, []);
@@ -56,7 +57,10 @@ export function ChartDrawingStore({
56
57
  const write = useCallback((next: readonly ChartDrawing[]) => {
57
58
  pendingRef.current = null;
58
59
  writtenRef.current = next;
59
- setStoredRef.current(next);
60
+ // Saved entries this build cannot read ride along, so the next edit never
61
+ // writes away a drawing a newer build made.
62
+ const unreadable = restoredRef.current?.unreadable ?? [];
63
+ setStoredRef.current(unreadable.length > 0 ? [...next, ...unreadable as ChartDrawing[]] : next);
60
64
  }, []);
61
65
 
62
66
  useEffect(() => {
@@ -783,6 +783,7 @@ export function formatCompositePointDetails(point: TimeSeriesPoint | null | unde
783
783
  details.push(`${isFiscalPeriod ? "Period ended" : "Observed"} ${observedAt}`);
784
784
  }
785
785
  if (availableAt && availableAt !== observedAt) details.push(`Available ${availableAt}`);
786
+ if (point.nativeAmount) details.push(`Native ${compactNumber(point.nativeAmount.value)} ${point.nativeAmount.currency}`);
786
787
 
787
788
  const quality = point.provenance?.quality;
788
789
  if (quality) details.push(`${quality[0]!.toUpperCase()}${quality.slice(1)}`);
@@ -2,7 +2,7 @@ import { memo, useEffect, useRef } from "react";
2
2
  import { Box, ScrollBox, Span, Text, useShortcutLabel, useUiCapabilities, type ScrollBoxRenderable } from "../../../ui";
3
3
  import { colors as themeColors, hoverBg } from "../../../theme/colors";
4
4
  import { CANONICAL_EXCHANGE_ALIASES } from "../../../utils/exchanges";
5
- import { MISSING_VALUE, displayWidth, formatPercentRaw } from "../../../utils/format";
5
+ import { MISSING_VALUE, displayWidth, formatPercentRaw, formatCompact } from "../../../utils/format";
6
6
  import type { ResolvedSeries } from "../../../time-series/types";
7
7
  import { consumeChartMouseEvent, type ChartMouseEvent } from "../core/pointer";
8
8
  import {
@@ -333,8 +333,11 @@ export function CompositeLegend({
333
333
  // What a futures price counts, beside its number as FUT prints it.
334
334
  const statedUnit = entry.points.length > 0 && !formatValue && entry.statedUnit ? ` ${entry.statedUnit}` : "";
335
335
  // A statement value names the fiscal period it reports, as FA's columns do.
336
+ const native = cursorValue?.point?.nativeAmount;
337
+ const statementEnd = native ? cursorValue?.point?.observedAt.toISOString().slice(0, 10) : undefined;
336
338
  const fiscalPeriod = withFiscalPeriods && cursorValue?.value != null ? cursorValue.point?.fiscalPeriod : undefined;
337
- const valueTail = `${ownDate ? ` ${ownDate}` : ""}${fiscalPeriod ? ` ${fiscalPeriod}` : ""}${changeText}`;
339
+ const readDate = statementEnd ?? ownDate;
340
+ const valueTail = `${readDate ? ` ${readDate}` : ""}${fiscalPeriod && !statementEnd ? ` ${fiscalPeriod}` : ""}${native && withFiscalPeriods ? ` (${formatCompact(native.value)} ${native.currency})` : ""}${changeText}`;
338
341
  const readsRight = entry.points.length > 0 && entry.axis === "right" && leftPanels.has(entry.panelId);
339
342
  const axisNote = readsRight && withAxisNotes ? RIGHT_AXIS_NOTE : "";
340
343
  const valueText = entry.points.length === 0
@@ -75,6 +75,8 @@ export function usePlotGestures({
75
75
  renderer,
76
76
  plotSize,
77
77
  plotAspect,
78
+ cellWidthPx,
79
+ cellHeightPx,
78
80
  plotSpanFactor,
79
81
  setToolDrag,
80
82
  levelDomain,
@@ -96,6 +98,8 @@ export function usePlotGestures({
96
98
  renderer: ReturnType<typeof useNativeRenderer>;
97
99
  plotSize: MeasuredCellSize;
98
100
  plotAspect: number;
101
+ cellWidthPx: number;
102
+ cellHeightPx: number;
99
103
  plotSpanFactor: number;
100
104
  setToolDrag: Dispatch<SetStateAction<ChartToolDrag | null>>;
101
105
  levelDomain: CompositeAxisDomain | null;
@@ -358,14 +362,17 @@ export function usePlotGestures({
358
362
  }
359
363
  setToolDrag(null);
360
364
  if (isDrawingTool(drag.kind)) {
361
- const drawing = resolveDrawingFromDrag(scene, panel, drag, drawColor, nextDrawingId());
365
+ const drawing = resolveDrawingFromDrag(scene, panel, drag, drawColor, nextDrawingId(), {
366
+ width: plotSize.width * cellWidthPx,
367
+ height: plotSize.height * cellHeightPx,
368
+ });
362
369
  if (drawing) onDraw(drawing);
363
370
  return;
364
371
  }
365
372
  if (drag.kind !== "zoom") return;
366
373
  const range = resolveZoomBoxRange(scene, drag, frame.minimumSpanMs);
367
374
  if (range) onSetViewport(range);
368
- }, [drawColor, frame.minimumSpanMs, levels, onDraw, onSetViewport, panel, scene]);
375
+ }, [cellHeightPx, cellWidthPx, drawColor, frame.minimumSpanMs, levels, onDraw, onSetViewport, panel, plotSize.height, plotSize.width, scene]);
369
376
  const resetDrag = useCallback(() => {
370
377
  const drag = dragRef.current;
371
378
  if (drag?.kind === "pan") {
@@ -153,7 +153,7 @@ export function CompositePanelSurface({
153
153
  panel, scene, frame, viewport, armedTool, drawings, drawColor, levels, plotWidth,
154
154
  onActivate, onPointerPress, onPickTime, onPickPrice, onSelectDrawing, onEditDrawing, onDraw, onSelectLevel,
155
155
  onPanViewport, onSetViewport, onSetValueScale, onDragActiveChange, onToggleMaximized,
156
- isDesktopWeb, renderer, plotSize, plotAspect, plotSpanFactor, setToolDrag,
156
+ isDesktopWeb, renderer, plotSize, plotAspect, cellWidthPx, cellHeightPx, plotSpanFactor, setToolDrag,
157
157
  levelDomain, projectedLevels, levelDraftRef, setLevelDraft,
158
158
  plotPointer, pointerRatios, updateCursor, stopCoast, startCoast,
159
159
  });
@@ -11,6 +11,7 @@ import type {
11
11
  CompositePanelScene,
12
12
  } from "./types";
13
13
  import { clamp } from "../../../utils/math";
14
+ import { isRecord } from "../../../utils/guards";
14
15
 
15
16
  /** Pointer tools that take the drag away from panning while one is picked. */
16
17
  export type ChartToolKind = "measure" | "zoom" | "line" | "pencil" | "level" | "rect" | "fib" | "ray";
@@ -36,54 +37,129 @@ export interface ChartDrawing {
36
37
  }
37
38
 
38
39
  export const CHART_DRAWINGS_SETTING_KEY = "chartDrawings";
40
+
41
+ // What a public link to a chart carries, and what a link it receives is held
42
+ // to. A pane's own saved drawings have no cap: they are the person's work.
39
43
  const MAX_SHARED_CHART_DRAWINGS = 100;
40
44
  const MAX_SHARED_DRAWING_POINTS = 5_000;
45
+ // A shared pane fits in 128 KB; a chart's setup takes a KB or two of the rest.
46
+ const MAX_SHARED_DRAWING_BYTES = 96 * 1024;
47
+
48
+ const MAX_DRAWING_ID_LENGTH = 160;
49
+ const DRAWING_KEYS: ReadonlySet<string> = new Set(["id", "panelId", "points", "color"]);
50
+
51
+ /** One saved drawing, or null when this build cannot read it. */
52
+ function parseChartDrawing(entry: unknown): ChartDrawing | null {
53
+ if (!isRecord(entry) || !Object.keys(entry).every((key) => DRAWING_KEYS.has(key))) return null;
54
+ if (
55
+ typeof entry.id !== "string"
56
+ || entry.id.length === 0
57
+ || entry.id.length > MAX_DRAWING_ID_LENGTH
58
+ || typeof entry.panelId !== "string"
59
+ || entry.panelId.length === 0
60
+ || entry.panelId.length > 120
61
+ || typeof entry.color !== "string"
62
+ || !/^#[0-9a-f]{6}$/i.test(entry.color)
63
+ || !Array.isArray(entry.points)
64
+ || entry.points.length < 2
65
+ ) return null;
66
+ const points: ChartDrawingPoint[] = [];
67
+ for (const point of entry.points) {
68
+ if (
69
+ !isRecord(point)
70
+ || !Object.keys(point).every((key) => key === "time" || key === "value")
71
+ || typeof point.time !== "number"
72
+ || !Number.isFinite(point.time)
73
+ || typeof point.value !== "number"
74
+ || !Number.isFinite(point.value)
75
+ ) return null;
76
+ points.push({ time: point.time, value: point.value });
77
+ }
78
+ return { id: entry.id, panelId: entry.panelId, points, color: entry.color };
79
+ }
80
+
81
+ /** `id` with a mark that no drawing in `taken` has; the shape prefix stays first. */
82
+ function unusedDrawingId(id: string, taken: ReadonlySet<string>): string {
83
+ const base = id.slice(0, MAX_DRAWING_ID_LENGTH - 8);
84
+ for (let copy = 2; ; copy += 1) {
85
+ const candidate = `${base}~${copy}`;
86
+ if (!taken.has(candidate)) return candidate;
87
+ }
88
+ }
89
+
90
+ export interface SavedChartDrawings {
91
+ drawings: ChartDrawing[];
92
+ /** Entries this build cannot read, as they were, so writing the list back keeps them. */
93
+ unreadable: unknown[];
94
+ }
41
95
 
96
+ /**
97
+ * A pane's own saved drawings. An entry this build cannot read (damaged, or
98
+ * written by a newer build) is set aside on its own and every other one
99
+ * restores. Older builds reused ids across restarts, so two drawings can share
100
+ * one; the later gets an id of its own, or removing one would take both.
101
+ */
102
+ export function readSavedChartDrawings(value: unknown): SavedChartDrawings {
103
+ const saved: SavedChartDrawings = { drawings: [], unreadable: [] };
104
+ if (!Array.isArray(value)) return saved;
105
+ const ids = new Set<string>();
106
+ for (const entry of value) {
107
+ const drawing = parseChartDrawing(entry);
108
+ if (!drawing) {
109
+ saved.unreadable.push(entry);
110
+ continue;
111
+ }
112
+ const id = ids.has(drawing.id) ? unusedDrawingId(drawing.id, ids) : drawing.id;
113
+ ids.add(id);
114
+ saved.drawings.push(id === drawing.id ? drawing : { ...drawing, id });
115
+ }
116
+ return saved;
117
+ }
118
+
119
+ /** Every drawing of a pane's own saved list that this build can read. */
42
120
  export function parseChartDrawings(value: unknown): ChartDrawing[] {
43
- if (!Array.isArray(value) || value.length > MAX_SHARED_CHART_DRAWINGS) return [];
121
+ return readSavedChartDrawings(value).drawings;
122
+ }
123
+
124
+ /**
125
+ * The drawings a received public link carries: all of them readable and
126
+ * within what a link carries, else null.
127
+ */
128
+ export function parseSharedChartDrawings(value: unknown): ChartDrawing[] | null {
129
+ if (!Array.isArray(value) || value.length > MAX_SHARED_CHART_DRAWINGS) return null;
44
130
  let pointCount = 0;
45
131
  const drawings: ChartDrawing[] = [];
46
132
  for (const entry of value) {
47
- if (!entry || typeof entry !== "object" || Array.isArray(entry)) return [];
48
- const drawing = entry as Record<string, unknown>;
49
- if (!Object.keys(drawing).every((key) => ["id", "panelId", "points", "color"].includes(key))) return [];
50
- if (
51
- typeof drawing.id !== "string"
52
- || drawing.id.length === 0
53
- || drawing.id.length > 160
54
- || typeof drawing.panelId !== "string"
55
- || drawing.panelId.length === 0
56
- || drawing.panelId.length > 120
57
- || typeof drawing.color !== "string"
58
- || !/^#[0-9a-f]{6}$/i.test(drawing.color)
59
- || !Array.isArray(drawing.points)
60
- || drawing.points.length < 2
61
- ) return [];
62
- pointCount += drawing.points.length;
63
- if (pointCount > MAX_SHARED_DRAWING_POINTS) return [];
64
- const points: ChartDrawingPoint[] = [];
65
- for (const point of drawing.points) {
66
- if (!point || typeof point !== "object" || Array.isArray(point)) return [];
67
- const raw = point as Record<string, unknown>;
68
- if (
69
- !Object.keys(raw).every((key) => key === "time" || key === "value")
70
- || typeof raw.time !== "number"
71
- || !Number.isFinite(raw.time)
72
- || typeof raw.value !== "number"
73
- || !Number.isFinite(raw.value)
74
- ) return [];
75
- points.push({ time: raw.time, value: raw.value });
76
- }
77
- drawings.push({
78
- id: drawing.id,
79
- panelId: drawing.panelId,
80
- points,
81
- color: drawing.color,
82
- });
133
+ pointCount += isRecord(entry) && Array.isArray(entry.points) ? entry.points.length : 0;
134
+ const drawing = pointCount > MAX_SHARED_DRAWING_POINTS ? null : parseChartDrawing(entry);
135
+ if (!drawing) return null;
136
+ drawings.push(drawing);
83
137
  }
84
138
  return drawings;
85
139
  }
86
140
 
141
+ const utf8 = new TextEncoder();
142
+
143
+ /**
144
+ * What of a pane's drawings a public link carries: the newest that fit in one,
145
+ * in their order. A chart with more shares its latest work, not nothing, and
146
+ * every build opens the link with its drawings.
147
+ */
148
+ export function shareableChartDrawings(drawings: readonly ChartDrawing[]): ChartDrawing[] {
149
+ const kept: ChartDrawing[] = [];
150
+ let points = 0;
151
+ let bytes = 2;
152
+ for (let index = drawings.length - 1; index >= 0 && kept.length < MAX_SHARED_CHART_DRAWINGS; index -= 1) {
153
+ const drawing = drawings[index]!;
154
+ const size = utf8.encode(JSON.stringify(drawing)).byteLength + 1;
155
+ if (points + drawing.points.length > MAX_SHARED_DRAWING_POINTS || bytes + size > MAX_SHARED_DRAWING_BYTES) continue;
156
+ kept.push(drawing);
157
+ points += drawing.points.length;
158
+ bytes += size;
159
+ }
160
+ return kept.reverse();
161
+ }
162
+
87
163
  /**
88
164
  * The shape rides in the id (`fib:3`) rather than a field of its own: an older
89
165
  * build refuses a saved drawing with a key it does not know and would drop every
@@ -149,13 +225,62 @@ function drawingPointFrom(
149
225
  : { time: unprojectCompositeTimestamp(scene.timeScale, xRatio), value };
150
226
  }
151
227
 
152
- /** Data anchors for a finished drag, so a drawing survives pan and zoom. */
228
+ /** The plot's size in pixels, which a freehand stroke is simplified against. */
229
+ interface PlotPixelSize {
230
+ width: number;
231
+ height: number;
232
+ }
233
+
234
+ /**
235
+ * How far, in plot pixels, a saved freehand stroke may stray from the trail
236
+ * the pointer drew: under one, so the stroke looks the same once let go.
237
+ */
238
+ const STROKE_TOLERANCE_PX = 0.5;
239
+
240
+ /**
241
+ * The pointer's trail with only the points its shape needs: every point it had
242
+ * stays within `STROKE_TOLERANCE_PX` of the line through the ones kept
243
+ * (Ramer-Douglas-Peucker). The pointer reports every move, so a slow or long
244
+ * stroke would otherwise save thousands of points along the same line.
245
+ */
246
+ function simplifyStroke<T extends { xRatio: number; yRatio: number }>(path: readonly T[], plot: PlotPixelSize): T[] {
247
+ if (path.length <= 2 || !(plot.width > 0 && plot.height > 0)) return [...path];
248
+ const pixels = path.map((point) => ({ x: point.xRatio * plot.width, y: point.yRatio * plot.height }));
249
+ const keep = new Uint8Array(path.length);
250
+ keep[0] = 1;
251
+ keep[path.length - 1] = 1;
252
+ // A stack, not recursion: a long stroke is thousands of points deep.
253
+ const spans: Array<[number, number]> = [[0, path.length - 1]];
254
+ while (spans.length > 0) {
255
+ const [first, last] = spans.pop()!;
256
+ let farthest = -1;
257
+ let distance = STROKE_TOLERANCE_PX;
258
+ for (let index = first + 1; index < last; index += 1) {
259
+ // To the segment, not its line: a stroke that doubles back keeps its turn.
260
+ const next = distanceToSegment(pixels[index]!, pixels[first]!, pixels[last]!);
261
+ if (next > distance) {
262
+ distance = next;
263
+ farthest = index;
264
+ }
265
+ }
266
+ if (farthest < 0) continue;
267
+ keep[farthest] = 1;
268
+ spans.push([first, farthest], [farthest, last]);
269
+ }
270
+ return path.filter((_, index) => keep[index] === 1);
271
+ }
272
+
273
+ /**
274
+ * Data anchors for a finished drag, so a drawing survives pan and zoom. Given
275
+ * the plot's pixel size, a freehand stroke keeps only the points its shape needs.
276
+ */
153
277
  export function resolveDrawingFromDrag(
154
278
  scene: Pick<CompositeChartScene, "timeScale">,
155
279
  panel: CompositePanelScene,
156
280
  drag: ChartToolDrag,
157
281
  color: string,
158
282
  id: string,
283
+ plot?: PlotPixelSize,
159
284
  ): ChartDrawing | null {
160
285
  const domain = resolveMeasureAxisDomain(panel);
161
286
  // A ray needs only its price, so a click places one.
@@ -169,7 +294,7 @@ export function resolveDrawingFromDrag(
169
294
  return start && end ? { id: shapedDrawingId(drag.kind, id), panelId: panel.id, points: [start, end], color } : null;
170
295
  }
171
296
  const source = drag.kind === "pencil" && drag.path.length > 1
172
- ? drag.path
297
+ ? plot ? simplifyStroke(drag.path, plot) : drag.path
173
298
  : [
174
299
  { xRatio: drag.startXRatio, yRatio: drag.startYRatio },
175
300
  { xRatio: drag.endXRatio, yRatio: drag.endYRatio },
@@ -76,7 +76,7 @@ export interface ChartTableHeaderProps {
76
76
  height: number;
77
77
  /** Body rows the table holds. */
78
78
  tableRows: number;
79
- /** Table header rows, plus one when its columns overflow into a scrollbar. */
79
+ /** Rows occupied by the table header, disclosure and scrollbars. */
80
80
  tableChromeRows?: number;
81
81
  /** The table's columns, to count its scrollbar row when `tableChromeRows` is not given. */
82
82
  tableColumns?: readonly TableWidthColumn[];
@@ -181,7 +181,7 @@ export function useChartTableLayout(props: ChartTableHeaderProps): ChartTableLay
181
181
  figures: props.figures,
182
182
  tableRows: props.tableRows,
183
183
  tableChromeRows: props.tableChromeRows
184
- ?? (props.tableColumns ? chartTableChromeRows(props.tableColumns, props.width) : undefined),
184
+ ?? (props.tableColumns ? chartTableChromeRows(props.tableColumns, props.width, props.tableRows) : undefined),
185
185
  chart: hasChart
186
186
  ? {
187
187
  minRows: chart.minRows,
@@ -1,5 +1,5 @@
1
1
  import { statGridRows, type StatItem } from "../ui/stat-grid";
2
- import { getTableWidth, hasMeaningfulTableHorizontalOverflow, type TableWidthColumn } from "../ui/table-layout";
2
+ import { getTableWidth, hasMeaningfulTableHorizontalOverflow, hiddenTableColumnRows, type TableWidthColumn } from "../ui/table-layout";
3
3
 
4
4
  /** Drop optional columns in priority order, using the same widths as the table. */
5
5
  export function fitChartTableColumns<C extends TableWidthColumn & { id: string }>(
@@ -34,12 +34,11 @@ const FIGURE_SHARE = 0.25;
34
34
  const WRAPPED_FIGURE_SHARE = 1 / 3;
35
35
 
36
36
  /**
37
- * The rows a kit table spends outside its body: the header, plus a horizontal
38
- * scrollbar when its columns are wider than the pane (less the vertical
39
- * scrollbar's column).
37
+ * The rows a kit table spends outside its body: the header, a hidden-column
38
+ * disclosure, and a horizontal scrollbar when its columns are wider than the pane.
40
39
  */
41
- export function chartTableChromeRows(columns: readonly TableWidthColumn[], width: number): number {
42
- return hasMeaningfulTableHorizontalOverflow(getTableWidth(columns), width - 1) ? 2 : 1;
40
+ export function chartTableChromeRows(columns: readonly TableWidthColumn[], width: number, tableRows = 1): number {
41
+ return 1 + hiddenTableColumnRows(columns, tableRows) + Number(hasMeaningfulTableHorizontalOverflow(getTableWidth(columns), width - 1));
43
42
  }
44
43
 
45
44
  /**