SPB Git

Repository Public MIT

ButtonDescriptors.swift 20.6 KB 433 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Descriptors/ButtonDescriptors.swift8// Module           : GlassStudio9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0313//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 buttonDescriptors: [ComponentDescriptor] {46        [glassButton, glassIconButton, glassFloatingButton, glassSplitButton, glassButtonGroup]47    }4849    private static let variantOptions = [InspectorField.Option("regular", "Regular"), .init("prominent", "Prominent")]5051    private static func variant(_ values: InspectorValues) -> GlassButtonVariant {52        values.choice("variant") == "prominent" ? .prominent : .regular53    }5455    private static var glassButton: ComponentDescriptor {56        ComponentDescriptor(57            "glass-button",58            fields: [59                .text("title", "Title", default: "Save changes", maxLength: 60),60                .text("symbol", "Symbol", default: "checkmark", maxLength: 40),61                .choice("variant", "Variant", options: variantOptions),62                .size(),63                .toggle("destructive", "Destructive"),64                .toggle("loading", "Loading"),65                .toggle("disabled", "Disabled"),66            ],67            variants: [68                ComponentVariant("prominent", "Prominent", ["variant": .choice("prominent")]),69                ComponentVariant("destructive", "Destructive", ["destructive": .bool(true), "title": .text("Delete"), "symbol": .text("trash")]),70                ComponentVariant("loading", "Loading", ["variant": .choice("prominent"), "loading": .bool(true)]),71                ComponentVariant("large", "Large", ["size": .size(.large)]),72            ],73            isComposable: true,74            prefersStage: true,75            preview: { values in76                InScene(77                    GlassButton(78                        verbatim: values.text("title"),79                        systemImage: values.text("symbol").isEmpty ? nil : values.text("symbol"),80                        variant: variant(values),81                        role: values.bool("destructive") ? .destructive : nil,82                        size: values.size(),83                        isLoading: values.bool("loading")84                    ) {}85                    .disabled(values.bool("disabled"))86                ) { button in87                    ButtonFamilyScene(variant: variant(values), hero: button)88                }89            },90            snippet: { values in91                var arguments = [SwiftLiteral.string(values.text("title"))]92                if !values.text("symbol").isEmpty { arguments.append("systemImage: \(SwiftLiteral.string(values.text("symbol")))") }93                if values.choice("variant") == "prominent" { arguments.append("variant: .prominent") }94                if values.bool("destructive") { arguments.append("role: .destructive") }95                if values.size() != .regular { arguments.append("size: .\(values.size().rawValue)") }96                if values.bool("loading") { arguments.append("isLoading: true") }97                var code = "GlassButton(\(arguments.joined(separator: ", "))) {\n    // action\n}"98                if values.bool("disabled") { code += "\n.disabled(true)" }99                return code100            }101        )102    }103104    private static var glassIconButton: ComponentDescriptor {105        ComponentDescriptor(106            "glass-icon-button",107            fields: [108                .text("symbol", "Symbol", default: "square.and.arrow.up", maxLength: 40),109                .text("label", "Accessibility label", default: "Share", maxLength: 60),110                .choice("variant", "Variant", options: variantOptions),111                .size(),112                .toggle("destructive", "Destructive"),113            ],114            variants: [115                ComponentVariant("prominent", "Prominent", ["variant": .choice("prominent"), "symbol": .text("star.fill"), "label": .text("Favourite")]),116                ComponentVariant("destructive", "Destructive", ["destructive": .bool(true), "symbol": .text("trash"), "label": .text("Delete")]),117            ],118            isComposable: true,119            prefersStage: true,120            preview: { values in121                InScene(122                    GlassIconButton(123                        systemImage: values.text("symbol").isEmpty ? "questionmark" : values.text("symbol"),124                        label: Text(verbatim: values.text("label")),125                        variant: variant(values),126                        role: values.bool("destructive") ? .destructive : nil,127                        size: values.size()128                    ) {}129                ) { button in130                    IconButtonFamilyScene(variant: variant(values), hero: button)131                }132            },133            snippet: { values in134                var arguments = ["systemImage: \(SwiftLiteral.string(values.text("symbol").isEmpty ? "questionmark" : values.text("symbol")))", "accessibilityLabel: \(SwiftLiteral.string(values.text("label")))"]135                if values.choice("variant") == "prominent" { arguments.append("variant: .prominent") }136                if values.bool("destructive") { arguments.append("role: .destructive") }137                if values.size() != .regular { arguments.append("size: .\(values.size().rawValue)") }138                return "GlassIconButton(\(arguments.joined(separator: ", "))) {\n    // action\n}"139            }140        )141    }142143    private static var glassFloatingButton: ComponentDescriptor {144        let positions = GlassFloatingPosition.allCases.map { InspectorField.Option($0.rawValue, $0.rawValue) }145        return ComponentDescriptor(146            "glass-floating-button",147            fields: [148                .text("title", "Title", default: "New note", maxLength: 40),149                .text("symbol", "Symbol", default: "plus", maxLength: 40),150                .choice("position", "Position", options: positions, default: GlassFloatingPosition.bottomTrailing.rawValue),151                .toggle("extended", "Show title"),152                .toggle("presented", "Visible", default: true),153            ],154            variants: [155                ComponentVariant("extended", "Extended", ["extended": .bool(true)]),156                ComponentVariant("leading", "Bottom leading", ["position": .choice("bottomLeading")]),157            ],158            prefersStage: false,159            preview: { values in160                PreviewScreen(height: 520) {161                    SketchbookBoard()162                        .glassFloatingButton(163                            LocalizedStringKey(values.text("title")),164                            systemImage: values.text("symbol").isEmpty ? "plus" : values.text("symbol"),165                            position: GlassFloatingPosition(rawValue: values.choice("position")) ?? .bottomTrailing,166                            isExtended: values.bool("extended"),167                            isPresented: values.bool("presented")168                        ) {}169                }170            },171            snippet: { values in172                var arguments = [SwiftLiteral.string(values.text("title")), "systemImage: \(SwiftLiteral.string(values.text("symbol").isEmpty ? "plus" : values.text("symbol")))"]173                if values.choice("position") != "bottomTrailing" { arguments.append("position: \(SwiftLiteral.enumCase(values.choice("position"), fallback: "bottomTrailing"))") }174                if values.bool("extended") { arguments.append("isExtended: true") }175                if !values.bool("presented") { arguments.append("isPresented: false") }176                return "List([\"Harbour\", \"North pier\", \"Stairwells\"], id: \\.self) { board in\n    Text(board)\n}\n.glassFloatingButton(\(arguments.joined(separator: ", "))) {\n    // action\n}"177            }178        )179    }180181    private static var glassSplitButton: ComponentDescriptor {182        ComponentDescriptor(183            "glass-split-button",184            fields: [185                .text("title", "Title", default: "Send", maxLength: 40),186                .text("symbol", "Symbol", default: "paperplane", maxLength: 40),187                .choice("variant", "Variant", options: variantOptions, default: "prominent"),188                .size(),189                .number("items", "Menu items", in: 1...4, default: 2),190            ],191            variants: [ComponentVariant("regular", "Regular", ["variant": .choice("regular")])],192            isComposable: true,193            prefersStage: true,194            preview: { values in195                InScene(196                    GlassSplitButton(197                        LocalizedStringKey(values.text("title")),198                        systemImage: values.text("symbol").isEmpty ? nil : values.text("symbol"),199                        variant: variant(values),200                        size: values.size()201                    ) {} menu: {202                        ForEach(0..<Int(values.number("items")), id: \.self) { index in203                            Button(splitMenuTitles[index]) {}204                        }205                    }206                ) { button in207                    SplitButtonScene(hero: button)208                }209            },210            snippet: { values in211                var arguments = [SwiftLiteral.string(values.text("title"))]212                if !values.text("symbol").isEmpty { arguments.append("systemImage: \(SwiftLiteral.string(values.text("symbol")))") }213                if values.choice("variant") == "prominent" { arguments.append("variant: .prominent") }214                if values.size() != .regular { arguments.append("size: .\(values.size().rawValue)") }215                let items = splitMenuTitles.prefix(Int(values.number("items"))).map { "    Button(\(SwiftLiteral.string($0))) { }" }.joined(separator: "\n")216                return "GlassSplitButton(\(arguments.joined(separator: ", "))) {\n    // primary action\n} menu: {\n\(items)\n}"217            }218        )219    }220221    private static let splitMenuTitles = ["Send later…", "Save as draft", "Send without formatting", "Print"]222223    private static var glassButtonGroup: ComponentDescriptor {224        ComponentDescriptor(225            "glass-button-group",226            fields: [227                .choice("axis", "Axis", options: [.init("horizontal", "Horizontal"), .init("vertical", "Vertical")]),228                .choice("spacing", "Spacing", options: GlassSpacingStep.allCases.prefix(5).map { .init($0.rawValue, $0.rawValue) }, default: "xs"),229                .number("count", "Buttons", in: 2...5, default: 3),230            ],231            variants: [ComponentVariant("vertical", "Vertical", ["axis": .choice("vertical"), "count": .number(2)])],232            isComposable: true,233            prefersStage: true,234            preview: { values in235                InScene(236                    GlassButtonGroup(237                        axis: values.choice("axis") == "vertical" ? .vertical : .horizontal,238                        spacing: GlassSpacingStep(rawValue: values.choice("spacing")) ?? .xs,239                        accessibilityLabel: "Text style"240                    ) {241                        ForEach(Array(groupSymbols.prefix(Int(values.number("count")))), id: \.0) { symbol, label in242                            GlassIconButton(systemImage: symbol, label: Text(verbatim: label)) {}243                        }244                    }245                ) { group in246                    ButtonGroupScene(isVertical: values.choice("axis") == "vertical", hero: group)247                }248            },249            snippet: { values in250                var arguments: [String] = []251                if values.choice("axis") == "vertical" { arguments.append("axis: .vertical") }252                if values.choice("spacing") != "xs" { arguments.append("spacing: \(SwiftLiteral.enumCase(values.choice("spacing"), fallback: "xs"))") }253                arguments.append("accessibilityLabel: \"Text style\"")254                let buttons = groupSymbols.prefix(Int(values.number("count"))).map {255                    "    GlassIconButton(systemImage: \(SwiftLiteral.string($0.0)), accessibilityLabel: \(SwiftLiteral.string($0.1))) { }"256                }.joined(separator: "\n")257                return "GlassButtonGroup(\(arguments.joined(separator: ", "))) {\n\(buttons)\n}"258            }259        )260    }261262    private static let groupSymbols = [("bold", "Bold"), ("italic", "Italic"), ("underline", "Underline"), ("strikethrough", "Strikethrough"), ("textformat.size", "Text size")]263}264265// MARK: - Scenes266267/// The configured button above an action bar and the three sizes, over the colour stage.268private struct ButtonFamilyScene<Hero: View>: View {269    let variant: GlassButtonVariant270    let hero: Hero271272    var body: some View {273        VStack(spacing: 30) {274            hero275            VStack(spacing: 14) {276                ViewThatFits(in: .horizontal) {277                    HStack(spacing: 10) { actions }278                    VStack(spacing: 10) { actions }279                }280                HStack(spacing: 10) {281                    GlassButton(verbatim: L("Small"), variant: variant, size: .small) {}282                    GlassButton(verbatim: L("Regular"), variant: variant) {}283                    GlassButton(verbatim: L("Large"), variant: variant, size: .large) {}284                }285            }286        }287    }288289    @ViewBuilder private var actions: some View {290        GlassButton(verbatim: L("Cancel")) {}291        GlassButton(verbatim: L("Delete"), systemImage: "trash", role: .destructive) {}292        GlassButton(verbatim: L("Publish"), systemImage: "arrow.up", variant: .prominent) {}293    }294}295296/// The configured icon button above a toolbar cluster and the sizes, over the colour stage.297private struct IconButtonFamilyScene<Hero: View>: View {298    let variant: GlassButtonVariant299    let hero: Hero300301    var body: some View {302        VStack(spacing: 30) {303            hero304            GlassButtonGroup(spacing: .xs, accessibilityLabel: "Actions") {305                GlassIconButton(systemImage: "heart", label: Text(verbatim: L("Like"))) {}306                GlassIconButton(systemImage: "bookmark", label: Text(verbatim: L("Save"))) {}307                GlassIconButton(systemImage: "text.bubble", label: Text(verbatim: L("Comment"))) {}308                GlassIconButton(systemImage: "ellipsis", label: Text(verbatim: L("More"))) {}309            }310            HStack(spacing: 16) {311                GlassIconButton(systemImage: "plus", label: Text(verbatim: L("Small")), variant: variant, size: .small) {}312                GlassIconButton(systemImage: "plus", label: Text(verbatim: L("Regular")), variant: variant) {}313                GlassIconButton(systemImage: "plus", label: Text(verbatim: L("Large")), variant: variant, size: .large) {}314                GlassIconButton(systemImage: "star.fill", label: Text(verbatim: L("Favourite")), variant: .prominent, size: .large) {}315                GlassIconButton(systemImage: "trash", label: Text(verbatim: L("Delete")), role: .destructive, size: .large) {}316            }317        }318    }319}320321/// A board of drawn pictures inside a mock screen: what a floating button floats over.322private struct SketchbookBoard: View {323    @GlassThemed private var theme324325    private var boards: [String] {326        [L("Harbour"), L("North pier"), L("Stairwells"), L("Rooflines"), L("Tram depot"), L("Market hall")]327    }328329    var body: some View {330        ScrollView {331            VStack(alignment: .leading, spacing: 14) {332                VStack(alignment: .leading, spacing: 2) {333                    Eyebrow(L("6 boards"))334                    Text(verbatim: L("Sketchbook"))335                        .font(theme.font(.largeTitle))336                        .foregroundStyle(theme.color(.textPrimary))337                }338                LazyVGrid(columns: [GridItem(.flexible(), spacing: 12), GridItem(.flexible(), spacing: 12)], spacing: 14) {339                    ForEach(Array(boards.enumerated()), id: \.offset) { index, board in340                        VStack(alignment: .leading, spacing: 6) {341                            PreviewArtwork(seed: index)342                                .aspectRatio(1.25, contentMode: .fit)343                                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))344                            Text(verbatim: board)345                                .font(theme.font(.callout).weight(.medium))346                                .foregroundStyle(theme.color(.textPrimary))347                        }348                    }349                }350            }351            .padding(18)352        }353    }354}355356/// A message draft with its sending bar: an attachment button and the split button.357private struct SplitButtonScene<Hero: View>: View {358    @GlassThemed private var theme359    let hero: Hero360361    var body: some View {362        VStack(spacing: 14) {363            PreviewCard(padding: 0, elevated: true) {364                VStack(alignment: .leading, spacing: 0) {365                    line(L("To"), "Atelier Nord")366                    RowDivider()367                    line(L("Subject"), L("Revised floor plans"))368                    RowDivider()369                    Text(verbatim: L("The mezzanine moves forty centimetres to the east; the stair keeps its landing. Plans attached."))370                        .font(theme.font(.callout))371                        .foregroundStyle(theme.color(.textPrimary))372                        .lineSpacing(2)373                        .padding(14)374                }375            }376            HStack(spacing: 10) {377                GlassIconButton(systemImage: "paperclip", label: Text(verbatim: L("Attach a file"))) {}378                GlassIconButton(systemImage: "photo", label: Text(verbatim: L("Add a picture"))) {}379                Spacer(minLength: 8)380                hero381            }382        }383        .frame(maxWidth: 420)384    }385386    private func line(_ name: String, _ value: String) -> some View {387        HStack(spacing: 10) {388            Text(verbatim: name)389                .foregroundStyle(theme.color(.textSecondary))390            Text(verbatim: value)391                .foregroundStyle(theme.color(.textPrimary))392                .lineLimit(1)393            Spacer(minLength: 0)394        }395        .font(theme.font(.callout))396        .padding(.horizontal, 14)397        .padding(.vertical, 11)398    }399}400401/// A paragraph being edited, with the formatting group floating at its edge.402private struct ButtonGroupScene<Hero: View>: View {403    @GlassThemed private var theme404    let isVertical: Bool405    let hero: Hero406407    var body: some View {408        Group {409            if isVertical {410                HStack(alignment: .top, spacing: 12) { page; hero }411            } else {412                VStack(spacing: 14) { page; hero }413            }414        }415        .frame(maxWidth: 420)416    }417418    private var page: some View {419        PreviewCard(elevated: true) {420            VStack(alignment: .leading, spacing: 8) {421                Eyebrow(L("Site visit"))422                Text(verbatim: L("Minutes of 3 December"))423                    .font(theme.font(.headline))424                    .foregroundStyle(theme.color(.textPrimary))425                Text("\(Text(verbatim: L("The north pier stays closed until March.")).bold()) \(Text(verbatim: L("A shuttle links it to the central terminal."))) \(Text(verbatim: L("Next visit on Thursday.")).italic().underline())")426                    .font(theme.font(.callout))427                    .foregroundStyle(theme.color(.textPrimary))428                    .lineSpacing(2)429            }430        }431    }432}433
Files main
Menu

Theme