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
@@ -8,7 +8,6 @@ struct MemoryDetailsView: View {
var body: some View {
VStack(alignment: .leading, spacing: 3) {
CardSeparator()
CapacityBar(values: values.map { Double($0) }, colors: colors, total: Double(memory.total))
HStack(spacing: 4) {
ForEach(0..<4) { index in
@@ -6,50 +6,51 @@ extension MenuPanelView {
ResourceCard(
title: "metric.network", symbol: "network", color: Color("MetricNetwork"), value: "↓ " + MetricFormat.rate(total(\.download)),
secondaryValue: "↑ " + MetricFormat.rate(total(\.upload)), valueColor: Color("MetricMemory"),
secondaryValueColor: Color("SeriesUpload")
secondaryValueColor: Color("SeriesUpload"), headerAccessory: AnyView(networkInterfacePicker),
chart: {
PanelTrendChart(
dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricMemory"),
secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals, visibleSeriesCount: 2
).id(selectedInterface)
}
) {
PanelTrendChart(
dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricMemory"),
secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals, showsLegendValues: false
).id(selectedInterface)
CardSeparator()
HStack(alignment: .top, spacing: 8) {
HStack(spacing: 12) {
networkTotal(
"network.received", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received }),
symbol: "arrow.down", color: Color("MetricMemory"))
Divider().frame(height: 32)
networkTotal(
"network.sent", value: network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent }),
symbol: "arrow.up", color: Color("SeriesUpload"))
Divider().frame(height: 32)
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 4) {
Circle().fill(networkStatusColor).frame(width: 5, height: 5)
Picker("panel.interface", selection: $selectedInterface) {
Text("network.all").tag("")
ForEach(snapshot.network ?? [], id: \.identity) { item in
Text(verbatim: item.name).tag(item.identity)
}
}.labelsHidden().controlSize(.mini).fixedSize()
}
Text(networkStatusLabel).help(Text(networkStatusLabel))
}.frame(maxWidth: .infinity, alignment: .leading)
}.font(PanelStyle.label).lineLimit(1)
CardSeparator()
HStack(spacing: 8) {
}
VStack(spacing: 4) {
networkAddress("network.public", address: publicIPAddress)
Divider().frame(height: 15)
networkAddress(
"network.local",
address: addressInterface?.addresses.first(where: { !$0.contains(":") }) ?? addressInterface?.addresses.first)
}.font(PanelStyle.label)
.modifier(CardInset())
.accessibilityElement(children: .contain)
.accessibilityLabel(Text("network.addresses"))
}
.font(PanelStyle.label)
.accessibilityElement(children: .contain)
.accessibilityLabel(Text("network.addresses"))
}
.modifier(PanelPublicIPRefresh(metrics: metrics, address: $publicIPAddress))
}
private var networkInterfacePicker: some View {
HStack(spacing: 4) {
Circle().fill(networkStatusColor).frame(width: 5, height: 5)
Picker("panel.interface", selection: $selectedInterface) {
Text("network.all").tag("")
ForEach(snapshot.network ?? [], id: \.identity) { item in
Text(verbatim: item.name).tag(item.identity)
}
}.labelsHidden().controlSize(.mini).frame(maxWidth: 100)
}
.help(Text(networkStatusLabel))
.accessibilityElement(children: .contain)
.accessibilityValue(Text(networkStatusLabel))
}
func networkAddress(_ title: LocalizedStringKey, address: String?) -> some View {
HStack(spacing: 3) {
Text(title).foregroundStyle(.secondary)
@@ -10,6 +10,15 @@ extension MenuPanelView {
}.frame(height: 14)
}
func inlineMetric(_ title: LocalizedStringKey, _ value: String) -> some View {
HStack(spacing: 4) {
Text(title).foregroundStyle(.secondary)
MetricText(value: value).fontWeight(.medium)
}
.font(.system(size: 11)).lineLimit(1).minimumScaleFactor(0.8)
.frame(maxWidth: .infinity, alignment: .leading)
}
func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
@@ -24,15 +33,20 @@ extension MenuPanelView {
value: MetricFormat.percent(snapshot.cpu?.usage),
status: temperature.map { "\(Int($0.rounded()))°C" },
statusWarning: highTemperature,
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil,
chart: {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.cpu),
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval,
boundaryDates: chartBoundaries, intervals: chartIntervals)
}
) {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.cpu),
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval,
boundaryDates: chartBoundaries, intervals: chartIntervals)
CardSeparator()
HStack(spacing: 12) {
inlineMetric("cpu.user", MetricFormat.percent(snapshot.cpu?.user))
inlineMetric("cpu.system", MetricFormat.percent(snapshot.cpu?.system))
}.frame(height: 14)
if let cpu = snapshot.cpu {
CPUCoreGrid(
values: cpu.cores, kinds: CPUCoreTopology.cores,
@@ -48,17 +62,22 @@ extension MenuPanelView {
return ResourceCard(
title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage),
status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" },
detail: snapshot.gpu?.coreCount.map { String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), $0) }
detail: snapshot.gpu?.coreCount.map { String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), $0) },
chart: {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.gpu),
second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler),
color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
}
) {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.gpu),
second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler),
color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
HStack(spacing: 12) {
inlineMetric("gpu.renderer", MetricFormat.percent(snapshot.gpu?.renderer))
inlineMetric("gpu.tiler", MetricFormat.percent(snapshot.gpu?.tiler))
}.frame(height: 14)
let fans = displayedFans
if !fans.isEmpty {
CardSeparator()
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 10), count: min(2, fans.count)), spacing: 4) {
ForEach(fans) { fan in
FanSpeedIndicator(
@@ -68,12 +87,9 @@ extension MenuPanelView {
.frame(height: 16)
}
}
.modifier(CardInset())
} else if snapshot.fans == nil {
CardSeparator()
Text("metric.waiting").font(PanelStyle.label)
.frame(maxWidth: .infinity, alignment: .leading).frame(height: 16)
.modifier(CardInset())
}
}
}
@@ -86,22 +102,22 @@ extension MenuPanelView {
String(format: "%.1f / %.0f GiB", Double($0.used) / 1_073_741_824, Double($0.total) / 1_073_741_824)
} ?? "--",
status: snapshot.memory.map { MetricFormat.percent($0.usage) },
detail: header.title, detailColor: header.color, detailHelp: header.help
detail: header.title, detailColor: header.color, detailHelp: header.help,
chart: {
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } },
second: samples.map(\.memoryApp), third: samples.map(\.memoryWired), fourth: samples.map(\.memoryCompressed),
color: Color("MemoryApplication"), secondColor: Color("MemoryApplication"),
thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1),
firstValueFormat: .memory, firstLabel: "gpu.totalUtilization",
secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
}
) {
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } },
second: samples.map(\.memoryApp), third: samples.map(\.memoryWired), fourth: samples.map(\.memoryCompressed),
color: Color("MetricCPU"), secondColor: Color("MemoryApplication"),
thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1),
scaleLabel: MetricFormat.memory(snapshot.memory?.total), firstValueFormat: .memory, firstLabel: "gpu.totalUtilization",
secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals,
showsLegendValues: cardContentWidth >= 340)
if let memory = snapshot.memory {
MemoryDetailsView(memory: memory)
} else {
CardSeparator()
Text("metric.waiting").foregroundStyle(.secondary)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
@@ -114,15 +130,19 @@ extension MenuPanelView {
String(
format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 1_000_000_000,
Double($0.total) / 1_000_000_000)
} ?? "--"
} ?? "--",
chart: {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"),
secondColor: Color("MetricNetwork"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, visibleSeriesCount: 2
)
}
) {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"),
secondColor: Color("MetricNetwork"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals
)
HStack(spacing: 12) {
inlineMetric("disk.read", MetricFormat.rate(snapshot.diskIO?.read))
inlineMetric("disk.write", MetricFormat.rate(snapshot.diskIO?.written))
}.frame(height: 14)
StorageDetailsView(disk: snapshot.disk, health: snapshot.diskHealth) {
showVolumes.toggle()
}
@@ -150,24 +170,27 @@ extension MenuPanelView {
var batteryCard: some View {
ResourceCard(
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
value: MetricFormat.percent(snapshot.battery?.charge)
value: MetricFormat.percent(snapshot.battery?.charge),
chart: {
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map(\.battery),
second: samples.map(\.batteryPower),
color: Color("MetricBattery"),
secondColor: Color("SeriesUser"),
fixedScale: 1,
secondSeriesUsesAutonomousScale: true,
secondValueFormat: .watts,
firstLabel: "metric.battery",
secondLabel: snapshot.battery.map(batteryPowerLabel) ?? "battery.power",
expectedInterval: chartInterval,
boundaryDates: chartBoundaries,
intervals: chartIntervals
)
}
) {
PanelTrendChart(
dates: samples.map(\.date),
first: samples.map(\.battery),
second: samples.map(\.batteryPower),
color: Color("MetricBattery"),
secondColor: Color("SeriesUser"),
fixedScale: 1,
secondSeriesUsesAutonomousScale: true,
secondValueFormat: .watts,
firstLabel: "metric.battery",
secondLabel: snapshot.battery.map(batteryPowerLabel) ?? "battery.power",
expectedInterval: chartInterval,
boundaryDates: chartBoundaries,
intervals: chartIntervals
)
CardSeparator()
inlineMetric(snapshot.battery.map(batteryPowerLabel) ?? "battery.power", MetricFormat.watts(snapshot.battery?.power))
.frame(height: 14)
if let battery = snapshot.battery {
batteryDetails(battery)
} else {
+1 -1
View File
@@ -29,7 +29,7 @@ struct MenuPanelView: View {
let missingIDs = (0..<reservedFanCount).filter { id in !fans.contains { $0.id == id } }
return (fans + missingIDs.prefix(reservedFanCount - fans.count).map { FanMetrics(id: $0, rpm: nil) }).sorted { $0.id < $1.id }
}
var cardContentWidth: CGFloat { max(0, (measuredCardWidth ?? PanelLayout.cardWidth(size: panelSize)) - 20) }
var cardContentWidth: CGFloat { max(0, (measuredCardWidth ?? PanelLayout.cardWidth(size: panelSize)) - ResourceCardMetrics.padding * 2) }
var columns: Int { PanelLayout.columns(width: panelSize.width) }
private var cardHeights: [PanelCard: CGFloat] {
let coreCount = max(CPUCoreTopology.cores.count, ProcessInfo.processInfo.processorCount, snapshot.cpu?.cores.count ?? 0)
+5 -4
View File
@@ -25,12 +25,13 @@ nonisolated enum PanelLayout {
}
}
/// Fixed content rows with a 48pt plot. Nil fans reserve a discovery row.
/// Foreground details and the edge-to-edge background trend have separate budgets.
static func cardHeights(coreRows: Int, fanCount: Int?) -> [PanelCard: CGFloat] {
let base = ResourceCardMetrics.minimumHeight
let fanRows = fanCount.map { (max(0, $0) + 1) / 2 } ?? 1
return [.cpu: 152 + CGFloat(max(1, coreRows)) * 26,
.gpu: fanRows == 0 ? 124 : 144 + CGFloat(fanRows) * 20,
.memory: 180, .battery: 170, .storage: 170, .network: 208]
return [.cpu: base + CGFloat(max(0, coreRows - 2)) * 26,
.gpu: base + CGFloat(max(0, fanRows - 1)) * 20,
.memory: base, .battery: base, .storage: base, .network: base]
}
static func rowHeights(columns: Int, heights: [PanelCard: CGFloat]) -> [CGFloat] {
@@ -46,6 +46,10 @@ import AppKit
}
}
mark("interactive")
if ProcessInfo.processInfo.environment["KYMO_AUDIT_CAPTURE"] == "1" {
await wait(10)
mark("open1.10")
}
return
}
let quick = ProcessInfo.processInfo.environment["KYMO_AUDIT_QUICK"] == "1"
@@ -7,7 +7,6 @@ struct StorageDetailsView: View {
var body: some View {
VStack(alignment: .leading, spacing: 4) {
CardSeparator()
HStack(spacing: 8) {
VStack(spacing: 4) {
field("memory.available", value: MetricFormat.bytes(disk?.available))
+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
}