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
import PhotosUI
import SwiftUI
struct ProfileEditorView: View {
@Environment(AppModel.self) private var model
@Environment(\.dismiss) private var dismiss
@ScaledMetric(relativeTo: .body) private var bioEditorHeight: CGFloat = 144
@State private var original: EditableProfile?
@State private var loadError: String?
@State private var loadAttempt = 0
@State private var draft = ProfileEdit(displayName: "", bio: "", links: [])
@State private var showsPhotoPicker = false
@State private var photoSelection: PhotosPickerItem?
@State private var photoToCrop: UIImage?
@State private var isLoadingPhoto = false
@State private var isSaving = false
@State private var errorMessage: String?
@State private var confirmsDiscard = false
@State private var linkEditMode: EditMode = .inactive
private var hasChanges: Bool { original.map { draft != $0.draft } ?? false }
private var validationError: String? { original.flatMap { draft.validationError(comparedTo: $0.draft) } }
var body: some View {
NavigationStack {
Group {
if let original {
editor(original)
} else if let loadError {
ContentUnavailableView {
Label("Could not load profile", systemImage: "person.crop.circle.badge.exclamationmark")
} description: {
Text(loadError)
} actions: {
Button("Try Again") {
self.loadError = nil
loadAttempt += 1
}
}
} else {
ProgressView("Loading profile…")
}
}
.appNavigationTitle("Edit Profile")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel", role: .cancel) {
if hasChanges { confirmsDiscard = true } else { dismiss() }
}
.disabled(isSaving)
}
ToolbarItem(placement: .confirmationAction) {
if isSaving {
ProgressView().accessibilityLabel("Saving profile")
} else {
Button("Save") { save() }
.disabled(!hasChanges || isLoadingPhoto || validationError != nil || linkEditMode.isEditing)
}
}
}
.confirmationDialog("Discard profile changes?", isPresented: $confirmsDiscard, titleVisibility: .visible) {
Button("Discard Changes", role: .destructive) { dismiss() }
Button("Keep Editing", role: .cancel) {}
}
.alert("Profile Editor", isPresented: Binding(
get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })
) {
Button("OK", role: .cancel) { errorMessage = nil }
} message: {
Text(errorMessage ?? "")
}
.navigationDestination(item: $photoToCrop) { image in
AvatarCropView(image: image) { data in draft.avatar = .replace(data) }
}
}
.photosPicker(isPresented: $showsPhotoPicker, selection: $photoSelection, matching: .images)
.interactiveDismissDisabled(hasChanges || isSaving || isLoadingPhoto)
.task(id: loadAttempt) { await load() }
.task(id: photoSelection) { await loadPhoto(photoSelection) }
}
private func editor(_ original: EditableProfile) -> some View {
Form {
Section {
HStack(spacing: 16) {
avatarMenu(original)
TextField("Display name", text: $draft.displayName)
.textContentType(.nickname)
.accessibilityLabel("Display name")
.accessibilityIdentifier("profileEditDisplayName")
.padding(.horizontal, 16)
.frame(minHeight: 48)
.background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 20))
}
.padding(.vertical, 4)
.listRowBackground(Color.clear)
}
.disabled(linkEditMode.isEditing)
Section("Bio") {
TextEditor(text: $draft.bio)
.frame(height: bioEditorHeight)
.scrollContentBackground(.hidden)
.scrollBounceBehavior(.basedOnSize, axes: .vertical)
.scrollIndicators(.visible, axes: .vertical)
.scrollIndicatorsFlash(onAppear: true)
.accessibilityLabel("Bio")
.accessibilityIdentifier("profileEditBio")
}
.disabled(linkEditMode.isEditing)
Section {
ForEach(draft.links) { link in
NavigationLink {
ProfileLinkEditorView(link: link) { updated in
if let index = draft.links.firstIndex(where: { $0.id == updated.id }) {
draft.links[index] = updated
}
}
} label: {
VStack(alignment: .leading, spacing: 4) {
Text(link.label)
if !link.address.isEmpty, link.address != link.label {
Text(link.address).font(.footnote).foregroundStyle(.secondary).lineLimit(1)
}
}
}
}
.onMove { draft.links.move(fromOffsets: $0, toOffset: $1) }
.onDelete { draft.links.remove(atOffsets: $0) }
if draft.links.count < ProfileEdit.linkLimit && !linkEditMode.isEditing {
NavigationLink {
ProfileLinkEditorView(link: nil) { draft.links.append($0) }
} label: {
Label("Add Link", systemImage: "plus")
}
}
} header: {
HStack {
Text("Links")
Spacer()
if !draft.links.isEmpty || linkEditMode.isEditing {
EditButton()
.textCase(nil)
.accessibilityIdentifier("profileEditReorderLinks")
}
}
}
if let validationError {
Section { Text(validationError).foregroundStyle(.red) }
}
}
.environment(\.editMode, $linkEditMode)
.scrollDismissesKeyboard(.interactively)
.accessibilityIdentifier("profileEditForm")
.disabled(isSaving)
}
private func avatarMenu(_ original: EditableProfile) -> some View {
Menu {
Button("Choose Photo", systemImage: "photo") { showsPhotoPicker = true }
if canRemoveAvatar(original) {
Button("Remove Photo", systemImage: "trash", role: .destructive) {
draft.avatar = original.avatarURL == nil ? .keep : .remove
}
}
} label: {
avatarPreview(original)
.contentShape(Circle())
.overlay(alignment: .bottomTrailing) {
Image(systemName: "pencil")
.font(.caption2.weight(.semibold))
.foregroundStyle(.primary)
.frame(width: 22, height: 22)
.background(.regularMaterial, in: Circle())
.allowsHitTesting(false)
}
.overlay {
if isLoadingPhoto {
ProgressView()
.padding(8)
.background(.regularMaterial, in: Circle())
}
}
}
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.disabled(isLoadingPhoto)
.accessibilityLabel(isLoadingPhoto ? "Loading photo" : "Edit avatar")
.accessibilityIdentifier("profileEditAvatar")
}
@ViewBuilder
private func avatarPreview(_ original: EditableProfile) -> some View {
if case .replace(let data) = draft.avatar, let image = UIImage(data: data) {
Image(uiImage: image)
.resizable()
.scaledToFill()
.frame(width: 56, height: 56)
.clipShape(Circle())
.accessibilityHidden(true)
} else {
AccountAvatar(
account: Account(handle: "", displayName: "", avatarURL: draft.avatar == .keep ? original.avatarURL : nil),
size: 56, showsWhenHidden: true)
}
}
private func canRemoveAvatar(_ original: EditableProfile) -> Bool {
if case .replace = draft.avatar { return true }
return original.avatarURL != nil && draft.avatar == .keep
}
private func load() async {
do {
let profile = try await model.loadProfileEdit()
try Task.checkCancellation()
draft = profile.draft
original = profile
} catch {
if !Task.isCancelled { loadError = NetworkFailure.message(for: error) }
}
}
private func loadPhoto(_ selection: PhotosPickerItem?) async {
guard let selection else { return }
isLoadingPhoto = true
defer {
if photoSelection == selection {
isLoadingPhoto = false
photoSelection = nil
}
}
do {
guard let data = try await selection.loadTransferable(type: Data.self) else {
throw ServiceError.invalidImage
}
let image = try await Task.detached(priority: .userInitiated) {
guard let image = AvatarStore.decode(data, maximumPixelSize: 2048) else {
throw ServiceError.invalidImage
}
return image
}.value
guard !Task.isCancelled, photoSelection == selection else { return }
photoToCrop = image
} catch {
if !Task.isCancelled, photoSelection == selection {
errorMessage = "Could not load the photo. Choose another photo or try again."
}
}
}
private func save() {
guard let original, !isSaving else { return }
isSaving = true
let changes = draft
Task {
defer { isSaving = false }
do {
try await model.saveProfileEdit(changes, original: original)
dismiss()
} catch {
errorMessage = NetworkFailure.message(for: error)
}
}
}
}