SPB Git

Repository Public MIT

GlassProgress.swift 14.5 KB 368 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 under its label.46    case linear47    /// A small ring next to its label when determinate, a turning arc when indeterminate.48    case circular49    /// A large ring with the percentage in its centre and the label underneath: for a dashboard figure.50    case ring51    /// A row of segments, one per step, for a flow with a known number of steps.52    case steps53}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    }7374    /// A step brought inside `0...count`, and a count of at least one.75    public static func steps(_ step: Int, of count: Int) -> (step: Int, count: Int) {76        let total = max(1, count)77        return (min(max(step, 0), total), total)78    }7980    /// Number of completed segments shown for a fraction when the progress is drawn as `count` segments.81    public static func completedSegments(fraction: Double, count: Int) -> Int {82        let total = max(1, count)83        return min(total, Int((Self.fraction(value: fraction) * Double(total)).rounded()))84    }85}8687/// A progress indicator with an optional label, percentage and cancel button.88///89/// ```swift90/// GlassProgress("Uploading", value: uploaded, total: fileSize, onCancel: { cancelUpload() })91/// GlassProgress("Connecting")                              // indeterminate92/// GlassProgress("Storage", value: 0.8, style: .ring)       // large ring, percentage in the centre93/// GlassProgress("Shipping address", step: 2, of: 4)        // one segment per step94/// ```95///96/// The indicator is the native `ProgressView`, drawn by a GlassKit style in the theme's colours; GlassKit97/// adds the label row, clamps the value and exposes the percentage as the accessibility value. With Reduce98/// Motion the indeterminate bar stops moving and the indeterminate ring becomes the system spinner.99public struct GlassProgress: View {100    @GlassThemed private var theme101    @GlassAccessibility private var accessibility102    private let label: Text?103    private let fraction: Double?104    private let style: GlassProgressStyle105    private let showsPercent: Bool106    private let steps: (step: Int, count: Int)?107    private let onCancel: (@MainActor () -> Void)?108109    /// Creates a determinate indicator.110    ///111    /// - Parameters:112    ///   - value: completed amount; clamped to `0...total`.113    ///   - total: amount that means "finished".114    ///   - showsPercent: shows the percentage next to the label.115    ///   - onCancel: when set, a cancel button is shown.116    public init(117        _ label: LocalizedStringKey? = nil,118        value: Double,119        total: Double = 1,120        style: GlassProgressStyle = .linear,121        showsPercent: Bool = true,122        onCancel: (@MainActor () -> Void)? = nil123    ) {124        self.init(label: label.map { Text($0) }, fraction: GlassProgressMath.fraction(value: value, total: total), style: style, showsPercent: showsPercent, onCancel: onCancel)125    }126127    /// Creates an indeterminate indicator, for work whose length is unknown.128    public init(129        _ label: LocalizedStringKey? = nil,130        style: GlassProgressStyle = .linear,131        onCancel: (@MainActor () -> Void)? = nil132    ) {133        self.init(label: label.map { Text($0) }, fraction: nil, style: style, showsPercent: false, onCancel: onCancel)134    }135136    /// Creates an indicator from a `Text` label and an optional fraction (`nil` is indeterminate).137    public init(138        label: Text?,139        fraction: Double?,140        style: GlassProgressStyle = .linear,141        showsPercent: Bool = true,142        onCancel: (@MainActor () -> Void)? = nil143    ) {144        self.label = label145        self.fraction = fraction.map { GlassProgressMath.fraction(value: $0) }146        self.style = style147        self.showsPercent = showsPercent148        self.steps = nil149        self.onCancel = onCancel150    }151152    /// Creates a stepped indicator: `count` segments, the first `step` of them completed.153    ///154    /// - Parameters:155    ///   - label: name of the current step.156    ///   - step: number of completed steps, clamped to `0...count`.157    ///   - count: number of steps, at least one.158    ///   - showsCount: shows "2 / 4" next to the label.159    public init(160        _ label: LocalizedStringKey? = nil,161        step: Int,162        of count: Int,163        showsCount: Bool = true,164        onCancel: (@MainActor () -> Void)? = nil165    ) {166        let steps = GlassProgressMath.steps(step, of: count)167        self.label = label.map { Text($0) }168        self.fraction = Double(steps.step) / Double(steps.count)169        self.style = .steps170        self.showsPercent = showsCount171        self.steps = steps172        self.onCancel = onCancel173    }174175    public var body: some View {176        HStack(alignment: .center, spacing: theme.spacing.sm) {177            Group {178                switch style {179                case .linear, .steps:180                    VStack(alignment: .leading, spacing: theme.spacing.xs) {181                        header(spread: true)182                        indicator183                    }184                case .circular:185                    HStack(spacing: theme.spacing.sm) {186                        indicator187                        header(spread: false)188                    }189                case .ring:190                    VStack(spacing: theme.spacing.xs) {191                        indicator192                        if let label {193                            label194                                .font(theme.font(.caption).weight(.medium))195                                .foregroundStyle(theme.color(.textSecondary))196                                .multilineTextAlignment(.center)197                        }198                    }199                }200            }201            .accessibilityElement(children: .ignore)202            .accessibilityLabel(label ?? Text(GlassL10n.string(.loading)))203            .accessibilityValue(accessibilityValue)204            .accessibilityAddTraits(.updatesFrequently)205            if let onCancel {206                Button(action: onCancel) {207                    Label(GlassL10n.string(.cancel), systemImage: "xmark")208                        .labelStyle(.iconOnly)209                        .font(.system(.caption, weight: .bold))210                        .foregroundStyle(theme.color(.textSecondary))211                        .frame(width: 26, height: 26)212                        .background(theme.color(.textPrimary).opacity(0.08), in: Circle())213                }214                .buttonStyle(.plain)215                .glassMinimumHitTarget()216            }217        }218    }219220    @ViewBuilder221    private var indicator: some View {222        let drawing = GlassProgressDrawingStyle(223            style: style,224            segments: segmentCount,225            fill: theme.color(.primary),226            track: theme.color(.textPrimary).opacity(theme.isDark ? 0.16 : 0.1),227            text: theme.color(.textPrimary),228            font: theme.font(.headline).monospacedDigit(),229            showsPercent: showsPercent,230            reduceMotion: accessibility.reduceMotion231        )232        if let fraction {233            ProgressView(value: fraction).progressViewStyle(drawing)234        } else {235            ProgressView().progressViewStyle(drawing)236        }237    }238239    private var segmentCount: Int {240        steps?.count ?? 4241    }242243    @ViewBuilder244    private func header(spread: Bool) -> some View {245        if label != nil || trailingText != nil {246            HStack(alignment: .firstTextBaseline, spacing: theme.spacing.xs) {247                if let label {248                    label249                        .font(theme.font(.callout).weight(.medium))250                        .foregroundStyle(theme.color(.textPrimary))251                }252                if spread { Spacer(minLength: theme.spacing.xs) }253                if let trailingText {254                    Text(verbatim: trailingText)255                        .font(theme.font(.callout).monospacedDigit())256                        .foregroundStyle(theme.color(.textSecondary))257                }258            }259        }260    }261262    /// The percentage, or "2 / 4" for a stepped indicator.263    private var trailingText: String? {264        guard showsPercent, let fraction else { return nil }265        if let steps {266            return "\(steps.step.formatted()) / \(steps.count.formatted())"267        }268        return GlassProgressMath.percentText(fraction)269    }270271    private var accessibilityValue: Text {272        if let fraction {273            Text(verbatim: GlassL10n.string(.progressPercent, GlassProgressMath.percent(fraction)))274        } else {275            Text(GlassL10n.string(.loading))276        }277    }278}279280/// Draws the native `ProgressView` in the theme's colours: a capsule bar, a ring or a row of segments.281private struct GlassProgressDrawingStyle: ProgressViewStyle {282    let style: GlassProgressStyle283    let segments: Int284    let fill: Color285    let track: Color286    let text: Color287    let font: Font288    let showsPercent: Bool289    let reduceMotion: Bool290291    func makeBody(configuration: Configuration) -> some View {292        let fraction = configuration.fractionCompleted.map { GlassProgressMath.fraction(value: $0) }293        switch style {294        case .linear:295            bar(fraction)296        case .steps:297            stepRow(fraction ?? 0)298        case .circular:299            ring(fraction, diameter: 24, lineWidth: 3.5)300        case .ring:301            ring(fraction, diameter: 72, lineWidth: 7)302                .overlay {303                    if showsPercent, let fraction {304                        Text(verbatim: GlassProgressMath.percentText(fraction))305                            .font(font)306                            .foregroundStyle(text)307                            .minimumScaleFactor(0.6)308                            .lineLimit(1)309                            .padding(.horizontal, 12)310                    }311                }312        }313    }314315    private func bar(_ fraction: Double?) -> some View {316        Capsule()317            .fill(track)318            .frame(height: 6)319            .overlay {320                GeometryReader { geometry in321                    let width = geometry.size.width322                    if let fraction {323                        Capsule()324                            .fill(fill)325                            .frame(width: fraction > 0 ? max(6, width * fraction) : 0)326                    } else if reduceMotion {327                        Capsule().fill(fill).frame(width: width * 0.36).offset(x: width * 0.32)328                    } else {329                        TimelineView(.animation) { timeline in330                            let phase = timeline.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 1.5) / 1.5331                            Capsule().fill(fill).frame(width: width * 0.36).offset(x: width * (phase * 1.36 - 0.36))332                        }333                    }334                }335            }336            .clipShape(Capsule())337    }338339    private func stepRow(_ fraction: Double) -> some View {340        let done = GlassProgressMath.completedSegments(fraction: fraction, count: segments)341        return HStack(spacing: 4) {342            ForEach(0..<max(1, segments), id: \.self) { index in343                Capsule().fill(index < done ? fill : track).frame(height: 6)344            }345        }346    }347348    @ViewBuilder349    private func ring(_ fraction: Double?, diameter: CGFloat, lineWidth: CGFloat) -> some View {350        let stroke = StrokeStyle(lineWidth: lineWidth, lineCap: .round)351        ZStack {352            Circle().stroke(track, lineWidth: lineWidth)353            if let fraction {354                Circle().trim(from: 0, to: fraction).stroke(fill, style: stroke).rotationEffect(.degrees(-90))355            } else if reduceMotion {356                Circle().trim(from: 0, to: 0.28).stroke(fill, style: stroke).rotationEffect(.degrees(-90))357            } else {358                TimelineView(.animation) { timeline in359                    let turn = timeline.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 1.1) / 1.1360                    Circle().trim(from: 0, to: 0.28).stroke(fill, style: stroke).rotationEffect(.degrees(turn * 360 - 90))361                }362            }363        }364        .padding(lineWidth / 2)365        .frame(width: diameter, height: diameter)366    }367}368
Files main
Menu

Theme