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

geesawra.industries/old-fella

Old people's social media app

0
1
main
217 lines · 8.4 KB Raw History
import AVFoundation
import FoundationModels
import PhotosUI
import SwiftUI
import UIKit
import UniformTypeIdentifiers

extension ComposeView {
    var composerContent: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 16) {
                composerContext
                editor
                if !attachments.isEmpty || video != nil {
                    attachmentStrip
                        .transition(.opacity)
                }
                uncertainDraftNotice
            }
            .padding(.vertical, 16)
        }
        .accessibilityIdentifier("composerScrollView")
        .scrollDismissesKeyboard(.interactively)
        .overlayPreferenceValue(ComposerEditorBoundsKey.self) { anchor in
            if let anchor, textIsFocused, !isComposerBusy {
                GeometryReader { geometry in
                    if activeMention != nil {
                        mentionDropdown(editorFrame: geometry[anchor], viewport: geometry.size)
                    } else if activeEmoji != nil, !emojiResults.isEmpty {
                        emojiDropdown(editorFrame: geometry[anchor], viewport: geometry.size)
                    }
                }
            }
        }
        .safeAreaInset(edge: .bottom, spacing: 0) {
            attachmentToolbar
        }
        .animation(reduceMotion ? nil : .easeInOut(duration: 0.25), value: attachments.isEmpty)
        .appNavigationTitle(
            composerReplyTo == nil && composerQuotePostID == nil
                ? "New post" : (composerReplyTo == nil ? "Quote post" : "Reply"))
        .toolbar {
            counterToolbar
            publishToolbar
        }
    }

    @ViewBuilder
    var composerContext: some View {
        if let replyTo = composerReplyTo {
            contextRow(title: "Replying to", postID: replyTo, isQuote: false)
        }
        if let quotePostID = composerQuotePostID {
            contextRow(title: "Quoting", postID: quotePostID, isQuote: true)
        }
    }

    var editor: some View {
        HStack(alignment: .top, spacing: 12) {
            AccountAvatar(account: model.account, size: 40)
            ComposerTextEditor(
                text: $text, selection: $textSelection, isFocused: $textIsFocused,
                isEnabled: !isComposerBusy,
                onMediaPaste: { providers in Task { await loadPastedMedia(providers) } },
                onCaretChange: { caretRect = $0 }, onMentionChange: { activeMention = $0 },
                onEmojiChange: updateEmojiSuggestions
            )
            .frame(height: postEditorHeight)
            .anchorPreference(key: ComposerEditorBoundsKey.self, value: .bounds) { $0 }
            .scrollContentBackground(.hidden)
            .accessibilityLabel("Post text")
            .accessibilityIdentifier("composeTextField")
            .disabled(isComposerBusy)
            .overlay(alignment: .topLeading) {
                if text.isEmpty {
                    Text("What's up?")
                        .foregroundStyle(.tertiary)
                        .padding(.leading, 5)
                        .allowsHitTesting(false)
                        .accessibilityHidden(true)
                }
            }
        }
        .padding(.horizontal, 16)
    }

    @ViewBuilder
    var uncertainDraftNotice: some View {
        if draftIsUncertain {
            VStack(spacing: 8) {
                Text("Bluesky may have received this post. Check your profile before you post it again.")
                    .appFont(.footnote)
                    .foregroundStyle(.secondary)
                Button("Discard draft and start over") { confirmsDiscardUncertainDraft = true }
            }
            .padding()
        }
    }

    var attachmentToolbar: some View {
        VStack(spacing: 0) {
            Divider()
                .hidden()
            HStack(spacing: 18) {
                PhotosPicker(
                    selection: $selectedItems, maxSelectionCount: max(1, imageLimit - attachments.count),
                    matching: .any(of: [.images, .videos])
                ) {
                    Label("Add photos or video", systemImage: "photo.on.rectangle.angled")
                        .labelStyle(.iconOnly)
                        .font(.title3)
                        .frame(width: 44, height: 44)
                }
                .accessibilityLabel("Add photos or video")
                .accessibilityIdentifier("addPhotosButton")
                .disabled(
                    video != nil || attachments.count >= imageLimit || isLoadingImages || model.isPublishing
                        || generatingAltText || isWorkingWithDrafts)
                Button(action: requestDrafts) {
                    Label("Drafts", systemImage: "doc.on.doc")
                        .labelStyle(.iconOnly)
                        .font(.title3)
                        .frame(width: 44, height: 44)
                }
                .accessibilityIdentifier("draftsButton")
                .disabled(isComposerBusy)
                if isLoadingImages { ProgressView() }
                if isWorkingWithDrafts { ProgressView().accessibilityLabel("Updating drafts") }
                Spacer()
            }
            .padding(.horizontal, 16)
        }
    }


    @ToolbarContentBuilder
    var publishToolbar: some ToolbarContent {
        if onSharedCancel != nil {
            ToolbarItem(placement: .topBarLeading) {
                Button(role: .cancel, action: requestDismissal) {
                    Image(systemName: "xmark")
                }
                .accessibilityLabel("Cancel")
                .disabled(isComposerBusy)
                .accessibilityIdentifier("cancelComposeButton")
            }
        }
        ToolbarItem(placement: .topBarTrailing) {
            Button {
                if remindMissingAltText
                    && attachments.contains(where: {
                        $0.altText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
                    }) {
                    confirmsMissingAltText = true
                } else {
                    Task { await publish() }
                }
            } label: {
                Image(systemName: "arrow.up")
                    .fontWeight(.semibold)
                    .opacity(model.isPublishing ? 0 : 1)
                    .overlay {
                        if model.isPublishing {
                            ProgressView()
                                .progressViewStyle(.circular)
                                .controlSize(.small)
                                .accessibilityHidden(true)
                        }
                    }
            }
            .buttonStyle(.borderedProminent)
            .buttonBorderShape(.circle)
            .tint(AppPalette.accent)
            .disabled(
                !canPublish || isComposerBusy || draftIsUncertain
            )
            .accessibilityLabel(model.isPublishing ? "Publishing post" : "Post")
            .accessibilityIdentifier("publishButton")
        }
    }

    @ToolbarContentBuilder
    var counterToolbar: some ToolbarContent {
        let count = text.count
        let excess = count - characterLimit
        let isOverLimit = excess > 0
        let warningTint: Color? = isOverLimit ? .red : (count >= characterLimit - 20 ? .orange : nil)

        ToolbarItem(placement: .topBarLeading) {
            HStack(alignment: .top, spacing: 2) {
                Text(isOverLimit ? "+\(excess)" : "\(count)")
                    .appFont(.body, weight: .semibold)
                    .monospacedDigit()
                    .contentTransition(reduceMotion ? .identity : .numericText(value: Double(count)))
                if isOverLimit {
                    Text("over")
                        .appFont(.caption2, weight: .medium)
                        .padding(.top, 2)
                }
            }
            .foregroundStyle(.primary)
            .padding(.horizontal, 12)
            .frame(minWidth: 44, minHeight: 44)
            .fixedSize(horizontal: true, vertical: false)
            .glassEffect(.regular.tint(warningTint))
            .animation(reduceMotion ? nil : .snappy(duration: 0.2), value: count)
            .accessibilityElement(children: .ignore)
            .accessibilityLabel(
                isOverLimit
                    ? "\(count) of \(characterLimit) characters, \(excess) over the limit"
                    : "\(count) of \(characterLimit) characters")
            .accessibilityIdentifier("composeCharacterCount")
        }
        .sharedBackgroundVisibility(.hidden)
    }

}