import SwiftUI /// Bounded, timestamp-based curves. Gaps remain gaps; animation only runs on append. struct PanelTrendChart: View { let dates: [Date] let first: [Double?] var second: [Double?] = [] var third: [Double?] = [] let color: Color var secondColor: Color = .orange var thirdColor: Color = .purple var fixedScale: Double? = 1 var scaleLabel: String? var firstLabel: LocalizedStringKey = "panel.total" var secondLabel: LocalizedStringKey = "network.upload" var thirdLabel: LocalizedStringKey = "cpu.system" var expectedInterval: TimeInterval = 2 var boundaryDates: Set = [] @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var retainedScale: Double = 1 @State private var smallSamples = 0 @State private var hoveredDate: Date? @State private var hoverPoint: CGPoint? @State private var previousBegin: Date? @State private var previousEnd: Date? @State private var progress: CGFloat = 1 private var maximum: Double { max(1, (first + second + third).compactMap { $0 }.filter(\.isFinite).max() ?? 1) } private var scale: Double { max(0.0001, fixedScale ?? retainedScale) } private var index: Int? { guard !dates.isEmpty else { return nil } guard let hoveredDate else { return dates.count - 1 } return dates.indices.min { abs(dates[$0].timeIntervalSince(hoveredDate)) < abs(dates[$1].timeIntervalSince(hoveredDate)) } } private func formatted(_ value: Double?) -> String { guard let value, value.isFinite else { return "--" } if fixedScale == 1 { return MetricFormat.percent(value) } if fixedScale == nil { return MetricFormat.rate(value) } return MetricFormat.bytes(UInt64(max(0, value))) } private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color) -> some View { HStack(spacing: 3) { RoundedRectangle(cornerRadius: 1).fill(tint).frame(width: 7, height: 7) Text(label) Text(verbatim: formatted(values.last ?? nil)).monospacedDigit() }.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.8) } private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, index: Int) -> some View { HStack(spacing: 6) { RoundedRectangle(cornerRadius: 2).fill(tint).frame(width: 8, height: 8) Text(label) Spacer(minLength: 4) Text(verbatim: formatted(index < values.count ? values[index] : nil)).monospacedDigit() } } private func tooltip(index: Int) -> some View { VStack(alignment: .leading, spacing: 5) { Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.secondary) tooltipRow(firstLabel, values: first, tint: color, index: index) if !second.isEmpty { tooltipRow(secondLabel, values: second, tint: secondColor, index: index) } if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) } } .font(.system(size: 10)).padding(8) .background(Color("PanelTooltip"), in: .rect(cornerRadius: 7)) .overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2))) .shadow(color: .black.opacity(0.2), radius: 5, y: 2) } var body: some View { VStack(spacing: 3) { HStack(spacing: 10) { legend(firstLabel, values: first, tint: color) if !second.isEmpty { legend(secondLabel, values: second, tint: secondColor) } if !third.isEmpty { legend(thirdLabel, values: third, tint: thirdColor) } Spacer(minLength: 0) }.frame(height: 14) HStack(spacing: 5) { VStack(alignment: .trailing) { Text(verbatim: scaleLabel ?? formatted(scale)) Spacer(minLength: 0) Text(verbatim: formatted(scale / 2)) Spacer(minLength: 0) Text(verbatim: "0") }.font(.system(size: 8)).foregroundStyle(.secondary) .lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: 58) GeometryReader { proxy in ZStack(alignment: .topLeading) { PanelCurveCanvas(dates: dates, series: [first, second, third], colors: [color, secondColor, thirdColor], scale: scale, maximumGap: max(5, expectedInterval * 2), boundaryDates: boundaryDates, previousBegin: previousBegin, previousEnd: previousEnd, progress: progress) if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin { let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin) Path { path in path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: proxy.size.height)) }.stroke(.primary.opacity(0.45), style: StrokeStyle(lineWidth: 1, dash: [3, 2])) ForEach(0..<3, id: \.self) { series in let values = [first, second, third][series] if index < values.count, let value = values[index], value.isFinite { Circle().fill([color, secondColor, thirdColor][series]).frame(width: 5, height: 5) .position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / scale)))) } } } } .contentShape(Rectangle()) .onContinuousHover { phase in switch phase { case .active(let point): if let begin = dates.first, let end = dates.last { hoverPoint = point hoveredDate = begin.addingTimeInterval(end.timeIntervalSince(begin) * min(1, max(0, point.x / max(1, proxy.size.width)))) } case .ended: hoveredDate = nil; hoverPoint = nil } } .clipped() .overlay(alignment: .topLeading) { if let hoverPoint, let index { tooltip(index: index) .frame(width: min(180, proxy.size.width)) .offset(x: min(max(0, hoverPoint.x + 12), max(0, proxy.size.width - 180)), y: min(hoverPoint.y + 10, proxy.size.height - 12)) .allowsHitTesting(false) .accessibilityHidden(true) } } }.frame(height: 58).zIndex(10) } HStack { if let date = dates.first { Text(date, style: .time) } Spacer(minLength: 0) if let date = dates.last { Text(date, style: .time) } }.font(.system(size: 9)).foregroundStyle(.secondary).frame(height: 12) } .frame(maxWidth: .infinity) .zIndex(hoveredDate == nil ? 0 : 20) .onAppear { retainedScale = maximum } .onChange(of: dates) { old, new in let target = maximum if target > retainedScale { retainedScale = target; smallSamples = 0 } else if target < retainedScale * 0.5 { smallSamples += 1 if smallSamples >= 10 { retainedScale = target; smallSamples = 0 } } else { smallSamples = 0 } let append = PanelCurveGeometry.isAppend(from: old, to: new, maximumGap: max(5, expectedInterval * 2)) && !(new.last.map { boundaryDates.contains($0) } ?? false) var transaction = Transaction(); transaction.disablesAnimations = true withTransaction(transaction) { previousBegin = append && !reduceMotion ? old.first : nil previousEnd = append && !reduceMotion ? old.last : nil progress = previousBegin == nil ? 1 : 0 } } .task(id: dates.last) { guard progress == 0, !reduceMotion else { return } do { try await Task.sleep(for: .milliseconds(16)) } catch { return } withAnimation(.easeInOut(duration: 0.35)) { progress = 1 } } .onChange(of: reduceMotion) { _, reduced in if reduced { progress = 1; previousBegin = nil; previousEnd = nil } } .accessibilityElement(children: .combine) } } private struct PanelCurveCanvas: View, Animatable { let dates: [Date] let series: [[Double?]] let colors: [Color] let scale: Double let maximumGap: TimeInterval let boundaryDates: Set let previousBegin: Date? let previousEnd: Date? var progress: CGFloat var animatableData: CGFloat { get { progress } set { progress = newValue } } var body: some View { Canvas { context, size in var grid = Path() for step in 0...10 { let x = size.width * Double(step) / 10 grid.move(to: CGPoint(x: x, y: 0)); grid.addLine(to: CGPoint(x: x, y: size.height)) } for step in 0...2 { let y = size.height * Double(step) / 2 grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: size.width, y: y)) } context.stroke(grid, with: .color(.primary.opacity(0.10)), lineWidth: 0.5) guard let first = dates.first, let last = dates.last else { return } let begin = (previousBegin ?? first).timeIntervalSinceReferenceDate * (1 - progress) + first.timeIntervalSinceReferenceDate * progress let end = (previousEnd ?? last).timeIntervalSinceReferenceDate * (1 - progress) + last.timeIntervalSinceReferenceDate * progress for (seriesIndex, entry) in zip(series, colors).enumerated() { let (values, tint) = entry for run in PanelCurveGeometry.runs(dates: dates, values: values, maximumGap: maximumGap, boundaryDates: boundaryDates) { let points = run.map { item in CGPoint(x: end > begin ? size.width * (item.date.timeIntervalSinceReferenceDate - begin) / (end - begin) : size.width, y: size.height * (1 - min(1, max(0, item.value / scale)))) } guard let start = points.first, let finish = points.last else { continue } var line = Path(); line.move(to: start) for pair in zip(points, points.dropFirst()) { let middle = (pair.0.x + pair.1.x) / 2 // Horizontal tangents keep the rounded curve between adjacent sample values. line.addCurve(to: pair.1, control1: CGPoint(x: middle, y: pair.0.y), control2: CGPoint(x: middle, y: pair.1.y)) } if points.count == 1 { context.fill(Path(ellipseIn: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)), with: .color(tint)) } else { var area = line area.addLine(to: CGPoint(x: finish.x, y: size.height)); area.addLine(to: CGPoint(x: start.x, y: size.height)); area.closeSubpath() context.fill(area, with: .linearGradient(Gradient(colors: [tint.opacity(0.20), tint.opacity(0.01)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height))) context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round, dash: seriesIndex == 1 ? [4, 2] : seriesIndex == 2 ? [1, 2] : [])) } } } } } }