Cotton code
375 lines · 17.6 KB · SwiftRaw
// THE CASSETTE (the owner's ruling, 7 Nov 2026: the bare black cassette of the// Dark Room's `playlists` picture, no case, no J-card): one painted cassette// lying tilted on the music's black tolex, drawn by the list's face// (`list.cassette`), the song's (`song.cassette`) and the player's// (`PlayerFace.cassette`, the song's face under the player). A worn cream// label across its top: the title by hand (the signature hand, Ms Madi) above// the red rule, a smaller hand line under it; two cream hubs and the brown// tape packs seen through the shell; the time in small figures on the lower// shell.//// PAINTED (Round 22, `music22-cassette`; `scripts/import-cassette-materials.py`):// the shell, its shadow, the blank label, one hub, one full pack, the dark// inside and the strip of tape are wordless cut-outs, each laid where the// round's `layout.json` places it in the shell's 1200 x 745 pixels, the whole// scaled by the drawn width over 1200 and turned as the picture lies// (`tilt`). The face draws live only what the data decides: every word, each// pack's radius (the share of tape wound on it), the hubs' turn and the// counter's figures.//// THE PLAYER says where it stands (`TrackPlay`): the packs wind with the// position (the left shrinks as the right grows, the tape's area kept: the// radius of a share wound round the core), the hubs turn as far as the tape// has played and stand still under Reduce Motion, the counter reads the time// into the held song ("1:48"), and at rest the tape's length. Nothing here// keeps time: whatever plays redraws it.//// THE PARTS, tagged (`facePart`): the cassette is `play` — a tap plays or// pauses, so a tap on it never moves the deck; on the player's own card// (Listening's) the left hub is `previous`, the right hub `next`, and the// centre window `scrub` while it holds the song (a drag moves the playhead).// On a deck's card a drag is the deck's: it moves to the next card.import CottonPaperimport CottonValuesimport SwiftUIenum CassetteKnobs {    // THE SHELL'S PIXELS every placement is in (`layout.json`).    static let shell = CGSize(width: 1200, height: 745)    static let shadow = CGRect(x: -60, y: -60, width: 1320, height: 865)    static let window = CGRect(x: 210, y: 270, width: 780, height: 236)    static let tape = CGRect(x: 446, y: 434, width: 308, height: 16)    static let label = CGRect(x: 42, y: 50, width: 1116, height: 250)    /// The packs, the inside and the tape stay within the shell's outline.    static let inside = CGRect(x: 10, y: 10, width: 1170, height: 715)    static let insideCorner: CGFloat = 45    /// The hubs' centres, the hub's painting's side and the angles it lies    /// at in the picture, and the centre window the tape is seen through.    static let hubs = [CGPoint(x: 338, y: 386), CGPoint(x: 857, y: 386)]    static let hub: CGFloat = 166    static let hubAngles: [Double] = [18, 47]    static let centreWindow = CGRect(x: 459, y: 317, width: 281, height: 131)    /// A pack's radius: the core's, and full; the pack's painting is 576 px    /// a side and paints a full pack 280 px round its centre.    static let core: CGFloat = 95    static let full: CGFloat = 280    static let packPainted: CGFloat = 576    static let packPaintedRadius: CGFloat = 280    // THE LABEL'S WORDS, in the shell's pixels: the room they keep to, the    // title's line and size, the smaller hand line under the red rule.    static let ink = CGRect(x: 100, y: 78, width: 1000, height: 198)    static let titleCentre: CGFloat = 151    static let titleSize: CGFloat = 104    static let lineCentre: CGFloat = 251    static let lineSize: CGFloat = 42    static let lineWidth: CGFloat = 960    /// The hand's ink.    static let handInk = MusicMaterial.hand.colour    /// The most songs the hand line tries to name before "+N".    static let mostNamed = 12    // THE COUNTER on the lower shell, between its top edge and the holes.    static let counterCentre = CGPoint(x: 600, y: 590)    static let counterSize: CGFloat = 34    static let counterInk: Double = 0.72    /// The cassette as it lies, turned (the picture's −6°), and the room the    /// turned cassette and its shadow take, over the shell's size.    static let tilt: Double = -6    static let room = CGSize(width: 1300.0 / 1200, height: 900.0 / 745)    /// The widest the shell is drawn, in points.    static let widest: CGFloat = 340    /// How far the hubs turn for every second played, in degrees.    static let turnRate: Double = 48}/// One song on a tape, as its card holds it among its `songs`.public struct CassetteSong: Equatable, Sendable {    public var title: String?    /// Its length, in seconds.    public var seconds: TimeInterval    /// It can be played here.    public var available: Bool    public init(title: String?, seconds: TimeInterval, available: Bool = true) {        self.title = title        self.seconds = seconds        self.available = available    }}/// A tape as the cassette reads it off its card: its songs, how far it is/// wound, and its hand line.public enum CassetteTape {    /// The card's songs, in their order (its `songs` entries).    public static func songs(_ card: DeckCard) -> [CassetteSong] {        card.entries("songs").map { entry in            CassetteSong(                title: entry["title"]?.text, seconds: max(0, entry["duration"]?.number ?? 0),                available: entry["unavailable"]?.bool != true)        }    }    /// How far into the whole tape the player stands, in seconds: every song    /// before the one it holds, and how far into that one; nought while it    /// holds none.    public static func position(_ songs: [CassetteSong], _ play: TrackPlay) -> TimeInterval {        guard play.held, let song = play.song, songs.indices.contains(song) else { return 0 }        let before = songs[..<song].reduce(0) { $0 + $1.seconds }        return before + min(max(0, play.elapsed), songs[song].seconds)    }    /// The share of the tape wound onto the right reel: the position over    /// the whole tape's length; nought for a blank tape.    public static func wound(_ songs: [CassetteSong], _ play: TrackPlay) -> Double {        let whole = songs.reduce(0) { $0 + $1.seconds }        guard whole > 0 else { return 0 }        return min(1, max(0, position(songs, play) / whole))    }    /// A pack's radius, in the shell's pixels, with `share` of the tape wound    /// on it: its area is the tape's length.    public static func radius(_ share: Double) -> CGFloat {        let core = CassetteKnobs.core, full = CassetteKnobs.full        return sqrt(core * core + CGFloat(min(1, max(0, share))) * (full * full - core * core))    }    /// The hand line naming the first `named` of `titles`, "A / B / C", and    /// "+N" for the rest.    public static func named(_ titles: [String], _ named: Int) -> String {        let count = min(titles.count, max(0, named))        let shown = titles.prefix(count).joined(separator: " / ")        let rest = titles.count - count        guard rest > 0 else { return shown }        let more = ShellLines.line("cards", "cassette.more_short", ["n": String(rest)])        return shown.isEmpty ? more : "\(shown) \(more)"    }}/// What a cassette says, read off its card by the face that draws it.struct CassetteWords {    /// The label's title, by hand.    var title: String?    /// The titles its smaller hand line names, as many as fit, then "+N";    /// else `byline`, whole.    var titles: [String] = []    var byline: String?    /// The counter at rest: the tape's length.    var length: String?    /// The player's own card: its hubs step back and on, its window scrubs.    var steps = false    /// The tape's songs, for the packs.    var songs: [CassetteSong] = []}/// The bare cassette, tilted, from its words and where the player stands.struct BareCassette: View {    let words: CassetteWords    let play: TrackPlay    let toggle: (() -> Void)?    let seek: (TimeInterval) -> Void    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @State private var dragged: TimeInterval?    var body: some View {        let knobs = CassetteKnobs.self        GeometryReader { box in            let width = min(knobs.widest, box.size.width / knobs.room.width,                            box.size.height / knobs.room.height * knobs.shell.width / knobs.shell.height)            let s = max(0, width) / knobs.shell.width            let held = play.held && play.song != nil            let wound = CassetteTape.wound(words.songs, play)            let turned = held && !reduceMotion ? CassetteTape.position(words.songs, play) * knobs.turnRate : 0            ZStack(alignment: .topLeading) {                CassettePainted(name: "cassette-shell-shadow").placed(knobs.shadow, s)                ZStack(alignment: .topLeading) {                    CassettePainted(name: "cassette-window-dark").placed(knobs.window, s)                    if !words.songs.isEmpty {                        pack(CassetteTape.radius(1 - wound), at: knobs.hubs[0], s)                        pack(CassetteTape.radius(wound), at: knobs.hubs[1], s)                        CassettePainted(name: "cassette-tape").placed(knobs.tape, s)                    }                }                .frame(width: knobs.shell.width * s, height: knobs.shell.height * s, alignment: .topLeading)                .clipShape(InsideShape(s: s))                CassettePainted(name: "cassette-shell").placed(CGRect(origin: .zero, size: knobs.shell), s)                // The shell is the cassette's one element: its tap plays, the                // hubs, label and counter stand over it as their own.                Color.clear                    .placed(CGRect(origin: .zero, size: knobs.shell), s)                    .accessibilityElement()                    .accessibilityLabel(ShellLines.line("faces", play.held && play.playing ? "media.pause" : "media.play"))                    .accessibilityValue(words.title ?? "")                    .accessibilityAddTraits(.isButton)                    .accessibilityAction { toggle?() }                    .accessibilityIdentifier("cassette")                hubs(turned: turned, s)                CassettePainted(name: "cassette-label-blank").placed(knobs.label, s)                label(s)                counter(held: held, s)                window(held: held, s)            }            .frame(width: knobs.shell.width * s, height: knobs.shell.height * s, alignment: .topLeading)            .contentShape(RoundedRectangle(cornerRadius: knobs.insideCorner * s))            .onTapGesture { toggle?() }            .accessibilityElement(children: .contain)            .facePart(.play)            .rotationEffect(.degrees(knobs.tilt))            .frame(width: box.size.width, height: box.size.height)        }    }    /// A pack `radius` round the hub at `centre`, under the shell.    private func pack(_ radius: CGFloat, at centre: CGPoint, _ s: CGFloat) -> some View {        let knobs = CassetteKnobs.self        let side = radius * knobs.packPainted / knobs.packPaintedRadius        return CassettePainted(name: "cassette-pack")            .placed(CGRect(x: centre.x - side / 2, y: centre.y - side / 2, width: side, height: side), s)    }    /// The two hubs, turned; on the player's own card the left steps back a    /// song and the right on.    private func hubs(turned: Double, _ s: CGFloat) -> some View {        let knobs = CassetteKnobs.self        return ZStack(alignment: .topLeading) {            ForEach(Array(knobs.hubs.enumerated()), id: \.offset) { index, centre in                let frame = CGRect(x: centre.x - knobs.hub / 2, y: centre.y - knobs.hub / 2, width: knobs.hub, height: knobs.hub)                let hub = CassettePainted(name: "cassette-hub")                    .frame(width: frame.width * s, height: frame.height * s)                    .rotationEffect(.degrees(turned + knobs.hubAngles[index]))                    .contentShape(Circle())                if words.steps {                    hub                        .accessibilityElement()                        .accessibilityLabel(ShellLines.line("faces", index == 0 ? "hifi.previous" : "hifi.next"))                        .accessibilityAddTraits(.isButton)                        .accessibilityIdentifier(index == 0 ? "cassette-previous" : "cassette-next")                        .facePart(index == 0 ? .previous : .next)                        .offset(x: frame.minX * s, y: frame.minY * s)                } else {                    hub                        .accessibilityHidden(true)                        .offset(x: frame.minX * s, y: frame.minY * s)                }            }        }    }    /// The label's words by hand: the title above the red rule, the smaller    /// line under it.    private func label(_ s: CGFloat) -> some View {        let knobs = CassetteKnobs.self        return ZStack(alignment: .topLeading) {            if let title = words.title {                Text(title)                    .font(CottonFonts.signature(knobs.titleSize * s))                    .lineLimit(1)                    .minimumScaleFactor(0.45)                    .foregroundStyle(knobs.handInk)                    .accessibilityAddTraits(.isHeader)                    .accessibilityIdentifier("deck-title")                    .facePart(.title)                    .placed(CGRect(x: knobs.ink.minX, y: knobs.titleCentre - knobs.titleSize * 0.75,                                   width: knobs.ink.width, height: knobs.titleSize * 1.5), s)            }            line                .font(CottonFonts.signature(knobs.lineSize * s))                .lineLimit(1)                .foregroundStyle(knobs.handInk)                .accessibilityIdentifier("cassette-line")                .placed(CGRect(x: knobs.shell.width / 2 - knobs.lineWidth / 2, y: knobs.lineCentre - knobs.lineSize * 0.75,                               width: knobs.lineWidth, height: knobs.lineSize * 1.5), s)        }    }    /// The smaller hand line: the byline whole, else as many titles as fit    /// and "+N" for the rest.    @ViewBuilder private var line: some View {        if let byline = words.byline {            Text(byline).minimumScaleFactor(0.6)        } else if !words.titles.isEmpty {            let most = min(words.titles.count, CassetteKnobs.mostNamed)            ViewThatFits(in: .horizontal) {                ForEach(Array(stride(from: most, through: 1, by: -1)), id: \.self) { named in                    Text(CassetteTape.named(words.titles, named)).fixedSize()                }                Text(CassetteTape.named(words.titles, 1)).truncationMode(.middle)            }        }    }    /// The figures on the lower shell: the time into the held song, else the    /// tape's length.    private func counter(held: Bool, _ s: CGFloat) -> some View {        let knobs = CassetteKnobs.self        let said = held ? TrackClock.said(dragged ?? play.elapsed) : (words.length ?? "")        return Text(said)            .font(CottonFonts.type(knobs.counterSize * s))            .monospacedDigit()            .lineLimit(1)            .foregroundStyle(MusicMaterial.figure.colour.opacity(knobs.counterInk))            .accessibilityLabel(ShellLines.line("faces", "recording.position"))            .accessibilityValue(said)            .accessibilityIdentifier("cassette-counter")            .placed(CGRect(x: knobs.counterCentre.x - 200, y: knobs.counterCentre.y - knobs.counterSize,                           width: 400, height: knobs.counterSize * 2), s)    }    /// The centre window, on the player's own card while it holds the tape:    /// a drag across it moves the playhead in the held song. On a deck's    /// card a drag is the deck's, and moves it.    @ViewBuilder private func window(held: Bool, _ s: CGFloat) -> some View {        let frame = CassetteKnobs.centreWindow        if words.steps, held, play.duration > 0 {            Color.clear                .contentShape(Rectangle())                .frame(width: frame.width * s, height: frame.height * s)                .gesture(                    DragGesture(minimumDistance: 10)                        .onChanged { drag in                            guard frame.width * s > 0 else { return }                            dragged = TimeInterval(min(1, max(0, drag.location.x / (frame.width * s)))) * play.duration                        }                        .onEnded { _ in                            if let dragged { seek(dragged) }                            dragged = nil                        })                .accessibilityHidden(true)                .facePart(.scrub)                .offset(x: frame.minX * s, y: frame.minY * s)        }    }}/// The outline the packs, the inside and the tape keep within.private struct InsideShape: Shape {    let s: CGFloat    func path(in rect: CGRect) -> Path {        let inside = CassetteKnobs.inside        return Path(roundedRect: CGRect(x: inside.minX * s, y: inside.minY * s, width: inside.width * s, height: inside.height * s),                    cornerRadius: CassetteKnobs.insideCorner * s, style: .continuous)    }}/// One of the cassette's paintings, stretched to its frame; nothing where the/// build carries no pictures.private struct CassettePainted: View {    let name: String    var body: some View {        if let image = CottonMedia.image(name) {            image.resizable().interpolation(.high).accessibilityHidden(true)        }    }}private extension View {    /// This view laid at `rect` of the shell, in its pixels, scaled by `s`.    func placed(_ rect: CGRect, _ s: CGFloat) -> some View {        frame(width: rect.width * s, height: rect.height * s)            .offset(x: rect.minX * s, y: rect.minY * s)    }}