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

appShortcutsRuntime.ts

149 lines5.3 KB

1import * as QuickActions from "expo-quick-actions";
2import { Platform } from "react-native";
3import type { NavigationState } from "@react-navigation/native";
4import type { ScopedThreadRef } from "@t3tools/contracts";
5import { Atom } from "effect/reactivity";
6​
7import {
8 loadRecentThreadShortcuts,
9 saveRecentThreadShortcuts,
10 type RecentThreadShortcut,
11} from "../../persistence/imperative";
12import { appAtomRegistry } from "../../state/atom-registry";
13import { environmentThreadShells } from "../../state/threads";
14import {
15 activeThreadRef,
16 buildShortcutActions,
17 shortcutHref,
18 withRecentThreadShortcut,
19} from "./appShortcuts";
20​
21export interface RecentThreadShortcutsDependencies {
22 readonly load: () => Promise<ReadonlyArray<RecentThreadShortcut>>;
23 readonly save: (recents: ReadonlyArray<RecentThreadShortcut>) => Promise<void>;
24 readonly publish: (recents: ReadonlyArray<RecentThreadShortcut>) => Promise<void>;
26​
27/**
28 * Keeps the launcher's recent-thread list. Recording waits for the persisted
29 * list so the first thread opened after a cold start cannot clobber older
30 * entries, and a failed load never persists its empty fallback over valid
31 * history until a real thread open makes the in-memory list the new truth.
32 */
33export function createRecentThreadShortcuts(dependencies: RecentThreadShortcutsDependencies) {
34 let recents: ReadonlyArray<RecentThreadShortcut> | null = null;
35 let persistable = false;
36 let active: RecentThreadShortcut | null = null;
37 // Serialize saves so older lists cannot overwrite newer ones.
38 let saveQueue: Promise<unknown> = Promise.resolve();
39​
40 const commit = (next: ReadonlyArray<RecentThreadShortcut>) => {
41 recents = next;
42 if (persistable) {
43 saveQueue = saveQueue.then(
44 () =>
45 dependencies.save(next).catch((error: unknown) => {
46 console.warn("[app-shortcuts] failed to persist recent threads", error);
47 }),
48 () => undefined,
49 );
50 }
51 void dependencies.publish(next).catch((error: unknown) => {
52 console.warn("[app-shortcuts] failed to update launcher shortcuts", error);
53 });
54 };
55​
56 const withActive = (list: ReadonlyArray<RecentThreadShortcut>) => {
57 if (active === null) return list;
58 const next = withRecentThreadShortcut(list, active);
59 if (next !== list) persistable = true;
60 return next;
61 };
62​
63 const loaded = dependencies.load().then(
64 (threads) => {
65 persistable = true;
66 commit(withActive(threads));
67 },
68 (error: unknown) => {
69 console.warn("[app-shortcuts] failed to load recent threads", error);
70 commit(withActive([]));
71 },
72 );
73​
74 return {
75 loaded,
76 /** Resolves once every save issued so far has finished. */
77 saved: () => saveQueue,
78 recordActiveThread(next: RecentThreadShortcut | null): void {
79 active = next;
80 if (recents === null || next === null) return;
81 const updated = withActive(recents);
82 if (updated !== recents) commit(updated);
83 },
84 };
86​
87const activeThreadRefAtom = Atom.make<ScopedThreadRef | null>(null).pipe(
88 Atom.keepAlive,
89 Atom.withLabel("mobile:app-shortcuts-active-thread-ref"),
90);
91​
92const activeThreadShortcutAtom = Atom.make((get): RecentThreadShortcut | null => {
93 const ref = get(activeThreadRefAtom);
94 if (ref === null) return null;
95 const title = get(environmentThreadShells.threadShellAtom(ref))?.title ?? "";
96 return { environmentId: ref.environmentId, threadId: ref.threadId, title };
97}).pipe(
98 Atom.withEquality(
99 (left: RecentThreadShortcut | null, right: RecentThreadShortcut | null) =>
100 left === right ||
101 (left !== null &&
102 right !== null &&
103 left.environmentId === right.environmentId &&
104 left.threadId === right.threadId &&
105 left.title === right.title),
106 ),
107);
108​
109/** Wired to the root navigation container's state changes. */
110export function recordAppShortcutNavigationState(state: NavigationState): void {
111 // Launcher shortcuts are Android-only; iOS never subscribes to thread shells.
112 if (Platform.OS !== "android") return;
113 const next = activeThreadRef(state);
114 const current = appAtomRegistry.get(activeThreadRefAtom);
115 if (next?.environmentId === current?.environmentId && next?.threadId === current?.threadId) {
116 return;
117 }
118 appAtomRegistry.set(activeThreadRefAtom, next);
120​
121/**
122 * App-lifetime quick actions. `navigate` must queue until navigation is ready:
123 * a cold-start shortcut arrives as the launch action, and pushing it over the
124 * initial Home route makes back return home instead of exiting the app.
125 */
126export function installAppShortcuts(navigate: (href: string) => void): () => void {
127 const initialHref = QuickActions.initial ? shortcutHref(QuickActions.initial) : null;
128 if (initialHref !== null) navigate(initialHref);
129 const subscription = QuickActions.addListener((action) => {
130 const href = shortcutHref(action);
131 if (href !== null) navigate(href);
132 });
133 if (Platform.OS !== "android") return () => subscription.remove();
134​
135 const recents = createRecentThreadShortcuts({
136 load: loadRecentThreadShortcuts,
137 save: saveRecentThreadShortcuts,
138 publish: (list) => QuickActions.setItems(buildShortcutActions(list)),
139 });
140 const unsubscribe = appAtomRegistry.subscribe(
141 activeThreadShortcutAtom,
142 (active) => recents.recordActiveThread(active),
143 { immediate: true },
144 );
145 return () => {
146 subscription.remove();
147 unsubscribe();
148 };