Skip to content

Commit 90a22c8

Browse files
synistrclaude
andcommitted
feat(mobile): multiple windows on iPad and iPhone Duo
The app could only ever have one window: Expo's template declares the scene manifest with UIApplicationSupportsMultipleScenes off, so iPadOS and iPhone Duo never offered a second one. A config plugin turns the key on. UIKit then mounts the app again for every window scene, each with a React root of its own on the one JS runtime, so the app-wide singletons that assumed a single root now follow the window in use (lib/appWindows, fed by a native view that reports when its window becomes key, its scene activates or disconnects): - rootNavigationRef points at the active window's container, so notification taps, quick actions and other services navigate the window the person used last; an opened link is handled by that window only, and the launch link opens in the first window only. - Draft flows, branch checkouts and share imports are pruned against the routes of every window, so navigating in one window no longer drops a draft open in another. - Layout metrics read outside React are the active window's; the thread arrangement sheet opens in the window that asked for it. - A closed window is released: Expo mirrors the newest window onto the app delegate, which kept it and its React tree alive. Windows that connect together all lose their launch screen, which expo-splash-screen only hides for the newest. Capture builds keep a single full-screen window. Co-Authored-By: Claude Fable 5.2 <[email protected]>
1 parent fd8e386 commit 90a22c8

14 files changed

Lines changed: 419 additions & 48 deletions

‎apps/mobile/app.config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,10 @@ const config: ExpoConfig = {
447447
},
448448
],
449449
"./plugins/withIosCocoaPodsUuidCache.cjs",
450+
// Capture builds stay full screen with one window, so every shot is of the same scene.
451+
...(process.env.T3_SHOWCASE_CAPTURE_BUILD === "1"
452+
? []
453+
: ["./plugins/withIosMultipleWindows.cjs"]),
450454
// Compile out the unused pedometer to avoid an iOS motion purpose string.
451455
["expo-sensors", { motionPermission: false }],
452456
// Mods run in reverse order; expo-widgets must create and wipe the target before assets are added.

‎apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,11 @@ public final class T3NativeControlsModule: Module {
4949
Events("onMetricsChange")
5050
}
5151

52+
View(T3WindowStateView.self) {
53+
ViewName("WindowState")
54+
Events("onWindowStateChange")
55+
}
56+
5257
View(T3ScrollEdgeBleedView.self) {
5358
ViewName("ScrollEdgeBleed")
5459
}
@@ -200,6 +205,22 @@ public final class T3NativeControlsModule: Module {
200205
return bounds.width > bounds.height ? "landscape" : "portrait"
201206
}
202207

208+
// expo-splash-screen covers each window's root view with the launch screen but keeps, and
209+
// hides, only the newest. Windows that connect together would leave the others covered.
210+
@JS
211+
@MainActor
212+
func revealWindows() async {
213+
for case let windowScene as UIWindowScene in UIApplication.shared.connectedScenes {
214+
for window in windowScene.windows {
215+
guard let rootView = window.rootViewController?.view,
216+
rootView.responds(to: NSSelectorFromString("loadingView")),
217+
let launchScreen = rootView.value(forKey: "loadingView") as? UIView
218+
else { continue }
219+
launchScreen.removeFromSuperview()
220+
}
221+
}
222+
}
223+
203224
@JS
204225
@MainActor
205226
func isProtectedDataAvailable() async -> Bool {
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import ExpoModulesCore
2+
import UIKit
3+
4+
/// Tells a React root about the window it is in. UIKit mounts the app again for every window
5+
/// scene, and app-wide work such as an opened link belongs to the window used last.
6+
final class T3WindowStateView: ExpoView {
7+
let onWindowStateChange = EventDispatcher()
8+
private weak var observedWindow: UIWindow?
9+
10+
required init(appContext: AppContext? = nil) {
11+
super.init(appContext: appContext)
12+
isUserInteractionEnabled = false
13+
}
14+
15+
deinit {
16+
NotificationCenter.default.removeObserver(self)
17+
}
18+
19+
override func didMoveToWindow() {
20+
super.didMoveToWindow()
21+
let center = NotificationCenter.default
22+
center.removeObserver(self)
23+
guard let window, let scene = window.windowScene else {
24+
// A root view can outlive its window; it has nothing left to show.
25+
if observedWindow != nil { report("closed") }
26+
observedWindow = nil
27+
return
28+
}
29+
observedWindow = window
30+
// Side by side, both scenes are active; the key window is the one last touched.
31+
center.addObserver(self, selector: #selector(windowDidBecomeActive), name: UIWindow.didBecomeKeyNotification, object: window)
32+
center.addObserver(self, selector: #selector(windowDidBecomeActive), name: UIScene.didActivateNotification, object: scene)
33+
center.addObserver(self, selector: #selector(sceneDidDisconnect), name: UIScene.didDisconnectNotification, object: scene)
34+
if window.isKeyWindow { report("active") }
35+
}
36+
37+
@objc private func windowDidBecomeActive() {
38+
report("active")
39+
}
40+
41+
@objc private func sceneDidDisconnect() {
42+
report("closed")
43+
releaseAppDelegateWindow()
44+
}
45+
46+
private func report(_ state: String) {
47+
onWindowStateChange(["state": state])
48+
}
49+
50+
/// Expo mirrors the newest window onto the app delegate. Left there after its scene closed, it
51+
/// would keep the window, its root view and the React tree mounted in it alive.
52+
private func releaseAppDelegateWindow() {
53+
guard let closed = observedWindow,
54+
let delegate = UIApplication.shared.delegate as? NSObject,
55+
delegate.responds(to: NSSelectorFromString("window")),
56+
delegate.responds(to: NSSelectorFromString("setWindow:")),
57+
(delegate.value(forKey: "window") as? UIWindow) === closed
58+
else { return }
59+
let remaining = UIApplication.shared.connectedScenes
60+
.compactMap { ($0 as? UIWindowScene)?.keyWindow }
61+
.first { $0 !== closed }
62+
delegate.setValue(remaining, forKey: "window")
63+
}
64+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const { withInfoPlist } = require("expo/config-plugins");
2+
3+
// UIKit opens a second window (iPad, iPhone Duo) only for apps that declare support. Expo's
4+
// template writes the scene manifest with it off; the rest of the manifest stays as generated.
5+
module.exports = function withIosMultipleWindows(config) {
6+
return withInfoPlist(config, (nextConfig) => {
7+
nextConfig.modResults.UIApplicationSceneManifest = {
8+
...nextConfig.modResults.UIApplicationSceneManifest,
9+
UIApplicationSupportsMultipleScenes: true,
10+
};
11+
return nextConfig;
12+
});
13+
};

‎apps/mobile/src/App.tsx‎

Lines changed: 106 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ import { installComposerAttachmentUploads } from "./state/composer-attachment-up
33
import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery";
44
import * as Linking from "expo-linking";
55
import * 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";
88
import { Platform, StatusBar } from "react-native";
99
import { GestureHandlerRootView } from "react-native-gesture-handler";
1010
import { 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";
2122
import { pipe } from "effect/Function";
2223
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
@@ -86,11 +87,24 @@ import {
8687
} from "./features/layout/workspace/workspace-selection-store";
8788
import { workspaceDetailLinkAction } from "./features/layout/workspace/workspace-detail-selection";
8889
import { 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";
89101
import {
90102
attachRootNavigation,
91103
flushRootNavigationQueue,
104+
isRootNavigationWindow,
92105
linkToRootPath,
93106
rootNavigationRef,
107+
rootNavigationRoutes,
94108
} from "./lib/rootNavigation";
95109
import { pruneNewTaskFlowStates } from "./features/threads/new-task-flow-state";
96110
import { 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+
126150
const 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+
161198
const 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

176222
function 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+
181237
declare const module: { readonly hot?: FoundationHotModule } | undefined;
182238

183239
const appServiceDisposers = [
@@ -199,6 +255,7 @@ const appServiceDisposers = [
199255
installAppShortcuts(linkToAppPath),
200256
installAppUpdateChecks(),
201257
installShowcaseCapture(rootPathnameFromState),
258+
subscribeAppWindows(handleNavigationStateChange),
202259
];
203260
disposeOnFoundationReplace(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.
233291
export 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

245306
function 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 />

‎apps/mobile/src/features/threads/ThreadArrangementSheet.tsx‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context";
1414

1515
import { AppText as Text } from "../../components/ui/AppText";
1616
import { SymbolView } from "../../components/ui/AppSymbol";
17+
import { useAppWindowId } from "../../lib/appWindows";
1718
import { scopedThreadKey } from "../../lib/scopedEntities";
1819
import { deriveThreadArrangementSizing } from "../../lib/layout";
1920
import { environmentServerConfigsAtom } from "../../state/server";
@@ -24,7 +25,7 @@ import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/ol
2425
import {
2526
pendingThreadOrderAtom,
2627
threadDropBusyAtom,
27-
threadArrangementOpenAtom,
28+
threadArrangementWindowAtom,
2829
} from "../../state/thread-order";
2930
import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
3031
import { useThreadListActions } from "../home/useThreadListActions";
@@ -600,8 +601,10 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {
600601
}
601602

602603
export function ThreadArrangementHost() {
603-
const open = useAtomValue(threadArrangementOpenAtom);
604+
const open = useAtomValue(threadArrangementWindowAtom) === useAppWindowId();
604605
return open ? (
605-
<ThreadArrangementSheet onClose={() => appAtomRegistry.set(threadArrangementOpenAtom, false)} />
606+
<ThreadArrangementSheet
607+
onClose={() => appAtomRegistry.set(threadArrangementWindowAtom, null)}
608+
/>
606609
) : null;
607610
}

0 commit comments

Comments
 (0)