Cotton code
131 lines · 6.4 KB · SwiftRaw
// A history drawn: the small trend on a row and the whole history on a// parameter's or a metric's screen. Points come in the canonical unit, oldest// first; the band is the latest reading's own range as the lab printed it.// Colour only for state: a point in its tone's colour, the line and the band// in the look's trend roles.#if os(iOS)import CottonKitimport SwiftUI/// Where points stand on a canvas: days across, values up.struct HealthTrendScale {    let first: Date    let span: TimeInterval    let low: Double    let high: Double    init(_ points: [HealthPoint], band: HealthBand? = nil) {        let days = points.compactMap { HealthTrendScale.date($0.day) }        first = days.min() ?? Date()        span = max((days.max() ?? first).timeIntervalSince(first), 1)        var values = points.flatMap { [$0.value, $0.min, $0.max].compactMap { $0 } }        if let low = band?.low { values.append(low) }        if let high = band?.high { values.append(high) }        let least = values.min() ?? 0        let most = values.max() ?? 1        let pad = max((most - least) * 0.12, abs(most) * 0.02, 0.5)        low = least - pad        high = most + pad    }    func x(_ day: String, width: CGFloat, single: Bool) -> CGFloat {        guard !single, let date = HealthTrendScale.date(day) else { return width / 2 }        return CGFloat(date.timeIntervalSince(first) / span) * width    }    func y(_ value: Double, height: CGFloat) -> CGFloat {        height - CGFloat((value - low) / max(high - low, .ulpOfOne)) * height    }    static func date(_ day: String) -> Date? {        let parts = day.split(separator: "-").compactMap { Int($0) }        guard parts.count == 3 else { return nil }        var calendar = Calendar(identifier: .gregorian)        calendar.timeZone = TimeZone(identifier: "UTC") ?? .current        return calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2]))    }}/// The small trend beside a row: a line through the points, the last one a dot.struct HealthSparkline: View {    let points: [HealthPoint]    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        Canvas { context, size in            guard points.count > 1 else { return }            let scale = HealthTrendScale(points)            var line = Path()            for (i, point) in points.enumerated() {                let at = CGPoint(x: scale.x(point.day, width: size.width, single: false), y: scale.y(point.value, height: size.height))                if i == 0 { line.move(to: at) } else { line.addLine(to: at) }            }            context.stroke(line, with: .color(look.colour("trend_line", scheme)), style: StrokeStyle(lineWidth: look.gap("chart_line"), lineCap: .round, lineJoin: .round))            if let last = points.last {                let at = CGPoint(x: scale.x(last.day, width: size.width, single: false), y: scale.y(last.value, height: size.height))                let r = look.gap("chart_point") / 2                context.fill(Path(ellipseIn: CGRect(x: at.x - r, y: at.y - r, width: 2 * r, height: 2 * r)), with: .color(look.colour(last.tone?.role ?? "trend_point", scheme)))            }        }        .frame(width: look.gap("trend_width"), height: look.gap("trend_height"))        .accessibilityHidden(true)    }}/// A whole history: the lab's band behind, a day's least-to-most where Apple/// Health gives one, the line, each point in its state's colour (a report's/// reading ringed where both sources meet).struct HealthHistoryChart: View {    let points: [HealthPoint]    var band: HealthBand?    @Environment(\.vault) private var look    @Environment(\.colorScheme) private var scheme    var body: some View {        Canvas { context, size in            guard !points.isEmpty else { return }            let scale = HealthTrendScale(points, band: band)            let single = points.count == 1            if let band {                let top = scale.y(band.high ?? scale.high, height: size.height)                let bottom = scale.y(band.low ?? scale.low, height: size.height)                context.fill(Path(CGRect(x: 0, y: top, width: size.width, height: max(bottom - top, 1))), with: .color(look.colour("trend_band", scheme)))            }            let thin = StrokeStyle(lineWidth: look.gap("chart_line") / 2, lineCap: .round)            for point in points {                guard let least = point.min, let most = point.max, most > least else { continue }                let x = scale.x(point.day, width: size.width, single: single)                var whisker = Path()                whisker.move(to: CGPoint(x: x, y: scale.y(least, height: size.height)))                whisker.addLine(to: CGPoint(x: x, y: scale.y(most, height: size.height)))                context.stroke(whisker, with: .color(look.colour("separator", scheme)), style: thin)            }            if points.count > 1 {                var line = Path()                for (i, point) in points.enumerated() {                    let at = CGPoint(x: scale.x(point.day, width: size.width, single: single), y: scale.y(point.value, height: size.height))                    if i == 0 { line.move(to: at) } else { line.addLine(to: at) }                }                context.stroke(line, with: .color(look.colour("trend_line", scheme)), style: StrokeStyle(lineWidth: look.gap("chart_line"), lineCap: .round, lineJoin: .round))            }            let r = look.gap("chart_point") / 2            for point in points {                let at = CGPoint(x: scale.x(point.day, width: size.width, single: single), y: scale.y(point.value, height: size.height))                let dot = Path(ellipseIn: CGRect(x: at.x - r, y: at.y - r, width: 2 * r, height: 2 * r))                let ink = look.colour(point.tone?.role ?? "trend_point", scheme)                if point.source == "lab" && points.contains(where: { $0.source == "apple_health" }) {                    context.fill(dot, with: .color(look.colour("background", scheme)))                    context.stroke(dot, with: .color(ink), style: StrokeStyle(lineWidth: look.gap("xxs")))                } else {                    context.fill(dot, with: .color(ink))                }            }        }        .frame(height: look.gap("chart_height"))        .padding(.vertical, look.gap("s"))        .accessibilityHidden(true)    }}#endif