// ============================================================================= // SP BOUCHER | SOFTWARE & RESEARCH // ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING // ============================================================================= // // Project : SP GlassKit // File : Sources/SPGlassComponents/Feedback/GlassProgress.swift // Module : SPGlassComponents // Repository : https://git.spboucher.ai/sp-glasskit // Project Website : https://glass.spboucher.ai // Created : 2026-12-02 // Last Modified : 2026-12-02 // // 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 /// Shape of a ``GlassProgress``. public enum GlassProgressStyle: String, CaseIterable, Sendable { /// A horizontal bar under its label. case linear /// A small ring next to its label when determinate, a turning arc when indeterminate. case circular /// A large ring with the percentage in its centre and the label underneath: for a dashboard figure. case ring /// A row of segments, one per step, for a flow with a known number of steps. case steps } /// Pure arithmetic and formatting of progress values. public enum GlassProgressMath { /// Completed fraction between 0 and 1. A total that is zero, negative or not finite gives 0; so does a /// value that is not finite. public static func fraction(value: Double, total: Double = 1) -> Double { guard value.isFinite, total.isFinite, total > 0 else { return 0 } return min(max(value / total, 0), 1) } /// The fraction as a whole percentage in the given locale ("42 %", "42%"). public static func percentText(_ fraction: Double, locale: Locale = .current) -> String { Self.fraction(value: fraction).formatted(.percent.precision(.fractionLength(0)).locale(locale)) } /// The whole percentage, 0 to 100. public static func percent(_ fraction: Double) -> Int { Int((Self.fraction(value: fraction) * 100).rounded()) } /// A step brought inside `0...count`, and a count of at least one. public static func steps(_ step: Int, of count: Int) -> (step: Int, count: Int) { let total = max(1, count) return (min(max(step, 0), total), total) } /// Number of completed segments shown for a fraction when the progress is drawn as `count` segments. public static func completedSegments(fraction: Double, count: Int) -> Int { let total = max(1, count) return min(total, Int((Self.fraction(value: fraction) * Double(total)).rounded())) } } /// A progress indicator with an optional label, percentage and cancel button. /// /// ```swift /// GlassProgress("Uploading", value: uploaded, total: fileSize, onCancel: { cancelUpload() }) /// GlassProgress("Connecting") // indeterminate /// GlassProgress("Storage", value: 0.8, style: .ring) // large ring, percentage in the centre /// GlassProgress("Shipping address", step: 2, of: 4) // one segment per step /// ``` /// /// The indicator is the native `ProgressView`, drawn by a GlassKit style in the theme's colours; GlassKit /// adds the label row, clamps the value and exposes the percentage as the accessibility value. With Reduce /// Motion the indeterminate bar stops moving and the indeterminate ring becomes the system spinner. public struct GlassProgress: View { @GlassThemed private var theme @GlassAccessibility private var accessibility private let label: Text? private let fraction: Double? private let style: GlassProgressStyle private let showsPercent: Bool private let steps: (step: Int, count: Int)? private let onCancel: (@MainActor () -> Void)? /// Creates a determinate indicator. /// /// - Parameters: /// - value: completed amount; clamped to `0...total`. /// - total: amount that means "finished". /// - showsPercent: shows the percentage next to the label. /// - onCancel: when set, a cancel button is shown. public init( _ label: LocalizedStringKey? = nil, value: Double, total: Double = 1, style: GlassProgressStyle = .linear, showsPercent: Bool = true, onCancel: (@MainActor () -> Void)? = nil ) { self.init(label: label.map { Text($0) }, fraction: GlassProgressMath.fraction(value: value, total: total), style: style, showsPercent: showsPercent, onCancel: onCancel) } /// Creates an indeterminate indicator, for work whose length is unknown. public init( _ label: LocalizedStringKey? = nil, style: GlassProgressStyle = .linear, onCancel: (@MainActor () -> Void)? = nil ) { self.init(label: label.map { Text($0) }, fraction: nil, style: style, showsPercent: false, onCancel: onCancel) } /// Creates an indicator from a `Text` label and an optional fraction (`nil` is indeterminate). public init( label: Text?, fraction: Double?, style: GlassProgressStyle = .linear, showsPercent: Bool = true, onCancel: (@MainActor () -> Void)? = nil ) { self.label = label self.fraction = fraction.map { GlassProgressMath.fraction(value: $0) } self.style = style self.showsPercent = showsPercent self.steps = nil self.onCancel = onCancel } /// Creates a stepped indicator: `count` segments, the first `step` of them completed. /// /// - Parameters: /// - label: name of the current step. /// - step: number of completed steps, clamped to `0...count`. /// - count: number of steps, at least one. /// - showsCount: shows "2 / 4" next to the label. public init( _ label: LocalizedStringKey? = nil, step: Int, of count: Int, showsCount: Bool = true, onCancel: (@MainActor () -> Void)? = nil ) { let steps = GlassProgressMath.steps(step, of: count) self.label = label.map { Text($0) } self.fraction = Double(steps.step) / Double(steps.count) self.style = .steps self.showsPercent = showsCount self.steps = steps self.onCancel = onCancel } public var body: some View { HStack(alignment: .center, spacing: theme.spacing.sm) { Group { switch style { case .linear, .steps: VStack(alignment: .leading, spacing: theme.spacing.xs) { header(spread: true) indicator } case .circular: HStack(spacing: theme.spacing.sm) { indicator header(spread: false) } case .ring: VStack(spacing: theme.spacing.xs) { indicator if let label { label .font(theme.font(.caption).weight(.medium)) .foregroundStyle(theme.color(.textSecondary)) .multilineTextAlignment(.center) } } } } .accessibilityElement(children: .ignore) .accessibilityLabel(label ?? Text(GlassL10n.string(.loading))) .accessibilityValue(accessibilityValue) .accessibilityAddTraits(.updatesFrequently) if let onCancel { Button(action: onCancel) { Label(GlassL10n.string(.cancel), systemImage: "xmark") .labelStyle(.iconOnly) .font(.system(.caption, weight: .bold)) .foregroundStyle(theme.color(.textSecondary)) .frame(width: 26, height: 26) .background(theme.color(.textPrimary).opacity(0.08), in: Circle()) } .buttonStyle(.plain) .glassMinimumHitTarget() } } } @ViewBuilder private var indicator: some View { let drawing = GlassProgressDrawingStyle( style: style, segments: segmentCount, fill: theme.color(.primary), track: theme.color(.textPrimary).opacity(theme.isDark ? 0.16 : 0.1), text: theme.color(.textPrimary), font: theme.font(.headline).monospacedDigit(), showsPercent: showsPercent, reduceMotion: accessibility.reduceMotion ) if let fraction { ProgressView(value: fraction).progressViewStyle(drawing) } else { ProgressView().progressViewStyle(drawing) } } private var segmentCount: Int { steps?.count ?? 4 } @ViewBuilder private func header(spread: Bool) -> some View { if label != nil || trailingText != nil { HStack(alignment: .firstTextBaseline, spacing: theme.spacing.xs) { if let label { label .font(theme.font(.callout).weight(.medium)) .foregroundStyle(theme.color(.textPrimary)) } if spread { Spacer(minLength: theme.spacing.xs) } if let trailingText { Text(verbatim: trailingText) .font(theme.font(.callout).monospacedDigit()) .foregroundStyle(theme.color(.textSecondary)) } } } } /// The percentage, or "2 / 4" for a stepped indicator. private var trailingText: String? { guard showsPercent, let fraction else { return nil } if let steps { return "\(steps.step.formatted()) / \(steps.count.formatted())" } return GlassProgressMath.percentText(fraction) } private var accessibilityValue: Text { if let fraction { Text(verbatim: GlassL10n.string(.progressPercent, GlassProgressMath.percent(fraction))) } else { Text(GlassL10n.string(.loading)) } } } /// Draws the native `ProgressView` in the theme's colours: a capsule bar, a ring or a row of segments. private struct GlassProgressDrawingStyle: ProgressViewStyle { let style: GlassProgressStyle let segments: Int let fill: Color let track: Color let text: Color let font: Font let showsPercent: Bool let reduceMotion: Bool func makeBody(configuration: Configuration) -> some View { let fraction = configuration.fractionCompleted.map { GlassProgressMath.fraction(value: $0) } switch style { case .linear: bar(fraction) case .steps: stepRow(fraction ?? 0) case .circular: ring(fraction, diameter: 24, lineWidth: 3.5) case .ring: ring(fraction, diameter: 72, lineWidth: 7) .overlay { if showsPercent, let fraction { Text(verbatim: GlassProgressMath.percentText(fraction)) .font(font) .foregroundStyle(text) .minimumScaleFactor(0.6) .lineLimit(1) .padding(.horizontal, 12) } } } } private func bar(_ fraction: Double?) -> some View { Capsule() .fill(track) .frame(height: 6) .overlay { GeometryReader { geometry in let width = geometry.size.width if let fraction { Capsule() .fill(fill) .frame(width: fraction > 0 ? max(6, width * fraction) : 0) } else if reduceMotion { Capsule().fill(fill).frame(width: width * 0.36).offset(x: width * 0.32) } else { TimelineView(.animation) { timeline in let phase = timeline.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 1.5) / 1.5 Capsule().fill(fill).frame(width: width * 0.36).offset(x: width * (phase * 1.36 - 0.36)) } } } } .clipShape(Capsule()) } private func stepRow(_ fraction: Double) -> some View { let done = GlassProgressMath.completedSegments(fraction: fraction, count: segments) return HStack(spacing: 4) { ForEach(0.. some View { let stroke = StrokeStyle(lineWidth: lineWidth, lineCap: .round) ZStack { Circle().stroke(track, lineWidth: lineWidth) if let fraction { Circle().trim(from: 0, to: fraction).stroke(fill, style: stroke).rotationEffect(.degrees(-90)) } else if reduceMotion { Circle().trim(from: 0, to: 0.28).stroke(fill, style: stroke).rotationEffect(.degrees(-90)) } else { TimelineView(.animation) { timeline in let turn = timeline.date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 1.1) / 1.1 Circle().trim(from: 0, to: 0.28).stroke(fill, style: stroke).rotationEffect(.degrees(turn * 360 - 90)) } } } .padding(lineWidth / 2) .frame(width: diameter, height: diameter) } }