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

App.tsx

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