Cotton code
786 lines · 36.4 KB · SwiftRaw
// The HIGHLIGHT as a TORN STRIP OF PAPER lying on the books' navy felt// (`FaceGround.feltNavy`, under its lamp): the coordinator's Books pictures// of 4 Nov 2026 (`books27/highlight-a`), painted by Codex as wordless layers// (`books27/layers`, imported by `scripts/import-books-materials.py// layers`). A wide strip of cream paper torn on every side, in three painted// bands — its top, its middle repeated (the last repeat partial) to the// height the words need, its foot — over its shadow sliced the same way,// lying in the upper middle of the deck's room, as wide as the room. On it,// top to bottom:////   the PASSAGE large in Libre Caslon inside curly quotes, in lines ending//   on whole words, as many as it takes up to a sensible limit (nine, or//   fewer where the room is shorter): a longer passage stops at the last//   with an ellipsis, as the face did before. Each line is underlined in//   the highlight's colour as a PENCIL STROKE beneath the words (not the//   quotes): drawn, a little uneven in width and weight, grainy at its//   edges; never a flat rule and never a fill. Red, yellow or teal, by the//   choice the card says (`ink`, its stored value); a highlight that says//   none is set bare.//   one line under it: the book's TITLE in italic (Instrument Serif) and,//   after a middle dot, its AUTHOR in Caslon, cut with an ellipsis where it//   runs past its room.//   when the highlight has a NOTE, the painted CURL over the strip's lower//   right corner and on its face the note in a pencil hand (Caveat,//   graphite), at most two lines, turned a little. No note, no curl. The//   strip grows until no word lies under the curl.//// Tagged: the passage (`quote`), the note (`note`), the title (`title`),// the author (`subtitle`). Stepped by a tap, it cuts. Print on an object// scales with the object, never with Dynamic Type.//// Every word is the core's (`DeckCard`): the face sets them and adds only// the quotes and the middle dot.import CottonPaperimport CottonValuesimport CoreTextimport SwiftUIenum HighlightPassageFaceKnobs {    // THE STRIP, in the paintings' pixels (`layout.json`, a 2400 px wide    // strip), drawn as wide as the room and scaled by the room's width over    // 2400: its bands (the top's and the foot's rows, the middle's period),    // the writing's room in from the left and the top (the paintings'    // `safeTextBox`), how wide it is and how far above the foot it ends.    static let width: CGFloat = 2400    static let band: CGFloat = 250    static let period: CGFloat = 400    static let textLeft: CGFloat = 160    static let textTop: CGFloat = 130    static let textWidth: CGFloat = 2010    static let textFoot: CGFloat = 240    /// The shadow, larger than the strip by `shadowOut` on every side, its    /// top and foot slices as tall as the strip's bands and that much more.    static let shadowOut: CGFloat = 60    /// How much of the room left over lies above the strip (the upper    /// middle), and the most of the room's height it takes before the    /// passage is cut.    static let rise: CGFloat = 0.36    static let fill: CGFloat = 0.96    /// The passage, as shares of the room's width (the deck's card is 340    /// points wide on a phone): its size, the step from one baseline to the    /// next as a share of its size, the most lines it takes and the fewest    /// the room may cut it to.    static let passageSize: CGFloat = 0.059    static let passageStep: CGFloat = 1.34    static let passageMost = 9    static let passageLeast = 3    /// The line under it: the gap above it, the title's size (Instrument    /// Serif runs small for its points) and the author's, of the room's    /// width.    static let byGap: CGFloat = 0.03    static let titleSize: CGFloat = 0.052    static let authorSize: CGFloat = 0.04    // THE CURL (`highlight-curl`, 720 x 480, and its shadow 40 px larger),    // drawn `curlScale` times its painted size, its lower right corner    // `curlFoot` above the strip's lower right; the left edge of its paper    // down its rows (row, leftmost painted column), which no word comes    // nearer than `curlClear`; the note's room on its face (the middle and    // the width of its lines, in its painting's pixels), the note's size in    // the hand, its step, its lines and its turn.    static let curl = CGSize(width: 720, height: 480)    static let curlScale: CGFloat = 1.25    static let curlFoot: CGFloat = 30    static let curlShadowOut: CGFloat = 40    static let curlEdge: [(row: CGFloat, left: CGFloat)] = [        (30, 715), (40, 709), (80, 678), (120, 631), (160, 563), (200, 478), (240, 404), (280, 342),        (320, 295), (360, 259), (400, 222), (440, 138), (470, 0), (480, 0),    ]    static let curlClear: CGFloat = 40    static let noteMiddle = CGPoint(x: 490, y: 338)    static let noteWidth: CGFloat = 340    static let noteSize: CGFloat = 0.044    static let noteStep: CGFloat = 0.98    static let noteLines = 2    static let noteTurn: Double = -12    // THE PENCIL STROKE, as shares of the passage's size: how far below the    // baseline its middle runs, how thick it is, how far past each end of    // the line it runs, how much its middle wanders and its ends slope, and    // how its weight varies (the least share of its full weight the stroke    // is pressed to); the grain laid over it, as specks per point of its    // length, and the specks' size.    static let strokeDrop: CGFloat = 0.2    static let strokeWidth: CGFloat = 0.15    static let strokePast: CGFloat = 0.14    static let strokeWander: CGFloat = 0.035    static let strokeSlope: CGFloat = 0.05    static let strokeLeast: CGFloat = 0.62    static let strokeBody: Double = 0.42    static let grainDensity: CGFloat = 3.2    static let grainSize: CGFloat = 0.045}/// The pencil a highlight is underlined in, by its colour's stored value.public enum HighlightInk: String, CaseIterable, Sendable {    case red, yellow, teal    /// The highlight's ink, by the value the card's ink place says; nil, it    /// says none (or one this build has no pencil for) and the passage is    /// set bare.    public init?(_ card: DeckCard) {        guard let said = card.text("ink") else { return nil }        self.init(rawValue: said)    }    public var colour: Color {        switch self {        case .red: BooksMaterial.pencilRed.colour        case .yellow: BooksMaterial.pencilYellow.colour        case .teal: BooksMaterial.pencilTeal.colour        }    }}/// How a highlight's strip is set: what it says, where it lies in the room/// and how big it is.public enum HighlightPassageSetting {    /// `text` in lines no wider than `width` in `font`, each ending on a    /// whole word (a word wider than the room is broken where it must be),    /// at most `limit`: past it the last line takes the words that fit    /// before an ellipsis, its trailing punctuation dropped.    public static func lines(_ text: String, font: CTFont, width: CGFloat, limit: Int) -> [String] {        let words = text.split(whereSeparator: \.isWhitespace).map(String.init)        guard !words.isEmpty, limit > 0 else { return [] }        var lines: [String] = []        var line = ""        for word in words {            let joined = line.isEmpty ? word : line + " " + word            if wide(joined, font) <= width {                line = joined                continue            }            if !line.isEmpty { lines.append(line) }            line = ""            var rest = word            while wide(rest, font) > width, rest.count > 1 {                var cut = rest.count - 1                while cut > 1, wide(String(rest.prefix(cut)), font) > width { cut -= 1 }                lines.append(String(rest.prefix(cut)))                rest = String(rest.dropFirst(cut))            }            line = rest        }        if !line.isEmpty { lines.append(line) }        guard lines.count > limit else { return lines }        return Array(lines.prefix(limit - 1)) + [cut(lines[limit - 1], font: font, width: width)]    }    /// The last line `line` of words that run on past it, cut: the words    /// that fit before an ellipsis, its trailing punctuation dropped.    static func cut(_ line: String, font: CTFont, width: CGFloat) -> String {        var last = line.split(separator: " ").map(String.init)        let ellipsis = "\u{2026}"        func closed(_ words: [String]) -> String {            var said = words.joined(separator: " ")            while let end = said.last, ",;:.\u{2014}\u{2013}-".contains(end) { said.removeLast() }            return said + ellipsis        }        while last.count > 1, wide(closed(last), font) > width { last.removeLast() }        return closed(last)    }    /// How wide `text` is set in `font`, its trailing space not counted.    static func wide(_ text: String, _ font: CTFont) -> CGFloat {        let set = NSAttributedString(string: text, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font])        let line = CTLineCreateWithAttributedString(set)        return CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil) - CTLineGetTrailingWhitespaceWidth(line))    }    /// Libre Caslon as CoreText measures it.    static func caslon(_ size: CGFloat) -> CTFont {        _ = CottonFonts.caslon(1)        return CTFontCreateWithName(CottonFonts.caslonFace as CFString, max(1, size), nil)    }    /// Instrument Serif's italic as CoreText measures it: the title's.    static func italic(_ size: CGFloat) -> CTFont {        _ = CottonFonts.cap(1)        return CTFontCreateWithName(CottonFonts.capFace as CFString, max(1, size), nil)    }    /// The pencil hand as CoreText measures it: the note's.    static func hand(_ size: CGFloat) -> CTFont {        _ = CottonFonts.hand(1)        return CTFontCreateWithName(CottonFonts.handFace as CFString, max(1, size), nil)    }    /// The passage inside curly quotes; one the book already opens with a    /// quote mark is kept as it is.    public static func quoted(_ passage: String) -> String {        let said = passage.split(whereSeparator: \.isWhitespace).joined(separator: " ")        guard let first = said.first, !"\u{201C}\"\u{2018}'\u{00AB}".contains(first) else { return said }        return "\u{201C}" + said + "\u{201D}"    }    /// The line under the passage: the title, and the author after a middle    /// dot, each cut with an ellipsis where the two run past `width` (the    /// author first, then the title); nil, the card says neither.    public static func by(_ card: DeckCard, width: CGFloat, room: CGFloat) -> (title: String?, author: String?)? {        let knobs = HighlightPassageFaceKnobs.self        var title = card.text("source")        var author = card.text("subtitle")        guard title != nil || author != nil else { return nil }        let titleFont = italic(knobs.titleSize * room)        let authorFont = caslon(knobs.authorSize * room)        let dot = " \u{00B7} "        func wide() -> CGFloat {            (title.map { self.wide($0, titleFont) } ?? 0)                + (author.map { self.wide((title == nil ? "" : dot) + $0, authorFont) } ?? 0)        }        if wide() > width, let said = author {            let left = width - (title.map { self.wide($0, titleFont) } ?? 0) - self.wide(dot, authorFont)            if left > self.wide("M\u{2026}", authorFont) {                author = cutChars(said, font: authorFont, width: left)            } else if title != nil {                author = nil            }        }        if wide() > width, let said = title {            title = cutChars(said, font: titleFont, width: width)            author = nil        }        return (title, author)    }    /// `text` cut to the characters that fit `width` before an ellipsis.    static func cutChars(_ text: String, font: CTFont, width: CGFloat) -> String {        guard wide(text, font) > width else { return text }        var kept = text        while kept.count > 1, wide(kept.trimmingCharacters(in: .whitespaces) + "\u{2026}", font) > width { kept.removeLast() }        return kept.trimmingCharacters(in: .whitespaces) + "\u{2026}"    }    /// The note's lines in the pencil hand on a strip `width` wide; none    /// when there is no note.    public static func noteLines(_ card: DeckCard, width: CGFloat) -> [String] {        guard let note = card.text("note") else { return [] }        let knobs = HighlightPassageFaceKnobs.self        return lines(note, font: hand(knobs.noteSize * width), width: noteRoom(width), limit: knobs.noteLines)    }    /// The note's room across the curl's face on a strip `width` wide.    static func noteRoom(_ width: CGFloat) -> CGFloat {        let knobs = HighlightPassageFaceKnobs.self        return knobs.noteWidth * knobs.curlScale * width / knobs.width    }    /// The leftmost the curl's paper reaches at `row` of its painting; past    /// its top, nowhere.    static func curlLeft(_ row: CGFloat) -> CGFloat? {        let edge = HighlightPassageFaceKnobs.curlEdge        guard let first = edge.first, row >= first.row else { return nil }        for (a, b) in zip(edge, edge.dropFirst()) where row <= b.row {            return a.left + (b.left - a.left) * (row - a.row) / (b.row - a.row)        }        return edge.last?.left    }    /// The strip set in a room `room`: its words, its size and where it lies.    public static func strip(_ card: DeckCard, room: CGSize) -> HighlightStrip {        let knobs = HighlightPassageFaceKnobs.self        let width = room.width        let s = width / knobs.width        let inner = knobs.textWidth * s        let left = knobs.textLeft * s        let size = knobs.passageSize * width        let step = size * knobs.passageStep        let font = caslon(size)        let ascent = CTFontGetAscent(font)        let passage = card.text("quote").map(quoted)        let notes = noteLines(card, width: width)        let curl = notes.isEmpty ? nil : CGSize(width: knobs.curl.width * knobs.curlScale * s, height: knobs.curl.height * knobs.curlScale * s)        let titleFont = italic(knobs.titleSize * width), authorFont = caslon(knobs.authorSize * width)        let byHeight = max(CTFontGetAscent(titleFont) + CTFontGetDescent(titleFont), CTFontGetAscent(authorFont) + CTFontGetDescent(authorFont))        var limit = knobs.passageMost        while true {            let lines = passage.map { self.lines($0, font: font, width: inner, limit: limit) } ?? []            let passageHeight = lines.isEmpty ? 0 : ascent + CGFloat(lines.count - 1) * step + size * (knobs.strokeDrop + knobs.strokeWidth)            let top = knobs.textTop * s            let saysBy = card.text("source") != nil || card.text("subtitle") != nil            let byTop = top + passageHeight + (lines.isEmpty || !saysBy ? 0 : knobs.byGap * width)            var height = max(2 * knobs.band * s, byTop + (saysBy ? byHeight : 0) + knobs.textFoot * s)            // The words' rooms, to keep clear of the curl; the line under            // them is as wide as the curl leaves it.            let words: [CGRect] = lines.enumerated().map { index, line in                let base = top + ascent + CGFloat(index) * step                return CGRect(x: left, y: base - ascent, width: wide(line, font), height: ascent + size * (knobs.strokeDrop + knobs.strokeWidth))            }            func clearOf(_ rect: CGRect, at height: CGFloat) -> CGFloat {                guard let curl else { return .infinity }                let curlTop = height - knobs.curlFoot * s - curl.height                let row = (rect.maxY - curlTop) / (knobs.curlScale * s)                guard let reach = curlLeft(row) else { return .infinity }                return width - curl.width + reach * knobs.curlScale * s - knobs.curlClear * s            }            if curl != nil {                let byFloor = CGFloat(knobs.authorSize * width * 6)                while !(words.allSatisfy { $0.maxX <= clearOf($0, at: height) }                    && (!saysBy || clearOf(CGRect(x: left, y: byTop, width: 0, height: byHeight), at: height) - left >= min(byFloor, inner))) {                    height += 1                }            }            let byRoom = min(inner, clearOf(CGRect(x: left, y: byTop, width: 0, height: byHeight), at: height) - left)            let byLine = saysBy ? by(card, width: byRoom, room: width) : nil            if height <= room.height * knobs.fill || limit <= knobs.passageLeast || lines.count < limit {                let origin = CGPoint(x: (room.width - width) / 2, y: max(0, (room.height - height) * knobs.rise))                return HighlightStrip(                    origin: origin, size: CGSize(width: width, height: height), passage: lines, passageSize: size,                    passageLeft: left, passageTop: top, title: byLine?.title, author: byLine?.author, byTop: byTop, byHeight: byHeight,                    note: notes, curl: curl.map { CGRect(origin: CGPoint(x: width - $0.width, y: height - knobs.curlFoot * s - $0.height), size: $0) })            }            limit -= 1        }    }}/// A highlight's strip as it is set: where it lies in the room and how big/// it is, its passage's lines, size and place, the line under them, and,/// with a note, where its curl lies on the strip and the note's lines.public struct HighlightStrip: Equatable {    public let origin: CGPoint    public let size: CGSize    public let passage: [String]    public let passageSize: CGFloat    public let passageLeft: CGFloat    public let passageTop: CGFloat    public let title: String?    public let author: String?    public let byTop: CGFloat    public let byHeight: CGFloat    public let note: [String]    public let curl: CGRect?    /// The strip's rect in the room.    public var frame: CGRect { CGRect(origin: origin, size: size) }    /// Points to a painting's pixel.    public var scale: CGFloat { size.width / HighlightPassageFaceKnobs.width }    /// Whether `rect`, on the strip, reaches under the curl's paper.    public func underCurl(_ rect: CGRect) -> Bool {        guard let curl else { return false }        let knobs = HighlightPassageFaceKnobs.self        let k = knobs.curlScale * scale        guard let reach = HighlightPassageSetting.curlLeft((rect.maxY - curl.minY) / k) else { return false }        return rect.maxX > curl.minX + reach * k    }}/// A pencil stroke under a line `length` long: its outline, its body's/// weight and the grain over it, drawn from a seed so a card draws the same/// stroke every time.struct PencilStroke {    /// The stroke's band: its upper and lower edges, left to right.    let upper: [CGPoint]    let lower: [CGPoint]    /// The specks of graphite over and about the band: where, how big, how    /// dark.    let grain: [(at: CGPoint, size: CGFloat, weight: Double)]    /// The stroke under a line from 0 to `length` whose baseline is at    /// `base`, for type of `size`, drawn from `seed`.    init(length: CGFloat, base: CGFloat, size: CGFloat, seed: String) {        let knobs = HighlightPassageFaceKnobs.self        var draw = PencilDraw(seed)        let past = knobs.strokePast * size        let from = -past * draw.between(0.7, 1.2)        let to = length + past * draw.between(0.8, 1.3)        let middle = base + knobs.strokeDrop * size        let full = knobs.strokeWidth * size        let slope = knobs.strokeSlope * size * draw.between(-1, 1)        let wander = knobs.strokeWander * size        let phases = (draw.between(0, 2 * .pi), draw.between(0, 2 * .pi))        let pressure = (draw.between(0, 2 * .pi), draw.between(2, 4))        let steps = max(8, Int((to - from) / 2))        var upper: [CGPoint] = []        var lower: [CGPoint] = []        for step in 0...steps {            let share = CGFloat(step) / CGFloat(steps)            let x = from + share * (to - from)            let y = middle + slope * (share - 0.5)                + wander * (sin(share * 5.1 + phases.0) * 0.6 + sin(share * 13.7 + phases.1) * 0.4)            // Pressed down at the start, lifted off at the end; the weight            // between them never even.            let ends = min(1, share / 0.06) * min(1, (1 - share) / 0.1)            let press = knobs.strokeLeast + (1 - knobs.strokeLeast) * (0.5 + 0.5 * sin(share * pressure.1 * .pi + pressure.0))            let half = full / 2 * max(0.25, ends) * press * draw.between(0.9, 1.1)            upper.append(CGPoint(x: x, y: y - half))            lower.append(CGPoint(x: x, y: y + half * draw.between(0.85, 1.15)))        }        var grain: [(at: CGPoint, size: CGFloat, weight: Double)] = []        let specks = Int((to - from) * knobs.grainDensity)        for _ in 0..<specks {            let share = draw.between(0, 1)            let index = min(steps, Int(share * CGFloat(steps)))            let top = upper[index].y            let bottom = lower[index].y            // Most specks lie in the band; some stray past its edges, which            // is what makes the edges grainy rather than cut.            let spread = draw.between(-0.35, 1.35)            let y = top + spread * (bottom - top)            let inside = spread >= 0 && spread <= 1            grain.append((                at: CGPoint(x: from + share * (to - from), y: y),                size: knobs.grainSize * size * draw.between(0.6, 1.6),                weight: inside ? Double(draw.between(0.25, 0.7)) : Double(draw.between(0.1, 0.4))            ))        }        self.upper = upper        self.lower = lower        self.grain = grain    }    /// The band's outline.    var outline: Path {        Path { path in            guard let first = upper.first else { return }            path.move(to: first)            for point in upper.dropFirst() { path.addLine(to: point) }            for point in lower.reversed() { path.addLine(to: point) }            path.closeSubpath()        }    }    /// Drawn in `ink`: the body light, the grain darker over it and about    /// its edges.    func draw(in context: inout GraphicsContext, ink: Color) {        context.fill(outline, with: .color(ink.opacity(HighlightPassageFaceKnobs.strokeBody)))        for speck in grain {            let rect = CGRect(x: speck.at.x - speck.size / 2, y: speck.at.y - speck.size / 2, width: speck.size, height: speck.size * 0.7)            context.fill(Path(ellipseIn: rect), with: .color(ink.opacity(speck.weight)))        }    }}/// A seeded draw of numbers: the same words always draw the same stroke/// (SplitMix64 over the words' FNV-1a hash, never Swift's per-run hash).struct PencilDraw {    private var state: UInt64    init(_ seed: String) {        var hash: UInt64 = 0xcbf2_9ce4_8422_2325        for byte in seed.utf8 {            hash ^= UInt64(byte)            hash &*= 0x0000_0100_0000_01b3        }        state = hash    }    mutating func next() -> UInt64 {        state &+= 0x9e37_79b9_7f4a_7c15        var z = state        z = (z ^ (z >> 30)) &* 0xbf58_476d_1ce4_e5b9        z = (z ^ (z >> 27)) &* 0x94d0_49bb_1331_11eb        return z ^ (z >> 31)    }    /// A number between `low` and `high`.    mutating func between(_ low: CGFloat, _ high: CGFloat) -> CGFloat {        low + (high - low) * CGFloat(Double(next() >> 11) / Double(1 << 53))    }}public struct HighlightPassageFace: View {    let card: DeckCard    public init(card: DeckCard) {        self.card = card    }    public var body: some View {        GeometryReader { room in            let strip = HighlightPassageSetting.strip(card, room: room.size)            TornStrip(card: card, strip: strip)                .frame(width: strip.size.width, height: strip.size.height, alignment: .topLeading)                .offset(x: strip.origin.x, y: strip.origin.y)                .frame(width: room.size.width, height: room.size.height, alignment: .topLeading)        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("highlight-passage")    }}/// A painted layer, by its catalogue name: `count` of its rows from `from`/// (in the paintings' pixels, of a painting `size` big) laid at `at` down/// the strip, at `s` points to a pixel; nothing where this build carries no/// pictures.private struct Rows: View {    let name: String    let size: CGSize    let from: CGFloat    let count: CGFloat    let at: CGPoint    let s: CGFloat    var body: some View {        if let image = CottonMedia.image(name, scale: 3), count > 0 {            image.resizable().interpolation(.high)                .frame(width: size.width * s, height: size.height * s)                .offset(y: -from * s)                .frame(width: size.width * s, height: count * s, alignment: .top)                .clipped()                .offset(x: at.x * s, y: at.y * s)                .accessibilityHidden(true)        }    }}/// A painting sliced as the strip is: its top rows, its middle repeated/// (the last repeat partial) and its foot rows, `height` pixels tall from/// `at`.private struct Sliced: View {    let top: (name: String, size: CGSize, from: CGFloat)    let middle: (name: String, size: CGSize, from: CGFloat)    let foot: (name: String, size: CGSize, from: CGFloat)    let ends: CGFloat    let height: CGFloat    let at: CGPoint    let s: CGFloat    var body: some View {        let period = HighlightPassageFaceKnobs.period        let run = max(0, height - 2 * ends)        ZStack(alignment: .topLeading) {            Rows(name: top.name, size: top.size, from: top.from, count: ends, at: at, s: s)            ForEach(Array(stride(from: CGFloat(0), to: run, by: period)), id: \.self) { done in                Rows(name: middle.name, size: middle.size, from: middle.from, count: min(period, run - done),                     at: CGPoint(x: at.x, y: at.y + ends + done), s: s)            }            Rows(name: foot.name, size: foot.size, from: foot.from, count: ends, at: CGPoint(x: at.x, y: at.y + ends + run), s: s)        }    }}/// The strip in its own frame: its shadow, its three bands, the passage,/// the line under it, and the curl.private struct TornStrip: View {    let card: DeckCard    let strip: HighlightStrip    var body: some View {        let knobs = HighlightPassageFaceKnobs.self        let s = strip.scale        let height = strip.size.height / s        let out = knobs.shadowOut        let shadow = CGSize(width: knobs.width + 2 * out, height: 2 * knobs.band + knobs.period + 2 * out)        let band = CGSize(width: knobs.width, height: knobs.band)        let middle = CGSize(width: knobs.width, height: knobs.period)        ZStack(alignment: .topLeading) {            Sliced(top: ("highlight-strip-shadow", shadow, 0), middle: ("highlight-strip-shadow", shadow, knobs.band + out),                   foot: ("highlight-strip-shadow", shadow, knobs.band + out + knobs.period),                   ends: knobs.band + out, height: height + 2 * out, at: CGPoint(x: -out, y: -out), s: s)            Sliced(top: ("highlight-strip-top", band, 0), middle: ("highlight-strip-middle", middle, 0),                   foot: ("highlight-strip-bottom", band, 0), ends: knobs.band, height: height, at: .zero, s: s)            Passage(card: card, strip: strip)            By(strip: strip)            if let curl = strip.curl {                Curl(card: card, strip: strip, curl: curl)            }        }        .frame(width: strip.size.width, height: strip.size.height, alignment: .topLeading)    }}private struct Passage: View {    let card: DeckCard    let strip: HighlightStrip    var body: some View {        let knobs = HighlightPassageFaceKnobs.self        let width = strip.size.width        let size = strip.passageSize        let step = size * knobs.passageStep        let lines = strip.passage        let font = HighlightPassageSetting.caslon(size)        let ascent = CTFontGetAscent(font)        let ink = HighlightInk(card)        let room = knobs.textWidth * strip.scale        let height = lines.isEmpty ? 1 : ascent + CGFloat(lines.count - 1) * step + size * (knobs.strokeDrop + knobs.strokeWidth)        Canvas { context, _ in            for (index, line) in lines.enumerated() {                let base = ascent + CGFloat(index) * step                if let ink {                    // Beneath the words: the quotes stand bare.                    let lead = line.hasPrefix("\u{201C}") ? HighlightPassageSetting.wide("\u{201C}", font) : 0                    let trail = line.hasSuffix("\u{201D}") ? HighlightPassageSetting.wide("\u{201D}", font) : 0                    let length = HighlightPassageSetting.wide(line, font) - lead - trail                    var pencil = context                    pencil.blendMode = .multiply                    pencil.translateBy(x: lead, y: 0)                    PencilStroke(length: length, base: base, size: size, seed: "\(index) \(line)").draw(in: &pencil, ink: ink.colour)                }                let text = context.resolve(Text(line).font(CottonFonts.caslon(size)).foregroundStyle(BooksMaterial.ink.colour))                let far = CGSize(width: 10_000, height: 10_000)                context.draw(text, at: CGPoint(x: 0, y: base - text.firstBaseline(in: far)), anchor: .topLeading)            }        }        .frame(width: room, height: height, alignment: .topLeading)        .contentShape(Rectangle())        .accessibilityElement()        .accessibilityLabel(card.text("quote") ?? "")        .accessibilityIdentifier("highlight-quote")        .facePart(.quote)        .offset(x: strip.passageLeft, y: strip.passageTop)    }}/// The line under the passage: the title in italic, the author after a/// middle dot.private struct By: View {    let strip: HighlightStrip    var body: some View {        let knobs = HighlightPassageFaceKnobs.self        let width = strip.size.width        HStack(alignment: .firstTextBaseline, spacing: 0) {            if let title = strip.title {                Text(title)                    .font(CottonFonts.cap(knobs.titleSize * width))                    .lineLimit(1)                    .fixedSize()                    .accessibilityLabel(title)                    .accessibilityIdentifier("deck-title")                    .accessibilityAddTraits(.isHeader)                    .facePart(.title)            }            if let author = strip.author {                Text((strip.title == nil ? "" : " \u{00B7} ") + author)                    .font(CottonFonts.caslon(knobs.authorSize * width))                    .lineLimit(1)                    .fixedSize()                    .accessibilityLabel(author)                    .accessibilityIdentifier("highlight-author")                    .facePart(.subtitle)            }        }        .foregroundStyle(BooksMaterial.type.colour.opacity(0.85))        .frame(height: strip.byHeight, alignment: .leading)        .offset(x: strip.passageLeft, y: strip.byTop)    }}/// The curled corner: the flap's shadow on the paper, the flap (the paper's/// back, shaded from the fold to its tip, torn along its two free sides),/// the crease along the fold, and the note pencilled on it./// The painted curl over the strip's lower right corner, over its shadow,/// and the note pencilled on its face.private struct Curl: View {    let card: DeckCard    let strip: HighlightStrip    let curl: CGRect    var body: some View {        let knobs = HighlightPassageFaceKnobs.self        let k = curl.width / knobs.curl.width        let out = knobs.curlShadowOut        let size = knobs.noteSize * strip.size.width        ZStack(alignment: .topLeading) {            if let shadow = CottonMedia.image("highlight-curl-shadow", scale: 3) {                shadow.resizable().interpolation(.high)                    .frame(width: (knobs.curl.width + 2 * out) * k, height: (knobs.curl.height + 2 * out) * k)                    .offset(x: curl.minX - out * k, y: curl.minY - out * k)                    .accessibilityHidden(true)            }            if let paper = CottonMedia.image("highlight-curl", scale: 3) {                paper.resizable().interpolation(.high)                    .frame(width: curl.width, height: curl.height)                    .offset(x: curl.minX, y: curl.minY)                    .accessibilityHidden(true)            }            VStack(alignment: .leading, spacing: 0) {                ForEach(Array(strip.note.enumerated()), id: \.offset) { _, line in                    Text(line)                        .font(CottonFonts.hand(size))                        .foregroundStyle(BooksMaterial.graphite.colour)                        .lineLimit(1)                        .fixedSize()                        .frame(height: size * knobs.noteStep, alignment: .leading)                }            }            .frame(width: HighlightPassageSetting.noteRoom(strip.size.width), alignment: .leading)            .rotationEffect(.degrees(knobs.noteTurn))            .contentShape(Rectangle())            .accessibilityElement()            .accessibilityLabel(card.text("note") ?? "")            .accessibilityIdentifier("highlight-note")            .facePart(.note)            .frame(width: 1, height: 1)            .offset(x: curl.minX + knobs.noteMiddle.x * k, y: curl.minY + knobs.noteMiddle.y * k)        }    }}/// The torn strip, by its id beside the highlight's own, and the highlights/// it is reviewed in: invented passages from invented books.public enum HighlightPassageFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .feltNavy    public static let face = Face(id: "highlight.passage", specimens: [        Specimen("red-note", redNote), Specimen("yellow-bare", yellowBare),        Specimen("teal-cut", tealCut), Specimen("largest", largest),    ], steps: .cut) { card, _, _ in        HighlightPassageFace(card: card)    }    static func highlight(_ fields: [String: RecordValue]) -> DeckCard {        DeckCard(face: "highlight.passage", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)    }    /// Red, with a note: the corner curled with the note on it.    public static let redNote = highlight([        "quote": .text("The tide does not argue; it arrives, and the harbour makes room for it whether or not the boats are ready."),        "note": .text("A beacon, not a wall."),        "source": .text("The Harbour Lamp"),        "subtitle": .text("Asha Mercer"),        "place": .text("p. 37"),        "crumb": .text("The Lamp-Keeper's Daughter"),        "ink": .text("red"),    ])    /// Yellow, no note: no curl, the strip as short as its words.    public static let yellowBare = highlight([        "quote": .text("Every lamp is a promise made to someone you will never meet."),        "source": .text("The Harbour Lamp"),        "subtitle": .text("Asha Mercer"),        "place": .text("p. 112"),        "ink": .text("yellow"),    ])    /// Teal, a passage longer than the strip takes, cut; a short note.    public static let tealCut = highlight([        "quote": .text("""            She kept the weather in a ledger, one line a day, and when the ledger was full she began another, so that by the end \            of her life there were forty of them on the shelf above the stove, each one a year of small skies: rain at noon, \            wind from the east, a fog that would not lift until the fish were landed and the boats were in and the children \            had been called home for supper twice, and then a third time, because the fog had not lifted and the lamps along \            the harbour wall had been lit early and burned all night.            """),        "note": .text("Start one."),        "source": .text("A Field Guide to Small Weather"),        "subtitle": .text("Meera Example"),        "crumb": .text("Ledgers"),        "ink": .text("teal"),    ])    /// The fullest card: a long passage, three lines of note, a long title    /// and a long author, drawn at every text size Loom has, the largest    /// among them.    public static let largest = highlight([        "quote": .text("""            We do not keep the light for ourselves. We keep it for the ones still out past the point, who cannot see the \            rocks and cannot see us, and who must take it on trust that someone is awake, and turning the lamp, and \            trimming the wick, and that the night will end.            """),        "note": .text("""            Copied this out for Asha before her exams, then kept it for myself. The bit about trimming the wick is the \            whole job, really, every single day of it.            """),        "source": .text("The Harbour Lamp: A Novel of the Northern Coast"),        "subtitle": .text("Asha Mercer-Valcourt and Meera Example"),        "place": .text("p. 214"),        "crumb": .text("The Night the Lamp Went Out"),        "ink": .text("yellow"),    ])}