Cotton code
193 lines · 8.0 KB · SwiftRaw
// The chart face: a table's amounts, numbers or counts by month, week or day,// drawn as bars or a thin ink line on the paper with this period's figure// beside it — no axes. The definition names the chart (`TileLayout.chart`);// the core works out the series (`records.summarize` → `records::chart`),// summing an amount in minor units in one currency, and this only draws it.// Any table's definition — a kit tool's too — draws here with no code of its own.import SwiftUI/// The series the core answers for a chart face: one bucket per period of/// the window, oldest first.public struct ChartSeries: Hashable, Sendable, Codable {    public struct Bucket: Hashable, Sendable, Codable {        /// The period's first day, YYYY-MM-DD.        public var start: String        public var value: Double        /// The value as the core wrote it (`records::page::figure_words`).        public var words: String?        public init(start: String, value: Double, words: String? = nil) {            self.start = start            self.value = value            self.words = words        }    }    /// Rows of the window in a currency the chart does not draw.    public struct LeftOut: Hashable, Sendable, Codable {        public var currency: String?        public var rows: Int    }    public var kind: TileChart.Kind    public var by: TileChart.Period    public var x: String    public var y: String    /// The amounts' currency; nil for a count or a number.    public var currency: String?    public var buckets: [Bucket]    public var total: Double    public var leftOut: [LeftOut]    enum CodingKeys: String, CodingKey {        case kind, by, x, y, currency, buckets, total        case leftOut = "left_out"    }    public init(kind: TileChart.Kind, by: TileChart.Period, x: String, y: String, currency: String? = nil, buckets: [Bucket], total: Double, leftOut: [LeftOut] = []) {        self.kind = kind        self.by = by        self.x = x        self.y = y        self.currency = currency        self.buckets = buckets        self.total = total        self.leftOut = leftOut    }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        kind = try c.decode(TileChart.Kind.self, forKey: .kind)        by = try c.decode(TileChart.Period.self, forKey: .by)        x = try c.decode(String.self, forKey: .x)        y = try c.decode(String.self, forKey: .y)        currency = try c.decodeIfPresent(String.self, forKey: .currency)        buckets = try c.decode([Bucket].self, forKey: .buckets)        total = try c.decode(Double.self, forKey: .total)        leftOut = try c.decodeIfPresent([LeftOut].self, forKey: .leftOut) ?? []    }    /// The period today falls in — the window's last.    public var current: Bucket? { buckets.last }    /// The largest size of any bucket: what a full-height bar stands for.    var scale: Double { buckets.map { abs($0.value) }.max() ?? 0 }    /// One bar per bucket in a box of `size`, standing on its bottom edge, the    /// largest full height; an empty period has no height.    public func bars(in size: CGSize, gap: CGFloat) -> [CGRect] {        guard !buckets.isEmpty else { return [] }        let slot = size.width / CGFloat(buckets.count)        let width = max(slot - gap, 1)        return buckets.enumerated().map { index, bucket in            let height = scale > 0 ? CGFloat(abs(bucket.value) / scale) * size.height : 0            return CGRect(x: CGFloat(index) * slot + (slot - width) * 0.5, y: size.height - height, width: width, height: height)        }    }    /// One point per bucket at the middle of its slot, the largest at the top,    /// an empty period on the bottom edge.    public func plotted(in size: CGSize) -> [CGPoint] {        guard !buckets.isEmpty else { return [] }        let slot = size.width / CGFloat(buckets.count)        return buckets.enumerated().map { index, bucket in            let y = scale > 0 ? abs(bucket.value) / scale : 0            return CGPoint(x: (CGFloat(index) + 0.5) * slot, y: (1 - CGFloat(y)) * size.height)        }    }}/// A tile's chart: the table's own `tile.chart`, over the window ending with/// the period of the reader's today.struct ChartFace: View {    @Environment(\.records) private var store    let definition: TableDefinition    var now: Date = Date()    @State private var series: ChartSeries?    var body: some View {        TimelineView(.periodic(from: now, by: 60)) { context in            let today = Self.day(context.date)            let period = Self.periodKey(context.date, chart: definition.tile.chart)            ChartDrawing(series: series, name: definition.plural)                .task(id: definition.id + period) {                    guard let store else { return }                    series = try? await store.chart(table: definition.id, today: today, at: context.date.ISO8601Format())                }        }    }    static func periodKey(_ date: Date, chart: TileChart?) -> String {        guard chart?.by == .hour else { return day(date) }        let zone = (chart?.timezone).flatMap { TimeZone(identifier: $0) } ?? .gmt        let offset = zone.secondsFromGMT(for: date)        let hour = Int(floor((date.timeIntervalSince1970 + Double(offset)) / 3600))        return "\(hour):\(offset)"    }    /// The reader's calendar day, YYYY-MM-DD.    static func day(_ date: Date, calendar: Calendar = .current) -> String {        let c = calendar.dateComponents([.year, .month, .day], from: date)        return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)    }}/// The drawing itself: the series as bars or a line, past periods in pencil/// and today's in ink, this period's figure beside it.public struct ChartDrawing: View {    @Environment(\.theme) private var theme    let series: ChartSeries?    let name: String    public init(series: ChartSeries?, name: String) {        self.series = series        self.name = name    }    public var body: some View {        HStack(alignment: .bottom, spacing: ChartFaceKnobs.faceChartBarGap) {            GeometryReader { box in                if let series {                    switch series.kind {                    case .bar:                        let bars = series.bars(in: box.size, gap: ChartFaceKnobs.faceChartBarSlotGap)                        Path { path in path.addRects(Array(bars.dropLast())) }                            .fill(theme.print(.pencil))                        Path { path in if let last = bars.last { path.addRect(last) } }                            .fill(theme.print(.ink))                    case .line:                        let points = series.plotted(in: box.size)                        Path { path in                            guard let first = points.first else { return }                            path.move(to: first)                            points.dropFirst().forEach { path.addLine(to: $0) }                        }                        .stroke(theme.print(.ink), style: StrokeStyle(lineWidth: ChartFaceKnobs.faceChartLineWidth, lineCap: .round, lineJoin: .round))                    }                }            }            .frame(height: ChartFaceKnobs.faceChartHeight)            if let series, let current = series.current {                Text(current.words ?? "")                    .font(theme.type.title(theme.scale.titleSize - 2))                    .foregroundStyle(theme.print(.ink))                    .monospacedDigit()                    .lineLimit(1)            }        }        .accessibilityElement(children: .ignore)        .accessibilityLabel(series.flatMap { series in series.current.map { "\(name), \($0.words ?? "")" } } ?? name)    }}/// The sizes, counts and timings ChartFace draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum ChartFaceKnobs {    static let faceChartBarGap: CGFloat = 10    static let faceChartBarSlotGap: CGFloat = 3    static let faceChartHeight: CGFloat = 44    static let faceChartLineWidth: CGFloat = 1.25}