SPB Git

Repository Public License

Components+FamilyCChartsCanvas.swift 13.1 KB 228 lines swift

1import Charts2import PrismCore3import PrismObjectModel4import SwiftUI56/// Family C charts drawn by hand (Canvas / Path) or reduced to a single value.78struct FCGaugeChart: View {9    @Environment(AppRuntime.self) private var runtime10    @Environment(\.prismTheme) private var theme11    let o: PrismObject1213    var body: some View {14        let input = FCChartInput(runtime, theme, o, columns: ["value"])15        let value = input.source.rows.first?[FC.column(o, "value") ?? ""]?.numericValue16        let lower = runtime.number(o.props["min"]) ?? 0, upper = runtime.number(o.props["max"]) ?? 10017        let fraction = FamilyCMath.fraction(value ?? lower, min: lower, max: upper)18        let problem = input.source.problem ?? (upper > lower ? nil : "`max` must be greater than `min`.")19        FCPanel(20            title: input.title, fallbackLabel: "Gauge", problem: problem, isEmpty: value == nil, emptySymbol: "gauge.with.dots.needle.33percent", chart: true,21            summary: "\(input.text(value ?? 0)), between \(input.text(lower)) and \(input.text(upper)): \(Int((fraction * 100).rounded())) percent."22        ) {23            VStack(spacing: 2) {24                Canvas { context, size in25                    let line: CGFloat = 1626                    let radius = max(4, min(size.width / 2, size.height) - line / 2 - 2)27                    let center = CGPoint(x: size.width / 2, y: size.height - line / 2 - 1)28                    func arc(to f: Double) -> Path {29                        Path { $0.addArc(center: center, radius: radius, startAngle: .degrees(180), endAngle: .degrees(180 + 180 * f), clockwise: false) }30                    }31                    context.stroke(arc(to: 1), with: .color(.secondary.opacity(0.2)), style: StrokeStyle(lineWidth: line, lineCap: .round))32                    if fraction > 0 { context.stroke(arc(to: fraction), with: .color(input.color), style: StrokeStyle(lineWidth: line, lineCap: .round)) }33                }34                .frame(height: 110)35                .frame(maxWidth: 240)36                .overlay(alignment: .bottom) {37                    Text(input.text(value ?? 0)).font(.title.weight(.semibold)).monospacedDigit().lineLimit(1).minimumScaleFactor(0.5).padding(.horizontal, 44)38                }39                HStack {40                    Text(input.text(lower))41                    Spacer()42                    Text(input.text(upper))43                }44                .font(.caption).foregroundStyle(.secondary).monospacedDigit().frame(maxWidth: 240)45            }46            .frame(maxWidth: .infinity)47        }48    }49}5051struct FCRadarChart: View {52    @Environment(AppRuntime.self) private var runtime53    @Environment(\.prismTheme) private var theme54    let o: PrismObject5556    var body: some View {57        let input = FCChartInput(runtime, theme, o, columns: ["label", "value"])58        let points = Array(input.points(label: "label", value: "value").prefix(24))59        let top = runtime.number(o.props["max"]) ?? max(points.map(\.value).max() ?? 1, .leastNonzeroMagnitude)60        FCPanel(61            title: input.title, fallbackLabel: "Radar chart", problem: input.source.problem ?? (points.count < 3 && !points.isEmpty ? "A radar chart needs at least three rows; the query returned \(points.count)." : nil),62            isEmpty: points.isEmpty, emptySymbol: "hexagon", chart: true, summary: input.summary(points) + ". Scale up to \(input.text(top))."63        ) {64            Canvas { context, size in65                let center = CGPoint(x: size.width / 2, y: size.height / 2)66                let radius = max(10, min(size.width / 2 - 70, size.height / 2 - 24))67                let full = Array(repeating: 1.0, count: points.count)68                func polygon(_ fractions: [Double]) -> Path {69                    var path = Path()70                    path.addLines(FamilyCMath.radarPoints(fractions, center: center, radius: radius))71                    path.closeSubpath()72                    return path73                }74                for ring in 1...4 { context.stroke(polygon(full.map { $0 * Double(ring) / 4 }), with: .color(.secondary.opacity(0.3)), lineWidth: 0.75) }75                let rim = FamilyCMath.radarPoints(full, center: center, radius: radius)76                for p in rim { context.stroke(Path { $0.move(to: center); $0.addLine(to: p) }, with: .color(.secondary.opacity(0.3)), lineWidth: 0.75) }77                let fractions = points.map { FamilyCMath.fraction($0.value, min: 0, max: top) }78                let shape = polygon(fractions)79                context.fill(shape, with: .color(input.color.opacity(0.25)))80                context.stroke(shape, with: .color(input.color), style: StrokeStyle(lineWidth: 2, lineJoin: .round))81                for p in FamilyCMath.radarPoints(fractions, center: center, radius: radius) {82                    context.fill(Path(ellipseIn: CGRect(x: p.x - 3, y: p.y - 3, width: 6, height: 6)), with: .color(input.color))83                }84                context.draw(Text(input.text(top)).font(.caption2).foregroundStyle(.tertiary), at: CGPoint(x: center.x + 4, y: center.y - radius + 2), anchor: .topLeading)85                for (i, p) in FamilyCMath.radarPoints(full, center: center, radius: radius + 8).enumerated() {86                    let dx = p.x - center.x87                    let anchor: UnitPoint = abs(dx) < 2 ? (p.y < center.y ? .bottom : .top) : dx > 0 ? .leading : .trailing88                    context.draw(Text(points[i].label).font(.caption).foregroundStyle(.secondary), at: p, anchor: anchor)89                }90            }91            .frame(minHeight: 220)92        }93    }94}9596struct FCTreemapChart: View {97    @Environment(AppRuntime.self) private var runtime98    @Environment(\.prismTheme) private var theme99    let o: PrismObject100101    var body: some View {102        let input = FCChartInput(runtime, theme, o, columns: ["label", "value"])103        let points = input.points(label: "label", value: "value").filter { $0.value > 0 }.sorted { $0.value > $1.value }104        let palette = FC.palette(theme)105        let total = points.reduce(0) { $0 + $1.value }106        FCPanel(107            title: input.title, fallbackLabel: "Treemap", problem: input.source.problem, isEmpty: points.isEmpty,108            emptyTitle: input.source.rows.isEmpty ? "No data yet" : "No positive values",109            emptyMessage: input.source.rows.isEmpty ? "The chart fills in as records are added." : "A treemap shows values above zero.",110            emptySymbol: "rectangle.split.2x2", chart: true, summary: input.summary(points)111        ) {112            Canvas { context, size in113                let rects = FamilyCMath.treemap(points.map(\.value), in: CGRect(origin: .zero, size: size))114                for (i, rect) in rects.enumerated() where rect.width > 1 && rect.height > 1 {115                    let tile = rect.insetBy(dx: 1, dy: 1)116                    context.fill(Path(roundedRect: tile, cornerRadius: 3), with: .color(palette[i % palette.count].opacity(0.9)))117                    guard tile.width > 46, tile.height > 20 else { continue }118                    var clipped = context119                    clipped.clip(to: Path(tile))120                    clipped.draw(Text(points[i].label).font(.caption.weight(.semibold)).foregroundStyle(.white), at: CGPoint(x: tile.minX + 6, y: tile.minY + 4), anchor: .topLeading)121                    if tile.height > 38 {122                        let share = total > 0 ? " · " + (points[i].value / total).formatted(.percent.precision(.fractionLength(0)).locale(runtime.locale)) : ""123                        clipped.draw(Text(input.text(points[i].value) + share).font(.caption2).foregroundStyle(.white.opacity(0.9)), at: CGPoint(x: tile.minX + 6, y: tile.minY + 20), anchor: .topLeading)124                    }125                }126            }127            .frame(minHeight: 200)128        }129    }130}131132/// A tiny line without axes, for use inside rows, cards and tiles.133struct FCSparklineChart: View {134    @Environment(AppRuntime.self) private var runtime135    @Environment(\.prismTheme) private var theme136    let o: PrismObject137138    var body: some View {139        let input = FCChartInput(runtime, theme, o, columns: ["y"])140        let column = FC.column(o, "y") ?? ""141        let points = input.source.rows.enumerated().compactMap { i, row in row[column]?.numericValue.map { FCPoint(id: i, label: "", value: $0) } }142        let low = points.map(\.value).min() ?? 0, high = points.map(\.value).max() ?? 1143        let pad = high > low ? (high - low) * 0.12 : 1144        HStack(spacing: 8) {145            if !input.title.isEmpty { Text(input.title).font(.caption).foregroundStyle(.secondary).lineLimit(1) }146            if let problem = input.source.problem {147                Label(problem, systemImage: "exclamationmark.triangle").font(.caption).foregroundStyle(.orange)148            } else if points.isEmpty {149                Text("No data yet").font(.caption).foregroundStyle(.tertiary)150            } else {151                Chart(points) { p in152                    if o.props["fill"]?.boolValue == true {153                        AreaMark(x: .value("Index", p.id), yStart: .value("Base", low - pad), yEnd: .value("Value", p.value)).foregroundStyle(input.color.opacity(0.2)).interpolationMethod(.monotone)154                    }155                    LineMark(x: .value("Index", p.id), y: .value("Value", p.value)).foregroundStyle(input.color).interpolationMethod(.monotone).lineStyle(StrokeStyle(lineWidth: 1.75, lineCap: .round))156                    if p.id == points.last?.id { PointMark(x: .value("Index", p.id), y: .value("Value", p.value)).foregroundStyle(input.color).symbolSize(26) }157                }158                .chartXAxis(.hidden)159                .chartYAxis(.hidden)160                .chartLegend(.hidden)161                .chartYScale(domain: (low - pad)...(high + pad))162                .frame(minWidth: 60, idealWidth: 120, maxWidth: 220, minHeight: 28, maxHeight: 36)163                if o.props["showValue"]?.boolValue != false, let last = points.last {164                    Text(input.text(last.value)).font(.callout.weight(.medium)).monospacedDigit().lineLimit(1)165                }166            }167        }168        .accessibilityElement(children: .ignore)169        .accessibilityLabel(input.title.isEmpty ? "Sparkline" : input.title)170        .accessibilityValue(input.source.problem ?? (points.isEmpty ? "No data yet" : "\(points.count) values from \(input.text(points.first?.value ?? 0)) to \(input.text(points.last?.value ?? 0)); lowest \(input.text(low)), highest \(input.text(high))."))171    }172}173174/// Bullet graph: one measure against a target, over qualitative ranges.175struct FCBulletChart: View {176    @Environment(AppRuntime.self) private var runtime177    @Environment(\.prismTheme) private var theme178    let o: PrismObject179180    struct Band: Identifiable {181        let id: Int182        var lower: Double183        var upper: Double184    }185186    var body: some View {187        let input = FCChartInput(runtime, theme, o, columns: ["value"])188        let value = input.source.rows.first?[FC.column(o, "value") ?? ""]?.numericValue189        let target = runtime.number(o.props["target"])190        let limits = (runtime.resolve(o.props["ranges"]).arrayValue ?? []).compactMap(\.numericValue).filter { $0 > 0 }.sorted()191        let top = runtime.number(o.props["max"]) ?? max(limits.last ?? 0, (target ?? 0) * 1.1, (value ?? 0) * 1.1, .leastNonzeroMagnitude)192        let bands = bands(limits, top: top)193        FCPanel(194            title: input.title, fallbackLabel: "Bullet chart", problem: input.source.problem, isEmpty: value == nil, emptySymbol: "chart.bar.fill", chart: false,195            summary: "\(input.text(value ?? 0))" + (target.map { " against a target of \(input.text($0))" } ?? "") + ", on a scale to \(input.text(top)).",196            trailing: value.map { input.text($0) + (target.map { " / \(input.text($0))" } ?? "") } ?? ""197        ) {198            Chart {199                ForEach(bands) { b in200                    BarMark(xStart: .value("From", b.lower), xEnd: .value("To", b.upper), y: .value("Measure", "value"), height: .fixed(26))201                        .foregroundStyle(Color.secondary.opacity(0.42 - 0.3 * Double(b.id) / Double(max(bands.count - 1, 1))))202                }203                BarMark(xStart: .value("From", 0), xEnd: .value("Value", min(max(value ?? 0, 0), top)), y: .value("Measure", "value"), height: .fixed(10))204                    .foregroundStyle(input.color)205                if let target, target >= 0, target <= top {206                    RectangleMark(x: .value("Target", target), y: .value("Measure", "value"), width: .fixed(3), height: .fixed(22)).foregroundStyle(Color.primary)207                }208            }209            .chartYAxis(.hidden)210            .chartXScale(domain: 0...top)211            .fcValueAxis(horizontal: true, input.text)212            .frame(height: 58)213        }214    }215216    /// Consecutive bands up to each limit, then to the top of the scale; a single band when no ranges are given.217    private func bands(_ limits: [Double], top: Double) -> [Band] {218        var out: [Band] = []219        var lower = 0.0220        for limit in limits where limit < top && limit > lower {221            out.append(Band(id: out.count, lower: lower, upper: limit))222            lower = limit223        }224        out.append(Band(id: out.count, lower: lower, upper: top))225        return out226    }227}228
Files main
Menu

Theme