SPB Git

Repository Public MIT

GlassSecureField.swift 7.6 KB 188 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassForms/Forms/GlassSecureField.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/// What a secure field holds, for AutoFill and password managers.48public enum GlassSecureContent: String, CaseIterable, Sendable {49    /// An existing password.50    case password51    /// A password being chosen; the system may suggest a strong one.52    case newPassword5354    var contentKind: GlassTextContentKind {55        switch self {56        case .password: .password57        case .newPassword: .newPassword58        }59    }60}6162/// The reveal control of a secure field, separated from the view so that it can be tested.63public enum GlassSecureFieldReveal {64    /// The localisation key of the control: it names the action the button will perform.65    public static func labelKey(isRevealed: Bool) -> GlassL10n.Key {66        isRevealed ? .hidePassword : .showPassword67    }6869    /// The SF Symbol of the control.70    public static func systemImage(isRevealed: Bool) -> String {71        isRevealed ? "eye.slash" : "eye"72    }7374    /// Whether the content is shown in clear: only when revealing is allowed, was asked for, and the field is enabled.75    public static func showsClearText(allowsReveal: Bool, isRevealed: Bool, isEnabled: Bool) -> Bool {76        allowsReveal && isRevealed && isEnabled77    }78}7980/// The system `SecureField` with a label, validation and an optional, explicit reveal button.81///82/// ```swift83/// GlassSecureField("Password", text: $password, validation: GlassFieldValidation(.required(), .minLength(12)))84/// ```85///86/// The content is never logged, stored or copied by the component. It is hidden again every time the field87/// is created; revealing it takes a deliberate tap on a button labelled "Show password". While revealed the88/// text is shown in a plain field without autocorrection, so that nothing is learned by the keyboard.89public struct GlassSecureField: View {90    @Environment(\.isEnabled) private var isEnabled91    @GlassThemed private var theme92    @FocusState private var isFocused: Bool93    @State private var isRevealed = false94    @State private var hasFinishedEditing = false95    private let label: Text?96    @Binding private var text: String97    private let prompt: Text?98    private let helper: Text?99    private let content: GlassSecureContent100    private let allowsReveal: Bool101    private let validation: GlassFieldValidation102    private let trigger: GlassValidationTrigger103    private let errorMessage: String?104105    /// - Parameters:106    ///   - label: label shown above the field and read by VoiceOver.107    ///   - text: the secret.108    ///   - prompt: placeholder shown while the field is empty.109    ///   - helper: explanation shown under the field when there is no error.110    ///   - content: existing or new password, for AutoFill.111    ///   - allowsReveal: adds the button that shows the content in clear.112    ///   - validation: rules of the field.113    ///   - validateOn: when the validation message starts to show.114    ///   - errorMessage: error decided by the host; it replaces the validation message.115    public init(116        _ label: LocalizedStringKey,117        text: Binding<String>,118        prompt: LocalizedStringKey? = nil,119        helper: LocalizedStringKey? = nil,120        content: GlassSecureContent = .password,121        allowsReveal: Bool = false,122        validation: GlassFieldValidation = .none,123        validateOn trigger: GlassValidationTrigger = .afterEditing,124        errorMessage: String? = nil125    ) {126        self.label = Text(label)127        self._text = text128        self.prompt = prompt.map { Text($0) }129        self.helper = helper.map { Text($0) }130        self.content = content131        self.allowsReveal = allowsReveal132        self.validation = validation133        self.trigger = trigger134        self.errorMessage = errorMessage135    }136137    public var body: some View {138        let error = validation.visibleMessage(for: text, trigger: trigger, hasFinishedEditing: hasFinishedEditing, externalError: errorMessage)139        GlassFieldScaffold(label: label, isRequired: validation.isRequired, helper: helper, error: error) {140            HStack(spacing: theme.spacing.xs) {141                field142                    .textFieldStyle(.plain)143                    .labelsHidden()144                    .glassTextInput(GlassTextInputConfiguration(autocorrectionDisabled: true, capitalization: .never, keyboard: .asciiCapable, contentKind: content.contentKind))145                    .focused($isFocused)146                    .privacySensitive()147                    .onSubmit { hasFinishedEditing = true }148                if allowsReveal {149                    revealButton150                }151            }152            .glassFieldSurface(isFocused: isFocused, hasError: error != nil)153            .onChange(of: isFocused) { wasFocused, nowFocused in154                if wasFocused, !nowFocused { hasFinishedEditing = true }155            }156        }157    }158159    private var showsClearText: Bool {160        GlassSecureFieldReveal.showsClearText(allowsReveal: allowsReveal, isRevealed: isRevealed, isEnabled: isEnabled)161    }162163    @ViewBuilder164    private var field: some View {165        let accessibilityLabel = GlassFieldAccessibility.label(label, isRequired: validation.isRequired)166        if showsClearText {167            TextField(text: $text, prompt: prompt) { accessibilityLabel }168        } else {169            SecureField(text: $text, prompt: prompt) { accessibilityLabel }170        }171    }172173    private var revealButton: some View {174        Button {175            let wasFocused = isFocused176            isRevealed.toggle()177            // The secure and the plain field are different views: hand the focus to the new one.178            if wasFocused { isFocused = true }179        } label: {180            Label(GlassL10n.string(GlassSecureFieldReveal.labelKey(isRevealed: isRevealed)), systemImage: GlassSecureFieldReveal.systemImage(isRevealed: isRevealed))181                .labelStyle(.iconOnly)182                .foregroundStyle(theme.color(.textSecondary))183                .glassMinimumHitTarget()184        }185        .buttonStyle(.plain)186    }187}188
Files main
Menu

Theme