import SwiftUI enum TrendValueFormat { case percent case rate case bytes case memory case watts } /// Static curves skip missing vertices, retaining timestamps and explicit sampling breaks. 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 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 visibleSeriesCount = 1 var stackOrder: [Int] = [] @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? private var inputFrame: PanelCurveFrame { var series = [first, second, third, fourth] while series.last?.isEmpty == true { series.removeLast() } return PanelCurveFrame(dates: dates, series: series, intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count), boundaryDates: boundaryDates) } private var renderFrame: PanelCurveFrame { let raw = inputFrame guard !stackOrder.isEmpty else { return raw } return PanelCurveFrame(dates: raw.dates, series: stackOrder.map { index in raw.series.indices.contains(index) ? raw.series[index] : Array(repeating: nil, count: raw.dates.count) }, intervals: raw.intervals, boundaryDates: raw.boundaryDates) } private var renderColors: [Color] { let colors = [color, secondColor, thirdColor, fourthColor] return stackOrder.isEmpty ? colors : stackOrder.map { colors[min(max(0, $0), colors.count - 1)] } } private var maximum: Double { let values = stackOrder.isEmpty ? first + second + third + fourth : StackedSeries.bands(renderFrame.series, count: dates.count).last?.upper ?? [] return max(1, values.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 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: 3) { 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: 9)).padding(6) .background { TooltipBackground() } .overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2))) } var body: some View { GeometryReader { proxy in NativePanelCurve(frame: renderFrame, colors: renderColors, scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale], maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index, visibleSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count, filledSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count, stacked: !stackOrder.isEmpty) .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 } } .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))) } } .frame(maxWidth: .infinity, maxHeight: .infinity) .onAppear { retainedScale = maximum retainedSecondScale = secondMaximum } .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 } } .accessibilityElement(children: .ignore) .accessibilityLabel(Text(firstLabel)) .accessibilityValue(Text(verbatim: formatted(first.last ?? nil))) } }