SPB Git

Repository Public License

ThemeSpec.swift 11.1 KB 118 lines swift

1import Foundation2import PrismCore34/// The look of an app (blueprint `theme`): a named preset and/or explicit tokens. Explicit tokens win over the preset.5///6/// ```7/// {"preset": "midnight", "accent": "#5AC8FA", "appearance": "system|light|dark", "density": "compact|regular|comfortable", "radius": 0…28,8///  "font": "default|rounded|serif|monospaced", "headingFont": …, "headingWeight": "regular|semibold|bold|heavy|black",9///  "surface": "tinted|elevated|bordered|glass|flat",10///  "palette": {"background", "surface", "text", "border", "success", "warning", "danger", "info"},11///  "backgroundGradient": ["#…", "#…"], "backgroundAngle": 135, "chartColors": ["#…", …]}12/// ```13public enum ThemeSpec {14    public static let fonts = ["default", "rounded", "serif", "monospaced"]15    public static let weights = ["regular", "semibold", "bold", "heavy", "black"]16    public static let surfaces = ["tinted", "elevated", "bordered", "glass", "flat"]17    public static let paletteKeys = ["background", "surface", "text", "border", "success", "warning", "danger", "info"]18    public static let keys: Set<String> = [19        "preset", "accent", "appearance", "density", "radius", "font", "headingFont", "headingWeight", "surface", "palette",20        "backgroundGradient", "backgroundAngle", "chartColors",21    ]2223    public static let presets: [(name: String, summary: String, theme: JSONValue)] = [24        ("midnight", "Dark navy with a cyan accent; calm dashboards and tools.",25         ["accent": "#5AC8FA", "surface": "elevated", "radius": 12, "palette": ["background": "#0B1220", "surface": "#141D31", "text": "#E8EEF9", "border": "#24304A"], "chartColors": ["#5AC8FA", "#7D7AFF", "#FF9F0A", "#30D158", "#FF6482"]]),26        ("aurora", "Dark violet-to-teal gradient with glass panels; creative and media apps.",27         ["accent": "#B18CFF", "surface": "glass", "radius": 16, "font": "rounded", "backgroundGradient": ["#1B1035", "#0E2A3B", "#0B3B3A"], "backgroundAngle": 135, "palette": ["background": "#141230", "text": "#F1ECFF", "border": "#FFFFFF2E"], "chartColors": ["#B18CFF", "#5EEAD4", "#F472B6", "#FBBF24", "#60A5FA"]]),28        ("sunrise", "Warm peach gradient, light, rounded; friendly personal apps.",29         ["accent": "#F2542D", "surface": "elevated", "radius": 18, "font": "rounded", "headingWeight": "heavy", "backgroundGradient": ["#FFF3E6", "#FFE1D0"], "backgroundAngle": 100, "palette": ["background": "#FFF3E6", "surface": "#FFFFFF", "text": "#3B1F14", "border": "#F3CDB8"], "chartColors": ["#F2542D", "#F5B700", "#0E9594", "#7B2D8E", "#127475"]]),30        ("forest", "Deep green, dark, serif headings; nature, journaling, slow tools.",31         ["accent": "#A3E635", "surface": "tinted", "radius": 10, "headingFont": "serif", "palette": ["background": "#0F1F17", "surface": "#18301F", "text": "#E7F2E4", "border": "#2B4A33"], "chartColors": ["#A3E635", "#34D399", "#FDE68A", "#FB923C", "#93C5FD"]]),32        ("paper", "Cream paper with ink text, serif, thin borders; reading, writing, records.",33         ["accent": "#8A4B2A", "surface": "bordered", "radius": 4, "font": "serif", "headingWeight": "semibold", "palette": ["background": "#FAF6EC", "surface": "#FFFDF7", "text": "#2A241B", "border": "#D9CFBB"], "chartColors": ["#8A4B2A", "#2F5D62", "#B8860B", "#5E3B76", "#6B705C"]]),34        ("terminal", "Black with phosphor green, monospaced, square corners; developer and ops tools.",35         ["accent": "#39FF14", "surface": "bordered", "radius": 2, "font": "monospaced", "density": "compact", "palette": ["background": "#050805", "surface": "#0B120B", "text": "#B7F7B0", "border": "#1F3D1F", "success": "#39FF14", "info": "#3DDBD9"], "chartColors": ["#39FF14", "#3DDBD9", "#FFD60A", "#FF6B6B", "#C792EA"]]),36        ("candy", "Pink and white, very round, playful; kids, games, fun trackers.",37         ["accent": "#FF2D92", "surface": "elevated", "radius": 22, "font": "rounded", "headingWeight": "black", "density": "comfortable", "backgroundGradient": ["#FFE5F1", "#E9E4FF"], "backgroundAngle": 120, "palette": ["background": "#FFE5F1", "surface": "#FFFFFF", "text": "#3A1030", "border": "#F9BBD8"], "chartColors": ["#FF2D92", "#7C4DFF", "#00C2FF", "#FFB300", "#00D68F"]]),38        ("ocean", "Light sea-blue gradient with glass panels and a teal accent; travel, weather, wellness.",39         ["accent": "#0A9396", "surface": "glass", "radius": 14, "backgroundGradient": ["#E3F4FB", "#C9E8F2"], "backgroundAngle": 90, "palette": ["background": "#E3F4FB", "text": "#0B2B36", "border": "#FFFFFFB0"], "chartColors": ["#0A9396", "#005F73", "#EE9B00", "#CA6702", "#94D2BD"]]),40        ("graphite", "Neutral dark gray with an orange accent; professional, data-dense.",41         ["accent": "#FF9F0A", "surface": "tinted", "radius": 8, "density": "compact", "palette": ["background": "#1C1C1E", "surface": "#2C2C2E", "text": "#F2F2F7", "border": "#3A3A3C"], "chartColors": ["#FF9F0A", "#64D2FF", "#BF5AF2", "#30D158", "#FF453A"]]),42        ("blossom", "Soft lavender, light, rounded; calm planning and habit apps.",43         ["accent": "#7B5CD6", "surface": "elevated", "radius": 14, "font": "rounded", "palette": ["background": "#F5F1FF", "surface": "#FFFFFF", "text": "#251A45", "border": "#DDD3F7"], "chartColors": ["#7B5CD6", "#E05C97", "#3BA99C", "#F2A541", "#4C8DF6"]]),44        ("mono", "Black on white, no rounding, hairline borders; editorial and minimal tools.",45         ["accent": "#111111", "surface": "bordered", "radius": 0, "headingWeight": "black", "palette": ["background": "#FFFFFF", "surface": "#FFFFFF", "text": "#111111", "border": "#111111"], "chartColors": ["#111111", "#6B6B6B", "#A3A3A3", "#D4D4D4", "#E11D48"]]),46        ("ember", "Charcoal with a red-orange accent; fitness, timers, alerts.",47         ["accent": "#FF5A1F", "surface": "elevated", "radius": 12, "headingWeight": "heavy", "palette": ["background": "#17110F", "surface": "#241A17", "text": "#FBEDE7", "border": "#3A2A25"], "chartColors": ["#FF5A1F", "#FFB703", "#FB7185", "#8ECAE6", "#A7C957"]]),48        ("mint", "Fresh mint, light, emerald accent; health, food, finance for people.",49         ["accent": "#059669", "surface": "tinted", "radius": 12, "font": "rounded", "palette": ["background": "#EFFBF5", "surface": "#DDF5E9", "text": "#0B2E22", "border": "#B9E6D2"], "chartColors": ["#059669", "#0EA5E9", "#F59E0B", "#EC4899", "#6366F1"]]),50        ("royal", "Deep purple with gold, serif headings; premium, collections, events.",51         ["accent": "#E6B450", "surface": "elevated", "radius": 10, "headingFont": "serif", "headingWeight": "bold", "backgroundGradient": ["#1A0F2E", "#2A1548"], "backgroundAngle": 160, "palette": ["background": "#1A0F2E", "surface": "#2B1B47", "text": "#F4ECFF", "border": "#47306E"], "chartColors": ["#E6B450", "#C084FC", "#F472B6", "#5EEAD4", "#93C5FD"]]),52    ]5354    public static func preset(_ name: String) -> JSONValue? { presets.first { $0.name == name }?.theme }5556    /// The preset (if any) with the explicit tokens laid over it; the palette is merged key by key.57    public static func resolved(_ theme: [String: JSONValue]) -> [String: JSONValue] {58        guard let name = theme["preset"]?.stringValue, var out = preset(name)?.objectValue else { return theme }59        for (k, v) in theme where k != "palette" { out[k] = v }60        if let extra = theme["palette"]?.objectValue {61            var palette = out["palette"]?.objectValue ?? [:]62            for (k, v) in extra { palette[k] = v }63            out["palette"] = .object(palette)64        }65        return out66    }6768    public struct Problem: Sendable, Equatable {69        public var isError: Bool70        public var message: String71    }7273    public static func problems(_ theme: [String: JSONValue]) -> [Problem] {74        var out: [Problem] = []75        func err(_ m: String) { out.append(.init(isError: true, message: m)) }76        func hex(_ v: JSONValue?, _ what: String) -> RGBA? {77            guard let v else { return nil }78            guard let c = RGBA(hex: v.stringValue ?? "") else { err("\(what) must be a hex color like #1F6FEB."); return nil }79            return c80        }81        func oneOf(_ key: String, _ allowed: [String]) {82            if let v = theme[key], v.stringValue.map(allowed.contains) != true { err("Theme `\(key)` must be one of: \(allowed.joined(separator: ", ")).") }83        }84        for k in theme.keys.sorted() where !keys.contains(k) { err("Unknown theme token `\(k)`. Known: \(keys.sorted().joined(separator: ", ")).") }85        if let p = theme["preset"], p.stringValue.flatMap(preset) == nil { err("Unknown theme preset. Known: \(presets.map(\.name).joined(separator: ", ")).") }86        oneOf("appearance", ["system", "light", "dark"]); oneOf("density", ["compact", "regular", "comfortable"])87        oneOf("font", fonts); oneOf("headingFont", fonts); oneOf("headingWeight", weights); oneOf("surface", surfaces)88        _ = hex(theme["accent"], "Theme `accent`")89        if let r = theme["radius"], r.doubleValue.map({ (0...28).contains($0) }) != true { err("Theme `radius` must be a number from 0 to 28.") }90        if let a = theme["backgroundAngle"], a.doubleValue == nil { err("Theme `backgroundAngle` must be a number of degrees.") }91        if let p = theme["palette"] {92            if let o = p.objectValue {93                for k in o.keys.sorted() {94                    if paletteKeys.contains(k) { _ = hex(o[k], "Theme palette `\(k)`") } else { err("Unknown palette color `\(k)`. Known: \(paletteKeys.joined(separator: ", ")).") }95                }96            } else { err("Theme `palette` must be an object of hex colors.") }97        }98        for (key, range) in [("backgroundGradient", 2...3), ("chartColors", 1...8)] {99            guard let v = theme[key] else { continue }100            guard let list = v.arrayValue, range.contains(list.count) else { err("Theme `\(key)` needs \(range.lowerBound) to \(range.upperBound) hex colors."); continue }101            for c in list { _ = hex(c, "Each color of `\(key)`") }102        }103        // Legibility is checked on what will actually be shown: preset plus overrides.104        let r = resolved(theme)105        let backgrounds = ([r["palette"]?["background"]] + (r["backgroundGradient"]?.arrayValue ?? [])).compactMap { $0?.stringValue }.compactMap(RGBA.init(hex:))106        if let text = (r["palette"]?["text"]?.stringValue).flatMap(RGBA.init(hex:)) {107            for b in backgrounds + [(r["palette"]?["surface"]?.stringValue).flatMap(RGBA.init(hex:))].compactMap({ $0 }) where b.a > 0.9 {108                let ratio = text.contrast(with: b)109                if ratio < 3 { err("Theme text is not readable on its background (contrast \(String(format: "%.1f", ratio)):1; at least 4.5:1 is needed).") }110                else if ratio < 4.5 { out.append(.init(isError: false, message: "Theme text has low contrast on its background (\(String(format: "%.1f", ratio)):1; 4.5:1 is recommended).")) }111            }112        } else if backgrounds.count > 1, let lo = backgrounds.map(\.luminance).min(), let hi = backgrounds.map(\.luminance).max(), lo < 0.18, hi > 0.4 {113            out.append(.init(isError: false, message: "The background gradient goes from dark to light, so no single text color is readable everywhere; keep its colors all dark or all light."))114        }115        return out116    }117}118
Files main
Menu

Theme