// ============================================================================= // SP BOUCHER | SOFTWARE & RESEARCH // ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING // ============================================================================= // // Project : SP GlassKit // File : Sources/SPGlassForms/Selection/GlassStepper.swift // Module : SPGlassForms // Repository : https://git.spboucher.ai/sp-glasskit // Project Website : https://glass.spboucher.ai // Created : 2026-12-02 // Last Modified : 2026-12-03 // // Author : Simon-Pierre Boucher // Position : Professor of Finance // Institution : Université du Québec en Outaouais (UQO) // Organization : SP Boucher // Website : https://spboucher.ai // Git : https://git.spboucher.ai // // Preferred Contact: contact@spboucher.ai // Development : dev@spboucher.ai // Support : support@spboucher.ai // Security/Admin : admin@spboucher.ai // // Copyright (c) 2026 // Simon-Pierre Boucher // All rights reserved where applicable. This file is governed by the // applicable project license, copyright notices and relevant law. // Existing third-party rights and notices remain unaffected. // // License : MIT // // Do not embed credentials, private keys, access tokens, // certificates or confidential personal information. // // ============================================================================= // END OF SP BOUCHER SOURCE HEADER // ============================================================================= import SwiftUI /// Arithmetic of a stepper. Pure. public enum GlassStepperMath { public enum Direction: Sendable { case increment, decrement } /// Number of decimals (0 to 9) needed to write `value` exactly, for cleaning up binary rounding noise. static func decimals(of value: Double) -> Int { for digits in 0...9 { let scaled = value * pow(10, Double(digits)) if abs(scaled - scaled.rounded()) < 1e-9 * max(1, abs(scaled)) { return digits } } return 9 } /// `lower + index × step`, rounded to the decimals of `lower` and `step`, so that three steps of 0.1 give /// 0.3 and not 0.30000000000000004. public static func value(atStep index: Double, from lower: Double, step: Double) -> Double { let raw = lower + index * step let scale = pow(10, Double(max(decimals(of: step), decimals(of: lower)))) return (raw * scale).rounded() / scale } /// The value after one press. /// /// Steps are counted from the lower bound. A value lying between two steps moves to the next step in the /// direction pressed, not a full step away. The result never leaves `bounds`: when the upper bound is not /// on a step, incrementing stops at the bound itself, and decrementing from there returns to the last step. /// A step of zero or less leaves the value unchanged (clamped). public static func stepped(_ value: Double, by step: Double, _ direction: Direction, in bounds: ClosedRange) -> Double { let lower = bounds.lowerBound, upper = bounds.upperBound let clamped = min(max(value, lower), upper) guard step > 0 else { return clamped } let position = (clamped - lower) / step let nearest = position.rounded() let isOnStep = abs(position - nearest) < 1e-9 * max(1, abs(position)) let index: Double switch direction { case .increment: index = isOnStep ? nearest + 1 : position.rounded(.up) case .decrement: index = isOnStep ? nearest - 1 : position.rounded(.down) } return min(max(self.value(atStep: index, from: lower, step: step), lower), upper) } public static func canIncrement(_ value: Double, in bounds: ClosedRange) -> Bool { value < bounds.upperBound } public static func canDecrement(_ value: Double, in bounds: ClosedRange) -> Bool { value > bounds.lowerBound } } /// The system `Stepper` with bounds, a step and a formatted value. /// /// ```swift /// GlassStepper("Guests", value: $guests, in: 1...12) /// GlassStepper("Dose", value: $dose, in: 0...2.5, step: 0.25) { value in /// Measurement(value: value, unit: UnitMass.milligrams).formatted() /// } /// ``` /// /// The system draws the control. The value is shown next to the title and given to VoiceOver, which adjusts /// it with a vertical swipe. At a bound, the corresponding button is disabled. public struct GlassStepper: View { @GlassThemed private var theme private let title: Text @Binding private var value: Double private let bounds: ClosedRange private let step: Double private let format: (Double) -> String /// Creates a stepper over a `Double`, formatted by a closure. /// - Parameter format: text of a value, built with `FormatStyle` APIs so that it follows the locale. public init( _ title: LocalizedStringKey, value: Binding, in bounds: ClosedRange, step: Double = 1, format: @escaping (Double) -> String = { $0.formatted(.number.precision(.fractionLength(0...3))) } ) { self.title = Text(title) self._value = value self.bounds = bounds self.step = step self.format = format } /// Creates a stepper over an `Int`. public init( _ title: LocalizedStringKey, value: Binding, in bounds: ClosedRange, step: Int = 1, format: @escaping (Int) -> String = { $0.formatted(.number) } ) { self.title = Text(title) self._value = Binding { Double(value.wrappedValue) } set: { newValue in value.wrappedValue = Int(newValue.rounded()) } self.bounds = Double(bounds.lowerBound)...Double(bounds.upperBound) self.step = Double(max(step, 1)) self.format = { format(Int($0.rounded())) } } public var body: some View { Stepper(label: { ViewThatFits(in: .horizontal) { HStack(alignment: .firstTextBaseline) { titleText Spacer(minLength: theme.spacing.sm) valueText } VStack(alignment: .leading, spacing: theme.spacing.xxs) { titleText valueText } } }, onIncrement: GlassStepperMath.canIncrement(value, in: bounds) ? { press(.increment) } : nil, onDecrement: GlassStepperMath.canDecrement(value, in: bounds) ? { press(.decrement) } : nil) .accessibilityElement(children: .ignore) .accessibilityLabel(title) .accessibilityValue(Text(verbatim: format(value))) .accessibilityAdjustableAction { direction in switch direction { case .increment: press(.increment) case .decrement: press(.decrement) @unknown default: break } } } private func press(_ direction: GlassStepperMath.Direction) { value = GlassStepperMath.stepped(value, by: step, direction, in: bounds) } private var titleText: some View { title .font(theme.font(.body)) .foregroundStyle(theme.color(.textPrimary)) } private var valueText: some View { Text(verbatim: format(value)) .font(theme.font(.body).weight(.semibold).monospacedDigit()) .foregroundStyle(theme.color(.textPrimary)) .contentTransition(.numericText()) } }