Skip to content

Commit 59f9545

Browse files
author
Julius Marminge
committed
fix(mobile): use native image preview dismissal
1 parent 1dcd586 commit 59f9545

2 files changed

Lines changed: 46 additions & 178 deletions

File tree

‎apps/mobile/modules/t3-native-controls/ios/T3NativeFilePresentation.swift‎

Lines changed: 39 additions & 172 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import AVFoundation
21
import ImageIO
32
import QuickLook
43
import UIKit
@@ -9,135 +8,16 @@ private final class FilePreviewItem: NSObject, QLPreviewItem {
98
var previewItemTitle: String?
109
}
1110

12-
private struct PreparedPreviewFile {
13-
let url: URL
14-
let image: UIImage?
15-
}
16-
17-
/// UIKit supplies pinch/pan physics, header controls, sharing, and interactive zoom dismissal.
18-
private final class NativeImagePreviewController: UIViewController, UIScrollViewDelegate {
19-
var usesZoomTransition = false
20-
private let imageView: UIImageView
21-
private let scrollView = UIScrollView()
22-
private let url: URL
23-
private let onClose: () -> Void
24-
private let onDismiss: () -> Void
25-
private var viewportSize = CGSize.zero
11+
private final class FilePreviewController: QLPreviewController {
12+
var onAppear: (() -> Void)?
2613

27-
init(image: UIImage, url: URL, title: String, onClose: @escaping () -> Void, onDismiss: @escaping () -> Void) {
28-
self.imageView = UIImageView(image: image)
29-
self.url = url
30-
self.onClose = onClose
31-
self.onDismiss = onDismiss
32-
super.init(nibName: nil, bundle: nil)
33-
self.title = title
34-
}
35-
36-
required init?(coder: NSCoder) { nil }
37-
38-
override func viewDidLoad() {
39-
super.viewDidLoad()
40-
view.backgroundColor = .black
41-
scrollView.frame = view.bounds
42-
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
43-
scrollView.contentInsetAdjustmentBehavior = .never
44-
scrollView.showsHorizontalScrollIndicator = false
45-
scrollView.showsVerticalScrollIndicator = false
46-
scrollView.delegate = self
47-
scrollView.accessibilityIdentifier = "ImagePreviewScrollView"
48-
imageView.isAccessibilityElement = true
49-
imageView.accessibilityLabel = title
50-
imageView.accessibilityIdentifier = "ImagePreviewImage"
51-
scrollView.addSubview(imageView)
52-
view.addSubview(scrollView)
53-
54-
navigationItem.leftBarButtonItem = UIBarButtonItem(systemItem: .close, primaryAction: UIAction { [weak self] _ in
55-
self?.onClose()
56-
})
57-
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(share))
58-
navigationItem.rightBarButtonItem?.accessibilityLabel = "Share"
59-
let appearance = UINavigationBarAppearance()
60-
appearance.configureWithTransparentBackground()
61-
appearance.titleTextAttributes = [.foregroundColor: UIColor.white]
62-
navigationItem.standardAppearance = appearance
63-
navigationItem.scrollEdgeAppearance = appearance
64-
navigationItem.compactAppearance = appearance
65-
navigationController?.navigationBar.tintColor = .white
66-
67-
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(zoom))
68-
doubleTap.numberOfTapsRequired = 2
69-
let singleTap = UITapGestureRecognizer(target: self, action: #selector(toggleControls))
70-
singleTap.require(toFail: doubleTap)
71-
scrollView.addGestureRecognizer(singleTap)
72-
scrollView.addGestureRecognizer(doubleTap)
73-
if !usesZoomTransition {
74-
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(closeIfNotZoomed))
75-
swipe.direction = .down
76-
scrollView.addGestureRecognizer(swipe)
77-
}
78-
}
79-
80-
override func viewDidLayoutSubviews() {
81-
super.viewDidLayoutSubviews()
82-
let size = scrollView.bounds.size
83-
guard size != viewportSize, let image = imageView.image, size.width > 0, size.height > 0 else { return }
84-
viewportSize = size
85-
scrollView.minimumZoomScale = 1
86-
scrollView.zoomScale = 1
87-
imageView.frame = CGRect(origin: .zero, size: image.size)
88-
scrollView.contentSize = image.size
89-
let fit = min(size.width / image.size.width, size.height / image.size.height)
90-
scrollView.maximumZoomScale = max(fit * 4, 1)
91-
scrollView.minimumZoomScale = fit
92-
scrollView.zoomScale = fit
93-
centerImage()
94-
}
95-
96-
override func viewDidDisappear(_ animated: Bool) {
97-
super.viewDidDisappear(animated)
98-
if isBeingDismissed || navigationController?.isBeingDismissed == true || navigationController?.presentingViewController == nil {
99-
onDismiss()
100-
}
101-
}
102-
103-
func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }
104-
func scrollViewDidZoom(_ scrollView: UIScrollView) { centerImage() }
105-
106-
private func centerImage() {
107-
let horizontal = max(0, (scrollView.bounds.width - scrollView.contentSize.width) / 2)
108-
let vertical = max(0, (scrollView.bounds.height - scrollView.contentSize.height) / 2)
109-
scrollView.contentInset = UIEdgeInsets(top: vertical, left: horizontal, bottom: vertical, right: horizontal)
110-
}
111-
112-
@objc private func zoom(_ recognizer: UITapGestureRecognizer) {
113-
if scrollView.zoomScale > scrollView.minimumZoomScale * 1.01 {
114-
scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true)
115-
} else {
116-
let scale = min(scrollView.minimumZoomScale * 3, scrollView.maximumZoomScale)
117-
let point = recognizer.location(in: imageView)
118-
let size = CGSize(width: scrollView.bounds.width / scale, height: scrollView.bounds.height / scale)
119-
let rect = CGRect(x: point.x - size.width / 2, y: point.y - size.height / 2, width: size.width, height: size.height)
120-
scrollView.zoom(to: rect, animated: true)
121-
}
122-
}
123-
124-
@objc private func toggleControls() {
125-
guard let navigationController else { return }
126-
navigationController.setNavigationBarHidden(!navigationController.isNavigationBarHidden, animated: true)
127-
}
128-
129-
@objc private func closeIfNotZoomed() {
130-
if scrollView.zoomScale <= scrollView.minimumZoomScale * 1.01 { onClose() }
131-
}
132-
133-
@objc private func share(_ sender: UIBarButtonItem) {
134-
let sheet = UIActivityViewController(activityItems: [url], applicationActivities: nil)
135-
sheet.popoverPresentationController?.barButtonItem = sender
136-
present(sheet, animated: true)
14+
override func viewDidAppear(_ animated: Bool) {
15+
super.viewDidAppear(animated)
16+
onAppear?()
13717
}
13818
}
13919

140-
/// Shares file preparation and lifecycle between the image viewer and Quick Look documents.
20+
/// Quick Look owns image and document controls, zooming, and source-view transitions.
14121
final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
14222
QLPreviewControllerDelegate, UIAdaptivePresentationControllerDelegate {
14323
let identifier: String
@@ -147,7 +27,6 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
14727
private let sourceIdentifier: String
14828
private let item = FilePreviewItem()
14929
private var loading: Task<Void, Never>?
150-
private var presented = false
15130
private var dismissRequested = false
15231
private var finished = false
15332

@@ -164,44 +43,18 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
16443
do {
16544
let file = try await Self.prepareFile(url: url, title: title)
16645
guard !finished, !Task.isCancelled else {
167-
try? FileManager.default.removeItem(at: file.url.deletingLastPathComponent())
46+
try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
16847
return
16948
}
170-
item.previewItemURL = file.url
49+
item.previewItemURL = file
17150
item.previewItemTitle = title
172-
let preview: UIViewController
173-
if let image = file.image {
174-
let viewer = NativeImagePreviewController(
175-
image: image, url: file.url, title: title,
176-
onClose: { [weak self] in self?.dismiss() }, onDismiss: { [weak self] in self?.finish() }
177-
)
178-
let navigation = UINavigationController(rootViewController: viewer)
179-
navigation.modalPresentationStyle = .fullScreen
180-
navigation.overrideUserInterfaceStyle = .dark
181-
preview = navigation
182-
if #available(iOS 18.0, *), !UIAccessibility.isReduceMotionEnabled,
183-
sources?.view(for: sourceIdentifier)?.window != nil {
184-
viewer.usesZoomTransition = true
185-
let options = UIViewController.Transition.ZoomOptions()
186-
options.alignmentRectProvider = { context in
187-
AVMakeRect(aspectRatio: image.size, insideRect: context.zoomedViewController.view.bounds)
188-
}
189-
preview.preferredTransition = .zoom(options: options) { [weak self] _ in
190-
guard let self, let source = sources?.view(for: sourceIdentifier), source.window != nil else { return nil }
191-
return source
192-
}
193-
}
194-
navigation.view.backgroundColor = .black
195-
} else {
196-
let quickLook = QLPreviewController()
197-
quickLook.delegate = self
198-
quickLook.dataSource = self
199-
preview = quickLook
200-
}
51+
let preview = FilePreviewController()
52+
preview.delegate = self
53+
preview.dataSource = self
54+
preview.onAppear = { [weak self] in self?.resumePendingDismissal() }
20155
controller = preview
20256
presenter.present(preview, animated: !UIAccessibility.isReduceMotionEnabled) { [self] in
203-
presented = true
204-
if dismissRequested { dismiss() }
57+
resumePendingDismissal()
20558
}
20659
preview.presentationController?.delegate = self
20760
} catch {
@@ -214,11 +67,18 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
21467
dismissRequested = true
21568
loading?.cancel()
21669
guard !finished else { return }
217-
guard presented else {
218-
if controller?.presentingViewController == nil { finish() }
219-
return
70+
guard let controller else { finish(); return }
71+
// Drain Close from viewDidAppear after opening or cancelling an interactive dismissal.
72+
// Starting a second modal transition while UIKit is settling the first can strand it.
73+
guard !controller.isBeingPresented, !controller.isBeingDismissed else { return }
74+
controller.dismiss(animated: !UIAccessibility.isReduceMotionEnabled) { [self] in finish() }
75+
}
76+
77+
private func resumePendingDismissal() {
78+
// Appearance callbacks run before UIKit has cleared the current transition.
79+
DispatchQueue.main.async { [weak self] in
80+
if self?.dismissRequested == true { self?.dismiss() }
22081
}
221-
controller?.dismiss(animated: !UIAccessibility.isReduceMotionEnabled) { [self] in finish() }
22282
}
22383

22484
func numberOfPreviewItems(in controller: QLPreviewController) -> Int { item.previewItemURL == nil ? 0 : 1 }
@@ -227,6 +87,18 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
22787
item
22888
}
22989

90+
func previewController(_ controller: QLPreviewController, transitionViewFor item: QLPreviewItem) -> UIView? {
91+
guard !UIAccessibility.isReduceMotionEnabled else { return nil }
92+
return sources?.view(for: sourceIdentifier)
93+
}
94+
95+
func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem,
96+
inSourceView view: AutoreleasingUnsafeMutablePointer<UIView?>) -> CGRect {
97+
guard !UIAccessibility.isReduceMotionEnabled, let source = sources?.view(for: sourceIdentifier) else { return .zero }
98+
view.pointee = source
99+
return source.bounds
100+
}
101+
230102
func previewControllerDidDismiss(_ controller: QLPreviewController) { finish() }
231103

232104
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { finish() }
@@ -240,11 +112,11 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
240112
try? FileManager.default.removeItem(at: file.deletingLastPathComponent())
241113
}
242114
item.previewItemURL = nil
243-
completion(error)
115+
DispatchQueue.main.async { [completion] in completion(error) }
244116
}
245117

246118
/// Copy original bytes so preview and sharing do not mutate a draft or workspace file.
247-
nonisolated private static func prepareFile(url: URL, title: String) async throws -> PreparedPreviewFile {
119+
nonisolated private static func prepareFile(url: URL, title: String) async throws -> URL {
248120
try Task.checkCancellation()
249121
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("t3-preview-\(UUID().uuidString)")
250122
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
@@ -266,15 +138,10 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
266138
}
267139
try Task.checkCancellation()
268140
let type: UTType
269-
var previewImage: UIImage?
270141
if let image = CGImageSourceCreateWithURL(download as CFURL, nil),
271142
CGImageSourceGetCount(image) > 0, let imageType = CGImageSourceGetType(image),
272143
let detectedType = UTType(imageType as String) {
273144
type = detectedType
274-
// Animated images stay in Quick Look; static images are decoded before the zoom starts.
275-
if CGImageSourceGetCount(image) == 1 {
276-
previewImage = UIImage(contentsOfFile: download.path)?.preparingForDisplay()
277-
}
278145
} else if CGPDFDocument(download as CFURL) != nil {
279146
type = .pdf
280147
} else {
@@ -289,7 +156,7 @@ final class T3NativeFilePresentation: NSObject, QLPreviewControllerDataSource,
289156
while name.utf8.count > 200 { name.removeLast() }
290157
let file = directory.appendingPathComponent("\(name.isEmpty ? "Preview" : name).\(fileExtension)")
291158
try FileManager.default.moveItem(at: download, to: file)
292-
return PreparedPreviewFile(url: file, image: previewImage)
159+
return file
293160
} catch {
294161
try? FileManager.default.removeItem(at: directory)
295162
throw error

‎docs/internals/mobile-navigation.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -68,12 +68,13 @@ guarded `enterFullScreenAnimated:completionHandler:` selector as Expo Video;
6868
if that selector is unavailable, the player also falls back to a standard modal.
6969

7070
`FilePreviewModal` resolves image and PDF sources from a URI, a signed environment asset,
71-
or a retained composer file. On iOS, static images use `UIImageView` inside `UIScrollView`,
72-
with standard navigation-bar Close and Share items. The image is decoded before presentation
73-
so UIKit's iOS 18+ `preferredTransition` can zoom from the thumbnail into visible content.
74-
Quick Look delays image rendering until after presentation, leaving a blank zoom destination.
75-
It remains the viewer for PDFs and animated images, providing document search and sharing.
76-
Missing sources, older systems, and Reduce Motion use a standard presentation.
71+
or a retained composer file. On iOS, Quick Look owns image and document layout, controls,
72+
zooming, sharing, and interactive dismissal. Its delegate supplies the registered thumbnail
73+
and its bounds for Quick Look's source-view zoom. Do not layer `preferredTransition` or
74+
another image scroll view over that presentation: Quick Look coordinates its image gestures
75+
with the return to the thumbnail. Missing sources use the standard transition, and Reduce
76+
Motion disables animation. A pending programmatic Close waits until the current presentation
77+
or cancelled dismissal has settled before starting another transition.
7778

7879
The shared native presenter copies original bytes into its own temporary directory and
7980
removes that copy after dismissal. Network downloads write to disk, and sharing never edits

0 commit comments

Comments
 (0)