Repository Public
1// SP Notes Core2// File: Sources/SPNotesFeatures/MediaBlocks/ChartBlockView.swift3// Description: Detail view of a `chart` node: Swift Charts for the five kinds (bar, line, area, pie, scatter), the kind4// and axis choosers, and the data grid editor (a table on regular, one card per row on compact). A chart fed5// by a database shows live rows, says how fresh they are, and falls back on the node's snapshot offline.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Charts10import SPNotesDesign11import SPNotesDocument12import SPNotesSync13import SwiftUI1415public struct ChartBlockView: View {16 @State private var model: ChartBlockModel1718 /// - Parameters:19 /// - repositories: needed only for a chart with a `source` (live database rows).20 /// - onChange: receives the node with its updated attributes after each edit; the caller saves the page.21 public init(block: ChartBlock, repositories: NotesRepositories? = nil, onChange: @escaping (ChartBlock) -> Void = { _ in }) {22 _model = State(initialValue: ChartBlockModel(block: block, repositories: repositories, onChange: onChange))23 }2425 public init(model: ChartBlockModel) { _model = State(initialValue: model) }2627 public var body: some View {28 FeatureLayoutReader { sizeClass in29 ScrollView {30 VStack(alignment: .leading, spacing: NVSpace.lg) {31 header(compact: sizeClass.isCompact)32 origin33 chartCard(compact: sizeClass.isCompact)34 axes(compact: sizeClass.isCompact)35 data(compact: sizeClass.isCompact)36 }37 .padding(sizeClass.isCompact ? NVSpace.lg : NVSpace.xl)38 .frame(maxWidth: 980, alignment: .leading)39 .frame(maxWidth: .infinity)40 }41 .background(NVColor.bg)42 }43 .task { if model.phase == .idle { await model.load() } }44 }4546 private func header(compact: Bool) -> some View {47 VStack(alignment: .leading, spacing: NVSpace.sm) {48 TextField(L("Titre du graphique"), text: Binding(get: { model.block.title }, set: { model.setTitle($0) }), axis: .vertical)49 .textFieldStyle(.plain)50 .nvFont(compact ? .h3 : .h2)51 .foregroundStyle(NVColor.fg)52 .lineLimit(1...2)53 .accessibilityLabel(L("Titre du graphique"))54 ScrollView(.horizontal, showsIndicators: false) {55 HStack(spacing: NVSpace.sm) {56 ForEach(ChartKind.known, id: \.self) { kind in57 NVChip(ChartBlockModel.kindName(kind), systemImage: Self.symbol(kind), tone: .accent, isSelected: model.block.kind == kind) { model.setKind(kind) }58 }59 }60 }61 }62 }6364 static func symbol(_ kind: ChartKind) -> String {65 switch kind {66 case .line: return "chart.xyaxis.line"67 case .area: return "chart.line.uptrend.xyaxis"68 case .pie: return "chart.pie"69 case .scatter: return "chart.dots.scatter"70 default: return "chart.bar"71 }72 }7374 @ViewBuilder75 private var origin: some View {76 switch model.origin {77 case .node:78 EmptyView()79 case .live(let freshness):80 HStack(spacing: NVSpace.sm) {81 Image(systemName: "cylinder.split.1x2").foregroundStyle(NVColor.accent).accessibilityHidden(true)82 Text(model.databaseName.map { LF("Données en direct de « %@ »", $0) } ?? L("Données en direct de la base")).nvFont(.ui).foregroundStyle(NVColor.fg)83 Spacer(minLength: NVSpace.sm)84 if model.snapshotIsOutdated { FeatureButton(L("Mettre à jour l'instantané")) { model.updateSnapshot() } }85 }86 FeatureStatusBanner(failure: nil, freshness: freshness, retry: freshness.fromCache ? { Task { await model.load() } } : nil)87 case .snapshot:88 FeatureStatusBanner(failure: model.liveFailure.map { failure in89 FeatureFailure(kind: failure.kind, message: failure.isOffline ? L("Hors ligne · instantané enregistré dans la note") : LF("Base injoignable (%@) · instantané enregistré dans la note", failure.message), code: failure.code)90 }, freshness: nil, retry: { Task { await model.load() } })91 }92 }9394 private static let palette: [Color] = [NVColor.accent, NVColor.success, NVColor.warning, NVColor.danger, NVColor.fgMuted]9596 private func chartCard(compact: Bool) -> some View {97 VStack(alignment: .leading, spacing: NVSpace.sm) {98 if model.phase.isLoading {99 FeatureLoadingView().frame(height: compact ? 240 : 340)100 } else if model.marks.isEmpty || (model.block.kind == .pie && model.slices.isEmpty) {101 NVEmptyState(systemImage: Self.symbol(model.block.kind), title: L("Rien à tracer"),102 message: model.hasData ? L("Aucune valeur numérique dans les séries choisies.") : L("Ajoutez des colonnes et des lignes dans les données ci-dessous."))103 .frame(maxWidth: .infinity, minHeight: compact ? 220 : 300)104 } else {105 chart106 .frame(height: compact ? 260 : 360)107 .accessibilityElement(children: .contain)108 .accessibilityLabel(model.summary)109 if model.skippedCount > 0 {110 Text(LF("Valeurs non tracées (vides, non numériques ou négatives) : %lld", model.skippedCount)).nvFont(.micro).foregroundStyle(NVColor.fgMuted)111 }112 }113 }114 .padding(NVSpace.lg)115 .frame(maxWidth: .infinity, alignment: .leading)116 .nvCard()117 }118119 @ViewBuilder120 private var chart: some View {121 let marks = model.marks122 let series = model.yColumns123 switch model.block.kind {124 case .pie:125 Chart(model.slices) { slice in126 SectorMark(angle: .value(slice.series, slice.y), innerRadius: .ratio(0.55), angularInset: 1.5)127 .cornerRadius(3)128 .foregroundStyle(by: .value(model.xColumn ?? "", slice.label))129 .accessibilityLabel(slice.label)130 .accessibilityValue(ChartBlockModel.format(slice.y))131 }132 .chartForegroundStyleScale(range: Self.palette + Self.palette.map { $0.opacity(0.55) })133 .chartLegend(position: .bottom, alignment: .leading)134 case .scatter:135 Chart(marks) { mark in136 if let x = mark.x {137 PointMark(x: .value(model.xColumn ?? "", x), y: .value(mark.series, mark.y))138 .foregroundStyle(by: .value(L("Série"), mark.series))139 .symbol(by: .value(L("Série"), mark.series))140 .accessibilityLabel(mark.label)141 } else {142 PointMark(x: .value(model.xColumn ?? "", mark.label), y: .value(mark.series, mark.y))143 .foregroundStyle(by: .value(L("Série"), mark.series))144 .symbol(by: .value(L("Série"), mark.series))145 }146 }147 .chartForegroundStyleScale(domain: series, range: Array(Self.palette.prefix(max(1, series.count))))148 .chartLegend(series.count > 1 ? .visible : .hidden)149 .chartLegend(position: .bottom, alignment: .leading)150 case .line, .area:151 Chart(marks) { mark in152 if model.block.kind == .area {153 AreaMark(x: .value(model.xColumn ?? "", mark.label), y: .value(mark.series, mark.y), stacking: .unstacked)154 .foregroundStyle(by: .value(L("Série"), mark.series))155 .opacity(0.22)156 .interpolationMethod(.monotone)157 }158 LineMark(x: .value(model.xColumn ?? "", mark.label), y: .value(mark.series, mark.y))159 .foregroundStyle(by: .value(L("Série"), mark.series))160 .interpolationMethod(.monotone)161 .lineStyle(StrokeStyle(lineWidth: 2.5, lineCap: .round, lineJoin: .round))162 PointMark(x: .value(model.xColumn ?? "", mark.label), y: .value(mark.series, mark.y))163 .foregroundStyle(by: .value(L("Série"), mark.series))164 .symbolSize(28)165 }166 .chartForegroundStyleScale(domain: series, range: Array(Self.palette.prefix(max(1, series.count))))167 .chartLegend(series.count > 1 ? .visible : .hidden)168 .chartLegend(position: .bottom, alignment: .leading)169 default:170 Chart(marks) { mark in171 BarMark(x: .value(model.xColumn ?? "", mark.label), y: .value(mark.series, mark.y))172 .foregroundStyle(by: .value(L("Série"), mark.series))173 .position(by: .value(L("Série"), mark.series))174 .cornerRadius(3)175 }176 .chartForegroundStyleScale(domain: series, range: Array(Self.palette.prefix(max(1, series.count))))177 .chartLegend(series.count > 1 ? .visible : .hidden)178 .chartLegend(position: .bottom, alignment: .leading)179 }180 }181182 @ViewBuilder183 private func axes(compact: Bool) -> some View {184 if !model.columns.isEmpty {185 VStack(alignment: .leading, spacing: NVSpace.sm) {186 NVSectionHeader(L("Axes"))187 let layout = compact ? AnyLayout(VStackLayout(alignment: .leading, spacing: NVSpace.sm)) : AnyLayout(HStackLayout(alignment: .top, spacing: NVSpace.xl))188 layout {189 VStack(alignment: .leading, spacing: NVSpace.xs) {190 Text(model.block.kind == .pie ? L("Étiquettes") : L("Axe horizontal")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)191 chips(model.columns, selected: { $0 == model.xColumn }) { model.setX($0) }192 }193 VStack(alignment: .leading, spacing: NVSpace.xs) {194 Text(model.block.kind == .pie ? L("Valeurs (première série)") : L("Séries")).nvFont(.micro).foregroundStyle(NVColor.fgMuted)195 chips(model.columns.filter { $0 != model.xColumn }, selected: { model.yColumns.contains($0) }) { model.toggleY($0) }196 }197 }198 }199 }200 }201202 private func chips(_ names: [String], selected: @escaping (String) -> Bool, action: @escaping (String) -> Void) -> some View {203 ScrollView(.horizontal, showsIndicators: false) {204 HStack(spacing: NVSpace.sm) {205 ForEach(names, id: \.self) { name in NVChip(name, tone: .accent, isSelected: selected(name)) { action(name) } }206 }207 }208 }209210 private func data(compact: Bool) -> some View {211 VStack(alignment: .leading, spacing: NVSpace.sm) {212 NVSectionHeader(L("Données"), subtitle: model.canEditCells ? nil : L("Lues dans la base : modifiez-les dans la base.")) {213 if model.canEditCells {214 FeatureButton(L("Ligne"), systemImage: "plus") { model.addRow() }215 FeatureButton(L("Colonne"), systemImage: "plus") { model.addColumn() }216 }217 }218 if model.columns.isEmpty {219 Text(L("Aucune colonne. Ajoutez une colonne pour les catégories, puis une par série.")).nvFont(.ui).foregroundStyle(NVColor.fgMuted)220 } else if compact {221 ChartRowCards(model: model)222 } else {223 ChartDataGrid(model: model)224 }225 }226 }227}228229/// Regular layout: the table (editable when the node owns its data).230struct ChartDataGrid: View {231 @Bindable var model: ChartBlockModel232233 var body: some View {234 let columns = model.columns, rows = model.rows235 ScrollView(.horizontal, showsIndicators: true) {236 Grid(alignment: .leading, horizontalSpacing: 0, verticalSpacing: 0) {237 GridRow {238 ForEach(Array(columns.enumerated()), id: \.offset) { _, name in239 HStack(spacing: NVSpace.xs) {240 if model.canEditCells {241 TextField(L("Nom de colonne"), text: Binding(get: { name }, set: { model.renameColumn(name, to: $0) }))242 .textFieldStyle(.plain).nvFont(.uiStrong).foregroundStyle(NVColor.fg)243 if columns.count > 1 { FeatureIconButton("xmark", label: LF("Supprimer la colonne %@", name)) { model.removeColumn(name) } }244 } else {245 Text(name).nvFont(.uiStrong).foregroundStyle(NVColor.fg)246 }247 }248 .padding(.horizontal, NVSpace.sm).padding(.vertical, NVSpace.xs)249 .frame(minWidth: 150, maxWidth: .infinity, alignment: .leading)250 .background(NVColor.bgSunken)251 .overlay(alignment: .trailing) { Rectangle().fill(NVColor.line).frame(width: 1) }252 }253 if model.canEditCells { Color.clear.frame(width: 40, height: 1) }254 }255 ForEach(Array(rows.enumerated()), id: \.offset) { rowIndex, row in256 GridRow {257 ForEach(Array(columns.enumerated()), id: \.offset) { columnIndex, name in258 let cell = columnIndex < row.count ? row[columnIndex] : ChartCell.null259 Group {260 if model.canEditCells {261 TextField("", text: Binding(get: { ChartBlockModel.display(cell) }, set: { model.setCell(row: rowIndex, column: columnIndex, $0) }))262 .textFieldStyle(.plain)263 .accessibilityLabel(LF("%@, ligne %lld", name, rowIndex + 1))264 } else {265 Text(ChartBlockModel.display(cell))266 }267 }268 .nvFont(.ui).foregroundStyle(NVColor.fg).monospacedDigit()269 .multilineTextAlignment(cell.numericValue != nil && columnIndex > 0 ? .trailing : .leading)270 .padding(.horizontal, NVSpace.sm).padding(.vertical, NVSpace.sm)271 .frame(minWidth: 150, maxWidth: .infinity, alignment: cell.numericValue != nil && columnIndex > 0 ? .trailing : .leading)272 .overlay(alignment: .top) { Rectangle().fill(NVColor.line).frame(height: 1) }273 .overlay(alignment: .trailing) { Rectangle().fill(NVColor.line).frame(width: 1) }274 }275 if model.canEditCells {276 FeatureIconButton("minus.circle", label: LF("Supprimer la ligne %lld", rowIndex + 1)) { model.removeRow(rowIndex) }.frame(width: 40)277 }278 }279 }280 }281 .background(NVColor.bgElevated)282 .clipShape(NVRadius.shape(NVRadius.md))283 .overlay(NVRadius.shape(NVRadius.md).strokeBorder(NVColor.line, lineWidth: 1))284 }285 }286}287288/// Compact layout: one card per row, one labelled field per column.289struct ChartRowCards: View {290 @Bindable var model: ChartBlockModel291292 var body: some View {293 let columns = model.columns294 VStack(spacing: NVSpace.sm) {295 ForEach(Array(model.rows.enumerated()), id: \.offset) { rowIndex, row in296 VStack(alignment: .leading, spacing: NVSpace.xs) {297 ForEach(Array(columns.enumerated()), id: \.offset) { columnIndex, name in298 let cell = columnIndex < row.count ? row[columnIndex] : ChartCell.null299 HStack(alignment: .firstTextBaseline, spacing: NVSpace.sm) {300 Text(name).nvFont(columnIndex == 0 ? .uiStrong : .ui).foregroundStyle(NVColor.fgMuted).frame(width: 96, alignment: .leading)301 if model.canEditCells {302 TextField(L("Valeur"), text: Binding(get: { ChartBlockModel.display(cell) }, set: { model.setCell(row: rowIndex, column: columnIndex, $0) }))303 .textFieldStyle(.plain)304 .nvFont(columnIndex == 0 ? .uiStrong : .body).foregroundStyle(NVColor.fg).monospacedDigit()305 .frame(minHeight: 32)306 .accessibilityLabel(LF("%@, ligne %lld", name, rowIndex + 1))307 } else {308 Text(ChartBlockModel.display(cell)).nvFont(columnIndex == 0 ? .uiStrong : .body).foregroundStyle(NVColor.fg).monospacedDigit()309 }310 Spacer(minLength: 0)311 if columnIndex == 0, model.canEditCells {312 FeatureIconButton("minus.circle", label: LF("Supprimer la ligne %lld", rowIndex + 1)) { model.removeRow(rowIndex) }313 }314 }315 }316 }317 .padding(NVSpace.md)318 .frame(maxWidth: .infinity, alignment: .leading)319 .nvCard(radius: NVRadius.md)320 }321 }322 }323}324