@gloom-sh/terminal 0.20.10 → 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 (103) hide show
  1. package/package.json +1 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
  3. package/src/api-client/socket-connection.ts +355 -0
  4. package/src/api-client/socket-features.ts +75 -0
  5. package/src/api-client/socket-frames.ts +161 -0
  6. package/src/api-client/socket-listeners.ts +207 -0
  7. package/src/api-client/socket-quotes.ts +332 -0
  8. package/src/api-client/socket.ts +150 -983
  9. package/src/brokers/signed-in/adapter.ts +19 -5
  10. package/src/brokers/signed-in/client.ts +13 -1
  11. package/src/brokers/signed-in/sign-in-dialog.tsx +33 -9
  12. package/src/components/chart/native/kitty/manager.ts +2 -0
  13. package/src/components/chart/native/surface/manager.ts +211 -11
  14. package/src/components/command-bar/panel/index.tsx +2 -13
  15. package/src/components/command-bar/panel/layout.ts +1 -7
  16. package/src/components/command-bar/panel/runtime.ts +0 -1
  17. package/src/components/command-bar/panel/types.ts +0 -2
  18. package/src/components/data-table/column-menu.tsx +89 -0
  19. package/src/components/data-table/sort-menu.tsx +9 -2
  20. package/src/components/data-table/view.tsx +33 -6
  21. package/src/components/form-modal/content.tsx +10 -0
  22. package/src/components/index.ts +1 -1
  23. package/src/components/layout/pane/footer/index.tsx +25 -11
  24. package/src/components/layout/pane/footer/model.ts +62 -20
  25. package/src/components/layout/pane/sidebar.tsx +125 -15
  26. package/src/components/layout/shell/active-drag.ts +18 -13
  27. package/src/components/layout/shell/drag/magnets.ts +34 -18
  28. package/src/components/ticker/list-table-view.tsx +5 -0
  29. package/src/components/ui/data-table/column-order.ts +180 -0
  30. package/src/components/ui/data-table/index.tsx +12 -1
  31. package/src/components/ui/data-table/opentui/index.tsx +267 -23
  32. package/src/components/ui/data-table/opentui/model.ts +43 -4
  33. package/src/components/ui/data-table/types.ts +49 -0
  34. package/src/components/ui/data-table/use-column-order.ts +135 -0
  35. package/src/components/ui/index.ts +1 -1
  36. package/src/components/ui/table-layout.ts +120 -0
  37. package/src/docs/snapshot.json +3 -2
  38. package/src/i18n/es.ts +2 -0
  39. package/src/i18n/ja.ts +2 -0
  40. package/src/i18n/ko.ts +2 -0
  41. package/src/i18n/zh-cn.ts +2 -0
  42. package/src/i18n/zh-tw.ts +2 -0
  43. package/src/market-data/coordinator/index.ts +4 -3
  44. package/src/market-data/coordinator/quotes.ts +12 -4
  45. package/src/market-data/quotes/freshness.ts +12 -0
  46. package/src/market-data/quotes/live-valuation.ts +1 -1
  47. package/src/market-data/quotes/regular-session-valuation.ts +1 -1
  48. package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
  49. package/src/plugins/builtin/broker-manager/index.tsx +6 -6
  50. package/src/plugins/builtin/broker-manager/model.ts +15 -6
  51. package/src/plugins/builtin/broker-manager/pane-actions.tsx +11 -4
  52. package/src/plugins/builtin/broker-manager/sign-in-end.ts +50 -19
  53. package/src/plugins/builtin/broker-manager/table.ts +10 -4
  54. package/src/plugins/builtin/chat/sidebar.tsx +33 -16
  55. package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
  56. package/src/plugins/builtin/equity-screener/live.ts +74 -18
  57. package/src/plugins/builtin/equity-screener/model.ts +19 -4
  58. package/src/plugins/builtin/equity-screener/pane.tsx +19 -14
  59. package/src/plugins/builtin/equity-screener/refresh-anchor.ts +45 -0
  60. package/src/plugins/builtin/equity-screener/results.ts +22 -2
  61. package/src/plugins/builtin/equity-screener/screen-check.ts +9 -3
  62. package/src/plugins/builtin/futures/index.tsx +15 -1
  63. package/src/plugins/builtin/futures/table.tsx +1 -1
  64. package/src/plugins/builtin/fx-matrix/index.tsx +2 -0
  65. package/src/plugins/builtin/holders/pane.tsx +30 -20
  66. package/src/plugins/builtin/iv-history/events.ts +5 -0
  67. package/src/plugins/builtin/iv-history/headless.ts +7 -2
  68. package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
  69. package/src/plugins/builtin/macro-day/headless.ts +12 -3
  70. package/src/plugins/builtin/options/view.tsx +2 -0
  71. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  72. package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
  73. package/src/plugins/builtin/portfolio-list/pane/index.tsx +13 -0
  74. package/src/plugins/builtin/portfolio-list/table.tsx +5 -0
  75. package/src/plugins/builtin/rate-path/pane.tsx +2 -0
  76. package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
  77. package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
  78. package/src/plugins/builtin/seasonality/pane.tsx +2 -1
  79. package/src/plugins/builtin/thirteenf/pane.tsx +2 -0
  80. package/src/plugins/builtin/ticker-detail/financials/model.ts +28 -6
  81. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +26 -9
  82. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +58 -35
  83. package/src/plugins/builtin/vol-surface/heat-grid.tsx +2 -1
  84. package/src/plugins/builtin/vol-surface/pane.tsx +2 -1
  85. package/src/plugins/builtin/world-indices/index.tsx +5 -1
  86. package/src/plugins/builtin/yield-curve/index.tsx +2 -1
  87. package/src/renderers/dom/data-table/column-drag.ts +147 -0
  88. package/src/renderers/dom/data-table/index.tsx +22 -0
  89. package/src/renderers/dom/data-table/row.tsx +27 -5
  90. package/src/renderers/dom/styles.css +22 -0
  91. package/src/renderers/opentui/chart-surface.tsx +1 -0
  92. package/src/renderers/opentui/frame-hits.ts +33 -0
  93. package/src/renderers/opentui/host.tsx +2 -0
  94. package/src/renderers/opentui/native-surface.ts +14 -21
  95. package/src/renderers/opentui/test-utils.tsx +3 -0
  96. package/src/state/app/context/index.tsx +22 -0
  97. package/src/test-support/app-store.ts +24 -1
  98. package/src/time-series/live-quotes.ts +3 -9
  99. package/src/ui/host.tsx +18 -0
  100. package/src/ui/pointer-drag.ts +11 -2
  101. package/src/utils/fundamentals.ts +14 -3
  102. package/src/utils/share-multiples.cases.json +780 -2
  103. package/src/utils/share-multiples.ts +154 -24
@@ -1,6 +1,10 @@
1
1
  import { useCallback, useMemo, useSyncExternalStore } from "react";
2
2
  import { apiClient } from "../../../api-client";
3
- import { fetchSignedInBrokerConnection, type SignedInBrokerConnection } from "../../../brokers/signed-in/client";
3
+ import {
4
+ type BrokerReplacePrompt,
5
+ fetchSignedInBrokerConnection,
6
+ type SignedInBrokerConnection,
7
+ } from "../../../brokers/signed-in/client";
4
8
  import { isSignedInBrokerProfile, signedInBrokerId } from "../../../brokers/signed-in/profile";
5
9
  import { tf } from "../../../i18n";
6
10
  import { useAsyncResource } from "../../../react/async-resource";
@@ -9,16 +13,41 @@ import { formatDetailDate, formatShortDate } from "../../../utils/datetime-forma
9
13
 
10
14
  /**
11
15
  * Some brokers end a sign-in on their own clock, however often it was
12
- * refreshed, and Gloom flags it a day before. Only that case shows anything: a
13
- * server that predates the flag, or a sign-in with no end in sight, adds nothing.
16
+ * refreshed (IBKR: seven days after consent). While such a sign-in is live the
17
+ * pane always says when it ends, and Connect renews it early; Gloom flags the
18
+ * last stretch (`soon`), when it is time to renew. A broker with no such
19
+ * clock, or a sign-in that is not live, has no end to show.
14
20
  */
15
- export type SignInEnds = ReadonlyMap<string, number>;
21
+ export interface SignInEnd {
22
+ endsAt: number;
23
+ /** Gloom says it is time to renew: within its warning window, or past the end. */
24
+ soon: boolean;
25
+ }
26
+
27
+ /** What Gloom says about a profile's sign-in: when it ends, and what the broker asks on the next one. */
28
+ export interface SignInRead {
29
+ end: SignInEnd | null;
30
+ /**
31
+ * Whether the broker will or may ask to replace the Gloom connection it
32
+ * lists when the user signs in again; undefined from a Gloom server that
33
+ * predates it.
34
+ */
35
+ replacePrompt?: BrokerReplacePrompt | null;
36
+ }
16
37
 
17
- /** When the broker ends the sign-in, if Gloom says it is time to connect again. */
18
- export function signInEndOf(connection: Pick<SignedInBrokerConnection, "expiresAt" | "expiresSoon">): number | null {
19
- if (connection.expiresSoon !== true || !connection.expiresAt) return null;
38
+ export type SignInReads = ReadonlyMap<string, SignInRead>;
39
+
40
+ /** When the broker ends the live sign-in, and whether Gloom says to renew it now. */
41
+ export function signInEndOf(connection: Pick<SignedInBrokerConnection, "expiresAt" | "expiresSoon">): SignInEnd | null {
42
+ if (!connection.expiresAt) return null;
20
43
  const endsAt = Date.parse(connection.expiresAt);
21
- return Number.isFinite(endsAt) ? endsAt : null;
44
+ return Number.isFinite(endsAt) ? { endsAt, soon: connection.expiresSoon === true } : null;
45
+ }
46
+
47
+ /** What Gloom says about the account's connection to a broker. */
48
+ export function signInReadOf(connection: SignedInBrokerConnection): SignInRead {
49
+ const end = signInEndOf(connection);
50
+ return "replacePrompt" in connection ? { end, replacePrompt: connection.replacePrompt ?? null } : { end };
22
51
  }
23
52
 
24
53
  /** The profile row's status, in the place of "Connected": "Ends Oct 10". */
@@ -34,13 +63,15 @@ export function signInEndNote(endsAt: number, now = Date.now()): string {
34
63
  }
35
64
 
36
65
  /**
37
- * When each signed-in profile's sign-in ends, by instance id, for the profiles
38
- * whose broker is about to end it. Read from Gloom when the pane opens and
39
- * after a connect or sync; a failed read is the same as nothing to say.
66
+ * What Gloom says about each signed-in profile's sign-in, by instance id: when
67
+ * it ends, for a broker that ends it on a clock, and whether the broker will
68
+ * ask to replace Gloom's connection on the next one. Read from Gloom when the
69
+ * pane opens and after a connect or sync; a failed read is the same as
70
+ * nothing to say.
40
71
  */
41
- export function useSignInEnds(
72
+ export function useSignInReads(
42
73
  instances: readonly BrokerInstanceConfig[],
43
- ): { ends: SignInEnds; reload: () => void } {
74
+ ): { reads: SignInReads; reload: () => void } {
44
75
  const profiles = useMemo(
45
76
  () => instances.flatMap((instance) => isSignedInBrokerProfile(instance) && instance.enabled !== false
46
77
  ? [{ id: instance.id, broker: signedInBrokerId(instance) }]
@@ -59,7 +90,7 @@ export function useSignInEnds(
59
90
  ? async () => {
60
91
  const reads = await Promise.all(brokerKey.split(",").map(async (broker) => {
61
92
  try {
62
- return [broker, signInEndOf(await fetchSignedInBrokerConnection(broker))] as const;
93
+ return [broker, signInReadOf(await fetchSignedInBrokerConnection(broker))] as const;
63
94
  } catch {
64
95
  return [broker, null] as const;
65
96
  }
@@ -69,14 +100,14 @@ export function useSignInEnds(
69
100
  : null, [brokerKey, signedIn]);
70
101
  const { data, reload } = useAsyncResource(loader, { keepPreviousData: true });
71
102
 
72
- const ends = useMemo<SignInEnds>(() => {
73
- const byInstance = new Map<string, number>();
103
+ const reads = useMemo<SignInReads>(() => {
104
+ const byInstance = new Map<string, SignInRead>();
74
105
  for (const profile of profiles) {
75
- const endsAt = data?.get(profile.broker);
76
- if (endsAt != null) byInstance.set(profile.id, endsAt);
106
+ const read = data?.get(profile.broker);
107
+ if (read) byInstance.set(profile.id, read);
77
108
  }
78
109
  return byInstance;
79
110
  }, [data, profiles]);
80
111
  const refresh = useCallback(() => { reload(); }, [reload]);
81
- return { ends, reload: refresh };
112
+ return { reads, reload: refresh };
82
113
  }
@@ -45,15 +45,21 @@ export function buildBrokerColumns(width: number): BrokerColumn[] {
45
45
 
46
46
  /**
47
47
  * What a profile's STATUS says, in the table and atop its detail: the action
48
- * running on it, then the one that just failed on it, then a sign-in the
49
- * broker is about to end, then its own state ("Disabled", "Sign-in needed").
48
+ * running on it, then the one that just failed on it, then when the broker
49
+ * ends its sign-in, then its own state ("Disabled", "Sign-in needed").
50
50
  */
51
51
  export function brokerRowStatus(row: BrokerProfileRow, activity: BrokerRowActivity = {}): { text: string; color: string } {
52
52
  if (activity.busy) return { text: activity.busy, color: colors.warning };
53
53
  // A sign-in the broker wants says more than which step ran into it.
54
54
  if (activity.note?.status && row.state !== "sign-in") return { text: activity.note.status, color: colors.negative };
55
- // A sign-in the broker is about to end replaces "Connected" until it is renewed.
56
- if (row.signInEndsAt !== null) return { text: signInEndStatus(row.signInEndsAt), color: colors.warning };
55
+ // A sign-in the broker ends on its clock says when, in place of "Connected";
56
+ // in the profile's state colour until it is time to renew.
57
+ if (row.signInEnd !== null) {
58
+ return {
59
+ text: signInEndStatus(row.signInEnd.endsAt),
60
+ color: row.signInEnd.soon ? colors.warning : stateColor(row.state),
61
+ };
62
+ }
57
63
  return { text: row.stateLabel, color: stateColor(row.state) };
58
64
  }
59
65
 
@@ -1,6 +1,6 @@
1
1
  import { ActionRow } from "../../../components/ui/action-row";
2
2
  import { Icon } from "../../../components/ui/icon";
3
- import { useMemo, useSyncExternalStore } from "react";
3
+ import { useMemo, useRef, useSyncExternalStore, type ReactNode } from "react";
4
4
  import {
5
5
  getPaneSidebarWidthRange,
6
6
  PaneSidebar,
@@ -8,7 +8,8 @@ import {
8
8
  PaneSidebarList,
9
9
  PaneSidebarRow,
10
10
  } from "../../../components";
11
- import { Box, Span, Text, useUiCapabilities } from "../../../ui";
11
+ import { usePaneSidebarReveal } from "../../../components/layout/pane/sidebar";
12
+ import { Box, Span, Text, useUiCapabilities, type BoxRenderable } from "../../../ui";
12
13
  import { TextAttributes } from "../../../ui";
13
14
  import { blendHex, colors } from "../../../theme/colors";
14
15
  import { t } from "../../../i18n";
@@ -65,6 +66,22 @@ function ChannelNotificationIcon({
65
66
  );
66
67
  }
67
68
 
69
+ /** A section's header, kept in view while the keyboard's cursor is on it. */
70
+ function SectionHeaderRow({ width, cursor, backgroundColor, children }: {
71
+ width: number;
72
+ cursor: boolean;
73
+ backgroundColor: string;
74
+ children: ReactNode;
75
+ }) {
76
+ const ref = useRef<BoxRenderable>(null);
77
+ usePaneSidebarReveal(ref, cursor);
78
+ return (
79
+ <Box ref={ref} height={1} width={width} flexDirection="row" backgroundColor={backgroundColor}>
80
+ {children}
81
+ </Box>
82
+ );
83
+ }
84
+
68
85
  function ProfileIcon({
69
86
  color,
70
87
  onMouseDown,
@@ -182,13 +199,12 @@ export function ChannelSidebar({
182
199
  onResizeEnd: (nextWidth) => chatSidebarStore.commitWidth(nextWidth),
183
200
  } : undefined}
184
201
  >
185
- {({ backgroundColor: sidebarBg, listWidth }) => {
186
- const labelWidth = Math.max(listWidth - CHANNEL_ROW_INDENT - notificationWidth, 1);
202
+ {({ backgroundColor: sidebarBg, listWidth: sidebarWidth }) => {
187
203
  // The fill a keyboard-focused sidebar gives the row under its cursor.
188
204
  const cursorBackground = blendHex(colors.selected, colors.borderFocused, 0.32);
189
205
  // Every section reads the same: a caret, a label, and an optional
190
206
  // trailing action, so their channels can all share one indent.
191
- const sectionHeader = ({ key, label, fg, unread, expanded, onToggle, action }: {
207
+ const sectionHeader = (listWidth: number, { key, label, fg, unread, expanded, onToggle, action }: {
192
208
  key: string;
193
209
  label: string;
194
210
  fg?: string;
@@ -198,13 +214,13 @@ export function ChannelSidebar({
198
214
  action?: { ariaLabel: string; onPress: () => void };
199
215
  }) => {
200
216
  const rowWidth = Math.max(1, listWidth - (action ? SECTION_ACTION_WIDTH : 0));
217
+ const cursor = keyboardFocused && cursorHeaderKey === key;
201
218
  return (
202
- <Box
219
+ <SectionHeaderRow
203
220
  key={key}
204
- height={1}
205
221
  width={listWidth}
206
- flexDirection="row"
207
- backgroundColor={keyboardFocused && cursorHeaderKey === key ? cursorBackground : sidebarBg}
222
+ cursor={cursor}
223
+ backgroundColor={cursor ? cursorBackground : sidebarBg}
208
224
  >
209
225
  <ActionRow
210
226
  label={truncateWithEllipsis(label, Math.max(1, rowWidth - CHANNEL_ROW_INDENT))}
@@ -225,15 +241,16 @@ export function ChannelSidebar({
225
241
  )}
226
242
  </PaneSidebarAction>
227
243
  ) : null}
228
- </Box>
244
+ </SectionHeaderRow>
229
245
  );
230
246
  };
231
247
  return (
232
248
  <>
233
249
  <PaneSidebarList>
234
- {sidebarRows.map((row) => {
250
+ {({ listWidth }) => sidebarRows.map((row) => {
251
+ const labelWidth = Math.max(listWidth - CHANNEL_ROW_INDENT - notificationWidth, 1);
235
252
  if (row.kind === "public-header") {
236
- return sectionHeader({
253
+ return sectionHeader(listWidth, {
237
254
  key: row.key,
238
255
  label: "Channels",
239
256
  unread: hasUnread(row.channels),
@@ -243,7 +260,7 @@ export function ChannelSidebar({
243
260
  }
244
261
  if (row.kind === "team-header") {
245
262
  const canAddChannel = !!row.team && !!onCreateTeamChannel;
246
- return sectionHeader({
263
+ return sectionHeader(listWidth, {
247
264
  key: row.key,
248
265
  label: row.team ? `${teamPrefix(row.team)} ${row.team.name}` : "Team",
249
266
  fg: row.team ? teamAccentHex(row.team.accentColor) : colors.textDim,
@@ -259,7 +276,7 @@ export function ChannelSidebar({
259
276
  });
260
277
  }
261
278
  if (row.kind === "direct-header") {
262
- return sectionHeader({
279
+ return sectionHeader(listWidth, {
263
280
  key: row.key,
264
281
  label: "DMs",
265
282
  unread: hasUnread(row.channels),
@@ -325,7 +342,7 @@ export function ChannelSidebar({
325
342
  <Text fg={foregroundColor} selectable={false} onMouseDown={onMouseDown}> </Text>
326
343
  <ProfileIcon color={foregroundColor} onMouseDown={onMouseDown} />
327
344
  <Text fg={foregroundColor} selectable={false} onMouseDown={onMouseDown}>
328
- {` ${truncateWithEllipsis(t("Profile"), Math.max(listWidth - 3, 1))}`}
345
+ {` ${truncateWithEllipsis(t("Profile"), Math.max(sidebarWidth - 3, 1))}`}
329
346
  </Text>
330
347
  <Box flexGrow={1} onMouseDown={onMouseDown} />
331
348
  </>
@@ -333,7 +350,7 @@ export function ChannelSidebar({
333
350
  </PaneSidebarRow>
334
351
  )}
335
352
  {loading && focused && (
336
- <Box height={1} width={listWidth} flexDirection="row">
353
+ <Box height={1} width={sidebarWidth} flexDirection="row">
337
354
  <Text fg={colors.textDim}>{` ${t("syncing")}`}</Text>
338
355
  </Box>
339
356
  )}
@@ -386,6 +386,8 @@ export function ToolResultDetail({
386
386
  rootWidth={width}
387
387
  rootHeight={Math.max(3, height - headerHeight)}
388
388
  columns={columns}
389
+ // A tool's answer, read once: its columns are the tool's, not a layout to keep with the pane.
390
+ columnReorder={false}
389
391
  items={table.rows}
390
392
  sortColumnId={null}
391
393
  sortDirection="asc"
@@ -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
+ }
@@ -8,7 +8,16 @@ import { logFailure } from "../../../utils/log-failure";
8
8
  import { fetchScreen } from "./client";
9
9
  import { appendScreenPage } from "./model";
10
10
 
11
- /** Query changes and pagination cannot exchange data across immutable snapshots. */
11
+ /** A refresh re-reads what a long list holds, up to this many rows, so it does not walk an endless one. */
12
+ const REFRESH_ROW_LIMIT = 1_000;
13
+
14
+ /**
15
+ * Query changes and pagination cannot exchange data across immutable snapshots.
16
+ * A refresh of a screen already loaded replaces its rows in place: the first
17
+ * page of the new snapshot, then as many more as the list held, swapped in
18
+ * together so the table keeps its length and its scroll position. A refresh
19
+ * that finds the same snapshot keeps the pages as they are.
20
+ */
12
21
  export function useScreenResults(
13
22
  definition: ScreenDefinition,
14
23
  sessionKey: string,
@@ -42,6 +51,7 @@ export function useScreenResults(
42
51
  moreController.current = null;
43
52
  const request = new AbortController();
44
53
  controller.current = request;
54
+ const held = stateRef.current.identity === identity ? stateRef.current.data : null;
45
55
  setState((current) => ({
46
56
  identity,
47
57
  data: current.identity === identity ? current.data : null,
@@ -51,8 +61,18 @@ export function useScreenResults(
51
61
  updatedAt: current.identity === identity ? current.updatedAt : null,
52
62
  }));
53
63
  try {
54
- const data = await fetcher(definition, null, request.signal);
64
+ let data = await fetcher(definition, null, request.signal);
55
65
  if (request.signal.aborted || activeIdentity.current !== identity) return;
66
+ if (held?.snapshot && data.snapshot?.id === held.snapshot.id) {
67
+ data = held;
68
+ } else if (held) {
69
+ const wanted = Math.min(held.rows.length, REFRESH_ROW_LIMIT);
70
+ while (data.nextCursor && data.rows.length < wanted) {
71
+ const page = await fetcher(definition, data.nextCursor, request.signal);
72
+ if (request.signal.aborted || activeIdentity.current !== identity) return;
73
+ data = appendScreenPage(data, page);
74
+ }
75
+ }
56
76
  setState({
57
77
  identity,
58
78
  data,
@@ -1,10 +1,16 @@
1
1
  import type { NumericField, ScreenCheckPayload, ScreenCriterion, ScreenDefinition } from "../../../api-client/equity-screener";
2
- import { canonicalExchange, parsePublicTickerKey } from "../../../utils/exchanges";
2
+ import { parseListingArg } from "../../../cli/listing-arg";
3
+ import { canonicalExchange } from "../../../utils/exchanges";
3
4
  import { criterionText, formatScreenValue, GRADE_DISPLAY_FIELDS, parseScreenDefinition, screenDefinitionKey, screenLabel } from "./model";
4
5
 
5
- /** One listing, with the same exchange aliases the rest of the app accepts. */
6
+ /**
7
+ * One listing, read as `quote` reads it before it asks: 700:HKEX, 700.HK and
8
+ * 00700.HK are 0700:HKEX, GARAN.IS is GARAN:BIST, "VOD LN" VOD:LSE. A bare
9
+ * symbol stays bare, for the screen to pick its listing.
10
+ */
6
11
  export function screenCheckTicker(text: string): { symbol: string; exchange?: string } {
7
- const ticker = parsePublicTickerKey(text.trim());
12
+ const listing = parseListingArg(text.trim(), null, { listingSuffix: true });
13
+ const ticker = listing.exchange ? { symbol: listing.symbol, exchange: listing.exchange } : { symbol: listing.symbol };
8
14
  if (!/^[A-Z0-9][A-Z0-9./-]{0,31}$/.test(ticker.symbol)
9
15
  || (ticker.exchange !== undefined && !/^[A-Z0-9_-]{1,24}$/.test(ticker.exchange)))
10
16
  throw new Error("Enter one ticker, such as NVDA or NVDA:NASDAQ.");