Cotton code
498 lines · 22.0 KB · SwiftRaw
// THE ROLODEX, the material two faces wear (People's `person.rolodex` and// Calendar's `event.rolodex`, 3 Nov 2026: "We might use Rolodex for more// things in the future as one of the available views"): a 1960s rotary card// file standing bare on its ground, a cream card held upright on the rail// under two steel rings, the fan of cards behind with their faded tabs, the// cradle's knurled knobs either side. The frame, its shadow, the front card// with its five rules, the rings and the knobs are PAINTED (`Media.xcassets`,// cut and imported by `scripts/import-people-materials.py`).//// The component owns everything but what is typed on the card: the frame,// the rings, the knobs and their knurl, the stack's lift, the turn about the// rail (the leaving card falling away from its nested neighbour at −14°, in// reverse the fallen card rising in front of it), the untyped reverse, the// riffle at speed and the room the opened card leaves under the file. The// face that wears it fills one slot, the card's FRONT (`RolodexLeaf`), and// says what riffles over the leaves when the wheel goes by too fast to read// (its name line), what picture a neighbour shows, what an opened card// shows under the file, and which cards sit on the rail dimmed (an event// already past). A face is a rolodex by declaring `steps: .turns`;// the deck turns every such face the same way, by that declaration alone.import CottonPaperimport CottonValuesimport SwiftUIenum RolodexKnobs {    // THE FRAME, as painted (`rolodex-frame`, 1463 by 1414 pixels at the    // painting's size): its width over its height, the blank card standing    // at its front and the rail's middle as shares of it, and how far its    // shadow (`rolodex-shadow`) reaches past it on every side as a share of    // its width — measured off the painting by the cut that made the layers    // (`cut.py` beside them), so a repainted frame owes new knobs.    static let aspect: CGFloat = 1463.0 / 1414.0    static let card = CGRect(x: 0.1716, y: 0.1436, width: 0.8353 - 0.1716, height: 0.6726 - 0.1436)    static let rail: CGFloat = 0.7454    static let shadowReach: CGFloat = 0.08    /// The frame in the card's room: the most of its width and its height.    static let fillWidth: CGFloat = 0.98    static let fillHeight: CGFloat = 0.96    /// The opened card's room under the file, and the gap above it.    static let openedRoom: CGFloat = 160    static let openedGap: CGFloat = 12    /// Fixed knob bounds measured on the frame; the tread lies between its    /// side rims. Rotation is about the horizontal rail, projected vertically.    static let knobRects: [CGRect] = [0.0, 0.87].map {        CGRect(x: $0, y: 0.289, width: 0.13, height: 0.30)    }    static let treadLead: CGFloat = 0.13    static let treadWidth: CGFloat = 0.65    static let treadTop: CGFloat = 0.025    static let treadHeight: CGFloat = 0.95    static let treadBow: CGFloat = 0.07    static let teeth = 64    /// Eight tooth pitches per card: 45 degrees, with no jump when progress    /// resets after committing the selection (the knurl repeats exactly).    static let knobAngle = Double.pi / 4    // THE CARD (`rolodex-card`, laid over the frame's blank one): its five    // rules' heights and its two notches' middles, as shares of it.    static let rules: [CGFloat] = [0.3391, 0.4377, 0.5387, 0.6386, 0.7372]    static let notches: [CGFloat] = [0.351, 0.6479]    /// A ring (`rolodex-ring`): its width over its height as painted; its    /// top this far above the card's foot, as a share of the card's height,    /// and its foot this far under the rail, as a share of the frame's.    static let ringAspect: CGFloat = 90.0 / 246.0    static let ringTop: CGFloat = 0.145    static let ringFoot: CGFloat = 0.03}/// One card of the file as the wearing face types it: the card, its/// picture, the front card's size, and whether only its name line is typed/// (the wheel going by at reading speed, `FaceTurnBand.name`).public struct RolodexLeaf {    public let card: DeckCard    public let photo: FacePicture?    public let size: CGSize    public let nameOnly: Bool}/// The rotary card file a face wears, its front card the face's own.public struct Rolodex<Front: View, Name: View, Under: View>: View {    @Environment(\.faceTurn) private var turn    @Environment(\.faceOpened) private var opened    let card: DeckCard    let photo: FacePicture?    let picture: (DeckCard) -> FacePicture?    let front: (RolodexLeaf) -> Front    let name: (DeckCard, CGSize) -> Name    let under: (CGFloat) -> Under    let dims: (DeckCard) -> Bool    /// `card` on the file with `photo`; `picture` is a neighbour's, read    /// off its card; `front` types a card's front over the painted card;    /// `name` is the line that riffles over the leaves at speed; `under` is    /// what an opened card shows under the file, at the file's width;    /// `dims` says which cards' fronts are dimmed (`PeopleMaterial.dim`).    public init(        card: DeckCard, photo: FacePicture?, picture: @escaping (DeckCard) -> FacePicture?,        dims: @escaping (DeckCard) -> Bool = { _ in false },        @ViewBuilder front: @escaping (RolodexLeaf) -> Front,        @ViewBuilder name: @escaping (DeckCard, CGSize) -> Name,        @ViewBuilder under: @escaping (CGFloat) -> Under    ) {        self.card = card        self.photo = photo        self.picture = picture        self.front = front        self.name = name        self.under = under        self.dims = dims    }    public var body: some View {        let knobs = RolodexKnobs.self        GeometryReader { box in            let height = opened ? max(0, box.size.height - knobs.openedRoom) : box.size.height * knobs.fillHeight            let width = min(box.size.width * knobs.fillWidth, height * knobs.aspect)            VStack(spacing: opened ? knobs.openedGap : 0) {            RolodexObject(card: card, photo: photo, size: CGSize(width: width, height: width / knobs.aspect),                          progress: turn.progress,                          window: turn.window, band: turn.band,                          picture: picture, front: front, name: name, dims: dims)                .frame(width: width, height: width / knobs.aspect)            if opened {                under(width)            }            }                .frame(width: box.size.width, height: box.size.height)        }    }}/// Cards share the rail: a forward leaf falls away from its nested/// neighbour; in reverse the fallen leaf rises in front of the nested one.struct RolodexWheel {    let phase: Double    var shownAngle: Double { phase >= 0 ? phase * 180 : -14 * abs(phase) }    var arrivingAngle: Double {        let t = abs(phase)        let eased = t * t * (3 - 2 * t)        return phase >= 0 ? -14 * (1 - eased) : 90 * (1 - t)    }    var shownZ: Double { phase >= 0 ? 1 : 0 }    var arrivingZ: Double { phase >= 0 ? 0 : 1 }    static func showsFront(_ angle: Double) -> Bool { angle > -90 && angle < 90 }}/// A painted layer of the rolodex, by its catalogue name, at the scale it/// was painted for; nil where this build carries no pictures.func rolodexPainted(_ name: String) -> Image? {    CottonMedia.image(name, scale: 3)}/// The rotary card file standing on the ground: its shadow, the painted/// frame, the front card over its blank one, and the two rings over the/// card's notches and the rail.private struct RolodexObject<Front: View, Name: View>: View, Animatable {    let card: DeckCard    let photo: FacePicture?    let size: CGSize    var progress: Double    let window: [Int: DeckCard]    let band: FaceTurnBand    let picture: (DeckCard) -> FacePicture?    let front: (RolodexLeaf) -> Front    let name: (DeckCard, CGSize) -> Name    let dims: (DeckCard) -> Bool    nonisolated var animatableData: Double {        get { progress }        set { progress = newValue }    }    var body: some View {        let base = Int(progress.rounded(.towardZero))        let phase = progress - Double(base)        let shown = base == 0 ? card : (window[base] ?? card)        let arriving = window[base + (progress < 0 ? -1 : 1)]        let shownPhoto = base == 0 ? photo : picture(shown)        let arrivingPhoto = arriving.flatMap(picture)        let knobs = RolodexKnobs.self        let w = size.width        let h = size.height        let reach = knobs.shadowReach * w        let front = CGRect(x: knobs.card.minX * w, y: knobs.card.minY * h, width: knobs.card.width * w, height: knobs.card.height * h)        let ringTop = front.maxY - knobs.ringTop * front.height        let ringHeight = (knobs.rail + knobs.ringFoot) * h - ringTop        let ringWidth = ringHeight * knobs.ringAspect        ZStack(alignment: .topLeading) {            if let shadow = rolodexPainted("rolodex-shadow") {                shadow.resizable().interpolation(.high)                    .frame(width: w + 2 * reach, height: h + 2 * reach)                    .offset(x: -reach, y: -reach)                    .accessibilityHidden(true)            }            if let frame = rolodexPainted("rolodex-frame") {                frame.resizable().interpolation(.high)                    .frame(width: w, height: h)                    .mask {                        // The fixed knob crops preserve the original pixels                        // outside their inpainted treads. Keep the frame                        // intact under the lifted stack, including its top edge.                        Path { path in                            path.addRect(CGRect(origin: .zero, size: size))                            for knob in knobRects { path.addRect(knob) }                        }.fill(style: FillStyle(eoFill: true))                    }                    .accessibilityHidden(true)            }            if progress != 0 {                movingFrameParts            }            ForEach(Array(knobRects.enumerated()), id: \.offset) { index, rect in                RolodexKnob(index: index, progress: progress)                    .frame(width: rect.width, height: rect.height)                    .offset(x: rect.minX, y: rect.minY)                    .accessibilityHidden(true)                    .allowsHitTesting(false)            }            if band == .riffle {                riffle(card: shown, front: front)            } else {                if let arriving, phase != 0 {                    turningCard(arriving, photo: arrivingPhoto, front: front,                                angle: RolodexWheel(phase: phase).arrivingAngle)                        .accessibilityHidden(true)                        .allowsHitTesting(false)                        .zIndex(RolodexWheel(phase: phase).arrivingZ)                }                turningCard(shown, photo: shownPhoto, front: front,                            angle: RolodexWheel(phase: phase).shownAngle)                    .zIndex(RolodexWheel(phase: phase).shownZ)            }            if let ring = rolodexPainted("rolodex-ring") {                ForEach(Array(knobs.notches.enumerated()), id: \.offset) { _, notch in                    ring.resizable().interpolation(.high)                        .frame(width: ringWidth, height: ringHeight)                        .offset(x: front.minX + notch * front.width - ringWidth / 2, y: ringTop)                        .accessibilityHidden(true)                }                .zIndex(2)            }        }        .frame(width: w, height: h, alignment: .topLeading)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("rolodex")    }    // The stack remains a lifted piece of the original painting; its    // motion is independent of the fixed knob bodies and travelling knurl.    private var stackRect: CGRect {        CGRect(x: size.width * 0.145, y: 0,               width: size.width * 0.71, height: size.height * 0.14)    }    private var knobRects: [CGRect] {        RolodexKnobs.knobRects.map { rect in            CGRect(x: size.width * rect.minX, y: size.height * rect.minY,                   width: size.width * rect.width, height: size.height * rect.height)        }    }    private func piece(_ rect: CGRect) -> some View {        rolodexPainted("rolodex-frame")?.resizable().interpolation(.high)            .frame(width: size.width, height: size.height)            .offset(x: -rect.minX, y: -rect.minY)            .frame(width: rect.width, height: rect.height, alignment: .topLeading)            .clipped()    }    private var movingFrameParts: some View {        Group {            piece(stackRect)                .offset(x: stackRect.minX, y: stackRect.minY + sin(abs(progress) * .pi) * 3)        }        .accessibilityHidden(true)        .allowsHitTesting(false)    }    private func riffle(card: DeckCard, front: CGRect) -> some View {        ZStack(alignment: .topLeading) {            // Four phases of the painted card stock, pivoting at the same rail.            ForEach(0..<4) { leaf in                let travel = progress + Double(leaf) / 4                let phase = travel - floor(travel)                RolodexPaper(size: front.size)                    .rotation3DEffect(.degrees((phase - 0.5) * 150), axis: (x: 1, y: 0, z: 0),                                      anchor: UnitPoint(x: 0.5, y: (RolodexKnobs.rail * size.height - front.minY) / front.height), perspective: 0.32)                    .offset(x: front.minX, y: front.minY + CGFloat(leaf) * 2)            }            // Keep the painting's coloured tabs travelling above the card edges.            ForEach(0..<3) { tab in                piece(stackRect)                    .offset(x: stackRect.minX, y: stackRect.minY + CGFloat(tab) * 4 + CGFloat(sin(progress * .pi * 2)) * 4)            }            name(card, front.size)                .offset(x: front.minX, y: front.minY)        }        .allowsHitTesting(false)        .accessibilityIdentifier("rolodex-riffle")    }    private func turningCard(_ card: DeckCard, photo: FacePicture?, front: CGRect, angle: Double) -> some View {        Group {            if RolodexWheel.showsFront(angle) {                ZStack(alignment: .topLeading) {                    RolodexPaper(size: front.size)                    self.front(RolodexLeaf(card: card, photo: photo, size: front.size, nameOnly: band == .name))                }                .frame(width: front.width, height: front.height, alignment: .topLeading)                .modifier(RolodexDim(on: dims(card)))            } else {                // The untyped reverse, never mirrored live names or actions.                RolodexPaper(size: front.size)            }        }        .rotation3DEffect(.degrees(angle), axis: (x: 1, y: 0, z: 0),                          anchor: UnitPoint(x: 0.5, y: (RolodexKnobs.rail * size.height - front.minY) / front.height),                          perspective: 0.32)        .offset(x: front.minX, y: front.minY)        .frame(width: size.width, height: size.height, alignment: .topLeading)        // Fallen leaves go into the cradle, never through the shell's fan.        .mask(alignment: .topLeading) {            Rectangle().frame(width: size.width, height: size.height * 0.86)        }    }}/// A dimmed card: its paper and ink multiplied down by `PeopleMaterial.dim`.private struct RolodexDim: ViewModifier {    let on: Bool    func body(content: Content) -> some View {        if on {            content.colorMultiply(PeopleMaterial.dim.colour)        } else {            content        }    }}/// The card stock: the painted card, or its stand-in where this build/// carries no pictures.private struct RolodexPaper: View {    let size: CGSize    var body: some View {        if let paper = rolodexPainted("rolodex-card") {            paper.resizable().interpolation(.high)                .frame(width: size.width, height: size.height)                .cardPaperLaid()                .accessibilityHidden(true)        } else {            RolodexStandInCard(size: size)        }    }}/// The visible half of a cylinder. A tooth's vertical position is sin(theta)/// and its thickness is cos(theta); the back half is hidden by the body.enum RolodexKnurl {    struct Ridge {        let centre: CGFloat        let thickness: CGFloat    }    static func ridge(_ index: Int, progress: Double) -> Ridge? {        let pitch = 2 * Double.pi / Double(RolodexKnobs.teeth)        let theta = Double(index) * pitch + progress * RolodexKnobs.knobAngle        let facing = cos(theta)        guard facing > 0.0001 else { return nil }        return Ridge(centre: CGFloat((1 + sin(theta)) / 2),                     thickness: CGFloat(pitch * 0.48 * facing / 2))    }}/// The body and its light never take progress. Only the neutral knurl tooth/// moves; soft light composites the fixed body's shading over its relief.struct RolodexKnob: View {    let index: Int    var progress: Double    var staticBody: some View {        rolodexPainted(index == 0 ? "rolodex-knob-left" : "rolodex-knob-right")?            .resizable().interpolation(.high)    }    var body: some View {        staticBody.overlay {            Canvas { context, size in                guard let tooth = rolodexPainted("rolodex-knurl") else { return }                let knobs = RolodexKnobs.self                let lead = index == 0 ? knobs.treadLead : 1 - knobs.treadLead - knobs.treadWidth                let top = size.height * knobs.treadTop                let height = size.height * knobs.treadHeight                for index in 0..<knobs.teeth {                    guard let ridge = RolodexKnurl.ridge(index, progress: progress) else { continue }                    let y = top + ridge.centre * height                    let thickness = ridge.thickness * height                    // The tread's side boundaries bow with the painted rim.                    let bow = sin(ridge.centre * .pi) * size.width * knobs.treadBow                    let rect = CGRect(x: lead * size.width - bow,                                      y: y - thickness / 2,                                      width: knobs.treadWidth * size.width + bow,                                      height: thickness)                    context.draw(tooth, in: rect)                }            }            .mask(staticBody)            .blendMode(.softLight)        }        .compositingGroup()    }}/// Lines typed on a rolodex card: each line's baseline at its own height,/// drawn in a room from just above the first line's letters to just under/// the last's; a line wider than the room squeezed to it, never cut.struct RolodexTyped: View {    let lines: [String]    /// Each line's baseline, from the card's top.    let baselines: [CGFloat]    let font: Font    let size: CGFloat    let ink: Color    let width: CGFloat    /// A second strike this far right: a line struck heavy.    var strike: CGFloat = 0    /// The room's top, from the card's top.    static func top(_ baselines: [CGFloat], size: CGFloat) -> CGFloat {        (baselines.first ?? 0) - size * 1.2    }    var body: some View {        let top = Self.top(baselines, size: size)        let height = (baselines.last ?? 0) - top + size * 0.5        Canvas { context, room in            for (line, baseline) in zip(lines, baselines) {                let text = context.resolve(Text(line).font(font).foregroundStyle(ink))                let ideal = text.measure(in: CGSize(width: 10_000, height: 10_000))                let base = text.firstBaseline(in: CGSize(width: 10_000, height: 10_000))                let scale = ideal.width + strike > room.width ? room.width / (ideal.width + strike) : 1                var drawing = context                drawing.translateBy(x: 0, y: baseline - top)                drawing.scaleBy(x: scale, y: scale)                drawing.draw(text, at: CGPoint(x: 0, y: -base), anchor: .topLeading)                if strike > 0 {                    drawing.draw(text, at: CGPoint(x: strike, y: -base), anchor: .topLeading)                }            }        }        .frame(width: width, height: max(height, 1))    }}/// The card where this build carries no pictures: its cream and its rules,/// flat.private struct RolodexStandInCard: View {    let size: CGSize    var body: some View {        Canvas { context, room in            context.fill(Path(roundedRect: CGRect(origin: .zero, size: room), cornerRadius: room.width * 0.03), with: .color(PeopleMaterial.card.colour))            for share in RolodexKnobs.rules {                let y = share * room.height                context.stroke(                    Path { $0.move(to: CGPoint(x: room.width * 0.04, y: y)); $0.addLine(to: CGPoint(x: room.width * 0.96, y: y)) },                    with: .color(PeopleMaterial.rule.colour), lineWidth: 0.6)            }        }        .frame(width: size.width, height: size.height)        .accessibilityHidden(true)    }}/// A line the core filled from a cards-set template, cut round its/// `{said}`: the typed words before and after, and the said words between,/// which the hand writes ("Last spoke | yesterday | on a call").struct SaidRun: Equatable {    let lead: String    let said: String    let tail: String    /// `words` cut by the template at `path` of the cards set; nil when the    /// template has no `{said}` or `words` was not filled from it.    static func cut(_ words: String, by path: String) -> SaidRun? {        let template = ShellLines.line("cards", path)        guard let mark = template.range(of: "{said}") else { return nil }        let lead = String(template[..<mark.lowerBound])        let after = template[mark.upperBound...]        let joint = String(after.prefix { $0 != "{" })        guard words.hasPrefix(lead) else { return nil }        let rest = words.dropFirst(lead.count)        if joint.isEmpty {            return after.isEmpty && !rest.isEmpty ? SaidRun(lead: lead, said: String(rest), tail: "") : nil        }        guard let cut = rest.range(of: joint), cut.lowerBound > rest.startIndex else { return nil }        return SaidRun(lead: lead, said: String(rest[..<cut.lowerBound]), tail: String(rest[cut.lowerBound...]))    }}