SPB Git

Repository Public

ChartBlockSheet.swift 9.1 KB 184 lines swift

1// SP Notes iOS2// File: Features/Editor/Blocks/ChartBlockSheet.swift3// Description: Sheet of a `chart` block: kind, title, X column, a data grid for the columns and rows, and the live Swift Charts4//              preview. Cells that were not edited keep their stored value exactly (a number stays a number, a text a text).5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SPNotesCore9import SPNotesDesign10import SwiftUI1112/// Editing rules of the data grid, on the typed view (pure, tested).13struct ChartGrid {14    var block: ChartBlock1516    var columns: [String] { block.columns }17    var rows: [[ChartCell]] { block.rows }1819    /// What a typed text becomes: empty → null, a number (decimal point or comma) → number, anything else → text.20    static func cell(from text: String) -> ChartCell {21        let trimmed = text.trimmingCharacters(in: .whitespaces)22        if trimmed.isEmpty { return .null }23        if let number = Double(trimmed.replacingOccurrences(of: ",", with: ".")), number.isFinite { return .number(number) }24        return .string(text)25    }2627    func text(row: Int, column: Int) -> String {28        guard rows.indices.contains(row), rows[row].indices.contains(column) else { return "" }29        return rows[row][column].text30    }3132    /// Changes one cell; a text equal to what the cell already prints leaves the stored value untouched.33    mutating func setText(_ text: String, row: Int, column: Int) {34        var data = rows35        guard data.indices.contains(row), column >= 0, column < columns.count else { return }36        while data[row].count <= column { data[row].append(.null) }37        guard data[row][column].text != text else { return }38        data[row][column] = Self.cell(from: text)39        block.rows = data40    }4142    mutating func renameColumn(_ index: Int, to name: String) {43        var names = columns44        guard names.indices.contains(index), names[index] != name else { return }45        let old = names[index]46        names[index] = name47        // the X and Y selections follow the renamed column48        if block.x == old { block.x = name }49        let y = block.y50        if y.contains(old) { block.y = y.map { $0 == old ? name : $0 } }51        block.columns = names52    }5354    mutating func addRow() { block.rows = rows + [Array(repeating: ChartCell.null, count: max(1, columns.count))] }55    mutating func deleteRow(_ index: Int) {56        var data = rows57        guard data.indices.contains(index) else { return }58        data.remove(at: index)59        block.rows = data60    }6162    mutating func addColumn(named name: String) {63        var unique = name64        var suffix = 265        while columns.contains(unique) { unique = "\(name) \(suffix)"; suffix += 1 }66        block.columns = columns + [unique]67        block.rows = rows.map { $0 + [.null] }68    }6970    mutating func deleteColumn(_ index: Int) {71        var names = columns72        guard names.indices.contains(index), names.count > 1 else { return }73        let removed = names.remove(at: index)74        block.columns = names75        block.rows = rows.map { row in76            var row = row77            if row.indices.contains(index) { row.remove(at: index) }78            return row79        }80        if block.x == removed { block.x = nil }81        let y = block.y82        if y.contains(removed) { block.y = y.filter { $0 != removed } }83    }84}8586struct ChartBlockSheet: View {87    let original: ChartBlock88    let context: BlockDetailContext89    @State private var grid: ChartGrid90    @ScaledMetric(relativeTo: .footnote) private var cellWidth: CGFloat = 1049192    init(block: ChartBlock, context: BlockDetailContext) {93        original = block94        self.context = context95        _grid = State(initialValue: ChartGrid(block: block))96    }9798    private var kinds: [ChartKind] { ChartKind.known.contains(grid.block.kind) ? ChartKind.known : [grid.block.kind] + ChartKind.known }99100    var body: some View {101        BlockSheetScaffold(title: String(localized: "Graphique"), isEditable: context.isEditable, onCancel: context.dismiss,102                           onDone: { context.finish(grid.block.node(), original: original.node()) }, onDelete: context.delete) {103            Form {104                Section {105                    let plot = ChartPlot(grid.block)106                    if plot.isEmpty || (plot.kind == .pie && plot.pieData.isEmpty) {107                        NVEmptyState(systemImage: "chart.bar.xaxis", title: String(localized: "Aucune donnée à tracer"), message: String(localized: "Ajoute des valeurs numériques dans la grille."))108                            .frame(maxWidth: .infinity, minHeight: 160)109                    } else {110                        ChartBlockChart(plot: plot).frame(height: 220).accessibilityIdentifier("chart-preview")111                            .accessibilityLabel(Text("Graphique, \(BlockLabels.chartKind(grid.block.kind))"))112                    }113                    if grid.block.source != nil {114                        BlockNotice(text: String(localized: "Instantané d’une base de données : les valeurs sont celles de la dernière lecture sur le Web."), symbol: "cylinder.split.1x2")115                    }116                }117                Section("Présentation") {118                    Picker("Type", selection: Binding(get: { grid.block.kind }, set: { if $0 != grid.block.kind { grid.block.kind = $0 } })) {119                        ForEach(kinds, id: \.self) { Text(BlockLabels.chartKind($0)).tag($0) }120                    }121                    .accessibilityIdentifier("chart-kind")122                    TextField("Titre", text: Binding(get: { grid.block.title }, set: { if $0 != grid.block.title { grid.block.title = $0 } }))123                        .accessibilityIdentifier("chart-title")124                    if grid.columns.count > 1 {125                        Picker("Axe X", selection: Binding(get: { grid.block.resolvedX ?? "" }, set: { grid.block.x = $0 })) {126                            ForEach(grid.columns, id: \.self) { Text($0).tag($0) }127                        }128                    }129                }130                .disabled(!context.isEditable)131                Section {132                    ScrollView(.horizontal) { dataGrid.padding(.vertical, 4) }133                    if context.isEditable {134                        Button { grid.addRow() } label: { Label("Ajouter une ligne", systemImage: "plus") }.accessibilityIdentifier("chart-add-row")135                        Button { grid.addColumn(named: String(localized: "Série")) } label: { Label("Ajouter une colonne", systemImage: "plus.rectangle.on.rectangle") }.accessibilityIdentifier("chart-add-column")136                    }137                } header: { Text("Données") } footer: { Text("Les nombres s’écrivent avec un point ou une virgule. Une cellule vide n’est pas tracée.") }138            }139        }140    }141142    private var dataGrid: some View {143        Grid(horizontalSpacing: 6, verticalSpacing: 6) {144            GridRow {145                ForEach(Array(grid.columns.enumerated()), id: \.offset) { index, name in146                    HStack(spacing: 2) {147                        TextField("Colonne", text: Binding(get: { name }, set: { grid.renameColumn(index, to: $0) }))148                            .font(.footnote.weight(.semibold))149                        if context.isEditable, grid.columns.count > 1 {150                            Button { grid.deleteColumn(index) } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(NVColor.fgFaint) }151                                .buttonStyle(.plain)152                                .accessibilityLabel("Supprimer la colonne \(name)")153                        }154                    }155                    .padding(8)156                    .frame(width: cellWidth, alignment: .leading)157                    .background(NVColor.bgSunken, in: NVRadius.shape(NVRadius.sm))158                }159                Color.clear.frame(width: 30, height: 1)160            }161            ForEach(Array(grid.rows.enumerated()), id: \.offset) { rowIndex, _ in162                GridRow {163                    ForEach(Array(grid.columns.enumerated()), id: \.offset) { columnIndex, _ in164                        TextField("—", text: Binding(get: { grid.text(row: rowIndex, column: columnIndex) }, set: { grid.setText($0, row: rowIndex, column: columnIndex) }))165                            .font(.footnote)166                            .keyboardType(columnIndex == 0 ? .default : .numbersAndPunctuation)167                            .padding(8)168                            .frame(width: cellWidth, alignment: .leading)169                            .overlay(NVRadius.shape(NVRadius.sm).stroke(NVColor.line, lineWidth: 1))170                            .accessibilityIdentifier("chart-cell-\(rowIndex)-\(columnIndex)")171                    }172                    if context.isEditable {173                        Button { grid.deleteRow(rowIndex) } label: { Image(systemName: "minus.circle").foregroundStyle(NVColor.danger) }174                            .buttonStyle(.plain)175                            .frame(width: 30)176                            .accessibilityLabel("Supprimer la ligne \(rowIndex + 1)")177                    }178                }179            }180        }181        .disabled(!context.isEditable)182    }183}184
Files main
Menu

Theme