SPB Git

Repository Public

LabChartView.swift 48.3 KB 860 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantUI/Lab/LabChartView.swift3// Description: One chart of a `lab/1` result on Swift Charts: line, area, bar, scatter, histogram, fan (bands),4//              payoff, heatmap and surface; time, numeric and category axes; forecast vs observed styling; legend;5//              value inspection; accessibility (label, summary, audio graph); downsampling of long series.6import SwiftUI7import Charts8import VQuantKit910/// How a series is drawn once the chart type and the series' own style are combined.11enum LabMark: Equatable { case line, dashed, area, bar, points, band, bandLine, candles }1213struct LabSeries: Identifiable {14    let id: Int15    let key: String            // unique scale key16    let name: String17    let kind: VQLabResult.Chart.Series.Kind18    let mark: LabMark19    let color: Color20    let points: [VQChartPoint]         // drawn (downsampled)21    let all: [VQChartPoint]            // complete (inspection, accessibility)22    var segments: [[VQChartPoint]] { VQLabChartData.segments(points) }23}2425struct LabChartModel {26    let chart: VQLabResult.Chart27    let axis: VQLabResult.Chart.AxisType28    let series: [LabSeries]29    let categories: [String]30    let barSlot: Double?               // width of a bar slot on a continuous axis31    let barSeriesCount: Int32    let yRange: ClosedRange<Double>?33    let usesLog: Bool34    let downsampled: Bool35    /// OHLC arrays of the candle series, by series index.36    let candles: [Int: VQLabResult.Chart.Series]3738    init(_ chart: VQLabResult.Chart, maxPoints: Int) {39        self.chart = chart40        let axis = VQLabChartData.effectiveAxis(chart)41        self.axis = axis42        let type = chart.type.known ?? .line43        let palette = VQTokens.DataPalette.categorical44        var out: [LabSeries] = []45        var slot = 046        var reduced = false47        // In a fan chart every forecast series (bands and central line) shares one colour; observed data has its own.48        let fanForecast = palette[1], fanObserved = palette[0]49        for (i, s) in chart.series.enumerated() {50            let kind = s.kind.known ?? .calculated51            let styled: LabMark52            switch s.style?.known {53            case .line?: styled = kind == .forecast && type != .fan ? .dashed : .line54            case .dashed?: styled = .dashed55            case .bar?: styled = .bar56            case .points?: styled = .points57            case .band?: styled = .band58            case nil:59                switch type {60                case .area: styled = .area61                case .bar, .histogram: styled = .bar62                case .scatter: styled = .points63                default: styled = s.hasInterval && type == .fan && kind == .forecast ? .band : (kind == .forecast ? .dashed : .line)64                }65            }66            // New results say whether a band has its own centre line (`line`); older ones are drawn as before.67            var resolved = styled68            if s.hasInterval, styled != .bar, styled != .points, let centre = s.drawsCentreLine { resolved = centre ? .bandLine : .band }69            if type == .candles, s.hasCandles, axis == .time { resolved = .candles }70            let mark = resolved71            let color: Color72            if type == .fan { color = kind == .forecast ? fanForecast : (slot == 0 ? fanObserved : palette[min(palette.count - 1, slot + 1)]); if kind != .forecast { slot += 1 } }73            else { color = palette[min(palette.count - 1, slot)]; slot += 1 }74            let all = VQLabChartData.points(s, axis: axis)75            let drawn = mark == .bar || mark == .candles || mark == .points && all.count <= maxPoints ? all : VQLabChartData.downsample(all, limit: maxPoints)76            if drawn.count < all.count { reduced = true }77            out.append(LabSeries(id: i, key: "\(i)·\(s.name)", name: s.name, kind: kind, mark: mark, color: color, points: drawn, all: all))78        }79        series = out80        downsampled = reduced81        var cats: [String] = [], seen = Set<String>()82        if axis == .category { for s in out { for p in s.all { if case .category(let c) = p.x, seen.insert(c).inserted { cats.append(c) } } } }83        categories = cats84        let bars = out.filter { $0.mark == .bar || $0.mark == .candles }85        barSeriesCount = bars.count86        barSlot = axis == .category ? nil : VQLabChartData.minimumSpacing(bars.flatMap { $0.all.compactMap(\.x.scalar) })87        var values: [Double] = []88        for s in out { for p in s.all { values.append(p.y); if let l = p.lower { values.append(l) }; if let u = p.upper { values.append(u) } } }89        for s in chart.series where s.hasCandles { values += (s.high ?? []).compactMap { $0 } + (s.low ?? []).compactMap { $0 } }90        candles = Dictionary(uniqueKeysWithValues: chart.series.enumerated().compactMap { i, s in s.hasCandles ? (i, s) : nil })91        if let lo = values.min(), let hi = values.max() { yRange = lo...hi } else { yRange = nil }92        usesLog = chart.y.log && (values.min() ?? 0) > 093    }9495    var includesZero: Bool {96        switch chart.type.known {97        case .bar?, .histogram?, .area?, .payoff?: return true98        default: return series.contains { $0.mark == .bar }99        }100    }101    var showsZeroRule: Bool { (yRange?.lowerBound ?? 0) < 0 && (yRange?.upperBound ?? 0) > 0 }102}103104public struct LabChartView: View {105    private let chart: VQLabResult.Chart106    private let height: CGFloat107    private let showsHeader: Bool108    private let model: LabChartModel109    private let pinned: VQChartX?110    @State private var selectedDate: Date?111    @State private var selectedNumber: Double?112    @State private var selectedCategory: String?113    @Environment(\.vqTheme) private var theme114115    /// - Parameters:116    ///   - maxPoints: series longer than this are reduced for drawing (min/max per bucket, extremes kept);117    ///     inspection and accessibility still use every point.118    ///   - inspecting: a fixed inspection position (previews, snapshots); otherwise hover (macOS) or touch-and-drag (iOS).119    public init(_ chart: VQLabResult.Chart, height: CGFloat = 260, maxPoints: Int = 600, showsHeader: Bool = true, inspecting: VQChartX? = nil) {120        self.chart = chart; self.height = height; self.showsHeader = showsHeader121        self.model = LabChartModel(chart, maxPoints: maxPoints); self.pinned = inspecting122    }123124    private var isMatrix: Bool { chart.matrix != nil && (chart.type == .heatmap || chart.type == .surface || chart.series.isEmpty) }125    private var locale: VQNumberLocale { theme.numberLocale }126127    public var body: some View {128        VStack(alignment: .leading, spacing: VQS.s2) {129            if showsHeader {130                Text(chart.title).vqFont(VQTokens.Typography.heading).foregroundStyle(VQP.text1).fixedSize(horizontal: false, vertical: true)131                    .accessibilityAddTraits(.isHeader)132            }133            if isMatrix, let m = chart.matrix {134                LabMatrixView(chart: chart, matrix: m, height: height)135            } else if model.series.allSatisfy({ $0.all.isEmpty }) {136                VQEmptyState(title: theme.l("Nothing to plot"), message: theme.l("The engine returned no value for this figure."))137                    .frame(height: height)138            } else {139                LabLegend(series: model.series)140                plot141                    .frame(height: height)142                    .accessibilityElement(children: .ignore)143                    .accessibilityLabel(chart.title)144                    .accessibilityValue(VQLabChartData.summary(of: chart, locale: locale, language: theme.language))145                    .accessibilityChartDescriptor(LabChartDescriptor(chart: chart, model: model, locale: locale))146                if !chart.annotations.isEmpty { annotationKey }147            }148            if let note = chart.note, !note.isEmpty {149                Text(note).font(.system(size: 11.5, design: .serif).italic()).foregroundStyle(VQP.text2).fixedSize(horizontal: false, vertical: true)150            }151            if model.downsampled {152                Text(theme.l("Series reduced for display (minimum and maximum of each bucket kept); inspection reads every value."))153                    .vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).fixedSize(horizontal: false, vertical: true)154            }155        }156        .environment(\.locale, Locale(identifier: theme.language == .fr ? "fr_CA" : "en_CA"))157    }158159    // MARK: plot160161    private var selection: VQChartX? {162        if let pinned { return pinned }163        switch model.axis {164        case .time: return selectedDate.map(VQChartX.time)165        case .number: return selectedNumber.map(VQChartX.number)166        case .category: return selectedCategory.map(VQChartX.category)167        }168    }169170    /// The x position of the data nearest to the pointer, and each series' value there.171    private var inspected: (x: VQChartX, rows: [(series: LabSeries, point: VQChartPoint)])? {172        guard let selection else { return nil }173        var rows: [(LabSeries, VQChartPoint)] = []174        var snapped: VQChartX?175        if case .category(let c) = selection {176            snapped = selection177            for s in model.series { if let p = s.all.first(where: { $0.x == .category(c) }) { rows.append((s, p)) } }178        } else if let target = selection.scalar {179            // snap to the data point nearest to the pointer over every series, then read each series there180            var best: (distance: Double, point: VQChartPoint)?181            for s in model.series {182                guard let i = VQLabChartData.nearestIndex(s.all, to: target), let sx = s.all[i].x.scalar else { continue }183                if best == nil || abs(sx - target) < best!.distance { best = (abs(sx - target), s.all[i]) }184            }185            guard let anchor = best?.point else { return nil }186            snapped = anchor.x187            let at = anchor.x.scalar ?? target188            let tolerance = (model.barSlot ?? 0) / 2189            for s in model.series {190                guard let j = VQLabChartData.nearestIndex(s.all, to: at), let sx = s.all[j].x.scalar else { continue }191                let span = abs((s.all.last?.x.scalar ?? sx) - (s.all.first?.x.scalar ?? sx))192                let near = abs(sx - at) <= max(tolerance, span / Double(max(1, s.all.count - 1)) * 0.75)193                if near || s.all.count == 1 { rows.append((s, s.all[j])) }194            }195        }196        guard let snapped, !rows.isEmpty else { return nil }197        return (snapped, rows)198    }199200    private func value(_ v: Double) -> String {201        VQFormat.byUnitName(v, chart.y.unitName, decimals: chart.y.unit == .none || chart.y.unit == .ratio ? min(6, LabAxis.decimals(for: model.yRange, unit: chart.y.unit) + 2) : nil,202                            currency: chart.y.currency ?? "USD", compact: chart.y.unit == .currency && abs(v) >= 1e6, locale: locale)203    }204205    private func xText(_ x: VQChartX) -> String {206        switch x {207        case .time(let d):208            let iso = VQFormat.dateISO(d, timeZone: TimeZone(identifier: "UTC")!)209            let seconds = Int(d.timeIntervalSince1970) % 86_400210            return seconds == 0 ? iso : iso + String(format: " %02d:%02d", seconds / 3600, seconds % 3600 / 60)211        case .number(let n):212            if chart.x.unit != .none || chart.x.unitName != nil { return VQFormat.byUnitName(n, chart.x.unitName, currency: chart.x.currency ?? "USD", locale: locale) }213            return VQFormat.number(n, decimals: min(6, LabAxis.decimals(forSpan: xSpan) + 2), locale: locale)214        case .category(let c): return c215        }216    }217218    private var xSpan: Double? {219        let xs = model.series.flatMap { $0.all.compactMap(\.x.scalar) }220        guard let lo = xs.min(), let hi = xs.max() else { return nil }221        return hi - lo222    }223224    @ChartContentBuilder private var content: some ChartContent {225        if model.showsZeroRule {226            RuleMark(y: .value("zero", 0.0)).foregroundStyle(VQP.lineStrong).lineStyle(StrokeStyle(lineWidth: 1))227        }228        ForEach(model.series) { s in229            switch model.axis {230            case .time: LabSeriesMarks(series: s, model: model, upColor: theme.upDown.up, downColor: theme.upDown.down, x: { Date(timeIntervalSince1970: $0) })231            case .number: LabSeriesMarks(series: s, model: model, upColor: theme.upDown.up, downColor: theme.upDown.down, x: { $0 })232            case .category: LabCategoryMarks(series: s, model: model)233            }234        }235        ForEach(Array(chart.annotations.enumerated()), id: \.offset) { i, a in236            LabAnnotationMark(index: i, annotation: a, axis: model.axis)237        }238        if let inspected {239            LabSelectionRule(x: inspected.x)240                .annotation(position: .top, alignment: .center, spacing: 4, overflowResolution: .init(x: .fit(to: .chart), y: .fit(to: .chart))) {241                    LabInspector(title: xText(inspected.x), rows: inspected.rows.map { row in242                        if let c = model.candles[row.series.id], let o = c.open?[safe: row.point.index] ?? nil, let h = c.high?[safe: row.point.index] ?? nil, let l = c.low?[safe: row.point.index] ?? nil {243                            let f = { (v: Double) in VQFormat.number(v, decimals: 2, locale: locale) }      // the currency is in the axis title244                            return (row.series, "O \(f(o))  H \(f(h))  L \(f(l))  C \(f(row.point.y))")245                        }246                        var text = value(row.point.y)247                        if let lo = row.point.lower, let hi = row.point.upper { text += "  [\(value(lo)) ; \(value(hi))]" }248                        return (row.series, text)249                    })250                }251        }252    }253254    private var plot: some View {255        let colors = model.series.map(\.color)256        let base = Chart { content }257            .chartForegroundStyleScale(domain: model.series.map(\.key), range: colors)258            .chartLegend(.hidden)259            .chartXAxisLabel(position: .bottom, alignment: .center) { LabAxis.title(LabAxis.xTitle(chart)) }260            .chartYAxisLabel(position: .leading, alignment: .center) { LabAxis.title(LabAxis.yTitle(chart, language: theme.language)) }261            .chartYAxis {262                if model.usesLog, let r = model.yRange {263                    AxisMarks(position: .leading, values: LabAxis.logTicks(r)) { v in264                        AxisGridLine().foregroundStyle(VQP.line)265                        AxisValueLabel { if let d = v.as(Double.self) { LabAxis.label(VQFormat.number(d, decimals: d < 10 ? 1 : 0, locale: locale)) } }266                    }267                } else {268                    AxisMarks(position: .leading, values: .automatic(desiredCount: 5)) { v in269                        AxisGridLine().foregroundStyle(VQP.line)270                        AxisValueLabel { if let d = v.as(Double.self) { LabAxis.label(LabAxis.yText(d, chart: chart, range: model.yRange, locale: locale)) } }271                    }272                }273            }274            .chartPlotStyle { $0.background(VQP.ink1.opacity(0.001)) }275        return LabScaled(model: model, xSpan: xSpan, locale: locale, selectedDate: $selectedDate, selectedNumber: $selectedNumber, selectedCategory: $selectedCategory) { base }276    }277278    private var annotationKey: some View {279        VStack(alignment: .leading, spacing: 2) {280            ForEach(Array(chart.annotations.enumerated()), id: \.offset) { i, a in281                HStack(alignment: .firstTextBaseline, spacing: VQS.s2) {282                    LabAnnotationBadge(index: i)283                    Text(a.text).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).fixedSize(horizontal: false, vertical: true)284                }285            }286        }287    }288}289290// MARK: marks291292/// A series on a continuous axis (time or number). `x` turns a scalar position into the plotted value.293struct LabSeriesMarks<X: Plottable>: ChartContent {294    let series: LabSeries295    let model: LabChartModel296    var upColor: Color = VQTokens.UpDown.classic.up297    var downColor: Color = VQTokens.UpDown.classic.down298    let x: (Double) -> X299300    private func px(_ p: VQChartPoint) -> PlottableValue<X> { .value(model.chart.x.label, x(p.x.scalar ?? 0)) }301    private var yLabel: String { model.chart.y.label }302303    var body: some ChartContent {304        switch series.mark {305        case .line, .dashed:306            ForEach(Array(series.segments.enumerated()), id: \.offset) { n, segment in307                ForEach(segment, id: \.index) { p in308                    LineMark(x: px(p), y: .value(yLabel, p.y), series: .value("segment", "\(series.key)#\(n)"))309                        .foregroundStyle(by: .value("series", series.key))310                        .lineStyle(StrokeStyle(lineWidth: series.mark == .dashed ? 1.25 : 1.6, lineCap: .round, lineJoin: .round, dash: series.mark == .dashed ? [5, 3.5] : []))311                        .interpolationMethod(.linear)312                }313            }314            if series.points.count == 1, let p = series.points.first {315                PointMark(x: px(p), y: .value(yLabel, p.y)).foregroundStyle(by: .value("series", series.key)).symbolSize(24)316            }317        case .area:318            ForEach(series.points, id: \.index) { p in319                AreaMark(x: px(p), yStart: .value(yLabel, 0.0), yEnd: .value(yLabel, p.y))320                    .foregroundStyle(by: .value("series", series.key)).opacity(0.22).interpolationMethod(.linear)321                LineMark(x: px(p), y: .value(yLabel, p.y), series: .value("segment", series.key))322                    .foregroundStyle(by: .value("series", series.key)).lineStyle(StrokeStyle(lineWidth: 1.4, lineJoin: .round))323            }324        case .band, .bandLine:325            ForEach(series.points, id: \.index) { p in326                AreaMark(x: px(p), yStart: .value(yLabel, p.lower ?? p.y), yEnd: .value(yLabel, p.upper ?? p.y))327                    .foregroundStyle(by: .value("series", series.key)).opacity(0.16).interpolationMethod(.linear)328            }329            if series.mark == .bandLine {330                // the band has its own centre line (`line: true`)331                ForEach(series.points, id: \.index) { p in332                    LineMark(x: px(p), y: .value(yLabel, p.y), series: .value("segment", "\(series.key)#centre"))333                        .foregroundStyle(by: .value("series", series.key))334                        .lineStyle(StrokeStyle(lineWidth: 1.5, lineCap: .round, lineJoin: .round, dash: series.kind == .forecast && model.chart.type != .fan ? [5, 3.5] : []))335                }336            }337        case .candles:338            let slot = model.barSlot ?? 86_400339            let c = model.candles[series.id]340            ForEach(series.points, id: \.index) { p in341                let t = p.x.scalar ?? 0342                if let o = c?.open?[safe: p.index] ?? nil, let h = c?.high?[safe: p.index] ?? nil, let l = c?.low?[safe: p.index] ?? nil {343                    let rising = p.y >= o344                    // wick and body; a rising candle is hollow-toned (up colour), a falling one down colour: the body's345                    // position against the open says the direction without colour too346                    RuleMark(x: px(p), yStart: .value(yLabel, l), yEnd: .value(yLabel, h)).foregroundStyle(rising ? upColor : downColor).lineStyle(StrokeStyle(lineWidth: 1))347                    RectangleMark(xStart: .value(model.chart.x.label, x(t - slot * 0.32)), xEnd: .value(model.chart.x.label, x(t + slot * 0.32)), yStart: .value(yLabel, min(o, p.y)), yEnd: .value(yLabel, max(o, p.y) == min(o, p.y) ? p.y + (h - l) * 0.004 : max(o, p.y)))348                        .foregroundStyle(rising ? upColor : downColor)349                } else {350                    PointMark(x: px(p), y: .value(yLabel, p.y)).foregroundStyle(by: .value("series", series.key)).symbolSize(12)351                }352            }353        case .points:354            ForEach(series.points, id: \.index) { p in355                PointMark(x: px(p), y: .value(yLabel, p.y)).foregroundStyle(by: .value("series", series.key)).symbolSize(series.points.count > 200 ? 9 : 20).opacity(series.points.count > 200 ? 0.7 : 0.9)356            }357        case .bar:358            let slot = model.barSlot ?? 1359            let n = max(1, model.barSeriesCount)360            let position = model.series.filter { $0.mark == .bar }.firstIndex { $0.id == series.id } ?? 0361            let gap = model.chart.type == .histogram ? 0.04 : 0.18362            let width = slot * (1 - gap) / Double(n)363            ForEach(series.points, id: \.index) { p in364                let left = (p.x.scalar ?? 0) - slot * (1 - gap) / 2 + width * Double(position)365                RectangleMark(xStart: .value(model.chart.x.label, x(left)), xEnd: .value(model.chart.x.label, x(left + width)), yStart: .value(yLabel, 0.0), yEnd: .value(yLabel, p.y))366                    .foregroundStyle(by: .value("series", series.key)).opacity(0.9)367                if let lo = p.lower, let hi = p.upper {368                    RuleMark(x: .value(model.chart.x.label, x(left + width / 2)), yStart: .value(yLabel, lo), yEnd: .value(yLabel, hi))369                        .foregroundStyle(VQP.text1).lineStyle(StrokeStyle(lineWidth: 1.2))370                }371            }372        }373    }374}375376struct LabCategoryMarks: ChartContent {377    let series: LabSeries378    let model: LabChartModel379380    private func label(_ p: VQChartPoint) -> String { if case .category(let c) = p.x { return c } else { return p.x.label } }381    private var xLabel: String { model.chart.x.label }382    private var yLabel: String { model.chart.y.label }383384    var body: some ChartContent {385        ForEach(series.points, id: \.index) { p in386            switch series.mark {387            case .bar:388                BarMark(x: .value(xLabel, label(p)), y: .value(yLabel, p.y))389                    .foregroundStyle(by: .value("series", series.key))390                    .position(by: .value("group", series.key), axis: .horizontal, span: .ratio(model.barSeriesCount > 1 ? 0.82 : 0.62))391                    .opacity(0.9)392                if let lo = p.lower, let hi = p.upper {393                    RuleMark(x: .value(xLabel, label(p)), yStart: .value(yLabel, lo), yEnd: .value(yLabel, hi))394                        .foregroundStyle(VQP.text1).lineStyle(StrokeStyle(lineWidth: 1.2))395                        .position(by: .value("group", series.key), axis: .horizontal, span: .ratio(model.barSeriesCount > 1 ? 0.82 : 0.62))396                }397            case .points:398                PointMark(x: .value(xLabel, label(p)), y: .value(yLabel, p.y)).foregroundStyle(by: .value("series", series.key)).symbolSize(26)399            case .band, .bandLine:400                RuleMark(x: .value(xLabel, label(p)), yStart: .value(yLabel, p.lower ?? p.y), yEnd: .value(yLabel, p.upper ?? p.y))401                    .foregroundStyle(by: .value("series", series.key)).lineStyle(StrokeStyle(lineWidth: 6, lineCap: .round)).opacity(0.3)402                if series.mark == .bandLine { PointMark(x: .value(xLabel, label(p)), y: .value(yLabel, p.y)).foregroundStyle(by: .value("series", series.key)).symbolSize(22) }403            case .line, .dashed, .area, .candles:404                LineMark(x: .value(xLabel, label(p)), y: .value(yLabel, p.y), series: .value("segment", series.key))405                    .foregroundStyle(by: .value("series", series.key))406                    .lineStyle(StrokeStyle(lineWidth: series.mark == .dashed ? 1.25 : 1.6, lineJoin: .round, dash: series.mark == .dashed ? [5, 3.5] : []))407                if series.mark != .dashed {408                    PointMark(x: .value(xLabel, label(p)), y: .value(yLabel, p.y)).foregroundStyle(by: .value("series", series.key)).symbolSize(18)409                }410            }411        }412    }413}414415/// A numbered rule (vertical when the annotation has no y) or a numbered point; the texts are listed under the plot.416struct LabAnnotationMark: ChartContent {417    let index: Int418    let annotation: VQLabResult.Chart.Annotation419    let axis: VQLabResult.Chart.AxisType420421    var body: some ChartContent {422        if let x = VQLabChartData.x(annotation.x, axis: axis) {423            if let y = annotation.y {424                switch x {425                case .time(let d): PointMark(x: .value("x", d), y: .value("y", y)).foregroundStyle(VQP.text1).symbolSize(34).symbol(.diamond).annotation(position: .top, spacing: 2) { LabAnnotationBadge(index: index) }426                case .number(let n): PointMark(x: .value("x", n), y: .value("y", y)).foregroundStyle(VQP.text1).symbolSize(34).symbol(.diamond).annotation(position: .top, spacing: 2) { LabAnnotationBadge(index: index) }427                case .category(let c): PointMark(x: .value("x", c), y: .value("y", y)).foregroundStyle(VQP.text1).symbolSize(34).symbol(.diamond).annotation(position: .top, spacing: 2) { LabAnnotationBadge(index: index) }428                }429            } else {430                let style = StrokeStyle(lineWidth: 1, dash: [2, 3])431                switch x {432                case .time(let d): RuleMark(x: .value("x", d)).foregroundStyle(VQP.text2).lineStyle(style).annotation(position: .top, alignment: .center, spacing: 1) { LabAnnotationBadge(index: index) }433                case .number(let n): RuleMark(x: .value("x", n)).foregroundStyle(VQP.text2).lineStyle(style).annotation(position: .top, alignment: .center, spacing: 1) { LabAnnotationBadge(index: index) }434                case .category(let c): RuleMark(x: .value("x", c)).foregroundStyle(VQP.text2).lineStyle(style).annotation(position: .top, alignment: .center, spacing: 1) { LabAnnotationBadge(index: index) }435                }436            }437        }438    }439}440441struct LabAnnotationBadge: View {442    let index: Int443    var body: some View {444        Text("\(index + 1)").font(.system(size: 9, weight: .semibold, design: .monospaced)).foregroundStyle(VQP.ink0)445            .frame(width: 13, height: 13).background(Circle().fill(VQP.text2))446            .accessibilityHidden(true)447    }448}449450struct LabSelectionRule: ChartContent {451    let x: VQChartX452    var body: some ChartContent {453        let style = StrokeStyle(lineWidth: 1)454        switch x {455        case .time(let d): RuleMark(x: .value("x", d)).foregroundStyle(VQP.text3).lineStyle(style)456        case .number(let n): RuleMark(x: .value("x", n)).foregroundStyle(VQP.text3).lineStyle(style)457        case .category(let c): RuleMark(x: .value("x", c)).foregroundStyle(VQP.text3.opacity(0.5)).lineStyle(style)458        }459    }460}461462/// The value read-out of the inspected position.463struct LabInspector: View {464    let title: String465    let rows: [(series: LabSeries, text: String)]466    var body: some View {467        VStack(alignment: .leading, spacing: 3) {468            Text(title).font(.system(size: 10.5, weight: .semibold, design: .monospaced).monospacedDigit()).foregroundStyle(VQP.text1)469            ForEach(Array(rows.prefix(8).enumerated()), id: \.offset) { _, row in470                HStack(spacing: 5) {471                    LabSwatch(series: row.series)472                    Text(row.series.name).font(.system(size: 10.5)).foregroundStyle(VQP.text2).lineLimit(1)473                    Spacer(minLength: 8)474                    Text(row.text).font(.system(size: 10.5, design: .monospaced).monospacedDigit()).foregroundStyle(VQP.text1).lineLimit(1).fixedSize()475                }476            }477        }478        .padding(.horizontal, 8).padding(.vertical, 6)479        .frame(maxWidth: 420)480        .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(VQP.ink2))481        .overlay(RoundedRectangle(cornerRadius: 6, style: .continuous).strokeBorder(VQP.lineStrong, lineWidth: 1))482        .fixedSize()483    }484}485486// MARK: legend487488/// The swatch repeats the series' mark (solid, dashed, band, bar, points): the key reads without colour.489struct LabSwatch: View {490    let series: LabSeries491    var body: some View {492        Canvas { context, size in493            let mid = size.height / 2494            let shade = GraphicsContext.Shading.color(series.color)495            switch series.mark {496            case .line: context.stroke(Path { $0.move(to: CGPoint(x: 0, y: mid)); $0.addLine(to: CGPoint(x: size.width, y: mid)) }, with: shade, lineWidth: 2)497            case .dashed: context.stroke(Path { $0.move(to: CGPoint(x: 0, y: mid)); $0.addLine(to: CGPoint(x: size.width, y: mid)) }, with: shade, style: StrokeStyle(lineWidth: 1.6, dash: [4, 2.5]))498            case .band: context.fill(Path(CGRect(x: 0, y: 1, width: size.width, height: size.height - 2)), with: .color(series.color.opacity(0.3)))499            case .bandLine:500                context.fill(Path(CGRect(x: 0, y: 1, width: size.width, height: size.height - 2)), with: .color(series.color.opacity(0.3)))501                context.stroke(Path { $0.move(to: CGPoint(x: 0, y: mid)); $0.addLine(to: CGPoint(x: size.width, y: mid)) }, with: shade, lineWidth: 1.6)502            case .candles:503                context.stroke(Path { $0.move(to: CGPoint(x: size.width / 2, y: 0)); $0.addLine(to: CGPoint(x: size.width / 2, y: size.height)) }, with: .color(VQP.text2), lineWidth: 1)504                context.fill(Path(CGRect(x: size.width / 2 - 2.5, y: 2.5, width: 5, height: size.height - 5)), with: .color(VQP.text2))505            case .area:506                context.fill(Path(CGRect(x: 0, y: mid, width: size.width, height: size.height - mid)), with: .color(series.color.opacity(0.3)))507                context.stroke(Path { $0.move(to: CGPoint(x: 0, y: mid)); $0.addLine(to: CGPoint(x: size.width, y: mid)) }, with: shade, lineWidth: 1.6)508            case .bar: context.fill(Path(CGRect(x: size.width * 0.25, y: 1, width: size.width * 0.5, height: size.height - 2)), with: shade)509            case .points: context.fill(Path(ellipseIn: CGRect(x: size.width / 2 - 3, y: mid - 3, width: 6, height: 6)), with: shade)510            }511        }512        .frame(width: 16, height: 10)513        .accessibilityHidden(true)514    }515}516517struct LabLegend: View {518    let series: [LabSeries]519    @Environment(\.vqTheme) private var theme520521    var body: some View {522        LabFlow(spacing: 12, lineSpacing: 4) {523            ForEach(series) { s in524                HStack(spacing: 5) {525                    LabSwatch(series: s)526                    Text(s.name).vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text2).lineLimit(1)527                    if s.kind == .forecast { VQKindBadge(.forecast) } else if s.kind == .observed { VQKindBadge(.observed) }528                }529                .accessibilityElement(children: .combine)530            }531        }532        .accessibilityLabel(theme.l("Legend"))533    }534}535536/// Left-aligned wrapping row (legend entries).537struct LabFlow: Layout {538    var spacing: CGFloat = 8539    var lineSpacing: CGFloat = 4540541    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {542        let fitted = arrange(width: proposal.width ?? 360, subviews: subviews).size      // unspecified: a modest ideal width, so a long legend never widens its column543        return CGSize(width: proposal.width.map { $0.isFinite ? max($0, fitted.width) : fitted.width } ?? fitted.width, height: fitted.height)544    }545    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {546        let placed = arrange(width: bounds.width, subviews: subviews)547        for (i, origin) in placed.origins.enumerated() {548            subviews[i].place(at: CGPoint(x: bounds.minX + origin.x, y: bounds.minY + origin.y), proposal: ProposedViewSize(width: min(bounds.width, subviews[i].sizeThatFits(.unspecified).width), height: nil))549        }550    }551    private func arrange(width: CGFloat, subviews: Subviews) -> (size: CGSize, origins: [CGPoint]) {552        var x: CGFloat = 0, y: CGFloat = 0, lineHeight: CGFloat = 0, maxX: CGFloat = 0553        var origins: [CGPoint] = []554        for sub in subviews {555            let s = sub.sizeThatFits(.unspecified)556            let w = min(s.width, width)557            if x > 0, x + w > width + 0.5 { x = 0; y += lineHeight + lineSpacing; lineHeight = 0 }558            origins.append(CGPoint(x: x, y: y))559            x += w + spacing560            lineHeight = max(lineHeight, s.height)561            maxX = max(maxX, x - spacing)562        }563        return (CGSize(width: maxX, height: y + lineHeight), origins)564    }565}566567// MARK: axes and scales568569enum LabAxis {570    static func title(_ text: String) -> some View { Text(text).font(.system(size: 10.5, weight: .medium)).foregroundStyle(VQP.text2) }571    static func label(_ text: String) -> some View { Text(text).font(.system(size: 10, design: .monospaced).monospacedDigit()).foregroundStyle(VQP.text2) }572573    /// The currency of an axis goes in its title, once ("Strike (USD)"), not on every tick.574    static func xTitle(_ chart: VQLabResult.Chart) -> String { chart.x.currency.map { "\(chart.x.label) (\($0))" } ?? chart.x.label }575576    static func yTitle(_ chart: VQLabResult.Chart, language: VQLanguage) -> String {577        var t = chart.y.currency.map { "\(chart.y.label) (\($0))" } ?? chart.y.label578        if chart.y.log { t += VQL10n.string(" (log scale)", language) }579        return t580    }581582    /// Decimals that separate the ticks of a range.583    /// Decimals that tell apart ticks about a fifth of the span apart.584    static func decimals(forSpan span: Double?) -> Int {585        guard let span, span > 0, span.isFinite else { return 2 }586        return min(6, max(0, Int((-log10(span / 5)).rounded(.up))))587    }588    static func decimals(for range: ClosedRange<Double>?, unit: VQValueUnit) -> Int {589        guard let range else { return 2 }590        return decimals(forSpan: (range.upperBound - range.lowerBound) * (unit == .percent ? 100 : unit == .bps ? 10_000 : 1))591    }592593    /// Ticks of a log axis: 1-2-5 steps inside the range (denser steps when the range is short).594    static func logTicks(_ range: ClosedRange<Double>) -> [Double] {595        guard range.lowerBound > 0, range.upperBound > range.lowerBound else { return [] }596        for mantissas in [[1.0, 2, 5], [1, 1.5, 2, 3, 4, 5, 7], [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 7, 8, 9]] {597            var out: [Double] = []598            var k = floor(log10(range.lowerBound))599            while pow(10, k) <= range.upperBound {600                for m in mantissas { let v = m * pow(10, k); if v >= range.lowerBound && v <= range.upperBound { out.append(v) } }601                k += 1602            }603            if out.count >= 3 { return out }604        }605        return [range.lowerBound, range.upperBound]606    }607608    /// Tick text of a numeric x axis by its unit: percent as percent, the rest as plain numbers (the currency is in the title).609    static func xText(_ v: Double, chart: VQLabResult.Chart, span: Double?, locale: VQNumberLocale) -> String {610        switch chart.x.unit {611        case .percent: return VQFormat.percent(v, decimals: min(2, decimals(forSpan: span.map { $0 * 100 })), locale: locale)612        case .bps: return VQFormat.bps(v, locale: locale)613        default: return VQFormat.number(v, decimals: decimals(forSpan: span), locale: locale)614        }615    }616617    static func big(_ range: ClosedRange<Double>?, _ threshold: Double) -> Bool { range.map { max(abs($0.lowerBound), abs($0.upperBound)) >= threshold } ?? false }618619    static func yText(_ v: Double, chart: VQLabResult.Chart, range: ClosedRange<Double>?, locale: VQNumberLocale) -> String {620        let d = decimals(for: range, unit: chart.y.unit)621        switch chart.y.unit {622        case .percent: return VQFormat.percent(v, decimals: min(d, 2), locale: locale)623        case .bps: return VQFormat.bps(v, decimals: 0, locale: locale)624        // one notation per axis: compact when the axis reaches large magnitudes625        case .currency, .perShare: return big(range, 10_000) ? (v == 0 ? "0" : VQFormat.compact(v, decimals: 1, locale: locale)) : VQFormat.number(v, decimals: min(d, 2), locale: locale)626        case .count, .days: return big(range, 10_000) ? (v == 0 ? "0" : VQFormat.compact(v, decimals: 1, locale: locale)) : VQFormat.number(v, decimals: 0, locale: locale)627        case .ratio, .none: return big(range, 100_000) ? (v == 0 ? "0" : VQFormat.compact(v, decimals: 1, locale: locale)) : VQFormat.number(v, decimals: d, locale: locale)628        }629    }630}631632/// Applies the scales, x axis and selection binding that depend on the axis type.633struct LabScaled<Content: View>: View {634    let model: LabChartModel635    let xSpan: Double?636    let locale: VQNumberLocale637    @Binding var selectedDate: Date?638    @Binding var selectedNumber: Double?639    @Binding var selectedCategory: String?640    @ViewBuilder let content: () -> Content641    @Environment(\.vqTheme) private var theme642643    private var yDomain: ClosedRange<Double>? {644        guard let r = model.yRange else { return nil }645        if model.usesLog { return max(r.lowerBound * 0.95, .leastNonzeroMagnitude)...(r.upperBound * 1.05) }646        var lo = r.lowerBound, hi = r.upperBound647        if model.includesZero { lo = min(lo, 0); hi = max(hi, 0) }648        let pad = (hi - lo) * 0.06649        if pad == 0 { return (lo - 1)...(hi + 1) }650        return (lo == 0 ? 0 : lo - pad)...(hi == 0 ? 0 : hi + pad)651    }652653    private var timeFormat: Date.FormatStyle {654        let days = (xSpan ?? 0) / 86_400655        let utc = TimeZone(identifier: "UTC")!656        // months are written in the components' language, not the device's657        var style = Date.FormatStyle(timeZone: utc).locale(Locale(identifier: theme.language == .fr ? "fr_CA" : "en_CA"))658        if days > 365 * 3 { style = style.year() }659        else if days > 240 { style = style.month(.abbreviated).year(.twoDigits) }660        else if days >= 2 { style = style.day().month(.abbreviated) }661        else { style = style.hour().minute() }662        return style663    }664665    var body: some View {666        let scaled = content()667            .chartYScale(domain: yDomain ?? 0...1, type: model.usesLog ? .log : .linear)668        switch model.axis {669        case .time:670            scaled671                .chartXAxis {672                    AxisMarks(preset: .aligned, values: .automatic(desiredCount: 6)) { _ in673                        AxisGridLine().foregroundStyle(VQP.line.opacity(0.6))674                        AxisTick().foregroundStyle(VQP.lineStrong)675                        AxisValueLabel(format: timeFormat).font(.system(size: 10, design: .monospaced).monospacedDigit()).foregroundStyle(VQP.text2)676                    }677                }678                .chartXSelection(value: $selectedDate)679        case .number:680            scaled681                .chartXScale(domain: .automatic(includesZero: false))682                .chartXAxis {683                    AxisMarks(preset: .aligned, values: .automatic(desiredCount: 6)) { v in684                        AxisGridLine().foregroundStyle(VQP.line.opacity(0.6))685                        AxisTick().foregroundStyle(VQP.lineStrong)686                        AxisValueLabel { if let d = v.as(Double.self) { LabAxis.label(LabAxis.xText(d, chart: model.chart, span: xSpan, locale: locale)) } }687                    }688                }689                .chartXSelection(value: $selectedNumber)690        case .category:691            let crowded = model.categories.count * (model.categories.map(\.count).max() ?? 0) > 64692            scaled693                .chartXScale(domain: model.categories)694                .chartXAxis {695                    AxisMarks { v in696                        AxisTick().foregroundStyle(VQP.lineStrong)697                        AxisValueLabel(orientation: crowded ? .vertical : .horizontal) {698                            if let s = v.as(String.self) { Text(s).font(.system(size: 10)).foregroundStyle(VQP.text2) }699                        }700                    }701                }702                .chartXSelection(value: $selectedCategory)703        }704    }705}706707// MARK: heatmap and surface708709/// A matrix as coloured cells. Values are classed into the seven steps of the sequential ramp (or of the diverging710/// ramp when the range crosses zero). A **surface** is drawn the same way — a filled-contour map seen from above, with711/// the class boundaries as its contour legend — not as a 3-D surface.712struct LabMatrixView: View {713    let chart: VQLabResult.Chart714    let matrix: VQLabResult.Chart.Matrix715    let height: CGFloat716    @Environment(\.vqTheme) private var theme717    @State private var selectedX: String?718    @State private var selectedY: String?719720    private struct Cell: Identifiable { let id: Int; let column: Int; let row: Int; let value: Double? }721    private var isSurface: Bool { chart.type == .surface }722    private var steps: Int { 7 }723724    private func labels(_ values: [VQJSON]) -> [String] {725        values.map { v in726            if let n = v.doubleValue { return VQFormat.number(n, decimals: n.rounded() == n ? 0 : 2, locale: theme.numberLocale) }727            return v.displayString ?? ""728        }729    }730    private func ramp(_ scale: VQLabChartData.ColorScale) -> [Color] { scale.diverging ? VQTokens.DataPalette.diverging : VQTokens.DataPalette.sequential }731    /// Cells are described by `z` (new results) or, before that, by `y.unit`.732    private func text(_ v: Double) -> String {733        let cell = chart.cellAxis734        return VQFormat.byUnitName(v, cell.unitName, decimals: cell.unit == .percent ? 1 : (cell.unit == .none || cell.unit == .ratio ? 2 : nil), currency: cell.currency ?? "USD", locale: theme.numberLocale)735    }736    private func ink(_ band: Int, diverging: Bool) -> Color { band == 0 && diverging || band >= steps - 1 || (!diverging && band >= 4) ? VQP.ink0 : VQP.text1 }737738    var body: some View {739        let xs = labels(matrix.x), ys = labels(matrix.y)740        let scale = VQLabChartData.colorScale(matrix)741        // Cells are drawn on index scales (column c spans c…c+1). A heat map reads top to bottom like its table; a742        // surface has its smallest y at the bottom, like any chart.743        let cells: [Cell] = ys.indices.flatMap { r in xs.indices.map { c in744            Cell(id: r * xs.count + c, column: c, row: isSurface ? r : ys.count - 1 - r, value: matrix.z.indices.contains(r) && matrix.z[r].indices.contains(c) ? matrix.z[r][c] : nil)745        } }746        let rowLabel: (Int) -> String = { i in let r = isSurface ? i : ys.count - 1 - i; return ys.indices.contains(r) ? ys[r] : "" }747        let showValues = cells.count <= 170748        let stride = max(1, Int((Double(xs.count) / 11).rounded(.up)))749        let yStride = max(1, Int((Double(ys.count) / 14).rounded(.up)))750        let inset = cells.count > 400 ? 0.0 : 0.02751        VStack(alignment: .leading, spacing: VQS.s2) {752            if let scale {753                Chart(cells) { cell in754                    let x0 = Double(cell.column) + inset, x1 = Double(cell.column + 1) - inset, y0 = Double(cell.row) + inset, y1 = Double(cell.row + 1) - inset755                    if let v = cell.value {756                        let band = scale.band(v, steps: steps)757                        RectangleMark(xStart: .value("x", x0), xEnd: .value("x", x1), yStart: .value("y", y0), yEnd: .value("y", y1))758                            .foregroundStyle(ramp(scale)[band])759                            .annotation(position: .overlay) {760                                if showValues {761                                    Text(text(v)).font(.system(size: xs.count > 8 ? 9 : 10.5, design: .monospaced).monospacedDigit()).foregroundStyle(ink(band, diverging: scale.diverging))762                                        .lineLimit(1).fixedSize()763                                }764                            }765                    } else {766                        RectangleMark(xStart: .value("x", x0), xEnd: .value("x", x1), yStart: .value("y", y0), yEnd: .value("y", y1)).foregroundStyle(VQP.ink3.opacity(0.45))767                    }768                }769                .chartXScale(domain: 0...Double(max(1, xs.count)), range: .plotDimension(startPadding: 2, endPadding: 14))770                .chartYScale(domain: 0...Double(max(1, ys.count)))771                .chartXAxis {772                    AxisMarks(values: xs.indices.filter { $0 % stride == 0 }.map { Double($0) + 0.5 }) { v in773                        AxisValueLabel(anchor: .top) { if let d = v.as(Double.self), xs.indices.contains(Int(d)) { LabAxis.label(xs[Int(d)]) } }774                    }775                }776                .chartYAxis {777                    AxisMarks(position: .leading, values: ys.indices.filter { $0 % yStride == 0 }.map { Double($0) + 0.5 }) { v in778                        AxisValueLabel(anchor: .trailing) { if let d = v.as(Double.self) { LabAxis.label(rowLabel(Int(d))) } }779                    }780                }781                .chartXAxisLabel(position: .bottom, alignment: .center) { LabAxis.title(chart.x.label) }782                .chartYAxisLabel(position: .leading, alignment: .center) { LabAxis.title(isSurface || chart.y.unit == .none ? chart.y.label : chart.y.label) }783                .chartLegend(.hidden)784                .frame(height: max(height, CGFloat(ys.count) * 22 + 40))785                .accessibilityElement(children: .ignore)786                .accessibilityLabel(chart.title)787                .accessibilityValue(VQLabChartData.summary(of: chart, locale: theme.numberLocale, language: theme.language))788789                // the colour key: class boundaries (the contour levels of a surface)790                let levels = scale.levels(steps: steps)791                VStack(alignment: .leading, spacing: 3) {792                    if chart.z != nil {793                        // what the colours measure, from `z` — with its currency when it has one794                        Text(chart.cellAxis.currency.map { "\(chart.cellAxis.label) (\($0))" } ?? chart.cellAxis.label).font(.system(size: 10.5, weight: .medium)).foregroundStyle(VQP.text2)795                    }796                    HStack(spacing: 0) {797                        ForEach(0..<steps, id: \.self) { i in Rectangle().fill(ramp(scale)[i]).frame(height: 9) }798                    }799                    .clipShape(RoundedRectangle(cornerRadius: 2))800                    HStack(spacing: 0) {801                        ForEach(Array(levels.enumerated()), id: \.offset) { i, level in802                            Text(text(level)).font(.system(size: 9.5, design: .monospaced).monospacedDigit()).foregroundStyle(VQP.text2).lineLimit(1).minimumScaleFactor(0.7)803                                .frame(maxWidth: .infinity, alignment: i == 0 ? .leading : i == levels.count - 1 ? .trailing : .center)804                        }805                    }806                }807                .frame(maxWidth: 420)808                .accessibilityElement(children: .ignore)809                .accessibilityLabel(theme.l("Colour scale from %1$@ to %2$@", "\(text(levels.first ?? 0))", "\(text(levels.last ?? 0))"))810                if isSurface {811                    Text(theme.l("Surface shown as a filled-contour map (seen from above): each shade is a class of values; the boundaries are in the key."))812                        .vqFont(VQTokens.Typography.caption).foregroundStyle(VQP.text3).fixedSize(horizontal: false, vertical: true)813                }814            } else {815                VQEmptyState(title: theme.l("Empty matrix")).frame(height: height)816            }817        }818    }819}820821// MARK: accessibility — audio graph822823struct LabChartDescriptor: AXChartDescriptorRepresentable {824    let chart: VQLabResult.Chart825    let model: LabChartModel826    let locale: VQNumberLocale827828    func makeChartDescriptor() -> AXChartDescriptor {829        let range = model.yRange ?? 0...1830        let yAxis = AXNumericDataAxisDescriptor(title: chart.y.label, range: range.lowerBound...max(range.upperBound, range.lowerBound + .ulpOfOne), gridlinePositions: []) { v in831            VQFormat.byUnit(v, chart.y.unit, locale: locale)832        }833        // audio graphs want a modest number of points: the already-reduced series834        func reduced(_ s: LabSeries) -> [VQChartPoint] { VQLabChartData.downsample(s.all, limit: 200) }835        let xAxis: AXDataAxisDescriptor836        if model.axis == .category {837            xAxis = AXCategoricalDataAxisDescriptor(title: chart.x.label, categoryOrder: model.categories)838        } else {839            let xs = model.series.flatMap { $0.all.compactMap(\.x.scalar) }840            let lo = xs.min() ?? 0, hi = max(xs.max() ?? 1, (xs.min() ?? 0) + .ulpOfOne)841            let isTime = model.axis == .time842            xAxis = AXNumericDataAxisDescriptor(title: chart.x.label, range: lo...hi, gridlinePositions: []) { v in843                isTime ? VQFormat.dateISO(Date(timeIntervalSince1970: v), timeZone: TimeZone(identifier: "UTC")!) : VQFormat.number(v, locale: locale)844            }845        }846        let series = model.series.filter { $0.mark != .band }.map { s in847            AXDataSeriesDescriptor(name: s.name, isContinuous: s.mark != .bar && s.mark != .points, dataPoints: reduced(s).map { p in848                if case .category(let c) = p.x { return AXDataPoint(x: c, y: p.y) }849                return AXDataPoint(x: p.x.scalar ?? 0, y: p.y)850            })851        }852        return AXChartDescriptor(title: chart.title, summary: VQLabChartData.summary(of: chart, locale: locale), xAxis: xAxis, yAxis: yAxis, additionalAxes: [], series: series)853    }854}855856extension Array {857    /// The element at `index`, or nil when out of range.858    subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }859}860
Files main
Menu

Theme