import SwiftUI /// Real timestamps determine x positions; missing data and pauses break the path. struct PanelTrendChart: View { let dates: [Date] let first: [Double?] var second: [Double?] = [] let color: Color var secondColor: Color = .orange var fixedScale: Double? = 1 var scaleLabel: String? @State private var retainedScale: Double = 1 @State private var smallSamples = 0 private var maximum: Double { max(1, (first + second).compactMap { $0 }.filter(\.isFinite).max() ?? 1) } var body: some View { VStack(spacing: 2) { HStack { Text(verbatim: scaleLabel ?? (fixedScale == nil ? MetricFormat.rate(retainedScale) : "100%")) Spacer() }.font(.system(size: 9)).foregroundStyle(.secondary) Canvas { context, size in guard let begin = dates.first, let end = dates.last, end > begin else { return } let scale = fixedScale ?? retainedScale for (values, tint) in [(first, color), (second, secondColor)] { var path = Path() var connected = false for index in dates.indices { guard index < values.count, let value = values[index], value.isFinite else { connected = false; continue } if index > 0 && dates[index].timeIntervalSince(dates[index - 1]) > 5 { connected = false } let point = CGPoint(x: size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin), y: size.height * (1 - min(1, max(0, value / scale)))) if connected { path.addLine(to: point) } else { path.move(to: point) } connected = true } context.stroke(path, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round)) } }.frame(height: 44) HStack { if let date = dates.first { Text(date, style: .time) } Spacer() if let date = dates.last { Text(date, style: .time) } }.font(.system(size: 9)).foregroundStyle(.secondary) } .onAppear { retainedScale = maximum } .onChange(of: dates.last) { _, _ 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 } } .accessibilityHidden(true) } }