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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import Foundation
import SwiftUI
extension AppModel {
var padDefaultsKey: String? {
account.map { "oldsky.padColumns.\($0.id)" }
}
func savePadColumns() {
guard let key = padDefaultsKey,
let data = try? JSONEncoder().encode(padColumns.filter { $0.detail == nil })
else { return }
feedDefaults.set(data, forKey: key)
}
func restorePadColumns() {
let saved =
padDefaultsKey.flatMap { feedDefaults.data(forKey: $0) }
.flatMap { try? JSONDecoder().decode([PadColumn].self, from: $0) } ?? []
var seen: Set<String> = []
padColumns = saved.compactMap { column in
let normalized: PadColumn
if column.id == PadColumn.following.id {
normalized = .following
} else if column.id == PadColumn.notifications.id {
normalized = .notifications
} else if let feed = column.feed, feed.id == column.id {
normalized = PadColumn(feed: feed)
} else {
return nil
}
return seen.insert(normalized.id).inserted ? normalized : nil
}
if seen.insert(PadColumn.following.id).inserted { padColumns.insert(.following, at: 0) }
if seen.insert(PadColumn.notifications.id).inserted { padColumns.append(.notifications) }
padStates = [:]
}
func addPadFeed(_ feed: CustomFeed) {
guard account != nil, !padColumns.contains(where: { $0.id == feed.id }) else { return }
padColumns.append(PadColumn(feed: feed))
savePadColumns()
}
@discardableResult
func openPadDetail(_ detail: PadColumn.Detail, after sourceID: String? = nil) -> String? {
guard account != nil, !isSigningOut else { return nil }
let insertionIndex: Int
if let sourceID {
guard let source = padColumns.firstIndex(where: { $0.id == sourceID }) else { return nil }
insertionIndex = source + 1
} else {
insertionIndex = padColumns.endIndex
}
let column = PadColumn(detail: detail)
padColumns.insert(column, at: insertionIndex)
return column.id
}
func closePadColumn(id: String) {
guard id != PadColumn.following.id, id != PadColumn.notifications.id,
let column = padColumns.first(where: { $0.id == id })
else { return }
padColumns.removeAll { $0.id == id }
padStates[id] = nil
savePadColumns()
if column.detail == nil { contentInputsChanged() }
}
func movePadColumn(id: String, offset: Int) {
guard let index = padColumns.firstIndex(where: { $0.id == id }), !padColumns.isEmpty else { return }
let target = max(0, min(padColumns.count - 1, index + offset))
guard target != index else { return }
let column = padColumns.remove(at: index)
padColumns.insert(column, at: target)
savePadColumns()
}
func padFeedState(id: String) -> PadFeedState {
if let state = padStates[id] { return state }
let state = PadFeedState(title: padColumns.first(where: { $0.id == id })?.title ?? "")
padStates[id] = state
return state
}
func loadPadFeed(id: String, refresh: Bool = false) async {
guard let column = padColumns.first(where: { $0.id == id }), !column.isNotifications, column.detail == nil,
account != nil, contentPreferences != nil, !isSigningOut, !Task.isCancelled
else { return }
let state = padFeedState(id: id)
guard state.request == nil, refresh || state.posts.isEmpty else { return }
await loadPadPage(column: column, state: state, cursor: nil, refresh: refresh)
}
func retryPadFeed(id: String) async {
if padStates[id]?.retryPage == true {
await loadNextPadFeedPage(id: id)
} else {
await loadPadFeed(id: id, refresh: true)
}
}
func loadNextPadFeedPage(id: String) async {
guard let column = padColumns.first(where: { $0.id == id }), !column.isNotifications, column.detail == nil,
let state = padStates[id], state.request == nil, state.hasMore, let cursor = state.cursor,
account != nil, contentPreferences != nil, !isSigningOut, !Task.isCancelled
else { return }
await loadPadPage(column: column, state: state, cursor: cursor)
}
func loadPadPage(column: PadColumn, state: PadFeedState, cursor: String?, refresh: Bool = false) async {
guard !Task.isCancelled, padStates[column.id] === state, state.request == nil,
account != nil, contentPreferences != nil, !isSigningOut
else { return }
let request = UUID()
let generation = contentGeneration
let session = moderationSession
func isCurrent() -> Bool {
session == moderationSession && generation == contentGeneration && state.request == request
&& padStates[column.id] === state && !Task.isCancelled
}
beginPadRequest(state: state, request: request, cursor: cursor)
defer { finishPadRequest(state: state, request: request) }
let initialIDs = cursor == nil ? Set<String>() : Set(state.rowIDs)
var nextCursor = cursor
var firstPage = cursor == nil
var pagesLoaded = 0
var staged = FeedRefreshBuffer()
do {
repeat {
guard !Task.isCancelled else { return }
let loaded = try await loadPadFeedPage(column: column, cursor: nextCursor)
guard isCurrent() else { return }
let page = excludingDeletedPosts(loaded)
if refresh { nextCursor = stageRefreshPage(page, staged: &staged, nextCursor: nextCursor) }
let incoming = refresh ? staged.page(cursor: nextCursor) : page
try await prepareFeedPage(incoming, isCurrent: isCurrent)
try requireCurrentFeedRequest(isCurrent)
if !refresh {
applyPadPage(page, firstPage: firstPage, nextCursor: nextCursor, state: state)
nextCursor = state.cursor
}
firstPage = false
pagesLoaded += 1
if refresh, hasVisibleStagedPosts(staged) { break }
} while nextCursor != nil && (refresh || !state.rowIDs.contains(where: { !initialIDs.contains($0) }))
&& pagesLoaded < Self.maxFeedPagesPerLoad
if refresh { publishPadRefresh(staged, nextCursor: nextCursor, firstPage: firstPage, state: state) }
} catch {
await failPadLoad(
error, state: state, firstPage: firstPage,
refresh: refresh ? (staged, nextCursor) : nil, isCurrent: isCurrent)
}
}
private func failPadLoad(
_ error: Error, state: PadFeedState, firstPage: Bool, refresh: (FeedRefreshBuffer, String?)?,
isCurrent: () -> Bool
) async {
guard isCurrent(), !NetworkFailure.isCancellation(error) else { return }
if let (staged, cursor) = refresh, !firstPage {
guard (try? await prepareFeedPage(staged.page(cursor: cursor), isCurrent: isCurrent)) != nil,
isCurrent() else { return }
publishPadRefresh(staged, nextCursor: cursor, firstPage: false, state: state)
}
failPadPage(error, state: state, firstPage: firstPage)
}
private func publishPadRefresh(
_ staged: FeedRefreshBuffer, nextCursor: String?, firstPage: Bool, state: PadFeedState
) {
guard !firstPage else { return }
withContentUpdates {
applyMutedPostIDs(staged.muted)
let page = staged.page(cursor: nextCursor)
updatePosts(postsForCacheUpdate(from: page), mergingReplyContexts: staged.contexts)
if state.posts != staged.posts { state.posts = staged.posts }
if state.replyContexts != staged.contexts { state.replyContexts = staged.contexts }
if state.repostedBy != staged.reposts { state.repostedBy = staged.reposts }
state.requestedCursors = staged.cursors
state.cursor = nextCursor
state.hasMore = nextCursor != nil
state.hasLoaded = true
contentInputsChanged()
}
}
private func applyPadPage(_ page: FeedPage, firstPage: Bool, nextCursor: String?, state: PadFeedState) {
withContentUpdates {
applyMutedPostIDs(page.mutedPostIDs)
updatePosts(postsForCacheUpdate(from: page), mergingReplyContexts: page.replyContexts)
if firstPage {
state.requestedCursors = []
state.posts = page.posts
state.replyContexts = page.replyContexts
state.repostedBy = page.repostedBy
} else {
var seen = Set(state.posts.map(\.id))
state.posts.append(contentsOf: page.posts.filter { seen.insert($0.id).inserted })
state.replyContexts.merge(page.replyContexts) { _, new in new }
state.repostedBy.merge(page.repostedBy) { _, new in new }
}
if let nextCursor { state.requestedCursors.insert(nextCursor) }
state.cursor = page.cursor.flatMap { state.requestedCursors.contains($0) ? nil : $0 }
state.hasMore = state.cursor != nil
state.hasLoaded = true
contentInputsChanged()
}
}
private func beginPadRequest(state: PadFeedState, request: UUID, cursor: String?) {
state.request = request
state.errorMessage = nil
state.retryPage = false
if cursor == nil { state.isLoading = true } else { state.isLoadingMore = true }
}
private func finishPadRequest(state: PadFeedState, request: UUID) {
guard state.request == request else { return }
state.request = nil
state.isLoading = false
state.isLoadingMore = false
}
private func failPadPage(_ error: Error, state: PadFeedState, firstPage: Bool) {
state.retryPage = !firstPage && state.cursor != nil
state.errorMessage = NetworkFailure.message(for: error)
}
private func loadPadFeedPage(column: PadColumn, cursor: String?) async throws -> FeedPage {
if let feed = column.feed { return try await service.loadCustomFeed(uri: feed.id, cursor: cursor) }
return try await service.loadFollowingFeed(cursor: cursor)
}
}