1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import ImageIO
import Photos
import SwiftUI
import UIKit
import UniformTypeIdentifiers
struct ImageViewerRequest: Identifiable {
let id = UUID()
let urls: [URL]
let descriptions: [URL: String]
var localImages: [URL: Data] = [:]
var revealedGIFURLs: Set<URL> = []
let index: Int
let requiresGIFReveal: Bool
}
struct ImageViewer: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var selection: Int
@State private var dragOffset = CGSize.zero
@State private var isDismissing = false
let request: ImageViewerRequest
private var urls: [URL] { request.urls }
init(request: ImageViewerRequest) {
self.request = request
_selection = State(initialValue: request.index)
}
var body: some View {
GeometryReader { geometry in
let progress = min(
max(
abs(dragOffset.width) / max(geometry.size.width, 1),
abs(dragOffset.height) / max(geometry.size.height, 1)
), 1)
TabView(selection: $selection) {
ForEach(urls.indices, id: \.self) { index in
ImageViewerPage(
url: urls[index],
localData: request.localImages[urls[index]],
isGIFRevealed: request.revealedGIFURLs.contains(urls[index]),
requiresGIFReveal: request.requiresGIFReveal,
accessibilityLabel: "Image \(index + 1) of \(urls.count)",
description: request.descriptions[urls[index]],
dragOffset: index == selection ? dragOffset : .zero,
dragProgress: index == selection ? progress : 0,
canPageLeft: index < urls.count - 1,
canPageRight: index > 0,
onDrag: { dragOffset = $0 },
onDragEnd: { shouldDismiss in
endDrag(shouldDismiss: shouldDismiss, size: geometry.size)
}
)
.tag(index)
}
}
.tabViewStyle(.page(indexDisplayMode: urls.count > 1 ? .automatic : .never))
.background(Color.black.opacity(1 - progress).ignoresSafeArea())
.overlay(alignment: .topTrailing) {
Button(
action: { dismiss() },
label: {
Image(systemName: "xmark")
.font(.headline.weight(.semibold))
.foregroundStyle(.white)
.frame(width: 44, height: 44)
.background(.ultraThinMaterial, in: Circle())
}
)
.accessibilityLabel("Close image viewer")
.accessibilityIdentifier("imageViewerClose")
.padding(.top, 8)
.padding(.trailing, 16)
.opacity(1 - progress)
}
.allowsHitTesting(!isDismissing)
}
.presentationBackground(.clear)
.environment(\.colorScheme, .dark)
}
private func endDrag(shouldDismiss: Bool, size: CGSize) {
guard shouldDismiss else {
withAnimation(reduceMotion ? nil : .spring(response: 0.35, dampingFraction: 0.8)) {
dragOffset = .zero
}
return
}
guard !reduceMotion else {
dismiss()
return
}
isDismissing = true
withAnimation(.easeIn(duration: 0.2)) {
if abs(dragOffset.width) > abs(dragOffset.height) {
let direction: CGFloat = dragOffset.width < 0 ? -1 : 1
dragOffset.width = direction * max(size.width * 1.2, abs(dragOffset.width))
} else {
let direction: CGFloat = dragOffset.height < 0 ? -1 : 1
dragOffset.height = direction * max(size.height * 1.2, abs(dragOffset.height))
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) { dismiss() }
}
}
}
#if DEBUG
#Preview("Image viewer") {
PreviewHost { _ in
ImageViewer(
request: ImageViewerRequest(
urls: [MediaPreviewContent.imageURL],
descriptions: [MediaPreviewContent.imageURL: "A yellow sun over a teal landscape"],
localImages: [MediaPreviewContent.imageURL: MediaPreviewContent.attachment.data],
index: 0,
requiresGIFReveal: false
))
}
}
#Preview("Image viewer: local file unavailable") {
PreviewHost { _ in
ImageViewer(
request: ImageViewerRequest(
urls: [MediaPreviewContent.imageURL], descriptions: [:],
index: 0, requiresGIFReveal: false
))
}
}
#endif
private struct ImageViewerPage: View {
private struct LoadedImage {
let image: UIImage
let data: Data
}
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var loadedImage: LoadedImage?
@State private var isLoading = false
@State private var loadFailed = false
@State private var showsDescription = false
@State private var hiddenGIF: Data?
@State private var isSaving = false
@State private var showsSaved = false
@State private var saveError: String?
@AppStorage("showGIFsInline") private var showGIFsInline = true
let url: URL
let localData: Data?
let isGIFRevealed: Bool
let requiresGIFReveal: Bool
let accessibilityLabel: String
let description: String?
let dragOffset: CGSize
let dragProgress: CGFloat
let canPageLeft: Bool
let canPageRight: Bool
let onDrag: (CGSize) -> Void
let onDragEnd: (Bool) -> Void
var body: some View {
ZStack {
if let hiddenGIF {
Button("Show GIF", systemImage: "play.rectangle") {
Task { await displayImage(hiddenGIF) }
}
.accessibilityIdentifier("imageViewerShowGIF")
} else if let loadedImage {
ZoomableImageView(
image: loadedImage.image,
accessibilityLabel: accessibilityLabel,
accessibilityIdentifier: "imageViewerImage",
canPageLeft: canPageLeft,
canPageRight: canPageRight,
onDrag: onDrag,
onDragEnd: onDragEnd,
onSave: isSaving ? nil : { Task { await saveImage(loadedImage.data) } }
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.scaleEffect(reduceMotion ? 1 : 1 - dragProgress * 0.18)
.rotationEffect(.degrees(reduceMotion ? 0 : Double(max(-1, min(1, dragOffset.width / 200)) * 4)))
.offset(dragOffset)
.transition(.opacity)
} else if loadFailed {
VStack(spacing: 12) {
Label("Image could not be loaded", systemImage: "photo")
.foregroundStyle(.white)
Button("Try Again") { Task { await loadImage() } }
.buttonStyle(.borderedProminent)
}
.accessibilityIdentifier("imageViewerFailure")
} else {
ProgressView()
.tint(.white)
.accessibilityLabel("Loading image")
.accessibilityIdentifier("imageViewerLoading")
.transition(.opacity)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.animation(reduceMotion ? nil : .easeInOut(duration: 0.25), value: loadedImage != nil)
.overlay(alignment: .bottom) {
if showsDescription {
ScrollView {
VStack(alignment: .leading, spacing: 8) {
Text("Image description").appFont(.headline)
Text(description ?? "No image description provided.")
.textSelection(.enabled)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
}
.frame(maxHeight: 240)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16))
.padding(.horizontal, 16)
.padding(.bottom, 100)
.accessibilityIdentifier("imageDescription")
.opacity(1 - dragProgress)
}
}
.overlay(alignment: .bottomLeading) {
if let description, !description.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
Button(showsDescription ? "Hide description" : "Show description") {
showsDescription.toggle()
}
.appFont(.subheadline, weight: .medium)
.padding(10)
.background(.ultraThinMaterial, in: Capsule())
.padding(.leading, 16)
.padding(.bottom, 48)
.accessibilityIdentifier("imageDescriptionButton")
.opacity(1 - dragProgress)
}
}
.task {
if loadedImage == nil { await loadImage() }
}
.overlay(alignment: .top) {
if showsSaved {
Label("Saved to Photos", systemImage: "checkmark")
.appFont(.subheadline, weight: .medium)
.padding(.vertical, 10)
.padding(.horizontal, 14)
.background(.regularMaterial, in: Capsule())
.padding(.top, 8)
.allowsHitTesting(false)
}
}
.task(id: showsSaved) {
if showsSaved, (try? await Task.sleep(for: .seconds(3))) != nil { showsSaved = false }
}
.alert("Could Not Save Image", isPresented: Binding(
get: { saveError != nil }, set: { if !$0 { saveError = nil } })
) {
Button("OK", role: .cancel) { saveError = nil }
} message: {
Text(saveError ?? "")
}
}
@MainActor
private func loadImage() async {
guard !isLoading else { return }
isLoading = true
loadFailed = false
defer { isLoading = false }
#if DEBUG
let arguments = ProcessInfo.processInfo.arguments
if arguments.contains("-ui-testing"), arguments.contains("-ui-testing-image-load-delay") {
do {
try await Task.sleep(for: .seconds(3))
} catch {
return
}
}
#endif
let data: Data
if let localData {
data = localData
} else if url.scheme?.lowercased() == "data",
ProcessInfo.processInfo.arguments.contains("-ui-testing") {
let parts = url.absoluteString.split(separator: ",", maxSplits: 1)
guard parts.count == 2, let bytes = Data(base64Encoded: String(parts[1])) else {
loadFailed = true
return
}
data = bytes
} else {
do {
let (bytes, response) = try await GIFDownload.load(url)
guard let response = response as? HTTPURLResponse,
(200..<300).contains(response.statusCode)
else {
loadFailed = true
return
}
data = bytes
} catch {
loadFailed = true
return
}
}
guard !Task.isCancelled else { return }
if !isGIFRevealed && RemoteImageDecoder.isGIF(data) && (requiresGIFReveal || !showGIFsInline) {
hiddenGIF = data
return
}
await displayImage(data)
}
@MainActor
private func displayImage(_ data: Data) async {
let image = await ImageDecodeQueue.shared.decode(data, resolution: .fullSize)
guard !Task.isCancelled else { return }
loadedImage = image.map { LoadedImage(image: $0, data: data) }
hiddenGIF = nil
loadFailed = image == nil
}
@MainActor
private func saveImage(_ data: Data) async {
guard !isSaving else { return }
isSaving = true
showsSaved = false
defer { isSaving = false }
let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly)
guard status == .authorized || status == .limited else {
saveError = "Allow Old Fella to add photos in Settings, then try again."
return
}
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
let format = CGImageSourceGetType(source), let type = UTType(format as String)
else {
saveError = "Photos could not read this image."
return
}
do {
try await PHPhotoLibrary.shared().performChanges {
let options = PHAssetResourceCreationOptions()
options.contentType = type
PHAssetCreationRequest.forAsset().addResource(with: .photo, data: data, options: options)
}
showsSaved = true
UIAccessibility.post(notification: .announcement, argument: "Saved to Photos")
} catch {
saveError = "Photos could not save this image. Try again."
}
}
}