gloomberb 0.20.13 → 0.20.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/package.json +2 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +22 -4
  3. package/src/account/auth-dialog.tsx +22 -4
  4. package/src/account/auth-form.tsx +6 -1
  5. package/src/account/checkout-handoff.tsx +7 -14
  6. package/src/account/device-signin-dialog.tsx +35 -24
  7. package/src/api-client/crypto-markets.ts +10 -0
  8. package/src/api-client/errors.ts +3 -1
  9. package/src/api-client/index.ts +54 -0
  10. package/src/api-client/install-experiments.ts +8 -7
  11. package/src/api-client/money-markets.ts +7 -0
  12. package/src/api-client/paths.ts +2 -1
  13. package/src/api-client/product-waitlist.ts +63 -0
  14. package/src/api-client/request.ts +16 -4
  15. package/src/api-client/types/billing.ts +45 -0
  16. package/src/api-client/yearly-plan.ts +132 -0
  17. package/src/app/global-shortcuts.ts +5 -3
  18. package/src/app/pane-runtime/index.tsx +2 -2
  19. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  20. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  21. package/src/app/since-last-visit/keys.ts +26 -0
  22. package/src/app/since-last-visit/model.ts +266 -0
  23. package/src/app/since-last-visit/strip.tsx +193 -0
  24. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  25. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  26. package/src/app.tsx +15 -0
  27. package/src/architecture/floating-promise-allowlist.json +0 -1
  28. package/src/brokers/signed-in/sign-in-dialog.tsx +38 -38
  29. package/src/cli/commands/market.ts +103 -27
  30. package/src/cli/commands/overview.ts +18 -4
  31. package/src/cli/commands/system.ts +29 -1
  32. package/src/cli/commands/ticker.ts +12 -5
  33. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  34. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  35. package/src/cli/desktop-pane-shot-view.ts +3 -7
  36. package/src/cli/desktop-pane-shot.ts +26 -28
  37. package/src/cli/errors.ts +3 -1
  38. package/src/cli/freshness.ts +7 -2
  39. package/src/cli/glossary.ts +10 -5
  40. package/src/cli/help.ts +1 -0
  41. package/src/cli/helpers.ts +8 -16
  42. package/src/cli/history-export.ts +4 -0
  43. package/src/cli/history-rows.ts +24 -0
  44. package/src/cli/index.ts +4 -0
  45. package/src/cli/known-gaps.ts +2 -2
  46. package/src/cli/listing-arg.ts +79 -11
  47. package/src/cli/not-a-ticker.ts +4 -0
  48. package/src/cli/options.ts +29 -1
  49. package/src/cli/pane-functions/catalog.ts +70 -12
  50. package/src/cli/pane-functions/function-help.ts +1 -1
  51. package/src/cli/pane-functions/headless.ts +68 -3
  52. package/src/cli/pane-functions/index.ts +2 -2
  53. package/src/cli/pane-functions/options.ts +7 -0
  54. package/src/cli/pane-functions/resolver.ts +104 -15
  55. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  56. package/src/cli/report-tables.ts +20 -5
  57. package/src/cli/result.ts +22 -4
  58. package/src/cli/shot-temp-dir.ts +30 -0
  59. package/src/cli/suffixed-listing-rows.ts +11 -0
  60. package/src/cli/symbol-args.ts +5 -3
  61. package/src/cli/symbol-list.ts +23 -10
  62. package/src/cli/symbol-rows.ts +135 -3
  63. package/src/cli/treasury-yields.ts +15 -1
  64. package/src/components/chart/composite/composite-chart.tsx +3 -3
  65. package/src/components/chart/composite/format.ts +2 -1
  66. package/src/components/chart/composite/panel-surface/axis-markers.ts +133 -0
  67. package/src/components/chart/composite/panel-surface/level-labels.tsx +78 -0
  68. package/src/components/chart/composite/panel-surface/overlays.ts +108 -0
  69. package/src/components/chart/composite/panel-surface/pan-coast.ts +54 -0
  70. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +138 -0
  71. package/src/components/chart/composite/panel-surface/panel-levels.ts +47 -0
  72. package/src/components/chart/composite/panel-surface/plot-gestures.ts +403 -0
  73. package/src/components/chart/composite/panel-surface/plot-pointer.ts +65 -0
  74. package/src/components/chart/composite/panel-surface/plot-wheel.ts +102 -0
  75. package/src/components/chart/composite/panel-surface/pointer.ts +12 -0
  76. package/src/components/chart/composite/panel-surface/props.ts +79 -0
  77. package/src/components/chart/composite/panel-surface/tool-readout.ts +151 -0
  78. package/src/components/chart/composite/panel-surface/value-axis-gestures.ts +152 -0
  79. package/src/components/chart/composite/panel-surface.tsx +81 -1177
  80. package/src/components/command-bar/commands/collection-list.ts +1 -0
  81. package/src/components/command-bar/commands/direct/index.ts +31 -8
  82. package/src/components/command-bar/commands/registry.ts +7 -0
  83. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  84. package/src/components/command-bar/routes/root/results.ts +19 -2
  85. package/src/components/command-bar/routes/root/runtime.ts +3 -2
  86. package/src/components/command-bar/routes/root/selection.ts +3 -2
  87. package/src/components/command-bar/routes/root/shortcuts.ts +15 -0
  88. package/src/components/company-logo.tsx +10 -3
  89. package/src/components/data-table/sections.ts +6 -1
  90. package/src/components/layout/pane/title.ts +16 -6
  91. package/src/components/layout/shell/index.tsx +5 -1
  92. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  93. package/src/components/pane-settings-dialog/tui.tsx +6 -3
  94. package/src/components/pane-settings-dialog.tsx +2 -1
  95. package/src/components/pane-template-wizard.tsx +2 -0
  96. package/src/components/ticker/badge/format.ts +12 -3
  97. package/src/components/ticker/badge/index.tsx +9 -3
  98. package/src/components/ticker/list-table-view.tsx +119 -17
  99. package/src/components/ui/choice-dialog.tsx +1 -1
  100. package/src/components/ui/confirm-dialog.tsx +3 -2
  101. package/src/components/ui/data-table/display-columns.ts +16 -0
  102. package/src/components/ui/data-table/index.tsx +40 -9
  103. package/src/components/ui/data-table/types.ts +14 -0
  104. package/src/components/ui/frame.tsx +7 -3
  105. package/src/components/ui/icon.tsx +4 -2
  106. package/src/components/ui/list-view.tsx +8 -0
  107. package/src/components/ui/number-prompt-dialog.tsx +2 -1
  108. package/src/components/use-pane-notice-footer.tsx +3 -1
  109. package/src/core/state/app/layout-reducer.ts +3 -1
  110. package/src/core/state/app/layout.ts +2 -2
  111. package/src/data/config/layout.ts +14 -0
  112. package/src/data/config/store/normalize.ts +11 -1
  113. package/src/docs/snapshot.json +2 -2
  114. package/src/i18n/es.ts +39 -0
  115. package/src/i18n/ja.ts +39 -0
  116. package/src/i18n/ko.ts +39 -0
  117. package/src/i18n/zh-cn.ts +39 -0
  118. package/src/i18n/zh-tw.ts +39 -0
  119. package/src/layout/pane-follow.ts +141 -4
  120. package/src/layout/pane-layout-move.ts +10 -7
  121. package/src/layout/ticker-navigation.ts +13 -19
  122. package/src/layout/ticker-retarget.ts +3 -2
  123. package/src/market-data/market/format.ts +35 -1
  124. package/src/market-data/market/index-level.ts +19 -0
  125. package/src/market-data/quotes/contributions.ts +13 -0
  126. package/src/market-data/quotes/export-identity.ts +36 -1
  127. package/src/market-data/quotes/resolution.ts +16 -0
  128. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  129. package/src/plugins/builtin/account-management/model.ts +2 -0
  130. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  131. package/src/plugins/builtin/account-management/password-dialog.tsx +2 -2
  132. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  133. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  134. package/src/plugins/builtin/analytics/risk-client.ts +12 -2
  135. package/src/plugins/builtin/analytics/risk-headless.ts +66 -6
  136. package/src/plugins/builtin/analytics/risk-math.ts +23 -6
  137. package/src/plugins/builtin/analytics/risk-model.ts +20 -9
  138. package/src/plugins/builtin/analytics/risk-pane.tsx +2 -2
  139. package/src/plugins/builtin/awards/pane.tsx +6 -8
  140. package/src/plugins/builtin/changelog/index.tsx +6 -44
  141. package/src/plugins/builtin/changelog/versions.ts +17 -68
  142. package/src/plugins/builtin/chart-composer/catalog-inventory.ts +5 -2
  143. package/src/plugins/builtin/chart-composer/editor.tsx +1 -0
  144. package/src/plugins/builtin/chart-composer/pane.tsx +1 -1
  145. package/src/plugins/builtin/chart-composer/quick-add.tsx +4 -1
  146. package/src/plugins/builtin/chart-composer/series-catalog.ts +17 -1
  147. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  148. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  149. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  150. package/src/plugins/builtin/cloud/thesis/module.tsx +2 -0
  151. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +6 -2
  152. package/src/plugins/builtin/cpi/headless.ts +6 -1
  153. package/src/plugins/builtin/cpi/model.ts +17 -0
  154. package/src/plugins/builtin/cpi/pane.tsx +4 -2
  155. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  156. package/src/plugins/builtin/crypto-board/headless.ts +10 -2
  157. package/src/plugins/builtin/crypto-board/model.ts +89 -11
  158. package/src/plugins/builtin/crypto-board/pane.tsx +20 -5
  159. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  160. package/src/plugins/builtin/dividend-yield/client.ts +24 -2
  161. package/src/plugins/builtin/dividend-yield/headless.ts +4 -2
  162. package/src/plugins/builtin/dividend-yield/ranking.ts +2 -1
  163. package/src/plugins/builtin/dividend-yield/view.ts +5 -1
  164. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  165. package/src/plugins/builtin/earnings/board.tsx +36 -16
  166. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  167. package/src/plugins/builtin/earnings/history-table.ts +9 -1
  168. package/src/plugins/builtin/earnings/index.tsx +1 -1
  169. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  170. package/src/plugins/builtin/earnings-ripple/index.tsx +2 -0
  171. package/src/plugins/builtin/econ/calendar-model.ts +17 -1
  172. package/src/plugins/builtin/econ/fred-catalog.ts +33 -4
  173. package/src/plugins/builtin/econ-statistics/headless.ts +21 -0
  174. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  175. package/src/plugins/builtin/exposure/index.tsx +1 -1
  176. package/src/plugins/builtin/macro-day/headless.ts +21 -10
  177. package/src/plugins/builtin/macro-day/model.ts +42 -3
  178. package/src/plugins/builtin/macro-day/pane.tsx +26 -8
  179. package/src/plugins/builtin/macro-day/releases.ts +24 -1
  180. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  181. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  182. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  183. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  184. package/src/plugins/builtin/money-markets/client.ts +4 -1
  185. package/src/plugins/builtin/money-markets/headless.ts +15 -4
  186. package/src/plugins/builtin/money-markets/index.tsx +1 -1
  187. package/src/plugins/builtin/money-markets/pane.tsx +7 -1
  188. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  189. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  190. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -2
  191. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +61 -11
  192. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +11 -3
  193. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  194. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +178 -17
  195. package/src/plugins/builtin/portfolio-list/headless.ts +33 -6
  196. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  197. package/src/plugins/builtin/portfolio-list/pane/index.tsx +95 -18
  198. package/src/plugins/builtin/portfolio-list/pane/period-pnl.ts +24 -6
  199. package/src/plugins/builtin/portfolio-list/period-pnl.ts +16 -1
  200. package/src/plugins/builtin/portfolio-list/summary/index.tsx +4 -1
  201. package/src/plugins/builtin/portfolio-list/summary/totals.ts +6 -4
  202. package/src/plugins/builtin/portfolio-list/table.tsx +38 -16
  203. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  204. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  205. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  206. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  207. package/src/plugins/builtin/shared/cloud-upgrade.ts +4 -2
  208. package/src/plugins/builtin/shared/cpi-year-gap.ts +67 -0
  209. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  210. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  211. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  212. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +45 -2
  213. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  214. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  215. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  216. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  217. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  218. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  219. package/src/plugins/builtin/ticker-detail/headless.ts +280 -35
  220. package/src/plugins/builtin/ticker-detail/overview/components.tsx +4 -5
  221. package/src/plugins/builtin/ticker-detail/overview/model.ts +9 -2
  222. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +10 -2
  223. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  224. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  225. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  226. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  227. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  228. package/src/portfolio/collection-name.ts +2 -1
  229. package/src/portfolio/column-values.ts +34 -12
  230. package/src/portfolio/listed-symbol.ts +4 -2
  231. package/src/portfolio/period-pnl.ts +51 -1
  232. package/src/portfolio/suffixed-listings.ts +3 -1
  233. package/src/portfolio/watchlist-groups.ts +212 -0
  234. package/src/react/ticker-source.ts +3 -1
  235. package/src/renderers/dom/dialog-host.tsx +5 -5
  236. package/src/renderers/dom/styles.css +7 -0
  237. package/src/renderers/electrobun/view/remote/capability-invoker.ts +1 -1
  238. package/src/renderers/opentui/dialog-host.tsx +3 -4
  239. package/src/sources/gloomberb-cloud/normalizers.ts +5 -0
  240. package/src/sources/provider-router/history.ts +5 -2
  241. package/src/state/app/bootstrap.ts +11 -0
  242. package/src/state/app/context/index.tsx +6 -0
  243. package/src/sync/collections-contributor.ts +5 -2
  244. package/src/sync/config-merge.ts +10 -2
  245. package/src/sync/sanitize.ts +28 -0
  246. package/src/telemetry/usage-counts.ts +17 -0
  247. package/src/test-support/plugin-persistence.ts +12 -0
  248. package/src/tickers/company-name-listing.ts +4 -3
  249. package/src/tickers/company-name.ts +19 -1
  250. package/src/tickers/instrument-coverage.ts +27 -0
  251. package/src/tickers/search/home-listing.ts +38 -1
  252. package/src/tickers/search/index.ts +3 -2
  253. package/src/tickers/search/ranking.ts +21 -2
  254. package/src/time-series/base-series.ts +4 -0
  255. package/src/time-series/chart-seed.ts +1 -1
  256. package/src/time-series/financial-period-coverage.ts +4 -12
  257. package/src/time-series/parsed-history-cache.ts +1 -1
  258. package/src/time-series/resolve.ts +1 -1
  259. package/src/time-series/types.ts +5 -2
  260. package/src/time-series/use-chart-resolution.ts +6 -1
  261. package/src/types/config.ts +32 -0
  262. package/src/types/financials.ts +13 -0
  263. package/src/types/headless.ts +7 -0
  264. package/src/types/plugin-context.ts +5 -0
  265. package/src/types/ticker.ts +14 -0
  266. package/src/ui/ascii-font.ts +1 -4
  267. package/src/ui/dialog-stack.ts +17 -0
  268. package/src/ui/dialog.tsx +6 -2
  269. package/src/utils/async-deadline.ts +2 -2
  270. package/src/utils/crypto-pair.ts +9 -0
  271. package/src/utils/csv.ts +44 -5
  272. package/src/utils/exchanges.ts +13 -0
  273. package/src/utils/financial-statements.ts +60 -3
  274. package/src/utils/futures-generic.ts +17 -0
  275. package/src/utils/trailing-dividend.ts +13 -3
@@ -4,7 +4,7 @@ import { withCollectionConfigData, withCollectionMarketData } from "../../../../
4
4
  import { countCollectionTickers, findWatchlist } from "../../../../cli/helpers";
5
5
  import { slugifyName } from "../../../../utils/slugify";
6
6
  import { takeOption } from "../../../../cli/commands/command-utils";
7
- import { EXCHANGE_OPTION, requireSavedListing, savedListingName } from "../../../../cli/listing-arg";
7
+ import { EXCHANGE_OPTION, loadSavedListingOf, requireSavedListing, savedListingCandidates, savedListingName } from "../../../../cli/listing-arg";
8
8
  import {
9
9
  cliStyles,
10
10
  renderSection,
@@ -13,31 +13,53 @@ import {
13
13
  } from "../../../../utils/cli-output";
14
14
  import type { AppConfig } from "../../../../types/config";
15
15
  import type { CliCommandContext, CliCommandDef } from "../../../../types/plugin";
16
- import type { Watchlist } from "../../../../types/ticker";
16
+ import type { TickerRecord, Watchlist } from "../../../../types/ticker";
17
17
  import type { ConfigContext, MarketContext } from "../../../../cli/types";
18
18
  import {
19
19
  addTickerToWatchlist,
20
20
  deleteWatchlist as deleteWatchlistConfig,
21
21
  removeTickerFromWatchlist as removeWatchlistMembership,
22
22
  } from "../../../../portfolio/mutations";
23
+ import {
24
+ parseWatchlistGroupName,
25
+ setWatchlistGroup,
26
+ watchlistGroups,
27
+ watchlistTakesGroups,
28
+ withoutWatchlistGroupSymbols,
29
+ } from "../../../../portfolio/watchlist-groups";
23
30
  import { collectionAddCommand, showCollection } from "./render";
24
31
  import { listingFields, misplacedSymbolList, refuseDryRun, takeCollectionName } from "./shared";
25
32
  import { addOneSymbol, addSymbols, FILE_OPTION, listAddLookups, printSymbolRows, progressNotice, removeSymbols, requireSymbolList, retryNotice, shellWord, SYMBOL_LIST_HELP } from "./bulk-symbols";
26
33
  import { readNameEntries } from "../../../../cli/name-entries";
27
34
  import { CLI_COMMAND_GROUPS } from "../../../../cli/help";
28
35
 
29
- const ADD_USAGE = "Usage: gloom watchlist add <watchlist> <symbols...> [--file <path>]";
36
+ const ADD_USAGE = "Usage: gloom watchlist add <watchlist> <symbols...> [--file <path>] [--group <name>]";
30
37
  const REMOVE_USAGE = "Usage: gloom watchlist remove <watchlist> <symbols...> [--file <path>]";
38
+ const MOVE_USAGE = "Usage: gloom watchlist move <watchlist> <symbols...> --group <name>";
39
+ const UNGROUP_USAGE = "Usage: gloom watchlist ungroup <watchlist> <symbols...> | --group <name>";
40
+
41
+ const GROUPS_HELP = {
42
+ title: "Groups",
43
+ lines: [
44
+ "A watchlist's tickers can sit in named groups (Energy, Tech, Index funds), which PF shows under headers that collapse, and watchlist show in a Group column; the rest show under Ungrouped. A ticker is in one group of a list at most, and a ticker on two lists can be in a different group on each.",
45
+ "add --group puts the symbols added, and those already in the list, in the group, made when new. move --group puts symbols of the list in it. ungroup takes symbols out of their group, and ungroup --group takes every symbol out of that group. A group with no symbols left goes. Names are matched in any case.",
46
+ ],
47
+ };
48
+
49
+ const GROUP_OPTION = {
50
+ flags: "--group <name>",
51
+ description: "add, move: put the symbols in this group of the watchlist, made when new; ungroup: take every symbol out of it",
52
+ };
31
53
 
32
54
  /** Actions that change a watchlist without a preview, so --dry-run would change it anyway. add previews. */
33
- const MUTATING_ACTIONS = new Set(["create", "delete", "rm", "remove"]);
55
+ const MUTATING_ACTIONS = new Set(["create", "delete", "rm", "remove", "move", "ungroup"]);
34
56
 
35
57
  /** The watchlist the leading arguments name and the symbols after it; fails naming the watchlists there are. */
36
58
  function requireWatchlistArgs(
37
59
  config: AppConfig,
38
60
  args: readonly string[],
39
61
  file: string | undefined,
40
- verb: "add" | "remove",
62
+ verb: "add" | "remove" | "move" | "ungroup",
41
63
  usage: string,
42
64
  ctx: CliCommandContext,
43
65
  ): { watchlist: Watchlist; rest: string[] } {
@@ -45,7 +67,9 @@ function requireWatchlistArgs(
45
67
  const match = takeCollectionName(args, config.watchlists);
46
68
  if (!match) {
47
69
  // A pasted list in the place of the name is a list, not a watchlist that is missing.
48
- const pasted = misplacedSymbolList(args, file, { noun: "watchlist", verb, collections: config.watchlists, usage });
70
+ const pasted = verb === "add" || verb === "remove"
71
+ ? misplacedSymbolList(args, file, { noun: "watchlist", verb, collections: config.watchlists, usage })
72
+ : null;
49
73
  if (pasted) ctx.fail(pasted.message, pasted.details);
50
74
  // The watchlist goes first: `watchlist add USDJPY=X USDCHF=X` read USDJPY=X as its name, so the form is said too.
51
75
  ctx.fail(
@@ -93,9 +117,34 @@ async function deleteWatchlist(name: string, ctx: CliCommandContext) {
93
117
  });
94
118
  }
95
119
 
120
+ /** The group `--group` names, checked before anything is looked up; a team list takes none. */
121
+ function requireGroupName(watchlist: Watchlist, group: string | undefined, usage: string, ctx: CliCommandContext): string | null {
122
+ if (group == null) return null;
123
+ if (!watchlistTakesGroups(watchlist)) ctx.fail(`"${watchlist.name}" is a team watchlist; only your own watchlists have groups.`);
124
+ if (!group.trim()) ctx.fail("--group needs a group name.", usage);
125
+ try {
126
+ return parseWatchlistGroupName(group);
127
+ } catch (error) {
128
+ return ctx.fail(error instanceof Error ? error.message : String(error), usage);
129
+ }
130
+ }
131
+
132
+ /** Puts the rows an add stored or found in the list into its group, and says so on standard error beside the add's own lines. */
133
+ async function groupAdded(ctx: CliCommandContext, config: AppConfig, watchlist: Watchlist, keys: readonly string[], group: string | null) {
134
+ if (group == null || keys.length === 0 || ctx.cliOptions.dryRun) return;
135
+ const result = setWatchlistGroup(config, watchlist.id, keys, group);
136
+ if (result.moved.length === 0) return;
137
+ await saveConfig(result.config);
138
+ if (!ctx.cliOptions.quiet) {
139
+ console.error(cliStyles.muted(`Put ${result.moved.length === 1 ? result.moved[0] : `${result.moved.length} tickers`} in group "${result.group}".`));
140
+ }
141
+ }
142
+
96
143
  async function addTickerToWatchlistCommand(
97
144
  watchlist: Watchlist, symbol: string, notes: readonly string[], exchange: string | undefined, ctx: CliCommandContext, market: MarketContext,
145
+ group: string | null,
98
146
  ) {
147
+ const added: string[] = [];
99
148
  // A bare symbol is stored on the listing `quote` reads it as, and the notes say which; a match a list would leave for a choice fails.
100
149
  await addOneSymbol(ctx, market, {
101
150
  symbol,
@@ -103,22 +152,31 @@ async function addTickerToWatchlistCommand(
103
152
  collection: { kind: "watchlist", name: watchlist.name },
104
153
  notes,
105
154
  retry: (key) => `gloom watchlist add ${shellWord(watchlist.name)} ${key}`,
106
- add: (ticker) => addTickerToWatchlist(ticker, watchlist.id),
155
+ add: (ticker) => {
156
+ const result = addTickerToWatchlist(ticker, watchlist.id);
157
+ added.push(result.ticker.metadata.ticker);
158
+ return result;
159
+ },
160
+ member: (ticker) => ticker.metadata.watchlists.includes(watchlist.id),
107
161
  });
162
+ await groupAdded(ctx, market.config, watchlist, added, group);
108
163
  }
109
164
 
110
- async function addToWatchlistCommand(args: string[], file: string | undefined, exchange: string | undefined, ctx: CliCommandContext) {
165
+ async function addToWatchlistCommand(args: string[], file: string | undefined, exchange: string | undefined, rawGroup: string | undefined, ctx: CliCommandContext) {
111
166
  await withCollectionMarketData(ctx, async (market) => {
112
167
  const { watchlist, rest } = requireWatchlistArgs(market.config, args, file, "add", ADD_USAGE, ctx);
168
+ const group = requireGroupName(watchlist, rawGroup, ADD_USAGE, ctx);
113
169
  // Reading the names and looking the symbols up share their answers, so nothing is asked twice.
114
170
  const lookups = await listAddLookups(market.dataProvider);
115
171
  const list = await requireSymbolList(ctx, rest, file, ADD_USAGE, (entries) => readNameEntries(entries, lookups));
116
172
  if (list.single) {
117
- await addTickerToWatchlistCommand(watchlist, list.single, list.notes, exchange, ctx, market);
173
+ await addTickerToWatchlistCommand(watchlist, list.single, list.notes, exchange, ctx, market, group);
118
174
  return;
119
175
  }
120
176
  const retry = (key: string) => `gloom watchlist add ${shellWord(watchlist.name)} ${key}`;
121
177
  const dryRun = ctx.cliOptions.dryRun;
178
+ // The rows added, or found already in the list, which `--group` puts in its group.
179
+ const added: string[] = [];
122
180
  const rows = await addSymbols({
123
181
  symbols: list.symbols,
124
182
  exchange,
@@ -129,14 +187,94 @@ async function addToWatchlistCommand(args: string[], file: string | undefined, e
129
187
  retry,
130
188
  suggest: true,
131
189
  dryRun,
132
- add: (ticker) => addTickerToWatchlist(ticker, watchlist.id),
190
+ add: (ticker) => {
191
+ const result = addTickerToWatchlist(ticker, watchlist.id);
192
+ added.push(result.ticker.metadata.ticker);
193
+ return result;
194
+ },
195
+ member: (ticker) => ticker.metadata.watchlists.includes(watchlist.id),
133
196
  });
134
197
  printSymbolRows(ctx, rows, { verb: "add", collection: { kind: "watchlist", name: watchlist.name }, repeated: list.repeated, notes: list.notes, retry, dryRun });
198
+ await groupAdded(ctx, market.config, watchlist, added, group);
199
+ });
200
+ }
201
+
202
+ /**
203
+ * The saved rows of the list the symbols name, by key, as `remove` reads a
204
+ * symbol (SAN:EPA, `--exchange`, GARAN.IS); fails naming every symbol that is
205
+ * not in the list, before anything changes.
206
+ */
207
+ async function requireListedKeys(
208
+ symbols: readonly string[], exchange: string | undefined, store: ConfigContext["store"], watchlist: Watchlist, usage: string, ctx: CliCommandContext,
209
+ ): Promise<string[]> {
210
+ const held = (ticker: TickerRecord) => ticker.metadata.watchlists.includes(watchlist.id);
211
+ const keys: string[] = [];
212
+ const missing: string[] = [];
213
+ for (const input of symbols) {
214
+ let listings;
215
+ try {
216
+ listings = savedListingCandidates(input, exchange, { ownExchangeWins: true });
217
+ } catch (error) {
218
+ return ctx.fail(error instanceof Error ? error.message : String(error), usage);
219
+ }
220
+ const saved = listings[0]!.symbol ? await loadSavedListingOf(store, listings, held) : null;
221
+ if (saved && held(saved.ticker)) keys.push(saved.ticker.metadata.ticker);
222
+ else missing.push(listings[0]!.key || input.trim());
223
+ }
224
+ if (missing.length > 0) ctx.fail(`Not in "${watchlist.name}": ${missing.join(", ")}.`, usage);
225
+ return keys;
226
+ }
227
+
228
+ /**
229
+ * `watchlist move <list> <symbols...> --group <name>` puts the symbols in the
230
+ * group; `watchlist ungroup <list> <symbols...>` takes them out of theirs, and
231
+ * `watchlist ungroup <list> --group <name>` every symbol out of that group.
232
+ */
233
+ async function groupWatchlistSymbols(
234
+ action: "move" | "ungroup", args: string[], exchange: string | undefined, rawGroup: string | undefined, ctx: CliCommandContext,
235
+ ) {
236
+ const usage = action === "move" ? MOVE_USAGE : UNGROUP_USAGE;
237
+ await withCollectionConfigData(ctx, async ({ config, store }) => {
238
+ const { watchlist, rest } = requireWatchlistArgs(config, args, undefined, action, usage, ctx);
239
+ if (action === "move" && rawGroup == null) ctx.fail("watchlist move needs --group <name>: the group to put the symbols in.", usage);
240
+ const group = requireGroupName(watchlist, rawGroup, usage, ctx);
241
+ let keys: string[];
242
+ if (rest.length === 0) {
243
+ // `ungroup --group Energy` empties the group, which then goes.
244
+ const named = action === "ungroup" && group != null
245
+ ? watchlistGroups(watchlist).find((entry) => entry.name.toLocaleLowerCase() === group.toLocaleLowerCase())
246
+ : null;
247
+ if (action === "ungroup" && group != null && !named) ctx.fail(`"${watchlist.name}" has no group "${group}".`, usage);
248
+ if (!named) ctx.fail(usage);
249
+ keys = [...named.symbols];
250
+ } else {
251
+ const list = await requireSymbolList(ctx, rest, undefined, usage);
252
+ keys = await requireListedKeys(list.symbols, exchange, store, watchlist, usage, ctx);
253
+ }
254
+ const result = setWatchlistGroup(config, watchlist.id, keys, action === "move" ? group : null);
255
+ if (result.moved.length > 0) await saveConfig(result.config);
256
+ const data = { watchlist: watchlist.name, group: result.group, symbols: keys, moved: result.moved };
257
+ const named = (symbols: readonly string[]) => symbols.join(", ");
258
+ ctx.printResult({ data }, {
259
+ text: () => result.moved.length === 0
260
+ ? cliStyles.warning(result.group == null
261
+ ? `${named(keys)} ${keys.length === 1 ? "is" : "are"} in no group of "${watchlist.name}".`
262
+ : `${named(keys)} ${keys.length === 1 ? "is" : "are"} already in group "${result.group}" of "${watchlist.name}".`)
263
+ : cliStyles.success(result.group == null
264
+ ? `Took ${named(result.moved)} out of ${result.moved.length === 1 ? "its group" : "their groups"} in "${watchlist.name}".`
265
+ : `Moved ${named(result.moved)} to group "${result.group}" of "${watchlist.name}".`),
266
+ });
135
267
  });
136
268
  }
137
269
 
270
+ /** Rows that left the list leave its groups too: added back later, they start in none. */
271
+ async function withoutGroups(config: AppConfig, watchlist: Watchlist, keys: readonly string[]) {
272
+ const next = withoutWatchlistGroupSymbols(config, watchlist.id, keys);
273
+ if (next !== config) await saveConfig(next);
274
+ }
275
+
138
276
  async function removeTickerFromWatchlist(
139
- watchlist: Watchlist, symbol: string, notes: readonly string[], exchange: string | undefined, ctx: CliCommandContext, { store }: ConfigContext,
277
+ watchlist: Watchlist, symbol: string, notes: readonly string[], exchange: string | undefined, ctx: CliCommandContext, { store, config }: ConfigContext,
140
278
  ) {
141
279
  // SAN:EPA and SAN --exchange EPA name the stored listing, which a bare SAN may hold under another venue.
142
280
  // GARAN.IS is the row of GARAN:BIST, else a row still saved under that key (a broker's).
@@ -147,6 +285,7 @@ async function removeTickerFromWatchlist(
147
285
  if (!result.changed) ctx.fail(`${saved.key} is not in "${watchlist.name}".`);
148
286
 
149
287
  await store.saveTicker(result.ticker);
288
+ await withoutGroups(config, watchlist, [ticker.metadata.ticker]);
150
289
  ctx.printResult({ data: { changed: true, ...listingFields(saved), watchlist: watchlist.name }, ...notes.length > 0 ? { warnings: [...notes] } : {} }, {
151
290
  text: () => cliStyles.success(`Removed ${saved.label} from "${watchlist.name}".`),
152
291
  });
@@ -160,13 +299,19 @@ async function removeFromWatchlistCommand(args: string[], file: string | undefin
160
299
  await removeTickerFromWatchlist(watchlist, list.single, list.notes, exchange, ctx, context);
161
300
  return;
162
301
  }
302
+ const removed: string[] = [];
163
303
  const rows = await removeSymbols({
164
304
  symbols: list.symbols,
165
305
  exchange,
166
306
  store: context.store,
167
307
  holds: (ticker) => ticker.metadata.watchlists.includes(watchlist.id),
168
- remove: (ticker) => removeWatchlistMembership(ticker, watchlist.id),
308
+ remove: (ticker) => {
309
+ const result = removeWatchlistMembership(ticker, watchlist.id);
310
+ if (result.changed) removed.push(ticker.metadata.ticker);
311
+ return result;
312
+ },
169
313
  });
314
+ await withoutGroups(context.config, watchlist, removed);
170
315
  printSymbolRows(ctx, rows, { verb: "remove", collection: { kind: "watchlist", name: watchlist.name }, repeated: list.repeated, notes: list.notes });
171
316
  });
172
317
  }
@@ -219,7 +364,7 @@ async function listWatchlists(ctx: CliCommandContext) {
219
364
  export const watchlistCliCommand: CliCommandDef = {
220
365
  name: "watchlist",
221
366
  aliases: ["watchlists"],
222
- description: "Show watchlist quotes, and add or remove symbols",
367
+ description: "Show watchlist quotes, add or remove symbols, and group them",
223
368
  help: {
224
369
  group: CLI_COMMAND_GROUPS.portfolios,
225
370
  usage: [
@@ -227,10 +372,13 @@ export const watchlistCliCommand: CliCommandDef = {
227
372
  "watchlist show <name>",
228
373
  "watchlist create <name>",
229
374
  "watchlist delete <name>",
230
- "watchlist add <watchlist> <symbols...> [--file <path>]",
375
+ "watchlist add <watchlist> <symbols...> [--file <path>] [--group <name>]",
231
376
  "watchlist remove <watchlist> <symbols...> [--file <path>]",
377
+ "watchlist move <watchlist> <symbols...> --group <name>",
378
+ "watchlist ungroup <watchlist> <symbols...>",
379
+ "watchlist ungroup <watchlist> --group <name>",
232
380
  ],
233
- options: [EXCHANGE_OPTION, FILE_OPTION],
381
+ options: [EXCHANGE_OPTION, FILE_OPTION, GROUP_OPTION],
234
382
  examples: [
235
383
  "watchlist show Growth",
236
384
  "watchlist create Growth",
@@ -241,15 +389,23 @@ export const watchlistCliCommand: CliCommandDef = {
241
389
  "watchlist add Growth --file holdings.csv",
242
390
  "watchlist add Growth --file holdings.csv --dry-run",
243
391
  "watchlist show Growth --csv",
392
+ "watchlist add Funds VTSAX FXAIX --group \"Index funds\"",
393
+ "watchlist move Growth XOM CVX --group Energy",
394
+ "watchlist ungroup Growth XOM",
244
395
  ],
245
- sections: [SYMBOL_LIST_HELP],
396
+ sections: [SYMBOL_LIST_HELP, GROUPS_HELP],
246
397
  },
247
398
  execute: async (rawArgs, ctx) => {
248
399
  const args = [...rawArgs];
249
400
  const exchange = takeOption(args, "--exchange");
250
401
  const hasFile = args.some((arg) => arg === "--file" || arg.startsWith("--file="));
251
402
  const file = hasFile ? takeOption(args, "--file") ?? "" : undefined;
403
+ const hasGroup = args.some((arg) => arg === "--group" || arg.startsWith("--group="));
404
+ const group = hasGroup ? takeOption(args, "--group") ?? "" : undefined;
252
405
  const action = args[0];
406
+ if (group != null && action !== "add" && action !== "move" && action !== "ungroup") {
407
+ ctx.fail(`--group is an option of watchlist add, move and ungroup, not watchlist ${action ?? "list"}.`, MOVE_USAGE);
408
+ }
253
409
  if (file != null && action !== "add" && action !== "remove") ctx.fail(`--file is an option of watchlist add and remove, not watchlist ${action ?? "list"}.`, ADD_USAGE);
254
410
  if (MUTATING_ACTIONS.has(action ?? "")) refuseDryRun(ctx, "watchlist", action!);
255
411
 
@@ -280,7 +436,12 @@ export const watchlistCliCommand: CliCommandDef = {
280
436
  }
281
437
 
282
438
  if (action === "add") {
283
- await addToWatchlistCommand(args.slice(1), file, exchange, ctx);
439
+ await addToWatchlistCommand(args.slice(1), file, exchange, group, ctx);
440
+ return;
441
+ }
442
+
443
+ if (action === "move" || action === "ungroup") {
444
+ await groupWatchlistSymbols(action, args.slice(1), exchange, group, ctx);
284
445
  return;
285
446
  }
286
447
 
@@ -9,6 +9,7 @@ import type {
9
9
  import type { TickerRecord } from "../../../types/ticker";
10
10
  import type { Quote } from "../../../types/financials";
11
11
  import { formatNumber, formatPercentRaw } from "../../../utils/format";
12
+ import { displayTickerKey } from "../../../utils/exchanges";
12
13
  import {
13
14
  collectionQuoteHeadline,
14
15
  dayMoveLine,
@@ -53,7 +54,7 @@ import { describeCollections } from "../../../portfolio/collection-name";
53
54
  import { currentListingName } from "../../../tickers/listing-name";
54
55
  import { REPORT_ROWS } from "../shared/headless-options";
55
56
  import { readPriceWindow, type PriceWindow } from "../../../utils/price-window";
56
- import { loadPeriodPnl, periodBasisText, periodBoughtText, periodUnpricedText } from "./period-pnl";
57
+ import { loadPeriodPnl, periodBasisText, periodBoughtText, periodCurrencyParts, periodFxLabel, periodUnpricedText } from "./period-pnl";
57
58
 
58
59
  /** An extended print without a known regular close cannot supply a regular-session change. */
59
60
  function regularChangeFields(quote: Quote | undefined, change: unknown) {
@@ -493,6 +494,16 @@ const PERIOD_COLUMNS: HeadlessPaneColumn[] = [
493
494
  { key: "contribution", header: "Contribution", align: "right", format: percent, description: "P&L over the book's value at the start, gross when it holds a short, in percent." },
494
495
  ];
495
496
 
497
+ /** `fn PF --from` on a book in more than one currency: each currency's price P&L, FX and total, and the book's. */
498
+ const PERIOD_CURRENCY_COLUMNS: HeadlessPaneColumn[] = [
499
+ { key: "currency", header: "Currency" },
500
+ { key: "local", header: "Local", align: "right", format: amount, description: "Its holdings' price P&L, in the portfolio's currency at the end's rate." },
501
+ { key: "fx", header: "FX", align: "right", format: amount, description: "The currency's move on its holdings' start value." },
502
+ { key: "total", header: "Total", align: "right", format: amount },
503
+ { key: "contribution", header: "Contribution", align: "right", format: percent, description: "The total over the book's value at the start, in percent." },
504
+ { key: "leftOut", header: "Left out", description: "Its holdings with no P&L over the window, which the figures leave out." },
505
+ ];
506
+
496
507
  /**
497
508
  * PF over a period (`--from`, `--to`): P&L and contribution by position
498
509
  * between two closes, as `portfolio show --from` reads them, on the
@@ -541,18 +552,30 @@ async function portfolioPeriodHoldings(
541
552
  contribution: row.contribution,
542
553
  };
543
554
  });
544
- const fxCurrencies = [...new Set(result.rows.flatMap((row) => row.rates ? [row.rates.currency] : []))];
545
- if (fxCurrencies.length) rows.push({ symbol: `FX (${fxCurrencies.join(", ")})`, pnl: result.fx, contribution: result.fxContribution });
555
+ // An FX line per currency, then the total; the book by currency under them, as portfolio show --from prints it.
556
+ const parts = periodCurrencyParts(result);
557
+ for (const part of parts) if (!part.own) rows.push({ symbol: periodFxLabel(part.currency), pnl: part.fx, contribution: part.fxContribution });
546
558
  rows.push({ symbol: "TOTAL", pnl: result.total, contribution: result.totalContribution });
559
+ // A holding by the listing it is (ES3:SGX), not the key it is saved under (ES3:XSES).
560
+ const listing = (symbol: string) => { const ticker = bySymbolTicker.get(symbol); return ticker ? listingLabel(ticker) : displayTickerKey(symbol); };
561
+ const byCurrency = parts.length > 1 ? [
562
+ ...parts.map((part) => ({ currency: part.currency, local: part.local, fx: part.own ? null : part.fx, total: part.total, contribution: part.contribution,
563
+ ...(part.unpriced.length ? { leftOut: part.unpriced.map(listing).join(", ") } : {}) })),
564
+ { currency: "TOTAL", local: result.total - result.fx, fx: result.fx, total: result.total, contribution: result.totalContribution,
565
+ ...(result.unpriced.length ? { leftOut: result.unpriced.map(listing).join(", ") } : {}) },
566
+ ] : [];
567
+ // The Left out column only when a holding is: each currency's figures name the ones they leave out.
568
+ const byCurrencyColumns = PERIOD_CURRENCY_COLUMNS.filter((column) => column.key !== "leftOut" || result.unpriced.length > 0)
569
+ .map((column) => column.align === "right" && column.key !== "contribution" ? { ...column, header: `${column.header} (${currency})` } : column);
547
570
  const futuresHeldNow = result.rows.some((row) => { const ticker = bySymbolTicker.get(row.symbol); return !!ticker && isFuturesTicker(ticker); });
548
- const bought = periodBoughtText(result);
571
+ const bought = periodBoughtText(result, listing);
549
572
  const notices = [
550
573
  `${periodBasisText(result, { futuresHeld: futuresHeldNow })}, in ${currency}.`,
551
574
  ...(result.contributionBase == null ? [] : [`Contribution is P&L over the book's ${result.contributionBasis === "gross" ? "gross exposure" : "value"} at the start, longs plus shorts at their absolute value when it holds a short; cash excluded.`]),
552
575
  ...(bought ? [bought] : []),
553
576
  ...(ordered.length > limit ? [`${ordered.length - limit} more position${ordered.length - limit === 1 ? "" : "s"} not shown; the FX line and the total include every position.`] : []),
554
577
  ];
555
- const unpricedText = periodUnpricedText(result);
578
+ const unpricedText = periodUnpricedText(result, listing);
556
579
  const errors = unpricedText ? [unpricedText] : [];
557
580
  return {
558
581
  freshness: {
@@ -563,8 +586,12 @@ async function portfolioPeriodHoldings(
563
586
  },
564
587
  columns: withListingLabels(withBookCurrency(PERIOD_COLUMNS, currency), tickers),
565
588
  rows,
589
+ ...(byCurrency.length ? {
590
+ textSections: [{ title: "By currency", columns: byCurrencyColumns, rows: byCurrency }],
591
+ exportTables: [{ title: "By currency", columns: byCurrencyColumns, rows: byCurrency, unit: currency }],
592
+ } : {}),
566
593
  complete: errors.length === 0,
567
- ...(errors.length ? { errors } : {}),
594
+ ...(errors.length ? { errors, incompleteDetail: `the total leaves out ${result.unpriced.map(listing).join(", ")}` } : {}),
568
595
  metadata: {
569
596
  collection: { kind: "portfolio", id: target.id, name: target.name },
570
597
  currency,
@@ -0,0 +1,220 @@
1
+ import { useCallback, useMemo, useRef } from "react";
2
+ import { ChoiceDialog, confirmDialog, TextPromptDialog, usePaneFooter, usePaneMenuItems } from "../../../../components";
3
+ import type { TickerTableGroup } from "../../../../components/ticker/list-table-view";
4
+ import { t, tf } from "../../../../i18n";
5
+ import {
6
+ renameWatchlistGroup,
7
+ sectionWatchlistItems,
8
+ setWatchlistGroup,
9
+ UNGROUPED_LABEL,
10
+ watchlistGroupOf,
11
+ watchlistGroups,
12
+ watchlistTakesGroups,
13
+ } from "../../../../portfolio/watchlist-groups";
14
+ import { syncConfigActiveLayoutState, useAppDispatch, useAppStateRef } from "../../../../state/app/context";
15
+ import { scheduleConfigSave } from "../../../../state/config-save-scheduler";
16
+ import type { AppConfig } from "../../../../types/config";
17
+ import type { ContextMenuItem } from "../../../../types/context-menu";
18
+ import type { TickerRecord, Watchlist } from "../../../../types/ticker";
19
+ import { useDialog, type PromptContext } from "../../../../ui/dialog";
20
+ import { logFailure } from "../../../../utils/log-failure";
21
+ import { usePluginAppActions } from "../../../runtime";
22
+
23
+ /** `g` moves the cursor row to a group: the row menu shows it beside Move to Group…. */
24
+ const MOVE_TO_GROUP_KEY = "g";
25
+ /** The section of the tickers in no group; no group's name is empty. */
26
+ const UNGROUPED_ID = "";
27
+ const NEW_GROUP_CHOICE = "\u0000new-group";
28
+
29
+ /** A section the pane shows collapsed, by its list: the group's name, or "" for Ungrouped. Kept in the pane's state. */
30
+ export interface CollapsedGroup {
31
+ list: string;
32
+ group: string;
33
+ }
34
+
35
+ /**
36
+ * A watchlist's rows under its groups, each group's rows in the order given
37
+ * (the table's sort), then Ungrouped. Undefined when no row is in a group, so
38
+ * a list without groups shows as it always has.
39
+ */
40
+ export function buildWatchlistTableGroups(
41
+ watchlist: Pick<Watchlist, "id" | "groups"> | null,
42
+ sortedTickers: readonly TickerRecord[],
43
+ collapsed: readonly CollapsedGroup[],
44
+ ): TickerTableGroup[] | undefined {
45
+ if (!watchlist) return undefined;
46
+ const sections = sectionWatchlistItems(watchlistGroups(watchlist), sortedTickers, (ticker) => ticker.metadata.ticker);
47
+ if (!sections) return undefined;
48
+ return sections.map(({ name, items }) => {
49
+ const id = name ?? UNGROUPED_ID;
50
+ return {
51
+ id,
52
+ label: name ?? t(UNGROUPED_LABEL),
53
+ tickers: items,
54
+ collapsed: collapsed.some((entry) => entry.list === watchlist.id && entry.group === id),
55
+ };
56
+ });
57
+ }
58
+
59
+ /** The pane's collapsed sections with one of a list's flipped. */
60
+ export function toggleCollapsedGroup(collapsed: readonly CollapsedGroup[], list: string, group: string): CollapsedGroup[] {
61
+ const shown = collapsed.filter((entry) => entry.list !== list || entry.group !== group);
62
+ return shown.length < collapsed.length ? shown : [...collapsed, { list, group }];
63
+ }
64
+
65
+ /**
66
+ * Moving the rows of a personal watchlist between its groups: Move to Group…
67
+ * (`g`) and Remove from Group in a row's menu, and Rename Group… and Delete
68
+ * Group… in the pane menu while the cursor is on a group's header. `onMoved`
69
+ * hears the group a row went to, so the pane can show it.
70
+ */
71
+ export function useWatchlistGroupActions({
72
+ watchlist,
73
+ cursorTicker,
74
+ cursorGroup,
75
+ enabled,
76
+ onMoved,
77
+ }: {
78
+ watchlist: Watchlist | null;
79
+ /** The ticker under the cursor, for `g`. */
80
+ cursorTicker: TickerRecord | null;
81
+ /** The named group whose header the cursor is on. */
82
+ cursorGroup: string | null;
83
+ enabled: boolean;
84
+ onMoved: (symbol: string, group: string | null) => void;
85
+ }): ((ticker: TickerRecord) => ContextMenuItem[]) | undefined {
86
+ const dialog = useDialog();
87
+ const dispatch = useAppDispatch();
88
+ const stateRef = useAppStateRef();
89
+ const { notify } = usePluginAppActions();
90
+ const busyRef = useRef(false);
91
+ const takesGroups = !!watchlist && watchlistTakesGroups(watchlist);
92
+ const listId = takesGroups ? watchlist.id : null;
93
+ const onMovedRef = useRef(onMoved);
94
+ onMovedRef.current = onMoved;
95
+
96
+ // With the panes' live state in the layout, so the config keeps the cursor where the row went.
97
+ const save = useCallback((config: AppConfig) => {
98
+ const state = stateRef.current;
99
+ const synced = syncConfigActiveLayoutState(config, state.paneState, state.focusedPaneId);
100
+ dispatch({ type: "SET_CONFIG", config: synced });
101
+ scheduleConfigSave(synced);
102
+ }, [dispatch, stateRef]);
103
+
104
+ // The list as it is now, in case a sync changed it while a dialog was open.
105
+ const currentList = useCallback(() => (listId ? stateRef.current.config.watchlists.find((entry) => entry.id === listId) ?? null : null), [listId, stateRef]);
106
+
107
+ const fail = useCallback((error: unknown) => {
108
+ notify({ type: "error", body: error instanceof Error ? error.message : String(error) });
109
+ }, [notify]);
110
+
111
+ const moveTo = useCallback((symbol: string, group: string | null) => {
112
+ const list = currentList();
113
+ if (!list) return;
114
+ try {
115
+ const result = setWatchlistGroup(stateRef.current.config, list.id, [symbol], group);
116
+ if (result.moved.length > 0) save(result.config);
117
+ onMovedRef.current(symbol, result.group);
118
+ } catch (error) {
119
+ fail(error);
120
+ }
121
+ }, [currentList, fail, save, stateRef]);
122
+
123
+ /** The name a new group is given, typed in a prompt; null when none was. */
124
+ const askName = useCallback(async (title: string, body: string | null, confirmLabel: string, initialValue = "") => {
125
+ const typed = await dialog.prompt<string>({
126
+ content: (context) => (
127
+ <TextPromptDialog {...context} title={title} body={body ? [body] : undefined} label={t("Name")} initialValue={initialValue}
128
+ placeholder={t("Energy")} confirmLabel={confirmLabel} width={52} />
129
+ ),
130
+ });
131
+ return typed?.trim() ? typed : null;
132
+ }, [dialog]);
133
+
134
+ const promptMove = useCallback(async (symbol: string) => {
135
+ const list = currentList();
136
+ if (!list || busyRef.current) return;
137
+ busyRef.current = true;
138
+ try {
139
+ const current = watchlistGroupOf(list, symbol);
140
+ const others = watchlistGroups(list).filter((group) => group.name !== current);
141
+ let choice: string | undefined = NEW_GROUP_CHOICE;
142
+ if (others.length > 0) {
143
+ choice = await dialog.prompt<string>({
144
+ content: (context: PromptContext<string>) => (
145
+ <ChoiceDialog {...context} title={tf("Move {symbol} to Group", { symbol })} choices={[
146
+ ...others.map((group) => ({ id: group.name, label: group.name })),
147
+ { id: NEW_GROUP_CHOICE, label: t("New Group…") },
148
+ ]} />
149
+ ),
150
+ });
151
+ }
152
+ if (choice == null) return;
153
+ const name = choice === NEW_GROUP_CHOICE
154
+ ? await askName(t("New Group"), tf("{symbol} moves to it in {watchlist}.", { symbol, watchlist: list.name }), t("Move"))
155
+ : choice;
156
+ if (name != null) moveTo(symbol, name);
157
+ } finally {
158
+ busyRef.current = false;
159
+ }
160
+ }, [askName, currentList, dialog, moveTo]);
161
+
162
+ const startMove = useCallback((symbol: string) => {
163
+ promptMove(symbol).catch((error: unknown) => {
164
+ fail(error);
165
+ logFailure("portfolio-list.groups", "Move to group failed")(error);
166
+ });
167
+ }, [fail, promptMove]);
168
+
169
+ const rowMenuItems = useMemo(() => listId ? (ticker: TickerRecord): ContextMenuItem[] => {
170
+ const symbol = ticker.metadata.ticker;
171
+ const inGroup = watchlistGroupOf(currentList(), symbol) != null;
172
+ return [
173
+ { id: "watchlist:move-to-group", label: t("Move to Group…"), accelerator: MOVE_TO_GROUP_KEY, onSelect: () => startMove(symbol) },
174
+ ...inGroup ? [{ id: "watchlist:remove-from-group", label: t("Remove from Group"), onSelect: () => moveTo(symbol, null) }] : [],
175
+ ];
176
+ // Built again when the list's groups change, so the cursor row's menu offers Remove from Group once it is in one.
177
+ } : undefined, [currentList, listId, moveTo, startMove, watchlist?.groups]);
178
+
179
+ const cursorSymbol = cursorTicker?.metadata.ticker ?? null;
180
+ usePaneFooter("portfolio-list-groups", () => enabled && listId && cursorSymbol ? {
181
+ keys: [{ id: "move-to-group", key: MOVE_TO_GROUP_KEY, label: "", title: t("Move to Group"), onPress: () => startMove(cursorSymbol) }],
182
+ } : null, [cursorSymbol, enabled, listId, startMove]);
183
+
184
+ const renameGroup = useCallback(async (group: string) => {
185
+ const list = currentList();
186
+ if (!list) return;
187
+ const name = await askName(t("Rename Group"), null, t("Rename"), group);
188
+ if (name == null) return;
189
+ try {
190
+ save(renameWatchlistGroup(stateRef.current.config, list.id, group, name));
191
+ } catch (error) {
192
+ fail(error);
193
+ }
194
+ }, [askName, currentList, fail, save, stateRef]);
195
+
196
+ const deleteGroup = useCallback(async (group: string) => {
197
+ const list = currentList();
198
+ const symbols = watchlistGroups(list).find((entry) => entry.name === group)?.symbols ?? [];
199
+ if (!list || symbols.length === 0) return;
200
+ const confirmed = await confirmDialog(dialog, {
201
+ title: tf("Delete the group {group}?", { group }),
202
+ body: [t("Its tickers stay in the list, in no group.")],
203
+ confirmLabel: t("Delete"),
204
+ });
205
+ if (!confirmed) return;
206
+ try {
207
+ const result = setWatchlistGroup(stateRef.current.config, list.id, symbols, null);
208
+ if (result.moved.length > 0) save(result.config);
209
+ } catch (error) {
210
+ fail(error);
211
+ }
212
+ }, [currentList, dialog, fail, save, stateRef]);
213
+
214
+ usePaneMenuItems("portfolio-list-group-header", () => enabled && listId && cursorGroup ? [
215
+ { id: "rename-group", label: t("Rename Group…"), onSelect: () => { renameGroup(cursorGroup).catch(logFailure("portfolio-list.groups", "Rename group failed")); } },
216
+ { id: "delete-group", label: t("Delete Group…"), onSelect: () => { deleteGroup(cursorGroup).catch(logFailure("portfolio-list.groups", "Delete group failed")); } },
217
+ ] : null, [cursorGroup, deleteGroup, enabled, listId, renameGroup]);
218
+
219
+ return rowMenuItems;
220
+ }