feat(menubar): 调整两排卡片布局并加入复合曲线与数值动效

This commit is contained in:
2026-11-03 10:10:44 +08:00
parent 0e8f598fe6
commit 906293b7c1
22 changed files with 400 additions and 122 deletions
@@ -8,7 +8,7 @@
"red": "0.960",
"green": "0.970",
"blue": "0.990",
"alpha": "1.000"
"alpha": "0.680"
}
}
},
@@ -26,7 +26,7 @@
"red": "0.100",
"green": "0.120",
"blue": "0.160",
"alpha": "1.000"
"alpha": "0.680"
}
}
}
+4 -1
View File
@@ -11,6 +11,8 @@ nonisolated struct TrendSample: Sendable {
var upload: Double?
var read: Double?
var write: Double?
var cpuUser: Double?
var cpuSystem: Double?
}
/// Bounded sampling history; no timer or UI visibility dependence.
@@ -24,7 +26,8 @@ nonisolated struct MetricHistory: Sendable {
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
battery: snapshot.battery?.charge, upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written))
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system))
let current = snapshot.network ?? []
let keys = Set(current.map(\.identity))
interfaces = interfaces.filter { keys.contains($0.key) }
+1
View File
@@ -23,6 +23,7 @@ nonisolated struct MetricsSnapshot: Sendable {
var memory: MemoryMetrics?
var network: [NetworkInterfaceMetrics]?
var networkPath: NetworkPathStatus?
var defaultNetworkInterface: String?
var disk: DiskMetrics?
var diskHealth: DiskHealthMetrics?
var diskIO: DiskIOMetrics?
@@ -10,6 +10,7 @@ nonisolated final class NetworkPathObserver: @unchecked Sendable {
private let monitor = NWPathMonitor()
private let lock = NSLock()
private var status: NetworkPathStatus?
private var primaryInterface: String?
init() {
monitor.pathUpdateHandler = { [weak self] path in
@@ -22,6 +23,7 @@ nonisolated final class NetworkPathObserver: @unchecked Sendable {
}
self.lock.lock()
self.status = next
self.primaryInterface = path.status == .satisfied ? path.availableInterfaces.first?.name : nil
self.lock.unlock()
}
monitor.start(queue: DispatchQueue(label: "cn.airnan.kymo.network-path"))
@@ -33,5 +35,11 @@ nonisolated final class NetworkPathObserver: @unchecked Sendable {
return status
}
func defaultInterface() -> String? {
lock.lock()
defer { lock.unlock() }
return primaryInterface
}
deinit { monitor.cancel() }
}
+1
View File
@@ -50,6 +50,7 @@ actor SystemSampler {
result.memory = MemoryMonitor.sample()
result.network = network.sample()
result.networkPath = networkPath.snapshot()
result.defaultNetworkInterface = networkPath.defaultInterface()
result.disk = DiskMonitor.sample()
result.diskIO = diskIO.sample()
result.battery = BatteryMonitor.sample()
+28
View File
@@ -0,0 +1,28 @@
import Foundation
import IOKit
import Darwin
/// Cached local model metadata, without serial numbers or network/device names.
nonisolated enum HardwareIdentity {
static let displayName: String = {
let entry = IORegistryEntryFromPath(kIOMainPortDefault, "IODeviceTree:/product")
var product: String?
if entry != 0 {
defer { IOObjectRelease(entry) }
if let data = IORegistryEntryCreateCFProperty(entry, "product-name" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? Data {
product = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .controlCharacters)
}
}
let model = string("hw.model")
let chip = string("machdep.cpu.brand_string")
return [product?.isEmpty == false ? product : model, chip].compactMap { $0 }.joined(separator: " · ")
}()
private static func string(_ key: String) -> String? {
var count = 0
guard sysctlbyname(key, nil, &count, nil, 0) == 0, count > 0 else { return nil }
var bytes = [CChar](repeating: 0, count: count)
guard sysctlbyname(key, &bytes, &count, nil, 0) == 0 else { return nil }
return String(cString: bytes)
}
}
+52 -44
View File
@@ -26,28 +26,18 @@ struct MenuPanelView: View {
var body: some View {
VStack(spacing: 8) {
header
if columns == 3 && panelSize.height >= 810 {
VStack(spacing: 8) {
HStack(alignment: .top, spacing: 8) {
cpuCard.frame(width: (panelSize.width - 36) * 0.35)
gpuCard.frame(width: (panelSize.width - 36) * 0.33)
memoryCard.frame(width: (panelSize.width - 36) * 0.32)
}.frame(height: panelSize.height - 590)
HStack(alignment: .top, spacing: 8) {
networkCard.frame(width: (panelSize.width - 36) * 0.42)
diskCard.frame(width: (panelSize.width - 36) * 0.27)
batteryCard.frame(width: (panelSize.width - 36) * 0.31)
}.frame(height: 240)
}
if columns == 3 {
if panelSize.height >= 810 { resourceRows }
else { ScrollView { resourceRows } }
} else {
ScrollView {
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .top), count: columns), spacing: 8) {
cpuCard.frame(minHeight: 240)
gpuCard.frame(minHeight: 240)
batteryCard.aspectRatio(1, contentMode: .fit)
memoryCard.frame(minHeight: 240)
networkCard.frame(minHeight: 250)
diskCard.frame(minHeight: 250)
batteryCard.frame(minHeight: 250)
networkCard.frame(minHeight: 250)
}
}
}
@@ -55,7 +45,6 @@ struct MenuPanelView: View {
ProcessTableView(snapshot: snapshot.processes, wide: panelSize.width >= 900, logicalCPUCount: snapshot.cpu?.cores.count ?? 1).frame(maxWidth: .infinity, maxHeight: .infinity)
.frame(minHeight: 170)
}
footer
}
.padding(10)
.frame(width: panelSize.width, height: panelSize.height)
@@ -71,33 +60,49 @@ struct MenuPanelView: View {
.modifier(AppearanceStyle(preferences: preferences))
}
private var resourceRows: some View {
VStack(spacing: 8) {
HStack(alignment: .top, spacing: 8) {
cpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize))
gpuCard.frame(width: PanelLayout.firstRowWideCardWidth(size: panelSize))
batteryCard.frame(width: PanelLayout.resourceRowHeight(size: panelSize))
}.frame(height: PanelLayout.resourceRowHeight(size: panelSize))
HStack(alignment: .top, spacing: 8) {
memoryCard.frame(width: (panelSize.width - 36) / 3)
diskCard.frame(width: (panelSize.width - 36) / 3)
networkCard.frame(width: (panelSize.width - 36) / 3)
}.frame(height: 240)
}
}
private var header: some View {
HStack(spacing: 10) {
Image("BrandMark").renderingMode(.template)
Text("Kymo").font(.system(size: 18, weight: .semibold))
Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")")
.font(.system(size: 10)).foregroundStyle(.secondary)
if panelSize.width >= 900 {
Text(verbatim: "\(ProcessInfo.processInfo.processorCount) CPU · \(MetricFormat.bytes(snapshot.memory?.total))")
.font(.system(size: 11)).foregroundStyle(.secondary)
Text(verbatim: HardwareIdentity.displayName)
.font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)
}
Spacer()
VStack(alignment: .trailing, spacing: 2) {
Label(metrics.isPaused ? "panel.paused" : "panel.sampling", systemImage: metrics.isPaused ? "pause.circle" : "circle.fill")
.foregroundStyle(metrics.isPaused ? Color.secondary : Color("MetricBattery"))
Text(snapshot.date, style: .time).foregroundStyle(.secondary)
}.font(.system(size: 10))
Spacer(minLength: 8)
controls
}.padding(.horizontal, 4)
}
private func chart(_ key: KeyPath<TrendSample, Double?>, color: Color) -> some View {
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color)
private func chart(_ key: KeyPath<TrendSample, Double?>, color: Color, label: LocalizedStringKey = "panel.total") -> some View {
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color, firstLabel: label)
}
private func line(_ key: LocalizedStringKey, _ value: String) -> some View {
HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); Text(verbatim: value).monospacedDigit() }
HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); AnimatedMetricText(value: value) }
}
private var cpuCard: some View {
ResourceCard(title: "metric.cpu", symbol: "cpu", color: Color("MetricCPU"), value: MetricFormat.percent(snapshot.cpu?.usage)) {
chart(\.cpu, color: Color("MetricCPU"))
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.cpu),
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
color: Color("MetricCPU"), secondColor: Color("MetricNetwork"), thirdColor: Color("MetricDisk"),
firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system")
if let cpu = snapshot.cpu {
HStack { line("cpu.user", MetricFormat.percent(cpu.user)); line("cpu.system", MetricFormat.percent(cpu.system)) }
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 5) {
@@ -115,7 +120,7 @@ struct MenuPanelView: View {
} else { Text("metric.waiting").foregroundStyle(.secondary) }
Spacer(minLength: 0)
HStack { line("system.load", snapshot.load.map(MetricFormat.decimal).joined(separator: " / ")); Spacer(minLength: 8); Text(verbatim: String(format: "%.1f h", snapshot.uptime / 3600)) }
HStack { line("system.load", snapshot.load.map(MetricFormat.decimal).joined(separator: " / ")); Spacer(minLength: 8); AnimatedMetricText(value: String(format: "%.1f h", snapshot.uptime / 3600)) }
}
}
@@ -148,7 +153,7 @@ struct MenuPanelView: View {
line("memory.app", MetricFormat.bytes(m.used - min(m.used, m.wired + m.compressed)))
HStack { line("memory.wired", MetricFormat.bytes(m.wired)); line("memory.compressed", MetricFormat.bytes(m.compressed)) }
HStack { line("memory.available", MetricFormat.bytes(m.total - min(m.total, m.used))); line("memory.swap", MetricFormat.bytes(m.swapUsed)) }
HStack { Text("memory.pressure").foregroundStyle(.secondary); Spacer(); pressure(m.pressure); Text(verbatim: MetricFormat.percent(m.usage)).foregroundStyle(Color("MetricMemory")) }
HStack { Text("memory.pressure").foregroundStyle(.secondary); Spacer(); pressure(m.pressure); AnimatedMetricText(value: MetricFormat.percent(m.usage)).foregroundStyle(Color("MetricMemory")) }
} else { Text("metric.waiting") }
}
}
@@ -169,10 +174,11 @@ struct MenuPanelView: View {
}.labelsHidden().controlSize(.mini).frame(maxWidth: 200)
Spacer(minLength: 0)
}
if let item = network.first, let address = item.addresses.first {
Text(verbatim: "\(item.name) · \(address)").font(.system(size: 10)).lineLimit(1).truncationMode(.middle).textSelection(.enabled)
}
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), fixedScale: nil).id(selectedInterface)
if let item = addressInterface {
Text(verbatim: "\(item.name) · \(item.addresses.first(where: { !$0.contains(":") }) ?? item.addresses.first ?? "--")")
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.8).textSelection(.enabled)
} else { Text("panel.addressUnknown").foregroundStyle(.secondary) }
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload").id(selectedInterface)
if !network.isEmpty && total(\.download) == nil { Text("panel.rateBaseline").foregroundStyle(.secondary) }
HStack { line("network.received", network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received })); line("network.sent", network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent })) }
switch snapshot.networkPath {
@@ -208,6 +214,10 @@ struct MenuPanelView: View {
}
}
private var addressInterface: NetworkInterfaceMetrics? {
let name = selectedInterface.isEmpty ? snapshot.defaultNetworkInterface : network.first?.name
return snapshot.network?.first { $0.name == name && $0.active }
}
private var networkDates: [Date] { selectedInterface.isEmpty ? samples.map(\.date) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.date) }
private var networkDownloads: [Double?] { selectedInterface.isEmpty ? samples.map(\.download) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.download) }
private var networkUploads: [Double?] { selectedInterface.isEmpty ? samples.map(\.upload) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.upload) }
@@ -215,7 +225,7 @@ struct MenuPanelView: View {
ResourceCard(title: "metric.disk", symbol: "internaldrive", color: Color("MetricDisk"), value: snapshot.disk.map { String(format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 1_000_000_000, Double($0.total) / 1_000_000_000) } ?? "--") {
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil)
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write")
Text("disk.physicalIO").foregroundStyle(.secondary)
HStack { line("disk.read", MetricFormat.rate(snapshot.diskIO?.read)); line("disk.write", MetricFormat.rate(snapshot.diskIO?.written)) }
HStack { line("disk.remainingLife", MetricFormat.percent(snapshot.diskHealth?.remainingLife)); line("disk.powerOnHours", snapshot.diskHealth?.powerOnHours.map { "\($0) h" } ?? "--") }
@@ -243,7 +253,7 @@ struct MenuPanelView: View {
private var batteryCard: some View {
ResourceCard(title: "metric.battery", symbol: "battery.100percent", color: Color("MetricBattery"), value: MetricFormat.percent(snapshot.battery?.charge)) {
if let battery = snapshot.battery {
chart(\.battery, color: Color("MetricBattery"))
chart(\.battery, color: Color("MetricBattery"), label: "metric.battery")
Text(battery.charging ? "battery.charging" : battery.externalPower ? "battery.external" : "battery.discharging")
line("battery.cycles", battery.cycles.map(String.init) ?? "--")
line("battery.health", MetricFormat.percent(battery.health))
@@ -251,7 +261,7 @@ struct MenuPanelView: View {
Text(battery.charging ? "battery.timeFull" : "battery.timeEmpty").foregroundStyle(.secondary)
Spacer()
if battery.externalPower && !battery.charging { Text("battery.timeNotApplicable") }
else if let minutes = battery.minutesRemaining { Text(verbatim: "\(minutes) min") }
else if let minutes = battery.minutesRemaining { AnimatedMetricText(value: "\(minutes) min") }
else { Text("battery.timeUnknown") }
}
@@ -260,10 +270,8 @@ struct MenuPanelView: View {
}
}
}
private var footer: some View {
private var controls: some View {
HStack(spacing: 8) {
Text(verbatim: "v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "--")").font(.system(size: 10)).foregroundStyle(.secondary)
Spacer()
HStack(spacing: 2) {
Button { keepAwake.toggle() } label: {
Image(systemName: keepAwake.isEnabled ? "cup.and.saucer.fill" : "cup.and.saucer")
@@ -292,7 +300,7 @@ struct MenuPanelView: View {
}
.help(Text("action.quit")).accessibilityLabel(Text("action.quit"))
}
.buttonStyle(FooterButtonStyle())
.buttonStyle(PanelControlButtonStyle())
.padding(4)
.glassEffect(.regular, in: .capsule)
}
@@ -302,15 +310,15 @@ struct MenuPanelView: View {
}
private struct FooterButtonStyle: ButtonStyle {
private struct PanelControlButtonStyle: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
FooterButtonBody(isPressed: configuration.isPressed) {
PanelControlButtonBody(isPressed: configuration.isPressed) {
configuration.label
}
}
}
private struct FooterButtonBody<Content: View>: View {
private struct PanelControlButtonBody<Content: View>: View {
let isPressed: Bool
@ViewBuilder var content: () -> Content
@State private var isHovered = false
+3
View File
@@ -2,6 +2,9 @@ import Foundation
import CoreGraphics
nonisolated enum PanelLayout {
static func resourceRowHeight(size: CGSize) -> CGFloat { min(230, max(220, size.height - 590)) }
static func firstRowWideCardWidth(size: CGSize) -> CGFloat { (size.width - 36 - resourceRowHeight(size: size)) / 2 }
static func contentSize(visible: CGRect, chrome: CGSize = .zero) -> CGSize {
CGSize(width: max(1, min(1240, visible.width - 32 - max(0, chrome.width))),
height: max(1, min(820, visible.height - 32 - max(0, chrome.height))))
+1 -1
View File
@@ -71,7 +71,7 @@ struct ProcessTableView: View {
}
}
.font(.system(size: 12)).padding(10)
.background(Color("PanelCard"), in: .rect(cornerRadius: 14))
.modifier(PanelCardBackground(radius: 14))
.overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(.primary.opacity(0.1)))
.onAppear { rebuild(retainOrder: false) }
.onChange(of: snapshot?.date) { _, _ in rebuild(retainOrder: held && (byMemory ? rows.contains { $0.residentBytes != nil } : rows.contains { $0.cpu != nil })) }
+13 -6
View File
@@ -2174,19 +2174,19 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "CPU: one core = 100%, may exceed 100% · Memory: RSS · Restricted fields shown as --"
"value" : "CPU: one core = 100%, may exceed 100% · Memory: physical resident size (RSS) · Restricted fields shown as --"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "CPU:单核 100%,可超过 100% · 内存:RSS · 受限字段显示 --"
"value" : "CPU:单核 100%,可超过 100% · 内存:实际驻留物理内存(RSS)· 受限字段显示 --"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "CPU:單核 100%,可超過 100% · 記憶體:RSS · 受限欄位顯示 --"
"value" : "CPU:單核 100%,可超過 100% · 記憶體:實際駐留實體記憶體(RSS)· 受限欄位顯示 --"
}
}
}
@@ -2243,19 +2243,19 @@
"en" : {
"stringUnit" : {
"state" : "translated",
"value" : "RSS"
"value" : "Memory"
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
"value" : "RSS"
"value" : "内存"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
"value" : "RSS"
"value" : "記憶體"
}
}
}
@@ -2398,6 +2398,13 @@
}
}
},
"panel.total" : {
"localizations" : {
"en" : { "stringUnit" : { "state" : "translated", "value" : "Total" } },
"zh-Hans" : { "stringUnit" : { "state" : "translated", "value" : "总占用" } },
"zh-Hant" : { "stringUnit" : { "state" : "translated", "value" : "總佔用" } }
}
},
"panel.totalNetwork" : {
"extractionState" : "manual",
"localizations" : {
+28
View File
@@ -0,0 +1,28 @@
import Foundation
nonisolated enum PanelCurveGeometry {
struct Sample {
let date: Date
let value: Double
}
static func isAppend(from old: [Date], to new: [Date]) -> Bool {
guard old.count > 1, let previous = old.last, let next = new.last,
next > previous, next.timeIntervalSince(previous) <= 5 else { return false }
if new.count == old.count + 1 { return Array(new.dropLast()) == old }
return new.count == old.count && Array(old.dropFirst()) == Array(new.dropLast())
}
static func runs(dates: [Date], values: [Double?]) -> [[Sample]] {
var result: [[Sample]] = []
var run: [Sample] = []
func flush() { if !run.isEmpty { result.append(run); run.removeAll(keepingCapacity: true) } }
for index in dates.indices {
guard index < values.count, let value = values[index], value.isFinite else { flush(); continue }
if index > 0 && (dates[index].timeIntervalSince(dates[index - 1]) > 5 || dates[index] <= dates[index - 1]) { flush() }
run.append(Sample(date: dates[index], value: value))
}
flush()
return result
}
}
+147 -52
View File
@@ -1,90 +1,185 @@
import SwiftUI
/// Real timestamps determine x positions; missing data and pauses break the path.
/// Bounded, timestamp-based curves. Gaps remain gaps; animation only runs on append.
struct PanelTrendChart: View {
let dates: [Date]
let first: [Double?]
var second: [Double?] = []
var third: [Double?] = []
let color: Color
var secondColor: Color = .orange
var thirdColor: Color = .purple
var fixedScale: Double? = 1
var scaleLabel: String?
var firstLabel: LocalizedStringKey = "panel.total"
var secondLabel: LocalizedStringKey = "network.upload"
var thirdLabel: LocalizedStringKey = "cpu.system"
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var hoveredDate: Date?
@State private var previousBegin: Date?
@State private var previousEnd: Date?
@State private var progress: CGFloat = 1
private var maximum: Double { max(1, (first + second).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var middleLabel: String {
if let fixedScale { return fixedScale == 1 ? "50%" : MetricFormat.bytes(UInt64(max(0, fixedScale / 2))) }
return MetricFormat.rate(retainedScale / 2)
private var maximum: Double { max(1, (first + second + third).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var scale: Double { max(0.0001, fixedScale ?? retainedScale) }
private var index: Int? {
guard !dates.isEmpty else { return nil }
guard let hoveredDate else { return dates.count - 1 }
return dates.indices.min { abs(dates[$0].timeIntervalSince(hoveredDate)) < abs(dates[$1].timeIntervalSince(hoveredDate)) }
}
private func formatted(_ value: Double?) -> String {
guard let value, value.isFinite else { return "--" }
if fixedScale == 1 { return MetricFormat.percent(value) }
if fixedScale == nil { return MetricFormat.rate(value) }
return MetricFormat.bytes(UInt64(max(0, value)))
}
private func value(_ values: [Double?]) -> String {
guard let index, index < values.count else { return "--" }
return formatted(values[index])
}
private func legend(_ label: LocalizedStringKey, values: [Double?], tint: Color) -> some View {
HStack(spacing: 3) {
RoundedRectangle(cornerRadius: 1).fill(tint).frame(width: 7, height: 7)
Text(label)
Text(verbatim: value(values)).monospacedDigit()
}.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.8)
}
var body: some View {
VStack(spacing: 2) {
VStack(spacing: 3) {
HStack(spacing: 10) {
legend(firstLabel, values: first, tint: color)
if !second.isEmpty { legend(secondLabel, values: second, tint: secondColor) }
if !third.isEmpty { legend(thirdLabel, values: third, tint: thirdColor) }
Spacer(minLength: 0)
}.frame(height: 14)
HStack(spacing: 5) {
VStack(alignment: .trailing) {
Text(verbatim: scaleLabel ?? (fixedScale == nil ? MetricFormat.rate(retainedScale) : "100%"))
.lineLimit(1).minimumScaleFactor(0.75)
Text(verbatim: scaleLabel ?? formatted(scale))
Spacer(minLength: 0)
Text(verbatim: middleLabel).lineLimit(1).minimumScaleFactor(0.75)
Text(verbatim: formatted(scale / 2))
Spacer(minLength: 0)
Text(verbatim: "0")
}.font(.system(size: 8)).foregroundStyle(.secondary).frame(width: 52, height: 48)
Canvas { context, size in
var grid = Path()
for step in 0...10 {
let x = size.width * Double(step) / 10
grid.move(to: CGPoint(x: x, y: 0)); grid.addLine(to: CGPoint(x: x, y: size.height))
}
for step in 0...2 {
let y = size.height * Double(step) / 2
grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: size.width, y: y))
}
context.stroke(grid, with: .color(color.opacity(0.14)), lineWidth: 0.5)
guard let begin = dates.first, let end = dates.last, end > begin else { return }
let scale = fixedScale ?? retainedScale
for (values, tint) in [(first, color), (second, secondColor)] {
var path = Path()
var connected = false
var fill = Path()
var runStart: CGPoint?
var runEnd: CGPoint?
func closeRun() {
guard let start = runStart, let end = runEnd else { return }
fill.addLine(to: CGPoint(x: end.x, y: size.height))
fill.addLine(to: CGPoint(x: start.x, y: size.height)); fill.closeSubpath()
runStart = nil; runEnd = nil
}.font(.system(size: 8)).foregroundStyle(.secondary)
.lineLimit(1).minimumScaleFactor(0.6).frame(width: fixedScale == 1 ? 28 : 47, height: 58)
GeometryReader { proxy in
ZStack(alignment: .topLeading) {
PanelCurveCanvas(dates: dates, series: [first, second, third], colors: [color, secondColor, thirdColor],
scale: scale, previousBegin: previousBegin, previousEnd: previousEnd, progress: progress)
if hoveredDate != nil, let index, let begin = dates.first, let end = dates.last, end > begin {
let x = proxy.size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin)
Path { path in
path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: proxy.size.height))
}.stroke(.primary.opacity(0.45), style: StrokeStyle(lineWidth: 1, dash: [3, 2]))
ForEach(0..<3, id: \.self) { series in
let values = [first, second, third][series]
if index < values.count, let value = values[index], value.isFinite {
Circle().fill([color, secondColor, thirdColor][series]).frame(width: 5, height: 5)
.position(x: x, y: proxy.size.height * (1 - min(1, max(0, value / scale))))
}
}
}
}
for index in dates.indices {
guard index < values.count, let value = values[index], value.isFinite else { closeRun(); connected = false; continue }
if index > 0 && dates[index].timeIntervalSince(dates[index - 1]) > 5 { closeRun(); connected = false }
let point = CGPoint(x: size.width * dates[index].timeIntervalSince(begin) / end.timeIntervalSince(begin),
y: size.height * (1 - min(1, max(0, value / scale))))
if connected { path.addLine(to: point); fill.addLine(to: point) }
else { path.move(to: point); fill.move(to: point); runStart = point }
runEnd = point
connected = true
.contentShape(Rectangle())
.onContinuousHover { phase in
switch phase {
case .active(let point):
if let begin = dates.first, let end = dates.last {
hoveredDate = begin.addingTimeInterval(end.timeIntervalSince(begin) * min(1, max(0, point.x / max(1, proxy.size.width))))
}
case .ended: hoveredDate = nil
}
}
closeRun()
context.fill(fill, with: .linearGradient(Gradient(colors: [tint.opacity(0.45), tint.opacity(0.03)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height)))
context.stroke(path, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round))
}
}.frame(height: 48)
}.frame(height: 58).clipped()
}
HStack {
if let date = dates.first { Text(date, style: .time) }
Spacer()
Spacer(minLength: 0)
if hoveredDate != nil, let index { Text(dates[index], format: .dateTime.hour().minute().second()).foregroundStyle(.primary) }
Spacer(minLength: 0)
if let date = dates.last { Text(date, style: .time) }
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(maxWidth: .infinity)
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(height: 12)
}
.frame(maxWidth: .infinity)
.onAppear { retainedScale = maximum }
.onChange(of: dates.last) { _, _ in
.onChange(of: dates) { old, new in
let target = maximum
if target > retainedScale { retainedScale = target; smallSamples = 0 }
else if target < retainedScale * 0.5 {
smallSamples += 1
if smallSamples >= 10 { retainedScale = target; smallSamples = 0 }
} else { smallSamples = 0 }
let append = PanelCurveGeometry.isAppend(from: old, to: new)
var transaction = Transaction(); transaction.disablesAnimations = true
withTransaction(transaction) {
previousBegin = append && !reduceMotion ? old.first : nil
previousEnd = append && !reduceMotion ? old.last : nil
progress = previousBegin == nil ? 1 : 0
}
}
.task(id: dates.last) {
guard progress == 0, !reduceMotion else { return }
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
withAnimation(.easeInOut(duration: 0.35)) { progress = 1 }
}
.onChange(of: reduceMotion) { _, reduced in if reduced { progress = 1; previousBegin = nil; previousEnd = nil } }
.accessibilityElement(children: .combine)
}
}
private struct PanelCurveCanvas: View, Animatable {
let dates: [Date]
let series: [[Double?]]
let colors: [Color]
let scale: Double
let previousBegin: Date?
let previousEnd: Date?
var progress: CGFloat
var animatableData: CGFloat {
get { progress }
set { progress = newValue }
}
var body: some View {
Canvas { context, size in
var grid = Path()
for step in 0...10 {
let x = size.width * Double(step) / 10
grid.move(to: CGPoint(x: x, y: 0)); grid.addLine(to: CGPoint(x: x, y: size.height))
}
for step in 0...2 {
let y = size.height * Double(step) / 2
grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: size.width, y: y))
}
context.stroke(grid, with: .color(.primary.opacity(0.10)), lineWidth: 0.5)
guard let first = dates.first, let last = dates.last else { return }
let begin = (previousBegin ?? first).timeIntervalSinceReferenceDate * (1 - progress) + first.timeIntervalSinceReferenceDate * progress
let end = (previousEnd ?? last).timeIntervalSinceReferenceDate * (1 - progress) + last.timeIntervalSinceReferenceDate * progress
for (values, tint) in zip(series, colors) {
for run in PanelCurveGeometry.runs(dates: dates, values: values) {
let points = run.map { item in
CGPoint(x: end > begin ? size.width * (item.date.timeIntervalSinceReferenceDate - begin) / (end - begin) : size.width,
y: size.height * (1 - min(1, max(0, item.value / scale))))
}
guard let start = points.first, let finish = points.last else { continue }
var line = Path(); line.move(to: start)
for pair in zip(points, points.dropFirst()) {
let middle = (pair.0.x + pair.1.x) / 2
// Horizontal tangents keep the rounded curve between adjacent sample values.
line.addCurve(to: pair.1, control1: CGPoint(x: middle, y: pair.0.y), control2: CGPoint(x: middle, y: pair.1.y))
}
if points.count == 1 {
context.fill(Path(ellipseIn: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)), with: .color(tint))
} else {
var area = line
area.addLine(to: CGPoint(x: finish.x, y: size.height)); area.addLine(to: CGPoint(x: start.x, y: size.height)); area.closeSubpath()
context.fill(area, with: .linearGradient(Gradient(colors: [tint.opacity(0.20), tint.opacity(0.01)]), startPoint: .zero, endPoint: CGPoint(x: 0, y: size.height)))
context.stroke(line, with: .color(tint), style: StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round))
}
}
}
}
.accessibilityHidden(true)
}
}
@@ -0,0 +1,29 @@
import SwiftUI
/// The same system numeric roll/blur transition as the original metric rows.
struct AnimatedMetricText: View {
let value: String
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
Text(verbatim: value)
.monospacedDigit()
.contentTransition(.numericText())
.animation(reduceMotion ? nil : .spring(duration: 0.35, bounce: 0), value: value)
}
}
struct PanelCardBackground: ViewModifier {
let radius: CGFloat
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
func body(content: Content) -> some View {
content.background {
if reduceTransparency {
RoundedRectangle(cornerRadius: radius).fill(Color(nsColor: .windowBackgroundColor))
} else {
RoundedRectangle(cornerRadius: radius).fill(Color("PanelCard"))
}
}
}
}
+13 -9
View File
@@ -10,21 +10,25 @@ struct ResourceCard<Content: View>: View {
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Label { Text(title).foregroundStyle(.primary) } icon: {
Image(systemName: symbol).foregroundStyle(color)
}.font(.system(size: 13, weight: .semibold))
HStack(alignment: .firstTextBaseline) {
Text(verbatim: value).font(.system(size: 27, weight: .semibold, design: .rounded))
.foregroundStyle(color).monospacedDigit().lineLimit(1).minimumScaleFactor(0.8)
Spacer(minLength: 4)
if let secondaryValue { Text(verbatim: secondaryValue).font(.system(size: 15, weight: .semibold)).foregroundStyle(color).lineLimit(1) }
HStack(alignment: .firstTextBaseline, spacing: 6) {
Label { Text(title).foregroundStyle(.primary) } icon: {
Image(systemName: symbol).foregroundStyle(color)
}.font(.system(size: 13, weight: .semibold)).fixedSize()
Spacer(minLength: 0)
VStack(alignment: .trailing, spacing: 0) {
AnimatedMetricText(value: value)
.font(.system(size: 20, weight: .semibold, design: .rounded))
if let secondaryValue {
AnimatedMetricText(value: secondaryValue).font(.system(size: 11, weight: .semibold))
}
}.foregroundStyle(color).lineLimit(1).minimumScaleFactor(0.65)
}
content()
}
.font(.system(size: 11))
.padding(10)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.background(Color("PanelCard"), in: .rect(cornerRadius: 10))
.modifier(PanelCardBackground(radius: 10))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14)))
}
}