SPB Git

Repository Public License

Components+FamilyCCharts.swift 22.3 KB 430 lines swift

1import Charts2import PrismCore3import PrismObjectModel4import SwiftUI56struct FCPoint: Identifiable {7    let id: Int8    var label: String9    var value: Double10    var series = ""11    var x = 0.012    var size = 0.013}1415/// What every family C chart reads first: title, rows (or the reason there are none), color and value format.16@MainActor17struct FCChartInput {18    let runtime: AppRuntime19    let o: PrismObject20    let title: String21    let source: FCSource22    let color: Color23    let format: String2425    /// `columns` are the names of the props that must each name a column of the query.26    init(_ runtime: AppRuntime, _ theme: PrismTheme, _ o: PrismObject, columns: [String]) {27        self.runtime = runtime28        self.o = o29        title = runtime.string(o.props["title"])30        color = FC.toneColor(theme, runtime.string(o.props["tone"]))31        format = o.props["format"]?.stringValue ?? "number"32        if let unset = columns.first(where: { FC.column(o, $0) == nil }) {33            source = FCSource(problem: "Set `\(unset)` to a column of the query.")34        } else {35            source = FC.source(runtime, o, columns: columns.map { FC.column(o, $0) })36        }37    }3839    func text(_ value: Double) -> String { FC.number(runtime, value, format) }40    func plain(_ value: Double) -> String { FC.number(runtime, value, "number") }4142    /// One point per row: the text of the `label` prop's column and the number in the `value` prop's column.43    func points(label: String, value: String, series: String? = nil) -> [FCPoint] {44        let l = FC.column(o, label) ?? "", v = FC.column(o, value) ?? "", s = series.flatMap { FC.column(o, $0) }45        return source.rows.enumerated().map { i, row in46            FCPoint(id: i, label: FC.label(row[l]), value: row[v]?.numericValue ?? 0, series: s.map { FC.label(row[$0]) } ?? "")47        }48    }4950    func summary(_ points: [FCPoint]) -> String {51        let listed = points.prefix(24).map { "\($0.series.isEmpty ? "" : $0.series + ", ")\($0.label): \(text($0.value))" }.joined(separator: "; ")52        return points.count > 24 ? listed + "; and \(points.count - 24) more" : listed53    }54}5556extension View {57    /// Value axis labelled with the chart's number format.58    func fcValueAxis(horizontal: Bool = false, _ text: @escaping (Double) -> String) -> some View {59        Group {60            if horizontal {61                chartXAxis { AxisMarks { value in AxisGridLine(); AxisValueLabel { if let v = value.as(Double.self) { Text(text(v)) } } } }62            } else {63                chartYAxis { AxisMarks { value in AxisGridLine(); AxisValueLabel { if let v = value.as(Double.self) { Text(text(v)) } } } }64            }65        }66    }67}6869struct FCAreaChart: View {70    @Environment(AppRuntime.self) private var runtime71    @Environment(\.prismTheme) private var theme72    let o: PrismObject7374    var body: some View {75        let input = FCChartInput(runtime, theme, o, columns: ["x", "y"])76        let points = input.points(label: "x", value: "y")77        FCPanel(title: input.title, fallbackLabel: "Area chart", problem: input.source.problem, isEmpty: points.isEmpty, emptySymbol: "chart.xyaxis.line", chart: true, summary: input.summary(points)) {78            Chart(points) { p in79                AreaMark(x: .value("Group", p.label), y: .value("Value", p.value)).foregroundStyle(input.color.opacity(0.28).gradient).interpolationMethod(.monotone)80                LineMark(x: .value("Group", p.label), y: .value("Value", p.value)).foregroundStyle(input.color).interpolationMethod(.monotone)81                if points.count == 1 { PointMark(x: .value("Group", p.label), y: .value("Value", p.value)).foregroundStyle(input.color) }82            }83            .fcValueAxis(input.text)84            .frame(minHeight: 180)85        }86    }87}8889/// Scatter plot of two numeric columns; as a bubble chart a third column sets the area of each point.90struct FCScatterChart: View {91    @Environment(AppRuntime.self) private var runtime92    @Environment(\.prismTheme) private var theme93    let o: PrismObject94    let bubble: Bool9596    var body: some View {97        let input = FCChartInput(runtime, theme, o, columns: bubble ? ["x", "y", "size"] : ["x", "y"])98        let xName = FC.column(o, "x") ?? "", yName = FC.column(o, "y") ?? "", sizeName = FC.column(o, "size") ?? ""99        let labelName = FC.column(o, "labelColumn")100        let points: [FCPoint] = input.source.rows.enumerated().compactMap { i, row in101            guard let x = row[xName]?.numericValue, let y = row[yName]?.numericValue else { return nil }102            return FCPoint(id: i, label: labelName.map { FC.label(row[$0]) } ?? "", value: y, x: x, size: max(0, row[sizeName]?.numericValue ?? 0))103        }104        let skipped = input.source.rows.count - points.count105        FCPanel(106            title: input.title, fallbackLabel: bubble ? "Bubble chart" : "Scatter plot", problem: input.source.problem, isEmpty: points.isEmpty,107            emptyTitle: input.source.rows.isEmpty ? "No data yet" : "No numeric values",108            emptyMessage: input.source.rows.isEmpty ? "The chart fills in as records are added." : "“\(xName)” and “\(yName)” must hold numbers.",109            emptySymbol: "chart.dots.scatter", chart: true, summary: summary(points, input, xName, yName),110            trailing: skipped > 0 && !points.isEmpty ? "\(skipped) row\(skipped == 1 ? "" : "s") without numbers skipped" : ""111        ) {112            Chart(points) { p in113                if bubble {114                    PointMark(x: .value(input.source.title(xName), p.x), y: .value(input.source.title(yName), p.value))115                        .symbolSize(by: .value(input.source.title(sizeName), p.size))116                        .foregroundStyle(input.color.opacity(0.55))117                        .annotation(position: .overlay) { if !p.label.isEmpty { Text(p.label).font(.caption2).lineLimit(1).fixedSize() } }118                } else {119                    PointMark(x: .value(input.source.title(xName), p.x), y: .value(input.source.title(yName), p.value))120                        .foregroundStyle(input.color)121                        .annotation(position: .top, spacing: 2) { if !p.label.isEmpty { Text(p.label).font(.caption2).foregroundStyle(.secondary).lineLimit(1).fixedSize() } }122                }123            }124            .chartSymbolSizeScale(range: 120...2400)125            .chartXScale(domain: Self.domain(points.map(\.x)))126            .chartYScale(domain: Self.domain(points.map(\.value)))127            .chartLegend(.hidden)128            .chartXAxisLabel(input.source.title(xName))129            .chartYAxisLabel(input.source.title(yName))130            .fcValueAxis(input.text)131            .frame(minHeight: 200)132        }133    }134135    /// The data range with a margin, so points and bubbles at the edges are not cut off.136    static func domain(_ values: [Double]) -> ClosedRange<Double> {137        guard let low = values.min(), let high = values.max() else { return 0...1 }138        let pad = high > low ? (high - low) * 0.15 : max(abs(high) * 0.1, 1)139        return (low - pad)...(high + pad)140    }141142    private func summary(_ points: [FCPoint], _ input: FCChartInput, _ x: String, _ y: String) -> String {143        guard let xmin = points.map(\.x).min(), let xmax = points.map(\.x).max(), let ymin = points.map(\.value).min(), let ymax = points.map(\.value).max() else { return "" }144        return "\(points.count) points. \(x) from \(input.plain(xmin)) to \(input.plain(xmax)); \(y) from \(input.text(ymin)) to \(input.text(ymax))."145    }146}147148/// Stacked bars or one line per series: x, y and a series column.149struct FCSeriesChart: View {150    @Environment(AppRuntime.self) private var runtime151    @Environment(\.prismTheme) private var theme152    let o: PrismObject153    let lines: Bool154155    var body: some View {156        let input = FCChartInput(runtime, theme, o, columns: ["x", "y", "series"])157        let points = input.points(label: "x", value: "y", series: "series")158        FCPanel(title: input.title, fallbackLabel: lines ? "Multi-line chart" : "Stacked bar chart", problem: input.source.problem, isEmpty: points.isEmpty, emptySymbol: lines ? "chart.xyaxis.line" : "chart.bar.xaxis", chart: true, summary: input.summary(points)) {159            Chart(points) { p in160                if lines {161                    LineMark(x: .value("Group", p.label), y: .value("Value", p.value), series: .value("Series", p.series))162                        .foregroundStyle(by: .value("Series", p.series)).interpolationMethod(.monotone)163                    PointMark(x: .value("Group", p.label), y: .value("Value", p.value)).foregroundStyle(by: .value("Series", p.series))164                } else {165                    BarMark(x: .value("Group", p.label), y: .value("Value", p.value)).foregroundStyle(by: .value("Series", p.series)).cornerRadius(2)166                }167            }168            .modifier(ThemeChartPalette())169            .fcValueAxis(input.text)170            .frame(minHeight: 200)171        }172    }173}174175struct FCHorizontalBarChart: View {176    @Environment(AppRuntime.self) private var runtime177    @Environment(\.prismTheme) private var theme178    let o: PrismObject179180    var body: some View {181        let input = FCChartInput(runtime, theme, o, columns: ["label", "value"])182        let points = input.points(label: "label", value: "value")183        FCPanel(title: input.title, fallbackLabel: "Horizontal bar chart", problem: input.source.problem, isEmpty: points.isEmpty, emptySymbol: "chart.bar.xaxis", chart: true, summary: input.summary(points)) {184            Chart(points) { p in185                BarMark(x: .value("Value", p.value), y: .value("Group", p.label))186                    .foregroundStyle(input.color.gradient).cornerRadius(3)187                    .annotation(position: .trailing, spacing: 4) { Text(input.text(p.value)).font(.caption).foregroundStyle(.secondary).monospacedDigit() }188            }189            .fcValueAxis(horizontal: true, input.text)190            .chartXScale(range: .plotDimension(endPadding: 56))191            .frame(minHeight: min(420, max(120, CGFloat(points.count) * 30 + 30)))192        }193    }194}195196struct FCHeatmapChart: View {197    @Environment(AppRuntime.self) private var runtime198    @Environment(\.prismTheme) private var theme199    let o: PrismObject200201    struct Cell: Identifiable {202        let id: Int203        var x: String204        var y: String205        var value: Double206    }207208    var body: some View {209        let input = FCChartInput(runtime, theme, o, columns: ["x", "y", "value"])210        let cells = cells(input)211        let low = cells.map(\.value).min() ?? 0, high = cells.map(\.value).max() ?? 0212        let showValues = o.props["showValues"]?.boolValue != false213        FCPanel(title: input.title, fallbackLabel: "Heatmap", problem: input.source.problem, isEmpty: cells.isEmpty, emptySymbol: "square.grid.3x3.fill", chart: true, summary: summary(cells, input)) {214            Chart(cells) { c in215                let f = high > low ? FamilyCMath.fraction(c.value, min: low, max: high) : 1216                RectangleMark(x: .value("Column", c.x), y: .value("Row", c.y))217                    .foregroundStyle(input.color.opacity(0.12 + 0.88 * f))218                    .cornerRadius(3)219                    .annotation(position: .overlay) {220                        if showValues { Text(input.text(c.value)).font(.caption2).monospacedDigit().foregroundStyle(f > 0.55 ? Color.white : Color.primary) }221                    }222            }223            .chartXAxis { AxisMarks { _ in AxisValueLabel() } }224            .chartYAxis { AxisMarks { _ in AxisValueLabel() } }225            .frame(minHeight: 180)226        }227    }228229    /// One cell per (x, y) pair; rows that share a pair are added together.230    private func cells(_ input: FCChartInput) -> [Cell] {231        let x = FC.column(o, "x") ?? "", y = FC.column(o, "y") ?? "", v = FC.column(o, "value") ?? ""232        var order: [String] = []233        var cells: [String: Cell] = [:]234        for row in input.source.rows {235            let cx = FC.label(row[x]), cy = FC.label(row[y]), key = cx + "\u{1}" + cy236            if cells[key] == nil { cells[key] = Cell(id: order.count, x: cx, y: cy, value: 0); order.append(key) }237            cells[key]?.value += row[v]?.numericValue ?? 0238        }239        return order.compactMap { cells[$0] }240    }241242    private func summary(_ cells: [Cell], _ input: FCChartInput) -> String {243        guard let top = cells.max(by: { $0.value < $1.value }), let bottom = cells.min(by: { $0.value < $1.value }) else { return "" }244        return "\(cells.count) cells. Highest: \(top.x), \(top.y): \(input.text(top.value)). Lowest: \(bottom.x), \(bottom.y): \(input.text(bottom.value))."245    }246}247248struct FCHistogramChart: View {249    @Environment(AppRuntime.self) private var runtime250    @Environment(\.prismTheme) private var theme251    let o: PrismObject252253    struct Bar: Identifiable {254        let id: Int255        let bin: FamilyCMath.Bin256    }257258    var body: some View {259        let input = FCChartInput(runtime, theme, o, columns: ["value"])260        let column = FC.column(o, "value") ?? ""261        let values = input.source.rows.compactMap { $0[column]?.numericValue }262        let bins = FamilyCMath.histogram(values, bins: o.props["bins"]?.intValue ?? 10).enumerated().map { Bar(id: $0.offset, bin: $0.element) }263        FCPanel(264            title: input.title, fallbackLabel: "Histogram", problem: input.source.problem, isEmpty: bins.isEmpty,265            emptyTitle: input.source.rows.isEmpty ? "No data yet" : "No numeric values",266            emptyMessage: input.source.rows.isEmpty ? "The chart fills in as records are added." : "“\(column)” must hold numbers.",267            emptySymbol: "chart.bar.fill", chart: true, summary: summary(bins, values.count, input)268        ) {269            Chart(bins) { b in270                RectangleMark(xStart: .value("From", b.bin.lower + (b.bin.upper - b.bin.lower) * 0.02), xEnd: .value("To", b.bin.upper - (b.bin.upper - b.bin.lower) * 0.02), yStart: .value("Zero", 0), yEnd: .value("Count", b.bin.count))271                    .foregroundStyle(input.color.opacity(0.85))272                    .cornerRadius(2)273            }274            .chartXScale(domain: (bins.first?.bin.lower ?? 0)...(bins.last?.bin.upper ?? 1))275            .chartXAxis { AxisMarks { value in AxisGridLine(); AxisValueLabel { if let v = value.as(Double.self) { Text(input.text(v)) } } } }276            .chartXAxisLabel(input.source.title(column))277            .chartYAxisLabel("Records")278            .frame(minHeight: 180)279        }280    }281282    private func summary(_ bins: [Bar], _ count: Int, _ input: FCChartInput) -> String {283        guard let first = bins.first, let last = bins.last, let top = bins.max(by: { $0.bin.count < $1.bin.count }) else { return "" }284        return "\(count) values in \(bins.count) bins from \(input.text(first.bin.lower)) to \(input.text(last.bin.upper)). Fullest: \(input.text(top.bin.lower)) to \(input.text(top.bin.upper)) with \(top.bin.count)."285    }286}287288struct FCFunnelChart: View {289    @Environment(AppRuntime.self) private var runtime290    @Environment(\.prismTheme) private var theme291    let o: PrismObject292293    var body: some View {294        let input = FCChartInput(runtime, theme, o, columns: ["label", "value"])295        let points = input.points(label: "label", value: "value").map { p in FCPoint(id: p.id, label: p.label, value: max(0, p.value)) }296        let first = points.first?.value ?? 0297        let share: (FCPoint) -> String = { p in first > 0 ? (p.value / first).formatted(.percent.precision(.fractionLength(0)).locale(runtime.locale)) : "—" }298        FCPanel(299            title: input.title, fallbackLabel: "Funnel chart", problem: input.source.problem, isEmpty: points.isEmpty, emptySymbol: "line.3.horizontal.decrease", chart: true,300            summary: points.map { "\($0.label): \(input.text($0.value)) (\(share($0)))" }.joined(separator: "; ")301        ) {302            Chart(points) { p in303                BarMark(xStart: .value("Start", -p.value / 2), xEnd: .value("End", p.value / 2), y: .value("Stage", p.label))304                    .foregroundStyle(input.color.opacity(first > 0 ? 0.45 + 0.55 * (p.value / first) : 1))305                    .cornerRadius(4)306                    .annotation(position: .overlay) {307                        Text("\(input.text(p.value)) · \(share(p))").font(.caption.weight(.medium)).monospacedDigit().lineLimit(1).fixedSize()308                            .padding(.horizontal, 6).padding(.vertical, 1).background(.background.opacity(0.75), in: Capsule())309                    }310            }311            .chartXAxis(.hidden)312            .chartXScale(domain: (-max(first, points.map(\.value).max() ?? 1) / 2 * 1.02)...(max(first, points.map(\.value).max() ?? 1) / 2 * 1.02))313            .frame(minHeight: min(420, max(120, CGFloat(points.count) * 40)))314        }315    }316}317318struct FCWaterfallChart: View {319    @Environment(AppRuntime.self) private var runtime320    @Environment(\.prismTheme) private var theme321    let o: PrismObject322323    struct Step: Identifiable {324        let id: Int325        var label: String326        var start: Double327        var end: Double328        var isTotal = false329    }330331    var body: some View {332        let input = FCChartInput(runtime, theme, o, columns: ["label", "value"])333        let points = input.points(label: "label", value: "value")334        let steps = steps(points)335        FCPanel(336            title: input.title, fallbackLabel: "Waterfall chart", problem: input.source.problem, isEmpty: points.isEmpty, emptySymbol: "chart.bar.xaxis", chart: true,337            summary: steps.map { $0.isTotal ? "\($0.label): \(input.text($0.end))" : "\($0.label): \(input.text($0.end - $0.start)), running total \(input.text($0.end))" }.joined(separator: "; ")338        ) {339            Chart(steps) { s in340                BarMark(x: .value("Step", s.label), yStart: .value("Start", s.start), yEnd: .value("End", s.end), width: .ratio(0.6))341                    .foregroundStyle(s.isTotal ? input.color : s.end >= s.start ? theme.color("success") : theme.color("danger"))342                    .cornerRadius(2)343                    .annotation(position: s.end >= s.start ? .top : .bottom, spacing: 2) {344                        Text(input.text(s.isTotal ? s.end : s.end - s.start)).font(.caption2).monospacedDigit().foregroundStyle(.secondary)345                    }346            }347            .fcValueAxis(input.text)348            .frame(minHeight: 200)349        }350    }351352    private func steps(_ points: [FCPoint]) -> [Step] {353        let running = FamilyCMath.waterfall(points.map(\.value))354        var used = Set<String>()355        var out: [Step] = zip(points, running).map { p, r in356            // Bars are keyed by label: a repeated label gets a suffix so both steps stay visible.357            var label = p.label358            var n = 2359            while used.contains(label) { label = "\(p.label) (\(n))"; n += 1 }360            used.insert(label)361            return Step(id: p.id, label: label, start: r.start, end: r.end)362        }363        if o.props["showTotal"]?.boolValue != false, let last = running.last {364            var label = runtime.string(o.props["totalLabel"])365            if label.isEmpty { label = "Total" }366            while used.contains(label) { label += " " }367            out.append(Step(id: points.count, label: label, start: 0, end: last.end, isTotal: true))368        }369        return out370    }371}372373struct FCCandlestickChart: View {374    @Environment(AppRuntime.self) private var runtime375    @Environment(\.prismTheme) private var theme376    let o: PrismObject377378    struct Candle: Identifiable {379        let id: Int380        var label: String381        var open: Double382        var high: Double383        var low: Double384        var close: Double385    }386387    var body: some View {388        let input = FCChartInput(runtime, theme, o, columns: ["x", "open", "high", "low", "close"])389        let candles = candles(input)390        let low = candles.map(\.low).min() ?? 0, high = candles.map(\.high).max() ?? 1391        let pad = max((high - low) * 0.06, high == low ? 1 : 0)392        let up = theme.color("success"), down = theme.color("danger")393        FCPanel(394            title: input.title, fallbackLabel: "Candlestick chart", problem: input.source.problem, isEmpty: candles.isEmpty,395            emptyTitle: input.source.rows.isEmpty ? "No data yet" : "No complete rows",396            emptyMessage: input.source.rows.isEmpty ? "The chart fills in as records are added." : "Each row needs numeric open, high, low and close values.",397            emptySymbol: "chart.bar.xaxis", chart: true, summary: summary(candles, input)398        ) {399            Chart(candles) { c in400                RectangleMark(x: .value("Period", c.label), yStart: .value("Low", c.low), yEnd: .value("High", c.high), width: .fixed(1.5))401                    .foregroundStyle(c.close >= c.open ? up : down)402                RectangleMark(x: .value("Period", c.label), yStart: .value("Open", min(c.open, c.close)), yEnd: .value("Close", max(c.open, c.close)), width: .ratio(0.55))403                    .foregroundStyle(c.close >= c.open ? up : down)404                if c.open == c.close {405                    RectangleMark(x: .value("Period", c.label), y: .value("Close", c.close), width: .ratio(0.55), height: .fixed(1.5)).foregroundStyle(up)406                }407            }408            .chartYScale(domain: (low - pad)...(high + pad))409            .fcValueAxis(input.text)410            .frame(minHeight: 200)411        }412    }413414    private func candles(_ input: FCChartInput) -> [Candle] {415        let names = ["x", "open", "high", "low", "close"].map { FC.column(o, $0) ?? "" }416        return input.source.rows.enumerated().compactMap { i, row in417            guard let open = row[names[1]]?.numericValue, let high = row[names[2]]?.numericValue, let low = row[names[3]]?.numericValue,418                  let close = row[names[4]]?.numericValue else { return nil }419            let label = input.source.format(names[0]) == "date" ? CellFormat.text(row[names[0]] ?? .null, format: "date", runtime: runtime) : FC.label(row[names[0]])420            return Candle(id: i, label: label.isEmpty ? "(none)" : label, open: open, high: max(high, open, close, low), low: min(low, open, close, high), close: close)421        }422    }423424    private func summary(_ candles: [Candle], _ input: FCChartInput) -> String {425        guard let first = candles.first, let last = candles.last else { return "" }426        let low = candles.map(\.low).min() ?? 0, high = candles.map(\.high).max() ?? 0427        return "\(candles.count) periods from \(first.label) to \(last.label). Opened at \(input.text(first.open)), closed at \(input.text(last.close)); low \(input.text(low)), high \(input.text(high))."428    }429}430
Files main
Menu

Theme