Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/KitTests/PlaygroundTests.swift8// Module : GlassStudio9// 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 Testing43import SPGlassKit44@testable import GlassStudioKit4546@Suite("Playground document")47struct PlaygroundDocumentTests {48 let known: Set<String> = ["glass-button", "glass-badge"]4950 @Test func theRootIsAlwaysAStack() {51 #expect(PlaygroundDocument(name: "x").root.isStack)52 let wrapped = PlaygroundDocument(name: "x", root: .component("glass-button"))53 #expect(wrapped.root.isStack && wrapped.root.children.count == 1)54 }5556 @Test func insertMoveShiftAndRemove() throws {57 var document = PlaygroundDocument(name: "Demo")58 let row = PlaygroundNode.stack(.horizontal)59 let a = PlaygroundNode.component("glass-button"), b = PlaygroundNode.component("glass-badge"), c = PlaygroundNode.component("glass-button")60 try document.insert(row, into: document.root.id)61 try document.insert(a, into: document.root.id)62 try document.insert(b, into: document.root.id, at: 0)63 try document.insert(c, into: row.id)64 #expect(document.root.children.map(\.id) == [b.id, row.id, a.id])65 #expect(document.root.nodeCount == 5 && document.root.depth == 3)66 #expect(document.root.componentIDs == ["glass-badge", "glass-button"])6768 try document.move(a.id, into: row.id, at: 0)69 #expect(document.node(row.id)?.children.map(\.id) == [a.id, c.id])70 try document.move(b.id, into: document.root.id, at: 2)71 #expect(document.root.children.map(\.id) == [row.id, b.id], "moving later in the same stack accounts for the removed slot")72 let shifted = document.shift(b.id, by: -1)73 #expect(shifted && document.root.children.map(\.id) == [b.id, row.id])74 let shiftedAgain = document.shift(b.id, by: -1)75 #expect(!shiftedAgain, "already first")7677 let removed = try document.remove(row.id)78 #expect(removed.children.count == 2)79 #expect(document.root.nodeCount == 2 && document.node(a.id) == nil)80 }8182 @Test func invalidOperationsAreRefusedAndLeaveTheDocumentUntouched() throws {83 var document = PlaygroundDocument(name: "Demo")84 let row = PlaygroundNode.stack(.horizontal), leaf = PlaygroundNode.component("glass-button")85 try document.insert(row, into: document.root.id)86 try document.insert(leaf, into: row.id)87 let before = document88 #expect(throws: PlaygroundError.notAStack) { try document.insert(.component("glass-badge"), into: leaf.id) }89 #expect(throws: PlaygroundError.unknownNode) { try document.insert(.component("glass-badge"), into: UUID()) }90 #expect(throws: PlaygroundError.cannotRemoveRoot) { try document.remove(document.root.id) }91 #expect(throws: PlaygroundError.cannotMoveIntoItself) { try document.move(row.id, into: row.id) }92 #expect(throws: PlaygroundError.cannotRemoveRoot) { try document.move(document.root.id, into: row.id) }93 #expect(throws: PlaygroundError.notAStack) { try document.updateStack(leaf.id, axis: .depth, spacing: .xs, alignment: .leading) }94 #expect(throws: PlaygroundError.unknownNode) { try document.updateValues(row.id, values: [:]) }95 #expect(document == before)96 }9798 @Test func nodeAndDepthLimitsHold() throws {99 var document = PlaygroundDocument(name: "Big")100 for _ in 0..<(PlaygroundDocument.maximumNodes - 1) { try document.insert(.component("glass-button"), into: document.root.id) }101 #expect(throws: PlaygroundError.tooManyNodes(limit: 60)) { try document.insert(.component("glass-button"), into: document.root.id) }102103 var deep = PlaygroundDocument(name: "Deep")104 var parent = deep.root.id105 for _ in 0..<(PlaygroundDocument.maximumDepth - 1) {106 let stack = PlaygroundNode.stack()107 try deep.insert(stack, into: parent)108 parent = stack.id109 }110 #expect(deep.root.depth == PlaygroundDocument.maximumDepth)111 #expect(throws: PlaygroundError.tooDeep(limit: 6)) { try deep.insert(.component("glass-button"), into: parent) }112 let subtree = PlaygroundNode.stack(.vertical, [.stack(.vertical, [.component("glass-button")])])113 let secondLevel = try #require(deep.root.children.first?.children.first?.children.first?.id)114 #expect(throws: PlaygroundError.tooDeep(limit: 6)) { try deep.insert(subtree, into: secondLevel) }115 }116117 @Test func filesAreBoundedAndValidatedOnImport() throws {118 var document = PlaygroundDocument(name: "Round trip")119 try document.insert(.component("glass-button", ["title": .text("Hi")]), into: document.root.id)120 let data = try JSONEncoder().encode(document)121 #expect(try PlaygroundDocument.decode(data, knownComponents: known) == document)122 #expect(throws: PlaygroundError.unknownComponent("glass-button")) { try PlaygroundDocument.decode(data, knownComponents: []) }123 #expect(throws: PlaygroundError.malformed) { try PlaygroundDocument.decode(Data("{".utf8), knownComponents: known) }124 #expect(throws: PlaygroundError.malformed) { try PlaygroundDocument.decode(Data(repeating: 0x20, count: 600_000), knownComponents: known) }125126 // A hand-built file: a component with children, duplicate identifiers, a deep chain, a future schema.127 let leafWithChild = PlaygroundNode(kind: .component(id: "glass-button", values: [:]), children: [.component("glass-badge")])128 let shared = PlaygroundNode.component("glass-badge")129 var chain = PlaygroundNode.stack()130 for _ in 0..<10 { chain = .stack(.vertical, [chain]) }131 for root in [PlaygroundNode.stack(.vertical, [leafWithChild]), .stack(.vertical, [shared, shared])] {132 #expect(throws: PlaygroundError.malformed) { try PlaygroundDocument.validate(root, knownComponents: known) }133 }134 #expect(throws: PlaygroundError.tooDeep(limit: 6)) { try PlaygroundDocument.validate(chain, knownComponents: known) }135 #expect(throws: PlaygroundError.notAStack) { try PlaygroundDocument.validate(.component("glass-button"), knownComponents: known) }136 var future = try #require(JSONSerialization.jsonObject(with: data) as? [String: Any])137 future["schemaVersion"] = 5138 #expect(throws: PlaygroundError.malformed) { try PlaygroundDocument.decode(JSONSerialization.data(withJSONObject: future), knownComponents: known) }139 }140}141142@Suite("Playground code generation")143@MainActor144struct PlaygroundCodeGeneratorTests {145 @Test func typeNamesAreValidIdentifiers() {146 #expect(PlaygroundCodeGenerator.typeName(for: "Real estate screen") == "RealEstateScreenView")147 #expect(PlaygroundCodeGenerator.typeName(for: "Écran immobilier n° 2") == "EcranImmobilierN2View")148 #expect(PlaygroundCodeGenerator.typeName(for: "2026 dashboard") == "Composition2026DashboardView")149 #expect(PlaygroundCodeGenerator.typeName(for: "💥 \"); exit(0)") == "Exit0View")150 #expect(PlaygroundCodeGenerator.typeName(for: "") == "CompositionView")151 }152153 @Test func generatedSourceNestsStacksAndListsDependencies() throws {154 var document = PlaygroundDocument(name: "Toolbar demo", root: .stack(.vertical, spacing: .lg, alignment: .leading))155 let row = PlaygroundNode.stack(.horizontal, spacing: .xs)156 try document.insert(row, into: document.root.id)157 try document.insert(.component("glass-button", ["title": .text("Save \"now\""), "variant": .choice("prominent")]), into: row.id)158 try document.insert(.component("glass-icon-button"), into: row.id)159 try document.insert(.stack(.depth), into: document.root.id)160 let export = PlaygroundCodeGenerator.export(document, catalog: .standard)161162 #expect(export.fileName == "ToolbarDemoView.swift")163 #expect(export.dependencies == ["glass-button", "glass-icon-button"])164 #expect(export.installCommand == "spglass add glass-button glass-icon-button")165 #expect(export.source.contains("struct ToolbarDemoView: View {"))166 #expect(export.source.contains(" VStack(alignment: .leading, spacing: 24) {\n HStack(alignment: .center, spacing: 8) {\n GlassButton(\"Save \\\"now\\\"\""))167 #expect(export.source.contains("ZStack(alignment: .center) {\n EmptyView()"))168 #expect(export.source.contains("#Preview {\n ToolbarDemoView()\n}"))169 #expect(export.source.filter { $0 == "{" }.count == export.source.filter { $0 == "}" }.count)170 let manifest = try #require(JSONSerialization.jsonObject(with: Data(export.manifest.utf8)) as? [String: Any])171 #expect(manifest["components"] as? [String] == ["glass-button", "glass-icon-button"] && manifest["view"] as? String == "ToolbarDemoView")172 }173174 @Test func hostileTextStaysInsideItsLiteral() throws {175 var document = PlaygroundDocument(name: "x\n} import Darwin //")176 try document.insert(.component("glass-button", ["title": .text("\"); fatalError(); print(\""), "symbol": .text("\\(0)")]), into: document.root.id)177 let source = PlaygroundCodeGenerator.export(document, catalog: .standard).source178 #expect(source.components(separatedBy: "\n").filter { $0.hasPrefix("import ") } == ["import SwiftUI", "import SPGlassKit"])179 #expect(source.contains(#"GlassButton("\"); fatalError(); print(\"", systemImage: "\\(0)")"#))180 #expect(source.components(separatedBy: "\n")[0].hasPrefix("// x} import Darwin //"))181 }182}183184@Suite("Studio catalogue")185@MainActor186struct ComponentCatalogTests {187 @Test func descriptorsAreInCatalogueOrderWithUniqueFieldsAndValidVariants() {188 let catalog = ComponentCatalog.standard189 #expect(catalog.descriptors.map(\.info.number) == catalog.descriptors.map(\.info.number).sorted())190 #expect(Set(catalog.descriptors.map(\.id)).count == catalog.descriptors.count)191 for descriptor in catalog.descriptors {192 #expect(Set(descriptor.fields.map(\.id)).count == descriptor.fields.count, "\(descriptor.id) has duplicate field ids")193 for variant in descriptor.variants {194 for (key, value) in variant.values {195 let field = descriptor.fields.first { $0.id == key }196 #expect(field != nil, "\(descriptor.id) variant \(variant.id) sets unknown field \(key)")197 #expect(field?.validated(value) == value, "\(descriptor.id) variant \(variant.id) sets an invalid value for \(key)")198 }199 }200 #expect(!descriptor.snippet(descriptor.defaultValues).isEmpty)201 }202 }203204 @Test func snippetsAreBalancedForDefaultsAndVariants() {205 for descriptor in ComponentCatalog.standard.descriptors {206 for values in [descriptor.defaultValues] + descriptor.variants.map(descriptor.values(for:)) {207 let code = SwiftSourceBalance.strippingStrings(descriptor.snippet(values))208 #expect(code.filter { $0 == "(" }.count == code.filter { $0 == ")" }.count, "\(descriptor.id): parentheses")209 #expect(code.filter { $0 == "{" }.count == code.filter { $0 == "}" }.count, "\(descriptor.id): braces")210 }211 }212 }213214 @Test func searchAndLookup() {215 let catalog = ComponentCatalog.standard216 #expect(catalog.descriptor("glass-button")?.info.name == "GlassButton" && catalog.descriptor("nope") == nil)217 var filter = CatalogFilter(); filter.query = "split button"218 #expect(catalog.search(filter).map(\.id) == ["glass-split-button"])219 #expect(catalog.composableIDs.contains("glass-button") && !catalog.composableIDs.contains("glass-floating-button"))220 }221}222223/// Removes string literal contents so that brackets inside titles do not count.224enum SwiftSourceBalance {225 static func strippingStrings(_ source: String) -> String {226 var output = "", inString = false, escaped = false227 for character in source {228 if inString {229 if escaped { escaped = false } else if character == "\\" { escaped = true } else if character == "\"" { inString = false }230 } else if character == "\"" {231 inString = true232 } else {233 output.append(character)234 }235 }236 return output237 }238}239