// Four keys a list reads, and a slip's byline: a list split by day or by// month, a slip table's own grid, a row of choice words that makes a record,// and the line by hand saying who named part of a record. Each is drawn once,// for any table that names it (Mood was the first: its moments under their// days, two to a row, the emotion chips and "named by the assistant"; Notes// brought the months, a grid it opens on, and its "+").//// The reading lives here, pure, so the words and the order are settled by// tests; `RecordListSurface`, `SlipFace` and `ChoiceChips` only draw them.importCottonKitimportCottonValuesimportFoundation/// A slip's byline: the words a value of `column` is read as by hand at the/// slip's foot. A value with no words draws nothing.publictypealiasSlipByline = DefinitionSlipBylineextensionDefinitionSlipByline {publicinit(column: String, words: [String: String], ink: SectionInk? = nil) {self.init(_generated: (), column: column, words: words)self.ink = ink }}/// How many records stand across a list drawn as cards or as the contact/// sheet (`layout`).publictypealiasListGrid = DefinitionListGridextensionDefinitionListGrid {publicinit(columns: Int) {self.init(_generated: (), columns: columns) }}/// The ONE way a list draws its records, chosen by its definition: cards,/// the borderless contact sheet, or slips (absent). The person never switches/// it and no device remembers one (owner, 15 Oct 2026).publictypealiasListLayout = DefinitionListLayout/// The list's Paste button: the text or long text column a pasted text is/// written to (`paste` in the crate).publictypealiasListPaste = DefinitionListPasteextensionDefinitionListPaste {publicinit(column: String) { self.init(_generated: (), column: column) }}/// The chips over a list: the several-choice column whose words they are,/// and the fixed values a record made from them carries besides ("named by"/// the owner).publictypealiasChipRow = DefinitionChipRowextensionDefinitionChipRow {publicinit(column: String, sends: [String: RecordValue] = [:]) {self.init(_generated: (), column: column)self.sends = sends }}extensionTableDefinition {/// Whether the byline is drawn in red ink.publicvar bylineIsRed: Bool { slip.byline?.ink == .red }/// The list split by its `by_day` column: one section per day, newest day/// first, headed by the day's name and counted only when it holds more/// than one; within a day, the order the list already reads in. A record/// with no day goes last, under no heading. A record whose date column/// holds a MOMENT (a mood's `at`) stands under that moment's day on this/// phone — the day its slip prints, so "Tue 29 Sep · 10:58 PM" sits under/// Tuesday; else its `by_day` value, a bare day read as written.publicfunc daySections(of records: [TableRecord], now: Date = Date(), calendar: Calendar = .current) -> [RecordSection] {guardlet byDay else { return [RecordSection(heading: nil, records: records)] }var days: [String: [TableRecord]] = [:]var undated: [TableRecord] = []for record in records {guardlet key = momentDay(of: record, calendar: calendar) ?? Self.dayKey(record[byDay], calendar: calendar) else { undated.append(record)continue } days[key, default: []].append(record) }var sections = days.keys.sorted(by: >).map { key inRecordSection(heading: days[key]?.first.flatMap { dayHead(of: $0, calendar: calendar) }, records: days[key] ?? [], countsOne: false, dayWords: .timeUnderDay) }if !undated.isEmpty { sections.append(RecordSection(heading: nil, records: undated)) }return sections }/// The list split by its `by_month` column, once it is long enough to/// need it: more than `ListMonths.threshold` records over more than one/// month. Then one section per run of a month in the order the list/// already reads in (newest first), headed "September" — "September 2025"/// outside this year — and counted. A record whose date will not read/// joins the run it arrived in, never vanishing. Shorter, or all one/// month: one unheaded section, as the old Notes list drew.publicfunc monthSections(of records: [TableRecord], now: Date = Date(), calendar: Calendar = .current) -> [RecordSection] {let whole = [RecordSection(heading: nil, records: records)]if months != nil { return everyMonth(of: records, now: now, calendar: calendar) }guardlet byMonth, records.count > ListMonths.threshold else { return whole }var runs: [(key: String, at: DayParts?, records: [TableRecord])] = []for record in records {let at = record.dayParts(byMonth)let key = at?.month ?? runs.last?.key ?? ""iflet last = runs.last, last.key == key { runs[runs.count - 1].records.append(record) } else { runs.append((key, at, [record])) } }guardSet(runs.map(\.key)).count > 1else { return whole }return runs.map { run inRecordSection(heading: run.at?.monthTitle, records: run.records, dayWords: run.at == nil ? .full : .dayUnderMonth) } }/// The list split by its `by_month` column as `months` says: once it/// holds more than `over` records (absent: a dozen), however many months/// they span — a library is always in months. One section per month, a/// month met again later joining its first run (the list keeps its own/// order within it), each counted in the table's `count_words`; the/// undated moved last under `undated` (absent: no heading), never/// dropped.func everyMonth(of records: [TableRecord], now: Date, calendar: Calendar) -> [RecordSection] {guardlet byMonth, let months, records.count > (months.over ?? ListMonths.threshold) else {return [RecordSection(heading: nil, records: records)] }var runs: [(key: String, at: DayParts, records: [TableRecord])] = []var index: [String: Int] = [:]var undated: [TableRecord] = []for record in records {guardlet at = record.dayParts(byMonth) else { undated.append(record)continue }let key = at.monthiflet slot = index[key] { runs[slot].records.append(record) } else { index[key] = runs.count runs.append((key, at, [record])) } }var sections = runs.map { run inRecordSection(heading: run.at.monthTitle, records: run.records, dayWords: .dayUnderMonth) }if !undated.isEmpty { sections.append(RecordSection(heading: months.undated, records: undated)) }return sections }/// The heading over the day a record stands under, as the core said it:/// its moment's day when its date column holds a moment, else its/// `by_day` value's.func dayHead(of record: TableRecord, calendar: Calendar) -> String? {let key = momentDay(of: record, calendar: calendar) != nil ? date : byDayreturn record.dayParts(key)?.heading }/// "yyyy-MM-dd" of the moment a record's date column holds, as its day in/// `calendar`; nil when it holds a bare day or nothing.func momentDay(of record: TableRecord, calendar: Calendar) -> String? {guardlet text = record[date].text, !CottonDate.isDayOnly(text) else { returnnil }returnFaceText.dayKey(text, calendar: calendar).flatMap { Self.believable($0, calendar: calendar) } }/// "yyyy-MM-dd" of a day column's value: a bare day as written, an/// instant as its day in `calendar`.staticfunc dayKey(_ value: RecordValue, calendar: Calendar) -> String? {guardlet text = value.text else { returnnil }ifCottonDate.isDayOnly(text) { returnCottonDate.parse(text, calendar: calendar) == nil ? nil : believable(text, calendar: calendar) }returnFaceText.dayKey(text, calendar: calendar).flatMap { believable($0, calendar: calendar) } }/// A day only a spoiled stamp could name (a mail dated 2611) heads/// nothing: its record stands with the undated, under no heading, and a/// day head is only ever a day in words (291 words row 1).staticfunc believable(_ day: String, calendar: Calendar) -> String? {guardlet at = CottonDate.parse(day, calendar: calendar),CottonDate.believableYears.contains(calendar.component(.year, from: at)) else { returnnil }return day }/// The values a record made from the chips is written with: the chosen/// words in the column's own order (two people tapping the same chips in/// a different order write the same record), the row's fixed values, and/// the moment it was made — `date` as the instant, `by_day` as today./// Nil when nothing is chosen.publicfunc chipRecord(_ chosen: Set<String>, now: Date = Date(), calendar: Calendar = .current) -> [String: RecordValue]? {guardlet chips, let column = column(chips.column) else { returnnil }let words = (column.choices ?? []).filter(chosen.contains)guard !words.isEmpty else { returnnil }var data = chips.sends data[column.key] = .list(words.map(RecordValue.text))iflet date, self.column(date)?.type == .date { data[date] = .text(CottonDate.format(now)) }iflet byDay, self.column(byDay)?.type == .date, let today = FaceText.dayKey(CottonDate.format(now), calendar: calendar) { data[byDay] = .text(today) }return data }}extensionFaceText {/// A several-choice column's words, in the order written: a list of/// them, or the JSON array an engine writes into text. A plain word is a/// list of one.publicstaticfunc choices(_ value: RecordValue) -> [String] {switch value {case .list(let items):return items.compactMap(\.text)case .text(let text):let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)// A JSON array read whole, its words kept and anything else in it// (a null or a number typed into the text) dropped — never the// raw text as one word.if trimmed.hasPrefix("["), let items = (try? JSONSerialization.jsonObject(with: Data(trimmed.utf8))) as? [Any] {return items.compactMap { $0 as? String }.filter { !$0.isEmpty } }return trimmed.isEmpty ? [] : [trimmed]default:return [] } }/// A several-choice value as a face writes it — "tired \u{00B7} hopeful",/// the words as they are kept — or nil when none is chosen.publicstaticfunc choiceLine(_ value: RecordValue) -> String? {let words = choices(value).map { $0.replacingOccurrences(of: "_", with: " ") }return words.isEmpty ? nil : words.joined(separator: " \u{00B7} ") }}