SPB Git

Repository Public MIT

StudioModel.swift 8.1 KB 198 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Model/StudioModel.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 Observation43import SwiftUI44import SPGlassKit4546public enum StudioSection: String, CaseIterable, Identifiable, Sendable {47    case home, catalog, themes, playground, favorites, settings4849    public var id: String { rawValue }5051    public var title: String {52        switch self {53        case .home: L("Home")54        case .catalog: L("Catalogue")55        case .themes: L("Themes")56        case .playground: L("Playground")57        case .favorites: L("Favourites")58        case .settings: L("Settings")59        }60    }6162    public var symbol: String {63        switch self {64        case .home: "house"65        case .catalog: "square.grid.2x2"66        case .themes: "paintpalette"67        case .playground: "hammer"68        case .favorites: "star"69        case .settings: "gearshape"70        }71    }72}7374/// Options read from launch arguments, used by UI tests and for taking captures without driving the interface:75/// `-studioSection catalog -studioComponent glass-button -studioTheme aurora -studioAppearance dark76///  -studioDataDirectory /tmp/x -studioLanguage fr -studioTab code`.77public struct StudioLaunchOptions: Equatable, Sendable {78    public var section: StudioSection?79    public var componentID: String?80    public var themeID: String?81    public var appearance: GlassAppearance?82    public var dataDirectory: URL?83    public var language: String?84    public var detailTab: String?85    public var template: String?86    /// Shows only the preview of `componentID`, full window, for documentation captures.87    public var captureOnly = false88    public var variantID: String?89    public var backdrop: PreviewBackdrop?9091    public init(arguments: [String] = ProcessInfo.processInfo.arguments) {92        func value(_ name: String) -> String? {93            guard let index = arguments.firstIndex(of: "-\(name)"), index + 1 < arguments.count else { return nil }94            return arguments[index + 1]95        }96        section = value("studioSection").flatMap(StudioSection.init(rawValue:))97        componentID = value("studioComponent").flatMap { GlassComponentCatalog.component(id: $0)?.id }98        themeID = value("studioTheme").flatMap { GlassThemeID($0).isValid ? $0 : nil }99        appearance = value("studioAppearance").flatMap(GlassAppearance.init(rawValue:))100        dataDirectory = value("studioDataDirectory").map { URL(fileURLWithPath: $0, isDirectory: true) }101        language = value("studioLanguage").flatMap { ["en", "fr"].contains($0) ? $0 : nil }102        detailTab = value("studioTab")103        template = value("studioTemplate")104        captureOnly = value("studioCapture") == "1"105        variantID = value("studioVariant")106        backdrop = value("studioBackdrop").flatMap(PreviewBackdrop.init(rawValue:))107    }108}109110/// The Studio's state: the embedded catalogue, the local stores and what is currently shown.111/// Nothing here touches the network.112@MainActor113@Observable114public final class StudioModel {115    public let catalog: ComponentCatalog116    public let themes: ThemeStore117    public let favorites: FavoritesStore118    public let launch: StudioLaunchOptions119120    public var section: StudioSection = .home121    public var selectedComponentID: String?122    public var filter = CatalogFilter()123    public var preview = PreviewConfiguration()124    public var playground: PlaygroundDocument {125        didSet { if playground != oldValue { try? playgroundStore.save(playground) } }126    }127    public var selectedNodeID: UUID?128129    private let playgroundStore: AtomicFileStore<PlaygroundDocument>130131    public init(catalog: ComponentCatalog = .standard, launch: StudioLaunchOptions = StudioLaunchOptions()) {132        self.catalog = catalog133        self.launch = launch134        themes = ThemeStore(directory: launch.dataDirectory)135        favorites = FavoritesStore(directory: launch.dataDirectory)136        playgroundStore = AtomicFileStore(url: StudioPaths.dataDirectory(override: launch.dataDirectory).appendingPathComponent("playground.json"), maximumBytes: 512 * 1024)137        let known = catalog.composableIDs138        let template = launch.template.flatMap { name in PlaygroundTemplate.allCases.first { $0.rawValue == name } }139        let fallback = (template ?? .form).document(catalog: catalog)140        let stored = playgroundStore.load(default: fallback) { data in141            try PlaygroundDocument.decode(data, knownComponents: known)142        }.document143        playground = template == nil ? stored : fallback144145        if let section = launch.section { self.section = section }146        if let componentID = launch.componentID { selectedComponentID = componentID; if launch.section == nil { section = .catalog } }147        if let themeID = launch.themeID, themes.theme(GlassThemeID(themeID)) != nil { preview.themeID = GlassThemeID(themeID) }148        if let appearance = launch.appearance { preview.appearance = appearance }149        if let backdrop = launch.backdrop { preview.backdrop = backdrop }150    }151152    /// The theme applied to previews, with the preview's density.153    public var previewTheme: GlassTheme {154        preview.theme(from: themes.theme(preview.themeID) ?? .system)155    }156157    public var filteredDescriptors: [ComponentDescriptor] {158        catalog.search(filter, favorites: Set(favorites.componentIDs))159    }160161    public var favoriteDescriptors: [ComponentDescriptor] {162        favorites.componentIDs.compactMap(catalog.descriptor)163    }164165    public func open(_ componentID: String) {166        guard catalog.descriptor(componentID) != nil else { return }167        selectedComponentID = componentID168        section = .catalog169    }170171    /// Handles `glassstudio://component/<id>`, `glassstudio://theme/<id>` and `glassstudio://section/<name>`.172    @discardableResult173    public func open(url: URL) -> Bool {174        guard url.scheme == "glassstudio", let host = url.host else { return false }175        let value = url.pathComponents.dropFirst().first ?? ""176        switch host {177        case "component":178            guard catalog.descriptor(value) != nil else { return false }179            open(value)180        case "theme":181            guard themes.theme(GlassThemeID(value)) != nil else { return false }182            preview.themeID = GlassThemeID(value)183            section = .themes184        case "section":185            guard let target = StudioSection(rawValue: value) else { return false }186            section = target187        default:188            return false189        }190        return true191    }192193    public func resetPlayground(to template: PlaygroundTemplate) {194        playground = template.document(catalog: catalog)195        selectedNodeID = nil196    }197}198
Files main
Menu

Theme