Open History to see the last commit
1import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";
3import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
4import { Atom } from "effect/reactivity";
5
6import { scopedProjectKey } from "../../lib/scopedEntities";
7import { appAtomRegistry } from "../../state/atom-registry";
8import { isNewTaskDraftKey } from "../../state/new-task-draft-key";
9import {
10 draftRouteIdentity,
11 isDraftThreadRoute,
12 type NewTaskDraftRouteParams,
13} from "./thread-route-state";
14
15/** The flow a provider serves while no draft route is on the stack. */
16export const INACTIVE_FLOW_KEY = "inactive";
17
18/** The flow key for a draft Thread route: its key plus the draft it opened. */
19export function newTaskFlowKey(route: {
20 readonly key: string;
21 readonly params?: object;
22}): string | undefined {
23 const draft = (route.params as { draft?: NewTaskDraftRouteParams } | undefined)?.draft;
24 return draft ? `${route.key}:${draftRouteIdentity(draft)}` : undefined;
25}
26
27export interface NewTaskFlowState {
28 readonly environmentId: EnvironmentId | null;
29 readonly projectKey: string | null;
30 readonly draftKey: string | null;
31 readonly submitting: boolean;
32 readonly expandedProvider: string | null;
33}
34
35export const INITIAL_NEW_TASK_FLOW_STATE: NewTaskFlowState = {
36 environmentId: null,
37 projectKey: null,
38 draftKey: null,
39 submitting: false,
40 expandedProvider: null,
41};
42
43// Every draft route on the stack keeps its flow, not just the one the provider
44// currently serves: a draft Thread pushed above draft A must not drop A's
45// selection. Entries live exactly as long as their route (see prune below).
46const flowStatesAtom = Atom.make<Readonly<Record<string, NewTaskFlowState>>>({}).pipe(
47 Atom.keepAlive,
48 Atom.withLabel("mobile:new-task-flows"),
49);
50
51export const newTaskFlowStateAtom = Atom.family((flowKey: string) =>
52 Atom.make((get) => get(flowStatesAtom)[flowKey] ?? INITIAL_NEW_TASK_FLOW_STATE).pipe(
53 Atom.withLabel("mobile:new-task-flow"),
54 ),
55);
56
57export function readNewTaskFlowState(flowKey: string): NewTaskFlowState {
58 return appAtomRegistry.get(flowStatesAtom)[flowKey] ?? INITIAL_NEW_TASK_FLOW_STATE;
59}
60
61export function updateNewTaskFlowState(flowKey: string, patch: Partial<NewTaskFlowState>): void {
62 const flows = appAtomRegistry.get(flowStatesAtom);
63 appAtomRegistry.set(flowStatesAtom, {
64 ...flows,
65 [flowKey]: { ...(flows[flowKey] ?? INITIAL_NEW_TASK_FLOW_STATE), ...patch },
66 });
67}
68
69/**
70 * What a draft route's `draftId` means for a flow that has not bound a draft
71 * yet. Drafts hydrate from disk and projects arrive with the shell snapshot,
72 * so on a cold launch or deep link the answer can be "pending" for a while.
73 */
74export type RouteDraftResolution =
75 | { readonly kind: "none" }
76 | { readonly kind: "pending" }
77 | { readonly kind: "missing" }
78 | { readonly kind: "open"; readonly flow: NewTaskFlowState };
79
80export function resolveRouteDraft(input: {
81 readonly flow: NewTaskFlowState;
82 readonly routeDraftId: string | undefined;
83 readonly draftsLoaded: boolean;
84 readonly stamp:
85 | { readonly environmentId: EnvironmentId; readonly projectId: ProjectId }
86 | undefined;
87 readonly projects: ReadonlyArray<{
88 readonly environmentId: EnvironmentId;
89 readonly id: ProjectId;
90 }>;
91 /** See `stampedEnvironmentProjectsLoading`. */
92 readonly stampedEnvironmentLoading: boolean;
93}): RouteDraftResolution {
94 const { routeDraftId, stamp } = input;
95 if (routeDraftId === undefined || input.flow.draftKey !== null) return { kind: "none" };
96 if (!input.draftsLoaded) return { kind: "pending" };
97 if (!isNewTaskDraftKey(routeDraftId) || stamp === undefined) return { kind: "missing" };
98 // The stamped project must be loaded: the composer falls back to the
99 // environment's first project otherwise, and the draft would be sent
100 // somewhere the user never chose.
101 const loaded = input.projects.some(
102 (project) => project.environmentId === stamp.environmentId && project.id === stamp.projectId,
103 );
104 if (!loaded) return input.stampedEnvironmentLoading ? { kind: "pending" } : { kind: "missing" };
105 return {
106 kind: "open",
107 flow: {
108 ...input.flow,
109 environmentId: stamp.environmentId,
110 projectKey: scopedProjectKey(stamp.environmentId, stamp.projectId),
111 draftKey: routeDraftId,
112 },
113 };
114}
115
116/**
117 * Whether the stamped environment may still deliver its project list. An
118 * unknown, offline, or failed environment is settled, so a project it lacks
119 * sends the route back to the picker. Mirrors `threadRouteIsHydrating`.
120 */
121export function stampedEnvironmentProjectsLoading(input: {
122 readonly connectionsReady: boolean;
123 readonly connectionState: EnvironmentConnectionPhase | null;
124 readonly shellCacheRead: boolean;
125 readonly shellStatus: EnvironmentShellStatus;
126 readonly shellHasError: boolean;
127}): boolean {
128 if (input.shellHasError) return false;
129 if (!input.connectionsReady) return true;
130 if (input.connectionState === null) return false;
131 if (!input.shellCacheRead) return true;
132 // Only a first attempt is worth waiting out; a reconnecting environment's
133 // retries leave its shell synchronizing.
134 if (input.connectionState === "connecting") return true;
135 if (input.connectionState !== "connected") return false;
136 return input.shellStatus === "synchronizing" || input.shellStatus === "empty";
137}
138
139interface NavigationRoutes {
140 readonly routes: ReadonlyArray<{
141 readonly key: string;
142 readonly name: string;
143 readonly params?: object;
144 }>;
145}
146
147/** Flow keys of the draft routes on the stack. */
148export function liveNewTaskFlowKeys(state: NavigationRoutes): ReadonlySet<string> {
149 return new Set(
150 state.routes.flatMap((route) => {
151 const flowKey = isDraftThreadRoute(route) ? newTaskFlowKey(route) : undefined;
152 return flowKey === undefined ? [] : [flowKey];
153 }),
154 );
155}
156
157/**
158 * Drops the flow of every draft route that left the stack: popped (discarded)
159 * or promoted to a live thread, whose params no longer carry the draft.
160 */
161export function pruneNewTaskFlowStates(state: NavigationRoutes): void {
162 const flows = appAtomRegistry.get(flowStatesAtom);
163 const live = liveNewTaskFlowKeys(state);
164 const kept = Object.entries(flows).filter(([flowKey]) => live.has(flowKey));
165 if (kept.length === Object.keys(flows).length) return;
166 appAtomRegistry.set(flowStatesAtom, Object.fromEntries(kept));
167}