Cotton code
539 lines · 22.2 KB · SwiftRaw
// THE BLUE PEN LOOK (assets/design/days/pen.html, chosen by the owner 20 Nov// 2026): a careful person's notebook. Cool light grey ground, dark navy ink,// DM Mono Days throughout (DM Mono with a plain zero and the upright f;// CottonPaper's fonts, the same files Android ships).// One accent, the ballpoint blue, only for today's date, the tick circles,// the marks and the main button. Today's date circled by hand is the one// delight; nothing else is hand-drawn except the marks. No cards, shadows,// gradients or coloured blocks. Every Days screen draws from this file, so a// value here is pen.html's `:root` or one of its rules, by name, and the// same as Android's `days/pen/Pen.kt`.#if os(iOS)import CoreTextimport CottonPaperimport CottonWritingimport SwiftUIimport UIKit/// pen.html's `:root` colours, as the person's Look stands (shared/DECISIONS.md "Look"): the chosen paper's half/// for the phone's appearance, in the chosen ink, from the core's `look` (`LookModel`); before the core has ever/// answered on this phone, pen.html's own. Read inside a screen's body, a change in Look draws the screen again.@MainActorenum Pen {    private static var look: LookModel { LookModel.standing("days") }    /// `--sheet`: every Days screen is drawn on this.    static var sheet: Color { look.colour("sheet", 0xF1F2F6) }    /// `--ground`: what stands behind a sheet raised over Days.    static var ground: Color { look.colour("ground", 0xECEEF2) }    static var ink: Color { look.colour("ink", 0x171C33) }    static var quiet: Color { look.colour("quiet", 0x6B7088) }    static var faint: Color { look.colour("faint", 0xA3A7BA) }    static var rule: Color { look.colour("rule", 0xAAB0C6) }    /// The ink: the ballpoint blue by default.    static var pen: Color { look.colour("accent", 0x1D3FD8) }    static var penSoft: Color { look.colour("accent_soft", 0xDFE4FB) }    static var onPen: Color { look.colour("on_accent", 0xFFFFFF) }    /// The screen's side margin (`.screen` padding 20).    static let side: CGFloat = 20    /// The outline every chip and button is drawn with (`1.5px solid`).    static let stroke: CGFloat = 1.5}/// DM Mono Days (DM Mono, SIL OFL, with a plain zero and the upright f), registered once for the process.enum PenFonts {    static let files = ["DMMonoDays-Light", "DMMonoDays-Regular", "DMMonoDays-Medium"]    private static let registered: [String: String] = {        var names: [String: String] = [:]        for file in files {            guard let url = CottonFonts.file(file, extension: "ttf") else { continue }            _ = CTFontManagerRegisterFontsForURL(url as CFURL, .process, nil)            if let descriptors = CTFontManagerCreateFontDescriptorsFromURL(url as CFURL) as? [CTFontDescriptor],               let first = descriptors.first,               let name = CTFontDescriptorCopyAttribute(first, kCTFontNameAttribute) as? String {                names[file] = name            }        }        return names    }()    static func register() { _ = registered }    static func name(_ file: String) -> String? { registered[file] }}/// pen.html's type. Every size scales with the phone's text size/// (`relativeTo`), so larger text grows the screen rather than clipping it.@MainActorenum PenType {    enum Weight { case light, regular, medium }    /// pen.html's face at `size`, as Look stands: the chosen size's share of it, and DM Mono Days unless another face    /// is chosen (then that face, scaled with the phone's text size).    static func mono(_ size: CGFloat, _ weight: Weight = .regular, relativeTo style: Font.TextStyle = .body) -> Font {        let look = LookModel.standing("days")        let size = size * look.scale        if look.face != "own" {            let drawn = LookFaces.drawn(look.face, own: "mono")            return Font(WritingFonts.font(drawn, size: size, weight: weight == .medium ? .medium : weight == .light ? .light : .regular))        }        PenFonts.register()        let file = switch weight {        case .light: "DMMonoDays-Light"        case .regular: "DMMonoDays-Regular"        case .medium: "DMMonoDays-Medium"        }        if let name = PenFonts.name(file) { return .custom(name, size: size, relativeTo: style) }        return .system(size: size, weight: weight == .medium ? .medium : weight == .light ? .light : .regular, design: .monospaced)    }    /// DM Mono Days itself at `size`, whatever Look's face (the Look screen's own chip for it).    static func own(_ size: CGFloat) -> Font {        PenFonts.register()        return PenFonts.name("DMMonoDays-Regular").map { .custom($0, size: size, relativeTo: .body) } ?? .system(size: size, design: .monospaced)    }    /// `.num`: a day's numeral, Medium (as Android).    static var numeral: Font { mono(58, .medium, relativeTo: .largeTitle) }    /// `.wk`: the weekday and month beside it.    static var weekday: Font { mono(14, relativeTo: .subheadline) }    /// `body`: a row's words.    static var words: Font { mono(15, relativeTo: .body) }    /// `.r .t`: a row's time.    static var time: Font { mono(13, relativeTo: .footnote) }    /// `.r .w small`: the quiet suffix.    static var suffix: Font { mono(12, relativeTo: .caption) }    /// `.fold`, `.more`.    static var fold: Font { mono(12.5, relativeTo: .footnote) }    /// `.nav`: the two-word switch.    static var nav: Font { mono(14, relativeTo: .subheadline) }    static var navOn: Font { mono(14, .medium, relativeTo: .subheadline) }    /// `.grp`: a group's heading, uppercase.    static var group: Font { mono(12, relativeTo: .caption) }    /// `.chip`.    static var chip: Font { mono(12.5, relativeTo: .footnote) }    /// `.btn`.    static var button: Font { mono(13.5, relativeTo: .subheadline) }    /// `.mon`: the month's name on the jump sheet.    static var month: Font { mono(30, relativeTo: .title) }    /// `.mon small`, `.why`.    static var small: Font { mono(13, relativeTo: .footnote) }    /// `.grid span`: a weekday letter.    static var letter: Font { mono(11, relativeTo: .caption2) }    /// `.grid`: a day's number in the month.    static var cell: Font { mono(13, relativeTo: .footnote) }    /// The "+" and the item sheet's title.    static var title: Font { mono(20, relativeTo: .title3) }}/// The faces' own measures, read from the font at the phone's text size, for/// what SwiftUI's layout does not give: where a date's digits stand in their/// line, and the middle of a row's first line.enum PenMetrics {    private static func font(_ file: String, _ size: CGFloat, _ style: UIFont.TextStyle) -> UIFont {        PenFonts.register()        let scaled = UIFontMetrics(forTextStyle: style).scaledValue(for: size)        return PenFonts.name(file).flatMap { UIFont(name: $0, size: scaled) } ?? .monospacedSystemFont(ofSize: scaled, weight: .regular)    }    /// The numeral's line, above its digits (ascender less cap height) and under them (the descender).    static func numeralTrim(_ size: DynamicTypeSize) -> (top: CGFloat, bottom: CGFloat) {        let f = font("DMMonoDays-Medium", 58, .largeTitle)        return (max(0, f.ascender - f.capHeight), max(0, -f.descender))    }    /// From a row's first baseline up to the middle of its capitals.    static func wordsMiddle(_ size: DynamicTypeSize) -> CGFloat {        font("DMMonoDays-Regular", 15, .body).capHeight / 2    }}/// The words of the `days` line set (`ShellLines`), the same as Android's.enum DaysWords {    static func line(_ path: String, _ fills: [String: String] = [:]) -> String {        ShellLines.line("days", path, fills)    }}// MARK: - Drawn things/// Today's circle, drawn by hand in pen (pen.html's path, viewBox 100×70,/// stretched over the numeral with its overhang: left −12, top −8, width/// +22, height +14). The one delight.struct HandCircle: Shape {    func path(in rect: CGRect) -> Path {        let left = rect.minX - 12, top = rect.minY - 8        let w = rect.width + 22, h = rect.height + 14        func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: left + x / 100 * w, y: top + y / 70 * h) }        var path = Path()        path.move(to: p(12, 40))        path.addCurve(to: p(58, 7), control1: p(8, 18), control2: p(34, 6))        path.addCurve(to: p(94, 40), control1: p(84, 8), control2: p(97, 22))        path.addCurve(to: p(44, 64), control1: p(91, 58), control2: p(66, 66))        path.addCurve(to: p(13, 36), control1: p(22, 62), control2: p(9, 52))        path.addCurve(to: p(50, 10), control1: p(16, 22), control2: p(30, 12))        return path    }}/// The thin dotted rule (`border-bottom: 1.5px dotted var(--rule)`).struct DottedRule: View {    var colour: Color = Pen.rule    var body: some View {        GeometryReader { g in            Path { p in                p.move(to: CGPoint(x: 0.75, y: 0.75))                p.addLine(to: CGPoint(x: g.size.width, y: 0.75))            }            .stroke(colour, style: StrokeStyle(lineWidth: 1.5, lineCap: .round, dash: [0.1, 3.3]))        }        .frame(height: 1.5)        .accessibilityHidden(true)    }}/// The pen circle to tick (`.o`, 16 pt, 1.6 pt pen), or the tick once done (`.tick`).struct TickCircle: View {    let done: Bool    var body: some View {        if done {            Text("✓").font(PenType.words).foregroundStyle(Pen.pen).accessibilityHidden(true)        } else {            Circle().strokeBorder(Pen.pen, lineWidth: 1.6).frame(width: 16, height: 16).accessibilityHidden(true)        }    }}/// The small quiet dot (`.d`, 5 pt).struct QuietDot: View {    var size: CGFloat = 5    var body: some View { Circle().fill(Pen.faint).frame(width: size, height: size).accessibilityHidden(true) }}/// The marks' drawings, from the core's catalogue (`days.marks` strokes: one/// source for both phones), kept once read so every row draws from them.@MainActor @Observablefinal class DaysMarkDrawings {    static let shared = DaysMarkDrawings()    private(set) var strokes: [String: [Path]] = [:]    func take(_ catalogue: [DaysCatalogueMark]) {        var out: [String: [Path]] = [:]        for mark in catalogue where !mark.strokes.isEmpty {            let paths = mark.strokes.map(PenStroke.path).filter { !$0.isEmpty }            if !paths.isEmpty { out[mark.id] = paths }        }        strokes = out    }}/// A drawn mark by its catalogue id: its pen strokes from the catalogue,/// drawn as round-capped lines of 1.6 on a 24 by 24 square in pen blue,/// never filled. A mark with no drawing is the quiet dot (CONTRACT §8).struct DrawnMark: View {    let id: String    var size: CGFloat = 24    var body: some View {        let drawings = DaysMarkDrawings.shared        if let strokes = drawings.strokes[id] {            Canvas { context, box in                let scale = min(box.width, box.height) / 24                let at = CGAffineTransform(translationX: (box.width - 24 * scale) / 2, y: (box.height - 24 * scale) / 2).scaledBy(x: scale, y: scale)                for stroke in strokes {                    context.stroke(stroke.applying(at), with: .color(Pen.pen),                                   style: StrokeStyle(lineWidth: 1.6 * scale, lineCap: .round, lineJoin: .round))                }            }            .frame(width: size, height: size)            .accessibilityHidden(true)        } else {            QuietDot()        }    }    /// Whether the mark has a drawing (only drawn marks are ever offered).    static func drawn(_ id: String) -> Bool { DaysMarkDrawings.shared.strokes[id] != nil }    /// The words a mark is said with, for VoiceOver.    static func name(_ id: String) -> String { id.replacingOccurrences(of: "-", with: " ") }}/// One pen stroke as the catalogue writes it: an SVG path (M, L, H, V, C, S,/// Q, T, Z, absolute or relative). Anything it cannot read draws nothing.enum PenStroke {    static func path(_ d: String) -> Path {        var tokens: [String] = []        var number = ""        func flush() { if !number.isEmpty { tokens.append(number); number = "" } }        for ch in d {            if ch.isLetter && ch != "e" && ch != "E" {                flush(); tokens.append(String(ch))            } else if ch == "-" && !number.isEmpty && !(number.hasSuffix("e") || number.hasSuffix("E")) {                flush(); number = "-"            } else if ch == "." && number.contains(".") && !number.contains("e") {                flush(); number = "."            } else if ch.isNumber || ch == "." || ch == "-" || ch == "e" || ch == "E" || ch == "+" {                number.append(ch)            } else {                flush()            }        }        flush()        var path = Path()        var at = CGPoint.zero, start = CGPoint.zero        var lastControl: CGPoint?, lastQuad: CGPoint?        var command: Character = " "        var i = 0        func next() -> CGFloat? {            guard i < tokens.count, let v = Double(tokens[i]) else { return nil }            i += 1            return CGFloat(v)        }        while i < tokens.count {            if let c = tokens[i].first, c.isLetter {                command = c                i += 1                if c == "Z" || c == "z" {                    path.closeSubpath(); at = start; lastControl = nil; lastQuad = nil                    continue                }            } else if command == " " {                return Path()            }            let rel = command.isLowercase            func pt(_ x: CGFloat, _ y: CGFloat) -> CGPoint { rel ? CGPoint(x: at.x + x, y: at.y + y) : CGPoint(x: x, y: y) }            switch command {            case "M", "m":                guard let x = next(), let y = next() else { return Path() }                at = pt(x, y); start = at; path.move(to: at)                command = rel ? "l" : "L"                lastControl = nil; lastQuad = nil            case "L", "l":                guard let x = next(), let y = next() else { return Path() }                at = pt(x, y); path.addLine(to: at)                lastControl = nil; lastQuad = nil            case "H", "h":                guard let x = next() else { return Path() }                at = CGPoint(x: rel ? at.x + x : x, y: at.y); path.addLine(to: at)                lastControl = nil; lastQuad = nil            case "V", "v":                guard let y = next() else { return Path() }                at = CGPoint(x: at.x, y: rel ? at.y + y : y); path.addLine(to: at)                lastControl = nil; lastQuad = nil            case "C", "c":                guard let x1 = next(), let y1 = next(), let x2 = next(), let y2 = next(), let x = next(), let y = next() else { return Path() }                let c1 = pt(x1, y1), c2 = pt(x2, y2), end = pt(x, y)                path.addCurve(to: end, control1: c1, control2: c2)                at = end; lastControl = c2; lastQuad = nil            case "S", "s":                guard let x2 = next(), let y2 = next(), let x = next(), let y = next() else { return Path() }                let c1 = lastControl.map { CGPoint(x: 2 * at.x - $0.x, y: 2 * at.y - $0.y) } ?? at                let c2 = pt(x2, y2), end = pt(x, y)                path.addCurve(to: end, control1: c1, control2: c2)                at = end; lastControl = c2; lastQuad = nil            case "Q", "q":                guard let x1 = next(), let y1 = next(), let x = next(), let y = next() else { return Path() }                let c = pt(x1, y1), end = pt(x, y)                path.addQuadCurve(to: end, control: c)                at = end; lastQuad = c; lastControl = nil            case "T", "t":                guard let x = next(), let y = next() else { return Path() }                let c = lastQuad.map { CGPoint(x: 2 * at.x - $0.x, y: 2 * at.y - $0.y) } ?? at                let end = pt(x, y)                path.addQuadCurve(to: end, control: c)                at = end; lastQuad = c; lastControl = nil            default:                return Path()            }        }        return path    }}/// A row's mark: the tick circle, the drawn mark, or the dot. Never empty.struct MarkView: View {    let mark: DaysMark    var body: some View {        switch mark {        case .tick(let done): TickCircle(done: done)        case .drawn(let id): DrawnMark(id: id)        case .dot: QuietDot()        }    }}/// An outlined capsule (`.chip`), or the pen-soft one standing on (`.chip.on`).struct PenChip: View {    let words: String    var on = false    var name: String?    let tap: () -> Void    var body: some View {        Button(action: tap) {            Text(words)                .font(PenType.chip)                .foregroundStyle(on ? Pen.pen : Pen.ink)                .padding(.horizontal, 11)                .padding(.vertical, 5)                .frame(minHeight: 32)                .background(Capsule().fill(on ? Pen.penSoft : Color.clear))                .overlay(Capsule().strokeBorder(on ? Pen.pen : Pen.ink, lineWidth: Pen.stroke))                .contentShape(Capsule())        }        .buttonStyle(PenPress())        .accessibilityLabel(name ?? words)        .accessibilityAddTraits(on ? .isSelected : [])    }}/// A capsule button (`.btn`), filled with pen when it is the main one (`.btn.go`).struct PenButton: View {    let words: String    var go = false    let tap: () -> Void    var body: some View {        Button(action: tap) {            Text(words)                .font(PenType.button)                .foregroundStyle(go ? Pen.onPen : Pen.ink)                .padding(.horizontal, 16)                .padding(.vertical, 10)                .frame(minHeight: 44)                .background(Capsule().fill(go ? Pen.pen : Color.clear))                .overlay(Capsule().strokeBorder(go ? Pen.pen : Pen.ink, lineWidth: Pen.stroke))                .contentShape(Capsule())        }        .buttonStyle(PenPress())    }}/// The round pen-blue "+" (`.fab`, 56 pt).struct PenPlus: View {    let tap: () -> Void    var body: some View {        Button(action: tap) {            ZStack {                Circle().fill(Pen.pen)                Path { p in                    p.move(to: CGPoint(x: 11, y: 0)); p.addLine(to: CGPoint(x: 11, y: 22))                    p.move(to: CGPoint(x: 0, y: 11)); p.addLine(to: CGPoint(x: 22, y: 11))                }                .stroke(Pen.onPen, style: StrokeStyle(lineWidth: 1.6, lineCap: .round))                .frame(width: 22, height: 22)            }            .frame(width: 56, height: 56)            .contentShape(Circle())        }        .buttonStyle(PenPress())        .accessibilityLabel(DaysWords.line("a11y.add"))    }}/// Back to today (DECISIONS, 21 Nov 2026): a small round button at the/// bottom left, mirroring the "+" at the bottom right: today's date as a/// numeral in pen on the sheet, inside a pen ring as round as the "+" (the/// hand-drawn circle stays the date's own, the one delight). It stands only/// while today is off screen.struct PenToday: View {    let number: String    let tap: () -> Void    var body: some View {        Button(action: tap) {            ZStack {                Circle().fill(Pen.sheet)                Circle().stroke(Pen.pen, lineWidth: 1.6)                Text(verbatim: number)                    .font(PenType.mono(20, .medium, relativeTo: .title3))                    .foregroundStyle(Pen.pen)                    .minimumScaleFactor(0.6)                    .lineLimit(1)                    .padding(.horizontal, 8)            }            .frame(width: 56, height: 56)            .contentShape(Circle())        }        .buttonStyle(PenPress())        .accessibilityLabel(DaysWords.line("a11y.back_today"))    }}/// The small uppercase heading over a group (`.grp`), its count at the right.struct PenGroupHeading: View {    let name: String    var count: String?    var first = false    var body: some View {        VStack(spacing: 0) {            HStack(alignment: .lastTextBaseline) {                Text(name.uppercased()).font(PenType.group).tracking(12 * 0.08).foregroundStyle(Pen.quiet)                Spacer(minLength: 8)                if let count { Text(count).font(PenType.group).tracking(12 * 0.08).foregroundStyle(Pen.quiet) }            }            .padding(.top, first ? 4 : 16)            .padding(.bottom, 4)            DottedRule()        }        .padding(.bottom, 6)        .accessibilityElement(children: .combine)        .accessibilityAddTraits(.isHeader)    }}/// A label over a value on a sheet, drawn as a group heading's words.struct PenFieldLabel: View {    let words: String    var body: some View {        Text(words.uppercased()).font(PenType.group).tracking(0.96).foregroundStyle(Pen.quiet)            .padding(.top, 14).padding(.bottom, 4)            .accessibilityAddTraits(.isHeader)    }}/// A press in the pen look: the thing dims a little, no ripple, no lift.struct PenPress: ButtonStyle {    func makeBody(configuration: Configuration) -> some View {        configuration.label.opacity(configuration.isPressed ? 0.55 : 1)    }}/// Wraps its children into lines, as the page's `flex-wrap` chips do.struct PenFlow: Layout {    var spacing: CGFloat = 10    var lineSpacing: CGFloat = 8    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {        let width = proposal.width ?? .infinity        var x: CGFloat = 0, y: CGFloat = 0, line: CGFloat = 0, widest: CGFloat = 0        for view in subviews {            let size = view.sizeThatFits(.unspecified)            if x > 0 && x + size.width > width { y += line + lineSpacing; x = 0; line = 0 }            x += size.width + spacing            line = max(line, size.height)            widest = max(widest, x - spacing)        }        return CGSize(width: min(widest, width), height: y + line)    }    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {        var x = bounds.minX, y = bounds.minY, line: CGFloat = 0        for view in subviews {            let size = view.sizeThatFits(.unspecified)            if x > bounds.minX && x + size.width > bounds.maxX { y += line + lineSpacing; x = bounds.minX; line = 0 }            line = max(line, size.height)            view.place(at: CGPoint(x: x, y: y + (line - size.height) / 2), proposal: ProposedViewSize(size))            x += size.width + spacing        }    }}#endif