SPB Git

Repository Public

VQFormat.swift 16.1 KB 260 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Formatting/VQFormat.swift3// Description: Number and date formatting identical to the web app's `client/src/lib/format.ts` (tested against4//              strings generated by that file: Tests/…/Fixtures/format_golden.json).5//6// Rules of the design system: a missing value is "—" (never 0, never blank); fractions stay fractions in data and7// become "12,34 %" only here; fr-CA by default ("1 234,56"), en-CA on request ("1,234.56"). Render the result in the8// mono face with tabular figures.9import Foundation1011public enum VQNumberLocale: String, Sendable, Hashable, CaseIterable {12    case frCA = "fr-CA"13    case enCA = "en-CA"14    /// From `preference.numberFormat`; anything else is fr-CA (the web's default).15    public init(preference: String?) { self = preference == "en-CA" ? .enCA : .frCA }16    var group: String { self == .frCA ? "\u{00A0}" : "," }17    var decimal: String { self == .frCA ? "," : "." }18}1920/// Units of the `lab/1` result schema and of statement rows.21public enum VQValueUnit: String, Sendable, Hashable, CaseIterable {22    case ratio, percent, currency, bps, days, count23    case perShare = "per_share"24    case none = ""25    public init(_ raw: String?) { self = raw.flatMap(VQValueUnit.init(rawValue:)) ?? .none }26}2728public enum VQDirection: String, Sendable, Hashable { case up, down, flat }2930public enum VQFormat {31    /// "—"32    public static let nullText = "\u{2014}"33    private static let nbsp = "\u{00A0}"3435    private static func missing(_ v: Double?) -> Bool { v == nil || !(v!.isFinite) }36    private static func plus(_ v: Double, _ signed: Bool) -> String { signed && v > 0 ? "+" : "" }3738    /// Rounds half away from zero on the shortest decimal form of the double (what `Intl.NumberFormat` does:39    /// 1.005 → "1.01", 2.5 → "3") and returns the magnitude with exactly `decimals` fraction digits and a "." mark.40    static func fixedMagnitude(_ value: Double, decimals: Int) -> String {41        let d = max(0, min(decimals, 20))42        var input = Decimal(string: "\(abs(value))", locale: Locale(identifier: "en_US_POSIX")) ?? Decimal(abs(value))43        var rounded = Decimal()44        NSDecimalRound(&rounded, &input, d, .plain)45        var text = NSDecimalString(&rounded, Locale(identifier: "en_US_POSIX"))46        if d > 0 {47            if !text.contains(".") { text += "." }48            let have = text.count - (text.firstIndex(of: ".").map { text.distance(from: text.startIndex, to: $0) } ?? 0) - 149            if have < d { text += String(repeating: "0", count: d - have) }50        }51        return text52    }5354    /// Grouping and decimal mark of the locale applied to a "1234.50"-style magnitude.55    static func localized(_ magnitude: String, _ locale: VQNumberLocale) -> String {56        let parts = magnitude.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: false)57        let whole = Array(parts[0])58        var grouped = ""59        for (i, ch) in whole.enumerated() {60            if i > 0, (whole.count - i) % 3 == 0 { grouped += locale.group }61            grouped.append(ch)62        }63        return parts.count > 1 ? grouped + locale.decimal + parts[1] : grouped64    }6566    private static func body(_ value: Double, _ decimals: Int, _ locale: VQNumberLocale) -> String {67        (value < 0 ? "-" : "") + localized(fixedMagnitude(value, decimals: decimals), locale)68    }6970    // MARK: numbers7172    /// 1234.5 → "1 234,50"73    public static func number(_ value: Double?, decimals: Int = 2, signed: Bool = false, locale: VQNumberLocale = .frCA) -> String {74        guard let value, value.isFinite else { return nullText }75        return plus(value, signed) + body(value, decimals, locale)76    }7778    /// 12345 → "12 345"79    public static func int(_ value: Double?, signed: Bool = false, locale: VQNumberLocale = .frCA) -> String {80        number(value, decimals: 0, signed: signed, locale: locale)81    }82    public static func int(_ value: Int?, signed: Bool = false, locale: VQNumberLocale = .frCA) -> String {83        number(value.map(Double.init), decimals: 0, signed: signed, locale: locale)84    }8586    /// Compact magnitude with French financial suffixes: k, M, G (milliard), T (billion). 2.5e9 → "2,50 G"87    public static func compact(_ value: Double?, decimals: Int = 2, signed: Bool = false, prefix: String = "", locale: VQNumberLocale = .frCA) -> String {88        guard let value, value.isFinite else { return nullText }89        let magnitude = abs(value)90        let neg = value < 0 ? "-" : plus(value, signed)91        for (unit, suffix) in [(1e12, "T"), (1e9, "G"), (1e6, "M"), (1e3, "k")] where magnitude >= unit {92            let d = suffix == "k" ? min(decimals, 1) : decimals93            return "\(neg)\(prefix)\(localized(fixedMagnitude(magnitude / unit, decimals: d), locale))\(nbsp)\(suffix)"94        }95        return "\(neg)\(prefix)\(localized(fixedMagnitude(magnitude, decimals: decimals), locale))"96    }9798    /// 1234.5, "USD" → "1 234,50 $ US" (fr-CA) / "US$1,234.50" (en-CA). `compact` gives "1,23 G USD".99    public static func currency(_ value: Double?, _ code: String = "USD", decimals: Int = 2, signed: Bool = false, compact isCompact: Bool = false, locale: VQNumberLocale = .frCA) -> String {100        guard let value, value.isFinite else { return nullText }101        if isCompact { return "\(compact(value, decimals: decimals, signed: signed, locale: locale))\(nbsp)\(code)" }102        let magnitude = localized(fixedMagnitude(value, decimals: decimals), locale)103        let sign = value < 0 ? "-" : ""104        let isISO = code.utf8.count == 3 && code.utf8.allSatisfy { ($0 >= 65 && $0 <= 90) || ($0 >= 97 && $0 <= 122) }105        guard isISO else { return "\(plus(value, signed))\(sign)\(magnitude)\(nbsp)\(code)" }     // not an ISO code: number + code106        let upper = code.uppercased()107        switch locale {108        case .frCA:109            let symbol = ["USD": "$\(nbsp)US", "CAD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "AUD": "$\(nbsp)AU", "HKD": "$\(nbsp)HK", "CNY": "CN¥",110                          "NZD": "$\(nbsp)NZ", "SGD": "$\(nbsp)SG", "BRL": "R$"][upper] ?? upper111            return "\(plus(value, signed))\(sign)\(magnitude)\(nbsp)\(symbol)"112        case .enCA:113            let symbol = ["USD": "US$", "CAD": "$", "EUR": "€", "GBP": "£", "JPY": "JP¥", "AUD": "A$", "MXN": "MX$", "HKD": "HK$", "CNY": "CN¥",114                          "NZD": "NZ$", "INR": "₹", "KRW": "₩", "ILS": "₪", "BRL": "R$", "TWD": "NT$", "VND": "₫", "PHP": "₱", "XCD": "EC$",115                          "XAF": "FCFA\(nbsp)", "XOF": "F\u{202F}CFA\(nbsp)", "XPF": "CFPF\(nbsp)"][upper]116            return "\(plus(value, signed))\(sign)\(symbol ?? upper + nbsp)\(magnitude)"117        }118    }119120    /// A FRACTION to a percentage: 0.1234 → "12,34 %".121    public static func percent(_ fraction: Double?, decimals: Int = 2, signed: Bool = false, locale: VQNumberLocale = .frCA) -> String {122        guard let fraction, fraction.isFinite else { return nullText }123        return percentValue(fraction * 100, decimals: decimals, signed: signed, locale: locale)124    }125126    /// A value already in percent units (quotes' `changePct`): 12.34 → "12,34 %".127    public static func percentValue(_ percent: Double?, decimals: Int = 2, signed: Bool = false, locale: VQNumberLocale = .frCA) -> String {128        guard let percent, percent.isFinite else { return nullText }129        return "\(number(percent, decimals: decimals, signed: signed, locale: locale))\(nbsp)%"130    }131132    /// A FRACTION to basis points: 0.0025 → "25 pb".133    public static func bps(_ fraction: Double?, decimals: Int = 0, signed: Bool = false, locale: VQNumberLocale = .frCA) -> String {134        guard let fraction, fraction.isFinite else { return nullText }135        return "\(number(fraction * 10_000, decimals: decimals, signed: signed, locale: locale))\(nbsp)pb"136    }137138    /// Signed change: 1.5 → "+1,50", −0.2 → "-0,20".139    public static func delta(_ value: Double?, decimals: Int = 2, locale: VQNumberLocale = .frCA) -> String {140        number(value, decimals: decimals, signed: true, locale: locale)141    }142143    /// Direction of a change; values that round to zero at `decimals` are flat.144    public static func direction(_ value: Double?, decimals: Int = 2) -> VQDirection {145        guard let value, value.isFinite else { return .flat }146        let eps = 0.5 * pow(10, -Double(decimals))147        return value > eps ? .up : value < -eps ? .down : .flat148    }149150    /// Formats by declared unit. `percent` and `bps` values are FRACTIONS; `ratio` is a plain number (3 decimals);151    /// `currency` and `per_share` use `currency` (default USD); `days` → "d" in English, "j" in French152    /// (`language`, by default the host app's — the number format `locale` is a separate matter).153    public static func byUnit(_ value: Double?, _ unit: VQValueUnit, decimals: Int? = nil, currency code: String = "USD", signed: Bool = false, compact isCompact: Bool = false, locale: VQNumberLocale = .frCA, language: VQLanguage = .preferred) -> String {154        guard let value, value.isFinite else { return nullText }155        switch unit {156        case .percent: return percent(value, decimals: decimals ?? 2, signed: signed, locale: locale)157        case .bps: return bps(value, decimals: decimals ?? 0, signed: signed, locale: locale)158        case .currency: return currency(value, code, decimals: decimals ?? 2, signed: signed, compact: isCompact, locale: locale)159        case .perShare: return currency(value, code, decimals: decimals ?? 2, signed: signed, locale: locale)160        case .days: return "\(number(value, decimals: decimals ?? 0, signed: signed, locale: locale))\(nbsp)\(VQL10n.string("d", language))"161        case .count: return isCompact ? compact(value, decimals: decimals ?? 1, signed: signed, locale: locale) : number(value, decimals: decimals ?? 0, signed: signed, locale: locale)162        case .ratio: return number(value, decimals: decimals ?? 3, signed: signed, locale: locale)163        case .none: return number(value, decimals: decimals ?? 2, signed: signed, locale: locale)164        }165    }166167    /// Formats by the unit as the server names it. Everything `byUnit` knows, plus `years` (a duration in years:168    /// "3,2 ans" / "3.2 yr") — units added to the schema after `VQValueUnit` was fixed are handled here, so the169    /// enumeration never gains a case under the apps' feet. An unknown name formats as a plain number.170    public static func byUnitName(_ value: Double?, _ unitName: String?, decimals: Int? = nil, currency code: String = "USD", signed: Bool = false, compact isCompact: Bool = false, locale: VQNumberLocale = .frCA) -> String {171        guard let value, value.isFinite else { return nullText }172        if unitName == "years" { return "\(number(value, decimals: decimals ?? 1, signed: signed, locale: locale))\(nbsp)\(locale == .frCA ? (abs(value) >= 2 ? "ans" : "an") : "yr")" }173        return byUnit(value, VQValueUnit(unitName), decimals: decimals, currency: code, signed: signed, compact: isCompact, locale: locale)174    }175176    /// 850 → "850 ms", 2500 → "2,5 s", 125000 → "2 min 05 s"; nil → "".177    public static func duration(ms: Double?, locale: VQNumberLocale = .frCA) -> String {178        guard let ms, ms.isFinite else { return "" }179        if ms < 1000 { return "\(Int((ms + 0.5).rounded(.down))) ms" }180        if ms < 60_000 { return "\(localized(fixedMagnitude(ms / 1000, decimals: 1), locale)) s" }181        let s = Int((ms / 1000 + 0.5).rounded(.down))182        return "\(s / 60) min \(String(format: "%02d", s % 60)) s"183    }184185    /// Token counts: 950 → "950", 12 400 → "12,4 k", 1.2e6 → "1,20 M".186    public static func tokens(_ value: Double?, locale: VQNumberLocale = .frCA) -> String {187        guard let value, value.isFinite else { return nullText }188        return value < 1000 ? int(value, locale: locale) : compact(value, decimals: value < 1e6 ? 1 : 2, locale: locale)189    }190    public static func tokens(_ value: Int?, locale: VQNumberLocale = .frCA) -> String { tokens(value.map(Double.init), locale: locale) }191192    /// Cost of a run in USD: small amounts keep three decimals; nil (unknown price) → "—", never guessed.193    public static func cost(_ usd: Double?, locale: VQNumberLocale = .frCA) -> String {194        guard let usd, usd.isFinite else { return nullText }195        return currency(usd, "USD", decimals: usd > 0 && usd < 1 ? 3 : 2, locale: locale)196    }197198    // MARK: dates (the web always writes them in French; `language: .en` is the native apps' English variant)199200    private static let frMonths = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]201    private static let frShort = ["janv.", "févr.", "mars", "avr.", "mai", "juin", "juill.", "août", "sept.", "oct.", "nov.", "déc."]202    private static let enMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]203    private static let enShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]204205    private static func parts(_ date: Date, _ tz: TimeZone) -> (y: Int, m: Int, d: Int, h: Int, min: Int) {206        var cal = Calendar(identifier: .gregorian)207        cal.timeZone = tz208        let c = cal.dateComponents([.year, .month, .day, .hour, .minute], from: date)209        return (c.year ?? 1970, c.month ?? 1, c.day ?? 1, c.hour ?? 0, c.minute ?? 0)210    }211212    /// "20 novembre 2026" / "November 20, 2026"213    public static func date(_ date: Date?, language: VQLanguage = .fr, timeZone: TimeZone = .current) -> String {214        guard let date else { return nullText }215        let p = parts(date, timeZone)216        return language == .fr ? "\(p.d) \(frMonths[p.m - 1]) \(p.y)" : "\(enMonths[p.m - 1]) \(p.d), \(p.y)"217    }218219    /// "2026-11-20" in the given zone — the compact form for tables.220    public static func dateISO(_ date: Date?, timeZone: TimeZone = .current) -> String {221        guard let date else { return nullText }222        let p = parts(date, timeZone)223        return String(format: "%04d-%02d-%02d", p.y, p.m, p.d)224    }225226    /// "14 h 32" / "14:32"227    public static func time(_ date: Date?, language: VQLanguage = .fr, timeZone: TimeZone = .current) -> String {228        guard let date else { return nullText }229        let p = parts(date, timeZone)230        return language == .fr ? "\(p.h)\(nbsp)h\(nbsp)\(String(format: "%02d", p.min))" : String(format: "%d:%02d", p.h, p.min)231    }232233    /// "20 novembre 2026 à 14 h 32"234    public static func dateTime(_ date: Date?, language: VQLanguage = .fr, timeZone: TimeZone = .current) -> String {235        guard let date else { return nullText }236        return VQL10n.string("%1$@ at %2$@", language, self.date(date, language: language, timeZone: timeZone), time(date, language: language, timeZone: timeZone))237    }238239    /// As-of stamp of a data surface: the time when it is today, otherwise "19 nov." (+ year when it differs).240    public static func asOf(_ date: Date?, now: Date = Date(), language: VQLanguage = .fr, timeZone: TimeZone = .current) -> String {241        guard let date else { return nullText }242        let p = parts(date, timeZone), n = parts(now, timeZone)243        if p.y == n.y, p.m == n.m, p.d == n.d { return time(date, language: language, timeZone: timeZone) }244        let dayMonth = language == .fr ? "\(p.d) \(frShort[p.m - 1])" : "\(enShort[p.m - 1]) \(p.d)"245        return p.y == n.y ? dayMonth : (language == .fr ? "\(dayMonth) \(p.y)" : "\(dayMonth), \(p.y)")246    }247248    /// "à l'instant", "il y a 5 min", "il y a 3 h", "il y a 2 j", then the date.249    public static func relative(_ date: Date?, now: Date = Date(), language: VQLanguage = .fr, timeZone: TimeZone = .current) -> String {250        guard let date else { return nullText }251        func round(_ x: Double) -> Int { Int((x + 0.5).rounded(.down)) }252        let s = round(now.timeIntervalSince(date))253        if s < 45 { return VQL10n.string("just now", language) }254        if s < 3600 { return VQL10n.string("%lld min ago", language, max(1, round(Double(s) / 60))) }255        if s < 86_400 { return VQL10n.string("%lld h ago", language, round(Double(s) / 3600)) }256        if s < 7 * 86_400 { return VQL10n.string("%lld d ago", language, round(Double(s) / 86_400)) }257        return asOf(date, now: now, language: language, timeZone: timeZone)258    }259}260
Files main
Menu

Theme