Repository Public
1import Foundation2import SheetCore3import SheetCharts4import Statistics5import SheetUI67/// A table of a result: shown in the panel and written to the sheet with the same formats.8public struct ReportTable: Sendable, Hashable {9 public var title: String?10 public var rows: [[Value]]11 /// Leading rows that are column headers.12 public var headerRows: Int13 /// The first column holds row labels.14 public var headerColumn: Bool15 public var columnFormats: [Int: CellFormat] = [:]16 /// Row formats take precedence over column formats (key = row index, header rows included).17 public var rowFormats: [Int: CellFormat] = [:]18 /// Cell formats take precedence over both (row, column).19 public var cellFormats: [CellRef: CellFormat] = [:]20 public var note: String?2122 public init(title: String? = nil, rows: [[Value]], headerRows: Int = 1, headerColumn: Bool = true,23 columnFormats: [Int: CellFormat] = [:], rowFormats: [Int: CellFormat] = [:], note: String? = nil) {24 self.title = title; self.rows = Report.rectangular(rows); self.headerRows = headerRows; self.headerColumn = headerColumn25 self.columnFormats = columnFormats; self.rowFormats = rowFormats; self.note = note26 }2728 /// The table of an engine result (`TableReport`), first row as header.29 public init(title: String? = nil, report: any TableReport, headerRows: Int = 1) {30 self.init(title: title, rows: report.table(), headerRows: headerRows)31 }3233 /// Two columns: label, value — one format per row.34 public static func keyValue(title: String? = nil, header: (String, String)? = nil, _ items: [(String, Value, CellFormat)], note: String? = nil) -> ReportTable {35 var rows = [[Value]]()36 if let header { rows.append([.text(header.0), .text(header.1)]) }37 var t = ReportTable(title: title, rows: rows + items.map { [.text($0.0), $0.1] }, headerRows: header == nil ? 0 : 1, note: note)38 for (i, item) in items.enumerated() { t.rowFormats[i + t.headerRows] = item.2 }39 return t40 }4142 public var columnCount: Int { rows.first?.count ?? 0 }4344 public func format(row: Int, col: Int) -> CellFormat {45 cellFormats[CellRef(row, col)] ?? rowFormats[row] ?? columnFormats[col] ?? .auto46 }4748 /// The format actually applied to a cell: explicit formats as given; for `.auto` a whole number is shown49 /// without decimals only when its neighbours (the automatic numbers of its column, or of its row) are whole50 /// numbers too, so a column of estimates does not mix "16" with "16.9000".51 public func resolvedFormat(row: Int, col: Int) -> CellFormat {52 let f = format(row: row, col: col)53 guard case .auto = f, row < rows.count, col < rows[row].count, case .number(let x) = rows[row][col], x == x.rounded() else { return f }54 // (number of automatic numbers, all of them whole) along a line of cells55 func line(_ cells: [(Int, Int)]) -> (count: Int, whole: Bool) {56 var n = 0, whole = true57 for (r, c) in cells where r >= headerRows && c < rows[r].count {58 guard case .number(let v) = rows[r][c], case .auto = format(row: r, col: c) else { continue }59 n += 160 if v != v.rounded() { whole = false }61 }62 return (n, whole)63 }64 let column = line(rows.indices.map { ($0, col) }), inRow = line(rows[row].indices.map { (row, $0) })65 if (column.count >= 2 && column.whole) || (inRow.count >= 2 && inRow.whole) || (column.count < 2 && inRow.count < 2) { return .auto }66 let a = abs(x)67 return a >= 1e9 ? .scientific : (a >= 1000 ? .fixed(2) : .fixed(4))68 }6970 /// Display text of every cell.71 public func displayRows(locale: Locale = .current) -> [[String]] {72 rows.enumerated().map { r, row in row.enumerated().map { c, v in Fmt.text(v, resolvedFormat(row: r, col: c), locale: locale) } }73 }74}7576/// A headline figure of a result.77public struct Metric: Sendable, Hashable, Identifiable {78 public var id: String { label }79 public var label: String80 public var value: Value81 public var format: CellFormat82 /// Optional qualifier shown after the value ("two-sided", "years"…).83 public var detail: String?84 public init(_ label: String, _ value: Double, _ format: CellFormat = .auto, detail: String? = nil) {85 self.label = label; self.value = .finite(value); self.format = format; self.detail = detail86 }87 public init(_ label: String, text: String, detail: String? = nil) {88 self.label = label; self.value = .text(text); self.format = .auto; self.detail = detail89 }90 public func display(locale: Locale = .current) -> String {91 let t = value.isBlank ? "—" : Fmt.text(value, format, locale: locale)92 return detail.map { t + " " + $0 } ?? t93 }94}9596public struct TextBlock: Sendable, Hashable {97 public enum Kind: Sendable, Hashable { case interpretation, note, warning, assumptions }98 public var kind: Kind99 public var title: String?100 public var lines: [String]101 public init(_ kind: Kind, title: String? = nil, _ lines: [String]) { self.kind = kind; self.title = title; self.lines = lines }102}103104/// A chart of a result. `spec` uses literal data so it can be drawn anywhere; `summary` is the VoiceOver text.105public struct ChartBlock: Sendable, Hashable {106 public var title: String107 public var spec: ChartSpec108 public var summary: String109 public var height: Double110 public init(title: String, spec: ChartSpec, summary: String, height: Double = 250) {111 self.title = title; self.spec = spec; self.summary = summary; self.height = height112 }113}114115public enum ResultBlock: Sendable, Hashable {116 case metrics([Metric])117 case table(ReportTable)118 case chart(ChartBlock)119 case text(TextBlock)120 /// Several charts shown side by side when the panel is wide enough.121 case charts([ChartBlock])122123 public static func interpretation(_ s: String) -> ResultBlock { .text(TextBlock(.interpretation, [s])) }124 public static func note(_ lines: [String], title: String? = nil) -> ResultBlock { .text(TextBlock(.note, title: title, lines)) }125 public static func warning(_ s: String) -> ResultBlock { .text(TextBlock(.warning, [s])) }126 public static func assumptions(_ lines: [String], title: String? = nil) -> ResultBlock { .text(TextBlock(.assumptions, title: title, lines)) }127}128129/// Something more a result can do with the workbook (write residuals, insert a live model, apply a solution…).130public struct ResultAction: Sendable, Identifiable {131 public var id: String132 public var title: String133 public var systemImage: String134 public var help: String135 /// Marks the default action of a result (drawn prominent).136 public var isPrimary: Bool137 /// Runs on the main actor against the live session; returns a status message. Must use ONE `session.perform`.138 public var perform: @MainActor @Sendable (WorkbookSession) throws -> String?139 public init(id: String, title: String, systemImage: String, help: String = "", isPrimary: Bool = false,140 perform: @escaping @MainActor @Sendable (WorkbookSession) throws -> String?) {141 self.id = id; self.title = title; self.systemImage = systemImage; self.help = help; self.isPrimary = isPrimary; self.perform = perform142 }143}144145/// Everything a tool produced.146public struct ToolResult: Sendable {147 public var title: String148 public var subtitle: String?149 public var blocks: [ResultBlock]150 public var actions: [ResultAction]151 /// Suggested name of the report sheet (made unique and valid by the writer).152 public var sheetName: String153 /// False for results that have nothing to write as a report (e.g. a tool whose only output is an action).154 public var canWriteReport: Bool155156 public init(title: String, subtitle: String? = nil, blocks: [ResultBlock], actions: [ResultAction] = [], sheetName: String? = nil,157 canWriteReport: Bool = true) {158 self.title = title; self.subtitle = subtitle; self.blocks = blocks; self.actions = actions159 self.sheetName = sheetName ?? title; self.canWriteReport = canWriteReport160 }161162 public var tables: [ReportTable] { blocks.compactMap { if case .table(let t) = $0 { t } else { nil } } }163 public var charts: [ChartBlock] {164 blocks.flatMap { b -> [ChartBlock] in165 switch b {166 case .chart(let c): [c]167 case .charts(let cs): cs168 default: []169 }170 }171 }172 public func table(titled title: String) -> ReportTable? { tables.first { $0.title == title } }173}174175/// A user-facing failure of a tool (already localized).176public struct ToolError: Error, Sendable, Hashable, CustomStringConvertible {177 public var message: String178 public init(_ message: String) { self.message = message }179 public var description: String { message }180181 /// Readable text for any error thrown by the engines.182 public static func describe(_ error: any Error) -> String {183 if let e = error as? ToolError { return e.message }184 if let e = error as? StatError { return e.description }185 if let e = error as? LocalizedError, let d = e.errorDescription { return d }186 return String(describing: error)187 }188}189