Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mobile): adapt navigation and reports for iphone duo (#127599)

Chris Volzer0174c34b63ba
diff --git a/products/mobile/.argent/flows/screenshot-capture.yaml b/products/mobile/.argent/flows/screenshot-capture.yaml
new file mode 100644
index 000000000000..4153cf0a86a6
--- /dev/null
+++ b/products/mobile/.argent/flows/screenshot-capture.yaml
@@ -0,0 +1,40 @@
+# Fresh production-identity demo install, portrait orientation. See docs/TESTING.md.
+steps:
+ - launch: { ios: com.posthog.code.mobile, android: com.posthog.mobile }
+ - await: { visible: { id: try-demo }, timeout: 30000 }
+ - tap: { id: try-demo }
+ - await: { visible: { id: inbox-screen } }
+ - await: { idle: true }
+ - echo: Inbox
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false }
+ - tap: { id: inbox-row-demo-report-load-time }
+ - await: { visible: { id: handoff-picker-button } }
+ - await: { idle: true }
+ - echo: Report
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false }
+ - tap: { id: handoff-picker-button }
+ - await: { visible: { id: handoff-agent-posthog } }
+ - await: { idle: true }
+ - echo: Handoff
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false }
+ - swipe: { from: { text: Choose an agent }, direction: down }
+ - await: { hidden: { id: handoff-agent-posthog } }
+ - tap: { id: action-chat }
+ - await: { visible: { id: chat-input } }
+ - await: { idle: true }
+ - echo: Chat
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false }
+ - tap: { id: chat-back }
+ - await: { visible: { id: report-back } }
+ - tap: { id: report-back }
+ - await: { visible: { id: inbox-screen } }
+ - tap: { id: inbox-nav-views }
+ - await: { visible: { id: views-screen } }
+ - await: { idle: true }
+ - echo: Views
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false }
diff --git a/products/mobile/.argent/flows/screenshot-landscape.yaml b/products/mobile/.argent/flows/screenshot-landscape.yaml
new file mode 100644
index 000000000000..5587d3250636
--- /dev/null
+++ b/products/mobile/.argent/flows/screenshot-landscape.yaml
@@ -0,0 +1,34 @@
+# iOS fragment: run after screenshot-capture, which leaves Views open. See docs/TESTING.md.
+steps:
+ - tool: rotate
+ args: { orientation: LandscapeLeft }
+ - await: { idle: true }
+ - echo: Views
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false, rotation: LandscapeLeft }
+ - tap: { id: inbox-nav-home }
+ - await: { visible: { id: inbox-screen } }
+ - await: { idle: true }
+ - echo: Inbox
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false, rotation: LandscapeLeft }
+ - tap: { id: inbox-row-demo-report-load-time }
+ - await: { visible: { id: handoff-picker-button } }
+ - await: { idle: true }
+ - echo: Report
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false, rotation: LandscapeLeft }
+ - tap: { id: handoff-picker-button }
+ - await: { visible: { id: handoff-agent-posthog } }
+ - await: { idle: true }
+ - echo: Handoff
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false, rotation: LandscapeLeft }
+ - swipe: { from: { text: Choose an agent }, direction: down }
+ - await: { hidden: { id: handoff-agent-posthog } }
+ - tap: { id: action-chat }
+ - await: { visible: { id: chat-input } }
+ - await: { idle: true }
+ - echo: Chat
+ - tool: screenshot
+ args: { scale: 1, includeImageInContext: false, rotation: LandscapeLeft }
diff --git a/products/mobile/app.config.ts b/products/mobile/app.config.ts
index 5debd5ee0076..12fd28b8e4e9 100644
--- a/products/mobile/app.config.ts
+++ b/products/mobile/app.config.ts
@@ -60,7 +60,7 @@ export default ({ config, projectRoot }: ConfigContext): ExpoConfig => {
owner: 'posthog',
scheme,
version: '1.8.0',
- orientation: 'portrait',
+ orientation: 'default',
userInterfaceStyle: 'automatic',
icon: icons.png,
ios: {
diff --git a/products/mobile/app/_layout.tsx b/products/mobile/app/_layout.tsx
index 7688c0e9fb5a..24fe667ddd39 100644
--- a/products/mobile/app/_layout.tsx
+++ b/products/mobile/app/_layout.tsx
@@ -6,7 +6,7 @@ import { type ReactElement, useEffect, useState } from 'react'
import { StyleSheet, View } from 'react-native'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { KeyboardProvider } from 'react-native-keyboard-controller'
-import { SafeAreaProvider } from 'react-native-safe-area-context'
+import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'
import { queryClient } from '@/api/queryClient'
import { installAuthProvider, useAuthStore } from '@/auth/authStore'
import { BootSplash } from '@/auth/BootSplash'
@@ -26,6 +26,7 @@ import { initAnalytics } from '@/lib/posthogClient'
import { useScreenTracking } from '@/lib/useScreenTracking'
import { useAppearanceHydrated } from '@/ui/appearanceStore'
import { RouteErrorBoundary } from '@/ui/RouteErrorBoundary'
+import { SceneFrame } from '@/ui/SceneFrame'
import { createStyles, useTheme } from '@/ui/theme'
export { RouteErrorBoundary as ErrorBoundary }
@@ -91,34 +92,38 @@ export default function RootLayout(): ReactElement {
return (
<GestureHandlerRootView style={styles.root}>
<SafeAreaProvider>
- <KeyboardProvider>
- <QueryClientProvider client={queryClient}>
- <StatusBar style={scheme === 'dark' ? 'light' : 'dark'} />
- {/* Screens mount only after the session loads, so no query runs without a token. */}
- {ready ? (
- <Stack
- screenOptions={{
- headerShown: false,
- contentStyle: { backgroundColor: colors.background },
- }}
- >
- <Stack.Screen
- name="chat"
- dangerouslySingular={(): string => 'chat'}
- options={{
- presentation: 'card',
- }}
- />
- </Stack>
- ) : null}
- {!splashHidden && (
- <View style={StyleSheet.absoluteFill} onLayout={hideNativeSplash}>
- <BootSplash />
- </View>
- )}
- <AiApprovalDialog />
- </QueryClientProvider>
- </KeyboardProvider>
+ <SafeAreaView style={styles.root} edges={['left', 'right']}>
+ <SceneFrame>
+ <KeyboardProvider>
+ <QueryClientProvider client={queryClient}>
+ <StatusBar style={scheme === 'dark' ? 'light' : 'dark'} />
+ {/* Screens mount only after the session loads, so no query runs without a token. */}
+ {ready ? (
+ <Stack
+ screenOptions={{
+ headerShown: false,
+ contentStyle: { backgroundColor: colors.background },
+ }}
+ >
+ <Stack.Screen
+ name="chat"
+ dangerouslySingular={(): string => 'chat'}
+ options={{
+ presentation: 'card',
+ }}
+ />
+ </Stack>
+ ) : null}
+ {!splashHidden && (
+ <View style={StyleSheet.absoluteFill} onLayout={hideNativeSplash}>
+ <BootSplash />
+ </View>
+ )}
+ <AiApprovalDialog />
+ </QueryClientProvider>
+ </KeyboardProvider>
+ </SceneFrame>
+ </SafeAreaView>
</SafeAreaProvider>
</GestureHandlerRootView>
)
diff --git a/products/mobile/docs/DESIGN.md b/products/mobile/docs/DESIGN.md
index d5a3e9e559c7..9584d85dde95 100644
--- a/products/mobile/docs/DESIGN.md
+++ b/products/mobile/docs/DESIGN.md
@@ -88,6 +88,7 @@ Its 16pt input has an explicit 20pt line height, centered vertically without And
(54pt) and home indicator (34pt). `topOffset(insets, designTop)` and
`bottomOffset(insets, designBottom)` swap those for the device's insets. The web build has no
insets, so `useScreenInsets` uses the prototype's values there.
+ A minimum 12pt top inset keeps floating controls away from the edge when the native status area moves to a side.
- **Page titles.** Pushed pages share a 46pt navigation row and a 20pt gap before their title block.
Their blur fade ends 10pt before the content. `screenLayout` supplies these offsets to every page.
As the title scrolls under navigation, `ScreenChrome` fades in a smaller copy centered between the controls.
@@ -98,6 +99,42 @@ Its 16pt input has an explicit 20pt line height, centered vertically without And
`lineBreakStrategyIOS="standard"`, and web from the CSS property (`prettyWrap`).
Android wraps greedily.
+## Adaptive layouts
+
+Layout follows the space in the current window, including independent left and right safe areas.
+It does not identify devices by name or assume that an iPhone always has compact width.
+The native build supports rotation; iOS builds use Xcode 27.1 for the full Duo display.
+
+- A window at least 480pt tall keeps the inbox beside the selected report when the list has 300pt and the report has at least 440pt.
+ Before selection, the detail area asks the person to choose a report. Opening the device does not mark a report read.
+- Folding or entering a narrow Split View hides the inbox pane without remounting the selected report or its sheets.
+ The expanded inbox shows the same filters and actions as the main inbox and initially reveals the selected report.
+ It retries the reveal as rows are measured, and stops if the reader starts scrolling.
+ Both inbox lists prefetch reports as rows become visible, including rows beyond the initial prefetch window.
+ The report's inbox pane only prefetches while it is visible and its screen is focused.
+- Navigation uses a side rail in sufficiently tall, wide landscape windows, or when a side safe area signals side chrome.
+ It requires at least 600pt of safe width; narrow cover displays keep the phone navigation and full reading width.
+ The rail follows the side with the larger inset. Short windows keep horizontal tab navigation and the report's Back control,
+ without adding a second navigation bar below its actions.
+ Custom controls stay inside safe content; they do not occupy native reserved regions or infer a hinge angle.
+- Reports keep their contextual Chat action; their navigation bar does not add a second compose button.
+ The report action bar stays in the page layout when the keyboard opens or the window rotates.
+ With a navigation rail beside native side chrome, its bottom gutter is 16pt; phone layouts retain their bottom safe-area spacing.
+- Chat keeps a centered reading column up to 720pt wide. Resizing keeps the session, composer, queued messages and draft mounted.
+ Short landscape windows put the input and composer controls on one row, with a smaller header.
+ Empty-state suggestions scroll above the composer; Android keeps the app visible while editing instead of opening a full-screen editor.
+- Sign-in keeps its form within 600pt, and Settings uses the same 720pt reading width as chat.
+- Consecutive chart or number pins can share a row when each has enough width. Recent and Browse remain lists.
+ The first visible pin anchors the list when its columns change; chart tooltips can close as their canvases resize.
+ The chosen pin stays anchored through deferred row measurements until the user scrolls.
+- Sheets have a bounded width on expanded windows. Their height follows their current scene, including rotation and Split View.
+ Their floating presentation uses the full safe window width, even when opened from a narrow report pane.
+ Floating sheets subtract their bottom margin from the available height so their top stays below the safe area.
+ Resolve and Dismiss resize above the keyboard; their headings scroll with the form in short windows while Confirm stays visible.
+ Assignee and Project cards cap their width at 600pt; navigation menus cap at 400pt.
+ Android Back dismisses the top sheet or card on the focused screen before navigating away from that page.
+- Full-screen charts use the space remaining below the title and above the safe bottom edge, including short landscape phones.
+
## Component inventory
| Component | File | Notes |
diff --git a/products/mobile/docs/TESTING.md b/products/mobile/docs/TESTING.md
index 64e8aa091e64..47059694b514 100644
--- a/products/mobile/docs/TESTING.md
+++ b/products/mobile/docs/TESTING.md
@@ -79,6 +79,142 @@ Keep ingestion, ClickHouse, and replay storage running, wait for the returned se
If a session is missing, inspect local capture, ingestion, and replay storage logs before recording a playback pass.
The dummy's normal development shortcut can choose the latest project; the explicit command above keeps the SDK on the account's selected project.
+## Duo and resizable windows
+
+Use Xcode 27.1 or newer with an iPhone Duo runtime. Simulator checks supplement the required
+physical iOS and Android before-and-after screenshots.
+
+1. Open a report unfolded, scroll it, open Resolve and enter a note. Fold, unfold, rotate and
+ enter Split View on either side. Verify the report, scroll position and note remain.
+2. Change filters in the expanded inbox pane and select another report. Verify its highlight,
+ data and actions. A confirmation sheet must block the inbox and navigation behind its scrim.
+3. Tap Home from a report and switch Chats and Views through horizontal navigation and the rail.
+ Check pinned Errors and Sessions slots, larger text and shorter windows too.
+4. Enter a chat draft, queue a message and open Model. Resize with a streaming reply and the
+ keyboard visible. Keep the conversation, draft and queue without a duplicate send or stream.
+5. Scroll Views to a later chart pin, expand and collapse the window, and verify the same pin
+ stays near the top. Check menus, chart and number pins, and full-screen insights.
+6. Check empty and error states, long titles, and asymmetric safe areas on both sides. No
+ control should overlap system UI, clip, or require a particular fold pose.
+
+### Repeatable screenshot comparisons
+
+Use `.argent/flows/screenshot-capture.yaml` to capture Inbox, Report, Handoff, Chat with the keyboard,
+and Views from repository demo data. It launches the production app identity on either platform:
+`com.posthog.code.mobile` on iOS and `com.posthog.mobile` on Android. It leaves Views open.
+`.argent/flows/screenshot-landscape.yaml` continues from there on iOS and captures the same surfaces after rotation.
+These flows collect review images; they do not perform pixel-diff assertions or replace the smoke flows.
+
+Keep the base captures, then repeat on the same virtual devices after each layout revision.
+Record the source commit, model, OS, pixel dimensions, orientation, posture, theme, and text size beside each set.
+Use separate artifact directories such as `before/iphone-portrait` and `after/duo-inner-landscape`.
+Do not compare portrait-locked base screens with landscape screenshots as though the orientations match.
+
+| Virtual device | Capture matrix | Reference native pixels |
+| -------------------------------------------------------- | --------------------------------------------- | ---------------------------------------------- |
+| Ordinary iPhone, initially iPhone 17 Pro / iOS 27.0 | Portrait and landscape | 1206×2622 and 2622×1206 |
+| Android, initially Pixel 9 / Android 16 API 36 at 420dpi | Portrait and landscape | 1080×2424 and 2424×1080 |
+| iPhone Duo / iOS 27.1 | Closed cover, inner portrait, inner landscape | Cover 1398×2034; inner 2007×2853 and 2853×2007 |
+
+#### Build and prepare
+
+Use bundled Release builds with analytics and OTA updates disabled, so screenshots show the selected checkout.
+For iOS, use `scripts/ci-argent-build.sh` below. For Android, generate the native project in a disposable checkout
+with `CI=1 EXPO_NO_DOTENV=1 APP_VARIANT=production pnpm exec expo prebuild --platform android --no-install`.
+Set `expo.modules.updates.ENABLED` to `false` in the generated `android/app/src/main/AndroidManifest.xml` before building.
+With JDK 17, Android SDK/build tools 36 and the generated project's NDK installed, run:
+
+```sh
+cd android
+CI=1 EXPO_NO_DOTENV=1 EXPO_NO_TELEMETRY=1 DO_NOT_TRACK=1 APP_VARIANT=production \
+EXPO_PUBLIC_POSTHOG_KEY='' EXPO_PUBLIC_POSTHOG_HOST='' \
+./gradlew assembleRelease -PreactNativeArchitectures=arm64-v8a --max-workers=2 --console=plain
+```
+
+The APK is `android/app/build/outputs/apk/release/app-release.apk`. Use the emulator's architecture if it differs.
+Reinstall the selected build on a dedicated test device before each run to reset demo state; the flow expects **Try the demo**.
+Select explicit device IDs from `xcrun simctl list devices` or `adb devices`. Never reset a person's device or account for these captures.
+Use light appearance and the default text size for matching pairs; record accessibility variants separately.
+
+#### Capture and keep the PNGs
+
+From `products/mobile`, with the pinned private Argent install on PATH:
+
+```sh
+capture_device='<explicit simulator UDID>'
+capture_dir='/tmp/mobile-screenshots/after/iphone-portrait'
+mkdir -p "$capture_dir"
+argent run rotate --udid "$capture_device" --orientation Portrait
+argent e2e run screenshot-capture --platform ios --device "$capture_device" \
+ --output "$capture_dir" --json > "$capture_dir/report.json"
+```
+
+For Android, use its serial and `--platform android`. For Duo, select the posture before the portrait run:
+`argent run fold --udid "$capture_device" --posture closed` for the cover, or `--posture open` for the inner screen.
+An open posture initially turns the UI landscape, so rotate to Portrait again before `screenshot-capture`.
+For iOS landscape, run `screenshot-landscape` immediately after a successful portrait run, with a separate output directory.
+Its explicit `rotation: LandscapeLeft` makes the exported iOS framebuffer upright.
+
+Successful tool screenshots live in temporary Argent storage, even when `--output` is supplied.
+Copy them out before stopping the server. This exports stable names from either flow's JSON report:
+
+```sh
+python3 - "$capture_dir/report.json" "$capture_dir" <<'PY'
+import json
+import shutil
+import sys
+from pathlib import Path
+
+report = json.loads(Path(sys.argv[1]).read_text())
+if not report['ok']:
+ raise SystemExit('Capture failed; inspect the report before using its screenshots.')
+output = Path(sys.argv[2])
+output.mkdir(parents=True, exist_ok=True)
+for step in report['steps']:
+ if step['kind'] == 'echo':
+ name = step['message'].lower()
+ if step.get('tool') == 'screenshot':
+ shutil.copyfile(step['result']['image']['hostPath'], output / f'{name}.png')
+PY
+```
+
+Inspect every PNG, including the fully settled keyboard. Use an invented unsent draft if keyboard suggestions expose clipboard contents.
+Preserve raw images and label matching pairs **before** and **after**. The PR composites resize each portrait capture to 600px wide,
+place the pair on a neutral canvas with padding, and label the model and surface. Compare the native PNGs when checking small details.
+For a bezel view, capture the actual Device Hub window and crop surrounding controls while retaining about 60px of padding.
+Keep that framed presentation separate from the raw app screenshots.
+Upload reviewed images using `hogli pr:upload-image --print-markdown <files...>`; acknowledge its public-upload warning with `--yes`.
+Insert the resulting pinned image URLs into the existing PR description without removing earlier evidence.
+
+#### Capture tooling workarounds
+
+- Keep Argent 0.30.1 in a private install and expose the Android SDK and `adb` on PATH before starting its server.
+ If an emulator is visible to `adb` but absent from Argent, launch that dedicated AVD with `-grpc-use-token`.
+ Keep connection tokens out of screenshots, logs attached to the PR, and source control.
+- A native-devtools launch failure can need one restart of that private server. Retry the capture, then use direct device inspection
+ if it still cannot connect. Do not restart another task's server or report a skipped capture as a pass.
+ `argent run describe --udid "$capture_device"` can still read the iOS accessibility tree when selector flows cannot run.
+ Navigate with its current element coordinates and `gesture-tap`, then capture each state with `argent run screenshot`.
+- On Android, dismiss Gboard's first-run handwriting prompt. For a dedicated emulator, disable stylus handwriting with
+ `adb -s "$capture_device" shell settings put secure stylus_handwriting_enabled 0` and enable its software keyboard with
+ `adb -s "$capture_device" shell settings put secure show_ime_with_hard_keyboard 1`.
+- Android selector taps after rotation mis-targeted controls in the reference run. Inspect the current screenshot or element tree,
+ then use `adb -s "$capture_device" shell input tap <x-pixels> <y-pixels>` and `adb ... exec-out screencap -p` if needed.
+ Recalculate coordinates for each device and posture. Do not reuse the old screen's coordinates.
+- If the dedicated emulator stops answering shell requests, restart that AVD rather than restarting the shared `adb` server.
+- Capture landscape chat with the keyboard open on both platforms. The input, model and mode controls, and Send must remain visible.
+ Gboard must keep the app composer visible rather than opening its full-screen editor.
+ Scroll the empty-state suggestions, send a demo reply, and rotate with an unsent draft to check that the draft survives.
+
+For a complete layout review, also capture sign-in, Settings and its project picker, inbox filters and row actions,
+full report details, handoff options, verdict and decision sheets, saved chats, Views browse and detail screens,
+full-screen charts, and the Errors and Sessions lists and details.
+When demo mode cannot supply a detail screen, use invented diagnostic fixtures and label those captures separately;
+record the provider substitutions and do not claim live data or replay playback coverage.
+Capture every distinct screen on the open Duo, then repeat affected screens in portrait and on the closed cover.
+Keep matching ordinary-phone screenshots for each changed screen. Record unreachable states as missing coverage.
+After returning from chat, rotate a report and check that its footer stays attached to the content with one compose action.
+
## Chat navigation and header
On iOS and Android, open an existing chat and start a new chat. Both must fill the screen without a
diff --git a/products/mobile/eas.json b/products/mobile/eas.json
index cf4a0f7d8f4c..1c1292639740 100644
--- a/products/mobile/eas.json
+++ b/products/mobile/eas.json
@@ -6,7 +6,10 @@
"build": {
"base": {
"node": "24.13.0",
- "pnpm": "10.29.3"
+ "pnpm": "10.29.3",
+ "ios": {
+ "image": "macos-tahoe-26.6-xcode-27.1"
+ }
},
"development": {
"extends": "base",
diff --git a/products/mobile/jest.setup.ts b/products/mobile/jest.setup.ts
index 8e9537433e01..10fee9c535b6 100644
--- a/products/mobile/jest.setup.ts
+++ b/products/mobile/jest.setup.ts
@@ -10,6 +10,11 @@ jest.mock('@react-native-async-storage/async-storage', () =>
jest.requireActual('@react-native-async-storage/async-storage/jest/async-storage-mock')
)
+jest.mock('expo-router', () => ({
+ ...jest.requireActual('expo-router'),
+ useIsFocused: () => true,
+}))
+
// Skia draws through a native module or CanvasKit wasm, and Jest has neither. A test that renders a screen with a
// chart gets an empty box of the same size and testID in its place.
jest.mock('@/ui/chart/MetricChartCanvas', () => {
diff --git a/products/mobile/src/auth/RegionSelect.tsx b/products/mobile/src/auth/RegionSelect.tsx
index 066cd8c496fd..90affc511f6f 100644
--- a/products/mobile/src/auth/RegionSelect.tsx
+++ b/products/mobile/src/auth/RegionSelect.tsx
@@ -1,12 +1,12 @@
import { type ReactElement, useRef, useState } from 'react'
-import { Modal, Text, useWindowDimensions, View } from 'react-native'
-
+import { Modal, Text, View } from 'react-native'
import { FloatingCard } from '@/ui/FloatingCard'
import { CheckIcon } from '@/ui/icons/CheckIcon'
import { ChevronDownIcon } from '@/ui/icons/ChevronDownIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { useScreenInsets } from '@/ui/useScreenInsets'
import { CLOUD_REGIONS, type CloudRegion } from './regions'
@@ -29,7 +29,7 @@ export function RegionSelect({ value, onChange, disabled }: RegionSelectProps):
const styles = useStyles()
const trigger = useRef<View>(null)
const [anchor, setAnchor] = useState<Anchor | null>(null)
- const { height: windowHeight } = useWindowDimensions()
+ const { height: windowHeight } = useSceneDimensions()
const insets = useScreenInsets()
const selected = CLOUD_REGIONS.find((region) => region.id === value) ?? CLOUD_REGIONS[0]
const close = (): void => setAnchor(null)
diff --git a/products/mobile/src/auth/SignInScreen.tsx b/products/mobile/src/auth/SignInScreen.tsx
index e84ca8222b5e..6ee1bced5164 100644
--- a/products/mobile/src/auth/SignInScreen.tsx
+++ b/products/mobile/src/auth/SignInScreen.tsx
@@ -279,6 +279,9 @@ const useStyles = createStyles(({ colors }) => ({
},
main: {
flexGrow: 1,
+ width: '100%',
+ maxWidth: 600,
+ alignSelf: 'center',
justifyContent: 'center',
paddingVertical: 24,
},
diff --git a/products/mobile/src/features/chat/ChatEmptyState.tsx b/products/mobile/src/features/chat/ChatEmptyState.tsx
index cbbcf92ad956..4fdaa30154c2 100644
--- a/products/mobile/src/features/chat/ChatEmptyState.tsx
+++ b/products/mobile/src/features/chat/ChatEmptyState.tsx
@@ -72,7 +72,8 @@ export function ChatEmptyState({ reportCount, suggestedPrompts, onPrompt }: Chat
const useStyles = createStyles(({ colors }) => ({
container: {
- flex: 1,
+ flexGrow: 1,
+ flexShrink: 0,
alignItems: 'center',
justifyContent: 'center',
gap: 10,
diff --git a/products/mobile/src/features/chat/ChatHeader.tsx b/products/mobile/src/features/chat/ChatHeader.tsx
index 36fed79d4767..f6941b55869d 100644
--- a/products/mobile/src/features/chat/ChatHeader.tsx
+++ b/products/mobile/src/features/chat/ChatHeader.tsx
@@ -23,6 +23,7 @@ const HEADER_FADE = 24
export const CHAT_HEADER_HEIGHT = HEADER_TOP + ROW_HEIGHT + HEADER_FADE
interface ChatHeaderProps {
+ compact?: boolean
webUrl: string | undefined
blurTarget?: RefObject<View | null>
onBack: () => void
@@ -32,6 +33,7 @@ interface ChatHeaderProps {
}
export function ChatHeader({
+ compact = false,
webUrl,
blurTarget,
onBack,
@@ -62,7 +64,14 @@ export function ChatHeader({
}
}
return (
- <View collapsable={false} style={[styles.header, { paddingTop: insets.top + HEADER_TOP }]} testID="chat-header">
+ <View
+ collapsable={false}
+ style={[
+ styles.header,
+ { paddingTop: insets.top + (compact ? 8 : HEADER_TOP), paddingBottom: compact ? 8 : HEADER_FADE },
+ ]}
+ testID="chat-header"
+ >
<BlurEdge solid={0.7} blurTarget={blurTarget} />
<FadeEdge direction="down" solid={0.7} opacity={layout.chromeTint} />
<Pressable44
@@ -74,14 +83,14 @@ export function ChatHeader({
>
<ChevronLeftIcon size={iconSizes.control} />
</Pressable44>
- <PillControl height={ROW_HEIGHT}>
+ <PillControl height={compact ? 44 : ROW_HEIGHT}>
<Pressable44
onPress={() => (newChatDisabledReason ? toasts.show(newChatDisabledReason) : onNewChat())}
accessibilityLabel="New chat"
accessibilityState={{ disabled: !!newChatDisabledReason }}
accessibilityHint={newChatDisabledReason}
pressedBackground={colors.background}
- style={styles.button}
+ style={[styles.button, compact && { height: 44 }]}
testID="chat-new"
>
<ComposeIcon size={iconSizes.control} />
@@ -92,7 +101,7 @@ export function ChatHeader({
accessibilityState={{ expanded: menuOpen, disabled: !webUrl && !onArchive }}
disabled={!webUrl && !onArchive}
pressedBackground={colors.background}
- style={styles.button}
+ style={[styles.button, compact && { height: 44 }]}
testID="chat-more"
>
<MoreIcon size={iconSizes.control} color={webUrl || onArchive ? colors.ink : colors.disabled} />
@@ -100,7 +109,7 @@ export function ChatHeader({
</PillControl>
<ChatHeaderMenu
visible={menuOpen}
- top={insets.top + HEADER_TOP + ROW_HEIGHT + 8}
+ top={insets.top + (compact ? 60 : HEADER_TOP + ROW_HEIGHT + 8)}
copying={copying}
archiving={archive.pending}
canCopy={!!webUrl}
diff --git a/products/mobile/src/features/chat/ChatHeaderMenu.tsx b/products/mobile/src/features/chat/ChatHeaderMenu.tsx
index 305072bce7dc..2d9017c5efcd 100644
--- a/products/mobile/src/features/chat/ChatHeaderMenu.tsx
+++ b/products/mobile/src/features/chat/ChatHeaderMenu.tsx
@@ -1,11 +1,11 @@
import type { ReactElement } from 'react'
-import { ActivityIndicator, useWindowDimensions } from 'react-native'
-
+import { ActivityIndicator } from 'react-native'
import { MenuDivider, MenuItem } from '@/features/views/list/ViewsMenu'
import { FloatingCard } from '@/ui/FloatingCard'
import { ArchiveIcon } from '@/ui/icons/ArchiveIcon'
import { CopyIcon } from '@/ui/icons/CopyIcon'
import { createStyles, useColors } from '@/ui/theme'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
interface ChatHeaderMenuProps {
visible: boolean
@@ -32,7 +32,7 @@ export function ChatHeaderMenu({
}: ChatHeaderMenuProps): ReactElement {
const colors = useColors()
const styles = useStyles()
- const { width } = useWindowDimensions()
+ const { width } = useSceneDimensions()
const busy = copying || archiving
return (
<FloatingCard
diff --git a/products/mobile/src/features/chat/ChatScreen.tsx b/products/mobile/src/features/chat/ChatScreen.tsx
index 8a6176e0425e..bbc337af8e03 100644
--- a/products/mobile/src/features/chat/ChatScreen.tsx
+++ b/products/mobile/src/features/chat/ChatScreen.tsx
@@ -1,10 +1,9 @@
import { BlurTargetView } from 'expo-blur'
import { usePathname } from 'expo-router'
import { type ReactElement, useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react'
-import { Keyboard, type TextInput, View } from 'react-native'
+import { Keyboard, ScrollView, type TextInput, View } from 'react-native'
import { useReanimatedKeyboardAnimation } from 'react-native-keyboard-controller'
import Animated, { useAnimatedStyle } from 'react-native-reanimated'
-
import { useAuthStore } from '@/auth/authStore'
import { sessionGeneration } from '@/auth/tokens'
import { useProjectScope } from '@/auth/useProjectScope'
@@ -17,8 +16,10 @@ import { useNow } from '@/lib/useNow'
import { taskWebUrl } from '@/model/adapters/chats'
import { reportWebUrl } from '@/model/adapters/report'
import type { InboxItem, ReportView } from '@/model/types'
+import { READING_WIDTH } from '@/ui/adaptiveLayout'
import { OverlayHost } from '@/ui/OverlayPortal'
import { createStyles } from '@/ui/theme'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { useScreenInsets } from '@/ui/useScreenInsets'
import { defaultModelSelection, isPermissionMode, modeLabel } from '../handoff/runOptions'
@@ -94,6 +95,9 @@ export function ChatScreen({
}: ChatScreenProps): ReactElement {
const styles = useStyles()
const insets = useScreenInsets()
+ const { height: sceneHeight, width: sceneWidth } = useSceneDimensions()
+ const compact = sceneHeight < 480 && sceneWidth >= 600
+ const headerHeight = compact ? 60 : CHAT_HEADER_HEIGHT
const now = useNow()
const inbox = useInboxItems()
const [target, setTarget] = useState<SessionOptions>(() => sessionTarget(initialTaskId, initialRunId))
@@ -603,17 +607,21 @@ export function ChatScreen({
<BlurTargetView ref={blurTarget} style={styles.body}>
<Animated.View style={[styles.keyboard, keyboardStyle]}>
{showEmptyState ? (
- <View style={[styles.empty, { paddingTop: insets.top + CHAT_HEADER_HEIGHT }]}>
+ <ScrollView
+ style={styles.empty}
+ contentContainerStyle={{ flexGrow: 1, paddingTop: insets.top + headerHeight }}
+ keyboardShouldPersistTaps="handled"
+ >
<ChatEmptyState
reportCount={attached.length}
suggestedPrompts={suggestedPrompts}
onPrompt={setText}
/>
- </View>
+ </ScrollView>
) : (
<SessionThread
session={session}
- topInset={insets.top + CHAT_HEADER_HEIGHT}
+ topInset={insets.top + headerHeight}
onRetryHistory={() => {
track('mobile_session_load_retried')
if (session.reconnect) session.reconnect()
@@ -667,6 +675,7 @@ export function ChatScreen({
<MentionPopover items={mentionItems} now={now} onPick={pickMention} />
) : null}
<Composer
+ compact={compact}
ref={input}
text={text}
onChangeText={changeText}
@@ -695,6 +704,7 @@ export function ChatScreen({
</Animated.View>
</BlurTargetView>
<ChatHeader
+ compact={compact}
key={session.taskId ?? 'new'}
webUrl={demo ? undefined : taskWebUrl(scope, session.taskId)}
blurTarget={blurTarget}
@@ -725,7 +735,7 @@ const useStyles = createStyles(({ colors }) => ({
flex: 1,
backgroundColor: colors.surface,
},
- body: { flex: 1 },
+ body: { flex: 1, width: '100%', maxWidth: READING_WIDTH, alignSelf: 'center' },
keyboard: { flex: 1 },
empty: { flex: 1 },
composerArea: { position: 'relative' },
diff --git a/products/mobile/src/features/chat/Composer.tsx b/products/mobile/src/features/chat/Composer.tsx
index 115fca827b54..a5038aadb624 100644
--- a/products/mobile/src/features/chat/Composer.tsx
+++ b/products/mobile/src/features/chat/Composer.tsx
@@ -1,5 +1,5 @@
import { forwardRef, type ReactElement, type ReactNode } from 'react'
-import { Text, TextInput, View } from 'react-native'
+import { ScrollView, Text, TextInput, View } from 'react-native'
import { ArrowUpIcon } from '@/ui/icons/ArrowUpIcon'
import { ChevronDownIcon } from '@/ui/icons/ChevronDownIcon'
@@ -11,6 +11,7 @@ import { iconSizes, inputReset, radii, type } from '@/ui/tokens'
import { MAX_ATTACHMENTS_PER_MESSAGE } from './attachments/attachmentRules'
interface ComposerProps {
+ compact?: boolean
text: string
onChangeText: (text: string) => void
chips?: ReactNode
@@ -81,6 +82,7 @@ function OptionChip({
export const Composer = forwardRef<TextInput, ComposerProps>(function Composer(
{
+ compact = false,
text,
onChangeText,
chips,
@@ -107,8 +109,22 @@ export const Composer = forwardRef<TextInput, ComposerProps>(function Composer(
const styles = useStyles()
const typed = text.trim().length > 0
return (
- <View style={[styles.card, shadows.popover]}>
- {chips ? <View style={styles.chips}>{chips}</View> : null}
+ <View style={[styles.card, shadows.popover, compact && styles.cardCompact]}>
+ {chips ? (
+ compact ? (
+ <ScrollView
+ horizontal
+ style={styles.chipsCompact}
+ contentContainerStyle={styles.chips}
+ keyboardShouldPersistTaps="handled"
+ showsHorizontalScrollIndicator={false}
+ >
+ {chips}
+ </ScrollView>
+ ) : (
+ <View style={styles.chips}>{chips}</View>
+ )
+ ) : null}
<TextInput
ref={ref}
value={text}
@@ -116,9 +132,10 @@ export const Composer = forwardRef<TextInput, ComposerProps>(function Composer(
placeholder="Ask anything…"
placeholderTextColor={colors.tertiary}
keyboardAppearance={scheme}
- style={styles.input}
+ style={[styles.input, compact && styles.inputCompact]}
autoFocus
multiline
+ disableFullscreenUI
returnKeyType="send"
// Keeps the keyboard up after sending, so a follow-up is one tap away.
submitBehavior="submit"
@@ -126,7 +143,7 @@ export const Composer = forwardRef<TextInput, ComposerProps>(function Composer(
accessibilityLabel="Message"
testID="chat-input"
/>
- <View style={styles.toolbar}>
+ <View style={[styles.toolbar, compact && styles.toolbarCompact]}>
<Pressable44
onPress={onAttach}
disabled={attachDisabled || attachFull}
@@ -217,6 +234,24 @@ const useStyles = createStyles(({ colors }) => ({
paddingBottom: 10,
gap: 10,
},
+ cardCompact: {
+ flexDirection: 'row',
+ flexWrap: 'nowrap',
+ alignItems: 'center',
+ paddingTop: 8,
+ paddingBottom: 8,
+ gap: 6,
+ },
+ chipsCompact: {
+ width: '22%',
+ flexGrow: 0,
+ maxHeight: 36,
+ },
+ inputCompact: {
+ flex: 1,
+ minWidth: 100,
+ maxHeight: 40,
+ },
chips: {
flexDirection: 'row',
flexWrap: 'wrap',
@@ -233,6 +268,11 @@ const useStyles = createStyles(({ colors }) => ({
color: colors.ink,
textAlignVertical: 'top',
},
+ toolbarCompact: {
+ flexShrink: 1,
+ gap: 4,
+ maxWidth: '65%',
+ },
toolbar: {
flexDirection: 'row',
alignItems: 'center',
diff --git a/products/mobile/src/features/handoff/ActionBar.tsx b/products/mobile/src/features/handoff/ActionBar.tsx
index 1cd8524fd851..ca416991740f 100644
--- a/products/mobile/src/features/handoff/ActionBar.tsx
+++ b/products/mobile/src/features/handoff/ActionBar.tsx
@@ -1,12 +1,12 @@
import type { ReactElement } from 'react'
import { Text, View } from 'react-native'
-import { KeyboardStickyView } from 'react-native-keyboard-controller'
import type { ActionBarState, ReportActions, ReportView } from '@/model/types'
import { ComposeIcon } from '@/ui/icons/ComposeIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useTheme } from '@/ui/theme'
import { iconSizes, layout, radii, type } from '@/ui/tokens'
+import { useAppLayout } from '@/ui/useAppLayout'
import { bottomOffset, useScreenInsets } from '@/ui/useScreenInsets'
import { ActionPill } from './ActionPill'
@@ -49,6 +49,9 @@ export function ActionBar({
const { colors, shadows } = useTheme()
const styles = useStyles()
const insets = useScreenInsets()
+ const { rail } = useAppLayout()
+ const bottomPadding =
+ rail && Math.max(insets.left, insets.right) > insets.bottom ? layout.minBottomPadding : bottomOffset(insets, 38)
const unstartedTaskId =
useHandoffEntry(report.id)?.unstartedTaskId ??
(report.task?.status === 'not_started' && !report.task.runId ? report.task.taskId : undefined)
@@ -112,50 +115,45 @@ export function ActionBar({
)
return (
- <KeyboardStickyView offset={{ opened: insets.bottom }}>
- <View
- style={[styles.bar, { paddingBottom: bottomOffset(insets, 38) }]}
- testID={`action-bar-${footerState}`}
- >
- {notice ? (
- <Text style={styles.notice} accessibilityRole="alert" testID="handoff-notice">
- {notice}
- </Text>
- ) : null}
- {hasPullRequests ? (
- <PullRequestCard
- pullRequests={state.pullRequests}
- onTaskChat={onTaskChat ? () => onTaskChat('pr_card') : undefined}
- reportId={report.id}
- >
- {activity || state.request || state.answer ? activityContent : null}
- </PullRequestCard>
- ) : activity || state.request || state.answer ? (
- <View style={styles.panel}>{activityContent}</View>
- ) : null}
- {showHandoff ? (
- <HandoffSplitButton
- report={report}
- onHandOff={() => void actions.handOff()}
- onOpenPicker={onOpenHandoff}
- pending={actions.pending.handOff}
- />
- ) : null}
- <View style={styles.pillRow}>
- <ActionPill onReassign={onReassign} onResolve={onResolve} onDismiss={onDismiss} />
- <Pressable44
- onPress={onChat}
- accessibilityLabel="Chat"
- pressedBackground={colors.inkHover}
- style={[styles.chat, shadows.fab]}
- haptic="selection"
- testID="action-chat"
- >
- <ComposeIcon size={iconSizes.navigation} color={colors.onInk} />
- </Pressable44>
- </View>
+ <View style={[styles.bar, { paddingBottom: bottomPadding }]} testID={`action-bar-${footerState}`}>
+ {notice ? (
+ <Text style={styles.notice} accessibilityRole="alert" testID="handoff-notice">
+ {notice}
+ </Text>
+ ) : null}
+ {hasPullRequests ? (
+ <PullRequestCard
+ pullRequests={state.pullRequests}
+ onTaskChat={onTaskChat ? () => onTaskChat('pr_card') : undefined}
+ reportId={report.id}
+ >
+ {activity || state.request || state.answer ? activityContent : null}
+ </PullRequestCard>
+ ) : activity || state.request || state.answer ? (
+ <View style={styles.panel}>{activityContent}</View>
+ ) : null}
+ {showHandoff ? (
+ <HandoffSplitButton
+ report={report}
+ onHandOff={() => void actions.handOff()}
+ onOpenPicker={onOpenHandoff}
+ pending={actions.pending.handOff}
+ />
+ ) : null}
+ <View style={styles.pillRow}>
+ <ActionPill onReassign={onReassign} onResolve={onResolve} onDismiss={onDismiss} />
+ <Pressable44
+ onPress={onChat}
+ accessibilityLabel="Chat"
+ pressedBackground={colors.inkHover}
+ style={[styles.chat, shadows.fab]}
+ haptic="selection"
+ testID="action-chat"
+ >
+ <ComposeIcon size={iconSizes.navigation} color={colors.onInk} />
+ </Pressable44>
</View>
- </KeyboardStickyView>
+ </View>
)
}
diff --git a/products/mobile/src/features/handoff/DecisionSheet.tsx b/products/mobile/src/features/handoff/DecisionSheet.tsx
index 546166be50a5..b2de4f2b8c48 100644
--- a/products/mobile/src/features/handoff/DecisionSheet.tsx
+++ b/products/mobile/src/features/handoff/DecisionSheet.tsx
@@ -1,13 +1,13 @@
import { type ReactElement, useMemo, useRef } from 'react'
-import { ScrollView, Text, useWindowDimensions } from 'react-native'
+import { ScrollView, Text } from 'react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
import { useReanimatedKeyboardAnimation } from 'react-native-keyboard-controller'
import Animated, { useAnimatedStyle } from 'react-native-reanimated'
-
import type { DecisionAnswerInput, DecisionQuestion } from '@/model/types'
import { BottomSheet } from '@/ui/BottomSheet'
import { createStyles } from '@/ui/theme'
import { type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { DecisionCard } from './DecisionCard'
import { SheetPageHeader } from './SheetPageHeader'
@@ -30,7 +30,7 @@ export function DecisionSheet({
notice,
}: DecisionSheetProps): ReactElement {
const styles = useStyles()
- const { height } = useWindowDimensions()
+ const { height } = useSceneDimensions()
const keyboard = useReanimatedKeyboardAnimation()
const scroll = useRef<ScrollView>(null)
const replyFocused = useRef(false)
diff --git a/products/mobile/src/features/handoff/HandoffSheet.tsx b/products/mobile/src/features/handoff/HandoffSheet.tsx
index a9a60d25c74d..80334493102e 100644
--- a/products/mobile/src/features/handoff/HandoffSheet.tsx
+++ b/products/mobile/src/features/handoff/HandoffSheet.tsx
@@ -1,8 +1,7 @@
import * as Clipboard from 'expo-clipboard'
import { type ReactElement, useEffect, useMemo, useRef, useState } from 'react'
-import { ActivityIndicator, ScrollView, Text, useWindowDimensions, View } from 'react-native'
+import { ActivityIndicator, ScrollView, Text, View } from 'react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
-
import { track } from '@/lib/analytics'
import { POSTHOG_AGENT } from '@/model/agent'
import type { ReportView } from '@/model/types'
@@ -15,6 +14,7 @@ import { PostHogLogomark } from '@/ui/icons/PostHogLogomark'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { useScreenInsets } from '@/ui/useScreenInsets'
import { BranchPage } from './BranchPage'
@@ -71,7 +71,7 @@ export function HandoffSheet({
const [activeAction, setActiveAction] = useState<ExternalHandoffTarget | 'copy' | null>(null)
const [error, setError] = useState<string | null>(null)
const busy = useRef(false)
- const { height } = useWindowDimensions()
+ const { height } = useSceneDimensions()
const insets = useScreenInsets()
const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
const defaults = useRunDefaults(visible)
diff --git a/products/mobile/src/features/handoff/ModelPage.tsx b/products/mobile/src/features/handoff/ModelPage.tsx
index f99acef2470f..a0c65956bc5d 100644
--- a/products/mobile/src/features/handoff/ModelPage.tsx
+++ b/products/mobile/src/features/handoff/ModelPage.tsx
@@ -1,13 +1,13 @@
import type { ReactElement } from 'react'
-import { ActivityIndicator, ScrollView, StyleSheet, Text, useWindowDimensions, View } from 'react-native'
+import { ActivityIndicator, ScrollView, StyleSheet, Text, View } from 'react-native'
import { GestureDetector, type NativeGesture } from 'react-native-gesture-handler'
-
import type { ModelChoiceApi, ReasoningEffortApi, ResolvedAiRunDefaultsApi } from '@/api/tasks'
import { Eyebrow } from '@/ui/Eyebrow'
import { CheckIcon } from '@/ui/icons/CheckIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import {
COST_BASELINE_LABEL,
@@ -76,7 +76,7 @@ export function ModelPage({
}: ModelPageProps): ReactElement {
const colors = useColors()
const styles = useStyles()
- const { height: windowHeight } = useWindowDimensions()
+ const { height: windowHeight } = useSceneDimensions()
const models = catalogue.catalogue
const pinned = model === 'default' ? undefined : model
const fallback = defaultModelSelection(defaults)
diff --git a/products/mobile/src/features/handoff/PullRequestPickerSheet.tsx b/products/mobile/src/features/handoff/PullRequestPickerSheet.tsx
index 2697fcd071df..cd29f0c94b53 100644
--- a/products/mobile/src/features/handoff/PullRequestPickerSheet.tsx
+++ b/products/mobile/src/features/handoff/PullRequestPickerSheet.tsx
@@ -1,13 +1,13 @@
import { type ReactElement, useMemo } from 'react'
-import { ScrollView, Text, useWindowDimensions, View } from 'react-native'
+import { ScrollView, Text, View } from 'react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
-
import type { PullRequestView } from '@/model/types'
import { BottomSheet } from '@/ui/BottomSheet'
import { CheckIcon } from '@/ui/icons/CheckIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { PULL_REQUEST_STATE_LABELS, pullRequestIdentity, pullRequestTitle } from './pullRequestDisplay'
import { SheetPageHeader } from './SheetPageHeader'
@@ -29,7 +29,7 @@ export function PullRequestPickerSheet({
}: PullRequestPickerSheetProps): ReactElement {
const colors = useColors()
const styles = useStyles()
- const { height } = useWindowDimensions()
+ const { height } = useSceneDimensions()
const listGesture = useMemo(() => Gesture.Native(), [])
return (
<BottomSheet
diff --git a/products/mobile/src/features/inbox/InboxFilterSheet.tsx b/products/mobile/src/features/inbox/InboxFilterSheet.tsx
index 727f435a999e..321675a1dd15 100644
--- a/products/mobile/src/features/inbox/InboxFilterSheet.tsx
+++ b/products/mobile/src/features/inbox/InboxFilterSheet.tsx
@@ -1,7 +1,6 @@
import { Fragment, type ReactElement, useMemo } from 'react'
-import { ScrollView, StyleSheet, Text, useWindowDimensions, View } from 'react-native'
+import { ScrollView, StyleSheet, Text, View } from 'react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
-
import { FEATURE_FLAGS, useFeatureFlag } from '@/lib/featureFlags'
import type { InboxItem } from '@/model/types'
import { BottomSheet } from '@/ui/BottomSheet'
@@ -12,6 +11,7 @@ import { Pressable44 } from '@/ui/Pressable44'
import { SegmentedPill } from '@/ui/SegmentedPill'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, radii, space, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import {
CREATED_WINDOW_OPTIONS,
@@ -51,7 +51,7 @@ export function InboxFilterSheet({
}: InboxFilterSheetProps): ReactElement {
const styles = useStyles()
const colors = useColors()
- const { height } = useWindowDimensions()
+ const { height } = useSceneDimensions()
const listGesture = useMemo(() => Gesture.Native(), [])
const modelScoreSort = useFeatureFlag(FEATURE_FLAGS.modelScoreSort)
const sortOptions = modelScoreSort ? [...SORT_OPTIONS, MODEL_SCORE_SORT_OPTION] : SORT_OPTIONS
diff --git a/products/mobile/src/features/inbox/InboxRow.tsx b/products/mobile/src/features/inbox/InboxRow.tsx
index aa70cbe2e449..f1201c505551 100644
--- a/products/mobile/src/features/inbox/InboxRow.tsx
+++ b/products/mobile/src/features/inbox/InboxRow.tsx
@@ -56,6 +56,7 @@ function prLabel(prNumber: number | undefined, state: PullRequestView['state'] |
interface InboxRowProps {
item: InboxItem
+ titleLines?: number
now: Date
onOpen: (reportId: string) => void
onLongPress: (item: InboxItem, anchor: RowAnchor) => void
@@ -64,6 +65,7 @@ interface InboxRowProps {
export const InboxRow = memo(function InboxRow({
item,
+ titleLines = 1,
now,
onOpen,
onLongPress,
@@ -121,7 +123,7 @@ export const InboxRow = memo(function InboxRow({
muted && styles.mutedTitle,
done && styles.doneTitle,
]}
- numberOfLines={1}
+ numberOfLines={titleLines}
>
{item.title}
</Text>
diff --git a/products/mobile/src/features/inbox/InboxRowActions.test.tsx b/products/mobile/src/features/inbox/InboxRowActions.test.tsx
index 73a5d882a89a..c8a6e348adb8 100644
--- a/products/mobile/src/features/inbox/InboxRowActions.test.tsx
+++ b/products/mobile/src/features/inbox/InboxRowActions.test.tsx
@@ -22,7 +22,7 @@ jest.mock(
() => jest.requireActual('react-native-safe-area-context/jest/mock').default
)
jest.mock('react-native-keyboard-controller', () => jest.requireActual('react-native-keyboard-controller/jest'))
-jest.mock('expo-router', () => ({ useRouter: () => ({ push: jest.fn() }) }))
+jest.mock('expo-router', () => ({ useRouter: () => ({ push: jest.fn() }), useIsFocused: () => true }))
jest.mock('@/lib/analytics', () => ({ track: jest.fn() }))
jest.mock('../report/hooks', () => ({ useReport: jest.fn(), useReportActions: jest.fn() }))
jest.mock('../reviewers/hooks', () => ({ useReportReviewers: () => undefined, useGithubOnlyReviewerCount: () => 0 }))
diff --git a/products/mobile/src/features/inbox/InboxScreen.tsx b/products/mobile/src/features/inbox/InboxScreen.tsx
index a5ed5aaf09eb..702b265a287b 100644
--- a/products/mobile/src/features/inbox/InboxScreen.tsx
+++ b/products/mobile/src/features/inbox/InboxScreen.tsx
@@ -1,30 +1,31 @@
import { useFocusEffect, useRouter } from 'expo-router'
import { type ReactElement, useCallback, useEffect, useRef, useState } from 'react'
import { FlatList, RefreshControl, View } from 'react-native'
-
import { useBootGate } from '@/auth/bootGate'
import { track } from '@/lib/analytics'
import { useNow } from '@/lib/useNow'
import type { InboxItem } from '@/model/types'
+import { INBOX_PANE_WIDTH } from '@/ui/adaptiveLayout'
import { FilterIcon } from '@/ui/icons/FilterIcon'
import { InboxIcon } from '@/ui/icons/InboxIcon'
import { WarningIcon } from '@/ui/icons/WarningIcon'
import { LoadingView, StateView } from '@/ui/StateView'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, layout } from '@/ui/tokens'
+import { useAppLayout } from '@/ui/useAppLayout'
import { bottomOffset, topOffset, useScreenInsets } from '@/ui/useScreenInsets'
-
import { apiErrorKind } from '../report/reportAnalytics'
import { TABS_HEADER_BOTTOM } from '../tabs/TabsHeader'
import { useTabHeader } from '../tabs/tabHeaderStore'
import type { RowAnchor } from './contextMenuPlacement'
-import { type CreatedWindow, type InboxSort, isDefaultInboxFilters, type SourceFilterKey } from './filters'
+import { isDefaultInboxFilters } from './filters'
import { useInboxItems, useSetReportRead } from './hooks'
import { InboxFilterSheet } from './InboxFilterSheet'
import { InboxListFooter } from './InboxListFooter'
import { InboxRow } from './InboxRow'
import { InboxRowActions, type RowMenuTarget } from './InboxRowActions'
-import { useInboxFilters, useInboxFiltersStore } from './inboxFiltersStore'
+import { inboxFilterActions } from './inboxFilterActions'
+import { useInboxFilters } from './inboxFiltersStore'
import { usePrefetchReports } from './usePrefetchReports'
function keyFor(item: InboxItem): string {
@@ -33,6 +34,7 @@ function keyFor(item: InboxItem): string {
export function InboxScreen(): ReactElement {
const styles = useStyles()
+ const { paired } = useAppLayout()
const colors = useColors()
const router = useRouter()
const insets = useScreenInsets()
@@ -88,33 +90,7 @@ export function InboxScreen(): ReactElement {
track('mobile_inbox_filters_opened')
setFiltersOpen(true)
}
- const setSort = (sort: InboxSort): void => {
- if (sort === filters.sort) {
- return
- }
- track('mobile_inbox_sort_changed', { sort })
- useInboxFiltersStore.getState().setSort(sort)
- }
- const setCreatedWindow = (window: CreatedWindow): void => {
- if (window === filters.createdWindow) {
- return
- }
- track('mobile_inbox_created_window_changed', { window })
- useInboxFiltersStore.getState().setCreatedWindow(window)
- }
- const toggleSource = (source: SourceFilterKey): void => {
- const selected = !filters.sources.includes(source)
- track('mobile_inbox_source_filter_changed', {
- source,
- selected,
- count: filters.sources.length + (selected ? 1 : -1),
- })
- useInboxFiltersStore.getState().toggleSource(source)
- }
- const clearFilters = (): void => {
- track('mobile_inbox_filters_cleared')
- useInboxFiltersStore.getState().clear()
- }
+ const { setSort, setCreatedWindow, toggleSource, clearFilters } = inboxFilterActions(filters)
const listFailed = query.isError
const loaded = !query.isLoading && !query.isError
@@ -158,9 +134,16 @@ export function InboxScreen(): ReactElement {
const renderItem = useCallback(
({ item }: { item: InboxItem }) => (
- <InboxRow item={item} now={now} onOpen={openReport} onLongPress={openRowMenu} onSetRead={setRead} />
+ <InboxRow
+ titleLines={paired ? 3 : 1}
+ item={item}
+ now={now}
+ onOpen={openReport}
+ onLongPress={openRowMenu}
+ onSetRead={setRead}
+ />
),
- [now, openReport, openRowMenu, setRead]
+ [paired, now, openReport, openRowMenu, setRead]
)
const empty = query.isLoading ? (
@@ -192,39 +175,57 @@ export function InboxScreen(): ReactElement {
)
return (
- <View style={styles.screen} testID="inbox-screen">
- <FlatList
- ref={listRef}
- data={query.data ?? []}
- keyExtractor={keyFor}
- renderItem={renderItem}
- ListEmptyComponent={empty}
- ListFooterComponent={
- <InboxListFooter
- isLoadingMore={query.isLoadingMore}
- loadMoreFailed={query.loadMoreFailed}
- onRetry={query.retryLoadMore}
- />
- }
- onEndReached={query.loadMore}
- onEndReachedThreshold={0.5}
- onViewableItemsChanged={prefetch.onViewableItemsChanged}
- viewabilityConfig={prefetch.viewabilityConfig}
- contentContainerStyle={[
- styles.content,
- { paddingTop: contentTop, paddingBottom: bottomOffset(insets, 120) },
- ]}
- refreshControl={
- <RefreshControl
- refreshing={query.isRefetching}
- onRefresh={() => refresh('pull')}
- tintColor={colors.tertiary}
- colors={[colors.tertiary]}
- progressBackgroundColor={colors.surface}
- progressViewOffset={contentTop}
+ <View style={[styles.screen, { flexDirection: 'row' }]} testID="inbox-screen">
+ <View
+ style={{
+ flexGrow: paired ? 0 : 1,
+ flexShrink: paired ? 0 : 1,
+ width: paired ? INBOX_PANE_WIDTH : undefined,
+ minWidth: 0,
+ }}
+ >
+ <FlatList
+ ref={listRef}
+ data={query.data ?? []}
+ keyExtractor={keyFor}
+ renderItem={renderItem}
+ ListEmptyComponent={empty}
+ ListFooterComponent={
+ <InboxListFooter
+ isLoadingMore={query.isLoadingMore}
+ loadMoreFailed={query.loadMoreFailed}
+ onRetry={query.retryLoadMore}
+ />
+ }
+ onEndReached={query.loadMore}
+ onEndReachedThreshold={0.5}
+ onViewableItemsChanged={prefetch.onViewableItemsChanged}
+ viewabilityConfig={prefetch.viewabilityConfig}
+ contentContainerStyle={[
+ styles.content,
+ { paddingTop: contentTop, paddingBottom: bottomOffset(insets, 120) },
+ ]}
+ refreshControl={
+ <RefreshControl
+ refreshing={query.isRefetching}
+ onRefresh={() => refresh('pull')}
+ tintColor={colors.tertiary}
+ colors={[colors.tertiary]}
+ progressBackgroundColor={colors.surface}
+ progressViewOffset={contentTop}
+ />
+ }
+ />
+ </View>
+ {paired ? (
+ <View style={{ flex: 1, borderLeftWidth: 1, borderLeftColor: colors.border }}>
+ <StateView
+ title="Choose a report"
+ message="Open a report from your inbox to investigate it here."
+ testID="inbox-detail-placeholder"
/>
- }
- />
+ </View>
+ ) : null}
<InboxRowActions target={rowMenu} onClose={() => setRowMenu(null)} />
<InboxFilterSheet
visible={filtersOpen}
diff --git a/products/mobile/src/features/inbox/ReportContextMenu.tsx b/products/mobile/src/features/inbox/ReportContextMenu.tsx
index 9393ef95d932..e6ef20c2c2ea 100644
--- a/products/mobile/src/features/inbox/ReportContextMenu.tsx
+++ b/products/mobile/src/features/inbox/ReportContextMenu.tsx
@@ -1,7 +1,6 @@
import { type ComponentType, type ReactElement, type ReactNode, useState } from 'react'
-import { ActivityIndicator, type LayoutChangeEvent, Text, useWindowDimensions, View } from 'react-native'
+import { ActivityIndicator, type LayoutChangeEvent, Text, View } from 'react-native'
import { useSafeAreaFrame } from 'react-native-safe-area-context'
-
import type { InboxItem } from '@/model/types'
import { FloatingCard } from '@/ui/FloatingCard'
import { ChatBubbleIcon } from '@/ui/icons/ChatBubbleIcon'
@@ -17,6 +16,7 @@ import type { IconProps } from '@/ui/icons/types'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, layout, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { bottomOffset, topOffset, useScreenInsets } from '@/ui/useScreenInsets'
import { TABS_HEADER_BOTTOM } from '../tabs/TabsHeader'
@@ -120,7 +120,7 @@ export function ReportContextMenu({
const styles = useStyles()
const colors = useColors()
const insets = useScreenInsets()
- const { width: windowWidth } = useWindowDimensions()
+ const { width: windowWidth } = useSceneDimensions()
// The overlay covers the full screen, which on Android edge-to-edge includes the navigation bar that the window height leaves out.
const { height: screenHeight } = useSafeAreaFrame()
const [height, setHeight] = useState<number | null>(null)
diff --git a/products/mobile/src/features/inbox/ReportInbox.test.tsx b/products/mobile/src/features/inbox/ReportInbox.test.tsx
new file mode 100644
index 000000000000..3d72a41b7e31
--- /dev/null
+++ b/products/mobile/src/features/inbox/ReportInbox.test.tsx
@@ -0,0 +1,164 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native'
+import { FlatList } from 'react-native'
+
+import { setAuthProvider } from '@/api/client'
+import { inboxFromReports } from '@/model/adapters/inbox'
+import { reportFixture } from '@/model/adapters/testFixtures'
+import type { InboxItem } from '@/model/types'
+
+import { reportDetailQuery, reportSignalsQuery } from '../report/queries'
+import { INITIAL_PREFETCH_COUNT } from './prefetchPlan'
+import { ReportInbox } from './ReportInbox'
+
+jest.mock('react-native-worklets', () => jest.requireActual('react-native-worklets/src/mock'))
+jest.mock('react-native-reanimated', () => ({
+ ...jest.requireActual('react-native-reanimated/mock'),
+ useReducedMotion: () => true,
+}))
+jest.mock(
+ 'react-native-safe-area-context',
+ () => jest.requireActual('react-native-safe-area-context/jest/mock').default
+)
+jest.mock('expo-router', () => ({ useRouter: () => ({ setParams: jest.fn() }) }))
+jest.mock('@/lib/analytics', () => ({ track: jest.fn() }))
+jest.mock('@/auth/useProjectScope', () => ({ useProjectScope: () => mockScope }))
+jest.mock('@/demo/demoMode', () => ({
+ ...jest.requireActual('@/demo/demoMode'),
+ useDataMode: () => mockDataMode,
+}))
+jest.mock('./hooks', () => ({
+ useInboxItems: () => ({ data: mockItems, unfiltered: mockItems }),
+ useSetReportRead: () => jest.fn(),
+}))
+jest.mock('./InboxRow', () => ({ InboxRow: () => null }))
+jest.mock('./InboxFilterSheet', () => ({ InboxFilterSheet: () => null }))
+jest.mock('./InboxRowActions', () => ({ InboxRowActions: () => null }))
+
+const mockScope = { host: 'https://app.example.com', projectId: 2 }
+let mockDataMode: 'live' | 'demo' = 'live'
+const mockItems = inboxFromReports(
+ Array.from({ length: INITIAL_PREFETCH_COUNT + 5 }, (_, index) => reportFixture({ id: `report-${index}` }))
+)
+
+function response(status: number, body: unknown): Response {
+ return {
+ ok: status < 400,
+ status,
+ headers: { get: () => null },
+ text: async () => JSON.stringify(body),
+ } as unknown as Response
+}
+
+describe('ReportInbox', () => {
+ beforeEach(() => {
+ mockDataMode = 'live'
+ })
+
+ afterEach(() => {
+ setAuthProvider(null)
+ jest.restoreAllMocks()
+ jest.useRealTimers()
+ })
+
+ test('warms the report cache when scrolling past the initial prefetch window', async () => {
+ setAuthProvider({
+ getAuth: () => ({ ...mockScope, accessToken: 'token', session: 1 }),
+ refreshAccessToken: async () => null,
+ })
+ const fetch = jest.spyOn(globalThis, 'fetch').mockImplementation(async (url) => {
+ const { pathname } = new URL(String(url))
+ if (pathname.includes('/today/')) {
+ return response(404, { detail: 'Not found' })
+ }
+ if (pathname.endsWith('/artefacts/')) {
+ return response(200, { results: [], next: null, count: 0 })
+ }
+ if (pathname.endsWith('/signals/')) {
+ return response(200, { signals: [] })
+ }
+ const id = pathname.match(/\/reports\/([^/]+)\/$/)?.[1]
+ return response(200, reportFixture({ id }))
+ })
+ const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
+ const view = render(
+ <QueryClientProvider client={client}>
+ <ReportInbox selectedReportId="report-0" active={false} />
+ </QueryClientProvider>
+ )
+ fireEvent(screen.UNSAFE_getByType(FlatList), 'viewableItemsChanged', {
+ viewableItems: [{ item: mockItems[0], index: 0, key: mockItems[0]?.id, isViewable: true }],
+ changed: [],
+ })
+ expect(fetch).not.toHaveBeenCalled()
+
+ view.rerender(
+ <QueryClientProvider client={client}>
+ <ReportInbox selectedReportId="report-0" active />
+ </QueryClientProvider>
+ )
+ await waitFor(() =>
+ expect(
+ client.getQueryData(reportDetailQuery(mockScope, `report-${INITIAL_PREFETCH_COUNT - 1}`).queryKey)
+ ).toBeDefined()
+ )
+
+ const index = INITIAL_PREFETCH_COUNT + 4
+ const item = mockItems[index]
+ if (!item) {
+ throw new Error('Missing visible report fixture')
+ }
+ const detailKey = reportDetailQuery(mockScope, item.reportId).queryKey
+ expect(client.getQueryData(detailKey)).toBeUndefined()
+
+ fireEvent(screen.UNSAFE_getByType(FlatList), 'viewableItemsChanged', {
+ viewableItems: [{ item, index, key: item.id, isViewable: true }],
+ changed: [],
+ })
+
+ await waitFor(() => expect(client.getQueryData(detailKey)).toMatchObject({ id: item.reportId }))
+ await waitFor(() =>
+ expect(client.getQueryData(reportSignalsQuery(mockScope, item.reportId).queryKey)).toEqual({ signals: [] })
+ )
+ })
+
+ test.each(['measured', 'dragged', 'inactive', 'unmounted'] as const)(
+ 'handles a delayed selected-report reveal when %s',
+ (state) => {
+ jest.useFakeTimers()
+ mockDataMode = 'demo'
+ const scroll = jest.spyOn(FlatList.prototype, 'scrollToIndex').mockImplementationOnce(function (
+ this: FlatList<InboxItem>,
+ { index }
+ ) {
+ this.props.onScrollToIndexFailed?.({ index, averageItemLength: 100, highestMeasuredFrameIndex: 2 })
+ })
+ scroll.mockImplementation(() => undefined)
+ const estimate = jest.spyOn(FlatList.prototype, 'scrollToOffset').mockImplementation(() => undefined)
+ const client = new QueryClient()
+ const view = render(
+ <QueryClientProvider client={client}>
+ <ReportInbox selectedReportId="report-15" active />
+ </QueryClientProvider>
+ )
+ const target = { index: 15, animated: false, viewPosition: 0.4 }
+ expect(scroll).toHaveBeenCalledTimes(1)
+ expect(scroll).toHaveBeenLastCalledWith(target)
+ expect(estimate).toHaveBeenCalledWith({ offset: 1500, animated: false })
+
+ fireEvent(screen.UNSAFE_getByType(FlatList), 'contentSizeChange', 300, 4000)
+ if (state === 'dragged') fireEvent(screen.UNSAFE_getByType(FlatList), 'scrollBeginDrag')
+ if (state === 'inactive') {
+ view.rerender(
+ <QueryClientProvider client={client}>
+ <ReportInbox selectedReportId="report-15" active={false} />
+ </QueryClientProvider>
+ )
+ }
+ if (state === 'unmounted') view.unmount()
+ act(() => jest.advanceTimersByTime(64))
+ expect(scroll).toHaveBeenCalledTimes(state === 'measured' ? 2 : 1)
+ expect(scroll).toHaveBeenLastCalledWith(target)
+ }
+ )
+})
diff --git a/products/mobile/src/features/inbox/ReportInbox.tsx b/products/mobile/src/features/inbox/ReportInbox.tsx
new file mode 100644
index 000000000000..874f4e9e7d95
--- /dev/null
+++ b/products/mobile/src/features/inbox/ReportInbox.tsx
@@ -0,0 +1,190 @@
+import { useRouter } from 'expo-router'
+import { type ReactElement, useCallback, useEffect, useRef, useState } from 'react'
+import { FlatList, RefreshControl, Text, View } from 'react-native'
+import { track } from '@/lib/analytics'
+import { useNow } from '@/lib/useNow'
+import type { InboxItem } from '@/model/types'
+import { AnimatedLogomark } from '@/ui/icons/AnimatedLogomark'
+import { FilterIcon } from '@/ui/icons/FilterIcon'
+import { Pressable44 } from '@/ui/Pressable44'
+import { LoadingView, StateView } from '@/ui/StateView'
+import { createStyles, useColors } from '@/ui/theme'
+import { layout, type } from '@/ui/tokens'
+import { useScreenInsets } from '@/ui/useScreenInsets'
+import type { RowAnchor } from './contextMenuPlacement'
+import { isDefaultInboxFilters } from './filters'
+import { useInboxItems, useSetReportRead } from './hooks'
+import { InboxFilterSheet } from './InboxFilterSheet'
+import { InboxListFooter } from './InboxListFooter'
+import { InboxRow } from './InboxRow'
+import { InboxRowActions, type RowMenuTarget } from './InboxRowActions'
+import { inboxFilterActions } from './inboxFilterActions'
+import { useInboxFilters } from './inboxFiltersStore'
+import { usePrefetchReports } from './usePrefetchReports'
+
+export function ReportInbox({ selectedReportId, active }: { selectedReportId: string; active: boolean }): ReactElement {
+ const styles = useStyles()
+ const colors = useColors()
+ const insets = useScreenInsets()
+ const router = useRouter()
+ const now = useNow()
+ const filters = useInboxFilters()
+ const query = useInboxItems({ filters, refreshWhileVisible: active })
+ const prefetch = usePrefetchReports(active ? query.data : undefined)
+ const setRead = useSetReportRead()
+ const filterActions = inboxFilterActions(filters)
+ const [filtersOpen, setFiltersOpen] = useState(false)
+ const listRef = useRef<FlatList<InboxItem>>(null)
+ const revealed = useRef(false)
+ const revealFailed = useRef(false)
+ const revealFrame = useRef<number | null>(null)
+ const revealSelected = useCallback((): void => {
+ if (!active || revealed.current || !query.data || !listRef.current) return
+ const index = query.data.findIndex((item) => item.reportId === selectedReportId)
+ if (index < 0) return
+ revealFailed.current = false
+ if (index > 0) listRef.current.scrollToIndex({ index, animated: false, viewPosition: 0.4 })
+ revealed.current = !revealFailed.current
+ }, [active, query.data, selectedReportId])
+ const cancelRevealFrame = useCallback((): void => {
+ if (revealFrame.current !== null) {
+ cancelAnimationFrame(revealFrame.current)
+ revealFrame.current = null
+ }
+ }, [])
+ const scheduleReveal = useCallback((): void => {
+ if (!active || revealed.current || revealFrame.current !== null) return
+ revealFrame.current = requestAnimationFrame(() => {
+ revealFrame.current = requestAnimationFrame(() => {
+ revealFrame.current = null
+ revealSelected()
+ })
+ })
+ }, [active, revealSelected])
+ useEffect(() => {
+ revealSelected()
+ return cancelRevealFrame
+ }, [revealSelected, cancelRevealFrame])
+ const [menu, setMenu] = useState<RowMenuTarget | null>(null)
+ const open = useCallback((id: string): void => router.setParams({ id, from: 'inbox' }), [router])
+ const onMenu = useCallback((item: InboxItem, anchor: RowAnchor): void => setMenu({ item, anchor }), [])
+ const onRead = useCallback(
+ (id: string, read: boolean): void => {
+ setRead(id, read).catch(() => undefined)
+ },
+ [setRead]
+ )
+ return (
+ <View style={styles.pane} testID="report-inbox">
+ <View style={[styles.header, { paddingTop: insets.top + 16 }]}>
+ <AnimatedLogomark height={18} animate={query.isRefetching} />
+ <View style={{ flex: 1 }}>
+ <Text style={styles.title} accessibilityRole="header">
+ Inbox
+ </Text>
+ {!isDefaultInboxFilters(filters) ? (
+ <Text style={{ color: colors.secondary }}>Filters on</Text>
+ ) : null}
+ </View>
+ <Pressable44
+ accessibilityLabel="Filter and sort"
+ testID="report-inbox-filter"
+ onPress={() => {
+ track('mobile_inbox_filters_opened')
+ setFiltersOpen(true)
+ }}
+ style={{ padding: 10 }}
+ >
+ <FilterIcon size={22} />
+ </Pressable44>
+ </View>
+ <FlatList
+ ref={listRef}
+ onScrollBeginDrag={() => {
+ revealed.current = true
+ cancelRevealFrame()
+ }}
+ onScrollToIndexFailed={({ averageItemLength, index }) => {
+ revealFailed.current = true
+ listRef.current?.scrollToOffset({ offset: averageItemLength * index, animated: false })
+ }}
+ onContentSizeChange={scheduleReveal}
+ onLayout={scheduleReveal}
+ data={query.data ?? []}
+ onViewableItemsChanged={prefetch.onViewableItemsChanged}
+ viewabilityConfig={prefetch.viewabilityConfig}
+ keyExtractor={(item) => item.id}
+ renderItem={({ item }) => (
+ <View style={item.reportId === selectedReportId && styles.selected} onLayout={scheduleReveal}>
+ <InboxRow
+ titleLines={3}
+ item={item}
+ now={now}
+ onOpen={open}
+ onLongPress={onMenu}
+ onSetRead={onRead}
+ />
+ </View>
+ )}
+ ListEmptyComponent={
+ query.isLoading || query.isRefetching ? (
+ <LoadingView label="Loading your inbox" />
+ ) : query.isError ? (
+ <StateView
+ title="Couldn't load your inbox"
+ actionLabel="Try again"
+ onAction={() => void query.refetch()}
+ />
+ ) : (
+ <StateView
+ title="No reports match this inbox"
+ message="Change your filters to see more reports."
+ />
+ )
+ }
+ ListFooterComponent={
+ <InboxListFooter
+ isLoadingMore={query.isLoadingMore}
+ loadMoreFailed={query.loadMoreFailed}
+ onRetry={query.retryLoadMore}
+ />
+ }
+ onEndReached={query.loadMore}
+ onEndReachedThreshold={0.5}
+ refreshControl={
+ <RefreshControl
+ refreshing={query.isRefetching}
+ onRefresh={() => void query.refetch()}
+ tintColor={colors.tertiary}
+ />
+ }
+ contentContainerStyle={[styles.content, { paddingBottom: insets.bottom + 20 }]}
+ />
+ <InboxFilterSheet
+ visible={filtersOpen}
+ onClose={() => setFiltersOpen(false)}
+ filters={filters}
+ items={query.unfiltered ?? []}
+ onSortChange={filterActions.setSort}
+ onCreatedWindowChange={filterActions.setCreatedWindow}
+ onToggleSource={filterActions.toggleSource}
+ onClear={filterActions.clearFilters}
+ />
+ <InboxRowActions target={menu} onClose={() => setMenu(null)} />
+ </View>
+ )
+}
+
+const useStyles = createStyles(({ colors }) => ({
+ pane: { flex: 1, borderRightWidth: 1, borderRightColor: colors.border, backgroundColor: colors.background },
+ header: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 12,
+ paddingHorizontal: layout.inboxGutter,
+ paddingBottom: 20,
+ },
+ title: { ...type.screenTitle, color: colors.ink },
+ content: { paddingHorizontal: 8, flexGrow: 1 },
+ selected: { backgroundColor: colors.sunken, borderRadius: 12 },
+}))
diff --git a/products/mobile/src/features/inbox/inboxFilterActions.ts b/products/mobile/src/features/inbox/inboxFilterActions.ts
new file mode 100644
index 000000000000..b60d7e47e3a4
--- /dev/null
+++ b/products/mobile/src/features/inbox/inboxFilterActions.ts
@@ -0,0 +1,40 @@
+import { track } from '@/lib/analytics'
+import type { CreatedWindow, InboxFilters, InboxSort, SourceFilterKey } from './filters'
+import { useInboxFiltersStore } from './inboxFiltersStore'
+
+export function inboxFilterActions(filters: InboxFilters): {
+ setSort: (sort: InboxSort) => void
+ setCreatedWindow: (window: CreatedWindow) => void
+ toggleSource: (source: SourceFilterKey) => void
+ clearFilters: () => void
+} {
+ const setSort = (sort: InboxSort): void => {
+ if (sort === filters.sort) {
+ return
+ }
+ track('mobile_inbox_sort_changed', { sort })
+ useInboxFiltersStore.getState().setSort(sort)
+ }
+ const setCreatedWindow = (window: CreatedWindow): void => {
+ if (window === filters.createdWindow) {
+ return
+ }
+ track('mobile_inbox_created_window_changed', { window })
+ useInboxFiltersStore.getState().setCreatedWindow(window)
+ }
+ const toggleSource = (source: SourceFilterKey): void => {
+ const selected = !filters.sources.includes(source)
+ track('mobile_inbox_source_filter_changed', {
+ source,
+ selected,
+ count: filters.sources.length + (selected ? 1 : -1),
+ })
+ useInboxFiltersStore.getState().toggleSource(source)
+ }
+ const clearFilters = (): void => {
+ track('mobile_inbox_filters_cleared')
+ useInboxFiltersStore.getState().clear()
+ }
+
+ return { setSort, setCreatedWindow, toggleSource, clearFilters }
+}
diff --git a/products/mobile/src/features/projects/ProjectSheet.tsx b/products/mobile/src/features/projects/ProjectSheet.tsx
index 859a1eec404e..a3a90755b059 100644
--- a/products/mobile/src/features/projects/ProjectSheet.tsx
+++ b/products/mobile/src/features/projects/ProjectSheet.tsx
@@ -1,6 +1,5 @@
import { type ReactElement, type ReactNode, useEffect, useMemo, useState } from 'react'
import { ActivityIndicator, ScrollView, Text, TextInput, useWindowDimensions, View } from 'react-native'
-
import { type AuthProject, useAuthStore } from '@/auth/authStore'
import { DEMO_PROJECT_NAME } from '@/demo/briefings'
import { useDemoMode } from '@/demo/demoMode'
@@ -11,6 +10,8 @@ import { SearchIcon } from '@/ui/icons/SearchIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors, useTheme } from '@/ui/theme'
import { iconSizes, inputReset, radii, type } from '@/ui/tokens'
+import { usePickerCardStyle } from '@/ui/usePickerCardStyle'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { topOffset, useScreenInsets } from '@/ui/useScreenInsets'
import { filterProjects, groupByOrganization } from './projectList'
@@ -26,12 +27,13 @@ const DEMO_PROJECT: AuthProject = { id: 0, name: DEMO_PROJECT_NAME, organization
const DEMO_PROJECTS = [DEMO_PROJECT]
interface ProjectRowProps {
+ compact?: boolean
project: AuthProject
selected: boolean
onPress: () => void
}
-function ProjectRow({ project, selected, onPress }: ProjectRowProps): ReactElement {
+function ProjectRow({ compact = false, project, selected, onPress }: ProjectRowProps): ReactElement {
const styles = useStyles()
const colors = useColors()
return (
@@ -41,7 +43,7 @@ function ProjectRow({ project, selected, onPress }: ProjectRowProps): ReactEleme
accessibilityState={{ checked: selected }}
accessibilityLabel={project.name}
pressedBackground={colors.background}
- style={styles.row}
+ style={[styles.row, compact && { minHeight: 44 }]}
testID={`project-sheet-${project.id}`}
>
<Text style={styles.rowLabel} numberOfLines={1}>
@@ -56,9 +58,13 @@ export function ProjectSheet({ visible, onClose, onSelect }: ProjectSheetProps):
const styles = useStyles()
const { colors, scheme } = useTheme()
const insets = useScreenInsets()
- const { height: windowHeight } = useWindowDimensions()
+ const { height: windowHeight } = useSceneDimensions()
+ const { width: windowWidth } = useWindowDimensions()
+ const side = Math.max(14, (windowWidth - insets.left - insets.right - 600) / 2)
+ const compact = windowHeight < 480
const top = topOffset(insets, 120)
const cardHeight = Math.max(320, Math.round((windowHeight - top) * 0.52))
+ const cardStyle = usePickerCardStyle(top, cardHeight)
const demo = useDemoMode((state) => state.enabled)
const storeProjects = useAuthStore((state) => state.projects)
const storeProjectId = useAuthStore((state) => state.projectId)
@@ -142,6 +148,7 @@ export function ProjectSheet({ visible, onClose, onSelect }: ProjectSheetProps):
: []),
...group.projects.map((project) => (
<ProjectRow
+ compact={compact}
key={project.id}
project={project}
selected={project.id === projectId}
@@ -172,36 +179,39 @@ export function ProjectSheet({ visible, onClose, onSelect }: ProjectSheetProps):
onClose={onClose}
accessibilityLabel="Project"
testID="project-sheet"
- style={[styles.card, { top, height: cardHeight }]}
+ style={[styles.card, compact && styles.cardCompact, { left: side, right: side }, cardStyle]}
>
- <View style={styles.header}>
- <Text style={styles.title}>Project</Text>
- <Pressable44
- onPress={onClose}
- accessibilityLabel="Close"
- pressedBackground={colors.hairline}
- style={styles.close}
- >
- <CloseIcon size={iconSizes.control} />
- </Pressable44>
- </View>
- <View style={styles.search}>
- <SearchIcon size={iconSizes.control} />
- <TextInput
- value={query}
- onChangeText={setQuery}
- placeholder="Find a project…"
- placeholderTextColor={colors.tertiary}
- keyboardAppearance={scheme}
- autoFocus
- autoCorrect={false}
- autoCapitalize="none"
- style={styles.input}
- accessibilityLabel="Search projects"
- testID="project-search"
- />
+ <View style={compact ? styles.controlsCompact : undefined}>
+ <View style={[styles.header, compact && styles.headerCompact]}>
+ <Text style={styles.title}>Project</Text>
+ <Pressable44
+ onPress={onClose}
+ accessibilityLabel="Close"
+ pressedBackground={colors.hairline}
+ style={styles.close}
+ >
+ <CloseIcon size={iconSizes.control} />
+ </Pressable44>
+ </View>
+ <View style={[styles.search, compact && styles.searchCompact]}>
+ <SearchIcon size={iconSizes.control} />
+ <TextInput
+ value={query}
+ onChangeText={setQuery}
+ placeholder="Find a project…"
+ placeholderTextColor={colors.tertiary}
+ keyboardAppearance={scheme}
+ autoFocus
+ autoCorrect={false}
+ disableFullscreenUI
+ autoCapitalize="none"
+ style={styles.input}
+ accessibilityLabel="Search projects"
+ testID="project-search"
+ />
+ </View>
</View>
- <ScrollView style={styles.list} keyboardShouldPersistTaps="handled">
+ <ScrollView style={[styles.list, compact && { marginTop: 2 }]} keyboardShouldPersistTaps="handled">
{content}
</ScrollView>
</FloatingCard>
@@ -209,6 +219,23 @@ export function ProjectSheet({ visible, onClose, onSelect }: ProjectSheetProps):
}
const useStyles = createStyles(({ colors }) => ({
+ cardCompact: {
+ paddingTop: 4,
+ paddingBottom: 4,
+ },
+ controlsCompact: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 12,
+ },
+ headerCompact: {
+ gap: 12,
+ },
+ searchCompact: {
+ flex: 1,
+ height: 44,
+ marginTop: 0,
+ },
card: {
left: 14,
right: 14,
@@ -254,6 +281,7 @@ const useStyles = createStyles(({ colors }) => ({
list: {
marginTop: 8,
flexGrow: 0,
+ flexShrink: 1,
},
organization: {
color: colors.tertiary,
diff --git a/products/mobile/src/features/replay/FrameSheet.tsx b/products/mobile/src/features/replay/FrameSheet.tsx
index 8793d5e921b2..d594e0fe6c21 100644
--- a/products/mobile/src/features/replay/FrameSheet.tsx
+++ b/products/mobile/src/features/replay/FrameSheet.tsx
@@ -1,6 +1,6 @@
-import { type ReactElement, useRef } from 'react'
-import { Text, useWindowDimensions, View } from 'react-native'
-
+import { type ReactElement, useMemo, useRef } from 'react'
+import { ScrollView, Text, View } from 'react-native'
+import { Gesture, GestureDetector } from 'react-native-gesture-handler'
import { BottomSheet } from '@/ui/BottomSheet'
import { ChevronLeftIcon } from '@/ui/icons/ChevronLeftIcon'
import { ChevronRightIcon } from '@/ui/icons/ChevronRightIcon'
@@ -10,6 +10,7 @@ import { Pressable44 } from '@/ui/Pressable44'
import { SegmentedPill } from '@/ui/SegmentedPill'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { FrameImage } from './FrameImage'
import type { SummaryChapter } from './replayModel'
@@ -37,7 +38,8 @@ export function FrameSheet({
}: FrameSheetProps): ReactElement {
const colors = useColors()
const styles = useStyles()
- const { width } = useWindowDimensions()
+ const { width } = useSceneDimensions()
+ const scrollGesture = useMemo(() => Gesture.Native(), [])
// The last chapter stays drawn while the sheet slides out.
const shown = useRef<number>(0)
if (position !== null) {
@@ -45,84 +47,90 @@ export function FrameSheet({
}
const index = shown.current
const chapter = chapters[index]
- const frameWidth = width - SHEET_PADDING * 2
+ const frameWidth = Math.min(600, width) - SHEET_PADDING * 2
return (
<BottomSheet
visible={position !== null}
onClose={onClose}
paddingHorizontal={SHEET_PADDING}
+ scrollGesture={scrollGesture}
accessibilityLabel="Chapter frame"
testID="session-frame-sheet"
>
{chapter ? (
- <View style={styles.body}>
- <View style={styles.header}>
- <Text style={styles.title} accessibilityRole="header">
- {`Frame at ${formatOffset(chapter.frameMs ?? chapter.startMs)}`}
- </Text>
- <Pressable44
- onPress={onClose}
- accessibilityLabel="Close"
- pressedBackground={colors.sunken}
- style={styles.close}
- testID="session-frame-close"
- >
- <CloseIcon size={iconSizes.control} />
- </Pressable44>
- </View>
- <FrameImage
- observationId={chapter.hasFrame ? observationId : null}
- chapter={chapter.index}
- style={{ width: frameWidth, height: Math.round(frameWidth / FRAME_ASPECT) }}
- accessibilityLabel={`Frame of ${chapter.title}`}
- />
- <View style={styles.captionRow}>
- <View style={styles.caption}>
- <Text style={styles.chapterTitle}>{chapter.title}</Text>
- <Text style={styles.meta}>
- {`Chapter ${index + 1} of ${chapters.length} · ${formatOffset(chapter.startMs)}`}
+ <GestureDetector gesture={scrollGesture}>
+ <ScrollView style={styles.scroll} contentContainerStyle={styles.body}>
+ <View style={styles.header}>
+ <Text style={styles.title} accessibilityRole="header">
+ {`Frame at ${formatOffset(chapter.frameMs ?? chapter.startMs)}`}
</Text>
+ <Pressable44
+ onPress={onClose}
+ accessibilityLabel="Close"
+ pressedBackground={colors.sunken}
+ style={styles.close}
+ testID="session-frame-close"
+ >
+ <CloseIcon size={iconSizes.control} />
+ </Pressable44>
</View>
- {chapter.isKeyMoment ? (
- <View style={styles.keyChip}>
- <FlagIcon size={iconSizes.small} color={colors.orange} />
- <Text style={styles.keyText}>Key moment</Text>
+ <FrameImage
+ observationId={chapter.hasFrame ? observationId : null}
+ chapter={chapter.index}
+ style={{ width: frameWidth, height: Math.round(frameWidth / FRAME_ASPECT) }}
+ accessibilityLabel={`Frame of ${chapter.title}`}
+ />
+ <View style={styles.captionRow}>
+ <View style={styles.caption}>
+ <Text style={styles.chapterTitle}>{chapter.title}</Text>
+ <Text style={styles.meta}>
+ {`Chapter ${index + 1} of ${chapters.length} · ${formatOffset(chapter.startMs)}`}
+ </Text>
</View>
+ {chapter.isKeyMoment ? (
+ <View style={styles.keyChip}>
+ <FlagIcon size={iconSizes.small} color={colors.orange} />
+ <Text style={styles.keyText}>Key moment</Text>
+ </View>
+ ) : null}
+ </View>
+ {chapters.length > 1 ? (
+ <SegmentedPill
+ style={styles.pager}
+ height={46}
+ segmentWidth={52}
+ segments={[
+ {
+ key: 'previous',
+ accessibilityLabel: 'Previous chapter',
+ onPress: () => onChangePosition(index - 1),
+ disabled: index === 0,
+ testID: 'session-frame-previous',
+ children: <ChevronLeftIcon size={iconSizes.control} />,
+ },
+ {
+ key: 'next',
+ accessibilityLabel: 'Next chapter',
+ onPress: () => onChangePosition(index + 1),
+ disabled: index === chapters.length - 1,
+ testID: 'session-frame-next',
+ children: <ChevronRightIcon size={iconSizes.control} />,
+ },
+ ]}
+ />
) : null}
- </View>
- {chapters.length > 1 ? (
- <SegmentedPill
- style={styles.pager}
- height={46}
- segmentWidth={52}
- segments={[
- {
- key: 'previous',
- accessibilityLabel: 'Previous chapter',
- onPress: () => onChangePosition(index - 1),
- disabled: index === 0,
- testID: 'session-frame-previous',
- children: <ChevronLeftIcon size={iconSizes.control} />,
- },
- {
- key: 'next',
- accessibilityLabel: 'Next chapter',
- onPress: () => onChangePosition(index + 1),
- disabled: index === chapters.length - 1,
- testID: 'session-frame-next',
- children: <ChevronRightIcon size={iconSizes.control} />,
- },
- ]}
- />
- ) : null}
- <Text style={styles.note}>Frames can show text that the recording did not mask.</Text>
- </View>
+ <Text style={styles.note}>Frames can show text that the recording did not mask.</Text>
+ </ScrollView>
+ </GestureDetector>
) : null}
</BottomSheet>
)
}
const useStyles = createStyles(({ colors }) => ({
+ scroll: {
+ flexShrink: 1,
+ },
body: {
gap: 14,
paddingBottom: 8,
diff --git a/products/mobile/src/features/report/ReportScreen.test.tsx b/products/mobile/src/features/report/ReportScreen.test.tsx
index 353ee3410da9..cd2a717d4533 100644
--- a/products/mobile/src/features/report/ReportScreen.test.tsx
+++ b/products/mobile/src/features/report/ReportScreen.test.tsx
@@ -1,7 +1,7 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react-native'
import type { ReactElement, ReactNode } from 'react'
-import { AppState } from 'react-native'
+import { AppState, Dimensions } from 'react-native'
import { setAuthProvider } from '@/api/client'
import { useDemoMode } from '@/demo/demoMode'
@@ -23,7 +23,13 @@ jest.mock('expo-notifications', () => ({}))
jest.mock('expo-router', () => ({
useFocusEffect: (callback: () => void) => require('react').useEffect(callback, [callback]),
useIsFocused: () => mockFocused,
- useRouter: () => ({ push: jest.fn(), setParams: jest.fn(), canGoBack: () => false, replace: jest.fn() }),
+ useRouter: () => ({
+ push: jest.fn(),
+ setParams: jest.fn(),
+ navigate: mockNavigate,
+ canGoBack: () => false,
+ replace: jest.fn(),
+ }),
}))
jest.mock('@/auth/useProjectScope', () => {
const scope = { host: 'https://app.example.com', projectId: 2 }
@@ -31,12 +37,74 @@ jest.mock('@/auth/useProjectScope', () => {
})
jest.mock('@/lib/analytics', () => ({ track: jest.fn() }))
+const mockNavigate = jest.fn()
const REPORT = reportFixture()
let mockFocused = true
const EXISTING = { uuid: 'existing-user', first_name: 'Existing', last_name: 'Reviewer', email: '[email protected]' }
const ADDED = { uuid: 'added-user', first_name: 'Added', last_name: 'Reviewer', email: '[email protected]' }
describe('ReportScreen', () => {
+ test.each([
+ { width: 951, height: 669, navigation: true },
+ { width: 874, height: 402, navigation: false },
+ ])('keeps report navigation usable at $width × $height', async ({ width, height, navigation }) => {
+ mockNavigate.mockClear()
+ useDemoMode.getState().setEnabled(true)
+ const previous = Dimensions.get('window')
+ Dimensions.set({ window: { ...previous, width, height } })
+ const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ const view = render(<ReportScreen reportId="demo-report-load-time" from="inbox" />, { wrapper })
+ try {
+ await waitFor(() => expect(screen.getByTestId('report-screen')).toBeTruthy())
+ expect(screen.getByTestId('action-chat')).toBeTruthy()
+ expect(screen.queryByTestId('inbox-chat')).toBeNull()
+ if (navigation) {
+ fireEvent.press(screen.getByTestId('inbox-nav-home'))
+ expect(mockNavigate).toHaveBeenCalledWith('/inbox')
+ } else {
+ expect(screen.queryByTestId('inbox-nav-home')).toBeNull()
+ }
+ } finally {
+ view.unmount()
+ client.clear()
+ Dimensions.set({ window: previous })
+ useDemoMode.getState().setEnabled(false)
+ }
+ })
+
+ test('keeps a verdict note and report instance while the window folds and unfolds', async () => {
+ useDemoMode.getState().setEnabled(true)
+ const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
+ const wrapper = ({ children }: { children: ReactNode }): ReactElement => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ )
+ const previous = Dimensions.get('window')
+ const view = render(<ReportScreen reportId="demo-report-load-time" from="inbox" />, { wrapper })
+ try {
+ await waitFor(() => expect(screen.getByTestId('report-screen')).toBeTruthy())
+ const report = screen.getByTestId('report-screen')
+ fireEvent.press(screen.getByText('Resolve'))
+ fireEvent.changeText(screen.getByTestId('resolve-sheet-note'), 'Keep this note while resizing')
+ for (const size of [
+ { width: 951, height: 669 },
+ { width: 466, height: 678 },
+ { width: 669, height: 951 },
+ ]) {
+ act(() => Dimensions.set({ window: { ...previous, ...size } }))
+ expect(screen.getByTestId('report-screen', { includeHiddenElements: true })).toBe(report)
+ expect(screen.getByTestId('resolve-sheet-note').props.value).toBe('Keep this note while resizing')
+ }
+ } finally {
+ view.unmount()
+ client.clear()
+ Dimensions.set({ window: previous })
+ useDemoMode.getState().setEnabled(false)
+ }
+ })
+
test.each(['abbreviated', 'full'] as const)('releases canvases when the %s report loses focus', async (kind) => {
useDemoMode.getState().setEnabled(true)
const client = new QueryClient({ defaultOptions: { queries: { gcTime: Infinity } } })
diff --git a/products/mobile/src/features/report/ReportScreen.tsx b/products/mobile/src/features/report/ReportScreen.tsx
index cc637f8856f8..660a48a44279 100644
--- a/products/mobile/src/features/report/ReportScreen.tsx
+++ b/products/mobile/src/features/report/ReportScreen.tsx
@@ -16,16 +16,18 @@ import {
RESOLVE_REASON_OPTIONS,
type ResolveReason,
} from '@/model/verdictReasons'
+import { INBOX_PANE_WIDTH, NAV_RAIL_WIDTH, READING_WIDTH } from '@/ui/adaptiveLayout'
import { ChartCanvasBudget } from '@/ui/chart/budget/ChartCanvasBudget'
import { FloatingCard } from '@/ui/FloatingCard'
import { WarningIcon } from '@/ui/icons/WarningIcon'
import { OverlayHost } from '@/ui/OverlayPortal'
+import { SceneFrame } from '@/ui/SceneFrame'
import { LoadingView, StateView } from '@/ui/StateView'
import { SCREEN_CONTENT_TOP } from '@/ui/screenLayout'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, layout } from '@/ui/tokens'
+import { useAppLayout } from '@/ui/useAppLayout'
import { topOffset, useScreenInsets } from '@/ui/useScreenInsets'
-
import { ActionBar, type TaskChatEntry } from '../handoff/ActionBar'
import { actionBarStateFor } from '../handoff/actionBarState'
import { HandoffSheet } from '../handoff/HandoffSheet'
@@ -33,9 +35,11 @@ import { useDecisionAnswer, useHandoffNotice } from '../handoff/hooks'
import { useReportWithLiveRun } from '../handoff/useReportWithLiveRun'
import { useInboxItems, useMarkReadOnOpen } from '../inbox/hooks'
import { useInboxFilters } from '../inbox/inboxFiltersStore'
+import { ReportInbox } from '../inbox/ReportInbox'
import { PrioritySheet } from '../priority/PrioritySheet'
import { AssigneeSheet } from '../reviewers/AssigneeSheet'
import { useGithubOnlyReviewerCount, useReportReviewersQuery } from '../reviewers/hooks'
+import { ReportNavigation } from '../tabs/ReportNavigation'
import { VerdictSheet } from '../verdict/VerdictSheet'
import { dismissCopy, hasOpenPullRequest, resolveCopy } from '../verdict/verdictCopy'
import { Activity } from './Activity'
@@ -73,11 +77,41 @@ function goBackOrInbox(router: ReturnType<typeof useRouter>): void {
export function ReportScreen({ reportId, from }: ReportScreenProps): ReactElement {
const demo = useDataMode() === 'demo'
const focused = useIsFocused()
+ const { rail, railSide, paired, reportNavigation: navigation } = useAppLayout()
return (
<OverlayHost>
- <ChartCanvasBudget active={focused}>
- {isReportId(reportId, demo) ? <ReportContent reportId={reportId} from={from} /> : <ReportNotFound />}
- </ChartCanvasBudget>
+ <View
+ style={{
+ flex: 1,
+ paddingBottom: navigation && !rail ? 100 : 0,
+ paddingLeft: rail && railSide === 'left' ? NAV_RAIL_WIDTH : 0,
+ paddingRight: rail && railSide === 'right' ? NAV_RAIL_WIDTH : 0,
+ }}
+ >
+ <View style={{ flex: 1, flexDirection: 'row' }}>
+ <SceneFrame
+ style={{
+ flexGrow: 0,
+ flexShrink: 0,
+ flexBasis: INBOX_PANE_WIDTH,
+ width: INBOX_PANE_WIDTH,
+ display: paired ? 'flex' : 'none',
+ }}
+ >
+ <ReportInbox selectedReportId={reportId} active={paired && focused} />
+ </SceneFrame>
+ <SceneFrame>
+ <ChartCanvasBudget active={focused}>
+ {isReportId(reportId, demo) ? (
+ <ReportContent reportId={reportId} from={from} />
+ ) : (
+ <ReportNotFound />
+ )}
+ </ChartCanvasBudget>
+ </SceneFrame>
+ </View>
+ </View>
+ {navigation ? <ReportNavigation /> : null}
</OverlayHost>
)
}
@@ -430,6 +464,9 @@ const useStyles = createStyles(({ colors }) => ({
flex: 1,
},
content: {
+ width: '100%',
+ maxWidth: READING_WIDTH,
+ alignSelf: 'center',
paddingHorizontal: layout.detailGutter,
paddingBottom: 28,
},
diff --git a/products/mobile/src/features/reviewers/AssigneeSheet.test.tsx b/products/mobile/src/features/reviewers/AssigneeSheet.test.tsx
index 120695bee384..57b183278d1a 100644
--- a/products/mobile/src/features/reviewers/AssigneeSheet.test.tsx
+++ b/products/mobile/src/features/reviewers/AssigneeSheet.test.tsx
@@ -9,6 +9,7 @@ import { OverlayHost } from '@/ui/OverlayPortal'
import { AssigneeSheet } from './AssigneeSheet'
+jest.mock('react-native-keyboard-controller', () => jest.requireActual('react-native-keyboard-controller/jest'))
jest.mock('react-native-worklets', () => jest.requireActual('react-native-worklets/src/mock'))
jest.mock('react-native-reanimated', () => ({
...jest.requireActual('react-native-reanimated/mock'),
diff --git a/products/mobile/src/features/reviewers/AssigneeSheet.tsx b/products/mobile/src/features/reviewers/AssigneeSheet.tsx
index 3f8817c76f8c..6aacef09cfb7 100644
--- a/products/mobile/src/features/reviewers/AssigneeSheet.tsx
+++ b/products/mobile/src/features/reviewers/AssigneeSheet.tsx
@@ -1,6 +1,5 @@
import { type ReactElement, useEffect, useMemo, useRef, useState } from 'react'
import { ActivityIndicator, ScrollView, Text, TextInput, useWindowDimensions, View } from 'react-native'
-
import { actionErrorMessage } from '@/lib/errors'
import type { Person, Reviewer } from '@/model/types'
import { Avatar } from '@/ui/Avatar'
@@ -12,6 +11,8 @@ import { SearchIcon } from '@/ui/icons/SearchIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors, useTheme } from '@/ui/theme'
import { iconSizes, inputReset, radii, type } from '@/ui/tokens'
+import { usePickerCardStyle } from '@/ui/usePickerCardStyle'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { topOffset, useScreenInsets } from '@/ui/useScreenInsets'
import { MAX_REVIEWERS, useAvailableReviewers } from './hooks'
@@ -41,12 +42,13 @@ function limitMessage(githubOnlyCount: number): string {
}
interface PersonRowProps {
+ compact?: boolean
person: Person
selected: boolean
onPress: () => void
}
-function PersonRow({ person, selected, onPress }: PersonRowProps): ReactElement {
+function PersonRow({ compact = false, person, selected, onPress }: PersonRowProps): ReactElement {
const styles = useStyles()
const colors = useColors()
return (
@@ -55,7 +57,7 @@ function PersonRow({ person, selected, onPress }: PersonRowProps): ReactElement
accessibilityRole="checkbox"
accessibilityState={{ checked: selected }}
pressedBackground={colors.background}
- style={styles.row}
+ style={[styles.row, compact && { minHeight: 44 }]}
testID={`assignee-${person.uuid}`}
>
<Avatar name={person.name} color={person.color} seed={person.uuid} size={32} fontSize={12} />
@@ -78,9 +80,13 @@ export function AssigneeSheet({
const styles = useStyles()
const { colors, scheme } = useTheme()
const insets = useScreenInsets()
- const { height: windowHeight } = useWindowDimensions()
+ const { height: windowHeight } = useSceneDimensions()
+ const { width: windowWidth } = useWindowDimensions()
+ const side = Math.max(14, (windowWidth - insets.left - insets.right - 600) / 2)
+ const compact = windowHeight < 480
const top = topOffset(insets, 120)
const cardHeight = Math.max(320, Math.round((windowHeight - top) * 0.52))
+ const cardStyle = usePickerCardStyle(top, cardHeight)
const [query, setQuery] = useState('')
const [selected, setSelected] = useState<Set<string>>(() => new Set())
const [limitHit, setLimitHit] = useState(false)
@@ -141,35 +147,53 @@ export function AssigneeSheet({
onClose={onClose}
accessibilityLabel="Assignee"
testID="assignee-sheet"
- style={[styles.card, { top, height: cardHeight }]}
+ style={[styles.card, compact && styles.cardCompact, { left: side, right: side }, cardStyle]}
>
- <View style={styles.header}>
- <Text style={styles.title}>Assignee</Text>
- <View style={styles.headerActions}>
- {changed ? (
+ <View style={compact ? styles.controlsCompact : undefined}>
+ <View style={[styles.header, compact && styles.headerCompact]}>
+ <Text style={styles.title}>Assignee</Text>
+ <View style={styles.headerActions}>
+ {changed ? (
+ <Pressable44
+ onPress={() => void save()}
+ disabled={pending || overLimit}
+ accessibilityState={{ busy: pending, disabled: pending || overLimit }}
+ pressedBackground={colors.inkHover}
+ style={styles.done}
+ testID="assignee-done"
+ >
+ {pending ? (
+ <ActivityIndicator size="small" color={colors.onInk} />
+ ) : (
+ <Text style={styles.doneText}>Done</Text>
+ )}
+ </Pressable44>
+ ) : null}
<Pressable44
- onPress={() => void save()}
- disabled={pending || overLimit}
- accessibilityState={{ busy: pending, disabled: pending || overLimit }}
- pressedBackground={colors.inkHover}
- style={styles.done}
- testID="assignee-done"
+ onPress={onClose}
+ accessibilityLabel="Close"
+ pressedBackground={colors.hairline}
+ style={styles.close}
>
- {pending ? (
- <ActivityIndicator size="small" color={colors.onInk} />
- ) : (
- <Text style={styles.doneText}>Done</Text>
- )}
+ <CloseIcon size={iconSizes.control} />
</Pressable44>
- ) : null}
- <Pressable44
- onPress={onClose}
- accessibilityLabel="Close"
- pressedBackground={colors.hairline}
- style={styles.close}
- >
- <CloseIcon size={iconSizes.control} />
- </Pressable44>
+ </View>
+ </View>
+ <View style={[styles.search, compact && styles.searchCompact]}>
+ <SearchIcon size={iconSizes.control} />
+ <TextInput
+ value={query}
+ onChangeText={setQuery}
+ placeholder="Assign to…"
+ placeholderTextColor={colors.tertiary}
+ keyboardAppearance={scheme}
+ autoFocus
+ autoCorrect={false}
+ disableFullscreenUI
+ style={styles.input}
+ accessibilityLabel="Search people"
+ testID="assignee-search"
+ />
</View>
</View>
{error ? (
@@ -182,29 +206,14 @@ export function AssigneeSheet({
{limitMessage(githubOnlyCount)}
</Text>
) : null}
- <View style={styles.search}>
- <SearchIcon size={iconSizes.control} />
- <TextInput
- value={query}
- onChangeText={setQuery}
- placeholder="Assign to…"
- placeholderTextColor={colors.tertiary}
- keyboardAppearance={scheme}
- autoFocus
- autoCorrect={false}
- style={styles.input}
- accessibilityLabel="Search people"
- testID="assignee-search"
- />
- </View>
- <ScrollView style={styles.list} keyboardShouldPersistTaps="handled">
+ <ScrollView style={[styles.list, compact && { marginTop: 2 }]} keyboardShouldPersistTaps="handled">
{trimmed ? null : (
<Pressable44
onPress={clear}
accessibilityRole="checkbox"
accessibilityState={{ checked: selected.size === 0 }}
pressedBackground={colors.background}
- style={styles.row}
+ style={[styles.row, compact && { minHeight: 44 }]}
testID="assignee-none"
>
<View style={styles.dashed}>
@@ -232,6 +241,7 @@ export function AssigneeSheet({
) : null}
{(people.data ?? []).map((person) => (
<PersonRow
+ compact={compact}
key={person.uuid}
person={person}
selected={selected.has(person.uuid)}
@@ -247,6 +257,23 @@ export function AssigneeSheet({
}
const useStyles = createStyles(({ colors }) => ({
+ cardCompact: {
+ paddingTop: 4,
+ paddingBottom: 4,
+ },
+ controlsCompact: {
+ flexDirection: 'row',
+ alignItems: 'center',
+ gap: 12,
+ },
+ headerCompact: {
+ gap: 12,
+ },
+ searchCompact: {
+ flex: 1,
+ height: 44,
+ marginTop: 0,
+ },
card: {
left: 14,
right: 14,
@@ -322,6 +349,7 @@ const useStyles = createStyles(({ colors }) => ({
list: {
marginTop: 8,
flexGrow: 0,
+ flexShrink: 1,
},
row: {
flexDirection: 'row',
diff --git a/products/mobile/src/features/settings/SettingsScreen.tsx b/products/mobile/src/features/settings/SettingsScreen.tsx
index 52a1ae828541..c826a3f3cb46 100644
--- a/products/mobile/src/features/settings/SettingsScreen.tsx
+++ b/products/mobile/src/features/settings/SettingsScreen.tsx
@@ -6,6 +6,7 @@ import { useViewer } from '@/auth/useViewer'
import { useDemoMode } from '@/demo/demoMode'
import { track } from '@/lib/analytics'
import { isInternalBuild } from '@/lib/environment'
+import { READING_WIDTH } from '@/ui/adaptiveLayout'
import { EnvironmentRibbon } from '@/ui/EnvironmentRibbon'
import { ScreenChrome } from '@/ui/ScreenChrome'
import { SCREEN_CONTENT_TOP } from '@/ui/screenLayout'
@@ -131,6 +132,9 @@ const useStyles = createStyles(({ colors }) => ({
backgroundColor: colors.background,
},
content: {
+ width: '100%',
+ maxWidth: READING_WIDTH,
+ alignSelf: 'center',
paddingHorizontal: layout.detailGutter,
},
title: {
diff --git a/products/mobile/src/features/tabs/BottomBar.tsx b/products/mobile/src/features/tabs/BottomBar.tsx
index e083947ddb39..7837fe552ea5 100644
--- a/products/mobile/src/features/tabs/BottomBar.tsx
+++ b/products/mobile/src/features/tabs/BottomBar.tsx
@@ -13,6 +13,7 @@ import { ViewsIcon } from '@/ui/icons/ViewsIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors, useTheme } from '@/ui/theme'
import { iconSizes, layout, radii, type } from '@/ui/tokens'
+import { useAppLayout } from '@/ui/useAppLayout'
import { bottomOffset, useScreenInsets } from '@/ui/useScreenInsets'
import type { NavPin } from './navPinStore'
@@ -27,7 +28,7 @@ interface BottomBarProps {
onChats: () => void
onViews: () => void
onPin: (pin: NavPin) => void
- onNewChat: () => void
+ onNewChat?: () => void
}
const BAR_GUTTER = 20
@@ -58,6 +59,7 @@ interface NavSlotProps {
function NavSlot({ label, Icon, onPress, disabled = false, testID }: NavSlotProps): ReactElement {
const colors = useColors()
const styles = useStyles()
+ const { rail } = useAppLayout()
return (
<Pressable44
onPress={onPress}
@@ -66,7 +68,11 @@ function NavSlot({ label, Icon, onPress, disabled = false, testID }: NavSlotProp
accessibilityLabel={label}
accessibilityState={{ selected: false, disabled }}
pressedBackground={colors.background}
- style={[styles.slot, disabled && styles.slotDisabled]}
+ style={[
+ styles.slot,
+ rail && { flexBasis: 'auto', flexShrink: 0, width: 46 },
+ disabled && styles.slotDisabled,
+ ]}
haptic="selection"
testID={testID}
>
@@ -76,23 +82,28 @@ function NavSlot({ label, Icon, onPress, disabled = false, testID }: NavSlotProp
}
interface SelectedSlotProps {
+ onPress: () => void
label: string
Icon: ComponentType<IconProps>
testID: string
}
-function SelectedSlot({ label, Icon, testID }: SelectedSlotProps): ReactElement {
+function SelectedSlot({ label, Icon, testID, onPress }: SelectedSlotProps): ReactElement {
+ const colors = useColors()
const styles = useStyles()
+ const { rail } = useAppLayout()
return (
- <View
- style={[styles.slot, styles.slotSelected]}
+ <Pressable44
+ onPress={onPress}
+ pressedBackground={colors.background}
+ style={[styles.slot, styles.slotSelected, rail && { flexBasis: 'auto', flexShrink: 0, width: 46 }]}
accessibilityRole="tab"
accessibilityLabel={label}
accessibilityState={{ selected: true }}
testID={testID}
>
<Icon size={iconSizes.navigation} />
- </View>
+ </Pressable44>
)
}
@@ -108,31 +119,73 @@ export function BottomBar({
const { colors, shadows } = useTheme()
const styles = useStyles()
const insets = useScreenInsets()
+ const { rail, railSide, contentWidth } = useAppLayout()
return (
- <View style={[styles.bar, { paddingBottom: bottomOffset(insets, 34) }]}>
- <BlurEdge direction="up" solid={0.6} />
- <FadeEdge direction="up" solid={0.6} opacity={layout.chromeTint} />
- <View style={[styles.nav, shadows.floatingBar]} accessibilityRole="tablist">
+ <View
+ style={[
+ styles.bar,
+ { paddingBottom: bottomOffset(insets, 34) },
+ rail && {
+ top: insets.top + 24,
+ bottom: insets.bottom + 16,
+ left: railSide === 'left' ? 8 : contentWidth + 8,
+ right: railSide === 'right' ? 8 : undefined,
+ width: 64,
+ paddingHorizontal: 0,
+ paddingTop: 0,
+ paddingBottom: 0,
+ flexDirection: 'column',
+ justifyContent: 'flex-end',
+ },
+ ]}
+ >
+ {rail ? null : (
+ <>
+ <BlurEdge direction="up" solid={0.6} />
+ <FadeEdge direction="up" solid={0.6} opacity={layout.chromeTint} />
+ </>
+ )}
+ <View
+ style={[
+ styles.nav,
+ !rail && styles.bottomNav,
+ shadows.floatingBar,
+ rail && {
+ height: (3 + pins.length) * 52 + 12,
+ width: 64,
+ flexDirection: 'column',
+ paddingVertical: 8,
+ gap: 6,
+ },
+ ]}
+ accessibilityRole="tablist"
+ >
{selected === 'home' ? (
- <SelectedSlot label="Home" Icon={HomeIcon} testID="inbox-nav-home" />
+ <SelectedSlot onPress={onHome} label="Home" Icon={HomeIcon} testID="inbox-nav-home" />
) : (
<NavSlot label="Home" Icon={HomeIcon} onPress={onHome} testID="inbox-nav-home" />
)}
{/* The testID keeps its old name because the Argent flows select this slot by it. */}
{selected === 'chats' ? (
- <SelectedSlot label="Chats" Icon={SpacesIcon} testID="inbox-nav-chat" />
+ <SelectedSlot onPress={onChats} label="Chats" Icon={SpacesIcon} testID="inbox-nav-chat" />
) : (
<NavSlot label="Chats" Icon={SpacesIcon} onPress={onChats} testID="inbox-nav-chat" />
)}
{selected === 'views' ? (
- <SelectedSlot label="Views" Icon={ViewsIcon} testID="inbox-nav-views" />
+ <SelectedSlot onPress={onViews} label="Views" Icon={ViewsIcon} testID="inbox-nav-views" />
) : (
<NavSlot label="Views" Icon={ViewsIcon} onPress={onViews} testID="inbox-nav-views" />
)}
{pins.map((pin) => {
const { label, Icon } = PIN_SLOTS[pin]
return selected === pin ? (
- <SelectedSlot key={pin} label={label} Icon={Icon} testID={`nav-pin-${pin}`} />
+ <SelectedSlot
+ onPress={() => onPin(pin)}
+ key={pin}
+ label={label}
+ Icon={Icon}
+ testID={`nav-pin-${pin}`}
+ />
) : (
<NavSlot
key={pin}
@@ -144,17 +197,23 @@ export function BottomBar({
)
})}
</View>
- <Pressable44
- onPress={onNewChat}
- accessibilityLabel="Chat"
- pressedBackground={colors.inkHover}
- style={[styles.chat, shadows.fab]}
- haptic="selection"
- testID="inbox-chat"
- >
- <ComposeIcon size={iconSizes.navigation} color={colors.onInk} />
- <Text style={styles.chatText}>Chat</Text>
- </Pressable44>
+ {onNewChat ? (
+ <Pressable44
+ onPress={onNewChat}
+ accessibilityLabel="Chat"
+ pressedBackground={colors.inkHover}
+ style={[
+ styles.chat,
+ shadows.fab,
+ rail && { width: 56, paddingLeft: 0, paddingRight: 0, justifyContent: 'center' },
+ ]}
+ haptic="selection"
+ testID="inbox-chat"
+ >
+ <ComposeIcon size={iconSizes.navigation} color={colors.onInk} />
+ {rail ? null : <Text style={styles.chatText}>Chat</Text>}
+ </Pressable44>
+ ) : null}
</View>
)
}
@@ -175,9 +234,6 @@ const useStyles = createStyles(({ colors }) => ({
},
// 54pt content box plus 4pt padding and a 1pt border on each side.
nav: {
- flex: 1,
- height: 64,
- flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
backgroundColor: colors.surface,
@@ -187,6 +243,11 @@ const useStyles = createStyles(({ colors }) => ({
paddingVertical: 4,
paddingHorizontal: 6,
},
+ bottomNav: {
+ flex: 1,
+ height: 64,
+ flexDirection: 'row',
+ },
// Slots shrink below the handoff's 72pt on phones narrower than the 402pt prototype frame, never below 44pt.
slot: {
flexBasis: 72,
diff --git a/products/mobile/src/features/tabs/NavMenu.tsx b/products/mobile/src/features/tabs/NavMenu.tsx
index d5bdab5e25eb..2cfd5fbbb9d0 100644
--- a/products/mobile/src/features/tabs/NavMenu.tsx
+++ b/products/mobile/src/features/tabs/NavMenu.tsx
@@ -1,6 +1,5 @@
import { type ComponentType, type ReactElement, useEffect, useState } from 'react'
-import { Text, useWindowDimensions, View } from 'react-native'
-
+import { Text, View } from 'react-native'
import { useAuthStore } from '@/auth/authStore'
import { ProjectSheet } from '@/features/projects/ProjectSheet'
import { track } from '@/lib/analytics'
@@ -15,6 +14,7 @@ import type { IconProps } from '@/ui/icons/types'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { iconSizes, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { topOffset, useScreenInsets } from '@/ui/useScreenInsets'
import { SignOutConfirm } from '../settings/SignOutConfirm'
@@ -82,9 +82,9 @@ export function NavMenu({
const colors = useColors()
const styles = useStyles()
const insets = useScreenInsets()
- const { width: windowWidth } = useWindowDimensions()
+ const { width: windowWidth } = useSceneDimensions()
// The handoff's 75% width is the content box; padding and border add 22pt.
- const width = Math.round(windowWidth * 0.75) + 22
+ const width = Math.min(400, Math.round(windowWidth * 0.75) + 22)
const [pickingProject, setPickingProject] = useState(false)
useEffect(() => {
diff --git a/products/mobile/src/features/tabs/ReportNavigation.tsx b/products/mobile/src/features/tabs/ReportNavigation.tsx
new file mode 100644
index 000000000000..b5c4de5f7a26
--- /dev/null
+++ b/products/mobile/src/features/tabs/ReportNavigation.tsx
@@ -0,0 +1,22 @@
+import { useRouter } from 'expo-router'
+import type { ReactElement } from 'react'
+
+import { useMobileProductFlags } from '@/lib/featureFlags'
+import { BottomBar } from './BottomBar'
+import { useNavPins } from './navPinStore'
+
+export function ReportNavigation(): ReactElement {
+ const router = useRouter()
+ const pins = useNavPins()
+ const flags = useMobileProductFlags()
+ return (
+ <BottomBar
+ selected="home"
+ pins={pins.filter((pin) => flags[pin])}
+ onHome={() => router.navigate('/inbox')}
+ onChats={() => router.navigate('/chats')}
+ onViews={() => router.navigate('/views')}
+ onPin={(pin) => router.navigate(pin === 'errors' ? '/errors' : '/replay')}
+ />
+ )
+}
diff --git a/products/mobile/src/features/tabs/TabsHeader.tsx b/products/mobile/src/features/tabs/TabsHeader.tsx
index 14358cfd962a..c8a248580a09 100644
--- a/products/mobile/src/features/tabs/TabsHeader.tsx
+++ b/products/mobile/src/features/tabs/TabsHeader.tsx
@@ -1,6 +1,7 @@
import type { ReactElement } from 'react'
import { Text, View } from 'react-native'
+import { INBOX_PANE_WIDTH } from '@/ui/adaptiveLayout'
import { BlurEdge } from '@/ui/BlurEdge'
import { FadeEdge } from '@/ui/FadeEdge'
import { AnimatedLogomark } from '@/ui/icons/AnimatedLogomark'
@@ -11,6 +12,7 @@ import { Pressable44 } from '@/ui/Pressable44'
import { RefreshHint } from '@/ui/RefreshHint'
import { createStyles, useColors } from '@/ui/theme'
import { layout, radii, type } from '@/ui/tokens'
+import { useAppLayout } from '@/ui/useAppLayout'
import { topOffset, useScreenInsets } from '@/ui/useScreenInsets'
import type { TabHeaderSlot, TabKey } from './tabHeaderStore'
@@ -58,6 +60,7 @@ export function TabsHeader({ tab, slot, onMore }: TabsHeaderProps): ReactElement
const colors = useColors()
const styles = useStyles()
const insets = useScreenInsets()
+ const { paired } = useAppLayout()
const editing = slot?.editing ?? null
const status = slot?.status ?? null
const hint = editing ? null : (slot?.hint ?? null)
@@ -71,6 +74,7 @@ export function TabsHeader({ tab, slot, onMore }: TabsHeaderProps): ReactElement
{
paddingTop: topOffset(insets, HEADER_TOP),
paddingBottom: withStatus ? STATUS_PADDING : HEADER_FADE,
+ maxWidth: tab === 'inbox' && paired ? INBOX_PANE_WIDTH : undefined,
},
]}
>
diff --git a/products/mobile/src/features/tabs/TabsLayout.test.tsx b/products/mobile/src/features/tabs/TabsLayout.test.tsx
index e9f486e94df8..41bc2e8832bd 100644
--- a/products/mobile/src/features/tabs/TabsLayout.test.tsx
+++ b/products/mobile/src/features/tabs/TabsLayout.test.tsx
@@ -1,6 +1,6 @@
import { act, fireEvent, renderRouter, screen, within } from 'expo-router/testing-library'
import { type ReactElement, useState } from 'react'
-import { Button, Text, View } from 'react-native'
+import { Button, Dimensions, Text, View } from 'react-native'
import { setAnalyticsClient } from '@/lib/analytics'
import { FEATURE_FLAGS, setFeatureFlags } from '@/lib/featureFlags'
@@ -10,6 +10,7 @@ import { restoreNavPins, setNavPinned, useNavPinStore } from './navPinStore'
import { TabsLayout } from './TabsLayout'
import { type TabHeaderSlot, type TabKey, useTabHeader, useTabHeaderStore } from './tabHeaderStore'
+jest.mock('react-native-keyboard-controller', () => jest.requireActual('react-native-keyboard-controller/jest'))
jest.mock('react-native-worklets', () => jest.requireActual('react-native-worklets/src/mock'))
// The router's testing library mocks Reanimated with this module after the hoisted mocks run, so the patch goes here.
jest.mock('react-native-reanimated/mock', () => ({
@@ -92,6 +93,8 @@ function InboxWithMenuStub(): ReactElement {
)
}
+const ORIGINAL_WINDOW = Dimensions.get('window')
+
describe('TabsLayout', () => {
beforeEach(() => {
restoreNavPins([])
@@ -99,6 +102,7 @@ describe('TabsLayout', () => {
})
afterEach(() => {
+ act(() => Dimensions.set({ window: ORIGINAL_WINDOW }))
setAnalyticsClient(null)
setFeatureFlags({})
})
@@ -157,7 +161,13 @@ describe('TabsLayout', () => {
expect(useNavPinStore.getState().pins).toEqual([pin])
})
- test('switches between Inbox, Chats and Views under one bar that keeps the /inbox, /chats and /views URLs', () => {
+ test.each([
+ { width: 402, height: 874 },
+ { width: 951, height: 669 },
+ { width: 669, height: 951 },
+ ])('switches Inbox, Chats and Views under one bar at $width × $height', ({ width, height }) => {
+ const previous = Dimensions.get('window')
+ Dimensions.set({ window: { ...previous, width, height } })
const capture = jest.fn()
setAnalyticsClient({ capture, identify: jest.fn(), reset: jest.fn() })
const router = renderRouter(
diff --git a/products/mobile/src/features/tabs/TabsLayout.tsx b/products/mobile/src/features/tabs/TabsLayout.tsx
index bf4950c54c05..6368aed7086e 100644
--- a/products/mobile/src/features/tabs/TabsLayout.tsx
+++ b/products/mobile/src/features/tabs/TabsLayout.tsx
@@ -1,7 +1,7 @@
import { useRouter } from 'expo-router'
import { type BottomTabBarProps, Tabs } from 'expo-router/js-tabs'
import { type ReactElement, useEffect, useLayoutEffect, useMemo, useState } from 'react'
-import { Linking } from 'react-native'
+import { Linking, View } from 'react-native'
import { useAuthStore } from '@/auth/authStore'
import { useProjectScope } from '@/auth/useProjectScope'
import { useViewer } from '@/auth/useViewer'
@@ -12,8 +12,11 @@ import { navListWebUrl } from '@/features/views/webLinks'
import { track } from '@/lib/analytics'
import { useMobileProductFlags } from '@/lib/featureFlags'
import { safeHttpsUrl } from '@/lib/urls'
-import { OverlayHost } from '@/ui/OverlayPortal'
+import { NAV_RAIL_WIDTH } from '@/ui/adaptiveLayout'
+import { OverlayHost, OverlayPortal } from '@/ui/OverlayPortal'
+import { SceneFrame } from '@/ui/SceneFrame'
import { useColors } from '@/ui/theme'
+import { useAppLayout } from '@/ui/useAppLayout'
import { useExitDemo, useSignOutAction } from '../settings/useSignOut'
import { BottomBar, type BottomBarSlot } from './BottomBar'
@@ -71,15 +74,19 @@ function TabBar({ state, navigation }: BottomTabBarProps): ReactElement {
useViewsOpenedEvent(focused === 'views')
return (
- <BottomBar
- selected={selectedSlot(tab)}
- pins={shownPins}
- onHome={() => goTo('inbox')}
- onChats={() => goTo('chats')}
- onViews={() => goTo('views')}
- onPin={goTo}
- onNewChat={() => router.push({ pathname: '/chat', params: { entry: 'compose' satisfies ChatSheetEntry } })}
- />
+ <OverlayPortal>
+ <BottomBar
+ selected={selectedSlot(tab)}
+ pins={shownPins}
+ onHome={() => goTo('inbox')}
+ onChats={() => goTo('chats')}
+ onViews={() => goTo('views')}
+ onPin={goTo}
+ onNewChat={() =>
+ router.push({ pathname: '/chat', params: { entry: 'compose' satisfies ChatSheetEntry } })
+ }
+ />
+ </OverlayPortal>
)
}
@@ -177,24 +184,35 @@ function TabsChrome(): ReactElement {
// above them. The header has no zIndex for the same reason: drawing order alone puts it between the two.
export function TabsLayout(): ReactElement {
const colors = useColors()
+ const { rail, railSide } = useAppLayout()
return (
<OverlayHost>
- <Tabs
- tabBar={renderTabBar}
- backBehavior="firstRoute"
- screenOptions={{
- headerShown: false,
- sceneStyle: { backgroundColor: colors.background },
+ <View
+ style={{
+ flex: 1,
+ paddingLeft: rail && railSide === 'left' ? NAV_RAIL_WIDTH : 0,
+ paddingRight: rail && railSide === 'right' ? NAV_RAIL_WIDTH : 0,
}}
>
- <Tabs.Screen name="inbox" />
- <Tabs.Screen name="chats" />
- <Tabs.Screen name="views" />
- {/* Always registered; the bar shows a slot only for a pinned list. */}
- <Tabs.Screen name="errors" />
- <Tabs.Screen name="replay" />
- </Tabs>
- <TabsChrome />
+ <SceneFrame>
+ <Tabs
+ tabBar={renderTabBar}
+ backBehavior="firstRoute"
+ screenOptions={{
+ headerShown: false,
+ sceneStyle: { backgroundColor: colors.background },
+ }}
+ >
+ <Tabs.Screen name="inbox" />
+ <Tabs.Screen name="chats" />
+ <Tabs.Screen name="views" />
+ {/* Always registered; the bar shows a slot only for a pinned list. */}
+ <Tabs.Screen name="errors" />
+ <Tabs.Screen name="replay" />
+ </Tabs>
+ <TabsChrome />
+ </SceneFrame>
+ </View>
</OverlayHost>
)
}
diff --git a/products/mobile/src/features/verdict/VerdictSheet.tsx b/products/mobile/src/features/verdict/VerdictSheet.tsx
index c09562f54fab..1b61d5fda757 100644
--- a/products/mobile/src/features/verdict/VerdictSheet.tsx
+++ b/products/mobile/src/features/verdict/VerdictSheet.tsx
@@ -1,9 +1,8 @@
import { type ReactElement, useEffect, useMemo, useRef, useState } from 'react'
-import { ActivityIndicator, type ScrollView, Text, TextInput, useWindowDimensions, View } from 'react-native'
+import { ActivityIndicator, type ScrollView, Text, TextInput, View } from 'react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
import { useReanimatedKeyboardAnimation } from 'react-native-keyboard-controller'
-import Animated, { useAnimatedStyle } from 'react-native-reanimated'
-
+import Animated from 'react-native-reanimated'
import { actionErrorMessage } from '@/lib/errors'
import { VERDICT_NOTE_MAX_LENGTH } from '@/model/verdictReasons'
import { BottomSheet } from '@/ui/BottomSheet'
@@ -11,6 +10,7 @@ import { CheckIcon } from '@/ui/icons/CheckIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useTheme } from '@/ui/theme'
import { iconSizes, inputReset, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import type { VerdictCopy } from './verdictCopy'
@@ -37,9 +37,11 @@ export function VerdictSheet<Reason extends string>({
}: VerdictSheetProps<Reason>): ReactElement {
const styles = useStyles()
const { colors, scheme } = useTheme()
- const { height } = useWindowDimensions()
+ const { height } = useSceneDimensions()
+ const compact = height < 480
const keyboard = useReanimatedKeyboardAnimation()
const scroll = useRef<ScrollView>(null)
+ const noteInput = useRef<TextInput>(null)
const listGesture = useMemo(() => Gesture.Native(), [])
const [reason, setReason] = useState<Reason | undefined>(undefined)
const [note, setNote] = useState('')
@@ -53,10 +55,6 @@ export function VerdictSheet<Reason extends string>({
}
}, [visible])
- // The sheet lifts with the keyboard, and the list gives up the keyboard's height so the button stays on screen.
- const keyboardStyle = useAnimatedStyle(() => ({ paddingBottom: Math.max(-keyboard.height.value, 0) }))
- const listStyle = useAnimatedStyle(() => ({ maxHeight: Math.max(height * 0.5 + keyboard.height.value, 120) }))
-
const canConfirm = reason !== undefined && !pending
const confirm = (): void => {
if (reason === undefined || pending) {
@@ -66,32 +64,45 @@ export function VerdictSheet<Reason extends string>({
onConfirm(reason, note).catch((confirmError: unknown) => setError(actionErrorMessage(confirmError)))
}
+ const heading = (
+ <>
+ <Text style={styles.title} accessibilityRole="header" numberOfLines={3}>
+ {copy.title}
+ </Text>
+ <Text style={styles.description}>{copy.description}</Text>
+ {error ? (
+ <Text style={styles.error} accessibilityRole="alert" testID={`${testID}-error`}>
+ {error}
+ </Text>
+ ) : null}
+ </>
+ )
+
return (
<BottomSheet
visible={visible}
onClose={onClose}
paddingHorizontal={20}
scrollGesture={listGesture}
+ keyboardHeight={keyboard.height}
accessibilityLabel={copy.title}
testID={testID}
>
- <Animated.View style={keyboardStyle}>
- <Text style={styles.title} accessibilityRole="header" numberOfLines={3}>
- {copy.title}
- </Text>
- <Text style={styles.description}>{copy.description}</Text>
- {error ? (
- <Text style={styles.error} accessibilityRole="alert" testID={`${testID}-error`}>
- {error}
- </Text>
- ) : null}
- <View style={styles.list}>
+ <View style={styles.content}>
+ {compact ? null : heading}
+ <View style={[styles.list, compact && { marginTop: 4 }]}>
<GestureDetector gesture={listGesture}>
<Animated.ScrollView
ref={scroll}
keyboardShouldPersistTaps="handled"
- style={[styles.scroll, listStyle]}
+ onLayout={() => {
+ if (noteInput.current?.isFocused()) {
+ scroll.current?.scrollToEnd({ animated: false })
+ }
+ }}
+ style={[styles.scroll, { maxHeight: Math.max(height * 0.5, 120) }]}
>
+ {compact ? heading : null}
<Text style={styles.fieldLabel}>Reason</Text>
<View accessibilityRole="radiogroup">
{options.map((option) => {
@@ -117,17 +128,19 @@ export function VerdictSheet<Reason extends string>({
<Text style={[styles.fieldLabel, styles.noteLabel]}>Note</Text>
<Text style={styles.noteInfo}>{copy.noteInfo}</Text>
<TextInput
+ ref={noteInput}
value={note}
onChangeText={setNote}
onFocus={() => scroll.current?.scrollToEnd({ animated: true })}
editable={!pending}
multiline
+ disableFullscreenUI
maxLength={VERDICT_NOTE_MAX_LENGTH}
placeholder={copy.notePlaceholder}
placeholderTextColor={colors.tertiary}
keyboardAppearance={scheme}
textAlignVertical="top"
- style={styles.note}
+ style={[styles.note, compact && styles.noteCompact]}
accessibilityLabel="Note"
testID={`${testID}-note`}
/>
@@ -141,6 +154,7 @@ export function VerdictSheet<Reason extends string>({
pressedBackground={colors.inkHover}
style={[
styles.confirm,
+ compact && { marginTop: 4, height: 44 },
{ backgroundColor: canConfirm || pending ? colors.ink : colors.disabledFill },
]}
testID={`${testID}-confirm`}
@@ -153,12 +167,16 @@ export function VerdictSheet<Reason extends string>({
</Text>
)}
</Pressable44>
- </Animated.View>
+ </View>
</BottomSheet>
)
}
const useStyles = createStyles(({ colors }) => ({
+ content: {
+ flexShrink: 1,
+ minHeight: 0,
+ },
title: {
...type.sheetTitle,
color: colors.ink,
@@ -179,9 +197,12 @@ const useStyles = createStyles(({ colors }) => ({
},
list: {
marginTop: 12,
+ flexShrink: 1,
+ minHeight: 0,
},
scroll: {
flexGrow: 0,
+ flexShrink: 1,
},
fieldLabel: {
...type.bodySmallStrong,
@@ -225,6 +246,13 @@ const useStyles = createStyles(({ colors }) => ({
borderColor: colors.hairline,
backgroundColor: colors.background,
},
+ noteCompact: {
+ height: 44,
+ minHeight: 44,
+ maxHeight: 44,
+ paddingTop: 8,
+ paddingBottom: 8,
+ },
confirm: {
marginTop: 16,
height: 52,
diff --git a/products/mobile/src/features/views/about/AboutSheet.tsx b/products/mobile/src/features/views/about/AboutSheet.tsx
index 91f8587b3b45..0fba54219dfc 100644
--- a/products/mobile/src/features/views/about/AboutSheet.tsx
+++ b/products/mobile/src/features/views/about/AboutSheet.tsx
@@ -1,5 +1,5 @@
import { type ReactElement, type ReactNode, useEffect, useMemo, useRef, useState } from 'react'
-import { Linking, ScrollView, Text, useWindowDimensions, View } from 'react-native'
+import { Linking, ScrollView, Text, View } from 'react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
import { safeHttpsUrl } from '@/lib/urls'
import { useNow } from '@/lib/useNow'
@@ -9,6 +9,7 @@ import { RefreshIcon } from '@/ui/icons/RefreshIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors, useTheme } from '@/ui/theme'
import { fonts, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { trackViewOpenedInWeb } from '../analytics'
import { forceAllowedAt, HINT_MS, refreshHintText } from '../freshness'
@@ -62,7 +63,7 @@ function AboutBody({
const styles = useStyles()
const snapshot = useLiveSnapshot(source)
const now = useNow(30_000)
- const { height } = useWindowDimensions()
+ const { height } = useSceneDimensions()
const { scope } = useViewsContext()
const updating = useItemUpdating(source.itemKey)
const [hint, setHint] = useState<string | null>(null)
diff --git a/products/mobile/src/features/views/fullScreen/FullScreenChart.tsx b/products/mobile/src/features/views/fullScreen/FullScreenChart.tsx
index a012e8a37f87..3aba2e655637 100644
--- a/products/mobile/src/features/views/fullScreen/FullScreenChart.tsx
+++ b/products/mobile/src/features/views/fullScreen/FullScreenChart.tsx
@@ -37,7 +37,6 @@ import {
import { useViewsContext } from '../useViewsContext'
import { freshnessKey, useSnapshot, viewsKeys } from '../viewsCache'
-const MIN_CHART_HEIGHT = 220
/** The legend takes the rows it needs, up to this share of the space; past that it scrolls. */
const MAX_LEGEND_SHARE = 0.38
const LEGEND_ROW_HEIGHT = 44
@@ -232,7 +231,7 @@ function TimeSeries({ snapshot, source, rangeText }: TimeSeriesProps): ReactElem
const legendHeight = many
? Math.min(model.series.length * LEGEND_ROW_HEIGHT + 2, area * MAX_LEGEND_SHARE) + LEGEND_GAP
: 0
- const chartHeight = Math.max(MIN_CHART_HEIGHT, Math.round(area - legendHeight))
+ const chartHeight = Math.max(1, Math.round(area - legendHeight))
return (
<View style={styles.fill} onLayout={(event) => setArea(event.nativeEvent.layout.height)}>
{area > 0 && kind ? (
diff --git a/products/mobile/src/features/views/list/ChooseTileSheet.tsx b/products/mobile/src/features/views/list/ChooseTileSheet.tsx
index f77586b0acaa..ecdfc5a6b996 100644
--- a/products/mobile/src/features/views/list/ChooseTileSheet.tsx
+++ b/products/mobile/src/features/views/list/ChooseTileSheet.tsx
@@ -1,14 +1,14 @@
import { type ReactElement, useEffect, useMemo, useRef, useState } from 'react'
-import { ActivityIndicator, ScrollView, Text, useWindowDimensions, View } from 'react-native'
+import { ActivityIndicator, ScrollView, Text, View } from 'react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
import Svg, { Path, Rect, Text as SvgText } from 'react-native-svg'
-
import type { DashboardTileView, InsightSnapshot, PinView } from '@/model/views'
import { BottomSheet } from '@/ui/BottomSheet'
import { CheckIcon } from '@/ui/icons/CheckIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { motion, radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { type TileSheetEntry, trackPinTileSheetClosed } from '../analytics'
import { insightQueryKey, tileTarget } from '../items'
@@ -71,7 +71,7 @@ function TileSheet({ target, visible, onClose, onChoose }: TileSheetProps): Reac
const colors = useColors()
const styles = useStyles()
const { pin, mode, chooseFirst, entry } = target
- const { height: windowHeight } = useWindowDimensions()
+ const { height: windowHeight } = useSceneDimensions()
const listGesture = useMemo(() => Gesture.Native(), [])
const { dashboard, retry } = useDashboardTiles(pin.ref)
const [chosen, setChosen] = useState<number | null>(pin.display.tileId ?? null)
diff --git a/products/mobile/src/features/views/list/PinScrollAnchor.test.ts b/products/mobile/src/features/views/list/PinScrollAnchor.test.ts
new file mode 100644
index 000000000000..59657bc956c4
--- /dev/null
+++ b/products/mobile/src/features/views/list/PinScrollAnchor.test.ts
@@ -0,0 +1,103 @@
+import { PinScrollAnchor, pinAnchorOffset } from './PinScrollAnchor'
+
+test('retains an accepted approximate scroll until measured native offset correction completes', () => {
+ const anchor = new PinScrollAnchor()
+ const scroll = jest.fn(() => true)
+ anchor.start('pin-49')
+
+ anchor.attempt(scroll)
+ expect(anchor.target).toBe('pin-49')
+ anchor.measure(['pin-47', 'pin-48'], anchor.version)
+ anchor.attempt(scroll)
+ expect(anchor.target).toBe('pin-49')
+
+ anchor.measure(['pin-49', 'pin-50'], anchor.version)
+ anchor.attempt(() => false)
+ expect(anchor.target).toBe('pin-49')
+ anchor.attempt(scroll)
+ expect(anchor.target).toBeNull()
+ expect(scroll.mock.calls).toEqual([['pin-49'], ['pin-49'], ['pin-49']])
+})
+
+test('keeps a measured target when synchronous index failure requires another exact scroll', () => {
+ const anchor = new PinScrollAnchor()
+ anchor.start('pin-49')
+ anchor.measure(['pin-49'], anchor.version)
+ anchor.attempt(() => {
+ anchor.fail()
+ return true
+ })
+ expect(anchor.target).toBe('pin-49')
+
+ anchor.attempt(() => true)
+ expect(anchor.target).toBeNull()
+})
+
+test.each(['drag or unmount', 'new layout'] as const)('%s cancels stale restoration work', (reason) => {
+ const anchor = new PinScrollAnchor()
+ anchor.start('pin-49')
+ const previousVersion = anchor.version
+ anchor.attempt(() => true)
+
+ if (reason === 'new layout') {
+ anchor.start('pin-49')
+ } else {
+ anchor.cancel()
+ }
+ anchor.measure(['pin-49'], previousVersion)
+ const retry = jest.fn(() => true)
+ anchor.attempt(retry)
+
+ if (reason === 'new layout') {
+ expect(anchor.target).toBe('pin-49')
+ anchor.measure(['pin-49'], anchor.version)
+ anchor.attempt(retry)
+ expect(anchor.target).toBeNull()
+ } else {
+ expect(retry).not.toHaveBeenCalled()
+ expect(anchor.target).toBeNull()
+ }
+})
+
+test.each([
+ [500, 200, 2000, 600, 700],
+ [500, -800, 2000, 600, 0],
+ [1300, 200, 2000, 600, 1400],
+ [0, 80, 200, 600, 0],
+])('keeps viewport correction within scrollable bounds %#', (offset, delta, content, viewport, expected) => {
+ expect(pinAnchorOffset(offset, delta, content, viewport)).toBe(expected)
+})
+
+test('late row layout rechecks a verified anchor in the same layout generation', () => {
+ const anchor = new PinScrollAnchor()
+ anchor.start('pin-49')
+ const version = anchor.version
+ anchor.measure(['pin-49'], version)
+ anchor.attempt(() => true)
+ expect(anchor.target).toBeNull()
+
+ anchor.recheck()
+ expect(anchor.target).toBe('pin-49')
+ expect(anchor.version).toBe(version)
+ expect(anchor.isMeasured).toBe(true)
+ anchor.attempt(() => false)
+ expect(anchor.target).toBe('pin-49')
+ anchor.attempt(() => true)
+ expect(anchor.target).toBeNull()
+})
+
+test.each(['cancel', 'new layout'] as const)(
+ '%s prevents a late measurement from restoring a completed anchor',
+ (reason) => {
+ const anchor = new PinScrollAnchor()
+ anchor.start('pin-49')
+ anchor.measure(['pin-49'], anchor.version)
+ anchor.attempt(() => true)
+
+ if (reason === 'cancel') anchor.cancel()
+ else anchor.start('pin-60')
+ anchor.recheck()
+ expect(anchor.target).toBe(reason === 'cancel' ? null : 'pin-60')
+ expect(anchor.isMeasured).toBe(false)
+ }
+)
diff --git a/products/mobile/src/features/views/list/PinScrollAnchor.ts b/products/mobile/src/features/views/list/PinScrollAnchor.ts
new file mode 100644
index 000000000000..6a7975a600db
--- /dev/null
+++ b/products/mobile/src/features/views/list/PinScrollAnchor.ts
@@ -0,0 +1,61 @@
+export class PinScrollAnchor {
+ private pending: string | null = null
+ private completed: string | null = null
+ private generation = 0
+ private failed = false
+ private measured = false
+
+ get target(): string | null {
+ return this.pending
+ }
+
+ get isMeasured(): boolean {
+ return this.measured
+ }
+
+ get version(): number {
+ return this.generation
+ }
+
+ start(target: string | null): void {
+ this.generation++
+ this.pending = target
+ this.completed = null
+ this.measured = false
+ }
+
+ recheck(): void {
+ if (this.pending === null) this.pending = this.completed
+ }
+
+ cancel(): void {
+ this.start(null)
+ }
+
+ measure(shortcutIds: readonly string[], version: number): void {
+ if (version === this.generation && this.pending !== null && shortcutIds.includes(this.pending)) {
+ this.measured = true
+ }
+ }
+
+ fail(): void {
+ this.failed = true
+ }
+
+ attempt(scroll: (target: string) => boolean): void {
+ const target = this.pending
+ if (target === null) return
+ const generation = this.generation
+ const measured = this.measured
+ this.failed = false
+ const sent = scroll(target)
+ if (sent && measured && !this.failed && this.generation === generation) {
+ this.completed = target
+ this.pending = null
+ }
+ }
+}
+
+export function pinAnchorOffset(offset: number, delta: number, contentHeight: number, viewportHeight: number): number {
+ return Math.max(0, Math.min(Math.max(0, contentHeight - viewportHeight), offset + delta))
+}
diff --git a/products/mobile/src/features/views/list/ViewsMenu.tsx b/products/mobile/src/features/views/list/ViewsMenu.tsx
index be39a19cc4c4..a681d0a51872 100644
--- a/products/mobile/src/features/views/list/ViewsMenu.tsx
+++ b/products/mobile/src/features/views/list/ViewsMenu.tsx
@@ -1,7 +1,6 @@
import { type ReactElement, type ReactNode, useState } from 'react'
-import { type LayoutChangeEvent, Text, useWindowDimensions, View } from 'react-native'
+import { type LayoutChangeEvent, Text, View } from 'react-native'
import { useSafeAreaFrame } from 'react-native-safe-area-context'
-
import { placeContextMenu, type RowAnchor } from '@/features/inbox/contextMenuPlacement'
import type { PinDisplayMode, PinView, ViewRef } from '@/model/views'
import { FloatingCard } from '@/ui/FloatingCard'
@@ -12,6 +11,7 @@ import { PinIcon } from '@/ui/icons/PinIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { layout, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { bottomOffset, topOffset, useScreenInsets } from '@/ui/useScreenInsets'
import { TABS_HEADER_BOTTOM } from '../../tabs/TabsHeader'
@@ -42,7 +42,7 @@ export function MenuCard({
}: MenuCardProps): ReactElement {
const styles = useStyles()
const insets = useScreenInsets()
- const { width: windowWidth } = useWindowDimensions()
+ const { width: windowWidth } = useSceneDimensions()
// The overlay covers the full screen, which on Android edge-to-edge includes the navigation bar.
const { height: screenHeight } = useSafeAreaFrame()
const [height, setHeight] = useState<number | null>(null)
diff --git a/products/mobile/src/features/views/list/ViewsScreen.tsx b/products/mobile/src/features/views/list/ViewsScreen.tsx
index 00f8286404dd..bc70edd7f6d9 100644
--- a/products/mobile/src/features/views/list/ViewsScreen.tsx
+++ b/products/mobile/src/features/views/list/ViewsScreen.tsx
@@ -1,7 +1,6 @@
import { useIsFocused, useRouter } from 'expo-router'
-import { type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { type ReactElement, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
import { Linking, Platform, RefreshControl, SectionList, Text, View, type ViewToken } from 'react-native'
-
import type { RowAnchor } from '@/features/inbox/contextMenuPlacement'
import { useMobileProductFlags } from '@/lib/featureFlags'
import { useNow } from '@/lib/useNow'
@@ -16,6 +15,7 @@ import { SearchField } from '@/ui/SearchField'
import { StateView } from '@/ui/StateView'
import { createStyles, useColors } from '@/ui/theme'
import { layout, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { bottomOffset, topOffset, useScreenInsets } from '@/ui/useScreenInsets'
import { NavPinMenu } from '../../tabs/NavPinMenu'
import { changeNavPin } from '../../tabs/navPinActions'
@@ -52,6 +52,7 @@ import { EditPinsList } from './EditPinsList'
import { EmptyPins } from './EmptyPins'
import { PinCard } from './PinCard'
import { PinHint } from './PinHint'
+import { PinScrollAnchor, pinAnchorOffset } from './PinScrollAnchor'
import { usePinFlows } from './usePinFlows'
import { type GroupPosition, groupPosition, ViewRow } from './ViewRow'
import { PinMenu, RowMenu } from './ViewsMenu'
@@ -62,6 +63,7 @@ type ListView = RecentView | BrowseRow
type ListItem =
| { type: 'pin'; key: string; shortcutId: string; pin: PinView; index: number; last: boolean }
+ | { type: 'pin-pair'; key: string; items: Extract<ListItem, { type: 'pin' }>[] }
| { type: 'pin-hint'; key: string; last: boolean }
| { type: 'empty-pins'; key: string }
| { type: 'note'; key: string; text: string }
@@ -152,8 +154,25 @@ function ViewsBody(): ReactElement {
const insets = useScreenInsets()
const now = useNow()
const context = useViewsContext()
+ const contentTop = topOffset(insets, TABS_HEADER_BOTTOM)
const demo = context.mode === 'demo'
const list = useViewsList()
+ const { width } = useSceneDimensions()
+ const grid = width >= 740
+ const pinAnchor = useRef({
+ grid,
+ visible: null as string | null,
+ restoration: new PinScrollAnchor(),
+ locked: false,
+ })
+ if (pinAnchor.current.grid !== grid) {
+ const target = pinAnchor.current.restoration.target ?? pinAnchor.current.visible
+ pinAnchor.current.restoration.start(target)
+ pinAnchor.current.visible = target
+ pinAnchor.current.locked = target !== null
+ pinAnchor.current.grid = grid
+ }
+ const anchorGeneration = pinAnchor.current.restoration.version
const actions = usePinActions()
const motion = useChartListMotion()
const viewport = useCanvasBudgetViewport()
@@ -172,12 +191,61 @@ function ViewsBody(): ReactElement {
const [menu, setMenu] = useState<MenuState | null>(null)
const [chooseTile, setChooseTile] = useState<ChooseTileTarget | null>(null)
const listRef = useRef<SectionList<ListItem, ListSection>>(null)
+ const scrollMetrics = useRef({ offset: 0, contentHeight: 0, viewportHeight: 0 })
+ const measuringAnchor = useRef<number | null>(null)
+ const pinRows = useRef(new Map<string, View>())
+ const anchorFrame = useRef<number | null>(null)
+ const restoreAnchor = useRef<() => void>(noop)
+ const cancelAnchorFrame = useCallback((): void => {
+ if (anchorFrame.current !== null) {
+ cancelAnimationFrame(anchorFrame.current)
+ anchorFrame.current = null
+ }
+ }, [])
+ const cancelAnchorRestore = useCallback((): void => {
+ cancelAnchorFrame()
+ measuringAnchor.current = null
+ pinAnchor.current.restoration.cancel()
+ pinAnchor.current.locked = false
+ }, [cancelAnchorFrame])
+ const scheduleAnchorRestore = useCallback((): void => {
+ if (pinAnchor.current.locked) pinAnchor.current.restoration.recheck()
+ if (!pinAnchor.current.restoration.target || anchorFrame.current !== null) return
+ anchorFrame.current = requestAnimationFrame(() => {
+ anchorFrame.current = requestAnimationFrame(() => {
+ anchorFrame.current = null
+ restoreAnchor.current()
+ })
+ })
+ }, [])
+ useEffect(() => cancelAnchorRestore, [cancelAnchorRestore])
+ const setPinRow = useCallback((shortcutIds: readonly string[], node: View | null): void => {
+ for (const id of shortcutIds) {
+ if (node) pinRows.current.set(id, node)
+ else pinRows.current.delete(id)
+ }
+ }, [])
+ const onPinLayout = useCallback(
+ (shortcutIds: readonly string[]): void => {
+ pinAnchor.current.restoration.measure(shortcutIds, anchorGeneration)
+ scheduleAnchorRestore()
+ },
+ [anchorGeneration, scheduleAnchorRestore]
+ )
const pins = list.pins.data ?? EMPTY_PINS
const edit = useEditPinsSession(pins.length)
const { editing, start: startEditing } = edit
const recent = list.recent.data ?? EMPTY_RECENT
const search = useViewsSearch(editing ? '' : text, pins, recent)
+ const anchorContent = useRef({ editing, text, searching: search.active })
+ useLayoutEffect(() => {
+ const previous = anchorContent.current
+ if (previous.editing !== editing || previous.text !== text || previous.searching !== search.active) {
+ cancelAnchorRestore()
+ }
+ anchorContent.current = { editing, text, searching: search.active }
+ }, [editing, text, search.active, cancelAnchorRestore])
const pinnedKeys = list.pinnedKeys
const hint = usePinHint({
pins: list.pins.data,
@@ -192,8 +260,23 @@ function ViewsBody(): ReactElement {
const viewable = useRef({ list: list.onViewableItemsChanged, budget: viewport.onViewableItemsChanged })
viewable.current = { list: list.onViewableItemsChanged, budget: viewport.onViewableItemsChanged }
const onViewableItemsChanged = useRef((info: { viewableItems: ViewToken[]; changed: ViewToken[] }) => {
- viewable.current.list(info)
- viewable.current.budget(info)
+ const expand = (tokens: ViewToken[]): ViewToken[] =>
+ tokens.flatMap((token) => {
+ const item = token.item as ListItem
+ return item.type === 'pin-pair'
+ ? item.items.map((pin) => ({ ...token, key: pin.key, item: pin }))
+ : [token]
+ })
+ const expanded = { viewableItems: expand(info.viewableItems), changed: expand(info.changed) }
+ if (!pinAnchor.current.restoration.target && !pinAnchor.current.locked) {
+ const firstPin = expanded.viewableItems.find((token) => (token.item as ListItem).type === 'pin')
+ pinAnchor.current.visible = firstPin
+ ? (firstPin.item as Extract<ListItem, { type: 'pin' }>).shortcutId
+ : null
+ }
+ viewable.current.list(expanded)
+ viewable.current.budget(expanded)
+ scheduleAnchorRestore()
}).current
// Row callbacks read the latest values through a ref, so they stay stable and memoized cards skip re-rendering.
@@ -460,12 +543,170 @@ function ViewsBody(): ReactElement {
return result
}, [search, pins, recent, list.pinsTruncated, now, hintTargetId, browseEntries, context.offline])
+ const displaySections = useMemo(
+ () =>
+ sections.map((section) => {
+ if (!grid) return section
+ const data: ListItem[] = []
+ for (let index = 0; index < section.data.length; index++) {
+ const first = section.data[index]
+ const second = section.data[index + 1]
+ if (
+ first?.type === 'pin' &&
+ first.pin.native &&
+ first.pin.display.mode !== 'row' &&
+ second?.type === 'pin' &&
+ second.pin.native &&
+ second.pin.display.mode !== 'row'
+ ) {
+ data.push({ type: 'pin-pair', key: `pair:${first.key}:${second.key}`, items: [first, second] })
+ index++
+ } else if (first) {
+ data.push(first)
+ }
+ }
+ return { ...section, data }
+ }),
+ [sections, grid]
+ )
+
+ const attemptAnchorRestore = useCallback((): void => {
+ const remembered = pinAnchor.current.visible
+ if (
+ pinAnchor.current.locked &&
+ remembered &&
+ !displaySections.some((section) =>
+ section.data.some((item) =>
+ item.type === 'pin'
+ ? item.shortcutId === remembered
+ : item.type === 'pin-pair' && item.items.some((pin) => pin.shortcutId === remembered)
+ )
+ )
+ ) {
+ cancelAnchorRestore()
+ }
+ pinAnchor.current.restoration.attempt((anchor) => {
+ for (let sectionIndex = 0; sectionIndex < displaySections.length; sectionIndex++) {
+ const itemIndex =
+ displaySections[sectionIndex]?.data.findIndex((item) =>
+ item.type === 'pin'
+ ? item.shortcutId === anchor
+ : item.type === 'pin-pair' && item.items.some((pin) => pin.shortcutId === anchor)
+ ) ?? -1
+ if (itemIndex >= 0) {
+ if (!listRef.current) return false
+ const showTarget = (): void => {
+ listRef.current?.scrollToLocation({
+ sectionIndex,
+ itemIndex,
+ animated: false,
+ viewOffset: contentTop,
+ })
+ }
+ const restoration = pinAnchor.current.restoration
+ const row = pinRows.current.get(anchor)
+ const nativeList = listRef.current.getScrollResponder()?.getNativeScrollRef()
+ const metrics = scrollMetrics.current
+ if (
+ restoration.isMeasured &&
+ row &&
+ nativeList &&
+ metrics.contentHeight > 0 &&
+ metrics.viewportHeight > 0
+ ) {
+ const version = restoration.version
+ if (measuringAnchor.current === version) return false
+ measuringAnchor.current = version
+ nativeList.measureInWindow(
+ (_listX: number, listY: number, listWidth: number, listHeight: number) => {
+ if (restoration.version !== version || restoration.target !== anchor) {
+ if (measuringAnchor.current === version) measuringAnchor.current = null
+ return
+ }
+ if (listWidth === 0 || listHeight === 0) {
+ measuringAnchor.current = null
+ return
+ }
+ row.measureInWindow((_rowX, rowY, rowWidth, rowHeight) => {
+ if (measuringAnchor.current === version) measuringAnchor.current = null
+ if (restoration.version !== version || restoration.target !== anchor) return
+ if (rowWidth === 0 || rowHeight === 0) {
+ showTarget()
+ return
+ }
+ const current = scrollMetrics.current
+ const offset = pinAnchorOffset(
+ current.offset,
+ rowY - listY - contentTop,
+ current.contentHeight,
+ current.viewportHeight
+ )
+ if (Math.abs(offset - current.offset) <= 1) {
+ restoration.attempt(() => true)
+ } else {
+ listRef.current?.getScrollResponder()?.scrollTo({ y: offset, animated: false })
+ scheduleAnchorRestore()
+ }
+ })
+ }
+ )
+ return false
+ }
+ showTarget()
+ return false
+ }
+ }
+ cancelAnchorRestore()
+ return false
+ })
+ }, [displaySections, contentTop, scheduleAnchorRestore, cancelAnchorRestore])
+ restoreAnchor.current = attemptAnchorRestore
+ useLayoutEffect(() => {
+ attemptAnchorRestore()
+ return cancelAnchorFrame
+ }, [attemptAnchorRestore, cancelAnchorFrame])
+
const renderItem = useCallback(
({ item }: { item: ListItem }): ReactElement | null => {
switch (item.type) {
+ case 'pin-pair':
+ return (
+ <View
+ style={{ flexDirection: 'row', gap: 16 }}
+ collapsable={false}
+ ref={(node) =>
+ setPinRow(
+ item.items.map((pin) => pin.shortcutId),
+ node
+ )
+ }
+ onLayout={() => onPinLayout(item.items.map((pin) => pin.shortcutId))}
+ >
+ {item.items.map((pin) => (
+ <View key={pin.key} style={[{ flex: 1, minWidth: 0 }, !pin.last && styles.pinGap]}>
+ <PinCard
+ pin={pin.pin}
+ index={pin.index}
+ demo={demo}
+ onOpen={openPin}
+ onMenu={openPinMenu}
+ onChooseTile={chooseTileFromCard}
+ onUnpin={unpinFromCard}
+ onPressTooltip={openPinPoint}
+ />
+ </View>
+ ))}
+ </View>
+ )
+
case 'pin':
return (
- <View style={!item.last && styles.pinGap}>
+ <View
+ style={!item.last && styles.pinGap}
+ collapsable={false}
+ ref={(node) => setPinRow([item.shortcutId], node)}
+ onLayout={() => onPinLayout([item.shortcutId])}
+ >
<PinCard
pin={item.pin}
index={item.index}
@@ -517,6 +758,8 @@ function ViewsBody(): ReactElement {
}
},
[
+ setPinRow,
+ onPinLayout,
demo,
openPin,
openPinMenu,
@@ -553,7 +796,6 @@ function ViewsBody(): ReactElement {
[startEditing, styles, colors]
)
- const contentTop = topOffset(insets, TABS_HEADER_BOTTOM)
const contentBottom = bottomOffset(insets, 120)
const { refresh } = list
const loading = list.pins.data === undefined && !list.pins.isError
@@ -632,9 +874,23 @@ function ViewsBody(): ReactElement {
body = (
<SectionList
ref={listRef}
- sections={sections}
+ sections={displaySections}
keyExtractor={keyOf}
renderItem={renderItem}
+ onScrollToIndexFailed={({ averageItemLength, index }) => {
+ if (!pinAnchor.current.restoration.target) return
+ pinAnchor.current.restoration.fail()
+ listRef.current?.getScrollResponder()?.scrollTo({ y: averageItemLength * index, animated: false })
+ }}
+ onContentSizeChange={(_width, height) => {
+ scrollMetrics.current.contentHeight = height
+ scheduleAnchorRestore()
+ }}
+ onLayout={(event) => {
+ scrollMetrics.current.viewportHeight = event.nativeEvent.layout.height
+ scheduleAnchorRestore()
+ }}
+ onScrollBeginDrag={cancelAnchorRestore}
renderSectionHeader={renderSectionHeader}
stickySectionHeadersEnabled={false}
ListHeaderComponent={
@@ -651,7 +907,16 @@ function ViewsBody(): ReactElement {
keyboardDismissMode="on-drag"
onViewableItemsChanged={onViewableItemsChanged}
viewabilityConfig={list.viewabilityConfig}
- onScroll={motion.onScroll}
+ onScroll={(event) => {
+ const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent
+ scrollMetrics.current = {
+ offset: contentOffset.y,
+ contentHeight: contentSize.height,
+ viewportHeight: layoutMeasurement.height,
+ }
+ motion.onScroll()
+ scheduleAnchorRestore()
+ }}
scrollEventThrottle={16}
initialNumToRender={INITIAL_VISIBLE_ROWS}
windowSize={5}
diff --git a/products/mobile/src/features/views/pointSheet/PointSheet.tsx b/products/mobile/src/features/views/pointSheet/PointSheet.tsx
index 4cd0232f2fed..0388499737f7 100644
--- a/products/mobile/src/features/views/pointSheet/PointSheet.tsx
+++ b/products/mobile/src/features/views/pointSheet/PointSheet.tsx
@@ -1,9 +1,8 @@
import * as Clipboard from 'expo-clipboard'
import { useRouter } from 'expo-router'
import { type ReactElement, type ReactNode, useEffect, useMemo, useRef, useState } from 'react'
-import { ActivityIndicator, Linking, ScrollView, StyleSheet, Text, useWindowDimensions, View } from 'react-native'
+import { ActivityIndicator, Linking, ScrollView, StyleSheet, Text, View } from 'react-native'
import { Gesture, GestureDetector, type NativeGesture } from 'react-native-gesture-handler'
-
import { ACTORS_LIMIT } from '@/api/actors'
import { safeHttpsUrl } from '@/lib/urls'
import type { ActorRow, InsightSnapshot } from '@/model/views'
@@ -22,6 +21,7 @@ import { PlayIcon } from '@/ui/icons/PlayIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { trackViewOpenedInWeb } from '../analytics'
import { SheetTitle } from '../screen/SheetTitle'
@@ -115,7 +115,7 @@ function PointBody({ request, actors, listGesture, onClose, onOpenAbout }: Point
const snapshot = useLiveSnapshot(source)
const { scope } = useViewsContext()
const router = useRouter()
- const { height } = useWindowDimensions()
+ const { height } = useSceneDimensions()
const [page, setPage] = useState<Page>('point')
const [selectedKey, setSelectedKey] = useState(point.rows[0]?.key ?? null)
if (!snapshot) {
diff --git a/products/mobile/src/features/views/range/RangeSheet.tsx b/products/mobile/src/features/views/range/RangeSheet.tsx
index 7637d114a214..fc957f611d7a 100644
--- a/products/mobile/src/features/views/range/RangeSheet.tsx
+++ b/products/mobile/src/features/views/range/RangeSheet.tsx
@@ -1,16 +1,6 @@
import { type ReactElement, useEffect, useMemo, useState } from 'react'
-import {
- AccessibilityInfo,
- Platform,
- ScrollView,
- StyleSheet,
- Switch,
- Text,
- useWindowDimensions,
- View,
-} from 'react-native'
+import { AccessibilityInfo, Platform, ScrollView, StyleSheet, Switch, Text, View } from 'react-native'
import { Gesture, GestureDetector } from 'react-native-gesture-handler'
-
import type { RangePresetKey } from '@/model/views'
import { BottomSheet } from '@/ui/BottomSheet'
import { CheckIcon } from '@/ui/icons/CheckIcon'
@@ -19,6 +9,7 @@ import { ChevronRightIcon } from '@/ui/icons/ChevronRightIcon'
import { Pressable44 } from '@/ui/Pressable44'
import { createStyles, useColors } from '@/ui/theme'
import { radii, type } from '@/ui/tokens'
+import { useSceneDimensions } from '@/ui/useSceneDimensions'
import { CHIP_PRESETS, customRange, formatRangeSpanForSpeech, MORE_PRESETS, RANGE_PRESETS } from '../rangePresets'
import type { ViewRange } from '../rangeStore'
@@ -63,7 +54,7 @@ export function RangeSheet({
const colors = useColors()
const styles = useStyles()
const [page, setPage] = useState<Page>('main')
- const { height } = useWindowDimensions()
+ const { height } = useSceneDimensions()
const listGesture = useMemo(() => Gesture.Native(), [])
useEffect(() => {
if (visible) {
diff --git a/products/mobile/src/ui/BottomSheet.tsx b/products/mobile/src/ui/BottomSheet.tsx
index 63e94a354d12..48e6a35972d1 100644
--- a/products/mobile/src/ui/BottomSheet.tsx
+++ b/products/mobile/src/ui/BottomSheet.tsx
@@ -1,13 +1,15 @@
import { type ReactElement, type ReactNode, useState } from 'react'
-import { type LayoutChangeEvent, View } from 'react-native'
+import { type LayoutChangeEvent, useWindowDimensions, View } from 'react-native'
import { GestureDetector, type NativeGesture } from 'react-native-gesture-handler'
-import Animated, { useAnimatedStyle } from 'react-native-reanimated'
+import Animated, { type SharedValue, useAnimatedStyle } from 'react-native-reanimated'
import { OverlayPortal } from './OverlayPortal'
import { Scrim } from './Scrim'
import { createStyles, useTheme } from './theme'
-import { motion, radii } from './tokens'
+import { layout, motion, radii } from './tokens'
+import { useOverlayBack } from './useOverlayBack'
import { usePresence } from './usePresence'
+import { useSceneDimensions } from './useSceneDimensions'
import { bottomOffset, useScreenInsets } from './useScreenInsets'
import { useSheetDrag } from './useSheetDrag'
@@ -17,6 +19,7 @@ interface BottomSheetProps {
children: ReactNode
paddingHorizontal?: number
scrollGesture?: NativeGesture
+ keyboardHeight?: SharedValue<number>
/** Defaults to `surface`. Sheets that hold surface cards use the screen background. */
backgroundColor?: string
accessibilityLabel?: string
@@ -29,6 +32,7 @@ export function BottomSheet({
children,
paddingHorizontal = 16,
scrollGesture,
+ keyboardHeight,
backgroundColor,
accessibilityLabel,
testID,
@@ -36,13 +40,27 @@ export function BottomSheet({
const { colors, shadows } = useTheme()
const styles = useStyles()
const insets = useScreenInsets()
+ const { height: sceneHeight } = useSceneDimensions()
+ const { width: windowWidth } = useWindowDimensions()
+ const width = windowWidth - insets.left - insets.right
+ const bottomMargin = width >= 600 ? insets.bottom + 16 : 0
+ const bottomPadding = bottomOffset(insets, 40)
const { mounted, progress } = usePresence(visible, motion.sheet)
const [height, setHeight] = useState(480)
const { drag, pan } = useSheetDrag(visible, onClose, scrollGesture)
+ useOverlayBack(visible, onClose)
- const sheetStyle = useAnimatedStyle(() => ({
- transform: [{ translateY: (1 - progress.value) * height + drag.value }],
- }))
+ const sheetStyle = useAnimatedStyle(() => {
+ const keyboard = Math.max(-(keyboardHeight?.value ?? 0), 0)
+ const compactKeyboard = keyboard > 0 && sceneHeight < 480
+ const marginBottom = keyboard > 0 ? Math.max(bottomMargin, keyboard + (compactKeyboard ? 4 : 8)) : bottomMargin
+ return {
+ transform: [{ translateY: (1 - progress.value) * height + drag.value }],
+ marginBottom,
+ maxHeight: Math.max(120, sceneHeight - insets.top - (compactKeyboard ? 4 : 12) - marginBottom),
+ paddingBottom: compactKeyboard ? 8 : keyboard > 0 ? layout.minBottomPadding : bottomPadding,
+ }
+ })
if (!mounted) {
return null
@@ -64,7 +82,15 @@ export function BottomSheet({
shadows.bottomSheet,
{
paddingHorizontal,
- paddingBottom: bottomOffset(insets, 40),
+ width: '100%',
+ maxWidth: 600,
+ alignSelf: 'center',
+ ...(width >= 600
+ ? {
+ borderBottomLeftRadius: radii.sheet,
+ borderBottomRightRadius: radii.sheet,
+ }
+ : {}),
backgroundColor: backgroundColor ?? colors.surface,
},
sheetStyle,
diff --git a/products/mobile/src/ui/FloatingCard.tsx b/products/mobile/src/ui/FloatingCard.tsx
index 2982cd1dbfe9..2825bb5a0e91 100644
--- a/products/mobile/src/ui/FloatingCard.tsx
+++ b/products/mobile/src/ui/FloatingCard.tsx
@@ -1,18 +1,19 @@
-import type { ReactElement, ReactNode } from 'react'
-import { type StyleProp, View, type ViewStyle } from 'react-native'
+import type { ComponentProps, ReactElement, ReactNode } from 'react'
+import { View } from 'react-native'
import Animated, { useAnimatedStyle } from 'react-native-reanimated'
import { OverlayPortal } from './OverlayPortal'
import { Scrim } from './Scrim'
import { createStyles, useTheme } from './theme'
import { motion, radii } from './tokens'
+import { useOverlayBack } from './useOverlayBack'
import { usePresence } from './usePresence'
interface FloatingCardProps {
visible: boolean
onClose: () => void
children: ReactNode
- style?: StyleProp<ViewStyle>
+ style?: ComponentProps<typeof Animated.View>['style']
transformOrigin?: string
accessory?: ReactNode
accessibilityLabel?: string
@@ -32,6 +33,7 @@ export function FloatingCard({
const { colors, shadows } = useTheme()
const styles = useStyles()
const { mounted, progress } = usePresence(visible, motion.menu, 'emphasized')
+ useOverlayBack(visible, onClose)
const cardStyle = useAnimatedStyle(() => ({
opacity: progress.value,
transform: [{ scale: 0.92 + 0.08 * progress.value }, { translateY: -6 * (1 - progress.value) }],
diff --git a/products/mobile/src/ui/SceneFrame.tsx b/products/mobile/src/ui/SceneFrame.tsx
new file mode 100644
index 000000000000..21086b4794d7
--- /dev/null
+++ b/products/mobile/src/ui/SceneFrame.tsx
@@ -0,0 +1,24 @@
+import { type ReactElement, type ReactNode, useCallback, useState } from 'react'
+import { type LayoutChangeEvent, type StyleProp, StyleSheet, View, type ViewStyle } from 'react-native'
+
+import { SceneDimensionsContext } from './sceneDimensions'
+import { useSceneDimensions } from './useSceneDimensions'
+
+export function SceneFrame({ children, style }: { children: ReactNode; style?: StyleProp<ViewStyle> }): ReactElement {
+ const parent = useSceneDimensions()
+ const [size, setSize] = useState<{ width: number; height: number } | null>(null)
+ const measure = useCallback(({ nativeEvent: { layout } }: LayoutChangeEvent): void => {
+ setSize((previous) =>
+ previous?.width === layout.width && previous.height === layout.height
+ ? previous
+ : { width: layout.width, height: layout.height }
+ )
+ }, [])
+ return (
+ <View style={[styles.frame, style]} onLayout={measure}>
+ <SceneDimensionsContext.Provider value={size ?? parent}>{children}</SceneDimensionsContext.Provider>
+ </View>
+ )
+}
+
+const styles = StyleSheet.create({ frame: { flex: 1, minWidth: 0, minHeight: 0 } })
diff --git a/products/mobile/src/ui/adaptiveLayout.test.ts b/products/mobile/src/ui/adaptiveLayout.test.ts
new file mode 100644
index 000000000000..5a5e8884a609
--- /dev/null
+++ b/products/mobile/src/ui/adaptiveLayout.test.ts
@@ -0,0 +1,28 @@
+import { adaptiveLayout } from './adaptiveLayout'
+
+test.each([
+ { width: 402, height: 874, left: 0, right: 0, rail: false, paired: false, side: 'right' },
+ { width: 951, height: 669, left: 0, right: 70, rail: true, paired: true, side: 'right' },
+ { width: 951, height: 669, left: 70, right: 0, rail: true, paired: true, side: 'left' },
+ { width: 820, height: 669, left: 44, right: 44, rail: true, paired: false, side: 'right' },
+ { width: 669, height: 951, left: 0, right: 0, rail: false, paired: false, side: 'right' },
+ { width: 466, height: 678, left: 0, right: 70, rail: false, paired: false, side: 'right' },
+ { width: 874, height: 402, left: 62, right: 62, rail: false, paired: false, side: 'right' },
+ { width: 923, height: 411, left: 24, right: 0, rail: false, paired: false, side: 'left' },
+])(
+ 'fits content after both safe edges and navigation ($width × $height, $left/$right)',
+ ({ width, height, left, right, rail, paired, side }) => {
+ const result = adaptiveLayout(width, height, left, right)
+ expect(result).toMatchObject({ rail, paired, railSide: side })
+ expect(result.contentWidth).toBe(width - left - right - (rail ? 80 : 0))
+ }
+)
+
+test.each([
+ { width: 951, height: 669, navigation: true },
+ { width: 669, height: 951, navigation: true },
+ { width: 874, height: 402, navigation: false },
+ { width: 923, height: 411, navigation: false },
+])('preserves report reading space at $width × $height', ({ width, height, navigation }) => {
+ expect(adaptiveLayout(width, height, 0, 0).reportNavigation).toBe(navigation)
+})
diff --git a/products/mobile/src/ui/adaptiveLayout.ts b/products/mobile/src/ui/adaptiveLayout.ts
new file mode 100644
index 000000000000..d7f7500822b9
--- /dev/null
+++ b/products/mobile/src/ui/adaptiveLayout.ts
@@ -0,0 +1,30 @@
+export const NAV_RAIL_WIDTH = 80
+export const INBOX_PANE_WIDTH = 300
+export const REPORT_MIN_WIDTH = 440
+export const READING_WIDTH = 720
+
+export function adaptiveLayout(
+ width: number,
+ height: number,
+ left: number,
+ right: number
+): {
+ rail: boolean
+ railSide: 'left' | 'right'
+ contentWidth: number
+ paired: boolean
+ reportNavigation: boolean
+} {
+ const safeWidth = Math.max(0, width - left - right)
+ const enoughHeight = height >= 480
+ const rail =
+ enoughHeight && safeWidth >= 600 && (Math.max(left, right) >= 44 || (safeWidth >= 840 && safeWidth > height))
+ const contentWidth = Math.max(0, safeWidth - (rail ? NAV_RAIL_WIDTH : 0))
+ return {
+ rail,
+ railSide: left > right ? 'left' : 'right',
+ contentWidth,
+ paired: enoughHeight && contentWidth >= INBOX_PANE_WIDTH + REPORT_MIN_WIDTH,
+ reportNavigation: enoughHeight && (rail || contentWidth >= 600),
+ }
+}
diff --git a/products/mobile/src/ui/chart/MetricChartCanvas.tsx b/products/mobile/src/ui/chart/MetricChartCanvas.tsx
index 826ae2df0476..cd6d1317a2f5 100644
--- a/products/mobile/src/ui/chart/MetricChartCanvas.tsx
+++ b/products/mobile/src/ui/chart/MetricChartCanvas.tsx
@@ -175,6 +175,7 @@ export function MetricChartCanvas(props: MetricChartProps): ReactElement {
{width > 0 ? (
<>
<MetricChartRenderer
+ key={`${geometry.width}:${geometry.height}`}
geometry={geometry}
kind={kind}
variant={variant}
diff --git a/products/mobile/src/ui/sceneDimensions.ts b/products/mobile/src/ui/sceneDimensions.ts
new file mode 100644
index 000000000000..084d7e99129e
--- /dev/null
+++ b/products/mobile/src/ui/sceneDimensions.ts
@@ -0,0 +1,3 @@
+import { createContext } from 'react'
+
+export const SceneDimensionsContext = createContext<{ width: number; height: number } | null>(null)
diff --git a/products/mobile/src/ui/tokens.ts b/products/mobile/src/ui/tokens.ts
index 8155ce9a198b..37ddfd492efd 100644
--- a/products/mobile/src/ui/tokens.ts
+++ b/products/mobile/src/ui/tokens.ts
@@ -110,6 +110,8 @@ export const layout = {
minTapTarget: 44,
/** Status bar height in the prototype frame. Top paddings in the handoff include it. */
designStatusBar: 54,
+ /** Leaves room above chrome when the system status area moves to a side. */
+ minTopInset: 12,
/** Home indicator height in the prototype frame. Bottom paddings in the handoff include it. */
designHomeIndicator: 34,
/** Smallest bottom padding, for devices with a home button, where the safe-area inset is 0. */
diff --git a/products/mobile/src/ui/useAppLayout.ts b/products/mobile/src/ui/useAppLayout.ts
new file mode 100644
index 000000000000..0f91ea08c345
--- /dev/null
+++ b/products/mobile/src/ui/useAppLayout.ts
@@ -0,0 +1,10 @@
+import { useWindowDimensions } from 'react-native'
+import { useSafeAreaInsets } from 'react-native-safe-area-context'
+
+import { adaptiveLayout } from './adaptiveLayout'
+
+export function useAppLayout(): ReturnType<typeof adaptiveLayout> {
+ const { width, height } = useWindowDimensions()
+ const { left, right } = useSafeAreaInsets()
+ return adaptiveLayout(width, height, left, right)
+}
diff --git a/products/mobile/src/ui/useOverlayBack.test.ts b/products/mobile/src/ui/useOverlayBack.test.ts
new file mode 100644
index 000000000000..04d5e2bd86ec
--- /dev/null
+++ b/products/mobile/src/ui/useOverlayBack.test.ts
@@ -0,0 +1,61 @@
+import { act, renderHook } from '@testing-library/react-native'
+import { BackHandler } from 'react-native'
+
+import { useOverlayBack } from './useOverlayBack'
+
+let mockFocused = true
+jest.mock('expo-router', () => ({ useIsFocused: () => mockFocused }))
+
+test('Android Back dismisses the top overlay before falling through to the page', () => {
+ const handlers: Parameters<typeof BackHandler.addEventListener>[1][] = []
+ const listener = jest.spyOn(BackHandler, 'addEventListener').mockImplementation((_event, handler) => {
+ handlers.push(handler)
+ return {
+ remove: () => {
+ handlers.splice(handlers.indexOf(handler), 1)
+ },
+ }
+ })
+ const pressBack = (): boolean =>
+ [...handlers].reverse().some((handler) => handler({ type: 'hardwareBackPress', timeStamp: 0 }) === true)
+ const closeOuter = jest.fn()
+ const closeInner = jest.fn()
+ const latestClose = jest.fn()
+ const view = renderHook<void, { outer: boolean; inner: boolean; close: () => void }>(
+ ({ outer, inner, close }) => {
+ useOverlayBack(outer, close)
+ useOverlayBack(inner, closeInner)
+ },
+ { initialProps: { outer: true, inner: false, close: closeOuter } }
+ )
+ try {
+ view.rerender({ outer: true, inner: true, close: closeOuter })
+ view.rerender({ outer: true, inner: true, close: latestClose })
+ act(() => expect(pressBack()).toBe(true))
+ expect(closeInner).toHaveBeenCalledTimes(1)
+ expect(closeOuter).not.toHaveBeenCalled()
+ expect(latestClose).not.toHaveBeenCalled()
+
+ mockFocused = false
+ view.rerender({ outer: true, inner: true, close: latestClose })
+ expect(pressBack()).toBe(false)
+ expect(closeInner).toHaveBeenCalledTimes(1)
+ expect(latestClose).not.toHaveBeenCalled()
+
+ mockFocused = true
+ view.rerender({ outer: true, inner: true, close: latestClose })
+ act(() => expect(pressBack()).toBe(true))
+ expect(closeInner).toHaveBeenCalledTimes(2)
+
+ view.rerender({ outer: true, inner: false, close: latestClose })
+ act(() => expect(pressBack()).toBe(true))
+ expect(latestClose).toHaveBeenCalledTimes(1)
+
+ view.rerender({ outer: false, inner: false, close: latestClose })
+ expect(pressBack()).toBe(false)
+ } finally {
+ mockFocused = true
+ view.unmount()
+ listener.mockRestore()
+ }
+})
diff --git a/products/mobile/src/ui/useOverlayBack.ts b/products/mobile/src/ui/useOverlayBack.ts
new file mode 100644
index 000000000000..7d63d6a1f63a
--- /dev/null
+++ b/products/mobile/src/ui/useOverlayBack.ts
@@ -0,0 +1,22 @@
+import { useIsFocused } from 'expo-router'
+import { useEffect, useRef } from 'react'
+import { BackHandler } from 'react-native'
+
+export function useOverlayBack(visible: boolean, onClose: () => void): void {
+ const focused = useIsFocused()
+ const close = useRef(onClose)
+ useEffect(() => {
+ close.current = onClose
+ }, [onClose])
+
+ useEffect(() => {
+ if (!visible || !focused) {
+ return
+ }
+ const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
+ close.current()
+ return true
+ })
+ return () => subscription.remove()
+ }, [visible, focused])
+}
diff --git a/products/mobile/src/ui/usePickerCardStyle.test.ts b/products/mobile/src/ui/usePickerCardStyle.test.ts
new file mode 100644
index 000000000000..d052d9ce7ee7
--- /dev/null
+++ b/products/mobile/src/ui/usePickerCardStyle.test.ts
@@ -0,0 +1,23 @@
+import { renderHook } from '@testing-library/react-native'
+
+import { usePickerCardStyle } from './usePickerCardStyle'
+
+jest.mock('react-native-keyboard-controller', () => ({
+ useReanimatedKeyboardAnimation: () => ({ height: { value: -235 } }),
+}))
+jest.mock('react-native-reanimated', () => ({
+ useAnimatedStyle: (update: () => object) => update(),
+}))
+jest.mock('./useSceneDimensions', () => ({
+ useSceneDimensions: () => ({ width: 874, height: 393 }),
+}))
+jest.mock('./useScreenInsets', () => ({
+ useScreenInsets: () => ({ top: 52, bottom: 0, left: 0, right: 0 }),
+}))
+
+test('keeps a picker above the keyboard when less than 120 points remain', () => {
+ const { result } = renderHook(() => usePickerCardStyle(90, 320))
+ expect(result.current).toEqual({ top: 56, height: 98 })
+ const style = result.current as { top: number; height: number }
+ expect(style.top + style.height).toBeLessThan(393 - 235)
+})
diff --git a/products/mobile/src/ui/usePickerCardStyle.ts b/products/mobile/src/ui/usePickerCardStyle.ts
new file mode 100644
index 000000000000..444825cbba21
--- /dev/null
+++ b/products/mobile/src/ui/usePickerCardStyle.ts
@@ -0,0 +1,19 @@
+import type { ComponentProps } from 'react'
+import { useReanimatedKeyboardAnimation } from 'react-native-keyboard-controller'
+import type Animated from 'react-native-reanimated'
+import { useAnimatedStyle } from 'react-native-reanimated'
+
+import { useSceneDimensions } from './useSceneDimensions'
+import { useScreenInsets } from './useScreenInsets'
+
+export function usePickerCardStyle(top: number, height: number): ComponentProps<typeof Animated.View>['style'] {
+ const keyboard = useReanimatedKeyboardAnimation()
+ const insets = useScreenInsets()
+ const { height: sceneHeight } = useSceneDimensions()
+ return useAnimatedStyle(() => {
+ const keyboardHeight = Math.max(-keyboard.height.value, 0)
+ const bottom = sceneHeight - Math.max(keyboardHeight, insets.bottom) - 4
+ const fittedTop = Math.min(top, Math.max(insets.top + 4, bottom - height))
+ return { top: fittedTop, height: Math.max(0, Math.min(height, bottom - fittedTop)) }
+ })
+}
diff --git a/products/mobile/src/ui/useSceneDimensions.ts b/products/mobile/src/ui/useSceneDimensions.ts
new file mode 100644
index 000000000000..1e91fb425472
--- /dev/null
+++ b/products/mobile/src/ui/useSceneDimensions.ts
@@ -0,0 +1,10 @@
+import { useContext } from 'react'
+import { type ScaledSize, useWindowDimensions } from 'react-native'
+
+import { SceneDimensionsContext } from './sceneDimensions'
+
+export function useSceneDimensions(): ScaledSize {
+ const window = useWindowDimensions()
+ const scene = useContext(SceneDimensionsContext)
+ return { ...window, ...scene }
+}
diff --git a/products/mobile/src/ui/useScreenInsets.ts b/products/mobile/src/ui/useScreenInsets.ts
index c10192d6e290..56981ae37cb2 100644
--- a/products/mobile/src/ui/useScreenInsets.ts
+++ b/products/mobile/src/ui/useScreenInsets.ts
@@ -6,6 +6,8 @@ import { layout } from './tokens'
export interface ScreenInsets {
top: number
bottom: number
+ left: number
+ right: number
}
// The web build has no insets, so it uses the prototype frame's status bar and home indicator to look like a phone.
@@ -13,17 +15,19 @@ export function useScreenInsets(): ScreenInsets {
const insets = useSafeAreaInsets()
if (Platform.OS === 'web') {
return {
+ left: insets.left,
+ right: insets.right,
top: Math.max(insets.top, layout.designStatusBar),
bottom: Math.max(insets.bottom, layout.designHomeIndicator),
}
}
- return { top: insets.top, bottom: insets.bottom }
+ return insets
}
-export function topOffset(insets: ScreenInsets, designTop: number): number {
- return insets.top + designTop - layout.designStatusBar
+export function topOffset(insets: Pick<ScreenInsets, 'top'>, designTop: number): number {
+ return Math.max(insets.top, layout.minTopInset) + designTop - layout.designStatusBar
}
-export function bottomOffset(insets: ScreenInsets, designBottom: number): number {
+export function bottomOffset(insets: Pick<ScreenInsets, 'bottom'>, designBottom: number): number {
return Math.max(insets.bottom + designBottom - layout.designHomeIndicator, layout.minBottomPadding)
}