SPB Git

Repository Public License

Components+FamilyCLogic.swift 20.9 KB 456 lines swift

1import CoreGraphics2import Foundation3import PrismCore4import PrismDataRuntime5import PrismLogicRuntime67/// Window-free computations of catalog family C. Everything here is pure, so it is tested without a renderer.8enum FamilyCMath {9    typealias Row = [String: JSONValue]1011    // MARK: Aggregates1213    static let aggregateFunctions = ["sum", "count", "avg", "min", "max"]1415    /// One aggregate over a list of numbers. `count` of nothing is 0; every other function of nothing is nil.16    static func aggregate(_ values: [Double], _ fn: String) -> Double? {17        if fn == "count" { return Double(values.count) }18        guard !values.isEmpty else { return nil }19        switch fn {20        case "avg": return values.reduce(0, +) / Double(values.count)21        case "min": return values.min()22        case "max": return values.max()23        default: return values.reduce(0, +)24        }25    }2627    /// An aggregate of a column over rows; `count` without a column counts the rows.28    static func aggregate(rows: [Row], column: String?, fn: String) -> Double? {29        guard let column, !column.isEmpty else { return fn == "count" ? Double(rows.count) : nil }30        return aggregate(rows.compactMap { $0[column]?.numericValue }, fn)31    }3233    struct ColumnStats: Equatable {34        var count = 035        var sum = 0.036        var min: Double?37        var max: Double?38        var average: Double? { count == 0 ? nil : sum / Double(count) }39    }4041    static func stats(_ values: [Double]) -> ColumnStats {42        ColumnStats(count: values.count, sum: values.reduce(0, +), min: values.min(), max: values.max())43    }4445    // MARK: Grouping4647    struct RowGroup: Equatable {48        var key: String49        var rows: [Row]50    }5152    /// Groups rows by the text of a column, keeping the order in which each key first appears.53    static func group(_ rows: [Row], by column: String) -> [RowGroup] {54        var order: [String] = []55        var buckets: [String: [Row]] = [:]56        for row in rows {57            let key = row[column]?.displayString ?? ""58            if buckets[key] == nil { order.append(key) }59            buckets[key, default: []].append(row)60        }61        return order.map { RowGroup(key: $0, rows: buckets[$0] ?? []) }62    }6364    struct Ranked: Equatable {65        var label: String66        var value: Double67    }6869    /// Top-N groups of an aggregate, largest first; ties keep the order of first appearance.70    static func rank(_ rows: [Row], label: String, value: String?, fn: String, limit: Int) -> [Ranked] {71        let ranked = group(rows, by: label).enumerated().compactMap { index, g -> (Int, Ranked)? in72            aggregate(rows: g.rows, column: value, fn: fn).map { (index, Ranked(label: g.key.isEmpty ? "(none)" : g.key, value: $0)) }73        }74        return ranked.sorted { $0.1.value != $1.1.value ? $0.1.value > $1.1.value : $0.0 < $1.0 }.prefix(max(1, limit)).map(\.1)75    }7677    struct RankedRow: Equatable {78        var row: Row79        var value: Double80    }8182    /// Rows ordered by a numeric column (rows without a number are left out); ties keep their original order.83    static func leaderboard(_ rows: [Row], value: String, highestFirst: Bool = true, limit: Int) -> [RankedRow] {84        let numbered = rows.enumerated().compactMap { index, row -> (Int, RankedRow)? in85            row[value]?.numericValue.map { (index, RankedRow(row: row, value: $0)) }86        }87        let sorted = numbered.sorted { a, b in88            if a.1.value != b.1.value { return highestFirst ? a.1.value > b.1.value : a.1.value < b.1.value }89            return a.0 < b.090        }91        return sorted.prefix(max(1, limit)).map(\.1)92    }9394    struct DuplicateGroup: Equatable {95        var value: String96        var rows: [Row]97    }9899    /// Groups of two or more rows sharing the same non-empty value in a column, largest group first.100    static func duplicates(_ rows: [Row], column: String, caseSensitive: Bool = false) -> [DuplicateGroup] {101        var order: [String] = []102        var buckets: [String: DuplicateGroup] = [:]103        for row in rows {104            let shown = (row[column]?.displayString ?? "").trimmingCharacters(in: .whitespaces)105            guard !shown.isEmpty else { continue }106            let key = caseSensitive ? shown : shown.lowercased()107            if buckets[key] == nil { order.append(key); buckets[key] = DuplicateGroup(value: shown, rows: []) }108            buckets[key]?.rows.append(row)109        }110        let groups = order.enumerated().compactMap { index, key in buckets[key].flatMap { $0.rows.count > 1 ? (index, $0) : nil } }111        return groups.sorted { $0.1.rows.count != $1.1.rows.count ? $0.1.rows.count > $1.1.rows.count : $0.0 < $1.0 }.map(\.1)112    }113114    // MARK: Pivot115116    struct Pivot: Equatable {117        var rowKeys: [String] = []118        var columnKeys: [String] = []119        var cells: [String: [String: Double]] = [:]120        var rowTotals: [String: Double] = [:]121        var columnTotals: [String: Double] = [:]122        var grandTotal: Double?123124        func cell(_ row: String, _ column: String) -> Double? { cells[row]?[column] }125    }126127    /// Rows × columns × aggregate. Keys are sorted; totals apply the same aggregate to the underlying rows (so an average total is a true average).128    static func pivot(_ rows: [Row], row: String, column: String, value: String?, fn: String) -> Pivot {129        var out = Pivot()130        var cellRows: [String: [String: [Row]]] = [:]131        var byRow: [String: [Row]] = [:], byColumn: [String: [Row]] = [:]132        for r in rows {133            let rk = r[row]?.displayString ?? "", ck = r[column]?.displayString ?? ""134            cellRows[rk, default: [:]][ck, default: []].append(r)135            byRow[rk, default: []].append(r)136            byColumn[ck, default: []].append(r)137        }138        out.rowKeys = byRow.keys.sorted()139        out.columnKeys = byColumn.keys.sorted()140        for (rk, columns) in cellRows {141            for (ck, list) in columns { if let v = aggregate(rows: list, column: value, fn: fn) { out.cells[rk, default: [:]][ck] = v } }142        }143        for (rk, list) in byRow { out.rowTotals[rk] = aggregate(rows: list, column: value, fn: fn) }144        for (ck, list) in byColumn { out.columnTotals[ck] = aggregate(rows: list, column: value, fn: fn) }145        out.grandTotal = rows.isEmpty ? nil : aggregate(rows: rows, column: value, fn: fn)146        return out147    }148149    // MARK: Histogram150151    struct Bin: Equatable {152        var lower: Double153        var upper: Double154        var count: Int155    }156157    /// Equal-width bins over the range of the values; the last bin includes the maximum.158    static func histogram(_ values: [Double], bins: Int) -> [Bin] {159        let finite = values.filter(\.isFinite)160        guard let lo = finite.min(), let hi = finite.max() else { return [] }161        let n = min(max(bins, 1), 100)162        if lo == hi { return [Bin(lower: lo - 0.5, upper: hi + 0.5, count: finite.count)] }163        let width = (hi - lo) / Double(n)164        var out = (0..<n).map { Bin(lower: lo + Double($0) * width, upper: $0 == n - 1 ? hi : lo + Double($0 + 1) * width, count: 0) }165        for v in finite { out[min(n - 1, max(0, Int((v - lo) / width)))].count += 1 }166        return out167    }168169    // MARK: Waterfall170171    struct WaterfallStep: Equatable {172        var start: Double173        var end: Double174        var delta: Double { end - start }175    }176177    /// Running total of signed values: each step starts where the previous one ended.178    static func waterfall(_ deltas: [Double]) -> [WaterfallStep] {179        var running = 0.0180        return deltas.map { d in181            defer { running += d }182            return WaterfallStep(start: running, end: running + d)183        }184    }185186    // MARK: Treemap187188    /// Squarified treemap (Bruls, Huizing, van Wijk). Returns one rectangle per value, in the order given; non-positive values get an empty rectangle.189    static func treemap(_ values: [Double], in bounds: CGRect) -> [CGRect] {190        var out = Array(repeating: CGRect.zero, count: values.count)191        let items = values.enumerated().filter { $0.element > 0 && $0.element.isFinite }.sorted { $0.element > $1.element }192        let total = items.reduce(0) { $0 + $1.element }193        guard total > 0, bounds.width > 0, bounds.height > 0 else { return out }194        let scale = Double(bounds.width * bounds.height) / total195        var free = bounds196        var row: [(index: Int, area: Double)] = []197198        func worst(_ row: [(index: Int, area: Double)], side: Double) -> Double {199            let sum = row.reduce(0) { $0 + $1.area }200            guard let largest = row.map(\.area).max(), let smallest = row.map(\.area).min(), sum > 0, side > 0 else { return .infinity }201            return max(side * side * largest / (sum * sum), sum * sum / (side * side * smallest))202        }203        func place(_ row: [(index: Int, area: Double)]) {204            let sum = row.reduce(0) { $0 + $1.area }205            guard sum > 0 else { return }206            if free.width >= free.height {207                let width = CGFloat(sum) / free.height208                var y = free.minY209                for item in row {210                    let h = CGFloat(item.area) / width211                    out[item.index] = CGRect(x: free.minX, y: y, width: width, height: h)212                    y += h213                }214                free = CGRect(x: free.minX + width, y: free.minY, width: max(0, free.width - width), height: free.height)215            } else {216                let height = CGFloat(sum) / free.width217                var x = free.minX218                for item in row {219                    let w = CGFloat(item.area) / height220                    out[item.index] = CGRect(x: x, y: free.minY, width: w, height: height)221                    x += w222                }223                free = CGRect(x: free.minX, y: free.minY + height, width: free.width, height: max(0, free.height - height))224            }225        }226        for item in items {227            let next = (index: item.offset, area: item.element * scale)228            let side = Double(min(free.width, free.height))229            if row.isEmpty || worst(row + [next], side: side) <= worst(row, side: side) {230                row.append(next)231            } else {232                place(row)233                row = [next]234            }235        }236        place(row)237        return out238    }239240    // MARK: Radar241242    /// Vertices of a radar polygon: the first axis points up, the others follow clockwise. `fractions` are 0…1 of the radius.243    static func radarPoints(_ fractions: [Double], center: CGPoint, radius: CGFloat) -> [CGPoint] {244        let n = fractions.count245        return fractions.enumerated().map { i, f in246            let angle = -Double.pi / 2 + 2 * Double.pi * Double(i) / Double(max(n, 1))247            let r = radius * CGFloat(min(max(f, 0), 1))248            return CGPoint(x: center.x + r * CGFloat(cos(angle)), y: center.y + r * CGFloat(sin(angle)))249        }250    }251252    /// Position of a value between two bounds, clamped to 0…1 (0 when the bounds are equal).253    static func fraction(_ value: Double, min lower: Double, max upper: Double) -> Double {254        guard upper > lower, value.isFinite else { return 0 }255        return Swift.min(Swift.max((value - lower) / (upper - lower), 0), 1)256    }257258    // MARK: Commerce259260    struct Totals: Equatable {261        var itemCount: Double262        var subtotal: Double263        var tax: Double264        var total: Double265    }266267    static func roundMoney(_ value: Double) -> Double { (value * 100).rounded() / 100 }268269    /// Sum of price × quantity, with tax on the subtotal. `taxRate` is a fraction (0.15 = 15 %). Amounts are rounded to cents.270    static func totals(lines: [(price: Double, quantity: Double)], taxRate: Double) -> Totals {271        let subtotal = roundMoney(lines.reduce(0) { $0 + $1.price * $1.quantity })272        let tax = roundMoney(subtotal * max(taxRate, 0))273        return Totals(itemCount: lines.reduce(0) { $0 + $1.quantity }, subtotal: subtotal, tax: tax, total: roundMoney(subtotal + tax))274    }275276    /// Price and quantity of each row; a missing quantity column or value counts as 1.277    static func lines(_ rows: [Row], price: String, quantity: String?) -> [(price: Double, quantity: Double)] {278        rows.map { row in279            (price: row[price]?.numericValue ?? 0, quantity: quantity.flatMap { $0.isEmpty ? nil : row[$0]?.numericValue } ?? 1)280        }281    }282283    /// Whole-percent reduction from an original price, or nil when there is no real discount.284    static func discountPercent(amount: Double, original: Double?) -> Int? {285        guard let original, original > 0, amount < original, amount >= 0 else { return nil }286        let percent = Int(((original - amount) / original * 100).rounded())287        return percent > 0 ? percent : nil288    }289290    /// Two-way unit conversion at a fixed rate: forward multiplies, backward divides. A zero or invalid rate converts to nil.291    static func convert(_ amount: Double, rate: Double, forward: Bool, decimals: Int = 2) -> Double? {292        guard rate.isFinite, rate != 0, amount.isFinite else { return nil }293        let raw = forward ? amount * rate : amount / rate294        let scale = pow(10, Double(min(max(decimals, 0), 8)))295        return (raw * scale).rounded() / scale296    }297298    static func clampedStep(_ value: Double, by step: Double, min lower: Double?, max upper: Double?) -> Double {299        var v = value + step300        if let lower { v = Swift.max(v, lower) }301        if let upper { v = Swift.min(v, upper) }302        return v303    }304305    /// One receipt line: text on the left (shortened if needed), amount flush right, exactly `width` characters.306    static func receiptLine(_ left: String, _ right: String, width: Int) -> String {307        let room = max(1, width - right.count - 1)308        let label = left.count > room ? String(left.prefix(max(1, room - 1))) + "…" : left309        return label + String(repeating: " ", count: max(1, width - label.count - right.count)) + right310    }311312    static func centered(_ text: String, width: Int) -> String {313        let t = String(text.prefix(width))314        return String(repeating: " ", count: (width - t.count) / 2) + t315    }316317    /// The lines of a monospaced receipt: header, items, subtotal, optional tax, total, footer.318    static func receipt(title: String, lines: [(label: String, amount: String)], subtotal: String, tax: String?, total: String, footer: String, width: Int = 34) -> [String] {319        var out: [String] = []320        if !title.isEmpty { out += [centered(title.uppercased(), width: width), String(repeating: "-", count: width)] }321        out += lines.map { receiptLine($0.label, $0.amount, width: width) }322        if lines.isEmpty { out.append(centered("(no items)", width: width)) }323        out.append(String(repeating: "-", count: width))324        if tax != nil { out.append(receiptLine("SUBTOTAL", subtotal, width: width)) }325        if let tax { out.append(receiptLine("TAX", tax, width: width)) }326        out.append(receiptLine("TOTAL", total, width: width))327        if !footer.isEmpty { out += [String(repeating: "=", count: width), centered(footer, width: width)] }328        return out329    }330331    // MARK: Social332333    /// Whole percentages that always add up to 100 (largest-remainder method); all zero when nobody voted.334    static func pollPercentages(_ votes: [Double]) -> [Int] {335        let clean = votes.map { $0.isFinite ? max($0, 0) : 0 }336        let total = clean.reduce(0, +)337        guard total > 0 else { return clean.map { _ in 0 } }338        let exact = clean.map { $0 / total * 100 }339        var out = exact.map { Int($0.rounded(.down)) }340        let order = exact.indices.sorted { a, b in341            let ra = exact[a] - Double(out[a]), rb = exact[b] - Double(out[b])342            return ra != rb ? ra > rb : a < b343        }344        for i in order.prefix(max(0, 100 - out.reduce(0, +))) { out[i] += 1 }345        return out346    }347348    /// Moves a vote: the previous choice loses one, the new one gains one. Voting for the current choice again changes nothing.349    static func vote(_ state: JSONValue, for option: String) -> JSONValue {350        var votes = state["votes"]?.objectValue ?? [:]351        let previous = state["choice"]?.stringValue352        if previous == option { return ["votes": .object(votes), "choice": .string(option)] }353        if let previous, !previous.isEmpty { votes[previous] = .int(max(0, Int(votes[previous]?.numericValue ?? 0) - 1)) }354        votes[option] = .int(Int(votes[option]?.numericValue ?? 0) + 1)355        return ["votes": .object(votes), "choice": .string(option)]356    }357358    /// Adds one to a reaction's count in a `{emoji: count}` object.359    static func react(_ state: JSONValue, with reaction: String) -> JSONValue {360        var counts = state.objectValue ?? [:]361        counts[reaction] = .int(Int(counts[reaction]?.numericValue ?? 0) + 1)362        return .object(counts)363    }364365    /// Up to two initials of a name, e.g. "Ada Lovelace" → "AL".366    static func initials(_ name: String) -> String {367        let words = name.split(whereSeparator: { !$0.isLetter && !$0.isNumber })368        let letters = words.count > 1 ? [words.first, words.last].compactMap { $0?.first } : Array((words.first ?? "").prefix(2))369        return letters.isEmpty ? "?" : String(letters).uppercased()370    }371372    // MARK: Dates373374    /// Parses `YYYY-MM-DD` (local midnight) or an ISO 8601 timestamp. `hasTime` tells whether hours are meaningful.375    static func parseDate(_ text: String, calendar: Calendar = .current) -> (date: Date, hasTime: Bool)? {376        let t = text.trimmingCharacters(in: .whitespaces)377        if t.count > 10 {378            let iso = ISO8601DateFormatter()379            for options in [[.withInternetDateTime, .withFractionalSeconds], [.withInternetDateTime]] as [ISO8601DateFormatter.Options] {380                iso.formatOptions = options381                if let d = iso.date(from: t.replacingOccurrences(of: " ", with: "T")) { return (d, true) }382            }383        }384        let parts = t.prefix(10).split(separator: "-").compactMap { Int($0) }385        guard parts.count == 3, DateCoding.date(from: t) != nil,386              let d = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2])) else { return nil }387        return (d, false)388    }389390    /// "Today", "Yesterday", "3 days ago", "In 2 weeks"…; minutes and hours only when the value carries a time.391    static func relativeDate(_ date: Date, now: Date, hasTime: Bool = false, calendar: Calendar = .current) -> String {392        func phrase(_ n: Int, _ unit: String, future: Bool) -> String {393            let text = "\(n) \(unit)\(n == 1 ? "" : "s")"394            return future ? "In \(text)" : "\(text) ago"395        }396        let seconds = now.timeIntervalSince(date)397        if hasTime && abs(seconds) < 86_400 {398            let future = seconds < 0, s = abs(seconds)399            if s < 60 { return "Just now" }400            if s < 3_600 { return phrase(Int(s / 60), "minute", future: future) }401            return phrase(Int(s / 3_600), "hour", future: future)402        }403        let days = calendar.dateComponents([.day], from: calendar.startOfDay(for: date), to: calendar.startOfDay(for: now)).day ?? 0404        if days == 0 { return "Today" }405        if days == 1 { return "Yesterday" }406        if days == -1 { return "Tomorrow" }407        let future = days < 0, n = abs(days)408        if n < 7 { return phrase(n, "day", future: future) }409        if n < 30 { return phrase(n / 7, "week", future: future) }410        if n < 365 { return phrase(n / 30, "month", future: future) }411        return phrase(n / 365, "year", future: future)412    }413414    static func relativeDate(_ text: String, now: Date, calendar: Calendar = .current) -> String {415        guard let parsed = parseDate(text, calendar: calendar) else { return text }416        return relativeDate(parsed.date, now: now, hasTime: parsed.hasTime, calendar: calendar)417    }418419    // MARK: Filters420421    /// The control a filter bar shows for a column.422    enum FilterControl: Equatable {423        case choice([String])424        case text425        case range426        case dateRange427        case flag428    }429430    /// Which control fits a column: a short list of known values becomes a dropdown, free text a "contains" field.431    static func filterControl(type: ColumnType, options: [String], distinct: [String], maxChoices: Int = 12) -> FilterControl {432        switch type {433        case .boolean: return .flag434        case .date: return .dateRange435        case .number, .integer, .currency: return .range436        case .text:437            if !options.isEmpty { return .choice(options) }438            return (1...maxChoices).contains(distinct.count) ? .choice(distinct) : .text439        }440    }441442    /// State keys a filter bar writes for a column (see `prism.filterBar`).443    static func filterKeys(_ column: String, _ control: FilterControl) -> [String] {444        switch control {445        case .range: [column + "Min", column + "Max"]446        case .dateRange: [column + "From", column + "To"]447        default: [column]448        }449    }450451    /// Number of filters currently set in a filter-bar state object.452    static func activeFilterCount(_ state: JSONValue) -> Int {453        (state.objectValue ?? [:]).values.filter { !$0.isNull && $0 != .string("") }.count454    }455}456
Files main
Menu

Theme