Cotton code
365 lines · 17.2 KB · SwiftRaw
// The object that stands on a card — a field's or an act's.//// The architect's ruling of 13 Oct 2026: every object on a card is in ONE// style, the flat enamel of Home's caps — a small object on the card's paper,// centred, never photographed stationery or a tear-off pad. Most are generated// pictures (`CardEnamel`, `scripts/gen-cards/make_enamel_objects.py`); the rest// are the value itself, drawn: a date is the calendar's month leaf with// its day, a status an ink ring filled when done, a number its figure, words// their first words, a link the linked tool's cap, a person their print.// `CardObject` names which, as data, and `CardObjectView` draws it in the// square the card gives it.import CottonValuesimport SwiftUI/// The generated enamel objects. The raw value is the imageset's name less its/// `object-` prefix.enum CardEnamel: String, CaseIterable, Sendable {    // Fields.    case clock, bell, pin, flame, file, picture, link, person    case repeats = "repeat"    // Acts.    case done, snooze, move, share, agent, bin, archive, open, edit    case phone, message, mail, star, pushpin, retry, restore, copy, camera    case group, bookmark, flag    /// A chat over a phone number (WhatsApp) and the pictures someone posts    /// (Instagram) — each drawn as what it is, never the app's mark.    case chat, lens    /// A bell that will not ring (Mute), and this phone (Keep on this phone)    /// — never the pushpin, which is Pin's.    case muted, device    /// Generated device kinds, separate from Call's handset.    case devicePhone = "device-phone"    case mac, linux    /// Junk: the envelope crossed out; Block sender: a raised hand — never    /// the bin, which is Delete's and Bin's alone (architect, r7).    case junk, block    /// Hide: an eye struck through — a held message hidden from your copy,    /// never the bin (architect, r8).    case hidden    /// Revoke: the link's two links pulled apart, a red break between them —    /// never Make the link's chain (one object per act).    case unlink    /// Only you: a closed padlock — a record held for its owner alone; never    /// the person, which is a field's and Call's.    case lock    var asset: String { "object-\(rawValue)" }    /// The object a definition names (`"object": "bell"`), when it is one.    static func named(_ name: String?) -> CardEnamel? {        guard let name else { return nil }        switch name {        // The names the first card kit's definitions used for its objects.        case "ring": return .repeats        case "note": return .edit        case "arrow.triangle.2.circlepath": return .repeats        default: return CardEnamel(rawValue: name)        }    }}enum CardObject: Equatable, Sendable {    static func named(_ word: String, cards: ThemeCards) -> CardObject? {        let name = cards.objects[word] ?? word        if name == "ring" { return .ring(filled: false) }        if name == "check" { return .enamel(.done) }        if name == "gauge" { return .gauge }        return CardEnamel.named(name).map(CardObject.enamel)    }    case gauge    /// The calendar's month leaf: the month on its band, the day under    /// it; neither for an empty date.    case leaf(day: Int?, month: String?)    /// The clock face with its hands at the time; no hands for an empty time.    case clock(ClockTime?)    /// One of the generated enamel objects.    case enamel(CardEnamel)    case tool(name: String, picture: ToolPicture?)    /// The value itself set large — a number is its own object.    case figure(String)    /// Words are their own first words, in handwriting.    case words(String)    /// A status: an ink ring, filled when the record is done.    case ring(filled: Bool)    /// A tool's or a project's cap, printed with its name.    case cap(name: String, colour: CapColour)    /// A cap nobody has picked yet: the cap alone, no plus.    case emptyCap    /// People, as their prints, the first in front.    case people([CardPerson])    /// A polaroid of a stored picture, or an empty print.    case print(key: String?, seed: String)}struct CardObjectView: View {    @Environment(\.theme) private var theme    let object: CardObject    /// The square the card gives the object.    let side: CGFloat    var body: some View {        drawn            .frame(width: side, height: side)            .accessibilityHidden(true)    }    @ViewBuilder private var drawn: some View {        switch object {        case .gauge:            Image(systemName: "gauge.with.dots.needle.33percent")                .resizable()                .scaledToFit()                .foregroundStyle(theme.print(.ink))                .frame(width: side * CardObjectKnobs.cardObjectEnamelSide, height: side * CardObjectKnobs.cardObjectEnamelSide)        case .leaf(let day, let month):            CardMonthLeaf(day: day, month: month, side: side * CardObjectKnobs.cardObjectLeafSideFraction)        case .clock(let time):            enamel(.clock) {                if let time {                    let hands = CardEnamelPrint.hands(time)                    // Where the live hands sit on the clock picture, in unit                    // coordinates of its square — measured off the generated                    // pictures, so a regenerated clock owes new keys.                    let reach = CardObjectKnobs.cardObjectClockReach                    hand(                        length: reach * CardObjectKnobs.cardObjectClockHourHandLength,                        width: CardObjectKnobs.cardObjectClockHourHandWidth, degrees: hands.hour)                    hand(                        length: reach * CardObjectKnobs.cardObjectClockMinuteHandLength,                        width: CardObjectKnobs.cardObjectClockMinuteHandWidth, degrees: hands.minute)                }            }        case .enamel(let picture):            enamel(picture) { EmptyView() }        case .tool(let name, let picture):            ToolObject(name: name, picture: picture, printing: .contentOnly,                       side: side, imageVariant: .small)        case .figure(let text):            Text(text)                .font(theme.type.display(InkFit.figureSize(text, face: theme.type.display,                    preferred: side * CardObjectKnobs.cardObjectFigureTypeFraction,                    width: side * CardObjectKnobs.cardObjectFigureWidth, scale: theme.scale)))                .foregroundStyle(theme.print(.ink).opacity(Double(CardObjectKnobs.cardObjectFigureInkOpacity)))                .lineLimit(1)                .fixedSize(horizontal: true, vertical: true)                .frame(width: side * CardObjectKnobs.cardObjectFigureWidth)        case .words(let words):            // A name of a word or two is set large, as its own object, wrapping            // to a second line before it shrinks; a longer run of words smaller,            // three lines at most. Never cut off: `InkFit` sizes it so every            // line's ink, the hand's last swash included, stands inside.            let name = words.count <= CardObjectKnobs.cardObjectWordsNameMaxCharacters            let width = side * CardObjectKnobs.cardObjectWordsWidth            let lines = name ? CardObjectKnobs.cardObjectWordsNameLines : CardObjectKnobs.cardObjectWordsSentenceLines            // The phone's Text clips ink at its own typographic bounds, and the            // hand's last letter leans past its advance (Hyderabad's final d            // drew as an a): a hair space at each end puts that ink inside the            // bounds, measured by InkFit exactly as it is drawn.            let room = CardObjectKnobs.cardObjectWordsInkRoom            let set = InkFit.set(                words, face: theme.type.hand,                preferred: side * (name ? CardObjectKnobs.cardObjectWordsShortTypeFraction : CardObjectKnobs.cardObjectWordsLongTypeFraction),                width: width, lines: lines, padded: room, scale: theme.scale)            let size = set.size            Text(room + set.words + room)                .accessibilityLabel(words)                .font(theme.type.hand(size))                .foregroundStyle(theme.print(.ink).opacity(Double(CardObjectKnobs.cardObjectWordsInkOpacity)))                .multilineTextAlignment(.center)                .fixedSize(horizontal: false, vertical: true)                .frame(width: width, height: side * CardObjectKnobs.cardObjectWordsHeight)        case .ring(let filled):            ZStack {                if filled {                    Circle().fill(theme.print(.ink).opacity(Double(CardObjectKnobs.cardObjectRingFillInkOpacity)))                } else {                    Circle().strokeBorder(                        theme.print(.ink).opacity(Double(CardObjectKnobs.cardObjectRingInkOpacity)),                        lineWidth: max(CardObjectKnobs.cardObjectRingStrokeMin, side * CardObjectKnobs.cardObjectRingStrokeFraction))                }            }            .frame(width: side * CardObjectKnobs.cardObjectRingSide, height: side * CardObjectKnobs.cardObjectRingSide)        case .cap(let name, let colour):            ProjectCap(name: name, colour: colour, side: side * CardObjectKnobs.cardObjectCapSide)        case .emptyCap:            EmptyCap(side: side * CardObjectKnobs.cardObjectCapSide, adds: false)        case .people(let people):            CardPeople(people: people, side: side)        case .print(let key, let seed):            CardPrint(key: key, seed: seed, width: side * CardObjectKnobs.cardObjectPrintSide)        }    }    /// A generated enamel object, with what is drawn live on it.    private func enamel(_ picture: CardEnamel, @ViewBuilder prints: () -> some View) -> some View {        ZStack {            if let image = CottonMedia.image(picture.asset) {                image                    .resizable()                    .interpolation(.high)                    .scaledToFit()                    .accessibilityHidden(true)            }            prints()        }        .frame(width: side * CardObjectKnobs.cardObjectEnamelSide, height: side * CardObjectKnobs.cardObjectEnamelSide)    }    /// One hand of the clock, turning about the dial's centre.    private func hand(length: CGFloat, width: CGFloat, degrees: Double) -> some View {        let square = side * CardObjectKnobs.cardObjectEnamelSide        return Capsule()            .fill(theme.print(.ink).opacity(Double(CardObjectKnobs.cardObjectClockHandInkOpacity)))            .frame(width: max(CardObjectKnobs.cardObjectClockHandWidthMin, square * width), height: square * length)            .offset(y: -square * length * 0.5)            .rotationEffect(.degrees(degrees))            .position(x: CardObjectKnobs.cardObjectClockCentreX * square, y: CardObjectKnobs.cardObjectClockCentreY * square)    }}/// The calendar's month leaf, small: a cream leaf with the month on its/// red band and the day set large under it.struct CardMonthLeaf: View {    @Environment(\.theme) private var theme    let day: Int?    let month: String?    let side: CGFloat    var body: some View {        let shape = RoundedRectangle(cornerRadius: side * CardObjectKnobs.cardLeafCorner, style: .continuous)        VStack(spacing: 0) {            Text(month?.uppercased() ?? " ")                .font(theme.type.meta(side * CardObjectKnobs.cardLeafMonthTypeFraction))                .tracking(side * CardObjectKnobs.cardLeafMonthTracking)                .foregroundStyle(theme.sheet(.cream))                .lineLimit(1)                .frame(maxWidth: .infinity)                .frame(height: side * CardObjectKnobs.cardLeafBandHeight)                .background(theme.print(.red).opacity(Double(CardObjectKnobs.cardLeafBandOpacity)))            Text(day.map(String.init) ?? "")                .font(theme.type.display(side * CardObjectKnobs.cardLeafDayTypeFraction))                .foregroundStyle(theme.print(.ink).opacity(Double(CardObjectKnobs.cardLeafDayInkOpacity)))                .monospacedDigit()                .lineLimit(1)                .frame(maxWidth: .infinity, maxHeight: .infinity)        }        .background(theme.sheet(.cream))        .clipShape(shape)        .overlay(shape.strokeBorder(theme.colors.hairline.color, lineWidth: theme.scale.hairline))        .frame(width: side * CardObjectKnobs.cardLeafWidth, height: side * CardObjectKnobs.cardLeafHeight)    }}/// People on a card: up to three prints, overlapped, the first in front. A/// person with no picture is a face print with their initials, never a blank/// grey square (architect, r7).private struct CardPeople: View {    @Environment(\.theme) private var theme    let people: [CardPerson]    let side: CGFloat    var body: some View {        let drawn = Array(people.prefix(CardObjectKnobs.cardObjectPeopleMax))        let width = side * (drawn.count > 1 ? CardObjectKnobs.cardObjectPeopleManyWidth : CardObjectKnobs.cardObjectPeopleOneWidth)        let step = width * CardObjectKnobs.cardObjectPeopleStep        let span = width + step * CGFloat(max(0, drawn.count - 1))        ZStack(alignment: .leading) {            ForEach(Array(drawn.enumerated().reversed()), id: \.element.id) { index, person in                CardPrint(key: person.pictureKey, seed: person.id, width: width, name: person.name)                    .offset(x: step * CGFloat(index))            }        }        .frame(width: span, alignment: .leading)    }}/// A thumb-size polaroid of a stored picture; a person's face print with/// their initials until they have one, an empty print for anything else.private struct CardPrint: View {    @Environment(\.theme) private var theme    let key: String?    let seed: String    let width: CGFloat    /// Whose print it is, when it is a person's.    var name: String? = nil    @State private var slot = MediaImageSlot()    var body: some View {        Group {            if let image = slot.image(for: key) {                InstantPrint(seed: seed, size: .thumb) {                    Image(uiImage: image).resizable().scaledToFill()                }            } else if let initials = name.flatMap(CardPerson.initials) {                InstantPrint(seed: seed, size: .thumb) {                    ZStack {                        Rectangle().fill(theme.sheet(.cream))                        Text(initials)                            .font(theme.type.title(width * CardObjectKnobs.cardPrintInitialsTypeFraction))                            .foregroundStyle(theme.print(.pencil))                            .lineLimit(1)                    }                }            } else {                EmptyPrint(seed: seed, size: .thumb)            }        }        .frame(width: width)        .mediaSlot($slot, key: key, edge: width)    }}/// The sizes, counts and timings CardObject draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum CardObjectKnobs {    static let cardObjectWordsLongTypeFraction: CGFloat = 0.17    static let cardObjectWordsShortTypeFraction: CGFloat = 0.26    static let cardObjectWordsNameLines = 2    static let cardObjectWordsSentenceLines = 3    static let cardObjectPeopleManyWidth: CGFloat = 0.5    static let cardObjectPeopleOneWidth: CGFloat = 0.64    static let cardLeafBandHeight: CGFloat = 0.26    static let cardLeafBandOpacity: CGFloat = 0.86    static let cardLeafCorner: CGFloat = 0.12    static let cardLeafDayInkOpacity: CGFloat = 0.88    static let cardLeafDayTypeFraction: CGFloat = 0.46    static let cardLeafHeight: CGFloat = 0.9    static let cardLeafMonthTracking: CGFloat = 0.01    static let cardLeafMonthTypeFraction: CGFloat = 0.15    static let cardLeafWidth: CGFloat = 0.82    static let cardObjectCapSide: CGFloat = 0.78    static let cardObjectClockCentreX: CGFloat = 0.5    static let cardObjectClockCentreY: CGFloat = 0.5    static let cardObjectClockHandInkOpacity: CGFloat = 0.9    static let cardObjectClockHandWidthMin: CGFloat = 1.2    static let cardObjectClockHourHandLength: CGFloat = 0.62    static let cardObjectClockHourHandWidth: CGFloat = 0.03    static let cardObjectClockMinuteHandLength: CGFloat = 0.92    static let cardObjectClockMinuteHandWidth: CGFloat = 0.02    static let cardObjectClockReach: CGFloat = 0.206    static let cardObjectEnamelSide: CGFloat = 0.78    static let cardObjectFigureInkOpacity: CGFloat = 0.88    static let cardObjectFigureTypeFraction: CGFloat = 0.4    static let cardObjectFigureWidth: CGFloat = 0.96    static let cardObjectLeafSideFraction: CGFloat = 0.7    static let cardObjectPeopleMax = 3    static let cardObjectPeopleStep: CGFloat = 0.62    static let cardObjectPrintSide: CGFloat = 0.7    static let cardObjectRingFillInkOpacity: CGFloat = 0.86    static let cardObjectRingInkOpacity: CGFloat = 0.78    static let cardObjectRingSide: CGFloat = 0.52    static let cardObjectRingStrokeFraction: CGFloat = 0.045    static let cardObjectRingStrokeMin: CGFloat = 1.5    static let cardObjectWordsHeight: CGFloat = 0.8    /// The room either end of a card's words for the hand's overhanging ink.    static let cardObjectWordsInkRoom = "\u{200A}"    static let cardObjectWordsInkOpacity: CGFloat = 0.78    static let cardObjectWordsNameMaxCharacters = 16    static let cardObjectWordsWidth: CGFloat = 0.92    static let cardPrintInitialsTypeFraction: CGFloat = 0.3}