Cotton code
492 lines · 22.2 KB · SwiftRaw
// The FILM as a VIDEO in its SLEEVE (the owner's pick, 30 Oct 2026; the film// picture `objects-2/books-films/7-film-vhs`): a worn cardboard VHS sleeve// lying flat with its black cassette half drawn out to the right, bare on the// films' claret baize (`FaceGround.claret`) with no paper and no rule of the// deck's. The sleeve's card and its rubbed corners, the cassette with its// windows and reels, the round sticker, the spine label and the baize are// PAINTED (`Media.xcassets`, cut and imported by// `scripts/import-film-materials.py`); the face draws live only what the// card decides:////   the sleeve's front is the film's own poster, drawn first and multiplied//   by the sleeve's card, its bumped corners and rubbed edges laid over it,//   with the year and the running time printed under its head ("1974 ·//   1:52:00"); a film kept without a poster has a plain printed sleeve, its//   title set large in bold condensed capitals.//   the round sticker on the cassette: once watched, the core's word for it//   and the day ("WATCHED" over "18 OCT") over the rating as stars struck in//   red, as many filled as it has, a half one half filled, the rest//   outlined; still to watch, its state alone ("TO WATCH"), no stars.//   the spine label: the title typed in capitals down it.//// Tagged: the poster (`picture`), or a plain sleeve's title, and the spine// label (`title`); the year's line (`subtitle`); the sticker's word (`state`)// and its day (`when`). Stepped by a tap, it cuts.//// Every word is the core's (`DeckCard`): the face only prints and types them,// in capitals.import CottonPaperimport CottonValuesimport CoreTextimport SwiftUI#if canImport(UIKit)    import UIKit#else    import AppKit#endifenum FilmVHSFaceKnobs {    // THE SLEEVE (`vhs-sleeve-grain`, 860 by 1467 at its cut) and THE    // CASSETTE (`vhs-cassette`, 818 by 1456): each's width over its height    // and its shadow's reach as a share of its width; on the cassette, the    // sticker's middle and its width, and the spine label's rect, as shares    // of the cassette, read off the painting (its label area between the    // windows, its spine's recess) — a repainted cassette owes new knobs.    static let sleeveAspect: CGFloat = 860.0 / 1467.0    static let sleeveShadowReach: CGFloat = 0.0802    static let cassetteAspect: CGFloat = 818.0 / 1456.0    static let cassetteShadowReach: CGFloat = 0.0795    static let sticker = CGPoint(x: 0.43, y: 0.495)    static let stickerWidth: CGFloat = 0.5    static let spine = CGRect(x: 0.852, y: 0.17, width: 0.104, height: 0.66)    /// The cassette's height, of the sleeve's, and how much of its width    /// stays in the sleeve.    static let cassetteHeight: CGFloat = 0.95    static let inSleeve: CGFloat = 0.2    /// The two in the card's room: the most of its width and height.    static let fillWidth: CGFloat = 0.97    static let fillHeight: CGFloat = 0.92    /// The poster laid a hair past the sleeve's edges, of its width.    static let bleed: CGFloat = 0.006    // THE SLEEVE'S PRINT, as shares of its height: the year's line under a    // poster's head, its size; a plain sleeve's title, its top, its size of    // the sleeve's width, the most lines it takes, its margin.    static let yearAt: CGFloat = 0.3    static let yearSize: CGFloat = 0.042    static let plainTop: CGFloat = 0.07    static let plainTitle: CGFloat = 0.27    static let plainLines = 4    static let plainMargin: CGFloat = 0.09    // THE STICKER, as shares of its width: the words' size, the stars' size    // and their gap, of a star.    static let stickerType: CGFloat = 0.15    static let star: CGFloat = 0.12    static let starGap: CGFloat = 0.12    static let starsOf = 5    /// The spine label's type, of its width.    static let spineType: CGFloat = 0.5}/// What the sleeve and the cassette say.public enum FilmVHSSetting {    /// The year and the running time, as the cards join words.    public static func year(_ card: DeckCard) -> String? {        let made = [card.text("subtitle"), card.text("length")].compactMap { $0 }        return made.isEmpty ? nil : made.joined(separator: ShellLines.line("cards", "join"))    }    /// The sticker's words: the core's word for watched and the day, or the    /// state still to watch; nil, neither kept.    public static func sticker(_ card: DeckCard) -> (word: String, day: String?)? {        if let day = card.dated {            return ((card.label("date", kind: "film") ?? "").uppercased(), DayStamp.of(day))        }        return card.text("state").map { ($0.uppercased(), nil) }    }    /// A plain sleeve's title in its capitals, in lines on a sleeve `size`.    public static func plainTitle(_ card: DeckCard, sleeve size: CGSize) -> [String] {        guard let title = card.text("title")?.split(whereSeparator: \.isNewline).joined(separator: " ") else { return [] }        let knobs = FilmVHSFaceKnobs.self        return TornPageSetting.lines(            title.uppercased(), font: condensed(knobs.plainTitle * size.width),            width: size.width * (1 - 2 * knobs.plainMargin), limit: knobs.plainLines).map(\.words)    }    /// The bold condensed capitals a plain sleeve's title is set in    /// (`CottonFonts.flap`), as CoreText measures them.    static func condensed(_ size: CGFloat) -> CTFont {        #if canImport(UIKit)            UIFont.systemFont(ofSize: max(1, size), weight: .semibold, width: .compressed) as CTFont        #else            NSFont.systemFont(ofSize: max(1, size), weight: .semibold, width: .compressed) as CTFont        #endif    }}/// A painted layer, by its catalogue name, at the scale it was painted for;/// nil where this build carries no pictures.private func painted(_ name: String) -> Image? {    CottonMedia.image(name, scale: 3)}public struct FilmVHSFace<Poster: View>: View {    let card: DeckCard    /// The poster on the sleeve's front; nil prints a plain sleeve.    var poster: Poster?    public init(card: DeckCard, poster: Poster? = nil) {        self.card = card        self.poster = poster    }    public var body: some View {        let knobs = FilmVHSFaceKnobs.self        GeometryReader { box in            // The sleeve's height sets both: the cassette drawn out beside it.            let wide = knobs.sleeveAspect + knobs.cassetteHeight * knobs.cassetteAspect * (1 - knobs.inSleeve)            let height = min(box.size.height * knobs.fillHeight, box.size.width * knobs.fillWidth / wide)            VideoInSleeve(card: card, poster: poster, height: height)                .frame(width: height * wide, height: height)                .frame(width: box.size.width, height: box.size.height)        }    }}/// The cassette drawn out of its sleeve: their shadows, the cassette with its/// sticker and spine label, the sleeve over its left edge.private struct VideoInSleeve<Poster: View>: View {    let card: DeckCard    let poster: Poster?    let height: CGFloat    var body: some View {        let knobs = FilmVHSFaceKnobs.self        let sleeve = CGSize(width: height * knobs.sleeveAspect, height: height)        let cassette = CGSize(width: height * knobs.cassetteHeight * knobs.cassetteAspect, height: height * knobs.cassetteHeight)        let cassetteAt = CGPoint(x: sleeve.width - knobs.inSleeve * cassette.width, y: (height - cassette.height) / 2)        ZStack(alignment: .topLeading) {            if let shadow = painted("vhs-cassette-shadow") {                let reach = knobs.cassetteShadowReach * cassette.width                shadow.resizable().interpolation(.high)                    .frame(width: cassette.width + 2 * reach, height: cassette.height + 2 * reach)                    .offset(x: cassetteAt.x - reach, y: cassetteAt.y - reach)                    .accessibilityHidden(true)            }            Cassette(card: card, size: cassette)                .frame(width: cassette.width, height: cassette.height)                .offset(x: cassetteAt.x, y: cassetteAt.y)            if let shadow = painted("vhs-sleeve-shadow") {                let reach = knobs.sleeveShadowReach * sleeve.width                shadow.resizable().interpolation(.high)                    .frame(width: sleeve.width + 2 * reach, height: sleeve.height + 2 * reach)                    .offset(x: -reach, y: -reach)                    .accessibilityHidden(true)            }            Sleeve(card: card, poster: poster, size: sleeve)                .frame(width: sleeve.width, height: sleeve.height)        }        .frame(width: cassetteAt.x + cassette.width, height: height, alignment: .topLeading)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("film-vhs")    }}/// The sleeve's front: the poster multiplied by its card, its wear over it,/// the year's line printed under its head; or a plain printed sleeve.private struct Sleeve<Poster: View>: View {    let card: DeckCard    let poster: Poster?    let size: CGSize    var body: some View {        let knobs = FilmVHSFaceKnobs.self        let bleed = knobs.bleed * size.width        let grain = painted("vhs-sleeve-grain")        let title = poster == nil ? FilmVHSSetting.plainTitle(card, sleeve: size) : []        let titleSize = knobs.plainTitle * size.width        let year = FilmVHSSetting.year(card)        let yearSize = knobs.yearSize * size.height        let yearAt = poster == nil            ? knobs.plainTop * size.height + CGFloat(title.count) * titleSize * 1.05 + yearSize * 1.4            : knobs.yearAt * size.height        ZStack(alignment: .topLeading) {            Group {                if let poster {                    poster                        .frame(width: size.width + 2 * bleed, height: size.height + 2 * bleed)                        .clipped()                        .offset(x: -bleed, y: -bleed)                        .accessibilityElement()                        .accessibilityLabel(card.text("title") ?? "")                        .accessibilityIdentifier("deck-title")                        .facePart(.picture)                } else {                    BooksMaterial.sleeve.colour                }            }            .frame(width: size.width, height: size.height, alignment: .topLeading)            .mask {                if let grain { grain.resizable() } else { Rectangle() }            }            if let grain {                grain.resizable().interpolation(.high).blendMode(.multiply).allowsHitTesting(false)            }            if !title.isEmpty {                VStack(alignment: .leading, spacing: -titleSize * 0.14) {                    ForEach(Array(title.enumerated()), id: \.offset) { _, line in                        Text(line).font(CottonFonts.flap(titleSize)).lineLimit(1).fixedSize()                    }                }                .foregroundStyle(BooksMaterial.cream.colour)                .offset(x: knobs.plainMargin * size.width, y: knobs.plainTop * size.height)                .accessibilityElement()                .accessibilityLabel(card.text("title") ?? "")                .accessibilityAddTraits(.isHeader)                .accessibilityIdentifier("deck-title")                .facePart(.title)            }            if let year {                Text(year)                    .font(CottonFonts.type(yearSize))                    .foregroundStyle(BooksMaterial.cream.colour)                    .shadow(color: .black.opacity(0.45), radius: yearSize * 0.15, x: 0, y: yearSize * 0.06)                    .lineLimit(1)                    .minimumScaleFactor(0.6)                    .frame(width: size.width * 0.84)                    .offset(x: size.width * 0.08, y: yearAt - yearSize)                    .accessibilityIdentifier("film-year")                    .facePart(.subtitle)            }            if let wear = painted("vhs-sleeve-wear") {                wear.resizable().interpolation(.high).allowsHitTesting(false)            }        }        .frame(width: size.width, height: size.height, alignment: .topLeading)        .compositingGroup()    }}/// The cassette: its round sticker and its spine label.private struct Cassette: View {    let card: DeckCard    let size: CGSize    var body: some View {        let knobs = FilmVHSFaceKnobs.self        let sticker = knobs.stickerWidth * size.width        let spine = CGRect(x: knobs.spine.minX * size.width, y: knobs.spine.minY * size.height, width: knobs.spine.width * size.width, height: knobs.spine.height * size.height)        ZStack(alignment: .topLeading) {            Group {                if let plastic = painted("vhs-cassette") {                    plastic.resizable().interpolation(.high)                } else {                    RoundedRectangle(cornerRadius: 4).fill(BooksMaterial.plastic.colour)                }            }            .frame(width: size.width, height: size.height)            .accessibilityHidden(true)            Sticker(card: card, size: sticker)                .frame(width: sticker, height: sticker)                .offset(x: knobs.sticker.x * size.width - sticker / 2, y: knobs.sticker.y * size.height - sticker / 2)            SpineLabel(title: card.text("title"), size: spine.size)                .frame(width: spine.width, height: spine.height)                .offset(x: spine.minX, y: spine.minY)        }        .frame(width: size.width, height: size.height, alignment: .topLeading)    }}/// The round sticker: watched and the day over the stars, or the state.private struct Sticker: View {    let card: DeckCard    let size: CGFloat    var body: some View {        let knobs = FilmVHSFaceKnobs.self        let said = FilmVHSSetting.sticker(card)        let rating = card.dated == nil ? nil : card.rating        let type = knobs.stickerType * size        let star = knobs.star * size        let rows = (said == nil ? 0 : 1) + (said?.day == nil ? 0 : 1) + (rating == nil ? 0 : 1)        let step = type * 1.25        let first = size / 2 - step * CGFloat(rows - 1) / 2        ZStack(alignment: .topLeading) {            Group {                if let paper = painted("vhs-sticker") {                    paper.resizable().interpolation(.high)                } else {                    Circle().fill(BooksMaterial.paper.colour)                }            }            .frame(width: size, height: size)            .shadow(color: .black.opacity(0.35), radius: size * 0.015, x: size * 0.01, y: size * 0.015)            .accessibilityHidden(true)            Canvas { context, room in                var row = 0                func centred(_ words: String) {                    let text = context.resolve(Text(words).font(CottonFonts.type(type)).foregroundStyle(BooksMaterial.type.colour))                    let far = CGSize(width: 10_000, height: 10_000)                    let wide = text.measure(in: far).width                    let room = room.width * 0.78                    let base = first + CGFloat(row) * step + type * 0.35                    ObjectWriting.type(&context, words, font: CottonFonts.type(type), ink: BooksMaterial.type.colour,                                       at: CGPoint(x: (size - min(wide, room)) / 2, y: base), width: room, fits: true)                    row += 1                }                if let said {                    centred(said.word)                    if let day = said.day { centred(day) }                }                if let rating {                    let wide = CGFloat(knobs.starsOf) * star + CGFloat(knobs.starsOf - 1) * star * knobs.starGap                    let top = first + CGFloat(row) * step - star * 0.55                    for index in 0..<knobs.starsOf {                        let fill = min(1, max(0, rating - Double(index)))                        let rect = CGRect(x: (size - wide) / 2 + CGFloat(index) * star * (1 + knobs.starGap), y: top, width: star, height: star)                        let shape = FiveStar().path(in: rect)                        if fill > 0 {                            var filled = context                            filled.clip(to: Path(CGRect(x: rect.minX, y: rect.minY, width: rect.width * fill, height: rect.height)))                            filled.fill(shape, with: .color(BooksMaterial.red.colour))                        }                        context.stroke(shape, with: .color(BooksMaterial.red.colour), style: StrokeStyle(lineWidth: max(0.7, star * 0.07), lineJoin: .round))                    }                }            }            .frame(width: size, height: size)            .blendMode(.multiply)            .accessibilityHidden(true)            // The parts: the word, and the day under it.            if let said {                part(said.day == nil ? .state : .state, CGRect(x: size * 0.15, y: first - type, width: size * 0.7, height: type * 1.3))                    .accessibilityElement()                    .accessibilityLabel(said.word)                    .accessibilityIdentifier("film-sticker-word")                if said.day != nil {                    part(.when, CGRect(x: size * 0.15, y: first + step - type, width: size * 0.7, height: type * 1.3))                        .accessibilityElement()                        .accessibilityLabel(said.day ?? "")                        .accessibilityIdentifier("film-sticker-day")                }            }            if let rating {                Color.clear                    .frame(width: size * 0.7, height: star)                    .offset(x: size * 0.15, y: first + CGFloat(rows - 1) * step - star * 0.55)                    .accessibilityElement()                    .accessibilityLabel(ShellLines.line("cards", "deck.position", ["at": rating.formatted(), "of": "\(knobs.starsOf)"]))                    .accessibilityIdentifier("face-rating")            }        }        .frame(width: size, height: size, alignment: .topLeading)    }    /// A clear room tagged as `tag`, at `rect` on the sticker.    private func part(_ tag: FacePart, _ rect: CGRect) -> some View {        Color.clear            .contentShape(Rectangle())            .frame(width: max(1, rect.width), height: max(1, rect.height))            .facePart(tag)            .offset(x: rect.minX, y: rect.minY)    }}/// The spine label, the title typed down it in capitals.private struct SpineLabel: View {    let title: String?    let size: CGSize    var body: some View {        let knobs = FilmVHSFaceKnobs.self        let type = knobs.spineType * size.width        ZStack {            Group {                if let paper = painted("vhs-spine") {                    paper.resizable().interpolation(.high)                } else {                    Rectangle().fill(BooksMaterial.paper.colour)                }            }            .frame(width: size.width, height: size.height)            .accessibilityHidden(true)            if let title {                // Typed along the label, read from its head to its foot.                Canvas { context, room in                    var turned = context                    turned.translateBy(x: room.width / 2 + type * 0.35, y: room.height * 0.07)                    turned.rotate(by: .degrees(90))                    ObjectWriting.type(&turned, title.uppercased(), font: CottonFonts.type(type), ink: BooksMaterial.type.colour,                                       at: .zero, width: room.height * 0.86, fits: true)                }                .frame(width: size.width, height: size.height)                .blendMode(.multiply)                .contentShape(Rectangle())                .accessibilityElement()                .accessibilityLabel(title)                .accessibilityIdentifier("film-spine")                .facePart(.title)            }        }        .frame(width: size.width, height: size.height)    }}/// A five-pointed star, its point up, filling its square.private struct FiveStar: Shape {    func path(in rect: CGRect) -> Path {        let centre = CGPoint(x: rect.midX, y: rect.midY + rect.height * 0.05)        let outer = rect.width / 2        let inner = outer * 0.42        var path = Path()        for index in 0..<10 {            let radius = index % 2 == 0 ? outer : inner            let angle = -CGFloat.pi / 2 + CGFloat(index) * .pi / 5            let point = CGPoint(x: centre.x + radius * cos(angle), y: centre.y + radius * sin(angle))            if index == 0 { path.move(to: point) } else { path.addLine(to: point) }        }        path.closeSubpath()        return path    }}/// The video in its sleeve, by its id beside the film's own face, and the/// films it is reviewed in: invented titles, an invented poster. The/// specimen world's today is Friday 30 October 2026; a day is said as the/// core says it (`weekday_date`), a running time as its clock (`form: clock`).public enum FilmVHSFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .claret    public static let face = Face(id: "film.vhs", specimens: [        Specimen("seen", seen, picture: "poster-ferry"), Specimen("to-see", toSee, picture: "poster-ferry"), Specimen("no-poster", noPoster),    ], steps: .cut) { card, picture, _ in        FilmVHSFace(card: card, poster: picture)    }    static func film(_ fields: [String: RecordValue]) -> DeckCard {        DeckCard(face: "film.vhs", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)    }    /// A film watched and rated four of five, its poster kept.    public static let seen = film([        "title": .text("Night Ferry"),        "subtitle": .text("1974"),        "length": .text("1:52:00"),        "director": .text("R. Example"),        "photo": .text("poster-ferry"),        "state": .text("Watched"),        "date": .text("Sun 18 Oct"),        "count": .number(4),    ])    /// The same film still to watch: its state, no day, no stars.    public static let toSee = film([        "title": .text("Night Ferry"),        "subtitle": .text("1974"),        "length": .text("1:52:00"),        "photo": .text("poster-ferry"),        "state": .text("To watch"),        "date": .text("Add date"),    ])    /// No poster kept: a plain sleeve, its title set large; half a star.    public static let noPoster = film([        "title": .text("Invented Harbour"),        "subtitle": .text("1994"),        "length": .text("2:06:00"),        "state": .text("Watched"),        "date": .text("Sat 17 Oct"),        "count": .number(3.5),    ])}