fix(charts): 修复浮窗层级并平滑切频与曲线移出
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import SwiftUI
|
||||
|
||||
/// Charts export their plot anchor; the owning card draws the tooltip above all content.
|
||||
struct ChartTooltipPresentation {
|
||||
let plot: Anchor<CGRect>
|
||||
let point: CGPoint
|
||||
let content: AnyView
|
||||
}
|
||||
|
||||
struct ChartTooltipPreference: PreferenceKey {
|
||||
static var defaultValue: ChartTooltipPresentation? { nil }
|
||||
static func reduce(value: inout ChartTooltipPresentation?, nextValue: () -> ChartTooltipPresentation?) {
|
||||
if let next = nextValue() { value = next }
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures the actual localized tooltip, then keeps it inside the card.
|
||||
struct ChartTooltipLayer: Layout {
|
||||
let point: CGPoint
|
||||
|
||||
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
|
||||
proposal.replacingUnspecifiedDimensions()
|
||||
}
|
||||
|
||||
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
|
||||
guard let tooltip = subviews.first else { return }
|
||||
let width = min(180, max(1, bounds.width - 20))
|
||||
let tooltipProposal = ProposedViewSize(width: width, height: nil)
|
||||
let size = tooltip.sizeThatFits(tooltipProposal)
|
||||
let x = min(max(10, point.x + 12), max(10, bounds.width - size.width - 10))
|
||||
let below = point.y + 10
|
||||
let preferredY = below + size.height <= bounds.height - 10 ? below : point.y - size.height - 10
|
||||
let y = min(max(10, preferredY), max(10, bounds.height - size.height - 10))
|
||||
tooltip.place(at: CGPoint(x: bounds.minX + x, y: bounds.minY + y), anchor: .topLeading, proposal: tooltipProposal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Foundation
|
||||
|
||||
/// A render frame may keep one outgoing point beyond the bounded 60-sample history.
|
||||
nonisolated struct PanelCurveFrame {
|
||||
let dates: [Date]
|
||||
let series: [[Double?]]
|
||||
let intervals: [TimeInterval]
|
||||
let boundaryDates: Set<Date>
|
||||
|
||||
struct Domain {
|
||||
let begin: TimeInterval
|
||||
let end: TimeInterval
|
||||
func position(_ date: Date) -> Double {
|
||||
end > begin ? (date.timeIntervalSinceReferenceDate - begin) / (end - begin) : 1
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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])))
|
||||
}
|
||||
}
|
||||
@@ -13,13 +13,19 @@ nonisolated enum PanelCurveGeometry {
|
||||
return new.count == old.count && Array(old.dropFirst()) == Array(new.dropLast())
|
||||
}
|
||||
|
||||
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = []) -> [[Sample]] {
|
||||
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 }
|
||||
return pair.isEmpty ? fallback : max(5, (pair.max() ?? 2) * 2)
|
||||
}
|
||||
|
||||
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = []) -> [[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 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > maximumGap || dates[index] <= dates[index - 1]) { flush() }
|
||||
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() }
|
||||
run.append(Sample(date: dates[index], value: value))
|
||||
}
|
||||
flush()
|
||||
|
||||
@@ -16,6 +16,7 @@ struct PanelTrendChart: View {
|
||||
var thirdLabel: LocalizedStringKey = "cpu.system"
|
||||
var expectedInterval: TimeInterval = 2
|
||||
var boundaryDates: Set<Date> = []
|
||||
var intervals: [TimeInterval] = []
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
@State private var retainedScale: Double = 1
|
||||
@State private var smallSamples = 0
|
||||
@@ -24,7 +25,14 @@ struct PanelTrendChart: View {
|
||||
@State private var previousBegin: Date?
|
||||
@State private var previousEnd: Date?
|
||||
@State private var progress: CGFloat = 1
|
||||
@State private var lastFrame: PanelCurveFrame?
|
||||
@State private var displayedFrame: PanelCurveFrame?
|
||||
|
||||
private var inputFrame: PanelCurveFrame {
|
||||
PanelCurveFrame(dates: dates, series: [first, second, third],
|
||||
intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count),
|
||||
boundaryDates: boundaryDates)
|
||||
}
|
||||
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? {
|
||||
@@ -62,7 +70,7 @@ struct PanelTrendChart: View {
|
||||
if !third.isEmpty { tooltipRow(thirdLabel, values: third, tint: thirdColor, index: index) }
|
||||
}
|
||||
.font(.system(size: 10)).padding(8)
|
||||
.background(Color("PanelTooltip"), in: .rect(cornerRadius: 7))
|
||||
.background { TooltipMaterialBackground() }
|
||||
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(.primary.opacity(0.2)))
|
||||
.shadow(color: .black.opacity(0.2), radius: 5, y: 2)
|
||||
}
|
||||
@@ -86,8 +94,10 @@ struct PanelTrendChart: View {
|
||||
.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, maximumGap: max(5, expectedInterval * 2), boundaryDates: boundaryDates, previousBegin: previousBegin, previousEnd: previousEnd, progress: progress)
|
||||
PanelCurveCanvas(frame: displayedFrame ?? inputFrame, colors: [color, secondColor, thirdColor],
|
||||
scale: scale, maximumGap: max(5, expectedInterval * 2),
|
||||
targetBegin: (lastFrame ?? inputFrame).dates.first, targetEnd: (lastFrame ?? inputFrame).dates.last,
|
||||
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
|
||||
@@ -114,17 +124,11 @@ struct PanelTrendChart: View {
|
||||
}
|
||||
}
|
||||
.clipped()
|
||||
.overlay(alignment: .topLeading) {
|
||||
if let hoverPoint, let index {
|
||||
tooltip(index: index)
|
||||
.frame(width: min(180, proxy.size.width))
|
||||
.offset(x: min(max(0, hoverPoint.x + 12), max(0, proxy.size.width - 180)),
|
||||
y: min(hoverPoint.y + 10, proxy.size.height - 12))
|
||||
.allowsHitTesting(false)
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
}.frame(height: 58).zIndex(10)
|
||||
}.frame(height: 58)
|
||||
.anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { plot in
|
||||
guard let hoverPoint, let index else { return nil }
|
||||
return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index)))
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
if let date = dates.first { Text(date, style: .time) }
|
||||
@@ -133,40 +137,47 @@ struct PanelTrendChart: View {
|
||||
}.font(.system(size: 9)).foregroundStyle(.secondary).frame(height: 12)
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.zIndex(hoveredDate == nil ? 0 : 20)
|
||||
.onAppear { retainedScale = maximum }
|
||||
.onChange(of: dates) { old, new in
|
||||
.onAppear { retainedScale = maximum; lastFrame = inputFrame; displayedFrame = inputFrame }
|
||||
.onChange(of: dates) { _, _ 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, maximumGap: max(5, expectedInterval * 2)) && !(new.last.map { boundaryDates.contains($0) } ?? false)
|
||||
let next = inputFrame
|
||||
let old = lastFrame
|
||||
let gap = PanelCurveGeometry.allowedGap(at: next.dates.count - 1, intervals: next.intervals, fallback: max(5, expectedInterval * 2))
|
||||
let append = old.map { PanelCurveGeometry.isAppend(from: $0.dates, to: next.dates, maximumGap: gap) } == true
|
||||
&& !(next.dates.last.map { boundaryDates.contains($0) } ?? false)
|
||||
let animated = append && !reduceMotion
|
||||
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
|
||||
lastFrame = next
|
||||
displayedFrame = next
|
||||
if animated, let old { displayedFrame = PanelCurveFrame.transition(from: old, to: next) }
|
||||
previousBegin = animated ? old?.dates.first : nil
|
||||
previousEnd = animated ? old?.dates.last : nil
|
||||
progress = animated ? 0 : 1
|
||||
}
|
||||
}
|
||||
.task(id: dates.last) {
|
||||
.task(id: lastFrame?.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 } }
|
||||
.onChange(of: reduceMotion) { _, reduced in if reduced { progress = 1; previousBegin = nil; previousEnd = nil; lastFrame = inputFrame; displayedFrame = inputFrame } }
|
||||
.accessibilityElement(children: .combine)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PanelCurveCanvas: View, Animatable {
|
||||
let dates: [Date]
|
||||
let series: [[Double?]]
|
||||
let frame: PanelCurveFrame
|
||||
let colors: [Color]
|
||||
let scale: Double
|
||||
let maximumGap: TimeInterval
|
||||
let boundaryDates: Set<Date>
|
||||
let targetBegin: Date?
|
||||
let targetEnd: Date?
|
||||
let previousBegin: Date?
|
||||
let previousEnd: Date?
|
||||
var progress: CGFloat
|
||||
@@ -187,14 +198,14 @@ private struct PanelCurveCanvas: View, Animatable {
|
||||
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 (seriesIndex, entry) in zip(series, colors).enumerated() {
|
||||
guard let first = targetBegin, let last = targetEnd else { return }
|
||||
let domain = PanelCurveFrame.domain(previousBegin: previousBegin, previousEnd: previousEnd,
|
||||
begin: first, end: last, progress: Double(progress))
|
||||
for (seriesIndex, entry) in zip(frame.series, colors).enumerated() {
|
||||
let (values, tint) = entry
|
||||
for run in PanelCurveGeometry.runs(dates: dates, values: values, maximumGap: maximumGap, boundaryDates: boundaryDates) {
|
||||
for run in PanelCurveGeometry.runs(dates: frame.dates, values: values, maximumGap: maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) {
|
||||
let points = run.map { item in
|
||||
CGPoint(x: end > begin ? size.width * (item.date.timeIntervalSinceReferenceDate - begin) / (end - begin) : size.width,
|
||||
CGPoint(x: size.width * domain.position(item.date),
|
||||
y: size.height * (1 - min(1, max(0, item.value / scale))))
|
||||
}
|
||||
guard let start = points.first, let finish = points.last else { continue }
|
||||
|
||||
@@ -30,5 +30,18 @@ struct ResourceCard<Content: View>: View {
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
.modifier(PanelCardBackground(radius: 10))
|
||||
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14)))
|
||||
.overlayPreferenceValue(ChartTooltipPreference.self) { tooltip in
|
||||
GeometryReader { proxy in
|
||||
if let tooltip {
|
||||
let plot = proxy[tooltip.plot]
|
||||
ChartTooltipLayer(point: CGPoint(x: plot.minX + tooltip.point.x, y: plot.minY + tooltip.point.y)) {
|
||||
tooltip.content.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
.frame(width: proxy.size.width, height: proxy.size.height)
|
||||
}
|
||||
}
|
||||
.allowsHitTesting(false)
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
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 }
|
||||
}
|
||||
Reference in New Issue
Block a user