feat(ui): 实现全卡堆叠趋势与单页资源进程布局

This commit is contained in:
2026-11-15 17:59:52 +08:00
parent 469766892d
commit 99e558625b
37 changed files with 579 additions and 195 deletions
+22 -11
View File
@@ -10,6 +10,7 @@ struct NativePanelCurve: NSViewRepresentable {
var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
@@ -18,7 +19,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))
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked))
}
struct Input: Equatable {
let frame: PanelCurveFrame
@@ -28,6 +29,7 @@ struct NativePanelCurve: NSViewRepresentable {
var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
}
final class PlotView: NSView {
private(set) var input: Input?
@@ -38,6 +40,7 @@ struct NativePanelCurve: NSViewRepresentable {
private var hoverDots: [CAShapeLayer] = []
private var seriesLayers: [SeriesLayer] = []
private var palette: [NSColor] = []
private var plottedBands: [StackedSeries.Band] = []
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
@@ -67,7 +70,7 @@ struct NativePanelCurve: NSViewRepresentable {
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 {
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || old?.stacked != value.stacked {
rebuildPaths()
}
updateHover()
@@ -122,13 +125,16 @@ struct NativePanelCurve: NSViewRepresentable {
}
let domain = PanelCurveFrame.domain(begin: first, end: last)
let frame = 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]
series.resize(bounds)
let value = input.scales[min(index, input.scales.count - 1)]
let value = input.scales[input.stacked ? 0 : min(index, input.scales.count - 1)]
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 upper = input.stacked ? plottedBands[index].upper : frame.series[index]
let lower = input.stacked ? plottedBands[index].lower : nil
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: upper, maximumGap: input.maximumGap,
boundaryDates: frame.boundaryDates, intervals: frame.intervals, lowerValues: lower)
let line = CGMutablePath(), dots = CGMutablePath(), area = CGMutablePath()
for run in runs {
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
@@ -143,11 +149,16 @@ 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.
// Close against the matching lower boundary, never against another run or missing component.
let lowerPoints = run.reversed().map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.lower / scale)))) }
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)
if let lowerStart = lowerPoints.first { fill.addLine(to: lowerStart) }
for (a, b) in zip(lowerPoints, lowerPoints.dropFirst()) {
let mid = (a.x + b.x) / 2
fill.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
fill.closeSubpath(); area.addPath(fill)
}
series.line.path = line
series.points.path = dots
@@ -164,9 +175,9 @@ struct NativePanelCurve: NSViewRepresentable {
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]
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 scale = input.scales[min(series, input.scales.count - 1)]
let scale = input.scales[input.stacked ? 0 : min(series, input.scales.count - 1)]
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1))))
hoverDots[series].path = CGPath(ellipseIn: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5), transform: nil)
}
+8 -2
View File
@@ -4,6 +4,7 @@ nonisolated enum PanelCurveGeometry {
struct Sample {
let date: Date
let value: Double
var lower: Double = 0
}
static func allowedGap(at index: Int, intervals: [TimeInterval], fallback: TimeInterval) -> TimeInterval {
@@ -12,7 +13,7 @@ nonisolated enum PanelCurveGeometry {
return interval.isFinite && interval > 0 ? max(5, interval * 2) : fallback
}
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = []) -> [[Sample]] {
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = [], lowerValues: [Double?]? = nil) -> [[Sample]] {
var result: [[Sample]] = []
var run: [Sample] = []
func flush() { if !run.isEmpty { result.append(run); run.removeAll(keepingCapacity: true) } }
@@ -20,7 +21,12 @@ nonisolated enum PanelCurveGeometry {
if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > allowedGap(at: index, intervals: intervals, fallback: maximumGap) || dates[index] <= dates[index - 1]) { flush() }
// Missing values do not create vertices, but their timestamps can still carry a real break.
guard index < values.count, let value = values[index], value.isFinite else { continue }
run.append(Sample(date: dates[index], value: value))
var lower = 0.0
if let lowerValues {
guard lowerValues.indices.contains(index), let base = lowerValues[index], base.isFinite else { continue }
lower = base
}
run.append(Sample(date: dates[index], value: value, lower: lower))
}
flush()
return result
+21 -4
View File
@@ -31,6 +31,7 @@ struct PanelTrendChart: View {
var boundaryDates: Set<Date> = []
var intervals: [TimeInterval] = []
var visibleSeriesCount = 1
var stackOrder: [Int] = []
@State private var retainedScale: Double = 1
@State private var smallSamples = 0
@State private var retainedSecondScale: Double = 1
@@ -45,7 +46,22 @@ struct PanelTrendChart: View {
intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count),
boundaryDates: boundaryDates)
}
private var maximum: Double { max(1, (first + second + third + fourth).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var renderFrame: PanelCurveFrame {
let raw = inputFrame
guard !stackOrder.isEmpty else { return raw }
return PanelCurveFrame(dates: raw.dates, series: stackOrder.map { index in
raw.series.indices.contains(index) ? raw.series[index] : Array(repeating: nil, count: raw.dates.count)
}, intervals: raw.intervals, boundaryDates: raw.boundaryDates)
}
private var renderColors: [Color] {
let colors = [color, secondColor, thirdColor, fourthColor]
return stackOrder.isEmpty ? colors : stackOrder.map { colors[min(max(0, $0), colors.count - 1)] }
}
private var maximum: Double {
let values = stackOrder.isEmpty ? first + second + third + fourth
: StackedSeries.bands(renderFrame.series, count: dates.count).last?.upper ?? []
return max(1, values.compactMap { $0 }.filter(\.isFinite).max() ?? 1)
}
private var secondMaximum: Double { max(1, second.compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
private var scale: Double { max(0.0001, fixedScale ?? retainedScale) }
private var secondaryScale: Double { max(0.0001, retainedSecondScale) }
@@ -94,10 +110,11 @@ struct PanelTrendChart: View {
var body: some View {
GeometryReader { proxy in
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
NativePanelCurve(frame: renderFrame, colors: renderColors,
scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale],
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
visibleSeriesCount: visibleSeriesCount, filledSeriesCount: visibleSeriesCount)
visibleSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count,
filledSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count, stacked: !stackOrder.isEmpty)
.contentShape(Rectangle())
.onContinuousHover { phase in
switch phase {
@@ -114,7 +131,7 @@ struct PanelTrendChart: View {
return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index)))
}
}
.frame(height: ResourceCardMetrics.plotHeight)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onAppear {
retainedScale = maximum
retainedSecondScale = secondMaximum
+32
View File
@@ -0,0 +1,32 @@
import Foundation
/// Additive components retain their raw values; only render boundaries are cumulative.
nonisolated enum StackedSeries {
struct Band {
var lower: [Double?]
var upper: [Double?]
}
static func bands(_ components: [[Double?]], count: Int, limit: Double? = nil) -> [Band] {
var result = components.map { _ in Band(lower: Array(repeating: nil, count: count), upper: Array(repeating: nil, count: count)) }
guard !components.isEmpty else { return result }
for point in 0..<count {
var values: [Double] = []
for component in components {
guard component.indices.contains(point), let value = component[point], value.isFinite, value >= 0 else { break }
values.append(value)
}
guard values.count == components.count else { continue }
let total = values.reduce(0, +)
guard total.isFinite else { continue }
if let limit, limit.isFinite, limit > 0, total > limit + max(1, limit) * 1e-12 { continue }
var lower = 0.0
for (series, value) in values.enumerated() {
result[series].lower[point] = lower
lower += value
result[series].upper[point] = lower
}
}
return result
}
}
+94 -1
View File
@@ -1,11 +1,43 @@
import AppKit
import SwiftUI
/// Historical visual speed tiers; they deliberately do not reproduce physical RPM.
nonisolated struct FanRotation {
private(set) var phase: Double = 0
private(set) var speed: Double = 0
private var reference: TimeInterval = 0
static func speed(rpm: Double?, reducedMotion: Bool) -> Double {
guard !reducedMotion, let rpm, rpm.isFinite, rpm > 0 else { return 0 }
switch rpm {
case ..<2000: return 90
case ..<4000: return 180
case ..<6000: return 300
default: return 450
}
}
func angle(at time: TimeInterval) -> Double {
(phase + max(0, time - reference) * speed).truncatingRemainder(dividingBy: 360)
}
mutating func update(rpm: Double?, reducedMotion: Bool, at time: TimeInterval) {
phase = angle(at: time)
reference = time
speed = Self.speed(rpm: rpm, reducedMotion: reducedMotion)
}
}
struct FanSpeedIndicator: View {
let title: Text
let rpm: Double?
var isActive = true
@Environment(\.accessibilityReduceMotion) private var reduceMotion
var body: some View {
HStack(spacing: 4) {
HStack(spacing: 3) {
FanRotor(rpm: rpm, isActive: isActive, reduceMotion: reduceMotion)
.frame(width: 11, height: 11).accessibilityHidden(true)
title.foregroundStyle(.secondary)
MetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
.monospacedDigit().fontWeight(.medium)
@@ -13,3 +45,64 @@ struct FanSpeedIndicator: View {
.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.7)
}
}
/// Only this native icon animates; sampling updates do not create display timers.
struct FanRotor: NSViewRepresentable {
let rpm: Double?
let isActive: Bool
let reduceMotion: Bool
func makeNSView(context: Context) -> RotorView { RotorView() }
func updateNSView(_ view: RotorView, context: Context) {
view.configure(rpm: rpm, active: isActive, reducedMotion: reduceMotion)
}
static func dismantleNSView(_ view: RotorView, coordinator: ()) { view.stop() }
final class RotorView: NSImageView {
static let animationKey = "fan.rotation"
private var rpm: Double?
private var active = false
private var reducedMotion = false
private(set) var rotation = FanRotation()
init() {
super.init(frame: .zero)
wantsLayer = true
image = NSImage(systemSymbolName: "fanblades.fill", accessibilityDescription: nil)
contentTintColor = .secondaryLabelColor
imageScaling = .scaleProportionallyUpOrDown
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(rpm: Double?, active: Bool, reducedMotion: Bool) {
self.rpm = rpm; self.active = active; self.reducedMotion = reducedMotion
refresh()
}
func stop() {
active = false; refresh()
layer?.removeAnimation(forKey: Self.animationKey)
}
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); refresh() }
private func refresh() {
let readable = active && window != nil ? rpm : nil
let speed = FanRotation.speed(rpm: readable, reducedMotion: reducedMotion)
guard speed != rotation.speed else { return }
rotation.update(rpm: readable, reducedMotion: reducedMotion, at: CACurrentMediaTime())
let radians = rotation.phase * .pi / 180
CATransaction.begin(); CATransaction.setDisableActions(true)
layer?.removeAnimation(forKey: Self.animationKey)
layer?.transform = CATransform3DMakeRotation(radians, 0, 0, 1)
if speed > 0 {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.fromValue = radians; animation.toValue = radians + .pi * 2
animation.duration = 360 / speed
animation.repeatCount = .infinity
animation.timingFunction = CAMediaTimingFunction(name: .linear)
layer?.add(animation, forKey: Self.animationKey)
}
CATransaction.commit()
}
}
}
+2 -2
View File
@@ -28,8 +28,8 @@ struct CardField<Content: View>: View {
struct CardSurface: ViewModifier {
func body(content: Content) -> some View {
content.modifier(PanelCardBackground(radius: 10))
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14)))
content.modifier(PanelCardBackground(radius: ResourceCardMetrics.radius))
.overlay(RoundedRectangle(cornerRadius: ResourceCardMetrics.radius).strokeBorder(.primary.opacity(0.06)))
}
}
+1 -2
View File
@@ -26,7 +26,7 @@ struct ResourceCard<Chart: View, Content: View>: View {
GeometryReader { bounds in
ZStack(alignment: .bottomLeading) {
chart()
.frame(width: bounds.size.width, height: ResourceCardMetrics.plotHeight)
.frame(width: bounds.size.width, height: bounds.size.height)
VStack(alignment: .leading, spacing: ResourceCardMetrics.gap) {
header
HStack(alignment: .firstTextBaseline, spacing: 6) {
@@ -42,7 +42,6 @@ struct ResourceCard<Chart: View, Content: View>: View {
}
.font(.system(size: 9))
.padding(ResourceCardMetrics.padding)
.padding(.bottom, ResourceCardMetrics.plotHeight - ResourceCardMetrics.padding)
.frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading)
}
.background(Color("PanelCard"))
@@ -6,7 +6,6 @@ nonisolated enum ResourceCardMetrics {
static let minimumHeight: CGFloat = 176
static let padding: CGFloat = 10
static let radius: CGFloat = 16
static let plotHeight: CGFloat = 48
static let titleHeight: CGFloat = 14
static let headlineHeight: CGFloat = 34
static let gap: CGFloat = 4
+27
View File
@@ -0,0 +1,27 @@
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 }
}
}