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 = [] 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) } } } } }