SPB Git

Repository Public MIT

GlassProgress.swift 7.4 KB 203 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 SwiftUI4243/// Shape of a ``GlassProgress``.44public enum GlassProgressStyle: String, CaseIterable, Sendable {45    /// A horizontal bar.46    case linear47    /// A ring when determinate, a spinner when indeterminate.48    case circular49}5051/// Pure arithmetic and formatting of progress values.52public enum GlassProgressMath {53    /// Completed fraction between 0 and 1. A total that is zero, negative or not finite gives 0; so does a54    /// value that is not finite.55    public static func fraction(value: Double, total: Double = 1) -> Double {56        guard value.isFinite, total.isFinite, total > 0 else { return 0 }57        return min(max(value / total, 0), 1)58    }5960    /// The fraction as a whole percentage in the given locale ("42 %", "42%").61    public static func percentText(_ fraction: Double, locale: Locale = .current) -> String {62        Self.fraction(value: fraction).formatted(.percent.precision(.fractionLength(0)).locale(locale))63    }6465    /// The whole percentage, 0 to 100.66    public static func percent(_ fraction: Double) -> Int {67        Int((Self.fraction(value: fraction) * 100).rounded())68    }69}7071/// A system progress indicator with an optional label, percentage and cancel button.72///73/// ```swift74/// GlassProgress("Uploading", value: uploaded, total: fileSize, onCancel: { cancelUpload() })75/// GlassProgress("Connecting")            // indeterminate76/// ```77///78/// The indicator is the native `ProgressView`; GlassKit adds the label row, clamps the value and exposes the79/// percentage as the accessibility value.80public struct GlassProgress: View {81    @GlassThemed private var theme82    private let label: Text?83    private let fraction: Double?84    private let style: GlassProgressStyle85    private let showsPercent: Bool86    private let onCancel: (@MainActor () -> Void)?8788    /// Creates a determinate indicator.89    ///90    /// - Parameters:91    ///   - value: completed amount; clamped to `0...total`.92    ///   - total: amount that means "finished".93    ///   - showsPercent: shows the percentage next to the label.94    ///   - onCancel: when set, a cancel button is shown.95    public init(96        _ label: LocalizedStringKey? = nil,97        value: Double,98        total: Double = 1,99        style: GlassProgressStyle = .linear,100        showsPercent: Bool = true,101        onCancel: (@MainActor () -> Void)? = nil102    ) {103        self.init(label: label.map { Text($0) }, fraction: GlassProgressMath.fraction(value: value, total: total), style: style, showsPercent: showsPercent, onCancel: onCancel)104    }105106    /// Creates an indeterminate indicator, for work whose length is unknown.107    public init(108        _ label: LocalizedStringKey? = nil,109        style: GlassProgressStyle = .linear,110        onCancel: (@MainActor () -> Void)? = nil111    ) {112        self.init(label: label.map { Text($0) }, fraction: nil, style: style, showsPercent: false, onCancel: onCancel)113    }114115    /// Creates an indicator from a `Text` label and an optional fraction (`nil` is indeterminate).116    public init(117        label: Text?,118        fraction: Double?,119        style: GlassProgressStyle = .linear,120        showsPercent: Bool = true,121        onCancel: (@MainActor () -> Void)? = nil122    ) {123        self.label = label124        self.fraction = fraction.map { GlassProgressMath.fraction(value: $0) }125        self.style = style126        self.showsPercent = showsPercent127        self.onCancel = onCancel128    }129130    public var body: some View {131        HStack(alignment: .center, spacing: theme.spacing.sm) {132            Group {133                switch style {134                case .linear:135                    VStack(alignment: .leading, spacing: theme.spacing.xxs) {136                        header137                        indicator.progressViewStyle(.linear)138                    }139                case .circular:140                    HStack(spacing: theme.spacing.xs) {141                        indicator.progressViewStyle(.circular)142                        header143                    }144                }145            }146            .accessibilityElement(children: .ignore)147            .accessibilityLabel(label ?? Text(GlassL10n.string(.loading)))148            .accessibilityValue(accessibilityValue)149            .accessibilityAddTraits(.updatesFrequently)150            if let onCancel {151                Button(action: onCancel) {152                    Label(GlassL10n.string(.cancel), systemImage: "xmark.circle.fill")153                        .labelStyle(.iconOnly)154                }155                .buttonStyle(.borderless)156                .glassMinimumHitTarget()157            }158        }159        .tint(theme.color(.primary))160    }161162    @ViewBuilder163    private var indicator: some View {164        if let fraction {165            ProgressView(value: fraction)166        } else {167            ProgressView()168        }169    }170171    @ViewBuilder172    private var header: some View {173        if label != nil || percentText != nil {174            HStack(alignment: .firstTextBaseline, spacing: theme.spacing.xs) {175                if let label {176                    label177                        .font(theme.font(.callout))178                        .foregroundStyle(theme.color(.textPrimary))179                }180                if style == .linear { Spacer(minLength: theme.spacing.xs) }181                if let percentText {182                    Text(verbatim: percentText)183                        .font(theme.font(.callout).monospacedDigit())184                        .foregroundStyle(theme.color(.textSecondary))185                }186            }187        }188    }189190    private var percentText: String? {191        guard showsPercent, let fraction else { return nil }192        return GlassProgressMath.percentText(fraction)193    }194195    private var accessibilityValue: Text {196        if let fraction {197            Text(verbatim: GlassL10n.string(.progressPercent, GlassProgressMath.percent(fraction)))198        } else {199            Text(GlassL10n.string(.loading))200        }201    }202}203
Files main
Menu

Theme