Files
Kymo/kymo/UI/Charts/NativePanelCurve.swift
T

218 lines
12 KiB
Swift

import AppKit
import SwiftUI
/// Bounded static lines and per-run area paths. Hover never rebuilds geometry.
struct NativePanelCurve: NSViewRepresentable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
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, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked))
}
struct Input: Equatable {
let frame: PanelCurveFrame
let colors: [Color]
let scales: [Double]
let maximumGap: TimeInterval
var hoveredIndex: Int? = nil
var visibleSeriesCount: Int? = nil
var filledSeriesCount = 1
var stacked = false
}
final class PlotView: NSView {
private(set) var input: Input?
private(set) var pathBuildCount = 0
let grid = CAShapeLayer()
let curves = CALayer()
let hoverLine = CAShapeLayer()
private var hoverDots: [CAShapeLayer] = []
private var seriesLayers: [SeriesLayer] = []
private var palette: [NSColor] = []
private var plottedBands: [StackedSeries.Band] = []
override var isFlipped: Bool { true }
override func hitTest(_ point: NSPoint) -> NSView? { nil }
init() {
super.init(frame: .zero)
wantsLayer = true
layer?.masksToBounds = true
curves.anchorPoint = .zero
grid.fillColor = nil; grid.lineWidth = 0.5
grid.isHidden = true
hoverLine.fillColor = nil; hoverLine.lineWidth = 1; hoverLine.lineDashPattern = [3, 2]
for child in [grid, curves, hoverLine] { layer?.addSublayer(child) }
setAccessibilityElement(false)
}
required init?(coder: NSCoder) { nil }
func configure(_ value: Input) {
guard input != value else { return }
let old = input
let frameChanged = old?.frame != value.frame
input = value
CATransaction.begin(); CATransaction.setDisableActions(true)
curves.isHidden = value.colors.isEmpty || value.scales.isEmpty
ensureLayers(value.frame.series.count)
if old?.colors != value.colors || old?.frame.series.count != value.frame.series.count
|| old?.filledSeriesCount != value.filledSeriesCount { updatePalette() }
for index in seriesLayers.indices {
seriesLayers[index].root.isHidden = index >= (value.visibleSeriesCount ?? value.frame.series.count)
}
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || old?.stacked != value.stacked {
rebuildPaths()
}
updateHover()
CATransaction.commit()
}
private func ensureLayers(_ count: Int) {
while seriesLayers.count < count {
let series = SeriesLayer(); seriesLayers.append(series); curves.addSublayer(series.root)
let dot = CAShapeLayer(); hoverDots.append(dot); layer?.addSublayer(dot)
}
while seriesLayers.count > count {
seriesLayers.removeLast().root.removeFromSuperlayer()
hoverDots.removeLast().removeFromSuperlayer()
}
}
private func updatePalette() {
effectiveAppearance.performAsCurrentDrawingAppearance {
palette = input?.colors.map(NSColor.init) ?? []
grid.strokeColor = NSColor.labelColor.withAlphaComponent(0.10).cgColor
hoverLine.strokeColor = NSColor.labelColor.withAlphaComponent(0.45).cgColor
guard !palette.isEmpty else { return }
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
let dark = effectiveAppearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua
series.area.fillColor = index < (input?.filledSeriesCount ?? 0)
? color.withAlphaComponent(dark ? 0.16 : 0.12).cgColor : nil
hoverDots[index].fillColor = color.cgColor
}
}
}
private func updateGrid() {
grid.frame = bounds; hoverLine.frame = bounds
curves.bounds = bounds; curves.position = .zero
let path = CGMutablePath()
for step in 0...10 {
let x = bounds.width * Double(step) / 10
path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height))
}
for step in 0...2 {
let y = bounds.height * Double(step) / 2
path.move(to: CGPoint(x: 0, y: y)); path.addLine(to: CGPoint(x: bounds.width, y: y))
}
grid.path = path
}
private func rebuildPaths() {
pathBuildCount += 1
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(begin: first, end: last)
let frame = input.frame
plottedBands = input.stacked ? StackedSeries.bands(frame.series, count: frame.dates.count, limit: input.scales.first) : []
for index in frame.series.indices {
let series = seriesLayers[index]
series.resize(bounds)
let value = input.scales[input.stacked ? 0 : min(index, input.scales.count - 1)]
let scale = value.isFinite && value > 0 ? value : 1
let upper = input.stacked ? plottedBands[index].upper : frame.series[index]
let lower = input.stacked ? plottedBands[index].lower : nil
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: upper, maximumGap: input.maximumGap,
boundaryDates: frame.boundaryDates, intervals: frame.intervals, lowerValues: lower)
let line = CGMutablePath(), dots = CGMutablePath(), area = 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 else { continue }
if points.count == 1 {
dots.addEllipse(in: CGRect(x: start.x - 2, y: start.y - 2, width: 4, height: 4)); continue
}
let segment = CGMutablePath(); segment.move(to: start)
for (a, b) in zip(points, points.dropFirst()) {
let mid = (a.x + b.x) / 2
segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
line.addPath(segment)
// Close against the matching lower boundary, never against another run or missing component.
let lowerPoints = run.reversed().map { CGPoint(x: bounds.width * domain.position($0.date),
y: bounds.height * (1 - min(1, max(0, $0.lower / scale)))) }
let fill = CGMutablePath(); fill.addPath(segment)
if let lowerStart = lowerPoints.first { fill.addLine(to: lowerStart) }
for (a, b) in zip(lowerPoints, lowerPoints.dropFirst()) {
let mid = (a.x + b.x) / 2
fill.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
}
fill.closeSubpath(); area.addPath(fill)
}
series.line.path = line
series.points.path = dots
series.area.path = area
}
}
private func updateHover() {
for dot in hoverDots { dot.path = nil; dot.frame = bounds }
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(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 {
guard series < (input.visibleSeriesCount ?? input.frame.series.count) else { continue }
let values = input.stacked && plottedBands.indices.contains(series) ? plottedBands[series].upper : input.frame.series[series]
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
let scale = input.scales[input.stacked ? 0 : min(series, input.scales.count - 1)]
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1))))
hoverDots[series].path = CGPath(ellipseIn: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5), transform: nil)
}
}
override func setFrameSize(_ size: NSSize) {
let changed = frame.size != size
super.setFrameSize(size)
if changed {
CATransaction.begin(); CATransaction.setDisableActions(true)
updateGrid(); rebuildPaths(); updateHover(); CATransaction.commit()
}
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
CATransaction.begin(); CATransaction.setDisableActions(true)
updatePalette(); CATransaction.commit()
}
override func viewDidChangeEffectiveAppearance() {
super.viewDidChangeEffectiveAppearance()
CATransaction.begin(); CATransaction.setDisableActions(true)
updatePalette(); CATransaction.commit()
}
private final class SeriesLayer {
let root = CALayer(), area = CAShapeLayer(), line = CAShapeLayer(), points = CAShapeLayer()
init() {
line.fillColor = nil; line.lineWidth = 1.4; line.lineCap = .round; line.lineJoin = .round
root.addSublayer(area); root.addSublayer(line); root.addSublayer(points)
}
func resize(_ bounds: CGRect) {
root.frame = bounds
let local = CGRect(origin: .zero, size: bounds.size)
area.frame = local; line.frame = local; points.frame = local
}
func clear() { area.path = nil; line.path = nil; points.path = nil }
}
}
}