SPB Git

Repository Public MIT

FormsDescriptors.swift 16.7 KB 336 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Apps/GlassStudio/Kit/Descriptors/FormsDescriptors.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 formDescriptors: [ComponentDescriptor] {46        [glassTextField, glassSecureField, glassSearchField, glassTextArea, glassOTPField]47    }4849    /// `, name: "text"` when the text is not empty. Optional string arguments are omitted otherwise.50    private static func optional(_ name: String, _ text: String) -> String? {51        text.isEmpty ? nil : "\(name): \(SwiftLiteral.string(text))"52    }5354    private static func key(_ text: String) -> LocalizedStringKey? {55        text.isEmpty ? nil : LocalizedStringKey(text)56    }5758    private static func call(_ name: String, _ arguments: [String?], disabled: Bool = false) -> String {59        "\(name)(\(arguments.compactMap { $0 }.joined(separator: ", ")))" + (disabled ? "\n.disabled(true)" : "")60    }6162    // MARK: GlassTextField6364    private static func inputConfiguration(_ id: String) -> GlassTextInputConfiguration {65        switch id {66        case "email": .email67        case "username": .username68        case "url": .url69        case "number": .number70        case "name": .name71        default: .standard72        }73    }7475    private static var glassTextField: ComponentDescriptor {76        ComponentDescriptor(77            "glass-text-field",78            fields: [79                .text("label", "Label", default: "Full name", maxLength: 40),80                .text("text", "Value", default: "", maxLength: 80),81                .text("prompt", "Prompt", default: "Ada Lovelace", maxLength: 60),82                .text("helper", "Helper", default: "", maxLength: 100),83                .choice("input", "Input", options: [84                    .init("standard", "Standard"), .init("email", "E-mail"), .init("username", "User name"), .init("url", "Web address"),85                    .init("number", "Number"), .init("name", "Name"),86                ]),87                .text("error", "Error message", default: "", maxLength: 100),88                .toggle("disabled", "Disabled"),89            ],90            variants: [91                ComponentVariant("helper", "With helper", ["label": .text("E-mail"), "prompt": .text("name@example.com"), "helper": .text("Only used to sign you in."), "input": .choice("email")]),92                ComponentVariant("error", "Error", ["label": .text("E-mail"), "text": .text("ada@"), "input": .choice("email"), "error": .text("Enter a valid e-mail address.")]),93                ComponentVariant("disabled", "Disabled", ["text": .text("Ada Lovelace"), "disabled": .bool(true)]),94            ],95            isComposable: true,96            preview: { values in97                BoundPreview(values.text("text")) { text in98                    GlassTextField(99                        LocalizedStringKey(values.text("label")),100                        text: text,101                        prompt: key(values.text("prompt")),102                        helper: key(values.text("helper")),103                        errorMessage: values.text("error").isEmpty ? nil : values.text("error"),104                        input: inputConfiguration(values.choice("input"))105                    )106                    .disabled(values.bool("disabled"))107                }108                .id(values.text("text"))109            },110            snippet: { values in111                call("GlassTextField", [112                    SwiftLiteral.string(values.text("label")),113                    "text: .constant(\(SwiftLiteral.string(values.text("text"))))",114                    optional("prompt", values.text("prompt")),115                    optional("helper", values.text("helper")),116                    optional("errorMessage", values.text("error")),117                    values.choice("input") == "standard" ? nil : "input: \(SwiftLiteral.enumCase(values.choice("input"), fallback: "standard"))",118                ], disabled: values.bool("disabled"))119            }120        )121    }122123    // MARK: GlassSecureField124125    private static var glassSecureField: ComponentDescriptor {126        ComponentDescriptor(127            "glass-secure-field",128            fields: [129                .text("label", "Label", default: "Password", maxLength: 40),130                .text("text", "Value", default: "", maxLength: 60),131                .text("prompt", "Prompt", default: "", maxLength: 60),132                .text("helper", "Helper", default: "At least 12 characters.", maxLength: 100),133                .choice("content", "Content", options: [.init("password", "Existing password"), .init("newPassword", "New password")]),134                .toggle("reveal", "Reveal button"),135                .text("error", "Error message", default: "", maxLength: 100),136            ],137            variants: [138                ComponentVariant("reveal", "Reveal button", ["reveal": .bool(true), "text": .text("glass-demo")]),139                ComponentVariant("new", "New password", ["label": .text("New password"), "content": .choice("newPassword"), "reveal": .bool(true)]),140                ComponentVariant("error", "Error", ["text": .text("glass"), "helper": .text(""), "error": .text("This password is too short.")]),141            ],142            isComposable: true,143            preview: { values in144                BoundPreview(values.text("text")) { text in145                    GlassSecureField(146                        LocalizedStringKey(values.text("label")),147                        text: text,148                        prompt: key(values.text("prompt")),149                        helper: key(values.text("helper")),150                        content: values.choice("content") == "newPassword" ? .newPassword : .password,151                        allowsReveal: values.bool("reveal"),152                        errorMessage: values.text("error").isEmpty ? nil : values.text("error")153                    )154                }155                .id(values.text("text"))156            },157            snippet: { values in158                call("GlassSecureField", [159                    SwiftLiteral.string(values.text("label")),160                    "text: .constant(\(SwiftLiteral.string(values.text("text"))))",161                    optional("prompt", values.text("prompt")),162                    optional("helper", values.text("helper")),163                    values.choice("content") == "newPassword" ? "content: .newPassword" : nil,164                    values.bool("reveal") ? "allowsReveal: true" : nil,165                    optional("errorMessage", values.text("error")),166                ])167            }168        )169    }170171    // MARK: GlassSearchField172173    private static let sampleDrinks = ["Café crème", "Thé vert", "Chocolat chaud", "Citronnade"]174    private static let sampleSuggestions = [("café", "clock"), ("thé", "clock"), ("chocolat", "cup.and.saucer")]175176    private static func showsCancel(_ values: InspectorValues) -> Bool? {177        switch values.choice("cancel") {178        case "always": true179        case "never": false180        default: nil181        }182    }183184    private static var glassSearchField: ComponentDescriptor {185        ComponentDescriptor(186            "glass-search-field",187            fields: [188                .choice("style", "Presentation", options: [.init("inline", "Inline field"), .init("system", "System search")]),189                .text("text", "Query", default: "", maxLength: 60),190                .text("prompt", "Prompt", default: "Search drinks", maxLength: 60),191                .choice("cancel", "Cancel button", options: [.init("automatic", "Automatic"), .init("always", "Always"), .init("never", "Never")]),192                .number("suggestions", "Suggestions", in: 0...3, default: 0),193            ],194            variants: [195                ComponentVariant("query", "With a query", ["text": .text("thé")]),196                ComponentVariant("cancel", "Cancel button", ["cancel": .choice("always")]),197                ComponentVariant("suggestions", "System search with suggestions", ["style": .choice("system"), "suggestions": .number(3)]),198            ],199            isComposable: true,200            preview: { values in201                BoundPreview(values.text("text")) { text in202                    if values.choice("style") == "system" {203                        NavigationStack {204                            List(sampleDrinks, id: \.self) { drink in205                                Text(verbatim: drink)206                            }207                            .navigationTitle(Text(verbatim: "Drinks"))208                            .glassSearchable(209                                text: text,210                                prompt: key(values.text("prompt")),211                                suggestions: sampleSuggestions.prefix(Int(values.number("suggestions"))).map { GlassSearchSuggestion(title: $0.0, systemImage: $0.1) }212                            )213                        }214                        .frame(minHeight: 320)215                    } else {216                        GlassSearchField(text: text, prompt: key(values.text("prompt")), showsCancel: showsCancel(values))217                    }218                }219                .id(values.text("text"))220            },221            snippet: { values in222                let text = "text: .constant(\(SwiftLiteral.string(values.text("text"))))"223                guard values.choice("style") == "system" else {224                    return call("GlassSearchField", [text, optional("prompt", values.text("prompt")), showsCancel(values).map { "showsCancel: \(SwiftLiteral.bool($0))" }])225                }226                let suggestions = sampleSuggestions.prefix(Int(values.number("suggestions"))).map {227                    "        GlassSearchSuggestion(title: \(SwiftLiteral.string($0.0)), systemImage: \(SwiftLiteral.string($0.1))),"228                }229                let modifier = call("    .glassSearchable", [text, optional("prompt", values.text("prompt")), suggestions.isEmpty ? nil : "suggestions: [\n\(suggestions.joined(separator: "\n"))\n    ]"])230                let drinks = sampleDrinks.map(SwiftLiteral.string).joined(separator: ", ")231                return "NavigationStack {\n    List([\(drinks)], id: \\.self) { drink in\n        Text(drink)\n    }\n    .navigationTitle(\"Drinks\")\n\(modifier)\n}"232            }233        )234    }235236    // MARK: GlassTextArea237238    private static var glassTextArea: ComponentDescriptor {239        ComponentDescriptor(240            "glass-text-area",241            fields: [242                .text("label", "Label", default: "Notes", maxLength: 40),243                .text("text", "Value", default: "", maxLength: 280),244                .text("placeholder", "Placeholder", default: "Anything the team should know", maxLength: 80),245                .toggle("limited", "Character limit", default: true),246                .number("limit", "Limit", in: 20...500, step: 20, default: 280),247                .number("minHeight", "Minimum height", in: 60...240, step: 12, default: 96),248                .text("error", "Error message", default: "", maxLength: 100),249            ],250            variants: [251                ComponentVariant("filled", "Filled", ["text": .text("The client prefers the morning.\nBring the printed plans."), "limit": .number(120)]),252                ComponentVariant("unlimited", "No limit", ["limited": .bool(false), "minHeight": .number(180)]),253                ComponentVariant("error", "Error", ["error": .text("Describe the issue before sending.")]),254            ],255            isComposable: true,256            preview: { values in257                BoundPreview(GlassTextLimit.clamp(values.text("text"), to: values.bool("limited") ? Int(values.number("limit")) : nil)) { text in258                    GlassTextArea(259                        LocalizedStringKey(values.text("label")),260                        text: text,261                        placeholder: values.text("placeholder").isEmpty ? nil : values.text("placeholder"),262                        limit: values.bool("limited") ? Int(values.number("limit")) : nil,263                        minHeight: values.number("minHeight"),264                        errorMessage: values.text("error").isEmpty ? nil : values.text("error")265                    )266                }267                .id("\(values.text("text"))\n\(values.bool("limited"))\(values.number("limit"))")268            },269            snippet: { values in270                let limit = values.bool("limited") ? Int(values.number("limit")) : nil271                return call("GlassTextArea", [272                    SwiftLiteral.string(values.text("label")),273                    "text: .constant(\(SwiftLiteral.string(GlassTextLimit.clamp(values.text("text"), to: limit))))",274                    optional("placeholder", values.text("placeholder")),275                    limit.map { "limit: \($0)" },276                    values.number("minHeight") == 96 ? nil : "minHeight: \(SwiftLiteral.number(values.number("minHeight")))",277                    optional("errorMessage", values.text("error")),278                ])279            }280        )281    }282283    // MARK: GlassOTPField284285    private static var glassOTPField: ComponentDescriptor {286        ComponentDescriptor(287            "glass-otp-field",288            fields: [289                .number("length", "Digits", in: 4...8, default: 6),290                .text("code", "Code", default: "", maxLength: 8),291                .text("label", "Accessibility label", default: "", maxLength: 60),292                .toggle("error", "Error"),293                .toggle("disabled", "Disabled"),294            ],295            variants: [296                ComponentVariant("partial", "Partly entered", ["code": .text("123")]),297                ComponentVariant("error", "Error", ["code": .text("123456"), "error": .bool(true)]),298                ComponentVariant("four", "Four digits", ["length": .number(4)]),299                ComponentVariant("disabled", "Disabled", ["code": .text("12"), "disabled": .bool(true)]),300            ],301            isComposable: true,302            preview: { values in303                let length = Int(values.number("length"))304                BoundPreview(GlassOTPSanitizer.sanitize(values.text("code"), length: length)) { code in305                    GlassOTPField(code: code, length: length, label: key(values.text("label")), hasError: values.bool("error"))306                        .disabled(values.bool("disabled"))307                }308                .id("\(values.text("code"))-\(length)")309            },310            snippet: { values in311                let length = Int(values.number("length"))312                return call("GlassOTPField", [313                    "code: .constant(\(SwiftLiteral.string(GlassOTPSanitizer.sanitize(values.text("code"), length: length))))",314                    length == 6 ? nil : "length: \(length)",315                    optional("label", values.text("label")),316                    values.bool("error") ? "hasError: true" : nil,317                ], disabled: values.bool("disabled"))318            }319        )320    }321}322323/// Owns the value a binding-driven component edits. The descriptor re-creates it (`.id`) when the inspector324/// value that seeds it changes.325private struct BoundPreview<Value, Content: View>: View {326    @State private var value: Value327    private let content: (Binding<Value>) -> Content328329    init(_ initial: Value, @ViewBuilder content: @escaping (Binding<Value>) -> Content) {330        _value = State(initialValue: initial)331        self.content = content332    }333334    var body: some View { content($value) }335}336
Files main
Menu

Theme