Repository Public MIT
1import Foundation2import SPGlassKit34/// The files produced from a composition.5public struct PlaygroundExport: Equatable, Sendable {6 public let fileName: String7 public let source: String8 /// Registry identifiers the generated view needs.9 public let dependencies: [String]10 public let installCommand: String11 /// A small JSON manifest listing the dependencies, for tooling.12 public let manifest: String13}1415/// Turns a composition into a readable SwiftUI file. Component code comes from each descriptor's typed16/// template; text values are escaped by ``SwiftLiteral``; nothing is evaluated.17@MainActor18public enum PlaygroundCodeGenerator {19 public static func export(_ document: PlaygroundDocument, catalog: ComponentCatalog) -> PlaygroundExport {20 let typeName = typeName(for: document.name)21 var lines: [String] = [22 "// \(commentSafe(document.name)) — generated by SP Glass Studio. Edit freely.",23 "import SwiftUI",24 "import SPGlassKit",25 "",26 "struct \(typeName): View {",27 " var body: some View {",28 ]29 lines.append(SwiftLiteral.indent(code(for: document.root, catalog: catalog), levels: 2))30 lines.append(contentsOf: [" .padding()", " }", "}", "", "#Preview {", " \(typeName)()", "}", ""])3132 let dependencies = document.root.componentIDs33 let manifestObject: [String: Any] = ["schemaVersion": 1, "name": document.name, "view": typeName, "components": dependencies, "package": "SPGlassKit", "minimumOS": ["iOS": "26.0", "macOS": "26.0"]]34 let manifestData = (try? JSONSerialization.data(withJSONObject: manifestObject, options: [.prettyPrinted, .sortedKeys])) ?? Data("{}".utf8)35 return PlaygroundExport(36 fileName: "\(typeName).swift",37 source: lines.joined(separator: "\n"),38 dependencies: dependencies,39 installCommand: dependencies.isEmpty ? "" : "spglass add " + dependencies.joined(separator: " "),40 manifest: String(decoding: manifestData, as: UTF8.self) + "\n"41 )42 }4344 static func code(for node: PlaygroundNode, catalog: ComponentCatalog) -> String {45 switch node.kind {46 case .component(let id, let values):47 guard let descriptor = catalog.descriptor(id) else { return "EmptyView() // unknown component" }48 return descriptor.snippet(InspectorValues(fields: descriptor.fields, values: values)).trimmingCharacters(in: .whitespacesAndNewlines)49 case .stack(let axis, let spacing, let alignment):50 let points = SwiftLiteral.number(GlassSpacing.standard[spacing])51 let header: String52 switch axis {53 case .vertical: header = "VStack(alignment: .\(alignment.rawValue), spacing: \(points)) {"54 case .horizontal: header = "HStack(alignment: .center, spacing: \(points)) {"55 case .depth: header = "ZStack(alignment: .\(alignment.rawValue)) {"56 }57 if node.children.isEmpty { return header + "\n EmptyView()\n}" }58 let body = node.children.map { SwiftLiteral.indent(code(for: $0, catalog: catalog)) }.joined(separator: "\n")59 return header + "\n" + body + "\n}"60 }61 }6263 /// An upper camel case type name from a free-form title: "Real estate screen" → `RealEstateScreenView`.64 public static func typeName(for name: String) -> String {65 let folded = name.folding(options: [.diacriticInsensitive], locale: Locale(identifier: "en"))66 let words = folded.split(whereSeparator: { !($0.isASCII && ($0.isLetter || $0.isNumber)) }).prefix(6)67 var result = words.map { $0.prefix(1).uppercased() + $0.dropFirst() }.joined()68 if result.isEmpty || result.first?.isNumber == true { result = "Composition" + result }69 return String(result.prefix(48)) + "View"70 }7172 private static func commentSafe(_ text: String) -> String {73 String(text.unicodeScalars.filter { $0.value >= 0x20 && $0.value != 0x7F && $0.value != 0x2028 && $0.value != 0x2029 }.map(Character.init).prefix(80))74 }75}76