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
+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)))
}
}