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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
import SwiftUI
#if DEBUG
#Preview("Notifications") {
PreviewHost { _ in NotificationsView(isActive: true) }
}
#endif
struct NotificationsView: View {
@AppStorage("notificationMutualsOnly") private var mutualsOnly = false
@AppStorage("notificationExcludedTypes") private var excludedTypesRaw = ""
let isActive: Bool
var scrollToTopRequest = 0
var padColumnControls: ((Bool) -> AnyView)?
var openPadRoute: ((AppRoute) -> Void)?
@Environment(AppModel.self) private var model
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var readError: String?
@State private var path: [AppRoute] = []
@State private var composeRequest: ComposeRequest?
@State private var selectedNotificationGroup: NotificationGroup?
@ScaledMetric(relativeTo: .subheadline) private var notificationQuoteIndent = 7
private var filter: NotificationFilter {
NotificationFilter(mutualsOnly: mutualsOnly, excludedTypesRaw: excludedTypesRaw)
}
private var filteredGroups: [NotificationGroup] {
model.notificationGroups.compactMap { group in
let notifications = group.notifications.filter { filter.includes($0, follows: model.follows($0.author)) }
return notifications.isEmpty ? nil : NotificationGroup(notifications: notifications)
}
}
private var displayedRows: [NotificationGroupState] {
filter.isActive ? filteredGroups.map { NotificationGroupState(group: $0) } : model.notificationRows
}
var body: some View {
let _: Void = ViewUpdateMetrics.record("NotificationsView")
NavigationStack(path: $path) {
content
.appNavigationTitle("Notifications")
.toolbar {
ToolbarItem(placement: .topBarTrailing) { filterMenu }
if let padColumnControls {
ToolbarItem(placement: .topBarLeading) { padColumnControls(true) }
.sharedBackgroundVisibility(.hidden)
ToolbarItem(placement: .topBarTrailing) { padColumnControls(false) }
}
}
.navigationDestination(for: AppRoute.self) { route in
AppRouteDestination(route: route, openRoute: openRoute, openComposer: showComposer)
}
}
.sheet(item: $composeRequest) { request in
ComposerSheet(replyTo: request.replyTo, quotePostID: request.quotePostID)
}
.sheet(item: $selectedNotificationGroup) { group in
NavigationStack {
let accounts = visibleAccounts(in: group)
List {
PeopleListRows(accounts: accounts, rowIdentifierPrefix: "notificationGroupAccount") { authorID in
selectedNotificationGroup = nil
openRoute(.profile(authorID))
}
if accounts.isEmpty {
ContentUnavailableView("No accounts to show", systemImage: "person.2")
.listRowSeparator(.hidden)
}
}
.listStyle(.plain)
.appNavigationTitle(group.notifications[0].reason == .like ? "Liked by" : "Reposted by")
.toolbar { Button("Done") { selectedNotificationGroup = nil } }
}
}
.task(id: isActive && model.contentPreferences != nil) {
if isActive, model.contentPreferences != nil {
await loadAndMarkNotifications(refresh: false)
}
}
.onChange(of: model.contentRevision) { _, _ in
if isActive && (padColumnControls == nil || !model.isRestoringSession) {
Task { await loadAndMarkNotifications(refresh: false) }
}
}
.safeAreaInset(edge: .top) {
if let readError {
HStack {
Text("Could not mark notifications as read: \(readError)")
Button("Try Again") { Task { await loadAndMarkNotifications() } }
}
.appFont(.caption)
.padding(8)
.background(.regularMaterial)
}
}
}
private func visibleAccounts(in group: NotificationGroup) -> [Post.Author] {
let visibleIDs = Set(filteredGroups.flatMap(\.notifications).map(\.id))
var seen: Set<String> = []
return group.notifications.compactMap { notification in
let author = notification.author
guard visibleIDs.contains(notification.id), model.isAccountSummaryVisible(author),
seen.insert(author.id).inserted
else { return nil }
return author
}
}
private var filterMenu: some View {
Menu {
Toggle("Mutuals only", isOn: $mutualsOnly)
Menu("Show Only") {
Toggle(
"All types",
isOn: Binding(
get: { filter.showsAllTypes },
set: { enabled in
if enabled { excludedTypesRaw = "" }
}
))
ForEach(FeedNotification.Reason.allCases, id: \.self) { reason in
Toggle(
reason.filterLabel,
isOn: Binding(
get: { filter.typeIsSelected(reason) },
set: { enabled in
excludedTypesRaw = filter.settingType(reason, enabled: enabled)
}
))
}
}
.menuActionDismissBehavior(.disabled)
} label: {
Image(systemName: "line.3.horizontal.decrease")
.overlay(alignment: .topTrailing) {
if filter.isActive {
Circle().fill(.tint).frame(width: 6, height: 6).offset(x: 4, y: -3)
}
}
}
.accessibilityLabel("Filter notifications")
.accessibilityIdentifier("notificationFilterButton")
}
private func retryNotifications() async {
if model.retryNotificationsPage {
await model.loadNextNotificationsPage()
} else {
await loadAndMarkNotifications()
}
}
private func loadAndMarkNotifications(refresh: Bool = true) async {
let seenAt = Date()
let accepted: Bool
if refresh {
accepted = await model.loadNotifications()
} else {
accepted = await model.loadNotificationsIfNeeded()
}
guard accepted, isActive, !Task.isCancelled else { return }
do {
try await model.markNotificationsRead(seenAt: seenAt)
readError = nil
} catch {
guard !Task.isCancelled, !NetworkFailure.isCancellation(error) else { return }
readError = NetworkFailure.message(for: error)
}
}
private func openRoute(_ route: AppRoute) {
if let openPadRoute { openPadRoute(route) } else { path.append(route) }
}
private func showComposer(replyTo: String?, quotePostID: String?) {
composeRequest = ComposeRequest(replyTo: replyTo, quotePostID: quotePostID)
}
}
extension NotificationsView {
@ViewBuilder
private var content: some View {
let rows = displayedRows
let hasVisibleNotifications = !rows.isEmpty
let isLoading = model.contentPreferences == nil || model.showsNotificationsPlaceholder
let loadingLabel = model.contentPreferences == nil ? "Loading content preferences" : "Loading notifications"
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 !isLoading, let error = model.notificationsErrorMessage, !model.hasLoadedNotifications {
ContentUnavailableView {
Label("Could not load notifications", systemImage: "bell.slash")
} description: {
Text(error)
} actions: {
Button("Try Again") { Task { await retryNotifications() } }
.buttonStyle(.borderedProminent)
}
} else if !isLoading && !hasVisibleNotifications {
VStack {
ContentUnavailableView {
Label("No notifications to show", systemImage: "bell")
} description: {
Text(
filter.isActive
? "No notifications match your filters."
: (model.hasMoreNotifications
? "No visible activity in these pages. You can load older notifications."
: "New activity will appear here."))
} actions: {
if model.hasMoreNotifications {
Button("Load more notifications") { Task { await model.loadNextNotificationsPage() } }
.disabled(model.isLoadingMoreNotifications)
} else {
Button("Refresh") { Task { await loadAndMarkNotifications() } }
}
}
}
} else {
GeometryReader { geometry in
List {
Group {
if isLoading {
PostLoadingPlaceholder(
label: loadingLabel, count: max(1, Int(ceil(geometry.size.height / 108)))
)
.accessibilityIdentifier("initialNotificationLoadingCards")
.listRowInsets(EdgeInsets())
.listRowSeparator(.hidden)
} else {
ForEach(rows) { row in
NotificationRow(
state: row, openRoute: { openRoute($0) }, openComposer: showComposer,
showGroup: { selectedNotificationGroup = $0 }
)
.transition(.opacity)
.listRowSeparator(.hidden)
.listRowInsets(EdgeInsets())
}
}
}
.animation(reduceMotion ? nil : .easeInOut(duration: 0.25), value: isLoading)
if !isLoading && model.hasMoreNotifications {
HStack {
Spacer()
if model.isLoadingMoreNotifications {
ProgressView().accessibilityLabel("Loading more notifications")
} else {
Button("Load more notifications") {
Task { await model.loadNextNotificationsPage() }
}
.buttonStyle(.bordered)
.accessibilityIdentifier("loadMoreNotificationsButton")
}
Spacer()
}
.listRowSeparator(.hidden)
}
}
.listStyle(.plain)
.refreshable { await loadAndMarkNotifications() }
.background {
ScrollRefreshControl(
isRefreshing: isLoading || model.isRefreshingFeed, isActive: isActive,
accessibilityIdentifier: "initialNotificationsRefreshControl",
accessibilityLabel: loadingLabel,
scrollToTopRequest: scrollToTopRequest, allowsScrollToTop: isActive && path.isEmpty
)
.allowsHitTesting(false)
.accessibilityHidden(true)
}
}
}
}
}