SPB Git

Repository Public MIT

GlassTextField.swift 5.9 KB 137 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassForms/Forms/GlassTextField.swift8// Module           : SPGlassForms9// 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 SPGlassCore43import SPGlassTokens44import SPGlassThemes45import SPGlassEffects4647/// A single-line text field with a label, a helper text, validation and focus handling.48///49/// ```swift50/// @State private var email = ""51/// @FocusState private var emailFocused: Bool52///53/// GlassTextField("Email", text: $email, prompt: "name@example.com", systemImage: "envelope",54///                validation: GlassFieldValidation(.required(), .custom(message: "Enter a valid address") { $0.contains("@") }),55///                input: .email, focus: $emailFocused)56///     .onSubmit { register() }57/// ```58///59/// The field is content: it sits on an opaque surface with a hairline. While focused it takes the theme's60/// focus colour and a crisp outer ring; when invalid, the destructive colour, a mark inside the field and a61/// sentence under it; when the host confirms the value (`successMessage`), the success colour, a check mark and62/// the confirmation. A status is never carried by colour alone.63public struct GlassTextField: View {64    @FocusState private var ownFocus: Bool65    @State private var hasFinishedEditing = false66    private let label: Text?67    @Binding private var text: String68    private let prompt: Text?69    private let helper: Text?70    private let systemImage: String?71    private let validation: GlassFieldValidation72    private let trigger: GlassValidationTrigger73    private let errorMessage: String?74    private let successMessage: String?75    private let input: GlassTextInputConfiguration76    private let externalFocus: FocusState<Bool>.Binding?7778    /// - Parameters:79    ///   - label: label shown above the field and read by VoiceOver.80    ///   - text: the value.81    ///   - prompt: placeholder shown while the field is empty.82    ///   - helper: explanation shown under the field when there is no error.83    ///   - systemImage: SF Symbol shown at the leading edge of the field; decorative.84    ///   - validation: rules of the field.85    ///   - validateOn: when the validation message starts to show.86    ///   - errorMessage: error decided by the host; it replaces the validation message.87    ///   - successMessage: confirmation decided by the host ("Available"), already localised; shown with a check88    ///     mark when there is no error.89    ///   - input: autocorrection, capitalisation, keyboard and content type.90    ///   - focus: focus binding owned by the host; `nil` lets the field track its own focus.91    public init(92        _ label: LocalizedStringKey,93        text: Binding<String>,94        prompt: LocalizedStringKey? = nil,95        helper: LocalizedStringKey? = nil,96        systemImage: String? = nil,97        validation: GlassFieldValidation = .none,98        validateOn trigger: GlassValidationTrigger = .afterEditing,99        errorMessage: String? = nil,100        successMessage: String? = nil,101        input: GlassTextInputConfiguration = .standard,102        focus: FocusState<Bool>.Binding? = nil103    ) {104        self.label = Text(label)105        self._text = text106        self.prompt = prompt.map { Text($0) }107        self.helper = helper.map { Text($0) }108        self.systemImage = systemImage109        self.validation = validation110        self.trigger = trigger111        self.errorMessage = errorMessage112        self.successMessage = successMessage113        self.input = input114        self.externalFocus = focus115    }116117    public var body: some View {118        let focus = externalFocus ?? $ownFocus119        let error = validation.visibleMessage(for: text, trigger: trigger, hasFinishedEditing: hasFinishedEditing, externalError: errorMessage)120        let success = error == nil ? successMessage : nil121        GlassFieldScaffold(label: label, isRequired: validation.isRequired, helper: helper, error: error, success: success) {122            TextField(text: $text, prompt: prompt) {123                GlassFieldAccessibility.label(label, isRequired: validation.isRequired)124            }125            .textFieldStyle(.plain)126            .labelsHidden()127            .glassTextInput(input)128            .focused(focus)129            .glassFieldSurface(isFocused: focus.wrappedValue, hasError: error != nil, isValid: success != nil, systemImage: systemImage)130            .onChange(of: focus.wrappedValue) { wasFocused, isFocused in131                if wasFocused, !isFocused { hasFinishedEditing = true }132            }133            .onSubmit { hasFinishedEditing = true }134        }135    }136}137
Files main
Menu

Theme