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
@@ -0,0 +1,193 @@
1
+ import { useEffect, useMemo, useState } from "react";
2
+ import { Box, Text, useActionShortcut, useUiCapabilities } from "../../ui";
3
+ import { Button, terminalButtonColumns } from "../../components/ui/button";
4
+ import { TickerBadge } from "../../components/ticker/badge";
5
+ import { getTickerBadgeText, TICKER_BADGE_CHROME_WIDTH } from "../../components/ticker/badge/format";
6
+ import { t, tf } from "../../i18n";
7
+ import { useAppLanguage } from "../../i18n/react";
8
+ import { useQuoteEntries } from "../../market-data/hooks";
9
+ import { buildQuoteKey, resolveEntryData } from "../../market-data/selectors";
10
+ import { useViewport } from "../../react/input";
11
+ import { useThemeColors } from "../../theme/theme-context";
12
+ import type { Quote } from "../../types/financials";
13
+ import { displayWidth } from "../../utils/format";
14
+ import { bindSinceLastVisitKeys } from "./keys";
15
+ import { formatVisitTime, liveMovePercent, type VisitMove } from "./model";
16
+ import type { SinceLastVisit, SinceLastVisitMove } from "./use-since-last-visit";
17
+
18
+ /** Cells between the lead and the chips, and between the two actions. */
19
+ const GAP = 2;
20
+ /** A window this wide (in cells) says "since your last visit" in full on the desktop and the web. */
21
+ const NATIVE_FULL_LEAD_COLUMNS = 110;
22
+
23
+ interface StripChip {
24
+ move: VisitMove;
25
+ percent: number;
26
+ quote: Quote | null;
27
+ }
28
+
29
+ interface TerminalFit {
30
+ lead: string;
31
+ chips: number;
32
+ /** Hide says its key. */
33
+ hideKey: boolean;
34
+ turnOff: boolean;
35
+ }
36
+
37
+ /**
38
+ * What the terminal's one row has room for. The date of the last visit (the
39
+ * short lead), Hide and one move always stay: a move without its date would
40
+ * read as the day's. Turn off stays next, as long as a move fits beside it
41
+ * (the command bar's Since Last Visit has it too); then as many moves as fit,
42
+ * biggest first; then Hide's key; then the lead in full.
43
+ */
44
+ function fitTerminalStrip(
45
+ width: number,
46
+ [fullLead, shortLead]: readonly [string, string],
47
+ chipColumns: readonly number[],
48
+ hideColumns: { withKey: number; bare: number },
49
+ turnOffColumns: number,
50
+ ): TerminalFit {
51
+ const fit = (option: Omit<TerminalFit, "chips">): TerminalFit => {
52
+ // One cell of padding at each edge, a gap after the lead and before each action.
53
+ let room = width - 2 - displayWidth(option.lead) - GAP
54
+ - GAP - (option.hideKey ? hideColumns.withKey : hideColumns.bare)
55
+ - (option.turnOff ? GAP + turnOffColumns : 0);
56
+ let chips = 0;
57
+ for (const columns of chipColumns) {
58
+ if (columns > room) break;
59
+ room -= columns;
60
+ chips += 1;
61
+ }
62
+ return { ...option, chips };
63
+ };
64
+ const withTurnOff = [
65
+ fit({ lead: fullLead, hideKey: true, turnOff: true }),
66
+ fit({ lead: shortLead, hideKey: true, turnOff: true }),
67
+ fit({ lead: shortLead, hideKey: false, turnOff: true }),
68
+ ];
69
+ const whole = withTurnOff.find((option) => option.chips === chipColumns.length);
70
+ if (whole) return whole;
71
+ const most = withTurnOff.reduce((best, option) => (option.chips > best.chips ? option : best));
72
+ return most.chips > 0 ? most : fit({ lead: shortLead, hideKey: false, turnOff: false });
73
+ }
74
+
75
+ /**
76
+ * The strip a returning user sees above the layout: when they were last
77
+ * here, then what moved most in their own portfolios and watchlists since,
78
+ * each a ticker chip that opens its research. Hide puts it away for this
79
+ * session (the notification dismiss key too); Turn off puts it away for good,
80
+ * until Since Last Visit in the command bar turns it on again.
81
+ */
82
+ export function SinceLastVisitStrip({ strip }: { strip: SinceLastVisit }) {
83
+ useAppLanguage();
84
+ const colors = useThemeColors();
85
+ const { nativePaneChrome = false } = useUiCapabilities();
86
+ const { width } = useViewport();
87
+ const dismissKey = useActionShortcut("notification-dismiss");
88
+ // The chip under the pointer says its price, as ticker chips do.
89
+ const [hovered, setHovered] = useState<string | null>(null);
90
+ const recap = strip.recap;
91
+ const moves: readonly SinceLastVisitMove[] = recap?.moves ?? [];
92
+ const entries = useQuoteEntries(useMemo(() => moves.map((entry) => entry.instrument), [moves]));
93
+ const now = Date.now();
94
+ const chips = moves.flatMap<StripChip>(({ move, instrument }) => {
95
+ const quote = resolveEntryData(entries.get(buildQuoteKey(instrument))) ?? null;
96
+ const percent = liveMovePercent(move, quote, now);
97
+ return percent == null ? [] : [{ move, percent, quote }];
98
+ });
99
+ const first = chips[0]?.move ?? null;
100
+
101
+ useEffect(() => {
102
+ if (!first) return;
103
+ strip.noteShown();
104
+ return bindSinceLastVisitKeys({ open: () => strip.open(first), dismiss: strip.hide });
105
+ }, [first, strip]);
106
+ // Every move it named stopped comparing (a currency or a split changed under it): nothing is left to say.
107
+ const exhausted = !!recap && chips.length === 0;
108
+ useEffect(() => {
109
+ if (exhausted) strip.hide();
110
+ }, [exhausted, strip]);
111
+
112
+ if (!recap || chips.length === 0) return null;
113
+
114
+ const when = formatVisitTime(recap.seenAt, now);
115
+ const fullLead = tf("Since your last visit, {time}", { time: when });
116
+ const shortLead = tf("Since {time}", { time: when });
117
+ const hideButton = { label: "Hide", compact: true, shortcut: dismissKey || undefined } as const;
118
+ const bareHideButton = { label: "Hide", compact: true } as const;
119
+ const turnOffButton = { label: "Turn off", compact: true } as const;
120
+ const chipText = (chip: StripChip) => getTickerBadgeText({ symbol: chip.move.symbol, status: "ready", quote: chip.quote, move: chip.percent });
121
+
122
+ // The desktop and the web lay the chips out in CSS: one that has no room wraps out of sight.
123
+ const fit: TerminalFit = nativePaneChrome
124
+ ? { lead: width >= NATIVE_FULL_LEAD_COLUMNS ? fullLead : shortLead, chips: chips.length, hideKey: true, turnOff: true }
125
+ : fitTerminalStrip(
126
+ width,
127
+ [fullLead, shortLead],
128
+ chips.map((chip) => displayWidth(chipText(chip)) + TICKER_BADGE_CHROME_WIDTH),
129
+ { withKey: terminalButtonColumns(hideButton), bare: terminalButtonColumns(bareHideButton) },
130
+ terminalButtonColumns(turnOffButton),
131
+ );
132
+
133
+ const chipNodes = chips.slice(0, fit.chips).map((chip) => (
134
+ <TickerBadge
135
+ key={chip.move.key}
136
+ symbol={chip.move.symbol}
137
+ status="ready"
138
+ quote={chip.quote}
139
+ move={chip.percent}
140
+ hovered={hovered === chip.move.key}
141
+ onHoverStart={() => setHovered(chip.move.key)}
142
+ onHoverEnd={() => setHovered((current) => (current === chip.move.key ? null : current))}
143
+ onOpen={() => strip.open(chip.move)}
144
+ />
145
+ ));
146
+
147
+ return (
148
+ <Box
149
+ flexDirection="row"
150
+ height={1}
151
+ alignItems="center"
152
+ flexShrink={0}
153
+ backgroundColor={colors.panel}
154
+ data-gloom-role="since-last-visit"
155
+ style={nativePaneChrome ? { paddingInline: "var(--gloom-inset)", gap: "var(--gloom-space-sm)" } : undefined}
156
+ paddingX={nativePaneChrome ? undefined : 1}
157
+ >
158
+ <Box flexShrink={0} paddingRight={nativePaneChrome ? undefined : GAP}>
159
+ <Text fg={colors.textDim}>{fit.lead}</Text>
160
+ </Box>
161
+ <Box
162
+ flexDirection="row"
163
+ flexGrow={1}
164
+ flexShrink={1}
165
+ minWidth={0}
166
+ overflow="hidden"
167
+ // A chip the window has no room for wraps out of sight rather than being cut.
168
+ style={nativePaneChrome ? { flexWrap: "wrap", height: "100%", alignContent: "flex-start" } : undefined}
169
+ >
170
+ {chipNodes}
171
+ </Box>
172
+ <Box
173
+ flexDirection="row"
174
+ flexShrink={0}
175
+ paddingLeft={nativePaneChrome ? undefined : GAP}
176
+ style={nativePaneChrome ? { gap: "var(--gloom-space-sm)" } : undefined}
177
+ >
178
+ <Button
179
+ {...(fit.hideKey ? hideButton : bareHideButton)}
180
+ variant="plain"
181
+ title={t("Hide until you next open Gloom")}
182
+ stopPropagation
183
+ onPress={strip.hide}
184
+ />
185
+ {fit.turnOff ? (
186
+ <Box paddingLeft={nativePaneChrome ? undefined : GAP}>
187
+ <Button {...turnOffButton} variant="plain" title={t("Stop showing what moved since your last visit")} stopPropagation onPress={strip.turnOff} />
188
+ </Box>
189
+ ) : null}
190
+ </Box>
191
+ </Box>
192
+ );
193
+ }
@@ -0,0 +1,289 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
2
+ import { apiClient } from "../../api-client";
3
+ import type { AppPluginStateStorePort } from "../../core/app-service-ports";
4
+ import { t } from "../../i18n";
5
+ import type { MarketDataCoordinator } from "../../market-data/coordinator";
6
+ import type { InstrumentRef } from "../../market-data/request-types";
7
+ import { buildQuoteKey, resolveEntryData } from "../../market-data/selectors";
8
+ import { useAppActive, useAppVisible } from "../../state/app/activity";
9
+ import { useAppDispatch, useAppGetState, useAppSelector } from "../../state/app/context";
10
+ import { scheduleConfigSave } from "../../state/config-save-scheduler";
11
+ import { useInlineTickerOpener } from "../../state/hooks/inline-tickers";
12
+ import { recordFunctionOpen, recordFunctionShown } from "../../telemetry/usage-counts";
13
+ import type { AppNotificationRequest } from "../../types/plugin";
14
+ import { logFailure } from "../../utils/log-failure";
15
+ import {
16
+ MIN_AWAY_MS,
17
+ observeQuote,
18
+ recapSince,
19
+ trackedListings,
20
+ visitScope,
21
+ type TrackedListing,
22
+ type VisitMove,
23
+ type VisitObservation,
24
+ type VisitRecap,
25
+ } from "./model";
26
+ import { createVisitBaselineStore, VisitTracker } from "./visit-tracker";
27
+
28
+ /** How long the return waits for its quotes before it compares what it has. */
29
+ const COMPARE_WAIT_MS = 10_000;
30
+ /** Quotes ticking in batches are read once they settle, not on every tick. */
31
+ const SWEEP_DELAY_MS = 2_000;
32
+
33
+ /**
34
+ * Usage counts, by the strip's own names: never which tickers. Showing is not
35
+ * the user opening anything, so it counts as on screen at launch (`restored`);
36
+ * opening a move and turning the strip off are opens.
37
+ */
38
+ const SHOWN_FUNCTION = "LASTVISIT";
39
+ const OPENED_FUNCTION = "LASTVISIT-OPEN";
40
+ const OFF_FUNCTION = "LASTVISIT-OFF";
41
+
42
+ const SINCE_LAST_VISIT_OFF_MESSAGE = "Since Last Visit is off. Turn it on again from the command bar: Since Last Visit.";
43
+
44
+ /** Who is signed in, as the visit is kept for: the API client unless a test says otherwise. */
45
+ export interface VisitAccountSource {
46
+ subscribe(listener: () => void): () => void;
47
+ currentId(): string | null;
48
+ }
49
+
50
+ const apiAccount: VisitAccountSource = {
51
+ subscribe: (listener) => apiClient.subscribeCurrentUser(listener),
52
+ currentId: () => apiClient.getCurrentUser()?.id ?? null,
53
+ };
54
+
55
+ export interface SinceLastVisitMove {
56
+ move: VisitMove;
57
+ instrument: InstrumentRef;
58
+ }
59
+
60
+ export interface SinceLastVisit {
61
+ /** The last visit and what moved since, while the strip has something to show; null otherwise. */
62
+ recap: { seenAt: number; moves: SinceLastVisitMove[] } | null;
63
+ /** Hides the strip for this session. */
64
+ hide(): void;
65
+ /** Turns the strip off on this machine, with a toast that can undo it. */
66
+ turnOff(): void;
67
+ /** Opens a moved ticker's research. */
68
+ open(move: VisitMove): void;
69
+ /** The strip is on screen: counted once per session. */
70
+ noteShown(): void;
71
+ }
72
+
73
+ interface UseSinceLastVisitOptions {
74
+ /** This window shows the strip: the main window, with no setup or sign-in in front of the workspace. */
75
+ active: boolean;
76
+ marketData: Pick<MarketDataCoordinator, "getQuoteEntry" | "loadQuotesBatch" | "subscribeKeys">;
77
+ pluginState: Pick<AppPluginStateStorePort, "get" | "set" | "delete" | "keys">;
78
+ /** Settles once every plugin has registered: the signed-in account is known by then. */
79
+ pluginsReady?: Promise<unknown>;
80
+ notify(request: AppNotificationRequest): void;
81
+ account?: VisitAccountSource;
82
+ }
83
+
84
+ function usePromiseSettled(promise: Promise<unknown> | undefined): boolean {
85
+ const [settled, setSettled] = useState(!promise);
86
+ useEffect(() => {
87
+ if (!promise) {
88
+ setSettled(true);
89
+ return;
90
+ }
91
+ let live = true;
92
+ const done = () => {
93
+ if (live) setSettled(true);
94
+ };
95
+ promise.then(done, done);
96
+ return () => {
97
+ live = false;
98
+ };
99
+ }, [promise]);
100
+ return settled;
101
+ }
102
+
103
+ function currentObservations(
104
+ listings: readonly TrackedListing[],
105
+ marketData: Pick<MarketDataCoordinator, "getQuoteEntry">,
106
+ now: number,
107
+ ): Map<string, VisitObservation> {
108
+ const current = new Map<string, VisitObservation>();
109
+ for (const listing of listings) {
110
+ const observation = observeQuote(listing.symbol, resolveEntryData(marketData.getQuoteEntry(listing.instrument)), now);
111
+ if (observation) current.set(listing.key, observation);
112
+ }
113
+ return current;
114
+ }
115
+
116
+ /**
117
+ * The returning-user strip's session: which account's last visit to read,
118
+ * the one comparison of each account's return with it, and the prices this
119
+ * visit keeps for the next one. See `./model.ts` for what counts as a move
120
+ * and `./visit-tracker.ts` for when the visit is written.
121
+ */
122
+ export function useSinceLastVisit({
123
+ active,
124
+ marketData,
125
+ pluginState,
126
+ pluginsReady,
127
+ notify,
128
+ account = apiAccount,
129
+ }: UseSinceLastVisitOptions): SinceLastVisit {
130
+ const dispatch = useAppDispatch();
131
+ const getState = useAppGetState();
132
+ const enabled = useAppSelector((state) => state.config.sinceLastVisit !== false);
133
+ const initialized = useAppSelector((state) => state.initialized);
134
+ const portfolios = useAppSelector((state) => state.config.portfolios);
135
+ const watchlists = useAppSelector((state) => state.config.watchlists);
136
+ const tickers = useAppSelector((state) => state.tickers);
137
+ const allTracked = useMemo(() => trackedListings({ portfolios, watchlists }, tickers), [portfolios, tickers, watchlists]);
138
+ const trackedKey = allTracked.map((listing) => listing.key).join("\n");
139
+ // A ticker refresh replaces the map without changing which listings are tracked.
140
+ const tracked = useMemo(() => allTracked, [trackedKey]);
141
+ const trackedRef = useRef(tracked);
142
+ trackedRef.current = tracked;
143
+
144
+ const pluginsSettled = usePromiseSettled(pluginsReady);
145
+ const scope = useSyncExternalStore(account.subscribe, () => visitScope(account.currentId()), () => visitScope(account.currentId()));
146
+ const visible = useAppVisible();
147
+ const focused = useAppActive();
148
+ // In the app and looking at it: a hidden window, or a terminal in the
149
+ // background, keeps ticking prices nobody saw.
150
+ const present = visible && focused;
151
+ const running = enabled && active && initialized && pluginsSettled;
152
+
153
+ const store = useMemo(() => createVisitBaselineStore(pluginState), [pluginState]);
154
+ const tracker = useMemo(() => new VisitTracker(store), [store]);
155
+ useEffect(() => () => tracker.stop(), [tracker]);
156
+
157
+ /** Each account's return is compared once per session; a re-enable or a flip back reuses it. */
158
+ const compared = useRef(new Map<string, VisitRecap | null>());
159
+ const [shown, setShown] = useState<{ scope: string; recap: VisitRecap } | null>(null);
160
+ const [hidden, setHidden] = useState(false);
161
+ const countedShown = useRef(false);
162
+
163
+ // Off forgets every stored visit; on again starts a new one.
164
+ useEffect(() => {
165
+ if (!enabled) tracker.forget();
166
+ }, [enabled, tracker]);
167
+
168
+ useEffect(() => {
169
+ tracker.setPresent(running && present);
170
+ }, [present, running, tracker]);
171
+
172
+ // The return: the last visit read once for this account, compared with the
173
+ // quotes this session loads for it, before this visit may be written over it.
174
+ useEffect(() => {
175
+ if (!running) return;
176
+ const baseline = tracker.begin(scope);
177
+ if (compared.current.has(scope)) {
178
+ tracker.allowSaving();
179
+ return;
180
+ }
181
+ const listings = trackedRef.current;
182
+ const due = !!baseline && Date.now() - baseline.seenAt >= MIN_AWAY_MS
183
+ && listings.some((listing) => !!baseline.observations[listing.key]);
184
+ if (!due) {
185
+ compared.current.set(scope, null);
186
+ tracker.allowSaving();
187
+ return;
188
+ }
189
+ let done = false;
190
+ const settle = () => {
191
+ if (done) return;
192
+ done = true;
193
+ clearTimeout(timer);
194
+ const now = Date.now();
195
+ const recap = recapSince(baseline, trackedRef.current, currentObservations(trackedRef.current, marketData, now), now);
196
+ compared.current.set(scope, recap);
197
+ if (recap) setShown({ scope, recap });
198
+ tracker.allowSaving();
199
+ };
200
+ const timer = setTimeout(settle, COMPARE_WAIT_MS);
201
+ marketData.loadQuotesBatch(listings.map((listing) => listing.instrument)).then(settle, (error: unknown) => {
202
+ logFailure("since-last-visit", "Loading the return's quotes failed")(error);
203
+ settle();
204
+ });
205
+ return () => {
206
+ // A result that lands after this (another account, turned off, gone) is not this return's.
207
+ if (done) return;
208
+ done = true;
209
+ clearTimeout(timer);
210
+ };
211
+ }, [marketData, running, scope, tracker]);
212
+
213
+ // This visit's prices: whatever quotes the app has for the tracked listings,
214
+ // read when they change while the user is in the app.
215
+ useEffect(() => {
216
+ if (!running) return;
217
+ tracker.begin(scope);
218
+ tracker.retain(new Set(tracked.map((listing) => listing.key)));
219
+ let timer: ReturnType<typeof setTimeout> | null = null;
220
+ const sweep = () => {
221
+ timer = null;
222
+ for (const [key, observation] of currentObservations(tracked, marketData, Date.now())) tracker.observe(key, observation);
223
+ };
224
+ sweep();
225
+ const unsubscribe = marketData.subscribeKeys(tracked.map((listing) => buildQuoteKey(listing.instrument)), () => {
226
+ timer ??= setTimeout(sweep, SWEEP_DELAY_MS);
227
+ });
228
+ return () => {
229
+ unsubscribe();
230
+ if (timer == null) return;
231
+ clearTimeout(timer);
232
+ sweep();
233
+ };
234
+ }, [marketData, present, running, scope, tracked, tracker]);
235
+
236
+ const recap = useMemo(() => {
237
+ // Not over setup or the sign-in gate, which can open in front of a strip already shown.
238
+ if (!enabled || !active || hidden || !shown || shown.scope !== scope) return null;
239
+ const instruments = new Map(tracked.map((listing) => [listing.key, listing.instrument] as const));
240
+ // A ticker taken out of the collections leaves the strip with it.
241
+ const moves = shown.recap.moves.flatMap((move) => {
242
+ const instrument = instruments.get(move.key);
243
+ return instrument ? [{ move, instrument }] : [];
244
+ });
245
+ return moves.length > 0 ? { seenAt: shown.recap.seenAt, moves } : null;
246
+ }, [active, enabled, hidden, scope, shown, tracked]);
247
+
248
+ const setEnabled = useCallback((on: boolean) => {
249
+ const current = getState().config;
250
+ if ((current.sinceLastVisit !== false) === on) return;
251
+ const { sinceLastVisit: _previous, ...rest } = current;
252
+ dispatch({ type: "SET_CONFIG", config: on ? rest : { ...rest, sinceLastVisit: false } });
253
+ // Assembled when the write fires, recent tickers included, as the app's own saves are.
254
+ scheduleConfigSave(() => {
255
+ const state = getState();
256
+ return { ...state.config, recentTickers: state.recentTickers };
257
+ });
258
+ }, [dispatch, getState]);
259
+
260
+ const hide = useCallback(() => {
261
+ setHidden(true);
262
+ // Seen: a restart now compares with this visit, not the one before.
263
+ tracker.flush();
264
+ }, [tracker]);
265
+
266
+ const turnOff = useCallback(() => {
267
+ setEnabled(false);
268
+ recordFunctionOpen({ shortcut: OFF_FUNCTION, externalPluginId: null });
269
+ notify({
270
+ body: t(SINCE_LAST_VISIT_OFF_MESSAGE),
271
+ type: "info",
272
+ action: { label: t("Undo"), onClick: () => setEnabled(true) },
273
+ });
274
+ }, [notify, setEnabled]);
275
+
276
+ const openTicker = useInlineTickerOpener();
277
+ const open = useCallback((move: VisitMove) => {
278
+ recordFunctionOpen({ shortcut: OPENED_FUNCTION, externalPluginId: null });
279
+ openTicker(move.symbol);
280
+ }, [openTicker]);
281
+
282
+ const noteShown = useCallback(() => {
283
+ if (countedShown.current) return;
284
+ countedShown.current = true;
285
+ recordFunctionShown({ shortcut: SHOWN_FUNCTION, externalPluginId: null });
286
+ }, []);
287
+
288
+ return useMemo(() => ({ recap, hide, turnOff, open, noteShown }), [hide, noteShown, open, recap, turnOff]);
289
+ }
@@ -0,0 +1,191 @@
1
+ import type { AppPluginStateStorePort } from "../../core/app-service-ports";
2
+ import { createPersistScheduler, type PersistScheduler } from "../../state/persist-scheduler";
3
+ import { fnv1aHex } from "../../utils/hash";
4
+ import { logFailure } from "../../utils/log-failure";
5
+ import { readVisitBaseline, type VisitBaseline, type VisitObservation } from "./model";
6
+
7
+ /**
8
+ * The last visit's prices live in the app's local state store (SQLite in the
9
+ * terminal and the desktop app, browser storage on the web), one row per
10
+ * account, never in config.json, cloud sync or anything sent anywhere.
11
+ */
12
+ const STATE_OWNER = "core.since-last-visit";
13
+ const KEY_PREFIX = "visit:";
14
+ /** Accounts whose last visit this device keeps; the one seen longest ago goes first. */
15
+ export const MAX_KEPT_SCOPES = 3;
16
+ /** How long a visit's newest prices wait before they are written, at most. */
17
+ const VISIT_SAVE_DELAY_MS = 5 * 60_000;
18
+
19
+ export interface VisitBaselineStore {
20
+ load(scope: string): VisitBaseline | null;
21
+ save(baseline: VisitBaseline): void;
22
+ clear(): void;
23
+ }
24
+
25
+ type VisitStateStore = Pick<AppPluginStateStorePort, "get" | "set" | "delete" | "keys">;
26
+
27
+ function storeKey(scope: string): string {
28
+ return `${KEY_PREFIX}${fnv1aHex(scope)}`;
29
+ }
30
+
31
+ export function createVisitBaselineStore(pluginState: VisitStateStore): VisitBaselineStore {
32
+ const seenAtOf = (key: string): number => {
33
+ const value = pluginState.get<{ seenAt?: unknown }>(STATE_OWNER, key)?.value;
34
+ return typeof value?.seenAt === "number" ? value.seenAt : 0;
35
+ };
36
+ return {
37
+ load(scope) {
38
+ try {
39
+ // The row names its account; one that hashed to the same key is not this one's.
40
+ return readVisitBaseline(pluginState.get(STATE_OWNER, storeKey(scope))?.value, scope);
41
+ } catch (error) {
42
+ logFailure("since-last-visit", "Loading the last visit failed")(error);
43
+ return null;
44
+ }
45
+ },
46
+ save(baseline) {
47
+ try {
48
+ const key = storeKey(baseline.scope);
49
+ pluginState.set(STATE_OWNER, key, baseline);
50
+ const others = pluginState.keys(STATE_OWNER).filter((entry) => entry.startsWith(KEY_PREFIX) && entry !== key);
51
+ if (others.length < MAX_KEPT_SCOPES) return;
52
+ const oldestFirst = others.map((entry) => ({ entry, seenAt: seenAtOf(entry) })).sort((a, b) => a.seenAt - b.seenAt);
53
+ for (const { entry } of oldestFirst.slice(0, others.length - (MAX_KEPT_SCOPES - 1))) {
54
+ pluginState.delete(STATE_OWNER, entry);
55
+ }
56
+ } catch (error) {
57
+ logFailure("since-last-visit", "Saving the visit failed")(error);
58
+ }
59
+ },
60
+ clear() {
61
+ try {
62
+ for (const key of pluginState.keys(STATE_OWNER)) pluginState.delete(STATE_OWNER, key);
63
+ } catch (error) {
64
+ logFailure("since-last-visit", "Forgetting the last visits failed")(error);
65
+ }
66
+ },
67
+ };
68
+ }
69
+
70
+ /**
71
+ * One visit's prices for one account, from the moment it starts until it is
72
+ * written for the next one. A price is kept only while the user is in the
73
+ * app (`setPresent`): ticks that land while it is hidden or in the
74
+ * background were never seen. The stored baseline is the only copy of the
75
+ * last visit, so nothing is written over it until the return compared
76
+ * against it (`allowSaving`); after that the visit is written at most every
77
+ * `saveDelayMs`, when the user leaves, and when the app quits.
78
+ */
79
+ export class VisitTracker {
80
+ private scope: string | null = null;
81
+ private previous: VisitBaseline | null = null;
82
+ private readonly visit = new Map<string, VisitObservation>();
83
+ private present = false;
84
+ private lastPresentAt: number | null = null;
85
+ private saving = false;
86
+ private pending = false;
87
+ private readonly saver: PersistScheduler<null>;
88
+ private readonly now: () => number;
89
+
90
+ constructor(
91
+ private readonly store: VisitBaselineStore,
92
+ { saveDelayMs = VISIT_SAVE_DELAY_MS, now = Date.now }: { saveDelayMs?: number; now?: () => number } = {},
93
+ ) {
94
+ this.now = now;
95
+ this.saver = createPersistScheduler<null>({
96
+ delayMs: saveDelayMs,
97
+ save: () => this.write(),
98
+ onError: logFailure("since-last-visit", "Saving the visit failed"),
99
+ });
100
+ }
101
+
102
+ /**
103
+ * Starts the visit for an account (`visitScope`), writing the one under way
104
+ * for another account first. Returns the last visit stored for it, read
105
+ * once when the account's visit starts: the baseline the return compares with.
106
+ */
107
+ begin(scope: string): VisitBaseline | null {
108
+ if (scope === this.scope) return this.previous;
109
+ this.flush();
110
+ this.scope = scope;
111
+ this.visit.clear();
112
+ this.saving = false;
113
+ this.previous = this.store.load(scope);
114
+ this.lastPresentAt = this.present ? this.now() : null;
115
+ return this.previous;
116
+ }
117
+
118
+ /** Whether the user is in the app; leaving writes the visit. */
119
+ setPresent(present: boolean): void {
120
+ if (present === this.present) return;
121
+ this.lastPresentAt = this.now();
122
+ this.present = present;
123
+ if (!present) this.flush();
124
+ }
125
+
126
+ /** A price the user has on hand now, for a listing (`instrumentIdentityKey`). */
127
+ observe(key: string, observation: VisitObservation): void {
128
+ if (!this.scope || !this.present) return;
129
+ this.visit.set(key, observation);
130
+ this.lastPresentAt = this.now();
131
+ this.schedule();
132
+ }
133
+
134
+ /** Drops the prices of listings no longer in the user's collections, so the next visit never names them. */
135
+ retain(keys: ReadonlySet<string>): void {
136
+ let changed = false;
137
+ for (const key of this.visit.keys()) {
138
+ if (keys.has(key)) continue;
139
+ this.visit.delete(key);
140
+ changed = true;
141
+ }
142
+ if (changed) this.schedule();
143
+ }
144
+
145
+ /** The return has been compared with the last visit (or had none to compare with): this one may now replace it. */
146
+ allowSaving(): void {
147
+ if (this.saving) return;
148
+ this.saving = true;
149
+ this.schedule();
150
+ }
151
+
152
+ /** Writes the visit now, when it may be written. */
153
+ flush(): void {
154
+ this.saver.cancel();
155
+ this.write();
156
+ }
157
+
158
+ /** Writes what there is and stops: the app is going away. */
159
+ stop(): void {
160
+ this.setPresent(false);
161
+ this.flush();
162
+ }
163
+
164
+ /**
165
+ * Turned off: nothing pending is written, the visit is dropped and every
166
+ * stored one is deleted. The next `begin` starts over.
167
+ */
168
+ forget(): void {
169
+ this.saver.cancel();
170
+ this.pending = false;
171
+ this.visit.clear();
172
+ this.saving = false;
173
+ this.scope = null;
174
+ this.previous = null;
175
+ this.store.clear();
176
+ }
177
+
178
+ private schedule(): void {
179
+ if (!this.saving || !this.scope || this.visit.size === 0 || this.pending) return;
180
+ this.pending = true;
181
+ this.saver.schedule(null);
182
+ }
183
+
184
+ private write(): void {
185
+ this.pending = false;
186
+ if (!this.saving || !this.scope || this.visit.size === 0) return;
187
+ const seenAt = this.present ? this.now() : this.lastPresentAt;
188
+ if (seenAt == null) return;
189
+ this.store.save({ scope: this.scope, seenAt, observations: Object.fromEntries(this.visit) });
190
+ }
191
+ }