fix(charts): 修复浮窗层级并平滑切频与曲线移出
This commit is contained in:
@@ -14,6 +14,7 @@ nonisolated struct TrendSample: Sendable {
|
||||
var cpuUser: Double?
|
||||
var cpuSystem: Double?
|
||||
var breakBefore = false
|
||||
var expectedInterval: TimeInterval = 2
|
||||
}
|
||||
|
||||
/// Bounded sampling history; no timer or UI visibility dependence.
|
||||
@@ -22,18 +23,18 @@ nonisolated struct MetricHistory: Sendable {
|
||||
private(set) var samples: [TrendSample] = []
|
||||
private(set) var interfaces: [String: [InterfaceTrendSample]] = [:]
|
||||
|
||||
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false) {
|
||||
mutating func append(_ snapshot: MetricsSnapshot, breakBefore: Bool = false, expectedInterval: TimeInterval = 2) {
|
||||
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
|
||||
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
|
||||
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
|
||||
battery: snapshot.battery?.charge, upload: snapshot.uploadRate,
|
||||
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written,
|
||||
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore))
|
||||
cpuUser: snapshot.cpu?.user, cpuSystem: snapshot.cpu?.system, breakBefore: breakBefore, expectedInterval: expectedInterval))
|
||||
let current = snapshot.network ?? []
|
||||
let keys = Set(current.map(\.identity))
|
||||
interfaces = interfaces.filter { keys.contains($0.key) }
|
||||
for item in current {
|
||||
interfaces[item.identity, default: []].append(InterfaceTrendSample(date: snapshot.date, download: item.download, upload: item.upload))
|
||||
interfaces[item.identity, default: []].append(InterfaceTrendSample(date: snapshot.date, download: item.download, upload: item.upload, expectedInterval: expectedInterval))
|
||||
if interfaces[item.identity, default: []].count > Self.capacity { interfaces[item.identity]?.removeFirst() }
|
||||
}
|
||||
if samples.count > Self.capacity { samples.removeFirst(samples.count - Self.capacity) }
|
||||
@@ -44,4 +45,5 @@ nonisolated struct InterfaceTrendSample: Sendable {
|
||||
let date: Date
|
||||
let download: Double?
|
||||
let upload: Double?
|
||||
var expectedInterval: TimeInterval = 2
|
||||
}
|
||||
|
||||
@@ -12,15 +12,17 @@ final class MetricsStore {
|
||||
@ObservationIgnored private var generation = 0
|
||||
@ObservationIgnored private var visibilityGeneration = 0
|
||||
@ObservationIgnored private var task: Task<Void, Never>?
|
||||
@ObservationIgnored private let sampler = SystemSampler()
|
||||
@ObservationIgnored private let sampler: SystemSampler
|
||||
@ObservationIgnored private var scheduledInterval = 0
|
||||
@ObservationIgnored private var needsHistoryBoundary = true
|
||||
@ObservationIgnored private var lastPublishedAt: ContinuousClock.Instant?
|
||||
|
||||
init(sampling: SamplingPreferences? = nil) {
|
||||
init(sampling: SamplingPreferences? = nil, sampler: SystemSampler = SystemSampler()) {
|
||||
self.sampler = sampler
|
||||
self.sampling = sampling ?? SamplingPreferences()
|
||||
self.sampling.onChange = { [weak self] in
|
||||
guard let self, !self.isPaused, self.effectiveMilliseconds != self.scheduledInterval else { return }
|
||||
self.reschedule(reset: false)
|
||||
self.reschedule(reset: false, sampleImmediately: false)
|
||||
}
|
||||
start()
|
||||
}
|
||||
@@ -31,22 +33,30 @@ final class MetricsStore {
|
||||
reschedule(reset: true)
|
||||
}
|
||||
|
||||
private func reschedule(reset: Bool) {
|
||||
private func reschedule(reset: Bool, sampleImmediately: Bool = true) {
|
||||
generation += 1
|
||||
task?.cancel()
|
||||
needsHistoryBoundary = true
|
||||
needsHistoryBoundary = needsHistoryBoundary || reset
|
||||
scheduledInterval = effectiveMilliseconds
|
||||
var delay = Duration.zero
|
||||
if !sampleImmediately, let lastPublishedAt {
|
||||
delay = max(.zero, .milliseconds(effectiveMilliseconds) - lastPublishedAt.duration(to: .now))
|
||||
}
|
||||
let initialDelay = delay
|
||||
let currentGeneration = generation
|
||||
task = Task { [weak self, sampler] in
|
||||
guard !Task.isCancelled else { return }
|
||||
if initialDelay > .zero {
|
||||
do { try await Task.sleep(for: initialDelay) } catch { return }
|
||||
}
|
||||
if reset { await sampler.reset() }
|
||||
while !Task.isCancelled {
|
||||
let visibleGeneration = self?.visibilityGeneration
|
||||
var next = await sampler.sample(includeProcesses: self?.isPanelVisible == true, processUpdate: { [weak self] processes in
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self, self.generation == currentGeneration, self.visibilityGeneration == visibleGeneration,
|
||||
guard let self, self.visibilityGeneration == visibleGeneration,
|
||||
self.isPanelVisible, !self.isPaused else { return }
|
||||
self.snapshot.processes = processes
|
||||
if self.snapshot.processes.map({ $0.date > processes.date }) != true { self.snapshot.processes = processes }
|
||||
}
|
||||
})
|
||||
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
|
||||
@@ -56,7 +66,8 @@ final class MetricsStore {
|
||||
next.processes = completed
|
||||
}
|
||||
self?.snapshot = next
|
||||
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true)
|
||||
self?.history.append(next, breakBefore: self?.needsHistoryBoundary == true, expectedInterval: Double(self?.effectiveMilliseconds ?? 5_000) / 1000)
|
||||
self?.lastPublishedAt = .now
|
||||
self?.needsHistoryBoundary = false
|
||||
SamplingDiagnostics.record(next)
|
||||
let interval = self?.effectiveMilliseconds ?? 5_000
|
||||
@@ -70,6 +81,7 @@ final class MetricsStore {
|
||||
if isPaused { start() }
|
||||
else {
|
||||
generation += 1
|
||||
visibilityGeneration += 1
|
||||
task?.cancel()
|
||||
task = nil
|
||||
Task { await sampler.setProcessVisible(false) }
|
||||
|
||||
@@ -15,6 +15,7 @@ struct MenuPanelView: View {
|
||||
|
||||
private var snapshot: MetricsSnapshot { metrics.snapshot }
|
||||
private var samples: [TrendSample] { metrics.history.samples }
|
||||
private var chartIntervals: [TimeInterval] { samples.map(\.expectedInterval) }
|
||||
private var chartInterval: TimeInterval { Double(metrics.effectiveMilliseconds) / 1000 }
|
||||
private var chartBoundaries: Set<Date> { Set(samples.filter(\.breakBefore).map(\.date)) }
|
||||
private var columns: Int { panelSize.width >= 1160 ? 3 : panelSize.width >= 900 ? 2 : 1 }
|
||||
@@ -95,7 +96,7 @@ struct MenuPanelView: View {
|
||||
}
|
||||
|
||||
private func chart(_ key: KeyPath<TrendSample, Double?>, color: Color, label: LocalizedStringKey = "panel.total") -> some View {
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color, firstLabel: label, expectedInterval: chartInterval, boundaryDates: chartBoundaries)
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map { $0[keyPath: key] }, color: color, firstLabel: label, expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
||||
}
|
||||
private func line(_ key: LocalizedStringKey, _ value: String) -> some View {
|
||||
HStack(alignment: .firstTextBaseline) { Text(key).foregroundStyle(.secondary); Spacer(minLength: 6); AnimatedMetricText(value: value) }
|
||||
@@ -106,7 +107,7 @@ struct MenuPanelView: View {
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.cpu),
|
||||
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
|
||||
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
|
||||
firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries)
|
||||
firstLabel: "panel.total", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
||||
if let cpu = snapshot.cpu {
|
||||
HStack { line("cpu.user", MetricFormat.percent(cpu.user)); line("cpu.system", MetricFormat.percent(cpu.system)) }
|
||||
LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 5) {
|
||||
@@ -143,7 +144,7 @@ struct MenuPanelView: View {
|
||||
PanelTrendChart(dates: samples.map(\.date),
|
||||
first: samples.map { $0.memory.map { $0 * Double(snapshot.memory?.total ?? 1) } },
|
||||
color: Color("MetricMemory"), fixedScale: Double(snapshot.memory?.total ?? 1),
|
||||
scaleLabel: MetricFormat.bytes(snapshot.memory?.total), expectedInterval: chartInterval, boundaryDates: chartBoundaries)
|
||||
scaleLabel: MetricFormat.bytes(snapshot.memory?.total), expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
||||
if let m = snapshot.memory {
|
||||
|
||||
GeometryReader { geometry in
|
||||
@@ -182,7 +183,7 @@ struct MenuPanelView: View {
|
||||
Text(verbatim: "\(item.name) · \(item.addresses.first(where: { !$0.contains(":") }) ?? item.addresses.first ?? "--")")
|
||||
.font(.system(size: 10)).lineLimit(1).minimumScaleFactor(0.8).textSelection(.enabled)
|
||||
} else { Text("panel.addressUnknown").foregroundStyle(.secondary) }
|
||||
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", expectedInterval: chartInterval, boundaryDates: chartBoundaries).id(selectedInterface)
|
||||
PanelTrendChart(dates: networkDates, first: networkDownloads, second: networkUploads, color: Color("MetricNetwork"), secondColor: Color("SeriesUpload"), fixedScale: nil, firstLabel: "network.download", secondLabel: "network.upload", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: networkIntervals).id(selectedInterface)
|
||||
if !network.isEmpty && total(\.download) == nil { Text("panel.rateBaseline").foregroundStyle(.secondary) }
|
||||
HStack { line("network.received", network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.received })); line("network.sent", network.isEmpty ? "--" : MetricFormat.bytes(network.reduce(0) { $0 + $1.sent })) }
|
||||
switch snapshot.networkPath {
|
||||
@@ -222,6 +223,7 @@ struct MenuPanelView: View {
|
||||
let name = selectedInterface.isEmpty ? snapshot.defaultNetworkInterface : network.first?.name
|
||||
return snapshot.network?.first { $0.name == name && $0.active }
|
||||
}
|
||||
private var networkIntervals: [TimeInterval] { selectedInterface.isEmpty ? chartIntervals : (metrics.history.interfaces[selectedInterface] ?? []).map(\.expectedInterval) }
|
||||
private var networkDates: [Date] { selectedInterface.isEmpty ? samples.map(\.date) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.date) }
|
||||
private var networkDownloads: [Double?] { selectedInterface.isEmpty ? samples.map(\.download) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.download) }
|
||||
private var networkUploads: [Double?] { selectedInterface.isEmpty ? samples.map(\.upload) : (metrics.history.interfaces[selectedInterface] ?? []).map(\.upload) }
|
||||
@@ -229,7 +231,7 @@ struct MenuPanelView: View {
|
||||
ResourceCard(title: "metric.disk", symbol: "internaldrive", color: Color("MetricDisk"), value: snapshot.disk.map { String(format: "%.0f / %.0f GB", Double($0.total - min($0.total, $0.available)) / 1_000_000_000, Double($0.total) / 1_000_000_000) } ?? "--") {
|
||||
|
||||
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", expectedInterval: chartInterval, boundaryDates: chartBoundaries)
|
||||
PanelTrendChart(dates: samples.map(\.date), first: samples.map(\.read), second: samples.map(\.write), color: Color("MetricDisk"), secondColor: Color("MetricMemory"), fixedScale: nil, firstLabel: "disk.read", secondLabel: "disk.write", expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
||||
Text("disk.physicalIO").foregroundStyle(.secondary)
|
||||
HStack { line("disk.read", MetricFormat.rate(snapshot.diskIO?.read)); line("disk.write", MetricFormat.rate(snapshot.diskIO?.written)) }
|
||||
HStack { line("disk.remainingLife", MetricFormat.percent(snapshot.diskHealth?.remainingLife)); line("disk.powerOnHours", snapshot.diskHealth?.powerOnHours.map { "\($0) h" } ?? "--") }
|
||||
|
||||
@@ -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