@devries-cameron20 / t3code Mirror · read-only / commits / 8c0670b2be
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 18:15 UTC

fix(mobile): one way to select a page, so split view stops pushing (#24742)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 24, 2026 at 22:24 UTC 8c0670b2be8ea315ff790415db2cf76bcae8e0a8
38 files changed +654 -877
apps/mobile/src/App.tsx
+17 -1
@@ -6,7 +6,12 @@ import { StatusBar } from "react-native";
6 import { GestureHandlerRootView } from "react-native-gesture-handler";
7 import { KeyboardProvider } from "react-native-keyboard-controller";
8 import { SafeAreaProvider } from "react-native-safe-area-context";
9 -import { createStaticNavigation, getStateFromPath } from "@react-navigation/native";
9 +import {
10 + createNavigationContainerRef,
11 + createStaticNavigation,
12 + getActionFromState,
13 + getStateFromPath,
14 +} from "@react-navigation/native";
15
16 import { RegistryContext } from "@effect/atom-react";
17 import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages";
@@ -38,6 +43,7 @@ import {
43 recordWorkspaceSelections,
44 settingsLinkPage,
45 } from "./features/workspace/workspace-selection-store";
46 +import { workspaceDetailLinkAction } from "./features/workspace/workspace-detail-selection";
47 import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";
48
49 import "../global.css";
@@ -54,6 +60,13 @@ const appLinking = {
60 config: { initialRouteName: "Home" },
61 filter: shouldHandleAppLink,
62 getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),
63 + getActionFromState: (
64 + state: Parameters<typeof getActionFromState>[0],
65 + options: Parameters<typeof getActionFromState>[1],
66 + ): ReturnType<typeof getActionFromState> =>
67 + // Our router handles the selection; React Navigation's type only lists its own actions.
68 + (workspaceDetailLinkAction(state) as ReturnType<typeof getActionFromState>) ??
69 + getActionFromState(state, options),
70 getStateFromPath: (path: string, options: Parameters<typeof getStateFromPath>[1]) =>
71 restoreSettingsLinkState(
72 restoreDraftLinkState(getStateFromPath(path, options), path),
@@ -62,6 +75,7 @@ const appLinking = {
75 };
76
77 const Navigation = createStaticNavigation(RootStack);
78 +const navigationRef = createNavigationContainerRef();
79
80 function SplashScreenCoordinator() {
81 const { isReady } = useAppearancePreferences();
@@ -116,7 +130,9 @@ function AppContent() {
130 <NativeLayoutMetricsProvider>
131 <IncomingShareProvider>
132 <Navigation
133 + ref={navigationRef}
134 linking={appLinking}
135 + onReady={() => recordWorkspaceSelections(navigationRef.getRootState())}
136 theme={navigationTheme}
137 onStateChange={recordWorkspaceSelections}
138 />
apps/mobile/src/Stack.tsx
+11 -1
@@ -149,6 +149,10 @@ import { nativeHeaderScrollEdgeEffects } from "./native/StackHeader";
149 import { HORIZONTAL_FORM_SHEET_OPTIONS, formSheetDetents } from "./native/sheet-surface";
150 import { useThreadOutboxDrain } from "./state/use-thread-outbox-drain";
151 import { useComposerAttachmentUploadWorker } from "./state/composer-attachment-uploads";
152 +import {
153 + selectWorkspaceDetail,
154 + workspaceDetailRouter,
155 +} from "./features/workspace/workspace-detail-selection";
156
157 const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
158
@@ -525,7 +529,12 @@ function RootStackLayout(props: {
529 if (!transition.shareIdToPresent) {
530 return;
531 }
528 - navigation.navigate("Thread", { draft: { incomingShareId: transition.shareIdToPresent } });
532 + navigation.dispatch(
533 + selectWorkspaceDetail({
534 + name: "Thread",
535 + params: { draft: { incomingShareId: transition.shareIdToPresent } },
536 + }),
537 + );
538 }, [navigation, pendingShare, props.state]);
539
540 return (
@@ -599,6 +608,7 @@ function NotFoundScreen() {
608
609 const RootStackConfig = createWorkspaceStackNavigator({
610 initialRouteName: "Home",
611 + UNSTABLE_router: workspaceDetailRouter,
612 // React Navigation calls layouts inline; compiled components would share the navigator's memo cache.
613 layout: (props) => <RootStackLayout {...props} />,
614 screenOptions: {
apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx
+1 -5
@@ -22,7 +22,6 @@ import { AudioFilePreview } from "./AudioFilePreview";
22 import { EmptyState } from "../../components/ui/EmptyState";
23 import { FilePreviewModal, type FilePreviewSource } from "../../components/FilePreviewModal";
24 import { LoadingScreen } from "../../components/LoadingScreen";
25 -import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
25 import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
26 import { isPdfFile } from "../../lib/filePreview";
27 import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
@@ -478,10 +477,7 @@ export function ThreadFilesTreeScreen(props: ThreadFilesRouteScreenProps) {
477 navigation.navigate("NewTaskFile", params);
478 return;
479 }
481 - const navigationAction = resolveFileSelectionNavigationAction({
482 - hasPersistentFileInspector: hasFileInspector,
483 - });
484 - if (navigationAction === "replace") {
480 + if (hasFileInspector) {
481 navigation.dispatch(StackActions.replace("ThreadFile", params));
482 return;
483 }
apps/mobile/src/features/home/HomeRouteScreen.tsx
+16 -4
@@ -28,7 +28,6 @@ import { HomeScreen } from "./HomeScreen";
28 import { HomeHeader } from "./HomeHeader";
29 import { useHomeListOptions } from "./home-list-options";
30 import { useAtomValueWhileVisible, useHomeRouteVisible } from "./home-route-visibility";
31 -import { useHomeThreadRouteSelection, useHomeThreadSelection } from "./home-thread-navigation";
31 import { buildHomeProjectScopes } from "./homeThreadList";
32 import { usePendingTaskListActions } from "./usePendingTaskListActions";
33 import { useThreadListActions } from "./useThreadListActions";
@@ -36,6 +35,7 @@ import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle
35 import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
36 import { openSettings } from "../settings/settings-navigation";
37 import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab";
38 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
39
40 export function HomeRouteScreen() {
41 const { width: windowWidth } = useWindowDimensions();
@@ -45,6 +45,7 @@ export function HomeRouteScreen() {
45 const headerWidth = nativePrimaryColumn ? (columnMetrics?.width ?? windowWidth) : windowWidth;
46 const { layout, panes, primarySidebarSearchQuery, setPrimarySidebarSearchQuery, startNewTask } =
47 useAdaptiveWorkspaceLayout();
48 + const selectDetail = useSelectWorkspaceDetail();
49 const projects = useProjects();
50 // Stop rebuilding the streaming thread list while Thread covers Home.
51 const visible = useHomeRouteVisible();
@@ -67,8 +68,18 @@ export function HomeRouteScreen() {
68 else if (workspace) workspace.dispatch({ type: "query", query, tab: "threads" });
69 else setLocalSearchQuery(query);
70 };
70 - const handleSelectThread = useHomeThreadSelection();
71 - const selectThreadRoute = useHomeThreadRouteSelection();
71 + const handleSelectThread = useCallback(
72 + (thread: EnvironmentThreadShell) =>
73 + selectDetail({
74 + name: "Thread",
75 + params: { environmentId: String(thread.environmentId), threadId: String(thread.id) },
76 + }),
77 + [selectDetail],
78 + );
79 + const selectThreadRoute = useCallback(
80 + (params: ReactNavigation.RootParamList["Thread"]) => selectDetail({ name: "Thread", params }),
81 + [selectDetail],
82 + );
83 const handleNewThreadOnBranch = useCallback(
84 (thread: EnvironmentThreadShell) => {
85 selectThreadRoute({
@@ -104,7 +115,8 @@ export function HomeRouteScreen() {
115 unsettleThread,
116 } = useThreadListActions();
117 const pendingTasks = usePendingNewTasks();
107 - const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
118 + const { openPendingTask, confirmDeletePendingTask } =
119 + usePendingTaskListActions(selectThreadRoute);
120 const environments = useMemo(() => {
121 const connectionStateByEnvironmentId = new Map(
122 workspaceEnvironments.map(
apps/mobile/src/features/home/home-thread-navigation.test.ts deleted
-238
@@ -1,238 +0,0 @@
1 -import * as NodeModule from "node:module";
2 -import type {
3 - StackNavigationState,
4 - StackRouter as StackRouterType,
5 - StackActions as StackActionsType,
6 -} from "@react-navigation/native";
7 -import { describe, expect, it, vi } from "vite-plus/test";
8 -
9 -function loadRouters() {
10 - const require = NodeModule.createRequire(import.meta.url);
11 - const nativePackage = require.resolve("@react-navigation/native/package.json");
12 - const requireFromNative = NodeModule.createRequire(nativePackage);
13 - const corePackage = requireFromNative.resolve("@react-navigation/core/package.json");
14 - const requireFromCore = NodeModule.createRequire(corePackage);
15 - return requireFromCore("@react-navigation/routers") as {
16 - readonly CommonActions: typeof import("@react-navigation/native").CommonActions;
17 - readonly StackActions: typeof StackActionsType;
18 - readonly StackRouter: typeof StackRouterType;
19 - };
20 -}
21 -
22 -vi.mock("react-native", () => ({ Platform: { OS: "ios" }, Keyboard: { dismiss: vi.fn() } }));
23 -
24 -vi.mock("../workspace/useAndroidWorkspaceSelection", () => ({
25 - useAndroidWorkspaceSelection: vi.fn(),
26 -}));
27 -
28 -vi.mock("@react-navigation/native", () => {
29 - const { CommonActions, StackActions } = loadRouters();
30 - return { CommonActions, StackActions };
31 -});
32 -
33 -import {
34 - createHomeThreadRouteAction,
35 - createHomeThreadNavigationAction,
36 -} from "./home-thread-navigation";
37 -
38 -const { StackActions, StackRouter } = loadRouters();
39 -const routeNames = ["Home", "Thread"];
40 -const routeParamList = {
41 - Home: undefined,
42 - Thread: undefined,
43 -};
44 -const router = StackRouter({});
45 -const routerOptions = {
46 - routeNames,
47 - routeParamList,
48 - routeGetIdList: {},
49 -};
50 -
51 -type ThreadSelection = Parameters<typeof createHomeThreadNavigationAction>[0]["thread"];
52 -
53 -function thread(id: string): ThreadSelection {
54 - return {
55 - environmentId: "environment-1",
56 - id,
57 - } as ThreadSelection;
58 -}
59 -
60 -function initialState() {
61 - return router.getInitialState(routerOptions);
62 -}
63 -
64 -function apply(
65 - state: StackNavigationState<Record<string, object | undefined>>,
66 - action: Parameters<typeof router.getStateForAction>[1],
67 -) {
68 - const nextState = router.getStateForAction(state, action, routerOptions);
69 - expect(nextState).not.toBeNull();
70 - return nextState as StackNavigationState<Record<string, object | undefined>>;
71 -}
72 -
73 -function selectThread(
74 - state: ReturnType<typeof initialState>,
75 - selectedThread: ThreadSelection,
76 - dismissingRouteKey: string | null = null,
77 -) {
78 - return apply(
79 - state,
80 - createHomeThreadNavigationAction({
81 - state,
82 - dismissingRouteKey,
83 - thread: selectedThread,
84 - }),
85 - );
86 -}
87 -
88 -function dismissRoute(state: ReturnType<typeof initialState>, routeKey: string) {
89 - return apply(state, {
90 - ...StackActions.pop(),
91 - source: routeKey,
92 - target: state.key,
93 - });
94 -}
95 -
96 -describe("createHomeThreadNavigationAction", () => {
97 - it("coalesces ordinary repeat selections onto the current thread route", () => {
98 - const firstState = selectThread(initialState(), thread("thread-a"));
99 - const threadRouteKey = firstState.routes[firstState.index]?.key;
100 - const secondAction = createHomeThreadNavigationAction({
101 - state: firstState,
102 - dismissingRouteKey: null,
103 - thread: thread("thread-b"),
104 - });
105 -
106 - const secondState = apply(firstState, secondAction);
107 - expect(secondState.routes).toHaveLength(2);
108 - expect(secondState.routes[secondState.index]).toMatchObject({
109 - key: threadRouteKey,
110 - name: "Thread",
111 - params: { environmentId: "environment-1", threadId: "thread-b" },
112 - });
113 - });
114 -
115 - it("keeps an overlap selection after native dismisses the outgoing route", () => {
116 - const outgoingState = selectThread(initialState(), thread("thread-a"));
117 - const outgoingRouteKey = outgoingState.routes[outgoingState.index]?.key;
118 - expect(outgoingRouteKey).toBeDefined();
119 -
120 - const overlapAction = createHomeThreadNavigationAction({
121 - state: outgoingState,
122 - dismissingRouteKey: outgoingRouteKey ?? null,
123 - thread: thread("thread-b"),
124 - });
125 - const overlapState = apply(outgoingState, overlapAction);
126 - const incomingRoute = overlapState.routes[overlapState.index];
127 - expect(incomingRoute?.key).not.toBe(outgoingRouteKey);
128 -
129 - const dismissedState = dismissRoute(overlapState, outgoingRouteKey!);
130 - expect(dismissedState.routes).toHaveLength(2);
131 - expect(dismissedState.routes[dismissedState.index]).toMatchObject({
132 - key: incomingRoute?.key,
133 - name: "Thread",
134 - params: { environmentId: "environment-1", threadId: "thread-b" },
135 - });
136 - });
137 -
138 - it("uses a fresh key for the same thread selected during dismissal", () => {
139 - const outgoingState = selectThread(initialState(), thread("thread-a"));
140 - const outgoingRouteKey = outgoingState.routes[outgoingState.index]?.key;
141 - expect(outgoingRouteKey).toBeDefined();
142 -
143 - const overlapState = selectThread(outgoingState, thread("thread-a"), outgoingRouteKey ?? null);
144 - const incomingRouteKey = overlapState.routes[overlapState.index]?.key;
145 - expect(incomingRouteKey).not.toBe(outgoingRouteKey);
146 -
147 - const dismissedState = dismissRoute(overlapState, outgoingRouteKey!);
148 - expect(dismissedState.routes[dismissedState.index]).toMatchObject({
149 - key: incomingRouteKey,
150 - params: { environmentId: "environment-1", threadId: "thread-a" },
151 - });
152 - });
153 -
154 - it("coalesces a second overlap selection onto the fresh incoming route", () => {
155 - const outgoingState = selectThread(initialState(), thread("thread-a"));
156 - const outgoingRouteKey = outgoingState.routes[outgoingState.index]?.key;
157 - expect(outgoingRouteKey).toBeDefined();
158 -
159 - const firstOverlapState = selectThread(
160 - outgoingState,
161 - thread("thread-b"),
162 - outgoingRouteKey ?? null,
163 - );
164 - const incomingRouteKey = firstOverlapState.routes[firstOverlapState.index]?.key;
165 - const secondOverlapAction = createHomeThreadNavigationAction({
166 - state: firstOverlapState,
167 - dismissingRouteKey: outgoingRouteKey ?? null,
168 - thread: thread("thread-c"),
169 - });
170 -
171 - const secondOverlapState = apply(firstOverlapState, secondOverlapAction);
172 - expect(secondOverlapState.routes).toHaveLength(3);
173 - expect(secondOverlapState.routes[secondOverlapState.index]).toMatchObject({
174 - key: incomingRouteKey,
175 - params: { environmentId: "environment-1", threadId: "thread-c" },
176 - });
177 -
178 - const dismissedState = dismissRoute(secondOverlapState, outgoingRouteKey!);
179 - expect(dismissedState.routes).toHaveLength(2);
180 - expect(dismissedState.routes[dismissedState.index]).toMatchObject({
181 - key: incomingRouteKey,
182 - params: { environmentId: "environment-1", threadId: "thread-c" },
183 - });
184 - });
185 -
186 - it("uses ordinary navigation when native pops before the selection", () => {
187 - const outgoingState = selectThread(initialState(), thread("thread-a"));
188 - const outgoingRouteKey = outgoingState.routes[outgoingState.index]?.key;
189 - expect(outgoingRouteKey).toBeDefined();
190 -
191 - const poppedState = dismissRoute(outgoingState, outgoingRouteKey!);
192 - const action = createHomeThreadNavigationAction({
193 - state: poppedState,
194 - dismissingRouteKey: outgoingRouteKey ?? null,
195 - thread: thread("thread-b"),
196 - });
197 -
198 - const selectedState = apply(poppedState, action);
199 - expect(selectedState.routes).toHaveLength(2);
200 - expect(selectedState.routes[selectedState.index]).toMatchObject({
201 - name: "Thread",
202 - params: { environmentId: "environment-1", threadId: "thread-b" },
203 - });
204 - });
205 -});
206 -
207 -describe("draft and live thread selection", () => {
208 - it("keeps the screen key and clears old identity when switching both ways", () => {
209 - const live = selectThread(initialState(), thread("thread-a"));
210 - const key = live.routes[live.index]!.key;
211 - const draft = apply(
212 - live,
213 - createHomeThreadRouteAction({
214 - state: live,
215 - dismissingRouteKey: null,
216 - params: { draft: { draftId: "new-task:draft-a" } },
217 - }),
218 - );
219 - expect(draft.routes[draft.index]).toMatchObject({
220 - key,
221 - params: {
222 - environmentId: undefined,
223 - threadId: undefined,
224 - draft: { draftId: "new-task:draft-a" },
225 - },
226 - });
227 - const restored = selectThread(draft, thread("thread-b"));
228 - expect(restored.routes[restored.index]).toMatchObject({
229 - key,
230 - params: {
231 - environmentId: "environment-1",
232 - threadId: "thread-b",
233 - draft: undefined,
234 - },
235 - });
236 - expect(restored.routes).toHaveLength(live.routes.length);
237 - });
238 -});
apps/mobile/src/features/home/home-thread-navigation.ts deleted
-114
@@ -1,114 +0,0 @@
1 -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
2 -import {
3 - CommonActions,
4 - StackActions,
5 - useNavigation,
6 - type NavigationState,
7 -} from "@react-navigation/native";
8 -import type { NativeStackNavigationProp } from "@react-navigation/native-stack";
9 -import { useCallback, useEffect, useRef } from "react";
10 -import { Platform } from "react-native";
11 -import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context";
12 -import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
13 -
14 -type ThreadSelection = Pick<EnvironmentThreadShell, "environmentId" | "id">;
15 -
16 -export function createHomeThreadRouteAction(input: {
17 - readonly state: Pick<NavigationState, "index" | "routes">;
18 - readonly dismissingRouteKey: string | null;
19 - readonly params: ReactNavigation.RootParamList["Thread"];
20 -}) {
21 - const currentRoute = input.state.routes[input.state.index];
22 - if (input.dismissingRouteKey !== null && currentRoute?.key === input.dismissingRouteKey) {
23 - return StackActions.push("Thread", input.params);
24 - }
25 - if (currentRoute?.name === "Thread") {
26 - return {
27 - ...CommonActions.setParams({
28 - environmentId: undefined,
29 - threadId: undefined,
30 - draft: undefined,
31 - ...input.params,
32 - }),
33 - source: currentRoute.key,
34 - };
35 - }
36 - return CommonActions.navigate("Thread", input.params);
37 -}
38 -
39 -export function createHomeThreadNavigationAction(input: {
40 - readonly state: Pick<NavigationState, "index" | "routes">;
41 - readonly dismissingRouteKey: string | null;
42 - readonly thread: ThreadSelection;
43 -}) {
44 - return createHomeThreadRouteAction({
45 - ...input,
46 - params: {
47 - environmentId: input.thread.environmentId,
48 - threadId: input.thread.id,
49 - },
50 - });
51 -}
52 -
53 -export function useHomeThreadRouteSelection() {
54 - const navigation =
55 - useNavigation<NativeStackNavigationProp<ReactNavigation.RootParamList, "Home">>();
56 - const dismissingRouteKey = useRef<string | null>(null);
57 - const { layout, setPrimarySidebarVisible } = useAdaptiveWorkspaceLayout();
58 - const selectAndroidWorkspace = useAndroidWorkspaceSelection();
59 -
60 - useEffect(() => {
61 - const clear = () => {
62 - dismissingRouteKey.current = null;
63 - };
64 - // For Home, swipe-back is opening; Thread's closing event targets the outgoing route.
65 - const removeTransitionStart = navigation.addListener("transitionStart", ({ data }) => {
66 - const state = navigation.getState();
67 - const currentRoute = state.routes[state.index];
68 - dismissingRouteKey.current =
69 - !data.closing && currentRoute?.name === "Thread" ? currentRoute.key : null;
70 - });
71 - const removeFocus = navigation.addListener("focus", clear);
72 -
73 - return () => {
74 - clear();
75 - removeTransitionStart();
76 - removeFocus();
77 - };
78 - }, [navigation]);
79 -
80 - return useCallback(
81 - (params: ReactNavigation.RootParamList["Thread"]) => {
82 - if (Platform.OS === "android") {
83 - selectAndroidWorkspace({
84 - name: "Thread",
85 - params,
86 - });
87 - return;
88 - }
89 - if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);
90 - navigation.dispatch((state) =>
91 - createHomeThreadRouteAction({
92 - state,
93 - dismissingRouteKey: dismissingRouteKey.current,
94 - params,
95 - }),
96 - );
97 - },
98 - [
99 - layout.primarySidebarOverlaysContent,
100 - navigation,
101 - selectAndroidWorkspace,
102 - setPrimarySidebarVisible,
103 - ],
104 - );
105 -}
106 -
107 -export function useHomeThreadSelection() {
108 - const selectRoute = useHomeThreadRouteSelection();
109 - return useCallback(
110 - (thread: ThreadSelection) =>
111 - selectRoute({ environmentId: thread.environmentId, threadId: thread.id }),
112 - [selectRoute],
113 - );
114 -}
apps/mobile/src/features/home/usePendingTaskListActions.ts
+1 -5
@@ -1,5 +1,4 @@
1 import * as Dialog from "../../components/ui/Dialog";
2 -import { useHomeThreadRouteSelection } from "./home-thread-navigation";
2 import { useCallback } from "react";
3
4 import { removeThreadOutboxMessage } from "../../state/thread-outbox-removal";
@@ -14,14 +13,11 @@ import {
13 import { withThreadDismissal } from "./thread-dismissal";
14
15 export function usePendingTaskListActions(
17 - selectRoute?: (params: ReactNavigation.RootParamList["Thread"]) => void,
16 + selectThreadRoute: (params: ReactNavigation.RootParamList["Thread"]) => void,
17 ): {
18 readonly openPendingTask: (pendingTask: PendingNewTask) => void;
19 readonly confirmDeletePendingTask: (pendingTask: PendingNewTask) => void;
20 } {
22 - const selectHomeRoute = useHomeThreadRouteSelection();
23 - const selectThreadRoute = selectRoute ?? selectHomeRoute;
24 -
21 const openPendingTask = useCallback(
22 (pendingTask: PendingNewTask) => {
23 selectThreadRoute(
apps/mobile/src/features/keyboard/CommandPalette.tsx
+26 -17
@@ -48,7 +48,6 @@ import { threadEnvironment } from "../../state/threads";
48 import { useAtomCommand } from "../../state/use-atom-command";
49 import { useWorkspaceEnvironments } from "../../state/workspace";
50 import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
51 -import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
51 import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
52 import { ThreadSearchMatchExcerpt } from "../threads/thread-search-match";
53 import {
@@ -62,6 +61,7 @@ import { threadJumpIndex } from "./threadKeyboardShortcuts";
61 import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
62 import { openSettings } from "../settings/settings-navigation";
63 import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab";
64 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
65
66 const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = [
67 "commandPalette",
@@ -212,7 +212,7 @@ export function CommandPalette(props: {
212 const navigation = useNavigation();
213 const selectTab = useSelectWorkspaceTab();
214 const { themeVariables } = useAppearancePreferences();
215 - const { selectThread, selectThreadRoute } = useAdaptiveWorkspaceLayout();
215 + const selectDetail = useSelectWorkspaceDetail();
216 const runCommand = props.onCommand;
217 const projects = useProjects();
218 const threads = useThreadShells();
@@ -323,12 +323,15 @@ export function CommandPalette(props: {
323 title: `New thread in ${activeProject.title}`,
324 searchTerms: ["new task", "chat", "create"],
325 run: () =>
326 - selectThreadRoute({
327 - draft: {
328 - requestId: uuidv4(),
329 - environmentId: activeProject.environmentId,
330 - projectId: activeProject.id,
331 - title: activeProject.title,
326 + selectDetail({
327 + name: "Thread",
328 + params: {
329 + draft: {
330 + requestId: uuidv4(),
331 + environmentId: activeProject.environmentId,
332 + projectId: activeProject.id,
333 + title: activeProject.title,
334 + },
335 },
336 }),
337 });
@@ -358,12 +361,15 @@ export function CommandPalette(props: {
361 detail: `New thread · ${savedConnectionsById[project.environmentId]?.environmentLabel ?? project.environmentId}`,
362 searchTerms: [project.workspaceRoot, "new thread", "project"],
363 run: () =>
361 - selectThreadRoute({
362 - draft: {
363 - requestId: uuidv4(),
364 - environmentId: project.environmentId,
365 - projectId: project.id,
366 - title: project.title,
364 + selectDetail({
365 + name: "Thread",
366 + params: {
367 + draft: {
368 + requestId: uuidv4(),
369 + environmentId: project.environmentId,
370 + projectId: project.id,
371 + title: project.title,
372 + },
373 },
374 }),
375 }));
@@ -391,7 +397,11 @@ export function CommandPalette(props: {
397 ...(thread.environmentId === activeThread?.environmentId && thread.id === activeThread.id
398 ? { secondary: true }
399 : {}),
394 - run: () => selectThread(thread),
400 + run: () =>
401 + selectDetail({
402 + name: "Thread",
403 + params: { environmentId: String(thread.environmentId), threadId: String(thread.id) },
404 + }),
405 };
406 });
407 // Recent means used recently: written in or opened, whichever is later.
@@ -410,8 +420,7 @@ export function CommandPalette(props: {
420 projects,
421 runCommand,
422 savedConnectionsById,
413 - selectThread,
414 - selectThreadRoute,
423 + selectDetail,
424 threads,
425 ]);
426 const rankedMessageKeys = useMemo(() => {
apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
+2 -1
@@ -32,6 +32,7 @@ import {
32 subscribeToHardwareKeyboardCommandRegistrations,
33 type HardwareKeyboardCommand,
34 } from "./hardwareKeyboardCommands";
35 +import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection";
36
37 const EMPTY_COPY_FEEDBACK: GitActionProgress = {
38 phase: "idle",
@@ -153,7 +154,7 @@ export function HardwareKeyboardCommandProvider({
154 }
155
156 if (command === "newTask") {
156 - navigation.navigate("Thread", { draft: {} });
157 + navigation.dispatch(selectWorkspaceDetail({ name: "Thread", params: { draft: {} } }));
158 return;
159 }
160 if (command === "back") {
apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
+35 -74
@@ -9,13 +9,7 @@ import type {
9 import { EnvironmentId, ThreadId, type SidebarProjectGroupingMode } from "@t3tools/contracts";
10 import { useAtomValue } from "@effect/atom-react";
11 import { useFocusEffect } from "@react-navigation/native";
12 -import {
13 - CommonActions,
14 - NavigationContext,
15 - NavigationRouteContext,
16 - StackActions,
17 - useNavigation,
18 -} from "@react-navigation/native";
12 +import { NavigationContext, NavigationRouteContext, useNavigation } from "@react-navigation/native";
13 import {
14 use,
15 useDeferredValue,
@@ -26,7 +20,7 @@ import {
20 useState,
21 type ReactNode,
22 } from "react";
29 -import { Platform, useWindowDimensions, View } from "react-native";
23 +import { Keyboard, Platform, useWindowDimensions, View } from "react-native";
24 import { KeyboardController, useKeyboardState } from "react-native-keyboard-controller";
25 import Animated, {
26 runOnJS,
@@ -47,10 +41,6 @@ import {
41 isWorkspaceListPath,
42 type WorkspaceAuxiliaryPaneRole,
43 } from "../../lib/layout";
50 -import {
51 - resolveThreadSelectionNavigationAction,
52 - resolveThreadSelectionOverlayState,
53 -} from "../../lib/adaptive-navigation";
44 import { scopedThreadKey } from "../../lib/scopedEntities";
45 import type { ThreadListFilters } from "../../persistence/mobile-preferences";
46 import { appAtomRegistry } from "../../state/atom-registry";
@@ -71,7 +61,11 @@ import {
61 ANDROID_WORKSPACE_RAIL_WIDTH,
62 } from "../workspace/AndroidWorkspaceNavigation";
63 import { AndroidWorkspaceSidebar } from "../workspace/AndroidWorkspaceSidebar";
74 -import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
64 +import {
65 + selectWorkspaceDetail,
66 + type WorkspaceDetail,
67 + type WorkspaceDetailSheet,
68 +} from "../workspace/workspace-detail-selection";
69 import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
70 import { HomeListOptionsProvider } from "../home/home-list-options";
71 import { newTaskDestination } from "../threads/new-task-project-selection";
@@ -493,78 +487,46 @@ function AdaptiveWorkspaceLayoutContent(
487 };
488 const handleOpenSettings = () => openWorkspaceTab("settings");
489
496 - const selectAndroidWorkspace = useAndroidWorkspaceSelection();
490 const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);
498 - function handleSelectThreadRoute(params: ReactNavigation.RootParamList["Thread"]) {
499 - deferredThreadSelection.run(() => applyThreadRouteSelection(params));
500 - }
501 - function applyThreadRouteSelection(params: ReactNavigation.RootParamList["Thread"]) {
502 - if (Platform.OS === "android") {
491 + /** The one way to show a page in the detail column; see `selectWorkspaceDetail`. */
492 + function handleSelectDetail(detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) {
493 + deferredThreadSelection.run(() => {
494 + if (Platform.OS === "android") Keyboard.dismiss();
495 setFileInspectorPreferredVisible(false);
504 - selectAndroidWorkspace({ name: "Thread", params });
505 - return;
506 - }
507 - const navigationAction = resolveThreadSelectionNavigationAction({
508 - usesSplitView: layout.usesSplitView,
509 - pathname,
510 - workspaceRouteName: navigation
511 - .getState()
512 - ?.routes.find((route) => route.key === props.workspaceRouteKey)?.name,
513 - });
514 - const overlayState = resolveThreadSelectionOverlayState({
515 - state: navigation.getState(),
516 - workspaceRouteKey: props.workspaceRouteKey,
517 - action: navigationAction,
518 - params,
496 + if (layout.primarySidebarOverlaysContent) setPrimarySidebarVisible(false);
497 + workspace?.dispatch({
498 + type: "select",
499 + tab: detail.name === "Thread" ? "threads" : "pullRequests",
500 + });
501 + navigation.dispatch(selectWorkspaceDetail(detail, sheet));
502 });
520 - if (overlayState !== null) {
521 - setFileInspectorPreferredVisible(false);
522 - navigation.dispatch(CommonActions.reset(overlayState));
523 - return;
524 - }
525 - if (navigationAction === "set-params") {
526 - setFileInspectorPreferredVisible(false);
527 - const state = navigation.getState();
528 - const route = state?.routes.find((candidate) => candidate.key === props.workspaceRouteKey);
529 - if (route?.name === "Thread") {
530 - navigation.dispatch({
531 - ...CommonActions.setParams({
532 - environmentId: undefined,
533 - threadId: undefined,
534 - draft: undefined,
535 - ...params,
536 - }),
537 - source: route.key,
538 - });
539 - } else {
540 - navigation.navigate("Thread", params);
541 - }
542 - return;
543 - }
544 - if (navigationAction === "replace") {
545 - setFileInspectorPreferredVisible(false);
546 - navigation.dispatch(StackActions.replace("Thread", params));
547 - return;
548 - }
549 - navigation.navigate("Thread", params);
503 }
504 + const handleSelectThreadRoute = (params: ReactNavigation.RootParamList["Thread"]) =>
505 + handleSelectDetail({ name: "Thread", params });
506
507 const projects = useProjects();
508 const compactAndroidSettings =
509 Platform.OS === "android" && androidSettingsOpen && !layout.usesSplitView;
510 + // Reads the open page when pressed, so the layout context doesn't change on every navigation.
511 const handleStartNewTask = () => {
556 - const thread = appAtomRegistry
557 - .get(environmentThreadShells.navigationThreadShellsAtom)
558 - .find((candidate) => candidate.environmentId === environmentId && candidate.id === threadId);
559 - const currentRoute = navigation
560 - .getState()
561 - ?.routes.find((route) => route.key === props.workspaceRouteKey);
562 - const draft =
512 + const state = rootStackState(navigation);
513 + const currentRoute = workspaceRoutesOf(
514 + state?.routes.slice(0, state.index + 1) ?? [],
515 + ).workspace.at(-1);
516 + const params =
517 currentRoute?.name === "Thread"
564 - ? (currentRoute.params as ReactNavigation.RootParamList["Thread"])?.draft
518 + ? (currentRoute.params as ReactNavigation.RootParamList["Thread"])
519 : undefined;
520 const first = (value: string | string[] | undefined) =>
521 Array.isArray(value) ? value[0] : value;
522 + const thread = appAtomRegistry
523 + .get(environmentThreadShells.navigationThreadShellsAtom)
524 + .find(
525 + (candidate) =>
526 + candidate.environmentId === first(params?.environmentId) &&
527 + candidate.id === first(params?.threadId),
528 + );
529 + const draft = params?.draft;
530 const draftEnvironmentId = first(draft?.environmentId);
531 const draftProjectId = first(draft?.projectId);
532 const currentProject = thread
@@ -786,8 +748,7 @@ function AdaptiveWorkspaceLayoutContent(
748 primarySidebarSearchQuery,
749 startNewTask: handleStartNewTask,
750 deferThreadSelectionUntil: deferredThreadSelection.waitFor,
789 - selectThread: handleSelectThread,
790 - selectThreadRoute: handleSelectThreadRoute,
751 + selectDetail: handleSelectDetail,
752 activateAuxiliaryPaneRole,
753 registerWorkspaceInspector,
754 setPrimarySidebarSearchQuery,
apps/mobile/src/features/layout/adaptive-workspace-context.ts
+6 -5
@@ -1,6 +1,9 @@
1 import type { WorkspaceTab } from "../workspace/workspace-tabs-state";
2 import { createContext, use, type ReactNode } from "react";
3 -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3 +import type {
4 + WorkspaceDetail,
5 + WorkspaceDetailSheet,
6 +} from "../workspace/workspace-detail-selection";
7 import {
8 deriveFileInspectorPaneLayout,
9 deriveLayout,
@@ -18,8 +21,8 @@ interface AdaptiveWorkspaceContextValue {
21 readonly primarySidebarSearchQuery: string;
22 readonly startNewTask: () => void;
23 readonly deferThreadSelectionUntil: (operation: Promise<unknown>) => void;
21 - readonly selectThread: (thread: EnvironmentThreadShell) => void;
22 - readonly selectThreadRoute: (params: ReactNavigation.RootParamList["Thread"]) => void;
24 + /** Use `useSelectWorkspaceDetail`, which also works outside the layout. */
25 + readonly selectDetail?: (detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) => void;
26 readonly activateAuxiliaryPaneRole: (role: WorkspaceAuxiliaryPaneRole) => () => void;
27 readonly registerWorkspaceInspector: (render: () => ReactNode) => () => void;
28 readonly setPrimarySidebarSearchQuery: (query: string) => void;
@@ -60,8 +63,6 @@ export const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextVa
63 primarySidebarSearchQuery: "",
64 startNewTask: () => undefined,
65 deferThreadSelectionUntil: () => undefined,
63 - selectThread: () => undefined,
64 - selectThreadRoute: () => undefined,
66 activateAuxiliaryPaneRole: () => () => undefined,
67 registerWorkspaceInspector: () => () => undefined,
68 setPrimarySidebarSearchQuery: () => undefined,
apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
+34 -22
@@ -29,6 +29,7 @@ import { WorkspaceNativeTabs } from "../workspace/WorkspaceNativeTabs.ios";
29 import { workspaceUsesColumns } from "../workspace/workspace-tabs-state";
30 import { isSettingsRoute, settingsOpenIn } from "../settings/settings-navigation";
31 import { workspaceRoutesOf } from "./workspace-overlay-routes";
32 +import { setNativelyPoppingWorkspaceRoute } from "../workspace/workspace-detail-selection";
33 import { useWorkspaceSidebarHeaderItem } from "./useWorkspaceSidebarHeaderItem";
34 import { useDeviceType, useNativeLayoutMetrics } from "../../native/native-layout-metrics";
35
@@ -71,18 +72,12 @@ const isPullRequestRoute = (route: Route) =>
72 route.name === "PullRequestFile" ||
73 route.name === "PullRequestFiles";
74
74 -/** Only these screens follow the sidebar's state; a thread's header draws its own toggle. */
75 -function SidebarToggleHeader(props: ComponentProps<typeof V5StackHeader>) {
76 - const sidebarItem = useWorkspaceSidebarHeaderItem();
77 - const options = {
78 - ...props.options,
79 - unstable_headerLeftItems: () => [sidebarItem],
80 - } as AppNativeStackNavigationOptions as typeof props.options;
81 - return <V5StackHeader {...props} options={options} />;
82 -}
75 +/** Beside the list, the first Settings page shows on one native screen that swaps its content. */
76 +const SETTINGS_DETAIL_SCREEN = "settings-detail";
77
78 function ColumnScreen(props: {
79 readonly descriptor: Descriptor;
80 + readonly screenKey?: string;
81 readonly primary?: boolean;
82 readonly attached?: boolean;
83 readonly selectedThreadKey?: string | null;
@@ -96,13 +91,20 @@ function ColumnScreen(props: {
91 }) {
92 const { descriptor } = props;
93 // Options a screen set inside this workspace tab slot, over its route's.
99 - const options = slotScreenOptions(
94 + const slotOptions = slotScreenOptions(
95 use(WorkspaceSlotOptionsContext),
96 descriptor.route.key,
97 descriptor.options,
98 );
104 - const Header =
105 - props.sidebarToggle && !options.unstable_headerLeftItems ? SidebarToggleHeader : V5StackHeader;
99 + const sidebarItem = useWorkspaceSidebarHeaderItem();
100 + // Swapping header components would unmount the native header config, which hides the bar.
101 + const options =
102 + props.sidebarToggle && !slotOptions.unstable_headerLeftItems
103 + ? ({
104 + ...slotOptions,
105 + unstable_headerLeftItems: () => [sidebarItem],
106 + } as AppNativeStackNavigationOptions as typeof slotOptions)
107 + : slotOptions;
108 const [presented, setPresented] = useState(false);
109 const primaryColumn = useMemo(
110 () =>
@@ -118,7 +120,7 @@ function ColumnScreen(props: {
120 const key = descriptor.route.key;
121 return (
122 <Split.Screen
121 - screenKey={key}
123 + screenKey={props.screenKey ?? key}
124 activityMode={props.attached === false ? "detached" : "attached"}
125 onDismiss={(event) => {
126 props.onDismiss(key, event.nativeEvent.isNativeDismiss);
@@ -143,7 +145,7 @@ function ColumnScreen(props: {
145 >
146 <NavigationContext value={descriptor.navigation}>
147 <NavigationRouteContext value={descriptor.route}>
146 - <Header
148 + <V5StackHeader
149 options={options}
150 canGoBack={!props.primary}
151 column={props.primary ? "primary" : "detail"}
@@ -156,6 +158,7 @@ function ColumnScreen(props: {
158 }
159 />
160 <ColumnContent
161 + key={key}
162 primary={props.primary}
163 insetHorizontally={
164 (options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
@@ -184,6 +187,8 @@ function WorkspaceColumns(
187 openWorkspaceTab,
188 } = useAdaptiveWorkspaceLayout();
189 const deviceType = useDeviceType();
190 + const settingsDetailIn = (detail: readonly Route[]) =>
191 + layout.usesSplitView && detail[0] && isSettingsRoute(detail[0].name) ? detail[0] : undefined;
192 // Split screens must remain mounted while UIKit animates a detached route away.
193 const [screens, setScreens] = useState({
194 routes: props.detail,
@@ -196,9 +201,13 @@ function WorkspaceColumns(
201 screens.observedRoutes !== props.detail ||
202 screens.observedDescriptors !== props.descriptors
203 ) {
199 - const routes = reconcileStackScreens(screens.routes, props.detail, screens.completed);
200 - const retained = new Set(routes.map((route) => route.key));
204 const active = new Set(props.detail.map((route) => route.key));
205 + const settingsSlot = settingsDetailIn(props.detail);
206 + const routes = reconcileStackScreens(screens.routes, props.detail, screens.completed).filter(
207 + // The slot's native screen stays; the pages it showed, and any above them, just go.
208 + (route) => !settingsSlot || active.has(route.key) || !isSettingsRoute(route.name),
209 + );
210 + const retained = new Set(routes.map((route) => route.key));
211 setScreens({
212 routes,
213 descriptors: Object.fromEntries(
@@ -280,6 +289,7 @@ function WorkspaceColumns(
289 props.primary.key,
290 );
291 collapsedColumn.current = transition.column;
292 + setNativelyPoppingWorkspaceRoute(transition.column.leaving);
293 if (transition.pop) props.navigation.dispatch(transition.pop);
294 };
295
@@ -301,9 +311,11 @@ function WorkspaceColumns(
311 onCollapse={() => {
312 collapsed.current = true;
313 collapsedColumn.current = { visible: compactColumn, leaving: null };
314 + setNativelyPoppingWorkspaceRoute(null);
315 }}
316 onExpand={() => {
317 collapsed.current = false;
318 + setNativelyPoppingWorkspaceRoute(null);
319 // Native callbacks can outlive the render that created them, so decide from the live
320 // router state. An expanded split has columns, so its tab gets a page beside the list.
321 const live = props.navigation.getState();
@@ -392,15 +404,14 @@ function WorkspaceColumns(
404 </Split.Screen>
405 {screens.routes.map((route) => {
406 const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];
407 + const inSettingsSlot = settingsDetailIn(props.detail)?.key === route.key;
408 + const screenKey = inSettingsSlot ? SETTINGS_DETAIL_SCREEN : route.key;
409 return descriptor ? (
410 <ColumnScreen
397 - key={route.key}
411 + key={screenKey}
412 + screenKey={screenKey}
413 descriptor={descriptor}
399 - sidebarToggle={
400 - layout.usesSplitView &&
401 - props.detail[0]?.key === route.key &&
402 - isSettingsRoute(route.name)
403 - }
414 + sidebarToggle={inSettingsSlot}
415 attached={props.detail.some((current) => current.key === route.key)}
416 onDismiss={handleNativeDismiss}
417 onAppearance={followCollapsedSplit}
@@ -469,6 +480,7 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean
480 <V5CardStackView
481 {...props}
482 onRootVisibilityChange={setPrimaryVisible}
483 + onNativePopChange={setNativelyPoppingWorkspaceRoute}
484 descriptors={descriptors}
485 state={{
486 ...props.state,
apps/mobile/src/features/pull-requests/PullRequestStackCard.tsx
+3 -3
@@ -1,7 +1,7 @@
1 import { StackActions, useNavigation } from "@react-navigation/native";
2 import { useState } from "react";
3 import { Platform, View } from "react-native";
4 -import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
4 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
5 import { AppText as Text } from "../../components/ui/AppText";
6 import { PullRequestCardGroup, PullRequestCardRow } from "./PullRequestControls";
7 import { pullRequestStatus } from "./pullRequestStatus";
@@ -14,7 +14,7 @@ export function PullRequestStackCard(props: {
14 readonly state: PullRequestStackState;
15 }) {
16 const navigation = useNavigation();
17 - const selectAndroidWorkspace = useAndroidWorkspaceSelection();
17 + const selectDetail = useSelectWorkspaceDetail();
18 const [expanded, setExpanded] = useState(false);
19 const stack = props.state.stack;
20 if (!stack) {
@@ -68,7 +68,7 @@ export function PullRequestStackCard(props: {
68 : () => {
69 const params = { ...props.params, number: layer.number };
70 if (Platform.OS === "android")
71 - selectAndroidWorkspace({ name: "PullRequest", params });
71 + selectDetail({ name: "PullRequest", params });
72 else navigation.dispatch(StackActions.push("PullRequest", params));
73 }
74 }
apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+4 -5
@@ -42,7 +42,7 @@ import {
42 } from "./pullRequestList";
43 import { useDebouncedValue } from "../../state/queries";
44 import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
45 -import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
45 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
46
47 function PullRequestScrollView(props: ScrollViewProps) {
48 return (
@@ -106,7 +106,7 @@ export function PullRequestsScreen(
106 const environmentId = environments.some((item) => item.environmentId === selectedEnvironmentId)
107 ? selectedEnvironmentId
108 : null;
109 - const selectAndroidWorkspace = useAndroidWorkspaceSelection();
109 + const selectDetail = useSelectWorkspaceDetail();
110 const selectPullRequest = useCallback(
111 (item: EnvironmentPullRequestListEntry) => {
112 Keyboard.dismiss();
@@ -118,10 +118,9 @@ export function PullRequestsScreen(
118 host: item.host,
119 initialSummary: item,
120 };
121 - if (Platform.OS === "android") selectAndroidWorkspace({ name: "PullRequest", params });
122 - else navigation.navigate("PullRequest", params);
121 + selectDetail({ name: "PullRequest", params });
122 },
124 - [navigation, selectAndroidWorkspace],
123 + [selectDetail],
124 );
125 const allProjects = useProjects();
126 const savedControls = listControls.controlsFor(environmentId);
apps/mobile/src/features/pull-requests/usePullRequestListActions.ts
+7 -6
@@ -22,7 +22,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli
22 import { scopedPullRequestListKey, type EnvironmentPullRequestListEntry } from "./pullRequestList";
23 import { copyPullRequestLink, sharePullRequestLink } from "./pullRequestLink";
24 import { pullRequestTarget } from "./usePullRequestDiff";
25 -import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
25 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
26
27 export function usePullRequestListActions(
28 environmentIds: readonly EnvironmentId[],
@@ -33,7 +33,7 @@ export function usePullRequestListActions(
33 ) {
34 const registry = use(RegistryContext);
35 const navigation = useNavigation();
36 - const selectAndroidWorkspace = useAndroidWorkspaceSelection();
36 + const selectDetail = useSelectWorkspaceDetail();
37 const permissionKey = JSON.stringify(environmentIds);
38 const permissionAtom = (() => {
39 const ids: readonly EnvironmentId[] = JSON.parse(permissionKey);
@@ -80,7 +80,10 @@ export function usePullRequestListActions(
80 )
81 throw new Error(`Review requests aren't available for this ${terminology.singular}.`);
82 if (Platform.OS === "android") {
83 - selectAndroidWorkspace({ name: "PullRequest", params: params(entry) }, params(entry));
83 + selectDetail(
84 + { name: "PullRequest", params: params(entry) },
85 + { name: "PullRequestReviewers", params: params(entry) },
86 + );
87 } else navigation.navigate("PullRequestReviewers", params(entry));
88 return;
89 }
@@ -112,9 +115,7 @@ export function usePullRequestListActions(
115 };
116 const select = (entry: EnvironmentPullRequestListEntry, action: string) => {
117 if (action === "open") {
115 - if (Platform.OS === "android")
116 - selectAndroidWorkspace({ name: "PullRequest", params: params(entry) });
117 - else navigation.navigate("PullRequest", params(entry));
118 + selectDetail({ name: "PullRequest", params: params(entry) });
119 return;
120 }
121 if (action === "request-review") {
apps/mobile/src/features/pull-requests/usePullRequestThreads.ts
+15 -10
@@ -1,7 +1,12 @@
1 import { AsyncResult } from "effect/reactivity";
2 import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3 import * as Dialog from "../../components/ui/Dialog";
4 -import { useNavigation, useNavigationState, useRoute } from "@react-navigation/native";
4 +import {
5 + StackActions,
6 + useNavigation,
7 + useNavigationState,
8 + useRoute,
9 +} from "@react-navigation/native";
10 import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility";
11 import {
12 AuthOrchestrationOperateScope,
@@ -15,7 +20,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli
20 import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
21 import { useRef, useState } from "react";
22 import { Platform } from "react-native";
18 -import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSelection";
23 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
24 import { pullRequestComposerContext } from "../../lib/composerContext";
25 import { scopedThreadKey } from "../../lib/scopedEntities";
26 import { uuidv4 } from "../../lib/uuid";
@@ -71,13 +76,16 @@ export function usePullRequestThreads(
76 const canAsk = !connected || canOperate;
77 const canCheckout = useEnvironmentScope(target.environmentId, AuthSourceControlWriteScope);
78 const navigation = useNavigation();
74 - const selectAndroidWorkspace = useAndroidWorkspaceSelection();
79 + const selectDetail = useSelectWorkspaceDetail();
80 const pending = useRef(false);
81 const previousPrompts = useRef(new Map<string, string>());
82 const openThread = (thread: LinkedThread) => {
78 - const destination = { environmentId: params.environmentId, threadId: thread.id };
79 - if (Platform.OS === "android") selectAndroidWorkspace({ name: "Thread", params: destination });
80 - else navigation.navigate("Thread", destination);
83 + openThreadRoute({ environmentId: params.environmentId, threadId: thread.id });
84 + };
85 + // Android shows one page at a time; iOS opens the thread over the pull request, so Back returns.
86 + const openThreadRoute = (destination: ReactNavigation.RootParamList["Thread"]) => {
87 + if (Platform.OS === "android") selectDetail({ name: "Thread", params: destination });
88 + else navigation.dispatch(StackActions.push("Thread", destination));
89 };
90 const [busy, setBusy] = useState(false);
91 const ask = async (thread?: LinkedThread, task: PullRequestAgentTask = "ask") => {
@@ -152,10 +160,7 @@ export function usePullRequestThreads(
160 );
161 previousPrompts.current.set(draftKey, pullRequestAgentPrompt(task, terminology));
162 if (thread) openThread(thread);
155 - else
156 - navigation.navigate("Thread", {
157 - draft: { draftId: draftKey, title: `Ask about #${pr.number}` },
158 - });
163 + else openThreadRoute({ draft: { draftId: draftKey, title: `Ask about #${pr.number}` } });
164 });
165 pending.current = false;
166 setBusy(false);
apps/mobile/src/features/review/ReviewSheet.tsx
+5 -3
@@ -68,6 +68,7 @@ import { resolveReviewAvailability } from "./reviewAvailability";
68 import { resolveSelectedReviewFileId } from "./reviewPaneSelection";
69 import { buildReviewSectionMenu } from "./review-section-menu";
70 import { reportShowcaseSceneRendered } from "../showcase/showcaseRenderSignal";
71 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
72
73 function ReviewHeader(
74 props: Parameters<typeof useReviewHeaderPresentation>[0] & {
@@ -433,6 +434,7 @@ export function ReviewSheet(props: ReviewSheetProps) {
434 useAdaptiveWorkspacePaneRole("inspector");
435 const { panes, showAuxiliaryPane } = useAdaptiveWorkspaceLayout();
436 const navigation = useNavigation();
437 + const selectDetail = useSelectWorkspaceDetail();
438 const insets = useSafeAreaInsets();
439 const { themeAppearance: selectedTheme } = useAppearancePreferences();
440 const headerIcon = String(useUniwindTheme()["--color-icon"]);
@@ -610,9 +612,9 @@ export function ReviewSheet(props: ReviewSheetProps) {
612 navigation.goBack();
613 return;
614 }
613 - navigation.navigate("Thread", {
614 - environmentId: String(environmentId),
615 - threadId: String(threadId),
615 + selectDetail({
616 + name: "Thread",
617 + params: { environmentId: String(environmentId), threadId: String(threadId) },
618 });
619 };
620 const androidHeaderSubtitle = [
apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx
+2 -1
@@ -34,6 +34,7 @@ import {
34 } from "./showcaseRenderSignal";
35 import { stageShowcaseAgentActivity } from "./stageShowcaseAgentActivity";
36 import { openSettings } from "../settings/settings-navigation";
37 +import { selectWorkspaceDetail } from "../workspace/workspace-detail-selection";
38
39 const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
40 const SHOWCASE_THREAD_ID = "remote-command-center";
@@ -250,7 +251,7 @@ function EnabledShowcaseCaptureCoordinator(props: { readonly pathname: string })
251 } else if (requestedScene === "review") {
252 navigation.dispatch(CommonActions.navigate("ThreadReview", params));
253 } else {
253 - navigation.dispatch(CommonActions.navigate("Thread", params));
254 + navigation.dispatch(selectWorkspaceDetail({ name: "Thread", params }));
255 }
256 }, [hasFixture, navigation, requestedScene, scene, showcaseThread]);
257
apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+20 -15
@@ -37,6 +37,7 @@ import { usePromptLinkResolver } from "../prompt-links/usePromptLinkResolver";
37 import { useIncomingShare } from "../sharing/IncomingShareProvider";
38 import { useNewTaskFlow } from "./new-task-flow-provider";
39 import { filterProjectScopes, getProjectScopeSelectionTarget } from "./new-task-project-selection";
40 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
41
42 type NewTaskRouteParams = {
43 readonly incomingShareId?: string | string[];
@@ -154,6 +155,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
155 const { projectScopes, selectedEnvironmentId, setProject } = useNewTaskFlow();
156 const { state: catalogState } = useWorkspaceState();
157 const navigation = useNavigation();
158 + const selectDetail = useSelectWorkspaceDetail();
159 const isFocused = useIsFocused();
160 const insets = useSafeAreaInsets();
161 const { getShare, releaseShareReservation } = useIncomingShare();
@@ -231,11 +233,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
233 root?.goBack();
234 return;
235 }
234 - root?.navigate("Thread", {
235 - draft: {
236 - environmentId: String(project.environmentId),
237 - projectId: String(project.id),
238 - incomingShareId: incomingShare?.id,
236 + selectDetail({
237 + name: "Thread",
238 + params: {
239 + draft: {
240 + environmentId: String(project.environmentId),
241 + projectId: String(project.id),
242 + incomingShareId: incomingShare?.id,
243 + },
244 },
245 });
246 }
@@ -282,18 +287,18 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
287 return;
288 }
289 resumedDestinationKeyRef.current = destinationKey;
285 - (navigation.getState()?.routeNames.includes("NewTaskProject")
286 - ? navigation
287 - : navigation.getParent()
288 - )?.navigate("Thread", {
289 - draft: {
290 - environmentId: reservedDestinationProject.environmentId,
291 - projectId: reservedDestinationProject.id,
292 - title: reservedDestinationProject.title,
293 - incomingShareId: incomingShare.id,
290 + selectDetail({
291 + name: "Thread",
292 + params: {
293 + draft: {
294 + environmentId: reservedDestinationProject.environmentId,
295 + projectId: reservedDestinationProject.id,
296 + title: reservedDestinationProject.title,
297 + incomingShareId: incomingShare.id,
298 + },
299 },
300 });
296 - }, [incomingShare, isFocused, navigation, reservedDestinationProject]);
301 + }, [incomingShare, isFocused, reservedDestinationProject, selectDetail]);
302
303 return (
304 <View collapsable={false} className="flex-1 bg-sheet">
apps/mobile/src/features/threads/ThreadFeed.tsx
+5 -3
@@ -289,6 +289,7 @@ import {
289 ThreadMarkdownImageView,
290 } from "./ThreadMarkdownImage";
291 import { openSettings } from "../settings/settings-navigation";
292 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
293
294 const WIDE_MARKDOWN_BLOCK_OPTIONS = {
295 // iOS blockquotes and selectable text measure separately; definite bubble width matches UIKit's drawing width.
@@ -435,6 +436,7 @@ function AssistantForkButton(props: {
436 });
437 const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
438 const navigation = useNavigation();
439 + const selectDetail = useSelectWorkspaceDetail();
440 const [busy, setBusy] = useState(false);
441 const canFork = canForkProjectedAssistantItem({
442 projectedItem: props.projectedItem,
@@ -473,9 +475,9 @@ function AssistantForkButton(props: {
475 );
476 return;
477 }
476 - navigation.navigate("Thread", {
477 - environmentId: props.environmentId,
478 - threadId: targetThreadId,
478 + selectDetail({
479 + name: "Thread",
480 + params: { environmentId: props.environmentId, threadId: targetThreadId },
481 });
482 })
483 .finally(() => setBusy(false));
apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+5 -1
@@ -78,6 +78,7 @@ import {
78 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
79 type ThreadListV2ListItem,
80 } from "./threadListV2";
81 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
82
83 type SidebarListItem =
84 | ThreadListV2ListItem
@@ -158,7 +159,10 @@ function ThreadNavigationSidebarPane(
159 const pendingTasks = usePendingNewTasks();
160 const activeNewTask = useActiveNewTask();
161 const queuedThreadKeys = useQueuedThreadKeys();
161 - const { confirmDeletePendingTask } = usePendingTaskListActions();
162 + const selectDetail = useSelectWorkspaceDetail();
163 + const { confirmDeletePendingTask } = usePendingTaskListActions((params) =>
164 + selectDetail({ name: "Thread", params }),
165 + );
166 const environments = Object.values(savedConnectionsById)
167 .map((connection) => ({
168 environmentId: connection.environmentId,
apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+5 -3
@@ -99,6 +99,7 @@ import {
99 useWorkspaceBackNavigation,
100 } from "../workspace/useAndroidWorkspaceNavigation";
101 import { openSettings } from "../settings/settings-navigation";
102 +import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
103
104 interface ThreadInspectorSelection {
105 readonly routeThreadIdentity: string | null;
@@ -340,6 +341,7 @@ function ThreadRouteContent(
341 };
342 })();
343 const navigation = useNavigation();
344 + const selectDetail = useSelectWorkspaceDetail();
345 const openPullRequest = useOpenPullRequest();
346 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
347 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
@@ -367,9 +369,9 @@ function ThreadRouteContent(
369 });
370 mergeBackBusyRef.current = false;
371 if (result._tag !== "Success") return;
370 - navigation.navigate("Thread", {
371 - environmentId: selectedThread.environmentId,
372 - threadId: mergeBackTargetThreadId,
372 + selectDetail({
373 + name: "Thread",
374 + params: { environmentId: selectedThread.environmentId, threadId: mergeBackTargetThreadId },
375 });
376 };
377 const params = props.route.params ?? {};
apps/mobile/src/features/workspace/useAndroidWorkspaceSelection.ts deleted
-27
@@ -1,27 +0,0 @@
1 -import { useNavigation } from "@react-navigation/native";
2 -import { useCallback } from "react";
3 -import { Keyboard } from "react-native";
4 -import {
5 - resetAndroidWorkspace,
6 - type AndroidWorkspaceDestination,
7 -} from "../../lib/android-workspace-navigation";
8 -import { useWorkspaceTabs } from "./WorkspaceTabsContext";
9 -
10 -export function useAndroidWorkspaceSelection() {
11 - const navigation = useNavigation();
12 - const dispatch = useWorkspaceTabs()?.dispatch;
13 - return useCallback(
14 - (
15 - destination: AndroidWorkspaceDestination,
16 - reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],
17 - ) => {
18 - Keyboard.dismiss();
19 - dispatch?.({
20 - type: "select",
21 - tab: destination.name === "Thread" ? "threads" : "pullRequests",
22 - });
23 - resetAndroidWorkspace(navigation, destination, reviewers);
24 - },
25 - [navigation, dispatch],
26 - );
27 -}
apps/mobile/src/features/workspace/useSelectWorkspaceDetail.ts new
+21
@@ -0,0 +1,21 @@
1 +import { useNavigation } from "@react-navigation/native";
2 +import { useAdaptiveWorkspaceLayout } from "../layout/adaptive-workspace-context";
3 +import {
4 + selectWorkspaceDetail,
5 + type WorkspaceDetail,
6 + type WorkspaceDetailSheet,
7 +} from "./workspace-detail-selection";
8 +
9 +/**
10 + * Shows a page in the detail column the way selecting its list row does. Inside the workspace
11 + * layout this also settles its panes; outside it, the root stack's router still does the rest.
12 + */
13 +export function useSelectWorkspaceDetail() {
14 + const navigation = useNavigation();
15 + const { selectDetail } = useAdaptiveWorkspaceLayout();
16 + return (
17 + selectDetail ??
18 + ((detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) =>
19 + navigation.dispatch(selectWorkspaceDetail(detail, sheet)))
20 + );
21 +}
apps/mobile/src/features/workspace/workspace-detail-selection.test.ts new
+141
@@ -0,0 +1,141 @@
1 +import * as NodeModule from "node:module";
2 +import { describe, expect, it } from "vite-plus/test";
3 +import {
4 + selectWorkspaceDetail,
5 + setNativelyPoppingWorkspaceRoute,
6 + workspaceDetailLinkAction,
7 + workspaceDetailRouter,
8 + type WorkspaceDetail,
9 +} from "./workspace-detail-selection";
10 +
11 +const require = NodeModule.createRequire(import.meta.url);
12 +const requireFromNative = NodeModule.createRequire(
13 + require.resolve("@react-navigation/native/package.json"),
14 +);
15 +const requireFromCore = NodeModule.createRequire(
16 + requireFromNative.resolve("@react-navigation/core/package.json"),
17 +);
18 +const { StackActions, StackRouter } = requireFromCore("@react-navigation/routers") as {
19 + readonly StackActions: typeof import("@react-navigation/native").StackActions;
20 + readonly StackRouter: typeof import("@react-navigation/native").StackRouter;
21 +};
22 +
23 +const base = StackRouter({});
24 +const router = { ...base, ...workspaceDetailRouter(base) };
25 +const options = {
26 + routeNames: [
27 + "Home",
28 + "Thread",
29 + "ThreadFiles",
30 + "PullRequest",
31 + "PullRequestReviewers",
32 + "Settings",
33 + "SettingsAppearance",
34 + "GitOverview",
35 + ],
36 + routeParamList: {},
37 + routeGetIdList: {},
38 +};
39 +type State = ReturnType<typeof base.getInitialState>;
40 +type RouterAction = Parameters<typeof base.getStateForAction>[1];
41 +
42 +const threadA = { name: "Thread", params: { environmentId: "env", threadId: "a" } } as const;
43 +const threadB = { name: "Thread", params: { environmentId: "env", threadId: "b" } } as const;
44 +const pullRequest = {
45 + name: "PullRequest",
46 + params: { environmentId: "env", projectId: "p", repository: "o/r", number: 1, host: "h" },
47 +} as const;
48 +
49 +function apply(state: State, action: Parameters<typeof base.getStateForAction>[1]) {
50 + const next = router.getStateForAction(state, action, options);
51 + if (!next) throw new Error(`Router rejected ${action.type}`);
52 + // React Navigation rehydrates every state a router returns, as a stale RESET needs.
53 + return base.getRehydratedState(next as State, options);
54 +}
55 +
56 +function select(
57 + state: State,
58 + detail: WorkspaceDetail,
59 + sheet?: Parameters<typeof selectWorkspaceDetail>[1],
60 +) {
61 + return apply(state, selectWorkspaceDetail(detail, sheet) as unknown as RouterAction);
62 +}
63 +
64 +function push(state: State, name: string, params?: object) {
65 + return apply(state, StackActions.push(name, params));
66 +}
67 +
68 +const home = () => base.getInitialState(options);
69 +const page = (state: State) => ({
70 + names: state.routes.map((route) => route.name),
71 + index: state.index,
72 +});
73 +
74 +describe("selectWorkspaceDetail", () => {
75 + it("swaps the open thread in place instead of pushing another", () => {
76 + const first = select(home(), threadA);
77 + const second = select(first, threadB);
78 + expect(page(second)).toEqual({ names: ["Home", "Thread"], index: 1 });
79 + expect(second.routes[1]?.key).toBe(first.routes[1]?.key);
80 + expect(second.routes[1]?.params).toEqual(threadB.params);
81 + });
82 +
83 + it.each([
84 + ["a page drilled into from the thread", (state: State) => push(state, "ThreadFiles")],
85 + ["a linked thread", (state: State) => push(state, "Thread", threadB.params)],
86 + ["a pull request opened from the thread", (state: State) => push(state, "PullRequest")],
87 + ["a sheet", (state: State) => push(state, "GitOverview")],
88 + ])("leaves only the selection when %s is on top", (_, drillIn) => {
89 + const thread = select(home(), threadA);
90 + const selected = select(drillIn(thread), threadA);
91 + expect(page(selected)).toEqual({ names: ["Home", "Thread"], index: 1 });
92 + expect(selected.routes[1]?.key).toBe(thread.routes[1]?.key);
93 + });
94 +
95 + it("replaces another tab's page and Settings with the selection", () => {
96 + const settings = push(push(select(home(), threadA), "Settings"), "SettingsAppearance");
97 + const selected = select(settings, pullRequest);
98 + expect(page(selected)).toEqual({ names: ["Home", "PullRequest"], index: 1 });
99 + expect(selected.routes[0]?.key).toBe(settings.routes[0]?.key);
100 + });
101 +
102 + it("puts Home under a cold-linked page and a sheet over the selection", () => {
103 + const cold = apply(home(), { type: "RESET", payload: { index: 0, routes: [pullRequest] } });
104 + const selected = select(cold, pullRequest, {
105 + name: "PullRequestReviewers",
106 + params: pullRequest.params,
107 + });
108 + expect(page(selected)).toEqual({
109 + names: ["Home", "PullRequest", "PullRequestReviewers"],
110 + index: 2,
111 + });
112 + });
113 +
114 + it("never reuses the page native Back is popping", () => {
115 + const thread = select(home(), threadA);
116 + setNativelyPoppingWorkspaceRoute(thread.routes[1]!.key);
117 + try {
118 + const selected = select(thread, threadA);
119 + expect(page(selected)).toEqual({ names: ["Home", "Thread"], index: 1 });
120 + expect(selected.routes[1]?.key).not.toBe(thread.routes[1]?.key);
121 + } finally {
122 + setNativelyPoppingWorkspaceRoute(null);
123 + }
124 + });
125 +});
126 +
127 +describe("workspaceDetailLinkAction", () => {
128 + it("selects a linked thread or pull request, and leaves other links alone", () => {
129 + expect(workspaceDetailLinkAction({ routes: [{ name: "Home" }, threadA] })).toEqual(
130 + selectWorkspaceDetail(threadA),
131 + );
132 + expect(workspaceDetailLinkAction({ routes: [pullRequest] })).toEqual(
133 + selectWorkspaceDetail(pullRequest),
134 + );
135 + expect(
136 + workspaceDetailLinkAction({
137 + routes: [{ name: "Home" }, { name: "Settings" }, { name: "SettingsAppearance" }],
138 + }),
139 + ).toBeUndefined();
140 + });
141 +});
apps/mobile/src/features/workspace/workspace-detail-selection.ts new
+114
@@ -0,0 +1,114 @@
1 +import type {
2 + NavigationAction,
3 + ParamListBase,
4 + PartialState,
5 + NavigationState,
6 + Router,
7 + StackNavigationState,
8 +} from "@react-navigation/native";
9 +import { workspaceRoutesOf } from "../layout/workspace-overlay-routes";
10 +
11 +type RootParams = ReactNavigation.RootParamList;
12 +
13 +/** A page the workspace's detail column shows on its own: what a list row selects. */
14 +export type WorkspaceDetail =
15 + | { readonly name: "Thread"; readonly params: RootParams["Thread"] }
16 + | { readonly name: "PullRequest"; readonly params: RootParams["PullRequest"] };
17 +
18 +/** Android opens the reviewers sheet over the pull request in the same step. */
19 +export type WorkspaceDetailSheet = {
20 + readonly name: "PullRequestReviewers";
21 + readonly params: RootParams["PullRequestReviewers"];
22 +};
23 +
24 +const SELECT_WORKSPACE_DETAIL = "SELECT_WORKSPACE_DETAIL";
25 +
26 +export interface SelectWorkspaceDetailAction {
27 + readonly type: typeof SELECT_WORKSPACE_DETAIL;
28 + readonly payload: { readonly detail: WorkspaceDetail; readonly sheet?: WorkspaceDetailSheet };
29 +}
30 +
31 +/**
32 + * Shows `detail` as the workspace's only page, the way selecting a list row does. Drilling in
33 + * from a page pushes instead.
34 + */
35 +export function selectWorkspaceDetail(
36 + detail: WorkspaceDetail,
37 + sheet?: WorkspaceDetailSheet,
38 +): SelectWorkspaceDetailAction {
39 + return { type: SELECT_WORKSPACE_DETAIL, payload: sheet ? { detail, sheet } : { detail } };
40 +}
41 +
42 +const IDENTITY = {
43 + Thread: ["environmentId", "threadId"],
44 + PullRequest: ["environmentId", "projectId", "repository", "number", "host"],
45 +} as const;
46 +
47 +type RouteLike = { readonly name: string; readonly key?: string; readonly params?: object };
48 +
49 +function showsDetail(route: RouteLike, detail: WorkspaceDetail) {
50 + if (route.name !== detail.name) return false;
51 + const current = route.params as Readonly<Record<string, unknown>> | undefined;
52 + const target = detail.params as Readonly<Record<string, unknown>> | undefined;
53 + return IDENTITY[detail.name].every((key) => current?.[key] === target?.[key]);
54 +}
55 +
56 +// UIKit pops a card by native Back before the router hears of it, so a row tapped meanwhile
57 +// must not reuse the card on its way out.
58 +let nativelyPoppingRoute: string | null = null;
59 +
60 +export function setNativelyPoppingWorkspaceRoute(key: string | null) {
61 + nativelyPoppingRoute = key;
62 +}
63 +
64 +/**
65 + * The root stack after selecting `detail`: Home, then the detail alone. The route already showing
66 + * it, or else the detail column's current page of the same kind, keeps its key, so the column
67 + * updates in place instead of pushing.
68 + */
69 +export function workspaceDetailState<
70 + State extends { readonly index: number; readonly routes: readonly RouteLike[] },
71 +>(state: State, detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet, popping?: string | null) {
72 + const { workspace } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));
73 + const leaving = workspace.findIndex((route) => route.key !== undefined && route.key === popping);
74 + const live = leaving < 0 ? workspace : workspace.slice(0, leaving);
75 + const home = live.find((route) => route.name === "Home") ?? { name: "Home" };
76 + const page = live.find((route) => route.name !== "Home" && route.name !== "Settings");
77 + const reused =
78 + live.findLast((route) => showsDetail(route, detail)) ??
79 + (page?.name === detail.name ? page : undefined);
80 + const routes = [
81 + home,
82 + reused ? { ...reused, params: detail.params } : { name: detail.name, params: detail.params },
83 + ...(sheet ? [sheet] : []),
84 + ];
85 + return { ...state, index: routes.length - 1, routes };
86 +}
87 +
88 +/** Root stack router overrides that handle `selectWorkspaceDetail`. */
89 +export function workspaceDetailRouter<Action extends NavigationAction>(
90 + original: Router<StackNavigationState<ParamListBase>, Action>,
91 +): Partial<Router<StackNavigationState<ParamListBase>, Action>> {
92 + return {
93 + getStateForAction(state, action, options) {
94 + if (action.type !== SELECT_WORKSPACE_DETAIL) {
95 + return original.getStateForAction(state, action, options);
96 + }
97 + const { detail, sheet } = (action as unknown as SelectWorkspaceDetailAction).payload;
98 + const next = workspaceDetailState(state, detail, sheet, nativelyPoppingRoute);
99 + const reset = { type: "RESET", payload: { ...next, stale: false } };
100 + return original.getStateForAction(state, reset as unknown as Action, options);
101 + },
102 + };
103 +}
104 +
105 +/** A link to a single thread or pull request selects it, like its list row would. */
106 +export function workspaceDetailLinkAction(
107 + state: PartialState<NavigationState> | NavigationState,
108 +): SelectWorkspaceDetailAction | undefined {
109 + const pages = state.routes.filter((route) => route.name !== "Home");
110 + const [page] = pages;
111 + if (pages.length !== 1 || !page || page.state) return undefined;
112 + if (page.name !== "Thread" && page.name !== "PullRequest") return undefined;
113 + return selectWorkspaceDetail({ name: page.name, params: page.params } as WorkspaceDetail);
114 +}
apps/mobile/src/features/workspace/workspace-selection-store.ts
+18 -2
@@ -46,12 +46,25 @@ function save() {
46 .catch(() => undefined);
47 }
48
49 +// Route keys only name routes of the session that wrote them; a saved one would make a tab rebuild
50 +// its page under a stale key, which UIKit animates as a pop and a push.
51 +function withoutRouteKeys(saved: WorkspaceSelections | undefined): WorkspaceSelections {
52 + const omitKey = <Selection extends { readonly key?: string }>({ key: _, ...rest }: Selection) =>
53 + rest;
54 + const { threads, pullRequests, settingsKey: _, ...rest } = saved ?? {};
55 + return {
56 + ...rest,
57 + ...(threads ? { threads: omitKey(threads) } : {}),
58 + ...(pullRequests ? { pullRequests: omitKey(pullRequests) } : {}),
59 + };
60 +}
61 +
62 /** Loads the saved selections once; pages visited before it resolves win over saved ones. */
63 export function hydrateWorkspaceSelections() {
64 if (!REMEMBERS) return Promise.resolve();
65 hydration ??= loadPreferences()
66 .then((preferences) => {
54 - selections = { ...preferences.workspaceSelections, ...selections };
67 + selections = { ...withoutRouteKeys(preferences.workspaceSelections), ...selections };
68 saved = selections;
69 AppState.addEventListener("change", (status) => {
70 if (status !== "active") save();
@@ -65,7 +78,10 @@ export function currentWorkspaceSelections() {
78 return selections;
79 }
80
68 -/** The navigation container's `onStateChange`: remembers the page each tab is showing. */
81 +/**
82 + * The navigation container's `onReady` and `onStateChange`: remembers the page each tab is
83 + * showing. The initial state, such as a cold start's reopened chat, reaches only `onReady`.
84 + */
85 export function recordWorkspaceSelections(state: NavigationState | undefined) {
86 if (!REMEMBERS || !state) return;
87 selections = workspaceSelectionsIn(state.routes.slice(0, state.index + 1), selections);
apps/mobile/src/lib/adaptive-navigation.test.ts deleted
-113
@@ -1,113 +0,0 @@
1 -import { describe, expect, it } from "vite-plus/test";
2 -
3 -import {
4 - resolveThreadSelectionNavigationAction,
5 - resolveThreadSelectionOverlayState,
6 -} from "./adaptive-navigation";
7 -
8 -describe("resolveThreadSelectionNavigationAction", () => {
9 - it("retains the draft screen despite its query-shaped path", () => {
10 - expect(
11 - resolveThreadSelectionNavigationAction({
12 - usesSplitView: true,
13 - pathname: "/threads?draft=local",
14 - workspaceRouteName: "Thread",
15 - }),
16 - ).toBe("set-params");
17 - });
18 - it("replaces nested thread content when a persistent sidebar selects a peer", () => {
19 - expect(
20 - resolveThreadSelectionNavigationAction({
21 - usesSplitView: true,
22 - pathname: "/threads/environment/thread/files/path",
23 - }),
24 - ).toBe("replace");
25 - });
26 -
27 - it("pushes from Home so the back stack survives collapsing to compact", () => {
28 - expect(
29 - resolveThreadSelectionNavigationAction({
30 - usesSplitView: true,
31 - pathname: "/",
32 - }),
33 - ).toBe("push");
34 - });
35 -});
36 -
37 -describe("resolveThreadSelectionOverlayState", () => {
38 - const stack = {
39 - key: "workspace",
40 - type: "stack",
41 - stale: false as const,
42 - routeNames: ["Home", "Thread", "ThreadFiles", "Connections", "SettingsLegal"],
43 - };
44 - const home = { key: "home", name: "Home" };
45 - const thread = {
46 - key: "thread",
47 - name: "Thread",
48 - params: { environmentId: "environment", threadId: "old-thread" },
49 - };
50 - const files = { key: "files", name: "ThreadFiles", params: thread.params };
51 - const settings = { key: "settings", name: "Connections" };
52 - const params = { environmentId: "environment", threadId: "new-thread" };
53 -
54 - it("replaces the underlying file route and dismisses every overlay above it", () => {
55 - expect(
56 - resolveThreadSelectionOverlayState({
57 - state: {
58 - ...stack,
59 - index: 4,
60 - routes: [home, thread, files, settings, { key: "legal", name: "SettingsLegal" }],
61 - },
62 - workspaceRouteKey: files.key,
63 - action: "replace",
64 - params,
65 - }),
66 - ).toEqual({ ...stack, index: 2, routes: [home, thread, { name: "Thread", params }] });
67 - });
68 -
69 - it("dismisses an overlay when selecting the current thread without replacing its route key", () => {
70 - expect(
71 - resolveThreadSelectionOverlayState({
72 - state: { ...stack, index: 2, routes: [home, thread, settings] },
73 - workspaceRouteKey: thread.key,
74 - action: "set-params",
75 - params: thread.params,
76 - }),
77 - ).toEqual({ ...stack, index: 1, routes: [home, thread] });
78 - });
79 -
80 - it.each([home, files])(
81 - "keeps $name in the back stack when pushing from beneath a sheet",
82 - (route) => {
83 - expect(
84 - resolveThreadSelectionOverlayState({
85 - state: { ...stack, index: 1, routes: [route, settings] },
86 - workspaceRouteKey: route.key,
87 - action: "push",
88 - params,
89 - }),
90 - ).toEqual({ ...stack, index: 1, routes: [route, { name: "Thread", params }] });
91 - },
92 - );
93 -});
94 -
95 -it("replacing a draft underneath an overlay removes its draft identity", () => {
96 - const result = resolveThreadSelectionOverlayState({
97 - state: {
98 - key: "root",
99 - type: "stack",
100 - stale: false,
101 - routeNames: ["Thread", "Connections"],
102 - index: 1,
103 - routes: [
104 - { key: "draft", name: "Thread", params: { draft: { draftId: "old" } } },
105 - { key: "settings", name: "Connections" },
106 - ],
107 - },
108 - workspaceRouteKey: "draft",
109 - action: "set-params",
110 - params: { environmentId: "env", threadId: "live" },
111 - });
112 - expect(result?.routes[0]?.params).toEqual({ environmentId: "env", threadId: "live" });
113 -});
apps/mobile/src/lib/adaptive-navigation.ts deleted
-56
@@ -1,56 +0,0 @@
1 -import type { NavigationState } from "@react-navigation/native";
2 -
3 -export type AdaptiveNavigationAction = "push" | "replace" | "set-params";
4 -
5 -const BASE_THREAD_ROUTE_PATTERN = /^\/threads\/[^/]+\/[^/]+\/?$/;
6 -
7 -export function isBaseThreadRoute(pathname: string): boolean {
8 - return BASE_THREAD_ROUTE_PATTERN.test(pathname) || /^\/new\/draft\/?$/.test(pathname);
9 -}
10 -
11 -/** Push from Home so it stays beneath Thread when split view collapses. */
12 -export function resolveThreadSelectionNavigationAction(input: {
13 - readonly usesSplitView: boolean;
14 - readonly pathname: string;
15 - readonly workspaceRouteName?: string;
16 -}): AdaptiveNavigationAction {
17 - if (!input.usesSplitView || input.pathname === "/") {
18 - return "push";
19 - }
20 -
21 - return input.workspaceRouteName === "Thread" || isBaseThreadRoute(input.pathname)
22 - ? "set-params"
23 - : "replace";
24 -}
25 -
26 -export function resolveThreadSelectionOverlayState(input: {
27 - readonly state: NavigationState | undefined;
28 - readonly workspaceRouteKey: string | undefined;
29 - readonly action: AdaptiveNavigationAction;
30 - readonly params: ReactNavigation.RootParamList["Thread"];
31 -}) {
32 - if (input.state === undefined) return null;
33 - const workspaceIndex = input.state.routes.findIndex(
34 - (route) => route.key === input.workspaceRouteKey,
35 - );
36 - if (workspaceIndex < 0 || workspaceIndex >= input.state.index) return null;
37 -
38 - const workspaceRoute = input.state.routes[workspaceIndex];
39 - const routes = input.state.routes.slice(0, workspaceIndex + (input.action === "push" ? 1 : 0));
40 - return {
41 - ...input.state,
42 - index: routes.length,
43 - routes: [
44 - ...routes,
45 - input.action === "set-params" && workspaceRoute?.name === "Thread"
46 - ? { ...workspaceRoute, params: input.params }
47 - : { name: "Thread", params: input.params },
48 - ],
49 - };
50 -}
51 -
52 -export function resolveFileSelectionNavigationAction(input: {
53 - readonly hasPersistentFileInspector: boolean;
54 -}): AdaptiveNavigationAction {
55 - return input.hasPersistentFileInspector ? "replace" : "push";
56 -}
apps/mobile/src/lib/android-workspace-navigation.test.ts
+18 -93
@@ -11,7 +11,6 @@ import {
11 parentThreadIsBelow,
12 resetAndroidWorkspace,
13 returnToAndroidWorkspaceList,
14 - type AndroidWorkspaceDestination,
14 } from "./android-workspace-navigation";
15 import type { RootStackResetAction } from "./root-stack-reset";
16
@@ -69,15 +68,8 @@ function apply(
68 return router.getRehydratedState(result, options);
69 }
70
72 -function select(
73 - state: ReturnType<typeof router.getInitialState>,
74 - destination?: AndroidWorkspaceDestination,
75 - reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],
76 -) {
77 - return apply(
78 - state,
79 - CommonActions.reset(androidWorkspaceNavigationState(state, destination, reviewers)),
80 - );
71 +function withThread() {
72 + return apply(router.getInitialState(options), StackActions.push(thread.name, thread.params));
73 }
74
75 function legacyHistory() {
@@ -92,69 +84,8 @@ function names(state: ReturnType<typeof router.getInitialState>) {
84 }
85
86 describe("Android workspace navigation", () => {
95 - it("replaces cross-tab history with one detail and returns directly to its list", () => {
96 - const previous = legacyHistory();
97 - const state = select(previous, pullRequest);
98 - expect(names(state)).toEqual(["Home", "PullRequest"]);
99 - expect(state.routes[0]?.key).toBe(previous.routes[0]?.key);
100 - expect(state.routes[1]?.key).toBe(previous.routes[2]?.key);
101 - expect(names(apply(state, StackActions.pop()))).toEqual(["Home"]);
102 - });
103 -
104 - it("replaces peer thread selections without leaving the previous thread underneath", () => {
105 - const first = select(router.getInitialState(options), thread);
106 - const second = select(first, {
107 - name: "Thread",
108 - params: { ...thread.params, threadId: "thread-b" },
109 - });
110 - expect(names(second)).toEqual(["Home", "Thread"]);
111 - expect(second.routes[1]?.params).toEqual({ ...thread.params, threadId: "thread-b" });
112 - expect(second.routes[1]?.key).not.toBe(first.routes[1]?.key);
113 - expect(names(apply(second, StackActions.pop()))).toEqual(["Home"]);
114 - });
115 -
116 - it("creates Home beneath cold-linked details and gives direct list escape", () => {
117 - const initial = router.getInitialState(options);
118 - const cold = apply(initial, CommonActions.reset({ index: 0, routes: [pullRequest] }));
119 - expect(names(select(cold, pullRequest))).toEqual(["Home", "PullRequest"]);
120 - expect(names(select(cold))).toEqual(["Home"]);
121 - });
122 -
123 - it("keeps a request-review flow above the chosen PR instead of an old chat", () => {
124 - const state = select(legacyHistory(), pullRequest, pullRequest.params);
125 - expect(names(state)).toEqual(["Home", "PullRequest", "PullRequestReviewers"]);
126 - const back = apply(state, StackActions.pop());
127 - expect(names(back)).toEqual(["Home", "PullRequest"]);
128 - expect(back.routes[back.index]?.params).toEqual(pullRequest.params);
129 - });
130 -
131 - it.each(["ThreadFiles", "ThreadTerminal", "GitOverview"])(
132 - "returns to chat when its sidebar row is selected from %s",
133 - (route) => {
134 - const detail = select(router.getInitialState(options), thread);
135 - const nested = apply(detail, StackActions.push(route, thread.params));
136 - const selected = select(nested, thread);
137 - expect(names(selected)).toEqual(["Home", "Thread"]);
138 - expect(selected.routes[1]?.key).toBe(detail.routes[1]?.key);
139 - expect(names(apply(selected, StackActions.pop()))).toEqual(["Home"]);
140 - },
141 - );
142 -
143 - it.each([{ environmentId: "environment-b" }, { repository: "owner/other" }])(
144 - "does not reuse another PR's key when its scope differs: %o",
145 - (change) => {
146 - const previous = select(router.getInitialState(options), pullRequest);
147 - const state = select(previous, {
148 - name: "PullRequest",
149 - params: { ...pullRequest.params, ...change },
150 - });
151 - expect(state.routes[1]?.key).not.toBe(previous.routes[1]?.key);
152 - expect(state.routes[1]?.params).toEqual({ ...pullRequest.params, ...change });
153 - },
154 - );
155 -
87 it("returns to a distinct previous thread, otherwise to the workspace list", () => {
157 - const parent = select(router.getInitialState(options), thread);
88 + const parent = withThread();
89 let state = apply(
90 parent,
91 StackActions.push("Thread", { ...thread.params, threadId: "child-a" }),
@@ -206,7 +137,7 @@ describe("Android workspace navigation", () => {
137 });
138
139 it("opens a linked thread above the current one so Back returns to it", () => {
209 - const parent = select(router.getInitialState(options), thread);
140 + const parent = withThread();
141 const child = { ...thread.params, threadId: "child-a" };
142 const open = (
143 state: ReturnType<typeof router.getInitialState>,
@@ -230,7 +161,7 @@ describe("Android workspace navigation", () => {
161 });
162
163 it("recognizes a parent only when its environment and thread are immediately below", () => {
233 - const parent = select(router.getInitialState(options), thread);
164 + const parent = withThread();
165 const child = apply(
166 parent,
167 StackActions.push("Thread", { ...thread.params, threadId: "child-a" }),
@@ -259,35 +190,29 @@ describe("Android workspace navigation", () => {
190 getParent: () => undefined,
191 getState: () => root,
192 };
262 - resetAndroidWorkspace(
263 - {
264 - dispatch: (action) => actions.push(action),
265 - getParent: () => rootNavigation,
266 - getState: () => nested,
267 - },
268 - thread,
269 - );
193 + resetAndroidWorkspace({
194 + dispatch: (action) => actions.push(action),
195 + getParent: () => rootNavigation,
196 + getState: () => nested,
197 + });
198 const [action] = actions;
199 expect(action?.target).toBe(root.key);
272 - expect(names(apply(root, action!))).toEqual(["Home", "Thread"]);
200 + expect(names(apply(root, action!))).toEqual(["Home"]);
201 });
202
203 it("resets from the navigation container before any navigation action", () => {
204 const root = router.getInitialState(options);
205 const actions: RootStackResetAction[] = [];
206 // The container only learns the root state after the first action.
279 - resetAndroidWorkspace(
280 - {
281 - dispatch: (action) => actions.push(action),
282 - getParent: () => undefined,
283 - getState: () => undefined,
284 - getRootState: () => root,
285 - },
286 - thread,
287 - );
207 + resetAndroidWorkspace({
208 + dispatch: (action) => actions.push(action),
209 + getParent: () => undefined,
210 + getState: () => undefined,
211 + getRootState: () => root,
212 + });
213 const [action] = actions;
214 expect(action?.target).toBe(root.key);
290 - expect(names(apply(root, action!))).toEqual(["Home", "Thread"]);
215 + expect(names(apply(root, action!))).toEqual(["Home"]);
216 });
217 });
218
apps/mobile/src/lib/android-workspace-navigation.ts
+5 -38
@@ -1,10 +1,6 @@
1 import type { NavigationState } from "@react-navigation/native";
2 import { resetRootStack, type RootStackNavigation } from "./root-stack-reset";
3
4 -export type AndroidWorkspaceDestination =
5 - | { readonly name: "Thread"; readonly params: ReactNavigation.RootParamList["Thread"] }
6 - | { readonly name: "PullRequest"; readonly params: ReactNavigation.RootParamList["PullRequest"] };
7 -
4 function androidWorkspaceBackReturnsToThread(state: NavigationState) {
5 const current = state.routes[state.index];
6 const params = current?.params as ReactNavigation.RootParamList["Thread"] | undefined;
@@ -16,43 +12,14 @@ function androidWorkspaceBackReturnsToThread(state: NavigationState) {
12 );
13 }
14
19 -export function androidWorkspaceNavigationState(
20 - state: NavigationState,
21 - destination?: AndroidWorkspaceDestination,
22 - reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],
23 -) {
15 +/** The root stack with only the workspace list. */
16 +export function androidWorkspaceNavigationState(state: NavigationState) {
17 const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" };
25 - if (!destination) return { ...state, index: 0, routes: [home] };
26 - const identity =
27 - destination.name === "Thread"
28 - ? ["environmentId", "threadId"]
29 - : ["environmentId", "projectId", "repository", "number", "host"];
30 - const params = destination.params as Readonly<Record<string, unknown>>;
31 - const existing = state.routes.findLast((route) => {
32 - if (route.name !== destination.name) return false;
33 - const current = route.params as Readonly<Record<string, unknown>> | undefined;
34 - return identity.every((key) => current?.[key] === params[key]);
35 - });
36 - return {
37 - ...state,
38 - index: reviewers ? 2 : 1,
39 - routes: [
40 - home,
41 - { ...existing, ...destination },
42 - ...(reviewers ? [{ name: "PullRequestReviewers", params: reviewers }] : []),
43 - ],
44 - };
18 + return { ...state, index: 0, routes: [home] };
19 }
20
47 -/** Resets the root stack to a workspace list or detail. */
48 -export function resetAndroidWorkspace(
49 - navigation: RootStackNavigation,
50 - destination?: AndroidWorkspaceDestination,
51 - reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],
52 -) {
53 - resetRootStack(navigation, (state) =>
54 - androidWorkspaceNavigationState(state, destination, reviewers),
55 - );
21 +export function resetAndroidWorkspace(navigation: RootStackNavigation) {
22 + resetRootStack(navigation, androidWorkspaceNavigationState);
23 }
24
25 export function parentThreadIsBelow(
apps/mobile/src/native/createV5StackNavigator.ios.tsx
+18 -6
@@ -54,12 +54,24 @@ export function modalEnvelopeOptions(options: NativeStackNavigationOptions) {
54
55 /** Keep outgoing screens until UIKit completes its pop, as required by v5. */
56 export function V5CardStackView(
57 - props: V5StackViewProps & { readonly onRootVisibilityChange?: (visible: boolean) => void },
57 + props: V5StackViewProps & {
58 + readonly onRootVisibilityChange?: (visible: boolean) => void;
59 + /** The card native Back is popping, which the router still shows until the pop finishes. */
60 + readonly onNativePopChange?: (key: string | null) => void;
61 + },
62 ) {
63 const { preventedRoutes } = usePreventRemoveContext();
64 // Options a screen set inside this workspace tab slot, over its route's.
65 const slot = use(WorkspaceSlotOptionsContext);
66 const nativePopSource = useRef<string | null>(null);
67 + const { onNativePopChange } = props;
68 + const setNativePopSource = useCallback(
69 + (key: string | null) => {
70 + nativePopSource.current = key;
71 + onNativePopChange?.(key);
72 + },
73 + [onNativePopChange],
74 + );
75 const [screens, setScreens] = useState({
76 completedNativeDismissals: new Set<string>(),
77 nativeCompletingPops: new Set<string>(),
@@ -121,11 +133,11 @@ export function V5CardStackView(
133 descriptors,
134 };
135 });
124 - if (nativePopSource.current === key) nativePopSource.current = null;
136 + if (nativePopSource.current === key) setNativePopSource(null);
137 const action = nativeStackPopAction(state, key);
138 if (action) props.navigation.dispatch(action);
139 },
128 - [props.navigation, setScreens],
140 + [props.navigation, setNativePopSource, setScreens],
141 );
142 const removeDismissed = useCallback(
143 (key: string) => {
@@ -177,7 +189,7 @@ export function V5CardStackView(
189 onDidAppear={() => {
190 const source = nativePopSource.current;
191 if (source === route.key) {
180 - nativePopSource.current = null;
192 + setNativePopSource(null);
193 } else if (source) {
194 const state = props.navigation.getState();
195 const action = nativeStackPopAction(state, source, route.key);
@@ -194,7 +206,7 @@ export function V5CardStackView(
206 ...poppedKeys,
207 ]),
208 }));
197 - nativePopSource.current = null;
209 + setNativePopSource(null);
210 props.navigation.dispatch(action);
211 }
212 }
@@ -209,7 +221,7 @@ export function V5CardStackView(
221 const state = props.navigation.getState();
222 // Only native Back leaves the disappearing card active; JS navigation already changed history.
223 if (state.index > 0 && state.routes[state.index]?.key === route.key) {
212 - nativePopSource.current = route.key;
224 + setNativePopSource(route.key);
225 }
226 props.navigation.emit({
227 type: "transitionStart",
apps/mobile/src/native/useOpenPullRequest.ts
+6 -5
@@ -2,7 +2,7 @@ import { useNavigation, useRoute, StackActions } from "@react-navigation/native"
2 import { nativePullRequestDestination } from "../lib/pullRequestNavigation";
3 import { useCallback } from "react";
4 import { Platform } from "react-native";
5 -import { resetAndroidWorkspace } from "../lib/android-workspace-navigation";
5 +import { useSelectWorkspaceDetail } from "../features/workspace/useSelectWorkspaceDetail";
6 import { EnvironmentId, ThreadId } from "@t3tools/contracts";
7 import { useProjects, useThreadShell } from "../state/entities";
8 import { tryOpenExternalUrl } from "../lib/openExternalUrl";
@@ -14,6 +14,7 @@ type PullRequestContext = { readonly environmentId: string; readonly projectId:
14 // Avoid useRoute so layouts without route context can open any thread's pull requests.
15 export function useNavigateToPullRequest(options?: { readonly replace?: boolean }) {
16 const navigation = useNavigation();
17 + const selectDetail = useSelectWorkspaceDetail();
18 const projects = useProjects();
19 const replace = options?.replace;
20 return useCallback(
@@ -27,13 +28,13 @@ export function useNavigateToPullRequest(options?: { readonly replace?: boolean
28 (environmentId) => serverConfigs.get(environmentId)?.environment.capabilities,
29 );
30 if (!params) return tryOpenExternalUrl(url, "pull-request");
30 - if (Platform.OS === "android")
31 - resetAndroidWorkspace(navigation, { name: "PullRequest", params });
31 + // Android shows one page at a time; iOS opens it over the current page, so Back returns.
32 + if (Platform.OS === "android") selectDetail({ name: "PullRequest", params });
33 else if (replace) navigation.dispatch(StackActions.replace("PullRequest", params));
33 - else navigation.navigate("PullRequest", params);
34 + else navigation.dispatch(StackActions.push("PullRequest", params));
35 return true;
36 },
36 - [navigation, projects, replace],
37 + [navigation, projects, replace, selectDetail],
38 );
39 }
40
docs/internals/mobile-navigation.md
+26
@@ -5,6 +5,32 @@ so UIKit can animate the header within one navigation controller. The iPad sideb
5 has its own stack. Splitting Home and threads between controllers loses that
6 continuous transition.
7
8 +## Selecting versus drilling in
9 +
10 +Opening a page has two intents, and each has one action:
11 +
12 +- **Select** shows a thread or pull request as the workspace's only page, the
13 + way a list row does. Everything that selects (rows, the command palette,
14 + compose, notifications, deep links) uses
15 + [`selectWorkspaceDetail`](../../apps/mobile/src/features/workspace/workspace-detail-selection.ts),
16 + which the root stack's router handles. The resulting stack is the same on
17 + phones, collapsed splits, and expanded splits. Only route keys differ: the
18 + page already showing keeps its key, so the detail column updates in place
19 + instead of pushing.
20 +- **Drill in** opens a page over the current one so Back returns, with
21 + `StackActions.push`.
22 +
23 +`navigate` to `Thread` or `PullRequest` is rejected by lint, because it pushes
24 +or updates in place depending on what happens to be on top. Never infer the
25 +choice from transition events: UIKit reports the sidebar column appearing in
26 +split views too. The one native signal the router uses is the card native Back
27 +is popping. The workspace navigator reports it, and a selection never reuses
28 +that card.
29 +
30 +Beside the list, Settings pages share one native screen whose content swaps,
31 +like the system Settings app. A route per page would pop and push the column,
32 +and would unmount its header configuration, which hides the navigation bar.
33 +
34 ## UIKit constraints
35
36 The [react-native-screens patch](../../patches/react-native-screens@4.26.2.patch)
oxlint-plugin-t3code/index.ts
+2
@@ -12,6 +12,7 @@ import noLowValueComments from "./rules/no-low-value-comments.ts";
12 import noManualMemo from "./rules/no-manual-memo.ts";
13 import noManualEffectRuntimeInTests from "./rules/no-manual-effect-runtime-in-tests.ts";
14 import noMobileUniwindThemeEscapeHatches from "./rules/no-mobile-uniwind-theme-escape-hatches.ts";
15 +import noAmbiguousDetailNavigation from "./rules/no-ambiguous-detail-navigation.ts";
16 import noMobilePullRequestGlyphLiterals from "./rules/no-mobile-pull-request-glyph-literals.ts";
17 import noNativeTitleTooltip from "./rules/no-native-title-tooltip.ts";
18 import noOutsetStateIndicators from "./rules/no-outset-state-indicators.ts";
@@ -47,6 +48,7 @@ export default definePlugin({
48 "no-manual-effect-runtime-in-tests": noManualEffectRuntimeInTests,
49 "no-manual-memo": noManualMemo,
50 "no-mobile-uniwind-theme-escape-hatches": noMobileUniwindThemeEscapeHatches,
51 + "no-ambiguous-detail-navigation": noAmbiguousDetailNavigation,
52 "no-mobile-pull-request-glyph-literals": noMobilePullRequestGlyphLiterals,
53 "no-native-title-tooltip": noNativeTitleTooltip,
54 "no-outset-state-indicators": noOutsetStateIndicators,
oxlint-plugin-t3code/rules/no-ambiguous-detail-navigation.test.ts new
+25
@@ -0,0 +1,25 @@
1 +import { describe } from "@effect/vitest";
2 +
3 +import { createOxlintRuleHarness } from "../test/utils.ts";
4 +
5 +const rule = createOxlintRuleHarness("t3code/no-ambiguous-detail-navigation", {
6 + filename: "apps/mobile/src/features/threads/ThreadFeed.tsx",
7 +});
8 +
9 +describe("t3code/no-ambiguous-detail-navigation", () => {
10 + rule.valid(
11 + "allows selections, explicit pushes, and other routes",
12 + `
13 + selectDetail({ name: "Thread", params });
14 + navigation.dispatch(StackActions.push("PullRequest", params));
15 + navigation.navigate("ThreadFiles", params);
16 + `,
17 + );
18 +
19 + rule.invalid("reports navigating to a thread", `navigation.navigate("Thread", params);`);
20 +
21 + rule.invalid(
22 + "reports a navigate action to a pull request",
23 + `navigation.dispatch(CommonActions.navigate("PullRequest", params));`,
24 + );
25 +});
oxlint-plugin-t3code/rules/no-ambiguous-detail-navigation.ts new
+35
@@ -0,0 +1,35 @@
1 +import { defineRule, type ESTree } from "@oxlint/plugins";
2 +
3 +const DETAIL_ROUTES = new Set(["Thread", "PullRequest"]);
4 +
5 +const MESSAGE =
6 + "`navigate` to a Thread or PullRequest pushes or updates in place depending on what is on top. Use useSelectWorkspaceDetail to show it as the page, or StackActions.push to open it over the current one.";
7 +
8 +function calleeName(callee: ESTree.Expression) {
9 + if (callee.type === "Identifier") return callee.name;
10 + if (callee.type === "MemberExpression" && callee.property.type === "Identifier") {
11 + return callee.property.name;
12 + }
13 + return null;
14 +}
15 +
16 +export default defineRule({
17 + meta: {
18 + type: "problem",
19 + docs: {
20 + description:
21 + "Disallow `navigate` to the workspace's detail routes; selections and drill-ins each have one explicit action.",
22 + },
23 + },
24 + create(context) {
25 + return {
26 + CallExpression(node) {
27 + if (calleeName(node.callee as ESTree.Expression) !== "navigate") return;
28 + const [route] = node.arguments;
29 + if (route?.type !== "Literal" || typeof route.value !== "string") return;
30 + if (!DETAIL_ROUTES.has(route.value)) return;
31 + context.report({ node, message: MESSAGE });
32 + },
33 + };
34 + },
35 +});
vite.config.ts
+5
@@ -435,6 +435,11 @@ export default defineConfig({
435 ],
436 rules: { "t3code/no-mobile-pull-request-glyph-literals": "error" },
437 },
438 + {
439 + files: ["apps/mobile/src/**"],
440 + excludeFiles: ["**/*.test.{ts,tsx}"],
441 + rules: { "t3code/no-ambiguous-detail-navigation": "error" },
442 + },
443 {
444 // Raw ResizeObserver state commits miss the paint; observeResize flushes derived layout together.
445 files: ["apps/web/src/**"],