SPB Git

Repository Public MIT

GlassSlider.swift 8.2 KB 198 lines swift

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-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 SwiftUI42import SPGlassCore43import SPGlassTokens44import SPGlassThemes4546/// Arithmetic of a slider. Pure.47public enum GlassSliderMath {48    /// `value` brought inside `bounds` and, with a step, onto the nearest step counted from the lower bound.49    public static func snapped(_ value: Double, in bounds: ClosedRange<Double>, step: Double?) -> Double {50        let clamped = min(max(value, bounds.lowerBound), bounds.upperBound)51        guard let step, step > 0 else { return clamped }52        let index = ((clamped - bounds.lowerBound) / step).rounded()53        return min(GlassStepperMath.value(atStep: index, from: bounds.lowerBound, step: step), bounds.upperBound)54    }5556    /// Position of `value` inside `bounds`, from 0 to 1. An empty range gives 0.57    public static func fraction(_ value: Double, in bounds: ClosedRange<Double>) -> Double {58        let span = bounds.upperBound - bounds.lowerBound59        guard span > 0 else { return 0 }60        return min(max((value - bounds.lowerBound) / span, 0), 1)61    }62}6364/// The system `Slider` with a title, a readable value and bound labels.65///66/// ```swift67/// GlassSlider("Brightness", value: $brightness, in: 0...1, format: .percent.precision(.fractionLength(0)))68/// GlassSlider("Temperature", value: $celsius, in: 16...28, step: 0.5) { value in69///     Measurement(value: value, unit: UnitTemperature.celsius).formatted()70/// }71/// ```72///73/// The system draws the slider and its Liquid Glass thumb, and makes it adjustable with VoiceOver and the74/// keyboard. GlassKit shows the formatted value next to the title and gives the same text to VoiceOver, so75/// that "50 %" is read rather than "0.5".76public struct GlassSlider: View {77    @GlassThemed private var theme78    private let title: Text79    @Binding private var value: Double80    private let bounds: ClosedRange<Double>81    private let step: Double?82    private let showsValue: Bool83    private let showsBoundLabels: Bool84    private let format: (Double) -> String85    private let onEditingChanged: @MainActor (Bool) -> Void8687    /// Creates a slider whose value is formatted by a closure.88    /// - Parameters:89    ///   - step: distance between two values; `nil` is continuous.90    ///   - showsValue: shows the formatted value next to the title.91    ///   - showsBoundLabels: shows the formatted bounds at both ends of the track.92    ///   - onEditingChanged: called when a drag starts (`true`) and ends (`false`).93    ///   - format: text of a value, built with `FormatStyle` APIs so that it follows the locale.94    public init(95        _ title: LocalizedStringKey,96        value: Binding<Double>,97        in bounds: ClosedRange<Double> = 0...1,98        step: Double? = nil,99        showsValue: Bool = true,100        showsBoundLabels: Bool = false,101        onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in },102        format: @escaping (Double) -> String103    ) {104        self.title = Text(title)105        self._value = value106        self.bounds = bounds107        self.step = step108        self.showsValue = showsValue109        self.showsBoundLabels = showsBoundLabels110        self.onEditingChanged = onEditingChanged111        self.format = format112    }113114    /// Creates a slider whose value is formatted by a `FormatStyle`.115    public init<F: FormatStyle>(116        _ title: LocalizedStringKey,117        value: Binding<Double>,118        in bounds: ClosedRange<Double> = 0...1,119        step: Double? = nil,120        format: F,121        showsValue: Bool = true,122        showsBoundLabels: Bool = false,123        onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in }124    ) where F.FormatInput == Double, F.FormatOutput == String {125        self.init(title, value: value, in: bounds, step: step, showsValue: showsValue, showsBoundLabels: showsBoundLabels, onEditingChanged: onEditingChanged) { format.format($0) }126    }127128    /// Creates a slider that shows its value as a plain number with up to two decimals.129    public init(130        _ title: LocalizedStringKey,131        value: Binding<Double>,132        in bounds: ClosedRange<Double> = 0...1,133        step: Double? = nil,134        showsValue: Bool = true,135        showsBoundLabels: Bool = false,136        onEditingChanged: @escaping @MainActor (Bool) -> Void = { _ in }137    ) {138        self.init(title, value: value, in: bounds, step: step, format: FloatingPointFormatStyle<Double>.number.precision(.fractionLength(0...2)), showsValue: showsValue, showsBoundLabels: showsBoundLabels, onEditingChanged: onEditingChanged)139    }140141    public var body: some View {142        VStack(alignment: .leading, spacing: theme.spacing.xxs) {143            ViewThatFits(in: .horizontal) {144                HStack(alignment: .firstTextBaseline) {145                    titleText146                    Spacer(minLength: theme.spacing.sm)147                    valueText148                }149                VStack(alignment: .leading, spacing: theme.spacing.xxs) {150                    titleText151                    valueText152                }153            }154            .accessibilityHidden(true)155            slider156                .tint(theme.color(.primary))157                .accessibilityValue(Text(verbatim: format(value)))158        }159    }160161    private var titleText: some View {162        title163            .font(theme.font(.body))164            .foregroundStyle(theme.color(.textPrimary))165    }166167    @ViewBuilder168    private var valueText: some View {169        if showsValue {170            Text(verbatim: format(value))171                .font(theme.font(.body).monospacedDigit())172                .foregroundStyle(theme.color(.textSecondary))173        }174    }175176    @ViewBuilder177    private var slider: some View {178        let editing: (Bool) -> Void = { isEditing in onEditingChanged(isEditing) }179        if let step, step > 0 {180            if showsBoundLabels {181                Slider(value: $value, in: bounds, step: step) { title } minimumValueLabel: { boundLabel(bounds.lowerBound) } maximumValueLabel: { boundLabel(bounds.upperBound) } onEditingChanged: { editing($0) }182            } else {183                Slider(value: $value, in: bounds, step: step) { title } onEditingChanged: { editing($0) }184            }185        } else if showsBoundLabels {186            Slider(value: $value, in: bounds) { title } minimumValueLabel: { boundLabel(bounds.lowerBound) } maximumValueLabel: { boundLabel(bounds.upperBound) } onEditingChanged: { editing($0) }187        } else {188            Slider(value: $value, in: bounds) { title } onEditingChanged: { editing($0) }189        }190    }191192    private func boundLabel(_ bound: Double) -> some View {193        Text(verbatim: format(bound))194            .font(theme.font(.caption))195            .foregroundStyle(theme.color(.textSecondary))196    }197}198
Files main
Menu

Theme