The best way to control Claude Code, Codex and more from any computer or phone
fix(mobile): iOS image previews open without waiting for the gallery (#29044)
Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
shivam committed
Nov 5, 2026 at 06:48 UTC
70738cbd8aa94e506801c00df22d5d6ab5b86c83
10 files changed
+503
-152
apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+7
-1
@@ -66,7 +66,8 @@ public final class T3NativeControlsModule: Module {
66
identifier: identifier, promise: promise)
67
}.runOnQueue(.main)
68
69
- AsyncFunction("presentFiles") { (urls: [URL], titles: [String], selectedIndex: Int, sourceIdentifiers: [String], identifier: String, promise: Promise) in
69
+ // A nil URL is still resolving in JS and arrives later through updateFile.
70
+ AsyncFunction("presentFiles") { (urls: [URL?], titles: [String], selectedIndex: Int, sourceIdentifiers: [String], identifier: String, promise: Promise) in
71
guard !urls.isEmpty, urls.count == titles.count, urls.count == sourceIdentifiers.count,
72
urls.indices.contains(selectedIndex)
73
else {
@@ -81,6 +82,11 @@ public final class T3NativeControlsModule: Module {
82
file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
83
}.runOnQueue(.main)
84
85
+ // A nil URL marks the item as one that could not be resolved.
86
+ AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in
87
+ if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) }
88
+ }.runOnQueue(.main)
89
+
90
OnDestroy {
91
let presentation = self.videoPresentation
92
let file = self.filePresentation
apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
+195
-41
@@ -8,24 +8,71 @@ private final class FilePreviewItem: NSObject, QLPreviewItem {
8
var previewItemTitle: String?
9
}
10
11
+private enum FilePreviewState { case loading, ready, failed }
12
+
13
private final class FilePreviewController: QLPreviewController {
14
var onAppear: (() -> Void)?
15
+ // Quick Look shows a blank page for an item without a file, so loading and failure are ours to show.
16
+ private let spinner = UIActivityIndicatorView(style: .large)
17
+ private let failure = UILabel()
18
+ var state = FilePreviewState.ready {
19
+ didSet { if isViewLoaded { showState() } }
20
+ }
21
+
22
+ override func viewDidLoad() {
23
+ super.viewDidLoad()
24
+ failure.text = "This image could not be loaded."
25
+ failure.textColor = .secondaryLabel
26
+ failure.textAlignment = .center
27
+ failure.numberOfLines = 0
28
+ for status in [spinner, failure] as [UIView] {
29
+ status.isUserInteractionEnabled = false
30
+ status.translatesAutoresizingMaskIntoConstraints = false
31
+ view.addSubview(status)
32
+ NSLayoutConstraint.activate([
33
+ status.centerXAnchor.constraint(equalTo: view.centerXAnchor),
34
+ status.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 64),
35
+ status.widthAnchor.constraint(lessThanOrEqualTo: view.widthAnchor, constant: -48),
36
+ ])
37
+ }
38
+ showState()
39
+ }
40
+
41
+ override func viewDidLayoutSubviews() {
42
+ super.viewDidLayoutSubviews()
43
+ view.bringSubviewToFront(spinner)
44
+ view.bringSubviewToFront(failure)
45
+ }
46
47
override func viewDidAppear(_ animated: Bool) {
48
super.viewDidAppear(animated)
49
onAppear?()
50
}
51
+
52
+ private func showState() {
53
+ if state == .loading { spinner.startAnimating() } else { spinner.stopAnimating() }
54
+ failure.isHidden = state != .failed
55
+ }
56
}
57
58
final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
59
QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
60
let identifier: String
23
- private var controller: UIViewController?
61
+ private var controller: FilePreviewController?
62
private let completion: (Error?) -> Void
63
private weak var sources: T3PresentationSources?
64
private let sourceIdentifiers: [String]
65
private var items: [FilePreviewItem] = []
28
- private var loading: Task<Void, Never>?
66
+ private var urls: [URL?] = []
67
+ private var states: [FilePreviewState] = []
68
+ private var selectedIndex = 0
69
+ private weak var presenter: UIViewController?
70
+ /// Files that arrived while their page was off screen; Quick Look may still hold the blank page.
71
+ private var staleIndices = Set<Int>()
72
+ private var currentIndexObservation: NSKeyValueObservation?
73
+ private var download: (index: Int, task: Task<Void, Never>)?
74
+ private var placeholder: Task<Void, Never>?
75
+ private var openError: Error?
76
private var dismissRequested = false
77
private var finished = false
78
@@ -38,54 +85,155 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
85
super.init()
86
}
87
88
+ /// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead.
89
func present(url: URL, title: String, from presenter: UIViewController) {
42
- present(urls: [url], titles: [title], selectedIndex: 0, from: presenter)
90
+ load(urls: [url], titles: [title], selectedIndex: 0, from: presenter, opensWhileLoading: false)
91
+ }
92
+
93
+ /// Opens the selected image once it is ready, or a loading page if it is slow, and loads the rest
94
+ /// of the gallery behind it so a slow or broken sibling never holds the viewer back.
95
+ func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
96
+ load(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter, opensWhileLoading: true)
97
}
98
45
- func present(urls: [URL], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
46
- loading = Task { @MainActor [self] in
99
+ /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will.
100
+ func update(index: Int, url: URL?) {
101
+ guard !finished, urls.indices.contains(index), urls[index] == nil, states[index] == .loading else { return }
102
+ guard let url else {
103
+ failed(index, error: URLError(.resourceUnavailable))
104
+ return
105
+ }
106
+ urls[index] = url
107
+ loadNext()
108
+ }
109
+
110
+ private func load(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController,
111
+ opensWhileLoading: Bool) {
112
+ items = titles.map { title in
113
+ let item = FilePreviewItem()
114
+ item.previewItemTitle = title
115
+ return item
116
+ }
117
+ self.urls = urls
118
+ self.selectedIndex = selectedIndex
119
+ self.presenter = presenter
120
+ states = Array(repeating: .loading, count: urls.count)
121
+ if opensWhileLoading {
122
+ // A short grace keeps the zoom from the thumbnail into a loaded image when the file is quick.
123
+ placeholder = Task { @MainActor [self] in
124
+ try? await Task.sleep(nanoseconds: 250_000_000)
125
+ guard !Task.isCancelled, !finished, controller == nil else { return }
126
+ show()
127
+ }
128
+ }
129
+ loadNext()
130
+ }
131
+
132
+ /// Downloads one file at a time, nearest the page on screen first. The page on screen takes over
133
+ /// from a background download, which restarts later.
134
+ private func loadNext() {
135
+ guard !finished, !dismissRequested else { return }
136
+ let current = controller?.currentPreviewItemIndex ?? selectedIndex
137
+ guard let next = urls.indices
138
+ .filter({ urls[$0] != nil && states[$0] == .loading })
139
+ .min(by: { abs($0 - current) < abs($1 - current) })
140
+ else { return }
141
+ if let download {
142
+ guard next == current, download.index != current else { return }
143
+ download.task.cancel()
144
+ }
145
+ guard let url = urls[next] else { return }
146
+ let title = items[next].previewItemTitle ?? ""
147
+ let task = Task { @MainActor [self] in
148
+ let result: Result<URL, Error>
149
do {
48
- for (index, url) in urls.enumerated() {
49
- let title = titles[index]
50
- let file = try await Self.prepareFile(url: url, title: title)
51
- guard !finished, !Task.isCancelled else {
52
- try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
53
- return
54
- }
55
- // Quick Look knows which formats it renders; refuse before presenting so the caller
56
- // can fall back instead of showing an "unsupported format" page.
57
- guard QLPreviewController.canPreview(file as NSURL) else {
150
+ result = .success(try await Self.prepareFile(url: url, title: title))
151
+ } catch {
152
+ result = .failure(error)
153
+ }
154
+ guard !finished, !Task.isCancelled else {
155
+ if case .success(let file) = result {
156
try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
59
- throw NSError(
60
- domain: "T3NativePresentation",
61
- code: 3,
62
- userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
63
- )
64
- }
65
- let item = FilePreviewItem()
66
- item.previewItemURL = file
67
- item.previewItemTitle = title
68
- items.append(item)
157
}
70
- let preview = FilePreviewController()
71
- preview.delegate = self
72
- preview.dataSource = self
73
- preview.currentPreviewItemIndex = selectedIndex
74
- preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
75
- controller = preview
76
- presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
77
- resumePendingDismissal()
78
- }
79
- preview.presentationController?.delegate = self
80
- } catch {
81
- finish(error: error)
158
+ return
159
+ }
160
+ download = nil
161
+ switch result {
162
+ case .success(let file): loaded(next, file: file)
163
+ case .failure(let error): failed(next, error: error)
164
}
165
+ loadNext()
166
}
167
+ download = (next, task)
168
+ }
169
+
170
+ private func loaded(_ index: Int, file: URL) {
171
+ // Quick Look knows which formats it renders; refuse before presenting so the caller
172
+ // can fall back instead of showing an "unsupported format" page.
173
+ guard QLPreviewController.canPreview(file as NSURL) else {
174
+ try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
175
+ failed(index, error: NSError(
176
+ domain: "T3NativePresentation",
177
+ code: 3,
178
+ userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
179
+ ))
180
+ return
181
+ }
182
+ items[index].previewItemURL = file
183
+ states[index] = .ready
184
+ if controller != nil { refresh(index) } else if index == selectedIndex { show() }
185
+ }
186
+
187
+ private func failed(_ index: Int, error: Error) {
188
+ guard index != selectedIndex else {
189
+ openError = error
190
+ dismiss()
191
+ return
192
+ }
193
+ states[index] = .failed
194
+ refresh(index)
195
+ }
196
+
197
+ private func show() {
198
+ guard let presenter else { finish(); return }
199
+ placeholder?.cancel()
200
+ let preview = FilePreviewController()
201
+ preview.delegate = self
202
+ preview.dataSource = self
203
+ preview.currentPreviewItemIndex = selectedIndex
204
+ preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
205
+ controller = preview
206
+ preview.state = states[selectedIndex]
207
+ currentIndexObservation = preview.observe(\.currentPreviewItemIndex) { [weak self] _, _ in
208
+ DispatchQueue.main.async { self?.currentItemChanged() }
209
+ }
210
+ presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
211
+ resumePendingDismissal()
212
+ }
213
+ preview.presentationController?.delegate = self
214
+ }
215
+
216
+ private func refresh(_ index: Int) {
217
+ guard let controller else { return }
218
+ guard controller.currentPreviewItemIndex == index else {
219
+ if states[index] == .ready { staleIndices.insert(index) }
220
+ return
221
+ }
222
+ if states[index] == .ready { controller.refreshCurrentPreviewItem() }
223
+ controller.state = states[index]
224
+ }
225
+
226
+ private func currentItemChanged() {
227
+ guard !finished, let controller, states.indices.contains(controller.currentPreviewItemIndex) else { return }
228
+ let index = controller.currentPreviewItemIndex
229
+ if staleIndices.remove(index) != nil { controller.refreshCurrentPreviewItem() }
230
+ controller.state = states[index]
231
+ loadNext()
232
}
233
234
func dismiss() {
235
dismissRequested = true
88
- loading?.cancel()
236
+ download?.task.cancel()
237
guard !finished else { return }
238
guard let controller else { finish(); return }
239
// Drain Close from viewDidAppear after opening or cancelling an interactive dismissal.
@@ -133,15 +281,21 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
281
private func finish(error: Error? = nil) {
282
guard !finished else { return }
283
finished = true
136
- loading?.cancel()
137
- loading = nil
284
+ download?.task.cancel()
285
+ download = nil
286
+ placeholder?.cancel()
287
+ placeholder = nil
288
+ currentIndexObservation = nil
289
for item in items {
290
if let file = item.previewItemURL {
291
try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
292
}
293
}
294
items.removeAll()
144
- DispatchQueue.main.async { [completion] in completion(error) }
295
+ urls.removeAll()
296
+ states.removeAll()
297
+ let result = error ?? openError
298
+ DispatchQueue.main.async { [completion] in completion(result) }
299
}
300
301
/// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
apps/mobile/package.json
+1
-1
@@ -47,7 +47,7 @@
47
"generate": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON scripts/generate-uniwind-themes.mts",
48
"generate:highlights": "node scripts/generate-highlights.mts",
49
"eas-build-on-success": "node scripts/upload-sourcemaps.mts build",
50
- "test": "vp test run --project unit --project react",
50
+ "test": "vp test run --project unit --project react && T3_MOBILE_TEST_PLATFORM=android vp test run --project react src/components/FilePreviewModal.test.tsx",
51
"typecheck": "effect-tsgo tsrs --noEmit"
52
},
53
"dependencies": {
apps/mobile/src/components/FilePreview.ios.tsx
+43
-18
@@ -1,8 +1,8 @@
1
import * as Dialog from "./ui/Dialog";
2
import { requireNativeModule } from "expo";
3
-import { useEffect, useEffectEvent, useId } from "react";
3
+import { useEffect, useEffectEvent, useId, useRef, useState } from "react";
4
5
-import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
5
+import type { FilePreviewImage, ResolvedFilePreviewSource } from "./FilePreviewModal.types";
6
7
const NativeControls = requireNativeModule<{
8
presentFile(
@@ -12,22 +12,28 @@ const NativeControls = requireNativeModule<{
12
identifier: string,
13
): Promise<void>;
14
presentFiles(
15
- uris: readonly string[],
15
+ uris: readonly (string | null)[],
16
names: readonly string[],
17
selectedIndex: number,
18
sourceIdentifiers: readonly string[],
19
identifier: string,
20
): Promise<void>;
21
+ updateFile(identifier: string, index: number, uri: string | null): Promise<void>;
22
dismissFile(identifier: string): Promise<void>;
23
}>("T3NativeControls");
24
25
+// Null tells the viewer an image failed; undefined means its URL has not arrived yet.
26
+const nativeUri = (image: FilePreviewImage) => (image.failed ? null : image.uri);
27
+
28
function NativeFilePreview(props: {
29
readonly source: ResolvedFilePreviewSource;
30
readonly onRequestClose: () => void;
31
readonly onOpenError?: (error: unknown) => void;
32
}) {
29
- const { uri, name, sourceIdentifier, gallery } = props.source;
33
const identifier = useId();
34
+ // Later URLs reach the open viewer through updateFile instead of presenting again.
35
+ const [presented] = useState(props.source);
36
+ const delivered = useRef<(string | null | undefined)[]>([]);
37
const onRequestClose = useEffectEvent(props.onRequestClose);
38
const onOpenError = useEffectEvent((error: unknown) => {
39
if (props.onOpenError) props.onOpenError(error);
@@ -37,19 +43,27 @@ function NativeFilePreview(props: {
43
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- presents the native file preview and dismisses it on cleanup
44
useEffect(() => {
45
let canceled = false;
40
- const presentation =
41
- gallery && gallery.length > 1
42
- ? NativeControls.presentFiles(
43
- gallery.map((item) => item.uri),
44
- gallery.map((item) => item.name ?? "Preview"),
45
- Math.max(
46
- 0,
47
- gallery.findIndex((item) => item.uri === uri),
48
- ),
49
- gallery.map((item) => item.sourceIdentifier ?? ""),
50
- identifier,
51
- )
52
- : NativeControls.presentFile(uri, name ?? "Preview", sourceIdentifier ?? "", identifier);
46
+ let presentation: Promise<void>;
47
+ // Images open while still loading; other files must download first so Quick Look can refuse them.
48
+ if (presented.kind === "image") {
49
+ const { images, selectedIndex } = presented;
50
+ delivered.current = images.map((image) => image.uri);
51
+ presentation = NativeControls.presentFiles(
52
+ images.map((image) => image.uri ?? null),
53
+ images.map((image) => image.name ?? "Preview"),
54
+ selectedIndex,
55
+ images.map((image) => image.sourceIdentifier ?? ""),
56
+ identifier,
57
+ );
58
+ } else {
59
+ const { uri, name, sourceIdentifier } = presented;
60
+ presentation = NativeControls.presentFile(
61
+ uri,
62
+ name ?? "Preview",
63
+ sourceIdentifier ?? "",
64
+ identifier,
65
+ );
66
+ }
67
void presentation
68
.catch((error: unknown) => {
69
if (!canceled) onOpenError(error);
@@ -61,7 +75,18 @@ function NativeFilePreview(props: {
75
canceled = true;
76
void NativeControls.dismissFile(identifier).catch(() => undefined);
77
};
64
- }, [uri, name, sourceIdentifier, identifier, gallery]);
78
+ }, [presented, identifier]);
79
+
80
+ const images = props.source.kind === "image" ? props.source.images : undefined;
81
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hands image URLs that resolve after opening to the native viewer
82
+ useEffect(() => {
83
+ images?.forEach((image, index) => {
84
+ const uri = nativeUri(image);
85
+ if (uri === undefined || delivered.current[index] === uri) return;
86
+ delivered.current[index] = uri;
87
+ void NativeControls.updateFile(identifier, index, uri).catch(() => undefined);
88
+ });
89
+ }, [images, identifier]);
90
91
return null;
92
}
apps/mobile/src/components/FilePreview.tsx
+13
-14
@@ -6,14 +6,17 @@ import ImageViewing from "react-native-image-viewing";
6
import { useSafeAreaInsets } from "react-native-safe-area-context";
7
8
import { openAttachmentInViewer } from "../lib/attachmentDownload";
9
-import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
10
-import { MediaImagePreview } from "./MediaImagePreview";
9
+import type {
10
+ ResolvedFilePreviewDocument,
11
+ ResolvedFilePreviewSource,
12
+} from "./FilePreviewModal.types";
13
+import { imageViewingProps, MediaImagePreview } from "./MediaImagePreview";
14
import { PdfPreview } from "./PdfPreview";
15
import { ControlPill } from "./ui/ControlPill";
16
import { AppText as Text } from "./ui/AppText";
17
18
function PdfDocumentPreview(props: {
16
- readonly source: ResolvedFilePreviewSource;
19
+ readonly source: ResolvedFilePreviewDocument;
20
readonly onRequestClose: () => void;
21
}) {
22
const insets = useSafeAreaInsets();
@@ -41,7 +44,7 @@ function PdfDocumentPreview(props: {
44
}
45
46
function DocumentPreview(props: {
44
- readonly source: ResolvedFilePreviewSource;
47
+ readonly source: ResolvedFilePreviewDocument;
48
readonly onRequestClose: () => void;
49
readonly onOpenError?: (error: unknown) => void;
50
}) {
@@ -100,18 +103,14 @@ export function FilePreview(props: {
103
readonly onRequestClose: () => void;
104
readonly onOpenError?: (error: unknown) => void;
105
}) {
103
- if (props.source.kind === "pdf") return <PdfDocumentPreview {...props} />;
104
- if (props.source.kind !== "image") return <DocumentPreview {...props} />;
105
- if (props.source.actionsSource) return <MediaImagePreview {...props} />;
106
+ const { source } = props;
107
+ if (source.kind === "pdf") return <PdfDocumentPreview {...props} source={source} />;
108
+ if (source.kind !== "image") return <DocumentPreview {...props} source={source} />;
109
+ if (source.images[source.selectedIndex]?.actionsSource)
110
+ return <MediaImagePreview source={source} onRequestClose={props.onRequestClose} />;
111
return (
112
<ImageViewing
108
- images={
109
- props.source.gallery?.map((item) => ({ uri: item.uri })) ?? [{ uri: props.source.uri }]
110
- }
111
- imageIndex={Math.max(
112
- 0,
113
- props.source.gallery?.findIndex((item) => item.uri === props.source.uri) ?? 0,
114
- )}
113
+ {...imageViewingProps(source)}
114
visible
115
onRequestClose={props.onRequestClose}
116
swipeToCloseEnabled={false}
apps/mobile/src/components/FilePreviewModal.test.tsx
new
+140
@@ -0,0 +1,140 @@
1
+import { act } from "react";
2
+import { createRoot } from "react-dom/client";
3
+import { expect, it, vi } from "vite-plus/test";
4
+import { EnvironmentId, SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts";
5
+
6
+const harness = vi.hoisted(() => ({
7
+ refreshAssetUrl: vi.fn<(environmentId: string, resource: { url: string }) => Promise<string>>(),
8
+ alert: vi.fn(),
9
+ previews: [] as unknown[],
10
+ mounts: 0,
11
+ platform: { OS: process.env.T3_MOBILE_TEST_PLATFORM === "android" ? "android" : "ios" },
12
+}));
13
+
14
+vi.mock("react-native", () => ({ Platform: harness.platform }));
15
+vi.mock("../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl }));
16
+vi.mock("../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() }));
17
+vi.mock("../lib/attachmentDownload", () => ({
18
+ downloadAndShareAttachment: vi.fn(),
19
+ nativeViewerErrorMessage: () => "",
20
+ shareLocalAttachment: vi.fn(),
21
+}));
22
+vi.mock("../lib/previewPresentation", () => ({ usePreviewPresentation: () => {} }));
23
+vi.mock("./ui/Dialog", () => ({ alert: harness.alert }));
24
+vi.mock("./FilePreview", async () => {
25
+ const { useState } = await import("react");
26
+ return {
27
+ FilePreview: (props: { source: unknown }) => {
28
+ useState(() => harness.mounts++);
29
+ harness.previews.push(props.source);
30
+ return null;
31
+ },
32
+ };
33
+});
34
+
35
+import type { FilePreviewItem } from "./FilePreviewModal.types";
36
+import { FilePreviewModal } from "./FilePreviewModal";
37
+
38
+const environmentId = EnvironmentId.make("environment");
39
+const image = (url: string): FilePreviewItem => ({
40
+ kind: "image",
41
+ environmentId,
42
+ resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
43
+});
44
+
45
+async function openGallery(
46
+ selected: FilePreviewItem,
47
+ gallery: readonly FilePreviewItem[],
48
+ platform = harness.platform.OS,
49
+) {
50
+ harness.platform.OS = platform;
51
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
52
+ harness.previews.length = 0;
53
+ harness.mounts = 0;
54
+ harness.alert.mockClear();
55
+ const root = createRoot(document.createElement("div"));
56
+ const onRequestClose = vi.fn();
57
+ await act(async () =>
58
+ root.render(
59
+ <FilePreviewModal source={{ ...selected, gallery }} onRequestClose={onRequestClose} />,
60
+ ),
61
+ );
62
+ return { onRequestClose, [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
63
+}
64
+
65
+it("keeps the gallery stable while a sibling is still resolving", async () => {
66
+ const platform = harness.platform.OS;
67
+ const slow = Promise.withResolvers<string>();
68
+ harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) =>
69
+ resource.url.endsWith("slow.png") ? slow.promise : "https://signed.test/a.png",
70
+ );
71
+ const selected = image("https://github.com/a.png");
72
+ await using _preview = await openGallery(
73
+ selected,
74
+ [image("https://github.com/slow.png"), selected],
75
+ platform,
76
+ );
77
+
78
+ if (platform === "ios") {
79
+ expect(harness.previews.at(-1)).toMatchObject({
80
+ kind: "image",
81
+ selectedIndex: 1,
82
+ images: [
83
+ expect.not.objectContaining({ uri: expect.anything() }),
84
+ { uri: "https://signed.test/a.png" },
85
+ ],
86
+ });
87
+ } else {
88
+ expect(harness.previews).toEqual([]);
89
+ }
90
+ await act(async () => slow.resolve("https://signed.test/slow.png"));
91
+ expect(harness.previews.at(-1)).toMatchObject({
92
+ selectedIndex: 1,
93
+ images: [{ uri: "https://signed.test/slow.png" }, { uri: "https://signed.test/a.png" }],
94
+ });
95
+ expect(harness.mounts).toBe(1);
96
+});
97
+
98
+it("handles a failed sibling without leaving a pending page", async () => {
99
+ const platform = harness.platform.OS;
100
+ harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
101
+ if (resource.url.endsWith("missing.png")) throw new Error("not found");
102
+ return `https://signed.test/${resource.url.split("/").pop()}`;
103
+ });
104
+ const selected = image("https://github.com/a.png");
105
+ await using preview = await openGallery(
106
+ selected,
107
+ [selected, image("https://github.com/missing.png"), image("https://github.com/c.png")],
108
+ platform,
109
+ );
110
+
111
+ if (platform === "android") {
112
+ expect(preview.onRequestClose).toHaveBeenCalledOnce();
113
+ expect(harness.alert).toHaveBeenCalledOnce();
114
+ expect(harness.previews).toEqual([]);
115
+ return;
116
+ }
117
+
118
+ expect(preview.onRequestClose).not.toHaveBeenCalled();
119
+ expect(harness.alert).not.toHaveBeenCalled();
120
+ expect(harness.previews.at(-1)).toMatchObject({
121
+ selectedIndex: 0,
122
+ images: [
123
+ { uri: "https://signed.test/a.png" },
124
+ { failed: true },
125
+ { uri: "https://signed.test/c.png" },
126
+ ],
127
+ });
128
+});
129
+
130
+it("closes the preview when the selected image cannot be resolved", async () => {
131
+ harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
132
+ if (resource.url.endsWith("missing.png")) throw new Error("not found");
133
+ return `https://signed.test/${resource.url.split("/").pop()}`;
134
+ });
135
+ const selected = image("https://github.com/missing.png");
136
+ await using preview = await openGallery(selected, [image("https://github.com/a.png"), selected]);
137
+
138
+ expect(preview.onRequestClose).toHaveBeenCalledOnce();
139
+ expect(harness.alert).toHaveBeenCalledOnce();
140
+});
apps/mobile/src/components/FilePreviewModal.tsx
+66
-57
@@ -1,5 +1,6 @@
1
import * as Dialog from "./ui/Dialog";
2
import { useContext, useEffect, useEffectEvent, useState } from "react";
3
+import { Platform } from "react-native";
4
5
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
6
import {
@@ -12,11 +13,7 @@ import { refreshAssetUrl } from "../state/assets";
13
import { filePreviewGallery, filePreviewKey, filePreviewName } from "../lib/filePreviewGallery";
14
import { FilePreviewGallery } from "./FilePreviewGallery";
15
import { FilePreview } from "./FilePreview";
15
-import type {
16
- FilePreviewItem,
17
- FilePreviewSource,
18
- ResolvedFilePreviewSource,
19
-} from "./FilePreviewModal.types";
16
+import type { FilePreviewItem, FilePreviewSource } from "./FilePreviewModal.types";
17
18
export type {
19
FilePreviewItem,
@@ -33,25 +30,21 @@ class PreviewResolutionError extends Error {
30
}
31
}
32
36
-interface ResolvedPreviewItem {
37
- readonly source: ResolvedFilePreviewSource;
33
+interface ResolvedPreviewUri {
34
+ readonly uri: string;
35
readonly dispose?: () => void;
36
}
37
41
-async function resolvePreviewItem(
38
+async function resolvePreviewUri(
39
item: FilePreviewItem,
40
signal: AbortSignal,
44
-): Promise<ResolvedPreviewItem | null> {
45
- const name = filePreviewName(item);
41
+): Promise<ResolvedPreviewUri | null> {
42
+ if ("uri" in item) return { uri: item.uri };
43
if ("attachment" in item) {
47
- const file = await loadLocalAttachmentPreview(item.attachment, signal).catch(
48
- (error: unknown) => {
49
- throw new PreviewResolutionError(error, "Attach the file again and retry.");
50
- },
51
- );
52
- return file && { source: { ...item, name, uri: file.uri }, dispose: file.dispose };
44
+ return loadLocalAttachmentPreview(item.attachment, signal).catch((error: unknown) => {
45
+ throw new PreviewResolutionError(error, "Attach the file again and retry.");
46
+ });
47
}
54
- if (!("environmentId" in item)) return { source: { ...item, name } };
48
// Refresh expired URLs before handing them to Quick Look or ACTION_VIEW, which retain them.
49
const url = await refreshAssetUrl(item.environmentId, item.resource, signal)
50
.then((value) => {
@@ -64,7 +57,7 @@ async function resolvePreviewItem(
57
"Reconnect to this environment and try again. The file may have been moved or deleted.",
58
);
59
});
67
- return { source: { ...item, name, uri: url + (item.srcFragment ?? "") } };
60
+ return { uri: url + (item.srcFragment ?? "") };
61
}
62
63
function ResolvedFilePreview(props: {
@@ -75,10 +68,11 @@ function ResolvedFilePreview(props: {
68
// Freeze the group at opening; streaming messages and URL refreshes must not reopen the viewer.
69
const [items] = useState(() => filePreviewGallery(props.source, []));
70
const selectedKey = filePreviewKey(props.source);
78
- const [gallery, setGallery] = useState<readonly ResolvedFilePreviewSource[] | null>(() =>
79
- items.every((item) => "uri" in item)
80
- ? items.map((item) => ({ ...item, name: filePreviewName(item) }))
81
- : null,
71
+ const selectedIndex = items.findIndex((item) => filePreviewKey(item) === selectedKey);
72
+ const progressiveGallery = Platform.OS === "ios";
73
+ // Undefined while resolving, null once it cannot be.
74
+ const [uris, setUris] = useState<readonly (string | null | undefined)[]>(() =>
75
+ items.map((item) => ("uri" in item ? item.uri : undefined)),
76
);
77
const onResolutionError = useEffectEvent((error: PreviewResolutionError) => {
78
if (props.onOpenError) props.onOpenError(error.cause);
@@ -88,42 +82,57 @@ function ResolvedFilePreview(props: {
82
// Resolves once per presentation and holds local file leases until it closes.
83
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- resolves preview files and holds their local file leases until the preview closes
84
useEffect(() => {
91
- if (items.every((item) => "uri" in item)) return;
85
const controller = new AbortController();
93
- // The first failure closes the preview at once and cancels the rest of the gallery.
94
- const fail = (error: unknown) => {
95
- if (controller.signal.aborted) return;
96
- controller.abort();
97
- onResolutionError(
98
- error instanceof PreviewResolutionError
99
- ? error
100
- : new PreviewResolutionError(error, "Try again."),
86
+ const leases: (() => void)[] = [];
87
+ const settle = (index: number, uri: string | null) =>
88
+ setUris((current) => current.map((value, at) => (at === index ? uri : value)));
89
+ items.forEach((item, index) => {
90
+ if ("uri" in item) return;
91
+ void resolvePreviewUri(item, controller.signal).then(
92
+ (resolved) => {
93
+ if (controller.signal.aborted) return resolved?.dispose?.();
94
+ if (resolved?.dispose) leases.push(resolved.dispose);
95
+ settle(index, resolved?.uri ?? null);
96
+ },
97
+ (error: unknown) => {
98
+ if (controller.signal.aborted) return;
99
+ if (progressiveGallery && index !== selectedIndex) return settle(index, null);
100
+ controller.abort();
101
+ onResolutionError(
102
+ error instanceof PreviewResolutionError
103
+ ? error
104
+ : new PreviewResolutionError(error, "Try again."),
105
+ );
106
+ },
107
);
102
- };
103
- const resolving = Promise.allSettled(
104
- items.map((item) =>
105
- resolvePreviewItem(item, controller.signal).catch((error: unknown) => {
106
- fail(error);
107
- throw error;
108
- }),
109
- ),
110
- );
111
- void resolving.then((settled) => {
112
- if (controller.signal.aborted) return;
113
- const sources = settled.flatMap((item) =>
114
- item.status === "fulfilled" && item.value ? [item.value.source] : [],
115
- );
116
- if (sources.length === items.length) setGallery(sources);
108
});
109
return () => {
110
controller.abort();
120
- void resolving.then((settled) => {
121
- for (const item of settled) if (item.status === "fulfilled") item.value?.dispose?.();
122
- });
111
+ for (const dispose of leases) dispose();
112
};
124
- }, [items]);
125
- const selected = gallery?.[items.findIndex((item) => filePreviewKey(item) === selectedKey)];
126
- if (!gallery || !selected) return null;
113
+ }, [items, selectedIndex, progressiveGallery]);
114
+ const selected = { ...items[selectedIndex]!, name: filePreviewName(items[selectedIndex]!) };
115
+ if (selected.kind === "image") {
116
+ // Android's viewer resets image gestures when its sources change during a presentation.
117
+ if (!progressiveGallery && uris.some((uri) => uri === undefined)) return null;
118
+ const images = items.map((item, index) => {
119
+ const uri = uris[index];
120
+ return {
121
+ ...item,
122
+ name: filePreviewName(item),
123
+ ...(uri ? { uri } : uri === null ? { failed: true } : {}),
124
+ };
125
+ });
126
+ return (
127
+ <FilePreview
128
+ source={{ kind: "image", images, selectedIndex }}
129
+ onRequestClose={props.onRequestClose}
130
+ {...(props.onOpenError ? { onOpenError: props.onOpenError } : {})}
131
+ />
132
+ );
133
+ }
134
+ const uri = uris[selectedIndex];
135
+ if (!uri) return null;
136
const onOpenError = (error: unknown) => {
137
if (props.onOpenError) return props.onOpenError(error);
138
Dialog.alert("Could not open preview", nativeViewerErrorMessage(error), [
@@ -135,14 +144,14 @@ function ResolvedFilePreview(props: {
144
onPress: () => {
145
const input = {
146
attachment: {
138
- name: filePreviewName(selected),
147
+ name: selected.name,
148
mimeType: selected.mimeType ?? "application/octet-stream",
149
},
150
signal: new AbortController().signal,
151
};
143
- const sharing = /^(file|content):/.test(selected.uri)
144
- ? shareLocalAttachment({ ...input, uri: selected.uri })
145
- : downloadAndShareAttachment({ ...input, url: selected.uri });
152
+ const sharing = /^(file|content):/.test(uri)
153
+ ? shareLocalAttachment({ ...input, uri })
154
+ : downloadAndShareAttachment({ ...input, url: uri });
155
void sharing.catch(() => Dialog.alert("Could not share file", "Please try again."));
156
},
157
},
@@ -152,7 +161,7 @@ function ResolvedFilePreview(props: {
161
};
162
return (
163
<FilePreview
155
- source={{ ...selected, gallery }}
164
+ source={{ ...selected, kind: selected.kind, uri }}
165
onRequestClose={props.onRequestClose}
166
onOpenError={onOpenError}
167
/>
apps/mobile/src/components/FilePreviewModal.types.ts
+17
-2
@@ -23,7 +23,22 @@ export type FilePreviewSource = FilePreviewItem & {
23
readonly gallery?: readonly FilePreviewItem[];
24
};
25
26
-export interface ResolvedFilePreviewSource extends FilePreviewMetadata {
26
+export interface ResolvedFilePreviewDocument extends FilePreviewMetadata {
27
+ readonly kind: "pdf" | "document";
28
readonly uri: string;
28
- readonly gallery?: readonly (FilePreviewMetadata & { readonly uri: string })[];
29
}
30
+
31
+/** `uri` is absent while it resolves; `failed` marks one that never will. */
32
+export interface FilePreviewImage extends FilePreviewMetadata {
33
+ readonly uri?: string;
34
+ readonly failed?: boolean;
35
+}
36
+
37
+/** Opens before every URL resolves; images keep their slot as URLs arrive. */
38
+export interface FilePreviewImages {
39
+ readonly kind: "image";
40
+ readonly images: readonly FilePreviewImage[];
41
+ readonly selectedIndex: number;
42
+}
43
+
44
+export type ResolvedFilePreviewSource = ResolvedFilePreviewDocument | FilePreviewImages;
apps/mobile/src/components/MediaImagePreview.tsx
+17
-16
@@ -1,4 +1,4 @@
1
-import { createContext, useContext, useState } from "react";
1
+import { createContext, useContext } from "react";
2
import { Pressable, View } from "react-native";
3
import ImageViewing from "react-native-image-viewing";
4
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -6,12 +6,12 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
6
import { useMediaActions } from "../state/mediaActions";
7
import { AppText } from "./ui/AppText";
8
import { SymbolView } from "./ui/AppSymbol";
9
-import type { ResolvedFilePreviewSource } from "./FilePreviewModal.types";
9
+import type { FilePreviewImages } from "./FilePreviewModal.types";
10
import { MediaActionsMenu } from "./MediaActionsMenu";
11
import { MediaSourceCaption } from "./MediaSourceCaption";
12
13
type MediaImagePreviewProps = {
14
- readonly source: ResolvedFilePreviewSource;
14
+ readonly source: FilePreviewImages;
15
readonly onRequestClose: () => void;
16
};
17
@@ -19,14 +19,14 @@ const ImagePreviewContext = createContext<MediaImagePreviewProps | null>(null);
19
20
function ImagePreviewHeader(header: { readonly imageIndex: number }) {
21
const props = useContext(ImagePreviewContext)!;
22
- const source = props.source.gallery?.[header.imageIndex] ?? props.source;
22
+ const source = props.source.images[header.imageIndex];
23
const insets = useSafeAreaInsets();
24
- const mediaActions = useMediaActions(source.actionsSource, props.onRequestClose);
24
+ const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose);
25
return (
26
<View className="bg-black/70" style={{ paddingTop: insets.top }}>
27
<View className="flex-row items-center gap-2 px-3">
28
<AppText className="flex-1 text-base text-white" numberOfLines={2}>
29
- {source.name ?? "Image"}
29
+ {source?.name ?? "Image"}
30
</AppText>
31
<MediaActionsMenu media={mediaActions} inModal />
32
<Pressable
@@ -43,20 +43,21 @@ function ImagePreviewHeader(header: { readonly imageIndex: number }) {
43
);
44
}
45
46
+// Images still resolving show the viewer's loading page, and remount by key once their URL arrives.
47
+export function imageViewingProps(source: FilePreviewImages) {
48
+ return {
49
+ images: source.images.map((image) => (image.uri ? { uri: image.uri } : {})),
50
+ keyExtractor: (_: unknown, index: number) => source.images[index]?.uri ?? `pending:${index}`,
51
+ // Stays fixed: react-native-image-viewing remounts the Modal and replays its fade when it changes.
52
+ imageIndex: source.selectedIndex,
53
+ };
54
+}
55
+
56
export function MediaImagePreview(props: MediaImagePreviewProps) {
47
- const gallery = props.source.gallery ?? [props.source];
48
- // Freeze imageIndex: react-native-image-viewing remounts the Modal and replays its fade when it changes.
49
- const [initialIndex] = useState(() =>
50
- Math.max(
51
- 0,
52
- gallery.findIndex((item) => item.uri === props.source.uri),
53
- ),
54
- );
57
return (
58
<ImagePreviewContext value={props}>
59
<ImageViewing
58
- images={gallery.map((item) => ({ uri: item.uri }))}
59
- imageIndex={initialIndex}
60
+ {...imageViewingProps(props.source)}
61
visible
62
presentationStyle="fullScreen"
63
onRequestClose={props.onRequestClose}
apps/mobile/vite.config.ts
+4
-2
@@ -27,6 +27,7 @@ const reactTests = [
27
"src/features/settings/components/BranchNamingSettings.test.tsx",
28
"src/features/settings/components/SettingsDragHandle.test.tsx",
29
"src/features/threads/ThreadMarkdownImage.test.tsx",
30
+ "src/components/FilePreviewModal.test.tsx",
31
"src/features/threads/UsageLimitRecoveryCard.test.tsx",
32
"src/features/threads/NewTaskDraftRouteScreen.test.tsx",
33
"src/native/NativeHeaderToolbar.test.tsx",
@@ -55,6 +56,7 @@ const babel: {
56
) => Promise<{ code?: string | null; map?: object | null } | null>;
57
} = require("@babel/core");
58
const babelConfig = require("./babel.config.js")({ cache: () => {} });
59
+const testPlatform = process.env.T3_MOBILE_TEST_PLATFORM === "android" ? "android" : "ios";
60
61
export default defineConfig({
62
test: {
@@ -77,7 +79,7 @@ export default defineConfig({
79
extends: true,
80
plugins: [
81
{
80
- name: "mobile-release-react-compiler",
82
+ name: `mobile-release-react-compiler-${testPlatform}`,
83
enforce: "pre",
84
async transform(code, id) {
85
if (
@@ -101,7 +103,7 @@ export default defineConfig({
103
caller: {
104
name: "metro",
105
bundler: "metro",
104
- platform: "ios",
106
+ platform: testPlatform,
107
isDev: false,
108
isServer: false,
109
isNodeModule: false,