Skip to content
TypeScript

feat(mobile): Settings is a workspace tab, and tabs never open on an empty detail (#24524)

Julius Marminge5848bc263bf4
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index 2ab9a1a191b..f2e44cec71c 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -31,6 +31,13 @@ import { useUiRuntimeMemoryWarningGc } from "./lib/useUiRuntimeMemoryWarningGc";
import { SubscriptionUsageCoordinator } from "./widgets/SubscriptionUsageCoordinator";
import { VoiceInputProvider } from "./features/voice-input/VoiceInputProvider";
import { GlobalVoiceInputControl } from "./features/voice-input/GlobalVoiceInputControl";
+import { restoreSettingsLinkState } from "./features/settings/settings-navigation";
+import {
+ hydrateWorkspaceSelections,
+ launchWorkspaceURL,
+ recordWorkspaceSelections,
+ settingsLinkPage,
+} from "./features/workspace/workspace-selection-store";
import { NativeLayoutMetricsProvider } from "./native/native-layout-metrics";
import "../global.css";
@@ -40,13 +47,18 @@ if (process.env.EXPO_PUBLIC_SHOWCASE === "1") {
}
void SplashScreen.preventAutoHideAsync().catch(() => {});
+void hydrateWorkspaceSelections();
const appLinking = {
prefixes: [Linking.createURL("/"), "t3code://", "t3code-dev://", "t3code-preview://"],
config: { initialRouteName: "Home" },
filter: shouldHandleAppLink,
+ getInitialURL: async () => (await Linking.getInitialURL()) ?? (await launchWorkspaceURL()),
getStateFromPath: (path: string, options: Parameters<typeof getStateFromPath>[1]) =>
- restoreDraftLinkState(getStateFromPath(path, options), path),
+ restoreSettingsLinkState(
+ restoreDraftLinkState(getStateFromPath(path, options), path),
+ settingsLinkPage(),
+ ),
};
const Navigation = createStaticNavigation(RootStack);
@@ -107,7 +119,11 @@ function AppContent() {
<GlobalVoiceInputControl>
<NativeLayoutMetricsProvider>
<IncomingShareProvider>
- <Navigation linking={appLinking} theme={navigationTheme} />
+ <Navigation
+ linking={appLinking}
+ theme={navigationTheme}
+ onStateChange={recordWorkspaceSelections}
+ />
</IncomingShareProvider>
<Dialog.Host />
<ThreadArrangementHost />
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx
index bcd1a97ce52..2fed9166e27 100644
--- a/apps/mobile/src/Stack.tsx
+++ b/apps/mobile/src/Stack.tsx
@@ -3,7 +3,6 @@ import { ComponentCatalogScreen } from "./features/development/ComponentCatalogS
import { PullRequestGuideStopScreen } from "./features/pull-requests/guide/PullRequestGuideScreen";
import { PullRequestInlineCommentScreen } from "./features/pull-requests/PullRequestInlineCommentScreen";
import { PullRequestDiscussionScreen } from "./features/pull-requests/PullRequestDiscussionScreen";
-import { createV5SheetStackNavigator } from "./native/createV5StackNavigator";
import { createWorkspaceStackNavigator } from "./features/layout/createWorkspaceStackNavigator";
import {
createPathConfigForStaticNavigation,
@@ -25,7 +24,6 @@ import { androidWorkspaceDestinationAnimation } from "./lib/android-workspace-na
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
import { WorkspaceConnectionStatusProvider } from "./features/home/WorkspaceConnectionTitle";
import { WorkspaceRootScreen } from "./features/workspace/WorkspaceRootScreen";
-import { AndroidWorkspaceSettings } from "./features/workspace/AndroidWorkspaceSettings";
import { AndroidWorkspaceTabsProvider } from "./features/workspace/AndroidWorkspaceTabsProvider";
import {
PullRequestRouteScreen,
@@ -109,7 +107,6 @@ import {
ScheduledTaskModelPickerRouteScreen,
ScheduledTaskBranchPickerRouteScreen,
} from "./features/settings/ScheduledTaskPickerScreens";
-import { ScheduledTaskEditorProvider } from "./features/settings/scheduled-task-editor";
import { SettingsKeyboardRouteScreen } from "./features/settings/SettingsKeyboardRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsMicrophoneRouteScreen } from "./features/settings/SettingsMicrophoneRouteScreen";
@@ -126,6 +123,12 @@ import { SettingsNotificationsRouteScreen } from "./features/settings/SettingsNo
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { SettingsThreadsRouteScreen } from "./features/settings/SettingsThreadsRouteScreen";
import { SettingsEnvironmentFilterProvider } from "./features/settings/settings-environment-filter";
+import { openSettings, settingsOpenIn } from "./features/settings/settings-navigation";
+import { DEFAULT_SETTINGS_PAGE } from "./features/workspace/workspace-tab-navigation";
+import {
+ isWorkspaceOverlayRoute,
+ registerPresentedRoutes,
+} from "./features/layout/workspace-overlay-routes";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
SettingsLegalDocumentCloseHeaderButton,
@@ -212,8 +215,6 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
presentation: "fullScreenModal",
};
-const NESTED_NAVIGATOR_OPTIONS = { nativeContentInsetHorizontally: false, headerShown: false };
-
// Thread settings keep the Duo's vertical bar so cancel, search, filter and confirm sit in the
// rail. The picker stack spans the sheet so its header reaches the rail, and insets its content.
const THREAD_SETTINGS_SHEET_OPTIONS = {
@@ -223,295 +224,253 @@ const THREAD_SETTINGS_SHEET_OPTIONS = {
nativeContentInsetHorizontally: false,
};
-const SettingsContentStack = createV5SheetStackNavigator({
- initialRouteName: "Settings",
- screenOptions: {
- ...GLASS_HEADER_OPTIONS,
- unstable_navigationItemStyle: undefined,
- },
- screens: {
- Settings: createNativeStackScreen({
- screen: SettingsRouteScreen,
- linking: "",
- options: {
- title: "Settings",
- // Android draws its own app bar here. Hidden only from inside the screen, the native one
- // showed for the first frame of the Settings tab and pushed the page down.
- headerShown: Platform.OS !== "android",
- headerBackVisible: false,
- },
- }),
- SettingsEnvironments: createNativeStackScreen({
- screen: SettingsEnvironmentsRouteScreen,
- linking: "environments",
- options: {
- title: "Environments",
- },
- }),
- SettingsEnvironmentDetail: createNativeStackScreen({
- screen: SettingsEnvironmentDetailRouteScreen,
- linking: "environments/:environmentId",
- options: { title: "Environment" },
- }),
- SettingsEnvironmentNewThreads: createNativeStackScreen({
- screen: SettingsEnvironmentNewThreadsRouteScreen,
- linking: "new-threads",
- options: { title: "New threads" },
- }),
- SettingsEnvironmentSourceControl: createNativeStackScreen({
- screen: SettingsEnvironmentSourceControlRouteScreen,
- linking: "source-control",
- options: { title: "Source control" },
- }),
- SettingsEnvironmentAgentBehavior: createNativeStackScreen({
- screen: SettingsEnvironmentAgentBehaviorRouteScreen,
- linking: "agent-behavior",
- options: { title: "Agent behavior" },
- }),
- SettingsProviderAccounts: createNativeStackScreen({
- screen: SettingsProviderAccountsRouteScreen,
- linking: "provider-accounts",
- options: { title: "Provider accounts" },
- }),
- SettingsEnvironmentMaintenance: createNativeStackScreen({
- screen: SettingsEnvironmentMaintenanceRouteScreen,
- linking: "maintenance",
- options: { title: "Maintenance" },
- }),
- SettingsNotifications: createNativeStackScreen({
- screen: SettingsNotificationsRouteScreen,
- linking: "notifications",
- options: { title: "Notifications" },
- }),
- SettingsThreads: createNativeStackScreen({
- screen: SettingsThreadsRouteScreen,
- linking: "thread-preferences",
- options: { title: "Thread behavior" },
- }),
- SettingsAbout: createNativeStackScreen({
- screen: SettingsAboutRouteScreen,
- linking: "about",
- options: { title: "About T3 Code" },
- }),
- SettingsEnvironmentNew: createNativeStackScreen({
- screen: ConnectionsNewRouteScreen,
- linking: "environment-new",
- options: {
- title: "Add Environment",
- },
- }),
- SettingsArchive: createNativeStackScreen({
- screen: ArchivedThreadsRouteScreen,
- linking: "archive",
- options: {
- title: "Archived Threads",
- },
- }),
- SettingsNavigation: createNativeStackScreen({
- screen: SettingsNavigationRouteScreen,
- linking: "navigation-tabs",
- options: { title: "Navigation tabs" },
- }),
- SettingsAppearance: createNativeStackScreen({
- screen: SettingsAppearanceRouteScreen,
- linking: "appearance",
- options: {
- title: "Appearance",
- },
- }),
- SettingsProjectGrouping: createNativeStackScreen({
- screen: SettingsProjectGroupingRouteScreen,
- linking: "project-grouping",
- options: {
- title: "Organization",
- },
- }),
- SettingsOrganization: createNativeStackScreen({
- screen: SettingsProjectGroupingRouteScreen,
- linking: "organization",
- options: {
- title: "Organization",
- },
- }),
- SettingsProjectOverview: createNativeStackScreen({
- screen: SettingsProjectOverviewRouteScreen,
- linking: "project",
- options: { title: "Project overview" },
- }),
- SettingsKeyboard: createNativeStackScreen({
- screen: SettingsKeyboardRouteScreen,
- linking: "keyboard",
- options: {
- title: "Keyboard",
- },
- }),
- SettingsMicrophone: createNativeStackScreen({
- screen: SettingsMicrophoneRouteScreen,
- linking: "microphone",
- options: {
- title: "Microphone",
- },
- }),
- SettingsFollowUp: createNativeStackScreen({
- screen: SettingsFollowUpRouteScreen,
- linking: "follow-ups",
- options: {
- title: "Follow-ups",
- },
- }),
- SettingsScheduledTasks: createNativeStackScreen({
- screen: SettingsScheduledTasksRouteScreen,
- linking: "scheduled-tasks",
- options: {
- title: "Scheduled Tasks",
- headerTitleStyle: { fontSize: 16, fontWeight: "800" },
- },
- }),
- SettingsScheduledTaskNew: createNativeStackScreen({
- screen: SettingsScheduledTaskNewRouteScreen,
- linking: "scheduled-tasks/new",
- options: { title: "New scheduled task" },
- }),
- SettingsScheduledTaskEdit: createNativeStackScreen({
- screen: SettingsScheduledTaskEditRouteScreen,
- options: { title: "Edit scheduled task" },
- }),
- SettingsScheduledTaskBranch: createNativeStackScreen({
- screen: ScheduledTaskBranchPickerRouteScreen,
- options: { title: "Base branch" },
- }),
- SettingsScheduledTaskModel: createNativeStackScreen({
- screen: ScheduledTaskModelPickerRouteScreen,
- options: {
- headerShown: false,
- ...(Platform.OS === "android"
- ? { presentation: "card" as const }
- : {
- ...THREAD_SETTINGS_SHEET_OPTIONS,
- }),
- },
- }),
- SettingsClientStorage: createNativeStackScreen({
- screen: SettingsClientStorageRouteScreen,
- linking: "client-storage",
- options: {
- title: "Client Storage",
- },
- }),
- SettingsDiagnostics: createNativeStackScreen({
- screen: SettingsDiagnosticsRouteScreen,
- linking: "diagnostics",
- options: {
- title: "Diagnostics",
- },
- }),
- // Its params are a tap-time snapshot, not a stable resource address: `now` is the wall-clock
- // of the tap, `environmentIds` is the usage screen's local filter selection, and the window
- // id/kind identify freshly aggregated pools. React Navigation round-trips non-path params
- // through the URL as query strings, so a path here would bake in a permanently stale
- // timestamp and filter.
- SettingsUsageAccount: createNativeStackScreen({
- screen: UsageLimitAccountScreen,
- options: { title: "Account" },
- }),
- SettingsOpenSourceLicenses: createNativeStackScreen({
- screen: SettingsOpenSourceLicensesRouteScreen,
- linking: "open-source-licenses",
- options: {
- title: "Open source licenses",
- },
- }),
- SettingsOpenSourceLicense: createNativeStackScreen({
- screen: SettingsOpenSourceLicenseRouteScreen,
- linking: "open-source-licenses/:entryKey",
- options: {
- title: "License notice",
- },
- }),
- SettingsUsage: createNativeStackScreen({
- screen: UsageRouteScreen,
- linking: "usage",
- options: {
- title: "Usage",
- },
- }),
- },
-});
+// Settings pages are root routes so they share the workspace's columns and header. The
+// `Settings` route marks the Settings tab as open (see settings-navigation.ts).
+const SETTINGS_PAGE_OPTIONS = SHEET_GLASS_HEADER_OPTIONS;
-// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.
-const SettingsSheetStack = createV5SheetStackNavigator({
- initialRouteName: "SettingsContent",
- screenOptions: {
- headerShown: false,
- },
- screens: {
- SettingsContent: createNativeStackScreen({
- screen: SettingsContentStack,
- options: NESTED_NAVIGATOR_OPTIONS,
- linking: "",
- layout: ({ children }) => (
- <SettingsEnvironmentFilterProvider>
- <ScheduledTaskEditorProvider>{children}</ScheduledTaskEditorProvider>
- </SettingsEnvironmentFilterProvider>
- ),
- }),
- SettingsAuth: createNativeStackScreen({
- screen: SettingsAuthRouteScreen,
- linking: "auth",
- }),
- SettingsWaitlist: createNativeStackScreen({
- screen: SettingsAuthRouteScreen,
- linking: "waitlist",
- }),
- },
-});
+const SETTINGS_SCREENS = {
+ Settings: createNativeStackScreen({
+ screen: SettingsRouteScreen,
+ linking: "settings",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Settings",
+ ...(Platform.OS === "android" ? { animation: "none" as const } : {}),
+ // Android draws its own app bar here. Hidden only from inside the screen, the native one
+ // showed for the first frame of the Settings tab and pushed the page down.
+ headerShown: Platform.OS !== "android",
+ headerBackVisible: false,
+ },
+ }),
+ SettingsEnvironments: createNativeStackScreen({
+ screen: SettingsEnvironmentsRouteScreen,
+ linking: "settings/environments",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Environments",
+ },
+ }),
+ SettingsEnvironmentDetail: createNativeStackScreen({
+ screen: SettingsEnvironmentDetailRouteScreen,
+ linking: "settings/environments/:environmentId",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Environment" },
+ }),
+ SettingsEnvironmentNewThreads: createNativeStackScreen({
+ screen: SettingsEnvironmentNewThreadsRouteScreen,
+ linking: "settings/new-threads",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "New threads" },
+ }),
+ SettingsEnvironmentSourceControl: createNativeStackScreen({
+ screen: SettingsEnvironmentSourceControlRouteScreen,
+ linking: "settings/source-control",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Source control" },
+ }),
+ SettingsEnvironmentAgentBehavior: createNativeStackScreen({
+ screen: SettingsEnvironmentAgentBehaviorRouteScreen,
+ linking: "settings/agent-behavior",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Agent behavior" },
+ }),
+ SettingsProviderAccounts: createNativeStackScreen({
+ screen: SettingsProviderAccountsRouteScreen,
+ linking: "settings/provider-accounts",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Provider accounts" },
+ }),
+ SettingsEnvironmentMaintenance: createNativeStackScreen({
+ screen: SettingsEnvironmentMaintenanceRouteScreen,
+ linking: "settings/maintenance",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Maintenance" },
+ }),
+ SettingsNotifications: createNativeStackScreen({
+ screen: SettingsNotificationsRouteScreen,
+ linking: "settings/notifications",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Notifications" },
+ }),
+ SettingsThreads: createNativeStackScreen({
+ screen: SettingsThreadsRouteScreen,
+ linking: "settings/thread-preferences",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Thread behavior" },
+ }),
+ SettingsAbout: createNativeStackScreen({
+ screen: SettingsAboutRouteScreen,
+ linking: "settings/about",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "About T3 Code" },
+ }),
+ SettingsEnvironmentNew: createNativeStackScreen({
+ screen: ConnectionsNewRouteScreen,
+ linking: "settings/environment-new",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Add Environment",
+ },
+ }),
+ SettingsArchive: createNativeStackScreen({
+ screen: ArchivedThreadsRouteScreen,
+ linking: "settings/archive",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Archived Threads",
+ },
+ }),
+ SettingsNavigation: createNativeStackScreen({
+ screen: SettingsNavigationRouteScreen,
+ linking: "settings/navigation-tabs",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Navigation tabs" },
+ }),
+ SettingsAppearance: createNativeStackScreen({
+ screen: SettingsAppearanceRouteScreen,
+ linking: "settings/appearance",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Appearance",
+ },
+ }),
+ SettingsProjectGrouping: createNativeStackScreen({
+ screen: SettingsProjectGroupingRouteScreen,
+ linking: "settings/project-grouping",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Organization",
+ },
+ }),
+ SettingsOrganization: createNativeStackScreen({
+ screen: SettingsProjectGroupingRouteScreen,
+ linking: "settings/organization",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Organization",
+ },
+ }),
+ SettingsProjectOverview: createNativeStackScreen({
+ screen: SettingsProjectOverviewRouteScreen,
+ linking: "settings/project",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Project overview" },
+ }),
+ SettingsKeyboard: createNativeStackScreen({
+ screen: SettingsKeyboardRouteScreen,
+ linking: "settings/keyboard",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Keyboard",
+ },
+ }),
+ SettingsMicrophone: createNativeStackScreen({
+ screen: SettingsMicrophoneRouteScreen,
+ linking: "settings/microphone",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Microphone",
+ },
+ }),
+ SettingsFollowUp: createNativeStackScreen({
+ screen: SettingsFollowUpRouteScreen,
+ linking: "settings/follow-ups",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Follow-ups",
+ },
+ }),
+ SettingsScheduledTasks: createNativeStackScreen({
+ screen: SettingsScheduledTasksRouteScreen,
+ linking: "settings/scheduled-tasks",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Scheduled Tasks",
+ headerTitleStyle: { fontSize: 16, fontWeight: "800" },
+ },
+ }),
+ SettingsScheduledTaskNew: createNativeStackScreen({
+ screen: SettingsScheduledTaskNewRouteScreen,
+ linking: "settings/scheduled-tasks/new",
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "New scheduled task" },
+ }),
+ SettingsScheduledTaskEdit: createNativeStackScreen({
+ screen: SettingsScheduledTaskEditRouteScreen,
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Edit scheduled task" },
+ }),
+ SettingsScheduledTaskBranch: createNativeStackScreen({
+ screen: ScheduledTaskBranchPickerRouteScreen,
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Base branch" },
+ }),
+ SettingsScheduledTaskModel: createNativeStackScreen({
+ screen: ScheduledTaskModelPickerRouteScreen,
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ headerShown: false,
+ ...(Platform.OS === "android"
+ ? { presentation: "card" as const }
+ : {
+ ...THREAD_SETTINGS_SHEET_OPTIONS,
+ }),
+ },
+ }),
+ SettingsClientStorage: createNativeStackScreen({
+ screen: SettingsClientStorageRouteScreen,
+ linking: "settings/client-storage",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Client Storage",
+ },
+ }),
+ SettingsDiagnostics: createNativeStackScreen({
+ screen: SettingsDiagnosticsRouteScreen,
+ linking: "settings/diagnostics",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Diagnostics",
+ },
+ }),
+ // Its params are a tap-time snapshot, not a stable resource address: `now` is the wall-clock
+ // of the tap, `environmentIds` is the usage screen's local filter selection, and the window
+ // id/kind identify freshly aggregated pools. React Navigation round-trips non-path params
+ // through the URL as query strings, so a path here would bake in a permanently stale
+ // timestamp and filter.
+ SettingsUsageAccount: createNativeStackScreen({
+ screen: UsageLimitAccountScreen,
+ options: { ...SETTINGS_PAGE_OPTIONS, title: "Account" },
+ }),
+ SettingsOpenSourceLicenses: createNativeStackScreen({
+ screen: SettingsOpenSourceLicensesRouteScreen,
+ linking: "settings/open-source-licenses",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Open source licenses",
+ },
+ }),
+ SettingsOpenSourceLicense: createNativeStackScreen({
+ screen: SettingsOpenSourceLicenseRouteScreen,
+ linking: "settings/open-source-licenses/:entryKey",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "License notice",
+ },
+ }),
+ SettingsUsage: createNativeStackScreen({
+ screen: UsageRouteScreen,
+ linking: "settings/usage",
+ options: {
+ ...SETTINGS_PAGE_OPTIONS,
+ title: "Usage",
+ },
+ }),
+ SettingsAuth: createNativeStackScreen({
+ screen: SettingsAuthRouteScreen,
+ linking: "settings/auth",
+ options: { headerShown: false, presentation: "modal" },
+ }),
+ SettingsWaitlist: createNativeStackScreen({
+ screen: SettingsAuthRouteScreen,
+ linking: "settings/waitlist",
+ options: { headerShown: false, presentation: "modal" },
+ }),
+};
// A nested stack means a second UINavigationController with its own UINavigationBar, which breaks
// iOS 26's shared-header morphing between Home and Thread (each pair inside one bar morphs;
// across two bars the whole screen slides).
const THREAD_LINKING_PREFIX = "threads/:environmentId/:threadId";
-const WORKSPACE_OVERLAY_ROUTES = new Set([
- "PullRequestReview",
- "PullRequestInlineComment",
- "ConnectOnboarding",
- "Connections",
- "ConnectionsNew",
- "GitBranches",
- "GitCommit",
- "GitConfirm",
- "GitOverview",
- "NewTaskProject",
- "NewTaskFiles",
- "NewTaskFile",
- "NewTaskAttachment",
- "NewTaskThreadSettings",
- "AddProject",
- "AddProjectRepository",
- "AddProjectDestination",
- "AddProjectLocal",
- "AddProjectNew",
- "NewTaskEnvironment",
- "NewTaskBranch",
- "SettingsLegal",
- "SettingsSheet",
- "ThreadAgents",
- "ThreadBackgroundWork",
- "ThreadPullRequests",
- "ThreadQueue",
- "ThreadReviewComment",
- "ThreadDevicePreview",
- "ThreadBrowserPreview",
- "ThreadSettingsSheet",
-]);
-
function workspaceLocationFromState(state: NavigationState) {
- // Android opens Settings as a workspace page rather than an overlay, so the layout sees it.
- const routes = state.routes.filter(
- (route) =>
- !WORKSPACE_OVERLAY_ROUTES.has(route.name) ||
- (Platform.OS === "android" && route.name === "SettingsSheet"),
- );
+ const routes = state.routes.filter((route) => !isWorkspaceOverlayRoute(route.name));
const effectiveState =
routes.length > 0 && routes.length !== state.routes.length
? ({ ...state, routes, index: routes.length - 1 } as NavigationState)
@@ -543,6 +502,11 @@ function RootStackLayout(props: {
const path = getPathFromState(props.state, navigationPathConfig);
const pathname = path.startsWith("/") ? path : `/${path}`;
const workspaceLocation = workspaceLocationFromState(props.state);
+ const settingsOpen = settingsOpenIn(
+ props.state.routes
+ .slice(0, props.state.index + 1)
+ .filter((route) => !isWorkspaceOverlayRoute(route.name)),
+ );
const draftRoute = props.state.routes.findLast((route) => route.name === "Thread");
const draftParams = (
draftRoute?.params as
@@ -579,20 +543,22 @@ function RootStackLayout(props: {
<HardwareKeyboardCommandProvider pathname={pathname}>
<ThreadOutboxDrainWorker />
<ShowcaseCaptureCoordinator pathname={pathname} />
- <ExistingThreadSettingsRouteProvider>
- <WorkspaceConnectionStatusProvider>
- <AndroidWorkspaceTabsProvider state={props.state}>
- <AdaptiveWorkspaceLayout
- pathname={workspaceLocation.pathname}
- workspaceRouteKey={workspaceLocation.routeKey}
- selectedPullRequestKey={selectedPullRequestKey(props.state)}
- >
- {props.children}
- <HardwareKeyboardCommandOverlay />
- </AdaptiveWorkspaceLayout>
- </AndroidWorkspaceTabsProvider>
- </WorkspaceConnectionStatusProvider>
- </ExistingThreadSettingsRouteProvider>
+ <SettingsEnvironmentFilterProvider open={settingsOpen}>
+ <ExistingThreadSettingsRouteProvider>
+ <WorkspaceConnectionStatusProvider>
+ <AndroidWorkspaceTabsProvider state={props.state}>
+ <AdaptiveWorkspaceLayout
+ pathname={workspaceLocation.pathname}
+ workspaceRouteKey={workspaceLocation.routeKey}
+ selectedPullRequestKey={selectedPullRequestKey(props.state)}
+ >
+ {props.children}
+ <HardwareKeyboardCommandOverlay />
+ </AdaptiveWorkspaceLayout>
+ </AndroidWorkspaceTabsProvider>
+ </WorkspaceConnectionStatusProvider>
+ </ExistingThreadSettingsRouteProvider>
+ </SettingsEnvironmentFilterProvider>
</HardwareKeyboardCommandProvider>
</NewTaskFlowProvider>
);
@@ -974,18 +940,7 @@ const RootStackConfig = createWorkspaceStackNavigator({
sheetGrabberVisible: true,
},
}),
- SettingsSheet: createNativeStackScreen({
- screen: SettingsSheetStack,
- layout: ({ children }) => <AndroidWorkspaceSettings>{children}</AndroidWorkspaceSettings>,
- linking: "settings",
- options: {
- ...NESTED_NAVIGATOR_OPTIONS,
- gestureEnabled: true,
- headerShown: false,
- presentation: "card",
- animation: "none",
- },
- }),
+ ...SETTINGS_SCREENS,
SettingsLegal: createNativeStackScreen({
screen: SettingsLegalRouteScreen,
linking: "settings/legal",
@@ -1063,12 +1018,27 @@ function ScreenRenderFallback(props: RenderFailureProps & { readonly routeName:
const exit = navigation.canGoBack()
? { label: "Go back", onPress: () => navigation.goBack() }
: props.routeName === "Home"
- ? { label: "Open settings", onPress: () => navigation.navigate("SettingsSheet") }
+ ? // Home itself failed, and the Settings list renders inside it; open a Settings page.
+ {
+ label: "Open settings",
+ onPress: () => openSettings(navigation, DEFAULT_SETTINGS_PAGE),
+ }
: { label: "Return home", onPress: () => navigation.dispatch(StackActions.replace("Home")) };
return <RenderFailureView {...props} exit={exit} />;
}
+registerPresentedRoutes(
+ Object.entries(RootStackConfig.config.screens ?? {}).flatMap(([name, screen]) => {
+ const options = (screen as { readonly options?: unknown }).options;
+ const presentation =
+ options && typeof options === "object"
+ ? (options as { readonly presentation?: string }).presentation
+ : undefined;
+ return presentation !== undefined && presentation !== "card" ? [name] : [];
+ }),
+);
+
export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navigator }) {
const { width, height } = useWindowDimensions();
const nativeMetrics = useNativeLayoutMetrics();
@@ -1078,7 +1048,7 @@ export const RootStack = RootStackConfig.with(function AdaptiveRootStack({ Navig
<Navigator
screenLayout={(props) => <GuardedScreenLayout {...props} />}
screenOptions={({ route }) =>
- Platform.OS === "android" && route.name !== "SettingsSheet"
+ Platform.OS === "android"
? { animation: androidWorkspaceDestinationAnimation(route.name, usesSplitView) }
: {}
}
diff --git a/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts b/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts
index d4393d42653..734db0ff82d 100644
--- a/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts
+++ b/apps/mobile/src/features/cloud/connectOnboardingNavigation.ts
@@ -6,8 +6,8 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
-// Sign-in happens inside the Settings sheet; give its session-state transition
-// a beat to settle before presenting another formSheet on top.
+// Sign-in happens in its own modal; give its session-state transition a beat to
+// settle before presenting another formSheet on top.
const PRESENT_ONBOARDING_DELAY_MS = 600;
/**
diff --git a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
index 9cad44c7daa..03d589e7719 100644
--- a/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
+++ b/apps/mobile/src/features/connection/ConnectionsNewRouteScreen.tsx
@@ -32,6 +32,9 @@ import { SymbolView } from "../../components/ui/AppSymbol";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { CloudEnvironmentRows } from "./CloudEnvironmentRows";
import { splitEnvironmentSections } from "./environmentSections";
+import { openSettings } from "../settings/settings-navigation";
+import { leaveSettingsPage } from "../settings/settings-navigation";
+import { workspaceHasColumns } from "../workspace/workspace-selection-store";
type ConnectionsNewRouteParams = {
readonly mode?: string;
@@ -168,7 +171,8 @@ export function ConnectionsNewRouteScreen({
if (!navigation.canGoBack()) {
navigation.dispatch(StackActions.replace("Home"));
} else {
- navigation.goBack();
+ // Added from the Settings list, the new environment shows on Environments.
+ leaveSettingsPage(navigation, workspaceHasColumns(), "SettingsEnvironments");
}
}
};
@@ -390,7 +394,7 @@ function T3ConnectSection() {
label="Sign in to T3 Connect"
description="Reach your machines from anywhere, no network setup."
disabled={!isLoaded}
- onPress={() => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" })}
+ onPress={() => navigation.navigate("SettingsAuth")}
/>
)}
</View>
diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx
index 494966d886f..684e7ef5e35 100644
--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx
+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx
@@ -34,6 +34,8 @@ import { usePendingTaskListActions } from "./usePendingTaskListActions";
import { useThreadListActions } from "./useThreadListActions";
import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle";
import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
+import { openSettings } from "../settings/settings-navigation";
+import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab";
export function HomeRouteScreen() {
const { width: windowWidth } = useWindowDimensions();
@@ -54,6 +56,7 @@ export function HomeRouteScreen() {
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const navigation = useNavigation();
+ const selectTab = useSelectWorkspaceTab();
const workspace = useWorkspaceTabs();
const [localSearchQuery, setLocalSearchQuery] = useState("");
const searchQuery =
@@ -187,11 +190,7 @@ export function HomeRouteScreen() {
<WorkspaceEmptyDetail
onAddConnection={
Platform.OS === "android" && !catalogState.hasConnections
- ? () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironmentNew" },
- })
+ ? () => openSettings(navigation, "SettingsEnvironmentNew")
: undefined
}
onStartNewTask={
@@ -217,11 +216,7 @@ export function HomeRouteScreen() {
...getConnectionAwareBrandHeaderOptions({
headerWidth,
trailingItemCount: nativePrimaryColumn && deviceType === "pad" ? 2 : 1,
- onOpenEnvironments: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironments" },
- }),
+ onOpenEnvironments: () => openSettings(navigation, "SettingsEnvironments"),
}),
headerShown: Platform.OS !== "android",
}}
@@ -235,18 +230,8 @@ export function HomeRouteScreen() {
selectedProjectKey={selectedProjectKey}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
- onOpenEnvironments={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironments" },
- })
- }
- onOpenSettings={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- })
- }
+ onOpenEnvironments={() => openSettings(navigation, "SettingsEnvironments")}
+ onOpenSettings={() => selectTab("settings")}
onSearchQueryChange={setSearchQuery}
onStartNewTask={startNewTask}
/>
@@ -254,12 +239,7 @@ export function HomeRouteScreen() {
<HomeScreen
catalogState={catalogState}
environments={environments}
- onAddConnection={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironmentNew" },
- })
- }
+ onAddConnection={() => openSettings(navigation, "SettingsEnvironmentNew")}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onSettleThread={settleThread}
@@ -274,12 +254,7 @@ export function HomeRouteScreen() {
onRegenerateThreadTitle={regenerateThreadTitle}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
- onOpenSettings={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- })
- }
+ onOpenSettings={() => selectTab("settings")}
onSearchQueryChange={setSearchQuery}
onSelectThread={handleSelectThread}
onSelectPendingTask={openPendingTask}
diff --git a/apps/mobile/src/features/keyboard/CommandPalette.tsx b/apps/mobile/src/features/keyboard/CommandPalette.tsx
index 038152aab1f..5fa730cd1d3 100644
--- a/apps/mobile/src/features/keyboard/CommandPalette.tsx
+++ b/apps/mobile/src/features/keyboard/CommandPalette.tsx
@@ -60,6 +60,8 @@ import {
import { parseActiveThreadPath, type HardwareKeyboardCommand } from "./hardwareKeyboardCommands";
import { threadJumpIndex } from "./threadKeyboardShortcuts";
import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
+import { openSettings } from "../settings/settings-navigation";
+import { useSelectWorkspaceTab } from "../workspace/useSelectWorkspaceTab";
const PALETTE_COMMANDS: ReadonlyArray<HardwareKeyboardCommand> = [
"commandPalette",
@@ -208,6 +210,7 @@ export function CommandPalette(props: {
readonly onCommand: (command: HardwareKeyboardCommand) => void;
}) {
const navigation = useNavigation();
+ const selectTab = useSelectWorkspaceTab();
const { themeVariables } = useAppearancePreferences();
const { selectThread, selectThreadRoute } = useAdaptiveWorkspaceLayout();
const runCommand = props.onCommand;
@@ -269,66 +272,42 @@ export function CommandPalette(props: {
kind: "action",
title: "Open settings",
searchTerms: ["preferences", "configuration"],
- run: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- }),
+ run: () => selectTab("settings"),
},
{
key: "appearance",
kind: "action",
title: "Appearance",
searchTerms: ["theme", "colors", "dark", "light"],
- run: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsAppearance" },
- }),
+ run: () => openSettings(navigation, "SettingsAppearance"),
},
{
key: "environments",
kind: "action",
title: "Manage environments",
searchTerms: ["connections", "server", "remote"],
- run: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironments" },
- }),
+ run: () => openSettings(navigation, "SettingsEnvironments"),
},
{
key: "scheduledTasks",
kind: "action",
title: "Scheduled tasks",
searchTerms: ["schedule", "automations", "recurring"],
- run: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsScheduledTasks" },
- }),
+ run: () => openSettings(navigation, "SettingsScheduledTasks"),
},
{
key: "usage",
kind: "action",
title: "Usage",
searchTerms: ["limits", "accounts", "quota"],
- run: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsUsage" },
- }),
+ run: () => openSettings(navigation, "SettingsUsage"),
},
{
key: "archive",
kind: "action",
title: "Archived threads",
searchTerms: ["restore", "history"],
- run: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsArchive" },
- }),
+ run: () => openSettings(navigation, "SettingsArchive"),
},
];
const projectByKey = new Map(
@@ -423,6 +402,7 @@ export function CommandPalette(props: {
);
return [...actions, ...projectItems, ...threadItems];
}, [
+ selectTab,
activeThread,
activeThreadRef,
environments.length,
diff --git a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
index cdbfc7d446d..df104a71188 100644
--- a/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
+++ b/apps/mobile/src/features/keyboard/HardwareKeyboardCommandProvider.tsx
@@ -1,4 +1,5 @@
import { StackActions, useNavigation } from "@react-navigation/native";
+import { Platform } from "react-native";
import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
import {
createContext,
@@ -14,6 +15,10 @@ import {
} from "react";
import { tryCopyTextWithHaptic } from "../../lib/copyTextWithHaptic";
+import {
+ firstWorkspaceDetailOpen,
+ workspaceHasColumns,
+} from "../workspace/workspace-selection-store";
import { T3KeyboardCommands } from "../../native/T3KeyboardCommands";
import { useThreadShell } from "../../state/entities";
import type { GitActionProgress } from "../../state/use-vcs-action-state";
@@ -152,6 +157,9 @@ export function HardwareKeyboardCommandProvider({
return;
}
if (command === "back") {
+ // Beside a visible list, the first detail page has nothing to go back to.
+ if (Platform.OS === "ios" && workspaceHasColumns() && firstWorkspaceDetailOpen(navigation))
+ return;
if (navigation.canGoBack()) {
navigation.goBack();
} else {
diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
index 3cfeff980e5..a1676b31ed3 100644
--- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
+++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx
@@ -1,3 +1,4 @@
+import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { AdaptiveWorkspaceContext, useAdaptiveWorkspaceLayout } from "./adaptive-workspace-context";
import { createDeferredNavigation } from "./deferred-navigation";
import { uuidv4 } from "../../lib/uuid";
@@ -43,6 +44,7 @@ import {
type VerticalHinge,
deriveWorkspacePaneLayout,
isPrimarySidebarPinned,
+ isWorkspaceListPath,
type WorkspaceAuxiliaryPaneRole,
} from "../../lib/layout";
import {
@@ -91,6 +93,16 @@ import {
import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
import { AndroidHingeObserver } from "../../native/AndroidHingeObserver";
import { WindowHingeContext } from "../../native/window-hinge-context";
+import { useAndroidWorkspaceRoot } from "../workspace/AndroidWorkspaceTabsProvider";
+import { openSettings } from "../settings/settings-navigation";
+import { dispatchRootStackReset, rootStackState } from "../../lib/root-stack-reset";
+import {
+ currentWorkspaceSelections,
+ workspaceSelectionCheck,
+} from "../workspace/workspace-selection-store";
+import { workspaceTabNavigationState } from "../workspace/workspace-tab-navigation";
+import type { WorkspaceTab } from "../workspace/workspace-tabs-state";
+import { workspaceRoutesOf } from "./workspace-overlay-routes";
export { useAdaptiveWorkspaceLayout };
@@ -207,9 +219,10 @@ function AdaptiveWorkspaceLayoutContent(
const pathname = props.pathname;
const workspace = useWorkspaceTabs();
// Settings and Usage occupy the workspace rather than a list/detail pair.
+ const androidSettingsOpen = useAndroidWorkspaceRoot()?.settingsOpen ?? false;
+ const safeAreaInsets = useSafeAreaInsets();
const workspacePage =
- Platform.OS === "android" &&
- (pathname.startsWith("/settings") || workspace?.state.selectedTab === "usage");
+ Platform.OS === "android" && (androidSettingsOpen || workspace?.state.selectedTab === "usage");
const navigation = useNavigation();
const activeRoleOwner = useRef<symbol | null>(null);
const [primarySidebarPreferredVisible, setPrimarySidebarPreferredVisible] = useState(true);
@@ -233,10 +246,13 @@ function AdaptiveWorkspaceLayoutContent(
() => deriveLayout({ width: viewportWidth, height, nativeMetrics, nativeWorkspace }),
[height, viewportWidth, nativeMetrics, nativeWorkspace],
);
+ // The overlay sidebar closes when a page opens from it, and stays open on a list or on the
+ // page a tab switch opened (`keepOpenFor`, set by that switch).
const [overlaySidebar, setOverlaySidebar] = useState({
active: baseLayout.primarySidebarOverlaysContent,
pathname,
- visible: pathname === "/",
+ visible: isWorkspaceListPath(pathname),
+ keepOpenFor: null as string | null,
});
if (
overlaySidebar.active !== baseLayout.primarySidebarOverlaysContent ||
@@ -245,7 +261,11 @@ function AdaptiveWorkspaceLayoutContent(
setOverlaySidebar({
active: baseLayout.primarySidebarOverlaysContent,
pathname,
- visible: pathname === "/",
+ visible:
+ isWorkspaceListPath(pathname) ||
+ (overlaySidebar.keepOpenFor !== null &&
+ overlaySidebar.keepOpenFor === props.workspaceRouteKey),
+ keepOpenFor: null,
});
}
const preferredSidebarVisible = baseLayout.primarySidebarOverlaysContent
@@ -457,12 +477,35 @@ function AdaptiveWorkspaceLayoutContent(
}
setSupplementaryPanePreferredWidth(nextWidth);
};
- const handleOpenSettings = () => {
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- });
+ /**
+ * The one way to open a workspace tab: replaces the workspace with the tab's list and, when the
+ * window has columns, the page it last showed, keeping any sheet on top. An overlay sidebar
+ * stays open over that page.
+ */
+ const openWorkspaceTab = (
+ tab: WorkspaceTab | "settings",
+ options?: { readonly columns?: boolean },
+ ) => {
+ const state = rootStackState(navigation);
+ if (!state) return;
+ const { workspace, overlays } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));
+ const next = workspaceTabNavigationState(
+ { ...state, routes: workspace },
+ tab,
+ currentWorkspaceSelections(),
+ {
+ columns: Platform.OS === "ios" && (options?.columns ?? layout.usesSplitView),
+ check: workspaceSelectionCheck,
+ overlays,
+ },
+ );
+ if (layout.primarySidebarOverlaysContent) {
+ const opened = next.routes.at(-1 - overlays.length)?.key ?? null;
+ setOverlaySidebar((current) => ({ ...current, visible: true, keepOpenFor: opened }));
+ }
+ dispatchRootStackReset(navigation, state, next);
};
+ const handleOpenSettings = () => openWorkspaceTab("settings");
const selectAndroidWorkspace = useAndroidWorkspaceSelection();
const deferredThreadSelection = useMemo(() => createDeferredNavigation(), []);
@@ -521,6 +564,8 @@ function AdaptiveWorkspaceLayoutContent(
}
const projects = useProjects();
+ const compactAndroidSettings =
+ Platform.OS === "android" && androidSettingsOpen && !layout.usesSplitView;
const handleStartNewTask = () => {
const thread = appAtomRegistry
.get(environmentThreadShells.navigationThreadShellsAtom)
@@ -555,10 +600,7 @@ function AdaptiveWorkspaceLayoutContent(
// Minted here (root stack navigation) so the sidebar pane stays free of
// navigation hooks — on iOS it renders inside an independent nav tree.
const handleOpenEnvironmentSettings = () => {
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironments" },
- });
+ openSettings(navigation, "SettingsEnvironments");
};
const handleOpenThreadPullRequests = useOpenThreadPullRequests();
@@ -771,6 +813,7 @@ function AdaptiveWorkspaceLayoutContent(
toggleAuxiliaryPane,
togglePrimarySidebar,
setPrimarySidebarVisible,
+ openWorkspaceTab,
setAuxiliaryPaneWidth,
composerKeyboardActive,
setComposerEditing,
@@ -891,7 +934,17 @@ function AdaptiveWorkspaceLayoutContent(
Platform.OS === "android" && layout.usesSplitView ? contentTargetWidth : null
}
>
- {props.children}
+ {/* Compact Settings keeps the bottom navigation under all of its pages. */}
+ <SafeAreaInsetsContext
+ value={
+ compactAndroidSettings ? { ...safeAreaInsets, bottom: 0 } : safeAreaInsets
+ }
+ >
+ <View className="flex-1">{props.children}</View>
+ </SafeAreaInsetsContext>
+ {compactAndroidSettings ? (
+ <AndroidWorkspaceNavigation onNewThread={handleStartNewTask} />
+ ) : null}
</WorkspaceSettledContentWidthContext>
</WorkspaceContentWidthContext>
</View>
diff --git a/apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx b/apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx
index d58360e7e99..aa33effa936 100644
--- a/apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx
+++ b/apps/mobile/src/features/layout/WorkspaceEmptyDetail.tsx
@@ -8,13 +8,13 @@ import { EmptyState } from "../../components/ui/EmptyState";
import type { WorkspaceTab } from "../workspace/workspace-tabs-state";
export function WorkspaceEmptyDetail(props: {
- readonly tab?: WorkspaceTab;
+ readonly tab?: WorkspaceTab | "settings";
readonly onStartNewTask?: () => void;
readonly onAddConnection?: () => void;
}) {
const pullRequests = props.tab === "pullRequests";
- if (props.tab && props.tab !== "threads" && props.tab !== "pullRequests")
- return <View className="flex-1 bg-screen" />;
+ const settings = props.tab === "settings";
+ if (props.tab === "usage") return <View className="flex-1 bg-screen" />;
return (
<View
className={
@@ -49,16 +49,22 @@ export function WorkspaceEmptyDetail(props: {
type="hierarchical"
/>
<Text className="text-center text-xl font-t3-bold">
- {pullRequests ? "Select a pull request" : "Select a thread"}
+ {settings
+ ? "Select a setting"
+ : pullRequests
+ ? "Select a pull request"
+ : "Select a thread"}
</Text>
<Text className="text-center text-base text-foreground-muted">
- {pullRequests
- ? "Choose a pull request from the sidebar to review it."
- : Platform.OS === "android"
- ? "Choose a thread from the sidebar or start a new thread."
- : "Choose a thread from the sidebar or start a new task."}
+ {settings
+ ? "Choose a page from the sidebar."
+ : pullRequests
+ ? "Choose a pull request from the sidebar to review it."
+ : Platform.OS === "android"
+ ? "Choose a thread from the sidebar or start a new thread."
+ : "Choose a thread from the sidebar or start a new task."}
</Text>
- {props.onStartNewTask && !pullRequests ? (
+ {props.onStartNewTask && !pullRequests && !settings ? (
Platform.OS === "android" ? (
<NewThreadButton extended className="mt-2" onPress={props.onStartNewTask} />
) : (
diff --git a/apps/mobile/src/features/layout/adaptive-workspace-context.ts b/apps/mobile/src/features/layout/adaptive-workspace-context.ts
index 122248db589..04d82f548f3 100644
--- a/apps/mobile/src/features/layout/adaptive-workspace-context.ts
+++ b/apps/mobile/src/features/layout/adaptive-workspace-context.ts
@@ -1,3 +1,4 @@
+import type { WorkspaceTab } from "../workspace/workspace-tabs-state";
import { createContext, use, type ReactNode } from "react";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
@@ -26,6 +27,11 @@ interface AdaptiveWorkspaceContextValue {
readonly toggleAuxiliaryPane: () => void;
readonly togglePrimarySidebar: () => void;
readonly setPrimarySidebarVisible: (visible: boolean) => void;
+ /** Opens a workspace tab with its list and, with columns, the page it last showed. */
+ readonly openWorkspaceTab: (
+ tab: WorkspaceTab | "settings",
+ options?: { readonly columns?: boolean },
+ ) => void;
readonly setAuxiliaryPaneWidth: (width: number) => void;
/**
* Android split view while the thread composer has the soft keyboard: the
@@ -63,6 +69,7 @@ export const AdaptiveWorkspaceContext = createContext<AdaptiveWorkspaceContextVa
toggleAuxiliaryPane: () => undefined,
togglePrimarySidebar: () => undefined,
setPrimarySidebarVisible: () => undefined,
+ openWorkspaceTab: () => undefined,
setAuxiliaryPaneWidth: () => undefined,
composerKeyboardActive: false,
setComposerEditing: () => undefined,
diff --git a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
index bfa5ebf03f1..541c9ebc6ab 100644
--- a/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
+++ b/apps/mobile/src/features/layout/createWorkspaceStackNavigator.ios.tsx
@@ -27,6 +27,9 @@ import { scopedThreadKey } from "../../lib/scopedEntities";
import { WorkspaceTabsProvider, useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
import { WorkspaceNativeTabs } from "../workspace/WorkspaceNativeTabs.ios";
import { workspaceUsesColumns } from "../workspace/workspace-tabs-state";
+import { isSettingsRoute, settingsOpenIn } from "../settings/settings-navigation";
+import { workspaceRoutesOf } from "./workspace-overlay-routes";
+import { useWorkspaceSidebarHeaderItem } from "./useWorkspaceSidebarHeaderItem";
import { useDeviceType, useNativeLayoutMetrics } from "../../native/native-layout-metrics";
import { useAdaptiveWorkspaceLayout } from "./AdaptiveWorkspaceLayout";
@@ -55,6 +58,8 @@ import {
NativePrimaryColumnContext,
NativeWorkspaceInspectorContext,
NativeWorkspaceModeContext,
+ WorkspaceSlotOptionsContext,
+ slotScreenOptions,
} from "../../native/v5-workspace-context";
type ViewProps = ComponentProps<typeof NativeStackView>;
@@ -66,6 +71,16 @@ const isPullRequestRoute = (route: Route) =>
route.name === "PullRequestFile" ||
route.name === "PullRequestFiles";
+/** Only these screens follow the sidebar's state; a thread's header draws its own toggle. */
+function SidebarToggleHeader(props: ComponentProps<typeof V5StackHeader>) {
+ const sidebarItem = useWorkspaceSidebarHeaderItem();
+ const options = {
+ ...props.options,
+ unstable_headerLeftItems: () => [sidebarItem],
+ } as AppNativeStackNavigationOptions as typeof props.options;
+ return <V5StackHeader {...props} options={options} />;
+}
+
function ColumnScreen(props: {
readonly descriptor: Descriptor;
readonly primary?: boolean;
@@ -75,9 +90,19 @@ function ColumnScreen(props: {
readonly onDismiss: (routeKey: string, native: boolean) => void;
readonly onAppearance: (type: "willAppear" | "didAppear" | "willDisappear", key: string) => void;
readonly onCompose?: () => void;
+ /** Settings pages don't draw their own sidebar toggle, unlike threads and pull requests. */
+ readonly sidebarToggle?: boolean;
readonly navigation: ViewProps["navigation"];
}) {
const { descriptor } = props;
+ // Options a screen set inside this workspace tab slot, over its route's.
+ const options = slotScreenOptions(
+ use(WorkspaceSlotOptionsContext),
+ descriptor.route.key,
+ descriptor.options,
+ );
+ const Header =
+ props.sidebarToggle && !options.unstable_headerLeftItems ? SidebarToggleHeader : V5StackHeader;
const [presented, setPresented] = useState(false);
const primaryColumn = useMemo(
() =>
@@ -118,8 +143,8 @@ function ColumnScreen(props: {
>
<NavigationContext value={descriptor.navigation}>
<NavigationRouteContext value={descriptor.route}>
- <V5StackHeader
- options={descriptor.options}
+ <Header
+ options={options}
canGoBack={!props.primary}
column={props.primary ? "primary" : "detail"}
onCompose={
@@ -133,7 +158,7 @@ function ColumnScreen(props: {
<ColumnContent
primary={props.primary}
insetHorizontally={
- (descriptor.options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
+ (options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
}
>
<NativePrimaryColumnContext value={primaryColumn}>
@@ -156,6 +181,7 @@ function WorkspaceColumns(
setPrimarySidebarVisible,
toggleAuxiliaryPane,
startNewTask,
+ openWorkspaceTab,
} = useAdaptiveWorkspaceLayout();
const deviceType = useDeviceType();
// Split screens must remain mounted while UIKit animates a detached route away.
@@ -186,12 +212,16 @@ function WorkspaceColumns(
});
}
- const selectedTab = useWorkspaceTabs()?.state.selectedTab;
+ const workspaceTabs = useWorkspaceTabs();
+ const selectedTab = workspaceTabs?.state.selectedTab;
+ const settingsOpen = workspaceTabs?.settingsOpen ?? false;
const openNewTask = startNewTask;
// The cover detail rail needs room for thread tools above the fixed tabs.
// The unfolded Duo keeps compose in its detail bar.
const detailCompose =
- deviceType === "duo-unfolded" && selectedTab !== "pullRequests" ? openNewTask : undefined;
+ deviceType === "duo-unfolded" && selectedTab !== "pullRequests" && !settingsOpen
+ ? openNewTask
+ : undefined;
const inspector = use(NativeWorkspaceInspectorContext);
const hostRef = useRef<SplitHostCommands>(null);
const activeDetailKey = props.detail.at(-1)?.key;
@@ -274,6 +304,17 @@ function WorkspaceColumns(
}}
onExpand={() => {
collapsed.current = false;
+ // Native callbacks can outlive the render that created them, so decide from the live
+ // router state. An expanded split has columns, so its tab gets a page beside the list.
+ const live = props.navigation.getState();
+ const { workspace } = workspaceRoutesOf(live.routes.slice(0, live.index + 1));
+ if (workspace.some((route) => route.name !== "Home" && route.name !== "Settings")) return;
+ const tab = workspace.some((route) => route.name === "Settings")
+ ? "settings"
+ : (["threads", "pullRequests", "usage"] as const).find((candidate) =>
+ workspaceTabs?.isTabActive(candidate),
+ );
+ openWorkspaceTab(tab ?? "threads", { columns: true });
}}
preferredDisplayMode={
// UIKit applies the mode as a collapsed split expands, before the new width reaches JS, so a
@@ -341,7 +382,7 @@ function WorkspaceColumns(
/>
<ColumnContent>
<WorkspaceEmptyDetail
- tab={selectedTab}
+ tab={settingsOpen ? "settings" : selectedTab}
onStartNewTask={
// Duo provides compose in the detail bar; iPad uses the empty-state action.
detailCompose ? undefined : openNewTask
@@ -355,6 +396,11 @@ function WorkspaceColumns(
<ColumnScreen
key={route.key}
descriptor={descriptor}
+ sidebarToggle={
+ layout.usesSplitView &&
+ props.detail[0]?.key === route.key &&
+ isSettingsRoute(route.name)
+ }
attached={props.detail.some((current) => current.key === route.key)}
onDismiss={handleNativeDismiss}
onAppearance={followCollapsedSplit}
@@ -397,7 +443,7 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean
const descriptors = props.descriptors;
const baseRoute = { key: `${props.state.key}:workspace`, name: "Workspace" };
const visibleRoute = projection.detail.at(-1) ?? primaryRoute;
- const workspacePage = !workspaceUsesColumns(workspace.state.selectedTab, visibleRoute.name);
+ const workspacePage = !workspaceUsesColumns(workspace.state.selectedTab, workspace.settingsOpen);
const baseDescriptor: Descriptor = {
...primaryDescriptor,
navigation: props.descriptors[visibleRoute.key]!.navigation,
@@ -414,10 +460,6 @@ function WorkspaceStackView(props: ViewProps & { readonly nativeColumns: boolean
!layout.usesSplitView &&
(metrics?.verticalBarEdge ?? "none") === "none"
}
- onSelect={() => {
- if (props.state.index > 0)
- props.navigation.dispatch({ type: "POP_TO_TOP", target: props.state.key });
- }}
>
{props.nativeColumns && !workspacePage ? (
<WorkspaceColumns
@@ -518,10 +560,16 @@ function WorkspaceStackNavigator({
UNSTABLE_router,
});
if (!nativeWorkspaceColumnsReady) return null;
+ const settingsOpen = settingsOpenIn(
+ state.routes.slice(0, state.index + 1).filter((route) => {
+ const presentation = descriptors[route.key]?.options.presentation;
+ return presentation === undefined || presentation === "card";
+ }),
+ );
return (
<NativeWorkspaceModeContext value={usesNativeWorkspaceColumns}>
<NavigationContent>
- <WorkspaceTabsProvider settingsOpen={state.routes[state.index]?.name === "SettingsSheet"}>
+ <WorkspaceTabsProvider settingsOpen={settingsOpen}>
<WorkspaceStackView
nativeColumns={usesNativeWorkspaceColumns}
{...rest}
diff --git a/apps/mobile/src/features/layout/workspace-overlay-routes.ts b/apps/mobile/src/features/layout/workspace-overlay-routes.ts
new file mode 100644
index 00000000000..0e8a0099950
--- /dev/null
+++ b/apps/mobile/src/features/layout/workspace-overlay-routes.ts
@@ -0,0 +1,61 @@
+/**
+ * Root routes listed as presented over the workspace, including ones that are plain cards on
+ * Android but still sit above the workspace there.
+ */
+const LISTED_OVERLAY_ROUTES: ReadonlySet<string> = new Set([
+ "PullRequestReview",
+ "PullRequestInlineComment",
+ "ConnectOnboarding",
+ "Connections",
+ "ConnectionsNew",
+ "GitBranches",
+ "GitCommit",
+ "GitConfirm",
+ "GitOverview",
+ "NewTaskProject",
+ "NewTaskFiles",
+ "NewTaskFile",
+ "NewTaskAttachment",
+ "NewTaskThreadSettings",
+ "AddProject",
+ "AddProjectRepository",
+ "AddProjectDestination",
+ "AddProjectLocal",
+ "AddProjectNew",
+ "NewTaskEnvironment",
+ "NewTaskBranch",
+ "SettingsLegal",
+ "SettingsAuth",
+ "SettingsWaitlist",
+ "ThreadAgents",
+ "ThreadBackgroundWork",
+ "ThreadPullRequests",
+ "ThreadQueue",
+ "ThreadReviewComment",
+ "ThreadDevicePreview",
+ "ThreadBrowserPreview",
+ "ThreadSettingsSheet",
+]);
+
+// Every route whose `presentation` is a sheet or modal, read from the root stack's config once.
+let presentedRoutes: ReadonlySet<string> = new Set();
+
+export function registerPresentedRoutes(names: Iterable<string>) {
+ presentedRoutes = new Set(names);
+}
+
+/** Whether a root route is presented over the workspace (a sheet or modal). */
+export function isWorkspaceOverlayRoute(name: string) {
+ return LISTED_OVERLAY_ROUTES.has(name) || presentedRoutes.has(name);
+}
+
+/** The routes that make up the workspace, up to the first sheet or modal above it. */
+export function workspaceRoutesOf<Route extends { readonly name: string }>(
+ routes: readonly Route[],
+) {
+ const firstOverlay = routes.findIndex((route) => isWorkspaceOverlayRoute(route.name));
+ return {
+ workspace: firstOverlay < 0 ? routes : routes.slice(0, firstOverlay),
+ overlays: firstOverlay < 0 ? [] : routes.slice(firstOverlay),
+ };
+}
diff --git a/apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx b/apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx
index fd0211a69d5..f2c3f205ad5 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestToolbar.android.tsx
@@ -9,6 +9,7 @@ import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands
import { WorkspaceListToolbarRow } from "../workspace/WorkspaceListToolbarRow";
import { useWorkspaceTabs } from "../workspace/WorkspaceTabsContext";
import { usePullRequestFilterMenu } from "./PullRequestFilterMenuContext";
+import { openSettings } from "../settings/settings-navigation";
/** PR search shares the thread list's Android header row. */
export function PullRequestToolbar(props: { readonly onRequestVisibility?: () => void }) {
@@ -71,12 +72,7 @@ export function PullRequestToolbar(props: { readonly onRequestVisibility?: () =>
onOpenSearch={openSearch}
searchAccessibilityLabel="Search pull requests"
titleAccessibilityLabel="T3 Code, Pull requests"
- onOpenEnvironments={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironments" },
- })
- }
+ onOpenEnvironments={() => openSettings(navigation, "SettingsEnvironments")}
filter={
filters ? (
<AndroidAnchoredMenu
diff --git a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx
index 99fbc09f08e..ff806c53ec0 100644
--- a/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsAuthRouteScreen.tsx
@@ -4,7 +4,7 @@ import {
type UserProfileCustomPage,
UserProfileView,
} from "@clerk/expo/native-components";
-import { StackActions, useNavigation } from "@react-navigation/native";
+import { useNavigation } from "@react-navigation/native";
import { useEffect, useLayoutEffect, useState } from "react";
import { View } from "react-native";
@@ -25,7 +25,7 @@ export function SettingsAuthRouteScreen() {
useLayoutEffect(() => {
if (!hasCloudPublicConfig()) {
- navigation.dispatch(StackActions.replace("SettingsContent"));
+ navigation.goBack();
}
}, [navigation]);
@@ -35,7 +35,7 @@ export function SettingsAuthRouteScreen() {
function ConfiguredSettingsAuthRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const navigation = useNavigation();
- const handleHostBack = () => navigation.dispatch(StackActions.popTo("SettingsContent"));
+ const handleHostBack = () => navigation.goBack();
// Once signed in, stay on the profile view so signing out pops back instead of
// flashing the sign-in form.
const [hasBeenSignedIn, setHasBeenSignedIn] = useState(isSignedIn === true);
@@ -43,7 +43,7 @@ function ConfiguredSettingsAuthRouteScreen() {
useEffect(() => {
if (hasBeenSignedIn && isLoaded && isSignedIn === false) {
- navigation.dispatch(StackActions.popTo("SettingsContent"));
+ navigation.goBack();
}
}, [hasBeenSignedIn, isLoaded, isSignedIn, navigation]);
diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
index 44c104eedc2..06d5882c3b8 100644
--- a/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsEnvironmentDetailRouteScreen.tsx
@@ -202,13 +202,7 @@ function EnvironmentDetail({ environmentId }: { readonly environmentId: Environm
environmentId={environmentId}
connected={connected}
onAddRoute={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: {
- screen: "SettingsEnvironmentNew",
- params: { routeFor: environmentId },
- },
- })
+ navigation.navigate("SettingsEnvironmentNew", { routeFor: environmentId })
}
/>
{outdated ? (
diff --git a/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx
index 4a23fdf98a3..2f106cb29b3 100644
--- a/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsEnvironmentsRouteScreen.tsx
@@ -65,10 +65,7 @@ export function SettingsEnvironmentsRouteScreen() {
}
const openEnvironment = (environmentId: EnvironmentId) => {
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironmentDetail", params: { environmentId } },
- });
+ navigation.navigate("SettingsEnvironmentDetail", { environmentId });
};
const handleUpdateEnvironment = (
environmentId: EnvironmentId,
@@ -127,11 +124,7 @@ export function SettingsEnvironmentsRouteScreen() {
accessibilityLabel: "Add environment",
icon: "plus",
tintColor: headerIconColor,
- onPress: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironmentNew" },
- }),
+ onPress: () => navigation.navigate("SettingsEnvironmentNew"),
},
]}
>
diff --git a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
index fa48dbcd0a9..1b9ee6f84cf 100644
--- a/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsNotificationsRouteScreen.tsx
@@ -209,7 +209,7 @@ function ConfiguredSettingsNotificationsRouteScreen() {
{ text: "Cancel", style: "cancel" },
{
text: "Continue",
- onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
+ onPress: () => navigation.navigate("SettingsAuth"),
},
],
);
diff --git a/apps/mobile/src/features/settings/SettingsOpenSourceLicensesRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsOpenSourceLicensesRouteScreen.tsx
index 251e62565d8..eba94cdf3bd 100644
--- a/apps/mobile/src/features/settings/SettingsOpenSourceLicensesRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsOpenSourceLicensesRouteScreen.tsx
@@ -69,12 +69,8 @@ export function SettingsOpenSourceLicensesRouteScreen() {
<LicenseRow
entry={item}
onPress={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: {
- screen: "SettingsOpenSourceLicense",
- params: { entryKey: thirdPartyLicenseEntryKey(item) },
- },
+ navigation.navigate("SettingsOpenSourceLicense", {
+ entryKey: thirdPartyLicenseEntryKey(item),
})
}
/>
diff --git a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
index 7d5ae81eb8c..6d8bb10d907 100644
--- a/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsProjectOverviewRouteScreen.tsx
@@ -39,6 +39,9 @@ import {
SettingsEnvironmentFilterHeader,
} from "./components/SettingsEnvironmentFilterHeader";
import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";
+import { leaveSettingsPage } from "./settings-navigation";
+import { workspaceHasColumns } from "../workspace/workspace-selection-store";
+import { DEFAULT_SETTINGS_PAGE } from "../workspace/workspace-tab-navigation";
export function SettingsProjectOverviewRouteScreen() {
const insets = useSafeAreaInsets();
@@ -63,7 +66,8 @@ export function SettingsProjectOverviewRouteScreen() {
// The filter can move to another project while a removal is still running.
const finishProjectRemoval = (projectKey: string | null) => {
if (latestProjectKey.current !== projectKey) return;
- if (navigation.isFocused()) navigation.goBack();
+ if (navigation.isFocused())
+ leaveSettingsPage(navigation, workspaceHasColumns(), DEFAULT_SETTINGS_PAGE);
// Otherwise the filter keeps pointing at the removed project as an unavailable one.
selectProject(null);
};
diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
index cbcc949f7f9..b39e1cdde21 100644
--- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx
@@ -14,7 +14,8 @@ import {
ScreenScrollViewBottomInset,
} from "../../components/ui/ScreenScrollView";
import { useAuth, useUser } from "@clerk/expo";
-import { useNavigation } from "@react-navigation/native";
+import { useNavigation, useNavigationState } from "@react-navigation/native";
+import { use, useMemo } from "react";
import { Platform, View } from "react-native";
import { useWorkspaceSurface } from "../workspace/useWorkspaceSurface";
import { useDeviceType } from "../../native/native-layout-metrics";
@@ -26,18 +27,27 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { SettingsRow } from "./components/SettingsRow";
-import { SettingsSection } from "./components/SettingsSection";
+import { SettingsSection, SettingsSidebarContext } from "./components/SettingsSection";
import { SettingsScreen } from "./components/SettingsScreen";
import {
AndroidSettingsEnvironmentFilter,
SettingsEnvironmentFilterHeader,
} from "./components/SettingsEnvironmentFilterHeader";
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
+import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
export function SettingsRouteScreen() {
const surface = useWorkspaceSurface();
const deviceType = useDeviceType();
const compactTabs = useCompactWorkspaceTabs();
+ const { layout } = useAdaptiveWorkspaceLayout();
+ const inSidebar = use(NativePrimaryColumnContext) !== null && layout.usesSplitView;
+ // The page open beside the list: the route right above the Settings tab's route.
+ const selected = useNavigationState((state) => {
+ const list = state.routes.findIndex((route) => route.name === "Settings");
+ return list < 0 ? null : (state.routes[list + 1]?.name ?? null);
+ });
+ const sidebar = useMemo(() => (inSidebar ? { selected } : null), [inSidebar, selected]);
const content = hasCloudPublicConfig() ? (
<ConfiguredSettingsRouteScreen />
) : (
@@ -45,22 +55,27 @@ export function SettingsRouteScreen() {
);
return (
- <View className={`flex-1 ${surface.className}`}>
- <SettingsEnvironmentFilterHeader />
- <ScreenScrollViewBottomInset value={deviceType === "pad" || compactTabs ? 80 : 0}>
- {Platform.OS === "android" ? (
- <SettingsScreen title="Settings" trailing={<AndroidSettingsEnvironmentFilter />}>
- {content}
- </SettingsScreen>
- ) : (
- content
- )}
- </ScreenScrollViewBottomInset>
- </View>
+ <SettingsSidebarContext value={sidebar}>
+ <View className={`flex-1 ${surface.className}`}>
+ <SettingsEnvironmentFilterHeader />
+ <ScreenScrollViewBottomInset value={deviceType === "pad" || compactTabs ? 80 : 0}>
+ {Platform.OS === "android" ? (
+ <SettingsScreen title="Settings" trailing={<AndroidSettingsEnvironmentFilter />}>
+ {content}
+ </SettingsScreen>
+ ) : (
+ content
+ )}
+ </ScreenScrollViewBottomInset>
+ </View>
+ </SettingsSidebarContext>
);
}
function ConfiguredSettingsRouteScreen() {
+ // UIKit's scroll-edge material takes the scroll view's own color; like the chat list, match
+ // the sidebar's surface so the bar doesn't darken over content at rest.
+ const listSurface = use(NativePrimaryColumnContext) ? "bg-drawer" : "bg-screen";
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
@@ -77,7 +92,7 @@ function ConfiguredSettingsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
- className="flex-1"
+ className={`flex-1 ${listSurface}`}
contentContainerClassName="gap-4 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
>
@@ -88,7 +103,7 @@ function ConfiguredSettingsRouteScreen() {
label="T3 Account"
value={accountLabel}
disabled={!isLoaded}
- onPress={() => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" })}
+ onPress={() => navigation.navigate("SettingsAuth")}
/>
<SettingsRow
icon="desktopcomputer"
@@ -107,6 +122,9 @@ function ConfiguredSettingsRouteScreen() {
}
function LocalSettingsRouteScreen() {
+ // UIKit's scroll-edge material takes the scroll view's own color; like the chat list, match
+ // the sidebar's surface so the bar doesn't darken over content at rest.
+ const listSurface = use(NativePrimaryColumnContext) ? "bg-drawer" : "bg-screen";
const insets = useSafeAreaInsets();
const { savedConnectionsById } = useSavedRemoteConnections();
const environmentCount = Object.keys(savedConnectionsById).length;
@@ -116,7 +134,7 @@ function LocalSettingsRouteScreen() {
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
- className="flex-1"
+ className={`flex-1 ${listSurface}`}
contentContainerClassName="gap-4 px-5 pt-4"
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 18) + 18,
diff --git a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
index cb9e04f58e2..ac32ff13b00 100644
--- a/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsServerControlsRouteScreen.tsx
@@ -451,12 +451,8 @@ function ServerSettingsDetail(props: { readonly page: SettingsPage }) {
label={target.label}
value="Server and provider updates"
onPress={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: {
- screen: "SettingsEnvironmentDetail",
- params: { environmentId: target.environmentId },
- },
+ navigation.navigate("SettingsEnvironmentDetail", {
+ environmentId: target.environmentId,
})
}
/>
diff --git a/apps/mobile/src/features/settings/components/SettingsRow.tsx b/apps/mobile/src/features/settings/components/SettingsRow.tsx
index 24b030ea4a2..76894659ec9 100644
--- a/apps/mobile/src/features/settings/components/SettingsRow.tsx
+++ b/apps/mobile/src/features/settings/components/SettingsRow.tsx
@@ -1,9 +1,14 @@
-import { useNavigation } from "@react-navigation/native";
-import type { ComponentProps } from "react";
+import { useNavigation, useRoute } from "@react-navigation/native";
+import { use, type ComponentProps } from "react";
import { Platform } from "react-native";
import { ListRow } from "../../../components/ui/ListRow";
-import type { SettingsLegalDocumentTarget, SettingsSheetTarget } from "./settings-sheet-targets";
+import { ListRowLayout } from "../../../components/ui/ListRowLayout";
+import { RowPressable } from "../../../components/ui/RowPressable";
+import { cn } from "../../../lib/cn";
+import type { SettingsLegalDocumentTarget, SettingsPageTarget } from "./settings-page-targets";
+import { SettingsSidebarContext } from "./SettingsSection";
+import { openSettings } from "../settings-navigation";
export function SettingsRow(props: {
readonly disabled?: boolean;
@@ -11,33 +16,48 @@ export function SettingsRow(props: {
readonly label: string;
readonly value?: string;
readonly valuePosition?: "below" | "trailing";
- readonly target?: SettingsSheetTarget;
+ readonly target?: SettingsPageTarget;
readonly fullScreenTarget?: SettingsLegalDocumentTarget;
readonly onPress?: () => void;
}) {
const navigation = useNavigation();
+ const sidebar = use(SettingsSidebarContext);
+ // The Settings list opens pages in place of the detail column; a page's own rows push below.
+ const inList = ["Home", "Settings"].includes(useRoute().name);
const valueBelow =
props.valuePosition === "below" ||
(props.valuePosition === undefined && Platform.OS === "android");
- return (
- <ListRow
- icon={props.icon}
- label={props.label}
- description={valueBelow ? props.value : undefined}
- detail={valueBelow ? undefined : props.value}
- disabled={props.disabled}
- onPress={() => {
- if (props.target) {
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: props.target },
- });
- } else if (props.fullScreenTarget) {
- navigation.navigate(props.fullScreenTarget);
- } else {
- props.onPress?.();
- }
- }}
- />
- );
+ const content = {
+ icon: props.icon,
+ label: props.label,
+ description: valueBelow ? props.value : undefined,
+ detail: valueBelow ? undefined : props.value,
+ disabled: props.disabled,
+ };
+ const onPress = () => {
+ if (props.target) {
+ if (inList) openSettings(navigation, props.target);
+ else navigation.navigate(props.target);
+ } else if (props.fullScreenTarget) {
+ navigation.navigate(props.fullScreenTarget);
+ } else {
+ props.onPress?.();
+ }
+ };
+ if (sidebar) {
+ const selected = props.target !== undefined && props.target === sidebar.selected;
+ return (
+ <RowPressable
+ accessibilityRole="button"
+ accessibilityLabel={[props.label, props.value].filter(Boolean).join(", ")}
+ accessibilityState={{ disabled: Boolean(props.disabled), selected }}
+ disabled={props.disabled}
+ onPress={onPress}
+ className={cn("rounded-2xl", selected && "bg-subtle-strong")}
+ >
+ <ListRowLayout {...content} />
+ </RowPressable>
+ );
+ }
+ return <ListRow {...content} onPress={onPress} />;
}
diff --git a/apps/mobile/src/features/settings/components/SettingsScreen.tsx b/apps/mobile/src/features/settings/components/SettingsScreen.tsx
index db596347e77..e05d71239ac 100644
--- a/apps/mobile/src/features/settings/components/SettingsScreen.tsx
+++ b/apps/mobile/src/features/settings/components/SettingsScreen.tsx
@@ -1,4 +1,4 @@
-import { useNavigation, useNavigationState, useRoute } from "@react-navigation/native";
+import { useNavigation, useRoute } from "@react-navigation/native";
import type { ReactNode } from "react";
import { Platform, View } from "react-native";
@@ -22,7 +22,6 @@ export function SettingsScreen(
) {
const navigation = useNavigation();
const route = useRoute();
- const index = useNavigationState((state) => state.index);
const workspace = useWorkspaceTabs();
const surface = useWorkspaceSurface();
const deviceType = useDeviceType();
@@ -31,7 +30,7 @@ export function SettingsScreen(
// Android opens Settings as a workspace tab; its root page has nothing to go back to.
const workspaceRoot =
props.workspaceRoot ||
- (Platform.OS === "android" && workspace !== null && index === 0 && route.name === "Settings");
+ (Platform.OS === "android" && workspace !== null && route.name === "Settings");
return (
<View
diff --git a/apps/mobile/src/features/settings/components/SettingsSection.tsx b/apps/mobile/src/features/settings/components/SettingsSection.tsx
index 7bdc015de50..bf91ad80793 100644
--- a/apps/mobile/src/features/settings/components/SettingsSection.tsx
+++ b/apps/mobile/src/features/settings/components/SettingsSection.tsx
@@ -1 +1,38 @@
-export { ListSection as SettingsSection } from "../../../components/ui/ListSection";
+import { createContext, use, type ComponentProps } from "react";
+import { View } from "react-native";
+
+import { AppText as Text } from "../../../components/ui/AppText";
+import { ListSection } from "../../../components/ui/ListSection";
+
+/**
+ * Set while the Settings list is a split view's sidebar, naming the page open beside it. Like the
+ * system Settings app, the sidebar lists plain rows and highlights that page instead of cards.
+ */
+export const SettingsSidebarContext = createContext<{ readonly selected: string | null } | null>(
+ null,
+);
+
+export function SettingsSection(props: ComponentProps<typeof ListSection>) {
+ if (!use(SettingsSidebarContext)) return <ListSection {...props} />;
+ return (
+ <View className="gap-1">
+ {props.title ? (
+ <View className="flex-row items-center justify-between gap-3 px-2">
+ <View className="min-w-0 flex-1 flex-row items-center gap-2">
+ {props.titleIcon}
+ <Text textRole="footnote" className="shrink font-t3-medium text-foreground-muted">
+ {props.title}
+ </Text>
+ </View>
+ {props.trailing}
+ </View>
+ ) : null}
+ <View>{props.children}</View>
+ {props.footer ? (
+ <Text textRole="footnote" className="px-2 text-foreground-muted">
+ {props.footer}
+ </Text>
+ ) : null}
+ </View>
+ );
+}
diff --git a/apps/mobile/src/features/settings/components/settings-page-targets.ts b/apps/mobile/src/features/settings/components/settings-page-targets.ts
new file mode 100644
index 00000000000..21267a08714
--- /dev/null
+++ b/apps/mobile/src/features/settings/components/settings-page-targets.ts
@@ -0,0 +1,30 @@
+/** Settings pages a Settings row opens. */
+export const SETTINGS_PAGE_TARGETS = [
+ "SettingsEnvironments",
+ "SettingsNotifications",
+ "SettingsThreads",
+ "SettingsAbout",
+ "SettingsArchive",
+ "SettingsAppearance",
+ "SettingsNavigation",
+ "SettingsOrganization",
+ "SettingsProjectOverview",
+ "SettingsEnvironmentNewThreads",
+ "SettingsEnvironmentSourceControl",
+ "SettingsEnvironmentAgentBehavior",
+ "SettingsEnvironmentMaintenance",
+ "SettingsProviderAccounts",
+ "SettingsKeyboard",
+ "SettingsMicrophone",
+ "SettingsFollowUp",
+ "SettingsScheduledTasks",
+ "SettingsProjectGrouping",
+ "SettingsClientStorage",
+ "SettingsDiagnostics",
+ "SettingsOpenSourceLicenses",
+ "SettingsUsage",
+] as const;
+
+export type SettingsPageTarget = (typeof SETTINGS_PAGE_TARGETS)[number];
+
+export type SettingsLegalDocumentTarget = "SettingsLegal";
diff --git a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts b/apps/mobile/src/features/settings/components/settings-sheet-targets.ts
deleted file mode 100644
index 22fa5b4b98f..00000000000
--- a/apps/mobile/src/features/settings/components/settings-sheet-targets.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-export type SettingsSheetTarget =
- | "SettingsEnvironments"
- | "SettingsNotifications"
- | "SettingsThreads"
- | "SettingsAbout"
- | "SettingsArchive"
- | "SettingsAppearance"
- | "SettingsNavigation"
- | "SettingsOrganization"
- | "SettingsProjectOverview"
- | "SettingsEnvironmentNewThreads"
- | "SettingsEnvironmentSourceControl"
- | "SettingsEnvironmentAgentBehavior"
- | "SettingsEnvironmentMaintenance"
- | "SettingsProviderAccounts"
- | "SettingsKeyboard"
- | "SettingsMicrophone"
- | "SettingsFollowUp"
- | "SettingsScheduledTasks"
- | "SettingsProjectGrouping"
- | "SettingsClientStorage"
- | "SettingsDiagnostics"
- | "SettingsOpenSourceLicenses"
- | "SettingsUsage";
-
-export type SettingsLegalDocumentTarget = "SettingsLegal";
diff --git a/apps/mobile/src/features/settings/scheduled-task-editor.tsx b/apps/mobile/src/features/settings/scheduled-task-editor.tsx
index 265f42e0059..b4fd6b944d5 100644
--- a/apps/mobile/src/features/settings/scheduled-task-editor.tsx
+++ b/apps/mobile/src/features/settings/scheduled-task-editor.tsx
@@ -1,14 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
-import {
- createContext,
- use,
- useMemo,
- useCallback,
- type Dispatch,
- type ReactNode,
- type SetStateAction,
-} from "react";
+import { useMemo, useCallback, type Dispatch, type SetStateAction } from "react";
import { useProjects, useServerConfigs } from "../../state/entities";
import {
@@ -28,19 +20,8 @@ import {
type ScheduledTaskEditor,
} from "./scheduled-task-editor-state";
-const ScheduledTaskEditorContext = createContext<{
- readonly editor: ScheduledTaskEditor | null;
- readonly voiceOwnerKey: string;
- readonly readEditor: () => ScheduledTaskEditor | null;
- readonly setEditor: Dispatch<SetStateAction<ScheduledTaskEditor | null>>;
- readonly startEditor: (editor: ScheduledTaskEditor | null) => void;
- readonly hasChanges: boolean;
- readonly resetEditor: () => void;
- readonly draftForEnvironment: (environmentId: EnvironmentId) => ScheduledTaskDraft;
-} | null>(null);
-
-/** Keeps the form draft alive while its native picker routes are on top. */
-export function ScheduledTaskEditorProvider({ children }: { readonly children: ReactNode }) {
+/** The form draft lives in an atom, so it survives while its native picker routes are on top. */
+export function useScheduledTaskEditor() {
const { selectedTargets, selectedProjectKey, projectGroups } = useSettingsEnvironmentFilter();
const selectedGroup = projectGroups.find((group) => group.key === selectedProjectKey);
const configs = useServerConfigs();
@@ -102,7 +83,7 @@ export function ScheduledTaskEditorProvider({ children }: { readonly children: R
() => readScheduledTaskEditor(voiceOwnerKey, defaultEditor),
[defaultEditor, voiceOwnerKey],
);
- const value = useMemo(
+ return useMemo(
() => ({
editor,
voiceOwnerKey,
@@ -124,11 +105,4 @@ export function ScheduledTaskEditorProvider({ children }: { readonly children: R
draftForEnvironment,
],
);
- return <ScheduledTaskEditorContext value={value}>{children}</ScheduledTaskEditorContext>;
-}
-
-export function useScheduledTaskEditor() {
- const context = use(ScheduledTaskEditorContext);
- if (!context) throw new Error("Scheduled task editor provider is missing.");
- return context;
}
diff --git a/apps/mobile/src/features/settings/settings-environment-filter.tsx b/apps/mobile/src/features/settings/settings-environment-filter.tsx
index e82991262d1..8564c950da3 100644
--- a/apps/mobile/src/features/settings/settings-environment-filter.tsx
+++ b/apps/mobile/src/features/settings/settings-environment-filter.tsx
@@ -1,6 +1,14 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { buildProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
-import { createContext, useContext, useMemo, useState, type ReactNode } from "react";
+import {
+ createContext,
+ useContext,
+ useMemo,
+ useState,
+ type Dispatch,
+ type ReactNode,
+ type SetStateAction,
+} from "react";
import { useEnvironments, type EnvironmentPresentation } from "../../state/environments";
import { useProjects } from "../../state/entities";
@@ -11,41 +19,88 @@ export type SettingsTarget = EnvironmentPresentation & {
readonly serverConfig: NonNullable<EnvironmentPresentation["serverConfig"]>;
};
+// Several mounted Settings components read the scope at once (the list, its header, a page and
+// its editor), so share the derived lists across them for the same inputs.
+const targetsCache = new WeakMap<readonly EnvironmentPresentation[], readonly SettingsTarget[]>();
+const groupsCache = new WeakMap<object, Map<string, ReturnType<typeof buildProjectGroups>>>();
+
function connectedSettingsTargets(environments: readonly EnvironmentPresentation[]) {
- return environments.filter(
- (entry): entry is SettingsTarget =>
- entry.connection.phase === "connected" && entry.serverConfig !== null,
- );
+ let targets = targetsCache.get(environments);
+ if (!targets) {
+ targets = environments.filter(
+ (entry): entry is SettingsTarget =>
+ entry.connection.phase === "connected" && entry.serverConfig !== null,
+ );
+ targetsCache.set(environments, targets);
+ }
+ return targets;
+}
+
+function settingsProjectGroups(
+ projects: Parameters<typeof buildProjectGroups>[0]["projects"],
+ groupingMode: Parameters<typeof buildProjectGroups>[0]["settings"]["sidebarProjectGroupingMode"],
+) {
+ let byMode = groupsCache.get(projects);
+ if (!byMode) groupsCache.set(projects, (byMode = new Map()));
+ let groups = byMode.get(groupingMode);
+ if (!groups) {
+ groups = buildProjectGroups({
+ projects,
+ settings: { sidebarProjectGroupingMode: groupingMode, sidebarProjectGroupingOverrides: {} },
+ });
+ byMode.set(groupingMode, groups);
+ }
+ return groups;
}
-const SettingsEnvironmentFilterContext = createContext<{
- readonly availableTargets: readonly SettingsTarget[];
- readonly selectedTargets: readonly SettingsTarget[];
+interface SettingsEnvironmentSelection {
readonly selectedIds: ReadonlySet<EnvironmentId> | null;
- readonly projectGroups: ReturnType<typeof buildProjectGroups>;
- readonly selectableProjectGroups: ReturnType<typeof buildProjectGroups>;
readonly selectedProjectKey: string | null;
- readonly selectProject: (projectKey: string | null) => void;
- readonly selectAll: () => void;
- readonly toggleEnvironment: (environmentId: EnvironmentId) => void;
-} | null>(null);
+ readonly setSelectedIds: Dispatch<SetStateAction<ReadonlySet<EnvironmentId> | null>>;
+ readonly setSelectedProjectKey: Dispatch<SetStateAction<string | null>>;
+}
+
+const SettingsEnvironmentSelectionContext = createContext<SettingsEnvironmentSelection | null>(
+ null,
+);
-export function SettingsEnvironmentFilterProvider(props: { readonly children: ReactNode }) {
+/**
+ * Holds the Settings scope selection across Settings pages, which are separate root routes.
+ * It stays mounted for the whole app, so it keeps only the selection; the environment and
+ * project data is derived in the hook, by the Settings pages that are mounted. The selection
+ * resets when Settings closes.
+ */
+export function SettingsEnvironmentFilterProvider(props: {
+ readonly open: boolean;
+ readonly children: ReactNode;
+}) {
+ const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId> | null>(null);
+ const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
+ if (!props.open && (selectedIds !== null || selectedProjectKey !== null)) {
+ setSelectedIds(null);
+ setSelectedProjectKey(null);
+ }
+ const value = useMemo(
+ () => ({ selectedIds, selectedProjectKey, setSelectedIds, setSelectedProjectKey }),
+ [selectedIds, selectedProjectKey],
+ );
+ return (
+ <SettingsEnvironmentSelectionContext value={value}>
+ {props.children}
+ </SettingsEnvironmentSelectionContext>
+ );
+}
+
+export function useSettingsEnvironmentFilter() {
+ const selection = useContext(SettingsEnvironmentSelectionContext);
+ if (selection === null) throw new Error("Settings environment filter provider is missing.");
+ const { selectedIds, selectedProjectKey, setSelectedIds, setSelectedProjectKey } = selection;
const { environments } = useEnvironments();
const projects = useProjects();
const groupingSettings = useMobileProjectGroupingSettings();
const groupingMode = groupingSettings.sidebarProjectGroupingMode;
- const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId> | null>(null);
- const [selectedProjectKey, setSelectedProjectKey] = useState<string | null>(null);
- const projectGroups = useMemo(
- () =>
- buildProjectGroups({
- projects,
- settings: { sidebarProjectGroupingMode: groupingMode, sidebarProjectGroupingOverrides: {} },
- }),
- [projects, groupingMode],
- );
- const availableTargets = useMemo(() => connectedSettingsTargets(environments), [environments]);
+ const projectGroups = settingsProjectGroups(projects, groupingMode);
+ const availableTargets = connectedSettingsTargets(environments);
const selectedTargets = useMemo(
() =>
availableTargets.filter(
@@ -62,7 +117,7 @@ export function SettingsEnvironmentFilterProvider(props: { readonly children: Re
),
[projectGroups, selectedTargets],
);
- const value = useMemo(
+ return useMemo(
() => ({
availableTargets,
selectedTargets,
@@ -84,17 +139,8 @@ export function SettingsEnvironmentFilterProvider(props: { readonly children: Re
projectGroups,
selectableProjectGroups,
selectedProjectKey,
+ setSelectedIds,
+ setSelectedProjectKey,
],
);
- return (
- <SettingsEnvironmentFilterContext value={value}>
- {props.children}
- </SettingsEnvironmentFilterContext>
- );
-}
-
-export function useSettingsEnvironmentFilter() {
- const filter = useContext(SettingsEnvironmentFilterContext);
- if (filter === null) throw new Error("Settings environment filter provider is missing.");
- return filter;
}
diff --git a/apps/mobile/src/features/settings/settings-navigation.ts b/apps/mobile/src/features/settings/settings-navigation.ts
new file mode 100644
index 00000000000..b97bc948c0a
--- /dev/null
+++ b/apps/mobile/src/features/settings/settings-navigation.ts
@@ -0,0 +1,119 @@
+import type { NavigationState, PartialState } from "@react-navigation/native";
+
+import {
+ dispatchRootStackReset,
+ resetRootStack,
+ rootStackState,
+ type RootStackNavigation,
+} from "../../lib/root-stack-reset";
+
+type RootParams = ReactNavigation.RootParamList;
+
+/** Settings routes that open as modals over whatever is on screen, not as Settings pages. */
+const SETTINGS_MODAL_ROUTES = new Set(["SettingsLegal", "SettingsAuth", "SettingsWaitlist"]);
+
+/** Root routes that make up the Settings tab: its list and the pages it opens. */
+export type SettingsRouteName = Exclude<
+ Extract<keyof RootParams, `Settings${string}`>,
+ "SettingsLegal" | "SettingsAuth" | "SettingsWaitlist"
+>;
+
+/** A page in the Settings tab's detail column. */
+export type SettingsPageName = Exclude<SettingsRouteName, "Settings">;
+
+export function isSettingsRoute(name: string): boolean {
+ return name.startsWith("Settings") && !SETTINGS_MODAL_ROUTES.has(name);
+}
+
+/**
+ * Settings is open while its `Settings` route is under the topmost workspace page and that
+ * page is a Settings page. A Settings page pushed without it, such as a usage account opened
+ * from the Usage tab, stays a detail of the current tab.
+ */
+export function settingsOpenIn(workspaceRoutes: readonly { readonly name: string }[]): boolean {
+ return (
+ workspaceRoutes.some((route) => route.name === "Settings") &&
+ isSettingsRoute(workspaceRoutes.at(-1)?.name ?? "")
+ );
+}
+
+/**
+ * A `settings/...` link names only its page, so put the Settings tab's route under it. A bare
+ * `settings` link opens `page` beside the list when the window has columns.
+ */
+export function restoreSettingsLinkState(
+ state: PartialState<NavigationState> | undefined,
+ page: SettingsPageName | undefined,
+) {
+ if (!state) return state;
+ const routes = [...state.routes];
+ const list = routes.findIndex((route) => route.name === "Settings");
+ const first = routes.findIndex((route) => isSettingsRoute(route.name));
+ if (first < 0) return state;
+ if (list < 0) routes.splice(first, 0, { name: "Settings" });
+ const top = routes.at(-1);
+ if (page && top?.name === "Settings") routes.push({ name: page });
+ return routes.length === state.routes.length
+ ? state
+ : { ...state, index: routes.length - 1, routes };
+}
+
+type SettingsPageArgs<Name extends SettingsPageName> = undefined extends RootParams[Name]
+ ? [params?: RootParams[Name]]
+ : [params: RootParams[Name]];
+
+type RouteLike = { readonly name: string; readonly key?: string; readonly params?: object };
+
+/**
+ * Settings pages sit on the root stack above Home, under a `Settings` route that keeps the
+ * Settings list as the workspace's primary content. Opening a page replaces whatever was above
+ * Home, so the tab always starts from its list and Back returns there. Routes already on screen
+ * keep their keys, so reopening the open page doesn't rebuild it.
+ */
+export function settingsNavigationState<State extends { readonly routes: readonly RouteLike[] }>(
+ state: State,
+ page: SettingsPageName | undefined,
+ params?: object,
+ key?: string,
+) {
+ const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" };
+ const list = state.routes.find((route) => route.name === "Settings") ?? { name: "Settings" };
+ const current = page
+ ? state.routes.find(
+ (route) => route.name === page && JSON.stringify(route.params) === JSON.stringify(params),
+ )
+ : undefined;
+ const routes = [
+ home,
+ list,
+ ...(page ? [current ?? (key ? { key, name: page, params } : { name: page, params })] : []),
+ ];
+ return { ...state, index: routes.length - 1, routes };
+}
+
+/** Opens one Settings page in the Settings tab, from anywhere outside it. */
+export function openSettings<Name extends SettingsPageName>(
+ navigation: RootStackNavigation,
+ page: Name,
+ ...[params]: SettingsPageArgs<Name>
+) {
+ resetRootStack(navigation, (state) => settingsNavigationState(state, page, params));
+}
+
+/**
+ * Closes a Settings page that finished its job. The first page beside the list is replaced with
+ * `fallback` when the window has columns, since going back would leave the detail column empty.
+ */
+export function leaveSettingsPage(
+ navigation: RootStackNavigation & { readonly goBack: () => void },
+ columns: boolean,
+ fallback: SettingsPageName,
+) {
+ const state = rootStackState(navigation);
+ const below = state?.routes[state.index - 1];
+ if (state && columns && below?.name === "Settings") {
+ dispatchRootStackReset(navigation, state, settingsNavigationState(state, fallback));
+ } else {
+ navigation.goBack();
+ }
+}
diff --git a/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx b/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx
index 6e5d42c47d9..761fa805ddb 100644
--- a/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx
+++ b/apps/mobile/src/features/showcase/ShowcaseCaptureCoordinator.tsx
@@ -33,6 +33,7 @@ import {
subscribeToShowcaseRenderSignal,
} from "./showcaseRenderSignal";
import { stageShowcaseAgentActivity } from "./stageShowcaseAgentActivity";
+import { openSettings } from "../settings/settings-navigation";
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
const SHOWCASE_THREAD_ID = "remote-command-center";
@@ -243,12 +244,7 @@ function EnabledShowcaseCaptureCoordinator(props: { readonly pathname: string })
return;
}
if (requestedScene === "environments") {
- navigation.dispatch(
- CommonActions.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironments" },
- }),
- );
+ openSettings(navigation, "SettingsEnvironments");
} else if (requestedScene === "terminal") {
navigation.dispatch(
CommonActions.navigate("ThreadTerminal", { ...params, terminalId: "term-1" }),
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index f24ed10e6ca..6f0619ab37a 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -284,6 +284,7 @@ import {
ThreadMarkdownImageUnavailable,
ThreadMarkdownImageView,
} from "./ThreadMarkdownImage";
+import { openSettings } from "../settings/settings-navigation";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
// Native iOS blockquotes and adjacent selectable text are separate layout
@@ -1173,12 +1174,7 @@ function ThreadAutomationMessageRow(props: {
<Pressable
accessibilityRole="link"
hitSlop={6}
- onPress={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsScheduledTasks" },
- })
- }
+ onPress={() => openSettings(navigation, "SettingsScheduledTasks")}
>
<Text className="font-t3-medium text-xs text-foreground-secondary">
Open automation
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 256a8b13b73..d47e3455181 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -97,6 +97,7 @@ import {
useAndroidWorkspaceBack,
useWorkspaceBackNavigation,
} from "../workspace/useAndroidWorkspaceNavigation";
+import { openSettings } from "../settings/settings-navigation";
interface ThreadInspectorSelection {
readonly routeThreadIdentity: string | null;
@@ -256,10 +257,7 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {
onReconnectEnvironment(environmentId);
return;
}
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironments" },
- });
+ openSettings(navigation, "SettingsEnvironments");
}}
/>
);
diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx
index 010c902364c..fcd927b8d32 100644
--- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx
+++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx
@@ -151,18 +151,12 @@ function PoolWindowCard({
const navigation = useNavigation();
const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0);
const openAccount = (account: LimitAccount) =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: {
- screen: "SettingsUsageAccount",
- params: {
- accountKey: account.key,
- windowId: pool.id,
- windowKind: pool.kind,
- environmentIds,
- now,
- },
- },
+ navigation.navigate("SettingsUsageAccount", {
+ accountKey: account.key,
+ windowId: pool.id,
+ windowKind: pool.kind,
+ environmentIds,
+ now,
});
return (
<View className="gap-3 rounded-[24px] border-continuous bg-grouped-card p-4">
diff --git a/apps/mobile/src/features/workspace/AndroidWorkspaceSettings.tsx b/apps/mobile/src/features/workspace/AndroidWorkspaceSettings.tsx
deleted file mode 100644
index 9e616e2b8c0..00000000000
--- a/apps/mobile/src/features/workspace/AndroidWorkspaceSettings.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import type { ReactNode } from "react";
-import { Platform, View } from "react-native";
-import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
-import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
-import { AndroidWorkspaceNavigation } from "./AndroidWorkspaceNavigation";
-
-/** Settings keeps its existing stack inside the full workspace, above compact navigation. */
-export function AndroidWorkspaceSettings(props: { readonly children: ReactNode }) {
- const { layout, startNewTask } = useAdaptiveWorkspaceLayout();
- const insets = useSafeAreaInsets();
- if (Platform.OS !== "android") return props.children;
- return (
- <View className="flex-1 bg-header">
- <SafeAreaInsetsContext value={layout.usesSplitView ? insets : { ...insets, bottom: 0 }}>
- <View className="flex-1">{props.children}</View>
- </SafeAreaInsetsContext>
- {layout.usesSplitView ? null : <AndroidWorkspaceNavigation onNewThread={startNewTask} />}
- </View>
- );
-}
diff --git a/apps/mobile/src/features/workspace/WorkspaceNativeTabs.ios.tsx b/apps/mobile/src/features/workspace/WorkspaceNativeTabs.ios.tsx
index 7bc9ebacea8..344e787d044 100644
--- a/apps/mobile/src/features/workspace/WorkspaceNativeTabs.ios.tsx
+++ b/apps/mobile/src/features/workspace/WorkspaceNativeTabs.ios.tsx
@@ -1,17 +1,11 @@
-import { useNavigation } from "@react-navigation/native";
import {
WORKSPACE_TAB_LABELS,
NAVIGATION_TAB_ICONS,
useEnabledNavigationTabs,
} from "./navigation-tabs";
-import { useCallback, useMemo, useState, type ReactNode } from "react";
-import { Keyboard, View, useWindowDimensions, type NativeSyntheticEvent } from "react-native";
-import {
- Tabs,
- type TabSelectedEvent,
- type TabSelectionPreventedEvent,
- type TabSelectionRejectedEvent,
-} from "react-native-screens";
+import { useCallback, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { View, useWindowDimensions, type NativeSyntheticEvent } from "react-native";
+import { Tabs, type TabSelectedEvent, type TabSelectionRejectedEvent } from "react-native-screens";
import { WorkspaceTabsContext, useWorkspaceTabs } from "./WorkspaceTabsContext";
import {
@@ -20,12 +14,16 @@ import {
workspaceUsesColumns,
type WorkspaceTab,
} from "./workspace-tabs-state";
-import { NativeWorkspaceTabActivityContext } from "../../native/v5-workspace-context";
+import {
+ NativeWorkspaceTabActivityContext,
+ WorkspaceSlotOptionsContext,
+} from "../../native/v5-workspace-context";
import { useCompactWorkspaceTabs, useSystemWorkspaceTabBar } from "./useSystemWorkspaceTabBar";
import { useControlTheme } from "../../components/ui/useControlTheme";
import { useDeviceType } from "../../native/native-layout-metrics";
import { WorkspaceSidebarTabs } from "./WorkspaceSidebarTabs";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
+import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab";
const PULL_REQUEST_ICON = require("../../../assets/icons/pull-request.png");
@@ -36,8 +34,12 @@ function RetainedWorkspaceTab(props: {
readonly children: ReactNode;
}) {
const workspace = useWorkspaceTabs()!;
- const { isTabActive } = workspace;
- const isActive = useCallback(() => isTabActive(props.tab), [isTabActive, props.tab]);
+ // Whether this slot is the visible one, read by cleanups after the switch has committed.
+ const activeRef = useRef(props.active);
+ useLayoutEffect(() => {
+ activeRef.current = props.active;
+ }, [props.active]);
+ const isActive = useCallback(() => activeRef.current, []);
const activity = useMemo(
() => ({
active: props.active,
@@ -45,6 +47,19 @@ function RetainedWorkspaceTab(props: {
}),
[props.active, isActive],
);
+ const [optionsByRoute, setOptionsByRoute] = useState<ReadonlyMap<string, object>>(new Map());
+ // Stable, so writers and the cleanups that depend on them don't re-run on every write.
+ const setRouteOptions = useCallback(
+ (routeKey: string, options: object) =>
+ setOptionsByRoute((current) =>
+ new Map(current).set(routeKey, { ...current.get(routeKey), ...options }),
+ ),
+ [],
+ );
+ const slotOptions = useMemo(
+ () => ({ byRoute: optionsByRoute, set: setRouteOptions }),
+ [optionsByRoute, setRouteOptions],
+ );
const [content, setContent] = useState(
props.active ? { workspace, children: props.children } : null,
);
@@ -52,7 +67,9 @@ function RetainedWorkspaceTab(props: {
setContent({ workspace, children: props.children });
return content ? (
<NativeWorkspaceTabActivityContext value={activity}>
- <WorkspaceTabsContext value={content.workspace}>{content.children}</WorkspaceTabsContext>
+ <WorkspaceSlotOptionsContext value={slotOptions}>
+ <WorkspaceTabsContext value={content.workspace}>{content.children}</WorkspaceTabsContext>
+ </WorkspaceSlotOptionsContext>
</NativeWorkspaceTabActivityContext>
) : null;
}
@@ -60,13 +77,12 @@ function RetainedWorkspaceTab(props: {
export function WorkspaceNativeTabs(props: {
readonly children: ReactNode;
readonly hidden: boolean;
- readonly onSelect: () => void;
}) {
const workspace = useWorkspaceTabs()!;
const order = useEnabledNavigationTabs();
const primaryTabs = order.slice(0, 4);
const overflow = order[4];
- const navigation = useNavigation();
+ const selectTab = useSelectWorkspaceTab();
const [provenance, setProvenance] = useState(0);
const systemTabBar = useSystemWorkspaceTabBar();
const deviceType = useDeviceType();
@@ -95,16 +111,6 @@ export function WorkspaceNativeTabs(props: {
tabBarMinimizeBehavior: "never",
tabBarTintColor: colors["--color-primary"],
}}
- onTabSelectionPrevented={({
- nativeEvent,
- }: NativeSyntheticEvent<TabSelectionPreventedEvent>) => {
- if (nativeEvent.preventedScreenKey === "settings") {
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- });
- }
- }}
onTabSelectionRejected={({
nativeEvent,
}: NativeSyntheticEvent<TabSelectionRejectedEvent>) =>
@@ -114,18 +120,7 @@ export function WorkspaceNativeTabs(props: {
setProvenance(nativeEvent.provenance);
if (nativeEvent.actionOrigin === "programmatic-js") return;
const tab = workspaceTabForNativeSlot(primaryTabs, nativeEvent.selectedScreenKey);
- // UIKit sends reselects here even when preventNativeSelection is enabled.
- if (tab === "settings") {
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- });
- return;
- }
- if (!tab) return;
- Keyboard.dismiss();
- props.onSelect();
- workspace.dispatch({ type: "select", tab });
+ if (tab) selectTab(tab);
}}
>
{NATIVE_WORKSPACE_TAB_SLOTS.map((slot, index) => {
@@ -139,7 +134,6 @@ export function WorkspaceNativeTabs(props: {
screenKey={slot}
title=""
tabBarItemAccessibilityLabel={settings ? "Settings" : WORKSPACE_TAB_LABELS[tab]}
- preventNativeSelection={settings}
ios={{
icon: settings
? { type: "sfSymbol", name: "gearshape" }
@@ -166,7 +160,7 @@ export function WorkspaceNativeTabs(props: {
{(deviceType === "pad" ||
compactTabs ||
(layout.primarySidebarOverlaysContent &&
- (workspace.settingsOpen || !workspaceUsesColumns(selectedTab)))) &&
+ !workspaceUsesColumns(selectedTab, workspace.settingsOpen))) &&
!props.hidden ? (
<View
pointerEvents="box-none"
diff --git a/apps/mobile/src/features/workspace/WorkspaceNoTabs.tsx b/apps/mobile/src/features/workspace/WorkspaceNoTabs.tsx
index f217cbf86b9..1db0f2529de 100644
--- a/apps/mobile/src/features/workspace/WorkspaceNoTabs.tsx
+++ b/apps/mobile/src/features/workspace/WorkspaceNoTabs.tsx
@@ -1,6 +1,7 @@
import { useNavigation } from "@react-navigation/native";
import { View } from "react-native";
import { EmptyState } from "../../components/ui/EmptyState";
+import { openSettings } from "../settings/settings-navigation";
export function WorkspaceNoTabs() {
const navigation = useNavigation();
@@ -11,12 +12,7 @@ export function WorkspaceNoTabs() {
detail="Show a section to add it back to navigation."
actionLabel="Edit navigation tabs"
variant="plain"
- onAction={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsNavigation", initial: false },
- })
- }
+ onAction={() => openSettings(navigation, "SettingsNavigation")}
/>
</View>
);
diff --git a/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx b/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx
index 2ca3fc7cdf8..69efd96411f 100644
--- a/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx
+++ b/apps/mobile/src/features/workspace/WorkspaceRootScreen.tsx
@@ -1,6 +1,7 @@
import { WorkspaceNoTabs } from "./WorkspaceNoTabs";
import { WORKSPACE_TAB_LABELS, useEnabledNavigationTabs } from "./navigation-tabs";
import { WorkspaceExtraTab } from "./WorkspaceExtraTab";
+import { SettingsRouteScreen } from "../settings/SettingsRouteScreen";
import { WorkspaceSectionToolbar } from "./WorkspaceSectionToolbar";
import { useNavigation } from "@react-navigation/native";
import { use, useCallback, useMemo } from "react";
@@ -44,6 +45,8 @@ import {
useSidebarWorkspaceTabs,
useSystemWorkspaceTabBar,
} from "./useSystemWorkspaceTabBar";
+import { openSettings } from "../settings/settings-navigation";
+import { useSelectWorkspaceTab } from "./useSelectWorkspaceTab";
const TAB_TITLES = WORKSPACE_TAB_LABELS;
@@ -70,6 +73,7 @@ function WorkspaceRootTitle(props: {
function WorkspaceRootContent() {
const navigation = useNavigation();
+ const selectTab = useSelectWorkspaceTab();
const { width: windowWidth } = useWindowDimensions();
const { layout, startNewTask } = useAdaptiveWorkspaceLayout();
const primaryColumn = use(NativePrimaryColumnContext);
@@ -97,17 +101,14 @@ function WorkspaceRootContent() {
() => (
<WorkspaceRootTitle
maxWidth={Math.max(0, width - 160)}
- onOpenEnvironments={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "SettingsEnvironments" },
- })
- }
+ onOpenEnvironments={() => openSettings(navigation, "SettingsEnvironments")}
/>
),
[width, navigation],
);
const tab = state.tabs[state.selectedTab];
+ // Settings is a workspace tab too; its list takes the place of the selected tab's.
+ const settingsOpen = workspace.settingsOpen;
const bottomClearance =
layout.primarySidebarOverlaysContent && state.selectedTab === "usage"
? workspaceDockBottomClearance({ bottomInset: insets.bottom, keyboardHeight })
@@ -140,6 +141,7 @@ function WorkspaceRootContent() {
{Platform.OS === "ios" ? (
<NativeStackScreenOptions
optionsVersion={[
+ settingsOpen,
state.selectedTab,
state.selectionRevision,
width,
@@ -147,7 +149,11 @@ function WorkspaceRootContent() {
enabled.length,
]}
options={{
- title: enabled.length ? TAB_TITLES[state.selectedTab] : "Navigation",
+ title: settingsOpen
+ ? "Settings"
+ : enabled.length
+ ? TAB_TITLES[state.selectedTab]
+ : "Navigation",
headerShown: true,
headerTransparent: NATIVE_LIQUID_GLASS_SUPPORTED,
headerStyle: NATIVE_LIQUID_GLASS_SUPPORTED
@@ -158,7 +164,8 @@ function WorkspaceRootContent() {
? { headerSearchBarOptions: undefined, unstable_headerRightItems: () => [] }
: {}),
unstable_headerLeftItems: () => [],
- headerTitle: state.selectedTab === "usage" ? undefined : renderHeaderTitle,
+ headerTitle:
+ settingsOpen || state.selectedTab === "usage" ? undefined : renderHeaderTitle,
}}
/>
) : (
@@ -181,11 +188,7 @@ function WorkspaceRootContent() {
{
accessibilityLabel: "Settings",
icon: "gearshape",
- onPress: () =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- }),
+ onPress: () => selectTab("settings"),
},
]}
/>
@@ -195,7 +198,12 @@ function WorkspaceRootContent() {
sidebarPicker ? { ...insets, top: 0 } : compactTabs ? { ...insets, bottom: 0 } : insets
}
>
- {enabled.length === 0 ? (
+ {settingsOpen ? (
+ <>
+ <NativeStackScreenOptions options={{ headerSearchBarOptions: undefined }} />
+ <SettingsRouteScreen />
+ </>
+ ) : enabled.length === 0 ? (
<WorkspaceNoTabs />
) : state.selectedTab === "threads" ? (
<HomeRouteScreen />
@@ -208,13 +216,13 @@ function WorkspaceRootContent() {
{deviceType !== "pad" && deviceType !== "phone" && sidebarPicker ? (
<WorkspaceSidebarTabs />
) : null}
- {enabled.length === 0 ? null : state.selectedTab === "threads" ||
- state.selectedTab === "pullRequests" ? (
+ {enabled.length === 0 && !settingsOpen ? null : !settingsOpen &&
+ (state.selectedTab === "threads" || state.selectedTab === "pullRequests") ? (
<WorkspaceToolbar sidebar={sidebarNavigation} onNewTask={startNewTask} />
) : (
<WorkspaceSectionToolbar
onNewTask={startNewTask}
- showCompose={state.selectedTab !== "usage"}
+ showCompose={!settingsOpen && state.selectedTab !== "usage"}
/>
)}
</View>
diff --git a/apps/mobile/src/features/workspace/WorkspaceSectionToolbar.tsx b/apps/mobile/src/features/workspace/WorkspaceSectionToolbar.tsx
index cf105d8ad82..cb9128ba039 100644
--- a/apps/mobile/src/features/workspace/WorkspaceSectionToolbar.tsx
+++ b/apps/mobile/src/features/workspace/WorkspaceSectionToolbar.tsx
@@ -49,12 +49,7 @@ export function WorkspaceTabToolbarButtons() {
accessibilityLabel="Settings"
icon="gearshape"
tintColor={selected === "settings" ? selectedTint : undefined}
- onPress={() =>
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- })
- }
+ onPress={() => selectTab("settings")}
/>
</>
);
diff --git a/apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsx b/apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsx
index 4b260b0cc46..a5e608dc4a4 100644
--- a/apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsx
+++ b/apps/mobile/src/features/workspace/WorkspaceSidebarTabs.ios.tsx
@@ -51,11 +51,7 @@ export function WorkspaceSidebarTabs(props: {
onCompose={() => props.onNewTask?.()}
onSelectionChange={({ nativeEvent }) => {
const tab = tabs.find((candidate) => candidate === nativeEvent.tab);
- if (tab === "settings")
- navigation.navigate("SettingsSheet", {
- screen: "SettingsContent",
- params: { screen: "Settings" },
- });
+ if (tab === "settings") selectTab("settings");
else if (tab) selectTab(tab);
}}
// Keep the host stable while UIKit updates the bars' intrinsic size and safe area together.
diff --git a/apps/mobile/src/features/workspace/android-workspace-tabs.ts b/apps/mobile/src/features/workspace/android-workspace-tabs.ts
index 999838f52dc..30107666c8e 100644
--- a/apps/mobile/src/features/workspace/android-workspace-tabs.ts
+++ b/apps/mobile/src/features/workspace/android-workspace-tabs.ts
@@ -1,41 +1,33 @@
import type { NavigationState } from "@react-navigation/native";
import { androidWorkspaceNavigationState } from "../../lib/android-workspace-navigation";
+import {
+ isSettingsRoute,
+ settingsNavigationState,
+ settingsOpenIn,
+} from "../settings/settings-navigation";
import type { WorkspaceTab } from "./workspace-tabs-state";
/** Settings joins the two list tabs as a top-level Android destination. */
export type AndroidWorkspaceNavigationTab = WorkspaceTab | "settings";
-const WORKSPACE_ROUTES = new Set(["Home", "Thread", "PullRequest", "SettingsSheet"]);
+const WORKSPACE_ROUTES = new Set(["Home", "Thread", "PullRequest"]);
-/**
- * The Settings tab reuses the settings navigator, reset over Home alone so stale chat and
- * PR history is dropped while nested settings pages keep an ordinary Back.
- */
+/** The Settings tab resets over Home alone so stale chat and PR history is dropped. */
export function androidWorkspaceTabNavigationState(
state: NavigationState,
tab: AndroidWorkspaceNavigationTab,
) {
const home = androidWorkspaceNavigationState(state);
- if (tab !== "settings") return home;
- return {
- ...home,
- index: 1,
- routes: [
- ...home.routes,
- {
- name: "SettingsSheet",
- params: { screen: "SettingsContent", params: { screen: "Settings" } },
- },
- ],
- };
+ return tab === "settings" ? settingsNavigationState(home, undefined) : home;
}
-/** Settings stays selected while its navigator is the topmost workspace route. */
+/** Settings stays selected while one of its pages is the topmost workspace route. */
export function androidWorkspaceSettingsOpen(state: NavigationState): boolean {
- const top = state.routes
- .slice(0, state.index + 1)
- .findLast((route) => WORKSPACE_ROUTES.has(route.name));
- return top?.name === "SettingsSheet";
+ return settingsOpenIn(
+ state.routes
+ .slice(0, state.index + 1)
+ .filter((route) => WORKSPACE_ROUTES.has(route.name) || isSettingsRoute(route.name)),
+ );
}
export function androidWorkspaceTabFromNavigationState(
diff --git a/apps/mobile/src/features/workspace/useSelectWorkspaceTab.ts b/apps/mobile/src/features/workspace/useSelectWorkspaceTab.ts
index 6c31cee8738..1cd5d83df78 100644
--- a/apps/mobile/src/features/workspace/useSelectWorkspaceTab.ts
+++ b/apps/mobile/src/features/workspace/useSelectWorkspaceTab.ts
@@ -1,22 +1,20 @@
-import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback } from "react";
-import { Keyboard, Platform } from "react-native";
-import { resetAndroidWorkspace } from "../../lib/android-workspace-navigation";
+import { Keyboard } from "react-native";
+
+import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { useWorkspaceTabs } from "./WorkspaceTabsContext";
import type { WorkspaceTab } from "./workspace-tabs-state";
-/** Switch workspace tabs from inside the sidebar, closing any open detail first. */
+/** Opens a workspace tab, Settings included, from a tab bar, rail, toolbar or command. */
export function useSelectWorkspaceTab() {
- const workspace = useWorkspaceTabs()!;
- const navigation = useNavigation();
- const { dispatch } = workspace;
+ const dispatch = useWorkspaceTabs()?.dispatch;
+ const { openWorkspaceTab } = useAdaptiveWorkspaceLayout();
return useCallback(
- (tab: WorkspaceTab) => {
+ (tab: WorkspaceTab | "settings") => {
Keyboard.dismiss();
- if (Platform.OS === "android") resetAndroidWorkspace(navigation);
- else navigation.dispatch(StackActions.popTo("Home"));
- dispatch({ type: "select", tab });
+ openWorkspaceTab(tab);
+ if (tab !== "settings") dispatch?.({ type: "select", tab });
},
- [dispatch, navigation],
+ [dispatch, openWorkspaceTab],
);
}
diff --git a/apps/mobile/src/features/workspace/useSystemWorkspaceTabBar.ts b/apps/mobile/src/features/workspace/useSystemWorkspaceTabBar.ts
index 35c41afb339..cdeccc8b8a6 100644
--- a/apps/mobile/src/features/workspace/useSystemWorkspaceTabBar.ts
+++ b/apps/mobile/src/features/workspace/useSystemWorkspaceTabBar.ts
@@ -8,8 +8,7 @@ import { workspaceUsesColumns } from "./workspace-tabs-state";
function useWorkspacePage() {
const workspace = useWorkspaceTabs();
return (
- workspace !== null &&
- (workspace.settingsOpen || !workspaceUsesColumns(workspace.state.selectedTab))
+ workspace !== null && !workspaceUsesColumns(workspace.state.selectedTab, workspace.settingsOpen)
);
}
diff --git a/apps/mobile/src/features/workspace/workspace-selection-store.ts b/apps/mobile/src/features/workspace/workspace-selection-store.ts
new file mode 100644
index 00000000000..52c11038719
--- /dev/null
+++ b/apps/mobile/src/features/workspace/workspace-selection-store.ts
@@ -0,0 +1,142 @@
+import type { NavigationState } from "@react-navigation/native";
+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
+import * as Linking from "expo-linking";
+import { AppState, Dimensions, Platform } from "react-native";
+
+import { environmentCatalog } from "../../connection/catalog";
+import { deriveLayout } from "../../lib/layout";
+import {
+ NATIVE_METRICS_TIMEOUT_MS,
+ nativeWorkspaceColumnsSupportedFor,
+} from "../../native/NativeWorkspaceColumns";
+import {
+ currentNativeLayoutMetrics,
+ firstNativeLayoutMetrics,
+} from "../../native/native-layout-metrics";
+import { loadPreferences, savePreferencesPatch } from "../../persistence/imperative";
+import { rootStackState, type RootStackNavigation } from "../../lib/root-stack-reset";
+import { workspaceRoutesOf } from "../layout/workspace-overlay-routes";
+import type { WorkspaceSelections } from "../../persistence/mobile-preferences";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { environmentPresentations } from "../../state/presentation";
+import { environmentThreadShells, threadEnvironment } from "../../state/threads";
+import {
+ rememberedSettingsPage,
+ workspaceSelectionsIn,
+ type WorkspaceSelectionCheck,
+} from "./workspace-tab-navigation";
+
+// Only iOS columns reopen a remembered page; Android always opens a tab on its list.
+const REMEMBERS = Platform.OS === "ios";
+
+// Read synchronously when a tab opens, so it lives in memory and is saved when the app leaves
+// the foreground rather than on every chat switch.
+let selections: WorkspaceSelections = {};
+let saved = selections;
+let hydration: Promise<void> | null = null;
+
+function save() {
+ const writing = selections;
+ if (saved === writing) return;
+ // Marked saved only once written, so a failed write is retried on the next background.
+ void savePreferencesPatch({ workspaceSelections: writing })
+ .then(() => {
+ saved = writing;
+ })
+ .catch(() => undefined);
+}
+
+/** Loads the saved selections once; pages visited before it resolves win over saved ones. */
+export function hydrateWorkspaceSelections() {
+ if (!REMEMBERS) return Promise.resolve();
+ hydration ??= loadPreferences()
+ .then((preferences) => {
+ selections = { ...preferences.workspaceSelections, ...selections };
+ saved = selections;
+ AppState.addEventListener("change", (status) => {
+ if (status !== "active") save();
+ });
+ })
+ .catch(() => undefined);
+ return hydration;
+}
+
+export function currentWorkspaceSelections() {
+ return selections;
+}
+
+/** The navigation container's `onStateChange`: remembers the page each tab is showing. */
+export function recordWorkspaceSelections(state: NavigationState | undefined) {
+ if (!REMEMBERS || !state) return;
+ selections = workspaceSelectionsIn(state.routes.slice(0, state.index + 1), selections);
+}
+
+function environmentRemoved(environmentId: string) {
+ const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom);
+ return (
+ catalog.isReady &&
+ !appAtomRegistry
+ .get(environmentPresentations.presentationsAtom)
+ .has(environmentId as EnvironmentId)
+ );
+}
+
+/**
+ * A remembered chat is gone once its environment was removed, or once that environment's
+ * snapshot has loaded without it. Before it loads there is nothing to contradict it.
+ */
+export const workspaceSelectionCheck: WorkspaceSelectionCheck = {
+ thread: (selection) => {
+ if (environmentRemoved(selection.environmentId)) return false;
+ const environmentId = selection.environmentId as EnvironmentId;
+ if (!appAtomRegistry.get(threadEnvironment.snapshotAtom(environmentId))) return true;
+ return appAtomRegistry
+ .get(environmentThreadShells.environmentThreadIndexAtom(environmentId))
+ .has(selection.threadId as ThreadId);
+ },
+ pullRequest: (selection) => !environmentRemoved(selection.environmentId),
+};
+
+/** Whether the window lays the workspace out in columns, by the rule the layout itself uses. */
+export function workspaceHasColumns() {
+ const metrics = currentNativeLayoutMetrics();
+ const { width, height } = metrics ?? Dimensions.get("window");
+ return deriveLayout({
+ width,
+ height,
+ nativeMetrics: metrics,
+ nativeWorkspace: nativeWorkspaceColumnsSupportedFor(metrics),
+ }).usesSplitView;
+}
+
+/** The Settings page a bare `settings` link opens beside the list when there are columns. */
+export function settingsLinkPage() {
+ return REMEMBERS && workspaceHasColumns() ? rememberedSettingsPage(selections) : undefined;
+}
+
+/**
+ * Where a cold start without a link opens. A window that starts with columns reopens the last
+ * chat beside the list instead of an empty detail column; a compact window opens on the list.
+ * It waits for the first layout metrics as long as the workspace itself does.
+ */
+export async function launchWorkspaceURL(): Promise<string | null> {
+ if (!REMEMBERS) return null;
+ await Promise.all([
+ hydrateWorkspaceSelections(),
+ firstNativeLayoutMetrics(NATIVE_METRICS_TIMEOUT_MS),
+ ]);
+ const thread = selections.threads;
+ if (!thread || !workspaceHasColumns() || !workspaceSelectionCheck.thread(thread)) return null;
+ return Linking.createURL(
+ `threads/${encodeURIComponent(thread.environmentId)}/${encodeURIComponent(thread.threadId)}`,
+ );
+}
+
+/** Whether the workspace shows its first detail page, directly above its list. */
+export function firstWorkspaceDetailOpen(navigation: RootStackNavigation) {
+ const state = rootStackState(navigation);
+ if (!state) return false;
+ const { workspace, overlays } = workspaceRoutesOf(state.routes.slice(0, state.index + 1));
+ const list = (name: string | undefined) => name === "Home" || name === "Settings";
+ return overlays.length === 0 && !list(workspace.at(-1)?.name) && list(workspace.at(-2)?.name);
+}
diff --git a/apps/mobile/src/features/workspace/workspace-tab-navigation.test.ts b/apps/mobile/src/features/workspace/workspace-tab-navigation.test.ts
new file mode 100644
index 00000000000..a7c84f5f6d5
--- /dev/null
+++ b/apps/mobile/src/features/workspace/workspace-tab-navigation.test.ts
@@ -0,0 +1,162 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { restoreSettingsLinkState } from "../settings/settings-navigation";
+import { workspaceSelectionsIn, workspaceTabNavigationState } from "./workspace-tab-navigation";
+
+const home = { key: "home", name: "Home" };
+const thread = {
+ key: "thread",
+ name: "Thread",
+ params: { environmentId: "env", threadId: "thread-a" },
+};
+const pullRequest = {
+ key: "pr",
+ name: "PullRequest",
+ params: { environmentId: "env", projectId: "project", repository: "o/r", number: 7 },
+};
+const settings = { key: "settings", name: "Settings" };
+const available = { thread: () => true, pullRequest: () => true };
+const names = (state: { routes: readonly { name: string }[] }) =>
+ state.routes.map((route) => route.name);
+
+describe("workspace tab selections", () => {
+ it("remembers the chat, pull request and Settings page each tab showed", () => {
+ const afterThread = workspaceSelectionsIn([home, thread], {});
+ const afterPullRequest = workspaceSelectionsIn([home, pullRequest], afterThread);
+ expect(afterPullRequest).toMatchObject({
+ threads: thread.params,
+ pullRequests: pullRequest.params,
+ });
+ const afterSettings = workspaceSelectionsIn(
+ [home, settings, { key: "appearance", name: "SettingsAppearance" }],
+ afterPullRequest,
+ );
+ expect(afterSettings.settings).toBe("SettingsAppearance");
+ expect(workspaceSelectionsIn([home, thread], afterSettings)).toBe(afterSettings);
+ });
+
+ it("doesn't remember pages a Settings row doesn't open", () => {
+ for (const name of ["SettingsEnvironmentNew", "SettingsProjectOverview", "SettingsAuth"]) {
+ expect(workspaceSelectionsIn([home, settings, { key: name, name }], {}).settings).toBe(
+ undefined,
+ );
+ }
+ });
+});
+
+describe("opening a workspace tab", () => {
+ const columns = { columns: true, check: available };
+
+ it("opens the remembered page beside the list with columns, and the list without", () => {
+ const state = { routes: [home, thread] };
+ const selections = { threads: thread.params, pullRequests: pullRequest.params };
+ expect(names(workspaceTabNavigationState(state, "pullRequests", selections, columns))).toEqual([
+ "Home",
+ "PullRequest",
+ ]);
+ expect(
+ names(
+ workspaceTabNavigationState(state, "pullRequests", selections, {
+ columns: false,
+ check: available,
+ }),
+ ),
+ ).toEqual(["Home"]);
+ expect(names(workspaceTabNavigationState(state, "settings", {}, columns))).toEqual([
+ "Home",
+ "Settings",
+ "SettingsEnvironments",
+ ]);
+ });
+
+ it("keeps the route that is already open, so re-selecting a tab doesn't rebuild it", () => {
+ const next = workspaceTabNavigationState(
+ { routes: [home, thread] },
+ "threads",
+ { threads: thread.params },
+ columns,
+ );
+ expect(next.routes.map((route) => route.key)).toEqual(["home", "thread"]);
+ });
+
+ it("reopens a tab's page under the key it had, so its kept screen is reused", () => {
+ const columnsAvailable = { columns: true, check: available };
+ let selections = workspaceSelectionsIn([home, thread], {});
+ const away = workspaceTabNavigationState(
+ { routes: [home, thread] },
+ "pullRequests",
+ selections,
+ {
+ columns: false,
+ check: available,
+ },
+ );
+ selections = workspaceSelectionsIn(away.routes, selections);
+ const back = workspaceTabNavigationState(away, "threads", selections, columnsAvailable);
+ expect(back.routes.at(-1)).toMatchObject({ key: "thread", params: thread.params });
+ });
+
+ it("falls back to the list for a chat that no longer exists, or an unknown Settings page", () => {
+ const missing = { thread: () => false, pullRequest: () => true };
+ expect(
+ names(
+ workspaceTabNavigationState(
+ { routes: [home] },
+ "threads",
+ { threads: thread.params },
+ {
+ columns: true,
+ check: missing,
+ },
+ ),
+ ),
+ ).toEqual(["Home"]);
+ expect(
+ names(
+ workspaceTabNavigationState(
+ { routes: [home] },
+ "settings",
+ { settings: "SettingsGone" },
+ columns,
+ ),
+ ),
+ ).toEqual(["Home", "Settings", "SettingsEnvironments"]);
+ });
+
+ it("keeps an open sheet on top", () => {
+ const sheet = { key: "sheet", name: "ConnectOnboarding" };
+ const next = workspaceTabNavigationState(
+ { routes: [home] },
+ "threads",
+ { threads: thread.params },
+ {
+ ...columns,
+ overlays: [sheet],
+ },
+ );
+ expect(names(next)).toEqual(["Home", "Thread", "ConnectOnboarding"]);
+ expect(next.index).toBe(2);
+ });
+});
+
+describe("Settings links", () => {
+ it("puts the Settings list under a linked page, and a page beside a bare link with columns", () => {
+ const linked = restoreSettingsLinkState(
+ { routes: [{ name: "Home" }, { name: "SettingsKeyboard" }] },
+ undefined,
+ );
+ expect(names(linked!)).toEqual(["Home", "Settings", "SettingsKeyboard"]);
+ const bare = { routes: [{ name: "Home" }, { name: "Settings" }] };
+ expect(names(restoreSettingsLinkState(bare, "SettingsAppearance")!)).toEqual([
+ "Home",
+ "Settings",
+ "SettingsAppearance",
+ ]);
+ expect(restoreSettingsLinkState(bare, undefined)).toBe(bare);
+ });
+
+ it("opens the sign-in link as a modal over the workspace", () => {
+ const state = { routes: [{ name: "Home" }, { name: "SettingsAuth" }] };
+ expect(restoreSettingsLinkState(state, "SettingsAppearance")).toBe(state);
+ });
+});
diff --git a/apps/mobile/src/features/workspace/workspace-tab-navigation.ts b/apps/mobile/src/features/workspace/workspace-tab-navigation.ts
new file mode 100644
index 00000000000..27c11686fe1
--- /dev/null
+++ b/apps/mobile/src/features/workspace/workspace-tab-navigation.ts
@@ -0,0 +1,202 @@
+import type { WorkspaceSelections } from "../../persistence/mobile-preferences";
+import {
+ SETTINGS_PAGE_TARGETS,
+ type SettingsPageTarget,
+} from "../settings/components/settings-page-targets";
+import { settingsNavigationState } from "../settings/settings-navigation";
+import type { WorkspaceTab } from "./workspace-tabs-state";
+
+type RouteLike = {
+ readonly name: string;
+ readonly key?: string;
+ readonly params?: object | undefined;
+};
+type ThreadSelection = NonNullable<WorkspaceSelections["threads"]>;
+type PullRequestSelection = NonNullable<WorkspaceSelections["pullRequests"]>;
+
+/** Opened when Settings has columns and none of its pages has been opened yet. */
+export const DEFAULT_SETTINGS_PAGE = "SettingsEnvironments" satisfies SettingsPageTarget;
+
+// Pages a Settings row opens, minus Project overview: it shows the project chosen in the
+// Settings scope, which resets whenever Settings closes.
+const REMEMBERED_SETTINGS_PAGES: ReadonlySet<string> = new Set(
+ SETTINGS_PAGE_TARGETS.filter((page) => page !== "SettingsProjectOverview"),
+);
+
+export function rememberedSettingsPage(selections: WorkspaceSelections): SettingsPageTarget {
+ return selections.settings && REMEMBERED_SETTINGS_PAGES.has(selections.settings)
+ ? (selections.settings as SettingsPageTarget)
+ : DEFAULT_SETTINGS_PAGE;
+}
+
+/** Whether a remembered chat or pull request can still be opened. */
+export interface WorkspaceSelectionCheck {
+ readonly thread: (selection: ThreadSelection) => boolean;
+ readonly pullRequest: (selection: PullRequestSelection) => boolean;
+}
+
+function stringParam(params: object | undefined, key: string) {
+ const value = (params as Record<string, unknown> | undefined)?.[key];
+ return typeof value === "string" ? value : undefined;
+}
+
+function pullRequestSelection(
+ params: object | undefined,
+): Omit<PullRequestSelection, "key"> | undefined {
+ const value = params as Record<string, unknown> | undefined;
+ if (
+ typeof value?.environmentId !== "string" ||
+ typeof value.projectId !== "string" ||
+ typeof value.repository !== "string" ||
+ typeof value.number !== "number"
+ ) {
+ return undefined;
+ }
+ return {
+ environmentId: value.environmentId,
+ projectId: value.projectId,
+ repository: value.repository,
+ number: value.number,
+ ...(typeof value.host === "string" ? { host: value.host } : {}),
+ };
+}
+
+function samePullRequest(
+ left: PullRequestSelection | undefined,
+ right: Omit<PullRequestSelection, "key">,
+) {
+ return (
+ left?.environmentId === right.environmentId &&
+ left.projectId === right.projectId &&
+ left.repository === right.repository &&
+ left.number === right.number &&
+ left.host === right.host
+ );
+}
+
+/**
+ * The page each tab shows in a root route chain: the newest chat, the newest pull request, and
+ * the Settings page directly above the Settings route. Returns `previous` when nothing changed.
+ */
+export function workspaceSelectionsIn(
+ routes: readonly RouteLike[],
+ previous: WorkspaceSelections,
+): WorkspaceSelections {
+ let next = previous;
+ const thread = routes.findLast((route) => route.name === "Thread");
+ const environmentId = stringParam(thread?.params, "environmentId");
+ const threadId = stringParam(thread?.params, "threadId");
+ if (
+ environmentId &&
+ threadId &&
+ (next.threads?.environmentId !== environmentId ||
+ next.threads.threadId !== threadId ||
+ next.threads.key !== thread?.key)
+ ) {
+ next = { ...next, threads: { environmentId, threadId, key: thread?.key } };
+ }
+ const pullRequestRoute = routes.findLast((route) => route.name === "PullRequest");
+ const pullRequest = pullRequestSelection(pullRequestRoute?.params);
+ if (
+ pullRequest &&
+ (!samePullRequest(next.pullRequests, pullRequest) ||
+ next.pullRequests?.key !== pullRequestRoute?.key)
+ ) {
+ next = { ...next, pullRequests: { ...pullRequest, key: pullRequestRoute?.key } };
+ }
+ const list = routes.findIndex((route) => route.name === "Settings");
+ const page = list < 0 ? undefined : routes[list + 1];
+ if (
+ page &&
+ REMEMBERED_SETTINGS_PAGES.has(page.name) &&
+ (page.name !== next.settings || page.key !== next.settingsKey)
+ ) {
+ next = { ...next, settings: page.name, settingsKey: page.key };
+ }
+ return next;
+}
+
+function identityOf({ key: _key, ...identity }: PullRequestSelection) {
+ return identity;
+}
+
+let routeKeys = 0;
+
+/** New routes get their key here, so the caller knows which route it is about to show. */
+function keyed<Route extends RouteLike>(route: Route): Route & { readonly key: string } {
+ if (route.key !== undefined) return route as Route & { readonly key: string };
+ routeKeys += 1;
+ return { ...route, key: `${route.name}-workspace-${routeKeys}` };
+}
+
+function detailRoute(
+ state: { readonly routes: readonly RouteLike[] },
+ tab: "threads" | "pullRequests",
+ selections: WorkspaceSelections,
+ check: WorkspaceSelectionCheck,
+): RouteLike | undefined {
+ if (tab === "threads") {
+ const thread = selections.threads;
+ if (!thread || !check.thread(thread)) return undefined;
+ return (
+ state.routes.find(
+ (route) =>
+ route.name === "Thread" &&
+ stringParam(route.params, "environmentId") === thread.environmentId &&
+ stringParam(route.params, "threadId") === thread.threadId,
+ ) ?? {
+ key: thread.key,
+ name: "Thread",
+ params: { environmentId: thread.environmentId, threadId: thread.threadId },
+ }
+ );
+ }
+ const pullRequest = selections.pullRequests;
+ if (!pullRequest || !check.pullRequest(pullRequest)) return undefined;
+ return (
+ state.routes.find(
+ (route) =>
+ route.name === "PullRequest" &&
+ samePullRequest(pullRequestSelection(route.params), pullRequest),
+ ) ?? { key: pullRequest.key, name: "PullRequest", params: identityOf(pullRequest) }
+ );
+}
+
+/**
+ * The root stack for opening a workspace tab. With columns the detail column must show
+ * something, so the tab reopens the page it last showed (Settings falls back to its default);
+ * without columns the tab opens on its list. Routes already on screen keep their keys, and
+ * `overlays` (open sheets) stay on top.
+ */
+export function workspaceTabNavigationState<
+ State extends { readonly routes: readonly RouteLike[] },
+>(
+ state: State,
+ tab: WorkspaceTab | "settings",
+ selections: WorkspaceSelections,
+ options: {
+ readonly columns: boolean;
+ readonly check: WorkspaceSelectionCheck;
+ readonly overlays?: readonly RouteLike[];
+ },
+) {
+ const overlays = options.overlays ?? [];
+ if (tab === "settings") {
+ const page = options.columns ? rememberedSettingsPage(selections) : undefined;
+ const settings = settingsNavigationState(
+ state,
+ page,
+ undefined,
+ page === selections.settings ? selections.settingsKey : undefined,
+ );
+ const routes = [...settings.routes.map(keyed), ...overlays];
+ return { ...settings, index: routes.length - 1, routes };
+ }
+ const home = state.routes.find((route) => route.name === "Home") ?? { name: "Home" };
+ const detail =
+ options.columns && tab !== "usage"
+ ? detailRoute(state, tab, selections, options.check)
+ : undefined;
+ const routes = [...[home, ...(detail ? [detail] : [])].map(keyed), ...overlays];
+ return { ...state, index: routes.length - 1, routes };
+}
diff --git a/apps/mobile/src/features/workspace/workspace-tabs-state.test.ts b/apps/mobile/src/features/workspace/workspace-tabs-state.test.ts
index 197d4ba27a0..f476d009857 100644
--- a/apps/mobile/src/features/workspace/workspace-tabs-state.test.ts
+++ b/apps/mobile/src/features/workspace/workspace-tabs-state.test.ts
@@ -49,16 +49,11 @@ describe("Duo list clearance", () => {
});
describe("workspace root navigation", () => {
- it("keeps Usage and Settings out of the list/detail layout", () => {
+ it("pairs Settings, chats and pull requests with a detail column, and keeps Usage one page", () => {
expect(workspaceUsesColumns("usage")).toBe(false);
- expect(workspaceUsesColumns("threads", "SettingsSheet")).toBe(false);
- expect(workspaceUsesColumns("pullRequests", "SettingsSheet")).toBe(false);
- });
-
- it("restores columns for chat and pull request lists and their details", () => {
+ expect(workspaceUsesColumns("usage", true)).toBe(true);
expect(workspaceUsesColumns("threads")).toBe(true);
- expect(workspaceUsesColumns("threads", "Thread")).toBe(true);
- expect(workspaceUsesColumns("pullRequests", "PullRequest")).toBe(true);
+ expect(workspaceUsesColumns("pullRequests")).toBe(true);
});
it("keeps the registered defaults while customization is unavailable", () => {
diff --git a/apps/mobile/src/features/workspace/workspace-tabs-state.ts b/apps/mobile/src/features/workspace/workspace-tabs-state.ts
index 52bafb42a70..6355796c84e 100644
--- a/apps/mobile/src/features/workspace/workspace-tabs-state.ts
+++ b/apps/mobile/src/features/workspace/workspace-tabs-state.ts
@@ -14,8 +14,9 @@ export function resolveWorkspaceTabOrder(saved: readonly unknown[] | undefined)
export type WorkspaceTab = NavigationTab;
export type WorkspaceSearchMode = "resting" | "active" | "expanded";
-export function workspaceUsesColumns(tab: WorkspaceTab, detailRoute?: string) {
- return (tab === "threads" || tab === "pullRequests") && detailRoute !== "SettingsSheet";
+/** Settings, Chats and pull requests pair a list with a detail column; Usage is one page. */
+export function workspaceUsesColumns(tab: WorkspaceTab, settingsOpen = false) {
+ return settingsOpen || tab === "threads" || tab === "pullRequests";
}
export interface WorkspaceTabState {
diff --git a/apps/mobile/src/lib/adaptive-navigation.test.ts b/apps/mobile/src/lib/adaptive-navigation.test.ts
index bf0c8396754..320b92a803e 100644
--- a/apps/mobile/src/lib/adaptive-navigation.test.ts
+++ b/apps/mobile/src/lib/adaptive-navigation.test.ts
@@ -39,7 +39,7 @@ describe("resolveThreadSelectionOverlayState", () => {
key: "workspace",
type: "stack",
stale: false as const,
- routeNames: ["Home", "Thread", "ThreadFiles", "SettingsSheet", "SettingsLegal"],
+ routeNames: ["Home", "Thread", "ThreadFiles", "Connections", "SettingsLegal"],
};
const home = { key: "home", name: "Home" };
const thread = {
@@ -48,7 +48,7 @@ describe("resolveThreadSelectionOverlayState", () => {
params: { environmentId: "environment", threadId: "old-thread" },
};
const files = { key: "files", name: "ThreadFiles", params: thread.params };
- const settings = { key: "settings", name: "SettingsSheet" };
+ const settings = { key: "settings", name: "Connections" };
const params = { environmentId: "environment", threadId: "new-thread" };
it("replaces the underlying file route and dismisses every overlay above it", () => {
@@ -98,11 +98,11 @@ it("replacing a draft underneath an overlay removes its draft identity", () => {
key: "root",
type: "stack",
stale: false,
- routeNames: ["Thread", "SettingsSheet"],
+ routeNames: ["Thread", "Connections"],
index: 1,
routes: [
{ key: "draft", name: "Thread", params: { draft: { draftId: "old" } } },
- { key: "settings", name: "SettingsSheet" },
+ { key: "settings", name: "Connections" },
],
},
workspaceRouteKey: "draft",
diff --git a/apps/mobile/src/lib/android-workspace-navigation.test.ts b/apps/mobile/src/lib/android-workspace-navigation.test.ts
index 88c4e945fe3..c55c3a9e98d 100644
--- a/apps/mobile/src/lib/android-workspace-navigation.test.ts
+++ b/apps/mobile/src/lib/android-workspace-navigation.test.ts
@@ -12,8 +12,8 @@ import {
resetAndroidWorkspace,
returnToAndroidWorkspaceList,
type AndroidWorkspaceDestination,
- type AndroidWorkspaceResetAction,
} from "./android-workspace-navigation";
+import type { RootStackResetAction } from "./root-stack-reset";
const require = NodeModule.createRequire(import.meta.url);
const nativePackage = require.resolve("@react-navigation/native/package.json");
@@ -38,7 +38,9 @@ const options = {
"PullRequest",
"PullRequestFile",
"PullRequestReviewers",
- "SettingsSheet",
+ "Settings",
+ "SettingsUsage",
+ "SettingsUsageAccount",
],
routeParamList: {},
routeGetIdList: {},
@@ -159,7 +161,7 @@ describe("Android workspace navigation", () => {
);
let listSelected = false;
const navigation = {
- dispatch: (action: AndroidWorkspaceResetAction) => {
+ dispatch: (action: RootStackResetAction) => {
state = apply(state, action);
},
getParent: () => undefined,
@@ -248,13 +250,10 @@ describe("Android workspace navigation", () => {
).toBe(false);
});
- it("resets the root stack when a nested Settings stack has focus", () => {
- const root = apply(router.getInitialState(options), StackActions.push("SettingsSheet"));
- const settings = router.getInitialState({
- ...options,
- routeNames: ["SettingsContent", "SettingsEnvironments"],
- });
- const actions: AndroidWorkspaceResetAction[] = [];
+ it("resets the root stack when a nested stack has focus", () => {
+ const root = apply(router.getInitialState(options), StackActions.push("Thread", thread.params));
+ const nested = router.getInitialState({ ...options, routeNames: ["Nested", "NestedChild"] });
+ const actions: RootStackResetAction[] = [];
const rootNavigation = {
dispatch: () => undefined,
getParent: () => undefined,
@@ -264,7 +263,7 @@ describe("Android workspace navigation", () => {
{
dispatch: (action) => actions.push(action),
getParent: () => rootNavigation,
- getState: () => settings,
+ getState: () => nested,
},
thread,
);
@@ -275,7 +274,7 @@ describe("Android workspace navigation", () => {
it("resets from the navigation container before any navigation action", () => {
const root = router.getInitialState(options);
- const actions: AndroidWorkspaceResetAction[] = [];
+ const actions: RootStackResetAction[] = [];
// The container only learns the root state after the first action.
resetAndroidWorkspace(
{
@@ -303,7 +302,7 @@ describe("Android Settings tab", () => {
it("opens over Home alone, dropping chat and PR history, and Back returns to Home", () => {
const previous = legacyHistory();
const settings = openTab(previous, "settings");
- expect(names(settings)).toEqual(["Home", "SettingsSheet"]);
+ expect(names(settings)).toEqual(["Home", "Settings"]);
expect(settings.routes[0]?.key).toBe(previous.routes[0]?.key);
expect(selectedTab(settings, "threads")).toBe("settings");
const back = apply(settings, StackActions.pop());
@@ -312,32 +311,21 @@ describe("Android Settings tab", () => {
expect(selectedTab(back, "settings")).not.toBe("settings");
});
- it("stays selected under a nested settings page until a list tab returns to Home", () => {
+ it("stays selected under a settings page until a list tab returns to Home", () => {
const previous = legacyHistory();
- const settings = openTab(previous, "settings");
- // Usage pushes inside the nested settings navigator, which the root router never sees.
- const usage: State = {
- ...settings,
- routes: settings.routes.map((route) =>
- route.name === "SettingsSheet"
- ? {
- ...route,
- state: {
- routes: [
- {
- name: "SettingsContent",
- state: { index: 1, routes: [{ name: "Settings" }, { name: "SettingsUsage" }] },
- },
- ],
- },
- }
- : route,
- ),
- };
+ const usage = apply(openTab(previous, "settings"), StackActions.push("SettingsUsage"));
expect(selectedTab(usage, "threads")).toBe("settings");
const list = openTab(usage, "pullRequests");
expect(names(list)).toEqual(["Home"]);
expect(list.routes[0]?.key).toBe(previous.routes[0]?.key);
expect(selectedTab(list, "pullRequests")).toBe("pullRequests");
});
+
+ it("leaves a settings page opened from the Usage tab in that tab", () => {
+ const account = apply(
+ router.getInitialState(options),
+ StackActions.push("SettingsUsageAccount"),
+ );
+ expect(selectedTab(account, "usage")).toBe("usage");
+ });
});
diff --git a/apps/mobile/src/lib/android-workspace-navigation.ts b/apps/mobile/src/lib/android-workspace-navigation.ts
index af7ff01440f..0c5408d82b6 100644
--- a/apps/mobile/src/lib/android-workspace-navigation.ts
+++ b/apps/mobile/src/lib/android-workspace-navigation.ts
@@ -1,21 +1,10 @@
-import type { CommonActions, NavigationState } from "@react-navigation/native";
+import type { NavigationState } from "@react-navigation/native";
+import { resetRootStack, type RootStackNavigation } from "./root-stack-reset";
export type AndroidWorkspaceDestination =
| { readonly name: "Thread"; readonly params: ReactNavigation.RootParamList["Thread"] }
| { readonly name: "PullRequest"; readonly params: ReactNavigation.RootParamList["PullRequest"] };
-export type AndroidWorkspaceResetAction = ReturnType<typeof CommonActions.reset> & {
- readonly target: string;
-};
-
-interface WorkspaceNavigation {
- readonly dispatch: (action: AndroidWorkspaceResetAction) => void;
- readonly getParent: () => WorkspaceNavigation | undefined;
- readonly getState: () => NavigationState | undefined;
- /** Only on the navigation container, whose `getState` stays empty until the first action. */
- readonly getRootState?: () => NavigationState | undefined;
-}
-
function androidWorkspaceBackReturnsToThread(state: NavigationState) {
const current = state.routes[state.index];
const params = current?.params as ReactNavigation.RootParamList["Thread"] | undefined;
@@ -55,27 +44,15 @@ export function androidWorkspaceNavigationState(
};
}
-/**
- * Resets the root stack to a workspace list or detail. Always reads and targets the root
- * navigator: the sidebar and rail render in the root layout, where `useNavigation()` is the
- * container, and a container dispatch runs on the deepest focused navigator. With Settings
- * or New task open, that is their nested stack, which rejects the reset.
- */
+/** Resets the root stack to a workspace list or detail. */
export function resetAndroidWorkspace(
- navigation: WorkspaceNavigation,
+ navigation: RootStackNavigation,
destination?: AndroidWorkspaceDestination,
reviewers?: ReactNavigation.RootParamList["PullRequestReviewers"],
) {
- let root = navigation;
- for (let parent = root.getParent(); parent; parent = root.getParent()) root = parent;
- const state = root.getRootState?.() ?? root.getState();
- if (!state) return;
- // Same shape as `CommonActions.reset`, which would pull React Native into node tests.
- navigation.dispatch({
- type: "RESET",
- payload: androidWorkspaceNavigationState(state, destination, reviewers),
- target: state.key,
- });
+ resetRootStack(navigation, (state) =>
+ androidWorkspaceNavigationState(state, destination, reviewers),
+ );
}
export function parentThreadIsBelow(
@@ -114,7 +91,7 @@ export function linkedThreadStep(
}
export function returnToAndroidWorkspaceList(
- navigation: WorkspaceNavigation & { readonly goBack: () => void },
+ navigation: RootStackNavigation & { readonly goBack: () => void },
selectTab: () => void,
) {
const state = navigation.getState();
diff --git a/apps/mobile/src/lib/layout.ts b/apps/mobile/src/lib/layout.ts
index 5993d7897b4..44dfb9b6ebc 100644
--- a/apps/mobile/src/lib/layout.ts
+++ b/apps/mobile/src/lib/layout.ts
@@ -175,12 +175,17 @@ export function alignListPaneToHinge(input: {
* collapse it there. Compact layouts stay pinned so a reveal request (such as
* focusing search) cannot flip the saved preference for a later split view.
*/
+/** Home's list, or the Settings list in its place, with no detail selected. */
+export function isWorkspaceListPath(pathname: string): boolean {
+ return pathname === "/" || pathname === "/settings";
+}
+
export function isPrimarySidebarPinned(input: {
readonly pathname: string;
readonly nativeWorkspace: boolean;
readonly usesSplitView: boolean;
}): boolean {
- return input.pathname === "/" && !(input.nativeWorkspace && input.usesSplitView);
+ return isWorkspaceListPath(input.pathname) && !(input.nativeWorkspace && input.usesSplitView);
}
export function deriveWorkspacePaneLayout(input: {
diff --git a/apps/mobile/src/lib/root-stack-reset.ts b/apps/mobile/src/lib/root-stack-reset.ts
new file mode 100644
index 00000000000..87bca86a538
--- /dev/null
+++ b/apps/mobile/src/lib/root-stack-reset.ts
@@ -0,0 +1,44 @@
+import type { CommonActions, NavigationState } from "@react-navigation/native";
+
+export type RootStackResetAction = ReturnType<typeof CommonActions.reset> & {
+ readonly target: string;
+};
+
+export interface RootStackNavigation {
+ readonly dispatch: (action: RootStackResetAction) => void;
+ readonly getParent: () => RootStackNavigation | undefined;
+ readonly getState: () => NavigationState | undefined;
+ /** Only on the navigation container, whose `getState` stays empty until the first action. */
+ readonly getRootState?: () => NavigationState | undefined;
+}
+
+/**
+ * The root stack's state, read from anywhere. The sidebar and rail render in the root layout,
+ * where `useNavigation()` is the container, so walk up to the root navigator.
+ */
+export function rootStackState(navigation: RootStackNavigation) {
+ let root = navigation;
+ for (let parent = root.getParent(); parent; parent = root.getParent()) root = parent;
+ return root.getRootState?.() ?? root.getState();
+}
+
+/**
+ * Replaces the root stack. Targets the root explicitly: a container dispatch runs on the deepest
+ * focused navigator, which can be a nested stack that rejects the reset.
+ */
+export function dispatchRootStackReset(
+ navigation: RootStackNavigation,
+ state: NavigationState,
+ payload: RootStackResetAction["payload"],
+) {
+ // Same shape as `CommonActions.reset`, which would pull React Native into node tests.
+ navigation.dispatch({ type: "RESET", payload, target: state.key });
+}
+
+export function resetRootStack(
+ navigation: RootStackNavigation,
+ nextState: (state: NavigationState) => RootStackResetAction["payload"],
+) {
+ const state = rootStackState(navigation);
+ if (state) dispatchRootStackReset(navigation, state, nextState(state));
+}
diff --git a/apps/mobile/src/native/NativeHeaderToolbar.test.tsx b/apps/mobile/src/native/NativeHeaderToolbar.test.tsx
index 60fe05661f4..2b3275de637 100644
--- a/apps/mobile/src/native/NativeHeaderToolbar.test.tsx
+++ b/apps/mobile/src/native/NativeHeaderToolbar.test.tsx
@@ -19,7 +19,9 @@ const harness = vi.hoisted(() => ({
// Native headers retain the actions materialized when navigation applies options. Like React
// Navigation, the header renders again only when the options are no longer shallowly equal.
-vi.mock("@react-navigation/native", () => {
+vi.mock("@react-navigation/native", async () => {
+ // vi.mock factories run before the file's imports.
+ const { createContext } = await vi.importActual<typeof import("react")>("react");
const navigation = {
setOptions(options: HeaderOptions) {
harness.setOptionsCalls += 1;
@@ -39,6 +41,8 @@ vi.mock("@react-navigation/native", () => {
},
};
return {
+ // Outside a workspace tab slot the header writes to the route's navigation.
+ NavigationRouteContext: createContext(undefined),
useNavigation: () => navigation,
useRoute: () => ({ key: "file", name: "ThreadFile", params: harness.params }),
};
diff --git a/apps/mobile/src/native/NativeHeaderToolbar.tsx b/apps/mobile/src/native/NativeHeaderToolbar.tsx
index 3f7f98a4b23..0d075384e0a 100644
--- a/apps/mobile/src/native/NativeHeaderToolbar.tsx
+++ b/apps/mobile/src/native/NativeHeaderToolbar.tsx
@@ -1,9 +1,8 @@
-import { useNavigation, useRoute, type ParamListBase } from "@react-navigation/native";
+import { useRoute } from "@react-navigation/native";
import type {
NativeStackHeaderItem,
NativeStackHeaderItemMenu,
NativeStackNavigationOptions,
- NativeStackNavigationProp,
} from "@react-navigation/native-stack";
import {
Children,
@@ -17,11 +16,7 @@ import {
import type { ColorValue } from "react-native";
import type { HeaderBarButtonSearchBarPlacementItem } from "react-native-screens";
import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";
-import { NativeStackScreenOptions } from "./StackHeader";
-
-function useNativeStackNavigation(): NativeStackNavigationProp<ParamListBase> | null {
- return useNavigation<NativeStackNavigationProp<ParamListBase>>();
-}
+import { NativeStackScreenOptions, useScreenOptionsWriter } from "./StackHeader";
function labelFromChildren(children: ReactNode): string {
const parts: string[] = [];
@@ -230,7 +225,7 @@ function NativeHeaderToolbarRoot(props: {
readonly placement?: "left" | "right" | "bottom";
readonly children?: ReactNode;
}) {
- const navigation = useNativeStackNavigation();
+ const setOptions = useScreenOptionsWriter();
const route = useRoute();
const tabActivity = use(NativeWorkspaceTabActivityContext);
const isTabActive = tabActivity?.isActive;
@@ -242,20 +237,20 @@ function NativeHeaderToolbarRoot(props: {
);
useLayoutEffect(() => {
- if (!navigation) return;
+ if (!setOptions) return;
return () => {
if (isTabActive && !isTabActive()) return;
if (props.placement === "bottom") {
- navigation.setOptions({
+ setOptions({
unstable_headerToolbarItems: () => [],
} as NativeStackOptionsWithToolbar);
} else if (props.placement === "left") {
- navigation.setOptions({ unstable_headerLeftItems: () => [] });
+ setOptions({ unstable_headerLeftItems: () => [] });
} else {
- navigation.setOptions({ unstable_headerRightItems: () => [] });
+ setOptions({ unstable_headerRightItems: () => [] });
}
};
- }, [navigation, props.placement, isTabActive]);
+ }, [setOptions, props.placement, isTabActive]);
return (
<NativeStackScreenOptions
diff --git a/apps/mobile/src/native/NativeWorkspaceColumns.ios.tsx b/apps/mobile/src/native/NativeWorkspaceColumns.ios.tsx
index 9dde6d65e61..f29d1677b72 100644
--- a/apps/mobile/src/native/NativeWorkspaceColumns.ios.tsx
+++ b/apps/mobile/src/native/NativeWorkspaceColumns.ios.tsx
@@ -1,6 +1,7 @@
import { requireOptionalNativeModule } from "expo";
import { useEffect, useState } from "react";
import { Platform } from "react-native";
+import type { NativeLayoutMetrics } from "../lib/reserved-regions";
import { useNativeLayoutMetrics } from "./native-layout-metrics";
const nativeControls = requireOptionalNativeModule<{
@@ -10,9 +11,17 @@ const nativeControls = requireOptionalNativeModule<{
export const NATIVE_WORKSPACE_COLUMNS_SUPPORTED =
Platform.OS === "ios" && Platform.isPad && nativeControls?.supportsWorkspaceColumns === true;
+/** Whether a window with these metrics lays the workspace out in UIKit columns. */
+export function nativeWorkspaceColumnsSupportedFor(metrics: NativeLayoutMetrics | null) {
+ return (
+ NATIVE_WORKSPACE_COLUMNS_SUPPORTED ||
+ (nativeControls?.supportsWorkspaceColumns === true && metrics?.hasHinge === true)
+ );
+}
+
// Binaries without the native no-hinge fallback never report metrics on ordinary
// iPhones running iOS 27.1 or later. Use the compact navigator rather than staying blank.
-const NATIVE_METRICS_TIMEOUT_MS = 1000;
+export const NATIVE_METRICS_TIMEOUT_MS = 1000;
export function useNativeWorkspaceColumnsReady() {
const metrics = useNativeLayoutMetrics();
@@ -32,9 +41,5 @@ export function useNativeWorkspaceColumnsReady() {
}
export function useNativeWorkspaceColumnsSupported() {
- const metrics = useNativeLayoutMetrics();
- return (
- NATIVE_WORKSPACE_COLUMNS_SUPPORTED ||
- (nativeControls?.supportsWorkspaceColumns === true && metrics?.hasHinge === true)
- );
+ return nativeWorkspaceColumnsSupportedFor(useNativeLayoutMetrics());
}
diff --git a/apps/mobile/src/native/NativeWorkspaceColumns.tsx b/apps/mobile/src/native/NativeWorkspaceColumns.tsx
index e0eace5dbc3..5463cde7601 100644
--- a/apps/mobile/src/native/NativeWorkspaceColumns.tsx
+++ b/apps/mobile/src/native/NativeWorkspaceColumns.tsx
@@ -1,5 +1,10 @@
import { Platform } from "react-native";
export const NATIVE_WORKSPACE_COLUMNS_SUPPORTED = Platform.OS === "ios" && Platform.isPad;
+export const NATIVE_METRICS_TIMEOUT_MS = 0;
+
+export function nativeWorkspaceColumnsSupportedFor(_metrics: unknown) {
+ return NATIVE_WORKSPACE_COLUMNS_SUPPORTED;
+}
// oxlint-disable-next-line t3code/no-hookless-use-function -- Non-iOS stub of a hook; the .ios.tsx file calls hooks.
export function useNativeWorkspaceColumnsReady() {
diff --git a/apps/mobile/src/native/StackHeader.tsx b/apps/mobile/src/native/StackHeader.tsx
index 1b4d3c381a9..a206864d4d4 100644
--- a/apps/mobile/src/native/StackHeader.tsx
+++ b/apps/mobile/src/native/StackHeader.tsx
@@ -1,10 +1,17 @@
-import { useNavigation, type ParamListBase } from "@react-navigation/native";
+import {
+ NavigationRouteContext,
+ useNavigation,
+ type ParamListBase,
+} from "@react-navigation/native";
import type {
NativeStackNavigationOptions,
NativeStackNavigationProp,
} from "@react-navigation/native-stack";
import { isValidElement, use, useEffect, useLayoutEffect, useMemo, useRef } from "react";
-import { NativeWorkspaceTabActivityContext } from "./v5-workspace-context";
+import {
+ NativeWorkspaceTabActivityContext,
+ WorkspaceSlotOptionsContext,
+} from "./v5-workspace-context";
import type { ColorValue } from "react-native";
export {
@@ -160,6 +167,23 @@ function stabilizeOptionFunctions(
return value;
}
+/**
+ * Sets the current screen's options. Inside a workspace tab slot they're kept for that slot, so
+ * slots rendering the same route never overwrite each other's header.
+ */
+export function useScreenOptionsWriter() {
+ const navigation = useNativeStackNavigation();
+ const setSlotOptions = use(WorkspaceSlotOptionsContext)?.set;
+ const routeKey = use(NavigationRouteContext)?.key;
+ return useMemo(() => {
+ if (setSlotOptions && routeKey !== undefined)
+ return (options: NativeStackNavigationOptions) => setSlotOptions(routeKey, options);
+ return navigation
+ ? (options: NativeStackNavigationOptions) => navigation.setOptions(options)
+ : null;
+ }, [navigation, routeKey, setSlotOptions]);
+}
+
export function NativeStackScreenOptions(props: {
readonly options?: AppNativeStackNavigationOptions;
/**
@@ -173,6 +197,7 @@ export function NativeStackScreenOptions(props: {
readonly name?: string;
}) {
const navigation = useNativeStackNavigation();
+ const setOptions = useScreenOptionsWriter();
const tabActive = use(NativeWorkspaceTabActivityContext)?.active ?? true;
const lastAppliedOptionsSignatureRef = useRef<string | undefined>(undefined);
const latestOptionFunctionsRef = useRef(new Map<string, (...args: unknown[]) => unknown>());
@@ -192,7 +217,7 @@ export function NativeStackScreenOptions(props: {
lastAppliedOptionsSignatureRef.current = undefined;
return;
}
- if (!navigation || !stableOptions) {
+ if (!setOptions || !stableOptions) {
return;
}
const signature = optionsSignature([stableOptions, props.optionsVersion]);
@@ -204,7 +229,7 @@ export function NativeStackScreenOptions(props: {
// stabilized factories keep their identity, so one whose output changed needs a new wrapper
// to reach the header.
optionFunctionWrappersRef.current = new Map();
- navigation.setOptions(
+ setOptions(
stabilizeOptionFunctions(
normalizedOptions,
"options",
@@ -212,7 +237,7 @@ export function NativeStackScreenOptions(props: {
optionFunctionWrappersRef.current,
) as NativeStackNavigationOptions,
);
- }, [navigation, normalizedOptions, props.optionsVersion, stableOptions, tabActive]);
+ }, [setOptions, normalizedOptions, props.optionsVersion, stableOptions, tabActive]);
useEffect(() => {
if (!navigation || !props.listeners) {
diff --git a/apps/mobile/src/native/createV5StackNavigator.ios.tsx b/apps/mobile/src/native/createV5StackNavigator.ios.tsx
index 9b25c1ed109..af43b47d1a5 100644
--- a/apps/mobile/src/native/createV5StackNavigator.ios.tsx
+++ b/apps/mobile/src/native/createV5StackNavigator.ios.tsx
@@ -20,7 +20,8 @@ import {
type NativeStackNavigatorProps,
type NativeStackTypeBag,
} from "@react-navigation/native-stack";
-import { useCallback, useRef, useState, type ComponentProps } from "react";
+import { use, useCallback, useRef, useState, type ComponentProps } from "react";
+import { WorkspaceSlotOptionsContext, slotScreenOptions } from "./v5-workspace-context";
import { StyleSheet, View } from "react-native";
import { FormSheet, Stack } from "react-native-screens";
import { NativeScrollEdgeEffectsContext } from "./NativeScrollViewMarker";
@@ -56,6 +57,8 @@ export function V5CardStackView(
props: V5StackViewProps & { readonly onRootVisibilityChange?: (visible: boolean) => void },
) {
const { preventedRoutes } = usePreventRemoveContext();
+ // Options a screen set inside this workspace tab slot, over its route's.
+ const slot = use(WorkspaceSlotOptionsContext);
const nativePopSource = useRef<string | null>(null);
const [screens, setScreens] = useState({
completedNativeDismissals: new Set<string>(),
@@ -148,6 +151,7 @@ export function V5CardStackView(
{screens.routes.map((route, index) => {
const descriptor = props.descriptors[route.key] ?? screens.descriptors[route.key];
if (!descriptor) return null;
+ const options = slotScreenOptions(slot, route.key, descriptor.options);
const attached = props.state.routes.some((current) => current.key === route.key);
return (
<Stack.Screen
@@ -157,8 +161,7 @@ export function V5CardStackView(
attached || screens.nativeCompletingPops.has(route.key) ? "attached" : "detached"
}
preventNativeDismiss={
- preventedRoutes[route.key]?.preventRemove ||
- descriptor.options.gestureEnabled === false
+ preventedRoutes[route.key]?.preventRemove || options.gestureEnabled === false
}
onDismiss={removeDismissed}
onNativeDismiss={nativeDismiss}
@@ -229,7 +232,7 @@ export function V5CardStackView(
<NavigationContext value={descriptor.navigation}>
<NavigationRouteContext value={descriptor.route}>
<V5StackHeader
- options={descriptor.options}
+ options={options}
canGoBack={
attached
? props.state.routes.findIndex((current) => current.key === route.key) > 0
@@ -237,15 +240,12 @@ export function V5CardStackView(
}
/>
<NativeColumnContent
- backgroundColor={
- StyleSheet.flatten(descriptor.options.contentStyle)?.backgroundColor
- }
+ backgroundColor={StyleSheet.flatten(options.contentStyle)?.backgroundColor}
insetHorizontally={
- (descriptor.options as AppNativeStackNavigationOptions)
- .nativeContentInsetHorizontally
+ (options as AppNativeStackNavigationOptions).nativeContentInsetHorizontally
}
>
- <NativeScrollEdgeEffectsContext value={descriptor.options.scrollEdgeEffects}>
+ <NativeScrollEdgeEffectsContext value={options.scrollEdgeEffects}>
{descriptor.render()}
</NativeScrollEdgeEffectsContext>
</NativeColumnContent>
@@ -262,9 +262,7 @@ export function V5CardStackView(
export function V5StackView(props: V5StackViewProps) {
const groups = partitionStackPresentations(props.state.routes, (route) => {
const presentation = props.descriptors[route.key]?.options.presentation;
- return (
- route.name === "SettingsSheet" || (presentation !== undefined && presentation !== "card")
- );
+ return presentation !== undefined && presentation !== "card";
});
const routes = groups.map((group) => group[0]!);
const descriptors = Object.fromEntries(
@@ -304,118 +302,7 @@ export function V5StackView(props: V5StackViewProps) {
);
}
-export function V5SheetStackView(props: V5StackViewProps) {
- const { preventedRoutes } = usePreventRemoveContext();
- const groups = partitionStackPresentations(
- props.state.routes,
- (route) => props.descriptors[route.key]?.options.presentation === "formSheet",
- );
- const [retained, setRetained] = useState({
- groups: groups.slice(1),
- descriptors: props.descriptors,
- observedRoutes: props.state.routes,
- observedDescriptors: props.descriptors,
- });
- if (
- retained.observedRoutes !== props.state.routes ||
- retained.observedDescriptors !== props.descriptors
- ) {
- const active = new Set(groups.slice(1).map((group) => group[0]!.key));
- const sheets = [
- ...groups.slice(1),
- ...retained.groups.filter((group) => !active.has(group[0]!.key)),
- ];
- const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
- setRetained({
- groups: sheets,
- descriptors: Object.fromEntries(
- Object.entries({ ...retained.descriptors, ...props.descriptors }).filter(([key]) =>
- sheetKeys.has(key),
- ),
- ),
- observedRoutes: props.state.routes,
- observedDescriptors: props.descriptors,
- });
- }
- const removeSheet = (key: string) => {
- setRetained((current) => {
- const sheets = current.groups.filter((group) => group[0]!.key !== key);
- const sheetKeys = new Set(sheets.flatMap((group) => group.map((route) => route.key)));
- return {
- ...current,
- groups: sheets,
- descriptors: Object.fromEntries(
- Object.entries(current.descriptors).filter(([routeKey]) => sheetKeys.has(routeKey)),
- ),
- };
- });
- };
- const base = groups[0] ?? [];
- return (
- <View className="flex-1 bg-screen">
- <V5CardStackView
- {...props}
- state={{ ...props.state, routes: base, index: base.length - 1, preloadedRoutes: [] }}
- />
- {retained.groups.map((group) => {
- const first = group[0]!;
- const descriptor = props.descriptors[first.key] ?? retained.descriptors[first.key];
- if (!descriptor) return null;
- const options = descriptor.options;
- const attached = nativeWorkspacePopCount(props.state, first.key) > 0;
- return (
- <FormSheet
- key={first.key}
- isOpen={attached}
- detents={options.sheetAllowedDetents}
- initialDetentIndex={options.sheetInitialDetentIndex}
- largestUndimmedDetentIndex={options.sheetLargestUndimmedDetentIndex}
- prefersGrabberVisible={options.sheetGrabberVisible}
- prefersHorizontalBars={options.sheetPrefersHorizontalBars}
- preferredCornerRadius={options.sheetCornerRadius}
- prefersScrollingExpandsWhenScrolledToEdge={options.sheetExpandsWhenScrolledToEdge}
- nativeContainerStyle={{
- backgroundColor: StyleSheet.flatten(options.contentStyle)?.backgroundColor,
- }}
- preventNativeDismiss={
- group.some((route) => preventedRoutes[route.key]?.preventRemove) ||
- options.gestureEnabled === false
- }
- onNativeDismissPrevented={() => {
- const guarded = group.findLast((route) => preventedRoutes[route.key]?.preventRemove);
- if (guarded) {
- const state = props.navigation.getState();
- const action = nativeWorkspacePopAction(state, first.key);
- if (action) props.navigation.dispatch(action);
- }
- }}
- onDismiss={() => removeSheet(first.key)}
- onNativeDismiss={() => {
- const state = props.navigation.getState();
- const action = nativeWorkspacePopAction(state, first.key);
- if (action) props.navigation.dispatch(action);
- removeSheet(first.key);
- }}
- >
- <V5CardStackView
- {...props}
- descriptors={{ ...retained.descriptors, ...props.descriptors }}
- state={{
- ...props.state,
- routes: group,
- index: group.length - 1,
- preloadedRoutes: [],
- }}
- />
- </FormSheet>
- );
- })}
- </View>
- );
-}
-
function V5Navigator({
- nativeSheets,
id,
initialRouteName,
UNSTABLE_routeNamesChangeBehavior,
@@ -426,7 +313,7 @@ function V5Navigator({
screenLayout,
UNSTABLE_router,
...rest
-}: NativeStackNavigatorProps & { readonly nativeSheets?: boolean }) {
+}: NativeStackNavigatorProps) {
const { state, describe, descriptors, navigation, NavigationContent } = useNavigationBuilder<
StackNavigationState<ParamListBase>,
StackRouterOptions,
@@ -444,7 +331,7 @@ function V5Navigator({
screenLayout,
UNSTABLE_router,
});
- const StackView = nativeSheets ? V5SheetStackView : V5StackView;
+ const StackView = V5StackView;
return (
<NavigationContent>
<StackView
@@ -462,10 +349,6 @@ function V5StackNavigator(props: NativeStackNavigatorProps) {
return <V5Navigator {...props} />;
}
-function V5SheetStackNavigator(props: NativeStackNavigatorProps) {
- return <V5Navigator {...props} nativeSheets />;
-}
-
type V5TypeBag<ParamList extends ParamListBase, NavigatorID extends string | undefined> = Omit<
NativeStackTypeBag<ParamList, NavigatorID>,
"Navigator"
@@ -478,12 +361,3 @@ export function createV5StackNavigator<
>(config?: Config): TypedNavigator<TypeBag, Config> {
return createNavigatorFactory(V5StackNavigator)(config);
}
-
-export function createV5SheetStackNavigator<
- const ParamList extends ParamListBase,
- const NavigatorID extends string | undefined = string | undefined,
- const TypeBag extends NavigatorTypeBagBase = V5TypeBag<ParamList, NavigatorID>,
- const Config extends StaticConfig<TypeBag> = StaticConfig<TypeBag>,
->(config?: Config): TypedNavigator<TypeBag, Config> {
- return createNavigatorFactory(V5SheetStackNavigator)(config);
-}
diff --git a/apps/mobile/src/native/createV5StackNavigator.tsx b/apps/mobile/src/native/createV5StackNavigator.tsx
index 2b679f91d38..44ca075614c 100644
--- a/apps/mobile/src/native/createV5StackNavigator.tsx
+++ b/apps/mobile/src/native/createV5StackNavigator.tsx
@@ -1,4 +1 @@
-export {
- createNativeStackNavigator as createV5StackNavigator,
- createNativeStackNavigator as createV5SheetStackNavigator,
-} from "@react-navigation/native-stack";
+export { createNativeStackNavigator as createV5StackNavigator } from "@react-navigation/native-stack";
diff --git a/apps/mobile/src/native/native-layout-metrics.tsx b/apps/mobile/src/native/native-layout-metrics.tsx
index a2e28dc9161..5b36280ea9d 100644
--- a/apps/mobile/src/native/native-layout-metrics.tsx
+++ b/apps/mobile/src/native/native-layout-metrics.tsx
@@ -14,13 +14,40 @@ const DeviceTypeContext = createContext<DeviceType>(
// Column reservations come from UIKit's layout, outside the resizing navigator.
export const NativeColumnLayoutMetricsContext = createContext<NativeLayoutMetrics | null>(null);
+// The latest metrics outside React, for decisions made before the first screen renders.
+let latestMetrics: NativeLayoutMetrics | null = null;
+const metricsWaiters = new Set<(metrics: NativeLayoutMetrics) => void>();
+
+/** Resolves with the first native layout metrics, or null after `timeoutMs` without any. */
+export function firstNativeLayoutMetrics(timeoutMs: number) {
+ if (latestMetrics) return Promise.resolve(latestMetrics);
+ return new Promise<NativeLayoutMetrics | null>((resolve) => {
+ const settle = (metrics: NativeLayoutMetrics | null) => {
+ metricsWaiters.delete(settle);
+ clearTimeout(timeout);
+ resolve(metrics);
+ };
+ const timeout = setTimeout(() => settle(null), timeoutMs);
+ metricsWaiters.add(settle);
+ });
+}
+
+export function currentNativeLayoutMetrics() {
+ return latestMetrics;
+}
+
export function NativeLayoutMetricsProvider(props: { readonly children: ReactNode }) {
const [metrics, setMetrics] = useState<NativeLayoutMetrics | null>(null);
+ const publish = (next: NativeLayoutMetrics) => {
+ latestMetrics = next;
+ for (const settle of [...metricsWaiters]) settle(next);
+ setMetrics(next);
+ };
const deviceType = deriveDeviceType({ isPad: IS_PAD, metrics });
return (
<NativeLayoutContext value={metrics}>
<DeviceTypeContext value={deviceType}>
- <NativeLayoutObserver onChange={setMetrics} />
+ <NativeLayoutObserver onChange={publish} />
{props.children}
</DeviceTypeContext>
</NativeLayoutContext>
diff --git a/apps/mobile/src/native/v5-workspace-context.tsx b/apps/mobile/src/native/v5-workspace-context.tsx
index 5ecbad35c36..af20431771a 100644
--- a/apps/mobile/src/native/v5-workspace-context.tsx
+++ b/apps/mobile/src/native/v5-workspace-context.tsx
@@ -1,6 +1,27 @@
import { createContext, type ReactNode } from "react";
export const NativeWorkspaceModeContext = createContext(false);
+/**
+ * Each workspace tab slot renders the same routes, so header options a screen sets are kept per
+ * slot (by route key) instead of on the shared route: a slot's header then never shows options
+ * another slot set, and switching tabs has nothing left to update.
+ */
+export interface WorkspaceSlotOptions {
+ readonly byRoute: ReadonlyMap<string, object>;
+ readonly set: (routeKey: string, options: object) => void;
+}
+export const WorkspaceSlotOptionsContext = createContext<WorkspaceSlotOptions | null>(null);
+
+/** A route's options with whatever its screens set within this slot on top. */
+export function slotScreenOptions<Options extends object>(
+ slot: WorkspaceSlotOptions | null,
+ routeKey: string | undefined,
+ options: Options,
+): Options {
+ const own = routeKey === undefined ? undefined : slot?.byRoute.get(routeKey);
+ return own ? { ...options, ...own } : options;
+}
+
/** Retained tabs must not update another tab's navigation options. */
export const NativeWorkspaceTabActivityContext = createContext<{
readonly active: boolean;
diff --git a/apps/mobile/src/native/workspace-stack-projection.test.ts b/apps/mobile/src/native/workspace-stack-projection.test.ts
index 2b562a68137..a3c44d16fb7 100644
--- a/apps/mobile/src/native/workspace-stack-projection.test.ts
+++ b/apps/mobile/src/native/workspace-stack-projection.test.ts
@@ -23,7 +23,7 @@ const { StackRouter } = requireNavigation("@react-navigation/routers") as {
const home = { key: "home", name: "Home" };
const thread = { key: "thread", name: "Thread", params: { threadId: "draft-thread" } };
const files = { key: "files", name: "ThreadFiles", params: thread.params };
-const settings = { key: "settings", name: "SettingsSheet" };
+const settings = { key: "settings", name: "Settings" };
const legal = { key: "legal", name: "SettingsLegal" };
function history(
@@ -34,7 +34,7 @@ function history(
type: "stack",
stale: false,
index: routes.length - 1,
- routeNames: ["Home", "Thread", "ThreadFiles", "SettingsSheet", "SettingsLegal"],
+ routeNames: ["Home", "Thread", "ThreadFiles", "Settings", "SettingsLegal"],
routes,
preloadedRoutes: [],
};
@@ -44,20 +44,36 @@ describe("workspace router projection", () => {
it("keeps workspace flows beside Home and restores them after a modal closes", () => {
const draft = { key: "draft", name: "Thread", params: { draft: {} } };
const modal = { key: "connect", name: "ConnectOnboarding" };
- const routes = [home, thread, draft, settings, legal];
+ const routes = [home, thread, draft, legal];
const isOverlay = (route: { name: string }) => route.name === "ConnectOnboarding";
expect(projectWorkspaceStack(history([...routes, modal]), isOverlay)).toEqual({
primary: home,
- detail: [thread, draft, settings, legal],
+ detail: [thread, draft, legal],
overlays: [modal],
});
expect(projectWorkspaceStack(history(routes), isOverlay)).toEqual({
primary: home,
- detail: [thread, draft, settings, legal],
+ detail: [thread, draft, legal],
overlays: [],
});
});
+ it("shows the Settings list as the primary content and its pages as the detail", () => {
+ const environments = { key: "environments", name: "SettingsEnvironments" };
+ expect(projectWorkspaceStack(history([home, settings, environments]), () => false)).toEqual({
+ primary: home,
+ detail: [environments],
+ overlays: [],
+ });
+ });
+
+ it("returns from a Settings page to the Settings list that Home is showing", () => {
+ const environments = { key: "environments", name: "SettingsEnvironments" };
+ expect(
+ nativeStackPopAction(history([home, settings, environments]), environments.key, home.key),
+ ).toMatchObject({ payload: { count: 1 } });
+ });
+
it("retains a cold-linked detail route without changing the router history", () => {
const state = history([thread, files]);
expect(projectWorkspaceStack(state, () => false)).toEqual({
@@ -330,7 +346,7 @@ describe("v5 stack handoff", () => {
expect(
partitionStackPresentations(
[home, thread, settings, legal, secondModal],
- (route) => route.name === "SettingsSheet",
+ (route) => route.name === "Settings",
),
).toEqual([[home, thread], [settings, legal], [secondModal]]);
});
diff --git a/apps/mobile/src/native/workspace-stack-projection.ts b/apps/mobile/src/native/workspace-stack-projection.ts
index 71ebec0ed9c..341a432b66b 100644
--- a/apps/mobile/src/native/workspace-stack-projection.ts
+++ b/apps/mobile/src/native/workspace-stack-projection.ts
@@ -13,7 +13,10 @@ export function projectWorkspaceStack(
const firstOverlay = state.routes.findIndex(isOverlay);
const workspaceRoutes = state.routes.slice(0, firstOverlay < 0 ? undefined : firstOverlay);
const primary = workspaceRoutes.find((route) => route.name === "Home");
- const detail = workspaceRoutes.filter((route) => route.name !== "Home");
+ // The Settings tab's route only selects what Home shows; its pages are the detail.
+ const detail = workspaceRoutes.filter(
+ (route) => route.name !== "Home" && route.name !== "Settings",
+ );
const overlays = firstOverlay < 0 ? [] : state.routes.slice(firstOverlay);
return { primary, detail, overlays };
}
@@ -50,10 +53,13 @@ export function nativeStackPopAction(
destinationKey?: string,
) {
const sourceIndex = state.routes.findIndex((route) => route.key === dismissedKey);
- const destinationIndex =
+ let destinationIndex =
destinationKey === undefined
? sourceIndex - 1
: state.routes.findIndex((route) => route.key === destinationKey);
+ // Home's screen draws the Settings list, so going back to it from a Settings page stops there.
+ if (destinationIndex >= 0 && state.routes[destinationIndex + 1]?.name === "Settings")
+ destinationIndex += 1;
if (
sourceIndex <= 0 ||
sourceIndex > state.index ||
diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts
index a260a489d4c..63b45aee1a1 100644
--- a/apps/mobile/src/persistence/mobile-preferences.ts
+++ b/apps/mobile/src/persistence/mobile-preferences.ts
@@ -47,7 +47,35 @@ const PullRequestListPreferences = Schema.Struct({
});
export type PullRequestListPreferences = typeof PullRequestListPreferences.Type;
+/**
+ * The page each workspace tab last showed, reopened when the tab returns with columns. `key` is
+ * that page's route key: reopening under the same key reuses the screen a tab kept mounted.
+ */
+const WorkspaceSelections = Schema.Struct({
+ threads: Schema.optional(
+ Schema.Struct({
+ environmentId: Schema.String,
+ threadId: Schema.String,
+ key: Schema.optional(Schema.String),
+ }),
+ ),
+ pullRequests: Schema.optional(
+ Schema.Struct({
+ environmentId: Schema.String,
+ projectId: Schema.String,
+ repository: Schema.String,
+ number: Schema.Number,
+ host: Schema.optional(Schema.String),
+ key: Schema.optional(Schema.String),
+ }),
+ ),
+ settings: Schema.optional(Schema.String),
+ settingsKey: Schema.optional(Schema.String),
+});
+export type WorkspaceSelections = typeof WorkspaceSelections.Type;
+
const isThreadListFilters = Schema.is(ThreadListFilters);
+const isWorkspaceSelections = Schema.is(WorkspaceSelections);
const isPullRequestListPreferences = Schema.is(PullRequestListPreferences);
export interface Preferences {
@@ -87,6 +115,7 @@ export interface Preferences {
readonly threadListWorkingShelfExpanded?: boolean;
readonly threadListFilters?: ThreadListFilters;
readonly pullRequestListFilters?: PullRequestListPreferences;
+ readonly workspaceSelections?: WorkspaceSelections;
}
export class MobilePreferencesLoadError extends Schema.TaggedError<MobilePreferencesLoadError>()(
@@ -159,6 +188,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
threadListWorkingShelfExpanded?: boolean;
threadListFilters?: ThreadListFilters;
pullRequestListFilters?: PullRequestListPreferences;
+ workspaceSelections?: WorkspaceSelections;
} = {};
if (Array.isArray(parsed.hiddenNavigationTabs)) {
@@ -298,6 +328,9 @@ function sanitizePreferences(parsed: Preferences): Preferences {
if (isPullRequestListPreferences(parsed.pullRequestListFilters)) {
preferences.pullRequestListFilters = parsed.pullRequestListFilters;
}
+ if (isWorkspaceSelections(parsed.workspaceSelections)) {
+ preferences.workspaceSelections = parsed.workspaceSelections;
+ }
return preferences;
}
diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts
index e9a8e7518ab..472c1a266c6 100644
--- a/apps/mobile/src/state/use-remote-environment-registry.ts
+++ b/apps/mobile/src/state/use-remote-environment-registry.ts
@@ -176,7 +176,7 @@ export function useRemoteConnections() {
{ text: "Cancel", style: "cancel" },
{
text: "Open T3 Account",
- onPress: () => navigation.navigate("SettingsSheet", { screen: "SettingsAuth" }),
+ onPress: () => navigation.navigate("SettingsAuth"),
},
remove,
],