SPB Git

Repository Public MIT

GlassChart.swift 15.7 KB 371 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/SPGlassData/Data/GlassChart.swift8// Module           : SPGlassData9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Charts42import Foundation43import SwiftUI44import SPGlassCore45import SPGlassTokens46import SPGlassThemes47import SPGlassEffects48import SPGlassComponents4950/// A line, bar or area chart drawn with Swift Charts from typed points, with axis titles, a unit, a read-out51/// of the selected position and a textual description.52///53/// ```swift54/// GlassChart("Monthly revenue", points: revenue, kind: .line, xAxisTitle: "Month", yAxisTitle: "Revenue", unit: "k$")55///56/// GlassChart("Visits", points: visible, kind: .bar) {57///     Picker("Series", selection: $series) { … }.pickerStyle(.menu)58/// }59/// ```60///61/// The chart itself is opaque content: a card with a header, hairline gridlines and marks in the theme's62/// colours. The header's read-out shows the values at the selected position (touch or drag the plot, or bind63/// `selection`), and the latest position otherwise. The optional trailing closure is a small control (a64/// series or range picker) that floats on a glass surface above the top trailing corner of the plot. Each65/// mark carries an accessibility label and value, and the sentence produced by ``GlassChartLogic`` (count,66/// minimum, maximum, trend) is shown under the chart.67public struct GlassChart<Overlay: View>: View {68    @GlassThemed private var theme69    @Environment(\.locale) private var locale70    @Environment(\.timeZone) private var timeZone71    @State private var ownSelection: GlassChartX?72    private let title: Text73    private let points: [GlassChartPoint]74    private let kind: GlassChartKind75    private let xAxisTitle: String?76    private let yAxisTitle: String?77    private let unit: String?78    private let showsSummary: Bool79    private let selection: Binding<GlassChartX?>?80    private let overlay: Overlay8182    /// - Parameters:83    ///   - title: heading of the chart, also its accessibility label.84    ///   - points: the values. Points whose value is not finite are skipped.85    ///   - kind: line, bar or area.86    ///   - xAxisTitle: title of the horizontal axis, already localised.87    ///   - yAxisTitle: title of the vertical axis, already localised.88    ///   - unit: unit of the values ("k$", "ms"), appended to the vertical axis title and to spoken values.89    ///   - showsSummary: shows the generated description under the chart. It stays available to assistive90    ///     technologies when hidden.91    ///   - selection: the selected horizontal position. Without a binding the chart keeps its own.92    ///   - overlay: a small control drawn on glass over the top trailing corner of the plot.93    public init(94        _ title: LocalizedStringKey,95        points: [GlassChartPoint],96        kind: GlassChartKind = .line,97        xAxisTitle: String? = nil,98        yAxisTitle: String? = nil,99        unit: String? = nil,100        showsSummary: Bool = true,101        selection: Binding<GlassChartX?>? = nil,102        @ViewBuilder overlay: () -> Overlay103    ) {104        self.title = Text(title)105        self.points = GlassChartLogic.plottable(points)106        self.kind = kind107        self.xAxisTitle = xAxisTitle108        self.yAxisTitle = yAxisTitle109        self.unit = unit110        self.showsSummary = showsSummary111        self.selection = selection112        self.overlay = overlay()113    }114115    public var body: some View {116        VStack(alignment: .leading, spacing: theme.spacing.sm) {117            header118            if points.isEmpty {119                ContentUnavailableView {120                    Label { Text(GlassL10n.string(.noData)) } icon: { Image(systemName: "chart.xyaxis.line") }121                }122            } else {123                selectable(chart)124                    .frame(minHeight: 180, idealHeight: 220, maxHeight: 260)125                    .overlay(alignment: .topTrailing) { overlayControl }126                summary127            }128        }129        .padding(theme.spacing.md)130        .glassOpaqueSurface(in: theme.shape(\.large))131    }132133    // MARK: Header and read-out134135    private var selectedX: GlassChartX? { selection?.wrappedValue ?? ownSelection }136137    private var header: some View {138        HStack(alignment: .top, spacing: theme.spacing.sm) {139            VStack(alignment: .leading, spacing: 2) {140                title141                    .font(theme.font(.headline))142                    .foregroundStyle(theme.color(.textPrimary))143                    .accessibilityAddTraits(.isHeader)144                if !verticalAxisLabel.isEmpty {145                    Text(verbatim: verticalAxisLabel)146                        .font(theme.font(.caption))147                        .foregroundStyle(theme.color(.textSecondary))148                        .accessibilityHidden(true)149                }150            }151            Spacer(minLength: theme.spacing.xs)152            if let readout = GlassChartLogic.readout(of: points, at: selectedX) {153                VStack(alignment: .trailing, spacing: 2) {154                    ForEach(readout.values, id: \.id) { point in155                        HStack(alignment: .firstTextBaseline, spacing: theme.spacing.xxs) {156                            if let series = point.series {157                                Text(verbatim: series)158                                    .font(theme.font(.caption))159                                    .foregroundStyle(theme.color(.textSecondary))160                            }161                            Text(verbatim: GlassChartLogic.valueText(point.value, unit: unit, locale: locale))162                                .font(theme.font(.headline).monospacedDigit())163                                .foregroundStyle(theme.color(.textPrimary))164                        }165                    }166                    Text(verbatim: readout.x.label(locale: locale, timeZone: timeZone))167                        .font(theme.font(.caption))168                        .foregroundStyle(theme.color(.textSecondary))169                }170                .lineLimit(1)171                .accessibilityElement(children: .combine)172            }173        }174    }175176    // MARK: Plot177178    private var seriesColors: [Color] {179        [theme.color(.primary), theme.color(.textPrimary).opacity(0.45), theme.color(.warning), theme.color(.success), theme.color(.destructive)]180    }181182    private var chart: some View {183        let usesTime = GlassChartLogic.usesTimeAxis(points)184        let names = GlassChartLogic.seriesNames(points)185        let hasSeries = !names.isEmpty186        let xTitle = xAxisTitle ?? ""187        let yTitle = yAxisTitle ?? ""188        let grid = theme.color(.separator).opacity(0.7)189        let axisText = theme.color(.textSecondary)190        let axisFont = theme.font(.caption)191        return Chart {192            ForEach(points) { point in193                styled(mark(for: point, usesTime: usesTime, xTitle: xTitle, yTitle: yTitle, hasSeries: hasSeries), point: point, hasSeries: hasSeries)194                    .accessibilityLabel(markLabel(point))195                    .accessibilityValue(GlassChartLogic.valueText(point.value, unit: unit, locale: locale))196            }197            if let selectedX {198                rule(at: selectedX, usesTime: usesTime, xTitle: xTitle)199                    .foregroundStyle(theme.color(.textPrimary).opacity(0.35))200                    .lineStyle(StrokeStyle(lineWidth: 1))201                    .accessibilityHidden(true)202            }203        }204        .chartForegroundStyleScale(domain: hasSeries ? names : [""], range: Array(seriesColors.prefix(max(1, min(names.count, seriesColors.count)))))205        .chartYAxis {206            AxisMarks(position: .leading, values: .automatic(desiredCount: 4)) { _ in207                AxisGridLine(stroke: StrokeStyle(lineWidth: 1)).foregroundStyle(grid)208                AxisValueLabel().font(axisFont).foregroundStyle(axisText)209            }210        }211        .chartXAxis {212            AxisMarks { _ in213                AxisValueLabel().font(axisFont).foregroundStyle(axisText)214            }215        }216        .chartXAxisLabel(position: .bottom, alignment: .center) {217            if !xTitle.isEmpty {218                Text(verbatim: xTitle).font(axisFont).foregroundStyle(axisText)219            }220        }221        .chartLegend(hasSeries ? .visible : .hidden)222        .chartLegend(position: .top, alignment: .leading, spacing: theme.spacing.xs)223        .accessibilityLabel(title)224    }225226    /// Selection by touch or drag, handled by Swift Charts so that scrolling keeps working.227    @ViewBuilder228    private func selectable(_ chart: some View) -> some View {229        if GlassChartLogic.usesTimeAxis(points) {230            chart.chartXSelection(value: Binding<Date?> {231                if case .date(let date)? = selectedX { date } else { nil }232            } set: { date in233                select(date.flatMap { GlassChartLogic.nearestPosition(to: $0, in: points) })234            })235        } else {236            chart.chartXSelection(value: Binding<String?> {237                if case .category(let name)? = selectedX { name } else { nil }238            } set: { name in239                select(name.map { .category($0) })240            })241        }242    }243244    private func select(_ x: GlassChartX?) {245        if let selection {246            selection.wrappedValue = x247        } else {248            ownSelection = x249        }250    }251252    @ChartContentBuilder253    private func rule(at x: GlassChartX, usesTime: Bool, xTitle: String) -> some ChartContent {254        switch (x, usesTime) {255        case (.date(let date), true):256            RuleMark(x: .value(xTitle, date))257        default:258            RuleMark(x: .value(xTitle, x.label(locale: locale, timeZone: timeZone)))259        }260    }261262    @ChartContentBuilder263    private func mark(for point: GlassChartPoint, usesTime: Bool, xTitle: String, yTitle: String, hasSeries: Bool) -> some ChartContent {264        let y = PlottableValue.value(yTitle, point.value)265        let series = PlottableValue.value(GlassL10n.string(.chartSeries), point.series ?? "")266        switch (point.x, usesTime) {267        case (.date(let date), true):268            let x = PlottableValue.value(xTitle, date)269            switch kind {270            case .line:271                LineMark(x: x, y: y, series: series).interpolationMethod(.monotone).lineStyle(StrokeStyle(lineWidth: 2.25, lineCap: .round, lineJoin: .round))272            case .bar:273                BarMark(x: x, y: y).cornerRadius(4).position(by: series)274            case .area:275                AreaMark(x: x, y: y, series: series, stacking: .unstacked).interpolationMethod(.monotone).opacity(0.16)276                LineMark(x: x, y: y, series: series).interpolationMethod(.monotone).lineStyle(StrokeStyle(lineWidth: 2.25, lineCap: .round, lineJoin: .round))277            }278        default:279            let x = PlottableValue.value(xTitle, point.x.label(locale: locale, timeZone: timeZone))280            switch kind {281            case .line:282                LineMark(x: x, y: y, series: series).interpolationMethod(.monotone).lineStyle(StrokeStyle(lineWidth: 2.25, lineCap: .round, lineJoin: .round))283            case .bar:284                BarMark(x: x, y: y, width: .ratio(hasSeries ? 0.8 : 0.56)).cornerRadius(4).position(by: series)285            case .area:286                AreaMark(x: x, y: y, series: series, stacking: .unstacked).interpolationMethod(.monotone).opacity(0.16)287                LineMark(x: x, y: y, series: series).interpolationMethod(.monotone).lineStyle(StrokeStyle(lineWidth: 2.25, lineCap: .round, lineJoin: .round))288            }289        }290    }291292    /// Series are told apart by the legend's names and, for lines, by symbols as well as by colour.293    @ChartContentBuilder294    private func styled(_ content: some ChartContent, point: GlassChartPoint, hasSeries: Bool) -> some ChartContent {295        let series = PlottableValue.value(GlassL10n.string(.chartSeries), point.series ?? "")296        if hasSeries, kind == .line {297            content.foregroundStyle(by: series).symbol(by: series).symbolSize(36)298        } else if kind == .line {299            content.foregroundStyle(by: series).symbol(Circle()).symbolSize(36)300        } else {301            content.foregroundStyle(by: series)302        }303    }304305    private var verticalAxisLabel: String {306        switch (yAxisTitle, unit) {307        case (let title?, let unit?) where !unit.isEmpty: "\(title) (\(unit))"308        case (let title?, _): title309        case (nil, let unit?): unit310        case (nil, nil): ""311        }312    }313314    private func markLabel(_ point: GlassChartPoint) -> String {315        let position = point.x.label(locale: locale, timeZone: timeZone)316        guard let series = point.series else { return position }317        return "\(series), \(position)"318    }319320    @ViewBuilder321    private var overlayControl: some View {322        if Overlay.self != EmptyView.self {323            overlay324                .padding(.horizontal, theme.spacing.xs)325                .padding(.vertical, theme.spacing.xxs)326                .glassSurface(.regular, in: Capsule())327                .padding(theme.spacing.xs)328        }329    }330331    @ViewBuilder332    private var summary: some View {333        let text = GlassChartLogic.description(of: points, unit: unit, locale: locale, timeZone: timeZone)334        if showsSummary {335            VStack(alignment: .leading, spacing: theme.spacing.xs) {336                Rectangle()337                    .fill(theme.color(.separator).opacity(0.7))338                    .frame(height: 1)339                    .accessibilityHidden(true)340                Text(verbatim: text)341                    .font(theme.font(.caption))342                    .foregroundStyle(theme.color(.textSecondary))343                    .fixedSize(horizontal: false, vertical: true)344            }345        } else {346            Color.clear347                .frame(height: 1)348                .accessibilityElement()349                .accessibilityLabel(Text(verbatim: text))350        }351    }352}353354extension GlassChart where Overlay == EmptyView {355    /// Creates a chart without an overlay control.356    public init(357        _ title: LocalizedStringKey,358        points: [GlassChartPoint],359        kind: GlassChartKind = .line,360        xAxisTitle: String? = nil,361        yAxisTitle: String? = nil,362        unit: String? = nil,363        showsSummary: Bool = true,364        selection: Binding<GlassChartX?>? = nil365    ) {366        self.init(title, points: points, kind: kind, xAxisTitle: xAxisTitle, yAxisTitle: yAxisTitle, unit: unit, showsSummary: showsSummary, selection: selection) {367            EmptyView()368        }369    }370}371
Files main
Menu

Theme