// What a card drawn off a record (Home's, a search's, a customer's) reads// beyond the core's words: the pages its card turns to, its places under// their labels, a rating, the values stored under its places, a delivery's// states, the ways a person is reached, its file. A deck's card is answered// whole by the core (`shell.deck`, `DeckCard.answered`) and is never filled// here; on any card the phone reads only what the person sees once it is// held (its related lists' counts).importCottonFacesimportCottonKitimportCottonPaperimportCottonValuesimportSwiftUIenumDeckCardFill {enumRelatedCountFailure: Error { case missingTotal, noCore }/// The card with what its record and its table say beyond the core's/// words. `definition` is the table the deck's card target names; with/// none, the card turns to no pages and its places stand under no label.staticfunc filled(_ card: DeckCard, record: TableRecord, definition: TableDefinition?) -> DeckCard {var filled = card// An absent picture must stay absent all the way to the face.ifcase .text(let key)? = filled.fields["photo"], key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { filled.fields.removeValue(forKey: "photo") } filled.record = record.id filled.pages = pages(definition, record: record) filled.labels = labels(definition) filled.stars = stars(definition, record: record) filled.stored = stored(definition, record: record) filled.reach = reach(record) filled.file = AttachmentValue.read(record["storage_path"])?.refifDefinitionCardKind(rawValue: card.face) == .nancyDelivery { filled.delivery = KitchenDeliveryState.of(record) }return filled }/// The columns a card turns to (`card.pages`) that hold words, in order,/// each under its column's label.staticfunc pages(_ definition: TableDefinition?, record: TableRecord) -> [CardPage] {guardlet definition, let names = definition.card?.pages else { return [] }return names.compactMap { name inguardlet text = record[name].text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else { returnnil }returnCardPage(label: definition.column(name)?.label ?? name, text: text, markdown: definition.setsMarkdown(name)) } }/// The labels a card's places stand under, read off its table: each/// slot under its explicit card label or the first column filling it,/// every column under its own.staticfunc labels(_ definition: TableDefinition?) -> CardLabels {guardlet definition else { returnCardLabels() }var labels = CardLabels()for field in definition.card?.fields ?? [] {let label = field.label.map { ShellLines.line("cards", $0) } ?? field.column.flatMap { definition.column($0)?.label }guardlet label else { continue } labels.bySlot[field.slot.rawValue] = labels.bySlot[field.slot.rawValue] ?? label }for column in definition.columns { labels.byColumn[column.key] = column.label }return labels }/// The rating its facts name in the rating column, out of five.staticfunc stars(_ definition: TableDefinition?, record: TableRecord) -> Double? {guardlet facts = definition?.card?.fields.first(where: { $0.slot == .facts }) else { returnnil }let columns = [facts.column].compactMap { $0 } + facts.alsoguard columns.contains(KitchenColumns.rating), let value = record[KitchenColumns.rating].number, (0...Self.most).contains(value) else { returnnil }return value }/// The most stars a rating holds.staticlet most: Double = 5/// The value stored in the column that fills each slot, as kept (a/// state's "running", a dish's kind), by slot: the first column filling it./// The state place's set yes/no flag (`also`) stands first, by its key: a/// film converting on the Mac stores `needs_mac`, whatever its status.staticfunc stored(_ definition: TableDefinition?, record: TableRecord) -> [String: String] {var stored: [String: String] = [:]for field in definition?.card?.fields ?? [] {if field.slot == .state, let flag = field.also.first(where: { record[$0].bool == true || record[$0].number == 1 }) { stored[field.slot.rawValue] = flagcontinue }guard stored[field.slot.rawValue] == nil, let column = field.column, let text = record[column].text else { continue } stored[field.slot.rawValue] = text }return stored }/// The numbers and addresses a person's record holds, and their/// thread's channel.staticfunc reach(_ record: TableRecord) -> CardReach {func list(_ key: String) -> [String] {switch record[key] {case .list(let items): return items.compactMap { $0.text }case .text(let text): return [text]default: return [] } }let phones = list("phones")let emails = list("emails").filter { $0.contains("@") }let channel = record["thread_channel"].textreturnCardReach(phones: phones, emails: emails, channel: channel, call: ContactHandoff.call(phones: phones) != nil, message: ContactHandoff.message(phones: phones, channel: channel) != nil, email: emails.first.flatMap { ContactHandoff.link(.mail, ContactTarget(value: $0, kind: .email)) } != nil) }/// The definition's related lists counted over their whole filtered read,/// each said by the core (`count.words`) in its table's line/// (`cards.opened.related.<table>`, its plural forms). A list whose table/// the kit has no line for says its count beside its own label/// (`opened.related.labelled`, "Stories: 1"), which has no singular to/// say, so never "1 Stories". @MainActor staticfunc relatedCounts(_ record: TableRecord, definition: TableDefinition?, store: any Records, core: (any CottonCalling)?) asyncthrows -> [CardRelatedCount] {var counts: [CardRelatedCount] = []for related in definition?.related ?? [] where related.column != nil && related.applies(to: record) {guardlet core else { throwRelatedCountFailure.noCore }let page = tryawait store.list(table: related.table, project: nil, query: nil, page: 0,where: related.whereValues(parent: record), limit: 1)guardlet count = page.total else { throwRelatedCountFailure.missingTotal }let own = "opened.related.\(related.table)"let line = ShellLines.shipped("cards", own + ".other") == nil ? "opened.related.labelled" : ownlet said = tryawait core.call(CottonMethod.countWords,CountLines.Request(n: count, set: "cards", line: line, fills: ["label": related.label], units: nil),as: CountLines.Said.self).words counts.append(CardRelatedCount(id: related.table, said: said, count: count)) }return counts }}/// A card as the deck hands it to its face: filled with its readings/// (`DeckCardFill`), those off the store read once per record and kept.structDeckFilledCard<Content: View>: View {let card: DeckCardlet record: TableRecord @ViewBuilder let content: (DeckCard) -> Content @Environment(\.faceChoiceTable) privatevar faceChoiceTable @Environment(\.deckCardTarget) privatevar target @Environment(\.tableDefinitions) privatevar definitions @Environment(\.records) privatevar store @Environment(\.cottonCore) privatevar core @Environment(\.faceOpened) privatevar opened @Environment(Navigator.self) privatevar navigator: Navigator? @Environment(\.toolDefinitions) privatevar tools @State privatevar related: [CardRelatedCount] = [] @State privatevar relatedReadFailed = false @State privatevar readKey: String?var body: someView {let definition = target.flatMap { definitions[$0.target.table] } ?? definitions[faceChoiceTable]// A deck's card is the core's, whole; any other is filled here.var filled = card.answered ? card : DeckCardFill.filled(card, record: record, definition: definition)let key = reading(filled) filled.related = readKey == key ? related : [] filled.relatedReadFailed = readKey == key && relatedReadFailedreturn content(filled) .environment(\.faceRelatedOpening, { table inguardlet relation = definition?.related?.first(where: { $0.table == table }),let route = GroupOpening.related(relation, record: record, title: filled.text("title"), tables: definitions.all, tools: tools.all) else { return } navigator?.push(route) }) .preference(key: FanPageReadingPreference.self, value: FanPageReading(filled: key == nil || readKey == key)) .task(id: key) {await read(filled, definition: definition)guard !Task.isCancelled else { return } readKey = key } }/// What is read off the store, read again when its record — or, for an/// album, its count — changes; nothing for every other card.func reading(_ filled: DeckCard) -> String? {if opened && definitionHasRelated { return"related|\(record.id)|\(definitions.stamp ?? 0)|\(record.values)" }returnnil }privatevar definitionHasRelated: Bool {let definition = target.flatMap { definitions[$0.target.table] } ?? definitions[faceChoiceTable]return definition?.related?.contains(where: { $0.column != nil }) == true }privatefunc read(_ filled: DeckCard, definition: TableDefinition?) async {guardlet store else { return }if opened && definitionHasRelated {do { related = tryawaitDeckCardFill.relatedCounts(record, definition: definition, store: store, core: core) relatedReadFailed = false } catch { related = [] relatedReadFailed = true } } }}extensionTableDefinition {/// Whether `key` holds Markdown: its column says so, or the card's place/// it fills does (a note's body, `CardField.markdown`) — the definition's/// word, never the face's name.func setsMarkdown(_ key: String) -> Bool {if column(key)?.markdown == true { returntrue }return card?.fields.contains { $0.column == key && $0.markdown } ?? false }/// Whether the card's body holds Markdown: a search hit's snippet and/// title are set as its page is.var bodySetsMarkdown: Bool { card?.fields.first { $0.slot == .body }?.column.map(setsMarkdown) ?? false }}