Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassForms/Selection/GlassSlider.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 SwiftUI4243/// Arithmetic of a slider. Pure.44public enum GlassSliderMath {45 /// `value` brought inside `bounds` and, with a step, onto the nearest step counted from the lower bound.46 public static func snapped(_ value: Double, in bounds: ClosedRange<Double>, step: Double?) -> Double {47 let clamped = min(max(value, bounds.lowerBound), bounds.upperBound)48 guard let step, step > 0 else { return clamped }49 let index = ((clamped - bounds.lowerBound) / step).rounded()50 return min(GlassStepperMath.value(atStep: index, from: bounds.lowerBound, step: step), bounds.upperBound)51 }5253 /// Position of `value` inside `bounds`, from 0 to 1. An empty range gives 0.54 public static func fraction(_ value: Double, in bounds: ClosedRange<Double>) -> Double {55 let span = bounds.upperBound - bounds.lowerBound56 guard span > 0 else { return 0 }57 return min(max((value - bounds.lowerBound) / span, 0), 1)58 }5960 /// Most tick marks drawn under a track; with more steps than that, marks would touch.61 public static let maximumTicks = 216263 /// Positions (0 to 1) of the tick marks of a slider: one per step when there are at most64 /// ``maximumTicks`` of them, otherwise (and for a continuous slider) the quarters.65 public static func tickFractions(in bounds: ClosedRange<Double>, step: Double?) -> [Double] {66 let span = bounds.upperBound - bounds.lowerBound67 guard span > 0 else { return [] }68 if let step, step > 0 {69 let count = Int((span / step + 1e-9).rounded(.down))70 if count >= 1, count < maximumTicks {71 var fractions = (0...count).map { min(Double($0) * step / span, 1) }72 if let last = fractions.last, last < 1 - 1e-9 { fractions.append(1) }73 return fractions74 }75 }76 return [0, 0.25, 0.5, 0.75, 1]77 }7879 /// Distance between the end of a system slider and the centre of its thumb at that end, used to line the80 /// tick marks up with the thumb's travel. An approximation of the system metrics.81 static var thumbInset: CGFloat {82 #if os(macOS)83 1084 #else85 1986 #endif87 }88}8990/// The system `Slider` with a title, a readable value, tick marks and bound labels.91///92/// ```swift93/// GlassSlider("Brightness", value: $brightness, in: 0...1, format: .percent.precision(.fractionLength(0)))94/// GlassSlider("Temperature", value: $celsius, in: 16...28, step: 0.5, showsTicks: true) { value in95/// Measurement(value: value, unit: UnitTemperature.celsius).formatted()96/// }97/// ```98///99/// The system draws the slider and its Liquid Glass thumb, and makes it adjustable with VoiceOver and the100/// keyboard. GlassKit shows the formatted value next to the title and gives the same text to VoiceOver, so101/// that "50 %" is read rather than "0.5". Tick marks and bound labels sit under the track; they are102/// decoration, the value read-out carries the information.103public struct GlassSlider: View {104 @GlassThemed private var theme105 @Environment(\.isEnabled) private var isEnabled106 private let title: Text107 @Binding private var value: Double108 private let bounds: ClosedRange<Double>109 private let step: Double?110 private let showsValue: Bool111 private let showsBoundLabels: Bool112 private let showsTicks: Bool113 private let format: (Double) -> String114 private let onEditingChanged: @MainActor (Bool) -> Void115116 /// Creates a slider whose value is formatted by a closure.117 /// - Parameters:118 /// - step: distance between two values; `nil` is continuous.119 /// - showsValue: shows the formatted value next to the title.120 /// - showsBoundLabels: shows the formatted bounds under both ends of the track.121 /// - showsTicks: draws a mark under the track for each step (up to ``GlassSliderMath/maximumTicks``122 /// marks; a continuous slider gets quarter marks).123 /// - onEditingChanged: called when a drag starts (`true`) and ends (`false`).124 /// - format: text of a value, built with `FormatStyle` APIs so that it follows the locale.125 public init(126 _ title: LocalizedStringKey,127 value: Binding<Double>,128 in bounds: ClosedRange<Double> = 0...1,129 step: Double? = nil,130 showsValue: Bool = true,131 showsBoundLabels: Bool = false,132 showsTicks: Bool = false,133 onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in },134 format: @escaping (Double) -> String135 ) {136 self.title = Text(title)137 self._value = value138 self.bounds = bounds139 self.step = step140 self.showsValue = showsValue141 self.showsBoundLabels = showsBoundLabels142 self.showsTicks = showsTicks143 self.onEditingChanged = onEditingChanged144 self.format = format145 }146147 /// Creates a slider whose value is formatted by a `FormatStyle`.148 public init<F: FormatStyle>(149 _ title: LocalizedStringKey,150 value: Binding<Double>,151 in bounds: ClosedRange<Double> = 0...1,152 step: Double? = nil,153 format: F,154 showsValue: Bool = true,155 showsBoundLabels: Bool = false,156 showsTicks: Bool = false,157 onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in }158 ) where F.FormatInput == Double, F.FormatOutput == String {159 self.init(title, value: value, in: bounds, step: step, showsValue: showsValue, showsBoundLabels: showsBoundLabels, showsTicks: showsTicks, onEditingChanged: onEditingChanged) { format.format($0) }160 }161162 /// Creates a slider that shows its value as a plain number with up to two decimals.163 public init(164 _ title: LocalizedStringKey,165 value: Binding<Double>,166 in bounds: ClosedRange<Double> = 0...1,167 step: Double? = nil,168 showsValue: Bool = true,169 showsBoundLabels: Bool = false,170 showsTicks: Bool = false,171 onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in }172 ) {173 self.init(title, value: value, in: bounds, step: step, format: FloatingPointFormatStyle<Double>.number.precision(.fractionLength(0...2)), showsValue: showsValue, showsBoundLabels: showsBoundLabels, showsTicks: showsTicks, onEditingChanged: onEditingChanged)174 }175176 public var body: some View {177 VStack(alignment: .leading, spacing: theme.spacing.xxs) {178 ViewThatFits(in: .horizontal) {179 HStack(alignment: .firstTextBaseline) {180 titleText181 Spacer(minLength: theme.spacing.sm)182 valueText183 }184 VStack(alignment: .leading, spacing: theme.spacing.xxs) {185 titleText186 valueText187 }188 }189 .accessibilityHidden(true)190 slider191 .tint(theme.color(.primary))192 .accessibilityValue(Text(verbatim: format(value)))193 if showsTicks {194 ticks195 }196 if showsBoundLabels {197 HStack {198 boundLabel(bounds.lowerBound)199 Spacer(minLength: theme.spacing.sm)200 boundLabel(bounds.upperBound)201 }202 .accessibilityHidden(true)203 }204 }205 }206207 private var titleText: some View {208 title209 .font(theme.font(.body))210 .foregroundStyle(theme.color(.textPrimary))211 }212213 @ViewBuilder214 private var valueText: some View {215 if showsValue {216 Text(verbatim: format(value))217 .font(theme.font(.body).weight(.semibold).monospacedDigit())218 .foregroundStyle(theme.color(.textPrimary))219 .contentTransition(.numericText())220 .opacity(isEnabled ? 1 : 0.55)221 }222 }223224 @ViewBuilder225 private var slider: some View {226 let editing: (Bool) -> Void = { isEditing in onEditingChanged(isEditing) }227 if let step, step > 0 {228 Slider(value: $value, in: bounds, step: step) { title } onEditingChanged: { editing($0) }229 } else {230 Slider(value: $value, in: bounds) { title } onEditingChanged: { editing($0) }231 }232 }233234 /// Marks under the track. The marks up to the current value take the primary colour.235 private var ticks: some View {236 let fractions = GlassSliderMath.tickFractions(in: bounds, step: step)237 let current = GlassSliderMath.fraction(value, in: bounds)238 let reached = theme.color(.primary), rest = theme.color(.textSecondary).opacity(0.45)239 return Canvas { context, size in240 let inset = GlassSliderMath.thumbInset241 let span = max(size.width - 2 * inset, 0)242 for fraction in fractions {243 let rect = CGRect(x: (inset + span * fraction).rounded() - 0.5, y: 0, width: 1, height: size.height)244 context.fill(Path(roundedRect: rect, cornerRadius: 0.5), with: .color(fraction <= current + 1e-9 ? reached : rest))245 }246 }247 .frame(height: 5)248 .environment(\.layoutDirection, .leftToRight)249 .opacity(isEnabled ? 1 : 0.55)250 .accessibilityHidden(true)251 }252253 private func boundLabel(_ bound: Double) -> some View {254 Text(verbatim: format(bound))255 .font(theme.font(.caption).monospacedDigit())256 .foregroundStyle(theme.color(.textSecondary))257 }258}259