Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Monitor9// File : App/Sources/DesignSystem/Components.swift10// Description : Reusable interface pieces: cards, readouts, quality11// badges, meters, sparklines, live charts, key-value rows.12// Module : DesignSystem13// Repository : https://git.spboucher.ai/orix-monitor14// Created : 2026-11-2115// Last Modified : 2026-11-2116//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : Proprietary, all rights reserved (see license file)82// License File : LICENSE83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import ORIXMonitorCore91import SwiftUI9293/// The standard panel.94struct Card<Content: View>: View {95 var title: LocalizedStringKey?96 var family: MetricFamily?97 var quality: MetricQuality?98 @ViewBuilder var content: Content99 @Environment(\.density) private var density100 @Environment(\.colorBlindSafe) private var safe101102 init(_ title: LocalizedStringKey? = nil, family: MetricFamily? = nil, quality: MetricQuality? = nil, @ViewBuilder content: () -> Content) {103 self.title = title104 self.family = family105 self.quality = quality106 self.content = content()107 }108109 var body: some View {110 VStack(alignment: .leading, spacing: ORIX.Space.sm * density) {111 if let title {112 HStack(spacing: ORIX.Space.xs) {113 if let family {114 Image(systemName: family.symbol)115 .font(.system(size: 11, weight: .semibold))116 .foregroundStyle(family.color(colorBlindSafe: safe))117 .accessibilityHidden(true)118 }119 Text(title).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary)120 Spacer(minLength: 0)121 if let quality, quality != .measured, quality != .derived { QualityBadge(quality) }122 }123 }124 content125 }126 .padding(ORIX.Space.md * density)127 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)128 .background(ORIX.Palette.surface, in: RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous))129 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.card, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))130 }131}132133/// States how a value was obtained. Never colour alone: the label carries the meaning.134struct QualityBadge: View {135 var quality: MetricQuality136 init(_ quality: MetricQuality) { self.quality = quality }137138 var text: String {139 switch quality {140 case .measured: L("Measured")141 case .derived: L("Derived")142 case .estimated: L("Estimate")143 case .bestEffort: L("Best effort")144 case .unavailable: L("Unavailable")145 }146 }147148 var help: String {149 switch quality {150 case .measured: L("Read directly from a documented system interface.")151 case .derived: L("Computed from measured counters.")152 case .estimated: L("An estimate, not a measurement.")153 case .bestEffort: L("Read from a system property Apple does not document. It may be missing or change.")154 case .unavailable: L("Not available through supported system interfaces.")155 }156 }157158 var body: some View {159 Text(text)160 .font(.system(size: 9, weight: .semibold))161 .textCase(.uppercase)162 .lineLimit(1)163 .fixedSize()164 .padding(.horizontal, 5)165 .padding(.vertical, 2)166 .foregroundStyle(quality == .unavailable ? ORIX.Palette.textTertiary : ORIX.Palette.warning)167 .background((quality == .unavailable ? ORIX.Palette.textTertiary : ORIX.Palette.warning).opacity(0.14), in: Capsule())168 .help(help)169 .accessibilityLabel(Text(help))170 }171}172173/// A large number with its caption.174struct Readout: View {175 var value: String176 var caption: LocalizedStringKey?177 var size: CGFloat = 28178 var color: Color = ORIX.Palette.textPrimary179 @Environment(\.accessibilityReduceMotion) private var reduceMotion180181 var body: some View {182 VStack(alignment: .leading, spacing: 2) {183 Text(value).font(ORIX.Typeface.readout(size)).foregroundStyle(color).lineLimit(1).minimumScaleFactor(0.6)184 .contentTransition(reduceMotion ? .identity : .numericText())185 if let caption { Text(caption).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary) }186 }187 .accessibilityElement(children: .combine)188 }189}190191/// Label on the left, value on the right.192struct KeyValueRow: View {193 var label: String194 var value: String195 var quality: MetricQuality?196 var swatch: Color?197198 init(_ label: String, _ value: String, quality: MetricQuality? = nil, swatch: Color? = nil) {199 self.label = label200 self.value = value201 self.quality = quality202 self.swatch = swatch203 }204205 var body: some View {206 HStack(spacing: ORIX.Space.xs) {207 if let swatch { RoundedRectangle(cornerRadius: 2).fill(swatch).frame(width: 8, height: 8).accessibilityHidden(true) }208 Text(label).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)209 if let quality, quality == .bestEffort || quality == .estimated { QualityBadge(quality) }210 Spacer(minLength: ORIX.Space.xs)211 Text(value).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1).textSelection(.enabled)212 }213 .accessibilityElement(children: .combine)214 }215}216217/// The honest placeholder for anything the system does not expose.218struct UnavailableRow: View {219 var label: String220 var reason: String?221222 var body: some View {223 VStack(alignment: .leading, spacing: 2) {224 HStack {225 Text(label).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)226 Spacer()227 QualityBadge(.unavailable)228 }229 Text(reason ?? L("Not available through supported system interfaces."))230 .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)231 }232 .accessibilityElement(children: .combine)233 }234}235236/// A horizontal bar made of proportional segments.237struct SegmentBar: View {238 struct Segment: Identifiable {239 var id: String240 var value: Double241 var color: Color242 }243244 var segments: [Segment]245 var total: Double246 var height: CGFloat = 10247248 var body: some View {249 GeometryReader { proxy in250 HStack(spacing: 1) {251 ForEach(segments) { segment in252 Rectangle().fill(segment.color)253 .frame(width: max(0, proxy.size.width * CGFloat(total > 0 ? segment.value / total : 0)))254 }255 Spacer(minLength: 0)256 }257 .frame(height: height)258 .background(ORIX.Palette.surfaceRaised)259 .clipShape(Capsule())260 }261 .frame(height: height)262 .accessibilityHidden(true)263 }264}265266/// A thin level meter, 0…1.267struct Meter: View {268 var fraction: Double269 var color: Color270 var height: CGFloat = 6271272 var body: some View {273 GeometryReader { proxy in274 ZStack(alignment: .leading) {275 Capsule().fill(ORIX.Palette.surfaceRaised)276 Capsule().fill(color).frame(width: max(height, proxy.size.width * CGFloat(min(max(fraction, 0), 1))))277 }278 }279 .frame(height: height)280 .accessibilityHidden(true)281 }282}283284struct LivePoint: Identifiable, Equatable {285 var id: Date { date }286 var date: Date287 var value: Double288}289290/// A dependency-free line for small widgets and the menu bar. Draws real samples only; an empty input draws nothing.291struct Sparkline: View {292 var values: [Double]293 var color: Color294 /// Upper bound of the scale; nil scales to the largest value shown.295 var ceiling: Double?296 var filled = true297298 var body: some View {299 Canvas { context, size in300 guard values.count > 1 else { return }301 let top = max(ceiling ?? (values.max() ?? 1), .leastNonzeroMagnitude)302 let step = size.width / CGFloat(values.count - 1)303 var line = Path()304 for (index, value) in values.enumerated() {305 let point = CGPoint(x: CGFloat(index) * step, y: size.height - CGFloat(min(max(value / top, 0), 1)) * (size.height - 1) - 0.5)306 if index == 0 { line.move(to: point) } else { line.addLine(to: point) }307 }308 if filled {309 var area = line310 area.addLine(to: CGPoint(x: size.width, y: size.height))311 area.addLine(to: CGPoint(x: 0, y: size.height))312 area.closeSubpath()313 context.fill(area, with: .linearGradient(Gradient(colors: [color.opacity(0.32), color.opacity(0.02)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height)))314 }315 context.stroke(line, with: .color(color), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))316 }317 .accessibilityHidden(true)318 }319}320321/// One series of a live chart.322struct LiveSeries: Identifiable {323 var id: String324 var name: String325 var color: Color326 var points: [LivePoint]327}328329/// Real-time chart over the in-memory window, drawn on a SwiftUI `Canvas`.330///331/// It was first built with Swift Charts. Measured on the signed app, every page holding one cost about 185 MB of graphics332/// memory and, with an animation between samples, 10 % of a core. Drawing a few hundred points directly costs neither.333/// Stored history, opened occasionally and needing pointer inspection, still uses Swift Charts (`HistoryChart`).334struct LiveChart: View {335 var series: [LiveSeries]336 /// Fixed y range; nil scales to the data, from zero.337 var domain: ClosedRange<Double>?338 var format: (Double) -> String339 var stacked = false340 var height: CGFloat = 180341 /// Explicit y-axis ticks, for level scales with a handful of named steps.342 var ticks: [Double]?343344 private static let gutter: CGFloat = 62345 private static let footer: CGFloat = 18346347 var body: some View {348 VStack(alignment: .leading, spacing: 6) {349 Canvas { context, size in draw(&context, size) }350 .frame(height: height)351 .overlay {352 if series.allSatisfy({ $0.points.count < 2 }) {353 Text("Collecting samples…").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)354 }355 }356 if series.count > 1 {357 HStack(spacing: ORIX.Space.sm) {358 ForEach(series) { s in359 HStack(spacing: 5) {360 Circle().fill(s.color).frame(width: 8, height: 8)361 Text(s.name).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)362 }363 }364 }365 .accessibilityHidden(true)366 }367 }368 .accessibilityElement(children: .ignore)369 .accessibilityLabel(Text(accessibilitySummary))370 }371372 private var range: ClosedRange<Double> {373 if let domain { return domain }374 let values = stacked ? stackedTotals : series.flatMap { $0.points.map(\.value) }375 let bottom = min(0, values.min() ?? 0)376 let top = max((values.max() ?? 1) * 1.15, bottom + 1e-9)377 return bottom...top378 }379380 private var stackedTotals: [Double] {381 var totals: [Date: Double] = [:]382 for s in series { for p in s.points { totals[p.date, default: 0] += p.value } }383 return Array(totals.values)384 }385386 private func draw(_ context: inout GraphicsContext, _ size: CGSize) {387 let plot = CGRect(x: Self.gutter, y: 4, width: max(1, size.width - Self.gutter - 4), height: max(1, size.height - Self.footer - 4))388 let y = range389 let span = max(y.upperBound - y.lowerBound, 1e-12)390 func py(_ v: Double) -> CGFloat { plot.maxY - CGFloat((min(max(v, y.lowerBound), y.upperBound) - y.lowerBound) / span) * plot.height }391392 // Grid and y labels.393 let marks = ticks ?? (0...4).map { y.lowerBound + span * Double($0) / 4 }394 for mark in marks {395 var line = Path()396 line.move(to: CGPoint(x: plot.minX, y: py(mark)))397 line.addLine(to: CGPoint(x: plot.maxX, y: py(mark)))398 context.stroke(line, with: .color(ORIX.Palette.hairline), lineWidth: 1)399 context.draw(Text(format(mark)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary),400 at: CGPoint(x: plot.minX - 6, y: py(mark)), anchor: .trailing)401 }402403 let dates = series.flatMap { $0.points.map(\.date) }404 guard let first = dates.min(), let last = dates.max(), last > first else { return }405 let duration = last.timeIntervalSince(first)406 func px(_ d: Date) -> CGFloat { plot.minX + CGFloat(d.timeIntervalSince(first) / duration) * plot.width }407408 // Time labels: both ends and the middle.409 for (fraction, anchor) in [(0.0, UnitPoint.topLeading), (0.5, .top), (1.0, .topTrailing)] {410 let date = first.addingTimeInterval(duration * fraction)411 context.draw(Text(date, format: .dateTime.hour().minute().second()).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary),412 at: CGPoint(x: plot.minX + plot.width * fraction, y: plot.maxY + 3), anchor: anchor)413 }414415 context.clip(to: Path(plot))416 if stacked {417 // Areas stacked bottom to top, on the dates of the first series (all series are sampled together).418 var base = [Date: Double]()419 for s in series where s.points.count > 1 {420 var top = Path(), bottom: [CGPoint] = []421 for (i, p) in s.points.enumerated() {422 let low = base[p.date] ?? 0, high = low + p.value423 let point = CGPoint(x: px(p.date), y: py(high))424 if i == 0 { top.move(to: point) } else { top.addLine(to: point) }425 bottom.append(CGPoint(x: px(p.date), y: py(low)))426 base[p.date] = high427 }428 var area = top429 for point in bottom.reversed() { area.addLine(to: point) }430 area.closeSubpath()431 context.fill(area, with: .color(s.color.opacity(0.78)))432 context.stroke(top, with: .color(s.color), style: StrokeStyle(lineWidth: 1.2, lineJoin: .round))433 }434 } else {435 for s in series where s.points.count > 1 {436 var line = Path()437 for (i, p) in s.points.enumerated() {438 let point = CGPoint(x: px(p.date), y: py(p.value))439 if i == 0 { line.move(to: point) } else { line.addLine(to: point) }440 }441 if series.count == 1 {442 var area = line443 area.addLine(to: CGPoint(x: px(s.points.last!.date), y: plot.maxY))444 area.addLine(to: CGPoint(x: px(s.points.first!.date), y: plot.maxY))445 area.closeSubpath()446 context.fill(area, with: .linearGradient(Gradient(colors: [s.color.opacity(0.28), s.color.opacity(0.02)]),447 startPoint: CGPoint(x: 0, y: plot.minY), endPoint: CGPoint(x: 0, y: plot.maxY)))448 }449 context.stroke(line, with: .color(s.color), style: StrokeStyle(lineWidth: 1.6, lineCap: .round, lineJoin: .round))450 }451 }452 }453454 /// What VoiceOver reads instead of the drawing: the latest value and the range of each series.455 private var accessibilitySummary: String {456 let parts = series.compactMap { s -> String? in457 guard let last = s.points.last else { return nil }458 let values = s.points.map(\.value)459 return "\(s.name): \(format(last.value)). \(L("Minimum")) \(format(values.min() ?? 0)), \(L("Maximum")) \(format(values.max() ?? 0))."460 }461 return parts.isEmpty ? L("Collecting samples…") : parts.joined(separator: " ")462 }463}464465/// Section heading inside a detail page.466struct PageHeader: View {467 var title: LocalizedStringKey468 var subtitle: String?469 var family: MetricFamily470 var symbol: String?471 @Environment(\.colorBlindSafe) private var safe472473 var body: some View {474 HStack(spacing: ORIX.Space.sm) {475 Image(systemName: symbol ?? family.symbol)476 .font(.system(size: 18, weight: .semibold))477 .foregroundStyle(.white)478 .frame(width: 36, height: 36)479 .background((symbol == nil ? family.color(colorBlindSafe: safe) : ORIX.Palette.accentSecondary).gradient, in: RoundedRectangle(cornerRadius: 9, style: .continuous))480 .accessibilityHidden(true)481 VStack(alignment: .leading, spacing: 1) {482 Text(title).font(.system(size: 20, weight: .bold)).foregroundStyle(ORIX.Palette.textPrimary)483 if let subtitle { Text(subtitle).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled) }484 }485 Spacer()486 }487 .accessibilityElement(children: .ignore)488 .accessibilityLabel(Text(title))489 .accessibilityValue(Text(subtitle ?? ""))490 .accessibilityAddTraits(.isHeader)491 }492}493494/// A scrollable detail page on the ORIX canvas.495struct Page<Content: View>: View {496 @ViewBuilder var content: Content497 @Environment(\.density) private var density498499 var body: some View {500 ScrollView {501 VStack(alignment: .leading, spacing: ORIX.Space.md * density) { content }502 .padding(ORIX.Space.lg * density)503 .frame(maxWidth: 1500, alignment: .topLeading)504 .frame(maxWidth: .infinity, alignment: .top)505 }506 .background(ORIX.Palette.canvas)507 }508}509510/// Lays cards side by side at equal height when there is room, and stacks them otherwise.511/// Cards with a maximum width keep it; the others share what is left.512struct AdaptiveRowLayout: Layout {513 var spacing: CGFloat514 var breakpoint: CGFloat = 720515516 private func widths(_ subviews: Subviews, total: CGFloat) -> [CGFloat] {517 let available = total - spacing * CGFloat(max(subviews.count - 1, 0))518 let caps = subviews.map { $0.sizeThatFits(ProposedViewSize(width: 100_000, height: nil)).width }519 var result = [CGFloat](repeating: 0, count: subviews.count)520 var remaining = available521 var flexible: [Int] = []522 for (i, cap) in caps.enumerated() {523 if cap < 50_000 {524 result[i] = min(cap, available / CGFloat(subviews.count))525 remaining -= result[i]526 } else {527 flexible.append(i)528 }529 }530 if flexible.isEmpty {531 let extra = remaining / CGFloat(max(subviews.count, 1))532 return result.map { $0 + extra }533 }534 for i in flexible { result[i] = max(0, remaining / CGFloat(flexible.count)) }535 return result536 }537538 private func frames(_ subviews: Subviews, width: CGFloat) -> [CGRect] {539 guard !subviews.isEmpty else { return [] }540 if width >= breakpoint {541 let w = widths(subviews, total: width)542 let height = zip(subviews, w).map { $0.sizeThatFits(ProposedViewSize(width: $1, height: nil)).height }.max() ?? 0543 var x: CGFloat = 0544 return w.map { item in545 defer { x += item + spacing }546 return CGRect(x: x, y: 0, width: item, height: height)547 }548 }549 var y: CGFloat = 0550 return subviews.map { subview in551 let h = subview.sizeThatFits(ProposedViewSize(width: width, height: nil)).height552 defer { y += h + spacing }553 return CGRect(x: 0, y: y, width: width, height: h)554 }555 }556557 func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {558 let width = proposal.width ?? 900559 return CGSize(width: width, height: frames(subviews, width: width).map(\.maxY).max() ?? 0)560 }561562 func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {563 for (subview, frame) in zip(subviews, frames(subviews, width: bounds.width)) {564 subview.place(at: CGPoint(x: bounds.minX + frame.minX, y: bounds.minY + frame.minY), anchor: .topLeading, proposal: ProposedViewSize(frame.size))565 }566 }567}568569struct CardRow<Content: View>: View {570 @ViewBuilder var content: Content571 @Environment(\.density) private var density572573 var body: some View {574 AdaptiveRowLayout(spacing: ORIX.Space.md * density) { content }575 }576}577578/// Source and method of the metrics on a page, straight from the catalogue.579struct SourcesCard: View {580 var metrics: [MetricID]581582 var body: some View {583 Card("Sources and methods") {584 VStack(alignment: .leading, spacing: ORIX.Space.xs) {585 ForEach(metrics, id: \.self) { id in586 let d = MetricCatalog.descriptor(id)587 VStack(alignment: .leading, spacing: 2) {588 HStack(spacing: ORIX.Space.xs) {589 Text(L(d.name)).font(.system(size: 12, weight: .semibold))590 QualityBadge(d.quality)591 Spacer()592 Text(d.source).font(ORIX.Typeface.mono).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled)593 }594 Text(L(d.method)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)595 }596 .accessibilityElement(children: .combine)597 if id != metrics.last { Divider() }598 }599 }600 }601 }602}603