Cotton code
408 lines · 18.2 KB · SwiftRaw
// A DAY'S MEASURE as a BRASS POCKET PEDOMETER (Cotton Health, 13 Nov 2026):// the kind clipped to a waistcoat, lying on the honed slate// (`FaceGround.slate`), its bow and crown at the top, a cream enamel dial// under a domed glass.////   THE DIAL: one blued steel hand points to the day's value on a dial that//   tops at a round figure (`reading.dial`, `reading.top`, printed small//   under the twelve); a red lacquer tick on the rim marks the usual, the//   mean of the four weeks before (`reading.usual_dial`). The measure's//   name is printed just above the arbor (`reading.label`), the value large//   below the arbor in its unit (`reading.said`, `reading.unit`), the usual under//   that (`reading.usual`) and the day's least to most where the measure//   has them (`reading.range`).//   THE SUBDIAL, above the arbor: on the night's asleep row, the night's//   stages enamelled round it in four blues, deep to awake, each its share//   of the night (`reading.night.stages`); its time in bed beside it.//   THE RIM: on a day the period is logged, a small rose mark at the top of//   the rim (`reading.flow`), never a screen of its own.//// Under the instrument, chalked on the slate: the day (`date`). Tagged: the// measure (`title`), the value (`amount`), the day (`when`). Stepped by a// tap, it cuts. Print on an object scales with the object, never with// Dynamic Type. Every word is the core's (`DeckCard`, `health_card`): the// face only prints them.import CottonPaperimport CottonValuesimport SwiftUI/// Where the painted instruments' parts lie, as shares of their layers/// (`scripts/paint-health.py` prints them). A repainted instrument owes new/// knobs.enum HealthInstrumentKnobs {    /// A round instrument's layer: its width over its height, the arbor and    /// the dial's radius (a share of the width).    static let roundAspect: CGFloat = 1020.0 / 1230.0    static let arbor = CGPoint(x: 0.5, y: 0.58537)    static let dial: CGFloat = 0.35490    /// The pedometer's subdial and the stopwatch's, both above the arbor:    /// its middle and radius (a share of the width).    static let pedometerSub = CGPoint(x: 0.5, y: 0.46176)    static let stopwatchSub = CGPoint(x: 0.5, y: 0.46176)    static let subRadius: CGFloat = 0.07647    /// The tag's layer, and the bare face its words are engraved in.    static let tagAspect: CGFloat = 720.0 / 1220.0    static let tagFace = CGRect(x: 0.0833, y: 0.40, width: 0.8333, height: 0.5095)    /// The most of the card's room an instrument takes, its tilt, and the    /// share of the card's height kept under it for the chalked words.    static let fill: CGFloat = 0.94    static let turn: Double = -2.0    static let foot: CGFloat = 0.13    static let ink = HealthMaterial.dialInk.colour}/// What a day's measure says on its pedometer.public struct HealthReading: Equatable, Sendable {    public struct Stage: Equatable, Sendable {        public let stage: String        public let label: String        public let said: String        public let share: Double    }    public let measure: String?    public let label: String?    public let said: String?    public let unit: String?    public let usual: String?    public let range: String?    public let top: String?    public let dial: Double?    public let usualDial: Double?    public let flow: String?    public let inBed: String?    public let stages: [Stage]    public let day: String?    public init(_ card: DeckCard) {        var fields: [String: RecordValue] = [:]        if case .object(let object)? = card.fields["reading"] { fields = object }        func word(_ key: String, in fields: [String: RecordValue]) -> String? {            fields[key]?.text.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.flatMap { $0.isEmpty ? nil : $0 }        }        measure = word("measure", in: fields)        label = word("label", in: fields) ?? card.text("title")        self.said = word("said", in: fields) ?? card.text("subtitle")        unit = word("unit", in: fields)        usual = word("usual", in: fields)        range = word("range", in: fields)        top = word("top", in: fields)        dial = fields["dial"]?.number.map { min(max($0, 0), 1) }        usualDial = fields["usual_dial"]?.number.map { min(max($0, 0), 1) }        flow = word("flow", in: fields)        var night: [String: RecordValue] = [:]        if case .object(let object)? = fields["night"] { night = object }        inBed = word("in_bed", in: night)        if case .list(let list)? = night["stages"] {            stages = list.compactMap { value in                guard case .object(let stage) = value, let name = stage["stage"]?.text, let share = stage["share"]?.number else { return nil }                return Stage(stage: name, label: stage["label"]?.text ?? name, said: stage["said"]?.text ?? "", share: share)            }        } else {            stages = []        }        day = card.text("date")    }    /// The colour a night's stage is enamelled in.    static func tone(_ stage: String) -> Color {        switch stage {        case "deep": HealthMaterial.deep.colour        case "core": HealthMaterial.core.colour        case "rem": HealthMaterial.rem.colour        default: HealthMaterial.awake.colour        }    }}public struct HealthPedometerFace: View {    let card: DeckCard    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        let words = HealthReading(card)        HealthInstrument(aspect: HealthInstrumentKnobs.roundAspect, foot: words.day) { size in            PedometerDial(words: words, size: size)        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("health-pedometer")    }}/// An instrument laid on the slate: as large as the card lets it, a hair/// askew, its chalked foot line under it.struct HealthInstrument<Content: View>: View {    let aspect: CGFloat    let foot: String?    @ViewBuilder let content: (CGSize) -> Content    var body: some View {        let knobs = HealthInstrumentKnobs.self        GeometryReader { box in            let room = CGSize(width: box.size.width * knobs.fill, height: box.size.height * (1 - knobs.foot) * knobs.fill)            let height = min(room.height, room.width / aspect)            let size = CGSize(width: height * aspect, height: height)            VStack(spacing: box.size.height * 0.012) {                content(size)                    .frame(width: size.width, height: size.height)                    .rotationEffect(.degrees(knobs.turn))                if let foot {                    Text(verbatim: foot)                        .font(CottonFonts.serif(max(11, size.width * 0.06)))                        .foregroundStyle(HealthMaterial.chalk.colour.opacity(0.88))                        .lineLimit(1)                        .minimumScaleFactor(0.6)                        .accessibilityIdentifier("health-foot")                        .facePart(.when)                }            }            .frame(width: box.size.width, height: box.size.height)        }    }}/// A painted layer at the instrument's size; its bare colour where this/// build carries no pictures.struct HealthLayer: View {    let name: String    let size: CGSize    let bare: Color    var round = true    var body: some View {        if let painted = CottonMedia.image(name, scale: 3) {            painted.resizable().interpolation(.high)                .frame(width: size.width, height: size.height)                .accessibilityHidden(true)        } else if round {            let k = HealthInstrumentKnobs.self            Circle().fill(bare)                .frame(width: size.width * k.dial * 2.36, height: size.width * k.dial * 2.36)                .position(x: k.arbor.x * size.width, y: k.arbor.y * size.height)                .accessibilityHidden(true)        } else {            RoundedRectangle(cornerRadius: size.width * 0.1).fill(bare)                .frame(width: size.width * 0.84, height: size.height * 0.69)                .position(x: size.width / 2, y: size.height * 0.645)                .accessibilityHidden(true)        }    }}/// A hand from the arbor: blued steel, tapered, a round boss over its foot.struct DialHand: View {    /// Its turn from twelve, 0 to 1.    let turn: Double    let length: CGFloat    let width: CGFloat    var colour = HealthMaterial.bluedSteel.colour    var body: some View {        ZStack {            HandShape()                .fill(colour)                .frame(width: width, height: length * 1.2)                .offset(y: -length * 0.4)                .shadow(color: .black.opacity(0.35), radius: width * 0.4, x: width * 0.3, y: width * 0.6)            Circle().fill(colour).frame(width: width * 2.4, height: width * 2.4)        }        .rotationEffect(.degrees(turn * 360))        .accessibilityHidden(true)    }}/// A tapered hand, its tail a sixth of its length behind the arbor.struct HandShape: Shape {    func path(in rect: CGRect) -> Path {        var path = Path()        let tail = rect.height / 6        path.move(to: CGPoint(x: rect.midX, y: rect.minY))        path.addLine(to: CGPoint(x: rect.midX + rect.width / 2, y: rect.maxY - tail))        path.addLine(to: CGPoint(x: rect.midX + rect.width * 0.3, y: rect.maxY))        path.addLine(to: CGPoint(x: rect.midX - rect.width * 0.3, y: rect.maxY))        path.addLine(to: CGPoint(x: rect.midX - rect.width / 2, y: rect.maxY - tail))        path.closeSubpath()        return path    }}/// The glass's highlight over a dial.struct DialGlass: View {    let size: CGSize    var body: some View {        let k = HealthInstrumentKnobs.self        let side = size.width * k.dial * 2 * (744.0 / 724.0)        if let glass = CottonMedia.image("health-glass", scale: 3) {            glass.resizable().interpolation(.high)                .frame(width: side, height: side)                .position(x: k.arbor.x * size.width, y: k.arbor.y * size.height)                .allowsHitTesting(false)                .accessibilityHidden(true)        }    }}private struct PedometerDial: View {    let words: HealthReading    let size: CGSize    var body: some View {        let k = HealthInstrumentKnobs.self        let w = size.width        let r = k.dial * w        let centre = CGPoint(x: k.arbor.x * w, y: k.arbor.y * size.height)        ZStack {            HealthLayer(name: "health-pedometer", size: size, bare: HealthMaterial.brass.colour)            if let top = words.top {                Text(verbatim: top)                    .font(CottonFonts.type(w * 0.034))                    .foregroundStyle(k.ink.opacity(0.8))                    .position(x: centre.x, y: centre.y - r * 0.73)                    .accessibilityIdentifier("health-pedometer-top")            }            if let label = words.label {                Text(verbatim: label.uppercased())                    .font(CottonFonts.cap(w * 0.04))                    .tracking(w * 0.004)                    .foregroundStyle(k.ink)                    .lineLimit(1)                    .minimumScaleFactor(0.5)                    .frame(width: r * 1.3)                    .position(x: centre.x, y: centre.y - r * 0.17)                    .accessibilityIdentifier("health-pedometer-label")                    .facePart(.title)            }            VStack(spacing: w * 0.004) {                if let said = words.said {                    HStack(alignment: .firstTextBaseline, spacing: w * 0.012) {                        Text(verbatim: said)                            .font(CottonFonts.display(w * 0.11))                            .foregroundStyle(k.ink)                            .accessibilityIdentifier("health-pedometer-value")                            .facePart(.amount)                        if let unit = words.unit, !unit.isEmpty {                            Text(verbatim: unit)                                .font(CottonFonts.serif(w * 0.042))                                .foregroundStyle(k.ink.opacity(0.75))                        }                    }                    .lineLimit(1)                    .minimumScaleFactor(0.4)                }                if let usual = words.usual {                    Text(verbatim: usual)                        .font(CottonFonts.serif(w * 0.036))                        .foregroundStyle(HealthMaterial.lacquer.colour)                        .accessibilityIdentifier("health-pedometer-usual")                }                if let range = words.range {                    Text(verbatim: range)                        .font(CottonFonts.type(w * 0.032))                        .foregroundStyle(k.ink.opacity(0.7))                        .accessibilityIdentifier("health-pedometer-range")                }            }            .frame(width: r * 1.5)            .position(x: centre.x, y: centre.y + r * 0.42)            if !words.stages.isEmpty {                NightRing(stages: words.stages, radius: k.subRadius * w)                    .position(x: k.pedometerSub.x * w, y: k.pedometerSub.y * size.height)                if let inBed = words.inBed {                    Text(verbatim: inBed)                        .font(CottonFonts.type(w * 0.03))                        .foregroundStyle(k.ink.opacity(0.75))                        .position(x: k.pedometerSub.x * w + k.subRadius * w * 2.1, y: k.pedometerSub.y * size.height)                        .accessibilityIdentifier("health-pedometer-in-bed")                }            }            if let usual = words.usualDial {                Capsule()                    .fill(HealthMaterial.lacquer.colour)                    .frame(width: w * 0.012, height: r * 0.13)                    .offset(y: -r * 0.86)                    .rotationEffect(.degrees(usual * 360))                    .position(centre)                    .accessibilityIdentifier("health-pedometer-usual-tick")            }            if words.flow != nil {                Circle()                    .fill(HealthMaterial.rose.colour)                    .frame(width: w * 0.03, height: w * 0.03)                    .position(x: centre.x, y: centre.y - r * 1.04)                    .accessibilityIdentifier("health-pedometer-flow")            }            if let dial = words.dial {                DialHand(turn: dial, length: r * 0.84, width: w * 0.022)                    .position(centre)            }            DialGlass(size: size)        }        .frame(width: size.width, height: size.height)    }}/// A night's stages enamelled round a subdial, each its share of the ring.struct NightRing: View {    let stages: [HealthReading.Stage]    let radius: CGFloat    var body: some View {        let total = max(stages.map(\.share).reduce(0, +), 0.0001)        ZStack {            ForEach(Array(stages.enumerated()), id: \.offset) { at, stage in                let start = stages[..<at].map(\.share).reduce(0, +) / total                Circle()                    .trim(from: start, to: start + stage.share / total)                    .stroke(HealthReading.tone(stage.stage), style: StrokeStyle(lineWidth: radius * 0.42, lineCap: .butt))                    .rotationEffect(.degrees(-90))                    .accessibilityLabel(Text(verbatim: "\(stage.label) \(stage.said)"))            }        }        .frame(width: radius * 1.6, height: radius * 1.6)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("health-night")    }}/// A day's measure by its kind, and the days it is reviewed with: invented/// readings only.public enum HealthPedometerFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .slate    public static let face = Face(id: "health.pedometer", specimens: [        Specimen("steps", steps),        Specimen("heart", heart),        Specimen("night", night),        Specimen("period-day", periodDay),        Specimen("bare", bare),    ], steps: .cut) { card, _, _ in        HealthPedometerFace(card: card)    }    static func day(_ reading: [String: RecordValue], date: String = "Thu 12 Nov") -> DeckCard {        DeckCard(face: "health.pedometer", corner: nil, pressing: false, pace: nil, plate: nil,                 fields: ["reading": .object(reading), "date": .text(date), "title": reading["label"] ?? .null])    }    public static let steps = day(["measure": .text("steps"), "label": .text("Steps"), "said": .text("8,123"), "unit": .text("steps"),                                   "usual": .text("usual 10,233"), "top": .text("20,000"), "dial": .number(0.406), "usual_dial": .number(0.512)])    public static let heart = day(["measure": .text("resting_heart_rate"), "label": .text("Resting heart rate"), "said": .text("61"),                                   "unit": .text("bpm"), "usual": .text("usual 63"), "range": .text("58 to 64"), "top": .text("100"),                                   "dial": .number(0.61), "usual_dial": .number(0.63)])    public static let night = day(["measure": .text("sleep_asleep"), "label": .text("Asleep"), "said": .text("5 h 30 min"), "unit": .text(""),                                   "usual": .text("usual 6 h 48 min"), "top": .text("10 h 0 min"), "dial": .number(0.55), "usual_dial": .number(0.68),                                   "night": .object(["in_bed": .text("7 h 10 min"), "stages": .list([                                       .object(["stage": .text("deep"), "label": .text("Deep sleep"), "said": .text("1 h 0 min"), "share": .number(0.18)]),                                       .object(["stage": .text("core"), "label": .text("Core sleep"), "said": .text("3 h 0 min"), "share": .number(0.55)]),                                       .object(["stage": .text("rem"), "label": .text("REM sleep"), "said": .text("1 h 30 min"), "share": .number(0.27)]),                                   ])])])    public static let periodDay = day(["measure": .text("steps"), "label": .text("Steps"), "said": .text("4,210"), "unit": .text("steps"),                                       "usual": .text("usual 7,904"), "top": .text("10,000"), "dial": .number(0.421), "usual_dial": .number(0.79),                                       "flow": .text("Light")], date: "Wed 11 Nov")    public static let bare = day(["label": .text("Cardio fitness")], date: "Tue 10 Nov")}