SPB Git

Repository Public

TableInspector.swift 18.5 KB 297 lines swift

1// ORIX Docs2// File: App/Sources/Inspector/TableInspector.swift3// Description: The Table tab: style gallery, header row, alignment, row and column actions, column width, cell alignment, shading,4//              borders and padding, sorting and the formula of the current cell.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel1011struct TableInspector: View {12    @Bindable var session: DocumentSession13    /// The "pen" used by the border buttons.14    @State private var penWidth: Double = 0.7515    @State private var penColor = RGBA(hex: 0x16181D)16    @State private var penStyle: BorderLine.Style = .solid1718    private var pen: BorderLine { BorderLine(width: penWidth, color: penColor, style: penStyle) }1920    private static var lineStyles: [(value: BorderLine.Style, title: String)] {21        [(.solid, String(localized: "Solid")), (.dashed, String(localized: "Dashed")), (.dotted, String(localized: "Dotted")), (.double, String(localized: "Double"))]22    }2324    private func command(_ title: LocalizedStringKey, _ c: EditorCommand, _ symbol: String) -> some View {25        InspectorButton(title, symbol: symbol, isEnabled: session.isEnabled(c), identifier: "table-\(c.rawValue)") { session.run(c); session.refocusCanvas() }26            .help(c.title)27    }2829    private func table(_ name: String, key: String? = nil, _ change: (inout DocModel.Table) -> Void) {30        session.perform(name, coalesce: key.map { "table-\($0)" }) { $0.mutateTable(change) }31        session.refocusCanvas()32    }3334    private func cells(_ name: String, key: String? = nil, _ change: (inout TableCell) -> Void) {35        session.perform(name, coalesce: key.map { "cell-\($0)" }) { $0.formatCells(change) }36        session.refocusCanvas()37    }3839    var body: some View {40        let _ = session.selectionRevision41        let _ = session.revision42        if let sel = session.editor.tableSelection, let t = session.editor.currentTable {43            content(t, sel)44        } else {45            VStack(spacing: 0) {46                EmptyState(symbol: "tablecells", title: "No table selected", message: "Place the caret in a table to format it, or insert a new one.")47                InspectorButton("Insert Table…", symbol: "plus", isEnabled: session.isEnabled(.insertTable), prominent: true, fill: false, identifier: "table-insert") {48                    session.activeSheet = .insertTable49                }50            }51            .padding(.vertical, ORIX.Space.xl)52            .frame(maxWidth: .infinity)53        }54    }5556    @ViewBuilder private func content(_ t: DocModel.Table, _ sel: (block: Int, rows: ClosedRange<Int>, columns: ClosedRange<Int>)) -> some View {57        let firstCell: TableCell? = {58            guard t.rows.indices.contains(sel.rows.lowerBound) else { return nil }59            let row = t.rows[sel.rows.lowerBound]60            return DocumentEditor.cells(in: row, columns: sel.columns).first.map { row.cells[$0] }61        }()62        let caretCell: TableCell? = session.selection.head.path.cell.flatMap { c in63            t.rows.indices.contains(c.row) && t.rows[c.row].cells.indices.contains(c.cell) ? t.rows[c.row].cells[c.cell] : nil64        }65        let column = min(sel.columns.lowerBound, t.columnCount - 1)66        let cellCount = sel.rows.count * sel.columns.count6768        VStack(alignment: .leading, spacing: ORIX.Space.xs) {69            HStack(spacing: ORIX.Space.s) {70                Image(systemName: "tablecells").font(.system(size: 11, weight: .medium)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)71                Text("\(t.rows.count) rows × \(t.columnCount) columns").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.text)72                Spacer(minLength: 0)73            }74            Text(cellCount > 1 ? "Rows \(sel.rows.lowerBound + 1)–\(sel.rows.upperBound + 1), columns \(sel.columns.lowerBound + 1)–\(sel.columns.upperBound + 1) selected"75                               : "Row \(sel.rows.lowerBound + 1), column \(sel.columns.lowerBound + 1)")76                .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textSecondary)77        }78        .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.m)79        .frame(maxWidth: .infinity, alignment: .leading)80        .overlay(alignment: .bottom) { Rectangle().fill(ORIX.Palette.hairline.opacity(0.7)).frame(height: 1) }81        .accessibilityElement(children: .combine)8283        InspectorGroup("Table Style", id: "table.style") {84            HStack(spacing: 6) {85                ForEach(DocModel.TableStyle.all, id: \.name) { style in86                    TableStyleCard(style: style, isCurrent: t.style.name == style.name) {87                        // The gallery changes the look; the padding chosen for this table is kept.88                        table(String(localized: "Table Style")) { var s = style; s.cellPadding = $0.style.cellPadding; $0.style = s }89                    }90                }91            }92            SwitchRow("Header row", isOn: t.rows.first?.isHeader ?? false, identifier: "table-header-row") { _ in session.run(.toggleHeaderRow); session.refocusCanvas() }93            PropertyRow("Alignment") {94                IconSegments(items: [.init(value: HorizontalAnchor.left, symbol: "align.horizontal.left", title: String(localized: "Align table left")),95                                     .init(value: .center, symbol: "align.horizontal.center", title: String(localized: "Centre table")),96                                     .init(value: .right, symbol: "align.horizontal.right", title: String(localized: "Align table right"))],97                             selection: t.alignment, identifier: "table-align") { a in table(String(localized: "Table Alignment")) { $0.alignment = a } }98            }99        }100101        InspectorGroup("Rows and Columns", id: "table.structure") {102            Grid(horizontalSpacing: ORIX.Space.s, verticalSpacing: ORIX.Space.s) {103                GridRow { command("Row Above", .rowAbove, "arrow.up.to.line"); command("Row Below", .rowBelow, "arrow.down.to.line") }104                GridRow { command("Column Before", .columnLeft, "arrow.left.to.line"); command("Column After", .columnRight, "arrow.right.to.line") }105                GridRow { command("Delete Rows", .deleteRow, "minus"); command("Delete Columns", .deleteColumn, "minus") }106                GridRow { command("Merge Cells", .mergeCells, "arrow.down.right.and.arrow.up.left"); command("Split Cell", .splitCell, "arrow.up.left.and.arrow.down.right") }107            }108            PropertyRow("Column width") {109                LengthField(points: t.columnWidths[column], range: 18...1584, label: "Width of the current column", identifier: "table-column-width") { w in110                    table(String(localized: "Column Width"), key: "colwidth") { if $0.columnWidths.indices.contains(column) { $0.columnWidths[column] = max(18, w) } }111                }112            }113            InspectorButton("Distribute Columns Evenly", symbol: "rectangle.split.3x1", identifier: "table-distribute") {114                table(String(localized: "Distribute Columns")) { tb in115                    let w = tb.totalWidth / Double(max(1, tb.columnCount))116                    tb.columnWidths = Array(repeating: w, count: tb.columnCount)117                }118            }119            HStack(spacing: ORIX.Space.s) {120                command("Sort A → Z", .sortAscending, "arrow.up")121                command("Sort Z → A", .sortDescending, "arrow.down")122            }123            InspectorNote("Sorting orders the body rows by the current column; a header row stays in place.")124        }125126        InspectorGroup("Cells", id: "table.cells") {127            PropertyRow("Vertical alignment") {128                IconSegments(items: [.init(value: CellVerticalAlignment.top, symbol: "align.vertical.top", title: String(localized: "Align to top")),129                                     .init(value: .center, symbol: "align.vertical.center", title: String(localized: "Centre vertically")),130                                     .init(value: .bottom, symbol: "align.vertical.bottom", title: String(localized: "Align to bottom"))],131                             selection: firstCell?.vAlign, identifier: "table-valign") { a in cells(String(localized: "Cell Alignment")) { $0.vAlign = a } }132            }133            PropertyRow("Shading") {134                SwatchMenu(help: "Cell shading", current: firstCell?.shading, allowsNone: true, palette: ColorMenu.highlights, identifier: "table-shading") { c in135                    cells(String(localized: "Cell Shading"), key: "shading") { $0.shading = c }136                }137            }138            PropertyRow("Padding") {139                ValueField(value: t.style.cellPadding.left, range: 0...36, step: 1, decimals: 1, suffix: "↔", width: 62, label: "Horizontal cell padding, in points") { v in140                    table(String(localized: "Cell Padding"), key: "pad-h") { $0.style.cellPadding.left = v; $0.style.cellPadding.right = v }141                }142                ValueField(value: t.style.cellPadding.top, range: 0...36, step: 1, decimals: 1, suffix: "↕", width: 62, label: "Vertical cell padding, in points") { v in143                    table(String(localized: "Cell Padding"), key: "pad-v") { $0.style.cellPadding.top = v; $0.style.cellPadding.bottom = v }144                }145            }146            InspectorNote("Padding applies to every cell of the table, in points.")147        }148149        InspectorGroup("Cell Borders", id: "table.borders") {150            PropertyRow("Line") {151                ChoicePopup(selection: penStyle, options: TableInspector.lineStyles, width: 78, label: "Border style") { penStyle = $0 }152                ValueField(value: penWidth, range: 0.25...8, step: 0.25, decimals: 2, suffix: "pt", width: 66, label: "Border width") { penWidth = $0 }153                SwatchMenu(help: "Border colour", current: penColor) { if let c = $0 { penColor = c } }154            }155            PropertyRow("Sides") {156                HStack(spacing: 1) {157                    sideButton("square.tophalf.filled", "Top border", \.borderTop, firstCell)158                    sideButton("square.bottomhalf.filled", "Bottom border", \.borderBottom, firstCell)159                    sideButton("square.lefthalf.filled", "Left border", \.borderLeft, firstCell)160                    sideButton("square.righthalf.filled", "Right border", \.borderRight, firstCell)161                }162                .padding(1)163                .background(RoundedRectangle(cornerRadius: ORIX.Radius.s + 1).fill(ORIX.Palette.text.opacity(0.045)))164            }165            HStack(spacing: ORIX.Space.s) {166                InspectorButton("All", symbol: "squareshape.split.2x2", identifier: "table-borders-all") {167                    let p = pen168                    cells(String(localized: "Cell Borders")) { $0.borderTop = p; $0.borderBottom = p; $0.borderLeft = p; $0.borderRight = p }169                }170                .help("Draw every side of the selected cells with this line")171                InspectorButton("Outer", symbol: "square", identifier: "table-borders-outer") { outline() }172                    .help("Draw the outline of the selected cells with this line")173                InspectorButton("Clear", symbol: "square.dashed", identifier: "table-borders-clear") {174                    cells(String(localized: "Cell Borders")) { $0.borderTop = nil; $0.borderBottom = nil; $0.borderLeft = nil; $0.borderRight = nil }175                }176                .help("Remove the cell borders: the selected cells show the table style’s rules again")177            }178            InspectorNote("Cell borders are drawn over the rules of the table style.")179        }180181        InspectorGroup("Formula", id: "table.formula") {182            if let formula = caretCell?.formula, !formula.isEmpty {183                Text(verbatim: formula).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(ORIX.Palette.text).textSelection(.enabled)184                    .padding(.horizontal, 7).padding(.vertical, 5).frame(maxWidth: .infinity, alignment: .leading)185                    .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(ORIX.Palette.surface))186                    .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(ORIX.Palette.hairline))187                    .accessibilityLabel(Text("Formula of the current cell: \(formula)"))188                    .accessibilityIdentifier("table-formula")189            } else {190                InspectorNote("The current cell has no formula.")191            }192            HStack(spacing: ORIX.Space.s) {193                InspectorButton(caretCell?.formula == nil ? "Add Formula…" : "Edit Formula…", symbol: "function", isEnabled: session.isEnabled(.cellFormula), identifier: "table-formula-edit") {194                    session.activeSheet = .formula195                }196                command("Recalculate", .recalculate, "arrow.clockwise")197            }198        }199200        VStack {201            InspectorButton("Delete Table", symbol: "trash", identifier: "table-delete") { session.run(.deleteTable); session.refocusCanvas() }202        }203        .padding(.horizontal, ORIX.Space.l).padding(.vertical, ORIX.Space.m)204    }205206    private func sideButton(_ symbol: String, _ help: LocalizedStringKey, _ path: WritableKeyPath<TableCell, BorderLine?>, _ cell: TableCell?) -> some View {207        let on = cell?[keyPath: path] != nil208        return BarButton(symbol: symbol, help: help, isOn: on) {209            let p = pen210            cells(String(localized: "Cell Borders")) { $0[keyPath: path] = on ? nil : p }211        }212    }213214    /// Draws the outline of the selected block of cells.215    private func outline() {216        let p = pen217        session.perform(String(localized: "Cell Borders")) { e in218            guard let sel = e.tableSelection else { return }219            e.mutateTable { t in220                for r in sel.rows where t.rows.indices.contains(r) {221                    let indexes = DocumentEditor.cells(in: t.rows[r], columns: sel.columns)222                    for (k, ci) in indexes.enumerated() {223                        if r == sel.rows.lowerBound { t.rows[r].cells[ci].borderTop = p }224                        if r == sel.rows.upperBound { t.rows[r].cells[ci].borderBottom = p }225                        if k == 0 { t.rows[r].cells[ci].borderLeft = p }226                        if k == indexes.count - 1 { t.rows[r].cells[ci].borderRight = p }227                    }228                }229            }230        }231        session.refocusCanvas()232    }233}234235/// Model colour to SwiftUI colour, callable from the canvas renderer (which is not on the main actor).236nonisolated private func paint(_ c: RGBA) -> Color { Color(.sRGB, red: c.r, green: c.g, blue: c.b, opacity: c.a) }237238/// A miniature of a table style: header shading, banding and rules as the engine draws them.239private struct TableStyleCard: View {240    let style: DocModel.TableStyle241    let isCurrent: Bool242    let action: () -> Void243    @State private var hover = false244245    var body: some View {246        let s = style247        let academic = style.name == DocModel.TableStyle.academic.name248        Button(action: action) {249            VStack(spacing: 3) {250                Canvas { ctx, size in251                    let rect = CGRect(origin: .zero, size: size).insetBy(dx: 5, dy: 5)252                    let rows = 4, cols = 3253                    let rh = rect.height / CGFloat(rows), cw = rect.width / CGFloat(cols)254                    func line(_ b: BorderLine?, _ from: CGPoint, _ to: CGPoint, minWidth: CGFloat = 0.75) {255                        guard let b else { return }256                        var p = Path(); p.move(to: from); p.addLine(to: to)257                        ctx.stroke(p, with: .color(paint(b.color)), style: StrokeStyle(lineWidth: max(minWidth, b.width), dash: b.style == .dashed ? [3, 2] : (b.style == .dotted ? [1, 1.5] : [])))258                    }259                    for r in 0..<rows {260                        let row = CGRect(x: rect.minX, y: rect.minY + CGFloat(r) * rh, width: rect.width, height: rh)261                        if r == 0, let h = s.headerShading { ctx.fill(Path(row), with: .color(paint(h))) }262                        else if r > 0, r % 2 == 0, let band = s.bandedRowShading { ctx.fill(Path(row), with: .color(paint(band))) }263                        // Text stand-ins.264                        for c in 0..<cols {265                            let ink = r == 0 ? (paint(s.headerTextColor ?? RGBA(hex: 0x16181D))) : paint(RGBA(hex: 0x8A8FA3))266                            let bar = CGRect(x: rect.minX + CGFloat(c) * cw + 2.5, y: row.midY - 0.75, width: cw - 6, height: 1.5)267                            ctx.fill(Path(roundedRect: bar, cornerRadius: 0.75), with: .color(ink.opacity(r == 0 ? 0.9 : 0.55)))268                        }269                    }270                    for r in 1..<rows { let y = rect.minY + CGFloat(r) * rh; line(s.innerHorizontal, CGPoint(x: rect.minX, y: y), CGPoint(x: rect.maxX, y: y), minWidth: 0.5) }271                    for c in 1..<cols { let x = rect.minX + CGFloat(c) * cw; line(s.innerVertical, CGPoint(x: x, y: rect.minY), CGPoint(x: x, y: rect.maxY), minWidth: 0.5) }272                    if let o = s.outerBorder { ctx.stroke(Path(rect), with: .color(paint(o.color)), lineWidth: max(0.75, o.width)) }273                    if academic {274                        let rule = BorderLine(width: 1.1, color: RGBA(hex: 0x16181D))275                        line(rule, CGPoint(x: rect.minX, y: rect.minY), CGPoint(x: rect.maxX, y: rect.minY))276                        line(BorderLine(width: 0.6, color: RGBA(hex: 0x16181D)), CGPoint(x: rect.minX, y: rect.minY + rh), CGPoint(x: rect.maxX, y: rect.minY + rh), minWidth: 0.5)277                        line(rule, CGPoint(x: rect.minX, y: rect.maxY), CGPoint(x: rect.maxX, y: rect.maxY))278                    }279                }280                .frame(height: 38)281                .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(Color.white))282                .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.s).strokeBorder(isCurrent ? ORIX.Palette.accent : (hover ? ORIX.Palette.textTertiary : ORIX.Palette.hairline), lineWidth: isCurrent ? 1.5 : 1))283                Text(style.name).font(.system(size: 9.5, weight: isCurrent ? .semibold : .regular)).foregroundStyle(isCurrent ? ORIX.Palette.accent : ORIX.Palette.textSecondary).lineLimit(1)284                    .minimumScaleFactor(0.8)285            }286            .frame(maxWidth: .infinity)287            .contentShape(Rectangle())288        }289        .buttonStyle(.plain)290        .onHover { hover = $0 }291        .help(Text("\(style.name) table style"))292        .accessibilityLabel(Text("\(style.name) table style"))293        .accessibilityAddTraits(isCurrent ? .isSelected : [])294        .accessibilityIdentifier("table-style-\(style.name)")295    }296}297
Files main
Menu

Theme