Cotton code
201 lines · 9.3 KB · SwiftRaw
// Keys that let a list ask a question and a page gather what belongs to its// record: a slip's typed answers (`answers` — "Same as Example Person?" Merge// / Different, "Is this Example?" Yes / Not them), a list section that draws a// few of its records (`limit`) with a row opening the whole, several across// (`columns`) and merged with other tables' records linked the same way// (`with`), and a page section of the record's other links ("Also linked",// `links`). Each is drawn once, for any table that names it (People was the// first: the person page's sections, the suggestions and the faces to confirm).//// The reading lives here, pure, so the rules are settled by tests;// `SlipFace` and `RecordsSection` only draw them.import CottonKitimport CottonValuesimport Foundation/// A slip's answers: the choice column they write, the words each value is/// offered as, and the values in which the question is still open (`when`;/// a blank value is always open).public typealias SlipAnswers = DefinitionRecordAnswersextension DefinitionRecordAnswers {    public init(column: String, values: [String: String], when: [String] = [], leaves: Bool = true, primary: String? = nil) {        self.init(_generated: (), column: column, values: values)        self.when = when        self.leaves = leaves        self.primary = primary    }}/// Another table's records a list section merges in: those whose `link`/// column names the page's record.public typealias SectionLink = DefinitionSectionLinkextension DefinitionSectionLink {    public init(table: String, link: String) { self.init(_generated: (), table: table, link: link) }}/// The page section of the record's other links: every table but `except`.public typealias LinkedSection = DefinitionLinkedSectionextension DefinitionLinkedSection {    public init(except: [String] = []) {        self.init(_generated: ())        self.except = except    }}/// One of a record's links as the engine answers it in the record's `links`/// value: the table and id it opens, and what its row says.public struct LinkedRecord: Hashable, Sendable, Identifiable {    public var table: String    public var id: String    public var title: String?    public var container: String?    /// "scheduled" (a day it is due or starts) or anything else (a day it    /// was made).    public var whenKind: String?    public var when: String?    /// `when` as the core resolved it.    public var whenParts: DayParts?    /// The table and the id together: one record linked from two tables is    /// two rows.    public var key: String { "\(table):\(id)" }}extension TableDefinition {    /// Whether the slip's question is answered: its reply column holds the    /// owner's words (`reply`, `QuestionKeys`), or its answer column holds a    /// value that is not blank and not one of `when`. A table with neither    /// answers nothing.    public func isAnswered(_ record: TableRecord) -> Bool {        if let reply = slip.reply, !RecordValue.isBlank(record[reply.column]) { return true }        guard let answers = slip.answers else { return false }        let value = record[answers.column]        guard !RecordValue.isBlank(value), let text = value.text else { return false }        return !answers.when.contains(text)    }    /// The verbs the slip offers while its question is open, each the value    /// it writes and its words: the `primary` one first, then the column's    /// own choice order (a JSON object keeps no order); values the column    /// does not offer come after, by value. None once answered, or with no    /// answers.    public func answerVerbs(_ record: TableRecord) -> [(value: String, words: String)] {        guard let answers = slip.answers, !isAnswered(record) else { return [] }        let order = column(answers.column)?.choices ?? []        let offered = order.filter { answers.values[$0] != nil }        let rest = answers.values.keys.filter { !order.contains($0) }.sorted()        let all = offered + rest        let ranked = answers.primary.map { primary in all.filter { $0 == primary } + all.filter { $0 != primary } } ?? all        return ranked.compactMap { value in answers.values[value].map { (value, $0) } }    }    /// The record's other links, from its `links` value (a list of objects    /// the engine answers), less the tables `section` leaves out and any    /// link missing its table or id. One record linked twice is one row.    public func linkedRecords(of record: TableRecord, in section: LinkedSection) -> [LinkedRecord] {        guard case .list(let items) = record["links"] else { return [] }        var seen = Set<String>()        return items.compactMap { item -> LinkedRecord? in            guard case .object(let link) = item,                let table = link["table"]?.text, !table.isEmpty,                let id = link["id"]?.text, !id.isEmpty,                !section.except.contains(table)            else { return nil }            let row = LinkedRecord(                table: table, id: id, title: link["title"]?.text, container: link["container"]?.text,                whenKind: link["when_kind"]?.text, when: link["when"]?.text,                whenParts: link["@day_parts"].flatMap { parts in                    if case .object(let parts) = parts { return parts["when"].flatMap(DayParts.init) }                    return nil                })            return seen.insert(row.key).inserted ? row : nil        }    }}/// One row of a list section: a record and the table it is of, so records/// of several tables (`with`) can stand in one run.public struct SectionRow: Identifiable, Hashable, Sendable {    public var definition: TableDefinition    public var record: TableRecord    public var id: String { "\(definition.id):\(record.id)" }    public init(definition: TableDefinition, record: TableRecord) {        self.definition = definition        self.record = record    }    /// Several tables' records in one run, newest first by each table's own    /// `date`; a record with no date goes last, and ties keep the order they    /// came in (the section's own table first).    public static func merged(_ rows: [SectionRow]) -> [SectionRow] {        func day(_ row: SectionRow) -> Date? {            row.definition.date.flatMap { row.record[$0].text }.flatMap { FaceText.parse($0)?.date }        }        return rows.enumerated().sorted { a, b in            switch (day(a.element), day(b.element)) {            case let (x?, y?) where x != y: return x > y            case (.some, nil): return true            case (nil, .some): return false            default: return a.offset < b.offset            }        }.map(\.element)    }}extension LinkedRecord {    /// What the row is called: its title, else the kind's word — a record    /// that names nothing still says what it is.    public var rowTitle: String {        if let title = title?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty {            // The first line, as a note borrows its body's.            return String((title.split(separator: "\n").first.map(String.init) ?? title).prefix(60))        }        return BadgeKind.label(forKind: table)    }    /// "Todo in Garden · due Mon 10 Aug", "Note · written 2d ago".    /// `definition` is the linked record's own table's, whose words say its date.    public func caption(of definition: TableDefinition?, now: Date = Date(), calendar: Calendar = .current) -> String {        LinkedRecordText.caption(            kind: table, container: container,            when: LinkedRecordText.whenLabel(                words: definition?.linkedWhen, whenKind: whenKind, day: whenParts))    }}/// The words a record listed OUTSIDE its own tool wears. Moved here from the/// old person page's "Also linked", which wrote them first.public enum LinkedRecordText {    /// WHICH date a linked row is showing, said in the words its table's    /// definition gives (`linked_when`), each literally true of its record:    ///    ///     due Mon 10 Aug              a scheduled day, by default    ///     starts Mon 10 Aug 7:30 pm   an event's (`scheduled`)    ///     written 2d ago              a note's made day (`made`)    ///     added 2d ago                a made day, by default    ///     No date                     nothing resolvable at all    ///    /// A scheduled day reads as a day and a time, a made day through the    /// app's relative rule. No table is known here by its id.    public static func whenLabel(words: LinkedWhen?, whenKind: String?, day: DayParts?) -> String {        guard let day else { return CottonStrings.linkedNoDate }        if whenKind == "scheduled" {            return (words?.scheduled ?? ShellLines.line("definitions", "linked.due")).replacingOccurrences(of: "{when}", with: day.full)        }        return (words?.made ?? ShellLines.line("definitions", "linked.added")).replacingOccurrences(of: "{when}", with: day.recent)    }    /// The kind word, the container when the data knows one, and the    /// when-clause, joined by the app's middot.    public static func caption(kind: String, container: String?, when: String) -> String {        let word = BadgeKind.label(forKind: kind)        let name = container?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""        let head = name.isEmpty ? word : "\(word) in \(name)"        return "\(head) \u{00B7} \(when)"    }}