SPB Git

Repository Public MIT

GlassProgress.swift 7.5 KB 207 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassComponents/Feedback/GlassProgress.swift8// Module           : SPGlassComponents9// 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 SPGlassThemes45import SPGlassEffects4647/// Shape of a ``GlassProgress``.48public enum GlassProgressStyle: String, CaseIterable, Sendable {49    /// A horizontal bar.50    case linear51    /// A ring when determinate, a spinner when indeterminate.52    case circular53}5455/// Pure arithmetic and formatting of progress values.56public enum GlassProgressMath {57    /// Completed fraction between 0 and 1. A total that is zero, negative or not finite gives 0; so does a58    /// value that is not finite.59    public static func fraction(value: Double, total: Double = 1) -> Double {60        guard value.isFinite, total.isFinite, total > 0 else { return 0 }61        return min(max(value / total, 0), 1)62    }6364    /// The fraction as a whole percentage in the given locale ("42 %", "42%").65    public static func percentText(_ fraction: Double, locale: Locale = .current) -> String {66        Self.fraction(value: fraction).formatted(.percent.precision(.fractionLength(0)).locale(locale))67    }6869    /// The whole percentage, 0 to 100.70    public static func percent(_ fraction: Double) -> Int {71        Int((Self.fraction(value: fraction) * 100).rounded())72    }73}7475/// A system progress indicator with an optional label, percentage and cancel button.76///77/// ```swift78/// GlassProgress("Uploading", value: uploaded, total: fileSize, onCancel: { cancelUpload() })79/// GlassProgress("Connecting")            // indeterminate80/// ```81///82/// The indicator is the native `ProgressView`; GlassKit adds the label row, clamps the value and exposes the83/// percentage as the accessibility value.84public struct GlassProgress: View {85    @GlassThemed private var theme86    private let label: Text?87    private let fraction: Double?88    private let style: GlassProgressStyle89    private let showsPercent: Bool90    private let onCancel: (@MainActor () -> Void)?9192    /// Creates a determinate indicator.93    ///94    /// - Parameters:95    ///   - value: completed amount; clamped to `0...total`.96    ///   - total: amount that means "finished".97    ///   - showsPercent: shows the percentage next to the label.98    ///   - onCancel: when set, a cancel button is shown.99    public init(100        _ label: LocalizedStringKey? = nil,101        value: Double,102        total: Double = 1,103        style: GlassProgressStyle = .linear,104        showsPercent: Bool = true,105        onCancel: (@MainActor () -> Void)? = nil106    ) {107        self.init(label: label.map { Text($0) }, fraction: GlassProgressMath.fraction(value: value, total: total), style: style, showsPercent: showsPercent, onCancel: onCancel)108    }109110    /// Creates an indeterminate indicator, for work whose length is unknown.111    public init(112        _ label: LocalizedStringKey? = nil,113        style: GlassProgressStyle = .linear,114        onCancel: (@MainActor () -> Void)? = nil115    ) {116        self.init(label: label.map { Text($0) }, fraction: nil, style: style, showsPercent: false, onCancel: onCancel)117    }118119    /// Creates an indicator from a `Text` label and an optional fraction (`nil` is indeterminate).120    public init(121        label: Text?,122        fraction: Double?,123        style: GlassProgressStyle = .linear,124        showsPercent: Bool = true,125        onCancel: (@MainActor () -> Void)? = nil126    ) {127        self.label = label128        self.fraction = fraction.map { GlassProgressMath.fraction(value: $0) }129        self.style = style130        self.showsPercent = showsPercent131        self.onCancel = onCancel132    }133134    public var body: some View {135        HStack(alignment: .center, spacing: theme.spacing.sm) {136            Group {137                switch style {138                case .linear:139                    VStack(alignment: .leading, spacing: theme.spacing.xxs) {140                        header141                        indicator.progressViewStyle(.linear)142                    }143                case .circular:144                    HStack(spacing: theme.spacing.xs) {145                        indicator.progressViewStyle(.circular)146                        header147                    }148                }149            }150            .accessibilityElement(children: .ignore)151            .accessibilityLabel(label ?? Text(GlassL10n.string(.loading)))152            .accessibilityValue(accessibilityValue)153            .accessibilityAddTraits(.updatesFrequently)154            if let onCancel {155                Button(action: onCancel) {156                    Label(GlassL10n.string(.cancel), systemImage: "xmark.circle.fill")157                        .labelStyle(.iconOnly)158                }159                .buttonStyle(.borderless)160                .glassMinimumHitTarget()161            }162        }163        .tint(theme.color(.primary))164    }165166    @ViewBuilder167    private var indicator: some View {168        if let fraction {169            ProgressView(value: fraction)170        } else {171            ProgressView()172        }173    }174175    @ViewBuilder176    private var header: some View {177        if label != nil || percentText != nil {178            HStack(alignment: .firstTextBaseline, spacing: theme.spacing.xs) {179                if let label {180                    label181                        .font(theme.font(.callout))182                        .foregroundStyle(theme.color(.textPrimary))183                }184                if style == .linear { Spacer(minLength: theme.spacing.xs) }185                if let percentText {186                    Text(verbatim: percentText)187                        .font(theme.font(.callout).monospacedDigit())188                        .foregroundStyle(theme.color(.textSecondary))189                }190            }191        }192    }193194    private var percentText: String? {195        guard showsPercent, let fraction else { return nil }196        return GlassProgressMath.percentText(fraction)197    }198199    private var accessibilityValue: Text {200        if let fraction {201            Text(verbatim: GlassL10n.string(.progressPercent, GlassProgressMath.percent(fraction)))202        } else {203            Text(GlassL10n.string(.loading))204        }205    }206}207
Files main
Menu

Theme