Files
RedLintu16andClaude Opus 5.5 64ec524ba0 CrossSound for Apple platforms
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 13:28:34 -07:00

91 lines
3.1 KiB
Swift
Executable File

// NotificationBell — the header's bell: opens Notifications, with a dot while
// the feed holds something newer than what you last saw there.
//
// The dot comes from one tiny request (the newest entry only), made when a
// header appears and every few minutes after. Every tab root draws a header
// and they all appear at launch, so NotificationsState answers them together:
// one request a minute at most, however many bells ask.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
@MainActor
@Observable
final class NotificationsState {
static let shared = NotificationsState()
/// The feed has an entry newer than the last one the page showed.
private(set) var hasUnread = false
private var newest: Date?
@ObservationIgnored private var lastCheck: Date?
/// When the newest entry the page has shown was made (seconds since 1970;
/// 0 = the page was never opened, so anything at all is new).
private static let seenKey = "cs_notifications_seen"
func check(api: SoundCloudAPI) async {
if let lastCheck, Date().timeIntervalSince(lastCheck) < 60 { return }
lastCheck = Date()
// A failed look (offline, signed out) leaves the dot as it was.
guard let page = try? await api.getActivitiesPage(limit: 1),
let date = page.activities.first?.createdAt
else { return }
newest = date
update()
}
/// The page has shown everything up to [date] (its newest entry).
func markSeen(_ date: Date?) {
if let date, date.timeIntervalSince1970 > UserDefaults.standard.double(forKey: Self.seenKey) {
UserDefaults.standard.set(date.timeIntervalSince1970, forKey: Self.seenKey)
}
if let date, newest.map({ date > $0 }) ?? true { newest = date }
update()
}
private func update() {
let seen = UserDefaults.standard.double(forKey: Self.seenKey)
hasUnread = (newest?.timeIntervalSince1970 ?? 0) > seen
}
}
/// The bell itself, sized and styled like the header's other icons.
struct NotificationBell: View {
@Environment(AppServices.self) private var services
private var state = NotificationsState.shared
@ObserveInjection var inject
var body: some View {
AppLink(value: AppDestination.notifications) {
LitPalette { p in
Image(systemName: "bell")
.font(.system(size: 15, weight: .semibold))
.foregroundStyle(p.red)
.frame(width: 32, height: 32)
// Round on purpose: indicator dots are the one round shape left.
.overlay(alignment: .topTrailing) {
if state.hasUnread {
Circle()
.fill(p.red.color)
.frame(width: 8, height: 8)
.offset(x: -6, y: 6)
}
}
.contentShape(Rectangle())
}
}
.buttonStyle(.bareRow())
.help("Notifications")
.accessibilityLabel(state.hasUnread ? "Notifications, new" : "Notifications")
.task {
while !Task.isCancelled {
if services.currentUser != nil { await state.check(api: services.api) }
try? await Task.sleep(for: .seconds(300))
}
}
.enableInjection()
}
}