SPB Git

Repository Public

Tables.swift 5.4 KB 121 lines swift

1// SP Notes Core2// File: Sources/SPNotesDocument/Tables.swift3// Description: Helpers on a raw table node for a native table editor: grid of cells, cell text, rows, columns and4//              header row, built with the schema defaults.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// One cell of a table, as a native grid shows it.11public struct TableCell: Sendable, Hashable {12    /// Plain text of the cell (its blocks joined by line feeds).13    public var text: String14    public var isHeader: Bool15    public var colspan: Int16    public var rowspan: Int1718    public init(text: String, isHeader: Bool, colspan: Int = 1, rowspan: Int = 1) {19        self.text = text20        self.isHeader = isHeader21        self.colspan = colspan22        self.rowspan = rowspan23    }24}2526extension PMNode {27    /// Whether this node is a table.28    public var isTable: Bool { type == NodeType.table }2930    /// The rows of a table and their cells, in document order (row and column indices of the other helpers).31    public var tableGrid: [[TableCell]] {32        guard isTable else { return [] }33        return (content ?? []).map { row in34            (row.content ?? []).map { cell in35                TableCell(text: cell.plainText, isHeader: cell.type == NodeType.tableHeader,36                          colspan: cell.attrs?["colspan"]?.intValue ?? 1, rowspan: cell.attrs?["rowspan"]?.intValue ?? 1)37            }38        }39    }4041    private func hasCell(_ row: Int, _ column: Int) -> Bool {42        guard isTable, let rows = content, rows.indices.contains(row) else { return false }43        return (rows[row].content ?? []).indices.contains(column)44    }4546    /// Sets the text of a cell: its content becomes one paragraph of plain text (line feeds as hard breaks). Nothing47    /// changes when the text equals the cell's current plain text, so untouched formatted cells are preserved.48    @discardableResult49    public mutating func setTableCellText(_ text: String, row: Int, column: Int) -> Bool {50        guard hasCell(row, column) else { return false }51        let cell = content![row].content![column]52        guard cell.plainText != text else { return false }53        var paragraph = PMNode.paragraph(text)54        if let first = cell.content?.first, first.type == NodeType.paragraph, var attrs = first.attrs {55            if BlockID.usable(attrs["id"]) == nil { attrs["id"] = paragraph.attrs?["id"] }56            paragraph.attrs = attrs57        }58        content![row].content![column].content = [paragraph]59        return true60    }6162    private var columnCount: Int { (content ?? []).map { $0.content?.count ?? 0 }.max() ?? 0 }6364    /// Inserts an empty row before index `row` (clamped; pass the row count to append).65    @discardableResult66    public mutating func insertTableRow(at row: Int) -> Bool {67        guard isTable else { return false }68        let rows = content ?? []69        let hasBody = rows.contains { ($0.content ?? []).contains { $0.type != NodeType.tableHeader } }70        let cells = (0..<max(1, columnCount)).map { j -> PMNode in71            let headerColumn = hasBody && !rows.isEmpty && rows.allSatisfy { r in72                (r.content ?? []).indices.contains(j) && r.content![j].type == NodeType.tableHeader73            }74            return .tableCell(header: headerColumn)75        }76        var out = rows77        out.insert(PMNode(type: NodeType.tableRow, content: cells), at: max(0, min(row, rows.count)))78        content = out79        return true80    }8182    /// Deletes a row; false when it does not exist or is the last one.83    @discardableResult84    public mutating func deleteTableRow(at row: Int) -> Bool {85        guard isTable, let rows = content, rows.count > 1, rows.indices.contains(row) else { return false }86        content!.remove(at: row)87        return true88    }8990    /// Inserts an empty column before index `column` (clamped per row; pass the column count to append).91    @discardableResult92    public mutating func insertTableColumn(at column: Int) -> Bool {93        guard isTable, let rows = content, !rows.isEmpty else { return false }94        for r in rows.indices {95            var cells = rows[r].content ?? []96            let header = !cells.isEmpty && cells.allSatisfy { $0.type == NodeType.tableHeader }97            cells.insert(.tableCell(header: header), at: max(0, min(column, cells.count)))98            content![r].content = cells99        }100        return true101    }102103    /// Deletes a column; false when it does not exist in any row or a row would be left without a cell.104    @discardableResult105    public mutating func deleteTableColumn(at column: Int) -> Bool {106        guard isTable, let rows = content, column >= 0, rows.contains(where: { ($0.content?.count ?? 0) > column }),107              rows.allSatisfy({ ($0.content?.count ?? 0) != 1 || column != 0 }), columnCount > 1 else { return false }108        for r in rows.indices where (rows[r].content?.count ?? 0) > column { content![r].content!.remove(at: column) }109        return true110    }111112    /// Turns the first row into header cells, or back into plain cells when it is entirely made of header cells.113    @discardableResult114    public mutating func toggleTableHeaderRow() -> Bool {115        guard isTable, let first = content?.first, let cells = first.content, !cells.isEmpty else { return false }116        let target = cells.allSatisfy { $0.type == NodeType.tableHeader } ? NodeType.tableCell : NodeType.tableHeader117        for j in cells.indices { content![0].content![j].type = target }118        return true119    }120}121
Files main
Menu

Theme