@devries-cameron20 / t3code-1 / commits / d022d3bd8b
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): iOS image viewer pages and dismisses after slow opens (#36862)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 14, 2026 at 17:44 UTC d022d3bd8bea9421276232e23368684f3a5258f1
6 files changed +277 -170
apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+21 -5
@@ -10,6 +10,9 @@ public final class T3NativeControlsModule: Module {
10 private let presentationSources = T3PresentationSources()
11 private var videoPresentation: T3NativeVideoPresentation?
12 private var filePresentation: T3NativeFilePresentation?
13 + /// The last file preview that closed. Written on main, read synchronously from JS.
14 + private let filePreviewActivity = NSLock()
15 + private var finishedFilePreview: String?
16
17 public func definition() -> ModuleDefinition {
18 Events("videoPlaybackChange")
@@ -94,6 +97,12 @@ public final class T3NativeControlsModule: Module {
97 file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
98 }.runOnQueue(.main)
99
100 + // A tap can reach JS before the old viewer's close does; this tells it whether that viewer is gone.
101 + // A presentation main has not started yet reads as still open.
102 + Function("isFilePreviewFinished") { (identifier: String) -> Bool in
103 + self.filePreviewActivity.withLock { self.finishedFilePreview == identifier }
104 + }
105 +
106 // A nil URL marks the item as one that could not be resolved.
107 AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in
108 if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) }
@@ -294,15 +303,22 @@ public final class T3NativeControlsModule: Module {
303 guard filePresentation == nil, videoPresentation == nil,
304 appContext?.utilities?.currentViewController() != nil
305 else { throw URLError(.cannotLoadFromNetwork) }
297 - let file = T3NativeFilePresentation(identifier: identifier, sources: presentationSources,
298 - sourceIdentifiers: sourceIdentifiers) { [weak self] error in
299 - self?.filePresentation = nil
300 - if let error { promise.reject(error) } else { promise.resolve(nil) }
301 - }
306 + let file = T3NativeFilePresentation(
307 + identifier: identifier, sources: presentationSources, sourceIdentifiers: sourceIdentifiers,
308 + onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) },
309 + completion: { [weak self] error in
310 + self?.filePresentation = nil
311 + if let error { promise.reject(error) } else { promise.resolve(nil) }
312 + }
313 + )
314 filePresentation = file
315 return file
316 }
317
318 + private func setFinishedFilePreview(_ identifier: String) {
319 + filePreviewActivity.withLock { finishedFilePreview = identifier }
320 + }
321 +
322 private func presentFile(url: URL, title: String, sourceIdentifier: String,
323 identifier: String, promise: Promise) throws {
324 let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise)
apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
+145 -161
@@ -8,232 +8,217 @@ private final class FilePreviewItem: NSObject, QLPreviewItem {
8 var previewItemTitle: String?
9 }
10
11 -private enum FilePreviewState { case loading, ready, failed }
12 -
11 private final class FilePreviewController: QLPreviewController {
12 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 - }
13 + var onDismiss: (() -> Void)?
14
15 override func viewDidAppear(_ animated: Bool) {
16 super.viewDidAppear(animated)
17 onAppear?()
18 }
19
52 - private func showState() {
53 - if state == .loading { spinner.startAnimating() } else { spinner.stopAnimating() }
54 - failure.isHidden = state != .failed
20 + // Quick Look's own didDismiss callback can lag well behind the screen being tappable again,
21 + // so a tap on the thumbnail in that gap would land while JS still thinks the viewer is open.
22 + override func viewDidDisappear(_ animated: Bool) {
23 + super.viewDidDisappear(animated)
24 + if isBeingDismissed { onDismiss?() }
25 }
26 }
27
28 +/// How long the gallery waits for siblings once the selected file is ready; later ones are left out.
29 +private let siblingGraceNanoseconds: UInt64 = 1_000_000_000
30 +/// A load faster than this zooms straight from the thumbnail without a spinner.
31 +private let spinnerDelayNanoseconds: UInt64 = 250_000_000
32 +
33 +/// Quick Look only ever receives pages whose file is on disk: a page refreshed after it first
34 +/// rendered blank keeps a stale scroll offset, so drags scroll the image instead of paging or dismissing.
35 final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
36 QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
37 let identifier: String
38 private var controller: FilePreviewController?
39 private let completion: (Error?) -> Void
40 + private let onFinish: () -> Void
41 private weak var sources: T3PresentationSources?
42 private let sourceIdentifiers: [String]
65 - private var items: [FilePreviewItem] = []
43 + private var titles: [String] = []
44 private var urls: [URL?] = []
67 - private var states: [FilePreviewState] = []
45 + /// A prepared file, or nil while loading or after failing; `settled` tells those apart.
46 + private var files: [URL?] = []
47 + private var settled: [Bool] = []
48 + private var downloads: [Int: Task<Void, Never>] = [:]
49 private var selectedIndex = 0
50 + /// The pages Quick Look shows, as indices into `files`.
51 + private var pages: [Int] = []
52 + private var items: [FilePreviewItem] = []
53 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>?
54 + private var grace: Task<Void, Never>?
55 + private var spinnerDelay: Task<Void, Never>?
56 + private var spinner: UIView?
57 private var openError: Error?
58 private var dismissRequested = false
59 private var finished = false
60
61 init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String],
80 - completion: @escaping (Error?) -> Void) {
62 + onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
63 self.identifier = identifier
64 self.sources = sources
65 self.sourceIdentifiers = sourceIdentifiers
66 + self.onFinish = onFinish
67 self.completion = completion
68 super.init()
69 }
70
71 /// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead.
72 func present(url: URL, title: String, from presenter: UIViewController) {
90 - load(urls: [url], titles: [title], selectedIndex: 0, from: presenter, opensWhileLoading: false)
73 + present(urls: [url], titles: [title], selectedIndex: 0, from: presenter)
74 }
75
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.
76 + /// Loads the gallery in parallel and opens once the selected file is ready, with whichever
77 + /// siblings are ready by the end of a short grace, so a slow or broken one never holds it back.
78 func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
96 - load(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter, opensWhileLoading: true)
79 + self.titles = titles
80 + self.urls = urls
81 + self.selectedIndex = selectedIndex
82 + self.presenter = presenter
83 + files = Array(repeating: nil, count: urls.count)
84 + settled = Array(repeating: false, count: urls.count)
85 + spinnerDelay = Task { @MainActor [self] in
86 + try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds)
87 + guard !Task.isCancelled else { return }
88 + showSpinner()
89 + }
90 + for index in urls.indices { download(index) }
91 }
92
93 /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will.
94 func update(index: Int, url: URL?) {
101 - guard !finished, urls.indices.contains(index), urls[index] == nil, states[index] == .loading else { return }
95 + guard !finished, controller == nil, urls.indices.contains(index), urls[index] == nil,
96 + !settled[index]
97 + else { return }
98 guard let url else {
103 - failed(index, error: URLError(.resourceUnavailable))
99 + settle(index, result: .failure(URLError(.resourceUnavailable)))
100 return
101 }
102 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()
103 + download(index)
104 }
105
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
106 + private func download(_ index: Int) {
107 + guard let url = urls[index], downloads[index] == nil else { return }
108 + let title = titles[index]
109 + downloads[index] = Task { @MainActor [self] in
110 let result: Result<URL, Error>
111 do {
112 result = .success(try await Self.prepareFile(url: url, title: title))
113 } catch {
114 result = .failure(error)
115 }
154 - guard !finished, !Task.isCancelled else {
155 - if case .success(let file) = result {
156 - try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
157 - }
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()
116 + downloads[index] = nil
117 + settle(index, result: result)
118 }
167 - download = (next, task)
119 }
120
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 - ))
121 + private func settle(_ index: Int, result: Result<URL, Error>) {
122 + guard !finished, controller == nil, !dismissRequested else {
123 + if case .success(let file) = result { Self.remove(file) }
124 return
125 }
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 {
126 + settled[index] = true
127 + if let error = store(index, result: result), index == selectedIndex {
128 openError = error
129 dismiss()
130 return
131 }
193 - states[index] = .failed
194 - refresh(index)
132 + guard files[selectedIndex] != nil else { return }
133 + if settled.allSatisfy({ $0 }) {
134 + show()
135 + } else if grace == nil {
136 + grace = Task { @MainActor [self] in
137 + try? await Task.sleep(nanoseconds: siblingGraceNanoseconds)
138 + guard !Task.isCancelled else { return }
139 + show()
140 + }
141 + }
142 + }
143 +
144 + private func store(_ index: Int, result: Result<URL, Error>) -> Error? {
145 + switch result {
146 + case .success(let file):
147 + // Quick Look knows which formats it renders; refuse before presenting so the caller
148 + // can fall back instead of showing an "unsupported format" page.
149 + guard QLPreviewController.canPreview(file as NSURL) else {
150 + Self.remove(file)
151 + return NSError(
152 + domain: "T3NativePresentation",
153 + code: 3,
154 + userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
155 + )
156 + }
157 + files[index] = file
158 + return nil
159 + case .failure(let error):
160 + return error
161 + }
162 }
163
164 private func show() {
165 + guard !finished, controller == nil, !dismissRequested else { return }
166 guard let presenter else { finish(); return }
199 - placeholder?.cancel()
167 + cancelLoading()
168 + pages = files.indices.filter { files[$0] != nil }
169 + items = pages.map { index in
170 + let item = FilePreviewItem()
171 + item.previewItemURL = files[index]
172 + item.previewItemTitle = titles[index]
173 + return item
174 + }
175 let preview = FilePreviewController()
176 preview.delegate = self
177 preview.dataSource = self
203 - preview.currentPreviewItemIndex = selectedIndex
178 + preview.currentPreviewItemIndex = pages.firstIndex(of: selectedIndex) ?? 0
179 preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
180 + preview.onDismiss = { [weak self] in self?.finish() }
181 controller = preview
206 - preview.state = states[selectedIndex]
207 - currentIndexObservation = preview.observe(\.currentPreviewItemIndex) { [weak self] _, _ in
208 - DispatchQueue.main.async { self?.currentItemChanged() }
209 - }
182 presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
183 resumePendingDismissal()
184 }
185 preview.presentationController?.delegate = self
186 }
187
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]
188 + /// Shows over the tapped thumbnail that a slow open is on its way.
189 + private func showSpinner() {
190 + guard !finished, controller == nil, spinner == nil,
191 + sourceIdentifiers.indices.contains(selectedIndex),
192 + let source = sources?.view(for: sourceIdentifiers[selectedIndex]),
193 + let window = source.window
194 + else { return }
195 + let backing = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
196 + backing.backgroundColor = UIColor.black.withAlphaComponent(0.55)
197 + backing.layer.cornerRadius = 22
198 + backing.isUserInteractionEnabled = false
199 + let indicator = UIActivityIndicatorView(style: .medium)
200 + indicator.color = .white
201 + indicator.center = CGPoint(x: 22, y: 22)
202 + indicator.startAnimating()
203 + backing.addSubview(indicator)
204 + backing.center = source.convert(CGPoint(x: source.bounds.midX, y: source.bounds.midY), to: window)
205 + window.addSubview(backing)
206 + spinner = backing
207 }
208
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()
209 + private func cancelLoading() {
210 + for task in downloads.values { task.cancel() }
211 + downloads.removeAll()
212 + grace?.cancel()
213 + grace = nil
214 + spinnerDelay?.cancel()
215 + spinnerDelay = nil
216 + spinner?.removeFromSuperview()
217 + spinner = nil
218 }
219
220 func dismiss() {
221 dismissRequested = true
236 - download?.task.cancel()
222 guard !finished else { return }
223 guard let controller else { finish(); return }
224 // Drain Close from viewDidAppear after opening or cancelling an interactive dismissal.
@@ -257,10 +242,10 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
242
243 private func sourceView(for item: QLPreviewItem) -> UIView? {
244 guard !UIAccessibility.isReduceMotionEnabled,
260 - let index = items.firstIndex(where: { $0 === item }),
261 - sourceIdentifiers.indices.contains(index)
245 + let page = items.firstIndex(where: { $0 === item }),
246 + sourceIdentifiers.indices.contains(pages[page])
247 else { return nil }
263 - return sources?.view(for: sourceIdentifiers[index])
248 + return sources?.view(for: sourceIdentifiers[pages[page]])
249 }
250
251 func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
@@ -278,24 +263,20 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
263
264 func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() }
265
281 - private func finish(error: Error? = nil) {
266 + private func finish() {
267 guard !finished else { return }
268 finished = true
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 - }
269 + cancelLoading()
270 + for file in files.compactMap({ $0 }) { Self.remove(file) }
271 + files.removeAll()
272 items.removeAll()
295 - urls.removeAll()
296 - states.removeAll()
297 - let result = error ?? openError
298 - DispatchQueue.main.async { [completion] in completion(result) }
273 + DispatchQueue.main.async { [completion, openError] in completion(openError) }
274 + // After queueing the completion, so a new presentation JS starts on seeing this lands behind it.
275 + onFinish()
276 + }
277 +
278 + private static func remove(_ file: URL) {
279 + try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
280 }
281
282 /// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
@@ -305,6 +286,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
286 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
287 do {
288 let download = directory.appendingPathComponent("original")
289 + var mimeType: String?
290 if url.isFileURL {
291 try FileManager.default.copyItem(at: url, to: download)
292 } else if url.scheme == "data" {
@@ -317,6 +299,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
299 guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
300 throw URLError(.badServerResponse)
301 }
302 + mimeType = response.mimeType
303 try FileManager.default.moveItem(at: temporaryFile, to: download)
304 }
305 try Task.checkCancellation()
@@ -330,7 +313,8 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
313 type = detectedType
314 } else if CGPDFDocument(download as CFURL) != nil {
315 type = .pdf
333 - } else if originalExtension.lowercased() == "svg" {
316 + } else if originalExtension.lowercased() == "svg" || mimeType == "image/svg+xml" {
317 + // ImageIO cannot read SVG, and served images such as QR codes often have no extension.
318 type = .svg
319 }
320 let fileExtension: String
apps/mobile/src/components/ui/FilePreviewModal.tsx
+5 -2
@@ -31,6 +31,7 @@ const NativeControls = requireNativeModule<{
31 ): Promise<void>;
32 updateFile(identifier: string, index: number, uri: string | null): Promise<void>;
33 dismissFile(identifier: string): Promise<void>;
34 + isFilePreviewFinished(identifier: string): boolean;
35 }>("T3NativeControls");
36
37 // Null tells the viewer an image failed; undefined means its URL has not arrived yet.
@@ -38,10 +39,11 @@ const nativeUri = (image: FilePreviewImage) => (image.failed ? null : image.uri)
39
40 function NativeFilePreview(props: FilePreviewViewerProps) {
41 const identifier = useId();
41 - // Later URLs reach the open viewer through updateFile instead of presenting again.
42 + // Later URLs reach the native presentation through updateFile instead of presenting again.
43 const [presented] = useState(props.source);
44 const delivered = useRef<(string | null | undefined)[]>([]);
45 const onRequestClose = useEffectEvent(props.onRequestClose);
46 + const onPresent = useEffectEvent((isFinished: () => boolean) => props.onPresent?.(isFinished));
47 const onOpenError = useEffectEvent((error: unknown) => {
48 if (props.onOpenError) props.onOpenError(error);
49 else Dialog.alert("Could not open preview", "The file could not be loaded. Please try again.");
@@ -51,7 +53,7 @@ function NativeFilePreview(props: FilePreviewViewerProps) {
53 useEffect(() => {
54 let canceled = false;
55 let presentation: Promise<void>;
54 - // Images open while still loading; other files must download first so Quick Look can refuse them.
56 + // Images hand over before every URL resolves; other files must download first so Quick Look can refuse them.
57 if (presented.kind === "image") {
58 const { images, selectedIndex } = presented;
59 delivered.current = images.map((image) => image.uri);
@@ -71,6 +73,7 @@ function NativeFilePreview(props: FilePreviewViewerProps) {
73 identifier,
74 );
75 }
76 + onPresent(() => NativeControls.isFilePreviewFinished(identifier));
77 void presentation
78 .catch((error: unknown) => {
79 if (!canceled) onOpenError(error);
apps/mobile/src/components/ui/FilePreviewModal.types.ts
+2
@@ -54,4 +54,6 @@ export interface FilePreviewViewerProps {
54 readonly source: ResolvedFilePreviewSource;
55 readonly onRequestClose: () => void;
56 readonly onOpenError?: (error: unknown) => void;
57 + /** Called once the viewer hands its file to a native presentation, with a check for its close. */
58 + readonly onPresent?: (isFinished: () => boolean) => void;
59 }
apps/mobile/src/components/ui/FilePreviewSession.test.tsx
+72 -1
@@ -1,4 +1,4 @@
1 -import { act, useState } from "react";
1 +import { act, useEffect, useState } from "react";
2 import { createRoot } from "react-dom/client";
3 import { expect, it, vi } from "vite-plus/test";
4 import {
@@ -14,6 +14,7 @@ const harness = vi.hoisted(() => ({
14 alert: vi.fn(),
15 previews: [] as unknown[],
16 mounts: 0,
17 + presentationFinished: false,
18 }));
19
20 vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl }));
@@ -32,6 +33,9 @@ import { FilePreviewSession } from "./FilePreviewSession";
33 function Viewer(props: FilePreviewViewerProps) {
34 useState(() => harness.mounts++);
35 harness.previews.push(props.source);
36 + const { onPresent } = props;
37 + // Stands in for the native presentation starting.
38 + useEffect(() => onPresent?.(() => harness.presentationFinished), [onPresent]);
39 return null;
40 }
41
@@ -171,3 +175,70 @@ it("names the checked path when the server cannot find the file", async () => {
175 );
176 expect(harness.alert.mock.calls[0]?.[1]).not.toMatch(/reconnect/i);
177 });
178 +
179 +it.each([
180 + // Handed to native but not yet started there, or still on screen.
181 + ["image", false, 1],
182 + ["image", true, 2],
183 + // A PDF is still resolving here, so its viewer never presented and a re-render must not restart it.
184 + ["pdf", true, 1],
185 +] as const)(
186 + "a re-tap of the open %s restarts the preview only once its native viewer closed (closed: %s)",
187 + async (kind, finished, starts) => {
188 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
189 + harness.presentationFinished = finished;
190 + harness.mounts = 0;
191 + harness.refreshAssetUrl.mockReset();
192 + if (kind === "image") harness.refreshAssetUrl.mockResolvedValue("https://signed.test/a.png");
193 + else harness.refreshAssetUrl.mockReturnValue(new Promise(() => {}));
194 + const selected: FilePreviewItem = { ...image("https://github.com/a.png"), kind };
195 + const root = createRoot(document.createElement("div"));
196 + await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
197 + const render = () =>
198 + act(async () =>
199 + root.render(
200 + <FilePreviewSession
201 + source={{ ...selected, gallery: [selected] }}
202 + onRequestClose={() => {}}
203 + progressiveGallery
204 + Viewer={Viewer}
205 + />,
206 + ),
207 + );
208 + await render();
209 + await render();
210 + expect(harness.refreshAssetUrl).toHaveBeenCalledTimes(starts);
211 + },
212 +);
213 +
214 +it("does not carry a presented viewer over to a different item that is still resolving", async () => {
215 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
216 + harness.presentationFinished = true;
217 + harness.refreshAssetUrl.mockReset();
218 + harness.refreshAssetUrl.mockImplementation((_environmentId, resource) =>
219 + resource.url.endsWith("a.png")
220 + ? Promise.resolve("https://signed.test/a.png")
221 + : new Promise(() => {}),
222 + );
223 + const shown = image("https://github.com/a.png");
224 + const resolving: FilePreviewItem = { ...image("https://github.com/b.pdf"), kind: "pdf" };
225 + const root = createRoot(document.createElement("div"));
226 + await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
227 + const render = (item: FilePreviewItem) =>
228 + act(async () =>
229 + root.render(
230 + <FilePreviewSession
231 + source={{ ...item, gallery: [item] }}
232 + onRequestClose={() => {}}
233 + progressiveGallery
234 + Viewer={Viewer}
235 + />,
236 + ),
237 + );
238 + await render(shown);
239 + await render(resolving);
240 + await render(resolving);
241 + expect(
242 + harness.refreshAssetUrl.mock.calls.filter(([, r]) => r.url.endsWith("b.pdf")),
243 + ).toHaveLength(1);
244 +});
apps/mobile/src/components/ui/FilePreviewSession.tsx
+32 -1
@@ -97,6 +97,7 @@ function ResolvedFilePreview(
97 readonly source: FilePreviewSource;
98 readonly onRequestClose: () => void;
99 readonly onOpenError?: (error: unknown) => void;
100 + readonly onPresent: (isFinished: () => boolean) => void;
101 },
102 ) {
103 const { progressiveGallery, Viewer } = props;
@@ -161,6 +162,7 @@ function ResolvedFilePreview(
162 <Viewer
163 source={{ kind: "image", images, selectedIndex }}
164 onRequestClose={props.onRequestClose}
165 + onPresent={props.onPresent}
166 {...(props.onOpenError ? { onOpenError: props.onOpenError } : {})}
167 />
168 );
@@ -205,6 +207,7 @@ function ResolvedFilePreview(
207 }}
208 onRequestClose={props.onRequestClose}
209 onOpenError={onOpenError}
210 + onPresent={props.onPresent}
211 />
212 );
213 }
@@ -220,15 +223,43 @@ export function FilePreviewSession(props: FilePreviewModalProps & FilePreviewSes
223 ? null
224 : { ...props.source, gallery: filePreviewGallery(props.source, group) };
225 usePreviewPresentation(source && filePreviewKey(source), props.onRequestClose);
226 + // A tap can land after the native viewer closed but before its close reached the caller, which
227 + // still holds the same item; that tap only opens a new viewer under a new key.
228 + // Only a viewer that presented and has since closed reopens; one still resolving never does.
229 + const [opening, setOpening] = useState<{
230 + readonly source: FilePreviewModalProps["source"];
231 + readonly count: number;
232 + readonly presented: { readonly isFinished: () => boolean } | null;
233 + }>({ source: props.source, count: 0, presented: null });
234 + if (opening.source !== props.source) {
235 + const sameItem =
236 + opening.source !== null &&
237 + props.source !== null &&
238 + filePreviewKey(opening.source) === filePreviewKey(props.source);
239 + const reopened = sameItem && opening.presented?.isFinished() === true;
240 + setOpening({
241 + source: props.source,
242 + count: opening.count + (reopened ? 1 : 0),
243 + presented: sameItem && !reopened ? opening.presented : null,
244 + });
245 + }
246 + const { count } = opening;
247 + const onPresent = (isFinished: () => boolean) =>
248 + setOpening((current) =>
249 + current.count === count && current.presented === null
250 + ? { ...current, presented: { isFinished } }
251 + : current,
252 + );
253
254 if (!source) return null;
255 return (
256 <ResolvedFilePreview
227 - key={filePreviewKey(source)}
257 + key={`${opening.count}:${filePreviewKey(source)}`}
258 source={source}
259 onRequestClose={props.onRequestClose}
260 progressiveGallery={props.progressiveGallery}
261 Viewer={props.Viewer}
262 + onPresent={onPresent}
263 {...(props.onOpenError ? { onOpenError: props.onOpenError } : {})}
264 />
265 );