Files
Kymo/kymo/UI/Charts/PanelTrendChart.swift
T

187 lines
9.3 KiB
Swift

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 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<Date> = []
var intervals: [TimeInterval] = []
var plotHeight: CGFloat = PanelStyle.plotHeight
var showsLegendValues = true
@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 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 { TooltipBackground() }
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.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) {
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
scales: [scale, hasSecondaryScale ? secondaryScale : scale, hasSecondaryScale ? secondaryScale : scale, scale],
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index)
}
.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
}
.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: .combine)
}
}