@@ -3,8 +3,8 @@ import { installComposerAttachmentUploads } from "./state/composer-attachment-up
33import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery" ;
44import * as Linking from "expo-linking" ;
55import * as SplashScreen from "expo-splash-screen" ;
6- import { requireNativeModule } from "expo" ;
7- import { useEffect , useState } from "react" ;
6+ import { requireNativeModule , requireOptionalNativeModule } from "expo" ;
7+ import { useCallback , useEffect , useMemo , useState } from "react" ;
88import { Platform , StatusBar } from "react-native" ;
99import { GestureHandlerRootView } from "react-native-gesture-handler" ;
1010import { KeyboardProvider } from "react-native-keyboard-controller" ;
@@ -15,8 +15,9 @@ import {
1515 createStaticNavigation ,
1616 getActionFromState ,
1717 getStateFromPath ,
18+ NavigationIndependentTree ,
1819 type NavigationAction ,
19- type NavigationState ,
20+ type NavigationContainerRef ,
2021} from "@react-navigation/native" ;
2122import { pipe } from "effect/Function" ;
2223import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth" ;
@@ -86,11 +87,24 @@ import {
8687} from "./features/layout/workspace/workspace-selection-store" ;
8788import { workspaceDetailLinkAction } from "./features/layout/workspace/workspace-detail-selection" ;
8889import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics" ;
90+ import { NativeWindowObserver } from "./native/NativeWindowObserver" ;
91+ import {
92+ activateAppWindow ,
93+ allocateAppWindowId ,
94+ AppWindowContext ,
95+ appWindowCount ,
96+ closeAppWindow ,
97+ subscribeAppWindows ,
98+ useAppWindowId ,
99+ type AppWindowId ,
100+ } from "./lib/appWindows" ;
89101import {
90102 attachRootNavigation ,
91103 flushRootNavigationQueue ,
104+ isRootNavigationWindow ,
92105 linkToRootPath ,
93106 rootNavigationRef ,
107+ rootNavigationRoutes ,
94108} from "./lib/rootNavigation" ;
95109import { pruneNewTaskFlowStates } from "./features/threads/new-task-flow-state" ;
96110import { pruneNewTaskBranchCheckouts } from "./features/threads/NewTaskDraftRouteScreen" ;
@@ -123,6 +137,16 @@ function getAppStateFromPath(path: string, options: Parameters<typeof getStateFr
123137 ) ;
124138}
125139
140+ // A link that launched the app opens in its first window. A window opened later starts where the
141+ // app remembers; Android's replacement activity still reads the link that started it.
142+ let launchLinkTaken = false ;
143+
144+ async function initialWindowURL ( ) {
145+ const readsLaunchLink = ! launchLinkTaken || Platform . OS !== "ios" ;
146+ launchLinkTaken = true ;
147+ return ( readsLaunchLink ? await Linking . getInitialURL ( ) : null ) ?? ( await launchWorkspaceURL ( ) ) ;
148+ }
149+
126150const appLinking = {
127151 prefixes : [
128152 Linking . createURL ( "/" ) ,
@@ -133,7 +157,7 @@ const appLinking = {
133157 ] ,
134158 config : { initialRouteName : "Home" } ,
135159 filter : ( url : string ) => shouldHandleAppLink ( url , hasCloudPublicConfig ( ) ) ,
136- getInitialURL : async ( ) => ( await Linking . getInitialURL ( ) ) ?? ( await launchWorkspaceURL ( ) ) ,
160+ getInitialURL : initialWindowURL ,
137161 getActionFromState : (
138162 state : Parameters < typeof getActionFromState > [ 0 ] ,
139163 options : Parameters < typeof getActionFromState > [ 1 ] ,
@@ -158,26 +182,58 @@ function linkToAppPath(href: string): void {
158182 linkToRootPath ( href , appLinkAction ) ;
159183}
160184
185+ /** Every window's container hears an opened link; it belongs to the window in use. */
186+ function windowLinking ( windowId : AppWindowId ) {
187+ return {
188+ ...appLinking ,
189+ subscribe : ( listener : ( url : string ) => void ) => {
190+ const subscription = Linking . addEventListener ( "url" , ( { url } ) => {
191+ if ( isRootNavigationWindow ( windowId ) ) listener ( url ) ;
192+ } ) ;
193+ return ( ) => subscription . remove ( ) ;
194+ } ,
195+ } ;
196+ }
197+
161198const Navigation = createStaticNavigation ( RootStack ) ;
162199
163- function handleNavigationStateChange ( state : NavigationState | undefined ) : void {
200+ /**
201+ * Runs when any window navigates and when another window comes into use. The app's services
202+ * follow the window in use, so they read its state whichever window changed.
203+ */
204+ function handleNavigationStateChange ( ) : void {
205+ // A window that is still mounting reports once its container is ready.
206+ if ( ! rootNavigationRef . isReady ( ) ) return ;
207+ const state = rootNavigationRef . getRootState ( ) ;
164208 recordWorkspaceSelections ( state ) ;
165209 presentPendingIncomingShare ( ) ;
166210 resolvePendingNewTaskPromptLink ( state ) ;
167211 resolvePendingThreadPromptLink ( state ) ;
168212 if ( ! state ) return ;
169213 setAgentNotificationPathname ( workspaceLocationFromState ( state ) . pathname ) ;
170214 recordAppShortcutNavigationState ( state ) ;
171- pruneNewTaskFlowStates ( state ) ;
172- pruneNewTaskBranchCheckouts ( state ) ;
173- pruneIncomingShareImports ( state ) ;
215+ // A draft is live while any window still has its route.
216+ const routes = rootNavigationRoutes ( ) ;
217+ pruneNewTaskFlowStates ( routes ) ;
218+ pruneNewTaskBranchCheckouts ( routes ) ;
219+ pruneIncomingShareImports ( routes ) ;
174220}
175221
176222function handleNavigationReady ( ) : void {
177- handleNavigationStateChange ( rootNavigationRef . getRootState ( ) ) ;
223+ handleNavigationStateChange ( ) ;
178224 flushRootNavigationQueue ( ) ;
179225}
180226
227+ const nativeControls = requireOptionalNativeModule < {
228+ readonly revealWindows ?: ( ) => Promise < void > ;
229+ } > ( "T3NativeControls" ) ;
230+
231+ function hideSplashScreen ( ) : void {
232+ void SplashScreen . hide ( ) ;
233+ // expo-splash-screen hides the launch screen of the newest window only.
234+ if ( appWindowCount ( ) > 1 ) void nativeControls ?. revealWindows ?.( ) . catch ( ( ) => undefined ) ;
235+ }
236+
181237declare const module : { readonly hot ?: FoundationHotModule } | undefined ;
182238
183239const appServiceDisposers = [
@@ -199,6 +255,7 @@ const appServiceDisposers = [
199255 installAppShortcuts ( linkToAppPath ) ,
200256 installAppUpdateChecks ( ) ,
201257 installShowcaseCapture ( rootPathnameFromState ) ,
258+ subscribeAppWindows ( handleNavigationStateChange ) ,
202259] ;
203260disposeOnFoundationReplace ( typeof module === "undefined" ? undefined : module . hot , ( ) => {
204261 for ( const dispose of appServiceDisposers ) dispose ( ) ;
@@ -224,27 +281,44 @@ function SplashScreenCoordinator() {
224281 const canHide = isReady && ( shellCachesRead || waitEnded ) ;
225282 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once preferences and cached shells have loaded
226283 useEffect ( ( ) => {
227- if ( canHide ) void SplashScreen . hide ( ) ;
284+ if ( canHide ) hideSplashScreen ( ) ;
228285 } , [ canHide ] ) ;
229286
230287 return null ;
231288}
232289
290+ // iOS mounts this once per window, on one JS runtime: see lib/appWindows.
233291export default function App ( ) {
292+ const [ windowId ] = useState ( allocateAppWindowId ) ;
234293 return (
235- < RegistryContext . Provider value = { appAtomRegistry } >
236- < CloudAuthProvider >
237- < AppearancePreferencesProvider >
238- < AppContent />
239- </ AppearancePreferencesProvider >
240- </ CloudAuthProvider >
241- </ RegistryContext . Provider >
294+ < AppWindowContext value = { windowId } >
295+ < RegistryContext . Provider value = { appAtomRegistry } >
296+ < CloudAuthProvider >
297+ < AppearancePreferencesProvider >
298+ < AppContent />
299+ </ AppearancePreferencesProvider >
300+ </ CloudAuthProvider >
301+ </ RegistryContext . Provider >
302+ </ AppWindowContext >
242303 ) ;
243304}
244305
245306function AppContent ( ) {
307+ const windowId = useAppWindowId ( ) ;
246308 const { themeAppearance } = useAppearancePreferences ( ) ;
247309 const navigationTheme = useMobileNavigationTheme ( ) ;
310+ const linking = useMemo ( ( ) => windowLinking ( windowId ) , [ windowId ] ) ;
311+ const attachNavigation = useCallback (
312+ ( navigation : NavigationContainerRef < ReactNavigation . RootParamList > | null ) =>
313+ attachRootNavigation ( windowId , navigation ) ,
314+ [ windowId ] ,
315+ ) ;
316+
317+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this root's window with the store the app's services read outside React; a new window opens in use
318+ useEffect ( ( ) => {
319+ activateAppWindow ( windowId ) ;
320+ return ( ) => closeAppWindow ( windowId ) ;
321+ } , [ windowId ] ) ;
248322
249323 // 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
250324 useEffect ( ( ) => {
@@ -257,6 +331,11 @@ function AppContent() {
257331 return (
258332 < >
259333 < SplashScreenCoordinator />
334+ < NativeWindowObserver
335+ onChange = { ( state ) =>
336+ state === "active" ? activateAppWindow ( windowId ) : closeAppWindow ( windowId )
337+ }
338+ />
260339 < SubscriptionUsageCoordinator />
261340 < GestureHandlerRootView className = "flex-1" >
262341 < KeyboardProvider statusBarTranslucent >
@@ -265,13 +344,16 @@ function AppContent() {
265344 { /* native-stack needs the theme's dark flag to select dark native headers. */ }
266345 < GlobalVoiceInputControl >
267346 < NativeLayoutMetricsProvider >
268- < Navigation
269- ref = { attachRootNavigation }
270- linking = { appLinking }
271- onReady = { handleNavigationReady }
272- theme = { navigationTheme }
273- onStateChange = { handleNavigationStateChange }
274- />
347+ { /* Each window's root has a container; they are not nested, and each handles links. */ }
348+ < NavigationIndependentTree >
349+ < Navigation
350+ ref = { attachNavigation }
351+ linking = { linking }
352+ onReady = { handleNavigationReady }
353+ theme = { navigationTheme }
354+ onStateChange = { handleNavigationStateChange }
355+ />
356+ </ NavigationIndependentTree >
275357 < Dialog . Host />
276358 < ThreadArrangementHost />
277359 < ProjectChipIconRasterizer />
0 commit comments