Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Editor/ChartDrawing.swift3// Description: Native drawing of a `chart` node inside the document (bars, lines, areas, pie, scatter) with CoreGraphics, from the typed series of SPNotesDocument. The interactive view of the block sheet uses Swift Charts; this is its still picture in the text.4import AppKit5import SPNotesDocument6import SPNotesDesign78@MainActor enum ChartDrawing {9 /// Series colours, in order: the accent first, then hues that stay distinct in both appearances.10 static let palette: [NSColor] = [.nv(.accent), .nv(.success), .nv(.warning), .nv(.danger), .nv(.fgMuted), .nv(.accent, alpha: 0.55), .nv(.success, alpha: 0.55)]11 static func color(_ i: Int) -> NSColor { palette[i % palette.count] }1213 struct Scale { var min: Double, max: Double14 func y(_ v: Double, in r: CGRect) -> CGFloat { r.maxY - CGFloat((v - min) / (max - min == 0 ? 1 : max - min)) * r.height }15 }16 /// A value axis that includes zero for bars and areas and has round bounds.17 static func makeScale(_ values: [Double], includeZero: Bool) -> Scale {18 var lo = values.min() ?? 0, hi = values.max() ?? 119 if includeZero { lo = Swift.min(0, lo); hi = Swift.max(0, hi) }20 if lo == hi { hi = lo + 1 }21 let step = niceStep((hi - lo) / 4)22 return Scale(min: (lo / step).rounded(.down) * step, max: (hi / step).rounded(.up) * step)23 }24 static func niceStep(_ raw: Double) -> Double {25 guard raw > 0, raw.isFinite else { return 1 }26 let mag = pow(10, floor(log10(raw))); let n = raw / mag27 return (n <= 1 ? 1 : n <= 2 ? 2 : n <= 5 ? 5 : 10) * mag28 }29 static func label(_ v: Double) -> String {30 if abs(v) >= 1_000_000 { return String(format: "%.1f M", v / 1_000_000) }31 if abs(v) >= 10_000 { return String(format: "%.0f k", v / 1_000) }32 return v == v.rounded() ? String(format: "%.0f", v) : String(format: "%.2f", v)33 }3435 static func draw(_ chart: ChartBlock, in rect: CGRect) {36 let series = chart.series().filter { $0.points.contains { $0.y != nil } }37 guard !series.isEmpty else { return }38 let font = EditorTheme.uiFont(10)39 let labelAttrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: EditorTheme.mutedText]40 // legend (more than one series)41 var top = rect.minY42 if series.count > 1 {43 var x = rect.minX44 for (i, s) in series.enumerated() {45 let name = NSAttributedString(string: s.name, attributes: labelAttrs); let w = name.size().width46 if x + w + 18 > rect.maxX { break }47 color(i).setFill(); NSBezierPath(roundedRect: CGRect(x: x, y: top + 3, width: 8, height: 8), xRadius: 2, yRadius: 2).fill()48 name.draw(at: CGPoint(x: x + 12, y: top)); x += w + 2649 }50 top += 1851 }52 if chart.kind == .pie { drawPie(series[0], in: CGRect(x: rect.minX, y: top, width: rect.width, height: rect.maxY - top), attrs: labelAttrs); return }53 let values = series.flatMap { $0.points.compactMap(\.y) }54 let scale = makeScale(values, includeZero: chart.kind != .line && chart.kind != .scatter)55 let axisW = Swift.max((label(scale.max) as NSString).size(withAttributes: labelAttrs).width, (label(scale.min) as NSString).size(withAttributes: labelAttrs).width) + 856 let plot = CGRect(x: rect.minX + axisW, y: top + 6, width: rect.width - axisW - 4, height: rect.maxY - top - 6 - 18)57 // grid and value labels58 for i in 0...4 {59 let v = scale.min + (scale.max - scale.min) * Double(i) / 4; let y = scale.y(v, in: plot)60 EditorTheme.hairline.setStroke(); let line = NSBezierPath(); line.lineWidth = 1; line.move(to: CGPoint(x: plot.minX, y: y.rounded() + 0.5)); line.line(to: CGPoint(x: plot.maxX, y: y.rounded() + 0.5)); line.stroke()61 let s = NSAttributedString(string: label(v), attributes: labelAttrs); let size = s.size()62 s.draw(at: CGPoint(x: plot.minX - size.width - 6, y: y - size.height / 2))63 }64 let count = series.map(\.points.count).max() ?? 065 guard count > 0 else { return }66 let numericX = chart.kind == .scatter && series[0].points.allSatisfy { $0.x.numericValue != nil }67 let xs = series[0].points.compactMap { $0.x.numericValue }68 let xScale = numericX ? makeScale(xs, includeZero: false) : Scale(min: 0, max: 1)69 func xPos(_ i: Int, _ p: ChartPoint) -> CGFloat {70 if numericX, let v = p.x.numericValue { return plot.minX + CGFloat((v - xScale.min) / (xScale.max - xScale.min)) * plot.width }71 return chart.kind == .bar ? plot.minX + (CGFloat(i) + 0.5) * plot.width / CGFloat(count) : (count == 1 ? plot.midX : plot.minX + CGFloat(i) * plot.width / CGFloat(count - 1))72 }73 // category labels (as many as fit)74 if !numericX {75 let stride = Swift.max(1, Int(ceil(Double(count) * 56 / Double(Swift.max(1, plot.width)))))76 for (i, p) in series[0].points.enumerated() where i % stride == 0 {77 let s = NSAttributedString(string: String(p.x.text.prefix(12)), attributes: labelAttrs); let size = s.size()78 s.draw(at: CGPoint(x: Swift.min(Swift.max(plot.minX, xPos(i, p) - size.width / 2), plot.maxX - size.width), y: plot.maxY + 4))79 }80 } else {81 for v in [xScale.min, xScale.max] { let s = NSAttributedString(string: label(v), attributes: labelAttrs); let size = s.size(); s.draw(at: CGPoint(x: v == xScale.min ? plot.minX : plot.maxX - size.width, y: plot.maxY + 4)) }82 }83 let zero = scale.y(Swift.max(scale.min, Swift.min(scale.max, 0)), in: plot)84 for (si, s) in series.enumerated() {85 let c = color(si)86 switch chart.kind {87 case .bar:88 let band = plot.width / CGFloat(count), w = Swift.max(2, Swift.min(36, band * 0.72 / CGFloat(series.count)))89 for (i, p) in s.points.enumerated() { guard let v = p.y else { continue }90 let x = plot.minX + (CGFloat(i) + 0.5) * band - w * CGFloat(series.count) / 2 + w * CGFloat(si); let y = scale.y(v, in: plot)91 c.setFill(); NSBezierPath(roundedRect: CGRect(x: x + 0.5, y: Swift.min(y, zero), width: w - 1, height: Swift.max(1, abs(zero - y))), xRadius: 2, yRadius: 2).fill()92 }93 case .scatter:94 for (i, p) in s.points.enumerated() { guard let v = p.y else { continue }95 c.withAlphaComponent(0.85).setFill(); NSBezierPath(ovalIn: CGRect(x: xPos(i, p) - 3, y: scale.y(v, in: plot) - 3, width: 6, height: 6)).fill()96 }97 default: // line, area and kinds of a newer editor98 let pts: [CGPoint] = s.points.enumerated().compactMap { i, p in p.y.map { CGPoint(x: xPos(i, p), y: scale.y($0, in: plot)) } }99 guard let first = pts.first, let last = pts.last else { continue }100 if chart.kind == .area {101 let area = NSBezierPath(); area.move(to: CGPoint(x: first.x, y: zero)); pts.forEach { area.line(to: $0) }; area.line(to: CGPoint(x: last.x, y: zero)); area.close()102 c.withAlphaComponent(0.2).setFill(); area.fill()103 }104 let path = NSBezierPath(); path.lineWidth = 2; path.lineJoinStyle = .round; path.lineCapStyle = .round105 path.move(to: first); pts.dropFirst().forEach { path.line(to: $0) }106 c.setStroke(); path.stroke()107 if pts.count <= 24 { c.setFill(); pts.forEach { NSBezierPath(ovalIn: CGRect(x: $0.x - 2.5, y: $0.y - 2.5, width: 5, height: 5)).fill() } }108 }109 }110 }111112 private static func drawPie(_ s: ChartSeries, in rect: CGRect, attrs: [NSAttributedString.Key: Any]) {113 let slices = s.points.compactMap { p in p.y.flatMap { $0 > 0 ? (p.x.text, $0) : nil } }114 let total = slices.reduce(0) { $0 + $1.1 }; guard total > 0 else { return }115 let radius = Swift.min(rect.height, rect.width * 0.45) / 2 - 4116 let center = CGPoint(x: rect.minX + radius + 8, y: rect.midY)117 var angle: CGFloat = -90118 for (i, slice) in slices.enumerated() {119 let sweep = CGFloat(slice.1 / total) * 360120 let path = NSBezierPath(); path.move(to: center)121 path.appendArc(withCenter: center, radius: radius, startAngle: angle, endAngle: angle + sweep, clockwise: false); path.close()122 color(i).setFill(); path.fill()123 EditorTheme.surface.setStroke(); path.lineWidth = 1.5; path.stroke()124 angle += sweep125 }126 var y = rect.minY + 4; let x = center.x + radius + 20127 for (i, slice) in slices.enumerated().prefix(8) {128 color(i).setFill(); NSBezierPath(roundedRect: CGRect(x: x, y: y + 3, width: 8, height: 8), xRadius: 2, yRadius: 2).fill()129 NSAttributedString(string: "\(slice.0.prefix(24)) \(Int((slice.1 / total * 100).rounded())) %", attributes: attrs).draw(at: CGPoint(x: x + 14, y: y)); y += 17130 }131 }132}133