import SwiftUI private enum DraftRetryAction { case load, open(SavedPostDraft), delete(SavedPostDraft) } struct SavedDraftsView: View { @Environment(AppModel.self) private var model @Environment(\.dismiss) private var dismiss @Environment(\.accessibilityReduceMotion) private var reduceMotion let openDraft: (SavedPostDraft) async throws -> Void @State private var drafts: [SavedPostDraft] = [] @State private var cursor: String? @State private var isLoading = false @State private var showsLoadingIndicator = false @State private var hasLoaded = false @State private var errorMessage: String? @State private var activeDraftID: String? @State private var retryAction = DraftRetryAction.load private var showsEmptyState: Bool { hasLoaded && drafts.isEmpty && cursor == nil && errorMessage == nil && !isLoading } var body: some View { NavigationStack { List { ForEach(drafts) { draft in Button { Task { await open(draft) } } label: { row(draft) } .disabled(activeDraftID != nil || draft.unavailableReason != nil) .accessibilityIdentifier("savedDraft-\(draft.id)") .swipeActions { Button("Delete", role: .destructive) { Task { await delete(draft) } } .disabled(activeDraftID != nil) } } if isLoading && !drafts.isEmpty { ProgressView().frame(maxWidth: .infinity) } else if !isLoading && !drafts.isEmpty && cursor != nil { Button("Load more") { Task { await loadMore() } } } if let errorMessage { Text(errorMessage).foregroundStyle(.secondary) Button("Try again") { Task { await retry() } } .disabled(isLoading || activeDraftID != nil) } } .overlay { ZStack { if showsEmptyState { ContentUnavailableView( "No drafts", systemImage: "doc", description: Text("Saved posts appear here.")) .transition(.asymmetric(insertion: .opacity, removal: .identity)) } else if isLoading && drafts.isEmpty && showsLoadingIndicator { ProgressView("Loading drafts") .transition(.identity) } } .animation(reduceMotion ? nil : .easeIn(duration: 0.2), value: showsEmptyState) } .appNavigationTitle("Drafts") .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } .disabled(activeDraftID != nil) } } .interactiveDismissDisabled(activeDraftID != nil) .task { if !hasLoaded { await loadMore() } } .task(id: isLoading) { showsLoadingIndicator = false guard isLoading else { return } do { try await Task.sleep(for: .milliseconds(300)) } catch { return } guard !Task.isCancelled else { return } showsLoadingIndicator = true } } } private func row(_ draft: SavedPostDraft) -> some View { VStack(alignment: .leading, spacing: 4) { Text(draft.text.isEmpty ? "Post with attachments" : draft.text) .foregroundStyle(.primary) .lineLimit(3) HStack { if draft.replyTo != nil { Label("Reply", systemImage: "arrow.turn.down.right") } if draft.quotePostID != nil { Label("Quote", systemImage: "quote.bubble") } if draft.imageCount > 0 { Label("\(draft.imageCount)", systemImage: "photo") } if draft.hasVideo { Label("Video", systemImage: "video") } Text(draft.updatedAt, style: .date) if activeDraftID == draft.id { ProgressView() } } .appFont(.caption) .foregroundStyle(.secondary) if let reason = draft.unavailableReason { Text(reason).appFont(.caption).foregroundStyle(.secondary) } } } private func loadMore() async { guard !isLoading else { return } isLoading = true errorMessage = nil defer { isLoading = false } do { var requestedCursors: Set = [] repeat { if let cursor, !requestedCursors.insert(cursor).inserted { throw ServiceError.invalidResponse } let page = try await model.loadSavedDrafts(cursor: cursor) let existing = Set(drafts.map(\.id)) drafts.append(contentsOf: page.drafts.filter { !existing.contains($0.id) }) cursor = page.cursor.flatMap { $0.isEmpty ? nil : $0 } hasLoaded = true } while drafts.isEmpty && cursor != nil } catch { errorMessage = NetworkFailure.message(for: error) retryAction = .load } } private func open(_ draft: SavedPostDraft) async { activeDraftID = draft.id errorMessage = nil defer { activeDraftID = nil } do { try await openDraft(draft) } catch { errorMessage = NetworkFailure.message(for: error) retryAction = .open(draft) } } private func delete(_ draft: SavedPostDraft) async { activeDraftID = draft.id errorMessage = nil defer { activeDraftID = nil } do { try await model.deleteSavedDraft(id: draft.id) drafts.removeAll { $0.id == draft.id } if drafts.isEmpty && cursor != nil { await loadMore() } } catch { errorMessage = NetworkFailure.message(for: error) retryAction = .delete(draft) } } private func retry() async { switch retryAction { case .load: await loadMore() case .open(let draft): await open(draft) case .delete(let draft): await delete(draft) } } }