SPB Git

Repository Public

InsertTableSheet.swift 9.7 KB 172 lines swift

1// ORIX Docs2// File: App/Sources/Sheets/InsertTableSheet.swift3// Description: Inserts a table: size chosen on a grid or typed, optional header row and a gallery of table styles. The table takes4//              the width of the text column at the caret.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel1011struct InsertTableSheet: View {12    let session: DocumentSession13    @State private var rows = 314    @State private var columns = 315    @State private var headerRow = true16    @State private var style = DocModel.TableStyle.grid.name17    @State private var hover: (row: Int, column: Int)?1819    private static let gridRows = 8, gridColumns = 1020    private func close() { session.activeSheet = nil }2122    private func commit() {23        let width = session.columnWidthAtCaret24        let chosen = DocModel.TableStyle.all.first { $0.name == style } ?? .grid25        let r = rows, c = columns, header = headerRow26        session.perform(String(localized: "Insert Table")) { e in27            e.insertBlock(.table(DocModel.Table(rows: r, columns: c, width: width, headerRow: header, style: chosen)))28        }29        close()30    }3132    static func styleName(_ s: DocModel.TableStyle) -> String {33        switch s.name {34        case "Grid": return String(localized: "Grid")35        case "Banded": return String(localized: "Banded")36        case "Lined": return String(localized: "Lined")37        case "Academic": return String(localized: "Academic")38        case "Plain": return String(localized: "Plain")39        default: return s.name40        }41    }4243    var body: some View {44        let canInsert = session.isEnabled(.insertTable)45        SheetScaffold(title: "Insert Table", symbol: "tablecells", width: 560,46                      primaryTitle: "Insert", primaryEnabled: canInsert, onPrimary: commit, onCancel: close) {47            VStack(alignment: .leading, spacing: ORIX.Space.l) {48                if !canInsert { Notice(kind: .warning, text: String(localized: "A table cannot be inserted here. Place the caret in the body text, outside a table.")) }49                HStack(alignment: .top, spacing: ORIX.Space.xl) {50                    VStack(alignment: .leading, spacing: 6) {51                        FieldLabel("Size")52                        sizeGrid53                        Text(verbatim: "\((hover?.row ?? rows)) × \((hover?.column ?? columns))").font(.system(size: 11, weight: .medium).monospacedDigit())54                            .foregroundStyle(ORIX.Palette.textSecondary)55                            .accessibilityLabel(Text("\(hover?.row ?? rows) rows by \(hover?.column ?? columns) columns"))56                    }57                    VStack(alignment: .leading, spacing: ORIX.Space.m) {58                        InspectorRow(label: "Rows") {59                            NumberField(value: Double(rows), range: 1...200, decimals: 0, width: 70) { rows = Int($0) }.accessibilityIdentifier("table-rows")60                        }61                        InspectorRow(label: "Columns") {62                            NumberField(value: Double(columns), range: 1...26, decimals: 0, width: 70) { columns = Int($0) }.accessibilityIdentifier("table-columns")63                        }64                        Toggle("Header row", isOn: $headerRow).toggleStyle(.checkbox).font(ORIX.Font.label)65                            .help("The first row is styled as a header and repeats at the top of each page the table spans.")66                            .accessibilityIdentifier("table-header")67                        Text("Width: \(Int(session.columnWidthAtCaret.rounded())) pt (the text column)").font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary)68                    }69                    .frame(maxWidth: .infinity, alignment: .leading)70                }71                VStack(alignment: .leading, spacing: 6) {72                    FieldLabel("Style")73                    HStack(spacing: ORIX.Space.s) {74                        ForEach(DocModel.TableStyle.all, id: \.name) { s in75                            let selected = s.name == style76                            Button { style = s.name } label: {77                                VStack(spacing: 5) {78                                    TableStyleSwatch(style: s, header: headerRow)79                                        .frame(height: 54)80                                        .padding(6)81                                        .background(RoundedRectangle(cornerRadius: ORIX.Radius.m).fill(Color.white))82                                        .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.m).strokeBorder(selected ? ORIX.Palette.accent : ORIX.Palette.hairline, lineWidth: selected ? 2 : 1))83                                    HStack(spacing: 3) {84                                        if selected { Image(systemName: "checkmark").font(.system(size: 8, weight: .bold)).foregroundStyle(ORIX.Palette.accent) }85                                        Text(verbatim: InsertTableSheet.styleName(s)).font(.system(size: 10.5, weight: selected ? .semibold : .regular))86                                            .foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textSecondary)87                                    }88                                }89                                .contentShape(Rectangle())90                            }91                            .buttonStyle(.plain)92                            .accessibilityLabel(Text(verbatim: InsertTableSheet.styleName(s)))93                            .accessibilityAddTraits(selected ? .isSelected : [])94                            .accessibilityIdentifier("table-style-\(s.name)")95                        }96                    }97                }98            }99        }100    }101102    private var sizeGrid: some View {103        let cell: CGFloat = 17, gap: CGFloat = 3104        return VStack(spacing: gap) {105            ForEach(1...InsertTableSheet.gridRows, id: \.self) { r in106                HStack(spacing: gap) {107                    ForEach(1...InsertTableSheet.gridColumns, id: \.self) { c in108                        let on = r <= (hover?.row ?? rows) && c <= (hover?.column ?? columns)109                        RoundedRectangle(cornerRadius: 3)110                            .fill(on ? ORIX.Palette.accent.opacity(hover == nil ? 0.85 : 0.55) : ORIX.Palette.text.opacity(0.07))111                            .overlay(RoundedRectangle(cornerRadius: 3).strokeBorder(on ? ORIX.Palette.accent : ORIX.Palette.hairline, lineWidth: 0.5))112                            .frame(width: cell, height: cell)113                            .onHover { inside in if inside { hover = (r, c) } else if hover?.row == r && hover?.column == c { hover = nil } }114                            .onTapGesture { rows = r; columns = c; hover = nil }115                    }116                }117            }118        }119        .accessibilityElement()120        .accessibilityLabel(Text("Table size grid"))121        .accessibilityValue(Text("\(rows) rows by \(columns) columns"))122        .accessibilityAdjustableAction { direction in123            switch direction {124            case .increment: rows = min(200, rows + 1)125            case .decrement: rows = max(1, rows - 1)126            @unknown default: break127            }128        }129        .accessibilityIdentifier("table-grid")130    }131}132133/// A miniature of a table style, drawn from the style's own borders and shadings.134struct TableStyleSwatch: View {135    let style: DocModel.TableStyle136    let header: Bool137138    var body: some View {139        let style = style, header = header140        let ink = Color(hex: 0x5B6170)141        let academic = style.name == DocModel.TableStyle.academic.name142        return Canvas { ctx, size in143            let rows = 4, cols = 3144            let rh = size.height / CGFloat(rows), cw = size.width / CGFloat(cols)145            func color(_ c: RGBA) -> Color { Color(.sRGB, red: c.r, green: c.g, blue: c.b, opacity: c.a) }146            func hline(_ y: CGFloat, _ w: CGFloat, _ c: Color) { ctx.fill(Path(CGRect(x: 0, y: y - w / 2, width: size.width, height: w)), with: .color(c)) }147            func vline(_ x: CGFloat, _ w: CGFloat, _ c: Color) { ctx.fill(Path(CGRect(x: x - w / 2, y: 0, width: w, height: size.height)), with: .color(c)) }148            for r in 0..<rows {149                let rect = CGRect(x: 0, y: CGFloat(r) * rh, width: size.width, height: rh)150                if r == 0, header, let shade = style.headerShading { ctx.fill(Path(rect), with: .color(color(shade))) }151                else if let band = style.bandedRowShading, r % 2 == 0, r > 0 || !header { ctx.fill(Path(rect), with: .color(color(band))) }152                // Text stand-ins.153                for c in 0..<cols {154                    let isHeader = r == 0 && header155                    let textColor: Color = isHeader ? (style.headerTextColor.map(color) ?? ink) : ink.opacity(0.55)156                    let w = cw * (isHeader ? 0.55 : (c == 0 ? 0.6 : 0.4))157                    ctx.fill(Path(roundedRect: CGRect(x: CGFloat(c) * cw + 5, y: rect.midY - 1.5, width: w, height: isHeader ? 3.5 : 3), cornerRadius: 1.5), with: .color(textColor))158                }159            }160            if let b = style.innerHorizontal { for r in 1..<rows { hline(CGFloat(r) * rh, max(0.75, b.width), color(b.color)) } }161            if let b = style.innerVertical { for c in 1..<cols { vline(CGFloat(c) * cw, max(0.75, b.width), color(b.color)) } }162            if let b = style.outerBorder { ctx.stroke(Path(CGRect(origin: .zero, size: size).insetBy(dx: 0.5, dy: 0.5)), with: .color(color(b.color)), lineWidth: max(0.75, b.width)) }163            if academic {164                // Three-rule table: heavy rules above and below, a light rule under the header.165                hline(0.75, 1.5, ink); hline(size.height - 0.75, 1.5, ink)166                if header { hline(rh, 0.75, ink) }167            }168        }169        .accessibilityHidden(true)170    }171}172
Files main
Menu

Theme