// 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.importCottonKitimportCottonValuesimportFoundation/// 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).publictypealiasSlipAnswers = DefinitionRecordAnswersextensionDefinitionRecordAnswers {publicinit(column: String, values: [String: String], when: [String] = [], leaves: Bool = true, primary: String? = nil) {self.init(_generated: (), column: column, values: values)self.when = whenself.leaves = leavesself.primary = primary }}/// Another table's records a list section merges in: those whose `link`/// column names the page's record.publictypealiasSectionLink = DefinitionSectionLinkextensionDefinitionSectionLink {publicinit(table: String, link: String) { self.init(_generated: (), table: table, link: link) }}/// The page section of the record's other links: every table but `except`.publictypealiasLinkedSection = DefinitionLinkedSectionextensionDefinitionLinkedSection {publicinit(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.publicstructLinkedRecord: Hashable, Sendable, Identifiable {publicvar table: Stringpublicvar id: Stringpublicvar title: String?publicvar container: String?/// "scheduled" (a day it is due or starts) or anything else (a day it/// was made).publicvar whenKind: String?publicvar when: String?/// `when` as the core resolved it.publicvar whenParts: DayParts?/// The table and the id together: one record linked from two tables is/// two rows.publicvar key: String { "\(table):\(id)" }}extensionTableDefinition {/// 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.publicfunc isAnswered(_ record: TableRecord) -> Bool {iflet reply = slip.reply, !RecordValue.isBlank(record[reply.column]) { returntrue }guardlet answers = slip.answers else { returnfalse }let value = record[answers.column]guard !RecordValue.isBlank(value), let text = value.text else { returnfalse }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.publicfunc answerVerbs(_ record: TableRecord) -> [(value: String, words: String)] {guardlet 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 + restlet ranked = answers.primary.map { primary in all.filter { $0 == primary } + all.filter { $0 != primary } } ?? allreturn 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.publicfunc linkedRecords(of record: TableRecord, in section: LinkedSection) -> [LinkedRecord] {guardcase .list(let items) = record["links"] else { return [] }var seen = Set<String>()return items.compactMap { item -> LinkedRecord? inguardcase .object(let link) = item,let table = link["table"]?.text, !table.isEmpty,let id = link["id"]?.text, !id.isEmpty, !section.except.contains(table)else { returnnil }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 inifcase .object(let parts) = parts { return parts["when"].flatMap(DayParts.init) }returnnil })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.publicstructSectionRow: Identifiable, Hashable, Sendable {publicvar definition: TableDefinitionpublicvar record: TableRecordpublicvar id: String { "\(definition.id):\(record.id)" }publicinit(definition: TableDefinition, record: TableRecord) {self.definition = definitionself.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).publicstaticfunc 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 inswitch (day(a.element), day(b.element)) {caselet (x?, y?) where x != y: return x > ycase (.some, nil): returntruecase (nil, .some): returnfalsedefault: return a.offset < b.offset } }.map(\.element) }}extensionLinkedRecord {/// What the row is called: its title, else the kind's word — a record/// that names nothing still says what it is.publicvar rowTitle: String {iflet title = title?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty {// The first line, as a note borrows its body's.returnString((title.split(separator: "\n").first.map(String.init) ?? title).prefix(60)) }returnBadgeKind.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.publicfunc 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.publicenumLinkedRecordText {/// 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.publicstaticfunc whenLabel(words: LinkedWhen?, whenKind: String?, day: DayParts?) -> String {guardlet day else { returnCottonStrings.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.publicstaticfunc 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)" }}