import SwiftUI enum TrendValueFormat { case percent case rate case bytes case memory case watts } /// 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?] = [] var fourth: [Double?] = [] let color: Color var secondColor: Color = .orange var thirdColor: Color = .purple var fourthColor: Color = .yellow var fixedScale: Double? = 1 var scaleLabel: String? var secondSeriesUsesAutonomousScale = false var firstValueFormat: TrendValueFormat? var secondValueFormat: TrendValueFormat? var firstLabel: LocalizedStringKey = "panel.total" var secondLabel: LocalizedStringKey = "network.upload" var thirdLabel: LocalizedStringKey = "cpu.system" var fourthLabel: LocalizedStringKey = "memory.compressed" var expectedInterval: TimeInterval = 2 var boundaryDates: Set = [] var intervals: [TimeInterval] = [] var plotHeight: CGFloat = PanelStyle.plotHeight var showsLegendValues = true @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var retainedScale: Double = 1 @State private var smallSamples = 0 @State private var retainedSecondScale: Double = 1 @State private var smallSecondSamples = 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 @State private var lastFrame: PanelCurveFrame? @State private var displayedFrame: PanelCurveFrame? private var inputFrame: PanelCurveFrame { PanelCurveFrame(dates: dates, series: [first, second, third, fourth], intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count), boundaryDates: boundaryDates) } private var maximum: Double { max(1, (first + second + third + fourth).compactMap { $0 }.filter(\.isFinite).max() ?? 1) } private var secondMaximum: Double { max(1, second.compactMap { $0 }.filter(\.isFinite).max() ?? 1) } private var scale: Double { max(0.0001, fixedScale ?? retainedScale) } private var secondaryScale: Double { max(0.0001, retainedSecondScale) } private var hasSecondaryScale: Bool { secondSeriesUsesAutonomousScale && !second.isEmpty } private var automaticFormat: TrendValueFormat { if let firstValueFormat { return firstValueFormat } if fixedScale == 1 { return .percent } if fixedScale == nil { return .rate } return .bytes } 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?, format: TrendValueFormat? = nil) -> String { guard let value, value.isFinite else { return "--" } switch format ?? automaticFormat { case .percent: return MetricFormat.percent(value) case .rate: return MetricFormat.rate(value) case .bytes: return MetricFormat.bytes(UInt64(max(0, value))) case .memory: return MetricFormat.memory(UInt64(max(0, value))) case .watts: return MetricFormat.watts(value) } } private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil) -> some View { HStack(spacing: 3) { RoundedRectangle(cornerRadius: 1).fill(tint).frame(width: 7, height: 7) Text(label) if showsLegendValues { Text(verbatim: formatted(values.last ?? nil, format: format)).monospacedDigit() } }.font(PanelStyle.legend).lineLimit(1).minimumScaleFactor(0.8) } private func tooltipRow(_ label: LocalizedStringKey, values: [Double?], tint: Color, format: TrendValueFormat? = nil, 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, format: format)).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, format: secondValueFormat, index: index) } if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) } if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) } } .font(.system(size: 10)).padding(8) .background { TooltipMaterialBackground() } .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, format: secondValueFormat) } if !third.isEmpty { legend(thirdLabel, values: third, tint: thirdColor) } if !fourth.isEmpty { legend(fourthLabel, values: fourth, tint: fourthColor) } 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: plotHeight) GeometryReader { proxy in ZStack(alignment: .topLeading) { PanelCurveCanvas(frame: displayedFrame ?? inputFrame, colors: [color, secondColor, thirdColor, fourthColor], scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale], maximumGap: max(5, expectedInterval * 2), targetBegin: (lastFrame ?? inputFrame).dates.first, targetEnd: (lastFrame ?? inputFrame).dates.last, 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..<4, id: \.self) { series in let values = [first, second, third, fourth][series] if index < values.count, let value = values[index], value.isFinite { let seriesScale = [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale][series] Circle().fill([color, secondColor, thirdColor, fourthColor][series]).frame(width: 5, height: 5) .position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / seriesScale)))) } } } } .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() }.frame(height: plotHeight) .anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { plot in guard let hoverPoint, let index else { return nil } return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index))) } if hasSecondaryScale { VStack(alignment: .leading) { Text(verbatim: formatted(secondaryScale, format: .watts)) Spacer(minLength: 0) Text(verbatim: formatted(secondaryScale / 2, format: .watts)) Spacer(minLength: 0) Text(verbatim: "0 W") }.font(.system(size: 8)).foregroundStyle(.secondary) .lineLimit(1).minimumScaleFactor(0.6).frame(width: 45, height: plotHeight) } } HStack { if let date = dates.first { Text(date, style: .time) } Spacer(minLength: 0) if let date = dates.last { Text(date, style: .time) } }.font(PanelStyle.legend).foregroundStyle(.secondary).frame(height: 12) } .frame(maxWidth: .infinity) .onAppear { retainedScale = maximum retainedSecondScale = secondMaximum lastFrame = inputFrame displayedFrame = inputFrame } .onChange(of: dates) { _, _ 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 secondTarget = secondMaximum if secondTarget > retainedSecondScale { retainedSecondScale = secondTarget; smallSecondSamples = 0 } else if secondTarget < retainedSecondScale * 0.5 { smallSecondSamples += 1 if smallSecondSamples >= 10 { retainedSecondScale = secondTarget; smallSecondSamples = 0 } } else { smallSecondSamples = 0 } let next = inputFrame let old = lastFrame let gap = PanelCurveGeometry.allowedGap(at: next.dates.count - 1, intervals: next.intervals, fallback: max(5, expectedInterval * 2)) let append = old.map { PanelCurveGeometry.isAppend(from: $0.dates, to: next.dates, maximumGap: gap) } == true && !(next.dates.last.map { boundaryDates.contains($0) } ?? false) let animated = append && !reduceMotion var transaction = Transaction(); transaction.disablesAnimations = true withTransaction(transaction) { lastFrame = next displayedFrame = next if animated, let old { displayedFrame = PanelCurveFrame.transition(from: old, to: next) } previousBegin = animated ? old?.dates.first : nil previousEnd = animated ? old?.dates.last : nil progress = animated ? 0 : 1 } } .task(id: lastFrame?.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; lastFrame = inputFrame; displayedFrame = inputFrame } } .accessibilityElement(children: .combine) } } private struct PanelCurveCanvas: View, Animatable { let frame: PanelCurveFrame let colors: [Color] let scales: [Double] let maximumGap: TimeInterval let targetBegin: Date? let targetEnd: Date? 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 = targetBegin, let last = targetEnd else { return } let domain = PanelCurveFrame.domain(previousBegin: previousBegin, previousEnd: previousEnd, begin: first, end: last, progress: Double(progress)) for seriesIndex in frame.series.indices { let values = frame.series[seriesIndex] let tint = colors[min(seriesIndex, colors.count - 1)] let scale = scales[min(seriesIndex, scales.count - 1)] for run in PanelCurveGeometry.runs(dates: frame.dates, values: values, maximumGap: maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) { let points = run.map { item in CGPoint(x: size.width * domain.position(item.date), 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)) } } } } } }