Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Sources/SPGlassData/Data/GlassMetricCard.swift8// Module : SPGlassData9// 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 Foundation42import SwiftUI43import SPGlassCore44import SPGlassTokens45import SPGlassThemes46import SPGlassEffects47import SPGlassComponents4849/// A figure shown by a ``GlassMetricCard``: a value, its unit, its change and the period of that change.50public struct GlassMetric: Equatable, Sendable {51 public var value: Double52 /// Unit shown after the value ("ms", "k$"). Already localised.53 public var unit: String?54 /// Relative change as a fraction: `0.042` is +4.2 %. `nil` hides the change line.55 public var change: Double?56 /// The period the change refers to ("vs last month"). Already localised.57 public var period: String?58 /// Fewest and most fraction digits of the value.59 public var fractionDigits: ClosedRange<Int>60 /// Whether a rise is good news, bad news or neither.61 public var tone: GlassMetricTone62 /// Recent values, oldest first, drawn as a small line under the figure. Fewer than two finite values63 /// draw nothing.64 public var sparkline: [Double]6566 public init(67 value: Double,68 unit: String? = nil,69 change: Double? = nil,70 period: String? = nil,71 fractionDigits: ClosedRange<Int> = 0...2,72 tone: GlassMetricTone = .neutral,73 sparkline: [Double] = []74 ) {75 self.value = value76 self.unit = unit77 self.change = change78 self.period = period79 self.fractionDigits = fractionDigits80 self.tone = tone81 self.sparkline = sparkline82 }83}8485/// How the direction of a change should be read. It only colours the direction symbol; the direction itself86/// is always given by the symbol's shape and by a word.87public enum GlassMetricTone: String, CaseIterable, Sendable {88 /// No judgement: the symbol keeps the secondary text colour.89 case neutral90 /// A rise is good (revenue), a fall is bad.91 case positiveIsGood92 /// A fall is good (latency, errors), a rise is bad.93 case negativeIsGood9495 /// The badge tone of the change chip for a trend.96 public func badgeTone(for trend: GlassTrend) -> GlassBadgeTone {97 switch colorToken(for: trend) {98 case .success: .success99 case .destructive: .critical100 default: .neutral101 }102 }103104 /// The colour role of the direction symbol for a trend.105 public func colorToken(for trend: GlassTrend) -> GlassColorToken {106 switch (self, trend) {107 case (.neutral, _), (_, .flat): .textSecondary108 case (.positiveIsGood, .up), (.negativeIsGood, .down): .success109 case (.positiveIsGood, .down), (.negativeIsGood, .up): .destructive110 }111 }112}113114/// Pure formatting rules of ``GlassMetricCard``.115public enum GlassMetricFormatter {116 /// Text shown where a value is missing or not a finite number.117 public static let placeholder = "—"118 /// Changes smaller than this fraction display as 0.0 % and are therefore reported as unchanged.119 public static let flatTolerance = 0.0005120121 /// The value with the requested fraction digits, or ``placeholder`` when it is not finite.122 public static func valueText(_ value: Double, fractionDigits: ClosedRange<Int> = 0...2, locale: Locale = .current) -> String {123 guard value.isFinite else { return placeholder }124 let lower = max(0, fractionDigits.lowerBound)125 let upper = max(lower, fractionDigits.upperBound)126 return value.formatted(.number.precision(.fractionLength(lower...upper)).locale(locale))127 }128129 /// The direction of a change given as a fraction.130 public static func trend(for change: Double) -> GlassTrend {131 GlassTrend.of(change: change, tolerance: flatTolerance)132 }133134 /// The magnitude of a change as a percentage with at most one fraction digit ("4.2 %"), without a sign:135 /// the direction is carried by the symbol and the word next to it. `nil` when the change is not finite.136 public static func changeText(_ change: Double, locale: Locale = .current) -> String? {137 guard change.isFinite else { return nil }138 return abs(change).formatted(.percent.precision(.fractionLength(0...1)).locale(locale))139 }140141 /// The points of a sparkline in a unit square: x from 0 to 1 in order, y from 0 (smallest value) to 1142 /// (largest). Values that are not finite are skipped; fewer than two finite values give no points, and a143 /// constant series is drawn at mid height.144 public static func sparklinePoints(_ values: [Double]) -> [CGPoint] {145 let finite = values.filter(\.isFinite)146 guard finite.count >= 2, let low = finite.min(), let high = finite.max() else { return [] }147 let range = high - low148 return finite.enumerated().map { index, value in149 CGPoint(x: Double(index) / Double(finite.count - 1), y: range > 0 ? (value - low) / range : 0.5)150 }151 }152153 /// The change line as one phrase: direction word, magnitude and period ("Up 4.2 %, vs last month").154 /// An unchanged value reads as the direction word alone, followed by the period.155 ///156 /// - Parameter localization: language of the direction word (`"en"`, `"fr"`); `nil` follows the application.157 public static func changeDescription(_ change: Double, period: String? = nil, locale: Locale = .current, localization: String? = nil) -> String? {158 guard let magnitude = changeText(change, locale: locale) else { return nil }159 let trend = trend(for: change)160 let word = localization.map { trend.label(localization: $0) } ?? trend.label161 let head = trend == .flat ? word : "\(word) \(magnitude)"162 guard let period, !period.isEmpty else { return head }163 return "\(head), \(period)"164 }165}166167/// A card for one key figure, with states for loading, missing and failed data.168///169/// ```swift170/// GlassMetricCard("Response time", state: .loaded(GlassMetric(value: 182, unit: "ms", change: -0.062, period: "vs last week", tone: .negativeIsGood)))171/// GlassMetricCard("Revenue", systemImage: "banknote", state: .loaded(GlassMetric(value: 482, unit: "k$", change: 0.04, sparkline: lastTwelveWeeks)))172/// GlassMetricCard("Revenue", state: .failed(message: "The report is unavailable.")) { reload() }173/// ```174///175/// The title is an eyebrow label above a large tabular figure; the change is a chip (direction symbol and176/// magnitude, tinted by the metric's tone) followed by the period, and `sparkline` adds a small line of recent177/// values. The state is a `GlassLoadState<GlassMetric>` owned by the host: `.idle` shows a dash, `.loading` a178/// redacted placeholder, `.empty` "No data", `.failed` its message and, when `onRetry` is given, a retry button.179public struct GlassMetricCard: View {180 @GlassThemed private var theme181 @Environment(\.locale) private var locale182 private let title: Text183 private let systemImage: String?184 private let state: GlassLoadState<GlassMetric>185 private let onRetry: (@MainActor () -> Void)?186187 /// - Parameters:188 /// - title: name of the figure.189 /// - systemImage: optional SF Symbol shown in the top trailing corner. Decorative.190 /// - state: the figure, or why there is none.191 /// - onRetry: called by the retry button of the failed state. Without it no button is shown.192 public init(_ title: LocalizedStringKey, systemImage: String? = nil, state: GlassLoadState<GlassMetric>, onRetry: (@MainActor () -> Void)? = nil) {193 self.title = Text(title)194 self.systemImage = systemImage195 self.state = state196 self.onRetry = onRetry197 }198199 public var body: some View {200 VStack(alignment: .leading, spacing: theme.spacing.xs) {201 HStack(alignment: .center, spacing: theme.spacing.xs) {202 title203 .font(.system(.caption, weight: .semibold))204 .textCase(.uppercase)205 .tracking(0.6)206 .foregroundStyle(theme.color(.textSecondary))207 .lineLimit(2)208 Spacer(minLength: 0)209 if let systemImage {210 Image(systemName: systemImage)211 .font(.system(.footnote, weight: .semibold))212 .foregroundStyle(theme.color(.textSecondary))213 .accessibilityHidden(true)214 }215 }216 content217 }218 .frame(maxWidth: .infinity, alignment: .leading)219 .padding(theme.spacing.md)220 .glassOpaqueSurface(in: theme.shape(\.large))221 }222223 @ViewBuilder224 private var content: some View {225 switch state {226 case .idle:227 valueLine(GlassMetricFormatter.placeholder, unit: nil)228 .accessibilityLabel(Text(GlassL10n.string(.noData)))229 case .loading:230 figure(GlassMetric(value: 1234.5, unit: "—", change: 0.123, period: "— — — —"))231 .redacted(reason: .placeholder)232 .accessibilityElement(children: .ignore)233 .accessibilityLabel(Text(GlassL10n.string(.loading)))234 case .loaded(let metric):235 figure(metric)236 .accessibilityElement(children: .combine)237 case .empty:238 Text(GlassL10n.string(.noData))239 .font(theme.font(.body))240 .foregroundStyle(theme.color(.textSecondary))241 case .failed(let message):242 failure(message)243 }244 }245246 private func figure(_ metric: GlassMetric) -> some View {247 VStack(alignment: .leading, spacing: theme.spacing.xs) {248 valueLine(GlassMetricFormatter.valueText(metric.value, fractionDigits: metric.fractionDigits, locale: locale), unit: metric.unit)249 let points = GlassMetricFormatter.sparklinePoints(metric.sparkline)250 if !points.isEmpty {251 GlassSparkline(points: points, color: theme.color(.primary))252 .frame(height: 30)253 .padding(.vertical, 2)254 .accessibilityHidden(true)255 }256 if let change = metric.change, let magnitude = GlassMetricFormatter.changeText(change, locale: locale) {257 let trend = GlassMetricFormatter.trend(for: change)258 // Wraps under the chip when the card is narrow.259 ViewThatFits(in: .horizontal) {260 HStack(alignment: .center, spacing: theme.spacing.xs) {261 changeChip(trend: trend, magnitude: magnitude, tone: metric.tone, change: change)262 periodText(metric.period)263 }264 VStack(alignment: .leading, spacing: theme.spacing.xxs) {265 changeChip(trend: trend, magnitude: magnitude, tone: metric.tone, change: change)266 periodText(metric.period, lineLimit: 2)267 }268 }269 } else {270 periodText(metric.period)271 }272 }273 }274275 @ViewBuilder276 private func periodText(_ period: String?, lineLimit: Int = 1) -> some View {277 if let period, !period.isEmpty {278 Text(verbatim: period)279 .font(theme.font(.caption))280 .foregroundStyle(theme.color(.textSecondary))281 .lineLimit(lineLimit)282 .fixedSize(horizontal: false, vertical: lineLimit > 1)283 }284 }285286 /// Direction symbol and magnitude. The symbol's shape gives the direction; VoiceOver reads the word.287 private func changeChip(trend: GlassTrend, magnitude: String, tone: GlassMetricTone, change: Double) -> some View {288 let colors = chipColors(tone.colorToken(for: trend))289 return HStack(spacing: 3) {290 Image(systemName: trend.systemImage)291 .font(.system(.caption2, weight: .bold))292 .foregroundStyle(colors.accent)293 Text(verbatim: magnitude)294 .font(theme.font(.caption).weight(.semibold).monospacedDigit())295 .foregroundStyle(colors.foreground)296 }297 .lineLimit(1)298 .fixedSize()299 .padding(.horizontal, 7)300 .padding(.vertical, 3)301 .background(colors.background, in: Capsule())302 .accessibilityElement(children: .ignore)303 .accessibilityLabel(Text(verbatim: GlassMetricFormatter.changeDescription(change, locale: locale) ?? magnitude))304 }305306 private func chipColors(_ token: GlassColorToken) -> (background: Color, foreground: Color, accent: Color) {307 guard token == .success || token == .destructive else {308 return (theme.color(.textPrimary).opacity(0.08), theme.color(.textPrimary), theme.color(.textSecondary))309 }310 let swatch = GlassTintedSwatch(token, theme: theme, fraction: 0.18)311 return (swatch.background, swatch.foreground, swatch.accent)312 }313314 private func valueLine(_ value: String, unit: String?) -> some View {315 HStack(alignment: .firstTextBaseline, spacing: theme.spacing.xxs) {316 Text(verbatim: value)317 .font(theme.font(.largeTitle).monospacedDigit())318 .foregroundStyle(theme.color(.textPrimary))319 .lineLimit(1)320 .minimumScaleFactor(0.6)321 if let unit, !unit.isEmpty {322 Text(verbatim: unit)323 .font(theme.font(.callout).weight(.medium))324 .foregroundStyle(theme.color(.textSecondary))325 .lineLimit(1)326 }327 }328 }329330 private func failure(_ message: String) -> some View {331 VStack(alignment: .leading, spacing: theme.spacing.sm) {332 HStack(alignment: .top, spacing: theme.spacing.xs) {333 GlassIconTile(systemImage: "exclamationmark.triangle.fill", tone: .critical, size: 28)334 .accessibilityLabel(Text(GlassL10n.string(.error)))335 Text(verbatim: message.isEmpty ? GlassL10n.string(.errorTitle) : message)336 .font(theme.font(.callout))337 .foregroundStyle(theme.color(.textPrimary))338 .frame(minHeight: 28)339 }340 if let onRetry {341 GlassButton(verbatim: GlassL10n.string(.retry), systemImage: "arrow.clockwise", size: .small, action: onRetry)342 }343 }344 }345}346347/// A small line through points of the unit square, with a dot on the last one.348struct GlassSparkline: View {349 let points: [CGPoint]350 let color: Color351352 var body: some View {353 Canvas { context, size in354 guard points.count >= 2 else { return }355 let inset: CGFloat = 3356 let width = size.width - inset * 2, height = size.height - inset * 2357 func place(_ point: CGPoint) -> CGPoint {358 CGPoint(x: inset + point.x * width, y: inset + (1 - point.y) * height)359 }360 var line = Path()361 line.move(to: place(points[0]))362 for point in points.dropFirst() { line.addLine(to: place(point)) }363 context.stroke(line, with: .color(color), style: StrokeStyle(lineWidth: 1.75, lineCap: .round, lineJoin: .round))364 if let last = points.last {365 let center = place(last)366 context.fill(Path(ellipseIn: CGRect(x: center.x - 3, y: center.y - 3, width: 6, height: 6)), with: .color(color))367 }368 }369 }370}371