Cotton code
368 lines · 16.4 KB · SwiftRaw
// A CALL as a SLIP from the telephone's memory (Cotton Calling, 13 Nov// 2026): the strip a desk telephone's call printer tears off its roll for// each call, lying a hair askew on the calling desk's oxblood leather// (`FaceGround.leatherDesk`). It is paper because the slip IS paper.////   THE SLIP: a printer roll's warm white paper, a narrow strip torn across//   its head and its foot along the tear bar's regular teeth, its shadow on//   the leather.//   ON IT, printed through a two-colour ribbon in the printer's one//   typewriter face: when the call was (`date`, as the core says it), with//   the call's way printed after it (an arrow in for a call that came in,//   out for one made); a dashed rule; the NAME large (`title`), up to three//   lines, and the number under it where the call kept one (`number`); a//   dashed rule; what happened (`state`: "Incoming call", "Missed call"),//   and how long it lasted (`length`); and at the foot how it was made//   (`source`): the Cotton mark printed small for a call made with Cotton,//   else the way's name ("WhatsApp").//   A MISSED call is printed in the ribbon's red, its arrow and its words,//   as the call table's definition says (`red_when` on `outcome_label`://   `missed`, read off the stored value under the state place).//// Tagged: the name (`title`), the day (`when`) and what happened (`state`).// 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`): the face// only prints them.import CottonPaperimport CottonValuesimport SwiftUIenum CallSlipFaceKnobs {    /// The slip's width over its height, and the most of the card's room it    /// takes each way; how far askew it lies.    static let aspect: CGFloat = 0.78    static let fillWidth: CGFloat = 0.88    static let fillHeight: CGFloat = 0.94    static let turn: Double = 1.4    /// The tear bar's teeth along the head and the foot, as shares of the    /// slip's width: how deep, and how far apart.    static let toothDepth: CGFloat = 0.024    static let toothPitch: CGFloat = 0.05    /// The slip's shadow on the leather, in points.    static let shadowRadius: CGFloat = 4    static let shadowDrop: CGFloat = 3    static let shadowWeight: Double = 0.4    // THE PRINT, as shares of the slip's width: the margin, the type's    // sizes (the head, the name, the number, what happened, its length, the    // foot), the name's lines, the dashed rules' dash and weight, and the    // Cotton mark's height.    static let margin: CGFloat = 0.1    static let headSize: CGFloat = 0.06    static let nameSize: CGFloat = 0.115    static let nameLines = 3    static let numberSize: CGFloat = 0.06    static let stateSize: CGFloat = 0.078    static let lengthSize: CGFloat = 0.066    static let footSize: CGFloat = 0.052    static let dash: CGFloat = 0.022    static let ruleWeight: CGFloat = 0.006    static let markHeight: CGFloat = 0.12}/// How a call's card is printed on its slip.public enum CallSlipSetting {    /// The stored values of what happened that the ribbon prints red: the    /// call table's `red_when` on `outcome_label`.    public static let red: Set<String> = ["missed"]    /// The stored values of what happened on a call that came in; every    /// other was made from here.    public static let came: Set<String> = ["incoming", "missed"]    /// The stored way of a call made with Cotton.    public static let cotton = "cotton"    /// The slip prints the call in the ribbon's red.    public static func missed(_ card: DeckCard) -> Bool {        card.stored["state"].map { red.contains($0) } ?? false    }    /// The call's way, printed as an arrow after the day: in, out, or none    /// where the card does not say what happened.    public static func arrow(_ card: DeckCard) -> String? {        guard let state = card.stored["state"] else { return nil }        return came.contains(state) ? "arrow.down.left" : "arrow.up.right"    }    /// The call was made with Cotton: the foot prints the Cotton mark.    public static func madeWithCotton(_ card: DeckCard) -> Bool {        card.stored["source"] == cotton    }    /// The way's name printed at the foot, for a call made any other way.    public static func way(_ card: DeckCard) -> String? {        madeWithCotton(card) ? nil : said(card, "source")    }    /// The number printed under the name: none where the name is the    /// number (a caller the call kept no name for).    public static func number(_ card: DeckCard) -> String? {        guard let number = said(card, "number") else { return nil }        return number == said(card, "title") ? nil : number    }    /// A place's words, trimmed; nil for none.    static func said(_ card: DeckCard, _ slot: String) -> String? {        card.text(slot).map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.flatMap { $0.isEmpty ? nil : $0 }    }}public struct CallSlipFace: View {    let card: DeckCard    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        let knobs = CallSlipFaceKnobs.self        GeometryReader { box in            let width = min(box.size.width * knobs.fillWidth, box.size.height * knobs.fillHeight * knobs.aspect)            let size = CGSize(width: width, height: width / knobs.aspect)            CallSlip(card: card, size: size)                .frame(width: size.width, height: size.height)                .rotationEffect(.degrees(knobs.turn))                .frame(width: box.size.width, height: box.size.height)        }    }}/// The slip's outline: straight down its sides, torn along the tear bar's/// teeth across its head and its foot.struct TornSlip: Shape {    func path(in rect: CGRect) -> Path {        let knobs = CallSlipFaceKnobs.self        let depth = knobs.toothDepth * rect.width        let teeth = max(1, Int((rect.width / (knobs.toothPitch * rect.width)).rounded()))        let pitch = rect.width / CGFloat(teeth)        var path = Path()        path.move(to: CGPoint(x: rect.minX, y: rect.minY + depth))        for i in 0..<teeth {            let x = rect.minX + CGFloat(i) * pitch            path.addLine(to: CGPoint(x: x + pitch / 2, y: rect.minY))            path.addLine(to: CGPoint(x: x + pitch, y: rect.minY + depth))        }        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY - depth))        for i in 0..<teeth {            let x = rect.maxX - CGFloat(i) * pitch            path.addLine(to: CGPoint(x: x - pitch / 2, y: rect.maxY))            path.addLine(to: CGPoint(x: x - pitch, y: rect.maxY - depth))        }        path.closeSubpath()        return path    }}/// A rule the printer strikes in dashes across the slip.private struct SlipRule: View {    let width: CGFloat    var body: some View {        let knobs = CallSlipFaceKnobs.self        Canvas { context, room in            var path = Path()            path.move(to: CGPoint(x: 0, y: room.height / 2))            path.addLine(to: CGPoint(x: room.width, y: room.height / 2))            context.stroke(path, with: .color(CallingMaterial.rule.colour),                           style: StrokeStyle(lineWidth: knobs.ruleWeight * width, dash: [knobs.dash * width, knobs.dash * width * 0.7]))        }        .frame(height: max(1, knobs.ruleWeight * width * 2))        .accessibilityHidden(true)    }}/// The Cotton mark, printed small in the ribbon's black.struct PrintedCottonMark: View {    let height: CGFloat    var body: some View {        let box = CottonMark.contentBounds        Canvas { context, room in            let place = CottonMark.placement(in: room, minimumThread: 0.8, minimumKnot: 1.1)            let ink = GraphicsContext.Shading.color(CallingMaterial.ribbon.colour)            for thread in CottonMark.threads {                var path = Path()                path.move(to: place.at(CottonMark.points[thread.from]))                path.addLine(to: place.at(CottonMark.points[thread.to]))                context.stroke(path, with: ink, style: StrokeStyle(lineWidth: place.threadWidth, lineCap: .round))            }            for point in CottonMark.points where point.isKnot {                let at = place.at(point)                let r = place.knotRadius                context.fill(Path(ellipseIn: CGRect(x: at.x - r, y: at.y - r, width: r * 2, height: r * 2)), with: ink)            }        }        .frame(width: height * box.width / box.height, height: height)    }}/// The slip: its paper, and the call printed on it.private struct CallSlip: View {    let card: DeckCard    let size: CGSize    var body: some View {        let knobs = CallSlipFaceKnobs.self        let w = size.width        let missed = CallSlipSetting.missed(card)        let ink = missed ? CallingMaterial.ribbonRed.colour : CallingMaterial.ribbon.colour        let black = CallingMaterial.ribbon.colour        ZStack {            TornSlip()                .fill(CallingMaterial.slip.colour)                .shadow(color: .black.opacity(knobs.shadowWeight), radius: knobs.shadowRadius, x: knobs.shadowDrop * 0.4, y: knobs.shadowDrop)            // The roll's curl: the paper a shade darker toward its sides.            TornSlip()                .fill(LinearGradient(stops: [                    .init(color: .black.opacity(0.06), location: 0), .init(color: .clear, location: 0.18),                    .init(color: .clear, location: 0.82), .init(color: .black.opacity(0.07), location: 1),                ], startPoint: .leading, endPoint: .trailing))                .accessibilityHidden(true)            VStack(alignment: .leading, spacing: w * 0.035) {                head(ink: ink, black: black)                SlipRule(width: w)                VStack(alignment: .leading, spacing: w * 0.02) {                    if let name = CallSlipSetting.said(card, "title") {                        Text(name)                            .font(CottonFonts.type(knobs.nameSize * w))                            .foregroundStyle(black)                            .lineLimit(knobs.nameLines)                            .minimumScaleFactor(0.6)                            .fixedSize(horizontal: false, vertical: true)                            .accessibilityIdentifier("call-slip-name")                            .facePart(.title)                    }                    if let number = CallSlipSetting.number(card) {                        Text(number)                            .font(CottonFonts.type(knobs.numberSize * w))                            .foregroundStyle(black.opacity(0.8))                            .lineLimit(1)                            .minimumScaleFactor(0.6)                            .accessibilityIdentifier("call-slip-number")                    }                }                Spacer(minLength: 0)                SlipRule(width: w)                VStack(alignment: .leading, spacing: w * 0.015) {                    if let state = CallSlipSetting.said(card, "state") {                        Text(state)                            .font(CottonFonts.type(knobs.stateSize * w))                            .foregroundStyle(ink)                            .lineLimit(1)                            .minimumScaleFactor(0.6)                            .accessibilityIdentifier("call-slip-state")                            .facePart(.state)                    }                    if let length = CallSlipSetting.said(card, "length") {                        Text(length)                            .font(CottonFonts.type(knobs.lengthSize * w))                            .foregroundStyle(black)                            .lineLimit(1)                            .minimumScaleFactor(0.6)                            .accessibilityIdentifier("call-slip-length")                    }                }                foot(black: black)            }            .blendMode(.multiply)            .padding(.horizontal, knobs.margin * w)            .padding(.vertical, (knobs.margin + knobs.toothDepth) * w)            .frame(width: size.width, height: size.height, alignment: .topLeading)        }        .frame(width: size.width, height: size.height)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("call-slip")    }    /// The head: when the call was, and its way as an arrow after it.    private func head(ink: Color, black: Color) -> some View {        let knobs = CallSlipFaceKnobs.self        let w = size.width        return HStack(alignment: .firstTextBaseline, spacing: w * 0.03) {            if let when = CallSlipSetting.said(card, "date") {                Text(when)                    .font(CottonFonts.type(knobs.headSize * w))                    .foregroundStyle(black)                    .lineLimit(1)                    .minimumScaleFactor(0.6)                    .accessibilityIdentifier("call-slip-when")                    .facePart(.when)            }            Spacer(minLength: 0)            if let arrow = CallSlipSetting.arrow(card) {                Image(systemName: arrow)                    .font(CottonFonts.symbol(knobs.headSize * w, weight: .semibold))                    .foregroundStyle(ink)                    .accessibilityHidden(true)            }        }    }    /// The foot: the Cotton mark for a call made with Cotton, else the way's    /// name.    @ViewBuilder private func foot(black: Color) -> some View {        let knobs = CallSlipFaceKnobs.self        let w = size.width        HStack {            Spacer(minLength: 0)            if CallSlipSetting.madeWithCotton(card) {                PrintedCottonMark(height: knobs.markHeight * w)                    .accessibilityElement()                    .accessibilityLabel(Text(CallSlipSetting.said(card, "source") ?? ""))                    .accessibilityIdentifier("call-slip-cotton")            } else if let way = CallSlipSetting.way(card) {                Text(way)                    .font(CottonFonts.type(knobs.footSize * w))                    .foregroundStyle(black.opacity(0.75))                    .lineLimit(1)                    .accessibilityIdentifier("call-slip-way")            }        }    }}/// The slip, by its id, and the calls it is reviewed in: invented people/// and impossible numbers only. The specimen world's now is Friday 13/// November 2026; a call's day is said as the core says it (`ago`).public enum CallSlipFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .leatherDesk    public static let face = Face(id: "call.slip", specimens: [        Specimen("incoming", incoming), Specimen("missed", missed), Specimen("outgoing", outgoing),        Specimen("long-name", longName), Specimen("bare", bare),    ], steps: .cut) { card, _, _ in        CallSlipFace(card: card)    }    static func call(_ fields: [String: RecordValue], state: String?, source: String?) -> DeckCard {        var card = DeckCard(face: "call.slip", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)        if let state { card.stored["state"] = state }        if let source { card.stored["source"] = source }        return card    }    /// A call that came in over Cotton and was answered.    public static let incoming = call([        "title": .text("Mira Kaul"), "date": .text("12 min ago"), "state": .text("Incoming call"),        "length": .text("14 min 5 s"), "source": .text("Cotton"),    ], state: "incoming", source: "cotton")    /// A call that rang over Cotton and was not answered: printed red.    public static let missed = call([        "title": .text("Arjun Rao"), "date": .text("2 h ago"), "state": .text("Missed call"), "source": .text("Cotton"),    ], state: "missed", source: "cotton")    /// A call made and imported from another way, its number kept.    public static let outgoing = call([        "title": .text("Lakeview Clinic"), "number": .text("+1 555 0142"), "date": .text("Wed 11 Nov"),        "state": .text("Outgoing call"), "length": .text("3 min 40 s"), "source": .text("WhatsApp"),    ], state: "outgoing", source: "whatsapp")    /// A name that takes two lines.    public static let longName = call([        "title": .text("Arundhati Venkatalakshmi Krishnamurthy"), "date": .text("Mon 9 Nov"),        "state": .text("No answer"), "source": .text("Cotton"),    ], state: "no answer", source: "cotton")    /// A call that says nothing but who: a caller kept by number alone.    public static let bare = call(["title": .text("+1 555 0199"), "number": .text("+1 555 0199")], state: nil, source: nil)}