SPB Git

Repository Public

ChartRendering.swift 6.4 KB 131 lines swift

1// SP Notes iOS2// File: Editor/ChartRendering.swift3// Description: A `chart` block drawn natively with Swift Charts from the Core's typed view (`ChartBlock.series()`): the SwiftUI4//              view used live in the chart sheet, and its bitmap for the card inside the text (`ImageRenderer`).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Charts9import SPNotesCore10import SPNotesDesign11import SwiftUI12import UIKit1314/// One plotted value, flattened from the Core's series.15struct ChartDatum: Identifiable, Hashable {16    let id: Int17    let series: String18    let label: String19    let x: Double?20    let y: Double21}2223/// What the chart view plots: the points that have a value, and whether the X axis reads as numbers.24struct ChartPlot: Hashable {25    var kind: ChartKind26    var data: [ChartDatum]27    var seriesNames: [String]28    var numericX: Bool2930    init(_ chart: ChartBlock) {31        kind = chart.kind32        let series = chart.series()33        seriesNames = series.map(\.name)34        let allX = series.flatMap { $0.points.map(\.x) }35        let numbers = allX.map { cell -> Double? in if case .number(let d) = cell { return d } else { return nil } }36        // A numeric axis only for the kinds that read along X, and only when every X is a number.37        numericX = !allX.isEmpty && numbers.allSatisfy { $0 != nil } && (chart.kind == .line || chart.kind == .area || chart.kind == .scatter)38        var out: [ChartDatum] = []39        for s in series {40            for point in s.points {41                guard let y = point.y, y.isFinite else { continue }42                var x: Double?43                if case .number(let d) = point.x { x = d }44                out.append(ChartDatum(id: out.count, series: s.name, label: point.x.text, x: x, y: y))45            }46        }47        data = out48    }4950    var isEmpty: Bool { data.isEmpty }51    /// A pie shows one series: the first.52    var pieData: [ChartDatum] { data.filter { $0.series == seriesNames.first && $0.y > 0 } }5354    /// Categorical colours from the tokens. Violet is reserved for AI and never used for data.55    static let palette: [Color] = [NVColor.accent, NVColor.success, NVColor.warning, NVColor.danger, NVColor.fgMuted, NVColor.lineStrong]56}5758struct ChartBlockChart: View {59    let plot: ChartPlot6061    var body: some View {62        if plot.kind == .pie {63            Chart(plot.pieData) { datum in64                SectorMark(angle: .value("Valeur", datum.y), innerRadius: .ratio(0.5), angularInset: 1.5)65                    .cornerRadius(3)66                    .foregroundStyle(by: .value("Catégorie", datum.label))67            }68            .chartForegroundStyleScale(range: ChartPlot.palette)69            .chartLegend(position: .bottom, alignment: .leading)70        } else {71            Chart(plot.data) { datum in72                mark(datum)73            }74            .chartForegroundStyleScale(domain: plot.seriesNames, range: Array(ChartPlot.palette.prefix(max(1, min(plot.seriesNames.count, ChartPlot.palette.count)))))75            .chartLegend(plot.seriesNames.count > 1 ? .visible : .hidden)76            .chartXAxis { AxisMarks { _ in AxisGridLine().foregroundStyle(NVColor.line); AxisValueLabel().foregroundStyle(NVColor.fgMuted) } }77            .chartYAxis { AxisMarks { _ in AxisGridLine().foregroundStyle(NVColor.line); AxisValueLabel().foregroundStyle(NVColor.fgMuted) } }78        }79    }8081    @ChartContentBuilder private func mark(_ datum: ChartDatum) -> some ChartContent {82        let series = PlottableValue.value("Série", datum.series)83        if plot.numericX, let x = datum.x {84            switch plot.kind {85            case .line: LineMark(x: .value("X", x), y: .value("Y", datum.y)).foregroundStyle(by: series).interpolationMethod(.monotone)86            case .area: AreaMark(x: .value("X", x), y: .value("Y", datum.y), stacking: .unstacked).foregroundStyle(by: series).opacity(0.55)87            default: PointMark(x: .value("X", x), y: .value("Y", datum.y)).foregroundStyle(by: series)88            }89        } else {90            switch plot.kind {91            case .line: LineMark(x: .value("X", datum.label), y: .value("Y", datum.y)).foregroundStyle(by: series).interpolationMethod(.monotone).symbol(by: series)92            case .area: AreaMark(x: .value("X", datum.label), y: .value("Y", datum.y), stacking: .unstacked).foregroundStyle(by: series).opacity(0.55)93            case .scatter: PointMark(x: .value("X", datum.label), y: .value("Y", datum.y)).foregroundStyle(by: series)94            // bar, and any kind written by a newer editor (kept in the node, drawn as bars)95            default: BarMark(x: .value("X", datum.label), y: .value("Y", datum.y)).foregroundStyle(by: series).position(by: series).cornerRadius(3)96            }97        }98    }99}100101@MainActor102enum ChartSnapshot {103    private struct Key: Hashable { var plot: ChartPlot; var width: Int; var dark: Bool; var category: String }104    private static var cache: [Key: UIImage] = [:]105    private static var order: [Key] = []106    static func removeAll() { cache.removeAll(); order.removeAll() }107108    /// The chart as a bitmap for the card. Nil when there is nothing to plot (the card shows an empty state instead).109    static func image(_ chart: ChartBlock, width: CGFloat, traits: UITraitCollection) -> UIImage? {110        let plot = ChartPlot(chart)111        guard !plot.isEmpty, plot.kind != .pie || !plot.pieData.isEmpty else { return nil }112        let key = Key(plot: plot, width: Int(width.rounded()), dark: traits.userInterfaceStyle == .dark, category: traits.preferredContentSizeCategory.rawValue)113        if let cached = cache[key] { return cached }114        let height = min(240, max(150, width * 0.56))115        let view = ChartBlockChart(plot: plot)116            .padding(.top, 10)117            .frame(width: width, height: height)118            .environment(\.colorScheme, traits.userInterfaceStyle == .dark ? .dark : .light)119            .environment(\.dynamicTypeSize, DynamicTypeSize(traits.preferredContentSizeCategory) ?? .large)120        let renderer = ImageRenderer(content: view)121        renderer.scale = traits.displayScale > 0 ? traits.displayScale : 2122        renderer.isOpaque = false123        guard let image = renderer.uiImage else { return nil }124        // oldest first out (the card cache holds the bitmaps of the cards on screen; this one avoids re-rendering a chart)125        order.append(key)126        if order.count > 24 { cache[order.removeFirst()] = nil }127        cache[key] = image128        return image129    }130}131
Files main
Menu

Theme