SPB Git

Repository Public MIT

StudioRootView.swift 11.9 KB 254 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Views/StudioRootView.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 SPGlassKit4344/// The Studio's root: a native tab bar on iPhone, a split view with sidebar on iPad and Mac.45public struct StudioRootView: View {46    @State private var model: StudioModel47    @AppStorage("studio.language") private var language = ""48    @Environment(\.horizontalSizeClass) private var sizeClass4950    public init(model: StudioModel = StudioModel()) {51        _model = State(initialValue: model)52        if let forced = model.launch.language { StudioL10n.setLanguage(forced) }53    }5455    public var body: some View {56        Group {57            if model.launch.captureOnly, let id = model.selectedComponentID, let descriptor = model.catalog.descriptor(id) {58                CaptureView(model: model, descriptor: descriptor)59            } else if sizeClass == .compact {60                CompactRoot(model: model)61            } else {62                RegularRoot(model: model)63            }64        }65        .environment(\.locale, effectiveLanguage.isEmpty ? .current : Locale(identifier: effectiveLanguage))66        .id(effectiveLanguage)67        .onChange(of: language, initial: true) { _, newValue in68            if model.launch.language == nil { StudioL10n.setLanguage(newValue.isEmpty ? nil : newValue) }69        }70        .onOpenURL { model.open(url: $0) }71        .focusedSceneValue(\.studioModel, model)72    }7374    private var effectiveLanguage: String { model.launch.language ?? language }75}7677/// iPhone: one navigation stack per tab, so each tab keeps its own place.78private struct CompactRoot: View {79    @Bindable var model: StudioModel80    @State private var catalogPath: [String] = []8182    var body: some View {83        TabView(selection: $model.section) {84            Tab(StudioSection.catalog.title, systemImage: StudioSection.catalog.symbol, value: StudioSection.catalog) {85                NavigationStack(path: $catalogPath) {86                    GalleryView(model: model, usesLinks: true)87                        .navigationTitle(Text(L("Catalogue")))88                        .searchable(text: $model.filter.query, prompt: Text(L("Name, category or type")))89                        .toolbar {90                            ToolbarItem(placement: .primaryAction) { CatalogFilterMenu(filter: $model.filter) }91                        }92                        .navigationDestination(for: String.self) { id in93                            if let descriptor = model.catalog.descriptor(id) {94                                ComponentDetailView(model: model, descriptor: descriptor).id(id)95                            }96                        }97                }98            }99            Tab(StudioSection.themes.title, systemImage: StudioSection.themes.symbol, value: StudioSection.themes) {100                NavigationStack { ThemesView(model: model) }101            }102            Tab(StudioSection.playground.title, systemImage: StudioSection.playground.symbol, value: StudioSection.playground) {103                NavigationStack { PlaygroundView(model: model) }104            }105            Tab(StudioSection.favorites.title, systemImage: StudioSection.favorites.symbol, value: StudioSection.favorites) {106                NavigationStack { FavoritesView(model: model) }107            }108            Tab(StudioSection.settings.title, systemImage: StudioSection.settings.symbol, value: StudioSection.settings) {109                NavigationStack { SettingsView(model: model) }110            }111        }112        .onChange(of: model.section, initial: true) { _, section in113            // The compact layout has no Home tab: Home lives at the top of the catalogue.114            if section == .home { model.section = .catalog }115        }116        .onChange(of: model.selectedComponentID, initial: true) { _, id in117            if let id, catalogPath.last != id { catalogPath = [id] }118        }119        .onChange(of: catalogPath) { _, path in120            if path.isEmpty { model.selectedComponentID = nil }121        }122    }123}124125/// iPad and Mac: sections in the sidebar, the list in the middle, the component on the right.126private struct RegularRoot: View {127    @Bindable var model: StudioModel128    @State private var visibility = NavigationSplitViewVisibility.all129130    var body: some View {131        NavigationSplitView(columnVisibility: $visibility) {132            List(selection: Binding(get: { Optional(model.section) }, set: { if let value = $0 { model.section = value } })) {133                ForEach(StudioSection.allCases) { section in134                    Label(section.title, systemImage: section.symbol)135                        .tag(section)136                        .accessibilityIdentifier("section-\(section.rawValue)")137                }138            }139            .navigationTitle(Text(verbatim: "Glass Studio"))140            .navigationSplitViewColumnWidth(min: 180, ideal: 210, max: 260)141        } content: {142            Group {143                switch model.section {144                case .catalog: CatalogListView(model: model).navigationTitle(Text(L("Catalogue")))145                case .favorites: FavoritesView(model: model)146                case .themes: ThemesView(model: model)147                case .playground: PlaygroundView(model: model, part: .outline)148                case .home, .settings:149                    CatalogListView(model: model).navigationTitle(Text(L("Catalogue")))150                }151            }152            .navigationSplitViewColumnWidth(min: 260, ideal: 320, max: 420)153        } detail: {154            NavigationStack {155                switch model.section {156                case .home: HomeView(model: model)157                case .playground: PlaygroundView(model: model, part: .workspace)158                case .settings: SettingsView(model: model)159                case .themes:160                    ScrollView {161                        VStack(alignment: .leading, spacing: 16) {162                            PreviewCanvas(configuration: model.preview, theme: model.previewTheme, minHeight: 420) { ThemeSampleView() }163                            Text(L("Select a theme to apply it to every preview. Duplicate one to edit it.")).foregroundStyle(.secondary)164                        }165                        .padding(20)166                        .frame(maxWidth: 900)167                        .frame(maxWidth: .infinity)168                    }169                    .background(StudioPalette.page)170                    .navigationTitle(Text(verbatim: model.previewTheme.name))171                case .catalog, .favorites:172                    if let id = model.selectedComponentID, let descriptor = model.catalog.descriptor(id) {173                        ComponentDetailView(model: model, descriptor: descriptor).id(id)174                            .toolbar {175                                ToolbarItem(placement: .navigation) {176                                    Button(L("All components"), systemImage: "square.grid.2x2") { model.selectedComponentID = nil }177                                        .accessibilityIdentifier("show-gallery")178                                }179                            }180                    } else {181                        GalleryView(model: model)182                            .navigationTitle(Text(L("Catalogue")))183                    }184                }185            }186        }187    }188}189190public struct StudioModelKey: FocusedValueKey {191    public typealias Value = StudioModel192}193194extension FocusedValues {195    public var studioModel: StudioModel? {196        get { self[StudioModelKey.self] }197        set { self[StudioModelKey.self] = newValue }198    }199}200201/// Menu commands and keyboard shortcuts for macOS and iPadOS with a keyboard.202public struct StudioCommands: Commands {203    @FocusedValue(\.studioModel) private var model204205    public init() {}206207    public var body: some Commands {208        CommandMenu(L("Go")) {209            ForEach(Array(StudioSection.allCases.enumerated()), id: \.element) { index, section in210                Button(section.title) { model?.section = section }211                    .keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)212                    .disabled(model == nil)213            }214        }215        CommandMenu(L("Preview")) {216            Button(L("Next theme")) { cycleTheme(1) }.keyboardShortcut("]", modifiers: [.command, .shift]).disabled(model == nil)217            Button(L("Previous theme")) { cycleTheme(-1) }.keyboardShortcut("[", modifiers: [.command, .shift]).disabled(model == nil)218            Divider()219            Button(L("Light appearance")) { model?.preview.appearance = .light }.keyboardShortcut("l", modifiers: [.command, .option]).disabled(model == nil)220            Button(L("Dark appearance")) { model?.preview.appearance = .dark }.keyboardShortcut("d", modifiers: [.command, .option]).disabled(model == nil)221            Button(L("System appearance")) { model?.preview.appearance = .system }.keyboardShortcut("0", modifiers: [.command, .option]).disabled(model == nil)222            Divider()223            Button(L("Toggle simulated Reduce Transparency")) { model?.preview.simulateReduceTransparency.toggle() }.keyboardShortcut("t", modifiers: [.command, .option]).disabled(model == nil)224            Button(L("Toggle simulated Reduce Motion")) { model?.preview.simulateReduceMotion.toggle() }.keyboardShortcut("m", modifiers: [.command, .option]).disabled(model == nil)225        }226    }227228    private func cycleTheme(_ offset: Int) {229        guard let model else { return }230        let themes = model.themes.allThemes231        guard let index = themes.firstIndex(where: { $0.id == model.preview.themeID }) else { return }232        model.preview.themeID = themes[(index + offset + themes.count) % themes.count].id233    }234}235236/// A component preview alone on its backdrop, used to produce the documentation captures from the real,237/// running components.238private struct CaptureView: View {239    let model: StudioModel240    let descriptor: ComponentDescriptor241242    var body: some View {243        let variant = descriptor.variants.first { $0.id == model.launch.variantID }244        let values = variant.map(descriptor.values(for:)) ?? descriptor.defaultValues245        ZStack {246            PreviewBackdropView(backdrop: model.preview.resolvedBackdrop(prefersStage: descriptor.prefersStage)).ignoresSafeArea()247            descriptor.preview(values).padding(descriptor.isolatesNavigation(for: values) ? 0 : 20)248        }249        .glassTheme(model.previewTheme)250        .environment(\.colorScheme, model.preview.colorScheme ?? .light)251        .accessibilityIdentifier("capture")252    }253}254
Files main
Menu

Theme