1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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 }
}
}