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

useAppShortcuts.ts

135 lines4.4 KB

1import * as QuickActions from "expo-quick-actions";
2import { useEffect, useMemo, useRef, useState } from "react";
3import { Platform } from "react-native";
4import { useLinkTo, type NavigationState } from "@react-navigation/native";
5​
6import {
7 loadRecentThreadShortcuts,
8 saveRecentThreadShortcuts,
9 type RecentThreadShortcut,
10} from "../../persistence/imperative";
11import { useThreadShell } from "../../state/entities";
12import {
13 activeThreadRef,
14 buildShortcutActions,
15 shortcutHref,
16 withRecentThreadShortcut,
17} from "./appShortcuts";
18​
19export function useAppShortcuts(state: NavigationState): void {
20 useShortcutNavigation();
21 useRecentThreadShortcutSync(state);
23​
24function useShortcutNavigation(): void {
25 const linkTo = useLinkTo();
26 const handledInitialAction = useRef(false);
27​
28 useEffect(() => {
29 // Cold start: the tapped shortcut arrives as the launch action, before
30 // any listener can fire. Navigating from here pushes the target over the
31 // initial Home route, so back returns home instead of exiting the app.
32 if (!handledInitialAction.current) {
33 handledInitialAction.current = true;
34 const initialHref = QuickActions.initial ? shortcutHref(QuickActions.initial) : null;
35 if (initialHref !== null) {
36 linkTo(initialHref);
37 }
38 }
39​
40 const subscription = QuickActions.addListener((action) => {
41 const href = shortcutHref(action);
42 if (href !== null) {
43 linkTo(href);
44 }
45 });
46 return () => subscription.remove();
47 }, [linkTo]);
49​
50function useRecentThreadShortcutSync(state: NavigationState): void {
51 // Launcher shortcuts are Android-only. A null ref on iOS keeps this hook
52 // (mounted in the root stack layout) from subscribing the root to the
53 // active thread's shell, which would re-render every screen on each
54 // title/status/session change.
55 const threadRef = useMemo(
56 () => (Platform.OS === "android" ? activeThreadRef(state) : null),
57 [state],
58 );
59 const threadShell = useThreadShell(threadRef);
60 // null until the persisted list loads; recording waits on it so the first
61 // thread opened after a cold start cannot clobber older entries.
62 const [recents, setRecents] = useState<ReadonlyArray<RecentThreadShortcut> | null>(null);
63 // Gates storage writes: a failed load falls back to an empty in-memory
64 // list (so the launcher still gets the "New task" item), but persisting
65 // that fallback would erase valid history over a transient read error.
66 // Real thread opens flip this on — by then the list is the new truth.
67 const persistableRef = useRef(false);
68 // Saves are fire-and-forget; chaining them keeps an older list from
69 // finishing after (and overwriting) a newer one.
70 const saveQueueRef = useRef<Promise<unknown>>(Promise.resolve());
71​
72 useEffect(() => {
73 if (Platform.OS !== "android") {
74 return;
75 }
76​
77 let cancelled = false;
78 void loadRecentThreadShortcuts()
79 .then((threads) => {
80 if (!cancelled) {
81 persistableRef.current = true;
82 setRecents(threads);
83 }
84 })
85 .catch((error) => {
86 console.warn("[app-shortcuts] failed to load recent threads", error);
87 if (!cancelled) {
88 setRecents([]);
89 }
90 });
91 return () => {
92 cancelled = true;
93 };
94 }, []);
95​
96 const loaded = recents !== null;
97 const environmentId = threadRef?.environmentId ?? null;
98 const threadId = threadRef?.threadId ?? null;
99 const title = threadShell?.title ?? "";
100 useEffect(() => {
101 if (!loaded || environmentId === null || threadId === null) {
102 return;
103 }
104​
105 setRecents((current) => {
106 if (current === null) {
107 return current;
108 }
109 const next = withRecentThreadShortcut(current, { environmentId, threadId, title });
110 if (next !== current) {
111 persistableRef.current = true;
112 }
113 return next;
114 });
115 }, [loaded, environmentId, threadId, title]);
116​
117 useEffect(() => {
118 if (recents === null) {
119 return;
120 }
121​
122 if (persistableRef.current) {
123 saveQueueRef.current = saveQueueRef.current.then(
124 () =>
125 saveRecentThreadShortcuts(recents).catch((error) => {
126 console.warn("[app-shortcuts] failed to persist recent threads", error);
127 }),
128 () => undefined,
129 );
130 }
131 void QuickActions.setItems(buildShortcutActions(recents)).catch((error) => {
132 console.warn("[app-shortcuts] failed to update launcher shortcuts", error);
133 });
134 }, [recents]);