Cotton code
257 lines · 12.2 KB · SwiftRaw
// A theme as a database stores it: a definition-kind row that names a family// and overrides any of its knobs. The row form, in the definitions' own// snake_case:////   {//     "id": "default", "name": "Cotton", "family": "paper",//     "palette": { "light": { "accent": "#C6534B", "ink_body": "#444444",//                             "pencil": 0.55, "tags": { "fill": "#…", "ink": "#…" } },//                  "dark": { … } },//     "type": { "title": "fraunces_text", "body": "courier", … },//     "scale": { "tokens": { "radius": 8, "spacing": 12, "stroke": 1, … } },//     "texture": { "grain": true, "shadow": "soft", "tilt": true },//     "cap": { "colour": "navy", "texture": "enamel" }//   }//// DECODED TOLERANTLY, AND THAT IS THE DESIGN (note 26203e21, section 8): a key// this build does not know is ignored, a value it cannot read keeps the// family's own, and a family it does not ship draws `paper`. A theme written// by a newer build is then drawn by an older phone with the keys it knows —// never a blank screen and never a refusal. Every key is optional: a row of// `{ "family": "plain" }` is the plain family's own theme, and the seeded// default row is Cotton as it draws today.import Foundationextension Theme {    /// The theme a row describes, over its family's own. Data that is not a    /// JSON object is the default theme.    public static func decode(_ data: Data) -> Theme {        guard let row = try? JSONDecoder().decode(ThemeRowForm.self, from: data) else { return .paper }        return row.theme    }    /// The theme a row describes over its family's shipped row as `shipped`    /// hands it — the same layering as `decode`, with the shipped rows named    /// rather than read from this process's catalogue. Nil for data that is    /// not a row.    static func decode(_ data: Data, shipped: (ThemeFamily) -> Data?) -> Theme? {        guard let row = try? JSONDecoder().decode(ThemeRowForm.self, from: data) else { return nil }        return row.theme(over: Theme.shipped(row.drawnFamily, row: shipped(row.drawnFamily)))    }}/// The row as it is written: every key optional, and every value this build/// cannot read decoded as absent rather than as a refusal.typealias ThemeRowForm = DefinitionThemeDefinitionextension DefinitionThemeDefinition {    typealias Key = CodingKeys    typealias Palettes = DefinitionThemePalettes    typealias Texture = DefinitionThemeTexture    typealias Cap = DefinitionThemeCap    typealias Palette = ThemePaletteProjection    /// The theme: the family's own, each key the row names laid over it.    var theme: Theme { theme(over: Theme.standard(drawnFamily)) }    /// The family the row is drawn in: one this build does not ship is `paper`.    var drawnFamily: ThemeFamily { family.flatMap(ThemeFamily.init(rawValue:)) ?? .paper }    /// The row laid over `base`: each key it names, each one it leaves out the base's.    func theme(over base: Theme) -> Theme {        var theme = base        if let id, !id.isEmpty { theme.id = id }        if let name, !name.isEmpty { theme.name = name }        if let palette {            let light = palette.light.map { theme.palette.light.overridden(by: Palette($0)) } ?? theme.palette.light            // A row with no dark of its own is light-only, as Cotton is.            let dark = palette.dark.map { theme.palette.dark.overridden(by: Palette($0)) } ?? light            theme.palette = ThemePalettes(light: light, dark: dark)        }        if let type { theme.type = theme.type.overridden(by: type.compactMapValues(\.string)) }        if let tokens = scale?.tokens { theme.scale = theme.scale.overridden(by: tokens.compactMapValues(\.number)) }        if let texture { theme.texture = theme.texture.overridden(by: texture) }        if let cap { theme.cap = theme.cap.overridden(by: cap) }        if let acts { theme.acts = theme.acts.overridden(by: acts.compactMapValues { $0.object?.compactMapValues(\.string) }) }        if let cards { theme.cards = theme.cards.overridden(by: cards.compactMapValues { value in            guard let data = try? JSONEncoder().encode(value) else { return nil }            return try? JSONDecoder().decode(ThemeValue.self, from: data)        }) }        if let objects { theme.cards.objects.merge(objects.compactMapValues(\.string)) { _, row in row } }        return theme    }}extension DefinitionThemePalettes { typealias Key = CodingKeys }extension DefinitionThemeTexture { typealias Key = CodingKeys }extension DefinitionThemeCap { typealias Key = CodingKeys }struct ThemePaletteProjection {    let row: [String: DefinitionJSONValue]    init(_ row: [String: DefinitionJSONValue]) { self.row = row }    var colours: [String: String] { row.compactMapValues(\.string) }    var pencil: Double? { row["pencil"]?.number }    var tags: [String: String]? { row["tags"]?.object?.compactMapValues(\.string) }    var dyes: [String: String]? { row["dyes"]?.object?.compactMapValues(\.string) }    var paces: [String: String]? { row["paces"]?.object?.compactMapValues(\.string) }    var paceRules: [String: String]? { row["pace_rules"]?.object?.compactMapValues(\.string) }    var faces: [String: String]? { row["faces"]?.object?.compactMapValues(\.string) }    enum Key: String { case pencil, tags, dyes, paces, pace_rules, faces }}private extension DefinitionJSONValue {    var string: String? { if case .string(let word) = self { return word }; return nil }    var number: Double? {        switch self {        case .number(let value): return value        case .integer(let value): return Double(value)        case .unsigned(let value): return Double(value)        default: return nil        }    }    var object: [String: DefinitionJSONValue]? { if case .object(let fields) = self { return fields }; return nil }}/// A JSON number — and only a number: a `true` is not 1, and a string of/// digits is not a size.struct ThemeNumber: Decodable {    let value: Double    init(from decoder: Decoder) throws {        let container = try decoder.singleValueContainer()        if (try? container.decode(Bool.self)) != nil {            throw DecodingError.typeMismatch(Double.self, .init(codingPath: decoder.codingPath, debugDescription: "a flag is not a number"))        }        let read = try container.decode(Double.self)        guard read.isFinite else {            throw DecodingError.dataCorruptedError(in: container, debugDescription: "not a finite number")        }        value = read    }}extension ThemePalette {    /// The palette's role names, as a row spells them.    static var roles: [(name: String, path: WritableKeyPath<ThemePalette, ThemeColor>)] {        [            ("ground", \.ground), ("ground_muted", \.groundMuted), ("ground_elevated", \.groundElevated),            ("ink", \.ink), ("ink_body", \.inkBody), ("ink_secondary", \.inkSecondary), ("ink_tertiary", \.inkTertiary),            ("hairline", \.hairline), ("accent", \.accent), ("accent_contrast", \.accentContrast),            ("chip_ground", \.chipGround), ("highlight", \.highlight), ("selection", \.selection),            ("success", \.success), ("success_light", \.successLight), ("error", \.error), ("error_light", \.errorLight),            ("warning", \.warning), ("warning_light", \.warningLight),            ("print", \.print), ("paper", \.paper), ("shadow", \.shadow),        ]    }    /// The row's colours, each over this palette's own.    func overridden(by row: ThemeRowForm.Palette) -> ThemePalette {        var palette = self        for role in Self.roles {            if let read = row.colours[role.name].flatMap(ThemeColor.init(palette:)) { palette[keyPath: role.path] = read }        }        if let pencil = row.pencil, (0...1).contains(pencil) { palette.pencil = pencil }        if let tags = row.tags {            if let fill = tags[ThemeTagKey.fill.rawValue].flatMap(ThemeColor.init(palette:)) { palette.tags.fill = fill }            if let ink = tags[ThemeTagKey.ink.rawValue].flatMap(ThemeColor.init(palette:)) { palette.tags.ink = ink }        }        for (dye, hex) in row.dyes ?? [:] {            if let dye = PaperDye(rawValue: dye), let colour = ThemeColor(palette: hex) { palette.dyes[dye] = colour }        }        for (pace, hex) in row.paces ?? [:] {            if let colour = ThemeColor(palette: hex) { palette.paces[pace] = colour }        }        for (pace, hex) in row.paceRules ?? [:] {            if let colour = ThemeColor(palette: hex) { palette.paceRules[pace] = colour }        }        for (ink, hex) in row.faces ?? [:] {            if let colour = ThemeColor(palette: hex) { palette.faces[ink] = colour }        }        return palette    }}/// A tag's two keys.enum ThemeTagKey: String { case fill, ink }extension ThemeType {    /// The type roles, as a row spells them.    static var roles: [(name: String, path: WritableKeyPath<ThemeType, ThemeFace>)] {        [            ("display", \.display), ("title", \.title), ("body", \.body), ("meta", \.meta), ("hand", \.hand),            ("figure", \.figure), ("cap", \.cap), ("interface", \.interface), ("script", \.script),        ]    }    func overridden(by row: [String: String]) -> ThemeType {        var type = self        for role in Self.roles {            if let face = row[role.name].flatMap(ThemeFace.init(rawValue:)) { type[keyPath: role.path] = face }        }        return type    }}extension ThemeScale {    /// The finer knobs, as a row spells them.    static var knobs: [(name: String, path: WritableKeyPath<ThemeScale, CGFloat>)] {        [            ("radius_min", \.radiusMin), ("radius_fraction", \.radiusFraction), ("spacing", \.spacing),            ("inset_fraction", \.insetFraction), ("inset_min", \.insetMin), ("inset_max", \.insetMax),            ("stroke", \.stroke), ("hairline", \.hairline), ("title_size", \.titleSize), ("body_size", \.bodySize),            ("meta_size", \.metaSize), ("hand_size", \.handSize), ("section_title_size", \.sectionTitleSize),            ("screen_title_size", \.screenTitleSize), ("nav_circle", \.navCircle), ("nav_row_top", \.navRowTop),            ("nav_row_air", \.navRowAir),        ]    }    /// A row's `radius` sets the largest corner and scales the smallest with    /// it, so a paper theme keeps its corner's proportion; `spacing` is the    /// gap between objects; `stroke` a drawn line. The finer knobs are read    /// too, for a row that wants them. A negative or absurd number is not a    /// size and keeps the family's.    func overridden(by row: [String: Double]) -> ThemeScale {        var scale = self        func usable(_ value: Double?) -> CGFloat? {            guard let value, value >= 0, value < 1000 else { return nil }            return CGFloat(value)        }        if let radius = usable(row[ThemeScaleKey.radius.rawValue]) {            let proportion = self.radius > 0 ? self.radiusMin / self.radius : 1            scale.radius = radius            scale.radiusMin = radius * proportion        }        for knob in Self.knobs {            if let read = usable(row[knob.name]) { scale[keyPath: knob.path] = read }        }        // Every knob, the named ones too, by its spelling. A knob may be a        // negative offset or an angle, so only a non-finite or absurd number        // is passed over here.        for (name, value) in row where value.isFinite && abs(value) < 100_000 {            scale.values[name] = CGFloat(value)        }        return scale    }}/// The scale's one object (`tokens`), and the one token that moves two knobs.enum ThemeScaleKey: String { case tokens, radius }extension ThemeTexture {    func overridden(by row: ThemeRowForm.Texture) -> ThemeTexture {        var texture = self        if let grain = row.grain { texture.grain = grain }        if let shadow = row.shadow.flatMap(ThemeShadow.init(rawValue:)) { texture.shadow = shadow }        if let tilt = row.tilt { texture.tilt = tilt }        return texture    }}extension ThemeCap {    func overridden(by row: ThemeRowForm.Cap) -> ThemeCap {        var cap = self        if let colour = row.colour.flatMap(CapColour.init(rawValue:)) { cap.colour = colour }        if let texture = row.texture.flatMap(ThemeCapTexture.init(rawValue:)) { cap.texture = texture }        return cap    }}