Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workspace-selection-store.ts

158 lines6.3 KB

1import type { NavigationState } from "@react-navigation/native";
2import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
3import * as Linking from "expo-linking";
4import { AppState, Dimensions, Platform } from "react-native";
5​
6import { environmentCatalog } from "../../connection/catalog";
7import { deriveLayout } from "../../lib/layout";
8import {
9 NATIVE_METRICS_TIMEOUT_MS,
10 nativeWorkspaceColumnsSupportedFor,
11} from "../../native/NativeWorkspaceColumns";
12import {
13 currentNativeLayoutMetrics,
14 firstNativeLayoutMetrics,
15} from "../../native/native-layout-metrics";
16import { loadPreferences, savePreferencesPatch } from "../../persistence/imperative";
17import { rootStackState, type RootStackNavigation } from "../../lib/root-stack-reset";
18import { workspaceRoutesOf } from "../layout/workspace-overlay-routes";
19import type { WorkspaceSelections } from "../../persistence/mobile-preferences";
20import { appAtomRegistry } from "../../state/atom-registry";
21import { environmentPresentations } from "../../state/presentation";
22import { environmentThreadShells, threadEnvironment } from "../../state/threads";
23import {
24 rememberedSettingsPage,
25 workspaceSelectionsIn,
26 type WorkspaceSelectionCheck,
27} from "./workspace-tab-navigation";
28​
29// Only iOS columns reopen a remembered page; Android always opens a tab on its list.
30const REMEMBERS = Platform.OS === "ios";
31​
32// Read synchronously when a tab opens, so it lives in memory and is saved when the app leaves
33// the foreground rather than on every chat switch.
34let selections: WorkspaceSelections = {};
35let saved = selections;
36let hydration: Promise<void> | null = null;
37​
38function save() {
39 const writing = selections;
40 if (saved === writing) return;
41 // Marked saved only once written, so a failed write is retried on the next background.
42 void savePreferencesPatch({ workspaceSelections: writing })
43 .then(() => {
44 saved = writing;
45 })
46 .catch(() => undefined);
48​
49// Route keys only name routes of the session that wrote them; a saved one would make a tab rebuild
50// its page under a stale key, which UIKit animates as a pop and a push.
51function withoutRouteKeys(saved: WorkspaceSelections | undefined): WorkspaceSelections {
52 const omitKey = <Selection extends { readonly key?: string }>({ key: _, ...rest }: Selection) =>
53 rest;
54 const { threads, pullRequests, settingsKey: _, ...rest } = saved ?? {};
55 return {
56 ...rest,
57 ...(threads ? { threads: omitKey(threads) } : {}),
58 ...(pullRequests ? { pullRequests: omitKey(pullRequests) } : {}),
59 };
61​
62/** Loads the saved selections once; pages visited before it resolves win over saved ones. */
63export function hydrateWorkspaceSelections() {
64 if (!REMEMBERS) return Promise.resolve();
65 hydration ??= loadPreferences()
66 .then((preferences) => {
67 selections = { ...withoutRouteKeys(preferences.workspaceSelections), ...selections };
68 saved = selections;
69 AppState.addEventListener("change", (status) => {
70 if (status !== "active") save();
71 });
72 })
73 .catch(() => undefined);
74 return hydration;
76​
77export function currentWorkspaceSelections() {
78 return selections;
80​
81/**
82 * The navigation container's `onReady` and `onStateChange`: remembers the page each tab is
83 * showing. The initial state, such as a cold start's reopened chat, reaches only `onReady`.
84 */
85export function recordWorkspaceSelections(state: NavigationState | undefined) {
86 if (!REMEMBERS || !state) return;
87 selections = workspaceSelectionsIn(state.routes.slice(0, state.index + 1), selections);
89​
90function environmentRemoved(environmentId: string) {
91 const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom);
92 return (
93 catalog.isReady &&
94 !appAtomRegistry
95 .get(environmentPresentations.presentationsAtom)
96 .has(environmentId as EnvironmentId)
97 );
99​
100/**
101 * A remembered chat is gone once its environment was removed, or once that environment's
102 * snapshot has loaded without it. Before it loads there is nothing to contradict it.
103 */
104export const workspaceSelectionCheck: WorkspaceSelectionCheck = {
105 thread: (selection) => {
106 if (environmentRemoved(selection.environmentId)) return false;
107 const environmentId = selection.environmentId as EnvironmentId;
108 if (!appAtomRegistry.get(threadEnvironment.snapshotAtom(environmentId))) return true;
109 return appAtomRegistry
110 .get(environmentThreadShells.environmentThreadIndexAtom(environmentId))
111 .has(selection.threadId as ThreadId);
112 },
113 pullRequest: (selection) => !environmentRemoved(selection.environmentId),
114};
115​
116/** Whether the window lays the workspace out in columns, by the rule the layout itself uses. */
117export function workspaceHasColumns() {
118 const metrics = currentNativeLayoutMetrics();
119 const { width, height } = metrics ?? Dimensions.get("window");
120 return deriveLayout({
121 width,
122 height,
123 nativeMetrics: metrics,
124 nativeWorkspace: nativeWorkspaceColumnsSupportedFor(metrics),
125 }).usesSplitView;
127​
128/** The Settings page a bare `settings` link opens beside the list when there are columns. */
129export function settingsLinkPage() {
130 return REMEMBERS && workspaceHasColumns() ? rememberedSettingsPage(selections) : undefined;
132​
133/**
134 * Where a cold start without a link opens. A window that starts with columns reopens the last
135 * chat beside the list instead of an empty detail column; a compact window opens on the list.
136 * It waits for the first layout metrics as long as the workspace itself does.
137 */
138export async function launchWorkspaceURL(): Promise<string | null> {
139 if (!REMEMBERS) return null;
140 await Promise.all([
141 hydrateWorkspaceSelections(),
142 firstNativeLayoutMetrics(NATIVE_METRICS_TIMEOUT_MS),
143 ]);
144 const thread = selections.threads;
145 if (!thread || !workspaceHasColumns() || !workspaceSelectionCheck.thread(thread)) return null;
146 return Linking.createURL(
147 `threads/${encodeURIComponent(thread.environmentId)}/${encodeURIComponent(thread.threadId)}`,
148 );
150​
151/** Whether the workspace shows its first detail page, directly above its list. */
152export function firstWorkspaceDetailOpen(navigation: RootStackNavigation) {
153 const state = rootStackState(navigation);
154 if (!state) return false;
155 const { workspace, overlays } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));
156 const list = (name: string | undefined) => name === "Home" || name === "Settings";
157 return overlays.length === 0 && !list(workspace.at(-1)?.name) && list(workspace.at(-2)?.name);