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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
import Foundation
import SwiftUI
extension AppModel {
func contentInputsChanged() {
preparedContentNeedsUpdate = true
if preparedContentUpdateDepth == 0 { prepareContent() }
}
func moderationInputsChanged() {
moderationRevision = UUID()
moderationDecisions.removeAll(keepingCapacity: true)
moderationExpiryCandidates.removeAll(keepingCapacity: true)
contentInputsChanged()
}
func withContentUpdates(_ update: () -> Void) {
preparedContentUpdateDepth += 1
defer {
preparedContentUpdateDepth -= 1
if preparedContentUpdateDepth == 0, preparedContentNeedsUpdate { prepareContent() }
}
update()
}
func prepareContent() {
prepareCachedPosts()
preparedContentNeedsUpdate = false
contentPreparationCount += 1
let date = now()
// Prepare rows before SwiftUI reads them. Loading state does not change these results.
if moderationExpiry.map({ $0 <= date }) == true || preparedModerationTime.map({ date < $0 }) == true {
moderationDecisions.removeAll(keepingCapacity: true)
}
preparedModerationTime = date
preparedDecisionInputs = []
preparedPostDecisions.removeAll(keepingCapacity: true)
preparedAuthorDecisions.removeAll(keepingCapacity: true)
preparedQuoteDecisions.removeAll(keepingCapacity: true)
let expiry = prepareModerationDecisions(date: date)
prepareTimelineRows()
prepareNotificationRows()
preparePostViewStates()
finishModerationPreparation(date: date, expiry: expiry)
}
private func prepareCachedPosts() {
if hasCachedPosts != !posts.isEmpty { hasCachedPosts = !posts.isEmpty }
let previousCachedIDs = Set(cachedPostsByID.keys)
cachedPostsByID = postsByID
for collection in [replyContexts, threadContexts, authorPosts, searchReplyContexts] {
for key in collection.keys.sorted() {
for post in collection[key] ?? [] where cachedPostsByID[post.id] == nil {
cachedPostsByID[post.id] = post
}
}
}
for state in padStates.values {
for post in state.posts + state.replyContexts.values.flatMap({ $0 }) where cachedPostsByID[post.id] == nil {
cachedPostsByID[post.id] = post
}
}
for post in searchPosts where cachedPostsByID[post.id] == nil { cachedPostsByID[post.id] = post }
for savedPost in savedPosts {
var post = cachedPostsByID[savedPost.id] ?? savedPost
post.isSaved = true
cachedPostsByID[post.id] = post
}
cacheNotificationPosts()
if previousCachedIDs != Set(cachedPostsByID.keys) { postLookupRevision = UUID() }
for (id, post) in cachedPostsByID where postViewStates[id] == nil {
postViewStates[id] = PostViewState(post: post)
}
}
private func prepareModerationDecisions(date: Date) -> Date? {
var expiry = contentPreferences?.mutedWords.compactMap(\.expiresAt).filter { $0 > date }.min()
func recordExpiry(_ labels: [ModerationPolicy.Label]) {
for label in labels {
if let end = label.expiresAt, end > date { expiry = min(expiry ?? end, end) }
}
}
func prepare(author: Post.Author) {
recordExpiry(author.moderationLabels)
_ = contentDecision(author: author)
}
func prepare(post: Post) {
recordExpiry(post.moderationLabels)
_ = contentDecision(for: post)
prepare(author: post.author)
if let quote = post.quote, let author = quote.author {
recordExpiry(quote.moderationLabels)
prepare(author: author)
}
}
preparePostCollections(preparePost: { prepare(post: $0) }, prepareAuthor: { prepare(author: $0) })
prepareAuthorCollections(preparePost: { prepare(post: $0) }, prepareAuthor: { prepare(author: $0) })
return expiry
}
private func preparePostCollections(preparePost: (Post) -> Void, prepareAuthor: (Post.Author) -> Void) {
for post in posts { preparePost(post) }
for post in searchPosts { preparePost(post) }
for post in savedPosts { preparePost(post) }
for author in searchAccounts { prepareAuthor(author) }
for state in padStates.values {
for post in state.posts + state.replyContexts.values.flatMap({ $0 }) { preparePost(post) }
for author in state.repostedBy.values { prepareAuthor(author) }
}
for collection in [replyContexts, threadContexts, authorPosts, searchReplyContexts] {
for context in collection.values { for post in context { preparePost(post) } }
}
}
private func prepareAuthorCollections(preparePost: (Post) -> Void, prepareAuthor: (Post.Author) -> Void) {
for author in repostedBy.values { prepareAuthor(author) }
for author in searchRepostedBy.values { prepareAuthor(author) }
for authors in profileRepostedBy.values { for author in authors.values { prepareAuthor(author) } }
for profile in profiles.values { prepareAuthor(profile.author) }
for notification in notifications {
prepareAuthor(notification.author)
if let post = notification.relatedPost { preparePost(post) }
if let post = notification.parentPost { preparePost(post) }
}
}
private func prepareTimelineRows() {
let timeline = filteredTimelinePosts()
if timelinePosts != timeline { timelinePosts = timeline }
let rowIDs = timeline.map(\.id)
if timelineRowIDs != rowIDs { timelineRows = timeline.map { postViewState(for: $0) } }
for state in padStates.values {
let visiblePosts = filteredFeedPosts(state.posts, contexts: state.replyContexts, reposts: state.repostedBy)
if state.rowIDs != visiblePosts.map(\.id) {
state.rows = visiblePosts.map { postViewState(for: $0) }
}
}
}
private func prepareNotificationRows() {
let visible = visibleNotifications(in: notifications)
if visibleNotifications != visible { visibleNotifications = visible }
let groups = NotificationGroup.make(from: visible, pageStarts: notificationPageStarts)
if notificationGroups != groups { notificationGroups = groups }
let previousRows = Dictionary(uniqueKeysWithValues: notificationRows.map { ($0.id, $0) })
let rows = groups.map { group in
let row = previousRows[group.id] ?? NotificationGroupState(group: group)
row.update(group: group)
return row
}
if notificationRows.map(\.id) != rows.map(\.id) { notificationRows = rows }
if hasVisibleNotifications != !visible.isEmpty { hasVisibleNotifications = !visible.isEmpty }
let unread = visible.contains { !$0.isRead }
if hasUnreadNotifications != unread { hasUnreadNotifications = unread }
}
private func preparePostViewStates() {
for id in postViewStates.keys { updatePostViewState(id: id) }
for state in postViewStates.values {
state.updateReplyContext(resolvedReplyContext(for: state.post))
}
postViewStates = postViewStates.filter { cachedPostsByID[$0.key] != nil }
}
private func finishModerationPreparation(date: Date, expiry originalExpiry: Date?) {
var expiry = originalExpiry
let usedInputs = preparedDecisionInputs ?? []
moderationDecisions = moderationDecisions.filter { usedInputs.contains($0.key) }
moderationExpiryCandidates = moderationExpiryCandidates.filter {
moderationDecisions[$0.key] != nil && $0.value > date
}
if let cachedExpiry = moderationExpiryCandidates.values.min() {
expiry = min(expiry ?? cachedExpiry, cachedExpiry)
}
preparedDecisionInputs = nil
scheduleModerationExpiry(expiry)
}
func scheduleModerationExpiry(_ expiry: Date?) {
guard expiry != moderationExpiry else { return }
moderationExpiryTask?.cancel()
moderationExpiry = expiry
guard let expiry else {
moderationExpiryTask = nil
return
}
let delay = max(0, expiry.timeIntervalSince(now()))
moderationExpiryTask = Task { [weak self] in
do { try await Task.sleep(for: .seconds(delay)) } catch { return }
guard let self else { return }
self.refreshExpiredModeration()
}
}
func refreshExpiredModeration() {
let date = now()
guard moderationExpiry.map({ $0 <= date }) == true || preparedModerationTime.map({ date < $0 }) == true else {
return
}
moderationInputsChanged()
}
private func cacheNotificationPosts() {
for notification in notifications {
for post in [notification.relatedPost, notification.parentPost].compactMap({ $0 })
where cachedPostsByID[post.id] == nil { cachedPostsByID[post.id] = post }
}
}
}