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

geesawra.industries/old-fella

Old people's social media app

0
1
main
48 lines · 2.2 KB Raw History
import Foundation

struct FeedRefreshBuffer {
    var posts: [Post] = []
    var contexts: [String: [Post]] = [:]
    var reposts: [String: Post.Author] = [:]
    var muted: Set<String> = []
    var cursors: Set<String> = []

    func page(cursor: String?) -> FeedPage {
        FeedPage(posts: posts, cursor: cursor, replyContexts: contexts, repostedBy: reposts)
    }
}

extension AppModel {
    func hasVisibleStagedPosts(_ staged: FeedRefreshBuffer) -> Bool {
        let contexts = staged.contexts.keys.sorted().flatMap { staged.contexts[$0] ?? [] }
        let lookup = Dictionary((staged.posts + contexts).map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
        return !filteredFeedPosts(
            staged.posts, contexts: staged.contexts, reposts: staged.reposts, stagedPosts: lookup
        ).isEmpty
    }

    func stageRefreshPage(_ page: FeedPage, staged: inout FeedRefreshBuffer, nextCursor: String?) -> String? {
        staged.muted.formUnion(page.mutedPostIDs)
        let muted = staged.muted
        staged.posts.removeAll { muted.contains($0.id) }
        staged.contexts = staged.contexts.filter { !muted.contains($0.key) }.mapValues {
            $0.filter { !muted.contains($0.id) }
        }
        let incoming = postsForCacheUpdate(from: page).filter { !muted.contains($0.id) }
        let replacements = Dictionary(
            incoming.map { ($0.id, $0) }, uniquingKeysWith: { _, latest in latest })
        staged.posts = staged.posts.map { replacements[$0.id] ?? $0 }
        var seen = Set(staged.posts.map(\.id))
        staged.posts.append(
            contentsOf: page.posts.filter { !muted.contains($0.id) && seen.insert($0.id).inserted })
        staged.contexts = staged.contexts.mapValues { $0.map { replacements[$0.id] ?? $0 } }
        staged.contexts.merge(
            page.replyContexts.filter { !muted.contains($0.key) }.mapValues {
                $0.filter { !muted.contains($0.id) }
            }
        ) { _, new in new }
        staged.reposts.merge(page.repostedBy) { _, new in new }
        if let nextCursor { staged.cursors.insert(nextCursor) }
        return page.cursor.flatMap { staged.cursors.contains($0) ? nil : $0 }
    }
}