SPB Git

Repository Public

TableEditorSheet.swift 11.5 KB 241 lines swift

1// SP Notes iOS2// File: Features/Editor/Sheets/TableEditorSheet.swift3// Description: Native editor of a table node: a grid of text fields in a two-directional scroll view, header row, rows and columns4//              added or removed with the Document table helpers. Cells keep their formatting unless their text changes.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import SPNotesCore1011/// The editing state of a table, independent of the UI. Structure changes go straight to the node; texts are kept aside and12/// written to the node only by `result()`, so a cell whose text ends up unchanged keeps its formatted content.13struct TableEditorModel: Equatable {14    private(set) var node: PMNode15    /// Text of each cell as shown in the fields, parallel to the node's rows and cells.16    private(set) var texts: [[String]]17    private let original: PMNode1819    init(node: PMNode) {20        self.node = node21        self.original = node22        self.texts = node.tableGrid.map { $0.map(\.text) }23    }2425    var rowCount: Int { texts.count }26    var columnCount: Int { texts.map(\.count).max() ?? 0 }27    var hasHeaderRow: Bool {28        guard let first = node.tableGrid.first, !first.isEmpty else { return false }29        return first.allSatisfy(\.isHeader)30    }31    var canDeleteRow: Bool { rowCount > 1 }32    var canDeleteColumn: Bool { columnCount > 1 }33    var hasChanges: Bool { result() != original }3435    func isHeader(row: Int, column: Int) -> Bool {36        let grid = node.tableGrid37        guard grid.indices.contains(row), grid[row].indices.contains(column) else { return false }38        return grid[row][column].isHeader39    }4041    func text(row: Int, column: Int) -> String {42        guard texts.indices.contains(row), texts[row].indices.contains(column) else { return "" }43        return texts[row][column]44    }4546    mutating func setText(_ text: String, row: Int, column: Int) {47        guard texts.indices.contains(row), texts[row].indices.contains(column) else { return }48        texts[row][column] = text49    }5051    /// Inserts an empty row before `row` (pass `rowCount` to append).52    @discardableResult53    mutating func insertRow(at row: Int) -> Bool {54        let index = max(0, min(row, rowCount))55        guard node.insertTableRow(at: index) else { return false }56        let cells = node.tableGrid.indices.contains(index) ? node.tableGrid[index].count : max(1, columnCount)57        texts.insert(Array(repeating: "", count: cells), at: index)58        return true59    }6061    @discardableResult62    mutating func deleteRow(at row: Int) -> Bool {63        guard node.deleteTableRow(at: row) else { return false }64        texts.remove(at: row)65        return true66    }6768    /// Inserts an empty column before `column` (pass `columnCount` to append).69    @discardableResult70    mutating func insertColumn(at column: Int) -> Bool {71        guard node.insertTableColumn(at: column) else { return false }72        for r in texts.indices { texts[r].insert("", at: max(0, min(column, texts[r].count))) }73        return true74    }7576    @discardableResult77    mutating func deleteColumn(at column: Int) -> Bool {78        guard node.deleteTableColumn(at: column) else { return false }79        for r in texts.indices where texts[r].count > column { texts[r].remove(at: column) }80        return true81    }8283    @discardableResult84    mutating func toggleHeaderRow() -> Bool { node.toggleTableHeaderRow() }8586    /// The edited table: the node with every changed text applied (unchanged cells are left as they were).87    func result() -> PMNode {88        var out = node89        for (r, row) in texts.enumerated() {90            for (c, text) in row.enumerated() { out.setTableCellText(text, row: r, column: c) }91        }92        return out93    }94}9596/// Sheet editing a table. `onDone` receives the edited node (pass it to `NoteDocument.replaceBlockAtom(at:with:)`).97struct TableEditorSheet: View {98    var onDone: (PMNode) -> Void99    var onCancel: () -> Void100101    @State private var model: TableEditorModel102    @State private var confirmsDiscard = false103    @FocusState private var focus: CellID?104    @ScaledMetric(relativeTo: .body) private var columnWidth: CGFloat = 150105    @ScaledMetric(relativeTo: .body) private var handleSize: CGFloat = 44106107    private struct CellID: Hashable { var row: Int; var column: Int }108109    init(table: PMNode, onDone: @escaping (PMNode) -> Void, onCancel: @escaping () -> Void) {110        _model = State(initialValue: TableEditorModel(node: table))111        self.onDone = onDone112        self.onCancel = onCancel113    }114115    var body: some View {116        NavigationStack {117            VStack(spacing: 0) {118                Toggle(isOn: Binding(get: { model.hasHeaderRow }, set: { on in if on != model.hasHeaderRow { model.toggleHeaderRow() } })) {119                    Text("Ligne d’en-tête")120                }121                .tint(Color("AccentColor"))122                .padding(.horizontal, 16)123                .frame(minHeight: 52)124                .accessibilityIdentifier("table-header-toggle")125                Divider().overlay(Color("Border"))126                ScrollView([.horizontal, .vertical]) {127                    grid.padding(12)128                }129                .scrollDismissesKeyboard(.interactively)130                Divider().overlay(Color("Border"))131                HStack(spacing: 12) {132                    Button { model.insertRow(at: model.rowCount) } label: { Label { Text("Ligne") } icon: { Image(systemName: "plus") } }133                        .accessibilityLabel(Text("Ajouter une ligne à la fin"))134                        .accessibilityIdentifier("table-add-row")135                    Button { model.insertColumn(at: model.columnCount) } label: { Label { Text("Colonne") } icon: { Image(systemName: "plus") } }136                        .accessibilityLabel(Text("Ajouter une colonne à la fin"))137                        .accessibilityIdentifier("table-add-column")138                    Spacer()139                    Text("\(model.rowCount) × \(model.columnCount)")140                        .font(.footnote.monospacedDigit())141                        .foregroundStyle(Color("TextSecondary"))142                        .accessibilityLabel(Text("\(model.rowCount) lignes, \(model.columnCount) colonnes"))143                }144                .buttonStyle(.bordered)145                .padding(.horizontal, 16)146                .frame(minHeight: 60)147            }148            .background(Color("Background"))149            .navigationTitle(Text("Tableau"))150            .navigationBarTitleDisplayMode(.inline)151            .toolbar {152                ToolbarItem(placement: .cancellationAction) {153                    Button { if model.hasChanges { confirmsDiscard = true } else { onCancel() } } label: { Text("Annuler") }154                        .accessibilityIdentifier("table-cancel")155                }156                ToolbarItem(placement: .confirmationAction) {157                    Button { onDone(model.result()) } label: { Text("Terminé").bold() }158                        .accessibilityIdentifier("table-done")159                }160                ToolbarItemGroup(placement: .keyboard) {161                    Spacer()162                    Button { focus = nil } label: { Image(systemName: "keyboard.chevron.compact.down") }163                        .accessibilityLabel(Text("Masquer le clavier"))164                }165            }166            .confirmationDialog(Text("Abandonner les modifications du tableau ?"), isPresented: $confirmsDiscard, titleVisibility: .visible) {167                Button(role: .destructive) { onCancel() } label: { Text("Abandonner") }168                Button(role: .cancel) {} label: { Text("Continuer") }169            }170            .interactiveDismissDisabled(model.hasChanges)171        }172    }173174    private var grid: some View {175        Grid(alignment: .topLeading, horizontalSpacing: 6, verticalSpacing: 6) {176            GridRow {177                Color.clear.frame(width: handleSize, height: handleSize)178                ForEach(0..<model.columnCount, id: \.self) { column in columnHandle(column) }179            }180            ForEach(0..<model.rowCount, id: \.self) { row in181                GridRow {182                    rowHandle(row)183                    ForEach(0..<model.texts[row].count, id: \.self) { column in cell(row, column) }184                }185            }186        }187    }188189    private func cell(_ row: Int, _ column: Int) -> some View {190        let header = model.isHeader(row: row, column: column)191        return TextField(text: Binding(get: { model.text(row: row, column: column) }, set: { model.setText($0, row: row, column: column) }), axis: .vertical) { Text(verbatim: "") }192            .focused($focus, equals: CellID(row: row, column: column))193            .font(header ? .body.bold() : .body)194            .foregroundStyle(Color("TextPrimary"))195            .lineLimit(1...6)196            .padding(.horizontal, 10)197            .padding(.vertical, 10)198            .frame(width: columnWidth, alignment: .topLeading)199            .frame(minHeight: 44, alignment: .topLeading)200            .background(header ? Color("Surface2") : Color("Surface"), in: RoundedRectangle(cornerRadius: 8))201            .overlay(RoundedRectangle(cornerRadius: 8).stroke(focus == CellID(row: row, column: column) ? Color("AccentColor") : Color("Border"), lineWidth: 1))202            .accessibilityLabel(header ? Text("En-tête, ligne \(row + 1), colonne \(column + 1)") : Text("Cellule, ligne \(row + 1), colonne \(column + 1)"))203            .accessibilityIdentifier("table-cell-\(row)-\(column)")204    }205206    private func columnHandle(_ column: Int) -> some View {207        Menu {208            Button { model.insertColumn(at: column) } label: { Label { Text("Insérer une colonne à gauche") } icon: { Image(systemName: "arrow.left.to.line") } }209            Button { model.insertColumn(at: column + 1) } label: { Label { Text("Insérer une colonne à droite") } icon: { Image(systemName: "arrow.right.to.line") } }210            Button(role: .destructive) { focus = nil; model.deleteColumn(at: column) } label: { Label { Text("Supprimer la colonne") } icon: { Image(systemName: "trash") } }211                .disabled(!model.canDeleteColumn)212        } label: {213            Image(systemName: "ellipsis")214                .frame(width: columnWidth, height: handleSize)215                .foregroundStyle(Color("TextSecondary"))216                .background(Color("Surface2").opacity(0.6), in: RoundedRectangle(cornerRadius: 8))217                .contentShape(Rectangle())218        }219        .accessibilityLabel(Text("Actions de la colonne \(column + 1)"))220        .accessibilityIdentifier("table-column-menu-\(column)")221    }222223    private func rowHandle(_ row: Int) -> some View {224        Menu {225            Button { model.insertRow(at: row) } label: { Label { Text("Insérer une ligne au-dessus") } icon: { Image(systemName: "arrow.up.to.line") } }226            Button { model.insertRow(at: row + 1) } label: { Label { Text("Insérer une ligne en dessous") } icon: { Image(systemName: "arrow.down.to.line") } }227            Button(role: .destructive) { focus = nil; model.deleteRow(at: row) } label: { Label { Text("Supprimer la ligne") } icon: { Image(systemName: "trash") } }228                .disabled(!model.canDeleteRow)229        } label: {230            Image(systemName: "ellipsis")231                .rotationEffect(.degrees(90))232                .frame(width: handleSize, height: handleSize)233                .foregroundStyle(Color("TextSecondary"))234                .background(Color("Surface2").opacity(0.6), in: RoundedRectangle(cornerRadius: 8))235                .contentShape(Rectangle())236        }237        .accessibilityLabel(Text("Actions de la ligne \(row + 1)"))238        .accessibilityIdentifier("table-row-menu-\(row)")239    }240}241
Files main
Menu

Theme