SPB Git

Repository Public MIT

GlassThemeSwiftExporter.swift 7.6 KB 145 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 Foundation42import SPGlassTokens4344/// Generates Swift source that recreates a theme as a static constant.45public enum GlassThemeSwiftExporter {46    /// Returns a Swift file declaring `GlassTheme.<property>`.47    ///48    /// - Parameter moduleImport: module imported at the top of the file (`SPGlassKit` in package mode).49    ///   Pass `nil` when the GlassKit sources live in the same module as the generated file.50    public static func source(for theme: GlassTheme, moduleImport: String? = "SPGlassKit") -> String {51        var lines: [String] = []52        lines.append("// Theme \"\(commentSafe(theme.name))\" exported by SP GlassKit. Edit freely.")53        lines.append("import SwiftUI")54        if let moduleImport { lines.append("import \(moduleImport)") }55        lines.append("")56        lines.append("extension GlassTheme {")57        lines.append("    static let \(propertyName(for: theme.id)) = GlassTheme(")58        lines.append("        id: \(literal(theme.id.rawValue)),")59        lines.append("        name: \(literal(theme.name)),")60        lines.append("        summary: \(literal(theme.summary)),")61        lines.append("        appearance: .\(theme.appearance.rawValue),")62        lines.append("        light: \(palette(theme.light)),")63        lines.append("        dark: \(palette(theme.dark)),")64        lines.append("        typography: GlassTypography(design: .\(escapedCase(theme.typography.design.rawValue)), headingWeight: .\(theme.typography.headingWeight.rawValue), bodyWeight: .\(theme.typography.bodyWeight.rawValue)),")65        let s = theme.spacing66        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))),")67        let r = theme.radii68        lines.append("        radii: GlassRadii(small: \(number(r.small)), medium: \(number(r.medium)), large: \(number(r.large)), extraLarge: \(number(r.extraLarge))),")69        let m = theme.motion70        lines.append("        motion: GlassMotion(style: .\(m.style.rawValue), fast: \(number(m.fast)), standard: \(number(m.standard)), slow: \(number(m.slow))),")71        lines.append("        density: .\(theme.density.rawValue),")72        let tint = theme.glass.tint.map { ".\($0.rawValue)" } ?? "nil"73        lines.append("        glass: GlassMaterialTokens(variant: .\(theme.glass.variant.rawValue), tint: \(tint)),")74        lines.append("        hapticsEnabled: \(theme.hapticsEnabled)")75        lines.append("    )")76        lines.append("}")77        lines.append("")78        return lines.joined(separator: "\n")79    }8081    /// A Swift string literal for arbitrary text: quotes, backslashes, control characters and line breaks are escaped.82    public static func literal(_ text: String) -> String {83        var result = "\""84        for scalar in text.unicodeScalars {85            switch scalar {86            case "\"": result += "\\\""87            case "\\": result += "\\\\"88            case "\n": result += "\\n"89            case "\r": result += "\\r"90            case "\t": result += "\\t"91            case "\0": result += "\\0"92            default:93                if scalar.value < 0x20 || scalar.value == 0x7F || scalar.value == 0x2028 || scalar.value == 0x2029 {94                    result += "\\u{\(String(scalar.value, radix: 16))}"95                } else {96                    result.unicodeScalars.append(scalar)97                }98            }99        }100        return result + "\""101    }102103    /// A lower camel case Swift identifier derived from a theme identifier (`lou-ka-example` → `louKaExample`).104    public static func propertyName(for id: GlassThemeID) -> String {105        let parts = id.rawValue.split(whereSeparator: { !($0.isASCII && ($0.isLetter || $0.isNumber)) }).map(String.init)106        guard let first = parts.first else { return "customTheme" }107        var name = first.lowercased() + parts.dropFirst().map { $0.prefix(1).uppercased() + $0.dropFirst().lowercased() }.joined()108        if name.first?.isNumber == true { name = "theme" + name }109        // `GlassTheme.ocean` and the other built-in themes already exist: an exported copy must not redeclare them.110        if builtInNames.contains(name) { name += "Theme" }111        return reserved.contains(name) ? "`\(name)`" : name112    }113114    /// Static members that `GlassTheme` already declares.115    private static let builtInNames: Set<String> = ["system", "crystal", "obsidian", "aurora", "emerald", "solar", "ocean", "neon", "builtIn", "examples", "named"]116117    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"]118119    private static func escapedCase(_ name: String) -> String {120        name == "default" ? "`default`" : name121    }122123    private static func palette(_ palette: GlassPalette) -> String {124        let tokens = palette.definedTokens125        guard !tokens.isEmpty else { return "GlassPalette()" }126        let entries = tokens.compactMap { token -> String? in127            guard let colour = palette[token] else { return nil }128            let hex = String(format: "0x%06X", colour.rgbValue)129            let alpha = colour.isOpaque ? "" : ", alpha: \(number(colour.alpha))"130            return "            .\(token.rawValue): GlassRGBA(rgb: \(hex)\(alpha)),"131        }132        return "GlassPalette([\n" + entries.joined(separator: "\n") + "\n        ])"133    }134135    private static func number(_ value: Double) -> String {136        guard value.isFinite else { return "0" }137        if value == value.rounded(), abs(value) < 1e9 { return String(Int(value)) }138        return String(format: "%.4g", locale: Locale(identifier: "en_US_POSIX"), value)139    }140141    private static func commentSafe(_ text: String) -> String {142        String(text.unicodeScalars.filter { $0.value >= 0x20 && $0.value != 0x7F && $0.value != 0x2028 && $0.value != 0x2029 }.prefix(80)).replacingOccurrences(of: "*/", with: "* /")143    }144}145
Files main
Menu

Theme