Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Knowledge/TimelineModel.swift3// Description: View models of the timeline: the journal of real events (paged, filtered by family, grouped by day; the4// device's copy offline) and the time machine (state of a page or project at a date, with the server's own5// honesty about how exact it is, and restore behind a confirmation).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import Observation11import SPNotesAPI12import SPNotesDocument13import SPNotesStore14import SPNotesSync1516/// The events of one calendar day.17public struct TimelineDay: Identifiable, Sendable, Equatable {18 /// Start of the day.19 public var date: Date20 public var events: [EventRecord]21 public var id: Date { date }22}2324public enum TimelineScope: Sendable, Equatable {25 case workspace26 case page(String)27 case project(String)28}2930@Observable @MainActor31public final class TimelineModel {32 public let scope: TimelineScope33 public private(set) var events: [EventRecord] = []34 public private(set) var phase: LoadPhase = .idle35 public private(set) var freshness: Freshness?36 public private(set) var nextCursor: String?37 public private(set) var isLoadingMore = false38 /// The failure of "load more" (the list stays).39 public var actionFailure: FeatureFailure?40 /// Selected families (`page`, `task`…); empty = everything.41 public private(set) var families: Set<String> = []4243 private let repository: TimelineRepository44 private weak var router: (any FeatureRouter)?45 private let calendar: Calendar46 private let pageSize: Int4748 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, scope: TimelineScope = .workspace, timeZone: TimeZone = .current, pageSize: Int = 50,49 now: @escaping @Sendable () -> Date = { Date() }) {50 repository = repositories.timeline51 self.router = router52 self.scope = scope53 self.pageSize = pageSize54 var calendar = Calendar(identifier: .gregorian)55 calendar.timeZone = timeZone56 self.calendar = calendar57 }5859 public var canLoadMore: Bool { nextCursor != nil }6061 /// Newest day first, newest event first inside a day.62 public var days: [TimelineDay] {63 let grouped = Dictionary(grouping: events) { calendar.startOfDay(for: $0.at) }64 return grouped.keys.sorted(by: >).map { TimelineDay(date: $0, events: grouped[$0]!.sorted { ($0.at, $0.id) > ($1.at, $1.id) }) }65 }6667 private func query(cursor: String?) -> JournalQuery {68 var query = JournalQuery(kinds: families.sorted().map(EventKind.family), limit: pageSize, cursor: cursor)69 switch scope {70 case .workspace: break71 case .page(let id): query.pageId = id72 case .project(let id): query.projectId = id73 }74 return query75 }7677 public func load() async {78 phase = .loading79 do {80 let page = try await repository.events(query(cursor: nil))81 events = page.events82 nextCursor = page.nextCursor83 freshness = page.fetchedAt.map { Freshness(fetchedAt: $0, fromCache: page.source == .cache) }84 phase = .loaded85 } catch {86 phase = .failed(FeatureFailure(error))87 }88 }8990 public func loadMore() async {91 guard let cursor = nextCursor, !isLoadingMore else { return }92 isLoadingMore = true93 actionFailure = nil94 defer { isLoadingMore = false }95 do {96 let page = try await repository.events(query(cursor: cursor), policy: .networkOnly)97 let known = Set(events.map(\.id))98 events += page.events.filter { !known.contains($0.id) }99 nextCursor = page.nextCursor100 } catch {101 actionFailure = FeatureFailure(error)102 }103 }104105 public func toggle(family: String) async {106 if families.contains(family) { families.remove(family) } else { families.insert(family) }107 await load()108 }109110 public func clearFamilies() async {111 guard !families.isEmpty else { return }112 families = []113 await load()114 }115116 public func open(_ event: EventRecord) {117 guard let pageId = event.pageId, event.kind != EventKind.pagePurged else { return }118 router?.openPage(id: pageId, blockId: nil)119 }120121 /// `data.backfilled == true`: reconstructed from older data when 3.0 was deployed, not observed live.122 public nonisolated static func isBackfilled(_ event: EventRecord) -> Bool {123 guard let data = event.data, let json = try? JSONValue(data: data) else { return false }124 return json["backfilled"]?.boolValue == true125 }126127 public nonisolated static func isMachine(_ event: EventRecord) -> Bool { event.actor == EventActor.ai || event.actor == EventActor.agent }128129 public func dayTitle(_ day: TimelineDay, now: Date) -> String {130 if calendar.isDate(day.date, inSameDayAs: now) { return L("Aujourd'hui") }131 if let yesterday = calendar.date(byAdding: .day, value: -1, to: now), calendar.isDate(day.date, inSameDayAs: yesterday) { return L("Hier") }132 return FeatureFormat.day(day.date, timeZone: calendar.timeZone)133 }134135 public func time(_ event: EventRecord) -> String {136 var style = Date.FormatStyle(date: .omitted, time: .shortened)137 style.timeZone = calendar.timeZone138 style.locale = FeatureStrings.locale139 return event.at.formatted(style)140 }141}142143/// How faithful the time machine's answer is for one page, in words. Follows API-NEXT (`source` / `exact`) literally.144public enum TimeMachineHonesty {145 public enum Level: Sendable, Equatable { case exact, approximate, unknown, absent }146147 public static func level(_ page: TimeMachinePage) -> Level {148 if !page.existed { return .absent }149 switch page.source {150 case TimeMachineSource.current: return .exact151 case TimeMachineSource.version, TimeMachineSource.versionAfter: return page.exact == true ? .exact : .approximate152 default: return .unknown153 }154 }155156 public static func text(_ page: TimeMachinePage) -> String {157 if !page.existed { return L("Cette page n'existait pas encore à cette date.") }158 let saved = page.versionAt.map { FeatureFormat.dayTime($0) } ?? "?"159 switch page.source {160 case TimeMachineSource.current:161 return L("Exact : la page n'a pas changé depuis cette date.")162 case TimeMachineSource.version:163 return page.exact == true ? LF("Exact : version enregistrée le %@.", saved)164 : LF("Approximatif : dernière version enregistrée avant cette date (%@). Les modifications faites entre cet enregistrement et la date choisie n'y figurent pas.", saved)165 case TimeMachineSource.versionAfter:166 return LF("Approximatif : aucune version avant cette date ; voici la première enregistrée après (%@), telle que la page était juste avant.", saved)167 default:168 return L("Inconnu : la page existait, mais l'historique ne couvre pas cette date.")169 }170 }171}172173@Observable @MainActor174public final class TimeMachineModel {175 public let scope: TimelineScope176 /// The date shown.177 public private(set) var date: Date178 /// The range of the scrubber.179 public private(set) var range: ClosedRange<Date>180 public private(set) var snapshot: TimeMachineSnapshot?181 public private(set) var phase: LoadPhase = .idle182 public private(set) var freshness: Freshness?183 public var actionFailure: FeatureFailure?184 public private(set) var isRestoring = false185 /// The page awaiting the user's confirmation; nothing is restored before `confirmRestore()`.186 public private(set) var pendingRestore: TimeMachinePage?187 public private(set) var lastRestore: HistoryRestoreResult?188189 private let repository: TimelineRepository190 private weak var router: (any FeatureRouter)?191 private let now: @Sendable () -> Date192193 /// - Parameter scope: `.page` or `.project` (the time machine has no workspace scope).194 public init(repositories: NotesRepositories, router: (any FeatureRouter)? = nil, scope: TimelineScope, date: Date? = nil, now: @escaping @Sendable () -> Date = { Date() }) {195 repository = repositories.timeline196 self.router = router197 self.scope = scope198 self.now = now199 let end = now()200 self.date = date ?? end201 range = end.addingTimeInterval(-90 * 86_400) ... end202 }203204 /// 0 = start of the range, 1 = now.205 public var fraction: Double {206 let span = range.upperBound.timeIntervalSince(range.lowerBound)207 return span <= 0 ? 1 : min(1, max(0, date.timeIntervalSince(range.lowerBound) / span))208 }209210 public nonisolated static func date(fraction: Double, in range: ClosedRange<Date>) -> Date {211 range.lowerBound.addingTimeInterval(range.upperBound.timeIntervalSince(range.lowerBound) * min(1, max(0, fraction)))212 }213214 /// Moves the scrubber without asking the server (call `load()` when the gesture ends).215 public func scrub(to fraction: Double) { date = Self.date(fraction: fraction, in: range) }216217 public func setDate(_ newDate: Date) async {218 date = min(range.upperBound, max(range.lowerBound, newDate))219 await load()220 }221222 public func load() async {223 phase = .loading224 do {225 let cached: Cached<TimeMachineSnapshot>226 switch scope {227 case .page(let id): cached = try await repository.timeMachine(pageId: id, at: date)228 case .project(let id): cached = try await repository.timeMachine(projectId: id, at: date)229 case .workspace: throw RepositoryError.invalid(L("La machine à remonter le temps s'ouvre sur une page ou un projet."))230 }231 snapshot = cached.value232 freshness = Freshness(cached)233 // The journal only exists since 3.0 was deployed: the scrubber does not pretend to go further back with it.234 if let since = cached.value.journalSince, since < range.upperBound, since > range.lowerBound, date >= since { range = since ... range.upperBound }235 phase = .loaded236 } catch {237 phase = .failed(FeatureFailure(error))238 }239 }240241 /// A page can be restored when the server found a history entry for it that differs from the present.242 public nonisolated static func canRestore(_ page: TimeMachinePage) -> Bool {243 page.existed && page.versionId != nil && page.source != TimeMachineSource.current && page.changedSince != false244 }245246 public func requestRestore(_ page: TimeMachinePage) {247 guard Self.canRestore(page) else { return }248 actionFailure = nil249 pendingRestore = page250 }251252 public func cancelRestore() { pendingRestore = nil }253254 @discardableResult255 public func confirmRestore() async -> Bool {256 guard let page = pendingRestore, let versionId = page.versionId, !isRestoring else { return false }257 isRestoring = true258 actionFailure = nil259 defer { isRestoring = false }260 do {261 lastRestore = try await repository.restore(pageId: page.id, versionId: versionId, baseVersion: page.currentVersion)262 pendingRestore = nil263 await load()264 return true265 } catch {266 let failure = FeatureFailure(error)267 actionFailure = failure.code == "conflict"268 ? FeatureFailure(kind: .stale, message: L("La page a été modifiée ailleurs entre-temps. Rechargez puis recommencez."), code: failure.code) : failure269 pendingRestore = nil270 return false271 }272 }273274 public func open(_ page: TimeMachinePage) { router?.openPage(id: page.id, blockId: nil) }275276 /// Plain text of the historical content, for the preview.277 public nonisolated static func previewText(_ page: TimeMachinePage) -> String? {278 guard let raw = page.content, let document = try? NoteDocument(json: raw.data) else { return nil }279 let text = document.plainText().trimmingCharacters(in: .whitespacesAndNewlines)280 return text.isEmpty ? nil : text281 }282}283