// 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)importCottonKitimportSwiftUI/// The four places of the bottom bar (IA: Labs · Body · Reports · Settings).enumHealthTab: 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.enumHealthRoute: Hashable {case parameter(JSONValue)case report(String)case metric(JSONValue)}/// What a panel over Health holds.enumHealthSheet: 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 {switchself {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.enumHealthWords {staticfunc line(_ path: String, _ fills: [String: String] = [:]) -> String {ShellLines.line("health", path, fills) }}@MainActor@ObservablefinalclassHealthModel {var look: VaultLook?var tab: HealthTab = .labsvar 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 privatevar 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 = coreself.toasts = toastsVaultFonts.register() }// ── reading ─────────────────────────────────────────────────────────/// The look, once (`health.look` reads no database).func readLook() async {guard look == nilelse { return }do { look = tryawait 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<Answer: Decodable & Sendable>(_ method: String, _ request: JSONValue = .object([:]), as type: Answer.Type) async -> Answer? {do {returntryawait core.call(method, request, as: type) } catchlet error asCottonCallError {Log.write("health: \(method) refused — \(error.code)") toasts.show(error.message, tone: .error) } catch {Log.write("health: \(method) did not read — \(error)") }returnnil }/// The request a place reads with: the person shown (absent: the owner).func personal(_ extra: [String: JSONValue] = [:]) -> JSONValue {var request = JSONValue.object(extra)iflet 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 {guardlet confirm = act.confirm else { returntrue }returnawait withCheckedContinuation { continuation in asking = VaultAsking(confirm: confirm, tone: act.tone) { [weakself] yes inself?.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.requestfor (key, value) in extra { request = request.setting(key, value) }do {returntryawait core.callJSON(act.method, request) } catchlet error asCottonCallError {Log.write("health: \(act.method) refused — \(error.code)") toasts.show(error.message, tone: .error) } catch {Log.write("health: \(act.method) did not answer — \(error)") }returnnil }/// 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 {iflet input = act.input, extra[input.key] == nil { sheet = input.input == "choice" ? .choice(act) : .input(act)return }guardawait confirmed(act) else { return }// Opening a screen sends nothing until it reads its own answer.switch act.method {caseCottonMethod.healthParameter: push(.parameter(act.request))returncaseCottonMethod.healthReport:iflet id = act.request["id"]?.string { push(.report(id)) }returncaseCottonMethod.healthMetric: push(.metric(act.request))returncaseCottonMethod.healthLabs:// A person's chip: their records everywhere. show(act.request["person"]?.string)returncaseCottonMethod.healthAddReport: pickingFor = act.request["person"]?.string picking = truereturncaseCottonMethod.healthAct:switch act.request["act"]?.string {case"connect_apple_health":awaitDeviceReadings.read(.appleHealth, core: core, toasts: toasts) changed()returndefault: break }default: break }guardlet answer = await send(act, adding: extra) else { return }await take(answer, of: act) }/// An answer drawn where its method says.privatefunc take(_ answer: JSONValue, of act: VaultAct) async {// Sign in and Sign out are this device's own flow, as every app opens them.iflet value = answer["value"], value.text("platform_action") == "open_flow" {iflet flow = Self.decode(value, as: RecordKeptFlow.self) { _ = await nativeFlow?(flow) }return }switch act.request["act"]?.string {case"open_pdf":iflet value = Self.decode(answer, as: HealthActAnswer.self)?.value, let key = value.text("key") {open(pdf: key, title: act.label, contentType: value.text("contentType")) }returndefault: break }iflet 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>) {guardcase .success(let urls) = result, let url = urls.first else { return }guardlet path = Self.stage(url) else { toasts.show(HealthWords.line("add.unreadable"), tone: .error)return }iflet 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 = nilvar request = JSONValue.object(["path": .string(path)])for (key, value) in whose { request = request.setting(key, value) }do {let answer = tryawait core.call(CottonMethod.healthAddReport, request, as: HealthAddAnswer.self)let landed = ["added", "updated"].contains(answer.outcome)iflet toast = answer.toast { toasts.show(toast.text, tone: landed ? .success : .notice, window: Self.toastSeconds) }await readPeople() changed()ifletopen = answer.open { tab = .reportsawait run(open) } } catchlet error asCottonCallError {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).staticfunc 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 {tryFileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)tryFileManager.default.copyItem(at: url, to: target)return target.path } catch {Log.write("health: the picked file could not be staged — \(error)")returnnil } }/// The report's own PDF in the one viewer, from the phone's sealed store.privatefuncopen(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() {guardvar path = paths[tab], !path.isEmpty else { return } path.removeLast() paths[tab] = path }staticlet toastSeconds: TimeInterval = 4staticfunc decode<T: Decodable>(_ value: JSONValue, as type: T.Type) -> T? {do {let data = try JSONEncoder().encode(value)returntry JSONDecoder().decode(type, from: data) } catch {Log.write("health: an answer did not read as \(type) — \(error)")returnnil } }}extensionHealthModel {/// Whether this app draws Health: Cotton Health alone.staticvar applies: Bool { FlavourManifest.current?.flavour == "health" }}#endif/// What the app's root holds for Cotton Health: its model on the phone,/// nothing elsewhere.@MainActorfinalclassHealthAppHolder { #if os(iOS)let model: HealthModelinit(model: HealthModel) { self.model = model }var look: VaultLook? { model.look } #elsevar look: VaultLook? { nil } #endif}