Repository Public
1// SP Notes iOS2// File: App/ChangeFeed.swift3// Description: Scoped invalidation of the screens. 1.0 had one global `revision` bumped by every store change, so every visible4// query ran again at each autosave of the open note. 2.0 gives each kind of screen its own counter (`.task(id:)`5// key): a store change bumps only the scopes it can affect, and the autosaves of the note being typed are coalesced6// for the lists (they only change a preview and a date). Also debounces the WidgetKit timeline reloads.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPNotesCore1314/// The counters the screens key their queries on. Each is observable on its own (Observation tracks properties separately).15@MainActor16@Observable17final class ChangeFeed {18 /// Lists of notes (order, titles, previews, dates): immediate on a structural change, coalesced for the editor's own autosaves.19 private(set) var lists = 020 /// The set of pages, their hierarchy and flags (sidebar counts, folder tree, move sheet). Not bumped by a content autosave.21 private(set) var structure = 022 private(set) var tags = 023 private(set) var attachments = 024 private(set) var queue = 025 private(set) var conflicts = 026 private(set) var reminders = 027 private(set) var canvases = 028 private(set) var events = 029 private(set) var cache = 030 private(set) var entityQueue = 031 /// Everything, for screens that are never on screen while a note is being typed (history, storage figures).32 private(set) var any = 033 private var entityRevisions: [String: Int] = [:]34 /// Per page, changes that did NOT come from the editor of that page on this device (sync, another window, an extension).35 private var pageRevisions: [String: Int] = [:]3637 /// Bumps of one entity kind (`"task"`, `"edge"`, `"reference"`…: the kinds of the 3.0 feed).38 func entities(_ kind: String) -> Int { entityRevisions[kind] ?? 0 }39 /// External changes of one page (the open editor reloads on it; its own autosaves do not count).40 func page(_ id: String) -> Int { pageRevisions[id] ?? 0 }4142 /// What ran, for the tests and the performance report (not observable).43 struct Stats: Equatable, Sendable {44 /// Store changes received = what the 1.0 global counter would have been bumped by.45 var raw = 046 var lists = 047 var structure = 048 var pages = 049 var other = 050 }51 @ObservationIgnored private(set) var stats = Stats()5253 @ObservationIgnored private let listDelay: Duration54 @ObservationIgnored private var ownSaves: [String: OwnSave] = [:]55 @ObservationIgnored private var pendingLists: Task<Void, Never>?56 @ObservationIgnored private var pendingStructure = false5758 private struct OwnSave { var count: Int; var titleChanged: Bool }5960 init(listDelay: Duration = .milliseconds(1200)) { self.listDelay = listDelay }6162 /// The editor is about to autosave this page: the `.pages` change that follows is its own.63 func expectOwnSave(of pageId: String, titleChanged: Bool) {64 var entry = ownSaves[pageId] ?? OwnSave(count: 0, titleChanged: false)65 entry.count += 166 entry.titleChanged = entry.titleChanged || titleChanged67 ownSaves[pageId] = entry68 }6970 /// The save did not change anything (or failed): no change will come.71 func cancelOwnSave(of pageId: String) {72 guard var entry = ownSaves[pageId] else { return }73 entry.count -= 174 ownSaves[pageId] = entry.count > 0 ? entry : nil75 }7677 func receive(_ change: StoreChange) {78 stats.raw += 179 any &+= 180 switch change {81 case .pages(let ids):82 var external = Set<String>()83 var ownTitle = false84 for id in ids {85 if var entry = ownSaves[id] {86 ownTitle = ownTitle || entry.titleChanged87 entry.count -= 188 ownSaves[id] = entry.count > 0 ? entry : nil89 } else {90 external.insert(id)91 }92 }93 if external.isEmpty {94 // only the text being typed: the lists catch up after a pause; a renamed note also refreshes the trees then95 scheduleLists(structure: ownTitle)96 } else {97 for id in external { pageRevisions[id, default: 0] &+= 1 }98 stats.pages += external.count99 bumpListsNow(structure: true)100 }101 case .tags: tags &+= 1; stats.other += 1102 case .attachments: attachments &+= 1; stats.other += 1103 case .queue: queue &+= 1; stats.other += 1104 case .conflicts: conflicts &+= 1; stats.other += 1105 case .reminders: reminders &+= 1; stats.other += 1106 case .meta: stats.other += 1107 case .entities(let kind, _): entityRevisions[kind, default: 0] &+= 1; stats.other += 1108 case .entityQueue: entityQueue &+= 1; stats.other += 1109 case .canvases: canvases &+= 1; stats.other += 1110 case .events: events &+= 1; stats.other += 1111 case .cache: cache &+= 1; stats.other += 1112 case .reset:113 ownSaves.removeAll()114 for id in pageRevisions.keys { pageRevisions[id, default: 0] &+= 1 }115 for kind in entityRevisions.keys { entityRevisions[kind, default: 0] &+= 1 }116 tags &+= 1; attachments &+= 1; queue &+= 1; conflicts &+= 1; reminders &+= 1; canvases &+= 1; events &+= 1; cache &+= 1; entityQueue &+= 1117 resetGeneration &+= 1118 bumpListsNow(structure: true)119 @unknown default:120 bumpListsNow(structure: true)121 }122 }123124 /// Bumped by `.reset`: screens keyed on a page or an entity kind they never saw before still reload.125 private(set) var resetGeneration = 0126127 private func bumpListsNow(structure alsoStructure: Bool) {128 pendingLists?.cancel()129 pendingLists = nil130 lists &+= 1131 stats.lists += 1132 if alsoStructure || pendingStructure {133 pendingStructure = false134 structure &+= 1135 stats.structure += 1136 }137 }138139 private func scheduleLists(structure alsoStructure: Bool) {140 pendingStructure = pendingStructure || alsoStructure141 pendingLists?.cancel()142 pendingLists = Task { [weak self, listDelay] in143 try? await Task.sleep(for: listDelay)144 guard !Task.isCancelled, let self else { return }145 self.pendingLists = nil146 self.bumpListsNow(structure: false)147 }148 }149150 /// Delivers what is being coalesced now (the editor closes, the app goes to the background).151 func flush() {152 guard pendingLists != nil else { return }153 bumpListsNow(structure: false)154 }155}156157/// Reloads the widget timelines at most once per quiet period instead of at every store change (WidgetKit budgets reloads).158@MainActor159final class WidgetRefresher {160 private let delay: Duration161 private let reload: @MainActor () -> Void162 private var pending: Task<Void, Never>?163 private(set) var reloads = 0164 private(set) var requests = 0165166 init(delay: Duration = .seconds(2), reload: @escaping @MainActor () -> Void) {167 self.delay = delay168 self.reload = reload169 }170171 /// True for the changes a widget can show (notes, tasks, a full reset).172 static func concerns(_ change: StoreChange) -> Bool {173 switch change {174 case .pages, .reset: return true175 case .entities(let kind, _): return kind == "task"176 default: return false177 }178 }179180 func noteChange(_ change: StoreChange) {181 guard Self.concerns(change) else { return }182 requests += 1183 pending?.cancel()184 pending = Task { [weak self, delay] in185 try? await Task.sleep(for: delay)186 guard !Task.isCancelled else { return }187 self?.fire()188 }189 }190191 /// Reloads now when something is waiting (the app leaves the foreground: the Home Screen must be right).192 func flush() { if pending != nil { fire() } }193194 /// Unconditional reload (lock setting changed, sign-out).195 func reloadNow() { fire() }196197 private func fire() {198 pending?.cancel()199 pending = nil200 reloads += 1201 reload()202 }203}204