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-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 SwiftUI4243/// Arithmetic of a stepper. Pure.44public enum GlassStepperMath {45 public enum Direction: Sendable {46 case increment, decrement47 }4849 /// Number of decimals (0 to 9) needed to write `value` exactly, for cleaning up binary rounding noise.50 static func decimals(of value: Double) -> Int {51 for digits in 0...9 {52 let scaled = value * pow(10, Double(digits))53 if abs(scaled - scaled.rounded()) < 1e-9 * max(1, abs(scaled)) { return digits }54 }55 return 956 }5758 /// `lower + index × step`, rounded to the decimals of `lower` and `step`, so that three steps of 0.1 give59 /// 0.3 and not 0.30000000000000004.60 public static func value(atStep index: Double, from lower: Double, step: Double) -> Double {61 let raw = lower + index * step62 let scale = pow(10, Double(max(decimals(of: step), decimals(of: lower))))63 return (raw * scale).rounded() / scale64 }6566 /// The value after one press.67 ///68 /// Steps are counted from the lower bound. A value lying between two steps moves to the next step in the69 /// direction pressed, not a full step away. The result never leaves `bounds`: when the upper bound is not70 /// on a step, incrementing stops at the bound itself, and decrementing from there returns to the last step.71 /// A step of zero or less leaves the value unchanged (clamped).72 public static func stepped(_ value: Double, by step: Double, _ direction: Direction, in bounds: ClosedRange<Double>) -> Double {73 let lower = bounds.lowerBound, upper = bounds.upperBound74 let clamped = min(max(value, lower), upper)75 guard step > 0 else { return clamped }76 let position = (clamped - lower) / step77 let nearest = position.rounded()78 let isOnStep = abs(position - nearest) < 1e-9 * max(1, abs(position))79 let index: Double80 switch direction {81 case .increment: index = isOnStep ? nearest + 1 : position.rounded(.up)82 case .decrement: index = isOnStep ? nearest - 1 : position.rounded(.down)83 }84 return min(max(self.value(atStep: index, from: lower, step: step), lower), upper)85 }8687 public static func canIncrement(_ value: Double, in bounds: ClosedRange<Double>) -> Bool {88 value < bounds.upperBound89 }9091 public static func canDecrement(_ value: Double, in bounds: ClosedRange<Double>) -> Bool {92 value > bounds.lowerBound93 }94}9596/// The system `Stepper` with bounds, a step and a formatted value.97///98/// ```swift99/// GlassStepper("Guests", value: $guests, in: 1...12)100/// GlassStepper("Dose", value: $dose, in: 0...2.5, step: 0.25) { value in101/// Measurement(value: value, unit: UnitMass.milligrams).formatted()102/// }103/// ```104///105/// The system draws the control. The value is shown next to the title and given to VoiceOver, which adjusts106/// it with a vertical swipe. At a bound, the corresponding button is disabled.107public struct GlassStepper: View {108 @GlassThemed private var theme109 private let title: Text110 @Binding private var value: Double111 private let bounds: ClosedRange<Double>112 private let step: Double113 private let format: (Double) -> String114115 /// Creates a stepper over a `Double`, formatted by a closure.116 /// - Parameter format: text of a value, built with `FormatStyle` APIs so that it follows the locale.117 public init(118 _ title: LocalizedStringKey,119 value: Binding<Double>,120 in bounds: ClosedRange<Double>,121 step: Double = 1,122 format: @escaping (Double) -> String = { $0.formatted(.number.precision(.fractionLength(0...3))) }123 ) {124 self.title = Text(title)125 self._value = value126 self.bounds = bounds127 self.step = step128 self.format = format129 }130131 /// Creates a stepper over an `Int`.132 public init(133 _ title: LocalizedStringKey,134 value: Binding<Int>,135 in bounds: ClosedRange<Int>,136 step: Int = 1,137 format: @escaping (Int) -> String = { $0.formatted(.number) }138 ) {139 self.title = Text(title)140 self._value = Binding {141 Double(value.wrappedValue)142 } set: { newValue in143 value.wrappedValue = Int(newValue.rounded())144 }145 self.bounds = Double(bounds.lowerBound)...Double(bounds.upperBound)146 self.step = Double(max(step, 1))147 self.format = { format(Int($0.rounded())) }148 }149150 public var body: some View {151 Stepper(label: {152 ViewThatFits(in: .horizontal) {153 HStack(alignment: .firstTextBaseline) {154 titleText155 Spacer(minLength: theme.spacing.sm)156 valueText157 }158 VStack(alignment: .leading, spacing: theme.spacing.xxs) {159 titleText160 valueText161 }162 }163 }, onIncrement: GlassStepperMath.canIncrement(value, in: bounds) ? { press(.increment) } : nil,164 onDecrement: GlassStepperMath.canDecrement(value, in: bounds) ? { press(.decrement) } : nil)165 .accessibilityElement(children: .ignore)166 .accessibilityLabel(title)167 .accessibilityValue(Text(verbatim: format(value)))168 .accessibilityAdjustableAction { direction in169 switch direction {170 case .increment: press(.increment)171 case .decrement: press(.decrement)172 @unknown default: break173 }174 }175 }176177 private func press(_ direction: GlassStepperMath.Direction) {178 value = GlassStepperMath.stepped(value, by: step, direction, in: bounds)179 }180181 private var titleText: some View {182 title183 .font(theme.font(.body))184 .foregroundStyle(theme.color(.textPrimary))185 }186187 private var valueText: some View {188 Text(verbatim: format(value))189 .font(theme.font(.body).monospacedDigit())190 .foregroundStyle(theme.color(.textSecondary))191 }192}193