@gloom-sh/terminal 0.20.9 → 0.20.11

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 (212) hide show
  1. package/package.json +1 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
  3. package/src/api-client/auth.ts +6 -0
  4. package/src/api-client/data.ts +1 -0
  5. package/src/api-client/earnings.ts +15 -0
  6. package/src/api-client/index.ts +14 -3
  7. package/src/api-client/socket-connection.ts +355 -0
  8. package/src/api-client/socket-features.ts +75 -0
  9. package/src/api-client/socket-frames.ts +161 -0
  10. package/src/api-client/socket-listeners.ts +207 -0
  11. package/src/api-client/socket-quotes.ts +332 -0
  12. package/src/api-client/socket.ts +150 -983
  13. package/src/api-client/types/account.ts +10 -0
  14. package/src/api-client/types/billing.ts +10 -0
  15. package/src/api-client/types/econ.ts +19 -7
  16. package/src/api-client/types/market.ts +7 -0
  17. package/src/api-client/types/screener.ts +2 -0
  18. package/src/brokers/signed-in/adapter.ts +19 -5
  19. package/src/brokers/signed-in/client.ts +13 -1
  20. package/src/brokers/signed-in/sign-in-dialog.tsx +33 -9
  21. package/src/cli/commands/market.ts +18 -8
  22. package/src/cli/commands/overview.ts +26 -7
  23. package/src/cli/commands/ticker.ts +40 -15
  24. package/src/cli/desktop-pane-shot.ts +39 -0
  25. package/src/cli/errors.ts +20 -3
  26. package/src/cli/fx-pair.ts +11 -2
  27. package/src/cli/history-rows.ts +34 -3
  28. package/src/cli/index.ts +1 -1
  29. package/src/cli/listing-arg.ts +51 -13
  30. package/src/cli/pane-functions/headless.ts +4 -2
  31. package/src/cli/pane-functions/index.ts +1 -0
  32. package/src/cli/pane-functions/resolver.ts +2 -1
  33. package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
  34. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  35. package/src/components/chart/composite/chart-layout.ts +7 -4
  36. package/src/components/chart/composite/composite-chart.tsx +6 -16
  37. package/src/components/chart/composite/toolbar.tsx +258 -82
  38. package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
  39. package/src/components/chart/native/kitty/manager.ts +2 -0
  40. package/src/components/chart/native/surface/manager.ts +211 -11
  41. package/src/components/command-bar/list/model.ts +13 -0
  42. package/src/components/command-bar/panel/index.tsx +2 -13
  43. package/src/components/command-bar/panel/layout.ts +1 -7
  44. package/src/components/command-bar/panel/runtime.ts +0 -1
  45. package/src/components/command-bar/panel/types.ts +0 -2
  46. package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
  47. package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
  48. package/src/components/command-bar/surface/index.tsx +10 -5
  49. package/src/components/command-bar/workflow/alert.ts +21 -7
  50. package/src/components/data-table/column-menu.tsx +89 -0
  51. package/src/components/data-table/sort-menu.tsx +9 -2
  52. package/src/components/data-table/table-pane.ts +3 -1
  53. package/src/components/data-table/view.tsx +33 -6
  54. package/src/components/form-modal/content.tsx +10 -0
  55. package/src/components/index.ts +1 -1
  56. package/src/components/layout/pane/footer/index.tsx +25 -11
  57. package/src/components/layout/pane/footer/model.ts +88 -21
  58. package/src/components/layout/pane/sidebar.tsx +125 -15
  59. package/src/components/layout/shell/active-drag.ts +18 -13
  60. package/src/components/layout/shell/drag/magnets.ts +34 -18
  61. package/src/components/metric-treemap/heat-surface.tsx +2 -1
  62. package/src/components/metric-treemap/index.tsx +3 -2
  63. package/src/components/ticker/list-table-view.tsx +5 -0
  64. package/src/components/ui/confirm-dialog.tsx +253 -7
  65. package/src/components/ui/data-table/column-order.ts +180 -0
  66. package/src/components/ui/data-table/index.tsx +13 -2
  67. package/src/components/ui/data-table/opentui/index.tsx +267 -23
  68. package/src/components/ui/data-table/opentui/model.ts +43 -4
  69. package/src/components/ui/data-table/types.ts +56 -0
  70. package/src/components/ui/data-table/use-column-order.ts +135 -0
  71. package/src/components/ui/index.ts +1 -1
  72. package/src/components/ui/list-view.tsx +4 -3
  73. package/src/components/ui/status.tsx +9 -6
  74. package/src/components/ui/table-layout.ts +120 -0
  75. package/src/docs/snapshot.json +39 -2
  76. package/src/i18n/es.ts +14 -0
  77. package/src/i18n/ja.ts +14 -0
  78. package/src/i18n/ko.ts +14 -0
  79. package/src/i18n/zh-cn.ts +14 -0
  80. package/src/i18n/zh-tw.ts +14 -0
  81. package/src/market-data/coordinator/index.ts +4 -3
  82. package/src/market-data/coordinator/quotes.ts +12 -4
  83. package/src/market-data/fx-closes.ts +14 -2
  84. package/src/market-data/market/change-basis.ts +35 -1
  85. package/src/market-data/market/status.ts +37 -0
  86. package/src/market-data/performance.ts +4 -1
  87. package/src/market-data/quotes/freshness.ts +12 -0
  88. package/src/market-data/quotes/live-valuation.ts +26 -3
  89. package/src/market-data/quotes/regular-session-valuation.ts +1 -1
  90. package/src/market-data/realized-volatility.ts +3 -0
  91. package/src/market-data/us-bond-market.ts +115 -0
  92. package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
  93. package/src/plugins/builtin/account-management/keyboard.ts +3 -0
  94. package/src/plugins/builtin/account-management/model.ts +1 -0
  95. package/src/plugins/builtin/account-management/pane.tsx +51 -5
  96. package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
  97. package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
  98. package/src/plugins/builtin/broker-manager/index.tsx +6 -6
  99. package/src/plugins/builtin/broker-manager/model.ts +15 -6
  100. package/src/plugins/builtin/broker-manager/pane-actions.tsx +11 -4
  101. package/src/plugins/builtin/broker-manager/sign-in-end.ts +50 -19
  102. package/src/plugins/builtin/broker-manager/table.ts +10 -4
  103. package/src/plugins/builtin/chat/sidebar.tsx +33 -16
  104. package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
  105. package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
  106. package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
  107. package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
  108. package/src/plugins/builtin/correlation/compute.ts +4 -3
  109. package/src/plugins/builtin/earnings/board-model.ts +33 -0
  110. package/src/plugins/builtin/earnings/board-table.ts +50 -11
  111. package/src/plugins/builtin/earnings/board.tsx +29 -13
  112. package/src/plugins/builtin/earnings/calendar.tsx +15 -3
  113. package/src/plugins/builtin/earnings/client.ts +4 -1
  114. package/src/plugins/builtin/earnings/headless.ts +27 -14
  115. package/src/plugins/builtin/econ/calendar-source.ts +3 -0
  116. package/src/plugins/builtin/equity-screener/live.ts +74 -18
  117. package/src/plugins/builtin/equity-screener/model.ts +19 -4
  118. package/src/plugins/builtin/equity-screener/pane.tsx +19 -14
  119. package/src/plugins/builtin/equity-screener/refresh-anchor.ts +45 -0
  120. package/src/plugins/builtin/equity-screener/results.ts +22 -2
  121. package/src/plugins/builtin/equity-screener/screen-check.ts +9 -3
  122. package/src/plugins/builtin/futures/index.tsx +15 -1
  123. package/src/plugins/builtin/futures/table.tsx +1 -1
  124. package/src/plugins/builtin/fx-matrix/index.tsx +2 -0
  125. package/src/plugins/builtin/help/index.tsx +1 -1
  126. package/src/plugins/builtin/holders/pane.tsx +30 -20
  127. package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
  128. package/src/plugins/builtin/iv-history/events.ts +5 -0
  129. package/src/plugins/builtin/iv-history/headless.ts +19 -12
  130. package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
  131. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  132. package/src/plugins/builtin/macro-day/model.ts +17 -4
  133. package/src/plugins/builtin/macro-day/releases.ts +36 -15
  134. package/src/plugins/builtin/market-halts/model.ts +3 -2
  135. package/src/plugins/builtin/market-movers/headless.ts +2 -1
  136. package/src/plugins/builtin/market-movers/index.tsx +3 -2
  137. package/src/plugins/builtin/market-movers/model.ts +75 -22
  138. package/src/plugins/builtin/market-movers/screener.ts +2 -1
  139. package/src/plugins/builtin/market-movers/table.ts +7 -5
  140. package/src/plugins/builtin/options/view.tsx +2 -0
  141. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  142. package/src/plugins/builtin/pe-band/model.ts +4 -0
  143. package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
  144. package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
  145. package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
  146. package/src/plugins/builtin/portfolio-list/pane/index.tsx +15 -1
  147. package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
  148. package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
  149. package/src/plugins/builtin/portfolio-list/table.tsx +18 -1
  150. package/src/plugins/builtin/rate-path/pane.tsx +2 -0
  151. package/src/plugins/builtin/research/analyst-headless.ts +9 -1
  152. package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
  153. package/src/plugins/builtin/research/client.ts +25 -1
  154. package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
  155. package/src/plugins/builtin/research/event-model.ts +3 -13
  156. package/src/plugins/builtin/research/event-sources.ts +3 -1
  157. package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
  158. package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
  159. package/src/plugins/builtin/seasonality/pane.tsx +2 -1
  160. package/src/plugins/builtin/short-interest/headless.ts +2 -0
  161. package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
  162. package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
  163. package/src/plugins/builtin/thirteenf/pane.tsx +2 -0
  164. package/src/plugins/builtin/ticker-detail/financials/model.ts +28 -6
  165. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +26 -9
  166. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +58 -35
  167. package/src/plugins/builtin/vol-surface/heat-grid.tsx +2 -1
  168. package/src/plugins/builtin/vol-surface/pane.tsx +2 -1
  169. package/src/plugins/builtin/world-indices/index.tsx +5 -1
  170. package/src/plugins/builtin/yield-curve/headless.ts +5 -1
  171. package/src/plugins/builtin/yield-curve/index.tsx +7 -1
  172. package/src/portfolio/column-values.ts +47 -14
  173. package/src/portfolio/return-metrics.ts +4 -2
  174. package/src/renderers/dom/data-table/column-drag.ts +147 -0
  175. package/src/renderers/dom/data-table/index.tsx +22 -0
  176. package/src/renderers/dom/data-table/row.tsx +27 -5
  177. package/src/renderers/dom/host/image-surface.tsx +19 -9
  178. package/src/renderers/dom/host/input.tsx +4 -0
  179. package/src/renderers/dom/styles.css +22 -0
  180. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
  181. package/src/renderers/opentui/chart-surface.tsx +1 -0
  182. package/src/renderers/opentui/frame-hits.ts +33 -0
  183. package/src/renderers/opentui/host.tsx +2 -0
  184. package/src/renderers/opentui/native-surface.ts +14 -21
  185. package/src/renderers/opentui/test-utils.tsx +3 -0
  186. package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
  187. package/src/sources/provider-errors.ts +12 -0
  188. package/src/sources/provider-router/index.ts +12 -4
  189. package/src/state/app/context/index.tsx +22 -0
  190. package/src/state/pane-session.ts +145 -0
  191. package/src/test-support/app-store.ts +24 -1
  192. package/src/tickers/search/home-listing.ts +44 -1
  193. package/src/tickers/search/index.ts +5 -2
  194. package/src/tickers/search/ranking.ts +7 -7
  195. package/src/tickers/us-listing.ts +11 -5
  196. package/src/time-series/base-series.ts +7 -1
  197. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  198. package/src/time-series/fundamentals/series.ts +6 -0
  199. package/src/time-series/live-quotes.ts +3 -9
  200. package/src/time-series/resolve.ts +1 -0
  201. package/src/types/financials.ts +20 -0
  202. package/src/types/headless.ts +9 -0
  203. package/src/ui/host.tsx +20 -0
  204. package/src/ui/pointer-drag.ts +11 -2
  205. package/src/utils/exchanges.ts +13 -8
  206. package/src/utils/fundamentals.ts +14 -3
  207. package/src/utils/price-earnings.ts +17 -10
  208. package/src/utils/price-history-integrity.ts +15 -0
  209. package/src/utils/reason-codes.ts +79 -0
  210. package/src/utils/share-multiples.cases.json +1667 -0
  211. package/src/utils/share-multiples.ts +384 -0
  212. package/src/utils/untrusted-text.ts +11 -0
@@ -25,9 +25,12 @@ import { useAssetData, usePluginAppActions, usePluginTickerActions } from "../..
25
25
  import { earningsResultsAlertValues } from "../alerts/research-builder";
26
26
  import { cachedMembers, loadMembers } from "../members/client";
27
27
  import { isBoardRowLoading, useQuoteBoard } from "../shared/use-quote-board";
28
+ import { listingAbroadVenue } from "../../../utils/sec";
28
29
  import {
29
30
  addDays,
31
+ boardKey,
30
32
  boardReport,
33
+ boardRowOf,
31
34
  boardRows,
32
35
  fallbackReport,
33
36
  newYorkToday,
@@ -38,7 +41,7 @@ import {
38
41
  type BoardRow,
39
42
  type BoardSort,
40
43
  } from "./board-model";
41
- import { boardColumns, boardHasActuals, renderBoardCell, renderBoardSection, SORTABLE, type BoardCellContext, type BoardColumn } from "./board-table";
44
+ import { boardColumns, boardHasActuals, boardHasCurrencies, boardSymbolWidth, renderBoardCell, renderBoardSection, SORTABLE, type BoardCellContext, type BoardColumn } from "./board-table";
42
45
  import { EarningsCalendarView, CALENDAR_GROUP_ROWS, calendarSlotsPerRow } from "./calendar";
43
46
  import {
44
47
  boardRangeDays,
@@ -99,7 +102,9 @@ interface BoardData {
99
102
  * ERN without a ticker: the market's report days, largest companies first,
100
103
  * with the implied move and each company's average move. With tickers, or the
101
104
  * Names filter (Mine, a portfolio, a watchlist or a fund's holdings),
102
- * the upcoming reports of those companies instead.
105
+ * the upcoming reports of those companies instead. Every board reads the Hong
106
+ * Kong, China A and Singapore top 100's reports too, ranked by their value in
107
+ * dollars beside US companies, each with the currency of its figures (CCY).
103
108
  */
104
109
  export function EarningsBoard({ focused, width, height, scopedSymbols, highlight = null }: {
105
110
  focused: boolean;
@@ -185,13 +190,18 @@ export function EarningsBoard({ focused, width, height, scopedSymbols, highlight
185
190
  const days = useMemo(() => (market || range ? boardRangeDays(range, today) : relativeDays(today)), [market, range, today]);
186
191
  const weekOffset = boardRangeWeek(range, today);
187
192
  const week = useMemo(() => calendarWeekDates(today, weekOffset), [today, weekOffset]);
188
- // The calendar reads its week, reported days included; the table its days.
189
- const query = useMemo<EarningsCalendarQuery>(() => calendar
190
- ? { from: week[0]!, to: week.at(-1)!, perDay: market ? MARKET_PER_DAY : 0, symbols: named }
191
- : market || range
192
- ? { from: days[0]!.from, to: days.at(-1)!.to, perDay: market ? MARKET_PER_DAY : 0, symbols: named }
193
- : { from: today, to: addDays(today, HORIZON_DAYS), perDay: 0, symbols: named },
194
- [calendar, days, market, named, range, today, week]);
193
+ // EVTS 0700.HK names its listing, which the market board then keeps whatever the day's cut.
194
+ const highlightListing = market && highlight && listingAbroadVenue(boardKey(highlight)) ? boardKey(highlight) : null;
195
+ // The calendar reads its week, reported days included; the table its days. Each report says its currency
196
+ // (CCY), so every board reads the listings abroad too.
197
+ const query = useMemo<EarningsCalendarQuery>(() => {
198
+ const symbols = highlightListing && !named.includes(highlightListing) ? [...named, highlightListing] : named;
199
+ return calendar
200
+ ? { from: week[0]!, to: week.at(-1)!, perDay: market ? MARKET_PER_DAY : 0, symbols, markets: "all" }
201
+ : market || range
202
+ ? { from: days[0]!.from, to: days.at(-1)!.to, perDay: market ? MARKET_PER_DAY : 0, symbols, markets: "all" }
203
+ : { from: today, to: addDays(today, HORIZON_DAYS), perDay: 0, symbols, markets: "all" };
204
+ }, [calendar, days, highlightListing, market, named, range, today, week]);
195
205
  // A fund's read is named by the fund: its companies are known once its holdings are.
196
206
  const queryKey = fund ? `${fund.etf}|${earningsCalendarKey(query)}` : earningsCalendarKey(query);
197
207
 
@@ -208,7 +218,8 @@ export function EarningsBoard({ focused, width, height, scopedSymbols, highlight
208
218
  ]);
209
219
  if (cloud.status === "rejected" && (!perTicker || fallback.status === "rejected")) throw cloud.reason;
210
220
  const reports = cloud.status === "fulfilled" ? cloud.value.payload.reports.map((report) => boardReport(report, owned)) : [];
211
- const covered = new Set(reports.map((report) => report.symbol));
221
+ // A listing abroad named by another of its company's lines (0939.HK) is covered by its row.
222
+ const covered = new Set(reports.flatMap((report) => [report.symbol, ...report.listings ?? []]));
212
223
  const extra = fallback.status === "fulfilled"
213
224
  ? fallback.value.filter((event) => !covered.has(event.symbol)).map((event) => fallbackReport(event, owned, today))
214
225
  : [];
@@ -248,9 +259,13 @@ export function EarningsBoard({ focused, width, height, scopedSymbols, highlight
248
259
  const selected = reportRows.find((row) => row.key === selectedKey) ?? reportRows[0] ?? null;
249
260
  const open = reportRows.find((row) => row.key === openKey)?.report
250
261
  ?? (openKey ? data?.reports.find((report) => report.key === openKey) : undefined) ?? null;
251
- // A board with an actual keeps EPS ACT and EPS SURP when narrow; keyed by the flag, so the columns hold between renders.
262
+ // A board with an actual keeps EPS ACT and EPS SURP when narrow, and one with a listing abroad's report shows CCY;
263
+ // keyed by the flags, so the columns hold between renders.
252
264
  const actuals = boardHasActuals(rows);
253
- const columns = useMemo(() => boardColumns(width, { actuals }), [actuals, width]);
265
+ const currencies = boardHasCurrencies(rows);
266
+ // TICKER fits a listing abroad's key (601939:SSE) when the board has one.
267
+ const symbolWidth = boardSymbolWidth(rows);
268
+ const columns = useMemo(() => boardColumns(width, { actuals, currencies, symbolWidth }), [actuals, currencies, symbolWidth, width]);
254
269
  // The move on each report out today, beside its implied move, from the quotes every board reads.
255
270
  // Keyed by content: the rows are rebuilt on renders that change nothing, and the quote board reloads on a new list.
256
271
  const reportedKey = [...new Set(reportRows.filter((row) => row.report.dateStatus === "reported" && row.report.date === today)
@@ -292,7 +307,8 @@ export function EarningsBoard({ focused, width, height, scopedSymbols, highlight
292
307
 
293
308
  useEffect(() => {
294
309
  if (!highlight || highlighted.current === highlight) return;
295
- const row = reportRows.find((candidate) => candidate.report.symbol === highlight);
310
+ // 0700.HK as typed is the board's 0700:HKEX; 0939.HK is CCB's row under its A share.
311
+ const row = reportRows.find((candidate) => boardRowOf(candidate.report, highlight));
296
312
  if (!row) return;
297
313
  highlighted.current = highlight;
298
314
  setSelectedKey(row.key);
@@ -88,9 +88,11 @@ function locate(grid: readonly Slot[][][], key: string | null): Position | null
88
88
  /** What hovering a logo says: the company, when it reports and, once out, how it did. */
89
89
  function reportTitle(report: BoardReport): string {
90
90
  const when = report.timing ? TIMING_LABEL[report.timing] : "time not set";
91
+ // A listing abroad's figures say their currency (CNY for Tencent), as the table's CCY does.
92
+ const currency = report.currency && report.currency !== "USD" ? ` ${report.currency}` : "";
91
93
  const figures = report.epsActual != null
92
- ? `EPS ${epsText(report.epsActual)} vs ${epsText(report.epsEstimate)} est${report.epsSurprise != null ? `, ${signedPercent(report.epsSurprise)}` : ""}`
93
- : report.epsEstimate != null ? `EPS est ${epsText(report.epsEstimate)}` : null;
94
+ ? `EPS ${epsText(report.epsActual)} vs ${epsText(report.epsEstimate)} est${currency}${report.epsSurprise != null ? `, ${signedPercent(report.epsSurprise)}` : ""}`
95
+ : report.epsEstimate != null ? `EPS est ${epsText(report.epsEstimate)}${currency}` : null;
94
96
  return [`${report.symbol} · ${report.name}`, when, figures].filter(Boolean).join(" · ");
95
97
  }
96
98
 
@@ -267,6 +269,14 @@ const TILE_STYLE = {
267
269
  } as const;
268
270
  /** The logo of a calendar tile: a square near two cells tall, most of the slot's width. */
269
271
  const LOGO_STYLE = { width: "calc(var(--cell-h) * 1.75)", height: "calc(var(--cell-h) * 1.75)", flexShrink: 0 } as const;
272
+ /** The ticker under the logo is never wider than its tile: it ends in an ellipsis instead of running under the next. */
273
+ const LABEL_STYLE = { maxWidth: "100%", minWidth: 0 } as const;
274
+
275
+ /** A tile's ticker: a listing abroad's code without its venue (0700 for 0700:HKEX), which the tile's title names. */
276
+ function tileLabel(symbol: string): string {
277
+ const venue = symbol.indexOf(":");
278
+ return venue > 0 ? symbol.slice(0, venue) : symbol;
279
+ }
270
280
 
271
281
  function ReportTile({ report, selected, onPress, tileRef }: {
272
282
  report: BoardReport;
@@ -299,7 +309,9 @@ function ReportTile({ report, selected, onPress, tileRef }: {
299
309
  <Box style={LOGO_STYLE}>
300
310
  <CompanyLogoMark symbol={report.symbol} name={report.name} size="lead" />
301
311
  </Box>
302
- <ClippedText text={report.symbol} width={CALENDAR_SLOT_CELLS - 1} fg={ink} attributes={TextAttributes.BOLD} />
312
+ <Box style={LABEL_STYLE}>
313
+ <ClippedText text={tileLabel(report.symbol)} width={CALENDAR_SLOT_CELLS - 1} fg={ink} attributes={TextAttributes.BOLD} />
314
+ </Box>
303
315
  </Box>
304
316
  );
305
317
  }
@@ -32,11 +32,14 @@ export function resetEarningsCloudCaches() {
32
32
 
33
33
  const isDate = (value: unknown) => typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value);
34
34
  const numberOrNull = (value: unknown) => value === null || (typeof value === "number" && Number.isFinite(value));
35
+ const currencyOrAbsent = (value: unknown) => value == null || (typeof value === "string" && /^[A-Z]{3}$/.test(value));
36
+ const linesOrAbsent = (value: unknown) => value == null || (Array.isArray(value) && value.every((line) => typeof line === "string"));
35
37
 
36
38
  function validReport(report: EarningsReport): boolean {
37
39
  return !!report && typeof report.symbol === "string" && isDate(report.date)
38
40
  && [null, "bmo", "dmh", "amc"].includes(report.timing)
39
41
  && [report.marketCap, report.epsEstimate, report.epsActual, report.revenueEstimate].every(numberOrNull)
42
+ && currencyOrAbsent(report.currency) && linesOrAbsent(report.listings)
40
43
  && (report.implied === null || (typeof report.implied === "object" && Number.isFinite(report.implied.move) && isDate(report.implied.expiry)))
41
44
  && (report.realized === null || (typeof report.realized === "object" && Number.isFinite(report.realized.move)));
42
45
  }
@@ -69,7 +72,7 @@ type HistoryClient = Pick<typeof apiClient, "getCloudEarningsHistory">;
69
72
 
70
73
  /** Names a calendar query: the cache's key, and how the board tells one week's reports from another's. */
71
74
  export const earningsCalendarKey = (query: EarningsCalendarQuery) =>
72
- `${query.from}:${query.to}:${query.perDay ?? ""}:${[...(query.symbols ?? [])].sort().join(",")}`;
75
+ `${query.from}:${query.to}:${query.perDay ?? ""}:${[...(query.symbols ?? [])].sort().join(",")}${query.markets ? `:${query.markets}` : ""}`;
73
76
 
74
77
  export async function fetchEarningsCalendar(query: EarningsCalendarQuery, client: CalendarClient = apiClient) {
75
78
  try {
@@ -9,16 +9,15 @@ import type {
9
9
  HeadlessRowsResult,
10
10
  } from "../../../types/plugin";
11
11
  import type { EarningsEvent } from "../../../types/data-provider";
12
- import { addDays, boardReport, fallbackReport, MIN_AVERAGE_REPORTS, newYorkToday, type BoardReport } from "./board-model";
12
+ import { addDays, boardKey, boardReport, boardRowOf, fallbackReport, MIN_AVERAGE_REPORTS, newYorkToday, type BoardReport } from "./board-model";
13
13
  import { BOARD_WEEKS, boardRangeDays, boardRangeLabel, isBoardWeek, requestedBoardRange, type BoardRange } from "./calendar-model";
14
- import { fetchEarningsCalendar, fetchEarningsHistory, hasEarningsHistory, noHistoryAbroad } from "./client";
14
+ import { fetchEarningsCalendar, fetchEarningsHistory, hasEarningsHistory, noHistoryAbroad, sameHistoryListing } from "./client";
15
15
  import { loadEarningsCalendar } from "./data/cache";
16
16
  import { epsText, impliedText, moneyText, moveSize, signedPercent, TIMING_LABEL } from "./format";
17
17
  import { historyRows, periodText } from "./history-model";
18
18
  import { fiscalQuarterText } from "./fiscal-quarter";
19
19
  import { loadNoEarningsText } from "./no-earnings";
20
20
  import { EPS_BASIS_NOTE, epsBasisName, PROVISIONAL_NOTE, showsEpsBasis } from "../shared/earnings-report";
21
- import { isUsListingExchange } from "../../../utils/exchanges";
22
21
  import { listingAbroadVenue } from "../../../utils/sec";
23
22
  import { findUsListingOfCompany } from "../../../tickers/us-listing";
24
23
  import { shortCompanyName } from "../../../tickers/company-name";
@@ -42,7 +41,10 @@ const BOARD_COLUMNS: HeadlessPaneColumn[] = [
42
41
  { key: "timing", header: "When" },
43
42
  { key: "symbol", header: "Ticker" },
44
43
  { key: "name", header: "Name" },
45
- { key: "marketCap", header: "Mkt cap", align: right, format: (value) => moneyText(num(value)) },
44
+ // Dollars for every company, a listing abroad's too, so the board ranks them together.
45
+ { key: "marketCap", header: "Mkt cap $", align: right, format: (value) => moneyText(num(value)) },
46
+ // The EPS and sales figures' currency: a listing abroad's own (CNY for Tencent).
47
+ { key: "currency", header: "Ccy" },
46
48
  { key: "epsEstimate", header: "EPS est", align: right, format: (value) => epsText(num(value)) },
47
49
  { key: "epsAnalysts", header: "Ests", align: right },
48
50
  { key: "epsActual", header: "EPS act", align: right, format: (value) => epsText(num(value)) },
@@ -53,6 +55,9 @@ const BOARD_COLUMNS: HeadlessPaneColumn[] = [
53
55
  { key: "averageMove", header: "Avg move", align: right, format: (value) => moveSize(num(value)) },
54
56
  ];
55
57
 
58
+ /** What the board's currency and cap are, and which listings abroad it has, in its metadata. */
59
+ const BOARD_CURRENCY_NOTE = "currency is the ISO currency of a report's EPS and sales figures: dollars for US listings, a listing abroad's own (CNY for Tencent), never converted. marketCap is in dollars for every company, so the board ranks them together. Besides US listings the board has the Hong Kong, China A and Singapore top 100's reports whose date the company confirmed or that are out, from each listing's earnings history; they have no time of day, implied or average move. A company listed on two of those markets is shown once, under its primary listing, and found by any of its lines.";
60
+
56
61
  /** What an ERN <ticker> report's quarter is, in its metadata. */
57
62
  const FISCAL_QUARTER_NOTE = "fiscalQuarter is the quarter as the company names it (Q3 FY2027), from its earnings calls on record; fiscalPeriod is the month the quarter ended. A company whose calls do not name its quarters has fiscalQuarter null.";
58
63
 
@@ -96,7 +101,7 @@ const LISTING_HISTORY_COLUMNS: HeadlessPaneColumn[] = [
96
101
  const LISTING_PERIOD_NOTE = "period is what the figures cover: a quarter (Q3 FY2026, or its end month), a half (H1 FY2026), a year (FY2025) or a year to date (9M FY2026), a fiscal year named by the calendar year it ends in. A half-yearly reporter's half is never a quarter. currency is the ISO currency of every amount on the row, estimates included. EPS estimates and actuals are the street's quarter figures, compared only in one currency and on one basis; a period the street has no quarter for shows the company's reported EPS and revenue from its results announcement (filing) with no estimate, its EPS diluted (basis GAAP) where the filing gives one, else basic (basis basic). The announcements' figures and links come with Gloom Pro, as KPIS has them; the street's quarters are everyone's.";
97
102
 
98
103
  interface EarningsHeadlessDependencies {
99
- calendar(query: { from: string; to: string; perDay: number; symbols: string[] }, context: HeadlessPaneContext): Promise<EarningsCalendarPayload>;
104
+ calendar(query: { from: string; to: string; perDay: number; symbols: string[]; markets?: "all" }, context: HeadlessPaneContext): Promise<EarningsCalendarPayload>;
100
105
  history(symbol: string, context: HeadlessPaneContext): Promise<EarningsHistoryPayload>;
101
106
  upcoming(symbols: string[], context: HeadlessPaneContext): Promise<EarningsEvent[]>;
102
107
  }
@@ -114,15 +119,16 @@ const NO_OWNERSHIP = new Map();
114
119
  * report says so once, whether the ticker is on it and when, and where its
115
120
  * own report dates are.
116
121
  */
117
- function boardTickerNotice(symbol: string, board: ReadonlyArray<{ symbol: string; date: string }>, from: string, to: string): { notice: string; date: string | null } {
118
- const [bare = symbol, venue] = symbol.toUpperCase().split(":");
119
- // The board lists US tickers; a listing named abroad is never one of them.
120
- const report = venue && !isUsListingExchange(venue) ? undefined : board.find((entry) => entry.symbol.toUpperCase() === bare);
121
- const where = report ? `${symbol} reports on ${report.date}` : `${symbol} is not on it`;
122
+ function boardTickerNotice(symbol: string, board: ReadonlyArray<Pick<BoardReport, "symbol" | "listings" | "date">>, from: string, to: string): { notice: string; date: string | null; row: string | null } {
123
+ const report = board.find((entry) => boardRowOf(entry, symbol));
124
+ // CCB named by its H share is on the board under its A share.
125
+ const shownAs = report?.listings && !sameHistoryListing(report.symbol, boardKey(symbol)) ? ` (as ${report.symbol})` : "";
126
+ const where = report ? `${symbol} reports on ${report.date}${shownAs}` : `${symbol} is not on it`;
122
127
  const days = from === to ? from : `${from} to ${to}`;
123
128
  return {
124
129
  notice: `EVTS is the market's earnings board for ${days}, not one company's: ${where}. For ${symbol}'s own report dates run \`gloom fn ERN ${symbol}\`.`,
125
130
  date: report?.date ?? null,
131
+ row: report?.symbol ?? null,
126
132
  };
127
133
  }
128
134
 
@@ -166,9 +172,12 @@ async function boardRows(args: HeadlessPaneLoadArgs, context: HeadlessPaneContex
166
172
  const named = args.symbols;
167
173
  const days = boardRangeDays(range, today);
168
174
  // Named companies' upcoming reports by default; a chosen week or day reads that range for them as for the market.
175
+ // Every view of the board shows each report's currency, so it reads the listings abroad too; EVTS 0700.HK names its
176
+ // listing, which the board then keeps whatever the day's cut.
177
+ const abroad = highlight && listingAbroadVenue(boardKey(highlight)) ? [boardKey(highlight)] : [];
169
178
  const query = named.length && !range
170
- ? { from: today, to: addDays(today, 90), perDay: 0, symbols: named }
171
- : { from: days[0]!.from, to: days.at(-1)!.to, perDay: named.length ? 0 : 200, symbols: named };
179
+ ? { from: today, to: addDays(today, 90), perDay: 0, symbols: named, markets: "all" as const }
180
+ : { from: days[0]!.from, to: days.at(-1)!.to, perDay: named.length ? 0 : 200, symbols: named.length ? named : abroad, markets: "all" as const };
172
181
  const inRange = (event: EarningsEvent) => {
173
182
  const date = event.earningsDate.toISOString().slice(0, 10);
174
183
  return !range || (date >= query.from && date <= query.to);
@@ -180,7 +189,8 @@ async function boardRows(args: HeadlessPaneLoadArgs, context: HeadlessPaneContex
180
189
  if (cloud.status === "rejected" && (!named.length || fallback.status === "rejected")) throw cloud.reason;
181
190
  const payload = cloud.status === "fulfilled" ? cloud.value : null;
182
191
  const reports = (payload?.reports ?? []).map((report) => boardReport(report, NO_OWNERSHIP));
183
- const covered = new Set(reports.map((report) => report.symbol));
192
+ // A listing abroad named by another of its company's lines (0939:HKEX) is covered by its row.
193
+ const covered = new Set(reports.flatMap((report) => [report.symbol, ...report.listings ?? []]));
184
194
  const uncovered = fallback.status === "fulfilled" ? fallback.value.filter((event) => !covered.has(event.symbol)) : [];
185
195
  // The days ahead leave out a report just gone by, which the stored board has as the date board shows it.
186
196
  const stored = named.length && !range ? await storedPastReports(uncovered, today, context, deps) : new Map<EarningsEvent, BoardReport>();
@@ -195,6 +205,8 @@ async function boardRows(args: HeadlessPaneLoadArgs, context: HeadlessPaneContex
195
205
  symbol: report.symbol,
196
206
  name: report.name,
197
207
  marketCap: report.marketCap,
208
+ currency: report.currency ?? null,
209
+ ...report.listings ? { listings: report.listings } : {},
198
210
  epsEstimate: report.epsEstimate,
199
211
  epsAnalysts: report.epsAnalysts,
200
212
  epsActual: report.epsActual,
@@ -211,7 +223,7 @@ async function boardRows(args: HeadlessPaneLoadArgs, context: HeadlessPaneContex
211
223
  rows,
212
224
  errors: cloud.status === "rejected" ? [String(cloud.reason instanceof Error ? cloud.reason.message : cloud.reason)] : undefined,
213
225
  metadata: {
214
- ...(ticker ? { notices: [ticker.notice], highlight: { symbol: highlight, onBoard: ticker.date != null, date: ticker.date } } : {}),
226
+ ...(ticker ? { notices: [ticker.notice], highlight: { symbol: highlight, onBoard: ticker.date != null, date: ticker.date, row: ticker.row } } : {}),
215
227
  asOf: payload?.asOf ?? null,
216
228
  from: query.from,
217
229
  to: query.to,
@@ -219,6 +231,7 @@ async function boardRows(args: HeadlessPaneLoadArgs, context: HeadlessPaneContex
219
231
  epsBasis: EPS_BASIS_NOTE,
220
232
  provisional: PROVISIONAL_NOTE,
221
233
  marketCap: MARKET_CAP_NOTE,
234
+ currency: BOARD_CURRENCY_NOTE,
222
235
  total: all.length,
223
236
  returned: rows.length,
224
237
  truncated: rows.length < all.length,
@@ -22,6 +22,8 @@ export type EconCalendarFrom =
22
22
  events: EconEvent[];
23
23
  /** The first UTC day the stored calendar holds; null when it holds nothing. */
24
24
  storedFrom: string | null;
25
+ /** The first UTC day any read lists (the stored calendar's, or the furthest back it reaches); null from an older server. */
26
+ listedFrom: string | null;
25
27
  /** The last UTC day the calendar lists releases for; null from a server that does not say. */
26
28
  listedThrough: string | null;
27
29
  }
@@ -47,6 +49,7 @@ export async function fetchEconCalendarFrom(from: string): Promise<EconCalendarF
47
49
  return {
48
50
  events: withPercentUnits(payload.events.map(toEconEvent)),
49
51
  storedFrom: payload.storedFrom,
52
+ listedFrom: typeof payload.listedFrom === "string" && /^\d{4}-\d{2}-\d{2}$/.test(payload.listedFrom) ? payload.listedFrom : null,
50
53
  listedThrough: typeof payload.listedThrough === "string" && /^\d{4}-\d{2}-\d{2}$/.test(payload.listedThrough) ? payload.listedThrough : null,
51
54
  };
52
55
  } catch (error) {
@@ -6,7 +6,7 @@ import type { QueryEntry } from "../../../market-data/result-types";
6
6
  import { buildQuoteKey, resolveEntryData } from "../../../market-data/selectors";
7
7
  import type { Quote } from "../../../types/financials";
8
8
  import { isFiniteNumber } from "../../../utils/guards";
9
- import { isValuationMultiple } from "./model";
9
+ import { isValuationMultiple, screenRowId } from "./model";
10
10
 
11
11
  /**
12
12
  * A screen row with its quote laid over it: price, change, volume and market
@@ -107,32 +107,64 @@ function overlayLiveScreenRow(snapshotRow: ScreenRow, quote: Quote | null | unde
107
107
  /** The last overlay per snapshot row, so a row whose quote did not move keeps its object. */
108
108
  const liveRows = new WeakMap<ScreenRow, { quote: Quote | null; row: LiveScreenRow }>();
109
109
 
110
- function overlayRows(rows: readonly ScreenRow[], quoteOf: (key: string) => Quote | null | undefined): LiveScreenRow[] {
111
- return rows.map((row) => {
112
- const quote = quoteOf(screenRowQuoteKey(row));
113
- if (quote === undefined) return row;
114
- const cached = liveRows.get(row);
115
- if (cached && cached.quote === quote) return cached.row;
116
- const next = overlayLiveScreenRow(row, quote);
117
- liveRows.set(row, { quote, row: next });
118
- return next;
119
- });
110
+ /** Where each quote key sits in a rows array: a screen's rows are replaced as a whole, so this is read once per array. */
111
+ const rowPositions = new WeakMap<readonly ScreenRow[], Map<string, number[]>>();
112
+
113
+ function positionsByQuoteKey(rows: readonly ScreenRow[]): Map<string, number[]> {
114
+ let positions = rowPositions.get(rows);
115
+ if (!positions) {
116
+ positions = new Map();
117
+ rows.forEach((row, index) => {
118
+ const key = screenRowQuoteKey(row);
119
+ const at = positions!.get(key);
120
+ if (at) at.push(index);
121
+ else positions!.set(key, [index]);
122
+ });
123
+ rowPositions.set(rows, positions);
124
+ }
125
+ return positions;
126
+ }
127
+
128
+ /**
129
+ * The rows with their quotes laid over them. Only the rows a quote names are
130
+ * touched, so a long list costs what its quotes do, and the same array comes
131
+ * back while none of them moved a row (a tick for a row off the loaded pages,
132
+ * or one that changes none of what the row shows).
133
+ */
134
+ function overlayRows(
135
+ rows: readonly ScreenRow[],
136
+ quotes: Iterable<readonly [string, Quote | null | undefined]>,
137
+ ): readonly LiveScreenRow[] {
138
+ const positions = positionsByQuoteKey(rows);
139
+ let next: LiveScreenRow[] | null = null;
140
+ for (const [key, quote] of quotes) {
141
+ if (quote === undefined) continue;
142
+ for (const index of positions.get(key) ?? []) {
143
+ const row = rows[index]!;
144
+ let live: LiveScreenRow;
145
+ const cached = liveRows.get(row);
146
+ if (cached && cached.quote === quote) live = cached.row;
147
+ else {
148
+ live = overlayLiveScreenRow(row, quote);
149
+ liveRows.set(row, { quote, row: live });
150
+ }
151
+ if (live !== (next ?? rows)[index]) (next ??= [...rows])[index] = live;
152
+ }
153
+ }
154
+ return next ?? rows;
120
155
  }
121
156
 
122
157
  /** The pane's rows with the streamed quotes on screen laid over them. */
123
158
  export function overlayLiveScreenRows(
124
159
  rows: readonly ScreenRow[],
125
160
  entries: ReadonlyMap<string, QueryEntry<Quote>>,
126
- ): LiveScreenRow[] {
127
- return overlayRows(rows, (key) => {
128
- const entry = entries.get(key);
129
- return entry ? resolveEntryData(entry) : undefined;
130
- });
161
+ ): readonly LiveScreenRow[] {
162
+ return overlayRows(rows, Array.from(entries, ([key, entry]) => [key, resolveEntryData(entry)] as const));
131
163
  }
132
164
 
133
165
  /** Rows with quotes keyed by screenRowQuoteKey laid over them, for a report. */
134
- export function overlayScreenQuotes(rows: readonly ScreenRow[], quotes: ReadonlyMap<string, Quote>): LiveScreenRow[] {
135
- return overlayRows(rows, (key) => quotes.get(key));
166
+ export function overlayScreenQuotes(rows: readonly ScreenRow[], quotes: ReadonlyMap<string, Quote>): readonly LiveScreenRow[] {
167
+ return overlayRows(rows, quotes);
136
168
  }
137
169
 
138
170
  /** The fields a quote moves on a row (overlayLiveScreenRow). */
@@ -165,6 +197,30 @@ export function sortLiveScreenRows<T extends ScreenRow>(rows: readonly T[], sort
165
197
  .map(({ row }) => row);
166
198
  }
167
199
 
200
+ /**
201
+ * Where each row sits in the screen's order by the figures it shows
202
+ * (sortLiveScreenRows), by row id in that order. The pane takes it from
203
+ * figures sampled every few seconds, so a tick reorders nothing: the rows it
204
+ * moves are placed by it (placeLiveScreenRows), and the sort is not redone.
205
+ */
206
+ export function liveScreenPlaces(rows: readonly ScreenRow[], sort: ScreenDefinition["sort"]): ReadonlyMap<string, number> {
207
+ return new Map(sortLiveScreenRows(rows, sort).map((row, index) => [screenRowId(row), index]));
208
+ }
209
+
210
+ /** `rows` in the order of `places`; a row it does not know follows those it does, in the order it has. */
211
+ export function placeLiveScreenRows<T extends ScreenRow>(rows: readonly T[], places: ReadonlyMap<string, number>): T[] {
212
+ const placed: Array<T | undefined> = [];
213
+ const rest: T[] = [];
214
+ for (const row of rows) {
215
+ const place = places.get(screenRowId(row));
216
+ if (place === undefined || placed[place] !== undefined) rest.push(row);
217
+ else placed[place] = row;
218
+ }
219
+ const ordered: T[] = [];
220
+ for (const row of placed) if (row !== undefined) ordered.push(row);
221
+ return ordered.concat(rest);
222
+ }
223
+
168
224
  /** The extended sessions some row has a print for, in the order their columns go. */
169
225
  export function screenExtendedSessions(rows: readonly LiveScreenRow[]): ExtendedSession[] {
170
226
  return (["PRE", "POST", "OVERNIGHT"] as const).filter((session) => rows.some((row) => row.extended?.session === session));
@@ -339,8 +339,12 @@ export function screenMetricSetting(setting: unknown, fallback: NumericField): [
339
339
  * snapshot's day without one.
340
340
  */
341
341
  export function screenYtdBase(rows: readonly ScreenRow[], assembledAt?: string | null, now = Date.now()): string | null {
342
- const day = rows.map((row) => row.metrics.returnYtdPercent?.asOf?.slice(0, 10) ?? "").filter(Boolean).sort().at(-1)
343
- ?? assembledAt?.slice(0, 10);
342
+ let newest = "";
343
+ for (const row of rows) {
344
+ const day = row.metrics.returnYtdPercent?.asOf?.slice(0, 10);
345
+ if (day && day > newest) newest = day;
346
+ }
347
+ const day = newest || assembledAt?.slice(0, 10);
344
348
  return day ? yearToDateBaseLabel(day, "NYSE", now) : null;
345
349
  }
346
350
 
@@ -420,8 +424,19 @@ export function screenCurrencyEmpty(
420
424
  };
421
425
  }
422
426
 
423
- export const screenRowId = (row: Pick<ScreenRow, "symbol" | "exchange">) =>
424
- `${canonicalExchange(row.exchange)}:${row.symbol}`;
427
+ /**
428
+ * A row's id as last read: the table, the order and the lookups of a long list
429
+ * ask for it row by row on every render, and a screen's rows do not change
430
+ * between them.
431
+ */
432
+ const rowIds = new WeakMap<object, { symbol: string; exchange: string; id: string }>();
433
+ export const screenRowId = (row: Pick<ScreenRow, "symbol" | "exchange">) => {
434
+ const known = rowIds.get(row);
435
+ if (known && known.symbol === row.symbol && known.exchange === row.exchange) return known.id;
436
+ const id = `${canonicalExchange(row.exchange)}:${row.symbol}`;
437
+ rowIds.set(row, { symbol: row.symbol, exchange: row.exchange, id });
438
+ return id;
439
+ };
425
440
  export const screenLabel = (field: string) =>
426
441
  ({
427
442
  kpiArr: "Annual recurring revenue",
@@ -101,9 +101,10 @@ import {
101
101
  } from "./model";
102
102
  import { findNamedCollection, readWatchlistArgument } from "../../../portfolio/collection-name";
103
103
  import { useScreenResults } from "./results";
104
+ import { useRefreshAnchor } from "./refresh-anchor";
104
105
  import { screenWatchlistList } from "./watchlist";
105
106
  import { unmatchedCategoryText, unmatchedCategoryValues } from "./categories";
106
- import { overlayLiveScreenRows, screenExtendedMove, screenExtendedSessions, sortLiveScreenRows, type LiveScreenRow } from "./live";
107
+ import { liveScreenPlaces, overlayLiveScreenRows, placeLiveScreenRows, screenExtendedMove, screenExtendedSessions, type LiveScreenRow } from "./live";
107
108
  import { useLiveQuoteEntries } from "../../../state/hooks/quote-streaming";
108
109
  import { buildScreenerQuoteTargets } from "../../../market-data/quotes/screener-live-quotes";
109
110
  import { useLiveStreamingSetting } from "../../../state/hooks/live-streaming";
@@ -380,20 +381,16 @@ function EquityScreenView({
380
381
  LIVE_ORDER_SAMPLE_MS,
381
382
  `${data?.snapshot?.id ?? ""}:${JSON.stringify(definition.sort)}:${snapshotRows.length}`,
382
383
  );
383
- const rows = useMemo(() => {
384
- const order = new Map(sortLiveScreenRows(orderRows, definition.sort).map((row, index) => [screenRowId(row), index]));
385
- return liveRows
386
- .map((row, index) => ({ row, index, place: order.get(screenRowId(row)) ?? Number.POSITIVE_INFINITY }))
387
- .sort((a, b) => a.place - b.place || a.index - b.index)
388
- .map(({ row }) => row);
389
- }, [definition.sort, liveRows, orderRows]);
390
- const opened = rows.find((row) => screenRowId(row) === openId);
384
+ const places = useMemo(() => liveScreenPlaces(orderRows, definition.sort), [definition.sort, orderRows]);
385
+ const rows = useMemo(() => placeLiveScreenRows(liveRows, places), [liveRows, places]);
386
+ const { anchor: refreshAnchor, release: releaseRefreshAnchor } = useRefreshAnchor(data?.snapshot?.id ?? null, rows, visibleRange.start);
387
+ const opened = openId ? rows.find((row) => screenRowId(row) === openId) : undefined;
391
388
  const selected =
392
389
  opened ?? rows.find((row) => screenRowId(row) === selectedId) ?? rows[0];
393
390
  const currentSaved = saved.data?.find((row) => row.id === currentSavedId);
394
391
  // The pane menu's Save to Watchlist… takes the matches loaded, in the order shown (the first page is 100). A live
395
392
  // quote changes the rows but not who they are, so the menu is rebuilt only when the order does.
396
- const shownOrder = rows.map(screenRowId).join(" ");
393
+ const shownOrder = useMemo(() => [...places.keys()].join(" "), [places]);
397
394
  const watchlistList = useMemo(
398
395
  () => mode === "results" && !openId && data && screenDefinitionKey(data.definition) === screenDefinitionKey(definition)
399
396
  ? screenWatchlistList({ definition, rows, matched: data.universe.matched, savedName: currentSaved?.name })
@@ -443,22 +440,27 @@ function EquityScreenView({
443
440
  ]);
444
441
  const tableScroll = useRef<ScrollBoxRenderable>(null);
445
442
  const queryControl = useRef<SelectControl>(null);
446
- const loadMore = useTableLoadMore(
443
+ const loadMoreNearEnd = useTableLoadMore(
447
444
  tableScroll,
448
445
  !opened && !results.loading && !results.loadingMore && !!data?.nextCursor,
449
446
  results.loadMore,
450
447
  );
448
+ const loadMore = useCallback((source?: "programmatic" | "user") => {
449
+ if (source === "user") releaseRefreshAnchor();
450
+ loadMoreNearEnd();
451
+ }, [loadMoreNearEnd, releaseRefreshAnchor]);
451
452
  const metricFields = pickerFields(
452
453
  fields.data?.fields.filter((field) => field.kind === "number") ?? [],
453
454
  [metric],
454
455
  );
455
456
  // AS OF earns its column only when some row's focus metric is stale; the
456
457
  // snapshot decides, so a live quote freshening a row does not reflow the table.
457
- const staleFocus = snapshotRows.some((row) => row.metrics[metric]?.state === "stale");
458
+ const staleFocus = useMemo(() => snapshotRows.some((row) => row.metrics[metric]?.state === "stale"), [metric, snapshotRows]);
458
459
  // A pre-market, after-hours or overnight column only while a row has such a print.
459
- const extendedSessions = screenExtendedSessions(rows);
460
+ const extendedSessions = useMemo(() => screenExtendedSessions(rows), [rows]);
460
461
  // YTD names the close it is measured from, `31 Dec`.
461
- const ytdBase = screenYtdBase(snapshotRows, data?.snapshot?.assembledAt);
462
+ const assembledAt = data?.snapshot?.assembledAt;
463
+ const ytdBase = useMemo(() => screenYtdBase(snapshotRows, assembledAt), [assembledAt, snapshotRows]);
462
464
  // A screen its currency emptied says so, not that no company matches.
463
465
  const currencyEmpty = data && data.rows.length === 0 ? screenCurrencyEmpty(data.definition, data.universe) : null;
464
466
  // A criterion's name that matches nothing (`Utility`) says so with the names it was likely meant as.
@@ -1082,6 +1084,9 @@ function EquityScreenView({
1082
1084
  rootHeight={bodyHeight - 1}
1083
1085
  scrollRef={tableScroll}
1084
1086
  onBodyScrollActivity={loadMore}
1087
+ scrollToIndex={refreshAnchor?.index}
1088
+ scrollToIndexAlign={refreshAnchor ? "start" : "nearest"}
1089
+ scrollToIndexVersion={refreshAnchor?.version ?? 0}
1085
1090
  resetScrollKey={JSON.stringify(definition)}
1086
1091
  visibleRangeKey={JSON.stringify(definition)}
1087
1092
  onVisibleRangeChange={setVisibleRange}
@@ -0,0 +1,45 @@
1
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
2
+ import type { ScreenRow } from "../../../api-client/equity-screener";
3
+ import { screenRowId } from "./model";
4
+
5
+ /** How long a refresh keeps asking the table to hold the row that was at its top. */
6
+ const REFRESH_ANCHOR_HOLD_MS = 2_000;
7
+
8
+ export interface RefreshAnchor {
9
+ index: number;
10
+ version: number;
11
+ }
12
+
13
+ /**
14
+ * A refresh puts a new snapshot's rows under the scroll position. This asks
15
+ * the table to keep the row that sat at its top there: the anchor is the
16
+ * row's place in the new rows, as a `scrollToIndex` request with a new
17
+ * `version` per refresh. A list at its top stays there, and a row the new
18
+ * snapshot dropped leaves the scroll as it is. The request lapses once the
19
+ * user scrolls (`release`), and a moment after, when the table has long since
20
+ * applied it.
21
+ */
22
+ export function useRefreshAnchor(
23
+ snapshotId: string | null,
24
+ rows: readonly ScreenRow[],
25
+ firstVisible: number,
26
+ ): { anchor: RefreshAnchor | null; release: () => void } {
27
+ const topRow = rows[firstVisible];
28
+ const topRowId = topRow ? screenRowId(topRow) : null;
29
+ const kept = useRef({ snapshotId, topRowId, firstVisible });
30
+ const [anchor, setAnchor] = useState<RefreshAnchor | null>(null);
31
+ useLayoutEffect(() => {
32
+ const before = kept.current;
33
+ kept.current = { snapshotId, topRowId, firstVisible };
34
+ if (!before.topRowId || !before.snapshotId || !snapshotId || before.snapshotId === snapshotId || before.firstVisible === 0) return;
35
+ const index = rows.findIndex((row) => screenRowId(row) === before.topRowId);
36
+ if (index >= 0 && index !== before.firstVisible) setAnchor((current) => ({ index, version: (current?.version ?? 0) + 1 }));
37
+ });
38
+ useEffect(() => {
39
+ if (!anchor) return;
40
+ const timer = setTimeout(() => setAnchor(null), REFRESH_ANCHOR_HOLD_MS);
41
+ return () => clearTimeout(timer);
42
+ }, [anchor]);
43
+ const release = useCallback(() => setAnchor(null), []);
44
+ return { anchor, release };
45
+ }