perf(ui): 恢复数字滚动并优化曲线与圆环连续动效
This commit is contained in:
@@ -7,15 +7,24 @@ struct AnimatedMetricText: View {
|
||||
|
||||
var body: some View {
|
||||
if animates {
|
||||
Text(verbatim: value).monospacedDigit()
|
||||
.contentTransition(.opacity)
|
||||
.animation(.easeInOut(duration: MetricMotion.duration), value: value)
|
||||
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
|
||||
|
||||
|
||||
@@ -5,40 +5,48 @@ private struct MetricAnimationsKey: EnvironmentKey {
|
||||
static let defaultValue = false
|
||||
}
|
||||
extension EnvironmentValues {
|
||||
/// The owner supplies actual visibility and user/system motion policy.
|
||||
var metricAnimationsEnabled: Bool {
|
||||
get { self[MetricAnimationsKey.self] }
|
||||
set { self[MetricAnimationsKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// A finite compositor transition; native controls never create per-frame CPU timers.
|
||||
/// Finite property animations; no opacity substitution or per-frame CPU timer.
|
||||
@MainActor final class MetricMotion {
|
||||
static let duration: TimeInterval = 0.25
|
||||
static let duration: TimeInterval = 0.35
|
||||
static let key = "kymo.metric.movement"
|
||||
private weak var layer: CALayer?
|
||||
private var deadline: DispatchSourceTimer?
|
||||
// Core Animation stores every CATransition under this reserved key.
|
||||
private static let key = kCATransition
|
||||
var isRunning: Bool { layer?.animation(forKey: Self.key) != nil }
|
||||
|
||||
func start(on layer: CALayer?) {
|
||||
func start(on layer: CALayer?, animation: CAAnimation) {
|
||||
stop()
|
||||
guard let layer else { return }
|
||||
self.layer = layer
|
||||
let transition = CATransition()
|
||||
transition.type = .fade
|
||||
transition.duration = Self.duration
|
||||
transition.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
|
||||
transition.isRemovedOnCompletion = true
|
||||
layer.add(transition, forKey: Self.key)
|
||||
// AppKit backing layers can retain a finished transition; enforce a finite lifetime.
|
||||
// One coalescible cleanup deadline, never a per-frame CPU callback.
|
||||
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.
|
||||
let deadline = DispatchSource.makeTimerSource(queue: .main)
|
||||
deadline.schedule(deadline: .now() + Self.duration, leeway: .milliseconds(10))
|
||||
deadline.setEventHandler { [weak self] in MainActor.assumeIsolated { self?.stop() } }
|
||||
self.deadline = deadline
|
||||
deadline.resume()
|
||||
}
|
||||
/// 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() {
|
||||
deadline?.cancel(); deadline = nil
|
||||
layer?.removeAnimation(forKey: Self.key); layer = nil
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Small Core Graphics arcs avoid creating a SwiftUI path-rendering surface for every gauge.
|
||||
/// Arc geometry is submitted once; the compositor interpolates strokeEnd continuously.
|
||||
struct NativeMetricRing: NSViewRepresentable {
|
||||
let value: Double
|
||||
let color: Color
|
||||
@@ -11,11 +11,9 @@ struct NativeMetricRing: NSViewRepresentable {
|
||||
@Environment(\.metricAnimationsEnabled) private var animates
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: RingView, context: Context) -> CGSize? {
|
||||
// Owners supply explicit geometry; do not query AppKit's intrinsic layout on every update.
|
||||
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
|
||||
height: proposal.height.flatMap { $0.isFinite ? $0 : nil } ?? 10)
|
||||
}
|
||||
|
||||
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,
|
||||
@@ -31,57 +29,84 @@ struct NativeMetricRing: NSViewRepresentable {
|
||||
}
|
||||
final class RingView: NSView {
|
||||
private(set) var input: Input?
|
||||
private(set) var displayedValue = 0.0
|
||||
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() {
|
||||
super.init(frame: .zero)
|
||||
wantsLayer = true; layerContentsRedrawPolicy = .onSetNeedsDisplay
|
||||
wantsLayer = true
|
||||
for shape in [track, arc] {
|
||||
shape.fillColor = nil; shape.lineCap = .round
|
||||
layer?.addSublayer(shape)
|
||||
}
|
||||
setAccessibilityElement(false)
|
||||
}
|
||||
required init?(coder: NSCoder) { nil }
|
||||
func configure(_ value: Input) {
|
||||
guard value != input else { return }
|
||||
let previous = input
|
||||
let old = input
|
||||
let start = displayedValue
|
||||
input = value
|
||||
displayedValue = value.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 previous?.value != value.value {
|
||||
else if old?.value != value.value {
|
||||
motion.stop()
|
||||
if previous != nil, window != nil { motion.start(on: layer) }
|
||||
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 }
|
||||
effectiveAppearance.performAsCurrentDrawingAppearance {
|
||||
let color = NSColor(input.color)
|
||||
track.strokeColor = color.withAlphaComponent(input.trackOpacity).cgColor
|
||||
arc.strokeColor = color.cgColor
|
||||
}
|
||||
}
|
||||
private func updateGeometry() {
|
||||
guard let input else { return }
|
||||
let radius = max(0, min(bounds.width, bounds.height) / 2 - input.inset)
|
||||
let path = CGMutablePath()
|
||||
path.addArc(center: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius,
|
||||
startAngle: -.pi / 2, endAngle: 3 * .pi / 2, clockwise: false)
|
||||
for shape in [track, arc] {
|
||||
shape.frame = bounds; shape.path = path; shape.lineWidth = input.lineWidth
|
||||
}
|
||||
}
|
||||
override func setFrameSize(_ size: NSSize) {
|
||||
let changed = frame.size != size
|
||||
super.setFrameSize(size)
|
||||
if changed {
|
||||
motion.stop()
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
updateGeometry(); CATransaction.commit()
|
||||
}
|
||||
needsDisplay = true
|
||||
}
|
||||
private func settle() { motion.stop(); displayedValue = input?.value ?? 0; needsDisplay = true }
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
if window == nil { settle() }
|
||||
}
|
||||
override func setFrameSize(_ newSize: NSSize) {
|
||||
let changed = newSize != frame.size
|
||||
super.setFrameSize(newSize)
|
||||
if changed { needsDisplay = true }
|
||||
if window == nil { motion.stop() }
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
updateColors(); CATransaction.commit()
|
||||
}
|
||||
override func viewDidChangeEffectiveAppearance() {
|
||||
super.viewDidChangeEffectiveAppearance(); needsDisplay = true
|
||||
}
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
guard let input, let context = NSGraphicsContext.current?.cgContext else { return }
|
||||
let radius = max(0, min(bounds.width, bounds.height) / 2 - input.inset)
|
||||
guard radius > 0 else { return }
|
||||
let center = CGPoint(x: bounds.midX, y: bounds.midY)
|
||||
let tint = NSColor(input.color)
|
||||
context.saveGState(); defer { context.restoreGState() }
|
||||
context.setLineWidth(input.lineWidth); context.setLineCap(.round)
|
||||
context.setStrokeColor(tint.withAlphaComponent(input.trackOpacity).cgColor)
|
||||
context.strokeEllipse(in: CGRect(x: center.x - radius, y: center.y - radius, width: radius * 2, height: radius * 2))
|
||||
guard displayedValue > 0 else { return }
|
||||
context.setStrokeColor(tint.cgColor)
|
||||
context.addArc(center: center, radius: radius, startAngle: -.pi / 2,
|
||||
endAngle: -.pi / 2 + 2 * .pi * displayedValue, clockwise: false)
|
||||
context.strokePath()
|
||||
super.viewDidChangeEffectiveAppearance()
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
updateColors(); CATransaction.commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user