@devries-cameron20 / t3code Mirror · read-only / commits / 295a0a7332
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 11:00 UTC

feat(mobile): open iOS images in a native viewer modelled on Messages (#37100)

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

Julius Marminge committed Nov 15, 2026 at 10:30 UTC 295a0a7332aa1b0cc2f737dae71bd5e607a6ebb9
11 files changed +1090 -150
apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+25 -13
@@ -10,6 +10,7 @@ public final class T3NativeControlsModule: Module {
10 private let presentationSources = T3PresentationSources()
11 private var videoPresentation: T3NativeVideoPresentation?
12 private var filePresentation: T3NativeFilePresentation?
13 + private var imageViewer: T3NativeImageViewer?
14 /// The last file preview that closed. Written on main, read synchronously from JS.
15 private let filePreviewActivity = NSLock()
16 private var finishedFilePreview: String?
@@ -88,13 +89,21 @@ public final class T3NativeControlsModule: Module {
89 else {
90 throw URLError(.badURL)
91 }
91 - let file = try self.makeFilePresentation(sourceIdentifiers: sourceIdentifiers, identifier: identifier,
92 - promise: promise)
93 - guard let presenter = self.appContext?.utilities?.currentViewController() else {
94 - file.dismiss()
95 - return
96 - }
97 - file.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
92 + // A viewer still animating closed must not block the next one, as Quick Look's error alert did.
93 + self.imageViewer?.finishImmediately()
94 + guard self.filePresentation == nil, self.videoPresentation == nil,
95 + let presenter = self.appContext?.utilities?.currentViewController()
96 + else { throw URLError(.cannotLoadFromNetwork) }
97 + let viewer = T3NativeImageViewer(
98 + identifier: identifier, sources: self.presentationSources, sourceIdentifiers: sourceIdentifiers,
99 + onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) },
100 + completion: { [weak self] error in
101 + if self?.imageViewer?.identifier == identifier { self?.imageViewer = nil }
102 + if let error { promise.reject(error) } else { promise.resolve(nil) }
103 + }
104 + )
105 + self.imageViewer = viewer
106 + viewer.present(urls: urls, titles: titles, selectedIndex: selectedIndex, from: presenter)
107 }.runOnQueue(.main)
108
109 // A tap can reach JS before the old viewer's close does; this tells it whether that viewer is gone.
@@ -105,15 +114,17 @@ public final class T3NativeControlsModule: Module {
114
115 // A nil URL marks the item as one that could not be resolved.
116 AsyncFunction("updateFile") { (identifier: String, index: Int, url: URL?) in
108 - if self.filePresentation?.identifier == identifier { self.filePresentation?.update(index: index, url: url) }
117 + if self.imageViewer?.identifier == identifier { self.imageViewer?.update(index: index, url: url) }
118 }.runOnQueue(.main)
119
120 OnDestroy {
121 let presentation = self.videoPresentation
122 let file = self.filePresentation
123 + let images = self.imageViewer
124 DispatchQueue.main.async {
125 presentation?.dismiss()
126 file?.dismiss()
127 + images?.dismiss()
128 }
129 }
130
@@ -270,7 +281,7 @@ public final class T3NativeControlsModule: Module {
281 let isPlayableURL = url.isFileURL
282 ? FileManager.default.isReadableFile(atPath: url.path)
283 : (["https", "http"].contains(url.scheme?.lowercased() ?? "") && url.host != nil)
273 - guard videoPresentation == nil, filePresentation == nil,
284 + guard videoPresentation == nil, filePresentation == nil, imageViewer == nil,
285 let presenter = appContext?.utilities?.currentViewController(),
286 isPlayableURL
287 else {
@@ -298,13 +309,13 @@ public final class T3NativeControlsModule: Module {
309 if videoPresentation?.identifier == identifier { videoPresentation?.dismiss() }
310 }
311
301 - private func makeFilePresentation(sourceIdentifiers: [String], identifier: String,
312 + private func makeFilePresentation(sourceIdentifier: String, identifier: String,
313 promise: Promise) throws -> T3NativeFilePresentation {
303 - guard filePresentation == nil, videoPresentation == nil,
314 + guard filePresentation == nil, videoPresentation == nil, imageViewer == nil,
315 appContext?.utilities?.currentViewController() != nil
316 else { throw URLError(.cannotLoadFromNetwork) }
317 let file = T3NativeFilePresentation(
307 - identifier: identifier, sources: presentationSources, sourceIdentifiers: sourceIdentifiers,
318 + identifier: identifier, sources: presentationSources, sourceIdentifier: sourceIdentifier,
319 onFinish: { [weak self] in self?.setFinishedFilePreview(identifier) },
320 completion: { [weak self] error in
321 self?.filePresentation = nil
@@ -321,13 +332,14 @@ public final class T3NativeControlsModule: Module {
332
333 private func presentFile(url: URL, title: String, sourceIdentifier: String,
334 identifier: String, promise: Promise) throws {
324 - let file = try makeFilePresentation(sourceIdentifiers: [sourceIdentifier], identifier: identifier, promise: promise)
335 + let file = try makeFilePresentation(sourceIdentifier: sourceIdentifier, identifier: identifier, promise: promise)
336 guard let presenter = appContext?.utilities?.currentViewController() else { file.dismiss(); return }
337 file.present(url: url, title: title, from: presenter)
338 }
339
340 private func dismissFilePresentation(identifier: String) {
341 if filePresentation?.identifier == identifier { filePresentation?.dismiss() }
342 + if imageViewer?.identifier == identifier { imageViewer?.dismiss() }
343 }
344
345 private static func saveImageToLibrary(url: URL, mimeType: String, name: String, promise: Promise) {
apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift
+56 -124
@@ -25,13 +25,10 @@ private final class FilePreviewController: QLPreviewController {
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
28 /// A load faster than this zooms straight from the thumbnail without a spinner.
29 private let spinnerDelayNanoseconds: UInt64 = 250_000_000
30
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.
31 +/// Quick Look for PDFs and documents; images open in T3NativeImageViewer.
32 final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
33 QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
34 let identifier: String
@@ -39,30 +36,21 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
36 private let completion: (Error?) -> Void
37 private let onFinish: () -> Void
38 private weak var sources: T3PresentationSources?
42 - private let sourceIdentifiers: [String]
43 - private var titles: [String] = []
44 - private var urls: [URL?] = []
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?
54 - private var grace: Task<Void, Never>?
39 + private let sourceIdentifier: String
40 + private var file: URL?
41 + private var item: FilePreviewItem?
42 + private var download: Task<Void, Never>?
43 private var spinnerDelay: Task<Void, Never>?
44 private var spinner: UIView?
45 private var openError: Error?
46 private var dismissRequested = false
47 private var finished = false
48
61 - init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String],
49 + init(identifier: String, sources: T3PresentationSources, sourceIdentifier: String,
50 onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
51 self.identifier = identifier
52 self.sources = sources
65 - self.sourceIdentifiers = sourceIdentifiers
53 + self.sourceIdentifier = sourceIdentifier
54 self.onFinish = onFinish
55 self.completion = completion
56 super.init()
@@ -70,112 +58,59 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
58
59 /// Downloads the file before presenting so Quick Look can refuse a format the caller should share instead.
60 func present(url: URL, title: String, from presenter: UIViewController) {
73 - present(urls: [url], titles: [title], selectedIndex: 0, from: presenter)
74 - }
75 -
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) {
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)
61 spinnerDelay = Task { @MainActor [self] in
62 try? await Task.sleep(nanoseconds: spinnerDelayNanoseconds)
63 guard !Task.isCancelled else { return }
64 showSpinner()
65 }
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?) {
95 - guard !finished, controller == nil, urls.indices.contains(index), urls[index] == nil,
96 - !settled[index]
97 - else { return }
98 - guard let url else {
99 - settle(index, result: .failure(URLError(.resourceUnavailable)))
100 - return
101 - }
102 - urls[index] = url
103 - download(index)
104 - }
105 -
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
66 + download = Task { @MainActor [self] in
67 let result: Result<URL, Error>
68 do {
69 result = .success(try await Self.prepareFile(url: url, title: title))
70 } catch {
71 result = .failure(error)
72 }
116 - downloads[index] = nil
117 - settle(index, result: result)
73 + download = nil
74 + settle(result, title: title, presenter: presenter)
75 }
76 }
77
121 - private func settle(_ index: Int, result: Result<URL, Error>) {
78 + private func settle(_ result: Result<URL, Error>, title: String, presenter: UIViewController) {
79 guard !finished, controller == nil, !dismissRequested else {
80 if case .success(let file) = result { Self.remove(file) }
81 return
82 }
126 - settled[index] = true
127 - if let error = store(index, result: result), index == selectedIndex {
128 - openError = error
129 - dismiss()
130 - return
131 - }
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? {
83 switch result {
84 case .success(let file):
85 // Quick Look knows which formats it renders; refuse before presenting so the caller
86 // can fall back instead of showing an "unsupported format" page.
87 guard QLPreviewController.canPreview(file as NSURL) else {
88 Self.remove(file)
151 - return NSError(
89 + openError = NSError(
90 domain: "T3NativePresentation",
91 code: 3,
92 userInfo: [NSLocalizedDescriptionKey: "This file type cannot be previewed on this device."]
93 )
94 + finish()
95 + return
96 }
157 - files[index] = file
158 - return nil
97 + self.file = file
98 + show(file: file, title: title, presenter: presenter)
99 case .failure(let error):
160 - return error
100 + openError = error
101 + finish()
102 }
103 }
104
164 - private func show() {
165 - guard !finished, controller == nil, !dismissRequested else { return }
166 - guard let presenter else { finish(); return }
105 + private func show(file: URL, title: String, presenter: UIViewController) {
106 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 - }
107 + let item = FilePreviewItem()
108 + item.previewItemURL = file
109 + item.previewItemTitle = title
110 + self.item = item
111 let preview = FilePreviewController()
112 preview.delegate = self
113 preview.dataSource = self
178 - preview.currentPreviewItemIndex = pages.firstIndex(of: selectedIndex) ?? 0
114 preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
115 preview.onDismiss = { [weak self] in self?.finish() }
116 controller = preview
@@ -188,8 +123,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
123 /// Shows over the tapped thumbnail that a slow open is on its way.
124 private func showSpinner() {
125 guard !finished, controller == nil, spinner == nil,
191 - sourceIdentifiers.indices.contains(selectedIndex),
192 - let source = sources?.view(for: sourceIdentifiers[selectedIndex]),
126 + let source = sources?.view(for: sourceIdentifier),
127 let window = source.window
128 else { return }
129 let backing = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
@@ -207,10 +141,8 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
141 }
142
143 private func cancelLoading() {
210 - for task in downloads.values { task.cancel() }
211 - downloads.removeAll()
212 - grace?.cancel()
213 - grace = nil
144 + download?.cancel()
145 + download = nil
146 spinnerDelay?.cancel()
147 spinnerDelay = nil
148 spinner?.removeFromSuperview()
@@ -234,27 +166,23 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
166 }
167 }
168
237 - func numberOfPreviewItems(in controller: QLPreviewController) -> Int { items.count }
169 + func numberOfPreviewItems(in controller: QLPreviewController) -> Int { item == nil ? 0 : 1 }
170
171 func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
240 - items[index]
172 + item ?? FilePreviewItem()
173 }
174
243 - private func sourceView(for item: QLPreviewItem) -> UIView? {
244 - guard !UIAccessibility.isReduceMotionEnabled,
245 - let page = items.firstIndex(where: { $0 === item }),
246 - sourceIdentifiers.indices.contains(pages[page])
247 - else { return nil }
248 - return sources?.view(for: sourceIdentifiers[pages[page]])
175 + private var sourceView: UIView? {
176 + UIAccessibility.isReduceMotionEnabled ? nil : sources?.view(for: sourceIdentifier)
177 }
178
179 func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
252 - sourceView(for: item)
180 + sourceView
181 }
182
183 func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem,
184 inSourceView view: AutoreleasingUnsafeMutablePointer<UIView?>) -> CGRect {
257 - guard let source = sourceView(for: item) else { return .zero }
185 + guard let source = sourceView else { return .zero }
186 view.pointee = source
187 return source.bounds
188 }
@@ -267,9 +195,9 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
195 guard !finished else { return }
196 finished = true
197 cancelLoading()
270 - for file in files.compactMap({ $0 }) { Self.remove(file) }
271 - files.removeAll()
272 - items.removeAll()
198 + if let file { Self.remove(file) }
199 + file = nil
200 + item = nil
201 DispatchQueue.main.async { [completion, openError] in completion(openError) }
202 // After queueing the completion, so a new presentation JS starts on seeing this lands behind it.
203 onFinish()
@@ -279,29 +207,33 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
207 try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
208 }
209
210 + /// Writes the bytes behind a file, data or http(s) URL to `destination`, returning the MIME type it declares.
211 + nonisolated private static func copyOriginal(_ url: URL, to destination: URL) async throws -> String? {
212 + if url.isFileURL {
213 + try FileManager.default.copyItem(at: url, to: destination)
214 + return nil
215 + }
216 + if url.scheme == "data" {
217 + try Data(contentsOf: url).write(to: destination, options: .atomic)
218 + return url.absoluteString.lowercased().hasPrefix("data:image/svg+xml") ? "image/svg+xml" : nil
219 + }
220 + guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else { throw URLError(.unsupportedURL) }
221 + let (temporaryFile, response) = try await URLSession.shared.download(from: url)
222 + guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode) else {
223 + throw URLError(.badServerResponse)
224 + }
225 + try FileManager.default.moveItem(at: temporaryFile, to: destination)
226 + return response.mimeType
227 + }
228 +
229 /// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
283 - nonisolated private static func prepareFile(url: URL, title: String) async throws -> URL {
230 + nonisolated static func prepareFile(url: URL, title: String) async throws -> URL {
231 try Task.checkCancellation()
232 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("t3-preview-\(UUID().uuidString)")
233 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
234 do {
235 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" {
293 - try Data(contentsOf: url).write(to: download, options: .atomic)
294 - } else {
295 - guard ["https", "http"].contains(url.scheme?.lowercased() ?? "") else {
296 - throw URLError(.unsupportedURL)
297 - }
298 - let (temporaryFile, response) = try await URLSession.shared.download(from: url)
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 - }
236 + let mimeType = try await copyOriginal(url, to: download)
237 try Task.checkCancellation()
238 // Detect images and PDFs by content; preserve other extensions so Quick Look can decide support.
239 let filename = URL(fileURLWithPath: title).lastPathComponent as NSString
apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift new
+952
@@ -0,0 +1,952 @@
1 +import ImageIO
2 +import Photos
3 +import UIKit
4 +
5 +/// Full-screen image gallery modelled on Messages. It opens at once from the tapped thumbnail's
6 +/// own pixels and sharpens when the original arrives, so a slow or failed load never holds it back.
7 +final class T3NativeImageViewer: NSObject {
8 + let identifier: String
9 + private let completion: (Error?) -> Void
10 + private let onFinish: () -> Void
11 + private weak var sources: T3PresentationSources?
12 + private let sourceIdentifiers: [String]
13 + private var titles: [String] = []
14 + private var urls: [URL?] = []
15 + /// The original bytes on disk, kept for sharing.
16 + private var files: [URL?] = []
17 + private var placeholders: [UIImage?] = []
18 + private var loads: [Int: Task<Void, Never>] = [:]
19 + private var decodes: [Int: Task<Void, Never>] = [:]
20 + /// The last queued decode; each one waits for it, so one original decodes at a time.
21 + private var decodeQueue: Task<Void, Never>?
22 + /// Pages showing their decoded original; only the current page and its neighbours keep one.
23 + private var decoded: Set<Int> = []
24 + private var currentIndex = 0
25 + private var controller: T3ImageViewerController?
26 + private var finished = false
27 +
28 + init(identifier: String, sources: T3PresentationSources, sourceIdentifiers: [String],
29 + onFinish: @escaping () -> Void, completion: @escaping (Error?) -> Void) {
30 + self.identifier = identifier
31 + self.sources = sources
32 + self.sourceIdentifiers = sourceIdentifiers
33 + self.onFinish = onFinish
34 + self.completion = completion
35 + super.init()
36 + }
37 +
38 + func present(urls: [URL?], titles: [String], selectedIndex: Int, from presenter: UIViewController) {
39 + self.urls = urls
40 + self.titles = titles
41 + files = Array(repeating: nil, count: urls.count)
42 + currentIndex = selectedIndex
43 + let viewer = T3ImageViewerController(titles: titles, selectedIndex: selectedIndex)
44 + viewer.sourceView = { [weak self] index in self?.sourceView(index) }
45 + viewer.fileForPage = { [weak self] index in self?.file(at: index) }
46 + viewer.onRetry = { [weak self] index in self?.load(index, retry: true) }
47 + viewer.onDismissed = { [weak self] in self?.finish() }
48 + viewer.onPageChange = { [weak self] index in self?.show(page: index) }
49 + controller = viewer
50 + viewer.loadViewIfNeeded()
51 + placeholders = urls.indices.map { sourceView($0).flatMap(Self.thumbnail(of:)) }
52 + for (index, placeholder) in placeholders.enumerated() {
53 + if let placeholder { viewer.setImage(placeholder, at: index, full: false) }
54 + }
55 + presenter.present(T3ImageViewerNavigation(viewer: viewer), animated: false) { viewer.animateIn() }
56 + for index in urls.indices { load(index, retry: false) }
57 + }
58 +
59 + /// Delivers a URL that was still resolving when the gallery opened, or nil when it never will.
60 + func update(index: Int, url: URL?) {
61 + guard !finished, urls.indices.contains(index), urls[index] == nil else { return }
62 + guard let url else {
63 + controller?.setFailed(at: index, retryable: false)
64 + return
65 + }
66 + urls[index] = url
67 + load(index, retry: false)
68 + }
69 +
70 + func dismiss() {
71 + guard !finished else { return }
72 + guard let controller else { finish(); return }
73 + controller.close()
74 + }
75 +
76 + /// Ends at once, for a new viewer that must open while this one is still animating away.
77 + func finishImmediately() {
78 + guard !finished else { return }
79 + controller?.presentingViewController?.dismiss(animated: false)
80 + finish()
81 + }
82 +
83 + private func file(at index: Int) -> URL? {
84 + files.indices.contains(index) ? files[index] : nil
85 + }
86 +
87 + private func sourceView(_ index: Int) -> UIView? {
88 + guard sourceIdentifiers.indices.contains(index), !sourceIdentifiers[index].isEmpty else { return nil }
89 + return sources?.view(for: sourceIdentifiers[index])
90 + }
91 +
92 + private func load(_ index: Int, retry: Bool) {
93 + guard !finished, urls.indices.contains(index), let url = urls[index], loads[index] == nil else { return }
94 + if retry { controller?.setLoading(at: index) }
95 + let title = titles[index]
96 + loads[index] = Task { @MainActor [self] in
97 + defer { loads[index] = nil }
98 + do {
99 + let file = try await T3NativeFilePresentation.prepareFile(url: url, title: title)
100 + guard !finished, !Task.isCancelled else { Self.remove(file); return }
101 + if let previous = files[index] { Self.remove(previous) }
102 + files[index] = file
103 + decoded.remove(index)
104 + if isNearCurrent(index) { decode(index) }
105 + } catch {
106 + guard !finished, !Task.isCancelled else { return }
107 + controller?.setFailed(at: index, retryable: true)
108 + }
109 + }
110 + }
111 +
112 + /// Every original downloads up front, but a decoded one costs far more memory than its file,
113 + /// so only pages next to the current one decode, and pages further away fall back to their thumbnail.
114 + private func show(page index: Int) {
115 + currentIndex = index
116 + for other in decoded where !isNearCurrent(other) {
117 + decoded.remove(other)
118 + controller?.release(at: other, placeholder: placeholders[other])
119 + }
120 + // Queued decodes for pages paged past are skipped before they start.
121 + for (other, task) in decodes where !isNearCurrent(other) { task.cancel() }
122 + for near in files.indices where isNearCurrent(near) { decode(near) }
123 + }
124 +
125 + private func isNearCurrent(_ index: Int) -> Bool { abs(index - currentIndex) <= 1 }
126 +
127 + private func decode(_ index: Int) {
128 + guard !finished, let file = file(at: index), !decoded.contains(index), decodes[index] == nil else { return }
129 + let source = sourceView(index)
130 + let previous = decodeQueue
131 + let task = Task { @MainActor [self] in
132 + await previous?.value
133 + var settled = false
134 + defer {
135 + decodes[index] = nil
136 + // Paged away and back while this run waited: it was cancelled, so the page asks again.
137 + if !settled, !finished, isNearCurrent(index), !decoded.contains(index) { decode(index) }
138 + }
139 + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
140 + // ImageIO reads SVG poorly or not at all; the thumbnail is vector, so redraw it at full-screen size.
141 + let isSVG = file.pathExtension.lowercased() == "svg"
142 + let image = isSVG ? nil : await Task.detached(priority: .userInitiated) { Self.decode(file) }.value
143 + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
144 + if isSVG {
145 + // The open transition hides the thumbnail, which draws blank until it is back.
146 + await controller?.untilRevealed()
147 + guard !finished, !Task.isCancelled, isNearCurrent(index), files[index] == file else { return }
148 + }
149 + settled = true
150 + if let image = image ?? (isSVG ? source.flatMap(Self.render(_:)) : nil) {
151 + decoded.insert(index)
152 + controller?.setImage(image, at: index, full: true)
153 + } else {
154 + // A corrupt download or an SVG whose thumbnail is scrolled away; retrying downloads it again.
155 + // A file that is not an image must not reach Share.
156 + if !isSVG {
157 + Self.remove(file)
158 + files[index] = nil
159 + }
160 + controller?.setFailed(at: index, retryable: true)
161 + }
162 + }
163 + decodes[index] = task
164 + decodeQueue = task
165 + }
166 +
167 + private func finish() {
168 + guard !finished else { return }
169 + finished = true
170 + for task in loads.values { task.cancel() }
171 + loads.removeAll()
172 + for task in decodes.values { task.cancel() }
173 + decodes.removeAll()
174 + decodeQueue = nil
175 + for file in files.compactMap({ $0 }) { Self.remove(file) }
176 + files.removeAll()
177 + controller = nil
178 + DispatchQueue.main.async { [completion] in completion(nil) }
179 + // After queueing the completion, so a new presentation JS starts on seeing this lands behind it.
180 + onFinish()
181 + }
182 +
183 + private static func remove(_ file: URL) {
184 + try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
185 + }
186 +
187 + /// The decoded image a thumbnail already shows, uncropped, or a snapshot of a view that draws one.
188 + /// The largest image view wins, so an overlaid icon is never mistaken for the picture.
189 + private static func thumbnail(of view: UIView) -> UIImage? {
190 + var queue = [view]
191 + var best: (image: UIImage, area: CGFloat)?
192 + while let candidate = queue.popLast() {
193 + queue.append(contentsOf: candidate.subviews)
194 + guard let image = (candidate as? UIImageView)?.image, image.size.width > 0, image.size.height > 0 else { continue }
195 + let area = candidate.bounds.width * candidate.bounds.height
196 + if area > best?.area ?? 0 { best = (image, area) }
197 + }
198 + if let best, best.area >= view.bounds.width * view.bounds.height / 2 { return best.image }
199 + return snapshot(view, scale: view.window?.screen.scale ?? 2)
200 + }
201 +
202 + private static func render(_ view: UIView) -> UIImage? {
203 + let screen = view.window?.screen.bounds.size ?? CGSize(width: 1024, height: 1024)
204 + let fit = min(screen.width / max(view.bounds.width, 1), screen.height / max(view.bounds.height, 1))
205 + // The thumbnail was shown again after the open transition, in a frame not yet on screen.
206 + return snapshot(view, scale: max(1, fit) * (view.window?.screen.scale ?? 2), afterScreenUpdates: true)
207 + }
208 +
209 + private static func snapshot(_ view: UIView, scale: CGFloat, afterScreenUpdates: Bool = false) -> UIImage? {
210 + guard view.bounds.width > 1, view.bounds.height > 1, view.window != nil else { return nil }
211 + let format = UIGraphicsImageRendererFormat()
212 + format.scale = scale
213 + format.opaque = false
214 + return UIGraphicsImageRenderer(bounds: view.bounds, format: format).image { _ in
215 + view.drawHierarchy(in: view.bounds, afterScreenUpdates: afterScreenUpdates)
216 + }
217 + }
218 +
219 + /// Decodes off the main thread at no more than zooming needs, and keeps GIFs animated.
220 + nonisolated private static func decode(_ file: URL) -> UIImage? {
221 + guard let source = CGImageSourceCreateWithURL(file as CFURL, nil) else { return nil }
222 + let count = CGImageSourceGetCount(source)
223 + guard count > 0 else { return nil }
224 + let options: [CFString: Any] = [
225 + kCGImageSourceCreateThumbnailFromImageAlways: true,
226 + kCGImageSourceCreateThumbnailWithTransform: true,
227 + kCGImageSourceShouldCacheImmediately: true,
228 + kCGImageSourceThumbnailMaxPixelSize: 4096,
229 + ]
230 + var animationOptions = options
231 + animationOptions[kCGImageSourceThumbnailMaxPixelSize] = 1024
232 + animationOptions[kCGImageSourceShouldCacheImmediately] = nil
233 + // Every frame stays decoded while it plays, so an animation over this budget shows its first frame.
234 + if count > 1, let first = CGImageSourceCreateThumbnailAtIndex(source, 0, animationOptions as CFDictionary),
235 + first.bytesPerRow * first.height * count <= animationByteBudget {
236 + var frames: [(image: UIImage, delay: Double)] = [(UIImage(cgImage: first), frameDuration(source, 0))]
237 + for index in 1..<count {
238 + guard let frame = CGImageSourceCreateThumbnailAtIndex(source, index, animationOptions as CFDictionary) else { continue }
239 + frames.append((UIImage(cgImage: frame), frameDuration(source, index)))
240 + }
241 + // UIKit plays frames evenly, so each frame repeats once per tick of its delay; the repeats share
242 + // one bitmap. The tick grows with the animation's length to keep the timeline near 1,000 entries.
243 + let total = frames.reduce(0) { $0 + $1.delay }
244 + let tick = max(0.02, total / 1_000)
245 + let timeline = frames.flatMap { frame in
246 + Array(repeating: frame.image, count: max(1, Int((frame.delay / tick).rounded())))
247 + }
248 + if frames.count > 1 { return UIImage.animatedImage(with: timeline, duration: Double(timeline.count) * tick) }
249 + }
250 + return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary).map { UIImage(cgImage: $0) }
251 + }
252 +
253 + nonisolated private static func frameDuration(_ source: CGImageSource, _ index: Int) -> Double {
254 + let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any]
255 + let gif = properties?[kCGImagePropertyGIFDictionary] as? [CFString: Any]
256 + let png = properties?[kCGImagePropertyPNGDictionary] as? [CFString: Any]
257 + let delay = gif?[kCGImagePropertyGIFUnclampedDelayTime] as? Double
258 + ?? gif?[kCGImagePropertyGIFDelayTime] as? Double
259 + ?? png?[kCGImagePropertyAPNGUnclampedDelayTime] as? Double
260 + ?? png?[kCGImagePropertyAPNGDelayTime] as? Double
261 + ?? 0.1
262 + // Browsers treat near-zero delays as 0.1s.
263 + return delay < 0.011 ? 0.1 : delay
264 + }
265 +}
266 +
267 +private let animationByteBudget = 64 * 1024 * 1024
268 +
269 +private extension Array {
270 + subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }
271 +}
272 +
273 +/// One zoomable page. Its content never exceeds its bounds at the fitted zoom, so a vertical
274 +/// drag has nothing to scroll and always reaches the dismiss gesture.
275 +private final class T3ImageViewerPage: UIView, UIScrollViewDelegate {
276 + let scroll = UIScrollView()
277 + let imageView = UIImageView()
278 + private let spinner = UIActivityIndicatorView(style: .large)
279 + private let failure = UIStackView()
280 + private var spinnerDelay: DispatchWorkItem?
281 + private var laidOutSize = CGSize.zero
282 + private(set) var isFull = false
283 + var onRetry: (() -> Void)?
284 +
285 + override init(frame: CGRect) {
286 + super.init(frame: frame)
287 + scroll.delegate = self
288 + scroll.showsVerticalScrollIndicator = false
289 + scroll.showsHorizontalScrollIndicator = false
290 + scroll.contentInsetAdjustmentBehavior = .never
291 + scroll.decelerationRate = .fast
292 + scroll.alwaysBounceVertical = false
293 + scroll.alwaysBounceHorizontal = false
294 + scroll.bouncesZoom = true
295 + addSubview(scroll)
296 + imageView.contentMode = .scaleAspectFill
297 + imageView.clipsToBounds = true
298 + imageView.isAccessibilityElement = true
299 + imageView.accessibilityTraits = .image
300 + scroll.addSubview(imageView)
301 + spinner.color = .white
302 + spinner.hidesWhenStopped = true
303 + addSubview(spinner)
304 + configureFailure()
305 + }
306 +
307 + @available(*, unavailable)
308 + required init?(coder: NSCoder) { nil }
309 +
310 + private func configureFailure() {
311 + let icon = UIImageView(image: UIImage(systemName: "exclamationmark.triangle"))
312 + icon.tintColor = UIColor(white: 1, alpha: 0.8)
313 + icon.preferredSymbolConfiguration = UIImage.SymbolConfiguration(pointSize: 28, weight: .regular)
314 + let label = UILabel()
315 + label.text = "This image could not be loaded."
316 + label.textColor = UIColor(white: 1, alpha: 0.8)
317 + label.font = .preferredFont(forTextStyle: .subheadline)
318 + label.adjustsFontForContentSizeCategory = true
319 + label.textAlignment = .center
320 + label.numberOfLines = 0
321 + var configuration = UIButton.Configuration.gray()
322 + configuration.title = "Try Again"
323 + configuration.cornerStyle = .capsule
324 + configuration.baseForegroundColor = .white
325 + configuration.baseBackgroundColor = UIColor(white: 1, alpha: 0.18)
326 + let retry = UIButton(configuration: configuration, primaryAction: UIAction { [weak self] _ in self?.onRetry?() })
327 + failure.axis = .vertical
328 + failure.alignment = .center
329 + failure.spacing = 12
330 + failure.isHidden = true
331 + for view in [icon, label, retry] { failure.addArrangedSubview(view) }
332 + addSubview(failure)
333 + }
334 +
335 + var image: UIImage? { imageView.image }
336 +
337 + func setImage(_ image: UIImage, full: Bool) {
338 + guard full || !isFull else { return }
339 + let previous = imageView.image?.size
340 + imageView.image = image
341 + isFull = full
342 + stopLoading()
343 + failure.isHidden = true
344 + let ratio = { (size: CGSize) in size.width / max(size.height, 1) }
345 + // A sharper copy of the same picture keeps the reader's zoom; a different shape starts over.
346 + if previous == nil || abs(ratio(previous ?? .zero) - ratio(image.size)) > 0.01 { laidOutSize = .zero }
347 + setNeedsLayout()
348 + }
349 +
350 + /// Gives back a far-away page's decoded original, keeping the thumbnail until it returns.
351 + func release(to placeholder: UIImage?) {
352 + guard isFull else { return }
353 + isFull = false
354 + imageView.image = placeholder
355 + laidOutSize = .zero
356 + setNeedsLayout()
357 + setLoading()
358 + }
359 +
360 + func setLoading() {
361 + failure.isHidden = true
362 + imageView.alpha = 1
363 + guard imageView.image == nil, spinnerDelay == nil else { return }
364 + let work = DispatchWorkItem { [weak self] in self?.spinner.startAnimating() }
365 + spinnerDelay = work
366 + DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: work)
367 + }
368 +
369 + func setFailed(retryable: Bool) {
370 + stopLoading()
371 + guard !isFull else { return }
372 + failure.arrangedSubviews.last?.isHidden = !retryable
373 + failure.isHidden = false
374 + // A thumbnail stays visible behind the message, dimmed.
375 + imageView.alpha = imageView.image == nil ? 1 : 0.35
376 + }
377 +
378 + private func stopLoading() {
379 + spinnerDelay?.cancel()
380 + spinnerDelay = nil
381 + spinner.stopAnimating()
382 + imageView.alpha = 1
383 + }
384 +
385 + var isZoomed: Bool { scroll.zoomScale > scroll.minimumZoomScale + 0.01 }
386 +
387 + func resetZoom(animated: Bool) { scroll.setZoomScale(scroll.minimumZoomScale, animated: animated) }
388 +
389 + override func layoutSubviews() {
390 + super.layoutSubviews()
391 + scroll.frame = bounds
392 + spinner.center = CGPoint(x: bounds.midX, y: bounds.midY)
393 + let width = min(bounds.width - 48, 320)
394 + let height = failure.systemLayoutSizeFitting(CGSize(width: width, height: 0),
395 + withHorizontalFittingPriority: .required,
396 + verticalFittingPriority: .fittingSizeLevel).height
397 + failure.frame = CGRect(x: (bounds.width - width) / 2, y: (bounds.height - height) / 2, width: width, height: height)
398 + guard bounds.size != laidOutSize, let size = imageView.image?.size, size.width > 0, size.height > 0 else { return }
399 + laidOutSize = bounds.size
400 + let fit = min(bounds.width / size.width, bounds.height / size.height)
401 + scroll.minimumZoomScale = 1
402 + scroll.zoomScale = 1
403 + imageView.transform = .identity
404 + imageView.frame = CGRect(x: 0, y: 0, width: size.width * fit, height: size.height * fit)
405 + scroll.contentSize = imageView.frame.size
406 + // Enough to fill the screen and then some, or to see the original's pixels.
407 + let fill = max(bounds.width / imageView.frame.width, bounds.height / imageView.frame.height)
408 + let pixels = 1 / fit / (window?.screen.scale ?? 2)
409 + scroll.maximumZoomScale = max(3, fill * 1.5, pixels)
410 + centerImage()
411 + }
412 +
413 + /// The fitted frame of the image, for the opening transition.
414 + func fittedFrame(in view: UIView) -> CGRect {
415 + layoutIfNeeded()
416 + return imageView.convert(imageView.bounds, to: view)
417 + }
418 +
419 + func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }
420 +
421 + func scrollViewDidZoom(_ scrollView: UIScrollView) { centerImage() }
422 +
423 + private func centerImage() {
424 + let content = scroll.contentSize
425 + imageView.center = CGPoint(x: max(content.width, scroll.bounds.width) / 2,
426 + y: max(content.height, scroll.bounds.height) / 2)
427 + }
428 +
429 + func toggleZoom(at point: CGPoint) {
430 + if isZoomed { resetZoom(animated: true); return }
431 + guard imageView.image != nil else { return }
432 + let location = convert(point, to: imageView)
433 + let fill = max(scroll.bounds.width / imageView.bounds.width, scroll.bounds.height / imageView.bounds.height)
434 + let scale = min(scroll.maximumZoomScale, fill > 1.2 ? fill : 2.5)
435 + let width = scroll.bounds.width / scale
436 + let height = scroll.bounds.height / scale
437 + scroll.zoom(to: CGRect(x: location.x - width / 2, y: location.y - height / 2, width: width, height: height),
438 + animated: true)
439 + }
440 +}
441 +
442 +/// System bars, so UIKit places Close, the title, Save and Share: at the top and bottom of an iPhone,
443 +/// and in the side bar of an unfolded iPhone Duo.
444 +private final class T3ImageViewerNavigation: UINavigationController {
445 + init(viewer: T3ImageViewerController) {
446 + super.init(rootViewController: viewer)
447 + modalPresentationStyle = .overFullScreen
448 + modalPresentationCapturesStatusBarAppearance = true
449 + overrideUserInterfaceStyle = .dark
450 + view.backgroundColor = .clear
451 + if #unavailable(iOS 26.0) {
452 + // Before iOS 26 bars at the scroll edge are transparent; iOS 26 gives them its edge blur instead.
453 + let bar = UINavigationBarAppearance()
454 + bar.configureWithDefaultBackground()
455 + navigationBar.scrollEdgeAppearance = bar
456 + navigationBar.compactScrollEdgeAppearance = bar
457 + let tools = UIToolbarAppearance()
458 + tools.configureWithDefaultBackground()
459 + toolbar.scrollEdgeAppearance = tools
460 + toolbar.compactScrollEdgeAppearance = tools
461 + }
462 + setNavigationBarHidden(true, animated: false)
463 + setToolbarHidden(true, animated: false)
464 + }
465 +
466 + @available(*, unavailable)
467 + required init?(coder: NSCoder) { nil }
468 +
469 + override var childForStatusBarHidden: UIViewController? { topViewController }
470 + override var childForStatusBarStyle: UIViewController? { topViewController }
471 + override var childForHomeIndicatorAutoHidden: UIViewController? { topViewController }
472 +}
473 +
474 +final class T3ImageViewerController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
475 + var sourceView: (Int) -> UIView? = { _ in nil }
476 + var fileForPage: (Int) -> URL? = { _ in nil }
477 + var onRetry: (Int) -> Void = { _ in }
478 + var onPageChange: (Int) -> Void = { _ in }
479 + var onDismissed: () -> Void = {}
480 +
481 + private let titles: [String]
482 + private var currentIndex: Int
483 + private let backdrop = UIView()
484 + private let pager = UIScrollView()
485 + private var pages: [T3ImageViewerPage] = []
486 + private let titleLabel = UILabel()
487 + private let counterLabel = UILabel()
488 + private lazy var dismissPan = UIPanGestureRecognizer(target: self, action: #selector(handleDismissPan(_:)))
489 + private var chromeHidden = false
490 + private var chromeHiddenBeforeDrag = false
491 + private var dragAnchor = CGPoint.zero
492 + private var transitioning = true
493 + private var closeRequested = false
494 + private var closing = false
495 + private var revealed = false
496 + private var revealWaiters: [CheckedContinuation<Void, Never>] = []
497 + private var laidOutSize = CGSize.zero
498 + private var isLayingOut = false
499 + private lazy var saveItem = UIBarButtonItem(
500 + title: "Save to Photos", image: UIImage(systemName: "square.and.arrow.down"),
501 + primaryAction: UIAction { [weak self] _ in self?.save() })
502 + private lazy var shareItem = UIBarButtonItem(
503 + systemItem: .action, primaryAction: UIAction { [weak self] _ in self?.share() })
504 + private static let pageGap: CGFloat = 20
505 +
506 + init(titles: [String], selectedIndex: Int) {
507 + self.titles = titles
508 + currentIndex = selectedIndex
509 + super.init(nibName: nil, bundle: nil)
510 + }
511 +
512 + @available(*, unavailable)
513 + required init?(coder: NSCoder) { nil }
514 +
515 + override var prefersStatusBarHidden: Bool { chromeHidden }
516 + override var preferredStatusBarStyle: UIStatusBarStyle { .lightContent }
517 + override var prefersHomeIndicatorAutoHidden: Bool { chromeHidden }
518 + override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { .fade }
519 +
520 + override func viewDidLoad() {
521 + super.viewDidLoad()
522 + view.backgroundColor = .clear
523 + backdrop.backgroundColor = .black
524 + backdrop.alpha = 0
525 + view.addSubview(backdrop)
526 + pager.isPagingEnabled = true
527 + pager.showsHorizontalScrollIndicator = false
528 + pager.showsVerticalScrollIndicator = false
529 + pager.contentInsetAdjustmentBehavior = .never
530 + pager.alwaysBounceVertical = false
531 + pager.delegate = self
532 + pager.isHidden = true
533 + view.addSubview(pager)
534 + for index in titles.indices {
535 + let page = T3ImageViewerPage()
536 + page.imageView.accessibilityLabel = titles[index]
537 + page.onRetry = { [weak self] in self?.onRetry(index) }
538 + page.scroll.panGestureRecognizer.require(toFail: dismissPan)
539 + page.setLoading()
540 + pages.append(page)
541 + pager.addSubview(page)
542 + }
543 + pager.panGestureRecognizer.require(toFail: dismissPan)
544 + dismissPan.delegate = self
545 + dismissPan.maximumNumberOfTouches = 1
546 + view.addGestureRecognizer(dismissPan)
547 + let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:)))
548 + doubleTap.numberOfTapsRequired = 2
549 + pager.addGestureRecognizer(doubleTap)
550 + let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap))
551 + singleTap.require(toFail: doubleTap)
552 + pager.addGestureRecognizer(singleTap)
553 + configureChrome()
554 + updateTitle()
555 + }
556 +
557 + private func configureChrome() {
558 + navigationItem.leftBarButtonItem = UIBarButtonItem(
559 + systemItem: .close, primaryAction: UIAction { [weak self] _ in self?.close() })
560 + if #unavailable(iOS 26.0) {
561 + // Before iOS 26 a navigation item has no subtitle, so the count sits under the title by hand.
562 + titleLabel.font = .preferredFont(forTextStyle: .headline)
563 + counterLabel.font = .preferredFont(forTextStyle: .caption1)
564 + counterLabel.textColor = .secondaryLabel
565 + for label in [titleLabel, counterLabel] {
566 + label.textAlignment = .center
567 + label.adjustsFontForContentSizeCategory = true
568 + label.lineBreakMode = .byTruncatingMiddle
569 + }
570 + let titles = UIStackView(arrangedSubviews: [titleLabel, counterLabel])
571 + titles.axis = .vertical
572 + titles.alignment = .center
573 + navigationItem.titleView = titles
574 + }
575 + toolbarItems = [.flexibleSpace(), saveItem, shareItem]
576 + setContentScrollView(pager, for: .top)
577 + setContentScrollView(pager, for: .bottom)
578 + }
579 +
580 + /// Shows or hides the bars through UIKit, which also moves them out of an iPhone Duo's side bar.
581 + private func setBarsVisible(_ visible: Bool) {
582 + navigationController?.setNavigationBarHidden(!visible, animated: true)
583 + navigationController?.setToolbarHidden(!visible, animated: true)
584 + }
585 +
586 + private func updateTitle() {
587 + updateActions()
588 + let title = titles[safe: currentIndex]
589 + let counter = titles.count > 1 ? "\(currentIndex + 1) of \(titles.count)" : nil
590 + navigationItem.title = title
591 + if #available(iOS 26.0, *) { navigationItem.subtitle = counter }
592 + titleLabel.text = title
593 + counterLabel.text = counter
594 + counterLabel.isHidden = counter == nil
595 + }
596 +
597 + override func viewDidLayoutSubviews() {
598 + super.viewDidLayoutSubviews()
599 + backdrop.frame = view.bounds
600 + guard view.bounds.size != laidOutSize else { return }
601 + laidOutSize = view.bounds.size
602 + // Resizing the pager scrolls it; that must not move the reader to another page.
603 + isLayingOut = true
604 + defer { isLayingOut = false }
605 + // Pages sit a gap apart, like Photos, so the pager is a gap wider than the screen.
606 + let pageWidth = view.bounds.width + Self.pageGap
607 + pager.frame = CGRect(x: -Self.pageGap / 2, y: 0, width: pageWidth, height: view.bounds.height)
608 + for (index, page) in pages.enumerated() {
609 + page.transform = .identity
610 + page.frame = CGRect(x: CGFloat(index) * pageWidth + Self.pageGap / 2, y: 0,
611 + width: view.bounds.width, height: view.bounds.height)
612 + }
613 + pager.contentSize = CGSize(width: pageWidth * CGFloat(pages.count), height: view.bounds.height)
614 + pager.contentOffset = CGPoint(x: CGFloat(currentIndex) * pageWidth, y: 0)
615 + }
616 +
617 + func setImage(_ image: UIImage, at index: Int, full: Bool) {
618 + guard let page = pages[safe: index] else { return }
619 + page.setImage(image, full: full)
620 + updateActions()
621 + }
622 +
623 + func setLoading(at index: Int) { pages[safe: index]?.setLoading() }
624 +
625 + func release(at index: Int, placeholder: UIImage?) {
626 + pages[safe: index]?.release(to: placeholder)
627 + updateActions()
628 + }
629 +
630 + func setFailed(at index: Int, retryable: Bool) {
631 + pages[safe: index]?.setFailed(retryable: retryable)
632 + updateActions()
633 + }
634 +
635 + /// Save and Share act on the original, so they wait until the current page shows it.
636 + private func updateActions() {
637 + let ready = pages[safe: currentIndex]?.isFull == true
638 + saveItem.isEnabled = ready
639 + shareItem.isEnabled = ready
640 + }
641 +
642 + // MARK: Transitions
643 +
644 + private var reduceMotion: Bool { UIAccessibility.isReduceMotionEnabled }
645 +
646 + private func visibleSource(_ index: Int) -> UIView? {
647 + guard !reduceMotion, let source = sourceView(index), source.window === view.window, !source.isHidden else { return nil }
648 + let frame = source.convert(source.bounds, to: view)
649 + guard frame.width > 1, frame.height > 1, view.bounds.intersects(frame) else { return nil }
650 + return source
651 + }
652 +
653 + private static func cornerRadius(of view: UIView) -> CGFloat {
654 + var queue = [view]
655 + var depth = 0
656 + while !queue.isEmpty, depth < 4 {
657 + for candidate in queue where candidate.layer.cornerRadius > 0 { return candidate.layer.cornerRadius }
658 + queue = queue.flatMap(\.subviews)
659 + depth += 1
660 + }
661 + return 0
662 + }
663 +
664 + private func makeTransitionView(_ image: UIImage, frame: CGRect) -> UIImageView {
665 + let transition = UIImageView(image: image)
666 + transition.contentMode = .scaleAspectFill
667 + transition.clipsToBounds = true
668 + transition.frame = frame
669 + view.addSubview(transition)
670 + return transition
671 + }
672 +
673 + /// Returns once the open transition has finished and the thumbnails are on screen again.
674 + func untilRevealed() async {
675 + guard !revealed else { return }
676 + await withCheckedContinuation { revealWaiters.append($0) }
677 + }
678 +
679 + func animateIn() {
680 + view.layoutIfNeeded()
681 + let page = pages[currentIndex]
682 + let reveal = { [weak self] in
683 + guard let self else { return }
684 + self.pager.isHidden = false
685 + self.transitioning = false
686 + self.revealed = true
687 + for waiter in self.revealWaiters { waiter.resume() }
688 + self.revealWaiters.removeAll()
689 + self.setNeedsStatusBarAppearanceUpdate()
690 + UIAccessibility.post(notification: .screenChanged, argument: page.imageView)
691 + if self.closeRequested { self.close() }
692 + }
693 + guard let image = page.image, let source = visibleSource(currentIndex) else {
694 + pager.isHidden = false
695 + pager.alpha = 0
696 + setBarsVisible(true)
697 + UIView.animate(withDuration: reduceMotion ? 0.2 : 0.25, animations: {
698 + self.backdrop.alpha = 1
699 + self.pager.alpha = 1
700 + }, completion: { _ in reveal() })
701 + return
702 + }
703 + let transition = makeTransitionView(image, frame: source.convert(source.bounds, to: view))
704 + transition.layer.cornerRadius = Self.cornerRadius(of: source)
705 + let sourceAlpha = source.alpha
706 + source.alpha = 0
707 + let target = page.fittedFrame(in: view)
708 + let animator = UIViewPropertyAnimator(duration: 0.42, dampingRatio: 0.86) {
709 + transition.frame = target
710 + transition.layer.cornerRadius = 0
711 + self.backdrop.alpha = 1
712 + }
713 + setBarsVisible(true)
714 + animator.addCompletion { _ in
715 + source.alpha = sourceAlpha
716 + transition.removeFromSuperview()
717 + reveal()
718 + }
719 + animator.startAnimation()
720 + }
721 +
722 + /// Closes back into the current page's thumbnail, or away in the drag's direction when it is gone.
723 + func close(velocity: CGPoint = .zero) {
724 + closeRequested = true
725 + guard !transitioning, !closing else { return }
726 + closing = true
727 + transitioning = true
728 + setNeedsStatusBarAppearanceUpdate()
729 + setBarsVisible(false)
730 + let page = pages[currentIndex]
731 + guard let image = page.image else {
732 + UIView.animate(withDuration: 0.2, animations: { self.view.alpha = 0 }, completion: { _ in self.finishClose() })
733 + return
734 + }
735 + let transition = makeTransitionView(image, frame: page.imageView.convert(page.imageView.bounds, to: view))
736 + pager.isHidden = true
737 + guard let source = visibleSource(currentIndex) else {
738 + let direction: CGFloat = velocity.y < 0 ? -1 : 1
739 + let animator = UIViewPropertyAnimator(duration: 0.3, curve: .easeIn) {
740 + transition.center.y += direction * self.view.bounds.height
741 + self.backdrop.alpha = 0
742 + if self.reduceMotion { transition.alpha = 0 }
743 + }
744 + animator.addCompletion { _ in self.finishClose() }
745 + animator.startAnimation()
746 + return
747 + }
748 + let sourceAlpha = source.alpha
749 + source.alpha = 0
750 + let target = source.convert(source.bounds, to: view)
751 + let radius = Self.cornerRadius(of: source)
752 + let speed = hypot(velocity.x, velocity.y)
753 + let distance = hypot(target.midX - transition.center.x, target.midY - transition.center.y)
754 + let initial = distance > 0 ? CGVector(dx: velocity.x / distance, dy: velocity.y / distance) : .zero
755 + let timing = UISpringTimingParameters(dampingRatio: 0.88, initialVelocity: speed > 0 ? initial : .zero)
756 + let animator = UIViewPropertyAnimator(duration: 0.4, timingParameters: timing)
757 + animator.addAnimations {
758 + transition.frame = target
759 + transition.layer.cornerRadius = radius
760 + self.backdrop.alpha = 0
761 + }
762 + animator.addCompletion { _ in
763 + source.alpha = sourceAlpha
764 + self.finishClose()
765 + }
766 + animator.startAnimation()
767 + }
768 +
769 + private func finishClose() {
770 + presentingViewController?.dismiss(animated: false) { [onDismissed] in onDismissed() }
771 + }
772 +
773 + // MARK: Gestures
774 +
775 + func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
776 + guard gestureRecognizer === dismissPan else { return true }
777 + guard !transitioning, !pager.isDragging, !pager.isDecelerating,
778 + let page = pages[safe: currentIndex], !page.isZoomed
779 + else { return false }
780 + let velocity = dismissPan.velocity(in: view)
781 + return abs(velocity.y) > abs(velocity.x)
782 + }
783 +
784 + @objc private func handleDismissPan(_ gesture: UIPanGestureRecognizer) {
785 + let page = pages[currentIndex]
786 + let translation = gesture.translation(in: view)
787 + switch gesture.state {
788 + case .began:
789 + chromeHiddenBeforeDrag = chromeHidden
790 + dragAnchor = gesture.location(in: page)
791 + setChromeHidden(true)
792 + case .changed:
793 + // Shrink around the finger, as Photos does, so the touched spot stays under it.
794 + let progress = min(1, abs(translation.y) / (view.bounds.height / 2))
795 + let scale = 1 - 0.3 * progress
796 + let offset = CGPoint(x: dragAnchor.x - page.bounds.midX, y: dragAnchor.y - page.bounds.midY)
797 + page.transform = CGAffineTransform(translationX: translation.x + (1 - scale) * offset.x,
798 + y: translation.y + (1 - scale) * offset.y).scaledBy(x: scale, y: scale)
799 + backdrop.alpha = 1 - progress
800 + case .ended, .cancelled, .failed:
801 + let velocity = gesture.velocity(in: view)
802 + let flung = abs(velocity.y) > 800 && velocity.y * translation.y > 0
803 + if gesture.state == .ended, flung || abs(translation.y) > 120 {
804 + close(velocity: velocity)
805 + } else {
806 + UIViewPropertyAnimator(duration: 0.35, dampingRatio: 0.8) {
807 + page.transform = .identity
808 + self.backdrop.alpha = 1
809 + }.startAnimation()
810 + setChromeHidden(chromeHiddenBeforeDrag)
811 + }
812 + default:
813 + break
814 + }
815 + }
816 +
817 + @objc private func handleDoubleTap(_ gesture: UITapGestureRecognizer) {
818 + guard !transitioning, let page = pages[safe: currentIndex] else { return }
819 + page.toggleZoom(at: gesture.location(in: page))
820 + }
821 +
822 + @objc private func handleSingleTap() {
823 + guard !transitioning else { return }
824 + setChromeHidden(!chromeHidden)
825 + }
826 +
827 + private func setChromeHidden(_ hidden: Bool) {
828 + guard chromeHidden != hidden else { return }
829 + chromeHidden = hidden
830 + setBarsVisible(!hidden)
831 + UIView.animate(withDuration: 0.2) { self.setNeedsStatusBarAppearanceUpdate() }
832 + setNeedsUpdateOfHomeIndicatorAutoHidden()
833 + }
834 +
835 + func scrollViewDidScroll(_ scrollView: UIScrollView) {
836 + guard scrollView === pager, !transitioning, !isLayingOut, pager.bounds.width > 0 else { return }
837 + let index = Int((pager.contentOffset.x / pager.bounds.width).rounded())
838 + guard pages.indices.contains(index), index != currentIndex else { return }
839 + pages[currentIndex].resetZoom(animated: false)
840 + currentIndex = index
841 + updateTitle()
842 + onPageChange(index)
843 + }
844 +
845 + private func scroll(to index: Int) {
846 + guard pages.indices.contains(index), !transitioning else { return }
847 + pager.setContentOffset(CGPoint(x: CGFloat(index) * pager.bounds.width, y: 0), animated: !reduceMotion)
848 + }
849 +
850 + // MARK: Share, keyboard and accessibility
851 +
852 + private func save() {
853 + let image = pages[currentIndex].isFull ? pages[currentIndex].image : nil
854 + // Original bytes keep the format and metadata; an SVG only has its rendered image. The copy
855 + // belongs to this save, since closing the viewer deletes its files before Photos may read them.
856 + let original = fileForPage(currentIndex).flatMap { file -> URL? in
857 + guard file.pathExtension.lowercased() != "svg", let source = CGImageSourceCreateWithURL(file as CFURL, nil), CGImageSourceGetCount(source) > 0 else { return nil }
858 + let copy = FileManager.default.temporaryDirectory.appendingPathComponent("t3-save-\(UUID().uuidString)")
859 + .appendingPathComponent(file.lastPathComponent)
860 + do {
861 + try FileManager.default.createDirectory(at: copy.deletingLastPathComponent(), withIntermediateDirectories: true)
862 + try FileManager.default.copyItem(at: file, to: copy)
863 + return copy
864 + } catch {
865 + return nil
866 + }
867 + }
868 + guard original != nil || image != nil else { return }
869 + let cleanUp = { if let original { try? FileManager.default.removeItem(at: original.deletingLastPathComponent()) } }
870 + PHPhotoLibrary.requestAuthorization(for: .addOnly) { [weak self] status in
871 + guard status == .authorized || status == .limited else {
872 + cleanUp()
873 + DispatchQueue.main.async { self?.showSaveError("Allow T3 Code to add photos in Settings.") }
874 + return
875 + }
876 + PHPhotoLibrary.shared().performChanges({
877 + if let original {
878 + PHAssetCreationRequest.forAsset().addResource(with: .photo, fileURL: original, options: nil)
879 + } else if let image {
880 + PHAssetChangeRequest.creationRequestForAsset(from: image)
881 + }
882 + }, completionHandler: { saved, error in
883 + cleanUp()
884 + DispatchQueue.main.async {
885 + if saved {
886 + self?.confirmSaved()
887 + } else {
888 + self?.showSaveError(error?.localizedDescription ?? "Photos could not save this image.")
889 + }
890 + }
891 + })
892 + }
893 + }
894 +
895 + private func confirmSaved() {
896 + UINotificationFeedbackGenerator().notificationOccurred(.success)
897 + UIAccessibility.post(notification: .announcement, argument: "Saved to Photos")
898 + saveItem.image = UIImage(systemName: "checkmark")
899 + DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in
900 + self?.saveItem.image = UIImage(systemName: "square.and.arrow.down")
901 + }
902 + }
903 +
904 + private func showSaveError(_ message: String) {
905 + let alert = UIAlertController(title: "Could not save image", message: message, preferredStyle: .alert)
906 + alert.addAction(UIAlertAction(title: "OK", style: .default))
907 + present(alert, animated: true)
908 + }
909 +
910 + private func share() {
911 + let page = pages[currentIndex]
912 + let item: Any? = fileForPage(currentIndex) ?? (page.isFull ? page.image : nil)
913 + guard let item else { return }
914 + let sheet = UIActivityViewController(activityItems: [item], applicationActivities: nil)
915 + sheet.popoverPresentationController?.sourceItem = shareItem
916 + present(sheet, animated: true)
917 + }
918 +
919 + override var canBecomeFirstResponder: Bool { true }
920 +
921 + override func viewDidAppear(_ animated: Bool) {
922 + super.viewDidAppear(animated)
923 + becomeFirstResponder()
924 + }
925 +
926 + override var keyCommands: [UIKeyCommand]? {
927 + [
928 + UIKeyCommand(input: UIKeyCommand.inputEscape, modifierFlags: [], action: #selector(handleEscape)),
929 + UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags: [], action: #selector(handlePrevious)),
930 + UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags: [], action: #selector(handleNext)),
931 + ]
932 + }
933 +
934 + @objc private func handleEscape() { close() }
935 + @objc private func handlePrevious() { scroll(to: currentIndex - 1) }
936 + @objc private func handleNext() { scroll(to: currentIndex + 1) }
937 +
938 + override func accessibilityPerformEscape() -> Bool {
939 + close()
940 + return true
941 + }
942 +
943 + override func accessibilityScroll(_ direction: UIAccessibilityScrollDirection) -> Bool {
944 + switch direction {
945 + case .left: scroll(to: currentIndex + 1)
946 + case .right: scroll(to: currentIndex - 1)
947 + default: return false
948 + }
949 + UIAccessibility.post(notification: .pageScrolled, argument: counterLabel.text)
950 + return true
951 + }
952 +}
apps/mobile/modules/t3-native-controls/ios/T3NativePresentation.swift
+14 -7
@@ -7,21 +7,28 @@ final class T3PresentationSources {
7 init(_ view: UIView) { self.view = view }
8 }
9
10 - private var entries: [String: Entry] = [:]
10 + /// The same file embedded twice registers twice; removing one copy keeps the other.
11 + private var entries: [String: [Entry]] = [:]
12
13 func register(_ view: UIView, identifier: String) {
13 - entries[identifier] = Entry(view)
14 + var list = (entries[identifier] ?? []).filter { $0.view != nil && $0.view !== view }
15 + list.append(Entry(view))
16 + entries[identifier] = list
17 }
18
19 func remove(_ view: UIView, identifier: String) {
17 - if entries[identifier]?.view == nil || entries[identifier]?.view === view {
18 - entries.removeValue(forKey: identifier)
19 - }
20 + let list = (entries[identifier] ?? []).filter { $0.view != nil && $0.view !== view }
21 + entries[identifier] = list.isEmpty ? nil : list
22 }
23
24 func view(for identifier: String) -> UIView? {
23 - // Use the child bounds, not the wrapper's potentially stretched layout bounds.
24 - entries[identifier]?.view?.subviews.first
25 + let views = (entries[identifier] ?? []).compactMap(\.view)
26 + // Prefer an on-screen copy, the latest first; use the child bounds, not the wrapper's stretched ones.
27 + let source = views.last(where: { view in
28 + guard let window = view.window else { return false }
29 + return window.bounds.intersects(view.convert(view.bounds, to: window))
30 + }) ?? views.last
31 + return source?.subviews.first
32 }
33 }
34
apps/mobile/src/components/ui/FilePreviewSession.tsx
+7 -1
@@ -11,7 +11,12 @@ import {
11 } from "../../lib/attachmentDownload";
12 import { usePreviewPresentation } from "../../lib/previewPresentation";
13 import { refreshAssetUrl } from "../../state/assets";
14 -import { filePreviewGallery, filePreviewKey, filePreviewName } from "../../lib/filePreviewGallery";
14 +import {
15 + filePreviewGallery,
16 + filePreviewKey,
17 + filePreviewName,
18 + filePreviewSourceIdentifier,
19 +} from "../../lib/filePreviewGallery";
20 import { FilePreviewGallery } from "./FilePreviewGallery";
21 import type { MediaActionsSource } from "../../lib/mediaActionsSource";
22 import type {
@@ -155,6 +160,7 @@ function ResolvedFilePreview(
160 return {
161 ...item,
162 name: filePreviewName(item),
163 + sourceIdentifier: filePreviewSourceIdentifier(item),
164 ...(uri ? { uri } : uri === null ? { failed: true } : {}),
165 };
166 });
apps/mobile/src/features/threads/ThreadFeed.tsx
+6 -1
@@ -134,6 +134,7 @@ import { useResolveClassNames } from "uniwind";
134 import { useReduceMotionEnabled } from "../../lib/appState";
135 import { useFilePreviewGallery, FilePreviewGallery } from "../../components/ui/FilePreviewGallery";
136 import { assetImageSource } from "../../lib/assetImageSource";
137 +import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery";
138 import { composerImageGallery } from "../../lib/composerImageGallery";
139 import { isFileBackedComposerAttachment } from "../../lib/composerImages";
140 import { useLocalAttachmentPreview } from "../../lib/localAttachmentPreview";
@@ -556,13 +557,17 @@ function MessageAttachmentImage(props: {
557 readonly onPressPreview: (source: FilePreviewSource) => void;
558 }) {
559 const withGallery = useFilePreviewGallery();
559 - const sourceIdentifier = useId();
560 const resource = {
561 _tag: "attachment" as const,
562 attachmentId: props.attachmentId,
563 fileName: props.name,
564 mimeType: props.mimeType,
565 };
566 + const sourceIdentifier = filePreviewSourceIdentifier({
567 + kind: "image",
568 + environmentId: props.environmentId,
569 + resource,
570 + });
571 const uri = useAssetUrl(props.environmentId, resource);
572 const refreshAssetUrl = useRefreshAssetUrl(props.environmentId, resource);
573 const retriedImage = useRef(false);
apps/mobile/src/features/threads/ThreadMarkdownImage.tsx
+9 -1
@@ -22,6 +22,7 @@ import { useAssetUrlState } from "../../state/assets";
22 import { WorkspaceMutationIdContext } from "./workspaceMutationIdContext";
23 import { ZoomableImagePressable } from "./ZoomableImagePressable";
24 import { assetImageCacheKey } from "../../lib/assetImageSource";
25 +import { filePreviewSourceIdentifier } from "../../lib/filePreviewGallery";
26 import {
27 MARKDOWN_IMAGE_MAX_WIDTH,
28 type MarkdownImageDisplaySize,
@@ -91,6 +92,7 @@ const noSvgDocumentAtom = Atom.make(AsyncResult.initial<SvgDocument, SvgLoadErro
92 export function ThreadMarkdownImageView(props: {
93 readonly uri: string | null;
94 readonly sourceKey: string;
95 + readonly sourceIdentifier?: string;
96 readonly cacheKey?: string | undefined;
97 readonly unavailable: boolean;
98 readonly unavailableDetail?: string | undefined;
@@ -101,7 +103,8 @@ export function ThreadMarkdownImageView(props: {
103 readonly onPressPreview: (source: FilePreviewSource) => void;
104 }) {
105 const withGallery = useFilePreviewGallery();
104 - const sourceIdentifier = useId();
106 + const localSourceIdentifier = useId();
107 + const sourceIdentifier = props.sourceIdentifier ?? localSourceIdentifier;
108 const mediaActions = useMediaActions(props.actionsSource);
109 const contextWidth = useContext(MarkdownImageAvailableWidthContext);
110 const [measuredWidth, setMeasuredWidth] = useState(0);
@@ -307,6 +310,11 @@ export function ThreadMarkdownImage(props: {
310 : undefined
311 }
312 sourceKey={sourceKey}
313 + sourceIdentifier={filePreviewSourceIdentifier({
314 + kind: "image",
315 + environmentId: props.environmentId,
316 + resource: props.resource,
317 + })}
318 unavailable={assetUrl._tag === "Failure"}
319 unavailableDetail={
320 assetUrl._tag === "Failure" && assetUrl.reason === "missing-file-access"
apps/mobile/src/lib/filePreviewGallery.ts
+5
@@ -12,6 +12,11 @@ export function filePreviewKey(source: FilePreviewItem): string {
12 return source.uri;
13 }
14
15 +/** The thumbnail a gallery page opens from and closes into, including pages that were not tapped. */
16 +export function filePreviewSourceIdentifier(source: FilePreviewItem): string {
17 + return source.sourceIdentifier ?? `preview:${filePreviewKey(source)}`;
18 +}
19 +
20 export function filePreviewGallery(source: FilePreviewSource, group: readonly FilePreviewItem[]) {
21 if (source.kind !== "image") return [source];
22 const selectedKey = filePreviewKey(source);
docs/internals/mobile-navigation.md
+5 -2
@@ -67,8 +67,11 @@ See the [fork build instructions](../operations/mobile-screens-fork.md).
67 ## Native media presentations
68
69 iOS delegates full-screen video to [AVKit](../../apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift)
70 -and images and documents to [Quick Look](../../apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift).
71 -Each framework owns its controls and transition. A separate UIKit zoom transition
70 +and documents to [Quick Look](../../apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift).
71 +Each framework owns its controls and transition. Images open in our own
72 +[viewer](../../apps/mobile/modules/t3-native-controls/ios/T3NativeImageViewer.swift), because Quick Look
73 +dragged its image when a swipe or a dismiss started. The viewer keeps its controls in a
74 +navigation controller's bars, so UIKit can move them into an unfolded iPhone Duo's side bar. A separate UIKit zoom transition
75 prevents AVKit's native Close action from exiting full screen and interferes with
76 Quick Look's interactive return to its thumbnail. The AVKit entry selector is
77 guarded, with standard modal presentation as the fallback.
packages/client-runtime/src/mediaSource.test.ts
+9
@@ -37,6 +37,15 @@ describe("resolveMediaSource", () => {
37 name: "render",
38 });
39 });
40 +
41 + it("names a data URI by its kind, not its payload", () => {
42 + const href =
43 + "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciLz4=";
44 + expect(resolveMediaSource(href, { threadId, imageEmbed: true })).toMatchObject({
45 + kind: "image",
46 + name: "image",
47 + });
48 + });
49 });
50
51 describe("host paths", () => {
packages/client-runtime/src/mediaSource.ts
+2 -1
@@ -68,7 +68,8 @@ export function resolveMediaSource(
68 ? splitMarkdownLinkSearchAndHash(classified.uri).path
69 : splitFilePathPosition(classified.path).path;
70 // Local paths have already been decoded. Do not interpret literal #, ?, or % characters again.
71 - const basename = fileBasename(path);
71 + // A data URI carries no file name; its last path segment is the payload.
72 + const basename = /^data:/i.test(path) ? "" : fileBasename(path);
73 const extensionIndex = basename.lastIndexOf(".");
74 const detectedMimeType =
75 classified._tag === "Direct"