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)))
}
}
+1 -17
View File
@@ -1,6 +1,6 @@
import SwiftUI
/// Shared roles for the compact monitoring panel. Micro charts keep their own 8pt role.
/// Shared roles for auxiliary labels and native panel controls.
enum PanelStyle {
static let title = Font.system(size: 13, weight: .semibold)
static let label = Font.system(size: 10)
@@ -9,15 +9,6 @@ enum PanelStyle {
static let padding: CGFloat = 10
static let gap: CGFloat = 8
static let titleHeight: CGFloat = 20
static let plotHeight: CGFloat = 48
}
struct CardSeparator: View {
var body: some View {
Rectangle().fill(.primary.opacity(0.08)).frame(height: 1)
.padding(.vertical, 2)
.accessibilityHidden(true)
}
}
struct CardField<Content: View>: View {
@@ -42,13 +33,6 @@ struct CardSurface: ViewModifier {
}
}
struct CardInset: ViewModifier {
func body(content: Content) -> some View {
content.padding(.horizontal, 8).padding(.vertical, 5)
.background(.primary.opacity(0.04), in: RoundedRectangle(cornerRadius: 6))
}
}
/// Segment widths are proportional to the supplied total, without minimum fills.
struct CapacityBar: View {
let values: [Double]
+98 -49
View File
@@ -1,6 +1,7 @@
import SwiftUI
struct ResourceCard<Content: View>: View {
/// One fixed-size native host owns foreground, background trend and hover presentation.
struct ResourceCard<Chart: View, Content: View>: View {
let title: LocalizedStringKey
let symbol: String
let color: Color
@@ -14,69 +15,51 @@ struct ResourceCard<Content: View>: View {
var detail: String? = nil
var detailColor: Color? = nil
var detailHelp: String? = nil
var headerAccessory: AnyView? = nil
@ViewBuilder var chart: () -> Chart
@ViewBuilder var content: () -> Content
@Environment(\.colorScheme) private var colorScheme
var body: some View {
NativeContentHost(content: cardBody)
}
var body: some View { NativeContentHost(content: cardBody) }
private var cardBody: some View {
GeometryReader { bounds in
VStack(alignment: .leading, spacing: 4) {
HStack(alignment: .center, spacing: 6) {
Label {
Text(title).foregroundStyle(statusWarning ? .red : .primary)
} icon: {
Image(systemName: symbol).frame(width: 16, height: 16).foregroundStyle(statusWarning ? .red : color)
}.font(PanelStyle.title).fixedSize()
if let status {
Text(verbatim: status)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(statusWarning ? .red : color)
.padding(.horizontal, 6).frame(height: 16)
.background((statusWarning ? Color.red : color).opacity(0.14), in: Capsule())
if let warningText {
warningText
.font(.system(size: 10)).foregroundStyle(.red).lineLimit(1)
}
}
if let detail {
Text(verbatim: detail)
.font(.system(size: 10, weight: .medium)).foregroundStyle(detailColor ?? .secondary)
.padding(.horizontal, 6).frame(height: 16)
.background((detailColor ?? .primary).opacity(detailColor == nil ? 0.06 : 0.14), in: Capsule())
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
.help(Text(verbatim: detailHelp ?? detail))
.accessibilityLabel(Text(verbatim: detailHelp ?? detail))
}
Spacer(minLength: 0)
HStack(alignment: .center, spacing: 6) {
MetricText(value: value)
.font(PanelStyle.title)
.foregroundStyle(valueColor ?? color)
ZStack(alignment: .bottomLeading) {
chart()
.frame(width: bounds.size.width, height: ResourceCardMetrics.plotHeight)
VStack(alignment: .leading, spacing: ResourceCardMetrics.gap) {
header
HStack(alignment: .firstTextBaseline, spacing: 12) {
MetricHeadline(value: value, compact: secondaryValue != nil, color: valueColor ?? .primary)
if let secondaryValue {
MetricText(value: secondaryValue).font(PanelStyle.title)
.foregroundStyle(secondaryValueColor ?? color)
MetricHeadline(value: secondaryValue, compact: true, color: secondaryValueColor ?? .primary)
}
}.foregroundStyle(color).lineLimit(1)
}
.frame(height: PanelStyle.titleHeight)
VStack(alignment: .leading, spacing: 4) {
}
.frame(height: ResourceCardMetrics.headlineHeight, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
content()
Spacer(minLength: 0)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.font(PanelStyle.label)
.padding(ResourceCardMetrics.padding)
.padding(.bottom, ResourceCardMetrics.plotHeight - ResourceCardMetrics.padding)
.frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading)
}
.background(Color("PanelCard"))
.clipShape(.rect(cornerRadius: ResourceCardMetrics.radius))
.overlay(RoundedRectangle(cornerRadius: ResourceCardMetrics.radius).strokeBorder(.primary.opacity(0.07)))
.background {
RoundedRectangle(cornerRadius: ResourceCardMetrics.radius)
.fill(Color("PanelCard"))
.shadow(color: .black.opacity(colorScheme == .dark ? 0.16 : 0.06), radius: 6, x: 0, y: 2)
}
.font(PanelStyle.label)
.padding(PanelStyle.padding)
.frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading)
}
.modifier(CardSurface())
.overlayPreferenceValue(ChartTooltipPreference.self) { tooltip in
GeometryReader { proxy in
if let tooltip {
let plot = proxy[tooltip.plot]
ChartTooltipLayer(point: CGPoint(x: plot.minX + tooltip.point.x, y: plot.minY + tooltip.point.y)) {
ChartTooltipLayer(point: CGPoint(x: plot.minX + tooltip.point.x, y: plot.minY + tooltip.point.y),
minimumY: max(ResourceCardMetrics.tooltipMinimumY, plot.minY)) {
tooltip.content.fixedSize(horizontal: false, vertical: true)
}
.frame(width: proxy.size.width, height: proxy.size.height)
@@ -86,4 +69,70 @@ struct ResourceCard<Content: View>: View {
.accessibilityHidden(true)
}
}
private var header: some View {
HStack(spacing: 6) {
Label {
Text(title).foregroundStyle(statusWarning ? .red : .primary)
} icon: {
Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color)
}
.font(.system(size: 14, weight: .semibold)).fixedSize()
Spacer(minLength: 4)
if let status {
Text(verbatim: status)
.font(.system(size: 11, weight: .medium))
.foregroundStyle(statusWarning ? .red : .secondary)
.help(warningText ?? Text(verbatim: status))
.accessibilityLabel(warningText.map { Text("\(status) \($0)") } ?? Text(verbatim: status))
}
if let detail {
Text(verbatim: detail)
.font(.system(size: 10, weight: .medium)).foregroundStyle(detailColor ?? .secondary)
.padding(.horizontal, 6).frame(height: 18)
.background((detailColor ?? .primary).opacity(0.10), in: Capsule())
.lineLimit(1)
.help(Text(verbatim: detailHelp ?? detail))
.accessibilityLabel(Text(verbatim: detailHelp ?? detail))
}
headerAccessory
}
.lineLimit(1)
.frame(height: ResourceCardMetrics.titleHeight)
}
}
/// A preformatted value keeps its unit smaller without changing metric semantics.
private struct MetricHeadline: View {
let value: String
let compact: Bool
let color: Color
private var direction: Character? { value.first.flatMap { $0 == "↓" || $0 == "↑" ? $0 : nil } }
private var parts: [Substring] {
let number = direction == nil ? value : String(value.dropFirst()).trimmingCharacters(in: .whitespaces)
if number.hasSuffix("%") { return [number.dropLast(), "%"] }
return number.split(separator: " ", maxSplits: 1)
}
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: 3) {
if let direction {
Image(systemName: direction == "↓" ? "arrow.down" : "arrow.up")
.font(.system(size: 16, weight: .medium))
}
Text(verbatim: parts.first.map(String.init) ?? value)
.font(.system(size: compact ? 23 : 36, weight: .semibold))
if parts.count > 1 {
Text(verbatim: String(parts[1]))
.font(.system(size: compact ? 11 : 14, weight: .medium))
.foregroundStyle(Color.secondary)
}
}
.monospacedDigit().foregroundStyle(color)
.lineLimit(1).minimumScaleFactor(0.75)
.frame(maxWidth: .infinity, alignment: .leading)
.help(Text(verbatim: value))
.accessibilityElement(children: .ignore)
.accessibilityLabel(Text(verbatim: value))
}
}
@@ -0,0 +1,13 @@
import CoreGraphics
/// Shared geometry for resource foregrounds, background plots and panel budgets.
nonisolated enum ResourceCardMetrics {
static let minimumHeight: CGFloat = 264
static let padding: CGFloat = 16
static let radius: CGFloat = 20
static let plotHeight: CGFloat = 72
static let titleHeight: CGFloat = 20
static let headlineHeight: CGFloat = 44
static let gap: CGFloat = 6
static let tooltipMinimumY: CGFloat = 96
}