SPB Git

Repository Public

LabResultView.swift 16.1 KB 283 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Lab/LabResultView.swift3// Description: The generic renderer of a `lab/1` result: headline, warnings, metric grid, figures, tables,4//              diagnostics, assumptions, methodology, provenance. One view for every engine, on both platforms.5import SwiftUI6import VQuantKit78public struct LabResultView: View {9    public struct Options: Sendable, Equatable {10        /// Rows of a table shown before "show all".11        public var tableRowLimit = 1212        public var chartHeight: CGFloat = 25013        /// Points drawn per series (longer series are reduced for display).14        public var maxChartPoints = 60015        /// Everything open and no row limit (exports).16        public var expanded = false17        /// Sections to leave out.18        public var hidden: Set<Section> = []19        public init() {}20    }21    public enum Section: String, Sendable, Hashable, CaseIterable { case summary, charts, tables, diagnostics, assumptions, methodology, provenance }2223    private let result: VQLabResult24    private let options: Options25    @Environment(\.vqTheme) private var theme26    @State private var expandedTables: Set<String> = []2728    public init(_ result: VQLabResult, options: Options = Options()) { self.result = result; self.options = options }2930    private func shows(_ s: Section) -> Bool { !options.hidden.contains(s) }3132    public var body: some View {33        VStack(alignment: .leading, spacing: VQS.s8) {34            header35            if !result.success {36                VQEmptyState(systemImage: "exclamationmark.triangle", title: theme.l("The computation did not complete"), message: result.error)37            } else {38                if !result.warnings.isEmpty { warnings }39                if shows(.summary), !result.summary.isEmpty {40                    section(theme.l("Summary")) { VQMetricGrid(result.summary) }41                }42                if shows(.charts), !result.charts.isEmpty {43                    section(theme.l("Figures")) {44                        // two columns where there is room (Mac, iPad), one otherwise (iPhone, narrow panes)45                        ViewThatFits(in: .horizontal) {46                            LazyVGrid(columns: [GridItem(.flexible(minimum: 380), spacing: VQS.s6, alignment: .top), GridItem(.flexible(minimum: 380), spacing: VQS.s6, alignment: .top)], alignment: .leading, spacing: VQS.s8) { figures }47                            VStack(alignment: .leading, spacing: VQS.s8) { figures }48                        }49                    }50                }51                if shows(.tables), !result.tables.isEmpty { section(theme.l("Tables")) { tables } }52                if shows(.diagnostics), !result.diagnostics.isEmpty { section(theme.l("Diagnostics")) { LabDiagnosticsList(result.diagnostics) } }53                if shows(.assumptions), !result.assumptions.isEmpty { section(theme.l("Assumptions")) { assumptions } }54                if shows(.methodology), !result.methodology.isEmpty { section(theme.l("Methodology")) { VQMarkdownText(result.methodology).frame(maxWidth: 760, alignment: .leading) } }55                if shows(.provenance), let p = result.provenance { section(theme.l("Provenance")) { LabProvenancePanel(p) } }56            }57        }58        .frame(maxWidth: .infinity, alignment: .leading)59    }6061    private var figures: some View {62        ForEach(Array(result.charts.enumerated()), id: \.offset) { i, chart in63            VStack(alignment: .leading, spacing: VQS.s1) {64                Text("FIG. \(i + 1)").font(.system(size: 9.5, weight: .medium, design: .monospaced)).foregroundStyle(VQP.text3)65                LabChartView(chart, height: options.chartHeight, maxPoints: options.maxChartPoints)66            }67        }68    }6970    private func section<C: View>(_ title: String, @ViewBuilder _ content: () -> C) -> some View {71        VStack(alignment: .leading, spacing: VQS.s4) {72            VQSectionHeader(title)73            content()74        }75    }7677    private var header: some View {78        VStack(alignment: .leading, spacing: VQS.s2) {79            Text([result.engine.replacingOccurrences(of: "_", with: " "), result.engineVersion.map { "v\($0)" }].compactMap { $0 }.joined(separator: " · "))80                .vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3)81            if !result.title.isEmpty {82                Text(result.title).vqFont(VQTokens.Typography.displayMd).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)83                    .accessibilityAddTraits(.isHeader)84            }85            if !result.headline.isEmpty {86                Text(result.headline).vqFont(VQTokens.Typography.body).lineSpacing(4).foregroundStyle(VQP.text2).fixedSize(horizontal: false, vertical: true).frame(maxWidth: 760, alignment: .leading)87            }88        }89    }9091    private var warnings: some View {92        VStack(alignment: .leading, spacing: VQS.s2) {93            ForEach(Array(result.warnings.enumerated()), id: \.offset) { _, w in94                HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {95                    Image(systemName: "exclamationmark.triangle").font(.system(size: 11, weight: .semibold)).foregroundStyle(VQP.warn).accessibilityHidden(true)96                    Text(w).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)97                }98                .accessibilityElement(children: .combine)99                .accessibilityLabel(theme.l("Warning: ") + w)100            }101        }102        .padding(VQS.s3)103        .frame(maxWidth: .infinity, alignment: .leading)104        .overlay(alignment: .leading) { Rectangle().fill(VQP.warn).frame(width: 2) }105        .background(VQP.ink1)106    }107108    private var tables: some View {109        VStack(alignment: .leading, spacing: VQS.s6) {110            ForEach(result.tables) { table in111                let open = options.expanded || expandedTables.contains(table.id)112                let limited = !open && table.rows.count > options.tableRowLimit113                VStack(alignment: .leading, spacing: VQS.s2) {114                    Text(table.title).vqFont(VQTokens.Typography.heading).foregroundStyle(VQP.text1).accessibilityAddTraits(.isHeader)115                    VQDataTable(table, rowLimit: limited ? options.tableRowLimit : nil, locale: theme.numberLocale)116                    if table.rows.count > options.tableRowLimit, !options.expanded {117                        Button {118                            if open { expandedTables.remove(table.id) } else { expandedTables.insert(table.id) }119                        } label: {120                            Text(open ? theme.l("Show fewer") : theme.l("Show all %lld rows", table.rows.count))121                                .vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.accentText)122                        }123                        .buttonStyle(.plain)124                    }125                    if let note = table.note, !note.isEmpty {126                        Text(note).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).fixedSize(horizontal: false, vertical: true).frame(maxWidth: 760, alignment: .leading)127                    }128                }129            }130        }131    }132133    private var assumptions: some View {134        VStack(alignment: .leading, spacing: VQS.s2) {135            ForEach(Array(result.assumptions.enumerated()), id: \.offset) { _, a in136                HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {137                    VQKindBadge(.assumption)138                    Text(VQMarkdown.attributed(a)).vqFont(VQTokens.Typography.bodySm).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)139                }140            }141        }142        .frame(maxWidth: 760, alignment: .leading)143    }144}145146/// Diagnostics with a verdict glyph: ✓ passed, ✗ failed, ○ informational. Glyph and word, never colour alone.147public struct LabDiagnosticsList: View {148    private let diagnostics: [VQLabResult.Diagnostic]149    @Environment(\.vqTheme) private var theme150    public init(_ diagnostics: [VQLabResult.Diagnostic]) { self.diagnostics = diagnostics }151152    private func verdict(_ passed: Bool?) -> (symbol: String, color: Color, word: String) {153        switch passed {154        case true?: return ("checkmark.circle", theme.upDown.up, theme.l("passed"))155        case false?: return ("xmark.circle", VQP.critical, theme.l("failed (check)"))156        case nil: return ("circle.dotted", VQP.text3, theme.l("informational"))157        }158    }159    private func figures(_ d: VQLabResult.Diagnostic) -> String {160        var parts: [String] = []161        if let s = d.statistic { parts.append(theme.l("stat ") + VQFormat.number(s, decimals: abs(s) >= 100 ? 1 : 3, locale: theme.numberLocale)) }162        if let df = d.df { parts.append("df \(df)") }163        if let p = d.pvalue { parts.append("p " + (p < 0.0001 ? "< " + VQFormat.number(0.0001, decimals: 4, locale: theme.numberLocale) : VQFormat.number(p, decimals: 4, locale: theme.numberLocale))) }164        return parts.joined(separator: "   ")165    }166167    public var body: some View {168        VStack(alignment: .leading, spacing: 0) {169            ForEach(Array(diagnostics.enumerated()), id: \.offset) { _, d in170                let v = verdict(d.passed)171                HStack(alignment: .firstTextBaseline, spacing: VQS.s3) {172                    Image(systemName: v.symbol).font(.system(size: 13, weight: .medium)).foregroundStyle(v.color).frame(width: 16).accessibilityHidden(true)173                    VStack(alignment: .leading, spacing: 2) {174                        Text(d.name).vqFont(VQTokens.Typography.bodySm).fontWeight(.medium).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)175                        if !figures(d).isEmpty { Text(figures(d)).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text2) }176                        Text(d.conclusion).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).fixedSize(horizontal: false, vertical: true)177                    }178                    Spacer(minLength: 0)179                }180                .padding(.vertical, VQS.s2)181                .overlay(alignment: .bottom) { Rectangle().fill(VQP.line).frame(height: VQTokens.hairline) }182                .accessibilityElement(children: .ignore)183                .accessibilityLabel("\(d.name), \(v.word)")184                .accessibilityValue([figures(d), d.conclusion].filter { !$0.isEmpty }.joined(separator: ". "))185            }186        }187        .frame(maxWidth: 760, alignment: .leading)188    }189}190191/// Where the numbers come from: data sources, the specification, software versions, the code to reproduce.192public struct LabProvenancePanel: View {193    private let provenance: VQLabResult.Provenance194    @Environment(\.vqTheme) private var theme195    @State private var copied = false196    public init(_ provenance: VQLabResult.Provenance) { self.provenance = provenance }197198    private var sources: VQDataTable {199        let columns = [VQTableColumn(id: "symbol", title: VQL10n.string("Symbol", theme.language)), VQTableColumn(id: "provider", title: VQL10n.string("Provider", theme.language)),200                       VQTableColumn(id: "from", title: VQL10n.string("Start", theme.language)), VQTableColumn(id: "to", title: VQL10n.string("End", theme.language)),201                       VQTableColumn(id: "n", title: VQL10n.string("Observations", theme.language), alignment: .trailing), VQTableColumn(id: "freq", title: VQL10n.string("Frequency", theme.language)),202                       VQTableColumn(id: "adj", title: VQL10n.string("Adjustment", theme.language)), VQTableColumn(id: "at", title: VQL10n.string("Retrieved (UTC)", theme.language))]203        let utc = TimeZone(identifier: "UTC")!204        let rows = provenance.data.enumerated().map { i, d in205            VQTableRow(id: String(i), cells: [206                VQTableCell(d.symbol), VQTableCell(d.provider + (d.fallbackFrom.map { " (← \($0))" } ?? "")),207                VQTableCell(d.start ?? VQFormat.nullText, numeric: true), VQTableCell(d.end ?? VQFormat.nullText, numeric: true),208                VQTableCell(VQFormat.int(d.observations, locale: theme.numberLocale), numeric: true, sortValue: d.observations.map(Double.init)),209                VQTableCell(d.frequency ?? VQFormat.nullText), VQTableCell(d.adjusted ?? VQFormat.nullText),210                VQTableCell(d.retrievedAt.flatMap(VQISODate.parse).map { VQFormat.dateISO($0, timeZone: utc) + " " + VQFormat.time($0, language: .en, timeZone: utc) } ?? VQFormat.nullText, numeric: true),211            ])212        }213        return VQDataTable(VQL10n.string("Data sources", theme.language), columns: columns, rows: rows)214    }215216    private func subhead(_ text: String) -> some View { Text(text).vqFont(VQTokens.Typography.overline).foregroundStyle(VQP.text3) }217218    public var body: some View {219        VStack(alignment: .leading, spacing: VQS.s5) {220            if !provenance.data.isEmpty {221                VStack(alignment: .leading, spacing: VQS.s2) { subhead(theme.l("Data sources")); sources }222            }223            ViewThatFits(in: .horizontal) {224                HStack(alignment: .top, spacing: VQS.s8) { runAndSoftware }225                VStack(alignment: .leading, spacing: VQS.s5) { runAndSoftware }226            }227            if !provenance.spec.isEmpty {228                VStack(alignment: .leading, spacing: VQS.s2) {229                    subhead(theme.l("Specification"))230                    LazyVGrid(columns: [GridItem(.adaptive(minimum: 230), spacing: VQS.s5, alignment: .topLeading)], alignment: .leading, spacing: 3) {231                        ForEach(provenance.spec.keys.sorted(), id: \.self) { key in232                            pair(key, provenance.spec[key].map { $0.stringValue ?? $0.text() } ?? VQFormat.nullText)233                        }234                    }235                }236            }237            if let code = provenance.reproduce, !code.isEmpty {238                VStack(alignment: .leading, spacing: VQS.s2) {239                    HStack {240                        subhead(theme.l("Reproduce (Python)"))241                        Spacer()242                        Button {243                            VQPasteboard.copy(code)244                            copied = true245                        } label: {246                            Label(copied ? theme.l("Copied") : theme.l("Copy"), systemImage: copied ? "checkmark" : "doc.on.doc")247                                .vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2)248                        }249                        .buttonStyle(.plain)250                        .accessibilityLabel(theme.l("Copy the code"))251                    }252                    VQCodeBlock(code)253                }254            }255        }256    }257258    @ViewBuilder private var runAndSoftware: some View {259                VStack(alignment: .leading, spacing: VQS.s2) {260                    subhead(theme.l("Run (computation)"))261                    pair(theme.l("Computed (UTC)"), provenance.computedAt.flatMap(VQISODate.parse).map { VQFormat.dateISO($0, timeZone: TimeZone(identifier: "UTC")!) + " " + VQFormat.time($0, language: .en, timeZone: TimeZone(identifier: "UTC")!) } ?? VQFormat.nullText)262                    pair(theme.l("Duration"), VQFormat.duration(ms: provenance.durationMs, locale: theme.numberLocale).isEmpty ? VQFormat.nullText : VQFormat.duration(ms: provenance.durationMs, locale: theme.numberLocale))263                    pair(theme.l("Random seed"), provenance.seed.map(String.init) ?? theme.l("none (deterministic)"))264                }265                if !provenance.software.isEmpty {266                    VStack(alignment: .leading, spacing: VQS.s2) {267                        subhead(theme.l("Software"))268                        ForEach(provenance.software) { s in pair(s.name, s.version) }269                    }270                }271                }272273    private func pair(_ key: String, _ value: String) -> some View {274        HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {275            Text(key).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2)276            Spacer(minLength: VQS.s2)277            Text(value).vqFont(VQTokens.Typography.numSm).foregroundStyle(VQP.text1).lineLimit(2).multilineTextAlignment(.trailing)278        }279        .frame(minWidth: 200, maxWidth: 320)280        .accessibilityElement(children: .combine)281    }282}283
Files main
Menu

Theme