SPB Git

Repository Public License

ChartAndNavigationComponents.swift 6.4 KB 151 lines swift

1import Charts2import PrismCore3import PrismObjectModel4import SwiftUI56struct ChartPoint: Identifiable {7    let id: Int8    let label: String9    let value: Double10}1112@MainActor13private func chartPoints(_ runtime: AppRuntime, _ o: PrismObject, labelKey: String, valueKey: String) -> [ChartPoint] {14    let query = o.props["query"].flatMap { $0["$ref"]?.stringValue.flatMap { runtime.blueprint.object($0)?.props["query"] } ?? $0 }15    let x = o.props[labelKey]?.stringValue ?? "", y = o.props[valueKey]?.stringValue ?? ""16    return runtime.rows(query).enumerated().map { i, row in17        let label = row[x]?.displayString ?? ""18        return ChartPoint(id: i, label: label.isEmpty ? "(none)" : label, value: row[y]?.numericValue ?? 0)19    }20}2122private struct ChartFrame<Content: View>: View {23    let title: String24    let points: [ChartPoint]25    let summary: String26    @ViewBuilder var content: Content27    @Environment(\.prismTheme) private var theme2829    var body: some View {30        VStack(alignment: .leading, spacing: 8) {31            if !title.isEmpty { Text(title).font(.headline).accessibilityAddTraits(.isHeader) }32            if points.isEmpty {33                ContentUnavailableView("No data yet", systemImage: "chart.bar.xaxis", description: Text("The chart fills in as records are added."))34                    .frame(maxWidth: .infinity, minHeight: 160)35            } else {36                content.frame(minHeight: 200)37            }38        }39        .padding(14)40        .frame(maxWidth: .infinity, alignment: .leading)41        .prismSurface()42        .accessibilityElement(children: .contain)43        .accessibilityLabel(title.isEmpty ? "Chart" : title)44        .accessibilityValue(summary)45    }46}4748struct ChartComponent: View {49    enum Kind { case line, bar }50    @Environment(AppRuntime.self) private var runtime51    @Environment(\.prismTheme) private var theme52    let o: PrismObject53    let kind: Kind5455    var body: some View {56        let points = chartPoints(runtime, o, labelKey: "x", valueKey: "y")57        let currency = o.props["format"]?.stringValue == "currency"58        let tone = runtime.string(o.props["tone"])59        let color = tone.isEmpty || tone == "neutral" ? theme.accent : theme.color(tone)60        let format: (Double) -> String = { v in CellFormat.text(.double(v), format: currency ? "currency" : "number", runtime: runtime) }61        ChartFrame(title: runtime.string(o.props["title"]), points: points, summary: points.map { "\($0.label): \(format($0.value))" }.joined(separator: ", ")) {62            Chart(points) { p in63                if kind == .bar {64                    BarMark(x: .value("Group", p.label), y: .value("Value", p.value)).foregroundStyle(color.gradient).cornerRadius(3)65                } else {66                    LineMark(x: .value("Group", p.label), y: .value("Value", p.value)).foregroundStyle(color).interpolationMethod(.monotone)67                    PointMark(x: .value("Group", p.label), y: .value("Value", p.value)).foregroundStyle(color)68                }69            }70            .chartYAxis {71                AxisMarks { value in72                    AxisGridLine()73                    AxisValueLabel { if let v = value.as(Double.self) { Text(format(v)) } }74                }75            }76        }77    }78}7980struct PieChartComponent: View {81    @Environment(AppRuntime.self) private var runtime82    let o: PrismObject8384    var body: some View {85        let points = chartPoints(runtime, o, labelKey: "label", valueKey: "value").filter { $0.value > 0 }86        let currency = o.props["format"]?.stringValue == "currency"87        let format: (Double) -> String = { v in CellFormat.text(.double(v), format: currency ? "currency" : "number", runtime: runtime) }88        ChartFrame(title: runtime.string(o.props["title"]), points: points, summary: points.map { "\($0.label): \(format($0.value))" }.joined(separator: ", ")) {89            Chart(points) { p in90                SectorMark(angle: .value("Value", p.value), innerRadius: .ratio(o.props["donut"]?.boolValue == false ? 0 : 0.58), angularInset: 1.5)91                    .foregroundStyle(by: .value("Group", p.label))92                    .cornerRadius(3)93            }94            .chartLegend(position: .trailing, alignment: .center)95            .modifier(ThemeChartPalette())96        }97    }98}99100struct SidebarComponent: View {101    @Environment(AppRuntime.self) private var runtime102    let o: PrismObject103    @State private var local: String?104105    var body: some View {106        let selection = ChildSelection(runtime: runtime, o: o, local: $local)107        HStack(spacing: 0) {108            List(o.children, id: \.self, selection: Binding<String?>(get: { selection.current }, set: { if let id = $0 { selection.select(id) } })) { id in109                Label(selection.title(id), systemImage: SymbolName.safe(o.props["icons"]?[id]?.stringValue, fallback: "circle")).tag(id)110            }111            .listStyle(.sidebar)112            .frame(width: 190)113            .accessibilityLabel(o.name.isEmpty ? "Sections" : o.name)114            Divider()115            if !selection.current.isEmpty {116                NodeView(id: selection.current).padding(16).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)117            }118        }119    }120}121122struct InspectorComponent: View {123    @Environment(AppRuntime.self) private var runtime124    @Environment(\.prismTheme) private var theme125    @Environment(\.prismDesign) private var design126    let o: PrismObject127128    var body: some View {129        if design != nil || runtime.bool(o.props["presented"], default: true) {130            let title = runtime.string(o.props["title"])131            VStack(alignment: .leading, spacing: theme.spacing) {132                if !title.isEmpty { Text(title).font(.headline).accessibilityAddTraits(.isHeader) }133                ChildrenView(ids: o.children)134                Spacer(minLength: 0)135            }136            .padding(14)137            .frame(width: CGFloat(o.props["panelWidth"]?.doubleValue ?? 280), alignment: .topLeading)138            .frame(maxHeight: .infinity, alignment: .topLeading)139            .prismSurface()140        }141    }142}143144/// Uses the theme's chart palette for grouped marks when it defines one.145struct ThemeChartPalette: ViewModifier {146    @Environment(\.prismTheme) private var theme147    func body(content: Content) -> some View {148        if theme.chartColors.isEmpty { content } else { content.chartForegroundStyleScale(range: theme.chartColors) }149    }150}151
Files main
Menu

Theme