Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Apps/GlassStudio/Kit/Playground/PlaygroundModel.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 SPGlassKit4344public enum PlaygroundAxis: String, Codable, CaseIterable, Sendable { case vertical, horizontal, depth }45public enum PlaygroundAlignment: String, Codable, CaseIterable, Sendable { case leading, center, trailing }4647/// One node of a composition: a stack with children, or a known component with typed values.48public struct PlaygroundNode: Identifiable, Codable, Hashable, Sendable {49 public enum Kind: Codable, Hashable, Sendable {50 case stack(axis: PlaygroundAxis, spacing: GlassSpacingStep, alignment: PlaygroundAlignment)51 case component(id: String, values: [String: InspectorValue])52 }5354 public var id: UUID55 public var kind: Kind56 public var children: [PlaygroundNode]5758 public init(id: UUID = UUID(), kind: Kind, children: [PlaygroundNode] = []) {59 self.id = id; self.kind = kind; self.children = children60 }6162 public static func stack(_ axis: PlaygroundAxis = .vertical, spacing: GlassSpacingStep = .md, alignment: PlaygroundAlignment = .center, _ children: [PlaygroundNode] = []) -> PlaygroundNode {63 PlaygroundNode(kind: .stack(axis: axis, spacing: spacing, alignment: alignment), children: children)64 }6566 public static func component(_ id: String, _ values: [String: InspectorValue] = [:]) -> PlaygroundNode {67 PlaygroundNode(kind: .component(id: id, values: values))68 }6970 public var isStack: Bool {71 if case .stack = kind { true } else { false }72 }7374 public var nodeCount: Int { 1 + children.reduce(0) { $0 + $1.nodeCount } }75 public var depth: Int { 1 + (children.map(\.depth).max() ?? 0) }7677 /// Identifiers of the catalogue components used below this node, in first-use order.78 public var componentIDs: [String] {79 var result: [String] = []80 func visit(_ node: PlaygroundNode) {81 if case .component(let id, _) = node.kind, !result.contains(id) { result.append(id) }82 node.children.forEach(visit)83 }84 visit(self)85 return result86 }87}8889public enum PlaygroundError: Error, Equatable, Sendable {90 case tooManyNodes(limit: Int)91 case tooDeep(limit: Int)92 case notAStack93 case unknownNode94 case unknownComponent(String)95 case cannotMoveIntoItself96 case cannotRemoveRoot97 case malformed98}99100/// A composition: a tree whose root is always a stack. Every mutation is validated, so a document can101/// never exceed its limits or reference a component the Studio does not know.102public struct PlaygroundDocument: Codable, Hashable, Sendable {103 public static let maximumNodes = 60104 public static let maximumDepth = 6105 public static let currentSchemaVersion = 1106107 public var schemaVersion: Int108 public var name: String109 public private(set) var root: PlaygroundNode110111 public init(name: String, root: PlaygroundNode = .stack()) {112 schemaVersion = Self.currentSchemaVersion113 self.name = name114 self.root = root.isStack ? root : .stack(.vertical, [root])115 }116117 /// Checks a whole tree: root is a stack, limits hold, components are known, leaves have no children.118 public static func validate(_ root: PlaygroundNode, knownComponents: Set<String>) throws(PlaygroundError) {119 guard root.isStack else { throw .notAStack }120 guard root.nodeCount <= maximumNodes else { throw .tooManyNodes(limit: maximumNodes) }121 guard root.depth <= maximumDepth else { throw .tooDeep(limit: maximumDepth) }122 var seen: Set<UUID> = []123 var pending = [root]124 while let node = pending.popLast() {125 guard seen.insert(node.id).inserted else { throw .malformed }126 if case .component(let id, _) = node.kind {127 guard knownComponents.contains(id) else { throw .unknownComponent(id) }128 guard node.children.isEmpty else { throw .malformed }129 }130 pending.append(contentsOf: node.children)131 }132 }133134 /// Decodes a document from a file: bounded size, known schema, validated tree.135 public static func decode(_ data: Data, knownComponents: Set<String>) throws(PlaygroundError) -> PlaygroundDocument {136 guard data.count <= 512 * 1024, let document = try? JSONDecoder().decode(PlaygroundDocument.self, from: data),137 document.schemaVersion >= 1, document.schemaVersion <= currentSchemaVersion else { throw .malformed }138 try validate(document.root, knownComponents: knownComponents)139 var cleaned = document140 cleaned.name = String(document.name.unicodeScalars.filter { $0.value >= 0x20 }.map(Character.init).prefix(80))141 return cleaned142 }143144 public func node(_ id: UUID) -> PlaygroundNode? {145 func find(_ node: PlaygroundNode) -> PlaygroundNode? {146 if node.id == id { return node }147 for child in node.children { if let found = find(child) { return found } }148 return nil149 }150 return find(root)151 }152153 /// The parent of a node and the node's index among its siblings.154 public func location(of id: UUID) -> (parent: UUID, index: Int)? {155 func find(_ node: PlaygroundNode) -> (UUID, Int)? {156 if let index = node.children.firstIndex(where: { $0.id == id }) { return (node.id, index) }157 for child in node.children { if let found = find(child) { return found } }158 return nil159 }160 return find(root)161 }162163 private func depth(of id: UUID) -> Int? {164 func find(_ node: PlaygroundNode, _ level: Int) -> Int? {165 if node.id == id { return level }166 for child in node.children { if let found = find(child, level + 1) { return found } }167 return nil168 }169 return find(root, 1)170 }171172 private mutating func mutate(_ id: UUID, _ change: (inout PlaygroundNode) -> Void) -> Bool {173 func apply(_ node: inout PlaygroundNode) -> Bool {174 if node.id == id { change(&node); return true }175 for index in node.children.indices where apply(&node.children[index]) { return true }176 return false177 }178 return apply(&root)179 }180181 /// Inserts `node` into the stack `parent` at `index` (appended when `index` is nil).182 public mutating func insert(_ node: PlaygroundNode, into parent: UUID, at index: Int? = nil) throws(PlaygroundError) {183 guard let target = self.node(parent), let level = depth(of: parent) else { throw .unknownNode }184 guard target.isStack else { throw .notAStack }185 guard root.nodeCount + node.nodeCount <= Self.maximumNodes else { throw .tooManyNodes(limit: Self.maximumNodes) }186 guard level + node.depth <= Self.maximumDepth else { throw .tooDeep(limit: Self.maximumDepth) }187 _ = mutate(parent) { stack in188 let position = min(max(index ?? stack.children.count, 0), stack.children.count)189 stack.children.insert(node, at: position)190 }191 }192193 @discardableResult194 public mutating func remove(_ id: UUID) throws(PlaygroundError) -> PlaygroundNode {195 guard id != root.id else { throw .cannotRemoveRoot }196 guard let location = location(of: id), let removed = node(id) else { throw .unknownNode }197 _ = mutate(location.parent) { $0.children.remove(at: location.index) }198 return removed199 }200201 /// Moves a node to another stack, or to another position in the same stack.202 public mutating func move(_ id: UUID, into parent: UUID, at index: Int? = nil) throws(PlaygroundError) {203 guard id != root.id else { throw .cannotRemoveRoot }204 guard let moving = node(id), let origin = location(of: id) else { throw .unknownNode }205 func contains(_ node: PlaygroundNode, _ target: UUID) -> Bool {206 node.id == target || node.children.contains { contains($0, target) }207 }208 guard !contains(moving, parent) else { throw .cannotMoveIntoItself }209 var copy = self210 try copy.remove(id)211 var position = index212 // Removing an earlier sibling shifts the indices that follow it.213 if origin.parent == parent, let wanted = index, origin.index < wanted { position = wanted - 1 }214 try copy.insert(moving, into: parent, at: position)215 self = copy216 }217218 /// Moves a node one step among its siblings. Returns false at either end.219 @discardableResult220 public mutating func shift(_ id: UUID, by offset: Int) -> Bool {221 guard let location = location(of: id), let parent = node(location.parent) else { return false }222 let target = location.index + offset223 guard parent.children.indices.contains(target) else { return false }224 return mutate(location.parent) { $0.children.swapAt(location.index, target) }225 }226227 public mutating func updateStack(_ id: UUID, axis: PlaygroundAxis, spacing: GlassSpacingStep, alignment: PlaygroundAlignment) throws(PlaygroundError) {228 guard let node = node(id) else { throw .unknownNode }229 guard node.isStack else { throw .notAStack }230 _ = mutate(id) { $0.kind = .stack(axis: axis, spacing: spacing, alignment: alignment) }231 }232233 public mutating func updateValues(_ id: UUID, values: [String: InspectorValue]) throws(PlaygroundError) {234 guard let node = node(id), case .component(let componentID, _) = node.kind else { throw .unknownNode }235 _ = mutate(id) { $0.kind = .component(id: componentID, values: values) }236 }237}238