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

geesawra.industries/old-fella

Old people's social media app

0
1
main
238 lines · 12.1 KB Raw History
import SwiftUI

struct PostDetailView: View {
    @Environment(AppModel.self) private var model
    @State private var completedLoad: LoadRequest?
    let postID: String
    let openPost: (String) -> Void
    let openProfile: (String) -> Void
    let openComposer: (String?, String?) -> Void

    private struct LoadRequest: Equatable {
        let postID: String
        let contentRevision: UUID
    }

    var body: some View {
        let request = LoadRequest(postID: postID, contentRevision: model.contentRevision)
        let hasFinishedLoading = completedLoad == request
        Group {
            if let error = model.contentPreferencesError {
                ContentUnavailableView {
                    Label("Could not load content preferences", systemImage: "exclamationmark.triangle")
                } description: {
                    Text(error)
                } actions: {
                    Button("Retry") { Task { await model.reloadContentPreferences() } }
                    Link("Manage preferences in Bluesky", destination: BlueskyLinks.moderation)
                }
            } else if let post = model.post(id: postID), model.isHidden(post.author.id) {
                ContentUnavailableView {
                    Label("Post hidden", systemImage: "eye.slash")
                } description: {
                    Text("Unmute and unblock this account to see its posts.")
                } actions: {
                    Button("View account controls") { openProfile(post.author.id) }
                }
                .accessibilityIdentifier("hiddenPost")
            } else if hasFinishedLoading, model.threadContexts[postID] != nil, let post = model.post(id: postID) {
                let ancestors = model.threadAncestors(for: post)
                ThreadScrollView(anchorID: postID) { height in
                    VStack(alignment: .leading, spacing: 0) {
                        VStack(alignment: .leading, spacing: 0) {
                            ForEach(Array(ancestors.enumerated()), id: \.element.id) { index, ancestor in
                                row(for: ancestor, first: index == 0, last: false)
                            }
                        }
                        .background(Color(uiColor: .systemBackground))
                        VStack(alignment: .leading, spacing: 0) {
                            let continuation = model.threadContinuation(after: post)
                            let replies = model.directReplies(to: post, inThread: postID).filter {
                                $0.id != continuation.first?.id
                            }
                            let sideReplyPosts = postsWithSideReplies(in: continuation)
                            let hasReplies = !replies.isEmpty || !sideReplyPosts.isEmpty
                            let showsSeparator = !continuation.isEmpty || hasReplies
                            row(for: post, first: true, last: true)
                                .padding(.bottom, showsSeparator ? 0 : 24)
                                .modifier(
                                    ContentListRowStyle(contentInsets: EdgeInsets(), showsSeparator: showsSeparator))
                                .background(alignment: .top) { ThreadScrollAnchor(id: postID) }
                            if !continuation.isEmpty {
                                replyHeading("Thread Replies")
                                VStack(alignment: .leading, spacing: 0) {
                                    ForEach(continuation) { part in
                                        row(
                                            for: part, first: part.id == continuation.first?.id,
                                            last: part.id == continuation.last?.id)
                                    }
                                }
                                .modifier(ContentListRowStyle(contentInsets: EdgeInsets()))
                            }
                            replyHeading("Replies")
                            if !hasReplies {
                                Text(continuation.isEmpty ? "No replies yet." : "No other replies yet.")
                                    .foregroundStyle(.secondary)
                                    .padding(.horizontal, 16)
                                    .padding(.bottom, 12)
                            }
                            if !sideReplyPosts.isEmpty {
                                VStack(alignment: .leading, spacing: 0) {
                                    ForEach(sideReplyPosts) { part in
                                        moreReplies(
                                            for: part, last: part.id == sideReplyPosts.last?.id,
                                            showThreadPosition: true)
                                    }
                                }
                                .padding(.bottom, replies.isEmpty ? 24 : 0)
                                .modifier(
                                    ContentListRowStyle(contentInsets: EdgeInsets(), showsSeparator: !replies.isEmpty))
                            }
                            ForEach(replies) { reply in
                                let isLastReply = reply.id == replies.last?.id
                                let nestedReplies = model.directReplies(to: reply, inThread: postID)
                                let replyCount = max(max(0, reply.replyCount), nestedReplies.count)
                                let preview = Array(nestedReplies.prefix(10))
                                VStack(alignment: .leading, spacing: 0) {
                                    let hasMore = replyCount > preview.count
                                    row(for: reply, first: true, last: preview.isEmpty && !hasMore)
                                    ForEach(Array(preview.enumerated()), id: \.element.id) { index, nestedReply in
                                        let showsMore =
                                            nestedReply.replyCount > 0
                                            || !model.directReplies(to: nestedReply, inThread: postID).isEmpty
                                        let isLast = index == preview.count - 1 && !hasMore
                                        row(for: nestedReply, first: false, last: isLast && !showsMore)
                                        if showsMore {
                                            moreReplies(for: nestedReply, last: isLast)
                                        }
                                    }
                                    if hasMore {
                                        moreReplies(for: reply, last: true)
                                    }
                                }
                                .padding(.bottom, isLastReply ? 24 : 0)
                                .modifier(
                                    ContentListRowStyle(contentInsets: EdgeInsets(), showsSeparator: !isLastReply))
                            }
                        }
                        // Keep the minimum scroll height from stretching tappable post padding.
                        .fixedSize(horizontal: false, vertical: true)
                        .frame(minHeight: height, alignment: .topLeading)
                    }
                    .background(Color(uiColor: .systemGroupedBackground))
                }
            } else if model.deletedPostIDs.contains(postID) {
                ContentUnavailableView(
                    "Post deleted", systemImage: "text.bubble", description: Text("This post is no longer available."))
            } else if hasFinishedLoading, model.failedPostIDs.contains(postID) {
                ContentUnavailableView {
                    Label("Could not load post", systemImage: "text.bubble")
                } description: {
                    Text(model.postErrors[postID] ?? "Try loading this post again.")
                } actions: {
                    Button("Try again") { Task { await model.loadPost(id: postID) } }
                }
            } else if !hasFinishedLoading || model.isLoadingPost || model.threadContexts[postID] == nil {
                PostLoadingPlaceholder(label: "Loading post", count: 1)
                    .accessibilityIdentifier("postDetailLoading")
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
                    .background(Color(uiColor: .systemGroupedBackground))
            } else {
                ContentUnavailableView(
                    "Post not found", systemImage: "text.bubble", description: Text("This post is not available."))
            }
        }
        .task(id: request) {
            guard model.contentPreferences != nil else { return }
            await model.loadPost(id: request.postID)
            if !Task.isCancelled { completedLoad = request }
        }
        .appNavigationTitle("Post")
        .toolbarBackground(.visible, for: .navigationBar)
        .toolbar {
            if hasFinishedLoading, let post = model.post(id: postID), model.hasEarlierPosts(for: post) {
                ToolbarItem(placement: .topBarTrailing) {
                    Label("More above", systemImage: "arrow.up")
                        .appFont(.caption)
                        .accessibilityIdentifier("earlierPostsCue")
                }
            }
        }
    }

    private func replyHeading(_ title: LocalizedStringKey) -> some View {
        Text(title)
            .appFont(.headline)
            .accessibilityAddTraits(.isHeader)
            .padding(.horizontal, 16)
            .padding(.vertical, 12)
    }

    private func postsWithSideReplies(in posts: [Post]) -> [Post] {
        posts.enumerated().compactMap { index, post in
            let nextID = index + 1 < posts.count ? posts[index + 1].id : nil
            let continuationCount = nextID == nil ? 0 : 1
            let hasSideReplies = post.replyCount > continuationCount
                || model.directReplies(to: post, inThread: postID).contains { $0.id != nextID }
            return hasSideReplies ? post : nil
        }
    }

    private func moreReplies(for post: Post, last: Bool, showThreadPosition: Bool = false) -> some View {
        Button {
            openPost(post.id)
        } label: {
            Group {
                if showThreadPosition, let position = model.threadPositions[postID]?[post.id] {
                    Label("View replies to post \(position.index) of \(position.count)", systemImage: "chevron.right")
                } else {
                    Label("View more replies", systemImage: "chevron.right")
                }
            }
            .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)
            .padding(rowInsets(first: false, last: last))
            .contentShape(Rectangle())
        }
        .buttonStyle(.plain)
        .foregroundStyle(.tint)
        .accessibilityIdentifier("viewReplies-\(post.id)")
    }

    private func rowInsets(first: Bool, last: Bool) -> EdgeInsets {
        EdgeInsets(top: first ? 20 : 12, leading: 16, bottom: last ? 16 : 12, trailing: 16)
    }

    private func row(for post: Post, first: Bool, last: Bool) -> some View {
        PostRow(
            post: post,
            openPost: { if post.id != postID { openPost(post.id) } },
            openProfile: { openProfile(post.author.id) },
            openActor: openProfile,
            openQuotedPost: openPost,
            openComposer: openComposer,
            moderationContext: post.id == postID ? .contentView : .contentList,
            allowsPostNavigation: post.id != postID,
            contentInsets: rowInsets(first: first, last: last),
            threadPosition: model.threadPositions[postID]?[post.id]
        )
    }
}

#if DEBUG
    #Preview("Post detail and thread") {
        PreviewHost { _ in
            NavigationStack {
                PostDetailView(
                    postID: "thread-selected", openPost: { _ in }, openProfile: { _ in }, openComposer: { _, _ in })
            }
        }
    }

    #Preview("Post detail loading") {
        PreviewHost(signedIn: false) { _ in
            NavigationStack {
                PostDetailView(postID: "post-1", openPost: { _ in }, openProfile: { _ in }, openComposer: { _, _ in })
            }
        }
    }
#endif