Cotton code
551 lines · 24.3 KB · SwiftRaw
// The PAGE as a NEWSPAPER CLIPPING (Cotton Pages, 12 Nov 2026; the core// lane's face spec, `kits/pages/kit.json` `face`): a column cut out of the// paper and kept, held at its head in a steel bulldog clip, lying a hair// askew on the pages' cobalt enamel desk (`FaceGround.cobaltEnamel`). It is paper// because a clipping IS paper; nothing of the deck's paper is under it.////   THE CLIPPING: grey newsprint, cut straight with scissors along its head//   and its left side and TORN along its right side and its foot, a deckle//   of small uneven teeth with the fibres a shade darker where it tore; its//   shadow on the enamel under it.//   ON IT, top to bottom, as a paper sets a column: the site in spaced//   small capitals with the day it was kept at the right, over a double//   rule; the HEADLINE large, set in a newspaper's type chosen by the site//   (every page of one site wears the same, as a paper's own type is its//   own); the byline in italic; the lead picture, printed in HALFTONE (grey,//   its dots laid over it in the paper's ink); the excerpt in a text serif,//   as many lines as the column has room for; and at the foot, in small//   print, how long it takes to read, whether it is unread or being read,//   and the list it is kept in.//   THE CLIP at its head, over the cut: steel, or BRASS when the page is//   starred (the star is the clip's metal and nothing else).//// Tagged: the headline (`title`), the byline (`subtitle`), the picture// (`picture`), the excerpt (`body`), the day (`when`), the state (`state`)// and the list (`group`). 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 only sets them.import CottonPaperimport CottonValuesimport SwiftUIenum PageClippingFaceKnobs {    // THE CLIPPING in the card's room, as shares of the card's width: its    // inset from each side, its head below the card's top (the clip stands    // above it), its foot above the card's foot; how far askew it lies.    static let side: CGFloat = 0.07    static let head: CGFloat = 0.1    static let foot: CGFloat = 0.04    static let turn: Double = -1.1    /// The torn edges: how deep the deckle's teeth run and how far apart    /// they stand, in points; the darker fibres' band, in points.    static let tearDepth: CGFloat = 3.2    static let tearPitch: CGFloat = 3.6    static let fibres: CGFloat = 1.6    /// The clipping's shadow on the enamel, in points.    static let shadowRadius: CGFloat = 5    static let shadowDrop: CGFloat = 4    static let shadowWeight: Double = 0.22    // THE COLUMN, as shares of the clipping's width: its margin, the site's    // size and tracking (a share of its size), the rules' gap, the    // headline's size and its lines, the byline's size, the picture's    // shape (width over height), the excerpt's size and line step, the    // foot's size, and the gap between the column's parts.    static let margin: CGFloat = 0.07    static let siteSize: CGFloat = 0.036    static let siteTracking: CGFloat = 0.18    static let ruleGap: CGFloat = 2.5    static let headlineSize: CGFloat = 0.085    static let headlineLines = 3    static let bylineSize: CGFloat = 0.046    static let pictureShape: CGFloat = 2    static let excerptSize: CGFloat = 0.043    static let excerptStep: CGFloat = 1.32    static let footSize: CGFloat = 0.036    static let gap: CGFloat = 0.03    /// THE HALFTONE: the dots' pitch in points and their largest share of    /// the pitch; how strongly they are laid over the grey picture.    static let dotPitch: CGFloat = 3.2    static let dotLargest: CGFloat = 0.9    static let dotWeight: Double = 0.55    // THE CLIP, as shares of the card's width: its jaw's width and height,    // its lever's reach above the jaw, the wire's thickness in points.    static let clipWidth: CGFloat = 0.3    static let clipHeight: CGFloat = 0.085    static let leverReach: CGFloat = 0.06    static let wire: CGFloat = 2.6}/// How a clipping is set: the words its column carries, and the type its/// headline wears.public enum PageClippingSetting {    /// The newspaper types a headline is set in, by the site (`source`): one    /// site always wears the same.    public enum Headline: CaseIterable, Sendable {        /// A broadsheet's tall serif.        case broadsheet        /// An old paper's book serif.        case bookish        /// A tabloid's condensed sans.        case tabloid        public func font(_ size: CGFloat) -> Font {            switch self {            case .broadsheet: CottonFonts.display(size)            case .bookish: CottonFonts.caslon(size * 1.04)            case .tabloid: CottonFonts.letterboard(size * 1.12)            }        }    }    /// The headline's type for `card`: picked by its site (or its address's    /// host, which the source place says when the page names no site), the    /// broadsheet's where it says neither.    public static func headline(_ card: DeckCard) -> Headline {        guard let site = card.text("source")?.lowercased(), !site.isEmpty else { return .broadsheet }        var draw = PencilDraw(site)        let all = Headline.allCases        return all[Int(draw.next() % UInt64(all.count))]    }    /// The page is starred: the core says the starred flag in the state    /// place, which the clip shows as brass.    public static func starred(_ card: DeckCard) -> Bool {        card.stored["state"] == starredFlag    }    /// The state the foot prints: unread or reading, as the core says it;    /// nothing while the place holds the starred flag, which the clip says.    public static func state(_ card: DeckCard) -> String? {        starred(card) ? nil : card.text("state")    }    /// The foot's small print: how long it takes to read, the state and the    /// list, joined as the core joins.    public static func foot(_ card: DeckCard) -> String? {        let said = [card.text("length"), state(card), card.text("group")].compactMap { $0 }        return said.isEmpty ? nil : said.joined(separator: ShellLines.line("cards", "join"))    }    /// The column the starred flag is kept in.    static let starredFlag = "own_pages__starred"}public struct PageClippingFace: View {    let card: DeckCard    /// The lead picture; nil, the column runs on without one.    let picture: FacePicture?    public init(card: DeckCard, picture: FacePicture?) {        self.card = card        self.picture = picture    }    public var body: some View {        let knobs = PageClippingFaceKnobs.self        GeometryReader { box in            let width = box.size.width            let clipping = CGRect(                x: knobs.side * width, y: knobs.head * width,                width: width * (1 - 2 * knobs.side),                height: max(1, box.size.height - (knobs.head + knobs.foot) * width))            let seed = card.text("title") ?? card.record ?? "clipping"            ZStack(alignment: .topLeading) {                ZStack(alignment: .topLeading) {                    Newsprint(size: clipping.size, seed: seed)                    Column(card: card, picture: picture, size: clipping.size)                        .clipShape(TornClipping(seed: seed))                }                .frame(width: clipping.width, height: clipping.height)                .compositingGroup()                .shadow(color: PagesMaterial.ink.colour.opacity(knobs.shadowWeight), radius: knobs.shadowRadius, x: 0, y: knobs.shadowDrop)                .rotationEffect(.degrees(knobs.turn), anchor: .top)                .offset(x: clipping.minX, y: clipping.minY)                BulldogClip(brass: PageClippingSetting.starred(card), width: width)                    .position(x: width / 2, y: clipping.minY + knobs.clipHeight * width * 0.18)            }            .frame(width: box.size.width, height: box.size.height, alignment: .topLeading)        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("page-clipping")    }}/// The clipping's outline: cut straight along its head and its left side,/// torn along its right side and its foot, the same tear every time for/// the same page.struct TornClipping: Shape {    let seed: String    func path(in rect: CGRect) -> Path {        let knobs = PageClippingFaceKnobs.self        var draw = PencilDraw(seed)        var path = Path()        let depth = knobs.tearDepth        path.move(to: CGPoint(x: rect.minX, y: rect.minY))        path.addLine(to: CGPoint(x: rect.maxX - depth, y: rect.minY))        // The right side, torn down from the head.        var y = rect.minY        while y < rect.maxY - depth {            y = min(rect.maxY - depth, y + knobs.tearPitch * draw.between(0.5, 1.5))            path.addLine(to: CGPoint(x: rect.maxX - depth * draw.between(0, 1), y: y))        }        // The foot, torn back to the left side.        var x = rect.maxX - depth        while x > rect.minX {            x = max(rect.minX, x - knobs.tearPitch * draw.between(0.5, 1.5))            path.addLine(to: CGPoint(x: x, y: rect.maxY - depth * draw.between(0, 1)))        }        path.closeSubpath()        return path    }}/// The newsprint: grey paper in the torn outline, the fibres darker along/// the tear.private struct Newsprint: View {    let size: CGSize    let seed: String    var body: some View {        let shape = TornClipping(seed: seed)        ZStack {            shape.fill(PagesMaterial.newsprint.colour)            shape.stroke(PagesMaterial.tornEdge.colour, lineWidth: PageClippingFaceKnobs.fibres)                .clipShape(shape)        }        .frame(width: size.width, height: size.height)    }}/// The column printed on the clipping.private struct Column: View {    let card: DeckCard    let picture: FacePicture?    let size: CGSize    var body: some View {        let knobs = PageClippingFaceKnobs.self        let width = size.width        let room = width * (1 - 2 * knobs.margin)        let gap = knobs.gap * width        VStack(alignment: .leading, spacing: gap) {            Masthead(card: card, width: width)            if let title = card.text("title") {                Text(title)                    .font(PageClippingSetting.headline(card).font(knobs.headlineSize * width))                    .foregroundStyle(PagesMaterial.ink.colour)                    .lineLimit(knobs.headlineLines)                    .minimumScaleFactor(0.75)                    .lineSpacing(-knobs.headlineSize * width * 0.08)                    .fixedSize(horizontal: false, vertical: true)                    .accessibilityIdentifier("deck-title")                    .accessibilityAddTraits(.isHeader)                    .facePart(.title)            }            if let byline = card.text("subtitle") {                Text(byline)                    .font(CottonFonts.cap(knobs.bylineSize * width))                    .foregroundStyle(PagesMaterial.smallPrint.colour)                    .lineLimit(1)                    .minimumScaleFactor(0.7)                    .accessibilityIdentifier("page-byline")                    .facePart(.subtitle)            }            if let picture {                Halftone(picture: picture, size: CGSize(width: room, height: room / knobs.pictureShape))                    .accessibilityIdentifier("page-picture")                    .facePart(.picture)            }            if let excerpt = card.text("body") {                Text(excerpt)                    .font(CottonFonts.caslon(knobs.excerptSize * width))                    .foregroundStyle(PagesMaterial.ink.colour)                    .lineSpacing(knobs.excerptSize * width * (knobs.excerptStep - 1))                    .frame(maxHeight: .infinity, alignment: .topLeading)                    .clipped()                    .accessibilityIdentifier("page-excerpt")                    .facePart(.body)            } else {                Spacer(minLength: 0)            }            Foot(card: card, width: width)        }        .frame(width: room, alignment: .topLeading)        .padding(.horizontal, knobs.margin * width)        .padding(.top, knobs.margin * width * 1.3)        .padding(.bottom, knobs.margin * width)        .frame(width: size.width, height: size.height, alignment: .topLeading)    }}/// The column's head: the site in spaced small capitals, the day at the/// right, a double rule under them.private struct Masthead: View {    let card: DeckCard    let width: CGFloat    var body: some View {        let knobs = PageClippingFaceKnobs.self        let size = knobs.siteSize * width        VStack(alignment: .leading, spacing: knobs.ruleGap) {            HStack(alignment: .firstTextBaseline, spacing: size) {                if let site = card.text("source") {                    Text(site.uppercased())                        .font(CottonFonts.caslon(size))                        .tracking(size * knobs.siteTracking)                        .foregroundStyle(PagesMaterial.smallPrint.colour)                        .lineLimit(1)                        .minimumScaleFactor(0.6)                        .accessibilityLabel(site)                        .accessibilityIdentifier("page-site")                }                Spacer(minLength: 0)                if let date = card.text("date") {                    Text(date)                        .font(CottonFonts.caslon(size))                        .foregroundStyle(PagesMaterial.smallPrint.colour)                        .lineLimit(1)                        .accessibilityIdentifier("page-date")                        .facePart(.when)                }            }            Rectangle().fill(PagesMaterial.ink.colour).frame(height: 1.2)            Rectangle().fill(PagesMaterial.ink.colour).frame(height: 0.5)        }    }}/// The foot's small print.private struct Foot: View {    let card: DeckCard    let width: CGFloat    var body: some View {        let size = PageClippingFaceKnobs.footSize * width        HStack(spacing: size * 0.6) {            if let length = card.text("length") {                Text(length).accessibilityIdentifier("page-length")            }            if let state = PageClippingSetting.state(card) {                Text(state).accessibilityIdentifier("page-state").facePart(.state)            }            if let group = card.text("group") {                Text(group).accessibilityIdentifier("page-group").facePart(.group)            }            Spacer(minLength: 0)        }        .font(CottonFonts.caslon(size).smallCaps())        .foregroundStyle(PagesMaterial.smallPrint.colour)        .lineLimit(1)        .minimumScaleFactor(0.7)    }}/// The lead picture printed in halftone: the picture in grey, and over it/// the paper showing between a screen of dots, so its darks read as dots/// run together and its lights as the newsprint.private struct Halftone: View {    let picture: FacePicture    let size: CGSize    var body: some View {        let knobs = PageClippingFaceKnobs.self        // The picture is laid in its printed block, which stands whether or        // not the picture has come: a grey block, as a page printed dark.        Rectangle()            .fill(PagesMaterial.tornEdge.colour)            .overlay { picture }            .frame(width: size.width, height: size.height)            .clipped()            .grayscale(1)            .contrast(1.2)            .colorMultiply(PagesMaterial.newsprint.colour)            .overlay {                // The paper between the dots, laid lighter-wins: where the                // picture is darker than the paper the gaps show the paper,                // and the dots keep the picture's tone.                Canvas { context, box in                    let pitch = knobs.dotPitch                    let dot = pitch * knobs.dotLargest                    var screen = Path(CGRect(origin: .zero, size: box))                    var y: CGFloat = 0                    var row = 0                    while y < box.height + pitch {                        var x: CGFloat = row.isMultiple(of: 2) ? 0 : pitch / 2                        while x < box.width + pitch {                            screen.addEllipse(in: CGRect(x: x - dot / 2, y: y - dot / 2, width: dot, height: dot))                            x += pitch                        }                        y += pitch * 0.866                        row += 1                    }                    context.fill(screen, with: .color(PagesMaterial.newsprint.colour), style: FillStyle(eoFill: true))                }                .blendMode(.lighten)                .opacity(knobs.dotWeight)                .allowsHitTesting(false)            }            .frame(width: size.width, height: size.height)    }}/// The bulldog clip over the clipping's head: a jaw of pressed metal, its/// rivets, and the wire lever folded back above it; brass on a starred/// page, steel on any other.struct BulldogClip: View {    let brass: Bool    let width: CGFloat    var body: some View {        let knobs = PageClippingFaceKnobs.self        let jaw = CGSize(width: knobs.clipWidth * width, height: knobs.clipHeight * width)        let reach = knobs.leverReach * width        let metal = brass            ? (base: PagesMaterial.brass.colour, lit: PagesMaterial.brassLit.colour, shade: PagesMaterial.brassShade.colour)            : (base: PagesMaterial.steel.colour, lit: PagesMaterial.steelLit.colour, shade: PagesMaterial.steelShade.colour)        ZStack(alignment: .top) {            // The lever: a wire loop folded back over the jaw.            RoundedRectangle(cornerRadius: jaw.width * 0.18)                .stroke(LinearGradient(colors: [metal.lit, metal.shade], startPoint: .topLeading, endPoint: .bottomTrailing), lineWidth: knobs.wire)                .frame(width: jaw.width * 0.62, height: reach + jaw.height * 0.5)            // The jaw.            ClipJaw()                .fill(LinearGradient(colors: [metal.lit, metal.base, metal.shade], startPoint: .top, endPoint: .bottom))                .overlay(ClipJaw().stroke(metal.shade.opacity(0.8), lineWidth: 0.6))                .overlay(alignment: .center) {                    HStack(spacing: jaw.width * 0.5) {                        Rivet(metal: metal, size: jaw.height * 0.16)                        Rivet(metal: metal, size: jaw.height * 0.16)                    }                    .offset(y: -jaw.height * 0.12)                }                .frame(width: jaw.width, height: jaw.height)                .shadow(color: PagesMaterial.ink.colour.opacity(0.32), radius: 2.5, x: 0, y: 2)                .offset(y: reach)        }        .frame(width: jaw.width, height: reach + jaw.height, alignment: .top)        .offset(y: -reach / 2)        .accessibilityElement()        .accessibilityIdentifier(brass ? "page-clip-brass" : "page-clip-steel")    }}/// The jaw's outline: wider at its foot where it bites, its shoulders/// rounded where it is pressed over the spring.private struct ClipJaw: Shape {    func path(in rect: CGRect) -> Path {        let inset = rect.width * 0.08        let shoulder = rect.height * 0.35        var path = Path()        path.move(to: CGPoint(x: rect.minX + inset, y: rect.minY + shoulder))        path.addQuadCurve(to: CGPoint(x: rect.minX + inset + shoulder, y: rect.minY), control: CGPoint(x: rect.minX + inset, y: rect.minY))        path.addLine(to: CGPoint(x: rect.maxX - inset - shoulder, y: rect.minY))        path.addQuadCurve(to: CGPoint(x: rect.maxX - inset, y: rect.minY + shoulder), control: CGPoint(x: rect.maxX - inset, y: rect.minY))        path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))        path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))        path.closeSubpath()        return path    }}private struct Rivet: View {    let metal: (base: Color, lit: Color, shade: Color)    let size: CGFloat    var body: some View {        Circle()            .fill(RadialGradient(colors: [metal.lit, metal.shade], center: .topLeading, startRadius: 0, endRadius: size))            .frame(width: size, height: size)    }}/// The clipping, by its id beside the page's own, and the pages it is/// reviewed in: invented articles from invented papers, invented pictures.public enum PageClippingFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .cobaltEnamel    public static let face = Face(id: "page.clipping", specimens: [        Specimen("unread", unread, picture: "kelmoor-jetty"), Specimen("starred", starred, picture: "kelmoor-lake"),        Specimen("no-picture", noPicture), Specimen("bare", bare), Specimen("largest", largest, picture: "kelmoor-jetty"),    ], steps: .cut) { card, picture, _ in        PageClippingFace(card: card, picture: picture)    }    static func page(_ fields: [String: RecordValue], stored: [String: String] = [:]) -> DeckCard {        var card = DeckCard(face: "page.clipping", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)        card.stored = stored        return card    }    /// A kept page, unread, with its picture, byline and excerpt.    public static let unread = page([        "title": .text("The harbour that wakes before the town"),        "subtitle": .text("By A. Writer"),        "source": .text("Example Gazette"),        "date": .text("2 hours ago"),        "length": .text("6 min read"),        "state": .text("Unread"),        "photo": .text("kelmoor-jetty"),        "body": .text("The boats go out on the tide, one after another, while the gulls argue over the nets and the first light finds the harbour wall. Nobody in the town is awake yet, and nobody needs to be."),    ], stored: ["state": "unread"])    /// Starred and being read, in a list: the clip is brass.    public static let starred = page([        "title": .text("A field guide to small weather"),        "subtitle": .text("By Invented Correspondent"),        "source": .text("The Sample Review"),        "date": .text("Yesterday"),        "length": .text("12 min read"),        "state": .text("Starred"),        "group": .text("Weekend"),        "photo": .text("kelmoor-lake"),        "body": .text("She kept the weather in a ledger, one line a day, and when the ledger was full she began another."),    ], stored: ["state": "own_pages__starred"])    /// A page kept with no picture: the excerpt takes the column.    public static let noPicture = page([        "title": .text("Why the ferry timetable is a poem"),        "subtitle": .text("By A. Sample"),        "source": .text("invented.example"),        "date": .text("3 days ago"),        "length": .text("4 min read"),        "state": .text("Reading"),        "body": .text("""            Read it aloud and it scans: the early boat, the late boat, the boat that runs only on Thursdays in the season, \            and the one that waits for the train. Every line is a promise made to someone who will be standing on the \            jetty in the rain, and every footnote is an apology.            """),    ], stored: ["state": "reading"])    /// A link just kept, before its copy is fetched: its address's host and    /// the day alone.    public static let bare = page([        "title": .text("news.invented.example"),        "source": .text("news.invented.example"),        "date": .text("Just now"),        "state": .text("Unread"),    ], stored: ["state": "unread"])    /// The fullest card: a headline that runs past three lines, a long    /// byline, a long excerpt, every place of the foot, drawn at every text    /// size Loom has.    public static let largest = page([        "title": .text("After forty years the lighthouse keeper's ledgers are read again, and they say more about us than the weather"),        "subtitle": .text("By Invented Correspondent and A. Second Writer, in Kelmoor"),        "source": .text("The Northern Coast Sample Gazette"),        "date": .text("Sun 26 Oct 2026"),        "length": .text("23 min read"),        "state": .text("Reading"),        "group": .text("Long reads for the train"),        "photo": .text("kelmoor-jetty"),        "body": .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. The ledgers, forty of them on the shelf above the stove, say \            so in a hand that never changes.            """),    ], stored: ["state": "reading"])}