TypeScript
feat(mobile): without an inspector column, the inspector is a sheet (#27090)
Julius Marmingec6114b04a044
diff --git a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsxindex bcd03f36121..39eff844236 100644--- a/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx+++ b/apps/mobile/src/features/layout/AdaptiveWorkspaceLayout.tsx@@ -81,6 +81,7 @@ import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderEimport { PaneContext } from "../../components/ui/Pane";import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";import { WorkspaceInspectorPane } from "./workspace-inspector-pane";+import { WorkspaceInspectorSheet } from "./workspace-inspector-sheet";import {WorkspaceContentWidthContext,WorkspaceSettledContentWidthContext,@@ -129,11 +130,6 @@ export function Inspector(props: {</NavigationRouteContext.Provider></NavigationContext.Provider>);- const reveal =- props.revealKey === undefined || route === undefined- ? undefined- : { routeKey: route.key, key: props.revealKey };-const focusedRef = useRef(false);const deactivateRef = useRef<(() => void) | null>(null);@@ -142,7 +138,7 @@ export function Inspector(props: {deactivateRef.current?.();return;}- deactivateRef.current = registerWorkspaceInspector(render, reveal);+ deactivateRef.current = registerWorkspaceInspector(render, route?.key, props.revealKey);});// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Navigation focus events own the inspector registration lifetime.@@ -356,7 +352,17 @@ function AdaptiveWorkspaceLayoutContent(const [workspaceInspector, setWorkspaceInspector] = useState<{readonly render: () => ReactNode;readonly active: boolean;+ readonly routeKey: string | undefined;} | null>(null);+ // Without a column the inspector is a sheet, opened only on request for the route on top, and+ // shown again when that route returns to the top.+ const [inspectorSheetRoute, setInspectorSheetRoute] = useState<string | null>(null);+ const inspectorSheetOpen =+ !fileInspector.supported &&+ !workspacePage &&+ inspectorSheetRoute !== null &&+ workspaceInspector?.active === true &&+ workspaceInspector.routeKey === inspectorSheetRoute;const inspectorActive = workspaceInspector?.active ?? false;const panes = useMemo(() =>@@ -388,17 +394,22 @@ function AdaptiveWorkspaceLayoutContent(const workspaceInspectorOwner = useRef<symbol | null>(null);const registerWorkspaceInspector = (render: () => ReactNode,- reveal?: { readonly routeKey: string; readonly key: string },+ routeKey: string | undefined,+ revealKey?: string,) => {const owner = Symbol("workspace-inspector");workspaceInspectorOwner.current = owner;- setWorkspaceInspector({ render, active: true });- if (reveal && revealedInspectors.current.get(reveal.routeKey) !== reveal.key) {+ setWorkspaceInspector({ render, active: true, routeKey });+ if (+ routeKey !== undefined &&+ revealKey !== undefined &&+ revealedInspectors.current.get(routeKey) !== revealKey+ ) {const state = rootStackState(navigation);const live = new Set(state?.routes.slice(0, state.index + 1).map((route) => route.key));revealedInspectors.current = new Map(- [...revealedInspectors.current, [reveal.routeKey, reveal.key] as const].filter(- ([routeKey]) => live.has(routeKey) || routeKey === reveal.routeKey,+ [...revealedInspectors.current, [routeKey, revealKey] as const].filter(+ ([key]) => live.has(key) || key === routeKey,),);setFileInspectorPreferredVisible(true);@@ -452,7 +463,21 @@ function AdaptiveWorkspaceLayoutContent(};const sidebarCommands = primarySidebarPinned ? [] : (["toggleSidebar"] as const);useHardwareKeyboardCommand(sidebarCommands, handleToggleSidebarCommand);- const showInspector = () => setFileInspectorPreferredVisible(true);+ // Resizing into a column closes the sheet without this, so the inspector moves into the column.+ const dismissInspectorSheet = () => {+ setFileInspectorPreferredVisible(false);+ setInspectorSheetRoute(null);+ };+ const showInspector = () => {+ setFileInspectorPreferredVisible(true);+ if (fileInspector.supported) {+ setInspectorSheetRoute(null);+ return;+ }+ const state = rootStackState(navigation);+ const top = workspaceRoutesOf(state?.routes.slice(0, state.index + 1) ?? []).workspace.at(-1);+ setInspectorSheetRoute(top?.key ?? null);+ };const handleOpenFilesCommand = () => {const activeThread = parseActiveThreadPath(pathname);if (!layout.usesSplitView || !fileInspector.supported || activeThread === null) {@@ -466,7 +491,13 @@ function AdaptiveWorkspaceLayoutContent(return true;};useHardwareKeyboardCommand("files", handleOpenFilesCommand);- const toggleAuxiliaryPane = () => setFileInspectorPreferredVisible((current) => !current);+ const toggleAuxiliaryPane = () => {+ if (fileInspector.supported) {+ setFileInspectorPreferredVisible((current) => !current);+ setInspectorSheetRoute(null);+ } else if (inspectorSheetOpen) dismissInspectorSheet();+ else showInspector();+ };/*** 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@@ -502,6 +533,7 @@ function AdaptiveWorkspaceLayoutContent(threadSelectionDeferral.run(() => {if (Platform.OS === "android") Keyboard.dismiss();setFileInspectorPreferredVisible(false);+ setInspectorSheetRoute(null);if (layout.variant === "medium") setPrimarySidebarVisible(false);workspace?.dispatch({type: "select",@@ -795,6 +827,11 @@ function AdaptiveWorkspaceLayoutContent(sidebarByOrientation,};+ const inspectorSheet = (+ <WorkspaceInspectorSheet open={inspectorSheetOpen} onClose={dismissInspectorSheet}>+ {workspaceInspector?.render()}+ </WorkspaceInspectorSheet>+ );if (nativeWorkspace) {return (<HomeListOptionsProvider@@ -803,9 +840,14 @@ function AdaptiveWorkspaceLayoutContent(><AdaptiveWorkspaceContext value={contextValue}><NativeWorkspaceInspectorContext- value={{ render: workspaceInspector?.render, visible: inspectorColumnTargetWidth > 0 }}+ value={{+ // Without a column the sheet shows it; the hidden native column must not mount it too.+ render: fileInspector.supported ? workspaceInspector?.render : undefined,+ visible: inspectorColumnTargetWidth > 0,+ }}>{props.children}+ {inspectorSheet}</NativeWorkspaceInspectorContext></AdaptiveWorkspaceContext></HomeListOptionsProvider>@@ -966,6 +1008,7 @@ function AdaptiveWorkspaceLayoutContent(onClosed={handleWorkspaceInspectorClosed}/></PaneContext>+ {inspectorSheet}{shouldRenderNavigationRail && navigationRailWidth > 0 ? (// Its trailing inset clips the old rail as soon as Android fits the workspace to a cover display.<Viewdiff --git a/apps/mobile/src/features/layout/adaptive-workspace-context.ts b/apps/mobile/src/features/layout/adaptive-workspace-context.tsindex f443a56d652..419de9f4cb5 100644--- a/apps/mobile/src/features/layout/adaptive-workspace-context.ts+++ b/apps/mobile/src/features/layout/adaptive-workspace-context.ts@@ -23,9 +23,11 @@ interface AdaptiveWorkspaceContextValue {readonly selectDetail?: (detail: WorkspaceDetail, sheet?: WorkspaceDetailSheet) => void;readonly registerWorkspaceInspector: (render: () => ReactNode,- reveal?: { readonly routeKey: string; readonly key: string },+ routeKey: string | undefined,+ revealKey?: string,) => () => void;readonly setPrimarySidebarSearchQuery: (query: string) => void;+ /** Opens the inspector: its column where the window has one, otherwise a sheet. */readonly showInspector: () => void;readonly toggleAuxiliaryPane: () => void;/**diff --git a/apps/mobile/src/features/layout/workspace-inspector-sheet.tsx b/apps/mobile/src/features/layout/workspace-inspector-sheet.tsxnew file mode 100644index 00000000000..14f21fb7153--- /dev/null+++ b/apps/mobile/src/features/layout/workspace-inspector-sheet.tsx@@ -0,0 +1,100 @@+import { createContext, useRef, useState, type ReactNode } from "react";+import { Platform, View } from "react-native";+import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";+import { FormSheet } from "react-native-screens";+import { useResolveClassNames } from "uniwind";++import { RenderErrorBoundary, RenderFailureView } from "../../components/RenderErrorBoundary";+import { PaneContext } from "../../components/ui/Pane";+import { RoutedFormSheetContext } from "../../components/ui/RoutedFormSheetContext";+import { formSheetDetents } from "../../native/sheet-surface";++/**+ * Closes the inspector sheet around the inspector, then runs `then` once it is gone: a route+ * presented over a sheet that isn't one of the stack's own would race its dismissal.+ */+export const InspectorSheetContext = createContext<((then?: () => void) => void) | null>(null);++/** The inspector where the window has no column for it. Its content draws its own bar. */+export function WorkspaceInspectorSheet(props: {+ readonly open: boolean;+ readonly onClose: () => void;+ readonly children: ReactNode;+}) {+ const containerStyle = useResolveClassNames(Platform.OS === "android" ? "bg-header" : "bg-sheet");+ const insets = useSafeAreaInsets();+ // Stays mounted until the sheet has finished closing, so it doesn't empty as it slides away.+ // Each opening gets a fresh native sheet, even one that starts while the last is closing.+ const [presented, setPresented] = useState({+ open: props.open,+ mounted: props.open,+ session: 0,+ });+ if (presented.open !== props.open) {+ setPresented({+ open: props.open,+ mounted: presented.mounted || props.open,+ session: props.open ? presented.session + 1 : presented.session,+ });+ }+ const afterClose = useRef<(() => void) | null>(null);+ const closed = () => {+ setPresented((current) => ({ ...current, mounted: false }));+ const then = afterClose.current;+ afterClose.current = null;+ then?.();+ };+ const close = (then?: () => void) => {+ afterClose.current = then ?? null;+ props.onClose();+ };+ if (!presented.mounted) return null;+ return (+ <FormSheet+ key={presented.session}+ isOpen={props.open}+ detents={formSheetDetents(0.6, 0.95)}+ prefersGrabberVisible={Platform.OS === "ios"}+ // The inspector's bar holds its actions, so the Duo needs no rail inside this sheet.+ prefersHorizontalBars+ preferredCornerRadius={Platform.OS === "android" ? 28 : undefined}+ nativeContainerStyle={containerStyle}+ onDismiss={closed}+ onNativeDismiss={() => {+ props.onClose();+ closed();+ }}+ >+ <InspectorSheetContext value={close}>+ <RoutedFormSheetContext value={false}>+ {/* The sheet starts below the status bar. */}+ <SafeAreaInsetsContext value={{ ...insets, top: 0 }}>+ <PaneContext value="inspector">+ {/* Android FormSheet does not bound flex children. */}+ <View+ collapsable={false}+ className={+ Platform.OS === "android" ? "absolute inset-0 bg-header pt-3" : "flex-1 bg-sheet"+ }+ >+ <RenderErrorBoundary+ renderFallback={(fallback) => (+ <RenderFailureView {...fallback} title="The inspector couldn't be displayed" />+ )}+ >+ {props.children}+ </RenderErrorBoundary>+ {Platform.OS === "android" ? (+ <View+ pointerEvents="none"+ className="absolute top-1 h-1 w-8 self-center rounded-full bg-header-foreground/40"+ />+ ) : null}+ </View>+ </PaneContext>+ </SafeAreaInsetsContext>+ </RoutedFormSheetContext>+ </InspectorSheetContext>+ </FormSheet>+ );+}diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex 7ef53ff9cd9..35679ee1667 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -92,6 +92,7 @@ import { projectThreadContentPresentation } from "./threadContentPresentation";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import { Inspector, useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";+import { InspectorSheetContext } from "../layout/workspace-inspector-sheet";import {ThreadInspectorContentStack,type ThreadInspectorMode,@@ -547,16 +548,6 @@ function ThreadRouteContent(const gitActionProgress = useGitActionProgress(gitActionProgressTarget);const handleOpenGitInspector = () => {- if (!fileInspector.supported) {- if (selectedThread === null) {- return;- }- navigation.navigate("GitOverview", {- environmentId: String(selectedThread.environmentId),- threadId: String(selectedThread.id),- });- return;- }navigation.setParams({ inspector: undefined });setChosenInspectorMode("git");showInspector();@@ -565,13 +556,6 @@ function ThreadRouteContent(if (selectedThread === null || selectedThreadCwd === null) {return;}- if (!fileInspector.supported) {- navigation.navigate("ThreadFiles", {- environmentId: String(selectedThread.environmentId),- threadId: String(selectedThread.id),- });- return;- }navigation.setParams({ inspector: undefined });setChosenInspectorMode(props.renderInspector === undefined ? "files" : "route");showInspector();@@ -592,33 +576,46 @@ function ThreadRouteContent(threadId: String(selectedThread.id),path: path.split("/").filter((segment) => segment.length > 0),};- if (fileInspector.supported) {- navigation.navigate("ThreadFile", params);- return;- }navigation.navigate("ThreadFile", params);};- const safeAreaInsets = useSafeAreaInsets();- const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;const renderGitInspector = () => (- <GitOverviewSheet- headerInset={inspectorHeaderInset}- presentation="inspector"- route={{ params: { environmentId: environmentId!, threadId: threadId! } }}- />+ <InspectorHeaderInset>+ {(headerInset) => (+ <GitOverviewSheet+ headerInset={headerInset}+ presentation="inspector"+ route={{ params: { environmentId: environmentId!, threadId: threadId! } }}+ />+ )}+ </InspectorHeaderInset>);const renderFilesInspector = () =>selectedThread !== null && selectedThreadCwd !== null ? (- <ThreadFileNavigatorPane- cwd={selectedThreadCwd}- environmentId={selectedThread.environmentId}- headerInset={inspectorHeaderInset}- projectName={selectedThreadProject?.title ?? "Files"}- selectedPath={null}- onSelectFile={handleSelectInspectorFile}- />+ <InspectorHeaderInset>+ {(headerInset) => (+ <InspectorSheetContext.Consumer>+ {(closeInspectorSheet) => (+ <ThreadFileNavigatorPane+ cwd={selectedThreadCwd}+ environmentId={selectedThread.environmentId}+ headerInset={headerInset}+ projectName={selectedThreadProject?.title ?? "Files"}+ selectedPath={null}+ onSelectFile={(path) =>+ closeInspectorSheet+ ? closeInspectorSheet(() => handleSelectInspectorFile(path))+ : handleSelectInspectorFile(path)+ }+ />+ )}+ </InspectorSheetContext.Consumer>+ )}+ </InspectorHeaderInset>+ ) : null;+ const renderRouteInspector = () =>+ props.renderInspector ? (+ <InspectorHeaderInset>{props.renderInspector}</InspectorHeaderInset>) : null;- const renderRouteInspector = () => props.renderInspector?.(inspectorHeaderInset);const renderPreviewInspector = () =>previewTarget && panes.auxiliaryPaneVisible ? (<ThreadInspectorPreview@@ -797,9 +794,8 @@ function ThreadRouteContent(onPress: handleToggleInspector,}: undefined,- onOpenFilesInspector:- fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,- onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,+ onOpenFilesInspector: selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,+ onOpenGitInspector: handleOpenGitInspector,onMergeBack:mergeBackTargetThreadId !== null && mergeBackRun !== null? () => void handleMergeBack()@@ -1115,6 +1111,12 @@ function ThreadRouteContent();}+/** The inspector's top inset where it renders: under an Android column's status bar, not a sheet's. */+function InspectorHeaderInset(props: { readonly children: (headerInset: number) => ReactNode }) {+ const insets = useSafeAreaInsets();+ return props.children(Platform.OS === "ios" ? 0 : insets.top);+}+export function FullscreenThreadRouteScreen(props: StaticScreenProps<{readonly environmentId: string;diff --git a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsxindex 87da9c9992a..96b3d98f0c6 100644--- a/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx+++ b/apps/mobile/src/features/threads/git/GitOverviewSheet.tsx@@ -16,7 +16,7 @@ import {type StaticScreenProps,} from "@react-navigation/native";import { SymbolView } from "../../../components/ui/AppSymbol";-import { useEffect, useState } from "react";+import { use, useEffect, useState } from "react";import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";import { ScreenStack } from "react-native-screens";@@ -30,6 +30,7 @@ import { ListRow } from "../../../components/ui/ListRow";import { ListSection } from "../../../components/ui/ListSection";import { ScreenContent } from "../../../components/ui/ScreenContent";import { useAdaptiveWorkspaceLayout } from "../../layout/AdaptiveWorkspaceLayout";+import { InspectorSheetContext } from "../../layout/workspace-inspector-sheet";import { AppText as Text } from "../../../components/ui/AppText";import {NativeStackScreenOptions,@@ -77,6 +78,9 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {const insets = useSafeAreaInsets();const presentation = props.presentation ?? "sheet";const isInspector = presentation === "inspector";+ const closeInspectorSheet = use(InspectorSheetContext);+ const presentRoute = (present: () => void) =>+ closeInspectorSheet ? closeInspectorSheet(present) : present();const environmentId = EnvironmentId.make(props.route.params.environmentId);const threadId = ThreadId.make(props.route.params.threadId);const { selectedThread, selectedThreadProject, selectedEnvironmentRuntime } =@@ -163,19 +167,23 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {!input.featureBranch &&requiresDefaultBranchConfirmation(input.action, isDefaultRef)) {- navigation.navigate("GitConfirm", {- environmentId: String(environmentId),- threadId: String(threadId),- confirmAction: confirmableAction,- branchName,- includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"),- });+ presentRoute(() =>+ navigation.navigate("GitConfirm", {+ environmentId: String(environmentId),+ threadId: String(threadId),+ confirmAction: confirmableAction,+ branchName,+ includesCommit: String(+ input.action === "commit_push" || input.action === "commit_push_pr",+ ),+ }),+ );return;}- if (!isInspector) {- navigation.goBack();- }+ // Close a sheet so the thread shows the action's progress.+ if (!isInspector) navigation.goBack();+ else closeInspectorSheet?.();await gitActions.onRunSelectedThreadGitAction(input);};@@ -187,10 +195,12 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {}if (!canWriteSourceControl) return;if (item.dialogAction === "commit") {- navigation.navigate("GitCommit", {- environmentId: String(environmentId),- threadId: String(threadId),- });+ presentRoute(() =>+ navigation.navigate("GitCommit", {+ environmentId: String(environmentId),+ threadId: String(threadId),+ }),+ );return;}if (item.dialogAction === "push") {@@ -281,11 +291,13 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {disabled={busy || !isRepo}onPress={() => {const params = { environmentId, threadId };- navigation.dispatch(- presentation === "sheet"- ? StackActions.replace("ThreadReview", params)- : CommonActions.navigate("ThreadReview", params),- );+ if (presentation === "sheet") {+ navigation.dispatch(StackActions.replace("ThreadReview", params));+ } else {+ presentRoute(() =>+ navigation.dispatch(CommonActions.navigate("ThreadReview", params)),+ );+ }}}/><ListRow@@ -298,10 +310,12 @@ function GitOverviewSheetContent(props: GitOverviewSheetProps) {}disabled={busy || !isRepo}onPress={() =>- navigation.navigate("GitBranches", {- environmentId: String(environmentId),- threadId: String(threadId),- })+ presentRoute(() =>+ navigation.navigate("GitBranches", {+ environmentId: String(environmentId),+ threadId: String(threadId),+ }),+ )}/>{linkedPrActions.canLink ? (