import Foundation import RastrilloApple import RastrilloNative import SwiftUI /// What the window can do with its document, from the last detail answer /// (spec §6 rows 1 and 10). A 401 is not here: it pauses input and leaves /// the access alone while the session is re-minted. enum DocsAccess: Equatable, Sendable { case writable case readOnly /// A 403 or 404 from `refreshAccess`: deleted, or no longer shared. case unavailable } /// One row of spec §6's subtitle table, in its precedence order. The first /// that applies wins (`init(...)`). enum DocsSubtitleRow: Equatable, Sendable { case unavailable // 1 case failedHeld // 2 case cannotSaveOnDevice // 3 case tooManyUnsent // 4 case needsSignIn(pending: Int) // 5 case signedOut // 6 case offline(pending: Int) // 7, and 12 is `saved` with the banner case retrying(pending: Int) // 8 case saving // 9 case viewOnly // 10 case saved // 11 and 12 case loading // 13 /// - `savingShown`: the status has not been `.saved` for a whole second /// (the debounce, kept by the view in a `.task`, never in `body`). /// - `loading`: no projection yet. /// /// Row 13 is checked before rows 10 and 11: the table lists it last, but /// a document still loading is "saved" to the outbox, so taken in the /// table's order it could never show. init(access: DocsAccess, status: SyncStatus, savingShown: Bool, loading: Bool) { if access == .unavailable { self = .unavailable; return } switch status { case .failed(_, .held): self = .failedHeld; return case .failed(_, .cannotSaveOnDevice): self = .cannotSaveOnDevice; return case .failed(_, .tooManyUnsent): self = .tooManyUnsent; return case .needsSignIn(let pending): self = pending > 0 ? .needsSignIn(pending: pending) : .signedOut; return case .offline(let pending): self = .offline(pending: pending); return case .retrying(let pending): self = .retrying(pending: pending); return case .saving, .saved: break } if savingShown { self = .saving; return } if loading { self = .loading; return } self = access == .readOnly ? .viewOnly : .saved } /// Red, and the words say what went wrong (rows 1–6). var isNegative: Bool { switch self { case .unavailable, .failedHeld, .cannotSaveOnDevice, .tooManyUnsent, .needsSignIn, .signedOut: return true default: return false } } /// Only row 2 is semibold, as the kit's failed status is. var isEmphasised: Bool { self == .failedHeld } /// The kit's rule (offline, needs sign-in and failed are announced, a /// count change inside one kind is not, saving never is), plus No longer /// available, and View only when it arrives mid-session. static func announces(from old: DocsSubtitleRow, to new: DocsSubtitleRow) -> Bool { if sameKind(old, new) { return false } switch new { case .unavailable, .failedHeld, .cannotSaveOnDevice, .tooManyUnsent, .needsSignIn, .signedOut, .offline: return true case .viewOnly: return old != .loading default: return false } } static func sameKind(_ a: DocsSubtitleRow, _ b: DocsSubtitleRow) -> Bool { switch (a, b) { case (.offline, .offline), (.retrying, .retrying): return true case (.needsSignIn, .needsSignIn), (.needsSignIn, .signedOut), (.signedOut, .needsSignIn), (.signedOut, .signedOut): return true default: return a == b } } } /// Docs' catalog read in one localisation, so a view drawn in Arabic for a /// snapshot says Arabic even though the process runs in English, and the /// kit's sync wording in the same language. struct DocsStrings { let bundle: Bundle let localization: String init(locale: Locale) { let available = DocsResources.bundle.localizations.filter { $0 != "Base" } let chosen = Bundle.preferredLocalizations(from: available, forPreferences: [locale.identifier]).first ?? DocsResources.bundle.preferredLocalizations.first ?? "en" localization = chosen bundle = DocsResources.bundle.path(forResource: chosen, ofType: "lproj").flatMap(Bundle.init(path:)) ?? DocsResources.bundle } func callAsFunction(_ key: String) -> String { bundle.localizedString(forKey: key, value: nil, table: nil) } var sync: NativeSyncStrings { NativeSyncStrings.kit(localization: localization) } /// `native.subtitle.joined` ("%1$@ · %2$@"), looked up as a key and then /// formatted, so a right-to-left language can order the two. func joined(_ first: String?, _ second: String?) -> String { switch (first?.isEmpty == false ? first : nil, second) { case (let first?, let second?): return String(format: self("native.subtitle.joined"), first, second) case (let first?, nil): return first case (nil, let second?): return second case (nil, nil): return "" } } /// The state half of the subtitle, nil when the row says only the team. func state(_ row: DocsSubtitleRow) -> String? { let sync = self.sync switch row { case .unavailable: return self("native.subtitle.unavailable") case .failedHeld: return sync.failed(.held(.tooLarge)) case .cannotSaveOnDevice: return sync.failed(.cannotSaveOnDevice) case .tooManyUnsent: return sync.failed(.tooManyUnsent) case .needsSignIn(let pending): return sync.needsSignIn(pending) case .signedOut: return self("native.subtitle.signedOut") case .offline(let pending): return sync.offline(pending) case .retrying: return sync.retrying case .saving: return sync.saving case .viewOnly: return self("native.subtitle.viewOnly") case .saved: return self("native.subtitle.saved") case .loading: return nil } } func subtitle(team: String?, row: DocsSubtitleRow) -> String { joined(team, state(row)) } } /// The subtitle under the document's title: " · " (spec §6). /// Its own small view, so a sync status change re-evaluates this and /// nothing else: the body that hosts the text view never reads the status. @MainActor struct DocsSubtitleView: View { let model: DocsModel let team: String? /// Whether its changes are announced: false for a copy that is folded /// away while another shows (the iPhone's large title under its bar /// title), so each change is heard once. var announces = true var body: some View { DocsSubtitleBody(status: model.syncStatus, access: model.documentAccess, loading: model.loading, draft: model.isDraft, team: team, announces: announces) } } /// The subtitle given its inputs, holding the "Saving…" debounce and the /// announcements. `observe` hears every row shown (tests). @MainActor struct DocsSubtitleBody: View { let status: SyncStatus let access: DocsAccess let loading: Bool let draft: Bool let team: String? var observe: ((DocsSubtitleRow) -> Void)? = nil var announces = true @Environment(\.locale) private var locale /// The 1 s debounce for row 9, set only from the `.task` below. @State private var savingShown = false @State private var shown: DocsSubtitleRow? var body: some View { let row = DocsSubtitleRow(access: access, status: status, savingShown: savingShown, loading: loading) DocsSubtitleLine(row: row, team: team, strings: DocsStrings(locale: locale)) // Not `.saved` continuously for a second shows "Saving…"; every // return to `.saved` restarts the clock (spec §6, row 9). .task(id: Self.unsettled(status, draft: draft)) { guard Self.unsettled(status, draft: draft) else { savingShown = false; return } try? await Task.sleep(for: .seconds(1)) if !Task.isCancelled { savingShown = true } } .onChange(of: row, initial: true) { old, new in observe?(new) defer { shown = new } // Nothing is announced as the window opens, only changes. guard announces, let previous = shown, previous != new, DocsSubtitleRow.announces(from: old, to: new) else { return } AccessibilityNotification.Announcement(DocsStrings(locale: locale).state(new) ?? "").post() } } static func unsettled(_ status: SyncStatus, draft: Bool) -> Bool { draft || status != .saved } } /// The subtitle's drawing, given its row: muted, or negative (semibold for /// row 2), with an eye for View only. One accessibility element, present /// even when quiet, that updates frequently. struct DocsSubtitleLine: View { let row: DocsSubtitleRow let team: String? let strings: DocsStrings var body: some View { let text = strings.subtitle(team: team, row: row) HStack(spacing: DocsSpacing.sp1) { if row == .viewOnly { Image(systemName: "eye").font(DocsType.font(9, .semibold, ios: .caption2)) #if os(iOS) .imageScale(.small) #endif } Text(verbatim: text.isEmpty ? " " : text) .lineLimit(1) .truncationMode(.tail) } // 11pt; on iPhone and iPad it scales with Dynamic Type, to AX5 (§9). .font(DocsType.font(11, row.isEmphasised ? .semibold : .regular, ios: .caption2)) .foregroundStyle(row.isNegative ? OficinaPalette.negative : OficinaPalette.textMuted) .accessibilityElement(children: .ignore) .accessibilityLabel(Text(verbatim: text)) .accessibilityAddTraits(.updatesFrequently) .accessibilityIdentifier("docs.document.subtitle") } }