Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/Support/FeatureLoad.swift3// Description: What every feature view model shares: the loading phase, a typed failure a view can render calmly4// (offline is a state, not an alarm), and the freshness of a cached read model (`Cached<T>`).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import SPNotesAPI10import SPNotesSync1112/// A failure as the screens show it.13public struct FeatureFailure: Error, Equatable, Sendable {14 public enum Kind: String, Sendable, Equatable {15 /// The server cannot be reached; nothing was queued.16 case offline17 /// Offline and this was never fetched.18 case notCached19 /// The server does not have the feature.20 case unsupported21 case signedOut22 case notFound23 /// The data changed since it was read: reload and ask again.24 case stale25 /// The server said no (`code` is its stable code).26 case server27 case other28 }2930 public var kind: Kind31 /// Localised, ready to show.32 public var message: String33 public var code: String?3435 public init(kind: Kind, message: String, code: String? = nil) {36 self.kind = kind37 self.message = message38 self.code = code39 }4041 public init(_ error: Error) {42 if let failure = error as? FeatureFailure { self = failure; return }43 let mapped = RepositoryError.from(error)44 code = mapped.code45 switch mapped {46 case .offline:47 kind = .offline48 message = L("Hors ligne. Cette action a besoin du serveur ; rien n'a été mis en attente.")49 case .notCached:50 kind = .notCached51 message = L("Hors ligne, et ces données n'ont encore jamais été chargées sur cet appareil.")52 case .unsupported:53 kind = .unsupported54 message = L("Le serveur ne propose pas encore cette fonction.")55 case .signedOut:56 kind = .signedOut57 message = L("La session a expiré. Reconnectez-vous.")58 case .notFound:59 kind = .notFound60 message = L("Cet élément est introuvable ; il a peut-être été supprimé.")61 case .stale:62 kind = .stale63 message = L("Les données ont changé entre-temps. Rechargez puis recommencez.")64 case .server(let api):65 kind = .server66 message = api.message.isEmpty ? L("Le serveur a refusé la demande.") : api.message67 case .invalid(let detail):68 kind = .other69 message = detail70 case .store(let detail):71 kind = .other72 message = LF("Base locale : %@", detail)73 }74 }7576 /// Offline in the wide sense: the network is the reason (render the calm banner, not an error).77 public var isOffline: Bool { kind == .offline || kind == .notCached }78}7980/// The phase of a screen's main load. A screen that already has data keeps showing it while `loading` or `failed`.81public enum LoadPhase: Equatable, Sendable {82 case idle83 case loading84 case loaded85 case failed(FeatureFailure)8687 public var isLoading: Bool { self == .loading }88 public var failure: FeatureFailure? {89 if case .failed(let failure) = self { return failure }90 return nil91 }92}9394/// Where the data on screen comes from and how old it is.95public struct Freshness: Equatable, Sendable {96 public var fetchedAt: Date97 /// True when the server could not be asked and the device's last copy is shown.98 public var fromCache: Bool99100 public init(fetchedAt: Date, fromCache: Bool) {101 self.fetchedAt = fetchedAt102 self.fromCache = fromCache103 }104105 public init<T>(_ cached: Cached<T>) {106 fetchedAt = cached.fetchedAt107 fromCache = cached.source == .cache108 }109110 /// « Mis à jour il y a 3 heures » (relative to `now`).111 public func label(now: Date = Date()) -> String {112 LF("Mis à jour %@", FeatureFormat.relative(fetchedAt, now: now))113 }114}115116/// Date and number formats shared by the screens (deterministic given `now`).117public enum FeatureFormat {118 public static func relative(_ date: Date, now: Date = Date()) -> String {119 let formatter = RelativeDateTimeFormatter()120 formatter.unitsStyle = .full121 formatter.locale = FeatureStrings.locale122 // A date in the future (clock skew, a fixed "now" in renders) is never shown as « dans … ».123 if now.timeIntervalSince(date) < 60 { return L("à l'instant") }124 return formatter.localizedString(for: date, relativeTo: now)125 }126127 public static func day(_ date: Date, timeZone: TimeZone = .current) -> String {128 var style = Date.FormatStyle(date: .abbreviated, time: .omitted)129 style.timeZone = timeZone130 style.locale = FeatureStrings.locale131 return date.formatted(style)132 }133134 public static func dayTime(_ date: Date, timeZone: TimeZone = .current) -> String {135 var style = Date.FormatStyle(date: .abbreviated, time: .shortened)136 style.timeZone = timeZone137 style.locale = FeatureStrings.locale138 return date.formatted(style)139 }140141 /// `mm:ss` (or `h:mm:ss`) of a duration in seconds.142 public static func clock(_ seconds: Double) -> String {143 let total = max(0, Int(seconds.rounded(.down)))144 let h = total / 3600, m = (total % 3600) / 60, s = total % 60145 return h > 0 ? String(format: "%d:%02d:%02d", h, m, s) : String(format: "%02d:%02d", m, s)146 }147}148