Cotton code
411 lines · 17.9 KB · SwiftRaw
// A SONG as a 7-INCH SINGLE IN ITS PAPER SLEEVE (the owner's go, 4 Nov 2026; the// dark room's picture `songs`): the song's face in Music's Songs deck, a bare// object lying on the music's black tolex (`FaceGround.tolex`) with no paper// and no rule of the deck's. The paper sleeve, cream or blue — the album's// colour, so an album's singles share one (`SongSingle.paper`) — the record// showing through its round window, and over the record's middle its LABEL: the// album's cover cropped round inside a cream paper ring where the song has// one, else the blank cream label; on either the song's name in a condensed// heavy sans above the spindle hole, two lines at most, its artist in small// capitals under the hole over a thin rule, and its length small at the// label's foot. A favourite wears a small brass star on the sleeve's upper// right corner. Its shadow lies under it.//// PAINTED (`Media.xcassets`, `scripts/import-music-materials.py single`): the// two sleeves, the record, the blank label and the shadow are pictures cut// from wordless paintings, each laid where the materials' `layout.json`// places it in the single's 1165 x 1165 box, scaled by the drawn width over// 1165. The face draws live only what the data decides: every word, the// cover, the paper's colour and the star.//// THE PARTS, tagged (`facePart`): the label is `picture`, the song's name// `title`, its artist `subtitle`, the star `stars`, and the record round the// label, in the window, `play`.//// Every word is the card's: `title`, `subtitle` (the artist), `album` (whose// title picks the paper), `length` (the core's clock, "4:02"), `favourite`// (a yes or no), and its picture is the album's cover (`photo`).import CottonPaperimport CottonValuesimport SwiftUIenum SongSingleFaceKnobs {    // THE SINGLE'S BOX every placement is in, in the paintings' pixels    // (`layout.json`): the face draws the box and its shadow as wide as its    // room lets, never wider than `widest`, and every place below is scaled    // by the drawn width over it.    static let box = CGSize(width: 1165, height: 1165)    static let shadow = CGRect(x: -80, y: -80, width: 1325, height: 1325)    static let widest: CGFloat = 340    static let record = CGRect(x: 70, y: 82, width: 1000, height: 1000)    /// The sleeve's round window (`windowEllipse`), where the record shows.    static let window = CGRect(x: 244, y: 250, width: 652, height: 665)    // THE LABEL, over the record's middle: its round, laid larger than the    // layout's (340) as the picture has it, filling the window but for a    // ring of the record, so its words read on a phone; its painting's    // pixels (`painted`), every place on it below being in them; the    // spindle hole cut through it (measured off `single-label-blank`); and,    // over a cover, the cream paper ring the cover sits in.    static let label = CGRect(x: 320, y: 332, width: 500, height: 500)    static let painted: CGFloat = 340    static let hole: CGFloat = 13    static let ring: CGFloat = 16    /// The veil over a cover, so the cream words read on any picture.    static let veil: Double = 0.42    // THE LABEL'S WORDS, in the label painting's pixels about its centre    // (170, 170), clear of the spindle hole: the name above it, the artist, the    // rule and the length below it.    static let titleBox = CGRect(x: 52, y: 40, width: 236, height: 104)    static let titleSize: CGFloat = 50    static let titleSteps: [CGFloat] = [1, 0.84, 0.7]    static let titleTwoLines: CGFloat = 0.62    static let artistBox = CGRect(x: 60, y: 192, width: 220, height: 34)    static let artistSize: CGFloat = 24    static let artistTracking: CGFloat = 0.12    static let rule = CGRect(x: 120, y: 234, width: 100, height: 2)    static let lengthBox = CGRect(x: 110, y: 244, width: 120, height: 34)    static let lengthSize: CGFloat = 22    // THE STAR on the sleeve's upper right corner: its centre and its    // width, and the inner points' reach as a share of the outer's.    static let star = CGPoint(x: 1052, y: 116)    static let starSide: CGFloat = 92    static let starWaist: CGFloat = 0.45}/// What the single reads off its card.public enum SongSingle {    /// The paper a single's sleeve is made of.    public enum Paper: String, Equatable, Sendable, CaseIterable {        case cream        case blue        /// Its painting in the catalogue.        public var painting: String { "single-sleeve-\(rawValue)" }    }    /// The sleeve's paper: picked by the album's title, so every single off    /// one album shares it, else by the song's own; cream for a card with    /// neither. A hash of the words (FNV-1a over their UTF-8), the same on    /// every phone and every launch, which Swift's own `hashValue` is not.    public static func paper(_ card: DeckCard) -> Paper {        guard let words = card.text("album") ?? card.text("title") else { return .cream }        var hash: UInt64 = 0xcbf2_9ce4_8422_2325        for byte in words.utf8 {            hash ^= UInt64(byte)            hash = hash &* 0x100_0000_01b3        }        // A high bit: FNV's lowest is only the parity of the bytes'.        return (hash >> 32) % 2 == 0 ? .cream : .blue    }    /// The card's song is a favourite.    public static func favourite(_ card: DeckCard) -> Bool {        if case .bool(true)? = card.fields["favourite"] { return true }        return false    }    /// The words the label carries, in their order: the song's name, its    /// artist in capitals and its length.    public static func label(_ card: DeckCard) -> [String] {        [card.text("title"), card.text("subtitle")?.uppercased(), card.text("length")].compactMap { $0 }    }}struct SongSingleFace: View {    let card: DeckCard    /// The album's cover; nil lays the blank label.    var cover: FacePicture?    public init(card: DeckCard, cover: FacePicture?) {        self.card = card        self.cover = cover    }    public var body: some View {        let knobs = SongSingleFaceKnobs.self        GeometryReader { room in            let width = min(room.size.width, room.size.height, knobs.widest)            let s = width / knobs.shadow.width            ZStack(alignment: .topLeading) {                SinglePainted(name: "single-shadow").placed(knobs.shadow, s)                SinglePainted(name: "single-record").placed(knobs.record, s)                label(s)                SinglePainted(name: SongSingle.paper(card).painting).placed(CGRect(origin: .zero, size: knobs.box), s)                record(s)                labelParts(s)                if SongSingle.favourite(card) { star(s) }            }            .frame(width: knobs.box.width * s, height: knobs.box.height * s, alignment: .topLeading)            .offset(x: -knobs.shadow.minX * s, y: -knobs.shadow.minY * s)            .frame(width: width, height: width, alignment: .topLeading)            .frame(width: room.size.width, height: room.size.height)            .accessibilityElement(children: .contain)            .accessibilityIdentifier("song-single")        }    }    // MARK: The label    /// The label under the record: the cover cropped round in a cream paper    /// ring, the spindle hole through it, else the blank label.    private func label(_ s: CGFloat) -> some View {        let knobs = SongSingleFaceKnobs.self        let side = knobs.label.width * s        let k = knobs.label.width / knobs.painted        let inner = (knobs.painted / 2 - knobs.ring) / (knobs.painted / 2)        return ZStack {            if let cover {                SinglePainted(name: "single-label-blank")                cover                    .frame(width: side * inner, height: side * inner)                    .clipShape(Circle())                Circle()                    .fill(Color.black.opacity(knobs.veil))                    .frame(width: side * inner, height: side * inner)                Circle()                    .fill(MusicMaterial.window.colour)                    .frame(width: knobs.hole * 2 * k * s, height: knobs.hole * 2 * k * s)            } else {                SinglePainted(name: "single-label-blank")            }        }        .frame(width: side, height: side)        .allowsHitTesting(false)        .offset(x: knobs.label.minX * s, y: knobs.label.minY * s)    }    /// The label's words over it, each its part: the name, the artist, the    /// rule and the length; the label itself the picture under them.    private func labelParts(_ s: CGFloat) -> some View {        let knobs = SongSingleFaceKnobs.self        let ink = cover == nil ? MusicMaterial.labelInk.colour : MusicMaterial.engraving.colour        let k = knobs.label.width / knobs.painted        let inLabel = { (rect: CGRect) in            CGRect(x: knobs.label.minX + rect.minX * k, y: knobs.label.minY + rect.minY * k, width: rect.width * k, height: rect.height * k)        }        return ZStack(alignment: .topLeading) {            Circle()                .fill(Color.clear)                .contentShape(Circle())                .frame(width: knobs.label.width * s, height: knobs.label.height * s)                .accessibilityElement()                .accessibilityLabel(card.text("album") ?? card.text("title") ?? "")                .accessibilityIdentifier("single-label")                .facePart(.picture)                .at(knobs.label, s)            if let title = card.text("title") {                SingleTitle(words: title, s: s * k)                    .foregroundStyle(ink)                    .frame(width: knobs.titleBox.width * k * s, height: knobs.titleBox.height * k * s, alignment: .bottom)                    .accessibilityElement()                    .accessibilityLabel(title)                    .accessibilityAddTraits(.isHeader)                    .accessibilityIdentifier("deck-title")                    .facePart(.title)                    .at(inLabel(knobs.titleBox), s)            }            if let artist = card.text("subtitle") {                // Spaced while it fits, else close set and shrinking.                ViewThatFits(in: .horizontal) {                    artistLine(artist, tracking: knobs.artistTracking, k * s).fixedSize()                    artistLine(artist, tracking: 0, k * s).minimumScaleFactor(0.4)                }                    .foregroundStyle(ink)                    .frame(width: knobs.artistBox.width * k * s, height: knobs.artistBox.height * k * s)                    .accessibilityLabel(artist)                    .accessibilityIdentifier("face-byline")                    .facePart(.subtitle)                    .at(inLabel(knobs.artistBox), s)            }            Rectangle()                .fill(ink)                .frame(width: knobs.rule.width * k * s, height: max(0.5, knobs.rule.height * k * s))                .allowsHitTesting(false)                .accessibilityHidden(true)                .at(inLabel(knobs.rule), s)            if let length = card.text("length") {                Text(length)                    .font(CottonFonts.serif(knobs.lengthSize * k * s))                    .monospacedDigit()                    .lineLimit(1)                    .fixedSize()                    .foregroundStyle(ink)                    .frame(width: knobs.lengthBox.width * k * s, height: knobs.lengthBox.height * k * s)                    .allowsHitTesting(false)                    .accessibilityIdentifier("single-length")                    .at(inLabel(knobs.lengthBox), s)            }        }    }    /// The artist in small capitals, spaced by `tracking` of its size.    private func artistLine(_ artist: String, tracking: CGFloat, _ s: CGFloat) -> some View {        let size = SongSingleFaceKnobs.artistSize * s        return Text(artist.uppercased())            .font(CottonFonts.serif(size))            .tracking(tracking * size)            .lineLimit(1)    }    // MARK: The record and the star    /// The record seen through the window: a tap plays it.    private func record(_ s: CGFloat) -> some View {        let knobs = SongSingleFaceKnobs.self        let side = min(knobs.window.width, knobs.window.height)        let round = CGRect(x: knobs.window.midX - side / 2, y: knobs.window.midY - side / 2, width: side, height: side)        return Circle()            .fill(Color.clear)            .contentShape(Circle())            .frame(width: side * s, height: side * s)            .accessibilityElement()            .accessibilityLabel(ShellLines.line("faces", "media.play"))            .accessibilityValue(card.text("title") ?? "")            .accessibilityAddTraits(.isButton)            .accessibilityIdentifier("single-record")            .facePart(.play)            .at(round, s)    }    /// The brass star on the sleeve's corner: lit from the lamp, upper left.    private func star(_ s: CGFloat) -> some View {        let knobs = SongSingleFaceKnobs.self        let side = knobs.starSide        let rect = CGRect(x: knobs.star.x - side / 2, y: knobs.star.y - side / 2, width: side, height: side)        return SingleStar(waist: knobs.starWaist)            .fill(LinearGradient(                colors: [MusicMaterial.brass.colour, MusicMaterial.brassShade.colour],                startPoint: .topLeading, endPoint: .bottomTrailing))            .overlay(SingleStar(waist: knobs.starWaist).stroke(MusicMaterial.brassShade.colour, lineWidth: max(0.5, 3 * s)))            .shadow(color: .black.opacity(0.45), radius: 4 * s, x: 3 * s, y: 4 * s)            .frame(width: side * s, height: side * s)            .accessibilityElement()            .accessibilityLabel(ShellLines.line("faces", "single.favourite"))            .accessibilityIdentifier("single-star")            .facePart(.stars)            .at(rect, s)    }}/// The song's name in a condensed heavy sans: one line at its size, else a/// step or two smaller, else two lines smaller still, shrinking before it/// wraps.private struct SingleTitle: View {    let words: String    let s: CGFloat    var body: some View {        let knobs = SongSingleFaceKnobs.self        ViewThatFits(in: .horizontal) {            ForEach(knobs.titleSteps, id: \.self) { step in                line(knobs.titleSize * step).lineLimit(1).fixedSize()            }            line(knobs.titleSize * knobs.titleTwoLines)                .lineLimit(2)                .minimumScaleFactor(0.5)                .multilineTextAlignment(.center)        }    }    private func line(_ size: CGFloat) -> Text {        Text(words).font(.system(size: size * s, weight: .heavy).width(.condensed))    }}/// A five-pointed star, its points at the frame's edge, its waist the inner/// points' reach as a share of the outer's.private struct SingleStar: Shape {    let waist: CGFloat    func path(in rect: CGRect) -> Path {        let centre = CGPoint(x: rect.midX, y: rect.midY + rect.height * 0.04)        let outer = min(rect.width, rect.height) / 2        var path = Path()        for point in 0..<10 {            let reach = point % 2 == 0 ? outer : outer * waist            let angle = Double(point) * .pi / 5 - .pi / 2            let at = CGPoint(x: centre.x + reach * CGFloat(cos(angle)), y: centre.y + reach * CGFloat(sin(angle)))            if point == 0 { path.move(to: at) } else { path.addLine(to: at) }        }        path.closeSubpath()        return path    }}/// One of the single's paintings, stretched to its frame; nothing where the/// build carries no pictures. A painting takes no tap: the parts over it do.private struct SinglePainted: View {    let name: String    var body: some View {        if let image = CottonMedia.image(name) {            image.resizable().interpolation(.high).allowsHitTesting(false).accessibilityHidden(true)        }    }}private extension View {    /// This view laid at `rect` of the single's box, 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)    }    /// This view moved to `rect`'s corner of the single's box: last, after a    /// part is tagged (`facePart`), so the region the deck reads for it is    /// where it is drawn.    func at(_ rect: CGRect, _ s: CGFloat) -> some View {        offset(x: rect.minX * s, y: rect.minY * s)    }}/// The single's face, and the songs it is reviewed with.public enum SongSingleFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .tolex    public static let face = Face(id: "song.single", specimens: [        Specimen("with cover", harbour, picture: "poster-ferry"),        Specimen("no cover", train),        Specimen("favourite", favourite, picture: "kelmoor-lake"),        Specimen("long title", lanterns),    ]) { card, picture, _ in        SongSingleFace(card: card, cover: picture)    }    /// An invented song off an invented album, 4:02 long.    public static let harbour = DeckCard(face: .songSingle, fields: [        "title": .text("Harbour Lights"),        "subtitle": .text("The Low Tide"),        "album": .text("Night Ferry"),        "length": .text("4:02"),    ])    /// Another album's song, no cover.    public static let train = DeckCard(face: .songSingle, fields: [        "title": .text("Slow Train"),        "subtitle": .text("Mara Vance"),        "album": .text("Common Ground"),        "length": .text("3:17"),    ])    /// A favourite.    public static let favourite = DeckCard(face: .songSingle, fields: [        "title": .text("Blue Hour"),        "subtitle": .text("Sixteen Lanterns"),        "album": .text("Paper Moons"),        "length": .text("5:48"),        "favourite": .bool(true),    ])    /// A long song name off a long album.    public static let lanterns = DeckCard(face: .songSingle, fields: [        "title": .text("The Slow Train Home Through Sixteen Lanterns"),        "subtitle": .text("Mara Vance and The Low Tide"),        "album": .text("Sixteen Lanterns and the Blue Hour Sessions"),        "length": .text("11:09"),    ])}