Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Command Center (MCC)9// File : packages/swift-core/Sources/MCCCore/UI/Charts.swift10// Module : MCCCore11// Repository : https://git.spboucher.ai/maclustr-command-center12// Project Website : https://clustr.spboucher.ai13// Created : 2026-11-1814// Last Modified : 2026-11-1815//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Accessibility89import Charts90import SwiftUI9192/// One bucket of a series: the contract's `[ts_ms, avg, min, max]`.93public struct SeriesPoint: Sendable, Hashable, Identifiable {94 public var date: Date95 public var avg: Double96 public var min: Double97 public var max: Double98 public var id: Date { date }99 public init(date: Date, avg: Double, min: Double, max: Double) {100 self.date = date; self.avg = avg; self.min = min; self.max = max101 }102}103104public struct ChartSeries: Sendable, Hashable, Identifiable {105 public var id: String106 public var name: String107 public var points: [SeriesPoint]108109 public init(id: String, name: String, points: [SeriesPoint]) {110 self.id = id; self.name = name; self.points = points111 }112113 /// Builds a series from the contract's `MetricPoints`. Malformed rows are dropped, never patched.114 public init(id: String, name: String, metricPoints: [[Double]]) {115 self.id = id116 self.name = name117 self.points = metricPoints.compactMap { row in118 guard row.count >= 4 else { return nil }119 return SeriesPoint(date: Date(timeIntervalSince1970: row[0] / 1000), avg: row[1], min: row[2], max: row[3])120 }.sorted { $0.date < $1.date }121 }122123 /// The typical spacing of the buckets (median of the deltas).124 public var typicalStep: TimeInterval? {125 guard points.count >= 2 else { return nil }126 let deltas = zip(points.dropFirst(), points).map { $0.date.timeIntervalSince($1.date) }.sorted()127 return deltas[deltas.count / 2]128 }129130 /// Splits the series where buckets are missing (the server omits them): a gap is drawn as a gap, the line is131 /// never interpolated across it.132 public func segments(expectedStep: TimeInterval? = nil, tolerance: Double = 2.5) -> [[SeriesPoint]] {133 guard let step = expectedStep ?? typicalStep, step > 0 else { return points.isEmpty ? [] : [points] }134 var out: [[SeriesPoint]] = []135 var current: [SeriesPoint] = []136 for p in points {137 if let last = current.last, p.date.timeIntervalSince(last.date) > step * tolerance {138 out.append(current)139 current = []140 }141 current.append(p)142 }143 if !current.isEmpty { out.append(current) }144 return out145 }146147 public var gapCount: Int { max(0, segments().count - 1) }148149 public struct Summary: Sendable, Equatable {150 public var min: Double151 public var max: Double152 public var mean: Double153 public var last: Double154 public var gaps: Int155 }156157 public var summary: Summary? {158 guard let last = points.last else { return nil }159 return Summary(min: points.map(\.min).min() ?? last.min, max: points.map(\.max).max() ?? last.max,160 mean: points.map(\.avg).reduce(0, +) / Double(points.count), last: last.avg, gaps: gapCount)161 }162}163164/// Tiny inline trend. Gaps stay gaps. Hidden from VoiceOver unless a label is given (the adjacent value carries165/// the information).166public struct Sparkline: View {167 @Environment(\.mccTheme) private var theme168 private let series: ChartSeries169 private let tone: StatusTone?170 private let accessibilityText: String?171 public init(_ series: ChartSeries, tone: StatusTone? = nil, accessibilityLabel: String? = nil) {172 self.series = series; self.tone = tone; self.accessibilityText = accessibilityLabel173 }174 public var body: some View {175 Canvas { ctx, size in176 let pts = series.points177 guard pts.count >= 2, let t0 = pts.first?.date, let t1 = pts.last?.date, t1 > t0 else { return }178 let lo = pts.map(\.avg).min() ?? 0, hi = pts.map(\.avg).max() ?? 1179 let span = hi - lo == 0 ? 1 : hi - lo180 let color = tone?.color(theme) ?? theme.accent181 for seg in series.segments() {182 var path = Path()183 for (i, p) in seg.enumerated() {184 let x = size.width * p.date.timeIntervalSince(t0) / t1.timeIntervalSince(t0)185 let y = size.height - 1 - (size.height - 2) * (p.avg - lo) / span186 if i == 0 { path.move(to: CGPoint(x: x, y: y)) } else { path.addLine(to: CGPoint(x: x, y: y)) }187 }188 if seg.count == 1, let p = seg.first {189 let x = size.width * p.date.timeIntervalSince(t0) / t1.timeIntervalSince(t0)190 let y = size.height - 1 - (size.height - 2) * (p.avg - lo) / span191 ctx.fill(Path(ellipseIn: CGRect(x: x - 1, y: y - 1, width: 2, height: 2)), with: .color(color))192 } else {193 ctx.stroke(path, with: .color(color), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))194 }195 }196 }197 .frame(minWidth: 48, minHeight: 16)198 .accessibilityHidden(accessibilityText == nil)199 .accessibilityLabel(accessibilityText ?? "")200 }201}202203/// Time-series chart: average line, min–max band, visible gaps, one colour AND one dash pattern per series.204/// VoiceOver gets a textual summary and an audio graph.205public struct TimeSeriesChart: View {206 @Environment(\.mccTheme) private var theme207 private let title: String208 private let unit: String?209 private let series: [ChartSeries]210 private let domain: ClosedRange<Date>?211 private let showBand: Bool212 private let height: CGFloat213214 public init(title: String, unit: String?, series: [ChartSeries], domain: ClosedRange<Date>? = nil, showBand: Bool = true, height: CGFloat = 180) {215 self.title = title; self.unit = unit; self.series = series; self.domain = domain216 self.showBand = showBand; self.height = height217 }218219 private static let dashes: [[CGFloat]] = [[], [6, 3], [2, 3], [8, 3, 2, 3], [4, 4], [10, 4]]220221 private struct Segment: Identifiable {222 let id: String223 let seriesIndex: Int224 let points: [SeriesPoint]225 }226227 private var segments: [Segment] {228 series.enumerated().flatMap { index, s in229 s.segments().enumerated().map { Segment(id: "\(s.id)#\($0.offset)", seriesIndex: index, points: $0.element) }230 }231 }232233 public var body: some View {234 VStack(alignment: .leading, spacing: Tokens.Space.s2) {235 if series.allSatisfy({ $0.points.isEmpty }) {236 Text(tr("chart.no_data")).font(.callout).foregroundStyle(theme.textTertiary)237 .frame(maxWidth: .infinity, minHeight: height, alignment: .center)238 } else {239 chart.frame(height: height)240 if series.count > 1 { legend }241 }242 }243 .accessibilityElement(children: .ignore)244 .accessibilityLabel(title)245 .accessibilityValue(accessibilitySummary)246 .accessibilityChartDescriptor(Descriptor(title: title, unit: unit, series: series, summary: accessibilitySummary))247 }248249 private var chart: some View {250 Chart {251 ForEach(segments) { seg in252 let color = theme.chartColor(seg.seriesIndex)253 if showBand && series.count <= 2 {254 ForEach(seg.points) { p in255 AreaMark(x: .value("t", p.date), yStart: .value("min", p.min), yEnd: .value("max", p.max), series: .value("s", "band-" + seg.id))256 .foregroundStyle(color.opacity(theme.highContrast ? 0.32 : 0.18))257 .interpolationMethod(.linear)258 }259 }260 ForEach(seg.points) { p in261 LineMark(x: .value("t", p.date), y: .value("avg", p.avg), series: .value("s", seg.id))262 .foregroundStyle(color)263 .lineStyle(StrokeStyle(lineWidth: theme.highContrast ? 2.5 : 1.8, lineCap: .round, lineJoin: .round,264 dash: Self.dashes[seg.seriesIndex % Self.dashes.count]))265 .interpolationMethod(.linear)266 }267 if seg.points.count == 1, let p = seg.points.first {268 PointMark(x: .value("t", p.date), y: .value("avg", p.avg)).foregroundStyle(color).symbolSize(18)269 }270 }271 }272 .chartXScale(domain: domain ?? autoDomain)273 .chartXAxis {274 AxisMarks(values: .automatic(desiredCount: 5)) { _ in275 AxisGridLine().foregroundStyle(theme.palette.chartGrid)276 AxisValueLabel().foregroundStyle(theme.palette.chartAxis)277 }278 }279 .chartYAxis {280 AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { value in281 AxisGridLine().foregroundStyle(theme.palette.chartGrid)282 AxisValueLabel {283 if let v = value.as(Double.self) { Text(Format.metric(v, unit: unit)).foregroundStyle(theme.palette.chartAxis) }284 }285 }286 }287 .chartLegend(.hidden)288 }289290 private var autoDomain: ClosedRange<Date> {291 let all = series.flatMap(\.points).map(\.date)292 let lo = all.min() ?? Date(timeIntervalSinceNow: -3600), hi = all.max() ?? Date()293 return lo...(hi > lo ? hi : lo.addingTimeInterval(60))294 }295296 private var legend: some View {297 FlowLegend(items: series.enumerated().map { i, s in298 (name: s.name, color: theme.chartColor(i), dash: Self.dashes[i % Self.dashes.count])299 })300 }301302 private var accessibilitySummary: String {303 let parts = series.compactMap { s -> String? in304 guard let m = s.summary else { return series.count > 1 ? "\(s.name): \(tr("chart.no_data"))" : nil }305 let text = tr("chart.summary", Format.metric(m.min, unit: unit), Format.metric(m.mean, unit: unit),306 Format.metric(m.max, unit: unit), Format.metric(m.last, unit: unit))307 let gaps = m.gaps > 0 ? ", " + tr("chart.gaps", m.gaps) : ""308 return (series.count > 1 ? "\(s.name): " : "") + text + gaps309 }310 return parts.isEmpty ? tr("chart.no_data") : parts.joined(separator: ". ")311 }312313 private struct Descriptor: AXChartDescriptorRepresentable {314 let title: String315 let unit: String?316 let series: [ChartSeries]317 let summary: String318319 func makeChartDescriptor() -> AXChartDescriptor {320 let all = series.flatMap(\.points)321 let t0 = all.map(\.date.timeIntervalSince1970).min() ?? 0322 let t1 = max(all.map(\.date.timeIntervalSince1970).max() ?? 1, t0 + 1)323 let lo = all.map(\.min).min() ?? 0324 let hi = max(all.map(\.max).max() ?? 1, lo + 0.000_001)325 let unitText = unit326 let x = AXNumericDataAxisDescriptor(title: tr("chart.axis.time"), range: t0...t1, gridlinePositions: []) {327 Format.dateTime(Date(timeIntervalSince1970: $0))328 }329 let y = AXNumericDataAxisDescriptor(title: unitText ?? tr("chart.axis.value"), range: lo...hi, gridlinePositions: []) {330 Format.metric($0, unit: unitText)331 }332 let data = series.map { s in333 AXDataSeriesDescriptor(name: s.name, isContinuous: true,334 dataPoints: s.points.map { AXDataPoint(x: $0.date.timeIntervalSince1970, y: $0.avg) })335 }336 return AXChartDescriptor(title: title, summary: summary, xAxis: x, yAxis: y, additionalAxes: [], series: data)337 }338 }339}340341/// Legend whose entries show the dash pattern as well as the colour.342struct FlowLegend: View {343 @Environment(\.mccTheme) private var theme344 let items: [(name: String, color: Color, dash: [CGFloat])]345 var body: some View {346 ViewThatFits(in: .horizontal) {347 HStack(spacing: Tokens.Space.s5) { entries }348 VStack(alignment: .leading, spacing: Tokens.Space.s1) { entries }349 }350 }351 @ViewBuilder private var entries: some View {352 ForEach(Array(items.enumerated()), id: \.offset) { _, item in353 HStack(spacing: Tokens.Space.s2) {354 Path { p in p.move(to: CGPoint(x: 0, y: 4)); p.addLine(to: CGPoint(x: 22, y: 4)) }355 .stroke(item.color, style: StrokeStyle(lineWidth: 2, dash: item.dash))356 .frame(width: 22, height: 8)357 Text(item.name).font(.caption).foregroundStyle(theme.textSecondary).lineLimit(1)358 }359 }360 }361}362