SPB Git

Repository Public MIT

GlassOTPField.swift 7.7 KB 184 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassForms/Forms/GlassOTPField.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/// Cleans what is typed, pasted or filled into a one-time-code field. Pure.48public enum GlassOTPSanitizer {49    /// Keeps the decimal digits of `input`, converted to ASCII, up to `length` of them.50    ///51    /// Spaces, dashes and letters are dropped, so "123 456" and "123-456" both give "123456". Digits of other52    /// scripts (Arabic-Indic "١٢٣", Devanagari, full-width) become "0"..."9". Symbols that merely look like53    /// numbers (fractions, Roman numerals, circled digits) are not digits and are dropped.54    public static func sanitize(_ input: String, length: Int) -> String {55        var result = ""56        let length = max(length, 0)57        for scalar in input.unicodeScalars {58            if result.count >= length { break }59            guard scalar.properties.numericType == .decimal,60                  let value = scalar.properties.numericValue,61                  let digit = Int(exactly: value), (0...9).contains(digit) else { continue }62            result.append(String(digit))63        }64        return result65    }6667    /// The content of each of the `length` boxes: a digit, or `nil` for a box still empty.68    public static func segments(_ code: String, length: Int) -> [Character?] {69        let digits = Array(sanitize(code, length: length))70        return (0..<max(length, 0)).map { $0 < digits.count ? digits[$0] : nil }71    }7273    /// Index of the box that receives the next digit, or `nil` when the code is complete.74    public static func activeIndex(_ code: String, length: Int) -> Int? {75        let count = sanitize(code, length: length).count76        return count < length ? count : nil77    }7879    /// Whether the code is exactly `length` ASCII digits and nothing else.80    public static func isComplete(_ code: String, length: Int) -> Bool {81        length > 0 && code.count == length && sanitize(code, length: length) == code82    }83}8485/// A one-time-code field: one text field for the system, a row of boxes for the eye.86///87/// ```swift88/// GlassOTPField(code: $code, length: 6) { code in89///     verify(code)90/// }91/// ```92///93/// There is a single text field underneath, so typing, deleting, pasting a whole code and the system's94/// one-time-code AutoFill all work as in any field, and VoiceOver meets one element ("Verification code,95/// 3 of 6 digits entered"). The code lives only in the binding: the component stores nothing.96public struct GlassOTPField: View {97    @GlassThemed private var theme98    @Environment(\.isEnabled) private var isEnabled99    @FocusState private var isFocused: Bool100    @ScaledMetric(relativeTo: .title) private var boxHeight: CGFloat = 52101    @Binding private var code: String102    private let length: Int103    private let label: Text104    private let hasError: Bool105    private let onComplete: @MainActor (String) -> Void106107    /// - Parameters:108    ///   - code: the digits entered so far, ASCII only.109    ///   - length: number of digits of the code (4 to 8 is usual).110    ///   - label: accessibility label. Defaults to the localised "Verification code".111    ///   - hasError: outlines the boxes with the destructive colour, for a rejected code.112    ///   - onComplete: called once each time the code becomes complete.113    public init(114        code: Binding<String>,115        length: Int = 6,116        label: LocalizedStringKey? = nil,117        hasError: Bool = false,118        onComplete: @escaping @MainActor (String) -> Void = { _ in }119    ) {120        self._code = code121        self.length = max(length, 1)122        self.label = label.map { Text($0) } ?? Text(GlassL10n.string(.verificationCode))123        self.hasError = hasError124        self.onComplete = onComplete125    }126127    public var body: some View {128        boxes129            .accessibilityHidden(true)130            .overlay { field }131            .opacity(isEnabled ? 1 : 0.6)132            .onChange(of: code) { oldValue, newValue in133                let clean = GlassOTPSanitizer.sanitize(newValue, length: length)134                if clean != newValue {135                    code = clean136                } else if clean.count == length, oldValue != newValue {137                    onComplete(clean)138                }139            }140    }141142    /// The only text field. Its glyphs and caret are transparent; the boxes show the digits instead.143    private var field: some View {144        TextField(text: sanitizedCode) { label }145            .textFieldStyle(.plain)146            .labelsHidden()147            .glassTextInput(GlassTextInputConfiguration(autocorrectionDisabled: true, capitalization: .never, keyboard: .numberPad, contentKind: .oneTimeCode))148            .focused($isFocused)149            .foregroundStyle(.clear)150            .tint(.clear)151            .frame(maxWidth: .infinity, maxHeight: .infinity)152            .contentShape(Rectangle())153            .accessibilityLabel(label)154            .accessibilityValue(Text(GlassL10n.string(.codeDigitsEntered, code.count, length)))155    }156157    private var sanitizedCode: Binding<String> {158        Binding {159            code160        } set: { newValue in161            let clean = GlassOTPSanitizer.sanitize(newValue, length: length)162            if clean != code { code = clean }163        }164    }165166    private var boxes: some View {167        let segments = GlassOTPSanitizer.segments(code, length: length)168        let active = GlassOTPSanitizer.activeIndex(code, length: length)169        return HStack(spacing: theme.spacing.xs) {170            ForEach(segments.indices, id: \.self) { index in171                Text(verbatim: segments[index].map { String($0) } ?? " ")172                    .font(theme.font(.monospacedValue))173                    .foregroundStyle(theme.color(.textPrimary))174                    .minimumScaleFactor(0.5)175                    .lineLimit(1)176                    .frame(maxWidth: .infinity, minHeight: boxHeight)177                    .background(theme.color(.surface), in: theme.shape(\.small))178                    .glassFieldOutline(isFocused: isFocused && index == (active ?? length - 1), hasError: hasError, in: theme.shape(\.small))179            }180        }181        .environment(\.layoutDirection, .leftToRight)182    }183}184
Files main
Menu

Theme