Cotton code
158 lines · 7.4 KB · SwiftRaw
// One record of a table, as the interpreter holds it: an id and its column// values as typed JSON. The shared format stores a user table's columns as JSON// (`records.data`); a built-in table answers the same shape through its engine.// With the words, numbers and days the core resolved beside them. Plain// values: what a write answers (`ChangeRecord`) stays the app's.import Foundation/// A column's value as the core resolved it for a face: the words, or nil/// when the core read it and it says nothing. A face draws these as given.public struct ResolvedWords: Hashable, Sendable {    public var said: String?    public init(said: String?) { self.said = said }}/// A counted number as a card draws it (`page::number_parts`): the figure/// short enough to stand on the card ("4.2K") and the word under it.public struct NumberParts: Hashable, Sendable {    public var figure: String    public var unit: String}/// A stored date as the core resolved it (`page::DayParts`): every surface/// draws these parts and never reads a calendar for words.public struct DayParts: Hashable, Sendable {    /// The day as a key ("2026-10-15"), for comparing and grouping days.    public var day: String    /// "Today", "Friday": within a week either side, else nil.    public var near: String?    /// "11 Oct", the year outside the reader's.    public var dated: String    /// A page headed by its day: "Wednesday" over "1 October".    public var weekdayName: String    public var dayLong: String    /// "Tue 6 Oct", the year outside the reader's.    public var weekdayDate: String    /// The heading over a day's records: "Today", else the weekday date.    public var heading: String    /// Where no heading names the day: the clock today, "Yesterday", else the weekday date.    public var recent: String    /// Under a heading naming the day: the clock, or "All day".    public var underDay: String    public var clock: String?    /// "2 days late" or "late"; nil when not behind.    public var late: String?    /// The month as a key ("2026-09") and its heading ("September").    public var month: String    public var monthTitle: String    public var leafDay: Int    public var leafMonth: String    /// A date with an `until`, as one range ("1 Jul – 31 Jul 2026").    public var range: String?    /// A yearly date by its next time round: "Turns 34 on Mon 17 Aug", and    /// on a card, whose leaf says the day, "turns 34 tomorrow".    public var yearly: String?    public var yearlyCard: String?    /// The weekday date and the clock ("Mon 5 Oct · 3:24 am"), or the day alone.    public var full: String    /// "5 min ago", "3 h ago", "yesterday" within two days of a timed moment.    public var ago: String?    public init?(_ value: RecordValue) {        guard case .object(let o) = value, let day = o["day"]?.text, let dated = o["dated"]?.text,              let weekdayDate = o["weekday_date"]?.text, let weekdayName = o["weekday_name"]?.text,              let dayLong = o["day_long"]?.text, let heading = o["heading"]?.text,              let recent = o["recent"]?.text, let underDay = o["under_day"]?.text,              let month = o["month"]?.text, let monthTitle = o["month_title"]?.text,              let leafDay = o["leaf_day"]?.number, let leafMonth = o["leaf_month"]?.text else { return nil }        (self.day, self.near, self.dated, self.weekdayDate, self.heading) = (day, o["near"]?.text, dated, weekdayDate, heading)        (self.recent, self.underDay, self.clock, self.late) = (recent, underDay, o["clock"]?.text, o["late"]?.text)        (self.weekdayName, self.dayLong, self.range) = (weekdayName, dayLong, o["range"]?.text)        (self.yearly, self.yearlyCard) = (o["yearly"]?.text, o["yearly_card"]?.text)        (self.full, self.ago) = (o["full"]?.text ?? weekdayDate, o["ago"]?.text)        (self.month, self.monthTitle, self.leafDay, self.leafMonth) = (month, monthTitle, Int(leafDay), leafMonth)    }}public struct TableRecord: Hashable, Sendable, Identifiable, Codable {    public var id: String    public var values: [String: RecordValue]    public init(id: String, values: [String: RecordValue]) {        self.id = id        self.values = values    }    /// The byline a shared database's record carries from `records.get`: the    /// name of the person whose device last wrote it. Not a column of any    /// definition; the page's Edited line reads it.    public static let editedByKey = "edited_by"    /// Set false by the core on a record it will not delete alone (a later    /// occurrence of a repeating event: deleting it would take the series).    /// Not a column of any definition; absent means deletable.    public static let deletableKey = "deletable"    /// Whether the core lets this record be deleted on its own.    public var deletable: Bool { self[Self.deletableKey].bool != false }    /// The rollup columns whose source tool is not installed in this    /// database (`records.get`'s `computed_unavailable`), each as the core    /// sent it: `{table, words}`. Not a column of any definition.    public static let unavailableKey = "computed_unavailable"    /// Where the core puts each typed column's face words    /// (`cotton_core::records::page::column_words`).    public static let columnWordsKey = "@column_words"    /// Where the core puts each date column's parts (`page::day_parts`).    public static let dayPartsKey = "@day_parts"    /// A date column's parts as the core said them, or nil.    public func dayParts(_ key: String?) -> DayParts? {        guard let key, case .object(let days) = self[Self.dayPartsKey], let day = days[key] else { return nil }        return DayParts(day)    }    /// A counted number column's figure and unit as the core said them, or nil.    public func numberParts(_ key: String?) -> NumberParts? {        guard let key, case .object(let numbers) = self["@number_parts"], case .object(let parts)? = numbers[key],              let figure = parts["figure"]?.text else { return nil }        return NumberParts(figure: figure, unit: parts["unit"]?.text ?? "")    }    /// The day an upcoming list files this record under (`@slip_day`).    public var upcomingDay: DayParts? { DayParts(self["@slip_day"]) }    /// The core's words for a column, or nil when the core did not read it.    public func columnWords(_ key: String?) -> ResolvedWords? {        guard let key else { return nil }        if case .object(let words) = self[Self.columnWordsKey], let said = words[key] { return ResolvedWords(said: said.text) }        // A yearly day is said by its next time round (`DayParts.yearly`).        if let yearly = dayParts(key)?.yearly { return ResolvedWords(said: yearly) }        return nil    }    public subscript(_ key: String?) -> RecordValue {        guard let key else { return .null }        return values[key] ?? .null    }    /// A fixture or FFI record is one flat JSON object: `id` plus the columns.    public init(from decoder: Decoder) throws {        var all = try decoder.singleValueContainer().decode([String: RecordValue].self)        guard case .text(let id)? = all.removeValue(forKey: "id") else {            throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "a record needs a text id"))        }        self.id = id        self.values = all    }    public func encode(to encoder: Encoder) throws {        var all = values        all["id"] = .text(id)        var c = encoder.singleValueContainer()        try c.encode(all)    }}