Cotton code
775 lines · 30.5 KB · SwiftRaw
// THE SKIN. A face has structure — what goes where, which the table and tool// definitions already carry as data — and skin: colour, type, corner, spacing,// texture, shadow. The skin is this value, and it is the only place a face may// read one (design note 26203e21, section 6).//// One value, carried down the view tree as `\.theme`. Every face, page style// and paper reads its inks, its faces, its corner and its lift from it, never// from a constant; `ThemeScanGuardTests` reads `Faces/`, `Surfaces/PageStyles/`// and `Paper/` and fails on a palette, font or metric table named there.//// THE FAMILY IS CODE, THE THEME IS DATA. A family is a way of drawing — `paper`// (the photographed sheets, the typewriter, the bottle caps: Cotton's own look)// or `plain` (flat cards, system type, no texture) — and it ships in the// binary. A theme is a row in a database that picks a family and sets its// knobs, so a business's members see the business's look without a build.// Thousands of theme rows over a handful of families, never thousands of// families.//// `Theme.paper` IS TODAY'S COTTON, VALUE FOR VALUE. Every number in it is the// constant a face read before the theme existed (`Palettes.paper`, the// ribbon's channels, `CottonFonts`' faces, `PaperMetrics`, `Metrics`), so the// app draws pixel-identical with it — `ThemeDefaultTests` holds each value to// its source and `ThemeSnapshotTests` holds the pixels.import CoreTextimport SwiftUI#if canImport(UIKit)import UIKit#endif/// One database's look: a family and the knobs it is drawn with.public struct Theme: Equatable, Sendable {    /// The theme's parts live in one shared box, copied only on a write: a    /// face reads `theme` from its environment hundreds of times a body, and    /// an inline Theme (two palettes, the type, ~1,000 scale keys) copied    /// onto the stack at each read ran the record faces and SlipFace past    /// the phone's stack budget (`FaceStackTests`, 13 Oct 2026). A Theme value is    /// now one reference and an appearance.    private final class Storage: @unchecked Sendable {        var id: String        var name: String        var family: ThemeFamily        var palette: ThemePalettes        var type: ThemeType        var scale: ThemeScale        var texture: ThemeTexture        var cap: ThemeCap        var acts: ThemeActs        var cards: ThemeCards        init(id: String, name: String, family: ThemeFamily, palette: ThemePalettes, type: ThemeType, scale: ThemeScale, texture: ThemeTexture, cap: ThemeCap, acts: ThemeActs, cards: ThemeCards) {            self.id = id            self.name = name            self.family = family            self.palette = palette            self.type = type            self.scale = scale            self.texture = texture            self.cap = cap            self.acts = acts            self.cards = cards        }        func copy() -> Storage {            Storage(id: id, name: name, family: family, palette: palette, type: type, scale: scale, texture: texture, cap: cap, acts: acts, cards: cards)        }    }    private var storage: Storage    /// The row's id; `default` for the built-in theme a database is seeded with.    public var id: String {        get { storage.id }        set { unique(); storage.id = newValue }    }    public var name: String {        get { storage.name }        set { unique(); storage.name = newValue }    }    public var family: ThemeFamily {        get { storage.family }        set { unique(); storage.family = newValue }    }    public var palette: ThemePalettes {        get { storage.palette }        set { unique(); storage.palette = newValue }    }    public var type: ThemeType {        get { storage.type }        set { unique(); storage.type = newValue }    }    public var scale: ThemeScale {        get { storage.scale }        set { unique(); storage.scale = newValue }    }    public var texture: ThemeTexture {        get { storage.texture }        set { unique(); storage.texture = newValue }    }    public var cap: ThemeCap {        get { storage.cap }        set { unique(); storage.cap = newValue }    }    /// The stock each class of act is printed on.    public var acts: ThemeActs {        get { storage.acts }        set { unique(); storage.acts = newValue }    }    /// A field card's defaults.    public var cards: ThemeCards {        get { storage.cards }        set { unique(); storage.cards = newValue }    }    /// Which of the palette's two appearances is drawn. Set by `themed(_:)`    /// at the root from the colour scheme, so a face reads `colors` and never    /// asks the scheme itself.    public var appearance: ColorScheme = .light    /// The palette for the appearance being drawn.    public var colors: ThemePalette { palette.resolved(appearance) }    public init(        id: String,        name: String,        family: ThemeFamily,        palette: ThemePalettes,        type: ThemeType,        scale: ThemeScale,        texture: ThemeTexture,        cap: ThemeCap,        acts: ThemeActs,        cards: ThemeCards    ) {        storage = Storage(id: id, name: name, family: family, palette: palette, type: type, scale: scale, texture: texture, cap: cap, acts: acts, cards: cards)    }    private mutating func unique() {        if !isKnownUniquelyReferenced(&storage) { storage = storage.copy() }    }    public static func == (lhs: Theme, rhs: Theme) -> Bool {        lhs.appearance == rhs.appearance && (lhs.storage === rhs.storage || (lhs.id == rhs.id && lhs.name == rhs.name && lhs.family == rhs.family && lhs.palette == rhs.palette && lhs.type == rhs.type && lhs.scale == rhs.scale && lhs.texture == rhs.texture && lhs.cap == rhs.cap && lhs.acts == rhs.acts && lhs.cards == rhs.cards))    }    /// The family's own default theme — what a row that names only a family    /// draws, and what every key a row leaves out falls back to.    public static func standard(_ family: ThemeFamily) -> Theme {        switch family {        case .paper: return .paper        case .plain: return .plain        }    }}/// The ways of drawing that ship in the binary. Each draws every structure/// key a definition can name, so every definition renders in every family.public enum ThemeFamily: String, CaseIterable, Sendable {    /// Cotton's own: photographed paper, the typewriter and the hand, enamel    /// caps, a sheet tilted a hair and lying on the plaster.    case paper    /// Flat cards in the palette's own ground, the system face, no grain, no    /// tilt, solid tags; corner and spacing straight from the theme.    case plain}// MARK: - Palette/// One colour a theme names, as its four channels.////// Channels rather than a hex string because two of today's paints were/// written as channels (the ribbon, the photograph's fallbacks) and a hex/// rounds them; a row uses hex or precise CSS sRGB (`ThemeRow`).public struct ThemeColor: Equatable, Sendable {    public var red: Double    public var green: Double    public var blue: Double    public var alpha: Double    public init(red: Double, green: Double, blue: Double, alpha: Double = 1) {        self.red = red        self.green = green        self.blue = blue        self.alpha = alpha    }    /// RGBA supplied by a native surface or decoded document. These are    /// observed values, including extended sRGB, rather than authored ink.    public init?(components: [Double]) {        guard components.count == 4, components.allSatisfy(\.isFinite) else { return nil }        red = components[0]        green = components[1]        blue = components[2]        alpha = components[3]    }    /// Native paint over an opaque ground, retaining the supplied channels.    public func composited(over ground: ThemeColor) -> ThemeColor {        var result = ground        result.red = red * alpha + ground.red * (1 - alpha)        result.green = green * alpha + ground.green * (1 - alpha)        result.blue = blue * alpha + ground.blue * (1 - alpha)        result.alpha = 1        return result    }    /// From an authored palette colour.    public init(_ authored: CottonColor) {        let parts = authored.components        red = parts.red        green = parts.green        blue = parts.blue        alpha = parts.alpha    }    /// From `#RRGGBB` or `#RRGGBBAA`; nil for anything else, so a malformed    /// row keeps the family's value instead of drawing black.    public init?(hex: String) {        let digits = hex.hasPrefix("#") ? String(hex.dropFirst()) : hex        guard digits.count == 6 || digits.count == 8, let value = UInt64(digits, radix: 16) else { return nil }        let rgba = digits.count == 6 ? value << 8 | 0xFF : value        func channel(_ shift: UInt64) -> Double { Double((rgba >> shift) & 0xFF) / 255 }        red = channel(24)        green = channel(16)        blue = channel(8)        alpha = channel(0)    }    /// An authored palette value: hex, or CSS's precise three-channel sRGB    /// form. Reject non-finite and out-of-gamut values at the data boundary.    public init?(palette value: String) {        if let hex = ThemeColor(hex: value) { self = hex; return }        guard value.hasPrefix("color(srgb "), value.hasSuffix(")") else { return nil }        let fields = value.dropFirst(11).dropLast().split(whereSeparator: \.isWhitespace)        guard fields.count == 3 else { return nil }        let channels = fields.compactMap { Double($0) }        guard channels.count == 3, channels.allSatisfy({ $0.isFinite && (0...1).contains($0) }) else { return nil }        red = channels[0]        green = channels[1]        blue = channels[2]        alpha = 1    }    public var color: Color {        Color(.sRGB, red: red, green: green, blue: blue, opacity: alpha)    }    public func opacity(_ amount: Double) -> Color { color.opacity(amount) }    #if canImport(UIKit)    /// For the UIKit seams a face hosts (a PDF view, an image view).    public var uiColor: UIColor {        UIColor(cgColor: CGColor(srgbRed: red, green: green, blue: blue, alpha: alpha))    }    #endif}/// The palette for each appearance. Cotton is light-only today, so the/// default's dark is its light; a theme row may give a dark of its own.public struct ThemePalettes: Equatable, Sendable {    public var light: ThemePalette    public var dark: ThemePalette    public init(light: ThemePalette, dark: ThemePalette) {        self.light = light        self.dark = dark    }    public func resolved(_ scheme: ColorScheme) -> ThemePalette {        scheme == .dark ? dark : light    }}/// Every colour a face paints with, by role.////// The chrome roles are `CottonPalette`'s, so a face on the page ground and a/// settings row beside it agree. The print roles are what is set ON an object:/// the ribbon a sheet is typed with and the pencil that annotates it. The/// colour rule still binds every theme: monochrome plus one accent, state in/// the status colours, and colour never names a kind.public struct ThemePalette: Equatable, Sendable {    public var ground: ThemeColor    public var groundMuted: ThemeColor    public var groundElevated: ThemeColor    public var ink: ThemeColor    public var inkBody: ThemeColor    public var inkSecondary: ThemeColor    public var inkTertiary: ThemeColor    public var hairline: ThemeColor    public var accent: ThemeColor    public var accentContrast: ThemeColor    public var chipGround: ThemeColor    public var highlight: ThemeColor    public var selection: ThemeColor    public var success: ThemeColor    public var successLight: ThemeColor    public var error: ThemeColor    public var errorLight: ThemeColor    public var warning: ThemeColor    public var warningLight: ThemeColor    /// The ink typed on an object — the ribbon on paper.    public var print: ThemeColor    /// How much of `print` the pencil is: annotation, dates, counts.    public var pencil: Double    /// A card's own ground — what a sheet is filled with in a family that    /// draws its cards flat. Paper's sheets are photographs and ignore it.    public var paper: ThemeColor    /// The colour a shadow is cast in.    public var shadow: ThemeColor    /// Each paper's measured colour, as the theme row says it; a dye it    /// does not name is `PaperDye`'s own measurement.    public var dyes: [PaperDye: ThemeColor] = [:]    /// The paper a card is tinted to by its pace band (`late`, `soon`,    /// `upcoming`, `someday`, `done`), as the theme row says it.    public var paces: [String: ThemeColor] = [:]    /// The thin rule printed on a card, by its pace band.    public var paceRules: [String: ThemeColor] = [:]    /// The deck faces' stocks and inks (`palette.faces`: cream, buff,    /// shadow, slip, mount, ornament, ruling, margin, initials); an ink's    /// strength is its alpha.    public var faces: [String: ThemeColor] = [:]    /// A tag: its solid fill and the ink set on it, in a family whose tags    /// are solid. Paper's tags are slips of straw paper and ignore it.    public var tags: ThemeTags    public init(        ground: ThemeColor, groundMuted: ThemeColor, groundElevated: ThemeColor,        ink: ThemeColor, inkBody: ThemeColor, inkSecondary: ThemeColor, inkTertiary: ThemeColor,        hairline: ThemeColor, accent: ThemeColor, accentContrast: ThemeColor,        chipGround: ThemeColor, highlight: ThemeColor, selection: ThemeColor,        success: ThemeColor, successLight: ThemeColor, error: ThemeColor, errorLight: ThemeColor,        warning: ThemeColor, warningLight: ThemeColor,        print: ThemeColor, pencil: Double, paper: ThemeColor, shadow: ThemeColor, tags: ThemeTags    ) {        self.ground = ground        self.groundMuted = groundMuted        self.groundElevated = groundElevated        self.ink = ink        self.inkBody = inkBody        self.inkSecondary = inkSecondary        self.inkTertiary = inkTertiary        self.hairline = hairline        self.accent = accent        self.accentContrast = accentContrast        self.chipGround = chipGround        self.highlight = highlight        self.selection = selection        self.success = success        self.successLight = successLight        self.error = error        self.errorLight = errorLight        self.warning = warning        self.warningLight = warningLight        self.print = print        self.pencil = pencil        self.paper = paper        self.shadow = shadow        self.tags = tags    }    /// A text ink by name — `TextInk`'s levels.    public func color(_ ink: TextInk) -> Color {        switch ink {        case .ground: return ground.color        case .ink: return self.ink.color        case .body: return inkBody.color        case .secondary: return inkSecondary.color        case .tertiary: return inkTertiary.color        case .accent: return accent.color        case .inverse: return accentContrast.color        case .error: return error.color        }    }    /// A palette slot by name — the page ground a screen asks for. The Mac    /// sidebar's slots are window chrome beside every theme and keep the    /// generated palette's.    public func color(_ slot: ColorSlot) -> Color {        switch slot {        case .ground: return ground.color        case .groundMuted: return groundMuted.color        case .groundElevated: return groundElevated.color        case .ink: return ink.color        case .inkBody: return inkBody.color        case .inkSecondary: return inkSecondary.color        case .inkTertiary: return inkTertiary.color        case .hairline: return hairline.color        case .accent: return accent.color        case .accentContrast: return accentContrast.color        case .chipGround: return chipGround.color        case .highlight: return highlight.color        case .selection: return selection.color        case .statusSuccess: return success.color        case .statusSuccessLight: return successLight.color        case .statusError: return error.color        case .statusErrorLight: return errorLight.color        case .statusWarning: return warning.color        case .statusWarningLight: return warningLight.color        case .sidebarGround, .sidebarInk, .sidebarInkMuted, .sidebarSelection, .sidebarHairline:            return slot.color        }    }    /// A print ink by name — `PaperInk`'s four.    public func color(_ ink: PaperInk) -> Color {        switch ink {        case .ink: return print.color        case .pencil: return print.color.opacity(pencil)        case .red: return error.color        case .green: return success.color        }    }}/// A solid tag.public struct ThemeTags: Equatable, Sendable {    public var fill: ThemeColor    public var ink: ThemeColor    public init(fill: ThemeColor, ink: ThemeColor) {        self.fill = fill        self.ink = ink    }}// MARK: - Type/// The type roles, each mapped to a face that ships in the binary.////// `title` is an object's own name and `display` a page's; `body` is a/// record's content and `meta` its detail line; `hand` is annotation; `figure`/// is a number that stands alone; `cap` is the lettering on a bottle cap;/// `interface` is a control's label and a glyph's size. A theme picks among/// shipped faces — it never names a font file.public struct ThemeType: Equatable, Sendable {    public var display: ThemeFace    public var title: ThemeFace    public var body: ThemeFace    public var meta: ThemeFace    public var hand: ThemeFace    public var figure: ThemeFace    public var cap: ThemeFace    public var interface: ThemeFace    /// A screenplay's page. Courier in every family: the format's page count    /// is a page a minute only at Courier's pitch, so it is structure, not    /// skin — but it is still named here, with every other face.    public var script: ThemeFace    public init(        display: ThemeFace, title: ThemeFace, body: ThemeFace, meta: ThemeFace,        hand: ThemeFace, figure: ThemeFace, cap: ThemeFace, interface: ThemeFace,        script: ThemeFace    ) {        self.display = display        self.title = title        self.body = body        self.meta = meta        self.hand = hand        self.figure = figure        self.cap = cap        self.interface = interface        self.script = script    }    /// A page's title.    public func display(_ size: CGFloat) -> Font { display.font(size) }    /// An object's own name.    public func title(_ size: CGFloat) -> Font { title.font(size) }    /// A record's content.    public func body(_ size: CGFloat) -> Font { body.font(size) }    /// A detail line.    public func meta(_ size: CGFloat) -> Font { meta.font(size) }    /// Annotation.    public func hand(_ size: CGFloat) -> Font { hand.font(size) }    /// A number standing alone.    public func figure(_ size: CGFloat) -> Font { figure.font(size) }    /// The lettering on a cap.    public func cap(_ size: CGFloat) -> Font { cap.font(size) }    /// A screenplay's page.    public func script(_ size: CGFloat) -> Font { script.font(size) }    /// A control's label, a glyph's size — at a weight and design the control    /// decides.    public func interface(        _ size: CGFloat, weight: Font.Weight? = nil, design: Font.Design? = nil    ) -> Font {        interface.font(size, weight: weight, design: design)    }}/// The faces that ship: the paper set's bundled faces and the system's. The/// raw value is the row's spelling.public enum ThemeFace: String, CaseIterable, Sendable {    /// Fraunces at its title optical size, semibold — a page's title.    case frauncesTitle = "fraunces_title"    /// Fraunces at its text optical size — a name on paper.    case frauncesText = "fraunces_text"    /// Courier Prime — the typewriter.    case courier    /// Courier Prime italic.    case courierItalic = "courier_italic"    /// Caveat — the hand.    case caveat    /// Instrument Serif italic — a cap's lettering.    case instrumentItalic = "instrument_italic"    /// Courier New, the system's — a screenplay's page.    case courierNew = "courier_new"    /// The system face.    case system    /// The system face, semibold.    case systemSemibold = "system_semibold"    /// The system face, medium.    case systemMedium = "system_medium"    /// The system face, italic.    case systemItalic = "system_italic"    /// The system's monospaced figures.    case systemMonospaced = "system_monospaced"    /// Montserrat — a business flavour's reading face, worn only where its    /// look names it (`FlavourLook`). The core's theme rows do not carry it    /// yet (`THEME_FACES`), so only a look does.    case montserrat    /// Montserrat semibold — the same flavour's headings.    case montserratSemibold = "montserrat_semibold"    /// Barlow Condensed SemiBold — a letterboard tile's capitals, worn only    /// where a tool's fan tile says `letterboard` (`PaintedTile`).    case letterboard    /// The face at `size` points, fixed: print on an object scales with the    /// object, never with Dynamic Type (`Fonts.swift`).    public func font(_ size: CGFloat, weight: Font.Weight? = nil, design: Font.Design? = nil) -> Font {        switch self {        case .frauncesTitle: return CottonFonts.display(size)        case .frauncesText: return CottonFonts.serif(size)        case .courier: return CottonFonts.type(size)        case .courierItalic: return CottonFonts.typeItalic(size)        case .caveat: return CottonFonts.hand(size)        case .instrumentItalic: return CottonFonts.cap(size)        case .courierNew: return .custom("Courier New", size: size)        case .system: return Self.system(size, weight: weight, design: design)        case .systemSemibold: return Self.system(size, weight: weight ?? .semibold, design: design)        case .systemMedium: return Self.system(size, weight: weight ?? .medium, design: design)        case .systemItalic: return Self.system(size, weight: weight, design: design).italic()        case .systemMonospaced: return Self.system(size, weight: weight, design: design).monospacedDigit()        case .montserrat: return CottonFonts.brand(CottonFonts.brandRegularFace, size, fallback: .regular)        case .montserratSemibold: return CottonFonts.brand(CottonFonts.brandHeadingFace, size, fallback: .semibold)        case .letterboard: return CottonFonts.letterboard(size)        }    }    /// `Font.system` with the two optional knobs left to the system when    /// nobody named them, never below a point (`CottonFonts.drawable`) — `.system(size:)` and `.system(size:weight:)` are    /// different calls, and a call site's font must be the one it wrote.    private static func system(_ points: CGFloat, weight: Font.Weight?, design: Font.Design?) -> Font {        let size = CottonFonts.drawable(points)        switch (weight, design) {        case (nil, nil): return .system(size: size)        case (let weight?, nil): return .system(size: size, weight: weight)        case (nil, let design?): return .system(size: size, design: design)        case (let weight?, let design?): return .system(size: size, weight: weight, design: design)        }    }    /// The face CoreText measures by (`InkFit`): the bundled file's    /// PostScript name, or nil for the system's own.    public var postScriptName: String? {        switch self {        case .frauncesTitle: return CottonFonts.displayFace        case .frauncesText: return CottonFonts.textFace        case .courier: return CottonFonts.typeFace        case .courierItalic: return CottonFonts.typeItalicFace        case .caveat: return CottonFonts.handFace        case .instrumentItalic: return CottonFonts.capFace        case .courierNew: return "CourierNewPSMT"        case .montserrat: return CottonFonts.brandRegularFace        case .montserratSemibold: return CottonFonts.brandHeadingFace        case .letterboard: return CottonFonts.letterboardFace        case .system, .systemSemibold, .systemMedium, .systemItalic, .systemMonospaced: return nil        }    }    /// The face as CoreText measures it (`InkFit`) at `size`: the bundled    /// file, registered first, or the system's UI face.    public func measuring(_ size: CGFloat) -> CTFont {        CottonFonts.register()        let size = CottonFonts.drawable(size)        guard let name = postScriptName else {            return CTFontCreateUIFontForLanguage(.system, size, nil) ?? CTFontCreateWithName("Helvetica" as CFString, size, nil)        }        return CTFontCreateWithName(name as CFString, size, nil)    }    /// Whether the face is one of the system's, which grows and shrinks with    /// nothing bundled.    public var isSystem: Bool {        switch self {        case .system, .systemSemibold, .systemMedium, .systemItalic, .systemMonospaced: return true        default: return false        }    }}// MARK: - Scale/// Corner, spacing and stroke.////// The paper family's corner and inset are fractions of the object, clamped/// (`PaperMetrics`' design principle: lettering geometry as fractions of the/// object's own size); a flat family reads `radius` and `spacing` straight.public struct ThemeScale: Hashable, Sendable {    /// The largest corner an object wears.    public var radius: CGFloat    /// The smallest corner a paper object wears.    public var radiusMin: CGFloat    /// A paper object's corner as a fraction of its shorter side.    public var radiusFraction: CGFloat    /// The gap between two objects.    public var spacing: CGFloat    /// How far content sits inside an object's edge, as a fraction of its    /// width, and the clamp on it.    public var insetFraction: CGFloat    public var insetMin: CGFloat    public var insetMax: CGFloat    /// A drawn line — a ring, a border.    public var stroke: CGFloat    /// The thinnest rule.    public var hairline: CGFloat    /// A page's chrome: the nav circles and the air around them.    public var navCircle: CGFloat    public var navRowTop: CGFloat    public var navRowAir: CGFloat    /// The type sizes a print voice falls back to when a caller names none.    public var titleSize: CGFloat    public var bodySize: CGFloat    public var metaSize: CGFloat    public var handSize: CGFloat    public var sectionTitleSize: CGFloat    public var screenTitleSize: CGFloat    /// Every knob the row carries, by its row spelling — the named ones above    /// and the rest, read through `self[key]`.    public var values: [String: CGFloat] = [:]    /// A knob the theme carries. A key the row leaves out is the shipped    /// theme's (the core resolves a person's theme over it before it is read,    /// so this is the shipped theme answering for an older core).    public subscript(key: Key) -> CGFloat {        values[key.rawValue] ?? Theme.paper.scale.values[key.rawValue] ?? 0    }    /// A knob that counts something — columns, lines, people.    public func count(_ key: Key) -> Int { Int(self[key].rounded()) }    public init(        radius: CGFloat, radiusMin: CGFloat, radiusFraction: CGFloat,        spacing: CGFloat, insetFraction: CGFloat, insetMin: CGFloat, insetMax: CGFloat,        stroke: CGFloat, hairline: CGFloat,        navCircle: CGFloat, navRowTop: CGFloat, navRowAir: CGFloat,        titleSize: CGFloat, bodySize: CGFloat, metaSize: CGFloat, handSize: CGFloat,        sectionTitleSize: CGFloat, screenTitleSize: CGFloat    ) {        self.radius = radius        self.radiusMin = radiusMin        self.radiusFraction = radiusFraction        self.spacing = spacing        self.insetFraction = insetFraction        self.insetMin = insetMin        self.insetMax = insetMax        self.stroke = stroke        self.hairline = hairline        self.navCircle = navCircle        self.navRowTop = navRowTop        self.navRowAir = navRowAir        self.titleSize = titleSize        self.bodySize = bodySize        self.metaSize = metaSize        self.handSize = handSize        self.sectionTitleSize = sectionTitleSize        self.screenTitleSize = screenTitleSize    }    /// The corner for an object of `size`.    public func radius(for size: CGSize) -> CGFloat {        let shorter = min(size.width, size.height)        return min(radius, max(radiusMin, shorter * radiusFraction))    }    /// The inset for an object `width` points wide.    public func inset(forWidth width: CGFloat) -> CGFloat {        min(insetMax, max(insetMin, width * insetFraction))    }    /// The page's top on a screen with no circles.    public func barePageClearance(topInset: CGFloat) -> CGFloat {        topInset + self[.pageHeadGap]    }}// MARK: - Texture/// The material: whether the fibre shows, whether an object is lifted off the/// ground, whether it lies a hair askew.public struct ThemeTexture: Hashable, Sendable {    public var grain: Bool    public var shadow: ThemeShadow    /// Whether a sheet is tilted by its seed (`PaperMetrics.tilt`).    public var tilt: Bool    public init(grain: Bool, shadow: ThemeShadow, tilt: Bool) {        self.grain = grain        self.shadow = shadow        self.tilt = tilt    }}public enum ThemeShadow: String, CaseIterable, Sendable {    /// The two-layer contact shadow, thrown down and right.    case soft    /// Nothing cast.    case none}// MARK: - Cap/// The bottle cap's appearance — the database's own cap on Home and in the/// switcher.public struct ThemeCap: Equatable, Sendable {    /// The enamel; nil is the one the database's name hashes to.    public var colour: CapColour?    public var texture: ThemeCapTexture    public init(colour: CapColour?, texture: ThemeCapTexture) {        self.colour = colour        self.texture = texture    }}public enum ThemeCapTexture: String, CaseIterable, Sendable {    /// The photographed enamel cap.    case enamel    /// A flat disc in the enamel's colour.    case flat}// MARK: - The environmentprivate struct ThemeKey: EnvironmentKey {    static let defaultValue = Theme.paper}extension EnvironmentValues {    /// The look every face below is drawn in. Unset, it is `Theme.paper` —    /// Cotton's own — which is what a preview and a test draw.    public var theme: Theme {        get { self[ThemeKey.self] }        set { self[ThemeKey.self] = newValue }    }}extension View {    /// Draw everything below in `theme`, in the appearance the colour scheme    /// asks for.    public func themed(_ theme: Theme) -> some View {        modifier(ThemeRoot(theme: theme))    }}/// Sets the theme with its appearance read off the colour scheme, once, at/// the root — the one place a scheme is asked.private struct ThemeRoot: ViewModifier {    let theme: Theme    @Environment(\.colorScheme) private var scheme    func body(content: Content) -> some View {        var drawn = theme        drawn.appearance = scheme        return content.environment(\.theme, drawn)    }}