feat(panel): 调整资源卡片读数布局并保留趋势平移

逐核显示 CPU 占用,在 GPU 标题展示核数并补充分项读数。无电池设备显示整机功率。

存储与网络将曲线排在详情下方,CPU、GPU、内存和电池保留整卡趋势。数值直接刷新,曲线随采样平滑平移。顶栏展示版本号,底栏调整开机时间和刷新间隔。
This commit is contained in:
2026-11-15 22:03:46 +08:00
parent c886c4227d
commit 6300db3d15
27 changed files with 427 additions and 250 deletions
@@ -33,6 +33,8 @@ nonisolated enum SamplingDiagnostics {
payload["cores"] = snapshot.cpu?.cores.count
payload["cpuTemperature"] = snapshot.cpuTemperature
payload["gpuUsage"] = snapshot.gpuUsage
payload["gpuRenderer"] = snapshot.gpu?.renderer
payload["gpuTiler"] = snapshot.gpu?.tiler
payload["gpuCoreCount"] = snapshot.gpu?.coreCount
payload["processEnumerated"] = snapshot.processes?.enumerated
payload["processReadable"] = snapshot.processes?.readable
@@ -50,6 +52,7 @@ nonisolated enum SamplingDiagnostics {
payload["volumeCount"] = snapshot.volumes?.count
payload["batteryCycles"] = snapshot.battery?.cycles
payload["batteryHealth"] = snapshot.battery?.health
payload["systemPower"] = snapshot.systemPower
payload["batteryPower"] = snapshot.battery?.power
var info = task_vm_info_data_t()
var count = mach_msg_type_number_t(MemoryLayout<task_vm_info_data_t>.size / MemoryLayout<integer_t>.size)
+10 -5
View File
@@ -1,6 +1,6 @@
import SwiftUI
/// Core-kind columns contain one vertical segmented meter per real core.
/// Core-kind columns contain one continuously filled cell per real core.
struct CPUCoreGrid: View {
let values: [Double]
let kinds: [Int: CPUCoreTopology.Kind]
@@ -85,8 +85,13 @@ struct CPUCoreGrid: View {
private func core(index: Int) -> some View {
let kind = kinds[index]
let measured = values[index].isFinite ? values[index] : nil
return SegmentedCoreBar(value: measured, color: color(kind))
.frame(height: 30)
return RoundedRectangle(cornerRadius: 2)
.fill(color(kind).opacity(0.22))
.overlay(alignment: .bottom) {
Rectangle().fill(color(kind)).frame(height: CPUCoreGridLayout.rowHeight * (measured.map { min(1, max(0, $0)) } ?? 0))
}
.clipShape(.rect(cornerRadius: 2))
.frame(height: CPUCoreGridLayout.rowHeight)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.help(Text("\(kind.map { label($0) } ?? Text("cpu.core")) · \(index + 1): \(MetricFormat.percent(measured))"))
.accessibilityElement(children: .ignore)
@@ -98,8 +103,8 @@ struct CPUCoreGrid: View {
struct CPUCoreGridLayout: Layout {
static let columnSpacing: CGFloat = 3
static let rowSpacing: CGFloat = 4
static let rowHeight: CGFloat = 30
static let minimumCellWidth: CGFloat = 6
static let rowHeight: CGFloat = 11
static let minimumCellWidth: CGFloat = 7
static func rowCounts(count: Int, width: CGFloat) -> [Int] {
guard count > 0 else { return [] }
@@ -10,20 +10,6 @@ extension MenuPanelView {
}.frame(height: 16)
}
func inlineMetric(_ title: LocalizedStringKey, _ value: String) -> some View {
HStack(spacing: 4) {
Text(title).foregroundStyle(.secondary)
MetricText(value: value).fontWeight(.medium)
}
.font(.system(size: 10)).lineLimit(1)
}
func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
return "battery.power"
}
var cpuCard: some View {
let temperature = snapshot.cpuTemperature
let highTemperature = CPUTemperatureMonitor.isHighTemperature(temperature)
@@ -33,6 +19,7 @@ extension MenuPanelView {
status: temperature.map { "\(Int($0.rounded()))°C" },
statusWarning: highTemperature,
warningText: highTemperature ? Text("cpu.temperature.high", tableName: "CPUDetails") : nil,
chartPlacement: .background,
chart: {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.cpu),
@@ -43,8 +30,8 @@ extension MenuPanelView {
}
) {
HStack(spacing: 5) {
inlineMetric("cpu.user", MetricFormat.percent(snapshot.cpu?.user))
inlineMetric("cpu.system", MetricFormat.percent(snapshot.cpu?.system))
InlineMetric("cpu.user", MetricFormat.percent(snapshot.cpu?.user))
InlineMetric("cpu.system", MetricFormat.percent(snapshot.cpu?.system))
}.frame(height: 16)
if let cpu = snapshot.cpu {
CPUCoreGrid(
@@ -60,24 +47,26 @@ extension MenuPanelView {
var gpuCard: some View {
return ResourceCard(
title: "metric.gpu", symbol: "square.grid.2x2", color: Color("MetricGPU"), value: MetricFormat.percent(snapshot.gpuUsage),
titleBadge: snapshot.gpu?.coreCount.map {
String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), $0)
},
status: snapshot.gpuTemperature.map { "\(Int($0.rounded()))°C" },
chartPlacement: .background,
chart: {
PanelTrendChart(
dates: samples.map(\.date), first: samples.map(\.gpu),
second: samples.map { $0.gpu.map { max(0, 1 - $0) } },
third: samples.map(\.gpuRenderer), fourth: samples.map(\.gpuTiler),
color: Color("MetricGPU"), secondColor: Color("MemoryAvailable"),
thirdColor: Color("MetricCPU"), fourthColor: Color("SeriesSystem"),
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.idle", thirdLabel: "gpu.renderer", fourthLabel: "gpu.tiler",
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [0, 1])
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,
visibleSeriesCount: 3, filledSeriesCount: 1)
}
) {
HStack(spacing: 5) {
if let count = snapshot.gpu?.coreCount {
Text(verbatim: String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), count))
.foregroundStyle(.primary)
}
}.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9).frame(height: 16)
HStack(spacing: 8) {
gpuStage("gpu.renderer", snapshot.gpu?.renderer, Color("MetricCPU"))
gpuStage("gpu.tiler", snapshot.gpu?.tiler, Color("SeriesSystem"))
}.frame(height: 16)
let fans = displayedFans
if !fans.isEmpty {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 5, alignment: .leading), count: min(2, fans.count)), spacing: 2) {
@@ -97,6 +86,13 @@ extension MenuPanelView {
}
}
private func gpuStage(_ title: LocalizedStringKey, _ usage: Double?, _ tint: Color) -> some View {
HStack(spacing: 3) {
Circle().fill(tint).frame(width: 4, height: 4)
InlineMetric(title, MetricFormat.percent(usage))
}
}
var memoryCard: some View {
let header = MemoryHeaderInfo(memory: snapshot.memory, locale: locale)
return ResourceCard(
@@ -106,6 +102,7 @@ extension MenuPanelView {
} ?? "--",
detail: header.badgeTitle, detailColor: snapshot.memory?.pressure == 1 ? Color("MetricBattery") : header.color,
detailHelp: header.help + "\n" + MetricFormat.percent(snapshot.memory?.usage),
chartPlacement: .background,
chart: {
PanelTrendChart(
dates: samples.map(\.date),
@@ -168,55 +165,7 @@ extension MenuPanelView {
}
}
var batteryCard: some View {
ResourceCard(
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
value: MetricFormat.percent(snapshot.battery?.charge),
status: snapshot.battery.map { AppLocalization.string($0.externalPower ? "battery.acPower" : "battery.batterySource", locale: locale) },
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
)
}
) {
inlineMetric("battery.powerShort", MetricFormat.watts(snapshot.battery?.power))
.frame(height: 16)
if let battery = snapshot.battery {
batteryDetails(battery)
} else {
Text(snapshot.batteryState == .absent ? "panel.noBattery" : "panel.batteryFailed").foregroundStyle(.secondary)
.font(.system(size: 10)).frame(maxWidth: .infinity).frame(height: 32)
}
}
}
private func batteryDetails(_ battery: BatteryMetrics) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 8) {
inlineMetric("battery.healthShort", MetricFormat.percent(battery.health))
inlineMetric("battery.cyclesShort", battery.cycles.map(String.init) ?? "--")
}
HStack(spacing: 4) {
Text("battery.timeShort").foregroundStyle(.secondary)
if battery.externalPower {
Text("battery.notApplicableShort").help(Text("battery.timeNotApplicable"))
} else if let minutes = battery.minutesRemaining {
MetricText(value: "\(minutes) min")
} else {
Text("battery.timeUnknown")
}
}
}
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9)
PowerResourceCard(snapshot: snapshot, samples: samples, chartInterval: chartInterval,
chartBoundaries: chartBoundaries, chartIntervals: chartIntervals)
}
}
+20 -7
View File
@@ -81,7 +81,8 @@ struct MenuPanelView: View {
}
.background(Color("PanelBackground"), in: .rect(cornerRadius: 18))
.clipShape(.rect(cornerRadius: 18))
.transaction { $0.animation = nil; $0.disablesAnimations = true }
.transaction { $0.animation = nil }
.environment(\.panelMotionActive, metrics.isPanelVisible && !metrics.isPaused && !metrics.isSystemSleeping && !metrics.isDisplaySleeping)
.modifier(AppearanceStyle(preferences: preferences))
}
@@ -127,11 +128,23 @@ struct MenuPanelView: View {
}
}
private static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
private var brand: some View {
HStack(spacing: 6) {
Image("BrandMark").renderingMode(.template).resizable().scaledToFit()
.frame(width: 22, height: 22)
Text("Kymo").font(.system(size: 17, weight: .semibold))
HStack(alignment: .top, spacing: 3) {
Text("Kymo").font(.system(size: 17, weight: .semibold))
if let version = Self.version {
Text(verbatim: "v" + version)
.font(.system(size: 9, weight: .semibold)).monospacedDigit()
.padding(.horizontal, 5).padding(.vertical, 1)
.background(.primary.opacity(0.09), in: Capsule())
.offset(y: -2)
.accessibilityLabel(Text("about.version \(version)"))
}
}.fixedSize()
}
}
@@ -147,18 +160,18 @@ struct MenuPanelView: View {
private var footer: some View {
HStack {
Text(verbatim: HardwareIdentity.displayName)
.lineLimit(1).truncationMode(.middle)
.help(Text(verbatim: HardwareIdentity.displayName))
Spacer(minLength: 8)
HStack(spacing: 4) {
Text("panel.uptime")
MetricText(value: String(format: "%.1f h", snapshot.uptime / 3600))
}.fixedSize()
Divider().frame(height: 14)
Text(verbatim: HardwareIdentity.displayName)
.lineLimit(1).truncationMode(.middle)
.help(Text(verbatim: HardwareIdentity.displayName))
Spacer(minLength: 8)
HStack(spacing: 4) {
Image(systemName: "timer").help(Text("sampling.panel"))
IntervalControl(milliseconds: Binding(get: { metrics.sampling.panelMilliseconds }, set: { metrics.sampling.panelMilliseconds = $0 }))
IntervalControl(milliseconds: Binding(get: { metrics.sampling.panelMilliseconds }, set: { metrics.sampling.panelMilliseconds = $0 }), fieldWidth: 50)
}
.foregroundStyle(.primary)
.accessibilityLabel(Text("sampling.panel"))
+3 -3
View File
@@ -25,12 +25,12 @@ nonisolated enum PanelLayout {
}
}
/// Structural foreground height determines the full-height background chart.
/// Structural foreground height determines the room available for the trend below the text.
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: base + CGFloat(max(0, coreRows - 1)) * 34,
.gpu: base + CGFloat(max(0, fanRows - 1)) * 14,
return [.cpu: base + CGFloat(max(0, coreRows - 1)) * 15,
.gpu: base + CGFloat(max(0, fanRows - 1)) * 18,
.memory: base, .battery: base, .storage: base, .network: base]
}
@@ -0,0 +1,87 @@
import SwiftUI
struct PowerResourceCard: View {
let snapshot: MetricsSnapshot
let samples: [TrendSample]
let chartInterval: TimeInterval
let chartBoundaries: Set<Date>
let chartIntervals: [TimeInterval]
@Environment(\.locale) private var locale
private func batteryPowerLabel(_ battery: BatteryMetrics) -> LocalizedStringKey {
if battery.charging { return "battery.chargePower" }
if !battery.externalPower { return "battery.dischargePower" }
return "battery.power"
}
@ViewBuilder var body: some View {
if snapshot.batteryState == .absent {
ResourceCard(title: "power.system", symbol: "bolt.fill", color: Color("MetricBattery"),
value: MetricFormat.watts(snapshot.systemPower), chart: {
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.systemPower),
color: Color("MetricBattery"), fixedScale: nil, firstValueFormat: .watts,
firstLabel: "power.system", expectedInterval: chartInterval,
boundaryDates: chartBoundaries, intervals: chartIntervals)
}) {
Text(snapshot.systemPower == nil ? "power.sensorUnavailable" : "panel.noBattery")
.font(.system(size: 10)).foregroundStyle(.secondary)
}
} else {
batteryChargeCard
}
}
private var batteryChargeCard: some View {
ResourceCard(
title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"),
value: MetricFormat.percent(snapshot.battery?.charge),
status: snapshot.battery.map { AppLocalization.string($0.externalPower ? "battery.acPower" : "battery.batterySource", locale: locale) },
chartPlacement: .background,
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
)
}
) {
InlineMetric("battery.powerShort", MetricFormat.watts(snapshot.battery?.power))
.frame(height: 16)
if let battery = snapshot.battery {
batteryDetails(battery)
} else {
Text(snapshot.batteryState == .unknown ? "metric.waiting" : "panel.batteryFailed").foregroundStyle(.secondary)
.font(.system(size: 10)).frame(maxWidth: .infinity).frame(height: 32)
}
}
}
private func batteryDetails(_ battery: BatteryMetrics) -> some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 8) {
InlineMetric("battery.healthShort", MetricFormat.percent(battery.health))
InlineMetric("battery.cyclesShort", battery.cycles.map(String.init) ?? "--")
}
HStack(spacing: 4) {
Text("battery.timeShort").foregroundStyle(.secondary)
if battery.externalPower {
Text("battery.notApplicableShort").help(Text("battery.timeNotApplicable"))
} else if let minutes = battery.minutesRemaining {
MetricText(value: "\(minutes) min")
} else {
Text("battery.timeUnknown")
}
}
}
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.9)
}
}
@@ -6,11 +6,11 @@ struct StorageDetailsView: View {
let io: DiskIOMetrics?
var body: some View {
VStack(alignment: .leading, spacing: 4) {
VStack(alignment: .leading, spacing: 3) {
field("memory.available", value: MetricFormat.bytes(disk?.available))
ViewThatFits(in: .horizontal) {
HStack(spacing: 6) { read; write }.fixedSize(horizontal: true, vertical: true)
VStack(alignment: .leading, spacing: 4) { read; write }
VStack(alignment: .leading, spacing: 3) { read; write }
}
ViewThatFits(in: .horizontal) {
HStack(spacing: 4) {
@@ -18,7 +18,7 @@ struct StorageDetailsView: View {
Text("·").foregroundStyle(.secondary)
powerOn
}.fixedSize(horizontal: true, vertical: true)
VStack(alignment: .leading, spacing: 4) { life; powerOn }
VStack(alignment: .leading, spacing: 3) { life; powerOn }
}
}
.font(.system(size: 10)).lineLimit(1)
@@ -33,6 +33,6 @@ struct StorageDetailsView: View {
HStack(spacing: 3) {
Text(title).foregroundStyle(.secondary).help(Text(title))
MetricText(value: value).fontWeight(.medium).foregroundStyle(.primary)
}.frame(height: 16)
}.frame(height: 14)
}
}
+47 -25
View File
@@ -1,6 +1,50 @@
{
"sourceLanguage" : "en",
"strings" : {
"power.system": {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "System power"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "整机功率"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "整機功率"
}
}
}
},
"power.sensorUnavailable": {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Power sensor unavailable"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "功率传感器不可用"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "功率感測器無法使用"
}
}
}
},
"memory.distributionHelp" : {
"localizations": {
"en": {
@@ -23,28 +67,6 @@
}
}
},
"gpu.idle" : {
"localizations": {
"en": {
"stringUnit": {
"state": "translated",
"value": "Idle"
}
},
"zh-Hans": {
"stringUnit": {
"state": "translated",
"value": "空闲"
}
},
"zh-Hant": {
"stringUnit": {
"state": "translated",
"value": "閒置"
}
}
}
},
"disk.lifeShort" : {
"localizations": {
"en": {
@@ -2953,19 +2975,19 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "Uptime"
"value" : "System uptime"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "运行时间"
"value" : "开机时间"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "執行時間"
"value" : "開機時間"
}
}
}
+35 -4
View File
@@ -15,7 +15,7 @@ nonisolated enum PanelCurveProjection: Equatable {
}
}
/// Bounded static lines and per-run area paths. Hover never rebuilds geometry.
/// Bounded lines and per-run area paths. Hover never rebuilds geometry.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
let colors: [Color]
@@ -26,6 +26,7 @@ struct NativePanelCurve: NSViewRepresentable {
var filledSeriesCount = 1
var stacked = false
var projection: PanelCurveProjection = .fullHeight
var animates = false
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
@@ -34,7 +35,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, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked, projection: projection))
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked, projection: projection, animates: animates))
}
struct Input: Equatable {
let frame: PanelCurveFrame
@@ -46,6 +47,7 @@ struct NativePanelCurve: NSViewRepresentable {
var filledSeriesCount = 1
var stacked = false
var projection: PanelCurveProjection = .fullHeight
var animates = false
}
final class PlotView: NSView {
private(set) var input: Input?
@@ -57,6 +59,8 @@ struct NativePanelCurve: NSViewRepresentable {
private var hoverDots: [CAShapeLayer] = []
private var seriesLayers: [SeriesLayer] = []
private var palette: [NSColor] = []
private var drawingFrame: PanelCurveFrame?
private static let slideKey = "trend.slide"
private var plottedBands: [StackedSeries.Band] = []
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
@@ -79,7 +83,15 @@ struct NativePanelCurve: NSViewRepresentable {
guard input != value else { return }
let old = input
let frameChanged = old?.frame != value.frame
let slides = value.animates && value.hoveredIndex == nil && window?.isVisible == true
&& frameChanged && old.map { value.frame.follows($0.frame, maximumGap: value.maximumGap) } == true
input = value
if frameChanged || !value.animates || value.hoveredIndex != nil {
curves.removeAnimation(forKey: Self.slideKey)
}
if frameChanged {
drawingFrame = slides ? old.map { value.frame.includingOutgoing(from: $0.frame) } : nil
}
CATransaction.begin(); CATransaction.setDisableActions(true)
if old?.projection != value.projection { updateBaseline() }
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
@@ -93,8 +105,24 @@ struct NativePanelCurve: NSViewRepresentable {
rebuildPaths()
}
updateHover()
if slides, let old { slide(from: old.frame, to: value.frame) }
CATransaction.commit()
}
private func slide(from previous: PanelCurveFrame, to next: PanelCurveFrame) {
guard bounds.width > 0, let a = previous.dates.first, let b = previous.dates.last,
let c = next.dates.first, let d = next.dates.last else { return }
// Map the new geometry onto the old time domain, then reveal the new point.
let span = b.timeIntervalSince(a)
let transform = CGAffineTransform(a: d.timeIntervalSince(c) / span, b: 0, c: 0, d: 1,
tx: c.timeIntervalSince(a) / span * bounds.width, ty: 0)
let animation = CABasicAnimation(keyPath: "transform")
animation.fromValue = NSValue(caTransform3D: CATransform3DMakeAffineTransform(transform))
animation.toValue = NSValue(caTransform3D: CATransform3DIdentity)
animation.duration = 0.35
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
curves.add(animation, forKey: Self.slideKey)
}
private func ensureLayers(_ count: Int) {
while seriesLayers.count < count {
let series = SeriesLayer(); seriesLayers.append(series); curves.addSublayer(series.root)
@@ -153,7 +181,7 @@ struct NativePanelCurve: NSViewRepresentable {
return
}
let domain = PanelCurveFrame.domain(begin: first, end: last)
let frame = input.frame
let frame = drawingFrame ?? input.frame
plottedBands = input.stacked ? StackedSeries.bands(frame.series, count: frame.dates.count, limit: input.scales.first) : []
for index in frame.series.indices {
let series = seriesLayers[index]
@@ -205,7 +233,8 @@ struct NativePanelCurve: NSViewRepresentable {
for series in input.frame.series.indices {
guard series < (input.visibleSeriesCount ?? input.frame.series.count) else { continue }
let values = input.stacked && plottedBands.indices.contains(series) ? plottedBands[series].upper : input.frame.series[series]
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
let plottedIndex = index + (input.stacked ? (drawingFrame?.dates.count ?? input.frame.dates.count) - input.frame.dates.count : 0)
guard values.indices.contains(plottedIndex), let value = values[plottedIndex], value.isFinite else { continue }
let scale = input.scales[input.stacked ? 0 : min(series, input.scales.count - 1)]
let y = input.projection.y(value: value, scale: scale, series: series, height: bounds.height)
hoverDots[series].path = CGPath(ellipseIn: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5), transform: nil)
@@ -215,12 +244,14 @@ struct NativePanelCurve: NSViewRepresentable {
let changed = frame.size != size
super.setFrameSize(size)
if changed {
curves.removeAnimation(forKey: Self.slideKey)
CATransaction.begin(); CATransaction.setDisableActions(true)
updateGrid(); rebuildPaths(); updateHover(); CATransaction.commit()
}
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { curves.removeAnimation(forKey: Self.slideKey) }
CATransaction.begin(); CATransaction.setDisableActions(true)
updatePalette(); CATransaction.commit()
}
+18 -1
View File
@@ -1,12 +1,29 @@
import Foundation
/// A static render frame follows the bounded sampling history without outgoing points.
/// History remains bounded; a rolling plot can draw one outgoing vertex beyond its left edge.
nonisolated struct PanelCurveFrame: Equatable {
let dates: [Date]
let series: [[Double?]]
let intervals: [TimeInterval]
let boundaryDates: Set<Date>
/// Only adjacent samples from the same timeline can slide into view.
func follows(_ old: Self, maximumGap: TimeInterval) -> Bool {
guard old.dates.count >= 2, let before = old.dates.last, let end = dates.last,
let begin = old.dates.first, begin < before, end > before, !boundaryDates.contains(end),
end.timeIntervalSince(before) <= PanelCurveGeometry.allowedGap(at: dates.count - 1, intervals: intervals, fallback: maximumGap)
else { return false }
return dates.dropLast().elementsEqual(old.dates)
|| (dates.count == old.dates.count && dates.dropLast().elementsEqual(old.dates.dropFirst()))
}
func includingOutgoing(from old: Self) -> Self {
guard dates.first != old.dates.first, let outgoing = old.dates.first else { return self }
return Self(dates: [outgoing] + dates, series: series.enumerated().map { index, values in
[old.series.indices.contains(index) ? old.series[index].first ?? nil : nil] + values
}, intervals: [old.intervals.first ?? 2] + intervals, boundaryDates: boundaryDates)
}
struct Domain {
let begin: TimeInterval
let end: TimeInterval
+6 -2
View File
@@ -8,7 +8,7 @@ enum TrendValueFormat {
case watts
}
/// Static curves skip missing vertices, retaining timestamps and explicit sampling breaks.
/// Curves skip missing vertices, retaining timestamps and explicit sampling breaks.
struct PanelTrendChart: View {
let dates: [Date]
let first: [Double?]
@@ -31,8 +31,11 @@ struct PanelTrendChart: View {
var boundaryDates: Set<Date> = []
var intervals: [TimeInterval] = []
var visibleSeriesCount = 1
var filledSeriesCount: Int? = nil
var stackOrder: [Int] = []
var projection: PanelCurveProjection = .fullHeight
@Environment(\.panelMotionActive) private var active
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var retainedSecondScale: Double = 1
@@ -115,7 +118,8 @@ struct PanelTrendChart: View {
scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale],
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
visibleSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count,
filledSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count, stacked: !stackOrder.isEmpty, projection: projection)
filledSeriesCount: stackOrder.isEmpty ? (filledSeriesCount ?? visibleSeriesCount) : stackOrder.count, stacked: !stackOrder.isEmpty, projection: projection,
animates: active && !reduceMotion)
.contentShape(Rectangle())
.onContinuousHover { phase in
switch phase {
+2 -1
View File
@@ -5,6 +5,7 @@ struct IntervalControl: View {
@Binding var milliseconds: Int
var range: ClosedRange<Int> = 500...1_800_000
var step = 100
var fieldWidth: CGFloat = 64
@State private var text = ""
@FocusState private var focused: Bool
@@ -13,7 +14,7 @@ struct IntervalControl: View {
TextField("sampling.seconds", text: $text)
.labelsHidden()
.textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing)
.frame(width: 64).focused($focused)
.frame(width: fieldWidth).focused($focused)
.onChange(of: text) { _, value in
if let seconds = Double(value.replacingOccurrences(of: ",", with: ".")), seconds.isFinite,
seconds >= Double(range.lowerBound) / 1000, seconds <= Double(range.upperBound) / 1000 {
+22 -2
View File
@@ -1,9 +1,15 @@
import SwiftUI
/// Metrics change only when a new sample is published; no numeric transition or spring.
extension EnvironmentValues {
@Entry var panelMotionActive: Bool = true
}
struct MetricText: View {
let value: String
var body: some View { Text(verbatim: value).monospacedDigit() }
var body: some View {
Text(verbatim: value).monospacedDigit()
}
}
struct PanelCardBackground: ViewModifier {
@@ -13,3 +19,17 @@ struct PanelCardBackground: ViewModifier {
content.background(RoundedRectangle(cornerRadius: radius).fill(Color("PanelCard")))
}
}
struct InlineMetric: View {
let title: LocalizedStringKey
let value: String
init(_ title: LocalizedStringKey, _ value: String) { self.title = title; self.value = value }
var body: some View {
HStack(spacing: 4) {
Text(title).foregroundStyle(.secondary)
MetricText(value: value).fontWeight(.medium)
}
.font(.system(size: 10)).lineLimit(1)
}
}
+30 -13
View File
@@ -1,6 +1,11 @@
import SwiftUI
/// One fixed-size native host owns foreground, background trend and hover presentation.
enum CardChartPlacement {
case background
case belowDetails
}
/// One native host owns the text, chart and hover presentation.
struct ResourceCard<Chart: View, Content: View>: View {
let title: LocalizedStringKey
let symbol: String
@@ -9,6 +14,7 @@ struct ResourceCard<Chart: View, Content: View>: View {
var secondaryValue: String? = nil
var valueColor: Color? = nil
var secondaryValueColor: Color? = nil
var titleBadge: String? = nil
var status: String? = nil
var statusWarning = false
var warningText: Text? = nil
@@ -16,6 +22,7 @@ struct ResourceCard<Chart: View, Content: View>: View {
var detailColor: Color? = nil
var detailHelp: String? = nil
var headerAccessory: AnyView? = nil
var chartPlacement: CardChartPlacement = .belowDetails
@ViewBuilder var chart: () -> Chart
@ViewBuilder var content: () -> Content
@Environment(\.colorScheme) private var colorScheme
@@ -24,15 +31,17 @@ struct ResourceCard<Chart: View, Content: View>: View {
private var cardBody: some View {
GeometryReader { bounds in
ZStack(alignment: .bottomLeading) {
chart()
.frame(width: bounds.size.width, height: bounds.size.height)
VStack(alignment: .leading, spacing: 0) {
foreground
Spacer(minLength: 0)
VStack(alignment: .leading, spacing: ResourceCardMetrics.gap) {
foreground
.padding(.horizontal, ResourceCardMetrics.padding)
.padding(.top, ResourceCardMetrics.padding)
if chartPlacement == .belowDetails {
chart().frame(maxWidth: .infinity, maxHeight: .infinity).clipped()
}
.padding(ResourceCardMetrics.padding)
.frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading)
}
.frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading)
.background {
if chartPlacement == .background { chart() }
}
.background(Color("PanelCard"))
.clipShape(.rect(cornerRadius: ResourceCardMetrics.radius))
@@ -48,7 +57,7 @@ struct ResourceCard<Chart: View, Content: View>: View {
if let tooltip {
let plot = proxy[tooltip.plot]
ChartTooltipLayer(point: CGPoint(x: plot.minX + tooltip.point.x, y: plot.minY + tooltip.point.y),
minimumY: max(ResourceCardMetrics.tooltipMinimumY, plot.minY)) {
minimumY: ResourceCardMetrics.tooltipMinimumY) {
tooltip.content.fixedSize(horizontal: false, vertical: true)
}
.frame(width: proxy.size.width, height: proxy.size.height)
@@ -84,9 +93,17 @@ struct ResourceCard<Chart: View, Content: View>: View {
Image(systemName: symbol).foregroundStyle(statusWarning ? .red : color)
}
.font(.system(size: 11, weight: .semibold)).fixedSize()
if let titleBadge {
Text(verbatim: titleBadge)
.font(.system(size: 9, weight: .semibold)).monospacedDigit()
.foregroundStyle(.secondary)
.padding(.horizontal, 5).frame(height: 14)
.background(.primary.opacity(0.08), in: Capsule())
.fixedSize()
}
Spacer(minLength: 4)
if let status {
Text(verbatim: status)
MetricText(value: status)
.font(.system(size: 10, weight: .medium))
.foregroundStyle(statusWarning ? .red : .secondary)
.help(warningText ?? Text(verbatim: status))
@@ -126,10 +143,10 @@ private struct MetricHeadline: View {
Image(systemName: direction == "↓" ? "arrow.down" : "arrow.up")
.font(.system(size: 12, weight: .medium)).foregroundStyle(color)
}
Text(verbatim: parts.first.map(String.init) ?? value)
MetricText(value: parts.first.map(String.init) ?? value)
.font(.system(size: compact ? 16 : 28, weight: .semibold))
if parts.count > 1 {
Text(verbatim: String(parts[1]))
MetricText(value: String(parts[1]))
.font(.system(size: compact ? 10 : 12, weight: .medium))
.foregroundStyle(Color.primary.opacity(0.8))
}
-27
View File
@@ -1,27 +0,0 @@
import SwiftUI
/// Four square blocks fill from bottom to top; partial blocks retain the actual fraction.
struct SegmentedCoreBar: View {
let value: Double?
let color: Color
static func portions(_ value: Double?, count: Int = 4) -> [Double] {
guard count > 0 else { return [] }
let fraction = value.flatMap { $0.isFinite ? min(1, max(0, $0)) : nil } ?? 0
return (0..<count).map { min(1, max(0, fraction * Double(count) - Double($0))) }
}
var body: some View {
let fills = Self.portions(value)
VStack(spacing: 2) {
ForEach(Array(fills.indices.reversed()), id: \.self) { index in
ZStack(alignment: .bottom) {
Rectangle().fill(color.opacity(0.15))
Rectangle().fill(color).frame(height: 6 * fills[index])
}.frame(width: 6, height: 6).clipped()
}
}
.accessibilityHidden(true)
.transaction { $0.animation = nil; $0.disablesAnimations = true }
}
}