Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Components/VQMetric.swift3// Description: Numbers with their meaning: the kind badge (observed / calculated / assumption / forecast), the delta4// with its arrow glyph, the metric tile.5import SwiftUI6import VQuantKit78/// A small tag telling whether a number is observed, calculated, assumed or forecast. The shape of the border differs9/// per kind (solid, filled, dashed, dotted), not only the colour.10public struct VQKindBadge: View {11 private let kind: VQValueKind12 @Environment(\.vqTheme) private var theme1314 public init(_ kind: VQValueKind) { self.kind = kind }1516 private var ink: Color {17 switch kind {18 case .observed, .calculated: return VQP.text219 case .assumption: return VQP.warn20 case .forecast: return VQP.info21 }22 }23 private var stroke: StrokeStyle {24 switch kind {25 case .observed, .calculated: return StrokeStyle(lineWidth: 1)26 case .assumption: return StrokeStyle(lineWidth: 1, dash: [3, 2])27 case .forecast: return StrokeStyle(lineWidth: 1, lineCap: .round, dash: [0.5, 2.5])28 }29 }3031 public var body: some View {32 let shape = RoundedRectangle(cornerRadius: 3, style: .continuous)33 Text(kind.short(theme.language))34 .font(.system(size: 9, weight: .semibold, design: .default)).tracking(0.6)35 .foregroundStyle(ink)36 .padding(.horizontal, 4).padding(.vertical, 1.5)37 .background { if kind == .calculated { shape.fill(VQP.ink3) } }38 .overlay { shape.strokeBorder(kind == .observed || kind == .calculated ? VQP.lineStrong : ink.opacity(0.75), style: stroke) }39 .fixedSize()40 .accessibilityLabel(kind.label(theme.language))41 .accessibilityHint(kind.explanation(theme.language))42 .help(kind.explanation(theme.language))43 }44}4546/// ▲ up, ▼ down, – flat: the direction reads without colour.47public struct VQDirectionGlyph: View {48 private let direction: VQDirection49 private let size: CGFloat50 public init(_ direction: VQDirection, size: CGFloat = 8) { self.direction = direction; self.size = size }5152 public var body: some View {53 Canvas { context, s in54 var p = Path()55 switch direction {56 case .up: p.move(to: CGPoint(x: s.width / 2, y: s.height * 0.08)); p.addLine(to: CGPoint(x: s.width, y: s.height * 0.92)); p.addLine(to: CGPoint(x: 0, y: s.height * 0.92)); p.closeSubpath()57 case .down: p.move(to: CGPoint(x: 0, y: s.height * 0.08)); p.addLine(to: CGPoint(x: s.width, y: s.height * 0.08)); p.addLine(to: CGPoint(x: s.width / 2, y: s.height * 0.92)); p.closeSubpath()58 case .flat: p.addRect(CGRect(x: s.width * 0.1, y: s.height / 2 - 0.75, width: s.width * 0.8, height: 1.5))59 }60 context.fill(p, with: .foreground)61 }62 .frame(width: size, height: size)63 .accessibilityHidden(true)64 }65}6667/// A change: arrow glyph + sign + the person's up/down colour. Colour is never the only signal.68public struct VQDelta: View {69 private let value: Double?70 private let unit: VQValueUnit71 private let decimals: Int?72 private let currency: String73 private let isPercentPoints: Bool74 private let role: VQTokens.Typography.Role75 @Environment(\.vqTheme) private var theme7677 /// - Parameters:78 /// - value: a FRACTION for `percent` / `bps` (0.0123 = +1,23 %), a plain change otherwise.79 public init(_ value: Double?, unit: VQValueUnit = .none, decimals: Int? = nil, currency: String = "USD", role: VQTokens.Typography.Role = VQTokens.Typography.numSm) {80 self.value = value; self.unit = unit; self.decimals = decimals; self.currency = currency; self.isPercentPoints = false; self.role = role81 }8283 /// A change already in percentage points (quotes' and overview items' `changePct`: −1.24 = −1,24 %).84 public init(percentPoints value: Double?, decimals: Int = 2, role: VQTokens.Typography.Role = VQTokens.Typography.numSm) {85 self.value = value; self.unit = .percent; self.decimals = decimals; self.currency = "USD"; self.isPercentPoints = true; self.role = role86 }8788 private var direction: VQDirection {89 guard let value else { return .flat }90 let scaled = isPercentPoints ? value : (unit == .percent ? value * 100 : unit == .bps ? value * 10_000 : value)91 return VQFormat.direction(scaled, decimals: decimals ?? (unit == .bps ? 0 : 2))92 }93 private var text: String {94 if isPercentPoints { return VQFormat.percentValue(value, decimals: decimals ?? 2, signed: true, locale: theme.numberLocale) }95 return VQFormat.byUnit(value, unit, decimals: decimals, currency: currency, signed: true, locale: theme.numberLocale)96 }97 private var spoken: String {98 guard value != nil else { return theme.l("change not available") }99 switch direction {100 case .up: return theme.l("up %1$@", "\(text)")101 case .down: return theme.l("down %1$@", "\(text)")102 case .flat: return theme.l("unchanged")103 }104 }105106 public var body: some View {107 HStack(spacing: 3) {108 if value != nil, direction != .flat { VQDirectionGlyph(direction, size: role.size * 0.62) }109 Text(text).vqFont(role)110 }111 .foregroundStyle(value == nil ? VQP.text3 : theme.color(direction))112 .fixedSize()113 .accessibilityElement(children: .ignore)114 .accessibilityLabel(spoken)115 }116}117118/// Label above, tabular value by unit, optional delta and note, the kind badge. `Stat` / `Metric` on the web.119public struct VQMetricTile: View {120 private let label: String121 private let valueText: String122 private let kind: VQValueKind?123 private let delta: Double?124 private let deltaUnit: VQValueUnit125 private let note: String?126 private let large: Bool127 @Environment(\.vqTheme) private var theme128129 public init(label: String, value: Double?, unit: VQValueUnit = .none, kind: VQValueKind? = nil, decimals: Int? = nil, currency: String = "USD",130 delta: Double? = nil, deltaUnit: VQValueUnit? = nil, note: String? = nil, large: Bool = false, locale: VQNumberLocale? = nil) {131 self.label = label; self.kind = kind; self.delta = delta; self.deltaUnit = deltaUnit ?? unit; self.note = note; self.large = large132 self.valueText = VQFormat.byUnit(value, unit, decimals: decimals, currency: currency, compact: unit == .currency && abs(value ?? 0) >= 1e7, locale: locale ?? .frCA)133 self.usesExplicitLocale = locale != nil134 self.raw = (value, unit, decimals, currency)135 self.unitName = unit == .none ? nil : unit.rawValue136 }137138 /// A tile for a `lab/1` summary metric.139 public init(_ metric: VQLabResult.Metric) {140 self.label = metric.label; self.kind = metric.kind.known; self.delta = nil; self.deltaUnit = .none; self.note = metric.note; self.large = false141 self.valueText = metric.formatted()142 self.usesExplicitLocale = metric.text != nil143 self.raw = (metric.value, metric.unit, metric.decimals, metric.currency ?? "USD")144 self.unitName = metric.unitName145 }146147 private let usesExplicitLocale: Bool148 private let raw: (Double?, VQValueUnit, Int?, String)149 private let unitName: String?150151 private var text: String {152 usesExplicitLocale ? valueText : VQFormat.byUnitName(raw.0, unitName, decimals: raw.2, currency: raw.3, compact: raw.1 == .currency && abs(raw.0 ?? 0) >= 1e7, locale: theme.numberLocale)153 }154155 public var body: some View {156 VStack(alignment: .leading, spacing: VQS.s1) {157 HStack(alignment: .firstTextBaseline, spacing: VQS.s1) {158 Text(label).vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3).lineLimit(3).fixedSize(horizontal: false, vertical: true)159 Spacer(minLength: 0)160 if let kind { VQKindBadge(kind) }161 }162 HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {163 Text(text).vqFont(large ? VQTokens.Typography.numLg : VQTokens.Typography.numMd).foregroundStyle(VQP.text1)164 .fixedSize()165 if delta != nil { VQDelta(delta, unit: deltaUnit) }166 }167 if let note, !note.isEmpty {168 Text(note).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).lineLimit(3).fixedSize(horizontal: false, vertical: true)169 }170 }171 .frame(maxWidth: .infinity, alignment: .topLeading)172 .accessibilityElement(children: .combine)173 .accessibilityLabel(label)174 .accessibilityValue([text, kind?.label(theme.language), note].compactMap { $0 }.joined(separator: ", "))175 }176}177178/// Metric tiles in an adaptive grid separated by hairlines (not a card around each).179public struct VQMetricGrid: View {180 private let metrics: [VQLabResult.Metric]181 private let minimumWidth: CGFloat182 public init(_ metrics: [VQLabResult.Metric], minimumWidth: CGFloat = 168) { self.metrics = metrics; self.minimumWidth = minimumWidth }183184 public var body: some View {185 LazyVGrid(columns: [GridItem(.adaptive(minimum: minimumWidth, maximum: 420), spacing: VQS.s4, alignment: .topLeading)], alignment: .leading, spacing: VQS.s3) {186 ForEach(Array(metrics.enumerated()), id: \.offset) { _, m in187 VQMetricTile(m)188 .padding(.top, VQS.s2)189 .overlay(alignment: .top) { Rectangle().fill(VQP.line).frame(height: VQTokens.hairline) }190 }191 }192 }193}194