// 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. import CottonKit import CottonValues import Foundation /// 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. public typealias SlipByline = DefinitionSlipByline extension DefinitionSlipByline { public init(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`). public typealias ListGrid = DefinitionListGrid extension DefinitionListGrid { public init(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). public typealias ListLayout = DefinitionListLayout /// The list's Paste button: the text or long text column a pasted text is /// written to (`paste` in the crate). public typealias ListPaste = DefinitionListPaste extension DefinitionListPaste { public init(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). public typealias ChipRow = DefinitionChipRow extension DefinitionChipRow { public init(column: String, sends: [String: RecordValue] = [:]) { self.init(_generated: (), column: column) self.sends = sends } } extension TableDefinition { /// Whether the byline is drawn in red ink. public var 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. public func daySections(of records: [TableRecord], now: Date = Date(), calendar: Calendar = .current) -> [RecordSection] { guard let byDay else { return [RecordSection(heading: nil, records: records)] } var days: [String: [TableRecord]] = [:] var undated: [TableRecord] = [] for record in records { guard let 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 in RecordSection(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. public func 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) } guard let 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 ?? "" if let last = runs.last, last.key == key { runs[runs.count - 1].records.append(record) } else { runs.append((key, at, [record])) } } guard Set(runs.map(\.key)).count > 1 else { return whole } return runs.map { run in RecordSection(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] { guard let 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 { guard let at = record.dayParts(byMonth) else { undated.append(record) continue } let key = at.month if let slot = index[key] { runs[slot].records.append(record) } else { index[key] = runs.count runs.append((key, at, [record])) } } var sections = runs.map { run in RecordSection(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 : byDay return 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? { guard let text = record[date].text, !CottonDate.isDayOnly(text) else { return nil } return FaceText.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`. static func dayKey(_ value: RecordValue, calendar: Calendar) -> String? { guard let text = value.text else { return nil } if CottonDate.isDayOnly(text) { return CottonDate.parse(text, calendar: calendar) == nil ? nil : believable(text, calendar: calendar) } return FaceText.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). static func believable(_ day: String, calendar: Calendar) -> String? { guard let at = CottonDate.parse(day, calendar: calendar), CottonDate.believableYears.contains(calendar.component(.year, from: at)) else { return nil } 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. public func chipRecord(_ chosen: Set, now: Date = Date(), calendar: Calendar = .current) -> [String: RecordValue]? { guard let chips, let column = column(chips.column) else { return nil } let words = (column.choices ?? []).filter(chosen.contains) guard !words.isEmpty else { return nil } var data = chips.sends data[column.key] = .list(words.map(RecordValue.text)) if let date, self.column(date)?.type == .date { data[date] = .text(CottonDate.format(now)) } if let byDay, self.column(byDay)?.type == .date, let today = FaceText.dayKey(CottonDate.format(now), calendar: calendar) { data[byDay] = .text(today) } return data } } extension FaceText { /// 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. public static func 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. public static func choiceLine(_ value: RecordValue) -> String? { let words = choices(value).map { $0.replacingOccurrences(of: "_", with: " ") } return words.isEmpty ? nil : words.joined(separator: " \u{00B7} ") } }