SPB Git

Repository Public MIT

PlaygroundView.swift 18.0 KB 421 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Views/PlaygroundView.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 SwiftUI42import UniformTypeIdentifiers43import SPGlassKit4445/// A generated Swift file for the system file exporter.46struct SwiftSourceFile: FileDocument {47    static let readableContentTypes: [UTType] = [.swiftSource]48    var source: String4950    init(source: String) { self.source = source }5152    init(configuration: ReadConfiguration) throws {53        source = String(decoding: configuration.file.regularFileContents ?? Data(), as: UTF8.self)54    }5556    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {57        FileWrapper(regularFileWithContents: Data(source.utf8))58    }59}6061/// Renders a composition tree with the real components. No code is evaluated: each node maps to a62/// descriptor's compiled preview.63struct PlaygroundRenderer: View {64    let node: PlaygroundNode65    let catalog: ComponentCatalog66    let selection: UUID?67    @GlassThemed private var theme6869    var body: some View {70        content71            .overlay {72                if selection == node.id {73                    RoundedRectangle(cornerRadius: 6, style: .continuous)74                        .strokeBorder(theme.color(.focusRing), style: StrokeStyle(lineWidth: 2, dash: [5, 3]))75                        .allowsHitTesting(false)76                        .accessibilityHidden(true)77                }78            }79    }8081    @ViewBuilder82    private var content: some View {83        switch node.kind {84        case .component(let id, let values):85            if let descriptor = catalog.descriptor(id) {86                descriptor.preview(InspectorValues(fields: descriptor.fields, values: values))87            }88        case .stack(let axis, let spacing, let alignment):89            let distance = theme.spacing[spacing]90            let children = ForEach(node.children) { PlaygroundRenderer(node: $0, catalog: catalog, selection: selection) }91            switch axis {92            case .vertical:93                VStack(alignment: alignment.horizontal, spacing: distance) { children }.frame(minWidth: 24, minHeight: 24)94            case .horizontal:95                HStack(alignment: .center, spacing: distance) { children }.frame(minWidth: 24, minHeight: 24)96            case .depth:97                ZStack(alignment: Alignment(horizontal: alignment.horizontal, vertical: .center)) { children }.frame(minWidth: 24, minHeight: 24)98            }99        }100    }101}102103extension PlaygroundAlignment {104    var horizontal: HorizontalAlignment {105        switch self {106        case .leading: .leading107        case .center: .center108        case .trailing: .trailing109        }110    }111}112113/// One line of the composition outline.114struct PlaygroundOutlineRow: Identifiable {115    let id: UUID116    let node: PlaygroundNode117    let level: Int118119    static func rows(for root: PlaygroundNode) -> [PlaygroundOutlineRow] {120        var rows: [PlaygroundOutlineRow] = []121        func visit(_ node: PlaygroundNode, _ level: Int) {122            rows.append(PlaygroundOutlineRow(id: node.id, node: node, level: level))123            node.children.forEach { visit($0, level + 1) }124        }125        visit(root, 0)126        return rows127    }128}129130struct PlaygroundView: View {131    /// Which part of the playground this view shows. A split view puts the outline and the workspace in132    /// separate columns; elsewhere one view shows everything.133    enum Part { case everything, outline, workspace }134135    @Bindable var model: StudioModel136    var part = Part.everything137    @State private var tab = "canvas"138    @State private var message: String?139    @State private var exportsSwift = false140    @Environment(\.horizontalSizeClass) private var sizeClass141142    private var export: PlaygroundExport { PlaygroundCodeGenerator.export(model.playground, catalog: model.catalog) }143144    var body: some View {145        Group {146            if part == .outline {147                outline148            } else if part == .workspace {149                VStack(spacing: 0) {150                    tabPicker.padding()151                    if tab == "code" { code } else { canvas }152                }153            } else if sizeClass == .regular {154                HStack(spacing: 0) {155                    outline.frame(width: 300)156                    Divider()157                    VStack(spacing: 0) {158                        tabPicker.padding()159                        if tab == "canvas" { canvas } else { code }160                    }161                }162            } else {163                VStack(spacing: 0) {164                    tabPicker.padding([.horizontal, .top])165                    switch tab {166                    case "outline": outline167                    case "code": code168                    default: canvas169                    }170                }171            }172        }173        .navigationTitle(Text(L("Playground")))174        #if os(iOS)175        .navigationBarTitleDisplayMode(.inline)176        #endif177        .toolbar {178            ToolbarItemGroup(placement: .primaryAction) {179                if part != .outline {180                Menu {181                    ForEach(PlaygroundTemplate.allCases) { template in182                        Button(template.title, systemImage: template.symbol) { model.resetPlayground(to: template) }183                    }184                } label: {185                    Label(L("Templates"), systemImage: "square.grid.2x2")186                }187                .accessibilityIdentifier("playground-templates")188                PreviewOptionsMenu(configuration: $model.preview, themes: model.themes.allThemes)189                Menu {190                    Button(L("Copy Swift code"), systemImage: "doc.on.doc") { StudioPasteboard.copy(export.source) }191                    Button(L("Export Swift file…"), systemImage: "square.and.arrow.down") { exportsSwift = true }192                    Button(L("Copy dependency manifest"), systemImage: "list.bullet.rectangle") { StudioPasteboard.copy(export.manifest) }193                    if !export.installCommand.isEmpty {194                        Button(L("Copy install command"), systemImage: "terminal") { StudioPasteboard.copy(export.installCommand) }195                    }196                } label: {197                    Label(L("Export"), systemImage: "square.and.arrow.up")198                }199                .accessibilityIdentifier("playground-export")200                }201            }202        }203        .fileExporter(isPresented: $exportsSwift, document: SwiftSourceFile(source: export.source), contentType: .swiftSource, defaultFilename: export.fileName) { _ in }204        .alert(L("Playground"), isPresented: Binding(get: { message != nil }, set: { if !$0 { message = nil } })) {205            Button(L("OK")) { message = nil }206        } message: {207            Text(verbatim: message ?? "")208        }209        .accessibilityIdentifier("playground")210    }211212    private var tabPicker: some View {213        Picker(L("View"), selection: $tab) {214            if sizeClass != .regular, part == .everything { Text(L("Structure")).tag("outline") }215            Text(L("Canvas")).tag("canvas")216            Text(L("Code")).tag("code")217        }218        .pickerStyle(.segmented)219        .labelsHidden()220    }221222    private var canvas: some View {223        ScrollView {224            PreviewCanvas(configuration: model.preview, theme: model.previewTheme, minHeight: 360) {225                PlaygroundRenderer(node: model.playground.root, catalog: model.catalog, selection: model.selectedNodeID)226            }227            .padding()228        }229    }230231    private var code: some View {232        ScrollView {233            VStack(alignment: .leading, spacing: 20) {234                CodeView(export.source, title: export.fileName)235                if !export.installCommand.isEmpty { CodeView(export.installCommand, title: L("Install the components it uses")) }236                CodeView(export.manifest, title: L("Dependency manifest"))237            }238            .padding()239        }240    }241242    // MARK: Outline243244    private var selectedNode: PlaygroundNode? { model.selectedNodeID.flatMap(model.playground.node) }245246    /// The stack new nodes go into: the selected stack, the parent of the selected component, or the root.247    private var insertionTarget: UUID {248        if let node = selectedNode {249            if node.isStack { return node.id }250            if let parent = model.playground.location(of: node.id)?.parent { return parent }251        }252        return model.playground.root.id253    }254255    private func perform(_ change: (inout PlaygroundDocument) throws -> Void) {256        var document = model.playground257        do {258            try change(&document)259            model.playground = document260        } catch let error as PlaygroundError {261            message = describe(error)262        } catch {263            message = L("This change is not possible.")264        }265    }266267    private func shift(_ id: UUID, by offset: Int) {268        var document = model.playground269        if document.shift(id, by: offset) { model.playground = document }270    }271272    private func describe(_ error: PlaygroundError) -> String {273        switch error {274        case .tooManyNodes(let limit): L("A composition holds at most %lld elements.").replacingOccurrences(of: "%lld", with: "\(limit)")275        case .tooDeep(let limit): L("Stacks can be nested %lld levels deep at most.").replacingOccurrences(of: "%lld", with: "\(limit)")276        case .cannotMoveIntoItself: L("A stack cannot be moved into itself.")277        case .cannotRemoveRoot: L("The root stack cannot be removed.")278        default: L("This change is not possible.")279        }280    }281282    private var outline: some View {283        List(selection: $model.selectedNodeID) {284            Section {285                ForEach(PlaygroundOutlineRow.rows(for: model.playground.root)) { row in286                    outlineRow(row)287                        .tag(row.id)288                        .draggable(row.id.uuidString)289                        .dropDestination(for: String.self) { items, _ in290                            guard let moved = items.first.flatMap(UUID.init(uuidString:)), moved != row.id else { return false }291                            let before = model.playground292                            if row.node.isStack {293                                perform { try $0.move(moved, into: row.id) }294                            } else if let location = model.playground.location(of: row.id) {295                                perform { try $0.move(moved, into: location.parent, at: location.index) }296                            }297                            return model.playground != before298                        }299                }300            } header: {301                Text(L("Structure"))302            } footer: {303                Text(L("%1$lld of %2$lld elements. Drag rows to rearrange on iPad and Mac, or use the move buttons.")304                    .replacingOccurrences(of: "%1$lld", with: "\(model.playground.root.nodeCount)")305                    .replacingOccurrences(of: "%2$lld", with: "\(PlaygroundDocument.maximumNodes)"))306            }307308            Section(L("Add")) {309                Menu {310                    ForEach(PlaygroundAxis.allCases, id: \.self) { axis in311                        Button(axisTitle(axis)) {312                            let node = PlaygroundNode.stack(axis)313                            perform { try $0.insert(node, into: insertionTarget) }314                            model.selectedNodeID = node.id315                        }316                    }317                } label: {318                    Label(L("Add a stack"), systemImage: "square.stack.3d.up")319                }320                .accessibilityIdentifier("add-stack")321                Menu {322                    ForEach(GlassComponentCategory.allCases, id: \.self) { category in323                        let items = model.catalog.composable.filter { $0.info.category == category }324                        if !items.isEmpty {325                            Menu(category.title) {326                                ForEach(items) { descriptor in327                                    Button(descriptor.info.name) {328                                        let node = PlaygroundNode.component(descriptor.id)329                                        perform { try $0.insert(node, into: insertionTarget) }330                                        model.selectedNodeID = node.id331                                    }332                                }333                            }334                        }335                    }336                } label: {337                    Label(L("Add a component"), systemImage: "plus.square")338                }339                .accessibilityIdentifier("add-component")340            }341342            if let node = selectedNode {343                Section(L("Selected element")) {344                    nodeEditor(node)345                    if node.id != model.playground.root.id {346                        HStack {347                            Button(L("Move up"), systemImage: "arrow.up") { shift(node.id, by: -1) }348                            Button(L("Move down"), systemImage: "arrow.down") { shift(node.id, by: 1) }349                            Spacer()350                            Button(L("Remove"), systemImage: "trash", role: .destructive) {351                                perform { _ = try $0.remove(node.id) }352                                model.selectedNodeID = nil353                            }354                        }355                        .buttonStyle(.borderless)356                        .labelStyle(.iconOnly)357                    }358                }359            }360        }361        .accessibilityIdentifier("playground-outline")362    }363364    private func axisTitle(_ axis: PlaygroundAxis) -> String {365        switch axis {366        case .vertical: L("Vertical stack")367        case .horizontal: L("Horizontal stack")368        case .depth: L("Layered stack")369        }370    }371372    private func outlineRow(_ row: PlaygroundOutlineRow) -> some View {373        HStack(spacing: 8) {374            switch row.node.kind {375            case .stack(let axis, _, _):376                Image(systemName: axis == .vertical ? "rectangle.split.1x2" : axis == .horizontal ? "rectangle.split.2x1" : "square.stack").accessibilityHidden(true)377                Text(axisTitle(axis))378                Spacer(minLength: 0)379                Text(verbatim: "\(row.node.children.count)").font(.caption).foregroundStyle(.secondary).accessibilityHidden(true)380            case .component(let id, _):381                Image(systemName: model.catalog.descriptor(id)?.info.category.symbol ?? "questionmark.square").accessibilityHidden(true)382                Text(verbatim: model.catalog.descriptor(id)?.info.name ?? id)383            }384        }385        .padding(.leading, CGFloat(row.level) * 16)386        .contentShape(Rectangle())387        .accessibilityElement(children: .combine)388        .accessibilityValue(Text(L("Level %lld").replacingOccurrences(of: "%lld", with: "\(row.level + 1)")))389    }390391    @ViewBuilder392    private func nodeEditor(_ node: PlaygroundNode) -> some View {393        switch node.kind {394        case .stack(let axis, let spacing, let alignment):395            Picker(L("Direction"), selection: Binding(get: { axis }, set: { value in perform { try $0.updateStack(node.id, axis: value, spacing: spacing, alignment: alignment) } })) {396                ForEach(PlaygroundAxis.allCases, id: \.self) { Text(axisTitle($0)).tag($0) }397            }398            Picker(L("Spacing"), selection: Binding(get: { spacing }, set: { value in perform { try $0.updateStack(node.id, axis: axis, spacing: value, alignment: alignment) } })) {399                ForEach(GlassSpacingStep.allCases, id: \.self) { step in400                    Text(verbatim: "\(step.rawValue) · \(Int(GlassSpacing.standard[step]))").tag(step)401                }402            }403            Picker(L("Alignment"), selection: Binding(get: { alignment }, set: { value in perform { try $0.updateStack(node.id, axis: axis, spacing: spacing, alignment: value) } })) {404                Text(L("Leading")).tag(PlaygroundAlignment.leading)405                Text(L("Centre")).tag(PlaygroundAlignment.center)406                Text(L("Trailing")).tag(PlaygroundAlignment.trailing)407            }408        case .component(let id, let stored):409            if let descriptor = model.catalog.descriptor(id) {410                InspectorView(values: Binding(411                    get: { InspectorValues(fields: descriptor.fields, values: stored) },412                    set: { values in perform { try $0.updateValues(node.id, values: values.dictionary) } }413                ))414                .frame(minHeight: CGFloat(max(descriptor.fields.count, 1)) * 58 + 80)415                .scrollDisabled(true)416                .listRowInsets(EdgeInsets())417            }418        }419    }420}421
Files main
Menu

Theme