diff --git a/config/scripts/mobile-web-app/session/mobile-web-app-native-chat-touch-scroll-render.test.mjs b/config/scripts/mobile-web-app/session/mobile-web-app-native-chat-touch-scroll-render.test.mjs index 41370447cf7..1b69a0b8796 100644 --- a/config/scripts/mobile-web-app/session/mobile-web-app-native-chat-touch-scroll-render.test.mjs +++ b/config/scripts/mobile-web-app/session/mobile-web-app-native-chat-touch-scroll-render.test.mjs @@ -19,13 +19,17 @@ import { createRoot } from 'react-dom/client' import { Text, View } from 'react-native' import { GestureHandlerRootView } from 'react-native-gesture-handler' import { MobileNativeChatPageScroll } from './src/session/native-chat/transcript/viewport/MobileNativeChatPageScroll' +import { publishPageStorage } from './src/mobile-web-shell/bridge/page-storage/page-async-storage' import { MobileNativeChatPinchZoom, useMobileNativeChatPinchGesture } from './src/session/native-chat/transcript/viewport/mobile-native-chat-pinch-zoom' +// A pinch saves the size on release; accept that write as the app would. +publishPageStorage({}, () => true, 'host', '') + function Transcript() { - const { fontScale, pinchGesture } = useMobileNativeChatPinchGesture('chat') + const { fontScale, pinchGesture } = useMobileNativeChatPinchGesture() return {fontScale} diff --git a/mobile/src/components/markdown/MobileMarkdown.tsx b/mobile/src/components/markdown/MobileMarkdown.tsx index cbcd802af29..8004868d9f0 100644 --- a/mobile/src/components/markdown/MobileMarkdown.tsx +++ b/mobile/src/components/markdown/MobileMarkdown.tsx @@ -25,6 +25,10 @@ type Props = { /** Multiplier for every text size. Defaults to 1; the chat view passes >1 so its prose reads * larger than the compact base. */ textScale?: number + /** Multiplies the prose's line heights; code keeps its own. */ + lineSpacing?: number + /** The prose's face; code keeps mono. */ + fontFamily?: string // File targets call this with relative/absolute path and optional :line(:col); omit on screens without viewer to leave paths plain. onOpenFile?: (pathText: string) => void // Enable ::orca-visual directives only in assistant native-chat prose; keep callback identity stable for memoization. @@ -53,6 +57,8 @@ function MobileMarkdownContent({ fallback = '', rangeSelectable = false, textScale = 1, + lineSpacing = 1, + fontFamily, onOpenFile, renderVisual, renderImage, @@ -87,6 +93,7 @@ function MobileMarkdownContent({ ) : null } const tone = MARKDOWN_TONES[toneName] + const face = fontFamily ? { fontFamily } : null const ctx: MarkdownBlockContext = { growing, chatMath, @@ -95,10 +102,17 @@ function MobileMarkdownContent({ filePathsLinkedInTree: fileLinkExists !== undefined, tone, textScale, - listText: [styles.listText, scaledMarkdownText(styles.listText, textScale), tone.text], + lineSpacing, + fontFamily, + listText: [ + styles.listText, + scaledMarkdownText(styles.listText, textScale, lineSpacing), + face, + tone.text + ], listMarker: [ styles.listMarker, - scaledMarkdownText(styles.listMarker, textScale), + scaledMarkdownText(styles.listMarker, textScale, lineSpacing), tone.secondary ], rowLongPress: setup.androidTranscript ? setup.onLongPress : undefined, @@ -111,7 +125,12 @@ function MobileMarkdownContent({ return ( {renderBlocks(root.children, ctx, { - style: [styles.paragraph, scaledMarkdownText(styles.paragraph, textScale), tone.text], + style: [ + styles.paragraph, + scaledMarkdownText(styles.paragraph, textScale, lineSpacing), + face, + tone.text + ], selectable: rangeSelectable })} diff --git a/mobile/src/components/markdown/blocks/mobile-markdown-blocks.tsx b/mobile/src/components/markdown/blocks/mobile-markdown-blocks.tsx index 0cc0a9c48be..dbfac8ff067 100644 --- a/mobile/src/components/markdown/blocks/mobile-markdown-blocks.tsx +++ b/mobile/src/components/markdown/blocks/mobile-markdown-blocks.tsx @@ -45,6 +45,10 @@ const MERMAID_BASE = 13 export type MarkdownBlockContext = MarkdownInlineContext & { /** The text is still arriving: a diagram stays code until it stops. */ growing: boolean + /** Multiplies prose line heights; code keeps its own. */ + lineSpacing: number + /** The prose's face; undefined keeps the system font. */ + fontFamily?: string listText: StyleProp listMarker: StyleProp /** Interactive children own their touches and must forward the row action. */ @@ -99,7 +103,10 @@ function renderList(node: List, key: number, ctx: MarkdownBlockContext, depth: n role="checkbox" aria-checked={Boolean(item.checked)} aria-disabled - style={[styles.taskMarker, { height: styles.listText.lineHeight * ctx.textScale }]} + style={[ + styles.taskMarker, + { height: styles.listText.lineHeight * ctx.textScale * ctx.lineSpacing } + ]} > {item.checked ? ( @@ -151,7 +158,8 @@ function renderTable(node: Table, key: number, ctx: MarkdownBlockContext): React style={[ styles.tableCell, rowIndex === 0 ? styles.tableHeader : null, - scaledMarkdownText(styles.tableCell, ctx.textScale), + scaledMarkdownText(styles.tableCell, ctx.textScale, ctx.lineSpacing), + ctx.fontFamily ? { fontFamily: ctx.fontFamily } : null, { width, textAlign: node.align?.[cellIndex] ?? 'left' } ]} > @@ -242,8 +250,10 @@ function renderBlock( : node.depth === 2 ? styles.headingLarge : styles.heading, - ctx.textScale + ctx.textScale, + ctx.lineSpacing ), + ctx.fontFamily ? { fontFamily: ctx.fontFamily } : null, ctx.tone.text ]} > @@ -264,7 +274,8 @@ function renderBlock( { style: [ styles.quoteText, - scaledMarkdownText(styles.quoteText, ctx.textScale), + scaledMarkdownText(styles.quoteText, ctx.textScale, ctx.lineSpacing), + ctx.fontFamily ? { fontFamily: ctx.fontFamily } : null, ctx.tone.secondary ], selectable: true diff --git a/mobile/src/components/markdown/blocks/mobile-markdown-drawn-blocks.ts b/mobile/src/components/markdown/blocks/mobile-markdown-drawn-blocks.ts index 5993d115dce..7e8cba361d8 100644 --- a/mobile/src/components/markdown/blocks/mobile-markdown-drawn-blocks.ts +++ b/mobile/src/components/markdown/blocks/mobile-markdown-drawn-blocks.ts @@ -41,6 +41,8 @@ function sameContext(a: MarkdownBlockContext, b: MarkdownBlockContext): boolean a.growing === b.growing && a.chatMath === b.chatMath && a.textScale === b.textScale && + a.lineSpacing === b.lineSpacing && + a.fontFamily === b.fontFamily && a.tone === b.tone && a.onOpenFile === b.onOpenFile && a.onOpenLink === b.onOpenLink && diff --git a/mobile/src/components/markdown/mobile-markdown-styles.ts b/mobile/src/components/markdown/mobile-markdown-styles.ts index 2eb53b106a4..733f47dae5e 100644 --- a/mobile/src/components/markdown/mobile-markdown-styles.ts +++ b/mobile/src/components/markdown/mobile-markdown-styles.ts @@ -251,13 +251,17 @@ export const styles = themedStyleSheet(() => ({ } })) -/** A style's size and line height under the reader's zoom; null at 1x, where the sheet holds. */ +/** A style's size and line height under the reader's zoom and line spacing; null at 1x, where the sheet holds. */ export function scaledMarkdownText( style: { fontSize: number; lineHeight: number }, - textScale: number + textScale: number, + lineSpacing = 1 ): { fontSize: number; lineHeight: number } | null { - return textScale !== 1 - ? { fontSize: style.fontSize * textScale, lineHeight: style.lineHeight * textScale } + return textScale !== 1 || lineSpacing !== 1 + ? { + fontSize: style.fontSize * textScale, + lineHeight: style.lineHeight * textScale * lineSpacing + } : null } diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 0a5ec85d847..a0897069ac1 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -73,6 +73,28 @@ "on": "On", "off": "Off" }, + "nativeChatText": { + "heading": "TEXT", + "footer": "Pinch in a chat to change it; it saves here.", + "size": "Text size", + "sizeDefault": "Default", + "sizePoints": "{{size}} pt", + "sizeSpoken": "{{size}} points", + "font": "Font", + "fontPickerTitle": "Chat font", + "fontSystem": "System", + "fontSerif": "Serif", + "fontMono": "Monospace", + "fontMonoSubtitle": "Same as code", + "lineSpacing": "Line spacing", + "spacingCompact": "Compact", + "spacingDefault": "Default", + "spacingRelaxed": "Relaxed", + "reset": "Reset text settings", + "previewQuestion": "Why is the resume test flaky?", + "previewTools": "Read 3 files · Ran pnpm test", + "previewAnswer": "The test waits on `setTimeout(0)` while the stream is still flushing, so it passes only when the flush wins." + }, "nativeNotificationDeliverySettings": { "loadFailed": "Could not load delivery settings. Reopen this screen to retry.", "saveFailed": "Could not save delivery settings. Try again.", diff --git a/mobile/src/mobile-web-shell/page-storage/page-storage-keys.ts b/mobile/src/mobile-web-shell/page-storage/page-storage-keys.ts index 6e081d9a7c5..6546a341e75 100644 --- a/mobile/src/mobile-web-shell/page-storage/page-storage-keys.ts +++ b/mobile/src/mobile-web-shell/page-storage/page-storage-keys.ts @@ -26,7 +26,9 @@ export const TERMINAL_SETTINGS_STORAGE_KEYS = [ 'orca:terminalTextScale', 'orca:terminalFontStyle', 'orca:terminalAutocompleteEnabled', - 'orca:terminalLinkOpenMode' + 'orca:terminalLinkOpenMode', + /** Chat text size, font and spacing, so an open chat follows Settings too. */ + 'orca:nativeChatText' ] as const export const PAGE_STORAGE_EXACT_KEYS = [ @@ -45,7 +47,9 @@ export const PAGE_STORAGE_EXACT_KEYS = [ /** The split terminal's chosen direction. */ 'orca:terminalSplitLayout', /** Terminal font, line spacing and weight. */ - 'orca:terminalFontStyle' + 'orca:terminalFontStyle', + /** Chat text size, font and spacing; a pinch in a chat saves here. */ + 'orca:nativeChatText' ] as const /** @@ -55,7 +59,8 @@ export const PAGE_STORAGE_EXACT_KEYS = [ */ export const NEGOTIATED_PAGE_STORAGE_KEYS = [ 'orca:terminalSplitLayout', - 'orca:terminalFontStyle' + 'orca:terminalFontStyle', + 'orca:nativeChatText' ] as const /** Whether a page that declared `storageKeys` (null: declared nothing) reads this key in `init`. */ diff --git a/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts b/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts index 234399fd0b4..c7c71f6d94d 100644 --- a/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts +++ b/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts @@ -28,8 +28,14 @@ vi.mock('react-native-gesture-handler', () => { runOnJS: () => GestureChain onStart: () => GestureChain onUpdate: () => GestureChain + onFinalize: () => GestureChain + } + const chain: GestureChain = { + runOnJS: () => chain, + onStart: () => chain, + onUpdate: () => chain, + onFinalize: () => chain } - const chain: GestureChain = { runOnJS: () => chain, onStart: () => chain, onUpdate: () => chain } return { Gesture: { Simultaneous: () => ({}), Native: () => ({}), Pinch: () => chain }, GestureDetector: 'GestureDetector', diff --git a/mobile/src/session/native-chat/MobileNativeChatView.tsx b/mobile/src/session/native-chat/MobileNativeChatView.tsx index c6c4acc271e..3cd6f8e4702 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatView.tsx @@ -32,6 +32,7 @@ import { import { useMobileNativeChatTransientData } from './transcript/projection/use-mobile-native-chat-transient-data' import { useMobileNativeChatRowKeys } from './transcript/projection/mobile-native-chat-row-keys' import { useMobileNativeChatPinchGesture } from './transcript/viewport/mobile-native-chat-pinch-zoom' +import { useNativeChatTextSettings } from './preferences/native-chat-text-settings' import { useMobileNativeChatTailFollow } from './transcript/viewport/use-mobile-native-chat-tail-follow' import { useMobileNativeChatTurnDisclosure } from './transcript/turn-state/use-mobile-native-chat-turn-disclosure' import { mobileNativeChatComposerPlaceholder } from './composer/field/use-mobile-native-chat-input-lease' @@ -220,7 +221,8 @@ export function MobileNativeChatView({ const t = useMobileTranslation() const insets = useSafeAreaInsets() const bottomPad = keyboardInset > 0 ? keyboardInset + insets.bottom : insets.bottom - const { fontScale, pinchGesture } = useMobileNativeChatPinchGesture(sendSurfaceId) + const { fontScale, pinchGesture } = useMobileNativeChatPinchGesture() + const { font, lineSpacing } = useNativeChatTextSettings() const data = useMobileNativeChatTransientData( { folded, streaming, pending, imagePreviewsByMessageId }, @@ -314,8 +316,8 @@ export function MobileNativeChatView({ ) : null const header = mobileNativeChatListHeader(hasMore, olderPages, loadEarlier) - // Changing text scale relays out every row, so preserve the page’s reading anchor. - const layoutKey = `${fontScale}` + // Changing text size, face or spacing relays out every row, so preserve the page’s reading anchor. + const layoutKey = `${fontScale}:${font}:${lineSpacing}` const footer = mobileNativeChatListFooter(liveStatus, turns.waitingRows, renderItem) const emptyState = mobileNativeChatEmptyState(status, agent, error, sessionLive, clearing) diff --git a/mobile/src/session/native-chat/preferences/native-chat-text-settings.ts b/mobile/src/session/native-chat/preferences/native-chat-text-settings.ts new file mode 100644 index 00000000000..ea32b57f425 --- /dev/null +++ b/mobile/src/session/native-chat/preferences/native-chat-text-settings.ts @@ -0,0 +1,226 @@ +import AsyncStorage from '@react-native-async-storage/async-storage' +import { useEffect, useSyncExternalStore } from 'react' +import { Dimensions } from 'react-native' +import { getResponsiveLayoutMetrics } from '../../../layout/responsive-layout-metrics' +import { useShellStorage } from '../../../platform/shell-storage/shell-storage' +import { persistMirrored, subscribeMirroredKey } from '../../../storage/mirrored-storage-keys' +import { typography } from '../../../theme/mobile-theme' +import { serifFontFamily } from '../../../theme/mobile-serif-font' +import { CHAT_PROSE_SCALE } from '../transcript/messages/mobile-native-chat-message-styles' + +export const NATIVE_CHAT_TEXT_KEY = 'orca:nativeChatText' + +export type NativeChatFont = 'system' | 'serif' | 'mono' +export type NativeChatLineSpacing = 'compact' | 'default' | 'relaxed' +export type NativeChatTextSettings = { + /** Points; 14 is the chat's original type scale. */ + size: number + font: NativeChatFont + lineSpacing: NativeChatLineSpacing +} + +export const NATIVE_CHAT_TEXT_SIZE_MIN = 11 +export const NATIVE_CHAT_TEXT_SIZE_MAX = 24 +const BASE_TEXT_SIZE = 14 +const TABLET_TEXT_SIZE = 16 + +const LINE_SPACING: Record = { + compact: 0.9, + default: 1, + relaxed: 1.15 +} + +// Screen, not window: an iPad keeps its default in a narrow split. +export function defaultNativeChatTextSettings(): NativeChatTextSettings { + const screen = Dimensions.get('screen') + const tablet = getResponsiveLayoutMetrics(screen.width, screen.height).isTabletLayout + return { + size: tablet ? TABLET_TEXT_SIZE : BASE_TEXT_SIZE, + font: 'system', + lineSpacing: 'default' + } +} + +export function clampNativeChatTextSize(size: number): number { + return Number.isFinite(size) + ? Math.min(NATIVE_CHAT_TEXT_SIZE_MAX, Math.max(NATIVE_CHAT_TEXT_SIZE_MIN, Math.round(size))) + : defaultNativeChatTextSettings().size +} + +// Unknown fields fall back one by one, so a value from a newer build keeps what this one reads. +function parseSettings(raw: string | null): NativeChatTextSettings | null { + if (raw === null) { + return null + } + let parsed: unknown + try { + parsed = JSON.parse(raw) + } catch { + return null + } + if (typeof parsed !== 'object' || parsed === null) { + return null + } + const size = 'size' in parsed ? parsed.size : undefined + const font = 'font' in parsed ? parsed.font : undefined + const lineSpacing = 'lineSpacing' in parsed ? parsed.lineSpacing : undefined + const fallback = defaultNativeChatTextSettings() + return { + size: typeof size === 'number' ? clampNativeChatTextSize(size) : fallback.size, + font: font === 'system' || font === 'serif' || font === 'mono' ? font : fallback.font, + lineSpacing: + lineSpacing === 'compact' || lineSpacing === 'default' || lineSpacing === 'relaxed' + ? lineSpacing + : fallback.lineSpacing + } +} + +type Snapshot = { settings: NativeChatTextSettings; stored: boolean } + +// The phone default until the first storage read, which measures the screen; importing never does. +let snapshot: Snapshot = { + settings: { size: BASE_TEXT_SIZE, font: 'system', lineSpacing: 'default' }, + stored: false +} +// A change made while a read is in flight wins over that older read. +let changeCount = 0 +let writes: Promise = Promise.resolve() +let watchingScreen = false +const listeners = new Set<() => void>() + +function adopt(settings: NativeChatTextSettings | null): void { + const next = settings ?? defaultNativeChatTextSettings() + const stored = settings !== null + const held = snapshot.settings + if ( + snapshot.stored === stored && + held.size === next.size && + held.font === next.font && + held.lineSpacing === next.lineSpacing + ) { + return + } + snapshot = { settings: next, stored } + for (const listener of listeners) { + listener() + } +} + +// A foldable's default follows the screen it is on, until a size is saved. +function watchScreen(): void { + if (watchingScreen) { + return + } + watchingScreen = true + Dimensions.addEventListener('change', () => { + if (!snapshot.stored) { + adopt(null) + } + }) +} + +/** Rereads storage; the page calls it when the app republishes storage after a Settings change. */ +export function reloadNativeChatTextSettings(): Promise { + const readAt = changeCount + return Promise.resolve() + .then(() => AsyncStorage.getItem(NATIVE_CHAT_TEXT_KEY)) + .then((raw) => { + watchScreen() + if (changeCount === readAt) { + adopt(parseSettings(raw)) + } + }) + .catch(() => undefined) +} + +// A page's pinch lands in the app's mirror, which keeps Settings current; our own writes are already adopted. +subscribeMirroredKey(NATIVE_CHAT_TEXT_KEY, (raw, source) => { + if (source === 'page') { + changeCount += 1 + adopt(parseSettings(raw)) + } +}) +// Read on load: a page's chat chunk loads after its storage arrives, so the first frame has the saved size. +// An edit waits for this read, so it never merges into the defaults and overwrites what was saved. +let hydrated = false +const hydration = reloadNativeChatTextSettings().then(() => { + hydrated = true +}) + +function persist(settings: NativeChatTextSettings | null): Promise { + changeCount += 1 + const change = changeCount + adopt(settings) + // Queue writes so a slower earlier save cannot land after a newer one. + const write = writes.then(() => + persistMirrored(NATIVE_CHAT_TEXT_KEY, settings === null ? null : JSON.stringify(settings)) + ) + // A failed save shows what storage still holds, unless a newer change is on its way. + writes = write.catch(() => { + if (changeCount === change) { + void reloadNativeChatTextSettings() + } + }) + return writes +} + +export function updateNativeChatTextSettings( + change: Partial +): Promise { + return hydrated + ? persist({ ...snapshot.settings, ...change }) + : hydration.then(() => persist({ ...snapshot.settings, ...change })) +} + +export function resetNativeChatTextSettings(): Promise { + return persist(null) +} + +function subscribe(listener: () => void): () => void { + listeners.add(listener) + return () => { + listeners.delete(listener) + } +} + +/** The settings, and whether any are saved (Reset has nothing to do otherwise). */ +export function useNativeChatTextSettingsSnapshot(): Snapshot { + return useSyncExternalStore(subscribe, () => snapshot) +} + +export function useNativeChatTextSettings(): NativeChatTextSettings { + return useNativeChatTextSettingsSnapshot().settings +} + +/** For the chat view: an open page rereads the settings each time the app republishes its storage. */ +export function useNativeChatTextSettingsFollowingShell(): NativeChatTextSettings { + const shellStorage = useShellStorage() + useEffect(() => { + if (shellStorage !== null) { + void reloadNativeChatTextSettings() + } + }, [shellStorage]) + return useNativeChatTextSettings() +} + +export function nativeChatFontScale(size: number): number { + return size / BASE_TEXT_SIZE +} + +export function nativeChatFontFamily(font: NativeChatFont): string | undefined { + return font === 'serif' ? serifFontFamily : font === 'mono' ? typography.monoFamily : undefined +} + +/** Markdown props for message prose: the chat's larger prose scale, the chosen face and spacing. */ +export function useNativeChatProseText(fontScale: number): { + textScale: number + fontFamily: string | undefined + lineSpacing: number +} { + const { font, lineSpacing } = useNativeChatTextSettings() + return { + textScale: CHAT_PROSE_SCALE * fontScale, + fontFamily: nativeChatFontFamily(font), + lineSpacing: LINE_SPACING[lineSpacing] + } +} diff --git a/mobile/src/session/native-chat/transcript/agent-messages/MobileNativeChatAgentMessageCard.tsx b/mobile/src/session/native-chat/transcript/agent-messages/MobileNativeChatAgentMessageCard.tsx index acbbad227dd..8924419e1de 100644 --- a/mobile/src/session/native-chat/transcript/agent-messages/MobileNativeChatAgentMessageCard.tsx +++ b/mobile/src/session/native-chat/transcript/agent-messages/MobileNativeChatAgentMessageCard.tsx @@ -1,3 +1,4 @@ +import { useNativeChatProseText } from '../../preferences/native-chat-text-settings' import { memo } from 'react' import { Pressable, Text, View } from 'react-native' import { Bot, ChevronDown, ChevronUp } from 'lucide-react-native' @@ -23,7 +24,6 @@ import { useMobileAgentMessageView } from './mobile-agent-message-context' import { MobileAgentMessageSenders } from './MobileAgentMessageSenders' import { MobileNativeChatMessageTime } from '../messages/MobileNativeChatMessageTime' import { useMobileNativeChatDisclosure } from '../viewport/mobile-native-chat-disclosure-store' -import { CHAT_PROSE_SCALE } from '../messages/mobile-native-chat-message-styles' type AgentMessageCardProps = { message: NativeChatMessage @@ -44,6 +44,7 @@ export const MobileNativeChatAgentMessageCard = memo(function MobileNativeChatAg }: AgentMessageCardProps) { useMobileColorScheme() const t = useMobileTranslation() + const prose = useNativeChatProseText(fontScale) const text = mobileNativeChatDisplayCopyText(message) const [open, setOpen] = useMobileNativeChatDisclosure(`agent-message:${message.id}`, false) const headings: Record = { @@ -110,7 +111,7 @@ export const MobileNativeChatAgentMessageCard = memo(function MobileNativeChatAg {status} diff --git a/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatProse.tsx b/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatProse.tsx index d91a08c0c5a..30a7afc48e5 100644 --- a/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatProse.tsx +++ b/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatProse.tsx @@ -1,3 +1,4 @@ +import { useNativeChatProseText } from '../../preferences/native-chat-text-settings' import { mobileNativeChatMarkdownImageBlock } from './mobile-native-chat-markdown-image-block' import { useCallback, useContext, useEffect, useState } from 'react' import { Image, Pressable, Text, View } from 'react-native' @@ -18,12 +19,7 @@ import { readHostChatImage, type MobileNativeChatImageSource } from '../../visual/mobile-native-chat-image-preview' -import { - CHAT_PROSE_SCALE, - scaledType, - styles, - TEXT_SIZE -} from '../messages/mobile-native-chat-message-styles' +import { scaledType, styles, TEXT_SIZE } from '../messages/mobile-native-chat-message-styles' import type { MobileNativeChatVisualRender } from '../../visual/mobile-native-chat-visual-context' import { useMobileColorScheme } from '../../../../theme/use-mobile-color-scheme' import { useMobileTranslation } from '../../../../i18n/use-mobile-translation' @@ -57,6 +53,7 @@ export function Prose({ }): React.JSX.Element | null { useMobileColorScheme() const t = useMobileTranslation() + const prose = useNativeChatProseText(fontScale) const renderImage = useCallback( (href: string, alt: string): React.ReactNode => { const image = mobileNativeChatMarkdownImageBlock(href, alt) @@ -83,7 +80,7 @@ export function Prose({ content={text} tone="userMessage" rangeSelectable - textScale={CHAT_PROSE_SCALE * fontScale} + {...prose} onLongPress={onLongPress} renderImage={renderImage} /> @@ -101,7 +98,7 @@ export function Prose({ streaming={growing || revealing} renderVisual={renderVisual} rangeSelectable - textScale={CHAT_PROSE_SCALE * fontScale} + {...prose} onLongPress={onLongPress} renderImage={renderImage} /> diff --git a/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatReasoningRow.tsx b/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatReasoningRow.tsx index 1b536860ac2..3eb4e589263 100644 --- a/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatReasoningRow.tsx +++ b/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatReasoningRow.tsx @@ -1,3 +1,4 @@ +import { useNativeChatProseText } from '../../preferences/native-chat-text-settings' import { mobileNativeChatMemberId } from '../viewport/mobile-native-chat-reading-place' import { useState } from 'react' import { Pressable, Text, View } from 'react-native' @@ -15,7 +16,7 @@ import { MobileNativeChatMarkdown } from './MobileNativeChatMarkdown' import { colors } from '../../../../theme/mobile-theme' import { useMobileColorScheme } from '../../../../theme/use-mobile-color-scheme' import { MobileNativeChatLongPressContent } from './MobileNativeChatLongPressContent' -import { CHAT_PROSE_SCALE, styles } from '../messages/mobile-native-chat-message-styles' +import { styles } from '../messages/mobile-native-chat-message-styles' /** A grouped thought keeps its own source recovery when its original transcript row is hidden. */ export function MobileNativeChatGroupedThought({ @@ -110,6 +111,7 @@ export function MobileNativeChatReasoningBody({ onLongPress?: () => void }): React.JSX.Element { useMobileColorScheme() + const prose = useNativeChatProseText(fontScale) return ( diff --git a/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatUserMessageFold.tsx b/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatUserMessageFold.tsx index f2a9863b5bf..5545f424817 100644 --- a/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatUserMessageFold.tsx +++ b/mobile/src/session/native-chat/transcript/message-content/MobileNativeChatUserMessageFold.tsx @@ -8,15 +8,10 @@ import { styles as markdownStyles } from '../../../../components/markdown/mobile import { colors, spacing, typography, pressedStyle } from '../../../../theme/mobile-theme' import { themedStyleSheet } from '../../../../theme/themed-styles' import { useMobileColorScheme } from '../../../../theme/use-mobile-color-scheme' -import { CHAT_PROSE_SCALE } from '../messages/mobile-native-chat-message-styles' +import { useNativeChatProseText } from '../../preferences/native-chat-text-settings' import type { useMobileNativeChatFullMessage } from './MobileNativeChatFullContent' import { useMobileTranslation } from '../../../../i18n/use-mobile-translation' -const FOLDED_HEIGHT = - NATIVE_CHAT_USER_MESSAGE_MAX_UNFOLDED_LINES * - markdownStyles.paragraph.lineHeight * - CHAT_PROSE_SCALE - export function MobileNativeChatUserMessageFold({ text, fontScale, @@ -39,7 +34,12 @@ export function MobileNativeChatUserMessageFold({ const t = useMobileTranslation() const longText = useMemo(() => nativeChatUserMessageFolds(text), [text]) const [height, setHeight] = useState(null) - const clip = FOLDED_HEIGHT * fontScale + const { textScale, lineSpacing } = useNativeChatProseText(fontScale) + const clip = + NATIVE_CHAT_USER_MESSAGE_MAX_UNFOLDED_LINES * + markdownStyles.paragraph.lineHeight * + textScale * + lineSpacing // Native clips measure at the folded height; use >= with rounding tolerance or expanding to measure would loop. const folds = longText && (height === null || height >= clip - 1) return ( diff --git a/mobile/src/session/native-chat/transcript/message-content/mobile-native-chat-message-text.ts b/mobile/src/session/native-chat/transcript/message-content/mobile-native-chat-message-text.ts deleted file mode 100644 index fc94a187c3f..00000000000 --- a/mobile/src/session/native-chat/transcript/message-content/mobile-native-chat-message-text.ts +++ /dev/null @@ -1,21 +0,0 @@ -const FONT_SCALE_MIN = 0.8 -const FONT_SCALE_MAX = 1.8 - -function clampFontScale(scale: number): number { - if (Number.isNaN(scale)) { - return 1 - } - return Math.min(FONT_SCALE_MAX, Math.max(FONT_SCALE_MIN, scale)) -} - -export const FONT_SCALE_STEP = 0.05 - -// Quantize pinch changes because each fontScale remeasures the whole list; frame-level updates can repaint recycled iOS paragraphs with stale clipped content. -export function quantizeFontScale(scale: number): number { - if (Number.isNaN(scale)) { - return 1 - } - const stepped = Math.round(clampFontScale(scale) / FONT_SCALE_STEP) * FONT_SCALE_STEP - // Re-clamp: rounding can push the outermost step past the bound. - return clampFontScale(Number(stepped.toFixed(2))) -} diff --git a/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-pinch-zoom.tsx b/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-pinch-zoom.tsx index efa85f2d698..21d645bec6c 100644 --- a/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-pinch-zoom.tsx +++ b/mobile/src/session/native-chat/transcript/viewport/mobile-native-chat-pinch-zoom.tsx @@ -1,19 +1,27 @@ -import { useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react' +import { useEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react' import { Gesture, GestureDetector } from 'react-native-gesture-handler' import type { LegacyComposedGesture } from 'react-native-gesture-handler' -import { quantizeFontScale } from '../message-content/mobile-native-chat-message-text' +import { + clampNativeChatTextSize, + nativeChatFontScale, + updateNativeChatTextSettings, + useNativeChatTextSettingsFollowingShell +} from '../../preferences/native-chat-text-settings' -// Anchor each pinch on the committed scale so successive gestures compound. -// The overlay reuses one view across a worktree's chats, so the scale belongs to `scopeKey`'s chat. -export function useMobileNativeChatPinchGesture(scopeKey: string): { +// A pinch steps the saved text size in whole points, previews here, and saves once on release for every chat. +// Each step remeasures the whole list, so frame-level scales would repaint recycled iOS paragraphs with stale clipped content. +export function useMobileNativeChatPinchGesture(): { fontScale: number pinchGesture: LegacyComposedGesture } { - const [scaled, setScaled] = useState({ scopeKey, fontScale: 1 }) - const fontScale = scaled.scopeKey === scopeKey ? scaled.fontScale : 1 - const fontScaleRef = useRef(1) - fontScaleRef.current = fontScale - const pinchBase = useRef(1) + const { size } = useNativeChatTextSettingsFollowingShell() + const [pinched, setPinched] = useState(null) + const saved = useRef(size) + useEffect(() => { + saved.current = size + }, [size]) + const live = useRef(null) + const pinchBase = useRef(size) // Run callbacks on JS to access React state safely; simultaneous native scrolling keeps active lists from stealing pinch recognition. const pinchGesture = useMemo( () => @@ -22,22 +30,25 @@ export function useMobileNativeChatPinchGesture(scopeKey: string): { Gesture.Pinch() .runOnJS(true) .onStart(() => { - pinchBase.current = fontScaleRef.current + pinchBase.current = live.current ?? saved.current }) .onUpdate((e) => { - const fontScale = quantizeFontScale(pinchBase.current * e.scale) - // Same object for an unchanged step, so gesture noise commits nothing. - setScaled((previous) => - previous.scopeKey === scopeKey && previous.fontScale === fontScale - ? previous - : { scopeKey, fontScale } - ) + live.current = clampNativeChatTextSize(pinchBase.current * e.scale) + setPinched(live.current) + }) + .onFinalize(() => { + const next = live.current + live.current = null + if (next !== null && next !== saved.current) { + void updateNativeChatTextSettings({ size: next }) + } + setPinched(null) }) ), - [scopeKey] + [] ) - return { fontScale, pinchGesture } + return { fontScale: nativeChatFontScale(pinched ?? size), pinchGesture } } // Web: gesture handler 3 defaults to touch-action: none (froze touch scrolling); auto would let a pinch zoom the page instead of the text. diff --git a/mobile/src/settings/native-chat-settings-screen.tsx b/mobile/src/settings/native-chat-settings-screen.tsx index d637a55cf4e..4bfc8762e3b 100644 --- a/mobile/src/settings/native-chat-settings-screen.tsx +++ b/mobile/src/settings/native-chat-settings-screen.tsx @@ -1,50 +1,244 @@ import { useRouter } from 'expo-router' +import { useState, type ReactNode } from 'react' +import { Platform, Text, View } from 'react-native' +import { GestureHandlerRootView } from 'react-native-gesture-handler' import { ListRow } from '../components/list/ListGroup' +import { MobileSegmentedControl } from '../components/controls/MobileSegmentedControl' +import { MobileSlider } from '../components/controls/MobileSlider' import { MobileSwitch } from '../components/controls/MobileSwitch' +import { PickerModal, type PickerOption } from '../components/sheets/PickerModal' +import type { Translate } from '../i18n/mobile-i18n' import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { + defaultNativeChatTextSettings, + NATIVE_CHAT_TEXT_SIZE_MAX, + NATIVE_CHAT_TEXT_SIZE_MIN, + nativeChatFontScale, + resetNativeChatTextSettings, + updateNativeChatTextSettings, + useNativeChatTextSettingsSnapshot, + type NativeChatFont, + type NativeChatLineSpacing +} from '../session/native-chat/preferences/native-chat-text-settings' import { useMobileDefaultSessionViewPreference } from '../session/use-mobile-default-session-view-preference' +import { colors, spacing } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' -import { SettingsScreen, SettingsSection } from './settings-screen-frame' +import { NativeChatTextPreview } from './native-chat-text-preview' +import { SettingsScreen, SettingsSection, settingsScreenStyles } from './settings-screen-frame' + +const IOS = Platform.OS === 'ios' + +function fontOptions(t: Translate): PickerOption[] { + return [ + { + value: 'system', + label: t('settings.nativeChatText.fontSystem', 'System'), + subtitle: IOS ? 'SF Pro' : 'Roboto' + }, + { + value: 'serif', + label: t('settings.nativeChatText.fontSerif', 'Serif'), + subtitle: IOS ? 'New York' : 'Noto Serif' + }, + { + value: 'mono', + label: t('settings.nativeChatText.fontMono', 'Monospace'), + subtitle: t('settings.nativeChatText.fontMonoSubtitle', 'Same as code') + } + ] +} + +function lineSpacingSegments(t: Translate): { value: NativeChatLineSpacing; label: string }[] { + return [ + { value: 'compact', label: t('settings.nativeChatText.spacingCompact', 'Compact') }, + { value: 'default', label: t('settings.nativeChatText.spacingDefault', 'Default') }, + { value: 'relaxed', label: t('settings.nativeChatText.spacingRelaxed', 'Relaxed') } + ] +} + +/** A row whose control sits under its title, for controls too wide to share the line. */ +function StackedRow({ + title, + value, + children +}: { + title: string + value?: string + children: ReactNode +}) { + useMobileColorScheme() + return ( + + + {title} + {value !== undefined ? {value} : null} + + {children} + + ) +} export default function NativeChatSettingsScreen({ onBack }: { onBack?: () => void }) { useMobileColorScheme() const t = useMobileTranslation() const router = useRouter() + const { settings, stored } = useNativeChatTextSettingsSnapshot() + const [fontPickerOpen, setFontPickerOpen] = useState(false) + // The preview follows a drag; the size saves once when it ends. + const [draggedSize, setDraggedSize] = useState(null) + const size = draggedSize ?? settings.size + const fonts = fontOptions(t) const { defaultView, setDefaultView } = useMobileDefaultSessionViewPreference() const chatDefault = defaultView === 'chat' const label = t('settings.nativeChatSettingsScreen.openInChatUi', 'Open sessions in Chat UI') + // The slider's gesture needs a root here, as Terminal settings has. return ( - router.back())} - > - + router.back())} + overlays={ + + visible={fontPickerOpen} + title={t('settings.nativeChatText.fontPickerTitle', 'Chat font')} + options={fonts} + selected={settings.font} + onSelect={(font) => void updateNativeChatTextSettings({ font })} + onClose={() => setFontPickerOpen(false)} + /> + } > - setDefaultView(next ? 'chat' : 'terminal')} + + + + + + A + + + { + setDraggedSize(null) + if (next !== settings.size) { + void updateNativeChatTextSettings({ size: next }) + } + }} + accessibilityLabel={t('settings.nativeChatText.size', 'Text size')} + accessibilityValueText={t( + 'settings.nativeChatText.sizeSpoken', + '{{size}} points', + { + size + } + )} + testID="chat-text-size" + /> + + + A + + + + option.value === settings.font)?.label} + navigates + onPress={() => setFontPickerOpen(true)} + testID="chat-text-font" + /> + + void updateNativeChatTextSettings({ lineSpacing })} + fill + testIDPrefix="chat-text-spacing-" /> - } - /> - - + + + + + setDefaultView(next ? 'chat' : 'terminal')} + /> + } + /> + + + + void resetNativeChatTextSettings()} + testID="chat-text-reset" + /> + + + ) } + +const styles = themedStyleSheet(() => ({ + stacked: { + paddingHorizontal: spacing.lg, + paddingVertical: spacing.sm, + gap: spacing.xs + }, + stackedHeader: { + minHeight: 32, + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + gap: spacing.md + }, + stackedTitle: { fontSize: 15, color: colors.textPrimary }, + stackedValue: { fontSize: 15, color: colors.textSecondary }, + sliderLine: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm }, + slider: { flex: 1 }, + smallA: { fontSize: 13, color: colors.textSecondary }, + largeA: { fontSize: 20, color: colors.textSecondary } +})) diff --git a/mobile/src/settings/native-chat-text-preview.tsx b/mobile/src/settings/native-chat-text-preview.tsx new file mode 100644 index 00000000000..fe92eb13bef --- /dev/null +++ b/mobile/src/settings/native-chat-text-preview.tsx @@ -0,0 +1,62 @@ +import { Text, View, useWindowDimensions } from 'react-native' +import { useMobileTranslation } from '../i18n/use-mobile-translation' +import { useNativeChatProseText } from '../session/native-chat/preferences/native-chat-text-settings' +import { MobileNativeChatMarkdown } from '../session/native-chat/transcript/message-content/MobileNativeChatMarkdown' +import { styles as messageStyles } from '../session/native-chat/transcript/messages/mobile-native-chat-message-styles' +import { + toolStyles, + toolType +} from '../session/native-chat/transcript/tool-results/mobile-native-chat-tool-styles' +import { colors, radii, spacing } from '../theme/mobile-theme' +import { themedStyleSheet } from '../theme/themed-styles' +import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' + +const CODE = '```ts\nawait vi.waitFor(() =>\n expect(rows).toHaveLength(3))\n```' + +/** The chat's own parts at the chosen text settings: your bubble, a tool line, prose and code. */ +export function NativeChatTextPreview({ fontScale: chatScale }: { fontScale: number }) { + useMobileColorScheme() + const t = useMobileTranslation() + // Native text grows with the phone's Text Size and the chat page's doesn't; undo it so sizes match the chat. + const fontScale = chatScale / useWindowDimensions().fontScale + const prose = useNativeChatProseText(fontScale) + return ( + + + + + + + + {t('settings.nativeChatText.previewTools', 'Read 3 files · Ran pnpm test')} + + + + ) +} + +const styles = themedStyleSheet(() => ({ + preview: { + gap: spacing.md, + padding: spacing.md, + marginBottom: spacing.lg, + borderRadius: radii.surface, + backgroundColor: colors.bgBase, + borderWidth: 1, + borderColor: colors.borderSubtle + } +})) diff --git a/mobile/src/theme/mobile-serif-font.ios.ts b/mobile/src/theme/mobile-serif-font.ios.ts new file mode 100644 index 00000000000..394b55bafd5 --- /dev/null +++ b/mobile/src/theme/mobile-serif-font.ios.ts @@ -0,0 +1,2 @@ +// The system serif design, New York; iOS has no family named `serif`. +export const serifFontFamily: string = 'ui-serif' diff --git a/mobile/src/theme/mobile-serif-font.ts b/mobile/src/theme/mobile-serif-font.ts new file mode 100644 index 00000000000..8fab9840f17 --- /dev/null +++ b/mobile/src/theme/mobile-serif-font.ts @@ -0,0 +1,2 @@ +// Android's generic family is Noto Serif; .ios.ts and .web.ts pick theirs. +export const serifFontFamily: string = 'serif' diff --git a/mobile/src/theme/mobile-serif-font.web.ts b/mobile/src/theme/mobile-serif-font.web.ts new file mode 100644 index 00000000000..4b0897ee5b8 --- /dev/null +++ b/mobile/src/theme/mobile-serif-font.web.ts @@ -0,0 +1,2 @@ +// New York in WebKit; Android's WebView skips `ui-serif` and draws Noto Serif. +export const serifFontFamily: string = 'ui-serif, serif'