// 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). import CottonFaces import CottonKit import CottonPaper import CottonValues import SwiftUI enum DeckCardFill { enum RelatedCountFailure: 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. static func filled(_ card: DeckCard, record: TableRecord, definition: TableDefinition?) -> DeckCard { var filled = card // An absent picture must stay absent all the way to the face. if case .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"])?.ref if DefinitionCardKind(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. static func pages(_ definition: TableDefinition?, record: TableRecord) -> [CardPage] { guard let definition, let names = definition.card?.pages else { return [] } return names.compactMap { name in guard let text = record[name].text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else { return nil } return CardPage(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. static func labels(_ definition: TableDefinition?) -> CardLabels { guard let definition else { return CardLabels() } 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 } guard let 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. static func stars(_ definition: TableDefinition?, record: TableRecord) -> Double? { guard let facts = definition?.card?.fields.first(where: { $0.slot == .facts }) else { return nil } let columns = [facts.column].compactMap { $0 } + facts.also guard columns.contains(KitchenColumns.rating), let value = record[KitchenColumns.rating].number, (0...Self.most).contains(value) else { return nil } return value } /// The most stars a rating holds. static let 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. static func 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] = flag continue } 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. static func 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"].text return CardReach(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.`, 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 static func relatedCounts(_ record: TableRecord, definition: TableDefinition?, store: any Records, core: (any CottonCalling)?) async throws -> [CardRelatedCount] { var counts: [CardRelatedCount] = [] for related in definition?.related ?? [] where related.column != nil && related.applies(to: record) { guard let core else { throw RelatedCountFailure.noCore } let page = try await store.list(table: related.table, project: nil, query: nil, page: 0, where: related.whereValues(parent: record), limit: 1) guard let count = page.total else { throw RelatedCountFailure.missingTotal } let own = "opened.related.\(related.table)" let line = ShellLines.shipped("cards", own + ".other") == nil ? "opened.related.labelled" : own let said = try await 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. struct DeckFilledCard: View { let card: DeckCard let record: TableRecord @ViewBuilder let content: (DeckCard) -> Content @Environment(\.faceChoiceTable) private var faceChoiceTable @Environment(\.deckCardTarget) private var target @Environment(\.tableDefinitions) private var definitions @Environment(\.records) private var store @Environment(\.cottonCore) private var core @Environment(\.faceOpened) private var opened @Environment(Navigator.self) private var navigator: Navigator? @Environment(\.toolDefinitions) private var tools @State private var related: [CardRelatedCount] = [] @State private var relatedReadFailed = false @State private var readKey: String? var body: some View { 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 && relatedReadFailed return content(filled) .environment(\.faceRelatedOpening, { table in guard let 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)" } return nil } private var definitionHasRelated: Bool { let definition = target.flatMap { definitions[$0.target.table] } ?? definitions[faceChoiceTable] return definition?.related?.contains(where: { $0.column != nil }) == true } private func read(_ filled: DeckCard, definition: TableDefinition?) async { guard let store else { return } if opened && definitionHasRelated { do { related = try await DeckCardFill.relatedCounts(record, definition: definition, store: store, core: core) relatedReadFailed = false } catch { related = [] relatedReadFailed = true } } } } extension TableDefinition { /// 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 { return true } 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 } }