SPB Git

Repository Public MIT

CatalogViews.swift 17.8 KB 443 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Views/CatalogViews.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 SPGlassKit4344extension GlassComponentCategory {45    var title: String {46        switch self {47        case .navigation: L("Navigation")48        case .buttons: L("Buttons")49        case .forms: L("Forms")50        case .selection: L("Selection")51        case .containers: L("Containers")52        case .feedback: L("Feedback")53        case .data: L("Data")54        case .media: L("Media")55        case .maps: L("Maps")56        case .ai: L("AI interfaces")57        }58    }5960    var symbol: String {61        switch self {62        case .navigation: "sidebar.left"63        case .buttons: "button.horizontal"64        case .forms: "character.cursor.ibeam"65        case .selection: "switch.2"66        case .containers: "rectangle.on.rectangle"67        case .feedback: "bell"68        case .data: "tablecells"69        case .media: "play.rectangle"70        case .maps: "map"71        case .ai: "sparkles"72        }73    }74}7576extension GlassComponentKind {77    var title: String {78        switch self {79        case .nativeWrapper: L("System control")80        case .customGlass: L("Custom glass")81        case .contentComponent: L("Content")82        case .primitive: L("Primitive")83        }84    }8586    var explanation: String {87        switch self {88        case .nativeWrapper: L("Drawn by the system. GlassKit configures it and leaves the glass to the system.")89        case .customGlass: L("Draws its own Liquid Glass surface, with an opaque form for Reduce Transparency.")90        case .contentComponent: L("Content on an opaque, readable surface. Glass is kept for controls.")91        case .primitive: L("Shared building block.")92        }93    }9495    var symbol: String {96        switch self {97        case .nativeWrapper: "apple.logo"98        case .customGlass: "circle.lefthalf.filled"99        case .contentComponent: "doc.text"100        case .primitive: "cube"101        }102    }103}104105/// One row of the catalogue list (split view and favourites).106struct ComponentRow: View {107    let descriptor: ComponentDescriptor108    let isFavorite: Bool109110    var body: some View {111        HStack(spacing: 12) {112            StudioIconTile(systemImage: descriptor.info.category.symbol, tint: descriptor.info.category.tint, size: 30)113            VStack(alignment: .leading, spacing: 2) {114                Text(verbatim: descriptor.info.name).font(.body.weight(.medium))115                Text(descriptor.info.kind.title).font(.caption).foregroundStyle(.secondary)116            }117            Spacer(minLength: 0)118            if isFavorite {119                Image(systemName: "star.fill").font(.caption).foregroundStyle(.yellow).accessibilityLabel(Text(L("Favourite")))120            }121        }122        .padding(.vertical, 2)123        .accessibilityElement(children: .combine)124        .accessibilityIdentifier("component-\(descriptor.id)")125    }126}127128/// The searchable, filterable list of components.129struct CatalogListView: View {130    @Bindable var model: StudioModel131    var showsSelection = true132133    @ViewBuilder134    private var rows: some View {135        let results = model.filteredDescriptors136        if results.isEmpty {137            ContentUnavailableView.search(text: model.filter.query)138        }139        ForEach(GlassComponentCategory.allCases, id: \.self) { category in140            let items = results.filter { $0.info.category == category }141            if !items.isEmpty {142                Section(category.title) {143                    ForEach(items) { descriptor in144                        if showsSelection {145                            ComponentRow(descriptor: descriptor, isFavorite: model.favorites.contains(descriptor.id))146                                .tag(descriptor.id)147                        } else {148                            NavigationLink(value: descriptor.id) {149                                ComponentRow(descriptor: descriptor, isFavorite: model.favorites.contains(descriptor.id))150                            }151                        }152                    }153                }154            }155        }156    }157158    var body: some View {159        Group {160            if showsSelection {161                // Split view: the list drives the detail column through the selection.162                List(selection: $model.selectedComponentID) { rows }163            } else {164                // Navigation stack: rows are plain navigation links. A selection binding here would swallow taps.165                List { rows }166            }167        }168        .searchable(text: $model.filter.query, prompt: Text(L("Name, category or type")))169        .toolbar {170            ToolbarItem(placement: .primaryAction) { CatalogFilterMenu(filter: $model.filter) }171        }172        .accessibilityIdentifier("catalog-list")173    }174}175176struct CatalogFilterMenu: View {177    @Binding var filter: CatalogFilter178179    var body: some View {180        Menu {181            Picker(L("Category"), selection: $filter.category) {182                Text(L("All categories")).tag(GlassComponentCategory?.none)183                ForEach(GlassComponentCategory.allCases, id: \.self) { Text($0.title).tag(GlassComponentCategory?.some($0)) }184            }185            Picker(L("Type"), selection: $filter.kind) {186                Text(L("All types")).tag(GlassComponentKind?.none)187                ForEach([GlassComponentKind.nativeWrapper, .customGlass, .contentComponent], id: \.self) { Text($0.title).tag(GlassComponentKind?.some($0)) }188            }189            Picker(L("Platform"), selection: $filter.platform) {190                Text(L("All platforms")).tag(GlassPlatform?.none)191                ForEach(GlassPlatform.allCases, id: \.self) { Text(verbatim: $0.rawValue).tag(GlassPlatform?.some($0)) }192            }193            Toggle(L("Favourites only"), isOn: $filter.favoritesOnly)194            if filter.isActive {195                Button(L("Clear filters"), systemImage: "xmark.circle") { filter = CatalogFilter() }196            }197        } label: {198            Label(L("Filter"), systemImage: filter.category != nil || filter.kind != nil || filter.platform != nil || filter.favoritesOnly ? "line.3.horizontal.decrease.circle.fill" : "line.3.horizontal.decrease.circle")199        }200        .accessibilityIdentifier("catalog-filter")201    }202}203204enum DetailTab: String, CaseIterable, Identifiable {205    case preview, code, documentation206    var id: String { rawValue }207    var title: String {208        switch self {209        case .preview: L("Adjust")210        case .code: L("Code")211        case .documentation: L("Documentation")212        }213    }214}215216/// One component: its live preview first, then variants, parameters, code and documentation.217struct ComponentDetailView: View {218    @Bindable var model: StudioModel219    let descriptor: ComponentDescriptor220    @State private var values: InspectorValues221    @State private var tab: DetailTab222    #if os(macOS)223    @State private var showsInspector = true224    #else225    // An iPad in portrait has no room for a fourth column: parameters start inline, the column is on demand.226    @State private var showsInspector = false227    #endif228    @State private var variantID: String?229    @State private var showsLivePreview = false230    @Environment(\.horizontalSizeClass) private var sizeClass231232    init(model: StudioModel, descriptor: ComponentDescriptor) {233        self.model = model234        self.descriptor = descriptor235        let variant = descriptor.variants.first { $0.id == model.launch.variantID }236        _values = State(initialValue: variant.map(descriptor.values(for:)) ?? descriptor.defaultValues)237        _variantID = State(initialValue: variant?.id)238        _tab = State(initialValue: DetailTab(rawValue: model.launch.detailTab ?? "") ?? .preview)239    }240241    private var installSnippet: String {242        "spglass add \(descriptor.id)"243    }244245    private var packageSnippet: String {246        ".package(url: \"\(GlassKitInfo.repositoryURL).git\", from: \"\(GlassKitInfo.version)\")\n// target dependency: .product(name: \"SPGlassKit\", package: \"sp-glasskit\")\n\nimport SPGlassKit"247    }248249    private var isRegular: Bool { sizeClass == .regular }250251    var body: some View {252        ScrollView {253            VStack(alignment: .leading, spacing: 22) {254                PreviewCanvas(configuration: model.preview, theme: model.previewTheme, minHeight: isRegular ? 380 : 320, prefersStage: descriptor.prefersStage || descriptor.isolatesNavigation(for: values)) {255                    if descriptor.isolatesNavigation(for: values) {256                        // A navigation container owns the screen: it runs full screen, apart from the Studio's bars.257                        NavigationSchematic(componentID: descriptor.id)258                            .frame(height: 300)259                            .overlay(alignment: .bottom) {260                                Button { showsLivePreview = true } label: {261                                    Label(L("Run full screen"), systemImage: "play.fill").padding(.horizontal, 6)262                                }263                                .buttonStyle(.glassProminent)264                                .controlSize(.large)265                                .padding(.bottom, -8)266                                .accessibilityIdentifier("run-live-preview")267                            }268                            .padding(.bottom, 20)269                    } else {270                        descriptor.preview(values)271                    }272                }273                .accessibilityIdentifier("component-preview")274275                if !descriptor.variants.isEmpty { variants }276                header277278                Picker(L("Section"), selection: $tab) {279                    ForEach(DetailTab.allCases) { Text($0.title).tag($0) }280                }281                .pickerStyle(.segmented)282                .labelsHidden()283                .accessibilityIdentifier("detail-tabs")284285                switch tab {286                case .preview: adjustSection287                case .code: codeSection288                case .documentation: documentationSection289                }290            }291            .padding(.horizontal, 20)292            .padding(.top, 8)293            .padding(.bottom, 32)294            .frame(maxWidth: 920, alignment: .leading)295            .frame(maxWidth: .infinity)296        }297        .background(StudioPalette.page)298        .navigationTitle(Text(verbatim: descriptor.info.name))299        #if os(iOS)300        .navigationBarTitleDisplayMode(.inline)301        #endif302        .toolbar {303            ToolbarItemGroup(placement: .primaryAction) {304                Button(model.favorites.contains(descriptor.id) ? L("Remove from favourites") : L("Add to favourites"),305                       systemImage: model.favorites.contains(descriptor.id) ? "star.fill" : "star") {306                    model.favorites.toggle(descriptor.id)307                }308                .accessibilityIdentifier("toggle-favorite")309                PreviewOptionsMenu(configuration: $model.preview, themes: model.themes.allThemes)310                if isRegular {311                    Button(L("Parameters"), systemImage: "sidebar.trailing") { showsInspector.toggle() }312                }313            }314        }315        #if os(iOS)316        .fullScreenCover(isPresented: $showsLivePreview) { livePreview }317        #else318        .sheet(isPresented: $showsLivePreview) { livePreview.frame(minWidth: 820, minHeight: 600) }319        #endif320        .inspector(isPresented: Binding(get: { showsInspector && isRegular && tab != .documentation }, set: { showsInspector = $0 })) {321            InspectorView(values: $values)322                .inspectorColumnWidth(min: 240, ideal: 300, max: 380)323        }324    }325326    /// The real component on its own screen, with the current parameters, theme and appearance.327    private var livePreview: some View {328        descriptor.preview(values)329            .glassTheme(model.previewTheme)330            .preferredColorScheme(model.preview.colorScheme)331            .safeAreaInset(edge: .bottom) {332                Button { showsLivePreview = false } label: {333                    Label(L("Close preview"), systemImage: "xmark").padding(.horizontal, 6)334                }335                .buttonStyle(.glass)336                .controlSize(.large)337                .padding(.bottom, 64)338                .accessibilityIdentifier("close-live-preview")339            }340    }341342    private var header: some View {343        VStack(alignment: .leading, spacing: 10) {344            HStack(spacing: 8) {345                StudioIconTile(systemImage: descriptor.info.category.symbol, tint: descriptor.info.category.tint, size: 22)346                Text(verbatim: "\(descriptor.info.category.title) · \(descriptor.info.kind.title)").studioEyebrow()347            }348            Text(verbatim: descriptor.info.name)349                .font(.system(.title, design: .default, weight: .bold))350                .accessibilityAddTraits(.isHeader)351            Text(verbatim: descriptor.info.summary)352                .font(.body)353                .foregroundStyle(.secondary)354                .fixedSize(horizontal: false, vertical: true)355            ScrollView(.horizontal) {356                HStack(spacing: 8) {357                    Label { Text(verbatim: "iOS · iPadOS · macOS 26") } icon: { Image(systemName: "macbook.and.iphone") }.studioChip()358                    Text(verbatim: descriptor.info.module).font(.caption.monospaced()).studioChip()359                    Text(verbatim: descriptor.id).font(.caption.monospaced()).studioChip()360                }361            }362            .scrollIndicators(.hidden)363            Label(descriptor.info.kind.explanation, systemImage: descriptor.info.kind.symbol)364                .font(.footnote)365                .foregroundStyle(.secondary)366        }367    }368369    private var variants: some View {370        ScrollView(.horizontal) {371            HStack(spacing: 8) {372                StudioChip(title: L("Default"), isSelected: variantID == nil && values.isDefault) {373                    values = descriptor.defaultValues; variantID = nil374                }375                ForEach(descriptor.variants) { variant in376                    StudioChip(title: L(variant.title), isSelected: variantID == variant.id) {377                        values = descriptor.values(for: variant); variantID = variant.id378                    }379                    .accessibilityIdentifier("variant-\(variant.id)")380                }381            }382            .padding(.horizontal, 20)383            .padding(.vertical, 2)384        }385        .scrollIndicators(.hidden)386        .padding(.horizontal, -20)387        .accessibilityLabel(Text(L("Variants")))388    }389390    private var adjustSection: some View {391        VStack(alignment: .leading, spacing: 22) {392            if !isRegular || !showsInspector {393                VStack(alignment: .leading, spacing: 10) {394                    Text(L("Parameters")).font(.headline)395                    InspectorCard(values: $values)396                }397            }398            CodeView(descriptor.snippet(values), title: L("Code for this preview"))399        }400    }401402    private var codeSection: some View {403        VStack(alignment: .leading, spacing: 22) {404            CodeView(descriptor.snippet(values), title: L("Code for this preview"))405            CodeView(installSnippet, title: L("Install as source with the CLI"))406            CodeView(packageSnippet, title: L("Or use the Swift package"))407            if let example = model.exampleSource(for: descriptor.id) {408                CodeView(example, title: L("Complete example"))409            }410        }411    }412413    @ViewBuilder414    private var documentationSection: some View {415        if let markdown = StudioDocs.markdown(for: descriptor.id) {416            MarkdownDocView(markdown: markdown)417                .padding(18)418                .frame(maxWidth: .infinity, alignment: .leading)419                .studioCard()420        } else {421            ContentUnavailableView(L("No documentation bundled"), systemImage: "doc.questionmark")422        }423    }424}425426extension View {427    func studioChip() -> some View {428        font(.caption)429            .padding(.horizontal, 10)430            .padding(.vertical, 5)431            .background(StudioPalette.card, in: Capsule())432            .overlay(Capsule().strokeBorder(.primary.opacity(0.08), lineWidth: 1))433    }434}435436extension StudioModel {437    /// The source of the compiled example of a component, bundled with the Studio.438    func exampleSource(for componentID: String) -> String? {439        guard let url = Bundle.module.url(forResource: "example-\(componentID)", withExtension: "txt") else { return nil }440        return try? String(contentsOf: url, encoding: .utf8)441    }442}443
Files main
Menu

Theme