Cotton code
266 lines · 11.6 KB · SwiftRaw
// The UNLOCK card (12 Nov 2026): an assistant asks// to read sealed tables for a while, and the owner answers on this card. A// permission slip on framed paper: the question typed heavy, who asks under// it in pencil, their reason in hand, then one switch per table on a dotted// rule — each ticked in pencil while it is on — and at the foot the window's// length and how long the ask still waits, struck as stamps, with the queue// behind it small. Every word is the core's (`unlock.card`'s `fields`, by the// face definition's slots in `kits/keys/faces/unlock.json`); the face keeps// one tap of its own, a table's switch (`FaceTaps.flip`), and the shell owns// *Allow* and *Not now*.import CottonPaperimport CottonValuesimport SwiftUIenum UnlockCardFaceKnobs {    static let inset = EdgeInsets(top: 26, leading: 24, bottom: 22, trailing: 22)    static let titleSize: CGFloat = 26    static let shrink: CGFloat = 0.6    static let askerSize: CGFloat = 15    static let askerGap: CGFloat = 8    static let reasonSize: CGFloat = 19    static let reasonLines = 3    static let reasonTop: CGFloat = 14    static let togglesTop: CGFloat = 18    static let toggleSize: CGFloat = 18    static let toggleRow: CGFloat = 10    static let box: CGFloat = 22    static let boxGap: CGFloat = 12    static let lockWidth: CGFloat = 30    static let stampLabel: CGFloat = 14    static let stampGap: CGFloat = 10    static let queueSize: CGFloat = 13    static let turns: [Double] = [-2.5, 1.5]}/// What an unlock card reads off its `DeckCard`.public struct UnlockReading: Equatable, Sendable {    public struct Toggle: Equatable, Sendable {        public let table: String        public let label: String        public let on: Bool    }    public let title: String?    public let asker: String?    public let reason: String?    public let toggles: [Toggle]    public let stamps: [String]    public let queue: String?    public init(_ card: DeckCard) {        title = card.text("title")        asker = card.text("asker")        reason = card.text("reason")        if case .list(let rows)? = card.fields["toggles"] {            toggles = rows.compactMap { row in                guard case .object(let toggle) = row, let table = toggle["table"]?.text, !table.isEmpty else { return nil }                var on = false                if case .bool(let value)? = toggle["on"] { on = value }                return Toggle(table: table, label: toggle["label"]?.text ?? table, on: on)            }        } else {            toggles = []        }        stamps = [card.text("minutes"), card.text("expires")].compactMap { $0 }        queue = card.text("queue")    }}public struct UnlockCardFace: View {    let card: DeckCard    let taps: FaceTaps    public init(card: DeckCard, taps: FaceTaps = .none) {        self.card = card        self.taps = taps    }    private var reading: UnlockReading { UnlockReading(card) }    public var body: some View {        VStack(alignment: .leading, spacing: 0) {            HStack(alignment: .top, spacing: UnlockCardFaceKnobs.boxGap) {                VStack(alignment: .leading, spacing: UnlockCardFaceKnobs.askerGap) {                    if let title = reading.title {                        HeavyType(words: title, size: UnlockCardFaceKnobs.titleSize)                            .lineLimit(4)                            .minimumScaleFactor(UnlockCardFaceKnobs.shrink)                            .fixedSize(horizontal: false, vertical: true)                            .accessibilityIdentifier("deck-title")                            .facePart(.title)                    }                    if let asker = reading.asker {                        Text(asker)                            .font(CottonFonts.type(UnlockCardFaceKnobs.askerSize))                            .lineLimit(2)                            .minimumScaleFactor(UnlockCardFaceKnobs.shrink)                            .faceInk(.pencil)                            .accessibilityIdentifier("unlock-asker")                    }                }                .frame(maxWidth: .infinity, alignment: .leading)                PasskeyLock()                    .frame(width: UnlockCardFaceKnobs.lockWidth, height: UnlockCardFaceKnobs.lockWidth * 1.2)            }            if let reason = reading.reason {                FaceFact(value: reason, hand: true, size: UnlockCardFaceKnobs.reasonSize, lines: UnlockCardFaceKnobs.reasonLines)                    .padding(.top, UnlockCardFaceKnobs.reasonTop)                    .facePart(.body)            }            if !reading.toggles.isEmpty {                VStack(alignment: .leading, spacing: UnlockCardFaceKnobs.toggleRow) {                    DottedRule()                    ForEach(reading.toggles, id: \.table) { toggle in                        UnlockToggleRow(toggle: toggle, flip: taps.flip)                    }                    DottedRule()                }                .padding(.top, UnlockCardFaceKnobs.togglesTop)            }            Spacer(minLength: UnlockCardFaceKnobs.stampGap)            if !reading.stamps.isEmpty {                ChipWrap(spacing: UnlockCardFaceKnobs.stampGap) {                    ForEach(Array(reading.stamps.enumerated()), id: \.offset) { index, words in                        PasskeyStamp(stamp: PasskeyReading.Stamp(label: nil, words: words))                            .rotationEffect(.degrees(UnlockCardFaceKnobs.turns[index % UnlockCardFaceKnobs.turns.count]))                            .accessibilityIdentifier("unlock-stamp-\(index)")                    }                }            }            if let queue = reading.queue {                Text(queue)                    .font(CottonFonts.type(UnlockCardFaceKnobs.queueSize))                    .lineLimit(1)                    .faceInk(.pencil)                    .padding(.top, 8)                    .accessibilityIdentifier("unlock-queue")            }        }        .padding(UnlockCardFaceKnobs.inset)        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)        .onCardPaper(UnlockCardFaceCatalogue.stock.laid(card.pace))    }}/// One table's switch: a pencil box, ticked while on, and the table's name./// Tapped only where the shell hands the face its flip.struct UnlockToggleRow: View {    let toggle: UnlockReading.Toggle    let flip: ((String) -> Void)?    var body: some View {        let drawn = HStack(spacing: UnlockCardFaceKnobs.boxGap) {            UnlockTick(on: toggle.on)                .frame(width: UnlockCardFaceKnobs.box, height: UnlockCardFaceKnobs.box)            Text(toggle.label)                .font(CottonFonts.type(UnlockCardFaceKnobs.toggleSize))                .lineLimit(1)                .minimumScaleFactor(UnlockCardFaceKnobs.shrink)                .faceInk(toggle.on ? .ink : .pencil)                .strikethrough(!toggle.on)            Spacer(minLength: 0)        }        .contentShape(Rectangle())        if let flip {            Button { flip(toggle.table) } label: { drawn }                .buttonStyle(.plain)                .accessibilityLabel(toggle.label)                .accessibilityAddTraits(toggle.on ? .isSelected : [])                .accessibilityIdentifier("unlock-toggle-\(toggle.table)")        } else {            drawn                .accessibilityElement(children: .combine)                .accessibilityAddTraits(toggle.on ? .isSelected : [])                .accessibilityIdentifier("unlock-toggle-\(toggle.table)")        }    }}/// A box drawn in pencil, with a tick through it while on.struct UnlockTick: View {    let on: Bool    @Environment(\.theme) private var theme    var body: some View {        Canvas { context, size in            let ink = theme.print(.pencil)            let line = max(1.3, size.width * 0.07)            let box = CGRect(origin: .zero, size: size).insetBy(dx: line, dy: line)            context.stroke(Path(roundedRect: box, cornerRadius: size.width * 0.12), with: .color(ink), lineWidth: line)            guard on else { return }            var tick = Path()            tick.move(to: CGPoint(x: box.minX + box.width * 0.18, y: box.midY))            tick.addLine(to: CGPoint(x: box.minX + box.width * 0.42, y: box.maxY - box.height * 0.16))            tick.addLine(to: CGPoint(x: box.maxX + box.width * 0.08, y: box.minY - box.height * 0.12))            context.stroke(tick, with: .color(theme.print(.ink)), style: StrokeStyle(lineWidth: line * 1.5, lineCap: .round, lineJoin: .round))        }        .blendMode(theme.printBlend)        .accessibilityHidden(true)    }}/// The unlock card, by the kind's name, and the cards it is reviewed in.public enum UnlockCardFaceCatalogue {    public static let stock: FaceStock = .framed    public static let ground: FaceGround = .paper    public static let face = Face(id: "unlock.card", specimens: [        Specimen("asked", asked),        Specimen("one-off", oneOff),        Specimen("queued", queued),        Specimen("largest", largest),    ]) { card, _, taps in        UnlockCardFace(card: card, taps: taps)    }    static func unlock(_ fields: [String: RecordValue]) -> DeckCard {        DeckCard(face: .unlockCard, fields: fields)    }    static func toggles(_ rows: [(String, String, Bool)]) -> RecordValue {        .list(rows.map { .object(["table": .text($0.0), "label": .text($0.1), "on": .bool($0.2)]) })    }    public static let asked = unlock([        "title": .text("Allow Claude (claude.ai) to read Messages and Notes for 15 minutes?"),        "asker": .text("Claude (claude.ai) · Claude"),        "reason": .text("To find the address Asha sent last week."),        "toggles": toggles([("message", "Messages", true), ("note", "Notes", true)]),        "minutes": .text("15 minutes"),        "expires": .text("Waits 5 more minutes"),    ])    /// One table, no reason given, one table switched off.    public static let oneOff = unlock([        "title": .text("Allow Example Assistant to read Diary for 1 minute?"),        "asker": .text("Example Assistant"),        "toggles": toggles([("diary", "Diary", false)]),        "minutes": .text("1 minute"),        "expires": .text("Waits 1 more minute"),    ])    public static let queued = unlock([        "title": .text("Allow Claude (claude.ai) to read Messages, Notes and Money for 10 minutes?"),        "asker": .text("Claude (claude.ai) · Claude"),        "reason": .text("To total what was spent on the trip."),        "toggles": toggles([("message", "Messages", true), ("note", "Notes", false), ("transaction", "Money", true)]),        "minutes": .text("10 minutes"),        "expires": .text("Waits 3 more minutes"),        "queue": .text("2 more requests wait"),    ])    /// Every place at its longest.    public static let largest = unlock([        "title": .text("Allow The Example Cooperative's Research Assistant to read Messages, Notes, Money, Health records and Sealed diaries for 15 minutes?"),        "asker": .text("The Example Cooperative's Research Assistant · A token named for the long-running research project"),        "reason": .text("A long reason in the assistant's own words: which thread it is looking for, why the sealed tables hold it, and what it will do with what it reads."),        "toggles": toggles([            ("message", "Messages", true), ("note", "Notes", true), ("transaction", "Money", false),            ("health", "Health records", true), ("sealed_diary", "Sealed diaries of the long years", true),        ]),        "minutes": .text("15 minutes"),        "expires": .text("Waits 5 more minutes"),        "queue": .text("12 more requests wait"),    ])}