SPB Git

Repository Public MIT

ContainersDescriptors.swift 19.1 KB 401 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Descriptors/ContainersDescriptors.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 ComponentCatalog {45    static var containerDescriptors: [ComponentDescriptor] {46        [glassCard, glassPanel, glassSheet, glassPopover, glassAccordion]47    }4849    private static func call(_ name: String, _ arguments: [String]) -> String {50        arguments.isEmpty ? name : "\(name)(\(arguments.joined(separator: ", ")))"51    }5253    // MARK: GlassCard5455    private static let cardPaddings: [GlassSpacingStep] = [.xs, .sm, .md, .lg]5657    private static var glassCard: ComponentDescriptor {58        ComponentDescriptor(59            "glass-card",60            fields: [61                .text("title", "Title", default: "Monthly rent", maxLength: 60),62                .choice("style", "Style", options: [.init("opaque", "Opaque"), .init("floating", "Floating")]),63                .choice("padding", "Padding", options: cardPaddings.map { .init($0.rawValue, $0.rawValue) }, default: "md"),64                .toggle("tappable", "Tappable"),65            ],66            variants: [67                ComponentVariant("floating", "Floating", ["style": .choice("floating")]),68                ComponentVariant("tappable", "Tappable", ["style": .choice("floating"), "tappable": .bool(true), "title": .text("3 listings nearby")]),69                ComponentVariant("compact", "Compact", ["padding": .choice("xs")]),70            ],71            isComposable: true,72            preview: { values in73                CardPreview(74                    title: values.text("title"),75                    style: GlassCardStyle(rawValue: values.choice("style")) ?? .opaque,76                    padding: GlassSpacingStep(rawValue: values.choice("padding")) ?? .md,77                    isTappable: values.bool("tappable")78                )79            },80            snippet: { values in81                var arguments: [String] = []82                if !values.text("title").isEmpty { arguments.append(SwiftLiteral.string(values.text("title"))) }83                if values.choice("style") == "floating" { arguments.append("style: .floating") }84                if values.choice("padding") != "md" { arguments.append("padding: \(SwiftLiteral.enumCase(values.choice("padding"), fallback: "md"))") }85                if values.bool("tappable") { arguments.append("action: { }") }86                return call("GlassCard", arguments) + " {\n    Text(\"1,450 $\").font(.title2)\n    Text(\"Sample listing\").foregroundStyle(.secondary)\n}"87            }88        )89    }9091    // MARK: GlassPanel9293    private static var glassPanel: ComponentDescriptor {94        ComponentDescriptor(95            "glass-panel",96            fields: [97                .text("title", "Title", default: "Layers", maxLength: 40),98                .toggle("closable", "Close button", default: true),99                .toggle("resizable", "Resizable (macOS)", default: true),100                .number("width", "Width", in: 240...480, step: 20, default: 300),101                .number("height", "Height", in: 160...360, step: 20, default: 220),102            ],103            variants: [104                ComponentVariant("content", "Sized to content", ["resizable": .bool(false)]),105                ComponentVariant("permanent", "Without close button", ["closable": .bool(false)]),106                ComponentVariant("wide", "Wide", ["width": .number(440), "height": .number(200)]),107            ],108            preview: { values in109                PanelPreview(110                    title: values.text("title"),111                    closable: values.bool("closable"),112                    resizable: values.bool("resizable"),113                    size: CGSize(width: values.number("width"), height: values.number("height"))114                )115                .id(values)116            },117            snippet: { values in118                var arguments = [SwiftLiteral.string(values.text("title"))]119                if values.bool("resizable") {120                    arguments.append("size: .constant(CGSize(width: \(SwiftLiteral.number(values.number("width"))), height: \(SwiftLiteral.number(values.number("height")))))")121                }122                if values.bool("closable") { arguments.append("onClose: { }") }123                let hint = values.bool("resizable") ? "// Bind size to your own @State to let the user resize the panel on macOS.\n" : ""124                return hint + call("GlassPanel", arguments) + " {\n    Toggle(\"Transit\", isOn: .constant(true))\n    Toggle(\"Traffic\", isOn: .constant(false))\n}"125            }126        )127    }128129    // MARK: GlassSheet130131    private static func sheetDetents(_ values: InspectorValues) -> [GlassSheetDetent] {132        switch values.choice("detents") {133        case "halfAndFull": [.medium, .large]134        case "fraction": [.fraction(0.4), .large]135        default: [.large]136        }137    }138139    private static var glassSheet: ComponentDescriptor {140        ComponentDescriptor(141            "glass-sheet",142            fields: [143                .text("title", "Title", default: "Filters", maxLength: 40),144                .choice("detents", "Detents", options: [.init("large", "Large"), .init("halfAndFull", "Medium and large"), .init("fraction", "40 % and large")]),145                .toggle("dragIndicator", "Drag indicator", default: true),146                .toggle("closeButton", "Close button", default: true),147                .toggle("locked", "Disable swipe to dismiss"),148            ],149            variants: [150                ComponentVariant("half", "Medium and large", ["detents": .choice("halfAndFull")]),151                ComponentVariant("locked", "Locked", ["detents": .choice("fraction"), "locked": .bool(true), "title": .text("Terms of use")]),152            ],153            preview: { values in154                SheetPreview(155                    title: values.text("title"),156                    configuration: GlassSheetConfiguration(157                        detents: sheetDetents(values),158                        showsDragIndicator: values.bool("dragIndicator"),159                        showsCloseButton: values.bool("closeButton"),160                        isInteractiveDismissDisabled: values.bool("locked")161                    )162                )163            },164            snippet: { values in165                var configuration: [String] = []166                switch values.choice("detents") {167                case "halfAndFull": configuration.append("detents: [.medium, .large]")168                case "fraction": configuration.append("detents: [.fraction(0.4), .large]")169                default: break170                }171                if !values.bool("dragIndicator") { configuration.append("showsDragIndicator: false") }172                if !values.bool("closeButton") { configuration.append("showsCloseButton: false") }173                if values.bool("locked") { configuration.append("isInteractiveDismissDisabled: true") }174                var arguments = ["isPresented: .constant(true)"]175                if !values.text("title").isEmpty { arguments.append("title: \(SwiftLiteral.string(values.text("title")))") }176                if configuration == ["detents: [.medium, .large]"] {177                    arguments.append("configuration: .halfAndFull")178                } else if !configuration.isEmpty {179                    arguments.append("configuration: GlassSheetConfiguration(\(configuration.joined(separator: ", ")))")180                }181                return "// Bind isPresented to your own @State and set it from the button.\nGlassButton(\"Show sheet\", systemImage: \"rectangle.bottomhalf.inset.filled\") { }\n    .glassSheet(\(arguments.joined(separator: ", "))) {\n        Text(\"Sample sheet content.\")\n            .padding()\n    }"182            }183        )184    }185186    // MARK: GlassPopover187188    private static func popoverEdge(_ values: InspectorValues) -> Edge? {189        switch values.choice("arrowEdge") {190        case "top": .top191        case "bottom": .bottom192        case "leading": .leading193        case "trailing": .trailing194        default: nil195        }196    }197198    private static var glassPopover: ComponentDescriptor {199        ComponentDescriptor(200            "glass-popover",201            fields: [202                .text("title", "Title", default: "Price details", maxLength: 40),203                .text("message", "Message", default: "Sample price, taxes included.", maxLength: 160),204                .choice("arrowEdge", "Arrow edge", options: [.init("automatic", "Automatic"), .init("top", "Top"), .init("bottom", "Bottom"), .init("leading", "Leading"), .init("trailing", "Trailing")]),205                .choice("adaptation", "Compact adaptation", options: [.init("automatic", "Automatic"), .init("popover", "Popover"), .init("sheet", "Sheet"), .init("fullScreenCover", "Full screen cover")]),206            ],207            variants: [208                ComponentVariant("top", "Arrow on top", ["arrowEdge": .choice("top"), "adaptation": .choice("popover")]),209                ComponentVariant("sheet", "Sheet on compact widths", ["adaptation": .choice("sheet"), "title": .text("Help"), "message": .text("On a compact width this popover becomes a sheet with a close button.")]),210            ],211            preview: { values in212                PopoverPreview(213                    title: values.text("title"),214                    message: values.text("message"),215                    arrowEdge: popoverEdge(values),216                    adaptation: GlassPopoverAdaptation(rawValue: values.choice("adaptation")) ?? .automatic217                )218            },219            snippet: { values in220                var arguments = ["isPresented: .constant(true)"]221                if !values.text("title").isEmpty { arguments.append("title: \(SwiftLiteral.string(values.text("title")))") }222                if values.choice("arrowEdge") != "automatic" { arguments.append("arrowEdge: \(SwiftLiteral.enumCase(values.choice("arrowEdge"), fallback: "top"))") }223                if values.choice("adaptation") != "automatic" { arguments.append("compactAdaptation: \(SwiftLiteral.enumCase(values.choice("adaptation"), fallback: "automatic"))") }224                return "// Bind isPresented to your own @State and set it from the button.\nGlassButton(\"Show popover\", systemImage: \"info.circle\") { }\n    .glassPopover(\(arguments.joined(separator: ", "))) {\n        Text(verbatim: \(SwiftLiteral.string(values.text("message"))))\n            .padding()\n            .frame(minWidth: 220, alignment: .leading)\n    }"225            }226        )227    }228229    // MARK: GlassAccordion230231    /// Sample sections. The kit has no dedicated section type, so the sample reuses a small identifiable232    /// item of the kit; a host passes its own `Identifiable` model.233    fileprivate static let accordionSections = [234        GlassBreadcrumbItem(id: "delivery", title: "Delivery", systemImage: "shippingbox"),235        GlassBreadcrumbItem(id: "returns", title: "Returns", systemImage: "arrow.uturn.backward"),236        GlassBreadcrumbItem(id: "payment", title: "Payment", systemImage: "creditcard"),237        GlassBreadcrumbItem(id: "support", title: "Support", systemImage: "questionmark.circle"),238    ]239240    private static var glassAccordion: ComponentDescriptor {241        ComponentDescriptor(242            "glass-accordion",243            fields: [244                .choice("mode", "Mode", options: [.init("multiple", "Several sections at once"), .init("single", "One section at a time")]),245                .number("sections", "Sections", in: 2...4, default: 3),246                .toggle("expanded", "First section open", default: true),247            ],248            variants: [249                ComponentVariant("single", "One section at a time", ["mode": .choice("single")]),250                ComponentVariant("collapsed", "All collapsed", ["expanded": .bool(false)]),251            ],252            isComposable: true,253            preview: { values in254                AccordionPreview(255                    sections: Array(accordionSections.prefix(Int(values.number("sections")))),256                    mode: values.choice("mode") == "single" ? .single : .multiple,257                    firstExpanded: values.bool("expanded")258                )259                .id(values)260            },261            snippet: { values in262                let sections = accordionSections.prefix(Int(values.number("sections"))).map {263                    "    GlassBreadcrumbItem(id: \(SwiftLiteral.string($0.id)), title: \(SwiftLiteral.string($0.title)), systemImage: \(SwiftLiteral.string($0.systemImage ?? "circle"))),"264                }.joined(separator: "\n")265                var arguments = ["expanded: .constant(\(values.bool("expanded") ? "[\"delivery\"]" : "[]"))"]266                if values.choice("mode") == "single" { arguments.append("mode: .single") }267                return "// Sections are any Identifiable values of yours. Bind expanded to your own @State.\nGlassAccordion([\n\(sections)\n], \(arguments.joined(separator: ", "))) { section in\n    Label(section.title, systemImage: section.systemImage ?? \"circle\")\n} content: { section in\n    Text(verbatim: \"Sample details for \\(section.title).\")\n}"268            }269        )270    }271}272273// MARK: - Preview support274275/// A card with sample content; when it is tappable, it counts its taps so that the action is visible.276private struct CardPreview: View {277    let title: String278    let style: GlassCardStyle279    let padding: GlassSpacingStep280    let isTappable: Bool281    @State private var tapCount = 0282283    private var action: (@MainActor () -> Void)? {284        guard isTappable else { return nil }285        return { tapCount += 1 }286    }287288    var body: some View {289        if title.isEmpty {290            GlassCard(style: style, padding: padding, action: action) { content }291        } else {292            GlassCard(verbatim: title, style: style, padding: padding, action: action) { content }293        }294    }295296    @ViewBuilder private var content: some View {297        Text(verbatim: "1,450 $").font(.title2)298        Text(verbatim: L("Sample listing")).foregroundStyle(.secondary)299        if tapCount > 0 {300            Text(verbatim: StudioL10n.string("Action performed %d times", tapCount)).font(.caption).foregroundStyle(.secondary)301        }302    }303}304305/// A panel over a coloured backdrop, with real state for its size, its toggles and its close button.306private struct PanelPreview: View {307    let title: String308    let closable: Bool309    let resizable: Bool310    @State private var size: CGSize311    @State private var isShown = true312    @State private var showsTransit = true313    @State private var showsTraffic = false314315    init(title: String, closable: Bool, resizable: Bool, size: CGSize) {316        self.title = title317        self.closable = closable318        self.resizable = resizable319        _size = State(initialValue: size)320    }321322    private var onClose: (@MainActor () -> Void)? {323        guard closable else { return nil }324        return { isShown = false }325    }326327    var body: some View {328        ZStack {329            LinearGradient(colors: [.teal, .indigo], startPoint: .topLeading, endPoint: .bottomTrailing)330                .accessibilityHidden(true)331            if isShown {332                GlassPanel(title: Text(verbatim: title), size: resizable ? $size : nil, onClose: onClose) {333                    Toggle(L("Transit"), isOn: $showsTransit)334                    Toggle(L("Traffic"), isOn: $showsTraffic)335                }336                .padding()337            } else {338                GlassButton(verbatim: L("Show panel"), systemImage: "square.3.layers.3d") { isShown = true }339            }340        }341        .frame(minHeight: 320)342    }343}344345/// A button that presents the real sheet. The content always offers a way out, even when the close button346/// is hidden and swiping is disabled.347private struct SheetPreview: View {348    let title: String349    let configuration: GlassSheetConfiguration350    @State private var isPresented = false351352    var body: some View {353        GlassButton(verbatim: L("Show sheet"), systemImage: "rectangle.bottomhalf.inset.filled") { isPresented = true }354            .glassSheet(isPresented: $isPresented, title: title.isEmpty ? nil : LocalizedStringKey(title), configuration: configuration) {355                VStack(spacing: 16) {356                    Text(verbatim: L("Sample sheet content."))357                    GlassButton(verbatim: L("Close preview")) { isPresented = false }358                }359                .padding()360                .frame(maxWidth: .infinity, minHeight: 160)361            }362    }363}364365private struct PopoverPreview: View {366    let title: String367    let message: String368    let arrowEdge: Edge?369    let adaptation: GlassPopoverAdaptation370    @State private var isPresented = false371372    var body: some View {373        GlassButton(verbatim: L("Show popover"), systemImage: "info.circle") { isPresented = true }374            .glassPopover(isPresented: $isPresented, title: title.isEmpty ? nil : LocalizedStringKey(title), arrowEdge: arrowEdge, compactAdaptation: adaptation) {375                Text(verbatim: message)376                    .padding()377                    .frame(minWidth: 220, alignment: .leading)378            }379    }380}381382private struct AccordionPreview: View {383    let sections: [GlassBreadcrumbItem<String>]384    let mode: GlassAccordionMode385    @State private var expanded: Set<String>386387    init(sections: [GlassBreadcrumbItem<String>], mode: GlassAccordionMode, firstExpanded: Bool) {388        self.sections = sections389        self.mode = mode390        _expanded = State(initialValue: firstExpanded ? Set(sections.prefix(1).map(\.id)) : [])391    }392393    var body: some View {394        GlassAccordion(sections, expanded: $expanded, mode: mode) { section in395            Label(L(section.title), systemImage: section.systemImage ?? "circle")396        } content: { section in397            Text(verbatim: StudioL10n.string("Sample details for %@.", L(section.title)))398        }399    }400}401
Files main
Menu

Theme