Cotton code
339 lines · 13.0 KB · SwiftRaw
// A card's paper, every face's (architect, 22 Oct 2026: two decks must not// have two papers; the card architecture, 28 Oct 2026: a face lays its own).// Card design's textures-v2, in the final recipe's order// (`compose/blank-card-final.html`): two sheets of the same shape under the// card, a little right and down and turned; the card's shape filled with its// stock's tint over a soft shadow; the mottle multiplied at its opacity —// image 1 is a clean mottle, no specks (architect, 22 Oct 2026); the rim's// burnish multiplied; the notched rule recoloured to its ink; the face drawn// inside the rule.//// A face calls it on its own body, naming its stock: `.onCardPaper(.framed)`.// The stock is the face's data, declared beside the face in its file// (CottonFaces' `FaceStock`); a face that draws its own sheet (a// subscription's ticket, a membership's pass) calls nothing.// Whatever holds a card in a stack — the deck, a gallery, Loom — draws the// sheets under it beside the card (`CardSheetsUnder`), of the stock it knows// the card's face is printed on before the card is drawn (CottonFaces'// `FaceRegistry.stock(_:)`), so they stay put while the card is dragged.//// The tints, inks and opacities are the theme's data (`palette.faces`,// `palette.paces`, `palette.pace_rules`, the `card_*` tokens), never Swift's.// The pictures are 1080x1350, 3x a 360x450 pt card, scaled to the card's size// (`Media.xcassets`, written by `scripts/import-card-paper.py`).import SwiftUIpublic enum CardPaperKnobs {    /// The card's width over its height.    public static let aspect: CGFloat = 4.0 / 5.0    /// The width the recipe's offsets are measured against.    public static let recipeWidth: CGFloat = 376    /// The sheets under the card, nearest first: each one's offset (at the    /// recipe's width) and turn in degrees.    public static let under: [(offset: CGSize, turn: Double)] = [        (CGSize(width: 3, height: 4), 0.6),        (CGSize(width: 6, height: 7), -0.5),    ]    /// The room the sheets under the card take beyond it, right and down.    public static func underRoom(width: CGFloat) -> CGSize {        let far = under.last?.offset ?? .zero        return CGSize(width: (far.width + 2) * width / recipeWidth, height: (far.height + 2) * width / recipeWidth)    }    /// The printed rule's inset, as a share of the card's width (in the    /// rule's own picture).    public static let ruleInset: CGFloat = 0.025    /// Where a face's words may stand: inside the rule.    public static func contentInset(width: CGFloat) -> CGFloat { width * ruleInset }}/// What a card is printed on, by name; the theme says its tint and its rule.public enum CardStock: Hashable, Sendable {    /// The cream card (images 2a, 9, 11, 12).    case cream    /// The note's card: cream, the rule ornamented with sprigs (image 3).    case ornamented    /// The cream card framed by the notched rule in pencil.    case framed    /// A pace band's paper, by the band's key: its tint (`palette.paces`)    /// and its rule in the band's ink (`palette.pace_rules`).    case band(String)}extension Theme {    /// The paper a pace band's card is tinted to, by the band's key.    public func bandTint(_ band: String) -> Color? {        colors.paces[band]?.color    }    /// The rule printed on a pace band's card, by the band's key.    public func bandRule(_ band: String) -> Color {        colors.paceRules[band]?.color ?? print(.red)    }}/// The rule a stock prints inside its edge.enum CardRule {    case none    /// The plain notched rule (`deck-rule-notched`), in this ink.    case notched(Color)    /// The note's ornamented rule (`deck-rule-ornament`), in this ink.    case ornament(Color)}/// A stock as a theme prints it: its tint and its rule.struct CardInks {    let fill: Color    let rule: CardRule    init(_ stock: CardStock, theme: Theme) {        let cream = theme.colors.faces["cream"]?.color ?? .clear        switch stock {        case .cream:            fill = cream            rule = .none        case .ornamented:            fill = cream            rule = .ornament(theme.colors.faces["ornament"]?.color ?? .clear)        case .framed:            fill = cream            rule = .notched(theme.print(.pencil))        case .band(let band):            fill = theme.bandTint(band) ?? theme.colors.paper.color            rule = .notched(theme.bandRule(band))        }    }}/// What a theme's data says the card is made of. A paper family's card is/// the photographed sheet: its mottle and rim, its printed rule, its edge, a/// hairline shadow. A flat family's (`plain`, a business flavour's look) is a/// clean card: its stock's fill with no mottle or rim where the theme has no/// grain (`texture.grain`), no photographed rule, the theme's corner, the/// face drawn to its edge and cut by that corner, and a soft drop under it/// where the theme casts one (`texture.shadow: soft`) at the card's shadow/// strength (`card_shadow_opacity`). The colours are the theme's/// (`palette.faces.cream` the card, `ground` the page); nothing here names a/// flavour.public enum CardMaterial {    /// The card is flat rather than photographed paper.    public static func flat(_ theme: Theme) -> Bool { theme.family == .plain }    /// The paper's own mottle and rim are drawn.    public static func grain(_ theme: Theme) -> Bool { !flat(theme) || theme.texture.grain }    /// The face is drawn inside the printed rule, or to the flat card's edge.    public static func inset(_ theme: Theme, width: CGFloat) -> CGFloat {        flat(theme) ? 0 : CardPaperKnobs.contentInset(width: width)    }    /// The room a face is drawn in on a card of `size`: inside the rule, as    /// the paper pads it (`onCardPaper`).    public static func inside(_ size: CGSize, theme: Theme) -> CGSize {        let inset = inset(theme, width: size.width)        return CGSize(width: max(0, size.width - inset - inset), height: max(0, size.height - inset - inset))    }    /// The flat card's soft drop: how far it falls and spreads.    public static let dropRadius: CGFloat = 14    public static let dropFall: CGFloat = 6    /// The soft drop is cast.    public static func drops(_ theme: Theme) -> Bool { flat(theme) && theme.texture.shadow == .soft }}extension View {    /// This face printed on its card's paper: the stock's sheet under it,    /// the face inside its rule (to a flat card's edge, cut by its corner).    public func onCardPaper(_ stock: CardStock) -> some View {        modifier(OnCardPaper(stock: stock))    }}/// Where a card's paper lies, told to what stands over it: the deck's ink/// draws a stroke crossing the paper in the paper's own ink (owner, 2 Nov/// 2026). Each paper laid under it says its frame on the screen (global/// points) by its own id, and nil as it goes. Absent, nothing is told.public struct CardPaperReport: Sendable {    public let laid: @MainActor @Sendable (UUID, CGRect?) -> Void    public init(_ laid: @escaping @MainActor @Sendable (UUID, CGRect?) -> Void) {        self.laid = laid    }}private struct CardPaperReportKey: EnvironmentKey {    static let defaultValue: CardPaperReport? = nil}extension EnvironmentValues {    /// Told where each card paper under it lies (`CardPaperReport`).    public var cardPaperReport: CardPaperReport? {        get { self[CardPaperReportKey.self] }        set { self[CardPaperReportKey.self] = newValue }    }}extension View {    /// This view is a card's light paper: it says where it lies to whatever    /// stands over the card (`CardPaperReport`). A face that paints its own    /// sheet marks the sheet with it; `onCardPaper` marks the stock's.    public func cardPaperLaid() -> some View {        modifier(CardPaperLaid())    }}private struct CardPaperLaid: ViewModifier {    @Environment(\.cardPaperReport) private var report    @State private var id = UUID()    func body(content: Content) -> some View {        content            .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in report?.laid(id, frame) }            .onDisappear { report?.laid(id, nil) }    }}private struct OnCardPaper: ViewModifier {    let stock: CardStock    @Environment(\.theme) private var theme    func body(content: Content) -> some View {        GeometryReader { box in            ZStack {                CardSheet(inks: CardInks(stock, theme: theme))                content                    .padding(CardMaterial.inset(theme, width: box.size.width))                    .modifier(FlatCardCut(flat: CardMaterial.flat(theme)))            }        }        .cardPaperLaid()    }}/// One of the paper's pictures, stretched to the card.private struct PaperPicture: View {    let name: String    var body: some View {        if let image = CottonMedia.image(name) {            image.resizable().interpolation(.high)        }    }}/// The card's outline: everything of the paper is cut by it. Paper's is the/// photographed sheet's edge; a flat family's card is a rounded card of the/// theme's own corner (`scale.radius`, `radius_min`, `radius_fraction`).private struct CardOutline: View {    @Environment(\.theme) private var theme    var body: some View {        if CardMaterial.flat(theme) {            GeometryReader { box in                RoundedRectangle(cornerRadius: theme.scale.radius(for: box.size), style: .continuous).fill(Color.black)            }        } else {            PaperPicture(name: "deck-paper-shape")        }    }}/// A card's stock as the card in front shows it: fill, mottle, rim, rule.private struct CardSheet: View {    let inks: CardInks    @Environment(\.theme) private var theme    var body: some View {        let scale = theme.scale        let shadow = theme.print(.ink).opacity(Double(scale[.cardShadowOpacity]))        ZStack {            inks.fill            if CardMaterial.grain(theme) {                PaperPicture(name: "deck-paper-mottle")                    .blendMode(.multiply)                    .opacity(Double(scale[.cardMottleOpacity]))                PaperPicture(name: "deck-paper-rim")                    .blendMode(.multiply)                    .opacity(Double(scale[.cardRimOpacity]))            }            rule.opacity(Double(scale[.cardRuleOpacity]))        }        .mask(CardOutline())        .compositingGroup()        .background {            inks.fill.mask(CardOutline())                .shadow(color: shadow, radius: 1.5, x: 0, y: 2)                .shadow(color: CardMaterial.drops(theme) ? shadow : .clear,                        radius: CardMaterial.dropRadius, x: 0, y: CardMaterial.dropFall)        }        .accessibilityHidden(true)    }    /// The printed rule: the photographed paper's, never on a flat card.    @ViewBuilder private var rule: some View {        switch CardMaterial.flat(theme) ? CardRule.none : inks.rule {        case .none: EmptyView()        case .notched(let ink): ink.mask(PaperPicture(name: "deck-rule-notched"))        case .ornament(let ink): ink.mask(PaperPicture(name: "deck-rule-ornament"))        }    }}/// A face on a flat card runs to its edge and is cut by its corner; on/// paper it stands inside the rule, uncut.private struct FlatCardCut: ViewModifier {    let flat: Bool    func body(content: Content) -> some View {        if flat { content.mask(CardOutline()) } else { content }    }}/// The sheets under the card in front, of its stock a shade darker, drawn/// beside it at its size: how many show says more cards follow (none at a/// deck's end).public struct CardSheetsUnder: View {    let count: Int    let stock: CardStock    @Environment(\.theme) private var theme    public init(count: Int, stock: CardStock) {        self.count = count        self.stock = stock    }    public var body: some View {        GeometryReader { box in            let scale = box.size.width / CardPaperKnobs.recipeWidth            let fill = CardInks(stock, theme: theme).fill            ZStack {                ForEach((0..<min(count, CardPaperKnobs.under.count)).reversed(), id: \.self) { depth in                    let sheet = CardPaperKnobs.under[depth]                    UnderSheet(fill: fill)                        .rotationEffect(.degrees(sheet.turn))                        .offset(x: sheet.offset.width * scale, y: sheet.offset.height * scale)                }            }        }        .accessibilityHidden(true)    }}/// One sheet under the card: its stock's fill a shade darker, cut to the/// card's shape, on a hairline shadow.private struct UnderSheet: View {    let fill: Color    @Environment(\.theme) private var theme    var body: some View {        let shade = Double(theme.scale[.cardUnderShade])        let shadow = Double(theme.scale[.cardShadowOpacity])        let ink = theme.print(.ink)        let veil: Color = ink.opacity(shade)        let under: Color = ink.opacity(shadow)        fill            .overlay(Rectangle().fill(veil).blendMode(.multiply))            .mask(CardOutline())            .shadow(color: under, radius: 0.5, x: 0, y: 1)    }}