Cotton code
500 lines · 22.7 KB · SwiftRaw
// A face: what draws one card, by an id a kit names, with the specimens it is// reviewed in (Loom, 27 Oct 2026). A face takes the card the core worked out// (`DeckCard`), the picture it shows, if any (`FacePicture`), and its toggle// (`FaceTaps`; every other tap is its parts', `facePart`) — and nothing// else: no store, no core, no flavour. The app wires a face to data; the// Loom app and `CottonFacesTests` draw it from its specimens alone.//// One file per face, in its app's folder (Cotton/, Sharmila/, Nancy/,// Rigby/, Shared/), declaring `static let face = Face(id: …)` and the stock// it is printed on, `static let stock: FaceStock = …`, beside the view;// `FaceRegistry` is generated from those declarations// (`scripts/gen-faces-registry.py`), never written by hand.import CottonPaperimport CottonValuesimport SwiftUIpublic struct Face: Identifiable, Sendable {    /// The open id a kit names a face by. For now the card kind's name    /// (`DefinitionCardKind.rawValue`): `photo`, `event`, `film`.    public let id: String    /// The cards it is reviewed in. Light and dark, text sizes and looks are    /// the Loom app's to vary, not the specimen's.    public let specimens: [Specimen]    /// How the face is stepped from one card to the next by a tap beside    /// its parts, when it is (`FaceStep`); nil, it is not.    public let steps: FaceStep?    /// The cards a face that turns (`FaceStep.turns`) is spun through where    /// it is tested (Loom's face screen), after its opened specimens: a file    /// long enough to flick; empty, its own specimens.    public let spins: [Specimen]    /// The face tags no part (`FacePart`): its whole page is the deck's to    /// tap — stepped by its side thirds, read by its middle — so the shell    /// writes the card's words from the long-press fan, not from the card    /// (a note's torn page).    public let tagsNoPart: Bool    private let draw: @MainActor @Sendable (DeckCard, FacePicture?, FaceTaps) -> AnyView    public init<Drawn: View>(        id: String, specimens: [Specimen], steps: FaceStep? = nil, spins: [Specimen] = [], tagsNoPart: Bool = false,        @ViewBuilder draw: @escaping @MainActor @Sendable (DeckCard, FacePicture?, FaceTaps) -> Drawn    ) {        self.id = id        self.specimens = specimens        self.steps = steps        self.spins = spins        self.tagsNoPart = tagsNoPart        self.draw = { AnyView(draw($0, $1, $2)) }    }    /// The face drawn for `card`.    @MainActor public func view(_ card: DeckCard, picture: FacePicture?, taps: FaceTaps) -> AnyView {        draw(card, picture, taps)    }}/// How a face that is stepped by a tap goes from one card to the next: a/// tap on the screen's right third that lands on none of its parts brings/// the next card, on its left third the one before (Loom's face screen;/// the deck's move to come). The face declares it beside itself/// (`Face(id:specimens:steps:)`), so whatever steps it brings the face's own/// transition and none of its own.public enum FaceStep: Sendable, Equatable {    /// The card stands and is handed the next: the face answers the change    /// itself, as a split-flap board's letters flap over in place.    case inPlace    /// The next card is simply there: a plain cut, nothing animated, so    /// cards are tapped through as fast as a finger goes (a note's page).    case cut    /// The face turns on a rail (a rolodex, `Rolodex`): the shell supplies    /// the filled neighbours and signed travel, the face draws the wheel.    /// Whatever wears the rolodex declares it, and the deck turns it by    /// this declaration alone, never by the face's id.    case turns}/// The stock a face is printed on, as its file declares it beside the face/// (`static let stock`). The face lays it on its own body/// (`.onCardPaper(stock.laid(card.pace))`); `FaceRegistry.stock(_:)` keeps/// it by the face's id, so whatever stacks a card knows the sheets under it/// before the card is drawn.public enum FaceStock: Sendable, Equatable {    case cream    case ornamented    case framed    /// The pace band's paper of the card drawn.    case pace    /// The face draws its own sheet (a subscription's ticket, a membership's    /// pass) and lays none; the sheets under it are the framed stock's.    case own    /// The paper laid for a card of `pace`, and the sheets under it.    public func laid(_ pace: DeckPace?) -> CardStock {        switch self {        case .cream: .cream        case .ornamented: .ornamented        case .framed, .own: .framed        case .pace: .pace(pace)        }    }}/// The ground a face's card lies on, as its file declares it beside the face/// (`static let ground`), kept by the face's id (`FaceRegistry.ground(_:)`)/// so whatever stands a card on a screen lays the ground behind it before/// the card is drawn: the colour behind the card, and whether it is dark, so/// the words drawn on it beside the card take the light ink.public enum FaceGround: String, Sendable, CaseIterable {    /// The page ground Cotton's deck stands on: every paper face lies on it.    case paper    /// The music's warm charcoal wool felt, a turntable's mat.    case felt    /// The films' deep claret baize, the board's cloth in another dye: a    /// video's sleeve lies on it.    case claret    /// The Photos tool's deep oxblood bookcloth, an old family album's    /// cover: a lab print and an album's cork board lie on it.    case bookcloth    /// The books' dark navy wool felt under its warm lamp (`lamp`, Codex's    /// `books-lamp`: the glow from the upper left and the faint pool it    /// leaves lower right, one painting the screen's size): a standing    /// hardback, a stopped book lying and a highlight's torn strip lie on it.    case feltNavy    /// The music's black pebbled tolex, an amplifier case's, in the dark    /// room's one warm lamp, its glow laid upper left (`lamp`): a hi-fi deck    /// stands on it.    case tolex    /// The music's dark wood dance floor under the party's lights, which    /// drift slowly over it (`overlay`), and no lamp: the party's turntable    /// stands on it.    case partyFloor    /// The cinema's curtain-red velvet, the Picture House's, under its one    /// warm house light laid upper left (`lamp`): a film's one-sheet in its    /// lobby frame hangs on it.    case velvet    /// The calendar's pale blue glazed kitchen tiles, a tear-off calendar's    /// wall: an event hangs on them.    case kitchenTile    /// The people's desk top painted amethyst, the wood's grain under the    /// paint, as the People icon's (13 Nov 2026): a rolodex stands on it.    case amethystDesk    /// The messages' yellow painted pegboard: a thread's slips lie on it.    case pegboard    /// The email's rose linen: a letter lies on it.    case roseLinen    /// The notes' burnt-orange wool felt, a typewriter's: a torn page lies    /// on it.    case feltOrange    /// The todos' dark teal baize, a clipboard's desk: an index card's tray    /// stands on it.    case baizeTeal    /// The money's pink terrazzo, a piggy bank's counter: a till receipt, a    /// cheque and an account's card lie on it.    case terrazzo    /// The keys' pebbled leather dyed teal-blue, a valet tray's, as the Keys    /// icon's (13 Nov 2026): a passkey's card and a    /// secret lie on it.    case tealLeather    /// The downloads' record-shop checker floor, a milk crate's: a fetch's    /// slip lies on it.    case checker    /// The developer's charcoal felt desk mat, a terminal's: a memory, a    /// machine and a session lie on it.    case deskMat    /// The podcasts' kitchen windowsill counter, pale mint boomerang    /// formica in the window's daylight from the upper left (`lamp`): a    /// show's transistor radio stands on it.    case formicaCounter    /// The photos' darkroom bench, black enamel over planks worn pale where    /// trays slid, fixer rings dried on it, under the amber safelight: a lab    /// print and an album's slide carousel lie on it (12 Nov 2026).    case darkroomBench    /// The journal's bedside table, dark oiled walnut under the bedside    /// lamp's one warm pool (`lamp`): a diary lies open on it (12 Nov 2026).    case bedsideTable    /// The pages' desk top in cobalt-blue enamel, as the Pages icon's (13    /// Nov 2026): a page's newspaper clipping lies on it, and its reader    /// stands on it.    case cobaltEnamel    /// The calling desk's top, oxblood leather inlay waxed to a low sheen,    /// under the desk lamp's warm pool (`lamp`): the desk telephone stands    /// on it, a call's memory slip and a contact's card lie on it (13 Nov    /// 2026).    case leatherDesk    /// Cotton Health's honed blue-grey slate, a clinic's instrument shelf,    /// as the Health icon's (13 Nov 2026): the brass pedometer, the    /// stopwatch and the brass measurement tags lie on it.    case slate    /// Cotton Story's plain ground (17 Nov 2026): no material at all, the    /// near-white of a fresh page in light and near-black in dark, following    /// the phone (`StoryMaterial.ground`): every Story card lies on it flat.    case blank    /// The colour behind the card.    public var colour: Color {        switch self {        case .paper: CottonColors.groundMuted        case .felt: MusicMaterial.felt.colour        case .claret: BooksMaterial.baize.colour        case .bookcloth: PhotosMaterial.bookcloth.colour        case .feltNavy: BooksMaterial.felt.colour        case .tolex: MusicMaterial.tolex.colour        case .partyFloor: MusicMaterial.floor.colour        case .velvet: CinemasMaterial.velvet.colour        case .kitchenTile: GroundMaterial.kitchenTile.colour        case .amethystDesk: GroundMaterial.amethystDesk.colour        case .pegboard: GroundMaterial.pegboard.colour        case .roseLinen: GroundMaterial.roseLinen.colour        case .feltOrange: GroundMaterial.feltOrange.colour        case .baizeTeal: GroundMaterial.baizeTeal.colour        case .terrazzo: GroundMaterial.terrazzo.colour        case .tealLeather: GroundMaterial.tealLeather.colour        case .checker: GroundMaterial.checker.colour        case .deskMat: GroundMaterial.deskMat.colour        case .formicaCounter: GroundMaterial.formicaCounter.colour        case .darkroomBench: GroundMaterial.darkroomBench.colour        case .bedsideTable: GroundMaterial.bedsideTable.colour        case .cobaltEnamel: GroundMaterial.cobaltEnamel.colour        case .leatherDesk: GroundMaterial.leatherDesk.colour        case .slate: GroundMaterial.slate.colour        case .blank: StoryMaterial.ground.colour        }    }    /// The ground is dark: what is drawn on it beside the card is drawn in    /// light ink. It follows the ground's colour, never a list: light ink    /// where it stands out more than dark would (relative luminance under    /// `FaceGroundKnobs.lightInkBelow`), so a light ground (the kitchen    /// tile, the pegboard, the terrazzo) takes the dark ink and a new ground    /// cannot be declared with words that vanish on it (the Todos counter on    /// its dark ground, 12 Nov 2026).    public var dark: Bool {        FaceGroundKnobs.luminance(colour) < FaceGroundKnobs.lightInkBelow    }    /// The painted tile the ground is laid with, by its catalogue name    /// (`Media.xcassets`, a 3x master); nil, its colour alone.    public var tile: String? {        switch self {        case .paper: nil        case .felt: "music-felt"        case .claret: "films-baize"        case .bookcloth: "photos-bookcloth"        case .feltNavy: "books-felt"        case .tolex: "tolex"        case .partyFloor: "floor"        case .velvet: "velvet"        case .kitchenTile: "calendar-tile"        case .amethystDesk: "people-amethyst"        case .pegboard: "messages-pegboard"        case .roseLinen: "email-linen"        case .feltOrange: "notes-felt"        case .baizeTeal: "todos-baize"        case .terrazzo: "money-terrazzo"        case .tealLeather: "keys-teal"        case .checker: "downloads-checker"        case .deskMat: "developer-mat"        case .formicaCounter: "podcasts-formica"        case .darkroomBench: "photos-bench"        case .bedsideTable: "journal-bedside"        case .cobaltEnamel: "pages-cobalt"        case .leatherDesk: "calling-desk"        case .slate: "health-slate"        case .blank: nil        }    }}extension FaceGround {    /// The painted glow of the room's one lamp, laid once over the tile,    /// upper left (`FaceGroundLamp`); nil, the ground has none.    public var lamp: FaceGroundLamp? {        switch self {        case .tolex: FaceGroundLamp(name: "lamp-glow", rect: CGRect(x: -250, y: -250, width: 1450, height: 1450), strength: 1)        case .velvet: FaceGroundLamp(name: "house-light", rect: CGRect(x: -250, y: -280, width: 1024, height: 1024), strength: 0.42)        case .feltNavy: FaceGroundLamp(name: "books-lamp", rect: CGRect(x: 0, y: 0, width: 1290, height: 2796), strength: 1)        case .formicaCounter: FaceGroundLamp(name: "formica-daylight", rect: CGRect(x: 0, y: 0, width: 1800, height: 1800), strength: 1)        case .bedsideTable: FaceGroundLamp(name: "bedside-lamp", rect: CGRect(x: -510, y: -320, width: 2200, height: 2200), strength: 0.85)        case .leatherDesk: FaceGroundLamp(name: "desk-lamp", rect: CGRect(x: -520, y: -420, width: 2200, height: 2200), strength: 0.8)        default: nil        }    }}/// A lamp's glow laid once over a ground's tile: the painting by its/// catalogue name (a 3x master), where it is laid from the ground's upper/// left corner in its painting's pixels at three a point (its materials'/// `layout.json`: music11's `lampDefaultRect`, cinemas14's ground/// `houseLightRect`, books27's lamp the screen's own size), and how strongly/// (its `houseLightOpacity`; books27's is baked into its painting).public struct FaceGroundLamp: Equatable, Sendable {    public let name: String    public let rect: CGRect    public let strength: Double}extension FaceGround {    /// The painting laid over the tile, repeated, drifting: the party's    /// lights over its floor. Nil, the ground has none.    public var overlay: FaceGroundOverlay? {        switch self {        case .partyFloor: FaceGroundOverlay(name: "party-lights", heading: CGSize(width: 1, height: 0), speed: 0.5)        default: nil        }    }}/// A painting laid over a ground's tile, repeated, that drifts slowly along/// `heading` at `speed` points a second and wraps: by the time it has moved/// one whole lap (`travel`, whole tiles along each axis) it is laid as it/// started, so it drifts on for ever without a seam. Under Reduce Motion, and/// in a still picture of the ground, it lies where it starts.public struct FaceGroundOverlay: Equatable, Sendable {    /// The painting, by its catalogue name (a 3x master).    public let name: String    /// Whole tiles along each axis in one lap: (1, 0) drifts right.    public let heading: CGSize    /// Points a second.    public let speed: CGFloat    /// One tile, in points: the painting's side at three pixels a point.    public static let side = CGSize(width: 1024 / FaceGroundKnobs.pixelsPerPoint, height: 1024 / FaceGroundKnobs.pixelsPerPoint)    /// How far it moves in one lap, in points.    public var travel: CGSize { CGSize(width: heading.width * Self.side.width, height: heading.height * Self.side.height) }    /// How long one lap takes, in seconds.    public var lap: TimeInterval { Double(hypot(travel.width, travel.height) / speed) }    /// Where it lies `seconds` into its drift, wrapped into one lap: from    /// nought to `travel`, and back to nought, seamlessly, at each lap's end.    /// Under Reduce Motion it lies still where it starts.    public func offset(after seconds: TimeInterval, reduceMotion: Bool = false) -> CGSize {        guard !reduceMotion, lap > 0, seconds.isFinite else { return .zero }        let share = CGFloat((seconds / lap) - (seconds / lap).rounded(.down))        return CGSize(width: travel.width * share, height: travel.height * share)    }}enum FaceGroundKnobs {    static let pixelsPerPoint: CGFloat = 3    /// The relative luminance under which white ink stands out from a    /// ground more than black does (WCAG's contrast ratio: the two are equal    /// at the square root of 1.05 x 0.05, less 0.05).    static let lightInkBelow: Double = 0.179    /// A colour's relative luminance (WCAG), from its linear components.    static func luminance(_ colour: Color) -> Double {        let resolved = colour.resolve(in: EnvironmentValues())        return 0.2126 * Double(resolved.linearRed) + 0.7152 * Double(resolved.linearGreen) + 0.0722 * Double(resolved.linearBlue)    }}/// A ground laid: its colour, and over it its painted tile, repeated, where/// it has one and this build carries the pictures; the lamp's glow upper/// left, where it has one; and its overlay drifting over all, where it has/// one.public struct FaceGroundSurface: View {    let ground: FaceGround    public init(_ ground: FaceGround) {        self.ground = ground    }    public var body: some View {        Group {            if let name = ground.tile, let tile = CottonMedia.image(name, scale: 3) {                ground.colour.overlay(tile.resizable(resizingMode: .tile))            } else {                ground.colour            }        }        .overlay(alignment: .topLeading) {            if let lamp = ground.lamp, let glow = CottonMedia.image(lamp.name, scale: 3) {                let rect = lamp.rect                let k = FaceGroundKnobs.pixelsPerPoint                glow.resizable().interpolation(.high)                    .opacity(lamp.strength)                    .frame(width: rect.width / k, height: rect.height / k)                    .offset(x: rect.minX / k, y: rect.minY / k)                    .allowsHitTesting(false)                    .accessibilityHidden(true)            }        }        .overlay {            if let overlay = ground.overlay, let painting = CottonMedia.image(overlay.name, scale: 3) {                FaceGroundDrift(overlay: overlay, painting: painting)            }        }        .clipped()    }}/// A ground's overlay, repeated over the ground and drifting one lap after/// another for as long as it is on screen: one repeating animation of one/// lap the system runs, the view never redrawn for it. Still under Reduce/// Motion.struct FaceGroundDrift: View {    let overlay: FaceGroundOverlay    let painting: Image    @State private var drifting = false    @Environment(\.accessibilityReduceMotion) private var reduceMotion    var body: some View {        let side = FaceGroundOverlay.side        let travel = overlay.travel        let moved = drifting && !reduceMotion ? travel : .zero        GeometryReader { room in            // A tile more than the room each way the drift comes from, so            // the room is covered wherever in its lap the drift is.            painting.resizable(resizingMode: .tile)                .frame(width: room.size.width + side.width * 2, height: room.size.height + side.height * 2)                .offset(x: moved.width - side.width, y: moved.height - side.height)                .animation(drifting && !reduceMotion ? .linear(duration: overlay.lap).repeatForever(autoreverses: false) : nil, value: moved)        }        .allowsHitTesting(false)        .accessibilityHidden(true)        .onAppear { drifting = true }        .onDisappear { drifting = false }    }}extension FaceRegistry {    /// The stock of the sheets under a card wearing the face `id`, of `pace`,    /// known before the card is drawn: the face's (`stock(_:)`), and the pace    /// band's paper for an id this build has no face for, which the plain    /// face draws on that paper (`PlainFace`).    public static func sheetsUnder(_ id: String, pace: DeckPace?) -> CardStock {        (stock(id) ?? .pace).laid(pace)    }}/// A named state a face is reviewed in: invented data only.public struct Specimen: Sendable {    public let name: String    public let card: DeckCard    /// The fixture photograph it shows, by name (`Resources/Fixtures`), if any.    public let picture: String?    /// The part of the card selected, as the shell selects it while the    /// part's editor is open, which a face that knows its parts rings    /// (`selectedFacePart`); nil, none.    public let selected: FacePart?    public let opened: Bool    /// The card at each second of a specimen clock, for a specimen whose    /// card moves with the time (a board's clock turning over): `card` is    /// its second nought. Nil, the card stands still. The face keeps no    /// time; whatever draws the specimen counts the seconds    /// (`SpecimenClock`) and hands the face the card of the second.    public let ticking: (@Sendable (Int) -> DeckCard)?    /// Where the player stands with the card as it is reviewed, for a face    /// drawn under the player (a show's radio playing, paused): whatever    /// draws the specimen starts its specimen player there. Nil, the card is    /// drawn under whatever player is installed, or none.    public let play: TrackPlay?    /// The card is reviewed lying turned over (a sleeve's back): whatever    /// draws the specimen hands the face `faceTurnedOver`, and a tap turns    /// it back as it would on the deck.    public let turned: Bool    public init(        _ name: String, _ card: DeckCard, picture: String? = nil, selected: FacePart? = nil, opened: Bool = false,        ticking: (@Sendable (Int) -> DeckCard)? = nil, play: TrackPlay? = nil, turned: Bool = false    ) {        self.name = name        self.card = card        self.picture = picture        self.selected = selected        self.opened = opened        self.ticking = ticking        self.play = play        self.turned = turned    }    /// The specimen at `second` of its clock: its card that second, the    /// rest as it is; a specimen that does not tick, itself.    public func at(_ second: Int) -> Specimen {        guard let ticking else { return self }        return Specimen(name, ticking(second), picture: picture, selected: selected, opened: opened, ticking: ticking, play: play,                        turned: turned)    }}/// The one tap a face keeps on itself: a toggle (a todo's done box), flipped/// on the card. Every other tap is the shell's, by the part it lands on/// (`facePart`); nil draws the toggle as a card outside a deck does.public struct FaceTaps {    public var toggle: (() -> Void)?    /// One toggle of several, by its key, flipped on the card: an unlock    /// card's table switches (`UnlockCardFace`).    public var flip: ((String) -> Void)?    public init(toggle: (() -> Void)? = nil, flip: ((String) -> Void)? = nil) {        self.toggle = toggle        self.flip = flip    }    /// No tap offered.    public static var none: FaceTaps { FaceTaps() }}