SPB Git

Repository Public

ReportWriter.swift 14.4 KB 305 lines swift

1import Foundation2import SheetCore3import SheetCharts4import SheetUI56/// Writes results into the workbook as formatted reports. Every entry point is ONE undoable step.7public enum ReportWriter {8    public enum Destination: Sendable, Hashable {9        /// A new sheet inserted after the active one (the name is made valid and unique).10        case newSheet11        /// Top-left cell of the report on an existing sheet.12        case cell(CellAddress)13    }1415    public struct Outcome: Sendable, Hashable {16        public var sheet: Int17        public var range: RangeRef18        public var chartCount: Int19    }2021    static let accent = RGBA(hex: 0x0891B2)22    static let muted = RGBA(hex: 0x7A8098)2324    /// A sheet name that is valid (≤ 31 characters, no forbidden characters) and not used yet.25    public static func uniqueSheetName(_ base: String, in workbook: Workbook) -> String {26        var clean = String(base.map { ":\\/?*[]'".contains($0) ? " " : $0 }).trimmingCharacters(in: .whitespaces)27        if clean.isEmpty { clean = "Report" }28        clean = String(clean.prefix(28))29        if workbook.sheetIndex(named: clean) == nil { return clean }30        var i = 231        while workbook.sheetIndex(named: "\(clean) \(i)") != nil { i += 1 }32        return "\(clean) \(i)"33    }3435    // MARK: Session entry points3637    /// Writes the whole result (tables, texts, optionally charts) as one undoable step and selects it.38    @MainActor @discardableResult39    public static func write(_ result: ToolResult, to destination: Destination, includeCharts: Bool = true, session: WorkbookSession) -> Outcome {40        let after = session.sheetIndex41        let outcome = session.perform(L("Insert Report")) { engine in42            write(result, to: destination, includeCharts: includeCharts, engine: engine, insertSheetAt: after + 1)43        }44        session.select(RangeRef(outcome.range.topLeft), sheet: outcome.sheet)45        session.scrollTarget = outcome.range.topLeft46        session.statusMessage = L("Report written to %@", session.workbook.sheets[outcome.sheet].name + "!" + outcome.range.a1)47        return outcome48    }4950    /// Inserts one chart: its data block is written at `origin` (or on a new sheet) and the chart object is bound to it.51    @MainActor @discardableResult52    public static func insertChart(_ chart: ChartBlock, to destination: Destination, session: WorkbookSession) -> Outcome {53        let wrapper = ToolResult(title: chart.title, blocks: [.chart(chart)], sheetName: chart.title)54        return write(wrapper, to: destination, includeCharts: true, session: session)55    }5657    // MARK: Engine level (call inside a transaction; used directly by tests)5859    /// Lays the result out and writes it. Must run inside `engine.transaction` / `session.perform`.60    @discardableResult61    public static func write(_ result: ToolResult, to destination: Destination, includeCharts: Bool, engine: CalcEngine, insertSheetAt: Int? = nil) -> Outcome {62        let wb = engine.workbook63        var si: Int64        var origin: CellRef65        var isNew = false66        switch destination {67        case .newSheet:68            si = engine.addSheet(named: uniqueSheetName(result.sheetName, in: wb), at: insertSheetAt.map { min($0, wb.sheets.count) })69            origin = CellRef(0, 0)70            isNew = true71        case .cell(let a):72            si = min(max(a.sheet, 0), wb.sheets.count - 1)73            origin = a.cell74        }75        var w = Cursor(engine: engine, sheet: si, origin: origin)76        w.title(result.title)77        if let s = result.subtitle, !s.isEmpty { w.line(s, italic: false, color: muted) }78        w.skip()79        var charts = [ChartBlock]()80        for block in result.blocks {81            switch block {82            case .metrics(let metrics):83                for m in metrics { w.keyValue(m.label, m.value, m.format, detail: m.detail) }84                w.skip()85            case .table(let t): w.table(t); w.skip()86            case .text(let t):87                if let title = t.title { w.heading(title) }88                for l in t.lines { w.line(l, italic: t.kind == .note || t.kind == .assumptions, color: t.kind == .warning ? RGBA(hex: 0xB86A00) : nil) }89                w.skip()90            case .chart(let c): charts.append(c)91            case .charts(let cs): charts.append(contentsOf: cs)92            }93        }94        var chartCount = 095        if includeCharts, !charts.isEmpty {96            // chart objects go to the right of the report; their data blocks below it97            let sheet = wb.sheets[si]98            let reportWidthCols = max(w.maxCol - origin.col + 1, 2)99            var objectY = sheet.rowLayoutOffset(origin.row)100            let objectX = sheet.colLayoutOffset(origin.col + reportWidthCols + 1, isNew: isNew)101            var objects = [SheetObject]()102            for c in charts {103                w.heading(L("Chart data — %@", c.title))104                let bound = ChartBinder.bind(c.spec, engine: engine, sheet: si, origin: CellRef(w.row, origin.col))105                w.row = bound.range.r1 + 2106                w.maxCol = max(w.maxCol, bound.range.c1)107                var spec = bound.spec108                if spec.title.isEmpty { spec.title = c.title }109                if let object = try? spec.sheetObject(name: c.title, x: objectX, y: objectY, width: 480, height: max(c.height, 260) + 40) {110                    objects.append(object)111                    objectY += object.height + 16112                    chartCount += 1113                }114            }115            if !objects.isEmpty { engine.editMeta(sheet: si) { $0.objects.append(contentsOf: objects) } }116        }117        if isNew {118            engine.editMeta(sheet: si) { m in119                m.colWidths[origin.col] = 230120                for c in (origin.col + 1)...max(origin.col + 1, min(w.maxCol, origin.col + 60)) { m.colWidths[c] = 104 }121            }122        }123        return Outcome(sheet: si, range: RangeRef(r0: origin.row, c0: origin.col, r1: max(w.row - 1, origin.row), c1: max(w.maxCol, origin.col)), chartCount: chartCount)124    }125126    /// Writes new columns to the right of a data frame (first free columns), aligned with its data rows.127    /// `columns[i]` has one value per data row (blank where not computed). Returns the written range.128    @discardableResult129    public static func appendColumns(engine: CalcEngine, frame: DataFrame, names: [String], columns: [[Value]]) -> RangeRef? {130        guard !columns.isEmpty, frame.sheet < engine.workbook.sheets.count else { return nil }131        let sheet = engine.workbook.sheets[frame.sheet]132        // first block of `columns.count` empty columns to the right of the range133        var c0 = frame.range.c1 + 1134        search: while c0 + columns.count - 1 < Limits.maxCols {135            var free = true136            sheet.cells.forEach(in: RangeRef(r0: frame.range.r0, c0: c0, r1: frame.range.r1, c1: c0 + columns.count - 1)) { _, _, cell in137                if cell.hasContent { free = false }138            }139            if free { break search }140            c0 += 1141        }142        for (k, values) in columns.enumerated() {143            let c = c0 + k144            if frame.hasHeader {145                engine.set(sheet: frame.sheet, row: frame.range.r0, col: c, .value(.text(k < names.count ? names[k] : "")))146                engine.setStyle(sheet: frame.sheet, range: RangeRef(CellRef(frame.range.r0, c))) { $0.bold = true }147            }148            for (i, v) in values.enumerated() where !v.isBlank {149                engine.set(sheet: frame.sheet, row: frame.firstDataRow + i, col: c, .value(v))150            }151        }152        return RangeRef(r0: frame.range.r0, c0: c0, r1: frame.range.r1, c1: c0 + columns.count - 1)153    }154155    /// Session wrapper of `appendColumns` (one undoable step).156    @MainActor @discardableResult157    public static func appendColumns(session: WorkbookSession, label: String, frame: DataFrame, names: [String], columns: [[Value]]) -> RangeRef? {158        let rg = session.perform(label) { appendColumns(engine: $0, frame: frame, names: names, columns: columns) }159        if let rg { session.select(rg, sheet: frame.sheet); session.scrollTarget = rg.topLeft }160        return rg161    }162}163164private extension Sheet {165    func rowLayoutOffset(_ row: Int) -> Double {166        var y = 0.0167        if row > 0 { for r in 0..<min(row, 5000) { y += rowHeight(r) } }168        return y169    }170    /// x of a column; on a sheet being created the report widths (230 + 104·n) are not set yet, so they are assumed.171    func colLayoutOffset(_ col: Int, isNew: Bool) -> Double {172        if isNew { return col <= 0 ? 0 : 230 + Double(col - 1) * 104 }173        var x = 0.0174        if col > 0 { for c in 0..<min(col, 2000) { x += colWidth(c) } }175        return x176    }177}178179/// Sequential writer used by the report layout.180struct Cursor {181    let engine: CalcEngine182    let sheet: Int183    let origin: CellRef184    var row: Int185    var maxCol: Int186187    init(engine: CalcEngine, sheet: Int, origin: CellRef) {188        self.engine = engine; self.sheet = sheet; self.origin = origin; row = origin.row; maxCol = origin.col189    }190191    mutating func skip() { row += 1 }192193    private func put(_ r: Int, _ c: Int, _ v: Value) {194        guard !v.isBlank else { return }195        engine.set(sheet: sheet, row: r, col: c, .value(v))196    }197    private func style(_ r: Int, _ c0: Int, _ c1: Int, _ f: (inout CellStyle) -> Void) {198        engine.setStyle(sheet: sheet, range: RangeRef(r0: r, c0: c0, r1: r, c1: c1), f)199    }200201    mutating func title(_ s: String) {202        put(row, origin.col, .text(s))203        style(row, origin.col, origin.col) { $0.bold = true; $0.fontSize = 15 }204        row += 1205    }206207    mutating func heading(_ s: String) {208        put(row, origin.col, .text(s))209        style(row, origin.col, origin.col) { $0.bold = true; $0.textColor = ReportWriter.accent }210        row += 1211    }212213    mutating func line(_ s: String, italic: Bool, color: RGBA?) {214        put(row, origin.col, .text(s))215        if italic || color != nil { style(row, origin.col, origin.col) { $0.italic = italic; if let color { $0.textColor = color } } }216        row += 1217    }218219    mutating func keyValue(_ label: String, _ value: Value, _ format: CellFormat, detail: String?) {220        put(row, origin.col, .text(label))221        put(row, origin.col + 1, value)222        if case .number(let x) = value { style(row, origin.col + 1, origin.col + 1) { $0.numberFormat = format.code(for: x) } }223        else { style(row, origin.col + 1, origin.col + 1) { $0.hAlign = .right } }224        if let detail { put(row, origin.col + 2, .text(detail)); maxCol = max(maxCol, origin.col + 2) }225        maxCol = max(maxCol, origin.col + 1)226        row += 1227    }228229    mutating func table(_ t: ReportTable) {230        if let title = t.title { heading(title) }231        let width = t.columnCount232        guard width > 0 else { return }233        for (r, cells) in t.rows.enumerated() {234            let isHeader = r < t.headerRows235            for (c, v) in cells.enumerated() {236                put(row, origin.col + c, v)237                if case .number(let x) = v, !isHeader {238                    let code = t.resolvedFormat(row: r, col: c).code(for: x)239                    style(row, origin.col + c, origin.col + c) { $0.numberFormat = code }240                }241            }242            if isHeader {243                let last = r == t.headerRows - 1244                style(row, origin.col, origin.col + width - 1) { s in245                    s.bold = true246                    if last { s.borders.bottom = BorderEdge(style: .thin, color: ReportWriter.accent) }247                }248                if width > 1 { style(row, origin.col + 1, origin.col + width - 1) { $0.hAlign = .right } }249            }250            row += 1251        }252        if t.headerRows == 0, !t.rows.isEmpty { /* key/value block: no rule */ }253        if let note = t.note { line(note, italic: true, color: ReportWriter.muted) }254        maxCol = max(maxCol, origin.col + width - 1)255    }256}257258/// Turns the literal data of a chart spec into sheet cells and rebinds the spec to them.259public enum ChartBinder {260    /// Writes one column per literal reference (header + values) starting at `origin` and returns the spec261    /// with every literal replaced by a range reference, plus the written block. Call inside a transaction.262    public static func bind(_ spec: ChartSpec, engine: CalcEngine, sheet si: Int, origin: CellRef) -> (spec: ChartSpec, range: RangeRef) {263        var out = spec264        let sheetName = engine.workbook.sheets[si].name265        var col = origin.col266        var maxRows = 0267        func write(_ ref: DataRef?, _ header: String) -> DataRef? {268            guard let ref else { return nil }269            let values: [Value]270            switch ref {271            case .range: return ref272            case .literal(let v): values = v.map { $0.isFinite ? .number($0) : .blank }273            case .labels(let l): values = l.map { .text($0) }274            }275            guard !values.isEmpty else { return ref }276            engine.set(sheet: si, row: origin.row, col: col, .value(.text(header)))277            engine.setStyle(sheet: si, range: RangeRef(CellRef(origin.row, col))) { $0.bold = true; $0.borders.bottom = BorderEdge(style: .thin, color: ReportWriter.accent) }278            for (i, v) in values.enumerated() where !v.isBlank { engine.set(sheet: si, row: origin.row + 1 + i, col: col, .value(v)) }279            let rg = RangeRef(r0: origin.row + 1, c0: col, r1: origin.row + values.count, c1: col)280            col += 1281            maxRows = max(maxRows, values.count)282            return .range(sheet: sheetName, range: rg)283        }284        out.categories = write(spec.categories, L("Category"))285        out.rowLabels = write(spec.rowLabels, L("Row"))286        for (i, s) in spec.series.enumerated() {287            let name = s.name.isEmpty ? L("Series %d", i + 1) : s.name288            var t = s289            t.categories = write(s.categories, name + " – " + L("category"))290            t.x = write(s.x, name + " – x")291            t.values = write(s.values, name)292            t.lower = write(s.lower, name + " – " + L("lower"))293            t.upper = write(s.upper, name + " – " + L("upper"))294            t.size = write(s.size, name + " – " + L("size"))295            t.open = write(s.open, name + " – open")296            t.high = write(s.high, name + " – high")297            t.low = write(s.low, name + " – low")298            t.close = write(s.close, name + " – close")299            out.series[i] = t300        }301        let range = RangeRef(r0: origin.row, c0: origin.col, r1: origin.row + maxRows, c1: max(col - 1, origin.col))302        return (out, range)303    }304}305
Files main
Menu

Theme