Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassForms/Selection/GlassStepper.swift8// Module : SPGlassForms9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0313//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 SPGlassThemes4546/// Arithmetic of a stepper. Pure.47public enum GlassStepperMath {48 public enum Direction: Sendable {49 case increment, decrement50 }5152 /// Number of decimals (0 to 9) needed to write `value` exactly, for cleaning up binary rounding noise.53 static func decimals(of value: Double) -> Int {54 for digits in 0...9 {55 let scaled = value * pow(10, Double(digits))56 if abs(scaled - scaled.rounded()) < 1e-9 * max(1, abs(scaled)) { return digits }57 }58 return 959 }6061 /// `lower + index × step`, rounded to the decimals of `lower` and `step`, so that three steps of 0.1 give62 /// 0.3 and not 0.30000000000000004.63 public static func value(atStep index: Double, from lower: Double, step: Double) -> Double {64 let raw = lower + index * step65 let scale = pow(10, Double(max(decimals(of: step), decimals(of: lower))))66 return (raw * scale).rounded() / scale67 }6869 /// The value after one press.70 ///71 /// Steps are counted from the lower bound. A value lying between two steps moves to the next step in the72 /// direction pressed, not a full step away. The result never leaves `bounds`: when the upper bound is not73 /// on a step, incrementing stops at the bound itself, and decrementing from there returns to the last step.74 /// A step of zero or less leaves the value unchanged (clamped).75 public static func stepped(_ value: Double, by step: Double, _ direction: Direction, in bounds: ClosedRange<Double>) -> Double {76 let lower = bounds.lowerBound, upper = bounds.upperBound77 let clamped = min(max(value, lower), upper)78 guard step > 0 else { return clamped }79 let position = (clamped - lower) / step80 let nearest = position.rounded()81 let isOnStep = abs(position - nearest) < 1e-9 * max(1, abs(position))82 let index: Double83 switch direction {84 case .increment: index = isOnStep ? nearest + 1 : position.rounded(.up)85 case .decrement: index = isOnStep ? nearest - 1 : position.rounded(.down)86 }87 return min(max(self.value(atStep: index, from: lower, step: step), lower), upper)88 }8990 public static func canIncrement(_ value: Double, in bounds: ClosedRange<Double>) -> Bool {91 value < bounds.upperBound92 }9394 public static func canDecrement(_ value: Double, in bounds: ClosedRange<Double>) -> Bool {95 value > bounds.lowerBound96 }97}9899/// The system `Stepper` with bounds, a step and a formatted value.100///101/// ```swift102/// GlassStepper("Guests", value: $guests, in: 1...12)103/// GlassStepper("Dose", value: $dose, in: 0...2.5, step: 0.25) { value in104/// Measurement(value: value, unit: UnitMass.milligrams).formatted()105/// }106/// ```107///108/// The system draws the control. The value is shown next to the title and given to VoiceOver, which adjusts109/// it with a vertical swipe. At a bound, the corresponding button is disabled.110public struct GlassStepper: View {111 @GlassThemed private var theme112 private let title: Text113 @Binding private var value: Double114 private let bounds: ClosedRange<Double>115 private let step: Double116 private let format: (Double) -> String117118 /// Creates a stepper over a `Double`, formatted by a closure.119 /// - Parameter format: text of a value, built with `FormatStyle` APIs so that it follows the locale.120 public init(121 _ title: LocalizedStringKey,122 value: Binding<Double>,123 in bounds: ClosedRange<Double>,124 step: Double = 1,125 format: @escaping (Double) -> String = { $0.formatted(.number.precision(.fractionLength(0...3))) }126 ) {127 self.title = Text(title)128 self._value = value129 self.bounds = bounds130 self.step = step131 self.format = format132 }133134 /// Creates a stepper over an `Int`.135 public init(136 _ title: LocalizedStringKey,137 value: Binding<Int>,138 in bounds: ClosedRange<Int>,139 step: Int = 1,140 format: @escaping (Int) -> String = { $0.formatted(.number) }141 ) {142 self.title = Text(title)143 self._value = Binding {144 Double(value.wrappedValue)145 } set: { newValue in146 value.wrappedValue = Int(newValue.rounded())147 }148 self.bounds = Double(bounds.lowerBound)...Double(bounds.upperBound)149 self.step = Double(max(step, 1))150 self.format = { format(Int($0.rounded())) }151 }152153 public var body: some View {154 Stepper(label: {155 ViewThatFits(in: .horizontal) {156 HStack(alignment: .firstTextBaseline) {157 titleText158 Spacer(minLength: theme.spacing.sm)159 valueText160 }161 VStack(alignment: .leading, spacing: theme.spacing.xxs) {162 titleText163 valueText164 }165 }166 }, onIncrement: GlassStepperMath.canIncrement(value, in: bounds) ? { press(.increment) } : nil,167 onDecrement: GlassStepperMath.canDecrement(value, in: bounds) ? { press(.decrement) } : nil)168 .accessibilityElement(children: .ignore)169 .accessibilityLabel(title)170 .accessibilityValue(Text(verbatim: format(value)))171 .accessibilityAdjustableAction { direction in172 switch direction {173 case .increment: press(.increment)174 case .decrement: press(.decrement)175 @unknown default: break176 }177 }178 }179180 private func press(_ direction: GlassStepperMath.Direction) {181 value = GlassStepperMath.stepped(value, by: step, direction, in: bounds)182 }183184 private var titleText: some View {185 title186 .font(theme.font(.body))187 .foregroundStyle(theme.color(.textPrimary))188 }189190 private var valueText: some View {191 Text(verbatim: format(value))192 .font(theme.font(.body).weight(.semibold).monospacedDigit())193 .foregroundStyle(theme.color(.textPrimary))194 .contentTransition(.numericText())195 }196}197