Cotton code
302 lines · 14.5 KB · SwiftRaw
// What a column's value MEANS, per column type — the one place that reads and// writes the stored form, so an editor, a face and the change receipt all agree// on the bytes.//// The stored form is the shared definition format's (agreed with the faces'// builder on 1 Oct 2026):////   text, longtext, choice  .text(String)//   date                    .text("YYYY-MM-DD"), or a full ISO 8601 instant//                           ("2026-10-01T09:30:00Z") when the day has a time//   time                    .text("HH:mm"), 24-hour//   number                  .number(Double)//   amount                  .number — whole minor units; the currency is the//                           column the definition's `currency` names//   link                    .text(target record id)//   photo                   .text("photo:<hash>")//   file                    .object(["ref": .text("file:<hash>"), "name": .text])//   bool                    .bool//   empty                   .null//// Pure over values and a calendar, so every rule here is a unit test// (`ColumnValuesTests`) with no view in it.import CottonKitimport CottonValuesimport Foundation// ── Date and time ───────────────────────────────────────────────────────────/// A date column's value as a day and an optional clock time, and back.public struct WhenValue: Equatable, Sendable {    /// Local midnight of the day.    public var day: Date    /// The clock time, when the value states one.    public var time: ClockTime?    public init(day: Date, time: ClockTime?) {        self.day = day        self.time = time    }    /// Reads a date column's stored text. A bare day is a local calendar day;    /// an instant keeps its clock time — a date editor handed a time never    /// drops it by accident.    public static func read(_ value: RecordValue, calendar: Calendar = .current) -> WhenValue? {        // A month on its own (a card's expiry) opens on its first day.        if case .text(let raw) = value, let month = FaceText.month(raw, calendar: calendar) {            return WhenValue(day: month, time: nil)        }        guard case .text(let raw) = value, let at = CottonDate.parse(raw, calendar: calendar) else {            return nil        }        let day = calendar.startOfDay(for: at)        guard !CottonDate.isDayOnly(raw) else { return WhenValue(day: day, time: nil) }        let parts = calendar.dateComponents([.hour, .minute], from: at)        return WhenValue(day: day, time: ClockTime(hour: parts.hour ?? 0, minute: parts.minute ?? 0))    }    /// The stored form: a bare day when there is no time, otherwise the local    /// instant written as UTC ISO 8601 — the form the engines' `due_at` and    /// `starts_at` already use.    public func stored(calendar: Calendar = .current) -> RecordValue {        guard let time else {            let parts = calendar.dateComponents([.year, .month, .day], from: day)            return .text(                String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0))        }        let at =            calendar.date(bySettingHour: time.hour, minute: time.minute, second: 0, of: day) ?? day        return .text(CottonDate.format(at))    }    /// `Thu 1 Oct` or `Thu 1 Oct 9:30 am`, with the year when it is not this one.    public func words(now: Date, calendar: Calendar = .current) -> String {        let sameYear =            calendar.component(.year, from: day) == calendar.component(.year, from: now)        let dayWords = CottonDate.formatter(sameYear ? "EEE d MMM" : "EEE d MMM yyyy", calendar)            .string(from: day)        guard let time else { return dayWords }        return "\(dayWords) \(time.words(calendar: calendar))"    }}// ── Amount ──────────────────────────────────────────────────────────────────/// An amount column's value: minor units in one currency. The shared format/// stores an amount as a WHOLE NUMBER of minor units (1599 = 15.99) and reads/// its currency off the column the definition's `currency` names; the core/// refuses any other shape ("a whole number of minor units").public struct AmountValue: Equatable, Sendable {    public var minor: Int    public var currency: String    public init(minor: Int, currency: String) {        self.minor = minor        self.currency = currency    }    /// `currency` is the record's currency column value (the definition's    /// `column.currency`); a whole number with no currency reads in the    /// device's own.    public static func read(_ value: RecordValue, currency: String? = nil) -> AmountValue? {        guard case .number(let minor) = value else { return nil }        return AmountValue(minor: Int(minor.rounded()), currency: currency ?? defaultCurrency())    }    /// What an editor writes: the minor units alone, as the core keeps them.    public var stored: RecordValue { .number(Double(minor)) }    /// The currency's minor-unit digits: 2 for most, 0 for yen, 3 for dinar.    public static func digits(_ currency: String) -> Int {        let formatter = NumberFormatter()        formatter.numberStyle = .currency        formatter.currencyCode = currency        return formatter.maximumFractionDigits    }    /// The currency a new amount is written in when the column has none yet:    /// the device's own. No country is the default — the person's locale is.    public static func defaultCurrency(locale: Locale = .current) -> String {        locale.currency?.identifier ?? "XXX"    }    /// The currency's symbol as the core says it (`money.symbols.<CODE>`:    /// `₹` for INR, never the locale's `Rs`), else as the locale writes it    /// (`$`, `CHF`).    public static func symbol(_ currency: String, locale: Locale = .current) -> String {        if let said = coreSymbol(currency) { return said }        let formatter = NumberFormatter()        formatter.numberStyle = .currency        formatter.locale = locale        formatter.currencyCode = currency        return formatter.currencySymbol    }    /// The symbol the core's money lines give `currency` (the database's    /// row first, then the kit's map), the same mark every face draws; nil    /// for a code the map does not name, or names blank.    static func coreSymbol(_ currency: String) -> String? {        let path = "symbols.\(currency.uppercased())"        let said = ShellLines.line(MoneyLines.set, path)        guard said != "\(MoneyLines.set).\(path)", !said.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }        return said    }    /// What was typed, as minor units: digits, one decimal separator (`.` or    /// the locale's), thousands separators and spaces ignored. More decimals    /// than the currency has is refused, not rounded — a typed `1.005` is a    /// mistake, not a half-paisa.    public static func parse(_ typed: String, currency: String, locale: Locale = .current) -> Int? {        let decimal = locale.decimalSeparator ?? "."        let grouping = locale.groupingSeparator ?? ","        var text = typed.trimmingCharacters(in: .whitespaces)        let negative = text.hasPrefix("-")        if negative { text.removeFirst() }        text = text.replacingOccurrences(of: " ", with: "")        if grouping != decimal { text = text.replacingOccurrences(of: grouping, with: "") }        if decimal != "." { text = text.replacingOccurrences(of: decimal, with: ".") }        let halves = text.split(separator: ".", omittingEmptySubsequences: false)        guard !text.isEmpty, halves.count <= 2,            halves.allSatisfy({ $0.allSatisfy(\.isASCII) && $0.allSatisfy(\.isNumber) })        else { return nil }        let digits = digits(currency)        let whole = halves[0].isEmpty ? "0" : String(halves[0])        let fraction = halves.count == 2 ? String(halves[1]) : ""        guard fraction.count <= digits, !(halves[0].isEmpty && fraction.isEmpty) else { return nil }        let padded = fraction.padding(toLength: digits, withPad: "0", startingAt: 0)        guard let minor = Int(whole + padded) else { return nil }        return negative ? -minor : minor    }    /// The amount an editor echoes while it is being chosen, before any read    /// carries the core's words for it: `₹1,850.00`. Every face, card and    /// figure draws the core's amount (`column_words`); this is the one    /// money spelling Swift keeps, for a value not yet written.    public func words(locale: Locale = .current) -> String {        let formatter = NumberFormatter()        formatter.locale = locale        formatter.numberStyle = .currency        formatter.currencyCode = currency        if let said = Self.coreSymbol(currency) { formatter.currencySymbol = said }        formatter.groupingSize = 3        formatter.secondaryGroupingSize = currency.uppercased() == "INR" ? 2 : 3        let scale = pow(Decimal(10), formatter.maximumFractionDigits)        let major = Decimal(minor) / scale        return formatter.string(from: NSDecimalNumber(decimal: major)) ?? "\(currency) \(minor)"    }    /// The amount as typed back into its field: `1850.00` → `1850`, `18.5`.    public func typed(locale: Locale = .current) -> String {        let digits = Self.digits(currency)        let major = Decimal(minor) / pow(Decimal(10), digits)        let formatter = NumberFormatter()        formatter.locale = locale        formatter.numberStyle = .decimal        formatter.usesGroupingSeparator = false        formatter.maximumFractionDigits = digits        return formatter.string(from: major as NSDecimalNumber) ?? "\(major)"    }}// ── Number ──────────────────────────────────────────────────────────────────/// The core's line set an amount is said through (`kits/shell/lines/money.json`).enum MoneyLines {    static let set = "money"}public enum NumberValue {    /// What was typed, as a number: the locale's decimal separator or `.`,    /// thousands separators ignored. Nil for anything that is not one number.    public static func parse(_ typed: String, locale: Locale = .current) -> Double? {        let decimal = locale.decimalSeparator ?? "."        let grouping = locale.groupingSeparator ?? ","        var text = typed.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: " ", with: "")        if grouping != decimal { text = text.replacingOccurrences(of: grouping, with: "") }        if decimal != "." { text = text.replacingOccurrences(of: decimal, with: ".") }        guard !text.isEmpty, let number = Double(text), number.isFinite else { return nil }        return number    }    /// `2`, not `2.0`; `2.5`; grouped as the locale groups.    public static func words(_ number: Double, locale: Locale = .current) -> String {        let formatter = NumberFormatter()        formatter.locale = locale        formatter.numberStyle = .decimal        formatter.maximumFractionDigits = 6        return formatter.string(from: NSNumber(value: number)) ?? "\(number)"    }    /// As typed back into its field: no grouping, so editing never fights it.    public static func typed(_ number: Double, locale: Locale = .current) -> String {        let formatter = NumberFormatter()        formatter.locale = locale        formatter.numberStyle = .decimal        formatter.usesGroupingSeparator = false        formatter.maximumFractionDigits = 6        return formatter.string(from: NSNumber(value: number)) ?? "\(number)"    }}// ── Photo and file ──────────────────────────────────────────────────────────// ── Words ───────────────────────────────────────────────────────────────────/// A value as a line of words, per column type — what a field shows before it/// is tapped and what the change receipt prints for before and after. Nil for/// an empty value. A link's words are its target's title, which only the/// records know; here it is the id.public enum ColumnWords {    public static func words(        _ value: RecordValue, column: ColumnDefinition, now: Date = Date(),        calendar: Calendar = .current, locale: Locale = .current    ) -> String? {        if case .null = value { return nil }        if column.presentation == "password" { return value.text == nil ? nil : ShellLines.line("editing", "value.password_supplied") }        switch column.type {        case .text, .accountNumber, .longtext, .choice, .link, .url, .place:            guard case .text(let text) = value, !text.isEmpty else { return nil }            return text        case .date:            return WhenValue.read(value, calendar: calendar)?.words(now: now, calendar: calendar)        case .time:            return ClockTime.read(value)?.words(calendar: calendar)        case .bytes:            return value.number.flatMap(BytesReading.read)        case .number:            guard case .number(let number) = value else { return nil }            return NumberValue.words(number, locale: locale)        case .amount:            return AmountValue.read(value)?.words(locale: locale)        case .photo:            return AttachmentValue.read(value) == nil ? nil : "Photo"        case .file:            guard let file = AttachmentValue.read(value) else { return nil }            return file.name ?? "File"        case .bool:            guard case .bool(let on) = value else { return nil }            return on ? "Yes" : "No"        }    }}extension ClockTime {    /// `9:30 am` — the house clock.    public func words(calendar: Calendar = .current) -> String {        let reference = calendar.startOfDay(for: Date(timeIntervalSince1970: 0))        let at =            calendar.date(bySettingHour: hour, minute: minute, second: 0, of: reference) ?? reference        return DateFormats.houseTime(at, calendar: calendar)    }}extension AttachmentValue {    /// A photo is its bare ref; a file carries its name beside it.    public func stored(for type: ColumnType) -> RecordValue {        guard type == .file else { return .text(ref) }        var fields: [String: RecordValue] = ["ref": .text(ref)]        if let name { fields["name"] = .text(name) }        return .object(fields)    }}