~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
267 lines · 10.8 KB Raw History
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)
            }
        }
    }
}