The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; |
| 3 | import { |
| 4 | ARCHIVE_ENTRY_MAX_BYTES, |
| 5 | ARCHIVE_MAX_BYTES, |
| 6 | boundedZip, |
| 7 | } from "@t3tools/client-runtime/zip/bounded-zip"; |
| 8 | import { isZipError } from "@t3tools/client-runtime/zip/error"; |
| 9 | import { zipErrorText } from "@t3tools/client-runtime/zip/error-messages"; |
| 10 | import type { EnvironmentId } from "@t3tools/contracts"; |
| 11 | import { filePreviewDelimiter, parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; |
| 12 | import { |
| 13 | decodeFilePreviewText, |
| 14 | filePreviewKind, |
| 15 | hostPreviewMimeTypeFromExtension, |
| 16 | } from "@t3tools/shared/filePreview"; |
| 17 | import { LegendList } from "@legendapp/list/react-native"; |
| 18 | import * as Schema from "effect/Schema"; |
| 19 | import { fetch } from "expo/fetch"; |
| 20 | import { File } from "expo-file-system"; |
| 21 | import { useNavigation, usePreventRemove } from "@react-navigation/native"; |
| 22 | import { msg, T, useGT, useMessages, Var } from "gt-react-native"; |
| 23 | import { useEffect, useEffectEvent, useRef, useState } from "react"; |
| 24 | import { Keyboard, Pressable, ScrollView, TextInput, View } from "react-native"; |
| 25 | |
| 26 | import { PierreEntryIcon } from "../../components/PierreEntryIcon"; |
| 27 | import { AppBar } from "../../components/ui/AppBar"; |
| 28 | import { useContentBottomInset, useContentTopInset } from "../../components/ui/useBarInset"; |
| 29 | import { SymbolView } from "../../components/ui/AppSymbol"; |
| 30 | import { AppText as Text } from "../../components/ui/AppText"; |
| 31 | import { Button } from "../../components/ui/Button"; |
| 32 | import { EmptyState } from "../../components/ui/EmptyState"; |
| 33 | import { Progress } from "../../components/ui/Progress"; |
| 34 | import { NativeScrollView } from "../../native/NativeScrollViewMarker"; |
| 35 | import * as Dialog from "../../components/ui/Dialog"; |
| 36 | import { FilePreviewModal } from "../../components/ui/FilePreviewModal"; |
| 37 | import { m } from "../../i18n/messages"; |
| 38 | import { |
| 39 | nativeViewerErrorMessage, |
| 40 | shareGeneratedAttachment, |
| 41 | writeGeneratedAttachmentFile, |
| 42 | } from "../../lib/attachmentDownload"; |
| 43 | import { attachmentDocumentPresentation } from "../../lib/attachmentDocumentPresentation"; |
| 44 | import { |
| 45 | createComposerFileAttachment, |
| 46 | removePersistedComposerAttachmentFile, |
| 47 | } from "../../lib/composerImages"; |
| 48 | import { appendComposerDraftAttachments } from "../../state/use-composer-drafts"; |
| 49 | import { AttachmentDocumentBody, nativeViewerKind } from "./AttachmentDocumentBody"; |
| 50 | import { FilePreviewLoading } from "./FilePreviewFeedback"; |
| 51 | import { |
| 52 | buildZipTree, |
| 53 | flattenZipTree, |
| 54 | zipDownloadTimeLeft, |
| 55 | zipFolderLabel, |
| 56 | type ZipEntry, |
| 57 | type ZipTreeRow, |
| 58 | } from "./zipTree"; |
| 59 | |
| 60 | export function isZipFile(file: { readonly name: string; readonly mimeType: string }) { |
| 61 | const mime = file.mimeType.split(";", 1)[0]?.trim().toLowerCase(); |
| 62 | return ( |
| 63 | mime === "application/zip" || |
| 64 | mime === "application/x-zip-compressed" || |
| 65 | file.name.toLowerCase().endsWith(".zip") |
| 66 | ); |
| 67 | } |
| 68 | |
| 69 | interface ZipArchive { |
| 70 | readonly entries: ReadonlyArray<ZipEntry>; |
| 71 | readonly fileCount: number; |
| 72 | } |
| 73 | |
| 74 | // title and detail hold msg() strings; they resolve where they render. |
| 75 | const ZipFailure = Schema.Struct({ |
| 76 | title: Schema.String, |
| 77 | detail: Schema.String, |
| 78 | retry: Schema.Boolean, |
| 79 | }); |
| 80 | type ZipFailure = typeof ZipFailure.Type; |
| 81 | |
| 82 | const TOO_LARGE: ZipFailure = { |
| 83 | title: msg("Too large to browse here"), |
| 84 | detail: msg("Browsing works up to {size}. Save the ZIP to open it in another app.", { |
| 85 | size: formatAttachmentSize(ARCHIVE_MAX_BYTES), |
| 86 | }), |
| 87 | retry: false, |
| 88 | }; |
| 89 | const CANCELLED: ZipFailure = { |
| 90 | title: msg("Download cancelled"), |
| 91 | detail: msg("The ZIP wasn't downloaded. Try again to list its files."), |
| 92 | retry: true, |
| 93 | }; |
| 94 | const NETWORK: ZipFailure = { |
| 95 | title: msg("Couldn't download this ZIP"), |
| 96 | detail: msg("Check the connection to this environment and try again."), |
| 97 | retry: true, |
| 98 | }; |
| 99 | |
| 100 | class ZipFailureError extends Schema.TaggedError<ZipFailureError>()("ZipFailureError", { |
| 101 | failure: ZipFailure, |
| 102 | }) { |
| 103 | override get message(): string { |
| 104 | return m(this.failure.title); |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | const isZipFailureError = Schema.is(ZipFailureError); |
| 109 | |
| 110 | function errorMessage(cause: unknown, fallback: string) { |
| 111 | return cause instanceof Error ? (errorDisplayMessage(cause, m) ?? cause.message) : fallback; |
| 112 | } |
| 113 | |
| 114 | async function readArchiveBody( |
| 115 | body: ReadableStream<Uint8Array>, |
| 116 | onProgress: (receivedBytes: number) => void, |
| 117 | ) { |
| 118 | const reader = body.getReader(); |
| 119 | const chunks: Uint8Array[] = []; |
| 120 | let size = 0; |
| 121 | try { |
| 122 | while (true) { |
| 123 | const { value, done } = await reader.read(); |
| 124 | if (done) break; |
| 125 | size += value.byteLength; |
| 126 | if (size > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); |
| 127 | chunks.push(value); |
| 128 | onProgress(size); |
| 129 | } |
| 130 | } finally { |
| 131 | void reader.cancel().catch(() => {}); |
| 132 | } |
| 133 | const bytes = new Uint8Array(size); |
| 134 | let offset = 0; |
| 135 | for (const chunk of chunks) { |
| 136 | bytes.set(chunk, offset); |
| 137 | offset += chunk.byteLength; |
| 138 | } |
| 139 | return bytes.buffer; |
| 140 | } |
| 141 | |
| 142 | async function openArchive(bytes: ArrayBuffer): Promise<ZipArchive> { |
| 143 | let files: Awaited<ReturnType<typeof boundedZip>>; |
| 144 | try { |
| 145 | files = await boundedZip(bytes); |
| 146 | } catch (cause) { |
| 147 | throw new ZipFailureError({ |
| 148 | failure: { |
| 149 | title: msg("Couldn't browse this ZIP"), |
| 150 | detail: |
| 151 | cause instanceof Error |
| 152 | ? msg("{error} Save the ZIP to open it in another app.", { |
| 153 | error: isZipError(cause) ? zipErrorText(cause.code, m) : cause.message, |
| 154 | }) |
| 155 | : msg("It may be incomplete or damaged. Save the ZIP to open it in another app."), |
| 156 | retry: false, |
| 157 | }, |
| 158 | }); |
| 159 | } |
| 160 | const entries = [...files].map(([path, file]): ZipEntry => { |
| 161 | const name = path.split("/").findLast(Boolean) ?? path; |
| 162 | const dot = name.lastIndexOf("."); |
| 163 | return { |
| 164 | path, |
| 165 | name, |
| 166 | isDirectory: file.directory, |
| 167 | sizeBytes: file.bytes.byteLength, |
| 168 | mimeType: |
| 169 | (dot > 0 ? hostPreviewMimeTypeFromExtension(name.slice(dot).toLowerCase()) : null) ?? |
| 170 | "application/octet-stream", |
| 171 | bytes: file.bytes, |
| 172 | }; |
| 173 | }); |
| 174 | return { entries, fileCount: entries.filter((entry) => !entry.isDirectory).length }; |
| 175 | } |
| 176 | |
| 177 | type ArchiveState = |
| 178 | | { readonly status: "loading"; readonly receivedBytes: number; readonly timeLeft: string | null } |
| 179 | | { readonly status: "ready"; readonly archive: ZipArchive } |
| 180 | | { readonly status: "failed"; readonly failure: ZipFailure }; |
| 181 | |
| 182 | function useZipArchive(input: { |
| 183 | readonly uri: string | null; |
| 184 | readonly isLocal: boolean; |
| 185 | readonly sizeBytes: number; |
| 186 | readonly refresh: () => Promise<string | null>; |
| 187 | }) { |
| 188 | const [state, setState] = useState<ArchiveState>({ |
| 189 | status: "loading", |
| 190 | receivedBytes: 0, |
| 191 | timeLeft: null, |
| 192 | }); |
| 193 | const [revision, setRevision] = useState(0); |
| 194 | const controller = useRef<AbortController | null>(null); |
| 195 | const { uri, isLocal, sizeBytes } = input; |
| 196 | // The parent mints a new refresh callback on every render; it must not reload the archive. |
| 197 | const refresh = useEffectEvent(input.refresh); |
| 198 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Load archive bytes and cancel the stream on cleanup. |
| 199 | useEffect(() => { |
| 200 | if (!uri) return; |
| 201 | const abort = new AbortController(); |
| 202 | controller.current = abort; |
| 203 | const startedAt = Date.now(); |
| 204 | // oxlint-disable-next-line react/set-state-in-effect -- A new archive load resets its progress. |
| 205 | setState({ status: "loading", receivedBytes: 0, timeLeft: null }); |
| 206 | void (async () => { |
| 207 | if (sizeBytes > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); |
| 208 | if (isLocal) { |
| 209 | const file = new File(uri); |
| 210 | if ((file.size ?? 0) > ARCHIVE_MAX_BYTES) throw new ZipFailureError({ failure: TOO_LARGE }); |
| 211 | return openArchive(await file.arrayBuffer()); |
| 212 | } |
| 213 | const url = (await refresh()) ?? uri; |
| 214 | const response = await fetch(url, { signal: abort.signal }); |
| 215 | if (!response.ok || !response.body) throw new ZipFailureError({ failure: NETWORK }); |
| 216 | const bytes = await readArchiveBody(response.body, (receivedBytes) => |
| 217 | setState({ |
| 218 | status: "loading", |
| 219 | receivedBytes, |
| 220 | timeLeft: zipDownloadTimeLeft({ |
| 221 | receivedBytes, |
| 222 | totalBytes: sizeBytes, |
| 223 | elapsedMs: Date.now() - startedAt, |
| 224 | }), |
| 225 | }), |
| 226 | ); |
| 227 | abort.signal.throwIfAborted(); |
| 228 | return openArchive(bytes); |
| 229 | })() |
| 230 | .then((archive) => { |
| 231 | if (!abort.signal.aborted) setState({ status: "ready", archive }); |
| 232 | }) |
| 233 | .catch((cause: unknown) => { |
| 234 | if (!abort.signal.aborted) |
| 235 | setState({ |
| 236 | status: "failed", |
| 237 | failure: isZipFailureError(cause) ? cause.failure : NETWORK, |
| 238 | }); |
| 239 | }); |
| 240 | return () => abort.abort(); |
| 241 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reload the archive. |
| 242 | }, [uri, isLocal, sizeBytes, revision]); |
| 243 | return { |
| 244 | state, |
| 245 | retry: () => setRevision((value) => value + 1), |
| 246 | cancel: () => { |
| 247 | controller.current?.abort(); |
| 248 | setState({ status: "failed", failure: CANCELLED }); |
| 249 | }, |
| 250 | }; |
| 251 | } |
| 252 | |
| 253 | function ZipTreeRowView(props: { |
| 254 | readonly row: ZipTreeRow; |
| 255 | readonly collapsed: boolean; |
| 256 | readonly onToggle: (path: string) => void; |
| 257 | readonly onOpen: (entry: ZipEntry) => void; |
| 258 | }) { |
| 259 | const { node, depth } = props.row; |
| 260 | const entry = node.entry; |
| 261 | const gt = useGT(); |
| 262 | const messages = useMessages(); |
| 263 | const folder = entry ? null : zipFolderLabel(node.label); |
| 264 | return ( |
| 265 | <Pressable |
| 266 | accessibilityRole="button" |
| 267 | accessibilityLabel={entry ? entry.path : gt("{path} folder", { path: node.path })} |
| 268 | accessibilityState={entry ? undefined : { expanded: !props.collapsed }} |
| 269 | onPress={() => (entry ? props.onOpen(entry) : props.onToggle(node.path))} |
| 270 | className="mx-2 h-11 flex-row items-center gap-1.5 rounded-lg pr-2.5 active:bg-subtle" |
| 271 | style={{ paddingLeft: 8 + depth * 18 }} |
| 272 | > |
| 273 | <View className="w-4 items-center"> |
| 274 | {entry ? null : ( |
| 275 | <SymbolView |
| 276 | name={props.collapsed ? "chevron.right" : "chevron.down"} |
| 277 | size={12} |
| 278 | tintColorClassName="accent-icon-muted" |
| 279 | type="monochrome" |
| 280 | /> |
| 281 | )} |
| 282 | </View> |
| 283 | <View className="w-5 items-center"> |
| 284 | <PierreEntryIcon path={node.path} kind={entry ? "file" : "directory"} size={17} /> |
| 285 | </View> |
| 286 | <Text className="min-w-0 flex-1 text-[15px] text-foreground" numberOfLines={1}> |
| 287 | {folder ? ( |
| 288 | <> |
| 289 | <Text className="text-[15px] text-foreground-muted">{folder.prefix}</Text> |
| 290 | {folder.name} |
| 291 | </> |
| 292 | ) : ( |
| 293 | node.label |
| 294 | )} |
| 295 | </Text> |
| 296 | <Text className="text-xs text-foreground-muted"> |
| 297 | {entry |
| 298 | ? formatAttachmentSize(entry.sizeBytes, messages) |
| 299 | : props.collapsed |
| 300 | ? gt("{count, plural, one {{count} file} other {{count} files}}", { |
| 301 | count: node.fileCount, |
| 302 | }) |
| 303 | : ""} |
| 304 | </Text> |
| 305 | </Pressable> |
| 306 | ); |
| 307 | } |
| 308 | |
| 309 | function ZipArchiveHeader(props: { |
| 310 | readonly name: string; |
| 311 | readonly subtitle: string; |
| 312 | readonly onSave: () => void; |
| 313 | readonly onRemove: (() => void) | null; |
| 314 | }) { |
| 315 | const navigation = useNavigation(); |
| 316 | const gt = useGT(); |
| 317 | return ( |
| 318 | <AppBar |
| 319 | title={props.name} |
| 320 | subtitle={props.subtitle} |
| 321 | onBack={() => { |
| 322 | if (navigation.canGoBack()) navigation.goBack(); |
| 323 | }} |
| 324 | actions={[ |
| 325 | { accessibilityLabel: gt("Save ZIP"), icon: "square.and.arrow.up", onPress: props.onSave }, |
| 326 | ...(props.onRemove |
| 327 | ? [ |
| 328 | { |
| 329 | accessibilityLabel: gt("Remove from draft"), |
| 330 | icon: "trash" as const, |
| 331 | onPress: props.onRemove, |
| 332 | destructive: true, |
| 333 | overflowOnly: true, |
| 334 | }, |
| 335 | ] |
| 336 | : []), |
| 337 | ]} |
| 338 | /> |
| 339 | ); |
| 340 | } |
| 341 | |
| 342 | function ZipArchiveProgress(props: { |
| 343 | readonly receivedBytes: number; |
| 344 | readonly totalBytes: number; |
| 345 | readonly timeLeft: string | null; |
| 346 | readonly onCancel: () => void; |
| 347 | }) { |
| 348 | const { timeLeft } = props; |
| 349 | const gt = useGT(); |
| 350 | const messages = useMessages(); |
| 351 | return ( |
| 352 | <View className="flex-1 justify-center gap-3 bg-sheet px-8"> |
| 353 | <Text className="text-xl font-t3-semibold text-foreground"> |
| 354 | {props.totalBytes > 0 ? ( |
| 355 | <T> |
| 356 | <Var>{formatAttachmentSize(props.receivedBytes, messages)}</Var> |
| 357 | <Text className="text-xl text-foreground-muted"> |
| 358 | {" "} |
| 359 | of <Var>{formatAttachmentSize(props.totalBytes, messages)}</Var> |
| 360 | </Text> |
| 361 | </T> |
| 362 | ) : ( |
| 363 | formatAttachmentSize(props.receivedBytes, messages) |
| 364 | )} |
| 365 | </Text> |
| 366 | <Progress |
| 367 | value={props.totalBytes > 0 ? props.receivedBytes / props.totalBytes : undefined} |
| 368 | label={gt("ZIP download progress")} |
| 369 | /> |
| 370 | <Text className="text-sm text-foreground-muted"> |
| 371 | {timeLeft |
| 372 | ? gt("Downloading the ZIP so its files can be listed. {timeLeft} on this connection.", { |
| 373 | timeLeft, |
| 374 | }) |
| 375 | : gt("Downloading the ZIP so its files can be listed.")} |
| 376 | </Text> |
| 377 | <Button label={gt("Cancel")} onPress={props.onCancel} /> |
| 378 | </View> |
| 379 | ); |
| 380 | } |
| 381 | |
| 382 | function ZipArchiveFailure(props: { |
| 383 | readonly failure: ZipFailure; |
| 384 | readonly onRetry: () => void; |
| 385 | readonly onSave: () => void; |
| 386 | }) { |
| 387 | const gt = useGT(); |
| 388 | const resolveMessage = useMessages(); |
| 389 | return ( |
| 390 | <View className="flex-1 items-center justify-center bg-sheet px-6"> |
| 391 | <EmptyState |
| 392 | variant="plain" |
| 393 | title={resolveMessage(props.failure.title)} |
| 394 | detail={resolveMessage(props.failure.detail)} |
| 395 | action={ |
| 396 | <View className="flex-row gap-3"> |
| 397 | {props.failure.retry ? ( |
| 398 | <Button tone="primary" label={gt("Try again")} onPress={props.onRetry} /> |
| 399 | ) : null} |
| 400 | <Button |
| 401 | tone={props.failure.retry ? "secondary" : "primary"} |
| 402 | label={gt("Save ZIP")} |
| 403 | onPress={props.onSave} |
| 404 | /> |
| 405 | </View> |
| 406 | } |
| 407 | /> |
| 408 | </View> |
| 409 | ); |
| 410 | } |
| 411 | |
| 412 | function ZipArchiveList(props: { |
| 413 | readonly archive: ZipArchive; |
| 414 | readonly headerInset: number; |
| 415 | readonly onOpen: (entry: ZipEntry) => void; |
| 416 | }) { |
| 417 | const gt = useGT(); |
| 418 | const [query, setQuery] = useState(""); |
| 419 | const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set()); |
| 420 | const { archive } = props; |
| 421 | const rows = flattenZipTree(buildZipTree(archive.entries), collapsed, query); |
| 422 | const toggle = (path: string) => |
| 423 | setCollapsed((current) => { |
| 424 | const next = new Set(current); |
| 425 | if (!next.delete(path)) next.add(path); |
| 426 | return next; |
| 427 | }); |
| 428 | const fileCount = archive.fileCount; |
| 429 | const bottomInset = useContentBottomInset(); |
| 430 | return ( |
| 431 | <View className="flex-1 bg-sheet"> |
| 432 | <LegendList |
| 433 | renderScrollComponent={NativeScrollView} |
| 434 | contentInset={{ top: props.headerInset, bottom: bottomInset }} |
| 435 | className="flex-1" |
| 436 | data={rows} |
| 437 | keyExtractor={(row) => `${row.node.entry ? "f" : "d"}:${row.node.path}`} |
| 438 | contentInsetAdjustmentBehavior="never" |
| 439 | automaticallyAdjustsScrollIndicatorInsets |
| 440 | estimatedItemSize={44} |
| 441 | recycleItems |
| 442 | keyboardDismissMode="on-drag" |
| 443 | keyboardShouldPersistTaps="handled" |
| 444 | extraData={collapsed} |
| 445 | contentContainerStyle={{ paddingBottom: 4 }} |
| 446 | ListHeaderComponent={ |
| 447 | <View className="px-4 pt-3 pb-2.5"> |
| 448 | <View className="h-[38px] flex-row items-center gap-2 rounded-[10px] bg-subtle px-3"> |
| 449 | <SymbolView name="magnifyingglass" size={15} tintColorClassName="accent-icon-muted" /> |
| 450 | <TextInput |
| 451 | accessibilityLabel={gt("Filter files in ZIP")} |
| 452 | autoCapitalize="none" |
| 453 | autoCorrect={false} |
| 454 | placeholder={gt( |
| 455 | "{count, plural, one {Filter {count} file} other {Filter {count} files}}", |
| 456 | { count: fileCount }, |
| 457 | )} |
| 458 | placeholderTextColorClassName="accent-placeholder" |
| 459 | cursorColorClassName="accent-focus" |
| 460 | className="min-w-0 flex-1 font-sans text-[15px] text-foreground" |
| 461 | value={query} |
| 462 | onChangeText={setQuery} |
| 463 | /> |
| 464 | {query ? ( |
| 465 | <Pressable |
| 466 | accessibilityRole="button" |
| 467 | accessibilityLabel={gt("Clear filter")} |
| 468 | hitSlop={10} |
| 469 | onPress={() => setQuery("")} |
| 470 | > |
| 471 | <SymbolView |
| 472 | name="xmark.circle.fill" |
| 473 | size={16} |
| 474 | tintColorClassName="accent-icon-muted" |
| 475 | /> |
| 476 | </Pressable> |
| 477 | ) : null} |
| 478 | </View> |
| 479 | </View> |
| 480 | } |
| 481 | renderItem={({ item }) => ( |
| 482 | <ZipTreeRowView |
| 483 | row={item} |
| 484 | collapsed={collapsed.has(item.node.path)} |
| 485 | onToggle={toggle} |
| 486 | onOpen={props.onOpen} |
| 487 | /> |
| 488 | )} |
| 489 | ListEmptyComponent={ |
| 490 | query ? ( |
| 491 | <EmptyState |
| 492 | variant="plain" |
| 493 | title={gt("No files match “{query}”", { query: query.trim() })} |
| 494 | detail={gt("The filter checks file names and folder paths.")} |
| 495 | action={<Button label={gt("Clear filter")} onPress={() => setQuery("")} />} |
| 496 | /> |
| 497 | ) : ( |
| 498 | <EmptyState |
| 499 | variant="plain" |
| 500 | title={gt("This ZIP is empty")} |
| 501 | detail={gt("It has no files.")} |
| 502 | /> |
| 503 | ) |
| 504 | } |
| 505 | /> |
| 506 | </View> |
| 507 | ); |
| 508 | } |
| 509 | |
| 510 | export function ZipArchiveView(props: { |
| 511 | readonly name: string; |
| 512 | readonly subtitle: string; |
| 513 | readonly sizeBytes: number; |
| 514 | readonly uri: string | null; |
| 515 | readonly isLocal: boolean; |
| 516 | readonly refresh: () => Promise<string | null>; |
| 517 | readonly environmentId: EnvironmentId | null; |
| 518 | readonly draftKey: string | null; |
| 519 | readonly maxAttachmentBytes: number | undefined; |
| 520 | readonly onSave: () => void; |
| 521 | readonly onRemove: (() => void) | null; |
| 522 | }) { |
| 523 | const { state, retry, cancel } = useZipArchive(props); |
| 524 | const gt = useGT(); |
| 525 | const messages = useMessages(); |
| 526 | const [selection, setSelection] = useState<{ |
| 527 | readonly archive: ZipArchive; |
| 528 | readonly entry: ZipEntry; |
| 529 | } | null>(null); |
| 530 | const archive = state.status === "ready" ? state.archive : null; |
| 531 | const selected = selection && selection.archive === archive ? selection.entry : null; |
| 532 | const entryOpen = selected !== null; |
| 533 | usePreventRemove(entryOpen, () => setSelection(null)); |
| 534 | const headerInset = useContentTopInset(); |
| 535 | return ( |
| 536 | <View className="flex-1 bg-sheet"> |
| 537 | {entryOpen ? null : ( |
| 538 | <ZipArchiveHeader |
| 539 | name={props.name} |
| 540 | subtitle={ |
| 541 | archive |
| 542 | ? props.sizeBytes > 0 |
| 543 | ? gt( |
| 544 | "{count, plural, one {{count} file · {size}} other {{count} files · {size}}}", |
| 545 | { |
| 546 | count: archive.fileCount, |
| 547 | size: formatAttachmentSize(props.sizeBytes, messages), |
| 548 | }, |
| 549 | ) |
| 550 | : gt("{count, plural, one {{count} file} other {{count} files}}", { |
| 551 | count: archive.fileCount, |
| 552 | }) |
| 553 | : props.subtitle |
| 554 | } |
| 555 | onSave={props.onSave} |
| 556 | onRemove={props.onRemove} |
| 557 | /> |
| 558 | )} |
| 559 | {state.status === "ready" ? ( |
| 560 | <ZipArchiveList |
| 561 | archive={state.archive} |
| 562 | headerInset={headerInset} |
| 563 | onOpen={(entry) => { |
| 564 | Keyboard.dismiss(); |
| 565 | setSelection({ archive: state.archive, entry }); |
| 566 | }} |
| 567 | /> |
| 568 | ) : ( |
| 569 | <View className="flex-1" style={{ paddingTop: headerInset }}> |
| 570 | {state.status === "loading" ? ( |
| 571 | props.isLocal || state.receivedBytes === 0 ? ( |
| 572 | <FilePreviewLoading message={gt("Opening ZIP...")} /> |
| 573 | ) : ( |
| 574 | <ZipArchiveProgress |
| 575 | receivedBytes={state.receivedBytes} |
| 576 | totalBytes={props.sizeBytes} |
| 577 | timeLeft={state.timeLeft} |
| 578 | onCancel={cancel} |
| 579 | /> |
| 580 | ) |
| 581 | ) : ( |
| 582 | <ZipArchiveFailure failure={state.failure} onRetry={retry} onSave={props.onSave} /> |
| 583 | )} |
| 584 | </View> |
| 585 | )} |
| 586 | {selected ? ( |
| 587 | <View className="absolute inset-0"> |
| 588 | <ZipEntryView |
| 589 | key={selected.path} |
| 590 | archiveName={props.name} |
| 591 | entry={selected} |
| 592 | environmentId={props.environmentId} |
| 593 | draftKey={props.draftKey} |
| 594 | maxAttachmentBytes={props.maxAttachmentBytes} |
| 595 | onBack={() => setSelection(null)} |
| 596 | /> |
| 597 | </View> |
| 598 | ) : null} |
| 599 | </View> |
| 600 | ); |
| 601 | } |
| 602 | |
| 603 | async function addZipEntryToDraft(input: { |
| 604 | readonly entry: ZipEntry; |
| 605 | readonly draftKey: string; |
| 606 | readonly maxBytes: number; |
| 607 | readonly signal: AbortSignal; |
| 608 | }) { |
| 609 | const { entry, signal } = input; |
| 610 | const file = await writeGeneratedAttachmentFile({ |
| 611 | bytes: entry.bytes, |
| 612 | attachment: { name: entry.name, mimeType: entry.mimeType }, |
| 613 | }); |
| 614 | try { |
| 615 | signal.throwIfAborted(); |
| 616 | const attachment = await createComposerFileAttachment({ |
| 617 | uri: file.uri, |
| 618 | name: entry.name, |
| 619 | mimeType: entry.mimeType, |
| 620 | sizeBytes: entry.sizeBytes, |
| 621 | maxBytes: input.maxBytes, |
| 622 | }); |
| 623 | if (signal.aborted) { |
| 624 | await removePersistedComposerAttachmentFile(attachment.fileUri); |
| 625 | signal.throwIfAborted(); |
| 626 | } |
| 627 | // Rejected attachments are cleaned up by the draft store. |
| 628 | if (appendComposerDraftAttachments(input.draftKey, [attachment], { appendReference: true })) |
| 629 | throw new Error(m(msg("This message already has as many attachments as it can hold."))); |
| 630 | } finally { |
| 631 | file.dispose(); |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | type EntryContent = |
| 636 | | { readonly status: "loading" } |
| 637 | | { readonly status: "text"; readonly text: string; readonly truncated: boolean } |
| 638 | | { readonly status: "file"; readonly uri: string } |
| 639 | | { |
| 640 | readonly status: "failed"; |
| 641 | readonly reason: "tooBig" | "unreadable"; |
| 642 | readonly detail: string | null; |
| 643 | }; |
| 644 | |
| 645 | function ZipEntryView(props: { |
| 646 | readonly archiveName: string; |
| 647 | readonly entry: ZipEntry; |
| 648 | readonly environmentId: EnvironmentId | null; |
| 649 | readonly draftKey: string | null; |
| 650 | readonly maxAttachmentBytes: number | undefined; |
| 651 | readonly onBack: () => void; |
| 652 | }) { |
| 653 | const { entry, draftKey, maxAttachmentBytes } = props; |
| 654 | const gt = useGT(); |
| 655 | const messages = useMessages(); |
| 656 | const { mimeType } = entry; |
| 657 | const previewKind = filePreviewKind({ name: entry.name, mimeType }); |
| 658 | const isText = previewKind === "text" || previewKind === "markdown" || previewKind === "html"; |
| 659 | // Archive HTML is shown as source: a rendered page could load its sibling files. |
| 660 | const kind = previewKind === "html" ? "text" : previewKind; |
| 661 | const viewerKind = isText || kind === "audio" ? null : (nativeViewerKind(kind) ?? "document"); |
| 662 | const tooBig = entry.sizeBytes > ARCHIVE_ENTRY_MAX_BYTES; |
| 663 | const [content, setContent] = useState<EntryContent>( |
| 664 | tooBig ? { status: "failed", reason: "tooBig", detail: null } : { status: "loading" }, |
| 665 | ); |
| 666 | const [rendered, setRendered] = useState(true); |
| 667 | const [revision, setRevision] = useState(0); |
| 668 | const [viewerOpen, setViewerOpen] = useState(true); |
| 669 | const [viewerError, setViewerError] = useState<string | null>(null); |
| 670 | const [busy, setBusy] = useState<"save" | "attach" | null>(null); |
| 671 | const action = useRef<AbortController | null>(null); |
| 672 | const pendingViewerError = useRef<string | null>(null); |
| 673 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Cancel a pending save or attach when the entry closes. |
| 674 | useEffect(() => () => action.current?.abort(), []); |
| 675 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Write the selected entry to a cached file and release it on cleanup. |
| 676 | useEffect(() => { |
| 677 | if (tooBig) return; |
| 678 | const controller = new AbortController(); |
| 679 | let release: (() => void) | undefined; |
| 680 | void (async (): Promise<EntryContent> => { |
| 681 | if (isText) return { status: "text", ...decodeFilePreviewText(entry.bytes) }; |
| 682 | const file = await writeGeneratedAttachmentFile({ |
| 683 | bytes: entry.bytes, |
| 684 | attachment: { name: entry.name, mimeType }, |
| 685 | }); |
| 686 | if (controller.signal.aborted) { |
| 687 | file.dispose(); |
| 688 | controller.signal.throwIfAborted(); |
| 689 | } |
| 690 | release = file.dispose; |
| 691 | return { status: "file", uri: file.uri }; |
| 692 | })() |
| 693 | .then((value) => { |
| 694 | if (!controller.signal.aborted) setContent(value); |
| 695 | }) |
| 696 | .catch((cause: unknown) => { |
| 697 | if (!controller.signal.aborted) |
| 698 | setContent({ |
| 699 | status: "failed", |
| 700 | reason: "unreadable", |
| 701 | detail: |
| 702 | cause instanceof Error ? (errorDisplayMessage(cause, m) ?? cause.message) : null, |
| 703 | }); |
| 704 | }); |
| 705 | return () => { |
| 706 | controller.abort(); |
| 707 | release?.(); |
| 708 | }; |
| 709 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reread the entry. |
| 710 | }, [entry, isText, mimeType, tooBig, revision]); |
| 711 | |
| 712 | const run = (kind: "save" | "attach", task: (signal: AbortSignal) => Promise<unknown>) => { |
| 713 | if (busy) return; |
| 714 | setBusy(kind); |
| 715 | const controller = new AbortController(); |
| 716 | action.current = controller; |
| 717 | void task(controller.signal).then( |
| 718 | () => { |
| 719 | if (controller.signal.aborted) return; |
| 720 | setBusy(null); |
| 721 | }, |
| 722 | (cause: unknown) => { |
| 723 | if (controller.signal.aborted) return; |
| 724 | setBusy(null); |
| 725 | Dialog.alert( |
| 726 | kind === "save" ? m(msg("Could not save file")) : m(msg("Could not add file to chat")), |
| 727 | errorMessage(cause, m(msg("Please try again."))), |
| 728 | ); |
| 729 | }, |
| 730 | ); |
| 731 | }; |
| 732 | const save = () => |
| 733 | run("save", (signal) => |
| 734 | shareGeneratedAttachment({ |
| 735 | bytes: entry.bytes, |
| 736 | attachment: { name: entry.name, mimeType }, |
| 737 | signal, |
| 738 | }), |
| 739 | ); |
| 740 | const canAddToChat = draftKey !== null && maxAttachmentBytes !== undefined; |
| 741 | const addToChat = () => { |
| 742 | if (draftKey === null || maxAttachmentBytes === undefined) return; |
| 743 | run("attach", (signal) => |
| 744 | addZipEntryToDraft({ entry, draftKey, maxBytes: maxAttachmentBytes, signal }), |
| 745 | ); |
| 746 | }; |
| 747 | const openViewer = () => { |
| 748 | setViewerError(null); |
| 749 | setViewerOpen(true); |
| 750 | }; |
| 751 | |
| 752 | const text = content.status === "text" ? content : null; |
| 753 | const delimiter = filePreviewDelimiter({ name: entry.name, mimeType }); |
| 754 | const table = text && delimiter ? parseDelimitedPreview(text.text, delimiter) : null; |
| 755 | const uri = content.status === "file" ? content.uri : null; |
| 756 | const { renderedMode, activeMode } = attachmentDocumentPresentation({ |
| 757 | kind, |
| 758 | hasTable: table !== null, |
| 759 | hasEnvironment: props.environmentId !== null, |
| 760 | rendered, |
| 761 | }); |
| 762 | const folders = entry.path.split("/").slice(0, -1); |
| 763 | const subtitle = `${[props.archiveName, ...folders].join(" / ")} · ${formatAttachmentSize(entry.sizeBytes, messages)}`; |
| 764 | return ( |
| 765 | <View className="flex-1 bg-sheet"> |
| 766 | <AppBar |
| 767 | title={entry.name} |
| 768 | subtitle={subtitle} |
| 769 | onBack={props.onBack} |
| 770 | menus={[ |
| 771 | { |
| 772 | title: gt("File actions"), |
| 773 | icon: "ellipsis", |
| 774 | items: [ |
| 775 | ...(renderedMode |
| 776 | ? [ |
| 777 | { |
| 778 | id: "toggle-rendered", |
| 779 | title: rendered ? gt("Show source") : gt("Show preview"), |
| 780 | icon: rendered ? "doc.text" : "eye", |
| 781 | onPress: () => setRendered((value) => !value), |
| 782 | }, |
| 783 | ] |
| 784 | : []), |
| 785 | ...(canAddToChat |
| 786 | ? [ |
| 787 | { |
| 788 | id: "add-to-chat", |
| 789 | title: gt("Add to chat"), |
| 790 | icon: "plus.bubble", |
| 791 | disabled: busy !== null, |
| 792 | onPress: addToChat, |
| 793 | }, |
| 794 | ] |
| 795 | : []), |
| 796 | { |
| 797 | id: "save", |
| 798 | title: gt("Save file"), |
| 799 | icon: "square.and.arrow.up", |
| 800 | disabled: busy !== null, |
| 801 | onPress: save, |
| 802 | }, |
| 803 | ], |
| 804 | }, |
| 805 | ]} |
| 806 | /> |
| 807 | {content.status === "failed" ? ( |
| 808 | <ScrollView contentContainerClassName="flex-grow items-center justify-center px-6"> |
| 809 | <EmptyState |
| 810 | variant="plain" |
| 811 | title={ |
| 812 | content.reason === "tooBig" ? gt("Too big to preview") : gt("Couldn't read this file") |
| 813 | } |
| 814 | detail={ |
| 815 | content.reason === "tooBig" |
| 816 | ? gt("Previews stop at {size}. Save the file to open it in another app.", { |
| 817 | size: formatAttachmentSize(ARCHIVE_ENTRY_MAX_BYTES, messages), |
| 818 | }) |
| 819 | : (content.detail ?? gt("Could not read this file.")) |
| 820 | } |
| 821 | action={ |
| 822 | <Button |
| 823 | tone="primary" |
| 824 | label={gt("Save file")} |
| 825 | loading={busy === "save"} |
| 826 | onPress={save} |
| 827 | /> |
| 828 | } |
| 829 | /> |
| 830 | </ScrollView> |
| 831 | ) : viewerKind && uri && !viewerOpen ? ( |
| 832 | // Closing the viewer stays here so Save and Add to chat remain reachable. |
| 833 | <View className="flex-1 items-center justify-center bg-sheet px-6"> |
| 834 | <EmptyState |
| 835 | title={viewerError ? gt("No preview for this file") : entry.name} |
| 836 | detail={viewerError ?? gt("Open it in the file viewer, save it, or add it to chat.")} |
| 837 | actionLabel={gt("Open in file viewer")} |
| 838 | onAction={openViewer} |
| 839 | /> |
| 840 | </View> |
| 841 | ) : ( |
| 842 | <AttachmentDocumentBody |
| 843 | document={{ |
| 844 | kind, |
| 845 | activeMode, |
| 846 | uri, |
| 847 | content: text, |
| 848 | table, |
| 849 | error: null, |
| 850 | needsText: isText, |
| 851 | retry: () => setRevision((value) => value + 1), |
| 852 | revision, |
| 853 | }} |
| 854 | name={entry.name} |
| 855 | environmentId={props.environmentId} |
| 856 | htmlRender={false} |
| 857 | nativeViewer={viewerKind ? (uri ? "open" : "pending") : null} |
| 858 | nativeError={null} |
| 859 | onOpenNative={openViewer} |
| 860 | /> |
| 861 | )} |
| 862 | {viewerKind && uri && viewerOpen ? ( |
| 863 | <FilePreviewModal |
| 864 | source={{ kind: viewerKind, name: entry.name, mimeType, uri }} |
| 865 | onOpenError={(error) => { |
| 866 | pendingViewerError.current = nativeViewerErrorMessage(error); |
| 867 | }} |
| 868 | onRequestClose={() => { |
| 869 | setViewerError(pendingViewerError.current); |
| 870 | pendingViewerError.current = null; |
| 871 | setViewerOpen(false); |
| 872 | }} |
| 873 | /> |
| 874 | ) : null} |
| 875 | </View> |
| 876 | ); |
| 877 | } |