From 55c0c749513c64a8d5595c17b8a7f04b2d15ea2a Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 26 Jun 2026 12:10:58 -0700 Subject: [PATCH] Fix mobile file previews (#6315) Co-authored-by: Orca --- .../h/[hostId]/files/preview/[worktreeId].tsx | 14 ++ .../scripts/mock-server-file-preview-data.ts | 82 +++++++ mobile/scripts/mock-server-rpc-handlers.ts | 27 +-- .../scripts/mock-server-terminal-fixtures.ts | 21 ++ mobile/src/components/MobileMarkdown.test.ts | 28 +++ mobile/src/components/MobileMarkdown.tsx | 4 +- .../mobile-markdown-preview-html.ts | 98 ++++++++ mobile/src/files/MobileFileExplorerPanel.tsx | 68 +++--- .../src/files/MobileFileMarkdownPreview.tsx | 69 ++++++ mobile/src/files/MobileFilePreviewScreen.tsx | 220 ++++++++++++++++++ .../src/files/MobileFilePreviewSourceText.tsx | 41 ++++ .../mobile-file-preview-navigation.test.ts | 68 ++++++ .../files/mobile-file-preview-navigation.ts | 37 +++ .../files/mobile-file-preview-request.test.ts | 133 +++++++++++ .../src/files/mobile-file-preview-request.ts | 195 ++++++++++++++++ .../files/mobile-file-preview-route.test.ts | 77 ++++++ mobile/src/files/mobile-file-preview-route.ts | 68 ++++++ .../src/files/mobile-file-preview-styles.ts | 140 +++++++++++ .../files/mobile-file-preview-syntax.test.ts | 18 ++ .../src/files/mobile-file-preview-syntax.ts | 30 +++ 20 files changed, 1375 insertions(+), 63 deletions(-) create mode 100644 mobile/app/h/[hostId]/files/preview/[worktreeId].tsx create mode 100644 mobile/scripts/mock-server-file-preview-data.ts create mode 100644 mobile/scripts/mock-server-terminal-fixtures.ts create mode 100644 mobile/src/components/mobile-markdown-preview-html.ts create mode 100644 mobile/src/files/MobileFileMarkdownPreview.tsx create mode 100644 mobile/src/files/MobileFilePreviewScreen.tsx create mode 100644 mobile/src/files/MobileFilePreviewSourceText.tsx create mode 100644 mobile/src/files/mobile-file-preview-navigation.test.ts create mode 100644 mobile/src/files/mobile-file-preview-navigation.ts create mode 100644 mobile/src/files/mobile-file-preview-request.test.ts create mode 100644 mobile/src/files/mobile-file-preview-request.ts create mode 100644 mobile/src/files/mobile-file-preview-route.test.ts create mode 100644 mobile/src/files/mobile-file-preview-route.ts create mode 100644 mobile/src/files/mobile-file-preview-styles.ts create mode 100644 mobile/src/files/mobile-file-preview-syntax.test.ts create mode 100644 mobile/src/files/mobile-file-preview-syntax.ts diff --git a/mobile/app/h/[hostId]/files/preview/[worktreeId].tsx b/mobile/app/h/[hostId]/files/preview/[worktreeId].tsx new file mode 100644 index 000000000..8ab79117c --- /dev/null +++ b/mobile/app/h/[hostId]/files/preview/[worktreeId].tsx @@ -0,0 +1,14 @@ +import { useLocalSearchParams } from 'expo-router' +import { MobileFilePreviewScreen } from '../../../../../src/files/MobileFilePreviewScreen' +import { normalizeMobileFilePreviewRouteParams } from '../../../../../src/files/mobile-file-preview-route' + +export default function MobileFilePreviewRoute() { + const params = useLocalSearchParams<{ + hostId?: string | string[] + worktreeId?: string | string[] + relativePath?: string | string[] + name?: string | string[] + worktreeName?: string | string[] + }>() + return +} diff --git a/mobile/scripts/mock-server-file-preview-data.ts b/mobile/scripts/mock-server-file-preview-data.ts new file mode 100644 index 000000000..a64c76eda --- /dev/null +++ b/mobile/scripts/mock-server-file-preview-data.ts @@ -0,0 +1,82 @@ +import type { RpcRequest, RpcResponse } from './mock-server-rpc-handlers' + +type Respond = (response: RpcResponse) => void +type Success = (id: string, result: unknown, streaming?: boolean) => RpcResponse +type ErrorResponse = (id: string, code: string, message: string) => RpcResponse + +const MOCK_IMAGE_PNG_BASE64 = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l8sm7wAAAABJRU5ErkJggg==' + +const MOCK_FILE_CONTENT: Record = { + 'README.md': '# Mobile preview\n\nThis markdown file is served by the mock desktop.', + 'src/app.ts': "export const mobilePreview = 'ready'\n", + 'public/index.html': '

Mobile preview

HTML preview is ready.

' +} + +const MOCK_FILE_LIST = [ + { relativePath: 'README.md', basename: 'README.md', kind: 'text' }, + { relativePath: 'src/app.ts', basename: 'app.ts', kind: 'text' }, + { relativePath: 'public/index.html', basename: 'index.html', kind: 'text' }, + { relativePath: 'assets/logo.png', basename: 'logo.png', kind: 'binary' }, + { relativePath: 'dist/archive.zip', basename: 'archive.zip', kind: 'binary' } +] + +export function handleMockFilePreviewRequest( + request: RpcRequest, + respond: Respond, + success: Success, + error: ErrorResponse +): boolean { + switch (request.method) { + case 'files.list': + respond( + success(request.id, { + worktree: request.params?.worktree ?? 'id:mock', + rootPath: '/tmp/orca-mobile-repro/orca', + files: MOCK_FILE_LIST, + totalCount: MOCK_FILE_LIST.length, + truncated: false + }) + ) + return true + + case 'files.read': { + const relativePath = String(request.params?.relativePath ?? '') + const content = MOCK_FILE_CONTENT[relativePath] + if (content == null) { + respond(error(request.id, 'not_found', 'File not found')) + return true + } + respond( + success(request.id, { + worktree: request.params?.worktree ?? 'id:mock', + relativePath, + content, + truncated: false, + byteLength: Buffer.byteLength(content, 'utf8') + }) + ) + return true + } + + case 'files.readPreview': { + const relativePath = String(request.params?.relativePath ?? '') + if (relativePath !== 'assets/logo.png') { + respond(error(request.id, 'binary_file', 'binary_file')) + return true + } + respond( + success(request.id, { + content: MOCK_IMAGE_PNG_BASE64, + isBinary: true, + isImage: true, + mimeType: 'image/png' + }) + ) + return true + } + + default: + return false + } +} diff --git a/mobile/scripts/mock-server-rpc-handlers.ts b/mobile/scripts/mock-server-rpc-handlers.ts index 34514ebaf..22b725ad1 100644 --- a/mobile/scripts/mock-server-rpc-handlers.ts +++ b/mobile/scripts/mock-server-rpc-handlers.ts @@ -3,7 +3,9 @@ import { DESKTOP_PROTOCOL_VERSION, MIN_COMPATIBLE_MOBILE_VERSION } from '../../src/shared/protocol-version' +import { handleMockFilePreviewRequest } from './mock-server-file-preview-data' import { handleMockGitRequest } from './mock-server-git-state' +import { FAKE_SCROLLBACK, STREAMING_CHUNKS } from './mock-server-terminal-fixtures' import { createMockRepos, createMockWorktrees, readScenarioNumber } from './mobile-lag-scenario' const MOCK_REPO_COUNT = readScenarioNumber('MOCK_REPO_COUNT', 2) @@ -30,28 +32,6 @@ const FAKE_TERMINALS = [ } ] -const FAKE_SCROLLBACK = [ - '$ claude "refactor the auth module to use JWT tokens"', - '', - '⏳ Working on it...', - '', - "I'll refactor the auth module. Here's my plan:", - '1. Replace session-based auth with JWT', - '2. Add token refresh endpoint', - '3. Update middleware', - '', - 'Let me start by reading the current auth module...', - '' -].join('\n') - -const STREAMING_CHUNKS = [ - 'Reading src/auth/middleware.ts...\n', - 'Reading src/auth/session.ts...\n', - '\nI see the current implementation uses express-session.\n', - "I'll replace it with jsonwebtoken.\n", - '\nUpdating src/auth/middleware.ts...\n' -] - export type RpcRequest = { id: string method: string @@ -120,6 +100,9 @@ export function handleRequest( if (handleMockGitRequest(request, respond, success)) { return } + if (handleMockFilePreviewRequest(request, respond, success, error)) { + return + } switch (request.method) { case 'status.get': diff --git a/mobile/scripts/mock-server-terminal-fixtures.ts b/mobile/scripts/mock-server-terminal-fixtures.ts new file mode 100644 index 000000000..fec2a45c1 --- /dev/null +++ b/mobile/scripts/mock-server-terminal-fixtures.ts @@ -0,0 +1,21 @@ +export const FAKE_SCROLLBACK = [ + '$ claude "refactor the auth module to use JWT tokens"', + '', + '⏳ Working on it...', + '', + "I'll refactor the auth module. Here's my plan:", + '1. Replace session-based auth with JWT', + '2. Add token refresh endpoint', + '3. Update middleware', + '', + 'Let me start by reading the current auth module...', + '' +].join('\n') + +export const STREAMING_CHUNKS = [ + 'Reading src/auth/middleware.ts...\n', + 'Reading src/auth/session.ts...\n', + '\nI see the current implementation uses express-session.\n', + "I'll replace it with jsonwebtoken.\n", + '\nUpdating src/auth/middleware.ts...\n' +] diff --git a/mobile/src/components/MobileMarkdown.test.ts b/mobile/src/components/MobileMarkdown.test.ts index 32470043a..cfc7a0df4 100644 --- a/mobile/src/components/MobileMarkdown.test.ts +++ b/mobile/src/components/MobileMarkdown.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { normalizeMobileMarkdownPreviewHtml } from './mobile-markdown-preview-html' import { parseMobileMarkdown } from './mobile-markdown-parser' describe('parseMobileMarkdown', () => { @@ -21,4 +22,31 @@ describe('parseMobileMarkdown', () => { } ]) }) + + it('normalizes common README HTML into readable Markdown preview text', () => { + const normalized = normalizeMobileMarkdownPreviewHtml(` +

+ Orca + Orca +

+ +

+ GitHub stars + The AI Orchestrator
+ Run Codex side-by-side. +

+`) + + expect(normalized).toContain('# [Orca](https://onOrca.dev)') + expect(normalized).toContain('[GitHub stars](https://github.com/stablyai/orca/stargazers)') + expect(normalized).toContain('**The AI Orchestrator**') + expect(normalized).not.toContain(' { + expect( + normalizeMobileMarkdownPreviewHtml('

Use &lt;button&gt;

') + ).toBe('Use `<button>`') + }) }) diff --git a/mobile/src/components/MobileMarkdown.tsx b/mobile/src/components/MobileMarkdown.tsx index d56e1ac29..5ee7ca6b4 100644 --- a/mobile/src/components/MobileMarkdown.tsx +++ b/mobile/src/components/MobileMarkdown.tsx @@ -1,6 +1,7 @@ import { Fragment, memo, useMemo, type ReactNode } from 'react' import { Linking, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native' import { colors, radii, spacing, typography } from '../theme/mobile-theme' +import { normalizeMobileMarkdownPreviewHtml } from './mobile-markdown-preview-html' import { parseMobileMarkdown } from './mobile-markdown-parser' type Props = { @@ -87,7 +88,8 @@ function renderInline(text: string): ReactNode[] { function MobileMarkdownInner({ content, fallback = '' }: Props) { const text = content?.trim() ?? '' - const blocks = useMemo(() => parseMobileMarkdown(text), [text]) + const previewText = useMemo(() => normalizeMobileMarkdownPreviewHtml(text), [text]) + const blocks = useMemo(() => parseMobileMarkdown(previewText), [previewText]) if (!text) { return fallback ? {fallback} : null } diff --git a/mobile/src/components/mobile-markdown-preview-html.ts b/mobile/src/components/mobile-markdown-preview-html.ts new file mode 100644 index 000000000..14965a4ff --- /dev/null +++ b/mobile/src/components/mobile-markdown-preview-html.ts @@ -0,0 +1,98 @@ +// Why: README HTML snippets can document escaped entities; repeated cleanup +// passes must not turn `&lt;` into a real tag and strip it. +const escapedHtmlEntityTokens = [ + { pattern: /&nbsp;/gi, token: '\uE000ORCA_MD_ENTITY_NBSP\uE000', value: ' ' }, + { pattern: /&lt;/gi, token: '\uE000ORCA_MD_ENTITY_LT\uE000', value: '<' }, + { pattern: /&gt;/gi, token: '\uE000ORCA_MD_ENTITY_GT\uE000', value: '>' }, + { pattern: /&quot;/gi, token: '\uE000ORCA_MD_ENTITY_QUOT\uE000', value: '"' }, + { pattern: /&#39;/gi, token: '\uE000ORCA_MD_ENTITY_APOS\uE000', value: ''' } +] as const + +function protectEscapedHtmlEntities(value: string): string { + return escapedHtmlEntityTokens.reduce( + (next, entity) => next.replace(entity.pattern, entity.token), + value + ) +} + +function restoreEscapedHtmlEntities(value: string): string { + return escapedHtmlEntityTokens.reduce( + (next, entity) => next.replaceAll(entity.token, entity.value), + value + ) +} + +function decodeHtmlEntities(value: string, preserveEscapedEntities = false): string { + const next = preserveEscapedEntities ? protectEscapedHtmlEntities(value) : value + + return next + .replace(/ /gi, ' ') + .replace(/</gi, '<') + .replace(/>/gi, '>') + .replace(/"/gi, '"') + .replace(/'/gi, "'") + .replace(/&/gi, '&') +} + +function stripTags(value: string): string { + return decodeHtmlEntities(value.replace(/<[^>]+>/g, ''), true) + .replace(/[ \t]+\n/g, '\n') + .replace(/\n{3,}/g, '\n\n') + .trim() +} + +function attrValue(tag: string, name: string): string { + const pattern = new RegExp(`${name}\\s*=\\s*("[^"]*"|'[^']*'|[^\\s>]+)`, 'i') + const match = tag.match(pattern) + const raw = match?.[1] ?? '' + return decodeHtmlEntities(raw.replace(/^["']|["']$/g, '')) +} + +function normalizeInlineHtml(value: string): string { + return value + .replace(//gi, '\n') + .replace(/]*>/gi, (tag) => attrValue(tag, 'alt') || 'image') + .replace( + /]*href\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)[^>]*>([\s\S]*?)<\/a>/gi, + (tag, _href, label) => { + const href = attrValue(tag, 'href') + const text = stripTags(label) + return href && text ? `[${text}](${href})` : text + } + ) + .replace(/<(strong|b)\b[^>]*>([\s\S]*?)<\/\1>/gi, (_tag, _name, inner) => { + const text = stripTags(inner) + return text ? `**${text}**` : '' + }) + .replace(/<(em|i)\b[^>]*>([\s\S]*?)<\/\1>/gi, (_tag, _name, inner) => { + const text = stripTags(inner) + return text ? `*${text}*` : '' + }) + .replace(/<(code|kbd)\b[^>]*>([\s\S]*?)<\/\1>/gi, (_tag, _name, inner) => { + const text = stripTags(inner) + return text ? `\`${text}\`` : '' + }) +} + +export function normalizeMobileMarkdownPreviewHtml(content: string): string { + let next = content.replace(/\r\n?/g, '\n') + + // Why: repository Markdown often uses small HTML islands for centered README + // headers and badges. Preview mode should read like Markdown, while Source + // mode remains the exact file bytes. + next = next.replace(/]*>([\s\S]*?)<\/h\1>/gi, (_tag, level, inner) => { + const text = stripTags(normalizeInlineHtml(inner)) + return text ? `\n${'#'.repeat(Number(level))} ${text}\n` : '\n' + }) + next = next.replace(/]*>([\s\S]*?)<\/p>/gi, (_tag, inner) => { + const text = stripTags(normalizeInlineHtml(inner)) + return text ? `\n${text}\n` : '\n' + }) + next = next.replace(/]*>([\s\S]*?)<\/sub>/gi, (_tag, inner) => + stripTags(normalizeInlineHtml(inner)) + ) + next = normalizeInlineHtml(next) + next = stripTags(next) + + return restoreEscapedHtmlEntities(next) +} diff --git a/mobile/src/files/MobileFileExplorerPanel.tsx b/mobile/src/files/MobileFileExplorerPanel.tsx index 10df79199..8192eb900 100644 --- a/mobile/src/files/MobileFileExplorerPanel.tsx +++ b/mobile/src/files/MobileFileExplorerPanel.tsx @@ -21,7 +21,6 @@ import { } from 'lucide-react-native' import { useHostClient, useForceReconnect } from '../transport/client-context' import { getWorktreeLabel } from '../session/worktree-label' -import { classifyMobileArtifact } from '../session/mobile-artifact-kind' import { buildTree, flattenTree, @@ -31,9 +30,13 @@ import { type TreeNode } from './file-tree' import type { RpcSuccess } from '../transport/types' -import { triggerError, triggerSelection } from '../platform/haptics' +import { triggerSelection } from '../platform/haptics' import { colors, spacing } from '../theme/mobile-theme' import { fileExplorerStyles as styles } from './mobile-file-explorer-styles' +import { + canPreviewMobileFileRow, + navigateToMobileFilePreview +} from './mobile-file-preview-navigation' export function MobileFileExplorerPanel(props: { hostId: string @@ -50,7 +53,6 @@ export function MobileFileExplorerPanel(props: { const [expanded, setExpanded] = useState>(() => new Set()) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) - const [openingPath, setOpeningPath] = useState(null) const [truncated, setTruncated] = useState(false) const worktreeLabel = getWorktreeLabel(name, worktreeId) @@ -96,36 +98,22 @@ export function MobileFileExplorerPanel(props: { }) }, []) - const openFile = useCallback( - async (relativePath: string) => { - if (!client) { - return - } - setOpeningPath(relativePath) - try { - const response = await client.sendRequest('files.open', { - worktree: `id:${worktreeId}`, - relativePath - }) - if (!response.ok) { - throw new Error(response.error?.message || 'Unable to open file') - } - triggerSelection() - // The file now opens in the session. Full-screen pops back to it; when - // docked the session is already visible, so just close the panel. - if (embedded) { - onRequestClose?.() - } else { - router.back() - } - } catch (err) { - triggerError() - setError(err instanceof Error ? err.message : 'Unable to open file') - } finally { - setOpeningPath(null) - } + const previewFile = useCallback( + (relativePath: string, displayName: string) => { + triggerSelection() + navigateToMobileFilePreview( + router, + { + hostId, + worktreeId, + relativePath, + name: displayName, + worktreeName: name + }, + { embedded, onRequestClose } + ) }, - [client, embedded, onRequestClose, router, worktreeId] + [embedded, hostId, name, onRequestClose, router, worktreeId] ) const renderItem: ListRenderItem = ({ item }) => { @@ -133,8 +121,11 @@ export function MobileFileExplorerPanel(props: { const isExpanded = expanded.has(item.relativePath) // Images render in the mobile viewer (via files.readPreview), so a binary // image is openable; only non-previewable binaries are unavailable. - const isImage = item.kind === 'binary' && classifyMobileArtifact(item.relativePath) === 'image' - const disabled = item.kind === 'binary' && !isImage + const previewable = + item.kind !== 'directory' && + canPreviewMobileFileRow({ kind: item.kind, relativePath: item.relativePath }) + const isImage = item.kind === 'binary' && previewable + const disabled = item.kind === 'binary' && !previewable const markdown = item.kind === 'text' && isMarkdownPath(item.relativePath) return ( { if (isDirectory) { toggleDirectory(item.relativePath) } else if (!disabled) { - void openFile(item.relativePath) + previewFile(item.relativePath, item.name) } }} accessibilityLabel={ @@ -157,7 +148,7 @@ export function MobileFileExplorerPanel(props: { ? `Open folder ${item.name}` : disabled ? `${item.name} unavailable on mobile` - : `Open file ${item.name}` + : `Preview file ${item.name}` } > {isDirectory ? ( @@ -184,9 +175,6 @@ export function MobileFileExplorerPanel(props: { {disabled ? Unavailable on mobile : null} - {openingPath === item.relativePath ? ( - - ) : null} ) } diff --git a/mobile/src/files/MobileFileMarkdownPreview.tsx b/mobile/src/files/MobileFileMarkdownPreview.tsx new file mode 100644 index 000000000..b6e32f47e --- /dev/null +++ b/mobile/src/files/MobileFileMarkdownPreview.tsx @@ -0,0 +1,69 @@ +import { useState } from 'react' +import { Pressable, ScrollView, View } from 'react-native' +import { Code, Pencil } from 'lucide-react-native' +import { MobileMarkdown } from '../components/MobileMarkdown' +import { colors } from '../theme/mobile-theme' +import { + MobileFilePreviewSourceText, + MobileFilePreviewTruncatedNote +} from './MobileFilePreviewSourceText' +import { filePreviewStyles as styles } from './mobile-file-preview-styles' + +type Props = { + relativePath: string + content: string + truncated: boolean + byteLength: number +} + +export function MobileFileMarkdownPreview({ relativePath, content, truncated, byteLength }: Props) { + const [mode, setMode] = useState<'preview' | 'source'>('preview') + const previewSelected = mode === 'preview' + const sourceSelected = mode === 'source' + + return ( + + + setMode('source')} + accessibilityRole="button" + accessibilityState={{ selected: sourceSelected }} + accessibilityLabel="View Markdown source" + > + + + setMode('preview')} + accessibilityRole="button" + accessibilityState={{ selected: previewSelected }} + accessibilityLabel="View rendered Markdown preview" + > + + + + {mode === 'preview' ? ( + + {truncated ? : null} + + + ) : ( + + )} + + ) +} diff --git a/mobile/src/files/MobileFilePreviewScreen.tsx b/mobile/src/files/MobileFilePreviewScreen.tsx new file mode 100644 index 000000000..13bd70547 --- /dev/null +++ b/mobile/src/files/MobileFilePreviewScreen.tsx @@ -0,0 +1,220 @@ +import { useCallback, useEffect, useState } from 'react' +import { + ActivityIndicator, + Image, + Pressable, + ScrollView, + Text, + View, + useWindowDimensions +} from 'react-native' +import { SafeAreaView } from 'react-native-safe-area-context' +import { useRouter } from 'expo-router' +import { ChevronLeft } from 'lucide-react-native' +import { getWorktreeLabel } from '../session/worktree-label' +import { colors, spacing } from '../theme/mobile-theme' +import { useForceReconnect, useHostClient } from '../transport/client-context' +import { + loadMobileFilePreview, + previewError, + type MobileFilePreviewResult +} from './mobile-file-preview-request' +import { MobileFileMarkdownPreview } from './MobileFileMarkdownPreview' +import { MobileFilePreviewSourceText } from './MobileFilePreviewSourceText' +import { + displayNameFromPreviewPath, + type MobileFilePreviewRouteState +} from './mobile-file-preview-route' +import { filePreviewStyles as styles } from './mobile-file-preview-styles' + +type Props = { + route: MobileFilePreviewRouteState +} + +export function MobileFilePreviewScreen({ route }: Props) { + const router = useRouter() + const previewParams = route.ok ? route.params : null + const { client, state: connState } = useHostClient(previewParams?.hostId) + const forceReconnect = useForceReconnect() + const [preview, setPreview] = useState(() => + route.ok ? { status: 'loading', message: 'Loading preview...' } : previewError(route.message) + ) + const { width, height } = useWindowDimensions() + + const loadPreview = useCallback(async () => { + if (!previewParams) { + setPreview(previewError(route.ok ? 'Unable to load preview' : route.message)) + return + } + if (!client || connState !== 'connected') { + setPreview({ status: 'waiting', message: 'Waiting for desktop...', reconnect: true }) + return + } + setPreview({ status: 'loading', message: 'Loading preview...' }) + try { + const result = await loadMobileFilePreview( + client, + previewParams.worktreeId, + previewParams.relativePath + ) + setPreview(result) + } catch (err) { + const message = err instanceof Error ? err.message : 'Unable to load preview' + setPreview(previewError(message)) + } + }, [client, connState, previewParams, route]) + + useEffect(() => { + void loadPreview() + }, [loadPreview]) + + const retry = useCallback(async () => { + if (!previewParams) { + void loadPreview() + return + } + if ( + preview.status === 'waiting' || + (preview.status === 'error' && preview.reconnect) || + connState !== 'connected' + ) { + await forceReconnect(previewParams.hostId) + return + } + void loadPreview() + }, [connState, forceReconnect, loadPreview, preview, previewParams]) + + const title = previewParams?.name ?? displayNameFromPreviewPath(previewParams?.relativePath ?? '') + const worktreeLabel = getWorktreeLabel( + previewParams?.worktreeName, + previewParams?.worktreeId ?? '' + ) + const meta = previewParams ? `${worktreeLabel} - ${previewParams.relativePath}` : 'Preview' + + return ( + + + + [styles.backButton, pressed && styles.backButtonPressed]} + onPress={() => router.back()} + hitSlop={8} + accessibilityLabel="Back to files" + > + + + + + {title || 'Preview'} + + + {meta} + + + + + {renderPreviewBody(preview, { + relativePath: previewParams?.relativePath ?? '', + title: title || 'File', + imageWidth: Math.max(1, width - spacing.md * 2), + imageHeight: Math.max(240, height - 160), + onImageError: () => + setPreview({ status: 'error', message: 'Unable to load preview', reconnect: false }), + onRetry: retry + })} + + ) +} + +function renderPreviewBody( + preview: MobileFilePreviewResult, + options: { + relativePath: string + title: string + imageWidth: number + imageHeight: number + onImageError: () => void + onRetry: () => void + } +) { + if (preview.status === 'loading') { + return ( + + + {preview.message} + + ) + } + + if (preview.status === 'error' || preview.status === 'waiting') { + return ( + + {preview.message} + + Retry + + + ) + } + + if (preview.status === 'empty') { + return ( + + Empty file + + ) + } + + if (preview.kind === 'image') { + return ( + + + + + + ) + } + + if (preview.kind === 'markdown') { + return ( + + ) + } + + if (preview.kind === 'html') { + return ( + + ) + } + + return ( + + ) +} diff --git a/mobile/src/files/MobileFilePreviewSourceText.tsx b/mobile/src/files/MobileFilePreviewSourceText.tsx new file mode 100644 index 000000000..408870d01 --- /dev/null +++ b/mobile/src/files/MobileFilePreviewSourceText.tsx @@ -0,0 +1,41 @@ +import { useMemo } from 'react' +import { ScrollView, Text } from 'react-native' +import { MobileSyntaxSegments } from '../components/MobileSyntaxSegments' +import { formatPreviewByteLength } from './mobile-file-preview-request' +import { buildMobileFilePreviewSyntax } from './mobile-file-preview-syntax' +import { filePreviewStyles as styles } from './mobile-file-preview-styles' + +export function MobileFilePreviewSourceText({ + relativePath, + content, + truncated, + byteLength +}: { + relativePath: string + content: string + truncated?: boolean + byteLength?: number +}) { + const syntax = useMemo( + () => buildMobileFilePreviewSyntax(relativePath, content), + [content, relativePath] + ) + return ( + + {truncated ? ( + + ) : null} + + + + + ) +} + +export function MobileFilePreviewTruncatedNote({ byteLength }: { byteLength: number }) { + return ( + + Preview truncated. File size: {formatPreviewByteLength(byteLength)}. + + ) +} diff --git a/mobile/src/files/mobile-file-preview-navigation.test.ts b/mobile/src/files/mobile-file-preview-navigation.test.ts new file mode 100644 index 000000000..56d3a6247 --- /dev/null +++ b/mobile/src/files/mobile-file-preview-navigation.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, it, vi } from 'vitest' +import { + canPreviewMobileFileRow, + navigateToMobileFilePreview +} from './mobile-file-preview-navigation' + +describe('mobile-file-preview-navigation', () => { + it('navigates preview interactions to the encoded Expo target without files.open', () => { + const push = vi.fn() + const relativePath = 'assets/a #b?c%25 d\\logo.png' + + navigateToMobileFilePreview( + { push }, + { + hostId: 'host-1', + worktreeId: 'wt-1', + relativePath, + name: 'logo.png', + worktreeName: 'Orca' + } + ) + + expect(push).toHaveBeenCalledWith({ + pathname: '/h/[hostId]/files/preview/[worktreeId]', + params: { + hostId: 'host-1', + worktreeId: 'wt-1', + relativePath, + name: 'logo.png', + worktreeName: 'Orca' + } + }) + expect(push).toHaveBeenCalledTimes(1) + }) + + it('defers embedded close until after route push', () => { + const events: string[] = [] + const scheduleClose = vi.fn((callback: () => void) => { + events.push('schedule') + callback() + }) + + navigateToMobileFilePreview( + { + push: () => events.push('push') + }, + { + hostId: 'host-1', + worktreeId: 'wt-1', + relativePath: 'README.md' + }, + { + embedded: true, + scheduleClose, + onRequestClose: () => events.push('close') + } + ) + + expect(events).toEqual(['push', 'schedule', 'close']) + expect(scheduleClose).toHaveBeenCalledWith(expect.any(Function), 0) + }) + + it('keeps non-image binary rows disabled while previewing text and raster images', () => { + expect(canPreviewMobileFileRow({ kind: 'text', relativePath: 'src/app.ts' })).toBe(true) + expect(canPreviewMobileFileRow({ kind: 'binary', relativePath: 'assets/logo.webp' })).toBe(true) + expect(canPreviewMobileFileRow({ kind: 'binary', relativePath: 'archive.zip' })).toBe(false) + }) +}) diff --git a/mobile/src/files/mobile-file-preview-navigation.ts b/mobile/src/files/mobile-file-preview-navigation.ts new file mode 100644 index 000000000..e5024a4fb --- /dev/null +++ b/mobile/src/files/mobile-file-preview-navigation.ts @@ -0,0 +1,37 @@ +import { classifyMobileArtifact } from '../session/mobile-artifact-kind' +import { + createMobileFilePreviewHref, + type MobileFilePreviewHref, + type MobileFilePreviewRouteParams +} from './mobile-file-preview-route' + +export type MobileFilePreviewRouter = { + push: (href: MobileFilePreviewHref) => void +} + +type NavigateOptions = { + embedded?: boolean + onRequestClose?: () => void + scheduleClose?: (callback: () => void, delayMs: number) => unknown +} + +export function navigateToMobileFilePreview( + router: MobileFilePreviewRouter, + params: MobileFilePreviewRouteParams, + options: NavigateOptions = {} +): void { + router.push(createMobileFilePreviewHref(params)) + if (options.embedded && options.onRequestClose) { + // Why: closing the dock immediately can unmount the subtree before Expo + // commits the route transition. + const scheduleClose = options.scheduleClose ?? setTimeout + scheduleClose(options.onRequestClose, 0) + } +} + +export function canPreviewMobileFileRow(item: { + kind: 'text' | 'binary' + relativePath: string +}): boolean { + return item.kind === 'text' || classifyMobileArtifact(item.relativePath) === 'image' +} diff --git a/mobile/src/files/mobile-file-preview-request.test.ts b/mobile/src/files/mobile-file-preview-request.test.ts new file mode 100644 index 000000000..d26901113 --- /dev/null +++ b/mobile/src/files/mobile-file-preview-request.test.ts @@ -0,0 +1,133 @@ +import { describe, expect, it, vi } from 'vitest' +import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types' +import { + createMobileFilePreviewRequest, + formatPreviewByteLength, + loadMobileFilePreview, + normalizeMobileFilePreviewResponse +} from './mobile-file-preview-request' + +function ok(result: unknown): RpcSuccess { + return { id: '1', ok: true, result, _meta: { runtimeId: 'runtime-1' } } +} + +function fail(message: string, code = 'error'): RpcFailure { + return { id: '1', ok: false, error: { code, message }, _meta: { runtimeId: 'runtime-1' } } +} + +function clientWith(response: RpcResponse) { + return { + sendRequest: vi.fn(async () => response) + } +} + +describe('mobile-file-preview-request', () => { + it('selects readPreview for raster images and read for text-like files', () => { + expect(createMobileFilePreviewRequest('wt-1', 'assets/logo.png')).toEqual({ + method: 'files.readPreview', + params: { worktree: 'id:wt-1', relativePath: 'assets/logo.png' } + }) + expect(createMobileFilePreviewRequest('wt-1', 'docs/readme.md')).toEqual({ + method: 'files.read', + params: { worktree: 'id:wt-1', relativePath: 'docs/readme.md' } + }) + expect(createMobileFilePreviewRequest('wt-1', 'public/index.html')).toEqual({ + method: 'files.read', + params: { worktree: 'id:wt-1', relativePath: 'public/index.html' } + }) + }) + + it('loads images through readPreview and never calls files.open', async () => { + const client = clientWith( + ok({ content: 'aW1hZ2U=', isBinary: true, isImage: true, mimeType: 'image/png' }) + ) + + await expect(loadMobileFilePreview(client, 'wt-1', 'assets/logo.png')).resolves.toEqual({ + status: 'ready', + kind: 'image', + dataUri: 'data:image/png;base64,aW1hZ2U=' + }) + expect(client.sendRequest).toHaveBeenCalledWith('files.readPreview', { + worktree: 'id:wt-1', + relativePath: 'assets/logo.png' + }) + expect(client.sendRequest).not.toHaveBeenCalledWith('files.open', expect.anything()) + }) + + it.each([ + ['missing isBinary', { content: 'aW1hZ2U=', isImage: true, mimeType: 'image/png' }], + ['missing isImage', { content: 'aW1hZ2U=', isBinary: true, mimeType: 'image/png' }], + ['missing mimeType', { content: 'aW1hZ2U=', isBinary: true, isImage: true }], + ['empty content', { content: '', isBinary: true, isImage: true, mimeType: 'image/png' }] + ])('rejects invalid image preview results: %s', (_label, result) => { + expect(normalizeMobileFilePreviewResponse('assets/logo.png', ok(result))).toEqual({ + status: 'error', + message: 'Binary preview unavailable', + reconnect: false + }) + }) + + it('normalizes markdown, html, text, empty, and truncated reads', () => { + expect( + normalizeMobileFilePreviewResponse( + 'README.md', + ok({ content: '# Hi', truncated: false, byteLength: 4 }) + ) + ).toEqual({ + status: 'ready', + kind: 'markdown', + content: '# Hi', + truncated: false, + byteLength: 4 + }) + expect( + normalizeMobileFilePreviewResponse( + 'index.html', + ok({ content: '

Hi

', truncated: false, byteLength: 11 }) + ) + ).toMatchObject({ status: 'ready', kind: 'html' }) + expect( + normalizeMobileFilePreviewResponse( + 'src/app.ts', + ok({ content: 'const a = 1', truncated: true, byteLength: 700_000 }) + ) + ).toEqual({ + status: 'ready', + kind: 'text', + content: 'const a = 1', + truncated: true, + byteLength: 700_000 + }) + expect( + normalizeMobileFilePreviewResponse( + 'empty.txt', + ok({ content: '', truncated: false, byteLength: 0 }) + ) + ).toEqual({ status: 'empty', kind: 'text' }) + }) + + it.each([ + ['binary_file', 'Binary preview unavailable', false], + ['file_too_large', 'File too large for mobile preview', false], + ['ENOENT: no such file or directory', 'File not found', false], + [ + 'Remote connection dropped. Click Reconnect on the SSH target before retrying.', + 'Unable to reach the desktop filesystem', + true + ], + ['provider unavailable', 'Unable to reach the desktop filesystem', true], + ['permission denied', 'Unable to load preview', false] + ])('maps preview failure %s', (message, expected, reconnect) => { + expect(normalizeMobileFilePreviewResponse('src/app.ts', fail(message))).toEqual({ + status: 'error', + message: expected, + reconnect + }) + }) + + it('formats truncation byte counts for the UI note', () => { + expect(formatPreviewByteLength(512)).toBe('512 B') + expect(formatPreviewByteLength(4096)).toBe('4 KB') + expect(formatPreviewByteLength(1_572_864)).toBe('1.5 MB') + }) +}) diff --git a/mobile/src/files/mobile-file-preview-request.ts b/mobile/src/files/mobile-file-preview-request.ts new file mode 100644 index 000000000..d7bdc4d3b --- /dev/null +++ b/mobile/src/files/mobile-file-preview-request.ts @@ -0,0 +1,195 @@ +import { classifyMobileArtifact } from '../session/mobile-artifact-kind' +import type { RpcFailure, RpcResponse, RpcSuccess } from '../transport/types' +import type { RpcClient } from '../transport/rpc-client' +import { isMarkdownPath } from './file-tree' + +export type MobileFilePreviewReadMethod = 'files.read' | 'files.readPreview' + +export type MobileFilePreviewRequest = { + method: MobileFilePreviewReadMethod + params: { + worktree: string + relativePath: string + } +} + +export type MobileFilePreviewTextKind = 'html' | 'markdown' | 'text' + +export type MobileFilePreviewResult = + | { + status: 'loading' + message: string + } + | { + status: 'waiting' + message: string + reconnect: true + } + | { + status: 'ready' + kind: 'image' + dataUri: string + } + | { + status: 'ready' + kind: MobileFilePreviewTextKind + content: string + truncated: boolean + byteLength: number + } + | { + status: 'empty' + kind: MobileFilePreviewTextKind + } + | { + status: 'error' + message: string + reconnect: boolean + } + +type MobileFilePreviewClient = Pick + +export function createMobileFilePreviewRequest( + worktreeId: string, + relativePath: string +): MobileFilePreviewRequest { + return { + method: classifyMobileArtifact(relativePath) === 'image' ? 'files.readPreview' : 'files.read', + params: { + worktree: `id:${worktreeId}`, + relativePath + } + } +} + +export async function loadMobileFilePreview( + client: MobileFilePreviewClient, + worktreeId: string, + relativePath: string +): Promise { + const request = createMobileFilePreviewRequest(worktreeId, relativePath) + const response = await client.sendRequest(request.method, request.params) + return normalizeMobileFilePreviewResponse(relativePath, response) +} + +export function normalizeMobileFilePreviewResponse( + relativePath: string, + response: RpcResponse +): MobileFilePreviewResult { + if (!response.ok) { + return previewError( + (response as RpcFailure).error.message || (response as RpcFailure).error.code + ) + } + + const result = (response as RpcSuccess).result + if (classifyMobileArtifact(relativePath) === 'image') { + return normalizeImagePreviewResult(result) + } + return normalizeTextPreviewResult(relativePath, result) +} + +export function previewError(message: string): MobileFilePreviewResult { + const normalized = message.toLowerCase() + if (normalized === 'binary_file' || normalized.includes('binary_file')) { + return { status: 'error', message: 'Binary preview unavailable', reconnect: false } + } + if (normalized === 'file_too_large' || normalized.includes('file_too_large')) { + return { status: 'error', message: 'File too large for mobile preview', reconnect: false } + } + if ( + normalized.includes('remote connection dropped') || + normalized.includes('provider unavailable') || + normalized.includes('disconnected') + ) { + return { status: 'error', message: 'Unable to reach the desktop filesystem', reconnect: true } + } + if ( + normalized.includes('enoent') || + normalized.includes('no such file') || + normalized.includes('not found') || + normalized.includes('does not exist') + ) { + return { status: 'error', message: 'File not found', reconnect: false } + } + return { status: 'error', message: 'Unable to load preview', reconnect: false } +} + +export function formatPreviewByteLength(byteLength: number): string { + if (!Number.isFinite(byteLength) || byteLength < 0) { + return 'unknown size' + } + if (byteLength < 1024) { + return `${byteLength} B` + } + if (byteLength < 1024 * 1024) { + return `${Math.round(byteLength / 1024)} KB` + } + return `${(byteLength / (1024 * 1024)).toFixed(1)} MB` +} + +function normalizeImagePreviewResult(result: unknown): MobileFilePreviewResult { + if (!result || typeof result !== 'object') { + return previewError('binary_file') + } + const preview = result as { + content?: unknown + isBinary?: unknown + isImage?: unknown + mimeType?: unknown + } + if ( + preview.isBinary !== true || + preview.isImage !== true || + typeof preview.mimeType !== 'string' || + preview.mimeType.length === 0 || + typeof preview.content !== 'string' || + preview.content.length === 0 + ) { + return previewError('binary_file') + } + return { + status: 'ready', + kind: 'image', + dataUri: `data:${preview.mimeType};base64,${preview.content}` + } +} + +function normalizeTextPreviewResult( + relativePath: string, + result: unknown +): MobileFilePreviewResult { + if (!result || typeof result !== 'object') { + return previewError('Unable to load preview') + } + const preview = result as { + content?: unknown + truncated?: unknown + byteLength?: unknown + isBinary?: unknown + } + if (preview.isBinary === true) { + return previewError('binary_file') + } + if (typeof preview.content !== 'string') { + return previewError('Unable to load preview') + } + const kind = textKindForPreviewPath(relativePath) + if (preview.content.length === 0) { + return { status: 'empty', kind } + } + return { + status: 'ready', + kind, + content: preview.content, + truncated: preview.truncated === true, + byteLength: typeof preview.byteLength === 'number' ? preview.byteLength : preview.content.length + } +} + +function textKindForPreviewPath(relativePath: string): MobileFilePreviewTextKind { + if (classifyMobileArtifact(relativePath) === 'html') { + return 'html' + } + return isMarkdownPath(relativePath) ? 'markdown' : 'text' +} diff --git a/mobile/src/files/mobile-file-preview-route.test.ts b/mobile/src/files/mobile-file-preview-route.test.ts new file mode 100644 index 000000000..b4cab9418 --- /dev/null +++ b/mobile/src/files/mobile-file-preview-route.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import { + createMobileFilePreviewHref, + displayNameFromPreviewPath, + normalizeMobileFilePreviewRouteParams +} from './mobile-file-preview-route' + +describe('mobile-file-preview-route', () => { + it('normalizes valid route params without changing encoded-sensitive path characters', () => { + const relativePath = 'docs/a #b?c%25 d\\note.md' + const route = normalizeMobileFilePreviewRouteParams({ + hostId: 'host-1', + worktreeId: 'wt-1', + relativePath, + name: 'note.md', + worktreeName: 'Orca' + }) + + expect(route).toEqual({ + ok: true, + params: { + hostId: 'host-1', + worktreeId: 'wt-1', + relativePath, + name: 'note.md', + worktreeName: 'Orca' + } + }) + }) + + it('rejects missing, empty, or array-valued required params', () => { + expect(normalizeMobileFilePreviewRouteParams({ hostId: 'h', worktreeId: 'w' })).toEqual({ + ok: false, + message: 'Unable to load preview' + }) + expect( + normalizeMobileFilePreviewRouteParams({ + hostId: 'h', + worktreeId: 'w', + relativePath: '' + }) + ).toEqual({ ok: false, message: 'Unable to load preview' }) + expect( + normalizeMobileFilePreviewRouteParams({ + hostId: 'h', + worktreeId: 'w', + relativePath: ['a.ts', 'b.ts'] + }) + ).toEqual({ ok: false, message: 'Unable to load preview' }) + }) + + it('builds the Expo href object so Expo owns URL encoding', () => { + const relativePath = 'src/#hash ?query%20\\file.ts' + + expect( + createMobileFilePreviewHref({ + hostId: 'host-1', + worktreeId: 'wt-1', + relativePath, + name: 'file.ts' + }) + ).toEqual({ + pathname: '/h/[hostId]/files/preview/[worktreeId]', + params: { + hostId: 'host-1', + worktreeId: 'wt-1', + relativePath, + name: 'file.ts' + } + }) + }) + + it('derives display names from slash or backslash paths only for display', () => { + expect(displayNameFromPreviewPath('src/app.ts')).toBe('app.ts') + expect(displayNameFromPreviewPath('src\\app.ts')).toBe('app.ts') + }) +}) diff --git a/mobile/src/files/mobile-file-preview-route.ts b/mobile/src/files/mobile-file-preview-route.ts new file mode 100644 index 000000000..b758c1214 --- /dev/null +++ b/mobile/src/files/mobile-file-preview-route.ts @@ -0,0 +1,68 @@ +export type MobileFilePreviewParamValue = string | string[] | undefined + +export type MobileFilePreviewRouteParams = { + hostId: string + worktreeId: string + relativePath: string + name?: string + worktreeName?: string +} + +export type MobileFilePreviewRouteState = + | { ok: true; params: MobileFilePreviewRouteParams } + | { ok: false; message: string } + +export type MobileFilePreviewHref = { + pathname: '/h/[hostId]/files/preview/[worktreeId]' + params: MobileFilePreviewRouteParams +} + +type RawPreviewRouteParams = { + hostId?: MobileFilePreviewParamValue + worktreeId?: MobileFilePreviewParamValue + relativePath?: MobileFilePreviewParamValue + name?: MobileFilePreviewParamValue + worktreeName?: MobileFilePreviewParamValue +} + +function singleParam(value: MobileFilePreviewParamValue): string | null { + return typeof value === 'string' ? value : null +} + +function optionalSingleParam(value: MobileFilePreviewParamValue): string | undefined { + return typeof value === 'string' && value.length > 0 ? value : undefined +} + +export function normalizeMobileFilePreviewRouteParams( + params: RawPreviewRouteParams +): MobileFilePreviewRouteState { + const hostId = singleParam(params.hostId) + const worktreeId = singleParam(params.worktreeId) + const relativePath = singleParam(params.relativePath) + if (!hostId || !worktreeId || !relativePath) { + return { ok: false, message: 'Unable to load preview' } + } + return { + ok: true, + params: { + hostId, + worktreeId, + relativePath, + name: optionalSingleParam(params.name), + worktreeName: optionalSingleParam(params.worktreeName) + } + } +} + +export function createMobileFilePreviewHref( + params: MobileFilePreviewRouteParams +): MobileFilePreviewHref { + return { + pathname: '/h/[hostId]/files/preview/[worktreeId]', + params + } +} + +export function displayNameFromPreviewPath(relativePath: string): string { + return relativePath.split(/[\\/]/).filter(Boolean).at(-1) ?? relativePath +} diff --git a/mobile/src/files/mobile-file-preview-styles.ts b/mobile/src/files/mobile-file-preview-styles.ts new file mode 100644 index 000000000..0e7c2c5db --- /dev/null +++ b/mobile/src/files/mobile-file-preview-styles.ts @@ -0,0 +1,140 @@ +import { StyleSheet } from 'react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' + +export const filePreviewStyles = StyleSheet.create({ + container: { + flex: 1, + backgroundColor: colors.bgBase + }, + header: { + backgroundColor: colors.bgPanel, + borderBottomWidth: StyleSheet.hairlineWidth, + borderBottomColor: colors.borderSubtle + }, + topBar: { + minHeight: 58, + flexDirection: 'row', + alignItems: 'center', + gap: spacing.md, + paddingHorizontal: spacing.md + }, + backButton: { + width: 36, + height: 36, + alignItems: 'center', + justifyContent: 'center', + borderRadius: radii.button + }, + backButtonPressed: { + backgroundColor: colors.bgRaised + }, + titleBlock: { + flex: 1, + minWidth: 0 + }, + title: { + color: colors.textPrimary, + fontSize: typography.titleSize, + fontWeight: '600' + }, + meta: { + marginTop: 2, + color: colors.textSecondary, + fontSize: typography.metaSize + }, + state: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + gap: spacing.md, + padding: spacing.xl + }, + stateText: { + color: colors.textSecondary, + fontSize: typography.bodySize, + textAlign: 'center' + }, + errorText: { + color: colors.statusRed, + fontSize: typography.bodySize, + textAlign: 'center' + }, + retryButton: { + minHeight: 36, + alignItems: 'center', + justifyContent: 'center', + borderRadius: radii.button, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle, + paddingHorizontal: spacing.lg + }, + retryText: { + color: colors.textPrimary, + fontSize: typography.bodySize, + fontWeight: '600' + }, + scroll: { + flex: 1, + backgroundColor: colors.editorSurface + }, + textContent: { + padding: spacing.md, + paddingBottom: spacing.xl + }, + textPreview: { + color: colors.textPrimary, + fontFamily: typography.monoFamily, + fontSize: 13, + lineHeight: 19 + }, + markdownContent: { + padding: spacing.md, + paddingBottom: spacing.xl + }, + modeContainer: { + flex: 1, + backgroundColor: colors.editorSurface + }, + modeToolbar: { + flexDirection: 'row', + alignSelf: 'flex-start', + marginHorizontal: spacing.md, + marginVertical: spacing.sm, + padding: 1, + borderWidth: StyleSheet.hairlineWidth, + borderColor: colors.borderSubtle, + borderRadius: radii.button, + backgroundColor: colors.bgPanel + }, + modeToggle: { + width: 34, + height: 28, + alignItems: 'center', + justifyContent: 'center', + borderRadius: radii.row, + backgroundColor: 'transparent', + opacity: 0.72 + }, + modeToggleActive: { + backgroundColor: colors.bgRaised, + opacity: 1 + }, + truncatedNote: { + marginBottom: spacing.md, + color: colors.textSecondary, + fontSize: typography.metaSize + }, + imageContainer: { + flex: 1, + backgroundColor: colors.editorSurface + }, + imageScrollContent: { + flexGrow: 1, + alignItems: 'center', + justifyContent: 'center', + padding: spacing.md + }, + image: { + backgroundColor: colors.editorSurface + } +}) diff --git a/mobile/src/files/mobile-file-preview-syntax.test.ts b/mobile/src/files/mobile-file-preview-syntax.test.ts new file mode 100644 index 000000000..a4f0a598c --- /dev/null +++ b/mobile/src/files/mobile-file-preview-syntax.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest' +import { buildMobileFilePreviewSyntax } from './mobile-file-preview-syntax' + +describe('mobile-file-preview-syntax', () => { + it('returns syntax segments for supported source paths', () => { + const syntax = buildMobileFilePreviewSyntax('src/app.ts', 'const answer = 42') + + expect(syntax.language).toBe('typescript') + expect(syntax.segments.map((segment) => segment.text).join('')).toBe('const answer = 42') + }) + + it('falls back to a plain segment when highlighting is unavailable', () => { + expect(buildMobileFilePreviewSyntax('README.unknown', 'plain text')).toEqual({ + language: 'plaintext', + segments: [{ kind: 'plain', text: 'plain text' }] + }) + }) +}) diff --git a/mobile/src/files/mobile-file-preview-syntax.ts b/mobile/src/files/mobile-file-preview-syntax.ts new file mode 100644 index 000000000..5288ef807 --- /dev/null +++ b/mobile/src/files/mobile-file-preview-syntax.ts @@ -0,0 +1,30 @@ +import { + highlightMobileCode, + resolveMobileSyntaxLanguage, + type MobileSyntaxSegment +} from '../session/mobile-file-syntax' + +export type MobileFilePreviewSyntax = { + language: string + segments: MobileSyntaxSegment[] +} + +export function buildMobileFilePreviewSyntax( + relativePath: string, + content: string +): MobileFilePreviewSyntax { + try { + const language = resolveMobileSyntaxLanguage(relativePath) + const result = highlightMobileCode(content, language) + return { + language, + segments: result.segments.length > 0 ? result.segments : plainSegments(content) + } + } catch { + return { language: 'plaintext', segments: plainSegments(content) } + } +} + +function plainSegments(content: string): MobileSyntaxSegment[] { + return [{ kind: 'plain', text: content }] +}