Cotton code
910 lines · 43.5 KB · SwiftRaw
// The BOOK as a HARDBACK STANDING on the books' dark navy felt// (`FaceGround.feltNavy`; the coordinator's look for Cotton Books, 4 Nov// 2026, after the held-book picture `books7/held-book`): a worn cloth// hardback upright, its cover as the jacket, bare of the deck's paper. The// book's boards, spine and page block, its shadow, the blank jacket, the// gold cloth ribbon, the paper belly band and its shadow, the slip and the// felt are PAINTED (`Media.xcassets`, imported by// `scripts/import-books-materials.py`), each laid where the materials'// `layout.json` places it in an 846 x 1260 book box, scaled by the drawn// width over 846. The face draws live only what the card decides:////   the JACKET is the book's own cover, laid behind the boards' cut-out//   and mapped to the cut-out's corners (the board is turned a little),//   multiplied softly by the jacket paper's grain. A book kept without a//   cover shows the blank jacket there instead, its title set large in//   Libre Caslon in the upper half in up to three balanced lines (a title//   that is a file name broken after its underscores, hyphens and dots and//   at its capitals, never a word split for want of a space) and its author//   in spaced small capitals near the foot, inside the rule.//   the RIBBON comes out of the head a little way in from the spine and//   hangs down the cover's left margin, cover showing on both sides of it,//   as far as the reader is: nought, a sixth of the cover; from there down//   to the front's foot at the whole; finished, its whole length, its//   swallowtail hanging below the foot.//   the STATUS: reading, the belly band round the lower third says where//   the reader is ("READING · 41%") and, when the book's pages are known,//   the page they are on of them ("124 / 303") typed under it; finished,//   the band says the day ("FINISHED 12 OCT") with the rating's stars//   beside it; want to read, nothing but the book.//// A STOPPED book is drawn LYING on the felt, turned, in three-quarter view// (`books27/layers/stopped`, Codex's painted pose, 14 Nov 2026): its spine// and the foot of its page block showing, the cover (or the blank jacket// with its title and author) warped onto the cover's quad with the gloss// over it, the painted ribbon over the cover and past the foot, and the// slip standing out of the fore-edge a third of the way down, its words// ("Stopped at 23%" over "4 Nov") typed and warped onto it.//// Tagged: the jacket (`picture`), or on the blank jacket its title and// author (`title`, `subtitle`); the band (`state` while reading, `when` once// finished); the stars (`stars`); the slip (`state`). Stepped by a tap, it// cuts. Print on an object scales with the object, never with Dynamic Type.//// The status is the stored value under the card's state place, never its// label; every word is the core's (`DeckCard`) or a line: the face only// sets them.import CottonPaperimport CottonValuesimport CoreTextimport SwiftUIenum BookHardbackFaceKnobs {    // THE BOOK BOX every placement is in, in the paintings' pixels    // (`layout.json`): the face draws the book at most `widest` points wide,    // and every place below is scaled by the drawn width over the box's.    static let box = CGSize(width: 846, height: 1260)    static let widest: CGFloat = 250    /// The most of the card's room the book takes: of its width, and of its    /// height with a finished ribbon's hang under the book.    static let fillWidth: CGFloat = 0.9    static let fillHeight: CGFloat = 0.92    static let shadow = CGRect(x: -80, y: -80, width: 1006, height: 1420)    // THE JACKET: the boards' cut-out (its bounding rect, and its corners    // as the board is turned, clockwise from the top left), how far a cover    // runs under the rim, and the blank jacket laid in it.    static let jacket = CGRect(x: 66, y: 67, width: 696, height: 1172)    static let jacketCorners = [CGPoint(x: 68, y: 67), CGPoint(x: 762, y: 74), CGPoint(x: 762, y: 1239), CGPoint(x: 66, y: 1236)]    static let coverBleed: CGFloat = 2    static let blank = CGRect(x: 64, y: 65, width: 701, height: 1177)    /// The paper's grain a cover is multiplied by: the blank jacket's middle,    /// clear of its rule (as shares of it), and how strongly.    static let grain = CGRect(x: 0.18, y: 0.12, width: 0.64, height: 0.76)    static let grainStrength: Double = 0.4    /// The blank jacket's title: its rect, its size and the least it is    /// taken down to, the step from one baseline to the next as a share of    /// its size, the most lines it takes, and the step its size is taken    /// down by until it fits them.    static let title = CGRect(x: 210, y: 170, width: 480, height: 260)    static let titleSize: CGFloat = 72    static let titleLeast: CGFloat = 44    static let titleStep: CGFloat = 1.12    static let titleLines = 3    static let titleShrink: CGFloat = 0.94    /// The blank jacket's author: its rect (the materials' own, raised clear    /// of the rule and kept under the band), its size and tracking (a share    /// of its size).    static let author = CGRect(x: 210, y: 1108, width: 480, height: 60)    static let authorSize: CGFloat = 30    static let authorTracking: CGFloat = 0.16    // THE RIBBON (`book-ribbon`, full length): where it is laid — out of    // the head a little way in from the spine, over the cover's left    // margin, so cover shows on both sides of its cloth and the blank    // jacket's title stands clear of it (`books27/shelf-b`, `stopped`) —    // where the front starts and how tall it is, the swallowtail at its    // end; a finished book's hangs this far past the foot, its cloth run on    // from `ribbonRun` down the painting.    static let ribbon = CGRect(x: 116, y: 0, width: 112, height: 1260)    /// The cloth's run across its painting (the rest is its shadow's room),    /// and the least cover that shows on its spine side.    static let ribbonCloth: ClosedRange<CGFloat> = 2...73    static let ribbonInFrom: CGFloat = 40    static let ribbonFront: CGFloat = 68    static let ribbonFrontHeight: CGFloat = 1172    /// The shortest the ribbon hangs, a book not begun, as a share of the    /// front's height: about a sixth of the cover, never a stub at the head.    static let ribbonShortest: CGFloat = 1.0 / 6    static let ribbonTail: CGFloat = 64    static let ribbonHang: CGFloat = 96    static let ribbonRun: CGFloat = 600    // THE BAND (`book-band`) and its shadow, the room its words take on the    // front, the words' size and tracking (small capitals, a share of their    // size), the pages' size and the gap above them, the stars' size and    // the gaps between them and beside the words.    static let band = CGRect(x: 0, y: 848, width: 844, height: 260)    static let bandShadow = CGRect(x: -18, y: 830, width: 880, height: 296)    static let bandText = CGRect(x: 128, y: 906, width: 570, height: 140)    static let bandSize: CGFloat = 40    static let bandTracking: CGFloat = 0.12    static let pagesSize: CGFloat = 30    static let pagesGap: CGFloat = 12    static let star: CGFloat = 26    static let starGap: CGFloat = 4    static let starsBeside: CGFloat = 14    static let starsOf = 5    // A STOPPED BOOK LYING (`books27/layers/stopped`, its `layout.json`):    // the book turned in three-quarter view on one 1290 x 1600 canvas, every    // layer kept cut to its alpha's bounds and laid back at them; drawn at    // most `widest` wide over the canvas's `lyingReach` (the slip's shadow    // the rightmost), in the card's room.    static let lying = CGRect(x: 0, y: 21, width: 1262, height: 1563)    static let lyingBook = CGRect(x: 34, y: 21, width: 994, height: 1563)    static let lyingShadow = CGRect(x: 0, y: 261, width: 1106, height: 1171)    static let lyingSlip = CGRect(x: 846, y: 670, width: 382, height: 180)    static let lyingSlipShadow = CGRect(x: 846, y: 660, width: 416, height: 227)    static let lyingGloss = CGRect(x: 120, y: 337, width: 876, height: 910)    static let lyingRibbon = CGRect(x: 180, y: 280, width: 360, height: 1030)    static let lyingWidest: CGFloat = 340    /// The cover's quad, the slip's words' quad (top left, top right,    /// bottom right, bottom left), and the slip's words' size and leading.    static let coverQuad = [CGPoint(x: 440, y: 352), CGPoint(x: 980, y: 427), CGPoint(x: 759, y: 1231), CGPoint(x: 135, y: 1122)]    static let slipQuad = [CGPoint(x: 965, y: 716), CGPoint(x: 1198, y: 693), CGPoint(x: 1182, y: 786), CGPoint(x: 936, y: 814)]    static let slipText = CGSize(width: 234, height: 100)    static let slipSize: CGFloat = 32    /// The slip's words in from where it comes out of the pages.    static let slipInset: CGFloat = 14    static let slipLeading: CGFloat = 1.18}/// Where a book stands, by the value its state place stores.public enum BookHardbackStatus: String, CaseIterable, Sendable {    case wantToRead = "want_to_read", reading, finished, stopped    /// The card's status, by its state place's stored value; nil, it stores    /// none this face knows.    public init?(_ card: DeckCard) {        guard let stored = card.stored["state"] else { return nil }        self.init(rawValue: stored)    }}/// How the standing hardback is set.public enum BookHardbackSetting {    /// How far through the reader is, nought to one: the card's share, a    /// book not begun none.    public static func share(_ card: DeckCard) -> Double {        card.gaugeShare ?? 0    }    /// Where the ribbon ends, in the book box's pixels: down the front a    /// sixth of the cover for a book not begun (`ribbonShortest`), and from    /// there as far again as the reader is to the front's foot at the whole;    /// hanging past the foot once finished.    public static func ribbonEnd(_ card: DeckCard) -> CGFloat {        let knobs = BookHardbackFaceKnobs.self        if BookHardbackStatus(card) == .finished { return knobs.box.height + knobs.ribbonHang }        let hang = knobs.ribbonShortest + (1 - knobs.ribbonShortest) * CGFloat(min(1, max(0, share(card))))        return (knobs.ribbonFront + knobs.ribbonFrontHeight * hang).rounded()    }    /// The share said as a percentage.    static func percent(_ share: Double) -> String {        share.formatted(.percent.precision(.fractionLength(0)))    }    /// The band's words: where the reader is, or the day the book was    /// finished; nil, a book that wears no band.    public static func band(_ card: DeckCard) -> String? {        guard let state = card.text("state") else { return nil }        switch BookHardbackStatus(card) {        case .reading:            return ShellLines.line("cards", "book.band_reading", ["state": state, "share": percent(share(card))])        case .finished:            guard let day = card.dated else { return state }            return ShellLines.line("cards", "book.band_finished", ["state": state, "day": DayStamp.bare(day)])        case .wantToRead, .stopped, nil:            return nil        }    }    /// The page the reader is on of the book's pages ("124 / 303"), while    /// reading a book whose pages are known.    public static func pages(_ card: DeckCard) -> String? {        guard BookHardbackStatus(card) == .reading, let pages = card.number("pages"), pages > 0 else { return nil }        let at = Int((pages * share(card)).rounded())        return ShellLines.line("cards", "deck.position", ["at": at.formatted(), "of": Int(pages.rounded()).formatted()])    }    /// The stars a finished book's band carries, out of five in halves; nil,    /// unrated or not finished.    public static func stars(_ card: DeckCard) -> Double? {        BookHardbackStatus(card) == .finished ? card.rating : nil    }    /// The slip's lines: where the reader stopped, then the day they last    /// read; none, a book not stopped.    public static func slip(_ card: DeckCard) -> [String] {        guard BookHardbackStatus(card) == .stopped, let state = card.text("state") else { return [] }        let at = card.number("used") == nil            ? state : ShellLines.line("cards", "book.slip_stopped", ["state": state, "share": percent(share(card))])        return [at] + [card.text("last_read")].compactMap { $0 }    }    /// The blank jacket's title in Libre Caslon: its lines and the size they    /// are set at, by the rolodex's rule (`NameFit`) — wrapped at word    /// boundaries at the jacket's own size, taken down a step at a time    /// until it stands whole in the jacket's lines, and only at the least    /// size a word wider than the room split with a hyphen, never inside a    /// word otherwise; past the least size cut with an ellipsis — the lines    /// balanced, as near one width as the same count of lines allows. In the    /// book box's pixels.    public static func title(_ card: DeckCard) -> (lines: [String], size: CGFloat) {        let knobs = BookHardbackFaceKnobs.self        guard let title = card.text("title")?.split(whereSeparator: \.isWhitespace).joined(separator: " ") else { return ([], knobs.titleSize) }        var sizes = [knobs.titleSize]        while let size = sizes.last, size * knobs.titleShrink >= knobs.titleLeast { sizes.append(size * knobs.titleShrink) }        let pieces = fileNamePieces(title)        if pieces.count > 1 { return fileName(pieces, sizes: sizes) }        let fit = NameFit.lines(title.split(separator: " ").map(String.init), sizes: sizes, limit: knobs.titleLines) { size in            let font = HighlightPassageSetting.caslon(size)            return { HighlightPassageSetting.wide($0, font) <= knobs.title.width }        }        let font = HighlightPassageSetting.caslon(fit.size)        guard fit.lines.count <= knobs.titleLines else {            let kept = Array(fit.lines.prefix(knobs.titleLines))            let runOn = ([kept[knobs.titleLines - 1]] + fit.lines.dropFirst(knobs.titleLines)).joined(separator: " ")            return (kept.dropLast() + [HighlightPassageSetting.cut(runOn, font: font, width: knobs.title.width)], fit.size)        }        guard !fit.split else { return (fit.lines, fit.size) }        return (balanced(title, font: font, width: knobs.title.width, limit: knobs.titleLines), fit.size)    }    /// A title that is a file name, one run with no spaces    /// ("the_lamp_keepers_daughter.epub", "TheLampKeepersDaughter"), in the    /// pieces it may break between: after an underscore, a hyphen or a    /// dot, and before a capital that follows a small letter or a digit    /// that follows a letter. Its characters are all kept, in order; a title    /// with a space, or a run with nowhere to break, is one piece.    public static func fileNamePieces(_ title: String) -> [String] {        guard !title.contains(" ") else { return [title] }        var pieces: [String] = []        var piece = ""        var previous: Character?        for character in title {            let before = previous.map { ($0.isLowercase && character.isUppercase) || ($0.isLetter && character.isNumber) } ?? false            if before, !piece.isEmpty { pieces.append(piece); piece = "" }            piece.append(character)            if "_-.".contains(character) { pieces.append(piece); piece = "" }            previous = character        }        if !piece.isEmpty { pieces.append(piece) }        return pieces    }    /// A file name's lines: its pieces laid greedily, never a space added,    /// at the jacket's size taken down a step at a time until every piece    /// stands whole and the lines fit the jacket's; past the least size the    /// last line cut with an ellipsis. Balanced as a title is.    static func fileName(_ pieces: [String], sizes: [CGFloat]) -> (lines: [String], size: CGFloat) {        let knobs = BookHardbackFaceKnobs.self        let room = knobs.title.width        func laid(_ pieces: [String], _ font: CTFont, _ width: CGFloat) -> [String] {            var lines: [String] = []            for piece in pieces {                if let last = lines.last, HighlightPassageSetting.wide(last + piece, font) <= width {                    lines[lines.count - 1] = last + piece                } else {                    lines.append(piece)                }            }            return lines        }        for size in sizes.dropLast() {            let font = HighlightPassageSetting.caslon(size)            guard pieces.allSatisfy({ HighlightPassageSetting.wide($0, font) <= room }) else { continue }            let lines = laid(pieces, font, room)            guard lines.count <= knobs.titleLines else { continue }            // Balanced: the narrowest room that still lays it in as many.            var low = pieces.map { HighlightPassageSetting.wide($0, font) }.max() ?? 0            var high = room            while high - low > 0.5 {                let middle = (low + high) / 2                if laid(pieces, font, middle).count <= lines.count { high = middle } else { low = middle }            }            return (laid(pieces, font, high), size)        }        // At the least size a piece wider than the room breaks where it        // must, and what runs past the jacket's lines is cut with an        // ellipsis.        let size = sizes.last ?? knobs.titleLeast        let font = HighlightPassageSetting.caslon(size)        var parts: [String] = []        for piece in pieces {            var rest = piece            while HighlightPassageSetting.wide(rest, font) > room, rest.count > 1 {                var cut = rest.count - 1                while cut > 1, HighlightPassageSetting.wide(String(rest.prefix(cut)), font) > room { cut -= 1 }                parts.append(String(rest.prefix(cut)))                rest = String(rest.dropFirst(cut))            }            parts.append(rest)        }        var lines = laid(parts, font, room)        if lines.count > knobs.titleLines {            var last = lines[knobs.titleLines - 1]            while last.count > 1, HighlightPassageSetting.wide(last + "\u{2026}", font) > room { last.removeLast() }            while last.count > 1, let end = last.last, "_-.".contains(end) { last.removeLast() }            lines = Array(lines.prefix(knobs.titleLines - 1)) + [last + "\u{2026}"]        }        return (lines, size)    }    /// `text` in at most `limit` lines no wider than `width`, as many as it    /// takes at that width but each as near the same width as that count    /// allows: the narrowest room that still sets it in that many.    static func balanced(_ text: String, font: CTFont, width: CGFloat, limit: Int) -> [String] {        let widest = HighlightPassageSetting.lines(text, font: font, width: width, limit: limit)        guard widest.count > 1, widest.count <= limit, widest.last?.hasSuffix("\u{2026}") != true else { return widest }        // Never narrower than the widest word: balancing evens the lines, it        // never breaks a word to do it (HARBOU / R TEST).        let widestWord = text.split(separator: " ").map { HighlightPassageSetting.wide(String($0), font) }.max() ?? 0        var low = min(widestWord, width)        var high = width        while high - low > 0.5 {            let middle = (low + high) / 2            if HighlightPassageSetting.lines(text, font: font, width: middle, limit: .max).count <= widest.count {                high = middle            } else {                low = middle            }        }        return HighlightPassageSetting.lines(text, font: font, width: high, limit: limit)    }    /// The projective map that lays a rectangle `size`, from its top left,    /// on `corners`, clockwise from the top left: the cover on the turned    /// board.    public static func projection(_ size: CGSize, onto corners: [CGPoint]) -> ProjectionTransform {        let (p0, p1, p2, p3) = (corners[0], corners[1], corners[2], corners[3])        let dx1 = p1.x - p2.x, dx2 = p3.x - p2.x, dx3 = p0.x - p1.x + p2.x - p3.x        let dy1 = p1.y - p2.y, dy2 = p3.y - p2.y, dy3 = p0.y - p1.y + p2.y - p3.y        let den = dx1 * dy2 - dx2 * dy1        let g = den == 0 ? 0 : (dx3 * dy2 - dx2 * dy3) / den        let h = den == 0 ? 0 : (dx1 * dy3 - dx3 * dy1) / den        let a = p1.x - p0.x + g * p1.x, b = p3.x - p0.x + h * p3.x        let d = p1.y - p0.y + g * p1.y, e = p3.y - p0.y + h * p3.y        var m = ProjectionTransform()        m.m11 = a / size.width; m.m21 = b / size.height; m.m31 = p0.x        m.m12 = d / size.width; m.m22 = e / size.height; m.m32 = p0.y        m.m13 = g / size.width; m.m23 = h / size.height; m.m33 = 1        return m    }    /// The jacket's corners pushed `by` out from its middle, so a cover runs    /// under the boards' rim.    static func spread(_ corners: [CGPoint], by: CGFloat) -> [CGPoint] {        let middle = CGPoint(x: corners.map(\.x).reduce(0, +) / 4, y: corners.map(\.y).reduce(0, +) / 4)        return corners.map { CGPoint(x: $0.x + ($0.x < middle.x ? -by : by), y: $0.y + ($0.y < middle.y ? -by : by)) }    }}/// A painted layer, by its catalogue name, at the scale it was painted for;/// nothing where this build carries no pictures.private struct BookPainted: View {    let name: String    var body: some View {        if let image = CottonMedia.image(name, scale: 3) {            image.resizable().interpolation(.high).accessibilityHidden(true)        }    }}private extension View {    /// This view laid at `rect` of the book box, in its pixels, scaled by `s`.    func laid(_ rect: CGRect, _ s: CGFloat, alignment: Alignment = .center) -> some View {        frame(width: rect.width * s, height: rect.height * s, alignment: alignment)            .offset(x: rect.minX * s, y: rect.minY * s)    }}public struct BookHardbackFace<Cover: View>: View {    let card: DeckCard    /// The cover laid behind the boards' cut-out; nil lays the blank jacket.    var cover: Cover?    public init(card: DeckCard, cover: Cover? = nil) {        self.card = card        self.cover = cover    }    public var body: some View {        let knobs = BookHardbackFaceKnobs.self        let stopped = BookHardbackStatus(card) == .stopped        GeometryReader { room in            if stopped {                // Lying, turned: the canvas fitted to the card's room.                let box = knobs.lying                let s = min(knobs.lyingWidest / box.width, room.size.width * knobs.fillWidth / box.width,                            room.size.height * knobs.fillHeight / box.height)                LyingBook(card: card, cover: cover, s: s)                    .frame(width: box.maxX * s, height: box.maxY * s, alignment: .topLeading)                    .offset(x: (room.size.width - box.width * s) / 2 - box.minX * s,                            y: (room.size.height - box.height * s) / 2 - box.minY * s)                    .frame(width: room.size.width, height: room.size.height, alignment: .topLeading)            } else {                // The book's size is the same whatever it says.                let s = min(knobs.widest, room.size.width * knobs.fillWidth,                            room.size.height * knobs.fillHeight * knobs.box.width / (knobs.box.height + knobs.ribbonHang)) / knobs.box.width                StandingBook(card: card, cover: cover, s: s)                    .frame(width: knobs.box.width * s, height: knobs.box.height * s, alignment: .topLeading)                    .offset(x: (room.size.width - knobs.box.width * s) / 2,                            y: (room.size.height - (knobs.box.height + knobs.ribbonHang) * s) / 2)                    .frame(width: room.size.width, height: room.size.height, alignment: .topLeading)            }        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("book-hardback")    }}/// The book in its box, scaled by `s`: its shadow, the cover or the blank/// jacket, the boards, the ribbon, the band.private struct StandingBook<Cover: View>: View {    let card: DeckCard    let cover: Cover?    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let status = BookHardbackStatus(card)        ZStack(alignment: .topLeading) {            BookPainted(name: "book-shadow").laid(knobs.shadow, s)            if let cover {                Jacket(cover: cover, s: s)            } else {                BookPainted(name: "book-jacket-blank").laid(knobs.blank, s)            }            BookPainted(name: "book-boards").laid(CGRect(origin: .zero, size: knobs.box), s)            JacketPart(card: card, covered: cover != nil, s: s)            if cover == nil { BlankJacket(card: card, s: s) }            Ribbon(end: BookHardbackSetting.ribbonEnd(card), s: s)            if status == .reading || status == .finished {                BookPainted(name: "book-band-shadow").laid(knobs.bandShadow, s)                BookPainted(name: "book-band").laid(knobs.band, s)                Band(card: card, s: s)            }        }        .frame(width: knobs.box.width * s, height: knobs.box.height * s, alignment: .topLeading)    }}/// The cover on the turned board: drawn to the cut-out's bounding rect,/// multiplied softly by the jacket paper's grain, and mapped to the/// cut-out's corners, a hair past them so it runs under the rim.private struct Jacket<Cover: View>: View {    let cover: Cover    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let size = CGSize(width: knobs.jacket.width * s, height: knobs.jacket.height * s)        let corners = BookHardbackSetting.spread(knobs.jacketCorners, by: knobs.coverBleed)            .map { CGPoint(x: $0.x * s, y: $0.y * s) }        ZStack(alignment: .topLeading) {            cover                .frame(width: size.width, height: size.height)                .clipped()            // The paper's grain: the blank jacket's middle, clear of its            // rule, stretched over the cover.            BookPainted(name: "book-jacket-blank")                .frame(width: size.width / knobs.grain.width, height: size.height / knobs.grain.height)                .offset(x: -knobs.grain.minX * size.width / knobs.grain.width, y: -knobs.grain.minY * size.height / knobs.grain.height)                .frame(width: size.width, height: size.height, alignment: .topLeading)                .clipped()                .blendMode(.multiply)                .opacity(knobs.grainStrength)        }        .frame(width: size.width, height: size.height, alignment: .topLeading)        .compositingGroup()        .projectionEffect(BookHardbackSetting.projection(size, onto: corners))        .accessibilityHidden(true)    }}/// The jacket as the card's part: the cover (tagged where it is drawn), or/// the blank jacket under its title and author.private struct JacketPart: View {    let card: DeckCard    let covered: Bool    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        Color.clear            .contentShape(Rectangle())            .frame(width: knobs.jacket.width * s, height: knobs.jacket.height * s)            .accessibilityElement()            .accessibilityLabel(covered ? card.text("title") ?? "" : "")            .accessibilityAddTraits(covered ? .isHeader : [])            .accessibilityIdentifier(covered ? "deck-title" : "book-jacket-blank")            .accessibilityHidden(!covered)            .facePart(.picture)            // Moved into place after it is tagged, so the region the deck            // reads is where it stands.            .offset(x: knobs.jacket.minX * s, y: knobs.jacket.minY * s)    }}/// The blank jacket's words: the title in Libre Caslon, balanced, and the/// author in spaced small capitals inside the rule.private struct BlankJacket: View {    let card: DeckCard    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let (lines, size) = BookHardbackSetting.title(card)        ZStack(alignment: .topLeading) {            if !lines.isEmpty {                VStack(spacing: 0) {                    ForEach(Array(lines.enumerated()), id: \.offset) { _, line in                        Text(line)                            .font(CottonFonts.caslon(size * s))                            .lineLimit(1)                            .fixedSize()                            .frame(height: size * knobs.titleStep * s)                    }                }                .foregroundStyle(BooksMaterial.ink.colour)                .frame(width: knobs.title.width * s, height: knobs.title.height * s, alignment: .top)                .contentShape(Rectangle())                .accessibilityElement()                .accessibilityLabel(card.text("title") ?? "")                .accessibilityAddTraits(.isHeader)                .accessibilityIdentifier("deck-title")                .facePart(.title)                .offset(x: knobs.title.minX * s, y: knobs.title.minY * s)            }            if let author = card.text("subtitle") {                Text(author.uppercased())                    .font(CottonFonts.caslon(knobs.authorSize * s))                    .tracking(knobs.authorSize * knobs.authorTracking * s)                    .foregroundStyle(BooksMaterial.ink.colour)                    .lineLimit(1)                    .minimumScaleFactor(0.5)                    .frame(width: knobs.author.width * s, height: knobs.author.height * s)                    .contentShape(Rectangle())                    .accessibilityLabel(author)                    .accessibilityIdentifier("book-author")                    .facePart(.subtitle)                    .offset(x: knobs.author.minX * s, y: knobs.author.minY * s)            }        }    }}/// The gold ribbon from the head to `end`: the painting's cloth down to its/// swallowtail's place, run on past the painting where it hangs longer, and/// the swallowtail moved to its end.private struct Ribbon: View {    let end: CGFloat    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let painted = knobs.ribbon.height - knobs.ribbonTail        let body = max(0, end - knobs.ribbonTail)        ZStack(alignment: .topLeading) {            rows(from: 0, count: min(body, painted), at: 0)            if body > painted {                rows(from: knobs.ribbonRun, count: body - painted, at: painted)            }            rows(from: painted, count: knobs.ribbonTail, at: body)        }        .shadow(color: .black.opacity(0.3), radius: 6 * s, x: 2 * s, y: 5 * s)        .offset(x: knobs.ribbon.minX * s)        .accessibilityHidden(true)    }    /// `count` of the painting's rows from `from`, laid at `at` down the box.    private func rows(from: CGFloat, count: CGFloat, at: CGFloat) -> some View {        let knobs = BookHardbackFaceKnobs.self        return BookPainted(name: "book-ribbon")            .frame(width: knobs.ribbon.width * s, height: knobs.ribbon.height * s)            .offset(y: -from * s)            .frame(width: knobs.ribbon.width * s, height: count * s, alignment: .top)            .clipped()            .offset(y: at * s)    }}/// The band's words on its front run: where the reader is and the page/// they are on, or the day the book was finished and its stars.private struct Band: View {    let card: DeckCard    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let finished = BookHardbackStatus(card) == .finished        VStack(spacing: knobs.pagesGap * s) {            if let words = BookHardbackSetting.band(card) {                let said = Text(words.uppercased())                    .font(CottonFonts.caslon(knobs.bandSize * s))                    .tracking(knobs.bandSize * knobs.bandTracking * s)                    .lineLimit(1)                    .minimumScaleFactor(0.5)                    .accessibilityLabel(words)                    .accessibilityIdentifier("book-band")                    .facePart(finished ? .when : .state)                if let stars = BookHardbackSetting.stars(card) {                    ViewThatFits(in: .horizontal) {                        HStack(spacing: knobs.starsBeside * s) { said.fixedSize(); Stars(rating: stars, s: s) }                        VStack(spacing: knobs.pagesGap * s) { said; Stars(rating: stars, s: s) }                    }                } else {                    said                }            }            if let pages = BookHardbackSetting.pages(card) {                Text(pages)                    .font(CottonFonts.type(knobs.pagesSize * s))                    .monospacedDigit()                    .lineLimit(1)                    .minimumScaleFactor(0.5)                    .foregroundStyle(BooksMaterial.type.colour)                    .accessibilityIdentifier("book-pages")            }        }        .foregroundStyle(BooksMaterial.ink.colour)        .frame(width: knobs.bandText.width * s, height: knobs.bandText.height * s)        .offset(x: knobs.bandText.minX * s, y: knobs.bandText.minY * s)    }}/// A rating as printed stars: the given ones filled, a half one filled to/// its middle, the rest outlined, in the ink's own star glyphs.private struct Stars: View {    let rating: Double    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let size = knobs.star * s        HStack(spacing: knobs.starGap * s) {            ForEach(0..<knobs.starsOf, id: \.self) { index in                // The type's own stars, the empty one under the full one cut                // to its share: a drawn shape's fill, a stroke or a mask here                // moves the Mac renderer's rounding of the faces drawn after.                ZStack(alignment: .leading) {                    Text(verbatim: "\u{2606}").font(.system(size: size)).frame(width: size)                    Text(verbatim: "\u{2605}").font(.system(size: size)).frame(width: size)                        .frame(width: size * CGFloat(min(1, max(0, rating - Double(index)))), alignment: .leading)                        .clipped()                }                .frame(width: size, height: size, alignment: .leading)            }        }        .contentShape(Rectangle())        .accessibilityElement(children: .ignore)        .accessibilityLabel(ShellLines.line("cards", "deck.position", ["at": rating.formatted(), "of": "\(knobs.starsOf)"]))        .accessibilityIdentifier("face-rating")        .facePart(.stars)    }}/// A stopped book lying on the felt, turned, scaled by `s` from its/// canvas: its shadow, the slip's shadow and the slip out of its fore-edge,/// the book, the cover (or the blank jacket with its title and author)/// warped onto the cover's quad, the cover's gloss, the ribbon, and the/// slip's words warped onto its quad.private struct LyingBook<Cover: View>: View {    let card: DeckCard    let cover: Cover?    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let quad = knobs.coverQuad.map { CGPoint(x: $0.x * s, y: $0.y * s) }        ZStack(alignment: .topLeading) {            BookPainted(name: "book-lying-shadow").laid(knobs.lyingShadow, s)            BookPainted(name: "book-lying-slip-shadow").laid(knobs.lyingSlipShadow, s)            BookPainted(name: "book-lying-slip").laid(knobs.lyingSlip, s)            BookPainted(name: "book-lying").laid(knobs.lyingBook, s)            FlatJacket(card: card, cover: cover, s: s)                .frame(width: knobs.jacket.width * s, height: knobs.jacket.height * s, alignment: .topLeading)                .compositingGroup()                .projectionEffect(BookHardbackSetting.projection(CGSize(width: knobs.jacket.width * s, height: knobs.jacket.height * s), onto: quad))            BookPainted(name: "book-lying-gloss").laid(knobs.lyingGloss, s)            BookPainted(name: "book-lying-ribbon").laid(knobs.lyingRibbon, s)            Slip(card: card, s: s)        }        .frame(width: knobs.lying.maxX * s, height: knobs.lying.maxY * s, alignment: .topLeading)    }}/// The cover flat, in the jacket's own frame before it is warped: the/// cover multiplied by the paper's grain, or the blank jacket with its title/// and author; tagged as the standing book's jacket is.private struct FlatJacket<Cover: View>: View {    let card: DeckCard    let cover: Cover?    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let size = CGSize(width: knobs.jacket.width * s, height: knobs.jacket.height * s)        ZStack(alignment: .topLeading) {            if let cover {                cover.frame(width: size.width, height: size.height).clipped()                BookPainted(name: "book-jacket-blank")                    .frame(width: size.width / knobs.grain.width, height: size.height / knobs.grain.height)                    .offset(x: -knobs.grain.minX * size.width / knobs.grain.width, y: -knobs.grain.minY * size.height / knobs.grain.height)                    .frame(width: size.width, height: size.height, alignment: .topLeading)                    .clipped()                    .blendMode(.multiply)                    .opacity(knobs.grainStrength)            } else {                BookPainted(name: "book-jacket-blank")                    .frame(width: size.width, height: size.height)            }            ZStack(alignment: .topLeading) {                JacketPart(card: card, covered: cover != nil, s: s)                if cover == nil { BlankJacket(card: card, s: s) }            }            .offset(x: -knobs.jacket.minX * s, y: -knobs.jacket.minY * s)        }        .frame(width: size.width, height: size.height, alignment: .topLeading)    }}/// The slip's words typed flat, then warped onto the slip's quad.private struct Slip: View {    let card: DeckCard    let s: CGFloat    var body: some View {        let knobs = BookHardbackFaceKnobs.self        let lines = BookHardbackSetting.slip(card)        let size = CGSize(width: knobs.slipText.width * s, height: knobs.slipText.height * s)        let quad = knobs.slipQuad.map { CGPoint(x: $0.x * s, y: $0.y * s) }        VStack(alignment: .leading, spacing: 0) {            ForEach(Array(lines.enumerated()), id: \.offset) { _, line in                Text(line)                    .font(CottonFonts.type(knobs.slipSize * s))                    .lineLimit(1)                    .minimumScaleFactor(0.6)                    .frame(height: knobs.slipSize * knobs.slipLeading * s, alignment: .leading)            }        }        .foregroundStyle(BooksMaterial.type.colour)        .padding(.leading, knobs.slipInset * s)        .frame(width: size.width, height: size.height, alignment: .leading)        .compositingGroup()        .projectionEffect(BookHardbackSetting.projection(size, onto: quad))        .contentShape(Rectangle())        .accessibilityElement(children: .ignore)        .accessibilityLabel(lines.joined(separator: ShellLines.line("cards", "join")))        .accessibilityIdentifier("book-slip")        .facePart(.state)    }}/// The standing hardback, by its id beside the book's own face, and the/// books it is reviewed in: invented titles, an invented cover. A day is/// said as the core says it (`weekday_date`).public enum BookHardbackFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .feltNavy    public static let face = Face(id: "book.hardback", specimens: [        Specimen("reading", reading, picture: "cover-harbour"), Specimen("reading-no-cover", readingNoCover),        Specimen("want", want, picture: "cover-harbour"), Specimen("finished", finished, picture: "cover-harbour"),        Specimen("stopped", stopped, picture: "cover-harbour"), Specimen("largest", largest),        Specimen("long-word", longWord), Specimen("file-name", fileName), Specimen("stopped-no-cover", stoppedNoCover),    ], steps: .cut) { card, picture, _ in        BookHardbackFace(card: card, cover: picture)    }    static func book(_ status: BookHardbackStatus, _ fields: [String: RecordValue]) -> DeckCard {        var card = DeckCard(face: "book.hardback", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)        card.stored["state"] = status.rawValue        return card    }    /// Part way through, its cover kept and its pages known.    public static let reading = book(.reading, [        "title": .text("The Harbour Lamp"),        "subtitle": .text("Asha Mercer"),        "photo": .text("cover-harbour"),        "state": .text("Reading"),        "started": .text("Mon 12 Oct"),        "used": .number(41),        "pages": .number(303),        "date": .text("Add date"),    ])    /// No cover kept: the blank jacket with its title and author set.    public static let readingNoCover = book(.reading, [        "title": .text("A Field Guide to Small Weather"),        "subtitle": .text("Meera Example"),        "state": .text("Reading"),        "used": .number(60),        "pages": .number(190),        "date": .text("Add date"),    ])    /// Not begun: the book alone, its ribbon hanging its shortest, a sixth    /// of the cover.    public static let want = book(.wantToRead, [        "title": .text("The Harbour Lamp"),        "subtitle": .text("Asha Mercer"),        "photo": .text("cover-harbour"),        "state": .text("Want to read"),        "pages": .number(303),        "date": .text("Add date"),    ])    /// Finished, rated four and a half.    public static let finished = book(.finished, [        "title": .text("The Harbour Lamp"),        "subtitle": .text("Asha Mercer"),        "photo": .text("cover-harbour"),        "state": .text("Finished"),        "started": .text("Mon 28 Sep"),        "date": .text("Mon 12 Oct"),        "used": .number(100),        "pages": .number(303),        "count": .number(4.5),    ])    /// Put down a quarter of the way in: lying, turned, the slip out of its    /// fore-edge.    public static let stopped = book(.stopped, [        "title": .text("The Harbour Lamp"),        "subtitle": .text("Asha Mercer"),        "photo": .text("cover-harbour"),        "state": .text("Stopped"),        "used": .number(23),        "last_read": .text("4 Nov"),        "pages": .number(303),        "date": .text("Add date"),    ])    /// The fullest card: a title that takes the jacket's three lines and is    /// cut, a long author, a long book read part way, drawn at every text    /// size Loom has, the largest among them.    public static let largest = book(.reading, [        "title": .text("The Lamp-Keeper's Daughter and Other Stories of the Northern Coast, Collected and Annotated for the Winter Reader"),        "subtitle": .text("Asha Mercer-Valcourt and Meera Example"),        "state": .text("Reading"),        "used": .number(87),        "pages": .number(1024),        "date": .text("Add date"),    ])    /// No cover kept, a word too wide for the jacket at its own size: the    /// title taken down until the word stands whole, never broken in two.    public static let longWord = book(.wantToRead, [        "title": .text("The Featherstonehaugh Inheritance"),        "subtitle": .text("Meera Example"),        "state": .text("Want to read"),        "pages": .number(412),        "date": .text("Add date"),    ])    /// No cover kept and a title that is the file's own name: broken at    /// its underscores and dot, kept inside the jacket.    public static let fileName = book(.wantToRead, [        "title": .text("the_lamp_keepers_daughter_annotated_edition.epub"),        "subtitle": .text("Meera Example"),        "state": .text("Want to read"),        "date": .text("Add date"),    ])    /// Stopped, no cover kept: the blank jacket, its file-name title broken    /// sensibly, warped onto the lying book's cover.    public static let stoppedNoCover = book(.stopped, [        "title": .text("the_lamp_keepers_daughter.epub"),        "subtitle": .text("Meera Example"),        "state": .text("Stopped"),        "used": .number(61),        "last_read": .text("2 Nov"),        "date": .text("Add date"),    ])}