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

App.tsx

304 lines11.8 KB

1import { installPermissionUpdateNotice } from "./features/connection/permissionUpdateNotice";
2import { installComposerAttachmentUploads } from "./state/composer-attachment-uploads";
3import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery";
4import * as Linking from "expo-linking";
5import * as SplashScreen from "expo-splash-screen";
6import { requireNativeModule } from "expo";
7import { useEffect, useRef, useState } from "react";
8import { Platform, StatusBar } from "react-native";
9import { GestureHandlerRootView } from "react-native-gesture-handler";
10import { KeyboardProvider } from "react-native-keyboard-controller";
11import { SafeAreaProvider } from "react-native-safe-area-context";
12import {
13 CommonActions,
14 createPathConfigForStaticNavigation,
15 createStaticNavigation,
16 getActionFromState,
17 getStateFromPath,
18 type NavigationAction,
19 type NavigationState,
20} from "@react-navigation/native";
21import { pipe } from "effect/Function";
22import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
23​
24import { RegistryContext, useAtomValue } from "@effect/atom-react";
25import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages";
26import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet";
27import * as Dialog from "./components/ui/Dialog";
28import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
29import { prepareNativeShowcaseCapture } from "./features/showcase/nativeShowcaseScene";
30import { installShowcaseCapture } from "./features/showcase/ShowcaseCaptureCoordinator";
31import {
32 presentPendingIncomingShare,
33 pruneIncomingShareImports,
34 startIncomingShareInbox,
35} from "./features/sharing/IncomingShareProvider";
36import {
37 installAgentNotificationNavigation,
38 setAgentNotificationPathname,
39} from "./features/agent-awareness/notificationNavigation";
40import {
41 installAppShortcuts,
42 recordAppShortcutNavigationState,
43} from "./features/shortcuts/appShortcutsRuntime";
44import {
45 AppearancePreferencesProvider,
46 installAppearanceRuntime,
47 useAppearancePreferences,
48} from "./features/settings/appearance/AppearancePreferencesProvider";
49import { RootStack, rootPathnameFromState, workspaceLocationFromState } from "./Stack";
50import { appAtomRegistry } from "./state/atom-registry";
51import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
52import { environmentThreadShells, threadEnvironment } from "./state/threads";
53import { environmentShell, shellCachesReadAtom } from "./state/shell";
54import { OverlayPortalHost } from "./components/ui/OverlayPortal";
55import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
56import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
57import { takeScheduledTaskNewLink } from "./features/settings/scheduled-task-editor-state";
58import {
59 pairingFormLinkAction,
60 startDevAutoConnect,
61 withoutPairingTarget,
62} from "./features/connection/devAutoConnect";
63import {
64 resolvePendingNewTaskPromptLink,
65 takeNewTaskPromptLink,
66} from "./features/prompt-links/newTaskPromptLink";
67import {
68 resolvePendingThreadPromptLink,
69 takeThreadPromptLink,
70} from "./features/prompt-links/threadPromptLink";
71import {
72 disposeOnFoundationReplace,
73 type FoundationHotModule,
74} from "./lib/foundation-fast-refresh";
75import { useMobileNavigationTheme } from "./lib/useMobileNavigationTheme";
76import { installUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
77import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
78import { installSubscriptionUsageRefresh } from "./widgets/useSubscriptionUsage";
79import { GlobalVoiceInputControl } from "./features/voice-input/GlobalVoiceInputControl";
80import {
81 launchSplashHomeRowsPending,
82 settleLaunchSplashHomeRows,
83 splashCanHide,
84 useLaunchSplashHomeRowsPending,
85} from "./features/home/home-launch-splash";
86import { restoreSettingsLinkState } from "./features/settings/settings-navigation";
87import {
88 hydrateWorkspaceSelections,
89 launchWorkspaceURL,
90 recordWorkspaceSelections,
91 settingsLinkPage,
92} from "./features/layout/workspace/workspace-selection-store";
93import { workspaceDetailLinkAction } from "./features/layout/workspace/workspace-detail-selection";
94import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";
95import {
96 attachRootNavigation,
97 flushRootNavigationQueue,
98 linkToRootPath,
99 rootNavigationRef,
100} from "./lib/rootNavigation";
101import { pruneNewTaskFlowStates } from "./features/threads/new-task-flow-state";
102import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen";
103import { installAppUpdateChecks } from "./features/updates/app-updates";
104​
105import "../global.css";
106​
107if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
108 prepareNativeShowcaseCapture();
110​
111void SplashScreen.preventAutoHideAsync().catch(() => {});
112void hydrateWorkspaceSelections();
113​
114const linkingConfig = {
115 initialRouteName: "Home",
116 screens: createPathConfigForStaticNavigation(RootStack, { initialRouteName: "Home" }) ?? {},
117} as const;
118​
119function getAppStateFromPath(path: string, options: Parameters<typeof getStateFromPath>[1]) {
120 return pipe(
121 getStateFromPath(path, options),
122 (state) => restoreDraftLinkState(state, path),
123 (state) => restoreSettingsLinkState(state, settingsLinkPage()),
124 takeThreadPromptLink,
125 takeNewTaskPromptLink,
126 withoutPairingTarget,
127 startDevAutoConnect,
128 takeScheduledTaskNewLink,
129 );
131​
132const appLinking = {
133 prefixes: [
134 Linking.createURL("/"),
135 "t3code://",
136 "t3code-dev://",
137 "t3code-preview://",
138 DEFAULT_HOSTED_APP_URL,
139 ],
140 config: { initialRouteName: "Home" },
141 filter: (url: string) => shouldHandleAppLink(url, hasCloudPublicConfig()),
142 getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),
143 getActionFromState: (
144 state: Parameters<typeof getActionFromState>[0],
145 options: Parameters<typeof getActionFromState>[1],
146 ): ReturnType<typeof getActionFromState> =>
147 // Our router handles the selection; React Navigation's type only lists its own actions.
148 (workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??
149 pairingFormLinkAction(
150 state,
151 rootNavigationRef.isReady() ? rootNavigationRef.getRootState() : undefined,
152 ) ??
153 getActionFromState(state, options),
154 getStateFromPath: getAppStateFromPath,
155};
156​
157function appLinkAction(href: string): NavigationAction {
158 const state = getAppStateFromPath(href, linkingConfig);
159 if (!state) throw new Error(`Failed to parse the href to a navigation state (${href}).`);
160 return appLinking.getActionFromState(state, linkingConfig) ?? CommonActions.reset(state);
162​
163function linkToAppPath(href: string): void {
164 linkToRootPath(href, appLinkAction);
166​
167const Navigation = createStaticNavigation(RootStack);
168​
169function handleNavigationStateChange(state: NavigationState | undefined): void {
170 recordWorkspaceSelections(state);
171 presentPendingIncomingShare();
172 resolvePendingNewTaskPromptLink(state);
173 resolvePendingThreadPromptLink(state);
174 if (!state) return;
175 // A launch that opens another route has no Home rows for the splash to wait for.
176 if (state.routes[state.index]?.name !== "Home") settleLaunchSplashHomeRows();
177 setAgentNotificationPathname(workspaceLocationFromState(state).pathname);
178 recordAppShortcutNavigationState(state);
179 pruneNewTaskFlowStates(state);
180 pruneNewTaskBranchCheckouts(state);
181 pruneIncomingShareImports(state);
183​
184function handleNavigationReady(): void {
185 handleNavigationStateChange(rootNavigationRef.getRootState());
186 flushRootNavigationQueue();
188​
189declare const module: { readonly hot?: FoundationHotModule } | undefined;
190​
191const appServiceDisposers = [
192 installUiRuntimeMemoryWarningGc(),
193 subscribeComposerDraftModelReconciliation({
194 registry: appAtomRegistry,
195 threadShellAtom: environmentThreadShells.threadShellAtom,
196 threadRefsAtom: environmentThreadShells.threadRefsAtom,
197 shellStateAtom: environmentShell.stateAtom,
198 pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
199 }),
200 installAppearanceRuntime(),
201 installSubscriptionUsageRefresh(),
202 installPermissionUpdateNotice(),
203 installThreadOutboxDelivery(),
204 installComposerAttachmentUploads(),
205 startIncomingShareInbox(),
206 installAgentNotificationNavigation(linkToAppPath),
207 installAppShortcuts(linkToAppPath),
208 installAppUpdateChecks(),
209 installShowcaseCapture(rootPathnameFromState),
210];
211disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.hot, () => {
212 for (const dispose of appServiceDisposers) dispose();
213});
214​
215// Cached shells are local reads that end in a fraction of this time; the limit keeps a failed
216// read, or a list that does not lay out, from holding the splash screen.
217const SPLASH_WAIT_MS = 1_500;
218​
219function SplashScreenCoordinator() {
220 const { isReady } = useAppearancePreferences();
221 const shellCachesRead = useAtomValue(shellCachesReadAtom);
222 const homeRowsPending = useLaunchSplashHomeRowsPending();
223 const [waitEnded, setWaitEnded] = useState(false);
224 const hidden = useRef(false);
225​
226 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the limit on how long the native splash screen waits for cached shells and their rows
227 useEffect(() => {
228 const timer = setTimeout(() => setWaitEnded(true), SPLASH_WAIT_MS);
229 return () => clearTimeout(timer);
230 }, []);
231​
232 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once preferences have loaded and the cached rows are laid out
233 useEffect(() => {
234 const canHide = splashCanHide({
235 preferencesReady: isReady,
236 shellCachesRead,
237 // Home holds the splash in a layout effect of the commit that gives it rows. That can be
238 // this commit, after this render read the store.
239 homeRowsPending: homeRowsPending || launchSplashHomeRowsPending(),
240 waitEnded,
241 });
242 if (!canHide || hidden.current) return;
243 hidden.current = true;
244 settleLaunchSplashHomeRows();
245 void SplashScreen.hide();
246 }, [isReady, shellCachesRead, homeRowsPending, waitEnded]);
247​
248 return null;
250​
251export default function App() {
252 return (
253 <RegistryContext.Provider value={appAtomRegistry}>
254 <CloudAuthProvider>
255 <AppearancePreferencesProvider>
256 <AppContent />
257 </AppearancePreferencesProvider>
258 </CloudAuthProvider>
259 </RegistryContext.Provider>
260 );
262​
263function AppContent() {
264 const { themeAppearance } = useAppearancePreferences();
265 const navigationTheme = useMobileNavigationTheme();
266​
267 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- matches the Android navigation bar to the app theme, as StatusBar does for the status bar
268 useEffect(() => {
269 if (Platform.OS !== "android") return;
270 void requireNativeModule<{ setNavigationBarStyle(light: boolean): Promise<void> }>(
271 "T3NativeControls",
272 ).setNavigationBarStyle(themeAppearance === "light");
273 }, [themeAppearance]);
274​
275 return (
276 <>
277 <SplashScreenCoordinator />
278 <SubscriptionUsageCoordinator />
279 <GestureHandlerRootView className="flex-1">
280 <KeyboardProvider statusBarTranslucent>
281 <SafeAreaProvider>
282 <StatusBar barStyle={themeAppearance === "dark" ? "light-content" : "dark-content"} />
283 {/* native-stack needs the theme's dark flag to select dark native headers. */}
284 <GlobalVoiceInputControl>
285 <NativeLayoutMetricsProvider>
286 <Navigation
287 ref={attachRootNavigation}
288 linking={appLinking}
289 onReady={handleNavigationReady}
290 theme={navigationTheme}
291 onStateChange={handleNavigationStateChange}
292 />
293 <Dialog.Host />
294 <ThreadArrangementHost />
295 <ProjectChipIconRasterizer />
296 </NativeLayoutMetricsProvider>
297 </GlobalVoiceInputControl>
298 <OverlayPortalHost />
299 </SafeAreaProvider>
300 </KeyboardProvider>
301 </GestureHandlerRootView>
302 </>
303 );