// Cotton Health's one model: every act a screen shows comes back here as the // core gave it (`VaultAct`, the core's shared Act), after its question when // it has one and its field when it asks one, and its answer is drawn where its // method says. The model decides no screen: it carries answers to them, and // it holds the one person every screen shows (absent: the owner). #if os(iOS) import CottonKit import SwiftUI /// The four places of the bottom bar (IA: Labs · Body · Reports · Settings). enum HealthTab: String, CaseIterable, Hashable, Sendable { case labs, body, reports, settings } /// A screen pushed inside a tab: each reads its own answer with the request /// the act carried. enum HealthRoute: Hashable { case parameter(JSONValue) case report(String) case metric(JSONValue) } /// What a panel over Health holds. enum HealthSheet: Identifiable { /// An act's one field (a name, a date of birth). case input(VaultAct) /// Set sex: female, male, or not said. case choice(VaultAct) /// Whose report a picked PDF is: a kept person or someone new. case whose(path: String) /// Someone new's name, for a picked PDF. case newPerson(path: String) var id: String { switch self { case .input(let act): return "input:\(act.id)" case .choice(let act): return "choice:\(act.id)" case .whose(let path): return "whose:\(path)" case .newPerson(let path): return "new:\(path)" } } } /// The words Health's own controls say that no answer carries (the tabs /// before their answers, Someone new, the sex choices): the kit's `health` /// line set. enum HealthWords { static func line(_ path: String, _ fills: [String: String] = [:]) -> String { ShellLines.line("health", path, fills) } } @MainActor @Observable final class HealthModel { var look: VaultLook? var tab: HealthTab = .labs var paths: [HealthTab: [HealthRoute]] = [:] var sheet: HealthSheet? var asking: VaultAsking? /// The person every screen shows; nil is the owner. var person: String? /// The switcher's people, read again after every change. private(set) var people: HealthPeople? /// Bumped after every act that may change what a screen shows. private(set) var generation = 0 /// The tab titles, as each place's answer names itself. var titles: [HealthTab: String] = [:] /// The document picker is up for an Add a report act. var picking = false /// The person an Add a report act already named. @ObservationIgnored private var pickingFor: String? @ObservationIgnored let core: any CottonCalling @ObservationIgnored let toasts: ToastCenter @ObservationIgnored var viewer: ViewerPresenter? /// This device's own flows (Sign in, Sign out), from the shell. @ObservationIgnored var nativeFlow: (@MainActor (RecordKeptFlow) async -> Bool)? init(core: any CottonCalling, toasts: ToastCenter) { self.core = core self.toasts = toasts VaultFonts.register() } // ── reading ───────────────────────────────────────────────────────── /// The look, once (`health.look` reads no database). func readLook() async { guard look == nil else { return } do { look = try await core.call(CottonMethod.healthLook, EmptyRequest(), as: VaultLook.self) } catch { Log.write("health: the look could not be read — \(error)") } } /// One screen's answer. A refusal is said once and answers nil. func read(_ method: String, _ request: JSONValue = .object([:]), as type: Answer.Type) async -> Answer? { do { return try await core.call(method, request, as: type) } catch let error as CottonCallError { Log.write("health: \(method) refused — \(error.code)") toasts.show(error.message, tone: .error) } catch { Log.write("health: \(method) did not read — \(error)") } return nil } /// The request a place reads with: the person shown (absent: the owner). func personal(_ extra: [String: JSONValue] = [:]) -> JSONValue { var request = JSONValue.object(extra) if let person { request = request.setting("person", .string(person)) } return request } func readPeople() async { people = await read(CottonMethod.healthPeople, personal(), as: HealthPeople.self) } func changed() { generation += 1 } /// Show `id`'s records everywhere; every place reads again, its stack /// back at its root (nothing of one person stands over another's). func show(_ id: String?) { person = id paths = [:] changed() Task { await readPeople() } } // ── acts ──────────────────────────────────────────────────────────── /// Ask an act's question, if it has one. func confirmed(_ act: VaultAct) async -> Bool { guard let confirm = act.confirm else { return true } return await withCheckedContinuation { continuation in asking = VaultAsking(confirm: confirm, tone: act.tone) { [weak self] yes in self?.asking = nil continuation.resume(returning: yes) } } } /// Send one act's request, with what was typed added. Answers the core's /// answer, or nil when it was refused (the refusal said). func send(_ act: VaultAct, adding extra: [String: JSONValue] = [:]) async -> JSONValue? { var request = act.request for (key, value) in extra { request = request.setting(key, value) } do { return try await core.callJSON(act.method, request) } catch let error as CottonCallError { Log.write("health: \(act.method) refused — \(error.code)") toasts.show(error.message, tone: .error) } catch { Log.write("health: \(act.method) did not answer — \(error)") } return nil } /// Run an act end to end: its field, its question, its request, and its /// answer drawn where its method says. func run(_ act: VaultAct, adding extra: [String: JSONValue] = [:]) async { if let input = act.input, extra[input.key] == nil { sheet = input.input == "choice" ? .choice(act) : .input(act) return } guard await confirmed(act) else { return } // Opening a screen sends nothing until it reads its own answer. switch act.method { case CottonMethod.healthParameter: push(.parameter(act.request)) return case CottonMethod.healthReport: if let id = act.request["id"]?.string { push(.report(id)) } return case CottonMethod.healthMetric: push(.metric(act.request)) return case CottonMethod.healthLabs: // A person's chip: their records everywhere. show(act.request["person"]?.string) return case CottonMethod.healthAddReport: pickingFor = act.request["person"]?.string picking = true return case CottonMethod.healthAct: switch act.request["act"]?.string { case "connect_apple_health": await DeviceReadings.read(.appleHealth, core: core, toasts: toasts) changed() return default: break } default: break } guard let answer = await send(act, adding: extra) else { return } await take(answer, of: act) } /// An answer drawn where its method says. private func take(_ answer: JSONValue, of act: VaultAct) async { // Sign in and Sign out are this device's own flow, as every app opens them. if let value = answer["value"], value.text("platform_action") == "open_flow" { if let flow = Self.decode(value, as: RecordKeptFlow.self) { _ = await nativeFlow?(flow) } return } switch act.request["act"]?.string { case "open_pdf": if let value = Self.decode(answer, as: HealthActAnswer.self)?.value, let key = value.text("key") { open(pdf: key, title: act.label, contentType: value.text("contentType")) } return default: break } if let toast = answer["toast"].flatMap({ Self.decode($0, as: VaultToast.self) }) { toasts.show(toast.text, tone: .success, window: Self.toastSeconds) } // Someone added: their records, at once. if act.method == CottonMethod.healthAddPerson, let id = answer.text("person") { show(id) return } await readPeople() changed() } // ── a report from a PDF ───────────────────────────────────────────── /// The picker's file, copied where the core can read it, then whose it /// is: the person the act named, or asked. func picked(_ result: Result<[URL], Error>) { guard case .success(let urls) = result, let url = urls.first else { return } guard let path = Self.stage(url) else { toasts.show(HealthWords.line("add.unreadable"), tone: .error) return } if let person = pickingFor { Task { await add(path: path, whose: ["person": .string(person)]) } } else { sheet = .whose(path: path) } pickingFor = nil } /// `health.addReport {path, person | newPerson}`: its toast, and the /// report opened when one landed. func add(path: String, whose: [String: JSONValue]) async { sheet = nil var request = JSONValue.object(["path": .string(path)]) for (key, value) in whose { request = request.setting(key, value) } do { let answer = try await core.call(CottonMethod.healthAddReport, request, as: HealthAddAnswer.self) let landed = ["added", "updated"].contains(answer.outcome) if let toast = answer.toast { toasts.show(toast.text, tone: landed ? .success : .notice, window: Self.toastSeconds) } await readPeople() changed() if let open = answer.open { tab = .reports await run(open) } } catch let error as CottonCallError { Log.write("health: addReport refused — \(error.code)") toasts.show(error.message, tone: .error) } catch { Log.write("health: addReport did not answer — \(error)") } try? FileManager.default.removeItem(atPath: path) } /// A picked file copied into this app's own temporary folder (the /// picker's URL is lent only while it is open). static func stage(_ url: URL) -> String? { let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } let folder = FileManager.default.temporaryDirectory.appendingPathComponent("health-picked", isDirectory: true) let target = folder.appendingPathComponent(UUID().uuidString).appendingPathExtension("pdf") do { try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) try FileManager.default.copyItem(at: url, to: target) return target.path } catch { Log.write("health: the picked file could not be staged — \(error)") return nil } } /// The report's own PDF in the one viewer, from the phone's sealed store. private func open(pdf key: String, title: String, contentType: String?) { let item = ViewerItem(id: "health/\(key)", kind: .document, key: key, title: title, contentType: contentType ?? "application/pdf") viewer?.open(ViewerSet(items: [item], start: 0)) } // ── navigation ───────────────────────────────────────────────────── func push(_ route: HealthRoute) { paths[tab, default: []].append(route) } func pop() { guard var path = paths[tab], !path.isEmpty else { return } path.removeLast() paths[tab] = path } static let toastSeconds: TimeInterval = 4 static func decode(_ value: JSONValue, as type: T.Type) -> T? { do { let data = try JSONEncoder().encode(value) return try JSONDecoder().decode(type, from: data) } catch { Log.write("health: an answer did not read as \(type) — \(error)") return nil } } } extension HealthModel { /// Whether this app draws Health: Cotton Health alone. static var applies: Bool { FlavourManifest.current?.flavour == "health" } } #endif /// What the app's root holds for Cotton Health: its model on the phone, /// nothing elsewhere. @MainActor final class HealthAppHolder { #if os(iOS) let model: HealthModel init(model: HealthModel) { self.model = model } var look: VaultLook? { model.look } #else var look: VaultLook? { nil } #endif }