Cotton code
405 lines · 17.9 KB · SwiftRaw
// An ARTIST as a CRATE DIVIDER (the owner's go, 4 Nov 2026; the dark room's// picture `artists`): the artist's face in Music's Artists deck, a bare object// standing on the music's black tolex (`FaceGround.tolex`) with no paper and// no rule of the deck's. A low black crate, and standing in it the black// divider card, the artist's NAME in cream Libre Caslon on its raised tab —// one line, shrinking before it wraps, two at most — and on its foot the// artist's COUNTS in small capitals ("4 albums · 38 songs"). Behind the// divider the artist's albums stand in the crate, each a SPINE rising above// the last: up to five, the newest at the back, each tinted from its cover's// colour (the mean of its pixels) where it has one, else a warm grey, its// title in small cream serif on its left. An artist with no album stands its// divider alone; an empty crate is the shell's empty words, never this face.//// PAINTED (`Media.xcassets`, `scripts/import-music-materials.py divider`):// the crate, the divider, the blank spine and the divider's shadow are// pictures cut from wordless paintings. The crate is laid in its own// 1254 x 925 box and everything below is placed in it, scaled by the drawn// width over 1254, as measured off the paint (`ArtistDividerFaceKnobs`), not// as `layout.json` places them: there the divider stands so high in the crate// that it hides the spines whole. The crate's front is laid again over the// divider's foot and the spines', so they stand in it; its painted back wall,// stepped like a divider of its own, is left off above its side walls, as the// picture has no back wall above the albums. The face draws live only what// the data decides: every word, how many spines stand, and their tints.//// THE PARTS, tagged (`facePart`): the tab is `title`, the spines `body`, the// counts `state`.//// Every word is the card's: `title` (the artist's name), `albums` (a list of// the artist's albums, oldest first, each an object of `title` and its cover// `photo`), and the counts the deck read for the card (`DeckCard.related`,// the core's own plural words). A cover's colour is whatever draws pictures// says it is (`facePictureTint`).import CottonPaperimport CottonValuesimport SwiftUIenum ArtistDividerFaceKnobs {    // THE CRATE'S BOX every placement is in, in the paintings' pixels: the    // face draws the whole drawing — the spines above the crate, the crate    // under them — as wide as its room lets, never wider than `widest`.    static let box = CGSize(width: 1254, height: 925)    static let whole = CGRect(x: 0, y: -390, width: 1254, height: 1315)    static let widest: CGFloat = 340    /// Where the crate's painted front begins (its lip's brass edge), laid    /// again over what stands in the crate; and where its side walls end at    /// the back, above which its painted back wall is left off.    static let lip: CGFloat = 756    static let backWall: CGFloat = 392    // THE DIVIDER, standing in the crate inside its side walls, its foot    // behind the crate's front; its painting's tab (measured off its alpha:    // the tab's sides at its shoulder, its top and its shoulder) and its    // shadow's reach round it.    static let divider = CGRect(x: 97, y: 62, width: 1060, height: 738)    static let dividerPainted = CGSize(width: 1138, height: 792)    static let tabPainted = CGRect(x: 192, y: 5, width: 750, height: 117)    static let shadowReach: CGFloat = 75    // THE NAME on the tab, inside its edges: one line at its size, else a    // step or two smaller, else two lines smaller still.    static let nameInset = CGSize(width: 34, height: 10)    static let nameSize: CGFloat = 62    static let nameSteps: [CGFloat] = [1, 0.85, 0.72]    static let nameTwoLines: CGFloat = 0.6    // THE COUNTS on the divider's foot, clear of the crate's front.    static let counts = CGRect(x: 147, y: 668, width: 960, height: 52)    static let countsSize: CGFloat = 30    static let countsTracking: CGFloat = 0.16    // THE SPINES behind the divider: at most `most`; the front one's top    // this far above the tab's top, each further back `step` higher and    // `narrowing` narrower each side, the front one `inset` inside the    // divider's sides. Each is a sleeve standing in the crate down behind    // the divider, its painted spine laid on its top `band`.    static let most = 5    static let frontRise: CGFloat = 84    static let step: CGFloat = 88    static let inset: CGFloat = 30    static let narrowing: CGFloat = 12    static let band: CGFloat = 110    static let sleeveFoot: CGFloat = 760    /// The album's title on the spine: from its left, in its band.    static let spineTitle = CGRect(x: 40, y: 10, width: 700, height: 70)    static let spineTitleSize: CGFloat = 42    /// A cover's colour no lighter than this, so the cream title reads.    static let spineLightest: Double = 0.36}/// What the divider reads off its card.public enum ArtistDivider {    /// One of the artist's albums: its title and its cover's key.    public struct Album: Equatable, Sendable {        public let title: String?        public let photo: String?        public init(title: String?, photo: String?) {            self.title = title            self.photo = photo        }    }    /// The artist's albums, oldest first, as the card's `albums` lists them.    public static func albums(_ card: DeckCard) -> [Album] {        guard case .list(let listed)? = card.fields["albums"] else { return [] }        return listed.compactMap { value in            guard case .object(let album) = value else { return nil }            return Album(title: nonEmpty(album["title"]?.text), photo: nonEmpty(album["photo"]?.text))        }    }    /// The spines that stand, front to back: the newest `most` albums, the    /// newest at the back.    public static func spines(_ card: DeckCard) -> [Album] {        Array(albums(card).suffix(ArtistDividerFaceKnobs.most))    }    /// The counts on the divider's foot: the deck's counts of the artist's    /// albums and songs, joined as the cards join words; nil with none.    public static func counts(_ card: DeckCard) -> String? {        let said = card.related.map(\.said).filter { !$0.isEmpty }        return said.isEmpty ? nil : said.joined(separator: ShellLines.line("cards", "join"))    }    /// A spine's colour: its cover's, darkened until the cream title reads    /// on it; the warm grey stock where it has no cover's colour.    public static func tint(_ mean: Color?) -> Color {        guard let mean else { return MusicMaterial.spine.colour }        let rgb = mean.resolve(in: EnvironmentValues())        let (red, green, blue) = (Double(rgb.red), Double(rgb.green), Double(rgb.blue))        let light = 0.2126 * red + 0.7152 * green + 0.0722 * blue        guard light > ArtistDividerFaceKnobs.spineLightest else { return mean }        // Mixed toward black in the device's own channels, which scales each        // channel by the same share and so keeps the cover's hue.        return mean.mix(with: .black, by: 1 - ArtistDividerFaceKnobs.spineLightest / light, in: .device)    }    private static func nonEmpty(_ words: String?) -> String? {        guard let words, !words.isEmpty else { return nil }        return words    }}struct ArtistDividerFace: View {    let card: DeckCard    @Environment(\.facePictureTint) private var pictureTint    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        let knobs = ArtistDividerFaceKnobs.self        GeometryReader { room in            let width = min(room.size.width, knobs.widest, room.size.height * knobs.whole.width / knobs.whole.height)            let s = width / knobs.whole.width            ZStack(alignment: .topLeading) {                crate(from: knobs.backWall, s)                DividerPainted(name: "divider-shadow")                    .placed(knobs.divider.insetBy(dx: -knobs.shadowReach, dy: -knobs.shadowReach), s)                spines(s)                DividerPainted(name: "divider").placed(knobs.divider, s)                crate(from: knobs.lip, s)                name(s)                counts(s)            }            .frame(width: knobs.box.width * s, height: knobs.box.height * s, alignment: .topLeading)            .offset(y: -knobs.whole.minY * s)            .frame(width: width, height: knobs.whole.height * s, alignment: .topLeading)            .frame(width: room.size.width, height: room.size.height)            .accessibilityElement(children: .contain)            .accessibilityIdentifier("artist-divider")        }    }    /// The crate's painting from `top` down: from its side walls' tops for    /// the crate under everything, from its lip for its front laid over.    private func crate(from top: CGFloat, _ s: CGFloat) -> some View {        let knobs = ArtistDividerFaceKnobs.self        return DividerPainted(name: "crate")            .frame(width: knobs.box.width * s, height: knobs.box.height * s)            .mask(alignment: .topLeading) {                Rectangle()                    .frame(width: knobs.box.width * s, height: (knobs.box.height - top) * s)                    .offset(y: top * s)            }    }    /// Where the divider's painted tab is, in the crate's box.    private var tab: CGRect {        let knobs = ArtistDividerFaceKnobs.self        let k = knobs.divider.width / knobs.dividerPainted.width        return CGRect(            x: knobs.divider.minX + knobs.tabPainted.minX * k, y: knobs.divider.minY + knobs.tabPainted.minY * k,            width: knobs.tabPainted.width * k, height: knobs.tabPainted.height * k)    }    // MARK: The spines    /// Each album's spine, the back one first so the front ones stand over    /// it: a sleeve of its tint down behind the divider, the painted spine    /// over its top, its title on its left.    private func spines(_ s: CGFloat) -> some View {        let knobs = ArtistDividerFaceKnobs.self        let albums = ArtistDivider.spines(card)        let front = tab.minY - knobs.frontRise        return ZStack(alignment: .topLeading) {            ForEach(albums.indices.reversed(), id: \.self) { place in                let album = albums[place]                let side = knobs.inset + knobs.narrowing * CGFloat(place)                let top = front - knobs.step * CGFloat(place)                let rect = CGRect(                    x: knobs.divider.minX + side, y: top,                    width: knobs.divider.width - 2 * side, height: knobs.sleeveFoot - top)                DividerSpine(                    title: album.title, tint: ArtistDivider.tint(album.photo.flatMap(pictureTint)),                    width: rect.width, height: rect.height, s: s)                    .at(rect, s)            }        }        .accessibilityElement()        .accessibilityLabel(albums.compactMap(\.title).joined(separator: ShellLines.line("cards", "join")))        .accessibilityIdentifier("divider-spines")        .facePart(.body)    }    // MARK: The divider's words    /// The artist's name on the tab, in cream.    private func name(_ s: CGFloat) -> some View {        let knobs = ArtistDividerFaceKnobs.self        let room = tab.insetBy(dx: knobs.nameInset.width, dy: knobs.nameInset.height)        return Group {            if let name = card.text("title") {                DividerName(words: name, s: s)                    .foregroundStyle(MusicMaterial.engraving.colour)                    .frame(width: room.width * s, height: room.height * s)                    .accessibilityElement()                    .accessibilityLabel(name)                    .accessibilityAddTraits(.isHeader)                    .accessibilityIdentifier("deck-title")                    .facePart(.title)                    .at(room, s)            }        }    }    /// The counts on the divider's foot, in small capitals.    private func counts(_ s: CGFloat) -> some View {        let knobs = ArtistDividerFaceKnobs.self        return Group {            if let counts = ArtistDivider.counts(card) {                Text(counts.uppercased())                    .font(CottonFonts.caslon(knobs.countsSize * s))                    .tracking(knobs.countsTracking * knobs.countsSize * s)                    .lineLimit(1)                    .minimumScaleFactor(0.6)                    .foregroundStyle(MusicMaterial.engraving.colour)                    .frame(width: knobs.counts.width * s, height: knobs.counts.height * s)                    .accessibilityLabel(counts)                    .accessibilityIdentifier("divider-counts")                    .facePart(.state)                    .at(knobs.counts, s)            }        }    }}/// One album standing in the crate: a sleeve of its tint, the painted spine/// laid over its top band and tinted, the album's title on it.private struct DividerSpine: View {    let title: String?    let tint: Color    /// Its sleeve's size, in the crate's pixels.    let width: CGFloat    let height: CGFloat    let s: CGFloat    var body: some View {        let knobs = ArtistDividerFaceKnobs.self        ZStack(alignment: .topLeading) {            tint.overlay(Color.black.opacity(0.35))                .frame(width: width * s, height: (height - knobs.band / 2) * s)                .offset(y: knobs.band / 2 * s)            if let spine = CottonMedia.image("spine-blank") {                ZStack {                    tint                    spine.resizable().interpolation(.high).blendMode(.softLight)                }                .mask(spine.resizable())                .frame(width: width * s, height: knobs.band * s)            } else {                tint.frame(width: width * s, height: knobs.band * s)            }            if let title {                Text(title)                    .font(CottonFonts.caslon(knobs.spineTitleSize * s))                    .italic()                    .lineLimit(1)                    .minimumScaleFactor(0.6)                    .foregroundStyle(MusicMaterial.engraving.colour)                    .frame(width: min(knobs.spineTitle.width, width - knobs.spineTitle.minX * 2) * s, height: knobs.spineTitle.height * s, alignment: .leading)                    .offset(x: knobs.spineTitle.minX * s, y: knobs.spineTitle.minY * s)            }        }        .frame(width: width * s, height: height * s, alignment: .topLeading)        .allowsHitTesting(false)        .accessibilityHidden(true)    }}/// The artist's name in Libre Caslon: one line at its size, else a step or/// two smaller, else two lines smaller still, shrinking before it wraps.private struct DividerName: View {    let words: String    let s: CGFloat    var body: some View {        let knobs = ArtistDividerFaceKnobs.self        ViewThatFits(in: .horizontal) {            ForEach(knobs.nameSteps, id: \.self) { step in                line(knobs.nameSize * step).lineLimit(1).fixedSize()            }            line(knobs.nameSize * knobs.nameTwoLines)                .lineLimit(2)                .minimumScaleFactor(0.7)                .multilineTextAlignment(.center)        }    }    private func line(_ size: CGFloat) -> Text {        Text(words).font(CottonFonts.caslon(size * s))    }}/// One of the divider's paintings, stretched to its frame; nothing where/// the build carries no pictures. A painting takes no tap.private struct DividerPainted: 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 crate'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 crate'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 divider's face, and the artists it is reviewed with.public enum ArtistDividerFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .tolex    public static let face = Face(id: "artist.divider", specimens: [        Specimen("three albums", lowTide),        Specimen("one album no cover", maraVance),        Specimen("eight albums", lanterns),    ]) { card, _, _ in        ArtistDividerFace(card: card)    }    static func artist(_ name: String, _ albums: [(String, String?)], counts: [(String, String, Int)]) -> DeckCard {        var card = DeckCard(face: .artistDivider, fields: [            "title": .text(name),            "albums": .list(albums.map { title, photo in                .object(["title": .text(title), "photo": photo.map(RecordValue.text) ?? .null])            }),        ])        card.related = counts.map { CardRelatedCount(id: $0.0, said: $0.1, count: $0.2) }        return card    }    /// Three albums, each with its cover.    public static let lowTide = artist(        "The Low Tide", [("Paper Moons", "waterfall"), ("Common Ground", "kelmoor-lake"), ("Night Ferry", "poster-ferry")],        counts: [("music_album", "3 albums", 3), ("song", "31 songs", 31)])    /// One album, no cover.    public static let maraVance = artist(        "Mara Vance", [("Slow Train", nil)], counts: [("music_album", "1 album", 1), ("song", "9 songs", 9)])    /// Eight albums, some covered: five spines stand, the newest five.    public static let lanterns = artist(        "Sixteen Lanterns", [            ("Harbour Lights", nil), ("Blue Hour", "verandah"), ("Slow Train", nil), ("Night Ferry", "poster-ferry"),            ("Common Ground", nil), ("Paper Moons", "waterfall"), ("Harbour Lights Live", "kelmoor-lake"),            ("The Blue Hour Sessions", "cover-harbour"),        ],        counts: [("music_album", "8 albums", 8), ("song", "96 songs", 96)])}