@gloom-sh/terminal 0.20.14 → 0.20.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/index.ts +54 -0
  3. package/src/api-client/install-experiments.ts +8 -7
  4. package/src/api-client/paths.ts +2 -1
  5. package/src/api-client/product-waitlist.ts +63 -0
  6. package/src/api-client/request.ts +4 -2
  7. package/src/api-client/types/billing.ts +45 -0
  8. package/src/api-client/yearly-plan.ts +132 -0
  9. package/src/app/global-shortcuts.ts +5 -3
  10. package/src/app/pane-runtime/index.tsx +2 -2
  11. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  12. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  13. package/src/app/since-last-visit/keys.ts +26 -0
  14. package/src/app/since-last-visit/model.ts +266 -0
  15. package/src/app/since-last-visit/strip.tsx +193 -0
  16. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  17. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  18. package/src/app.tsx +15 -0
  19. package/src/cli/commands/market.ts +8 -4
  20. package/src/cli/commands/system.ts +29 -1
  21. package/src/cli/commands/ticker.ts +12 -5
  22. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  23. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  24. package/src/cli/desktop-pane-shot-view.ts +3 -7
  25. package/src/cli/desktop-pane-shot.ts +26 -28
  26. package/src/cli/help.ts +1 -0
  27. package/src/cli/history-rows.ts +24 -0
  28. package/src/cli/index.ts +4 -0
  29. package/src/cli/options.ts +29 -1
  30. package/src/cli/pane-functions/catalog.ts +41 -4
  31. package/src/cli/pane-functions/function-help.ts +1 -1
  32. package/src/cli/pane-functions/headless.ts +63 -1
  33. package/src/cli/pane-functions/index.ts +2 -2
  34. package/src/cli/pane-functions/resolver.ts +43 -0
  35. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  36. package/src/cli/report-tables.ts +20 -5
  37. package/src/cli/shot-temp-dir.ts +30 -0
  38. package/src/cli/suffixed-listing-rows.ts +11 -0
  39. package/src/components/chart/composite/composite-chart.tsx +3 -3
  40. package/src/components/command-bar/commands/direct/index.ts +31 -8
  41. package/src/components/command-bar/commands/registry.ts +7 -0
  42. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  43. package/src/components/command-bar/routes/root/results.ts +16 -0
  44. package/src/components/company-logo.tsx +10 -3
  45. package/src/components/data-table/sections.ts +6 -1
  46. package/src/components/layout/pane/title.ts +6 -2
  47. package/src/components/layout/shell/index.tsx +5 -1
  48. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  49. package/src/components/ticker/badge/format.ts +12 -3
  50. package/src/components/ticker/badge/index.tsx +9 -3
  51. package/src/components/ticker/list-table-view.tsx +119 -17
  52. package/src/components/ui/data-table/display-columns.ts +16 -0
  53. package/src/components/ui/data-table/index.tsx +40 -9
  54. package/src/components/ui/data-table/types.ts +14 -0
  55. package/src/core/state/app/layout-reducer.ts +3 -1
  56. package/src/core/state/app/layout.ts +2 -2
  57. package/src/data/config/layout.ts +14 -0
  58. package/src/data/config/store/normalize.ts +11 -1
  59. package/src/i18n/es.ts +38 -0
  60. package/src/i18n/ja.ts +38 -0
  61. package/src/i18n/ko.ts +38 -0
  62. package/src/i18n/zh-cn.ts +38 -0
  63. package/src/i18n/zh-tw.ts +38 -0
  64. package/src/layout/pane-follow.ts +141 -4
  65. package/src/layout/pane-layout-move.ts +10 -7
  66. package/src/layout/ticker-navigation.ts +13 -19
  67. package/src/layout/ticker-retarget.ts +3 -2
  68. package/src/market-data/market/index-level.ts +19 -0
  69. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  70. package/src/plugins/builtin/account-management/model.ts +2 -0
  71. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  72. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  73. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  74. package/src/plugins/builtin/awards/pane.tsx +6 -8
  75. package/src/plugins/builtin/changelog/index.tsx +6 -44
  76. package/src/plugins/builtin/changelog/versions.ts +17 -68
  77. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  78. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  79. package/src/plugins/builtin/cpi/pane.tsx +1 -1
  80. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  81. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  82. package/src/plugins/builtin/earnings/board.tsx +36 -16
  83. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  84. package/src/plugins/builtin/earnings/history-table.ts +1 -1
  85. package/src/plugins/builtin/earnings/index.tsx +1 -1
  86. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  87. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  88. package/src/plugins/builtin/exposure/index.tsx +1 -1
  89. package/src/plugins/builtin/macro-day/model.ts +6 -4
  90. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  91. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  92. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  93. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  94. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  95. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  96. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  97. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +176 -17
  98. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  99. package/src/plugins/builtin/portfolio-list/pane/index.tsx +90 -15
  100. package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
  101. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  102. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  103. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  104. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  105. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  106. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  107. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  108. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  109. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  110. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  111. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  112. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  113. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  114. package/src/plugins/builtin/ticker-detail/headless.ts +254 -34
  115. package/src/plugins/builtin/ticker-detail/overview/model.ts +7 -3
  116. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  117. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  118. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  119. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  120. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  121. package/src/portfolio/column-values.ts +20 -8
  122. package/src/portfolio/suffixed-listings.ts +3 -1
  123. package/src/portfolio/watchlist-groups.ts +212 -0
  124. package/src/react/ticker-source.ts +3 -1
  125. package/src/renderers/dom/styles.css +7 -0
  126. package/src/state/app/bootstrap.ts +11 -0
  127. package/src/state/app/context/index.tsx +6 -0
  128. package/src/sync/collections-contributor.ts +5 -2
  129. package/src/sync/config-merge.ts +10 -2
  130. package/src/sync/sanitize.ts +28 -0
  131. package/src/telemetry/usage-counts.ts +17 -0
  132. package/src/time-series/chart-seed.ts +1 -1
  133. package/src/time-series/financial-period-coverage.ts +4 -12
  134. package/src/time-series/parsed-history-cache.ts +1 -1
  135. package/src/time-series/resolve.ts +1 -1
  136. package/src/time-series/use-chart-resolution.ts +6 -1
  137. package/src/types/config.ts +32 -0
  138. package/src/types/headless.ts +5 -0
  139. package/src/types/plugin-context.ts +5 -0
  140. package/src/types/ticker.ts +14 -0
  141. package/src/ui/ascii-font.ts +1 -4
  142. package/src/utils/async-deadline.ts +2 -2
  143. package/src/utils/csv.ts +44 -5
  144. package/src/utils/futures-generic.ts +3 -0
@@ -0,0 +1,126 @@
1
+ import { useCallback, useEffect, useRef, useState } from "react";
2
+ import type { apiClient } from "../../../../api-client";
3
+ import { isEmailVerificationRequired, type WaitlistProduct, type WaitlistState } from "../../../../api-client/product-waitlist";
4
+ import { errorMessage } from "../../../../utils/errors";
5
+
6
+ /** The waitlist calls the tab makes; tests hand it their own. */
7
+ export type WaitlistClient = Pick<typeof apiClient, "getWaitlist" | "joinWaitlist" | "leaveWaitlist">;
8
+
9
+ export interface ProductWaitlist {
10
+ /** Whether the signed-in account is on the list; undefined until its read answers, or signed out. */
11
+ joined: boolean | undefined;
12
+ /** The account's place is being read. */
13
+ loading: boolean;
14
+ /** Why the read failed; null otherwise. */
15
+ error: string | null;
16
+ /**
17
+ * The service refused the account because its address is not verified: its
18
+ * place cannot be read or changed until it is. Not an error to retry.
19
+ */
20
+ unverified: boolean;
21
+ /** A join or a leave on its way. */
22
+ pending: "join" | "leave" | null;
23
+ /** Reads the account's place again. */
24
+ retry(): void;
25
+ /**
26
+ * Joins or leaves for `account`, the one the person decided as. Nothing is
27
+ * sent when another account holds the session by now, and an answer that
28
+ * lands after the account changed is not shown: null in both cases.
29
+ */
30
+ change(joined: boolean, account: string): Promise<WaitlistState | null>;
31
+ }
32
+
33
+ interface Snapshot {
34
+ account: string | null;
35
+ joined: boolean | undefined;
36
+ error: string | null;
37
+ unverified: boolean;
38
+ pending: "join" | "leave" | null;
39
+ }
40
+
41
+ function fresh(account: string | null): Snapshot {
42
+ return { account, joined: undefined, error: null, unverified: false, pending: null };
43
+ }
44
+
45
+ /**
46
+ * The signed-in account's place on a product's waitlist. Everything is the
47
+ * account's: a sign-in, a sign-out or another account starts from nothing at
48
+ * once, and no answer for the account that left is shown for the next one.
49
+ * A read that was already out when a join or a leave began is dropped, so it
50
+ * cannot put back the state from before the change. `account` is null for an
51
+ * account the app already knows is unverified: nothing is sent for it.
52
+ */
53
+ export function useProductWaitlist(client: WaitlistClient, product: WaitlistProduct, account: string | null): ProductWaitlist {
54
+ const [stored, setStored] = useState<Snapshot>(() => fresh(account));
55
+ const [reads, setReads] = useState(0);
56
+ const accountRef = useRef(account);
57
+ accountRef.current = account;
58
+ // Bumped by every change: a read that began before it answers too late.
59
+ const changes = useRef(0);
60
+ // The account a change is on its way for; a second press waits for it.
61
+ const changing = useRef<string | null>(null);
62
+
63
+ const snapshot = stored.account === account ? stored : fresh(account);
64
+ if (snapshot !== stored) setStored(snapshot);
65
+
66
+ const update = useCallback((forAccount: string, patch: Partial<Snapshot>) => {
67
+ setStored((current) => (current.account === forAccount ? { ...current, ...patch } : current));
68
+ }, []);
69
+
70
+ useEffect(() => {
71
+ if (!account) return;
72
+ let live = true;
73
+ const since = changes.current;
74
+ const current = () => live && accountRef.current === account && changes.current === since;
75
+ client.getWaitlist(product).then((state) => {
76
+ if (current()) update(account, { joined: state.joined, error: null, unverified: false });
77
+ }, (error: unknown) => {
78
+ if (!current()) return;
79
+ // Refused for an unverified address, the place is unknown again, not the last one read.
80
+ update(account, isEmailVerificationRequired(error) ? { joined: undefined, unverified: true } : { error: errorMessage(error) });
81
+ });
82
+ return () => { live = false; };
83
+ }, [account, client, product, reads, update]);
84
+
85
+ const retry = useCallback(() => {
86
+ if (accountRef.current) update(accountRef.current, { error: null, unverified: false });
87
+ setReads((count) => count + 1);
88
+ }, [update]);
89
+
90
+ const change = useCallback(async (joined: boolean, forAccount: string): Promise<WaitlistState | null> => {
91
+ if (accountRef.current !== forAccount || changing.current === forAccount) return null;
92
+ changing.current = forAccount;
93
+ changes.current += 1;
94
+ update(forAccount, { pending: joined ? "join" : "leave" });
95
+ try {
96
+ const state = joined ? await client.joinWaitlist(product) : await client.leaveWaitlist(product);
97
+ if (accountRef.current !== forAccount) return null;
98
+ update(forAccount, { joined: state.joined, error: null, unverified: false, pending: null });
99
+ return state;
100
+ } catch (error) {
101
+ if (accountRef.current === forAccount) {
102
+ if (isEmailVerificationRequired(error)) {
103
+ // The service holds no answer for this account until it verifies: nothing to read again.
104
+ update(forAccount, { joined: undefined, unverified: true, pending: null });
105
+ } else {
106
+ update(forAccount, { pending: null });
107
+ // The read this change dropped is asked again, so the state is known.
108
+ setReads((count) => count + 1);
109
+ }
110
+ }
111
+ throw error;
112
+ } finally {
113
+ if (changing.current === forAccount) changing.current = null;
114
+ }
115
+ }, [client, product, update]);
116
+
117
+ return {
118
+ joined: snapshot.joined,
119
+ loading: !!account && snapshot.joined === undefined && snapshot.error === null && !snapshot.unverified,
120
+ error: snapshot.error,
121
+ unverified: snapshot.unverified,
122
+ pending: snapshot.pending,
123
+ retry,
124
+ change,
125
+ };
126
+ }
@@ -1,4 +1,5 @@
1
1
  import { ADR_PAIR_TAB_ID } from "./adr-pair/model";
2
+ import { PHARMA_SIGNALS_TAB_ID } from "./pharma-signals/eligibility";
2
3
 
3
4
  /** What the grouping reads of a research tab. */
4
5
  export interface TickerResearchTabSummary {
@@ -23,9 +24,10 @@ interface TickerResearchGroupDef {
23
24
  * Trade is Chart with the ticket beside it, and closing the ticket goes back
24
25
  * to Chart (`ResearchTradeWorkspace`), so it is Chart's second view. ADR vs
25
26
  * Home, the receipt's price against its home line, is the last of
26
- * Financials. Both show only for some tickers, so each comes after the views
27
- * every ticker has. A plugin's own tab is in no group: it gets its own top
28
- * tab after these (`groupTickerResearchTabs`).
27
+ * Financials. Signals, a drug developer's add-on waitlist, is the last of
28
+ * Events, beside its catalysts. Each shows only for some tickers, so each
29
+ * comes after the views every ticker has. A plugin's own tab is in no group:
30
+ * it gets its own top tab after these (`groupTickerResearchTabs`).
29
31
  */
30
32
  const TICKER_RESEARCH_GROUPS: readonly TickerResearchGroupDef[] = [
31
33
  { id: "overview", name: "Overview", views: ["overview"] },
@@ -33,7 +35,7 @@ const TICKER_RESEARCH_GROUPS: readonly TickerResearchGroupDef[] = [
33
35
  { id: "financials", name: "Financials", views: ["financials", "revenue", "equity-diagnostic", "dividend-yield", ADR_PAIR_TAB_ID] },
34
36
  { id: "analysts", name: "Analysts", views: ["analyst-research", "earnings-calls"] },
35
37
  { id: "options", name: "Options", views: ["options"] },
36
- { id: "events", name: "Events", views: ["corporate-actions", "catalysts", "mna"] },
38
+ { id: "events", name: "Events", views: ["corporate-actions", "catalysts", "mna", PHARMA_SIGNALS_TAB_ID] },
37
39
  { id: "filings", name: "Filings", views: ["sec", "filing-events", "risk-factors"] },
38
40
  { id: "ownership", name: "Ownership", views: ["holders", "insider", "thirteenf", "congress", "short-interest"] },
39
41
  { id: "people", name: "People", views: ["executives", "jobs", "hiring-momentum"] },
@@ -5,6 +5,8 @@ import { AdrPairResearchTab } from "./adr-pair/tab";
5
5
  import { ADR_PAIR_TAB_ID } from "./adr-pair/model";
6
6
  import { listingDepositaryPair } from "../../../market-data/depositary-pair";
7
7
  import { hasStatementFinancials } from "./financials/model";
8
+ import { isPharmaSignalsListing, PHARMA_SIGNALS_TAB_ID } from "./pharma-signals/eligibility";
9
+ import { PharmaSignalsResearchTab } from "./pharma-signals/tab";
8
10
 
9
11
  /**
10
12
  * Tabs this module owns. They are registered through `setup()` like any other
@@ -36,4 +38,13 @@ export const TICKER_RESEARCH_BUILTIN_TABS: TickerResearchTabDef[] = [
36
38
  component: AdrPairResearchTab,
37
39
  isVisible: ({ financials }) => !!listingDepositaryPair(financials),
38
40
  },
41
+ {
42
+ // A drug developer's add-on that is not built yet: a no-charge waitlist, on no other listing.
43
+ id: PHARMA_SIGNALS_TAB_ID,
44
+ name: "Signals",
45
+ order: 36,
46
+ component: PharmaSignalsResearchTab,
47
+ instruments: ["equity"],
48
+ isVisible: ({ financials, instrumentKind }) => isPharmaSignalsListing(instrumentKind, financials?.profile),
49
+ },
39
50
  ];
@@ -40,7 +40,7 @@ import {
40
40
  import { formatOptionTicker } from "../utils/options";
41
41
  import { distributionHistory, forwardYieldMayHaveLapsed, lapsedDividend } from "../utils/forward-dividend";
42
42
  import { classifyInstrumentType } from "../tickers/instrument-kind";
43
- import { isIndexLevel, reportedQuoteVolume } from "../market-data/market/index-level";
43
+ import { isIndexLevel, quoteVolumeCurrency, reportedQuoteVolume } from "../market-data/market/index-level";
44
44
  import { futuresQuoteFromSettle } from "../market-data/market/change-basis";
45
45
  import { perpetualDisplaySymbol, perpetualListing } from "../tickers/perpetual-listing";
46
46
  import { premiumToUnderlying, type PerpetualPremiumRow } from "../market-data/perpetual-premium";
@@ -692,9 +692,8 @@ export function getColumnValue(
692
692
  return { text: volume != null ? formatCompact(volume, { fixedDecimals: true }) : MISSING_VALUE };
693
693
  }
694
694
  case "dollar_volume": {
695
- const volume = reportedQuoteVolume(quote);
696
- if (!displayQuote || volume == null) return { text: MISSING_VALUE };
697
- return { text: formatCompact(toBaseQuote(displayQuote.price * volume), { fixedDecimals: true }) };
695
+ const traded = tradedValue(quote, displayQuote, toBaseQuote);
696
+ return { text: traded == null ? MISSING_VALUE : formatCompact(traded, { fixedDecimals: true }) };
698
697
  }
699
698
  case "range_52w": {
700
699
  const position = fiftyTwoWeekPosition(displayQuote, quote);
@@ -869,6 +868,21 @@ export function getColumnValue(
869
868
  }
870
869
  }
871
870
 
871
+ /**
872
+ * The value a row's volume traded, in the base currency: shares or contracts at the price, or a coin's volume
873
+ * itself, which is already a value in its quote currency (quoteVolumeCurrency), never priced again.
874
+ */
875
+ function tradedValue(
876
+ quote: Quote | null | undefined,
877
+ displayQuote: { price: number } | null | undefined,
878
+ toBaseQuote: (value: number) => number,
879
+ ): number | null {
880
+ const volume = reportedQuoteVolume(quote);
881
+ if (volume == null) return null;
882
+ if (quoteVolumeCurrency(quote)) return toBaseQuote(volume);
883
+ return displayQuote ? toBaseQuote(displayQuote.price * volume) : null;
884
+ }
885
+
872
886
  export function getSortValue(
873
887
  col: ColumnConfig,
874
888
  ticker: TickerRecord,
@@ -942,10 +956,8 @@ export function getSortValue(
942
956
  return quote?.delisting ? null : headlineChangePercent(headlineQuote, quote) ?? null;
943
957
  case "volume":
944
958
  return reportedQuoteVolume(quote);
945
- case "dollar_volume": {
946
- const volume = reportedQuoteVolume(quote);
947
- return displayQuote && volume != null ? toBaseQuote(displayQuote.price * volume) : null;
948
- }
959
+ case "dollar_volume":
960
+ return tradedValue(quote, displayQuote, toBaseQuote);
949
961
  case "range_52w":
950
962
  return fiftyTwoWeekPosition(displayQuote, quote);
951
963
  case "market_cap": {
@@ -1,6 +1,7 @@
1
1
  import type { AppConfig } from "../types/config";
2
2
  import type { TickerMetadata, TickerPosition, TickerRecord } from "../types/ticker";
3
3
  import { listingSuffixVenue, tickerHasListingSuffix } from "../sources/listing-symbols";
4
+ import { moveWatchlistGroupSymbols } from "./watchlist-groups";
4
5
  import { canonicalExchange, parsePublicTickerKey, publicTickerKey } from "../utils/exchanges";
5
6
 
6
7
  /**
@@ -197,7 +198,8 @@ export async function mergeSavedSuffixedListings(
197
198
  ): Promise<{ tickers: TickerRecord[]; config: AppConfig; keptCustom: SuffixedListingMerge["keptCustom"] } | null> {
198
199
  const merge = mergeSuffixedListings(tickers);
199
200
  if (!merge) return null;
200
- const nextConfig = moveTargetWeights(config, merge.moved);
201
+ // Target weights and watchlist groups follow their rows to the listing's key.
202
+ const nextConfig = moveWatchlistGroupSymbols(moveTargetWeights(config, merge.moved), merge.moved);
201
203
  if (merge.saves.length === 0 && nextConfig === config) return null;
202
204
  if (nextConfig !== config) await save.config(nextConfig);
203
205
  if (merge.saves.length > 0) await save.tickers(merge.saves);
@@ -0,0 +1,212 @@
1
+ import type { AppConfig } from "../types/config";
2
+ import type { Watchlist, WatchlistGroup } from "../types/ticker";
3
+ import { parseCollectionRef } from "../team/collections";
4
+ import { isRecord } from "../utils/guards";
5
+
6
+ /** The longest name a group takes, so its header and the CLI's Group column stay readable. */
7
+ const MAX_GROUP_NAME_LENGTH = 40;
8
+
9
+ /** The section a list's tickers in no group show under; no group takes the name. */
10
+ export const UNGROUPED_LABEL = "Ungrouped";
11
+
12
+ const sameName = (left: string, right: string) => left.toLocaleLowerCase() === right.toLocaleLowerCase();
13
+
14
+ /**
15
+ * A list's groups as they are kept: names trimmed, two names that differ only
16
+ * in case one group under the first's name, each symbol in the first group
17
+ * that lists it, and a group left with no symbol dropped. Undefined when none
18
+ * remain, so a list without groups saves and syncs as it did before groups.
19
+ * Reads anything (a pulled or hand-edited config) and keeps what is well formed.
20
+ */
21
+ export function normalizeWatchlistGroups(value: unknown): WatchlistGroup[] | undefined {
22
+ if (!Array.isArray(value)) return undefined;
23
+ const groups: WatchlistGroup[] = [];
24
+ const placed = new Set<string>();
25
+ for (const entry of value) {
26
+ if (!isRecord(entry) || typeof entry.name !== "string" || !Array.isArray(entry.symbols)) continue;
27
+ const name = entry.name.trim();
28
+ if (!name) continue;
29
+ let group = groups.find((existing) => sameName(existing.name, name));
30
+ if (!group) {
31
+ group = { name, symbols: [] };
32
+ groups.push(group);
33
+ }
34
+ for (const symbol of entry.symbols) {
35
+ if (typeof symbol !== "string" || !symbol.trim() || placed.has(symbol)) continue;
36
+ placed.add(symbol);
37
+ group.symbols.push(symbol);
38
+ }
39
+ }
40
+ const kept = groups.filter((group) => group.symbols.length > 0);
41
+ return kept.length > 0 ? kept : undefined;
42
+ }
43
+
44
+ /** A list's groups, none for a list without; a config pulled from another device is read as it came, so this checks it. */
45
+ export function watchlistGroups(watchlist: Pick<Watchlist, "groups"> | null | undefined): WatchlistGroup[] {
46
+ return normalizeWatchlistGroups(watchlist?.groups) ?? [];
47
+ }
48
+
49
+ /** The name of the group a ticker of the list is in, by its key; null when it is in none. */
50
+ export function watchlistGroupOf(watchlist: Pick<Watchlist, "groups"> | null | undefined, symbol: string): string | null {
51
+ return watchlistGroups(watchlist).find((group) => group.symbols.includes(symbol))?.name ?? null;
52
+ }
53
+
54
+ /**
55
+ * Whether the list takes groups: a personal one. A team list is shared with
56
+ * everyone on the team and its items are the server's, so it has none.
57
+ */
58
+ export function watchlistTakesGroups(watchlist: Pick<Watchlist, "id" | "teamId">): boolean {
59
+ return !watchlist.teamId && parseCollectionRef(watchlist.id).scope !== "team";
60
+ }
61
+
62
+ /** A group name as typed, trimmed; throws saying why one cannot be used. */
63
+ export function parseWatchlistGroupName(input: string): string {
64
+ const name = input.trim().replace(/\s+/g, " ");
65
+ if (!name) throw new Error("A group needs a name.");
66
+ if (name.length > MAX_GROUP_NAME_LENGTH) throw new Error(`A group name is at most ${MAX_GROUP_NAME_LENGTH} characters.`);
67
+ if (sameName(name, UNGROUPED_LABEL)) throw new Error(`"${UNGROUPED_LABEL}" is where tickers in no group show; name the group something else.`);
68
+ return name;
69
+ }
70
+
71
+ function withGroups(config: AppConfig, watchlistId: string, groups: readonly WatchlistGroup[]): AppConfig {
72
+ const kept = normalizeWatchlistGroups(groups);
73
+ return {
74
+ ...config,
75
+ watchlists: config.watchlists.map((watchlist) => {
76
+ if (watchlist.id !== watchlistId) return watchlist;
77
+ const { groups: _groups, ...rest } = watchlist;
78
+ return kept ? { ...rest, groups: kept } : rest;
79
+ }),
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Puts `symbols` (tickers' keys) in the list's group `group` names, matched in
85
+ * any case, taking each out of any other group of the list; a new group goes
86
+ * last. `null` takes them out of their group. `moved` names the symbols whose
87
+ * group changed, and `group` is the name they are under now; the config comes
88
+ * back as it was when none moved.
89
+ */
90
+ export function setWatchlistGroup(
91
+ config: AppConfig,
92
+ watchlistId: string,
93
+ symbols: readonly string[],
94
+ group: string | null,
95
+ ): { config: AppConfig; group: string | null; moved: string[] } {
96
+ const watchlist = config.watchlists.find((entry) => entry.id === watchlistId);
97
+ if (!watchlist) throw new Error("Watchlist not found.");
98
+ const groups = watchlistGroups(watchlist);
99
+ const target = group == null ? null : groups.find((entry) => sameName(entry.name, group))?.name ?? parseWatchlistGroupName(group);
100
+ const moving = [...new Set(symbols)].filter((symbol) => watchlistGroupOf(watchlist, symbol) !== target);
101
+ if (moving.length === 0) return { config, group: target, moved: [] };
102
+ const next = groups.map((entry) => ({ name: entry.name, symbols: entry.symbols.filter((symbol) => !moving.includes(symbol)) }));
103
+ if (target != null) {
104
+ const existing = next.find((entry) => entry.name === target);
105
+ if (existing) existing.symbols.push(...moving);
106
+ else next.push({ name: target, symbols: [...moving] });
107
+ }
108
+ return { config: withGroups(config, watchlistId, next), group: target, moved: moving };
109
+ }
110
+
111
+ /** The list's groups without `symbols`, tickers that left the list: one added back later starts in no group. */
112
+ export function withoutWatchlistGroupSymbols(config: AppConfig, watchlistId: string, symbols: readonly string[]): AppConfig {
113
+ const watchlist = config.watchlists.find((entry) => entry.id === watchlistId);
114
+ const groups = watchlistGroups(watchlist);
115
+ if (!groups.some((group) => group.symbols.some((symbol) => symbols.includes(symbol)))) return config;
116
+ return withGroups(config, watchlistId, groups.map((group) => ({ ...group, symbols: group.symbols.filter((symbol) => !symbols.includes(symbol)) })));
117
+ }
118
+
119
+ /**
120
+ * The config without group symbols whose ticker is loaded and no longer on
121
+ * the list: taken off it some other way (the command bar, another device, an
122
+ * older build), so one added back later starts in no group. A symbol with no
123
+ * loaded row is kept: a pull may not have written it yet, or its row did not
124
+ * read, and a symbol with no row shows nowhere anyway.
125
+ */
126
+ export function withoutStaleWatchlistGroupSymbols(
127
+ config: AppConfig,
128
+ tickers: Iterable<{ metadata: { ticker: string; watchlists: readonly string[] } }>,
129
+ ): AppConfig {
130
+ if (!config.watchlists.some((watchlist) => watchlist.groups)) return config;
131
+ const listsOf = new Map<string, readonly string[]>();
132
+ for (const ticker of tickers) listsOf.set(ticker.metadata.ticker, ticker.metadata.watchlists);
133
+ let next = config;
134
+ for (const watchlist of config.watchlists) {
135
+ const stale = watchlistGroups(watchlist).flatMap((group) => group.symbols.filter((symbol) => {
136
+ const lists = listsOf.get(symbol);
137
+ return lists != null && !lists.includes(watchlist.id);
138
+ }));
139
+ if (stale.length > 0) next = withoutWatchlistGroupSymbols(next, watchlist.id, stale);
140
+ }
141
+ return next;
142
+ }
143
+
144
+ /**
145
+ * Names a group of the list, matched in any case, `to` instead. A name another
146
+ * group has merges the two, where the first of them was.
147
+ */
148
+ export function renameWatchlistGroup(config: AppConfig, watchlistId: string, from: string, to: string): AppConfig {
149
+ const watchlist = config.watchlists.find((entry) => entry.id === watchlistId);
150
+ const groups = watchlistGroups(watchlist);
151
+ const renamed = parseWatchlistGroupName(to);
152
+ if (!groups.some((group) => sameName(group.name, from))) throw new Error(`"${watchlist?.name ?? watchlistId}" has no group "${from}".`);
153
+ return withGroups(config, watchlistId, groups.map((group) => (sameName(group.name, from) ? { ...group, name: renamed } : group)));
154
+ }
155
+
156
+ /**
157
+ * Group symbols saved under an old key moved to their listing's key
158
+ * (`mergeSuffixedListings`: GARAN.IS into GARAN:BIST), as target weights are.
159
+ * A listing already in a group keeps that group.
160
+ */
161
+ export function moveWatchlistGroupSymbols(config: AppConfig, moved: ReadonlyMap<string, string>): AppConfig {
162
+ let changed = false;
163
+ const watchlists = config.watchlists.map((watchlist) => {
164
+ const groups = watchlistGroups(watchlist);
165
+ if (!groups.some((group) => group.symbols.some((symbol) => moved.has(symbol)))) return watchlist;
166
+ changed = true;
167
+ const grouped = new Set(groups.flatMap((group) => group.symbols));
168
+ const next = normalizeWatchlistGroups(groups.map((group) => ({
169
+ ...group,
170
+ symbols: group.symbols.flatMap((symbol) => {
171
+ const to = moved.get(symbol);
172
+ return to == null ? [symbol] : grouped.has(to) ? [] : [to];
173
+ }),
174
+ })));
175
+ const { groups: _groups, ...rest } = watchlist;
176
+ return next ? { ...rest, groups: next } : rest;
177
+ });
178
+ return changed ? { ...config, watchlists } : config;
179
+ }
180
+
181
+ export interface WatchlistSection<T> {
182
+ /** The group's name; null for the tickers in no group. */
183
+ name: string | null;
184
+ items: T[];
185
+ }
186
+
187
+ /**
188
+ * Items of a list under their sections, each section in the order the items
189
+ * come: every group that holds one, in the list's order, then the items in no
190
+ * group. Null when no item is in a group, so a list without groups shows as it
191
+ * always has.
192
+ */
193
+ export function sectionWatchlistItems<T>(
194
+ groups: readonly WatchlistGroup[],
195
+ items: readonly T[],
196
+ keyOf: (item: T) => string,
197
+ ): WatchlistSection<T>[] | null {
198
+ const groupOf = new Map<string, number>();
199
+ groups.forEach((group, index) => group.symbols.forEach((symbol) => groupOf.set(symbol, index)));
200
+ const grouped: T[][] = groups.map(() => []);
201
+ const ungrouped: T[] = [];
202
+ for (const item of items) {
203
+ const index = groupOf.get(keyOf(item));
204
+ if (index == null) ungrouped.push(item);
205
+ else grouped[index]!.push(item);
206
+ }
207
+ if (ungrouped.length === items.length) return null;
208
+ return [
209
+ ...groups.flatMap((group, index) => grouped[index]!.length > 0 ? [{ name: group.name, items: grouped[index]! }] : []),
210
+ ...ungrouped.length > 0 ? [{ name: null, items: ungrouped }] : [],
211
+ ];
212
+ }
@@ -6,7 +6,8 @@ import { usePluginAppActions, usePluginTickerActions } from "../plugins/runtime"
6
6
 
7
7
  /**
8
8
  * Shared Enter routing for panes that publish a cursor symbol: reuse the Ticker Research pane
9
- * already bound to this one instead of stacking another pane on top of it.
9
+ * already bound to this one, or a pinned one the layout has, instead of stacking another pane on
10
+ * top of it (`resolveTickerActivation`).
10
11
  */
11
12
  export function useTickerSourceActivate(): (
12
13
  symbol: string,
@@ -27,6 +28,7 @@ export function useTickerSourceActivate(): (
27
28
  floating: options?.floating ?? true,
28
29
  forceNewPane: options?.newPane,
29
30
  paneType: TICKER_RESEARCH_PANE_ID,
31
+ ...(activation.reusePaneId ? { reusePaneId: activation.reusePaneId } : {}),
30
32
  });
31
33
  }, [focusPane, paneId, pinTicker, stateRef]);
32
34
  }
@@ -319,6 +319,13 @@ button, [data-gloom-interactive="true"] { cursor: pointer; }
319
319
  [data-gloom-role="status-bar"] span {
320
320
  line-height: var(--cell-h);
321
321
  }
322
+ /* The returning-user strip under the header: one row of shell chrome, ruled off from the layout. */
323
+ [data-gloom-role="since-last-visit"] {
324
+ flex: none;
325
+ align-items: center;
326
+ border-bottom: 1px solid var(--gloom-hairline);
327
+ font-size: var(--gloom-type-ui);
328
+ }
322
329
  [data-gloom-role="pane-body"] {
323
330
  overflow: hidden;
324
331
  }
@@ -15,6 +15,7 @@ import { getDockedPaneIds } from "../../layout/pane-manager";
15
15
  import { debugLog } from "../../utils/debug-log";
16
16
  import { measurePerf, measurePerfAsync } from "../../utils/perf-marks";
17
17
  import { mergeSavedSuffixedListings } from "../../portfolio/suffixed-listings";
18
+ import { withoutStaleWatchlistGroupSymbols } from "../../portfolio/watchlist-groups";
18
19
  import { saveConfigImmediately } from "../config-save-scheduler";
19
20
 
20
21
  export const DEFAULT_WATCHLIST_TICKERS: Array<Pick<TickerMetadata, "ticker" | "exchange" | "currency" | "name">> = [
@@ -276,6 +277,16 @@ export async function initializeAppState({
276
277
  startupLog.warn("suffixed listing merge failed", { message: error instanceof Error ? error.message : String(error) });
277
278
  }
278
279
 
280
+ // A ticker that left a list some other way than its own remove leaves the list's groups too.
281
+ const ungrouped = withoutStaleWatchlistGroupSymbols(config, tickers);
282
+ if (ungrouped !== config) {
283
+ config = ungrouped;
284
+ dispatch({ type: "SET_CONFIG", config });
285
+ await saveConfigImmediately(config).catch((error: unknown) => {
286
+ startupLog.warn("stale watchlist group symbols not saved", { message: error instanceof Error ? error.message : String(error) });
287
+ });
288
+ }
289
+
279
290
  // Seed default watchlist tickers on first run
280
291
  if (tickers.length === 0) {
281
292
  const defaultWatchlistId = config.watchlists[0]?.id ?? "watchlist";
@@ -14,6 +14,7 @@ import {
14
14
  } from "react";
15
15
  import type { AppSessionStorePort } from "../../../core/app-service-ports";
16
16
  import { ThemeProvider } from "../../../theme/theme-context";
17
+ import { setCsvDecimal } from "../../../utils/csv";
17
18
  import { syncFontScale } from "../../../theme/font-scale";
18
19
  import {
19
20
  findPaneInstance,
@@ -698,6 +699,11 @@ export function AppProvider({
698
699
  }
699
700
  }, [state.config.fontSize]);
700
701
 
702
+ // Every CSV the app exports (a table's Export CSV, the quote board's) writes the decimal mark the reader set.
703
+ useLayoutEffect(() => {
704
+ setCsvDecimal(state.config.csvDecimal);
705
+ }, [state.config.csvDecimal]);
706
+
701
707
  useLayoutEffect(() => {
702
708
  stateRef.current = state;
703
709
  for (const listener of listenersRef.current) {
@@ -8,6 +8,7 @@ import type { SyncContributor } from "./types";
8
8
  import { isRecord, recordOrNull } from "../utils/guards";
9
9
  import { withoutMissingWatchlists } from "../portfolio/mutations";
10
10
  import { mergeSuffixedListings, moveTargetWeights } from "../portfolio/suffixed-listings";
11
+ import { moveWatchlistGroupSymbols } from "../portfolio/watchlist-groups";
11
12
  import { knownBrokerHoldings } from "../brokers/broker-portfolio-sync";
12
13
  import {
13
14
  localOnlyScope,
@@ -23,7 +24,7 @@ import {
23
24
  } from "./analytics-payload";
24
25
  import { idEntries } from "./broker-instances";
25
26
  import { CORE_CONFIG_CONTRIBUTOR_ID, log } from "./config-contributor";
26
- import { sanitizePortfolio, sanitizeWatchlist } from "./sanitize";
27
+ import { sanitizePortfolio, sanitizeWatchlist, WATCHLISTS_CARRY_GROUPS } from "./sanitize";
27
28
  import {
28
29
  lastSyncedTickersById,
29
30
  latestBrokerPortfolioSyncs,
@@ -55,6 +56,8 @@ export function collectCoreCollectionsPayload(
55
56
  exchangeRates: { USD: 1 },
56
57
  portfolios: config.portfolios.map(sanitizePortfolio),
57
58
  watchlists: config.watchlists.map(sanitizeWatchlist),
59
+ // The lists carry their groups, as the config payload's do: a reader can tell a list without them from an older build's.
60
+ [WATCHLISTS_CARRY_GROUPS]: true,
58
61
  analyticsByPortfolio: collectAnalyticsByPortfolio(config, tickers, financials, exchangeRates, brokerAccounts),
59
62
  accountsByPortfolio: collectAccountsByPortfolio(config, brokerAccounts),
60
63
  tickers: records,
@@ -168,6 +171,6 @@ function mergePulledSuffixedListings(
168
171
  else changed.push(row);
169
172
  }
170
173
  for (const kept of merged.keptCustom) log.info("sync.suffixed-listing.custom-kept", kept);
171
- const next = moveTargetWeights(config, merged.moved);
174
+ const next = moveWatchlistGroupSymbols(moveTargetWeights(config, merged.moved), merged.moved);
172
175
  return { config: next === config ? null : next };
173
176
  }
@@ -1,7 +1,7 @@
1
1
  import { normalizeStoredBaseCurrency } from "../utils/base-currency";
2
2
  import { stableStringify } from "../utils/hash";
3
3
  import type { AppConfig, BrokerInstanceConfig } from "../types/config";
4
- import type { Portfolio } from "../types/ticker";
4
+ import type { Portfolio, Watchlist } from "../types/ticker";
5
5
  import {
6
6
  addLegacyBuiltinDisabledPluginAliases,
7
7
  addLegacyBuiltinPluginOwnerAliases,
@@ -33,7 +33,9 @@ import {
33
33
  sanitizePortfolio,
34
34
  sanitizeUnknown,
35
35
  sanitizeWatchlist,
36
+ WATCHLISTS_CARRY_GROUPS,
36
37
  withLocalPluginSecrets,
38
+ withLocalWatchlistGroups,
37
39
  } from "./sanitize";
38
40
 
39
41
  export function collectCoreConfigPayload(config: AppConfig) {
@@ -43,6 +45,7 @@ export function collectCoreConfigPayload(config: AppConfig) {
43
45
  refreshIntervalMinutes: config.refreshIntervalMinutes,
44
46
  portfolios: config.portfolios.map(sanitizePortfolio),
45
47
  watchlists: config.watchlists.map(sanitizeWatchlist),
48
+ [WATCHLISTS_CARRY_GROUPS]: true,
46
49
  ...collectLayoutPayload(config),
47
50
  brokerInstances: config.brokerInstances.map(sanitizeBrokerInstance),
48
51
  // This build merges profiles one by one before it pushes, so a profile
@@ -169,7 +172,12 @@ export function mergeConfigPayload(
169
172
  ? mergeLocalBrokerPortfolioIdentity(config.portfolios, syncedPortfolios as Portfolio[], next.brokerInstances)
170
173
  : syncedPortfolios as AppConfig["portfolios"];
171
174
  }
172
- assign("watchlists");
175
+ // An older build pushes its lists without their groups: they keep the groups they have here.
176
+ if ("watchlists" in payload && canApply("watchlists")) {
177
+ next.watchlists = Array.isArray(payload.watchlists)
178
+ ? withLocalWatchlistGroups(payload.watchlists, config.watchlists, payload[WATCHLISTS_CARRY_GROUPS] === true)
179
+ : payload.watchlists as Watchlist[];
180
+ }
173
181
  assign("disabledSources");
174
182
  assign("theme");
175
183
  assign("chartPreferences");