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
import AVFoundation
import FoundationModels
import PhotosUI
import SwiftUI
import UIKit
import UniformTypeIdentifiers
extension ComposeView {
var canPublish: Bool {
(!text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !attachments.isEmpty || video != nil)
&& text.count <= characterLimit
}
var canGenerateAltText: Bool {
#if DEBUG
let arguments = ProcessInfo.processInfo.arguments
if let altTextTestMode { return altTextTestMode != "unavailable" }
if arguments.contains("-ui-testing") { return !arguments.contains("-ui-testing-alt-unavailable") }
#endif
return SystemLanguageModel.default.isAvailable
}
var attachmentStrip: some View {
ScrollView(.horizontal) {
HStack(spacing: 12) {
if video != nil {
ZStack(alignment: .topTrailing) {
Label("Video", systemImage: "video.fill")
.frame(width: 132, height: 132)
.background(
Color(uiColor: .secondarySystemBackground), in: RoundedRectangle(cornerRadius: 12))
Button {
video = nil
} label: {
Image(systemName: "xmark.circle.fill")
.font(.title2)
.symbolRenderingMode(.palette)
.foregroundStyle(.white, .black.opacity(0.65))
}
.padding(6)
.accessibilityLabel("Remove video")
}
.accessibilityIdentifier("videoAttachment")
}
ForEach(Array(attachments.enumerated()), id: \.element.id) { index, attachment in
VStack(alignment: .leading, spacing: 6) {
Button {
altTextReview = AltTextReview(
id: attachment.id, originalText: attachment.altText, draft: attachment.altText)
} label: {
AttachmentThumbnail(attachment: attachment, contentMode: .fill)
.frame(width: 132, height: 132)
.clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
}
.buttonStyle(.plain)
.accessibilityLabel("Edit alt text for image \(index + 1)")
.accessibilityIdentifier("editAltText-\(index)")
.overlay(alignment: .topTrailing) {
Button {
attachments.remove(at: index)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.title2)
.symbolRenderingMode(.palette)
.foregroundStyle(.white, .black.opacity(0.65))
}
.padding(6)
.accessibilityLabel("Remove image \(index + 1)")
}
}
}
}
.padding(.horizontal, 16)
.padding(.vertical, 12)
}
.fixedSize(horizontal: false, vertical: true)
.accessibilityIdentifier("imageAttachments")
.disabled(isComposerBusy)
}
func contextRow(title: String, postID: String, isQuote: Bool) -> some View {
let post = model.post(id: postID).flatMap { model.canShowTimelineContent($0) ? $0 : nil }
return ContextCard(
kind: isQuote ? .quote : .reply, title: title, showsHeader: false, openPost: {},
content: {
HStack(spacing: 8) {
Label(
post.map { "\(title) \(displayPreferences.name($0.author))" } ?? title,
systemImage: isQuote ? "quote.bubble" : "arrow.turn.down.right"
)
.frame(maxWidth: .infinity, alignment: .leading)
if let post {
if let date = post.createdAt {
PostTimestamp(date: date)
.fixedSize()
}
AuthorAvatar(author: post.author, size: 24)
}
}
.appFont(.subheadline, weight: .medium)
.foregroundStyle(isQuote ? AppPalette.quote : AppPalette.reply)
Text(
PostTextFacets.render(
post?.text ?? "Post preview unavailable",
facets: post?.facets ?? [],
linksEnabled: false
)
)
.appFont(.subheadline)
.fixedSize(horizontal: false, vertical: true)
.accessibilityIdentifier("composeContextText-\(postID)")
}
)
.padding(.horizontal, 16)
.accessibilityElement(children: .contain)
}
func altTextBinding(for id: UUID) -> Binding<String> {
Binding(
get: { attachments.first(where: { $0.id == id })?.altText ?? "" },
set: { newValue in
guard let index = attachments.firstIndex(where: { $0.id == id }) else { return }
attachments[index] = ImageAttachment(
id: id, data: attachments[index].data, altText: newValue, mimeType: attachments[index].mimeType)
}
)
}
}
struct AttachmentThumbnail: View {
let attachment: ImageAttachment
var contentMode: ContentMode = .fit
@State private var image: UIImage?
var body: some View {
Group {
if let image {
Image(uiImage: image).resizable().aspectRatio(contentMode: contentMode)
} else {
Color(uiColor: .systemGray5)
}
}
.task(id: attachment.id) {
image = nil
let decoded = await ImageDecodeQueue.shared.decode(attachment.data)
guard !Task.isCancelled else { return }
image = decoded
}
}
}
extension ComposeView {
func loadMedia(_ items: [PhotosPickerItem]) async {
isLoadingImages = true
defer {
isLoadingImages = false
selectedItems = []
}
let movieItems = items.filter { $0.supportedContentTypes.contains { $0.conforms(to: .movie) } }
guard movieItems.isEmpty || (items.count == 1 && attachments.isEmpty && video == nil) else {
mediaError = "Choose one video or up to ten photos."
return
}
if let item = movieItems.first {
guard let data = try? await item.loadTransferable(type: Data.self) else {
mediaError = "The video could not be read. Try again."
return
}
video = await prepareVideo(data)
} else {
for item in items.prefix(max(0, imageLimit - attachments.count)) {
guard let data = try? await item.loadTransferable(type: Data.self), addImage(data) else {
mediaError = "A photo could not be read. Try again."
continue
}
}
}
}
func loadPastedMedia(_ providers: [NSItemProvider]) async {
guard !isLoadingImages, !model.isPublishing else { return }
isLoadingImages = true
defer { isLoadingImages = false }
let movies = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.movie.identifier) }
guard movies.isEmpty || (providers.count == 1 && attachments.isEmpty && video == nil),
video == nil, attachments.count + providers.count <= imageLimit
else {
mediaError = "Choose one video or up to ten photos."
return
}
for provider in providers {
let isMovie = provider.hasItemConformingToTypeIdentifier(UTType.movie.identifier)
let type = isMovie ? UTType.movie.identifier : UTType.image.identifier
do {
let data: Data = try await withCheckedThrowingContinuation { continuation in
provider.loadDataRepresentation(forTypeIdentifier: type) { data, error in
if let data {
continuation.resume(returning: data)
} else {
continuation.resume(throwing: error ?? CocoaError(.fileReadCorruptFile))
}
}
}
if isMovie {
video = await prepareVideo(data)
} else if !addImage(data) {
mediaError = "A photo could not be read. Try again."
}
} catch {
mediaError = "The media could not be read. Try again."
}
}
}
func acknowledgeSharedImport() async {
guard let sharedImport else { return }
do {
try await SharedImportStore.acknowledge(sharedImport)
} catch {
mediaError = "The shared items could not be cleared. They will appear again when you open Old Fella."
}
}
func addSharedMedia(_ items: [SharedImport.Attachment]) async {
guard !items.isEmpty else { return }
isLoadingImages = true
defer { isLoadingImages = false }
for item in items {
switch item.kind {
case .image:
if !addImage(item.data) { mediaError = "A photo could not be read. Try again." }
case .video:
video = await prepareVideo(item.data)
}
}
}
func prepareVideo(_ data: Data) async -> VideoAttachment? {
do {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: directory) }
let input = directory.appendingPathComponent("input.mov")
let output = directory.appendingPathComponent("output.mp4")
try await Task.detached(priority: .userInitiated) { try data.write(to: input, options: .atomic) }.value
let asset = AVURLAsset(url: input)
guard let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality)
else {
throw CocoaError(.fileReadCorruptFile)
}
try await exporter.export(to: output, as: .mp4)
let result = try await Task.detached(priority: .userInitiated) {
try Data(contentsOf: output, options: .mappedIfSafe)
}.value
return VideoAttachment(data: result, mimeType: "video/mp4")
} catch {
mediaError = "The video could not be prepared. Try another video."
return nil
}
}
@discardableResult
func addImage(_ data: Data) -> Bool {
guard let image = UIImage(data: data), let jpeg = image.jpegData(compressionQuality: 0.88) else { return false }
attachments.append(ImageAttachment(data: jpeg, mimeType: "image/jpeg"))
return true
}
func publish() async {
guard !isComposerBusy, !draftIsUncertain else { return }
if let savedDraftID {
isWorkingWithDrafts = true
var pending = currentDraft
pending.publishResultUnknown = true
do {
_ = try await model.saveSavedDraft(pending, id: savedDraftID)
} catch {
isWorkingWithDrafts = false
draftError = NetworkFailure.message(for: error)
return
}
isWorkingWithDrafts = false
}
let succeeded = await model.publish(
text: text, replyTo: composerReplyTo, quotePostID: composerQuotePostID,
images: attachments, video: video, draftID: compositionID)
if succeeded {
if let savedDraftID {
isWorkingWithDrafts = true
do {
try await model.deleteSavedDraft(id: savedDraftID)
} catch {
clearComposer()
isWorkingWithDrafts = false
draftError = "The post was sent, but its saved draft could not be removed. "
+ NetworkFailure.message(for: error)
return
}
isWorkingWithDrafts = false
}
clearComposer()
if let onSharedPost { onSharedPost() } else { dismiss() }
} else if let savedDraftID, !draftIsUncertain {
isWorkingWithDrafts = true
defer { isWorkingWithDrafts = false }
do {
_ = try await model.saveSavedDraft(currentDraft, id: savedDraftID)
} catch {
draftError = NetworkFailure.message(for: error)
}
}
}
}