import AppKit import SwiftUI /// A bounded native plot; SwiftUI still owns axes, legends and hover presentation. 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? { // 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) -> PlotView { PlotView() } func updateNSView(_ view: PlotView, context: Context) { view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap, hoveredIndex: hoveredIndex, animates: animates)) } struct Input: Equatable { let frame: PanelCurveFrame let colors: [Color] 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 let motion = MetricMotion() var isAnimating: Bool { motion.isRunning } override var isFlipped: Bool { true } override func hitTest(_ point: NSPoint) -> NSView? { nil } init() { super.init(frame: .zero) wantsLayer = true layerContentsRedrawPolicy = .onSetNeedsDisplay setAccessibilityElement(false) } required init?(coder: NSCoder) { nil } func configure(_ value: Input) { guard input != value else { return } let previous = input let changedFrame = previous?.frame != value.frame input = value // Keep hover updates from restarting an existing transition. drawingFrame = value.frame if !value.animates { motion.stop() } else if changedFrame { motion.stop() if window != nil, let previous, let end = value.frame.dates.last, !value.frame.boundaryDates.contains(end), PanelCurveGeometry.isAppend(from: previous.frame.dates, to: value.frame.dates, maximumGap: value.maximumGap) { motion.start(on: layer) } } needsDisplay = true } private func settle() { motion.stop(); drawingFrame = input?.frame } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() if window == nil { settle() } } override func setFrameSize(_ newSize: NSSize) { let changed = frame.size != newSize super.setFrameSize(newSize) if changed { needsDisplay = true } } override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance() needsDisplay = true } override func draw(_ dirtyRect: NSRect) { guard let context = NSGraphicsContext.current?.cgContext else { return } context.saveGState() defer { context.restoreGState() } context.clip(to: bounds) context.setLineWidth(0.5) context.setStrokeColor(NSColor.labelColor.withAlphaComponent(0.10).cgColor) for step in 0...10 { let x = bounds.width * Double(step) / 10 context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height)) } for step in 0...2 { let y = bounds.height * Double(step) / 2 context.move(to: CGPoint(x: 0, y: y)); context.addLine(to: CGPoint(x: bounds.width, y: y)) } context.strokePath() guard let input, let frame = drawingFrame, let first = input.frame.dates.first, let last = input.frame.dates.last, !input.colors.isEmpty, !input.scales.isEmpty else { return } let domain = PanelCurveFrame.domain(previousBegin: nil, previousEnd: nil, begin: first, end: last, progress: 1) for index in frame.series.indices { let tint = NSColor(input.colors[min(index, input.colors.count - 1)]) let proposedScale = input.scales[min(index, input.scales.count - 1)] let scale = proposedScale.isFinite && proposedScale > 0 ? proposedScale : 1 let runs = PanelCurveGeometry.runs(dates: frame.dates, values: frame.series[index], maximumGap: input.maximumGap, boundaryDates: frame.boundaryDates, intervals: frame.intervals) context.setFillColor(tint.cgColor) context.setStrokeColor(tint.cgColor) context.setLineWidth(1.5) context.setLineCap(.round); context.setLineJoin(.round) 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 finish = points.last else { continue } if points.count == 1 { context.fillEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)) continue } let line = CGMutablePath(); line.move(to: start) for (a, b) in zip(points, points.dropFirst()) { let middle = (a.x + b.x) / 2 line.addCurve(to: b, control1: CGPoint(x: middle, y: a.y), control2: CGPoint(x: middle, y: b.y)) } let area = line.mutableCopy()! area.addLine(to: CGPoint(x: finish.x, y: bounds.height)) area.addLine(to: CGPoint(x: start.x, y: bounds.height)); area.closeSubpath() if let gradient = CGGradient(colorsSpace: CGColorSpace(name: CGColorSpace.sRGB), colors: [tint.withAlphaComponent(0.20).cgColor, tint.withAlphaComponent(0.01).cgColor] as CFArray, locations: [0, 1]) { context.saveGState(); context.addPath(area); context.clip() context.drawLinearGradient(gradient, start: .zero, end: CGPoint(x: 0, y: bounds.height), options: []) context.restoreGState() } context.addPath(line); context.strokePath() } } if let index = input.hoveredIndex, input.frame.dates.indices.contains(index), last > first { let x = bounds.width * domain.position(input.frame.dates[index]) context.setStrokeColor(NSColor.labelColor.withAlphaComponent(0.45).cgColor) context.setLineWidth(1); context.setLineDash(phase: 0, lengths: [3, 2]) context.move(to: CGPoint(x: x, y: 0)); context.addLine(to: CGPoint(x: x, y: bounds.height)); context.strokePath() context.setLineDash(phase: 0, lengths: []) for series in input.frame.series.indices { let values = 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 y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1)))) context.setFillColor(NSColor(input.colors[min(series, input.colors.count - 1)]).cgColor) context.fillEllipse(in: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5)) } } } } }