Repository navigation
Expand file tree
/
Copy pathEditProfileView.swift
More file actions
231 lines (207 loc) · 8.26 KB
/
Copy pathEditProfileView.swift
File metadata and controls
231 lines (207 loc) · 8.26 KB
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
import PhotosUI
import SwiftUI
struct EditProfileView: View {
@EnvironmentObject var app: AppViewModel
@EnvironmentObject var navigation: NavigationViewModel
@EnvironmentObject var pubkyProfile: PubkyProfileManager
@EnvironmentObject var contactsManager: ContactsManager
@State private var username: String = ""
@State private var bio: String = ""
@State private var links: [ProfileLinkInput] = []
@State private var tags: [String] = []
@State private var isSaving = false
@State private var isDeleting = false
@State private var showDeleteConfirmation = false
@State private var showDeleteFailureOptions = false
@State private var selectedPhotoItem: PhotosPickerItem?
@State private var avatarImage: UIImage?
var body: some View {
ZStack {
ProfileEditFormView(
navigationTitle: t("profile__edit_nav_title"),
name: $username,
bio: $bio,
links: $links,
tags: $tags,
publicKey: pubkyProfile.publicKey ?? "...",
publicKeyLabel: t("profile__create_pubky_display_label"),
bioPlaceholder: t("profile__create_bio_placeholder"),
isSaving: isSaving,
footerNote: t("profile__edit_public_note"),
deleteLabel: t("profile__delete_label"),
deleteActionStyle: .buttonWithIcon,
onSave: { await saveProfile() },
onCancel: { navigation.navigateBack() },
onDelete: { showDeleteConfirmation = true }
) {
avatarPicker
}
if isDeleting {
Color.customBlack.opacity(0.72)
.ignoresSafeArea()
ProgressView()
.progressViewStyle(CircularProgressViewStyle(tint: .white))
.scaleEffect(1.2)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.bottomSafeAreaPadding()
.background(Color.customBlack)
.navigationBarHidden(true)
.disabled(isDeleting)
.task {
loadProfileData()
}
.alert(t("profile__delete_title"), isPresented: $showDeleteConfirmation) {
Button(t("profile__delete_confirm"), role: .destructive) {
Task { await deleteProfile() }
}
Button(t("common__dialog_cancel"), role: .cancel) {}
} message: {
Text(t("profile__delete_description"))
}
.alert(t("profile__delete_error_title"), isPresented: $showDeleteFailureOptions) {
Button(t("common__retry")) {
Task { await deleteProfile() }
}
Button(t("profile__sign_out"), role: .destructive) {
Task { await disconnectAfterFailedDelete() }
}
Button(t("common__dialog_cancel"), role: .cancel) {}
} message: {
Text(t("profile__delete_error_description"))
}
}
// MARK: - Avatar Picker
private var avatarPicker: some View {
PhotosPicker(selection: $selectedPhotoItem, matching: .images) {
avatarContent
}
.accessibilityIdentifier("EditProfileAvatar")
.accessibilityLabel(t("profile__create_avatar_label"))
.onChange(of: selectedPhotoItem) { _, newItem in
Task { await loadSelectedImage(newItem) }
}
.frame(maxWidth: .infinity)
}
@ViewBuilder
private var avatarContent: some View {
if let avatarImage {
Image(uiImage: avatarImage)
.resizable()
.scaledToFill()
.frame(width: 96, height: 96)
.clipShape(Circle())
} else if let imageUrl = pubkyProfile.profile?.imageUrl {
PubkyImage(uri: imageUrl, size: 96)
} else {
Circle()
.fill(Color.gray6)
.frame(width: 96, height: 96)
.overlay {
Image("picture")
.resizable()
.scaledToFit()
.foregroundColor(.white32)
.frame(width: 32, height: 32)
}
}
}
// MARK: - Image Selection
private func loadSelectedImage(_ item: PhotosPickerItem?) async {
guard let item else { return }
do {
if let data = try await item.loadTransferable(type: Data.self),
let uiImage = UIImage(data: data)
{
avatarImage = uiImage
}
} catch {
Logger.error("Failed to load selected image: \(error)", context: "EditProfileView")
}
selectedPhotoItem = nil
}
// MARK: - Data Loading
private func loadProfileData() {
guard let profile = pubkyProfile.profile else { return }
username = profile.name
bio = profile.bio
links = profile.links.map { ProfileLinkInput(label: $0.label, url: $0.url) }
tags = profile.tags
}
// MARK: - Delete Profile
private func deleteProfile() async {
guard !isDeleting else { return }
isDeleting = true
await pubkyProfile.performProfileDeletion {
await deleteProfileWithSessionRetry()
}
isDeleting = false
}
private func deleteProfileWithSessionRetry() async {
do {
try await performDeleteProfile()
} catch {
if await pubkyProfile.refreshSessionIfPossible(after: error) {
do {
try await performDeleteProfile()
return
} catch {
Logger.error("Failed to delete profile after session refresh: \(error)", context: "EditProfileView")
}
} else {
Logger.error("Failed to delete profile: \(error)", context: "EditProfileView")
}
showDeleteFailureOptions = true
}
}
private func performDeleteProfile() async throws {
await PubkyProfileManager.removePrivatePaykitEndpointsBestEffort(context: "EditProfileView.deleteProfile", deferAppSync: true)
await contactsManager.deleteAllContactsBestEffort()
try await pubkyProfile.deleteProfile(cleanPrivatePaykitEndpoints: false)
navigation.path = [app.hasSeenProfileIntro ? .pubkyChoice : .profileIntro]
}
private func disconnectAfterFailedDelete() async {
do {
try await pubkyProfile.signOut()
navigation.path = [app.hasSeenProfileIntro ? .pubkyChoice : .profileIntro]
} catch {
app.toast(type: .error, title: t("profile__sign_out_title"), description: error.localizedDescription)
}
}
// MARK: - Save Profile
/// The save belongs to the Pubky session Save was tapped in. Once that session ends, even while the avatar still uploads
/// or the profile publishes, it stops quietly, with no toast and no navigation.
private func saveProfile() async {
let trimmedName = username.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedName.isEmpty else { return }
isSaving = true
defer { isSaving = false }
do {
let isSaved = try await pubkyProfile.saveProfile(
name: trimmedName,
bio: bio.trimmingCharacters(in: .whitespacesAndNewlines),
links: links.map { PubkyProfileLink(label: $0.label, url: $0.url) },
tags: tags,
avatarImage: avatarImage
)
guard isSaved else { return }
app.toast(type: .success, title: t("profile__edit_saved"), accessibilityIdentifier: "ProfileUpdatedToast")
navigation.navigateBack()
} catch {
Logger.error("Failed to save profile: \(error)", context: "EditProfileView")
app.toast(type: .error, title: t("profile__edit_error_title"), description: error.localizedDescription)
}
}
}
#Preview {
NavigationStack {
EditProfileView()
.environmentObject(AppViewModel())
.environmentObject(NavigationViewModel())
.environmentObject(PubkyProfileManager())
.environmentObject(ContactsManager())
.environment(KeyboardManager())
}
.preferredColorScheme(.dark)
}