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

geesawra.industries/old-fella

Old people's social media app

0
1
main
244 lines · 11.7 KB Raw History
import AVFoundation
import FoundationModels
import PhotosUI
import SwiftUI
import UIKit
import UniformTypeIdentifiers

extension ComposeView {
    var body: some View {
        composerContent
            .background {
                ComposerDismissalObserver(
                    preventsDismissal: hasDraftContent || isComposerBusy,
                    onAttempt: requestDismissal, onDismiss: clearComposer)
            }
            .accessibilityAction(.escape, requestDismissal)
            .sheet(isPresented: $showingDrafts) {
                SavedDraftsView(openDraft: openSavedDraft)
            }
            .confirmationDialog(
                "Save this post as a draft?", isPresented: $confirmsDraftAction, titleVisibility: .visible
            ) {
                Button("Save draft") { Task { await saveDraftAndContinue() } }
                Button("Discard", role: .destructive) { Task { await discardDraftAndContinue() } }
                Button("Keep editing") {}
            }
            .alert(
                "Draft could not be updated",
                isPresented: Binding(
                    get: { draftError != nil }, set: { if !$0 { draftError = nil } }
                )
            ) {
                Button("OK", role: .cancel) { draftError = nil }
            } message: {
                Text(draftError ?? "Try again.")
            }
            .sheet(item: $altTextReview) { review in
                NavigationStack {
                    ScrollView {
                        VStack(spacing: 16) {
                            if let attachment = attachments.first(where: { $0.id == review.id }) {
                                AttachmentThumbnail(attachment: attachment)
                                    .frame(maxWidth: .infinity, maxHeight: 360)
                                    .accessibilityLabel("Photo")
                            }
                            TextEditor(
                                text: Binding(
                                    get: { altTextReview?.draft ?? review.draft },
                                    set: { altTextReview?.draft = $0 }
                                )
                            )
                            .scrollContentBackground(.hidden)
                            .padding(8)
                            .frame(height: altTextEditorHeight)
                            .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 12))
                            .accessibilityLabel("Alt text")
                            .accessibilityIdentifier("altTextEditor")
                            .disabled(generatingAltText)
                            HStack {
                                if let index = attachments.firstIndex(where: { $0.id == review.id }),
                                    canGenerateAltText || generatingAltText {
                                    Button {
                                        if generatingAltText {
                                            cancelAltTextGeneration()
                                        } else {
                                            startAltTextGeneration(for: attachments[index])
                                        }
                                    } label: {
                                        HStack {
                                            if generatingAltText { ProgressView() }
                                            Text(generatingAltText ? "Stop generating" : "Generate alt text")
                                        }
                                    }
                                    .accessibilityIdentifier(
                                        generatingAltText ? "stopGeneratingAltTextButton" : "generateAltText-\(index)")
                                }
                                Spacer()
                                let count = (altTextReview?.draft ?? review.draft).count
                                Text("\(String(count))/\(String(altTextCharacterLimit))")
                                    .appFont(.footnote).monospacedDigit()
                                    .foregroundStyle(count > altTextCharacterLimit ? .red : .secondary)
                                    .accessibilityLabel("\(count) of \(altTextCharacterLimit) characters")
                                    .accessibilityIdentifier("altTextCharacterCount")
                            }
                            Spacer(minLength: 0)
                        }
                        .padding()
                    }
                    .scrollDismissesKeyboard(.interactively)
                    .appNavigationTitle("Alt text editor")
                    .toolbar {
                        ToolbarItem(placement: .cancellationAction) {
                            Button(role: .cancel) {
                                cancelAltTextGeneration()
                                altTextReview = nil
                            } label: {
                                Image(systemName: "xmark")
                            }
                            .accessibilityLabel("Cancel")
                        }
                        ToolbarItem(placement: .confirmationAction) {
                            Button("Save") {
                                if let current = altTextReview,
                                    let index = attachments.firstIndex(where: { $0.id == current.id }),
                                    attachments[index].altText == current.originalText {
                                    altTextBinding(for: current.id).wrappedValue = current.draft
                                }
                                altTextReview = nil
                            }
                            .disabled(generatingAltText || (altTextReview?.draft.count ?? 0) > altTextCharacterLimit)
                        }
                    }
                    .interactiveDismissDisabled(generatingAltText)
                }
            }
            .alert(
                "Media not added",
                isPresented: Binding(
                    get: { mediaError != nil },
                    set: { if !$0 { mediaError = nil } }
                )
            ) {
                Button("OK", role: .cancel) { mediaError = nil }
            } message: {
                Text(mediaError ?? "")
            }
            .alert(
                "Alt text unavailable",
                isPresented: Binding(
                    get: { altTextError != nil },
                    set: { if !$0 { altTextError = nil } }
                )
            ) {
                Button("OK", role: .cancel) { altTextError = nil }
            } message: {
                Text(altTextError ?? "")
            }
            .alert("Add alt text?", isPresented: $confirmsMissingAltText) {
                Button("Keep editing", role: .cancel) {}
                Button("Post without alt text") { Task { await publish() } }
            } message: {
                Text("Some images do not have alt text. Add descriptions so more people can understand them.")
            }
            .alert(
                model.publishResultUnknown ? "Post status unknown" : "Post not sent",
                isPresented: Binding(
                    get: { model.publishErrorMessage != nil },
                    set: { if !$0 { model.clearPublishError() } }
                )
            ) {
                Button("OK", role: .cancel) { model.clearPublishError() }
            } message: {
                Text(model.publishErrorMessage ?? "Try again.")
            }
            .confirmationDialog(
                "Replace attached media?", isPresented: $confirmsSharedMediaReplacement, titleVisibility: .visible
            ) {
                Button("Replace media") {
                    attachments = []
                    video = nil
                    Task {
                        await addSharedMedia(pendingSharedMedia)
                        pendingSharedMedia = []
                        if mediaError == nil { await acknowledgeSharedImport() }
                    }
                }
                Button("Keep current media", role: .cancel) {
                    pendingSharedMedia = []
                    Task { await acknowledgeSharedImport() }
                }
            } message: {
                Text("The shared media cannot be added to the current attachments.")
            }
            .confirmationDialog(
                "Discard this draft?", isPresented: $confirmsDiscardUncertainDraft, titleVisibility: .visible
            ) {
                Button("Discard draft", role: .destructive) {
                    draftsAction = .reset
                    Task { await discardDraftAndContinue() }
                }
            } message: {
                Text("Bluesky may have received this post. Discarding the draft will not remove a post from Bluesky.")
            }
            .task(id: MentionLookupRequest(mention: activeMention, retry: mentionRetry)) {
                await loadMentionSuggestions()
            }
            .task(id: activeEmoji) {
                await loadEmojiSuggestions()
            }
            .onChange(of: selectedItems) { _, items in
                guard !items.isEmpty else { return }
                Task { await loadMedia(items) }
            }
            .task {
                model.clearPublishError()
                if ProcessInfo.processInfo.arguments.contains("-ui-testing"),
                    ProcessInfo.processInfo.arguments.contains("-ui-testing-compose-images"),
                    let data = UIImage(systemName: "photo")?.pngData() {
                    if ProcessInfo.processInfo.arguments.contains("-ui-testing-compose-ten-images") {
                        attachments = (0..<imageLimit).map { _ in ImageAttachment(data: data, altText: "A photo") }
                    } else {
                        attachments = [ImageAttachment(data: data, altText: "A photo"), ImageAttachment(data: data)]
                    }
                }
                if ProcessInfo.processInfo.arguments.contains("-ui-testing"),
                    ProcessInfo.processInfo.arguments.contains("-ui-testing-compose-video"), video == nil {
                    video = VideoAttachment(data: Data([0]), mimeType: "video/mp4")
                }
                if let sharedContent {
                    if !sharedContent.text.isEmpty {
                        if !text.isEmpty { text += "\n" }
                        text += sharedContent.text
                        textSelection = NSRange(location: text.utf16.count, length: 0)
                    }
                    attachments.append(contentsOf: sharedContent.images)
                    video = sharedContent.video
                }
                if let sharedImport {
                    if !sharedImport.text.isEmpty {
                        if !text.isEmpty { text += "\n" }
                        text += sharedImport.text
                        textSelection = NSRange(location: text.utf16.count, length: 0)
                    }
                    let incoming = sharedImport.attachments
                    let hasVideo = incoming.contains { $0.kind == .video }
                    if !incoming.isEmpty
                        && (video != nil || (hasVideo && !attachments.isEmpty)
                            || attachments.count + incoming.count > imageLimit) {
                        pendingSharedMedia = incoming
                        confirmsSharedMediaReplacement = true
                    } else {
                        await addSharedMedia(incoming)
                        if mediaError == nil { await acknowledgeSharedImport() }
                    }
                }
                textIsFocused = true
            }
            .onDisappear {
                cancelAltTextGeneration()
            }
            .interactiveDismissDisabled(hasDraftContent || isComposerBusy)
    }

}