feat(ui): 统一实现卡片背景趋势与大数值布局

This commit is contained in:
2026-11-15 15:40:29 +08:00
parent 397156249b
commit 3c1a2baace
25 changed files with 447 additions and 268 deletions
+2 -1
View File
@@ -17,6 +17,7 @@ struct ChartTooltipPreference: PreferenceKey {
/// Measures the actual localized tooltip, then keeps it inside the card.
struct ChartTooltipLayer: Layout {
let point: CGPoint
var minimumY: CGFloat = 0
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
proposal.replacingUnspecifiedDimensions()
@@ -30,7 +31,7 @@ struct ChartTooltipLayer: Layout {
let x = min(max(10, point.x + 12), max(10, bounds.width - size.width - 10))
let below = point.y + 10
let preferredY = below + size.height <= bounds.height - 10 ? below : point.y - size.height - 10
let y = min(max(10, preferredY), max(10, bounds.height - size.height - 10))
let y = min(max(max(10, minimumY), preferredY), max(10, bounds.height - size.height - 10))
tooltip.place(at: CGPoint(x: bounds.minX + x, y: bounds.minY + y), anchor: .topLeading, proposal: tooltipProposal)
}
}
+28 -9
View File
@@ -1,13 +1,15 @@
import AppKit
import SwiftUI
/// Bounded static Core Graphics paths. No animation, gradient fill or per-frame work.
/// Bounded static lines and per-run area paths. Hover never rebuilds geometry.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
@@ -16,7 +18,7 @@ struct NativePanelCurve: NSViewRepresentable {
func makeNSView(context: Context) -> PlotView { PlotView() }
func updateNSView(_ view: PlotView, context: Context) {
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap,
hoveredIndex: hoveredIndex))
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount))
}
struct Input: Equatable {
let frame: PanelCurveFrame
@@ -24,6 +26,8 @@ struct NativePanelCurve: NSViewRepresentable {
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
}
final class PlotView: NSView {
private(set) var input: Input?
@@ -43,6 +47,7 @@ struct NativePanelCurve: NSViewRepresentable {
layer?.masksToBounds = true
curves.anchorPoint = .zero
grid.fillColor = nil; grid.lineWidth = 0.5
grid.isHidden = true
hoverLine.fillColor = nil; hoverLine.lineWidth = 1; hoverLine.lineDashPattern = [3, 2]
for child in [grid, curves, hoverLine] { layer?.addSublayer(child) }
setAccessibilityElement(false)
@@ -57,7 +62,11 @@ struct NativePanelCurve: NSViewRepresentable {
CATransaction.begin(); CATransaction.setDisableActions(true)
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
ensureLayers(value.frame.series.count)
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count { updatePalette() }
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count
|| old?.filledSeriesCount != value.filledSeriesCount { updatePalette() }
for index in seriesLayers.indices {
seriesLayers[index].root.isHidden = index >= (value.visibleSeriesCount ?? value.frame.series.count)
}
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap {
rebuildPaths()
}
@@ -83,6 +92,9 @@ struct NativePanelCurve: NSViewRepresentable {
for index in seriesLayers.indices {
let color = palette[min(index, palette.count - 1)], series = seriesLayers[index]
series.line.strokeColor = color.cgColor; series.points.fillColor = color.cgColor
let dark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
series.area.fillColor = index < (input?.filledSeriesCount ?? 0)
? color.withAlphaComponent(dark ? 0.16 : 0.12).cgColor : nil
hoverDots[index].fillColor = color.cgColor
}
}
@@ -117,7 +129,7 @@ struct NativePanelCurve: NSViewRepresentable {
let scale = value.isFinite && value > 0 ? value : 1
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: frame.series[index], maximumGap: input.maximumGap,
boundaryDates: frame.boundaryDates, intervals: frame.intervals)
let line = CGMutablePath(), dots = CGMutablePath()
let line = CGMutablePath(), dots = CGMutablePath(), area = CGMutablePath()
for run in runs {
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.value / scale)))) }
@@ -131,9 +143,15 @@ struct NativePanelCurve: NSViewRepresentable {
segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
line.addPath(segment)
// Each continuous run closes against its own baseline, preserving real gaps.
let fill = CGMutablePath(); fill.addPath(segment)
fill.addLine(to: CGPoint(x: points.last!.x, y: bounds.height))
fill.addLine(to: CGPoint(x: start.x, y: bounds.height)); fill.closeSubpath()
area.addPath(fill)
}
series.line.path = line
series.points.path = dots
series.area.path = area
}
}
private func updateHover() {
@@ -145,6 +163,7 @@ struct NativePanelCurve: NSViewRepresentable {
let x = bounds.width * domain.position(input.frame.dates[index])
let path = CGMutablePath(); path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height)); hoverLine.path = path
for series in input.frame.series.indices {
guard series < (input.visibleSeriesCount ?? input.frame.series.count) else { continue }
let values = input.frame.series[series]
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
let scale = input.scales[min(series, input.scales.count - 1)]
@@ -171,17 +190,17 @@ struct NativePanelCurve: NSViewRepresentable {
updatePalette(); CATransaction.commit()
}
private final class SeriesLayer {
let root = CALayer(), line = CAShapeLayer(), points = CAShapeLayer()
let root = CALayer(), area = CAShapeLayer(), line = CAShapeLayer(), points = CAShapeLayer()
init() {
line.fillColor = nil; line.lineWidth = 1.5; line.lineCap = .round; line.lineJoin = .round
root.addSublayer(line); root.addSublayer(points)
line.fillColor = nil; line.lineWidth = 1.8; line.lineCap = .round; line.lineJoin = .round
root.addSublayer(area); root.addSublayer(line); root.addSublayer(points)
}
func resize(_ bounds: CGRect) {
root.frame = bounds
let local = CGRect(origin: .zero, size: bounds.size)
line.frame = local; points.frame = local
area.frame = local; line.frame = local; points.frame = local
}
func clear() { line.path = nil; points.path = nil }
func clear() { area.path = nil; line.path = nil; points.path = nil }
}
}
}
+19 -65
View File
@@ -20,7 +20,6 @@ struct PanelTrendChart: View {
var thirdColor: Color = .purple
var fourthColor: Color = .yellow
var fixedScale: Double? = 1
var scaleLabel: String?
var secondSeriesUsesAutonomousScale = false
var firstValueFormat: TrendValueFormat?
var secondValueFormat: TrendValueFormat?
@@ -31,8 +30,7 @@ struct PanelTrendChart: View {
var expectedInterval: TimeInterval = 2
var boundaryDates: Set<Date> = []
var intervals: [TimeInterval] = []
var plotHeight: CGFloat = PanelStyle.plotHeight
var showsLegendValues = true
var visibleSeriesCount = 1
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var retainedSecondScale: Double = 1
@@ -73,16 +71,6 @@ struct PanelTrendChart: View {
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)
@@ -105,64 +93,28 @@ struct PanelTrendChart: View {
}
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
GeometryReader { proxy in
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale],
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
visibleSeriesCount: visibleSeriesCount, filledSeriesCount: visibleSeriesCount)
.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)
.frame(height: ResourceCardMetrics.plotHeight)
.onAppear {
retainedScale = maximum
retainedSecondScale = secondMaximum
@@ -181,6 +133,8 @@ struct PanelTrendChart: View {
if smallSecondSamples >= 10 { retainedSecondScale = secondTarget; smallSecondSamples = 0 }
} else { smallSecondSamples = 0 }
}
.accessibilityElement(children: .combine)
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text(firstLabel))
.accessibilityValue(Text(verbatim: formatted(first.last ?? nil)))
}
}