SPB Git

Repository Public MIT

SelectionDescriptors.swift 15.7 KB 315 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Descriptors/SelectionDescriptors.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 selectionDescriptors: [ComponentDescriptor] {46        [glassToggle, glassSlider, glassPicker, glassSegmentedControl, glassStepper]47    }4849    private static func call(_ name: String, _ arguments: [String?], trailing: String = "", disabled: Bool) -> String {50        "\(name)(\(arguments.compactMap { $0 }.joined(separator: ", ")))" + trailing + (disabled ? "\n.disabled(true)" : "")51    }5253    /// The sample options offered and the selected one, from the "count" and "selected" fields.54    private static func options(_ all: [String], _ values: InspectorValues) -> (options: [String], selected: String) {55        let options = Array(all.prefix(max(Int(values.number("count")), 1)))56        let index = min(max(Int(values.number("selected")), 1), options.count) - 157        return (options, options.indices.contains(index) ? options[index] : "")58    }5960    private static func array(_ strings: [String]) -> String {61        "[" + strings.map(SwiftLiteral.string).joined(separator: ", ") + "]"62    }6364    // MARK: GlassToggle6566    private static var glassToggle: ComponentDescriptor {67        ComponentDescriptor(68            "glass-toggle",69            fields: [70                .text("title", "Title", default: "Notifications", maxLength: 60),71                .text("description", "Description", default: "Alerts for new messages", maxLength: 120),72                .text("symbol", "Symbol", default: "bell", maxLength: 40),73                .choice("appearance", "Appearance", options: [.init("automatic", "Automatic"), .init("switch", "Switch"), .init("checkbox", "Checkbox")]),74                .toggle("on", "On", default: true),75                .toggle("disabled", "Disabled"),76            ],77            variants: [78                ComponentVariant("plain", "Title only", ["description": .text(""), "symbol": .text("")]),79                ComponentVariant("checkbox", "Checkbox", ["appearance": .choice("checkbox"), "symbol": .text("")]),80                ComponentVariant("off", "Off", ["on": .bool(false)]),81                ComponentVariant("disabled", "Disabled", ["disabled": .bool(true)]),82            ],83            isComposable: true,84            preview: { values in85                BoundPreview(values.bool("on")) { isOn in86                    GlassToggle(87                        LocalizedStringKey(values.text("title")),88                        description: values.text("description").isEmpty ? nil : LocalizedStringKey(values.text("description")),89                        systemImage: values.text("symbol").isEmpty ? nil : values.text("symbol"),90                        appearance: GlassToggleAppearance(rawValue: values.choice("appearance")) ?? .automatic,91                        isOn: isOn92                    )93                    .disabled(values.bool("disabled"))94                }95                .id(values.bool("on"))96            },97            snippet: { values in98                call("GlassToggle", [99                    SwiftLiteral.string(values.text("title")),100                    values.text("description").isEmpty ? nil : "description: \(SwiftLiteral.string(values.text("description")))",101                    values.text("symbol").isEmpty ? nil : "systemImage: \(SwiftLiteral.string(values.text("symbol")))",102                    values.choice("appearance") == "automatic" ? nil : "appearance: \(SwiftLiteral.enumCase(values.choice("appearance"), fallback: "automatic"))",103                    "isOn: .constant(\(SwiftLiteral.bool(values.bool("on"))))",104                ], disabled: values.bool("disabled"))105            }106        )107    }108109    // MARK: GlassSlider110111    private static func sliderStep(_ values: InspectorValues) -> Double? {112        Double(values.choice("step")).flatMap { $0 > 0 ? $0 : nil }113    }114115    private static var glassSlider: ComponentDescriptor {116        ComponentDescriptor(117            "glass-slider",118            fields: [119                .text("title", "Title", default: "Volume", maxLength: 60),120                .number("value", "Value", in: 0...100, default: 40),121                .number("upper", "Upper bound", in: 10...100, step: 10, default: 100),122                .choice("step", "Step", options: [.init("0", "Continuous"), .init("1", "1"), .init("5", "5"), .init("10", "10")]),123                .toggle("showsValue", "Show value", default: true),124                .toggle("boundLabels", "Bound labels"),125                .toggle("disabled", "Disabled"),126            ],127            variants: [128                ComponentVariant("stepped", "Stepped", ["title": .text("Brightness"), "step": .choice("10"), "boundLabels": .bool(true), "value": .number(60)]),129                ComponentVariant("bare", "Without value", ["showsValue": .bool(false)]),130                ComponentVariant("disabled", "Disabled", ["disabled": .bool(true)]),131            ],132            isComposable: true,133            preview: { values in134                let upper = values.number("upper")135                BoundPreview(min(values.number("value"), upper)) { value in136                    GlassSlider(137                        LocalizedStringKey(values.text("title")),138                        value: value,139                        in: 0...upper,140                        step: sliderStep(values),141                        showsValue: values.bool("showsValue"),142                        showsBoundLabels: values.bool("boundLabels")143                    )144                    .disabled(values.bool("disabled"))145                }146                .id("\(values.number("value"))-\(upper)")147            },148            snippet: { values in149                let upper = values.number("upper")150                return call("GlassSlider", [151                    SwiftLiteral.string(values.text("title")),152                    "value: .constant(\(SwiftLiteral.number(min(values.number("value"), upper))))",153                    "in: 0...\(SwiftLiteral.number(upper))",154                    sliderStep(values).map { "step: \(SwiftLiteral.number($0))" },155                    values.bool("showsValue") ? nil : "showsValue: false",156                    values.bool("boundLabels") ? "showsBoundLabels: true" : nil,157                ], disabled: values.bool("disabled"))158            }159        )160    }161162    // MARK: GlassPicker163164    private static let samplePlans = ["Starter", "Team", "Business", "Enterprise", "Education", "Nonprofit"]165    private static let planSymbols = ["Starter": "leaf", "Team": "person.3", "Business": "briefcase", "Enterprise": "building.2", "Education": "graduationcap", "Nonprofit": "heart"]166167    private static var glassPicker: ComponentDescriptor {168        ComponentDescriptor(169            "glass-picker",170            fields: [171                .text("title", "Title", default: "Plan", maxLength: 60),172                .choice("presentation", "Presentation", options: [.init("menu", "Menu"), .init("wheel", "Wheel"), .init("inline", "Inline")]),173                .number("count", "Options", in: 2...6, default: 4),174                .number("selected", "Selected option", in: 1...6, default: 1),175                .toggle("symbols", "Option symbols"),176                .toggle("disabled", "Disabled"),177            ],178            variants: [179                ComponentVariant("inline", "Inline", ["presentation": .choice("inline"), "count": .number(3)]),180                ComponentVariant("wheel", "Wheel", ["presentation": .choice("wheel"), "count": .number(6), "selected": .number(3)]),181                ComponentVariant("symbols", "Option symbols", ["symbols": .bool(true)]),182                ComponentVariant("disabled", "Disabled", ["disabled": .bool(true)]),183            ],184            isComposable: true,185            preview: { values in186                let sample = options(samplePlans, values)187                let presentation = GlassPickerPresentation(rawValue: values.choice("presentation")) ?? .menu188                BoundPreview(sample.selected) { selection in189                    if values.bool("symbols") {190                        GlassPicker(LocalizedStringKey(values.text("title")), selection: selection, options: sample.options, presentation: presentation) { plan in191                            Label { Text(verbatim: plan) } icon: { Image(systemName: planSymbols[plan] ?? "circle") }192                        }193                    } else {194                        GlassPicker(LocalizedStringKey(values.text("title")), selection: selection, options: sample.options, presentation: presentation)195                    }196                }197                .disabled(values.bool("disabled"))198                .id("\(sample.selected)-\(sample.options.count)")199            },200            snippet: { values in201                let sample = options(samplePlans, values)202                var trailing = ""203                if values.bool("symbols") {204                    let symbols = sample.options.map { "\(SwiftLiteral.string($0)): \(SwiftLiteral.string(planSymbols[$0] ?? "circle"))" }.joined(separator: ", ")205                    trailing = " { plan in\n    Label(plan, systemImage: [\(symbols)][plan] ?? \"circle\")\n}"206                }207                return call("GlassPicker", [208                    SwiftLiteral.string(values.text("title")),209                    "selection: .constant(\(SwiftLiteral.string(sample.selected)))",210                    "options: \(array(sample.options))",211                    values.choice("presentation") == "menu" ? nil : "presentation: \(SwiftLiteral.enumCase(values.choice("presentation"), fallback: "menu"))",212                ], trailing: trailing, disabled: values.bool("disabled"))213            }214        )215    }216217    // MARK: GlassSegmentedControl218219    private static let samplePeriods = ["Day", "Week", "Month", "Quarter", "Year", "Decade", "All"]220221    private static var glassSegmentedControl: ComponentDescriptor {222        ComponentDescriptor(223            "glass-segmented-control",224            fields: [225                .text("title", "Title", default: "Period", maxLength: 60),226                .number("count", "Options", in: 2...7, default: 4),227                .number("selected", "Selected option", in: 1...7, default: 2),228                .number("maximum", "Maximum segments", in: 2...7, default: Double(GlassSegmentedLayout.defaultMaximumSegments)),229                .toggle("disabled", "Disabled"),230            ],231            variants: [232                ComponentVariant("two", "Two options", ["count": .number(2), "selected": .number(1)]),233                ComponentVariant("menu", "Menu fallback", ["count": .number(7), "selected": .number(5)]),234                ComponentVariant("disabled", "Disabled", ["disabled": .bool(true)]),235            ],236            isComposable: true,237            preview: { values in238                let sample = options(samplePeriods, values)239                BoundPreview(sample.selected) { selection in240                    GlassSegmentedControl(241                        LocalizedStringKey(values.text("title")),242                        selection: selection,243                        options: sample.options,244                        maximumSegments: Int(values.number("maximum"))245                    ) { $0 }246                    .disabled(values.bool("disabled"))247                }248                .id("\(sample.selected)-\(sample.options.count)")249            },250            snippet: { values in251                let sample = options(samplePeriods, values)252                let maximum = Int(values.number("maximum"))253                return call("GlassSegmentedControl", [254                    SwiftLiteral.string(values.text("title")),255                    "selection: .constant(\(SwiftLiteral.string(sample.selected)))",256                    "options: \(array(sample.options))",257                    maximum == GlassSegmentedLayout.defaultMaximumSegments ? nil : "maximumSegments: \(maximum)",258                ], trailing: " { $0 }", disabled: values.bool("disabled"))259            }260        )261    }262263    // MARK: GlassStepper264265    private static var glassStepper: ComponentDescriptor {266        ComponentDescriptor(267            "glass-stepper",268            fields: [269                .text("title", "Title", default: "Guests", maxLength: 60),270                .number("value", "Value", in: 0...100, default: 2),271                .number("upper", "Upper bound", in: 1...100, default: 10),272                .number("step", "Step", in: 1...10, default: 1),273                .toggle("disabled", "Disabled"),274            ],275            variants: [276                ComponentVariant("step", "Step of 5", ["title": .text("Minutes"), "value": .number(15), "upper": .number(60), "step": .number(5)]),277                ComponentVariant("bound", "At the upper bound", ["value": .number(10)]),278                ComponentVariant("disabled", "Disabled", ["disabled": .bool(true)]),279            ],280            isComposable: true,281            preview: { values in282                let upper = Int(values.number("upper"))283                BoundPreview(min(Int(values.number("value")), upper)) { value in284                    GlassStepper(LocalizedStringKey(values.text("title")), value: value, in: 0...upper, step: Int(values.number("step")))285                        .disabled(values.bool("disabled"))286                }287                .id("\(values.number("value"))-\(upper)")288            },289            snippet: { values in290                let upper = values.number("upper")291                return call("GlassStepper", [292                    SwiftLiteral.string(values.text("title")),293                    "value: .constant(\(SwiftLiteral.number(min(values.number("value"), upper))))",294                    "in: 0...\(SwiftLiteral.number(upper))",295                    values.number("step") == 1 ? nil : "step: \(SwiftLiteral.number(values.number("step")))",296                ], disabled: values.bool("disabled"))297            }298        )299    }300}301302/// Owns the value a binding-driven component edits. The descriptor re-creates it (`.id`) when the inspector303/// value that seeds it changes.304private struct BoundPreview<Value, Content: View>: View {305    @State private var value: Value306    private let content: (Binding<Value>) -> Content307308    init(_ initial: Value, @ViewBuilder content: @escaping (Binding<Value>) -> Content) {309        _value = State(initialValue: initial)310        self.content = content311    }312313    var body: some View { content($value) }314}315
Files main
Menu

Theme