perf(ui): 移除监控动效并精简原生图表绘制

This commit is contained in:
2026-11-07 14:39:27 +08:00
parent 10c73c6026
commit 80706fa52e
54 changed files with 264 additions and 778 deletions
+2 -48
View File
@@ -4,54 +4,9 @@ struct MiniTrendChart: View {
let values: [Double?]
let color: Color
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var displayed: [Double?] = []
@State private var progress: CGFloat = 1
@State private var scrolling = false
var body: some View {
TrendCanvas(values: displayed, color: color, progress: progress, scrolling: scrolling)
.clipped()
.accessibilityHidden(true)
.onAppear { displayed = values; scrolling = false; progress = 1 }
.onChange(of: values) { old, new in
var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) {
scrolling = !reduceMotion && TrendScroll.isAppend(from: old, to: new)
displayed = scrolling ? old + [new.last!] : new
progress = scrolling ? 0 : 1
}
}
.task(id: values) {
guard scrolling, !reduceMotion else { return }
// Commit the starting frame before requesting interpolation; no repeating timer.
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
guard !Task.isCancelled else { return }
withAnimation(.easeInOut(duration: 0.35)) { progress = 1 }
}
.onChange(of: reduceMotion) { _, reduced in
if reduced {
var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) { displayed = values; scrolling = false; progress = 1 }
}
}
}
}
private struct TrendCanvas: View, Animatable {
let values: [Double?]
let color: Color
var progress: CGFloat
let scrolling: Bool
var animatableData: CGFloat {
get { progress }
set { progress = newValue }
}
var body: some View {
Canvas { context, size in
let values = Array(values.suffix(MetricHistory.capacity))
guard values.count > 1 else { return }
var path = Path()
var run: [CGPoint] = []
@@ -70,8 +25,7 @@ private struct TrendCanvas: View, Animatable {
}
for (index, value) in values.enumerated() {
guard let value, value.isFinite else { appendRun(); continue }
let x = size.width * TrendScroll.position(index: index, count: values.count,
progress: progress, scrolling: scrolling)
let x = size.width * CGFloat(index + MetricHistory.capacity - values.count) / CGFloat(MetricHistory.capacity - 1)
run.append(CGPoint(x: x, y: 2 + (size.height - 4) * (1 - min(1, max(0, value)))))
}
appendRun()
+17 -63
View File
@@ -1,14 +1,13 @@
import AppKit
import SwiftUI
/// Immutable paths plus compositor time-domain transforms preserve the original scrolling curve.
/// Bounded static Core Graphics paths. No animation, gradient fill or per-frame work.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
@Environment(\.metricAnimationsEnabled) private var animates
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
@@ -17,7 +16,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, animates: animates))
hoveredIndex: hoveredIndex))
}
struct Input: Equatable {
let frame: PanelCurveFrame
@@ -25,11 +24,9 @@ struct NativePanelCurve: NSViewRepresentable {
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
var animates = false
}
final class PlotView: NSView {
private(set) var input: Input?
private(set) var drawingFrame: PanelCurveFrame?
private(set) var pathBuildCount = 0
let grid = CAShapeLayer()
let curves = CALayer()
@@ -37,8 +34,6 @@ struct NativePanelCurve: NSViewRepresentable {
private var hoverDots: [CAShapeLayer] = []
private var seriesLayers: [SeriesLayer] = []
private var palette: [NSColor] = []
private let motion = MetricMotion()
var isAnimating: Bool { motion.isRunning }
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
@@ -59,43 +54,15 @@ struct NativePanelCurve: NSViewRepresentable {
let old = input
let frameChanged = old?.frame != value.frame
input = value
let animate = value.animates && !value.colors.isEmpty && !value.scales.isEmpty && window != nil && frameChanged && old.map {
guard let end = value.frame.dates.last, !value.frame.boundaryDates.contains(end) else { return false }
return PanelCurveGeometry.isAppend(from: $0.frame.dates, to: value.frame.dates, maximumGap: value.maximumGap)
} == true
CATransaction.begin(); CATransaction.setDisableActions(true)
if frameChanged {
motion.stop()
drawingFrame = animate ? PanelCurveFrame.transition(from: old!.frame, to: value.frame) : value.frame
} else if !value.animates {
motion.stop(); drawingFrame = value.frame
}
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
ensureLayers(value.frame.series.count)
if old?.colors != value.colors { updatePalette() }
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || !value.animates && old?.animates == true {
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count { updatePalette() }
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap {
rebuildPaths()
}
updateHover()
CATransaction.commit()
if animate, let old { startMovement(from: old.frame, to: value.frame) }
}
private func startMovement(from old: PanelCurveFrame, to next: PanelCurveFrame) {
guard let a = old.dates.first, let b = old.dates.last,
let c = next.dates.first, let d = next.dates.last else { return }
let previous = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: a, end: b, progress: 1)
let target = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: c, end: d, progress: 1)
let animation = CAKeyframeAnimation(keyPath: "transform")
animation.calculationMode = .linear
animation.timingFunction = CAMediaTimingFunction(name: .linear)
animation.keyTimes = (0...60).map { NSNumber(value: Double($0) / 60) }
animation.values = (0...60).map { step in
let p = MetricMotion.easeInOut(Double(step) / 60)
let map = PanelCurveFrame.horizontalTransform(from: previous, to: target, progress: p, width: bounds.width)
let transform = CGAffineTransform(a: map.scale, b: 0, c: 0, d: 1, tx: map.translation, ty: 0)
return NSValue(caTransform3D: CATransform3DMakeAffineTransform(transform))
}
motion.start(on: curves, animation: animation)
}
private func ensureLayers(_ count: Int) {
while seriesLayers.count < count {
@@ -116,7 +83,6 @@ struct NativePanelCurve: NSViewRepresentable {
for index in seriesLayers.indices {
let color = palette[min(index, palette.count - 1)], series = seriesLayers[index]
series.line.strokeColor = color.cgColor; series.points.fillColor = color.cgColor
series.gradient.colors = [color.withAlphaComponent(0.20).cgColor, color.withAlphaComponent(0.01).cgColor]
hoverDots[index].fillColor = color.cgColor
}
}
@@ -137,25 +103,25 @@ struct NativePanelCurve: NSViewRepresentable {
}
private func rebuildPaths() {
pathBuildCount += 1
guard let input, let frame = drawingFrame, let first = input.frame.dates.first, let last = input.frame.dates.last,
guard let input, let first = input.frame.dates.first, let last = input.frame.dates.last,
!input.scales.isEmpty else {
for series in seriesLayers { series.clear() }
return
}
let domain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1)
let domain = PanelCurveFrame.domain(begin: first, end: last)
let frame = input.frame
for index in frame.series.indices {
let series = seriesLayers[index]
let left = min(0, bounds.width * domain.position(frame.dates.first ?? first))
series.resize(CGRect(x: left, y: 0, width: bounds.width - left, height: bounds.height))
series.resize(bounds)
let value = input.scales[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 line = CGMutablePath(), areas = CGMutablePath(), dots = CGMutablePath()
let line = CGMutablePath(), dots = CGMutablePath()
for run in runs {
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.value / scale)))) }
guard let start = points.first, let end = points.last else { continue }
guard let start = points.first else { continue }
if points.count == 1 {
dots.addEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)); continue
}
@@ -165,15 +131,9 @@ struct NativePanelCurve: NSViewRepresentable {
segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
line.addPath(segment)
segment.addLine(to: CGPoint(x: end.x, y: bounds.height))
segment.addLine(to: CGPoint(x: start.x, y: bounds.height)); segment.closeSubpath()
areas.addPath(segment)
}
var local = CGAffineTransform(translationX: -left, y: 0)
series.line.path = line.copy(using: &local)
series.mask.path = areas.copy(using: &local)
series.points.path = dots.copy(using: &local)
series.gradient.isHidden = areas.isEmpty
series.line.path = line
series.points.path = dots
}
}
private func updateHover() {
@@ -181,7 +141,7 @@ struct NativePanelCurve: NSViewRepresentable {
hoverLine.path = nil
guard let input, !input.colors.isEmpty, let index = input.hoveredIndex, input.frame.dates.indices.contains(index),
let first = input.frame.dates.first, let last = input.frame.dates.last, last > first, !input.scales.isEmpty else { return }
let domain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1)
let domain = PanelCurveFrame.domain(begin: first, end: last)
let x = bounds.width * domain.position(input.frame.dates[index])
let path = CGMutablePath(); path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height)); hoverLine.path = path
for series in input.frame.series.indices {
@@ -196,14 +156,12 @@ struct NativePanelCurve: NSViewRepresentable {
let changed = frame.size != size
super.setFrameSize(size)
if changed {
motion.stop(); drawingFrame = input?.frame
CATransaction.begin(); CATransaction.setDisableActions(true)
updateGrid(); rebuildPaths(); updateHover(); CATransaction.commit()
}
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { motion.stop(); drawingFrame = input?.frame }
CATransaction.begin(); CATransaction.setDisableActions(true)
updatePalette(); CATransaction.commit()
}
@@ -213,21 +171,17 @@ struct NativePanelCurve: NSViewRepresentable {
updatePalette(); CATransaction.commit()
}
private final class SeriesLayer {
let root = CALayer(), line = CAShapeLayer(), mask = CAShapeLayer(), points = CAShapeLayer()
let gradient = CAGradientLayer()
let root = CALayer(), line = CAShapeLayer(), points = CAShapeLayer()
init() {
line.fillColor = nil; line.lineWidth = 1.5; line.lineCap = .round; line.lineJoin = .round
mask.fillColor = NSColor.white.cgColor
gradient.startPoint = CGPoint(x: 0.5, y: 0); gradient.endPoint = CGPoint(x: 0.5, y: 1)
gradient.locations = [0, 1]; gradient.mask = mask
root.addSublayer(gradient); root.addSublayer(line); root.addSublayer(points)
root.addSublayer(line); root.addSublayer(points)
}
func resize(_ bounds: CGRect) {
root.frame = bounds
let local = CGRect(origin: .zero, size: bounds.size)
gradient.frame = local; mask.frame = local; line.frame = local; points.frame = local
line.frame = local; points.frame = local
}
func clear() { line.path = nil; mask.path = nil; points.path = nil }
func clear() { line.path = nil; points.path = nil }
}
}
}
+3 -34
View File
@@ -1,6 +1,6 @@
import Foundation
/// A render frame may keep one outgoing point beyond the bounded 60-sample history.
/// A static render frame follows the bounded sampling history without outgoing points.
nonisolated struct PanelCurveFrame: Equatable {
let dates: [Date]
let series: [[Double?]]
@@ -15,38 +15,7 @@ nonisolated struct PanelCurveFrame: Equatable {
}
}
static func domain(previousBegin: Date?, previousEnd: Date?, begin: Date, end: Date, progress: Double) -> Domain {
let progress = min(1, max(0, progress))
return Domain(begin: (previousBegin ?? begin).timeIntervalSinceReferenceDate * (1 - progress) + begin.timeIntervalSinceReferenceDate * progress,
end: (previousEnd ?? end).timeIntervalSinceReferenceDate * (1 - progress) + end.timeIntervalSinceReferenceDate * progress)
}
struct HorizontalTransform {
let scale: Double
let translation: Double
}
/// Render paths once in the final domain, then map them into the original
/// interpolated time domain. This preserves expansion as well as translation.
static func horizontalTransform(from old: Domain, to target: Domain, progress: Double, width: Double) -> HorizontalTransform {
let p = min(1, max(0, progress))
let begin = old.begin * (1 - p) + target.begin * p
let end = old.end * (1 - p) + target.end * p
let span = end - begin, finalSpan = target.end - target.begin
guard span.isFinite, span > 0, finalSpan.isFinite, finalSpan > 0, width.isFinite else { return HorizontalTransform(scale: 1, translation: 0) }
return HorizontalTransform(scale: finalSpan / span, translation: (target.begin - begin) / span * width)
}
static func transition(from old: Self, to new: Self) -> Self {
guard old.dates.count > 1, old.dates.count == new.dates.count,
Array(old.dates.dropFirst()) == Array(new.dates.dropLast()),
let outgoing = old.dates.first else { return new }
let series = new.series.enumerated().map { index, values -> [Double?] in
let previous = index < old.series.count ? old.series[index] : []
return previous.isEmpty && values.isEmpty ? [] : [previous.first ?? nil] + values
}
return Self(dates: [outgoing] + new.dates, series: series,
intervals: [old.intervals.first ?? 2] + new.intervals,
boundaryDates: new.boundaryDates.union(old.boundaryDates.intersection([outgoing])))
static func domain(begin: Date, end: Date) -> Domain {
Domain(begin: begin.timeIntervalSinceReferenceDate, end: end.timeIntervalSinceReferenceDate)
}
}
-7
View File
@@ -6,13 +6,6 @@ nonisolated enum PanelCurveGeometry {
let value: Double
}
static func isAppend(from old: [Date], to new: [Date], maximumGap: TimeInterval = 5) -> Bool {
guard old.count > 1, let previous = old.last, let next = new.last,
next > previous, next.timeIntervalSince(previous) <= maximumGap 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 allowedGap(at index: Int, intervals: [TimeInterval], fallback: TimeInterval) -> TimeInterval {
guard index > 0, index < intervals.count else { return fallback }
let pair = [intervals[index - 1], intervals[index]].filter { $0.isFinite && $0 > 0 }
+4 -3
View File
@@ -41,7 +41,9 @@ struct PanelTrendChart: View {
@State private var hoverPoint: CGPoint?
private var inputFrame: PanelCurveFrame {
PanelCurveFrame(dates: dates, series: [first, second, third, fourth],
var series = [first, second, third, fourth]
while series.last?.isEmpty == true { series.removeLast() }
return PanelCurveFrame(dates: dates, series: series,
intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count),
boundaryDates: boundaryDates)
}
@@ -98,9 +100,8 @@ struct PanelTrendChart: View {
if !fourth.isEmpty { tooltipRow(fourthLabel, values: fourth, tint: fourthColor, index: index) }
}
.font(.system(size: 10)).padding(8)
.background { TooltipMaterialBackground() }
.background { TooltipBackground() }
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2)))
.shadow(color: .black.opacity(0.2), radius: 5, y: 2)
}
var body: some View {
-18
View File
@@ -1,18 +0,0 @@
import Foundation
/// Geometry for a single appended sample, including the outgoing point at full capacity.
nonisolated enum TrendScroll {
static func isAppend(from old: [Double?], to new: [Double?]) -> Bool {
guard !old.isEmpty, !new.isEmpty else { return false }
if old.count < MetricHistory.capacity {
return new.count == old.count + 1 && Array(new.dropLast()) == old
}
return new.count == old.count && Array(old.dropFirst()) == Array(new.dropLast())
}
static func position(index: Int, count: Int, progress: CGFloat, scrolling: Bool) -> CGFloat {
let offset = MetricHistory.capacity - count
let shift = scrolling ? 1 - min(1, max(0, progress)) : 0
return (CGFloat(index + offset) + shift) / CGFloat(MetricHistory.capacity - 1)
}
}
@@ -1,34 +0,0 @@
import SwiftUI
/// Short numeric transitions follow the owner-supplied motion policy.
struct AnimatedMetricText: View {
let value: String
@Environment(\.metricAnimationsEnabled) private var animates
var body: some View {
if animates {
RollingMetricText(value: value).equatable()
} else {
Text(verbatim: value).monospacedDigit()
}
}
}
/// Same numeric roll/blur and spring as the original implementation. Unchanged values
/// do not rebuild this subtree when the surrounding resource snapshot changes.
private struct RollingMetricText: View, Equatable {
let value: String
var body: some View {
Text(verbatim: value).monospacedDigit()
.contentTransition(.numericText())
.animation(.spring(duration: 0.35, bounce: 0), value: value)
}
}
struct PanelCardBackground: ViewModifier {
let radius: CGFloat
func body(content: Content) -> some View {
content.background(RoundedRectangle(cornerRadius: radius).fill(Color("PanelCard")))
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ struct FanSpeedIndicator: View {
.frame(width: 14, height: 14).accessibilityHidden(true)
title.foregroundStyle(.secondary)
Spacer(minLength: 2)
AnimatedMetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
MetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
.monospacedDigit().fontWeight(.medium)
}
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.7)
+5 -43
View File
@@ -64,33 +64,20 @@ struct HoverDetailPresenter<Detail: View>: NSViewRepresentable {
.padding(12)
.frame(width: 280)
.fixedSize(horizontal: false, vertical: true)
.modifier(DetailEntrance())
.background(Color("PanelCard"), in: .rect(cornerRadius: 12))
.overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(.primary.opacity(0.14)))
.onHover { [weak self] inside in self?.onHover(inside) })
if panel == nil {
let panel = DetailPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
panel.isReleasedWhenClosed = false
panel.isOpaque = false
panel.backgroundColor = .clear
panel.hasShadow = true
panel.hasShadow = false
panel.animationBehavior = .none
panel.hidesOnDeactivate = false
panel.level = parent.level
let material = NSVisualEffectView()
material.material = .menu
material.blendingMode = .behindWindow
material.state = .active
material.wantsLayer = true
material.layer?.cornerRadius = 12
material.layer?.masksToBounds = true
let host = NSHostingView(rootView: content)
host.translatesAutoresizingMaskIntoConstraints = false
material.addSubview(host)
NSLayoutConstraint.activate([
host.leadingAnchor.constraint(equalTo: material.leadingAnchor),
host.trailingAnchor.constraint(equalTo: material.trailingAnchor),
host.topAnchor.constraint(equalTo: material.topAnchor),
host.bottomAnchor.constraint(equalTo: material.bottomAnchor)
])
panel.contentView = material
panel.contentView = host
self.panel = panel
self.host = host
parent.addChildWindow(panel, ordered: .above)
@@ -124,28 +111,3 @@ struct HoverDetailPresenter<Detail: View>: NSViewRepresentable {
override var canBecomeMain: Bool { false }
}
}
/// One entrance per mounted child panel; sampling updates retain the revealed state.
private struct DetailEntrance: ViewModifier {
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var revealed = false
func body(content: Content) -> some View {
content
.opacity(revealed || reduceMotion ? 1 : 0)
.scaleEffect(revealed || reduceMotion ? 1 : 0.97)
.task {
guard !reduceMotion else { revealed = true; return }
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
guard !Task.isCancelled else { return }
withAnimation(.spring(duration: 0.2, bounce: 0)) { revealed = true }
}
.onChange(of: reduceMotion) { _, reduced in
if reduced {
var transaction = Transaction()
transaction.disablesAnimations = true
withTransaction(transaction) { revealed = true }
}
}
}
}
-105
View File
@@ -1,105 +0,0 @@
import SwiftUI
import QuartzCore
private struct MetricAnimationsKey: EnvironmentKey {
static let defaultValue = false
}
extension EnvironmentValues {
var metricAnimationsEnabled: Bool {
get { self[MetricAnimationsKey.self] }
set { self[MetricAnimationsKey.self] = newValue }
}
}
/// Finite property animations; no opacity substitution or per-frame CPU timer.
@MainActor final class MetricMotion {
static let duration: TimeInterval = 0.35
static let key = "kymo.metric.movement"
private weak var layer: CALayer?
private static let cleanup = MotionCleanup()
var isRunning: Bool { layer?.animation(forKey: Self.key) != nil }
func start(on layer: CALayer?, animation: CAAnimation) {
stop()
guard let layer else { return }
self.layer = layer
animation.duration = Self.duration
animation.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil)
animation.isRemovedOnCompletion = true
layer.add(animation, forKey: Self.key)
// Backing layers may retain completed animations. Bound their lifetime explicitly.
Self.cleanup.register(self)
}
/// Cubic timing curve used by the original SwiftUI easeInOut animation.
static func easeInOut(_ time: Double) -> Double {
let time = min(1, max(0, time))
var low = 0.0, high = 1.0
for _ in 0..<24 {
let u = (low + high) / 2, v = 1 - u
let x = 3 * v * v * u * 0.42 + 3 * v * u * u * 0.58 + u * u * u
if x < time { low = u } else { high = u }
}
let u = (low + high) / 2
return 3 * (1 - u) * u * u + u * u * u
}
func stop() {
Self.cleanup.remove(self)
finish()
}
fileprivate func finish() {
layer?.removeAnimation(forKey: Self.key); layer = nil
}
}
/// One one-shot timer serves the whole visible batch, retaining neither views nor motions.
@MainActor private final class MotionCleanup {
private struct Entry {
weak var motion: MetricMotion?
let deadline: DispatchTime
}
private var entries: [ObjectIdentifier: Entry] = [:]
private var timer: DispatchSourceTimer?
private var scheduled: UInt64?
func register(_ motion: MetricMotion) {
entries[ObjectIdentifier(motion)] = Entry(motion: motion, deadline: .now() + MetricMotion.duration)
schedule()
}
func remove(_ motion: MetricMotion) {
guard entries.removeValue(forKey: ObjectIdentifier(motion)) != nil else { return }
schedule()
}
private func schedule() {
guard let first = entries.values.map(\.deadline.uptimeNanoseconds).min() else {
timer?.cancel(); timer = nil; scheduled = nil
return
}
// Core Animation ends at 350 ms. Group nearby cleanup deadlines 10 ms later.
let deadline = first + 10_000_000
guard scheduled != deadline else { return }
scheduled = deadline
let newTimer = timer == nil
if newTimer {
let source = DispatchSource.makeTimerSource(queue: .main)
source.setEventHandler { [weak self] in MainActor.assumeIsolated { self?.complete() } }
timer = source
}
timer?.schedule(deadline: DispatchTime(uptimeNanoseconds: deadline), leeway: .milliseconds(10))
if newTimer { timer?.resume() }
}
private func complete() {
let now = DispatchTime.now().uptimeNanoseconds
let expired = entries.filter { $0.value.motion == nil || $0.value.deadline.uptimeNanoseconds <= now }
for (id, entry) in expired {
entries.removeValue(forKey: id)
entry.motion?.finish()
}
scheduled = nil
schedule()
}
}
+1 -3
View File
@@ -4,7 +4,6 @@ import SwiftUI
struct MetricProgressBar: View {
let value: Double
let color: Color
@Environment(\.metricAnimationsEnabled) private var animates
private var fraction: Double { value.isFinite ? min(1, max(0, value)) : 0 }
@@ -16,8 +15,7 @@ struct MetricProgressBar: View {
}
.frame(width: proxy.size.width, height: proxy.size.height)
.clipShape(Capsule())
.animation(animates ? .easeInOut(duration: MetricMotion.duration) : nil, value: fraction)
.transaction { if !animates { $0.disablesAnimations = true } }
.transaction { $0.animation = nil; $0.disablesAnimations = true }
}
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ struct MetricRingGauge: View {
VStack(spacing: 3) {
ZStack {
NativeMetricRing(value: fraction, color: color, lineWidth: 3, trackOpacity: 0.17, inset: 2)
AnimatedMetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold))
MetricText(value: MetricFormat.percent(value)).font(.system(size: 8, weight: .semibold))
.lineLimit(1).minimumScaleFactor(0.6).frame(width: 18, height: 12)
}.frame(width: 28, height: 28).accessibilityHidden(true)
Text(title).font(.system(size: 8)).foregroundStyle(.secondary)
+1 -3
View File
@@ -8,7 +8,6 @@ struct MetricRow<Detail: View>: View {
let history: [Double?]
let accent: Color
@ViewBuilder let detail: () -> Detail
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@State private var visible = false
@State private var rowHovered = false
@State private var detailHovered = false
@@ -33,7 +32,6 @@ struct MetricRow<Detail: View>: View {
Text(verbatim: value)
.font(.system(size: 13, weight: .semibold, design: .rounded))
.monospacedDigit()
.contentTransition(.numericText())
.frame(width: 46, alignment: .trailing)
}
.contentShape(Rectangle())
@@ -56,6 +54,6 @@ struct MetricRow<Detail: View>: View {
}
.onAppear { visible = true }
.onDisappear { visible = false; rowHovered = false; detailHovered = false; expanded = false }
.animation(!visible || reduceMotion ? nil : .spring(duration: 0.3, bounce: 0), value: value)
.transaction { $0.animation = nil; $0.disablesAnimations = true }
}
}
+15
View File
@@ -0,0 +1,15 @@
import SwiftUI
/// Metrics change only when a new sample is published; no numeric transition or spring.
struct MetricText: View {
let value: String
var body: some View { Text(verbatim: value).monospacedDigit() }
}
struct PanelCardBackground: ViewModifier {
let radius: CGFloat
func body(content: Content) -> some View {
content.background(RoundedRectangle(cornerRadius: radius).fill(Color("PanelCard")))
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
import AppKit
import SwiftUI
/// Keeps local animation rendering inside a fixed-size child host.
/// Keeps card rendering inside a fixed-size child host.
struct NativeContentHost<Content: View>: NSViewRepresentable {
let content: Content
+2 -23
View File
@@ -1,14 +1,13 @@
import AppKit
import SwiftUI
/// Arc geometry is submitted once; the compositor interpolates strokeEnd continuously.
/// Static arc geometry; sampling publishes the final value directly.
struct NativeMetricRing: NSViewRepresentable {
let value: Double
let color: Color
let lineWidth: CGFloat
let trackOpacity: Double
let inset: CGFloat
@Environment(\.metricAnimationsEnabled) private var animates
func sizeThatFits(_ proposal: ProposedViewSize, nsView: RingView, context: Context) -> CGSize? {
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
@@ -17,7 +16,7 @@ struct NativeMetricRing: NSViewRepresentable {
func makeNSView(context: Context) -> RingView { RingView() }
func updateNSView(_ view: RingView, context: Context) {
view.configure(Input(value: value.isFinite ? min(1, max(0, value)) : 0, color: color,
lineWidth: lineWidth, trackOpacity: trackOpacity, inset: inset, animates: animates))
lineWidth: lineWidth, trackOpacity: trackOpacity, inset: inset))
}
struct Input: Equatable {
let value: Double
@@ -25,18 +24,11 @@ struct NativeMetricRing: NSViewRepresentable {
let lineWidth: CGFloat
let trackOpacity: Double
let inset: CGFloat
var animates = false
}
final class RingView: NSView {
private(set) var input: Input?
let track = CAShapeLayer()
let arc = CAShapeLayer()
private let motion = MetricMotion()
var isAnimating: Bool { motion.isRunning }
var displayedValue: Double {
if isAnimating, let presentation = arc.presentation() { return Double(presentation.strokeEnd) }
return Double(arc.strokeEnd)
}
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
init() {
@@ -52,23 +44,12 @@ struct NativeMetricRing: NSViewRepresentable {
func configure(_ value: Input) {
guard value != input else { return }
let old = input
let start = displayedValue
input = value
CATransaction.begin(); CATransaction.setDisableActions(true)
if old?.color != value.color || old?.trackOpacity != value.trackOpacity { updateColors() }
if old?.inset != value.inset || old?.lineWidth != value.lineWidth { updateGeometry() }
arc.strokeEnd = value.value
CATransaction.commit()
if !value.animates { motion.stop() }
else if old?.value != value.value {
motion.stop()
if old != nil, window != nil, start != value.value {
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.fromValue = start; animation.toValue = value.value
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
motion.start(on: arc, animation: animation)
}
}
}
private func updateColors() {
guard let input else { return }
@@ -92,14 +73,12 @@ struct NativeMetricRing: NSViewRepresentable {
let changed = frame.size != size
super.setFrameSize(size)
if changed {
motion.stop()
CATransaction.begin(); CATransaction.setDisableActions(true)
updateGeometry(); CATransaction.commit()
}
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window == nil { motion.stop() }
CATransaction.begin(); CATransaction.setDisableActions(true)
updateColors(); CATransaction.commit()
}
+2 -2
View File
@@ -81,7 +81,7 @@ struct CapacityField: View {
Circle().fill(color).frame(width: 4, height: 4)
Text(title).font(PanelStyle.label).foregroundStyle(.secondary)
}.frame(height: 14)
AnimatedMetricText(value: value).font(PanelStyle.value).frame(height: 14)
MetricText(value: value).font(PanelStyle.value).frame(height: 14)
}
.frame(maxWidth: .infinity, alignment: .leading)
.lineLimit(1)
@@ -99,7 +99,7 @@ struct CardSectionHeader: View {
Text(title).font(PanelStyle.section)
Spacer(minLength: 4)
Text(valueLabel).font(PanelStyle.label).foregroundStyle(.secondary)
AnimatedMetricText(value: value).font(PanelStyle.value).foregroundStyle(color)
MetricText(value: value).font(PanelStyle.value).foregroundStyle(color)
}.frame(height: 16)
}
}
+2 -2
View File
@@ -47,11 +47,11 @@ struct ResourceCard<Content: View>: View {
}
Spacer(minLength: 0)
HStack(alignment: .center, spacing: 6) {
AnimatedMetricText(value: value)
MetricText(value: value)
.font(PanelStyle.title)
.foregroundStyle(valueColor ?? color)
if let secondaryValue {
AnimatedMetricText(value: secondaryValue).font(PanelStyle.title)
MetricText(value: secondaryValue).font(PanelStyle.title)
.foregroundStyle(secondaryValueColor ?? color)
}
}.foregroundStyle(color).lineLimit(1)
@@ -0,0 +1,8 @@
import SwiftUI
/// Opaque semantic surface; no backdrop material, blur or shadow.
struct TooltipBackground: View {
var body: some View {
RoundedRectangle(cornerRadius: 7).fill(Color("PanelTooltip"))
}
}
@@ -1,31 +0,0 @@
import SwiftUI
import AppKit
/// Within-window blending blurs the chart and labels below the card's root overlay.
struct TooltipMaterialBackground: View {
@Environment(\.accessibilityReduceTransparency) private var reduceTransparency
var body: some View {
Group {
if reduceTransparency { Color(nsColor: .windowBackgroundColor) }
else {
WithinWindowMaterial()
.overlay(Color("PanelTooltip").opacity(0.12))
}
}.clipShape(.rect(cornerRadius: 7))
}
}
private struct WithinWindowMaterial: NSViewRepresentable {
func makeNSView(context: Context) -> NSVisualEffectView {
let view = PassthroughVisualEffectView()
view.material = .popover
view.blendingMode = .withinWindow
view.state = .active
return view
}
func updateNSView(_ view: NSVisualEffectView, context: Context) {}
}
private final class PassthroughVisualEffectView: NSVisualEffectView {
override func hitTest(_ point: NSPoint) -> NSView? { nil }
}