SPB Git

Repository Public License

Theme.swift 7.4 KB 159 lines swift

1import PrismCore2import PrismIconKit3import SwiftUI45/// Semantic design tokens (spec §8). A blueprint's `theme` (a preset and/or explicit tokens, see `ThemeSpec`) overrides the defaults.6public struct PrismTheme: Sendable, Equatable {7    public var accent: Color = .accentColor8    public var appearance: String = "system"9    public var spacing: CGFloat = 1210    public var radius: CGFloat = 1011    public var pagePadding: CGFloat = 2012    public var fontDesign: Font.Design = .default13    public var headingDesign: Font.Design? = nil14    public var headingWeight: Font.Weight = .bold15    public var surface: String = "tinted"16    /// Custom colors; nil means the system's.17    public var background: Color? = nil18    public var backgroundGradient: [Color] = []19    public var backgroundAngle: Double = 9020    public var surfaceColor: Color? = nil21    public var text: Color? = nil22    public var border: Color? = nil23    public var tones: [String: Color] = [:]24    public var chartColors: [Color] = []25    private var derivedScheme: ColorScheme? = nil2627    public init() {}2829    public init(_ raw: [String: JSONValue]) {30        let json = ThemeSpec.resolved(raw)31        func color(_ v: JSONValue?) -> Color? { (v?.stringValue).flatMap(Color.init(hex:)) }32        func design(_ v: JSONValue?) -> Font.Design? {33            switch v?.stringValue { case "rounded": .rounded; case "serif": .serif; case "monospaced": .monospaced; case "default": .default; default: nil }34        }35        if let c = color(json["accent"]) { accent = c }36        if let a = json["appearance"]?.stringValue, ["system", "light", "dark"].contains(a) { appearance = a }37        if let d = json["density"]?.stringValue {38            spacing = d == "compact" ? 8 : d == "comfortable" ? 16 : 1239            pagePadding = d == "compact" ? 12 : d == "comfortable" ? 28 : 2040        }41        if let r = json["radius"]?.doubleValue { radius = CGFloat(min(max(r, 0), 28)) }42        if let d = design(json["font"]) { fontDesign = d }43        headingDesign = design(json["headingFont"])44        switch json["headingWeight"]?.stringValue {45        case "regular": headingWeight = .regular46        case "semibold": headingWeight = .semibold47        case "heavy": headingWeight = .heavy48        case "black": headingWeight = .black49        default: headingWeight = .bold50        }51        if let s = json["surface"]?.stringValue, ThemeSpec.surfaces.contains(s) { surface = s }52        let palette = json["palette"]?.objectValue ?? [:]53        background = color(palette["background"])54        surfaceColor = color(palette["surface"])55        text = color(palette["text"])56        border = color(palette["border"])57        for tone in ["success", "warning", "danger", "info"] { if let c = color(palette[tone]) { tones[tone] = c } }58        backgroundGradient = (json["backgroundGradient"]?.arrayValue ?? []).compactMap(color)59        if let a = json["backgroundAngle"]?.doubleValue { backgroundAngle = a }60        chartColors = (json["chartColors"]?.arrayValue ?? []).compactMap(color)61        // A custom background decides light or dark, so native controls stay legible on it.62        let reference = (palette["background"]?.stringValue ?? json["backgroundGradient"]?.arrayValue?.first?.stringValue).flatMap(RGBA.init(hex:))63        if let reference {64            derivedScheme = reference.luminance < 0.28 ? .dark : .light65            if text == nil { text = derivedScheme == .dark ? Color(white: 0.95) : Color(white: 0.1) }66        }67    }6869    public var colorScheme: ColorScheme? { derivedScheme ?? (appearance == "light" ? .light : appearance == "dark" ? .dark : nil) }70    public var hasCustomBackground: Bool { background != nil || !backgroundGradient.isEmpty }7172    public func color(_ tone: String) -> Color {73        switch tone {74        case "info": tones["info"] ?? .blue75        case "success": tones["success"] ?? .green76        case "warning": tones["warning"] ?? .orange77        case "danger": tones["danger"] ?? .red78        case "accent": accent79        default: .primary80        }81    }8283    /// Tint used for filled surfaces; neutral maps to secondary rather than primary.84    public func tint(_ tone: String) -> Color { tone == "neutral" || tone.isEmpty ? .secondary : color(tone) }8586    public func headingFont(_ base: Font) -> Font { base.weight(headingWeight) }8788    public static let accentChoices: [(name: String, hex: String)] = [89        ("Blue", "#0A84FF"), ("Indigo", "#5E5CE6"), ("Purple", "#BF5AF2"), ("Pink", "#FF375F"),90        ("Orange", "#FF9F0A"), ("Green", "#30D158"), ("Teal", "#40C8E0"), ("Graphite", "#8E8E93"),91    ]92}9394extension Color {95    public init?(hex: String) {96        guard let c = RGBA(hex: hex.hasPrefix("#") ? hex : "#" + hex.trimmingCharacters(in: .whitespaces)) else { return nil }97        self.init(.sRGB, red: c.r, green: c.g, blue: c.b, opacity: c.a)98    }99}100101/// The page backdrop of a themed app.102struct ThemeBackground: View {103    let theme: PrismTheme104    var body: some View {105        if theme.backgroundGradient.count > 1 {106            let a = theme.backgroundAngle * .pi / 180107            LinearGradient(colors: theme.backgroundGradient, startPoint: UnitPoint(x: 0.5 - cos(a) / 2, y: 0.5 - sin(a) / 2), endPoint: UnitPoint(x: 0.5 + cos(a) / 2, y: 0.5 + sin(a) / 2))108        } else if let background = theme.background {109            background110        } else {111            Color.clear112        }113    }114}115116/// The panel treatment shared by cards, statistics, charts and other grouped surfaces.117struct ThemeSurface: ViewModifier {118    @Environment(\.prismTheme) private var theme119    var radius: CGFloat? = nil120121    func body(content: Content) -> some View {122        let shape = RoundedRectangle(cornerRadius: radius ?? theme.radius, style: .continuous)123        let line = theme.border ?? Color(nsColor: .separatorColor).opacity(0.6)124        switch theme.surface {125        case "elevated":126            content.background(theme.surfaceColor.map(AnyShapeStyle.init) ?? AnyShapeStyle(.background), in: shape)127                .overlay(shape.strokeBorder(line.opacity(0.5), lineWidth: 0.5))128                .shadow(color: .black.opacity(0.14), radius: 10, y: 4)129        case "bordered":130            content.background(theme.surfaceColor.map(AnyShapeStyle.init) ?? AnyShapeStyle(.clear), in: shape).overlay(shape.strokeBorder(line, lineWidth: 1))131        case "glass":132            content.background(.ultraThinMaterial, in: shape).overlay(shape.strokeBorder(theme.border ?? .white.opacity(0.22), lineWidth: 1))133        case "flat":134            content.background(theme.surfaceColor.map(AnyShapeStyle.init) ?? AnyShapeStyle(.clear), in: shape)135        default:136            content.background(theme.surfaceColor.map(AnyShapeStyle.init) ?? AnyShapeStyle(.background.secondary), in: shape).overlay(shape.strokeBorder(line))137        }138    }139}140141extension View {142    /// Draws the app theme's panel behind this view.143    public func prismSurface(radius: CGFloat? = nil) -> some View { modifier(ThemeSurface(radius: radius)) }144}145146extension EnvironmentValues {147    @Entry public var prismTheme = PrismTheme()148    @Entry public var prismDesign: DesignContext? = nil149}150151/// Present while the preview is in Design mode: clicks select components instead of operating them.152public struct DesignContext {153    public var selectedID: String?154    public var select: (String) -> Void155    public init(selectedID: String?, select: @escaping (String) -> Void) {156        self.selectedID = selectedID; self.select = select157    }158}159
Files main
Menu

Theme