Cotton code
290 lines · 13.9 KB · SwiftRaw
// The QUOTA face (the approved Codex design in ~/lanes/faces/polish:// codex-26), on the core's places: a meter across the card — the quota's// name large, a half-round band washed green to its needle at the share// `used` (of a hundred) and buff past it, the share said large (`share`), the// hours left (`hours_left`), when it resets by hand (`resets_on`) with a// state stamped beside it, and its last readings as a fine line (`trend`).// Every word is the core's (`DeckCard`); the gauge is its numbers.import CottonPaperimport CottonValuesimport SwiftUIpublic struct QuotaFace: View {    let card: DeckCard    @Environment(\.theme) private var theme    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        GeometryReader { sheet in            let width = sheet.size.width - GaugeFacesKnobs.inset.leading - GaugeFacesKnobs.inset.trailing            let points = QuotaReading.points(card)            VStack(spacing: 0) {                if let title = card.text("title") {                    Text(title)                        .font(CottonFonts.type(GaugeFacesKnobs.quotaTitle))                        .lineLimit(2)                        .multilineTextAlignment(.center)                        .fixedSize(horizontal: false, vertical: true)                        .faceInk(.ink)                        .frame(maxWidth: .infinity)                        .accessibilityIdentifier("deck-title")                        .facePart(.title)                }                if let share = card.gaugeShare {                    HalfDial(share: share, marks: GaugeFacesKnobs.marks)                        .frame(width: width, height: width * GaugeFacesKnobs.meterHeight)                        .padding(.top, GaugeFacesKnobs.quotaGap * 2)                    Text(card.text("share") ?? share.formatted(.percent.precision(.fractionLength(0))))                        .font(CottonFonts.type(GaugeFacesKnobs.usedSize))                        .lineLimit(1)                        .minimumScaleFactor(0.7)                        .faceInk(.ink)                        .padding(.top, GaugeFacesKnobs.quotaGap)                }                if let left = card.text("hours_left") ?? card.text("body") {                    Text(left)                        .font(CottonFonts.type(GaugeFacesKnobs.leftSize))                        .lineLimit(1)                        .minimumScaleFactor(0.7)                        .faceInk(.ink)                        .padding(.top, GaugeFacesKnobs.quotaGap / 2)                }                HStack(alignment: .center, spacing: GaugeFacesKnobs.quotaGap) {                    if let reset = card.text("resets_on") ?? card.text("period") {                        Text(HandRun.tail(reset))                            .font(CottonFonts.hand(GaugeFacesKnobs.resetHand))                            .lineLimit(1)                            .minimumScaleFactor(0.7)                            .faceInk(.ink)                            .background(alignment: .bottom) {                                Capsule()                                    .fill(theme.print(.pencil).opacity(GaugeFacesKnobs.underlineOpacity))                                    .frame(height: GaugeFacesKnobs.underline)                                    .rotationEffect(.degrees(GaugeFacesKnobs.underlineTurn))                                    .blendMode(theme.printBlend)                            }                    }                    if let state = card.text("state") {                        RubberStamp(words: state.uppercased(), size: 12, turn: -6)                            .facePart(.state)                    }                }                .padding(.top, GaugeFacesKnobs.quotaGap / 2)                Spacer(minLength: GaugeFacesKnobs.quotaGap)                if points.count > 1 {                    QuotaTrend(points: points)                        .frame(width: width * GaugeFacesKnobs.trendShare, height: GaugeFacesKnobs.trendHeight)                } else if let date = card.text("date") {                    Text([card.label("date"), date].compactMap { $0 }.joined(separator: " "))                        .font(CottonFonts.type(FacePartsKnobs.labelSize + 1))                        .lineLimit(1)                        .faceInk(.pencil)                        .facePart(.when)                }            }            .padding(GaugeFacesKnobs.inset)        }        .onCardPaper(QuotaFaceCatalogue.stock.laid(card.pace))    }}/// A quota's last readings (`trend`, oldest first), each a share of a/// hundred and the share typed.enum QuotaReading {    struct Point: Equatable {        let share: Double        let said: String    }    static func points(_ card: DeckCard) -> [Point] {        guard case .list(let readings)? = card.fields["trend"] else { return [] }        return readings.compactMap { reading -> Point? in            guard case .number(let used) = reading else { return nil }            let share = min(1, max(0, used / 100))            return Point(share: share, said: share.formatted(.percent.precision(.fractionLength(0))))        }    }    /// The readings whose share is typed under the line: every one when    /// they are few, else the first, the middle and the last.    static func typed(_ count: Int) -> Set<Int> {        guard count > GaugeFacesKnobs.trendTypedAll else { return Set(0..<count) }        return [0, (count - 1) / 2, count - 1]    }}/// A quota's last readings as a fine line, a dot at each and its share/// typed under it.struct QuotaTrend: View {    let points: [QuotaReading.Point]    @Environment(\.theme) private var theme    var body: some View {        GeometryReader { box in            let rise = box.size.height - GaugeFacesKnobs.trendLabel - GaugeFacesKnobs.trendDot            let at = { (index: Int) -> CGPoint in                let x = points.count > 1 ? box.size.width * CGFloat(index) / CGFloat(points.count - 1) : box.size.width / 2                return CGPoint(x: x, y: GaugeFacesKnobs.trendDot / 2 + rise * (1 - points[index].share))            }            ZStack(alignment: .topLeading) {                // A soft wash under the line, down to its floor.                Path { path in                    path.move(to: CGPoint(x: at(0).x, y: rise + GaugeFacesKnobs.trendDot / 2))                    for index in points.indices { path.addLine(to: at(index)) }                    path.addLine(to: CGPoint(x: at(points.count - 1).x, y: rise + GaugeFacesKnobs.trendDot / 2))                    path.closeSubpath()                }                .fill(theme.print(.green).opacity(GaugeFacesKnobs.trendWash))                .blendMode(theme.printBlend)                Path { path in                    for index in points.indices {                        if index == 0 { path.move(to: at(index)) } else { path.addLine(to: at(index)) }                    }                }                .stroke(lineWidth: GaugeFacesKnobs.trendLine)                .faceInk(.pencil)                ForEach(points.indices, id: \.self) { index in                    Circle()                        .frame(width: GaugeFacesKnobs.trendDot, height: GaugeFacesKnobs.trendDot)                        .faceInk(.pencil)                        .position(at(index))                    if QuotaReading.typed(points.count).contains(index) {                        Text(points[index].said)                            .font(CottonFonts.type(GaugeFacesKnobs.trendType))                            .lineLimit(1)                            .fixedSize()                            .faceInk(.ink)                            .position(x: at(index).x, y: box.size.height - GaugeFacesKnobs.trendLabel / 2)                    }                }            }        }        .accessibilityHidden(true)    }}/// A half-round meter: a broad watercolour band, green to the share and/// buff past it, a ring of ticks outside it with the scale's marks, a dark/// needle on a brass hub at the share.struct HalfDial: View {    let share: Double    let marks: [String]    @Environment(\.theme) private var theme    var body: some View {        GeometryReader { box in            let radius = min(box.size.width / 2 - GaugeFacesKnobs.markRoom, box.size.height - GaugeFacesKnobs.markRoom / 2)            let centre = CGPoint(x: box.size.width / 2, y: box.size.height - GaugeFacesKnobs.markRoom / 3)            let band = radius * GaugeFacesKnobs.meterBand            let shown = max(0, min(1, share))            ZStack {                let zones = AngularGradient(                    colors: [theme.print(.green), theme.print(.green), theme.faceStocks.buff, theme.print(.red), theme.print(.red)],                    center: UnitPoint(x: centre.x / box.size.width, y: centre.y / box.size.height),                    startAngle: .degrees(180), endAngle: .degrees(360)                )                MeterBand(centre: centre, outer: radius * 0.9, inner: radius * 0.9 - band, from: 0, to: 1)                    .fill(zones)                    .opacity(GaugeFacesKnobs.zoneWash)                    .blur(radius: 0.8)                    .blendMode(theme.printBlend)                MeterBand(centre: centre, outer: radius * 0.9, inner: radius * 0.9 - band, from: 0, to: 1)                    .fill(zones)                    .opacity(GaugeFacesKnobs.zoneWash / 2)                    .offset(x: 0.8, y: -0.6)                    .blendMode(theme.printBlend)                ForEach(0...GaugeFacesKnobs.meterTicks, id: \.self) { tick in                    let angle = Double.pi * (1 - Double(tick) / Double(GaugeFacesKnobs.meterTicks))                    let long = tick % GaugeFacesKnobs.meterMajor == 0                    Path { path in                        path.move(to: CGPoint(x: centre.x + cos(angle) * radius * 0.93, y: centre.y - sin(angle) * radius * 0.93))                        path.addLine(to: CGPoint(x: centre.x + cos(angle) * radius * (long ? 1.02 : 0.98), y: centre.y - sin(angle) * radius * (long ? 1.02 : 0.98)))                    }                    .stroke(theme.print(.ink).opacity(0.8), lineWidth: long ? 1.2 : 0.7)                }                ForEach(Array(marks.enumerated()), id: \.offset) { index, mark in                    let angle = Double.pi * (1 - Double(index) / Double(max(1, marks.count - 1)))                    let reach = radius + GaugeFacesKnobs.markRoom * 0.55                    Text(mark)                        .font(CottonFonts.type(GaugeFacesKnobs.markSize))                        .fixedSize()                        .faceInk(.ink)                        .position(x: centre.x + cos(angle) * reach, y: centre.y - sin(angle) * reach)                }                MeterNeedle(centre: centre, angle: Double.pi * (1 - shown), length: radius * 1.0, width: radius * GaugeFacesKnobs.meterNeedle)                    .fill(theme.print(.red))                    .shadow(color: theme.faceStocks.shadow.opacity(0.3), radius: 1, x: 1, y: 1.2)                Circle()                    .fill(AngularGradient(colors: [theme.faceStocks.buff, theme.faceStocks.shadow.opacity(0.6), theme.faceStocks.buff, theme.faceStocks.shadow.opacity(0.8), theme.faceStocks.buff], center: .center, angle: .degrees(-45)))                    .overlay(Circle().inset(by: radius * GaugeFacesKnobs.meterHub * 0.22).stroke(theme.faceStocks.shadow.opacity(0.5), lineWidth: 0.8))                    .overlay(Circle().stroke(theme.faceStocks.shadow.opacity(0.7), lineWidth: 0.8))                    .frame(width: radius * GaugeFacesKnobs.meterHub, height: radius * GaugeFacesKnobs.meterHub)                    .shadow(color: theme.faceStocks.shadow.opacity(0.35), radius: 1.5, x: 0, y: 1)                    .position(centre)            }        }        .accessibilityHidden(true)    }    /// A stretch of the meter's band, `from` to `to` of its half round.    private struct MeterBand: Shape {        let centre: CGPoint        let outer: CGFloat        let inner: CGFloat        let from: Double        let to: Double        func path(in rect: CGRect) -> Path {            var path = Path()            guard to > from else { return path }            let start = Angle.degrees(180 + 180 * from)            let end = Angle.degrees(180 + 180 * to)            path.addArc(center: centre, radius: outer, startAngle: start, endAngle: end, clockwise: false)            path.addArc(center: centre, radius: inner, startAngle: end, endAngle: start, clockwise: true)            path.closeSubpath()            return path        }    }    /// A slender needle from the hub, tapered to its point.    private struct MeterNeedle: Shape {        let centre: CGPoint        let angle: Double        let length: CGFloat        let width: CGFloat        func path(in rect: CGRect) -> Path {            let tip = CGPoint(x: centre.x + cos(angle) * length, y: centre.y - sin(angle) * length)            let side = CGPoint(x: -sin(angle) * width / 2, y: -cos(angle) * width / 2)            var path = Path()            path.move(to: tip)            path.addLine(to: CGPoint(x: centre.x + side.x, y: centre.y + side.y))            path.addLine(to: CGPoint(x: centre.x - side.x, y: centre.y - side.y))            path.closeSubpath()            return path        }    }}/// The quota face, by the kind's name, and the cards it is reviewed in.public enum QuotaFaceCatalogue {    public static let stock: FaceStock = .framed    public static let ground: FaceGround = .paper    public static let face = Face(id: "quota", specimens: [Specimen("usage", usage)]) { card, _, _ in        QuotaFace(card: card)    }    public static let usage = DeckCard(face: .quota, fields: [        "title": .text("Assistant usage this week"),        "used": .number(62),        "share": .text("62 percent used"),        "hours_left": .text("38 hours left"),        "resets_on": .text("resets Sunday"),        "trend": .list([.number(24), .number(43), .number(62)]),        "date": .text("Thu 22 Oct"),    ])}