Cotton code
250 lines · 10.7 KB · SwiftRaw
// A project's brand kit, applied to a database's theme in one act (design// note 26203e21, section 6, last line).//// The kit is the project's own record — named colours and role-tagged font// families, as `update_project` writes them. The act lays the kit over the// database's current theme and writes the result as the database's theme// row; nothing else about the theme moves, so a brand on `plain` stays// plain and a brand on `paper` keeps its photographs.//// COLOURS ARE MATCHED BY THEIR NAMES, because a kit's colours are a list a// person named ("Accent red", "Ink", "Paper") and not a set of slots. A word// in the name picks the role; a name with no role word is left alone; and a// kit that names no role at all lends its FIRST colour to the accent, since a// brand's first colour is the one it leads with. The colour rule still binds// the result: one accent, ink and grounds, state in the status colours.//// FONTS ARE MAPPED TO A SHIPPED FACE, because a theme never names a font// file. A family the binary carries is that face; any other is the system// face of its kind (monospaced for a mono, semibold for a display), which is// the nearest a build can draw without shipping the file.//// THE ACCENT IS ALSO THE DATABASE'S CAP AND ITS TAGS, because that is where a// database shows its colour: the cap wears the enamel nearest the accent (a// cap is one of twelve photographed enamels, never a dyed hex), and a family// whose tags are solid fills them with the accent itself, inked to read on it.//// THE KIT ARRIVES AS PLAIN VALUES (`ThemeBrandKit`), never as the record it// was read from: the look calls no core and reads no wire value, so the app// reads the kit off the project's record (`ThemeModel.wear(brand:)`) and hands// the look only what it lays down.import Foundation/// A project's brand kit, as the look reads it: its named colours and its/// role-tagged font families, in the kit's order and in the record's own/// spelling (`{"colors": [{"name", "hex"}], "fonts": [{"role", "family"}]}`)./// A key the record leaves out is nil; what a nil means is the look's rule/// (`Theme.applying(brand:)`), not the reader's.public struct ThemeBrandKit: Codable, Equatable, Sendable {    public struct Colour: Codable, Equatable, Sendable {        public var name: String?        public var hex: String?        public init(name: String?, hex: String?) {            self.name = name            self.hex = hex        }    }    public struct Font: Codable, Equatable, Sendable {        public var role: String?        public var family: String?        public init(role: String?, family: String?) {            self.role = role            self.family = family        }    }    public var colors: [Colour]    public var fonts: [Font]    public init(colors: [Colour] = [], fonts: [Font] = []) {        self.colors = colors        self.fonts = fonts    }}extension Theme {    /// This theme with `brand` laid over it: its named colours on the    /// palette's roles, its fonts on the type roles.    public func applying(brand: ThemeBrandKit) -> Theme {        var theme = self        let colours = brand.colors.compactMap { entry -> (name: String, colour: ThemeColor)? in            guard let hex = entry.hex, let colour = ThemeColor(hex: hex) else { return nil }            return ((entry.name ?? "").lowercased(), colour)        }        var light = theme.palette.light        var matched = false        for (name, colour) in colours {            for role in ThemeBrandRole.allCases where role.matches(name) {                role.apply(colour, to: &light)                matched = true                break            }        }        if !matched, let first = colours.first {            light.accent = first.colour        }        // A palette that was light-only stays light-only.        var dark = theme.palette.dark == theme.palette.light ? light : theme.palette.dark        if light.accent != palette.light.accent {            let tags = ThemeTags(fill: light.accent, ink: Self.ink(on: light.accent, palette: light))            light.tags = tags            dark.tags = tags            theme.cap.colour = CapColour.nearest(to: light.accent)        }        theme.palette = ThemePalettes(light: light, dark: dark)        for font in brand.fonts {            guard let family = font.family, !family.isEmpty else { continue }            ThemeBrandFont(role: font.role ?? "body", family: family).apply(to: &theme.type)        }        return theme    }    /// The palette's ink on a light fill, its card on a dark one.    static func ink(on fill: ThemeColor, palette: ThemePalette) -> ThemeColor {        let luminance = 0.2126 * fill.red + 0.7152 * fill.green + 0.0722 * fill.blue        return luminance > 0.55 ? palette.ink : palette.paper    }}/// The palette roles a kit's colour can be named for, in the order a name is/// tried — the more specific word first, so "Ink (typewriter ribbon)" is the/// ribbon and "Plaster ground" is the muted ground.enum ThemeBrandRole: CaseIterable {    case print, accent, highlight, mutedGround, paper, ground, ink    private var words: [String] {        switch self {        case .print: return ["ribbon", "typewriter", "print"]        case .accent: return ["accent", "primary", "brand"]        case .highlight: return ["highlight"]        case .mutedGround: return ["plaster", "muted", "surface"]        case .paper: return ["paper", "card", "sheet"]        case .ground: return ["ground", "background"]        case .ink: return ["ink", "text", "foreground"]        }    }    func matches(_ name: String) -> Bool {        let tokens = Set(name.split { !$0.isLetter }.map(String.init))        return words.contains { tokens.contains($0) }    }    func apply(_ colour: ThemeColor, to palette: inout ThemePalette) {        switch self {        case .print: palette.print = colour        case .accent: palette.accent = colour        case .highlight: palette.highlight = colour        case .mutedGround: palette.groundMuted = colour        case .paper: palette.paper = colour        case .ground: palette.ground = colour        case .ink:            palette.ink = colour            palette.inkBody = colour        }    }}/// One of a kit's fonts, on the type roles it fills.struct ThemeBrandFont {    let role: String    let family: String    /// The shipped face a family is, or nil for one the binary does not carry.    var shipped: ThemeFace? {        let name = family.lowercased()        if name.contains("caveat") { return .caveat }        if name.contains("instrument") { return .instrumentItalic }        if name.contains("courier prime") { return name.contains("italic") ? .courierItalic : .courier }        if name.contains("courier") { return .courierNew }        if name.contains("fraunces") { return name.contains("text") ? .frauncesText : .frauncesTitle }        return nil    }    func apply(to type: inout ThemeType) {        // The hand and the cap's lettering are faces of their own, whatever        // role the kit filed them under.        switch shipped {        case .caveat?:            type.hand = .caveat            return        case .instrumentItalic?:            type.cap = .instrumentItalic            return        default:            break        }        switch role {        case "display":            type.display = shipped ?? .systemSemibold            type.title = shipped.map { $0 == .frauncesTitle ? .frauncesText : $0 } ?? .systemSemibold        case "mono":            let face = shipped ?? .systemMonospaced            type.figure = face        default:            let face = shipped ?? .system            type.body = face            type.meta = face == .courier ? .courierItalic : (face == .system ? .system : face)        }    }}extension Theme {    /// The theme as its row: every key written, so the row stands alone and a    /// later build's default cannot change a theme someone chose. Colours are    /// written as `#RRGGBBAA`.    public var row: Data {        func hex(_ colour: ThemeColor) -> String { colour.hexWithAlpha }        func palette(_ palette: ThemePalette) -> [String: Any] {            var out: [String: Any] = [:]            for role in ThemePalette.roles { out[role.name] = hex(palette[keyPath: role.path]) }            out[ThemeRowForm.Palette.Key.pencil.rawValue] = palette.pencil            out[ThemeRowForm.Palette.Key.tags.rawValue] = [                ThemeTagKey.fill.rawValue: hex(palette.tags.fill), ThemeTagKey.ink.rawValue: hex(palette.tags.ink),            ]            return out        }        var type: [String: Any] = [:]        for role in ThemeType.roles { type[role.name] = self.type[keyPath: role.path].rawValue }        var tokens: [String: Any] = self.scale.values.mapValues { Double($0) }        tokens[ThemeScaleKey.radius.rawValue] = Double(self.scale.radius)        for knob in ThemeScale.knobs { tokens[knob.name] = Double(self.scale[keyPath: knob.path]) }        let scale: [String: Any] = [ThemeScaleKey.tokens.rawValue: tokens]        var cap: [String: Any] = [ThemeRowForm.Cap.Key.texture.rawValue: self.cap.texture.rawValue]        if let colour = self.cap.colour { cap[ThemeRowForm.Cap.Key.colour.rawValue] = colour.rawValue }        let row: [String: Any] = [            ThemeRowForm.Key.id.rawValue: id,            ThemeRowForm.Key.name.rawValue: name,            ThemeRowForm.Key.family.rawValue: family.rawValue,            ThemeRowForm.Key.palette.rawValue: [                ThemeRowForm.Palettes.Key.light.rawValue: palette(self.palette.light),                ThemeRowForm.Palettes.Key.dark.rawValue: palette(self.palette.dark),            ],            ThemeRowForm.Key.type.rawValue: type,            ThemeRowForm.Key.scale.rawValue: scale,            ThemeRowForm.Key.texture.rawValue: [                ThemeRowForm.Texture.Key.grain.rawValue: texture.grain,                ThemeRowForm.Texture.Key.shadow.rawValue: texture.shadow.rawValue,                ThemeRowForm.Texture.Key.tilt.rawValue: texture.tilt,            ],            ThemeRowForm.Key.cap.rawValue: cap,        ]        return (try? JSONSerialization.data(withJSONObject: row, options: [.sortedKeys])) ?? Data()    }}extension ThemeColor {    /// `#RRGGBB`, and `#RRGGBBAA` for a colour that is not opaque — what a    /// person types and reads.    public var hex: String {        let full = hexWithAlpha        return alpha >= 1 ? String(full.prefix(7)) : full    }    /// `#RRGGBBAA`, every channel written — the row's spelling.    public var hexWithAlpha: String {        func byte(_ value: Double) -> String { String(format: "%02X", Int((min(1, max(0, value)) * 255).rounded())) }        return "#" + byte(red) + byte(green) + byte(blue) + byte(alpha)    }}