// ============================================================================= // SP BOUCHER | SOFTWARE & RESEARCH // ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING // ============================================================================= // // Project : SP GlassKit // File : Sources/SPGlassForms/Selection/GlassSlider.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 slider. Pure. public enum GlassSliderMath { /// `value` brought inside `bounds` and, with a step, onto the nearest step counted from the lower bound. public static func snapped(_ value: Double, in bounds: ClosedRange, step: Double?) -> Double { let clamped = min(max(value, bounds.lowerBound), bounds.upperBound) guard let step, step > 0 else { return clamped } let index = ((clamped - bounds.lowerBound) / step).rounded() return min(GlassStepperMath.value(atStep: index, from: bounds.lowerBound, step: step), bounds.upperBound) } /// Position of `value` inside `bounds`, from 0 to 1. An empty range gives 0. public static func fraction(_ value: Double, in bounds: ClosedRange) -> Double { let span = bounds.upperBound - bounds.lowerBound guard span > 0 else { return 0 } return min(max((value - bounds.lowerBound) / span, 0), 1) } /// Most tick marks drawn under a track; with more steps than that, marks would touch. public static let maximumTicks = 21 /// Positions (0 to 1) of the tick marks of a slider: one per step when there are at most /// ``maximumTicks`` of them, otherwise (and for a continuous slider) the quarters. public static func tickFractions(in bounds: ClosedRange, step: Double?) -> [Double] { let span = bounds.upperBound - bounds.lowerBound guard span > 0 else { return [] } if let step, step > 0 { let count = Int((span / step + 1e-9).rounded(.down)) if count >= 1, count < maximumTicks { var fractions = (0...count).map { min(Double($0) * step / span, 1) } if let last = fractions.last, last < 1 - 1e-9 { fractions.append(1) } return fractions } } return [0, 0.25, 0.5, 0.75, 1] } /// Distance between the end of a system slider and the centre of its thumb at that end, used to line the /// tick marks up with the thumb's travel. An approximation of the system metrics. static var thumbInset: CGFloat { #if os(macOS) 10 #else 19 #endif } } /// The system `Slider` with a title, a readable value, tick marks and bound labels. /// /// ```swift /// GlassSlider("Brightness", value: $brightness, in: 0...1, format: .percent.precision(.fractionLength(0))) /// GlassSlider("Temperature", value: $celsius, in: 16...28, step: 0.5, showsTicks: true) { value in /// Measurement(value: value, unit: UnitTemperature.celsius).formatted() /// } /// ``` /// /// The system draws the slider and its Liquid Glass thumb, and makes it adjustable with VoiceOver and the /// keyboard. GlassKit shows the formatted value next to the title and gives the same text to VoiceOver, so /// that "50 %" is read rather than "0.5". Tick marks and bound labels sit under the track; they are /// decoration, the value read-out carries the information. public struct GlassSlider: View { @GlassThemed private var theme @Environment(\.isEnabled) private var isEnabled private let title: Text @Binding private var value: Double private let bounds: ClosedRange private let step: Double? private let showsValue: Bool private let showsBoundLabels: Bool private let showsTicks: Bool private let format: (Double) -> String private let onEditingChanged: @MainActor (Bool) -> Void /// Creates a slider whose value is formatted by a closure. /// - Parameters: /// - step: distance between two values; `nil` is continuous. /// - showsValue: shows the formatted value next to the title. /// - showsBoundLabels: shows the formatted bounds under both ends of the track. /// - showsTicks: draws a mark under the track for each step (up to ``GlassSliderMath/maximumTicks`` /// marks; a continuous slider gets quarter marks). /// - onEditingChanged: called when a drag starts (`true`) and ends (`false`). /// - format: text of a value, built with `FormatStyle` APIs so that it follows the locale. public init( _ title: LocalizedStringKey, value: Binding, in bounds: ClosedRange = 0...1, step: Double? = nil, showsValue: Bool = true, showsBoundLabels: Bool = false, showsTicks: Bool = false, onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in }, format: @escaping (Double) -> String ) { self.title = Text(title) self._value = value self.bounds = bounds self.step = step self.showsValue = showsValue self.showsBoundLabels = showsBoundLabels self.showsTicks = showsTicks self.onEditingChanged = onEditingChanged self.format = format } /// Creates a slider whose value is formatted by a `FormatStyle`. public init( _ title: LocalizedStringKey, value: Binding, in bounds: ClosedRange = 0...1, step: Double? = nil, format: F, showsValue: Bool = true, showsBoundLabels: Bool = false, showsTicks: Bool = false, onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in } ) where F.FormatInput == Double, F.FormatOutput == String { self.init(title, value: value, in: bounds, step: step, showsValue: showsValue, showsBoundLabels: showsBoundLabels, showsTicks: showsTicks, onEditingChanged: onEditingChanged) { format.format($0) } } /// Creates a slider that shows its value as a plain number with up to two decimals. public init( _ title: LocalizedStringKey, value: Binding, in bounds: ClosedRange = 0...1, step: Double? = nil, showsValue: Bool = true, showsBoundLabels: Bool = false, showsTicks: Bool = false, onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in } ) { self.init(title, value: value, in: bounds, step: step, format: FloatingPointFormatStyle.number.precision(.fractionLength(0...2)), showsValue: showsValue, showsBoundLabels: showsBoundLabels, showsTicks: showsTicks, onEditingChanged: onEditingChanged) } public var body: some View { VStack(alignment: .leading, spacing: theme.spacing.xxs) { ViewThatFits(in: .horizontal) { HStack(alignment: .firstTextBaseline) { titleText Spacer(minLength: theme.spacing.sm) valueText } VStack(alignment: .leading, spacing: theme.spacing.xxs) { titleText valueText } } .accessibilityHidden(true) slider .tint(theme.color(.primary)) .accessibilityValue(Text(verbatim: format(value))) if showsTicks { ticks } if showsBoundLabels { HStack { boundLabel(bounds.lowerBound) Spacer(minLength: theme.spacing.sm) boundLabel(bounds.upperBound) } .accessibilityHidden(true) } } } private var titleText: some View { title .font(theme.font(.body)) .foregroundStyle(theme.color(.textPrimary)) } @ViewBuilder private var valueText: some View { if showsValue { Text(verbatim: format(value)) .font(theme.font(.body).weight(.semibold).monospacedDigit()) .foregroundStyle(theme.color(.textPrimary)) .contentTransition(.numericText()) .opacity(isEnabled ? 1 : 0.55) } } @ViewBuilder private var slider: some View { let editing: (Bool) -> Void = { isEditing in onEditingChanged(isEditing) } if let step, step > 0 { Slider(value: $value, in: bounds, step: step) { title } onEditingChanged: { editing($0) } } else { Slider(value: $value, in: bounds) { title } onEditingChanged: { editing($0) } } } /// Marks under the track. The marks up to the current value take the primary colour. private var ticks: some View { let fractions = GlassSliderMath.tickFractions(in: bounds, step: step) let current = GlassSliderMath.fraction(value, in: bounds) let reached = theme.color(.primary), rest = theme.color(.textSecondary).opacity(0.45) return Canvas { context, size in let inset = GlassSliderMath.thumbInset let span = max(size.width - 2 * inset, 0) for fraction in fractions { let rect = CGRect(x: (inset + span * fraction).rounded() - 0.5, y: 0, width: 1, height: size.height) context.fill(Path(roundedRect: rect, cornerRadius: 0.5), with: .color(fraction <= current + 1e-9 ? reached : rest)) } } .frame(height: 5) .environment(\.layoutDirection, .leftToRight) .opacity(isEnabled ? 1 : 0.55) .accessibilityHidden(true) } private func boundLabel(_ bound: Double) -> some View { Text(verbatim: format(bound)) .font(theme.font(.caption).monospacedDigit()) .foregroundStyle(theme.color(.textSecondary)) } }