SPB Git

Repository Public MIT

GlassThemeSwiftExporter.swift 7.6 KB 144 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassThemes/GlassThemeSwiftExporter.swift8// Module           : SPGlassThemes9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation4243/// Generates Swift source that recreates a theme as a static constant.44public enum GlassThemeSwiftExporter {45    /// Returns a Swift file declaring `GlassTheme.<property>`.46    ///47    /// - Parameter moduleImport: module imported at the top of the file (`SPGlassKit` in package mode).48    ///   Pass `nil` when the GlassKit sources live in the same module as the generated file.49    public static func source(for theme: GlassTheme, moduleImport: String? = "SPGlassKit") -> String {50        var lines: [String] = []51        lines.append("// Theme \"\(commentSafe(theme.name))\" exported by SP GlassKit. Edit freely.")52        lines.append("import SwiftUI")53        if let moduleImport { lines.append("import \(moduleImport)") }54        lines.append("")55        lines.append("extension GlassTheme {")56        lines.append("    static let \(propertyName(for: theme.id)) = GlassTheme(")57        lines.append("        id: \(literal(theme.id.rawValue)),")58        lines.append("        name: \(literal(theme.name)),")59        lines.append("        summary: \(literal(theme.summary)),")60        lines.append("        appearance: .\(theme.appearance.rawValue),")61        lines.append("        light: \(palette(theme.light)),")62        lines.append("        dark: \(palette(theme.dark)),")63        lines.append("        typography: GlassTypography(design: .\(escapedCase(theme.typography.design.rawValue)), headingWeight: .\(theme.typography.headingWeight.rawValue), bodyWeight: .\(theme.typography.bodyWeight.rawValue)),")64        let s = theme.spacing65        lines.append("        spacing: GlassSpacing(xxs: \(number(s.xxs)), xs: \(number(s.xs)), sm: \(number(s.sm)), md: \(number(s.md)), lg: \(number(s.lg)), xl: \(number(s.xl)), xxl: \(number(s.xxl))),")66        let r = theme.radii67        lines.append("        radii: GlassRadii(small: \(number(r.small)), medium: \(number(r.medium)), large: \(number(r.large)), extraLarge: \(number(r.extraLarge))),")68        let m = theme.motion69        lines.append("        motion: GlassMotion(style: .\(m.style.rawValue), fast: \(number(m.fast)), standard: \(number(m.standard)), slow: \(number(m.slow))),")70        lines.append("        density: .\(theme.density.rawValue),")71        let tint = theme.glass.tint.map { ".\($0.rawValue)" } ?? "nil"72        lines.append("        glass: GlassMaterialTokens(variant: .\(theme.glass.variant.rawValue), tint: \(tint)),")73        lines.append("        hapticsEnabled: \(theme.hapticsEnabled)")74        lines.append("    )")75        lines.append("}")76        lines.append("")77        return lines.joined(separator: "\n")78    }7980    /// A Swift string literal for arbitrary text: quotes, backslashes, control characters and line breaks are escaped.81    public static func literal(_ text: String) -> String {82        var result = "\""83        for scalar in text.unicodeScalars {84            switch scalar {85            case "\"": result += "\\\""86            case "\\": result += "\\\\"87            case "\n": result += "\\n"88            case "\r": result += "\\r"89            case "\t": result += "\\t"90            case "\0": result += "\\0"91            default:92                if scalar.value < 0x20 || scalar.value == 0x7F || scalar.value == 0x2028 || scalar.value == 0x2029 {93                    result += "\\u{\(String(scalar.value, radix: 16))}"94                } else {95                    result.unicodeScalars.append(scalar)96                }97            }98        }99        return result + "\""100    }101102    /// A lower camel case Swift identifier derived from a theme identifier (`lou-ka-example` → `louKaExample`).103    public static func propertyName(for id: GlassThemeID) -> String {104        let parts = id.rawValue.split(whereSeparator: { !($0.isASCII && ($0.isLetter || $0.isNumber)) }).map(String.init)105        guard let first = parts.first else { return "customTheme" }106        var name = first.lowercased() + parts.dropFirst().map { $0.prefix(1).uppercased() + $0.dropFirst().lowercased() }.joined()107        if name.first?.isNumber == true { name = "theme" + name }108        // `GlassTheme.ocean` and the other built-in themes already exist: an exported copy must not redeclare them.109        if builtInNames.contains(name) { name += "Theme" }110        return reserved.contains(name) ? "`\(name)`" : name111    }112113    /// Static members that `GlassTheme` already declares.114    private static let builtInNames: Set<String> = ["system", "crystal", "obsidian", "aurora", "emerald", "solar", "ocean", "neon", "builtIn", "examples", "named"]115116    private static let reserved: Set<String> = ["default", "class", "struct", "enum", "func", "let", "var", "static", "public", "private", "import", "extension", "protocol", "self", "init", "in", "for", "if", "else", "switch", "case", "return", "true", "false", "nil", "operator", "internal"]117118    private static func escapedCase(_ name: String) -> String {119        name == "default" ? "`default`" : name120    }121122    private static func palette(_ palette: GlassPalette) -> String {123        let tokens = palette.definedTokens124        guard !tokens.isEmpty else { return "GlassPalette()" }125        let entries = tokens.compactMap { token -> String? in126            guard let colour = palette[token] else { return nil }127            let hex = String(format: "0x%06X", colour.rgbValue)128            let alpha = colour.isOpaque ? "" : ", alpha: \(number(colour.alpha))"129            return "            .\(token.rawValue): GlassRGBA(rgb: \(hex)\(alpha)),"130        }131        return "GlassPalette([\n" + entries.joined(separator: "\n") + "\n        ])"132    }133134    private static func number(_ value: Double) -> String {135        guard value.isFinite else { return "0" }136        if value == value.rounded(), abs(value) < 1e9 { return String(Int(value)) }137        return String(format: "%.4g", locale: Locale(identifier: "en_US_POSIX"), value)138    }139140    private static func commentSafe(_ text: String) -> String {141        String(text.unicodeScalars.filter { $0.value >= 0x20 && $0.value != 0x7F && $0.value != 0x2028 && $0.value != 0x2029 }.prefix(80)).replacingOccurrences(of: "*/", with: "* /")142    }143}144
Files main
Menu

Theme