SPB Git

Repository Public

FormulaSheet.swift 7.4 KB 141 lines swift

1// ORIX Docs2// File: App/Sources/Sheets/FormulaSheet.swift3// Description: Edits the formula of the table cell under the caret, with the supported syntax at hand and the result evaluated live4//              on the current table.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel1011struct FormulaSheet: View {12    let session: DocumentSession13    private let table: DocModel.Table?14    private let row: Int15    private let cell: Int16    private let reference: String17    private let hadFormula: Bool18    @State private var formula: String19    @FocusState private var focused: Bool2021    init(session: DocumentSession) {22        self.session = session23        let path = session.selection.start.path24        if let c = path.cell, let t = session.doc.blocks(in: session.selection.story)[path.block].table,25           t.rows.indices.contains(c.row), t.rows[c.row].cells.indices.contains(c.cell) {26            table = t; row = c.row; cell = c.cell27            let grid = DocumentEditor.gridStart(t.rows[c.row], cell: c.cell)28            reference = FormulaSheet.columnLetters(grid) + String(c.row + 1)29            let current = t.rows[c.row].cells[c.cell].formula30            hadFormula = current != nil31            _formula = State(initialValue: current ?? "=")32        } else {33            table = nil; row = 0; cell = 0; reference = ""; hadFormula = false34            _formula = State(initialValue: "")35        }36    }3738    static func columnLetters(_ index: Int) -> String {39        var n = index, s = ""40        repeat { s = String(UnicodeScalar(UInt8(65 + n % 26))) + s; n = n / 26 - 1 } while n >= 041        return s42    }4344    private var trimmed: String { formula.trimmingCharacters(in: .whitespacesAndNewlines) }45    private var isBlank: Bool { trimmed.isEmpty || trimmed == "=" }4647    /// The value the formula gives on the current table; nil when it cannot be evaluated.48    private var result: String? {49        guard let table, !isBlank else { return nil }50        return TableFormula.evaluate(trimmed, in: table, row: row, cell: cell)51    }5253    private func close() { session.activeSheet = nil }5455    private func apply() {56        guard result != nil else { return }57        let f = trimmed.hasPrefix("=") ? trimmed : "=" + trimmed58        session.perform(String(localized: "Cell Formula")) { $0.setCellFormula(f) }59        close()60    }6162    private func clear() {63        session.perform(String(localized: "Clear Formula")) { $0.setCellFormula(nil) }64        close()65    }6667    private static let examples = ["=SUM(ABOVE)", "=SUM(LEFT)", "=AVERAGE(ABOVE)", "=MIN(ABOVE)", "=MAX(ABOVE)", "=COUNT(ABOVE)", "=PRODUCT(LEFT)"]6869    var body: some View {70        let value = result71        SheetScaffold(title: "Cell Formula", symbol: "sum",72                      subtitle: table == nil ? nil : "Cell \(reference). The cell shows the result, recalculated when the table changes.", width: 540,73                      primaryTitle: "Apply", primaryEnabled: value != nil, onPrimary: apply, onCancel: close,74                      accessory: {75                          if hadFormula {76                              Button("Clear Formula", role: .destructive, action: clear)77                                  .buttonStyle(ORIXButtonStyle(prominent: false)).accessibilityIdentifier("formula-clear")78                                  .help("Removes the formula and keeps the last value as plain text.")79                          }80                      }) {81            if table == nil {82                EmptyState(symbol: "tablecells", title: "No table cell selected", message: "Place the caret in a table cell, then choose Table › Cell Formula.")83                    .frame(height: 150)84            } else {85                VStack(alignment: .leading, spacing: ORIX.Space.m) {86                    LabeledField(label: "Formula") {87                        TextField("", text: $formula, prompt: Text(verbatim: "=SUM(ABOVE)")).textFieldStyle(.roundedBorder)88                            .font(.system(size: 13, design: .monospaced)).focused($focused).autocorrectionDisabled()89                            .accessibilityLabel(Text("Formula")).accessibilityIdentifier("formula-field")90                    }91                    HStack(spacing: 8) {92                        FieldLabel("Result")93                        if isBlank {94                            Text("Type a formula or pick an example.").font(ORIX.Font.label).foregroundStyle(ORIX.Palette.textTertiary)95                        } else if let value {96                            Label { Text(verbatim: value).font(.system(size: 14, weight: .semibold).monospacedDigit()) } icon: { Image(systemName: "equal.circle.fill").foregroundStyle(ORIX.Palette.positive) }97                                .foregroundStyle(ORIX.Palette.text).accessibilityIdentifier("formula-result")98                        } else {99                            Label("This formula cannot be evaluated. Check the function name, the references and the parentheses.", systemImage: "exclamationmark.triangle.fill")100                                .font(ORIX.Font.label).foregroundStyle(ORIX.Palette.critical).accessibilityIdentifier("formula-error")101                        }102                        Spacer(minLength: 0)103                    }104                    .frame(minHeight: 30).padding(.horizontal, 10).background(ORIX.Palette.surfaceRaised).well()105106                    VStack(alignment: .leading, spacing: 5) {107                        FieldLabel("Examples")108                        FlowLayout(spacing: 5, lineSpacing: 5) {109                            ForEach(FormulaSheet.examples, id: \.self) { ex in110                                Button { formula = ex; focused = true } label: {111                                    Text(verbatim: ex).font(.system(size: 10.5, design: .monospaced)).padding(.horizontal, 7).padding(.vertical, 3)112                                        .foregroundStyle(ORIX.Palette.accent).background(Capsule().fill(ORIX.Palette.accent.opacity(0.11)))113                                }114                                .buttonStyle(.plain)115                            }116                        }117                    }118                    VStack(alignment: .leading, spacing: 4) {119                        FieldLabel("Syntax")120                        syntaxRow("Functions", "SUM  AVERAGE  MIN  MAX  COUNT  PRODUCT")121                        syntaxRow("Directions", "ABOVE  BELOW  LEFT  RIGHT")122                        syntaxRow("References", "B2   A1:A4   (columns A, B, C…; rows from 1)")123                        syntaxRow("Arithmetic", "+  -  *  /  ( )     =B2*C2    =SUM(A1:A4)/2")124                        Text("Cells that do not hold a number are skipped. Numbers may be written 1,234.50, 1 234,50, (120), $45 or 12 %.")125                            .font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).fixedSize(horizontal: false, vertical: true)126                    }127                    .padding(10).frame(maxWidth: .infinity, alignment: .leading).well()128                }129            }130        }131        .onAppear { focused = true }132    }133134    private func syntaxRow(_ name: LocalizedStringKey, _ value: String) -> some View {135        HStack(alignment: .firstTextBaseline, spacing: 8) {136            Text(name).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 74, alignment: .leading)137            Text(verbatim: value).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.text)138        }139    }140}141
Files main
Menu

Theme