// What a column value reads as on a face: one short line of type, by the // column's type. Pure, so the words under a slip are settled by a test rather // than by reading a view body. import CottonKit import CottonValues import Foundation public enum FaceText { /// The value as a face writes it, or nil when there is nothing to write. /// `links` answers a link column's target by id with that record's title. public static func line( _ value: RecordValue, words: ResolvedWords? = nil, column: ColumnDefinition?, links: [String: String] = [:], currency: String? = nil, calendar: Calendar = .current, locale: Locale = .current, readsPlaceholder: Bool = true, now: Date = Date(), unitWords: [String: String] = [:] ) -> String? { guard let column else { return value.text } if column.isSecret, column.reveal != nil { return value.isNull ? nil : "••••••••" } // A blank value reads its column's placeholder on a face. The reading // layer (`TableDefinition+Reading`) asks without it: it says which // words are a placeholder, so a face can draw them in pencil and a // subtitle can leave a blank column out. if readsPlaceholder, RecordValue.isBlank(value), let placeholder = column.placeholder { return placeholder } // The core said this column (`column_words`): draw its words, never our own. if let words { return words.said } switch column.type { // Account numbers reach Swift already resolved by the core to their ending. case .accountNumber: return value.text case .text where column.format == .words: return value.text.flatMap(PlainWords.sentence) // An app's id the definition names (`labels`) reads as its words; // else the built-in reading. case .text where column.format == .appName: if let raw = value.text, let label = column.labels?[raw] { return label } return CallApp.name(value.text) case .text: // A token the definition names reads as its words, and a token // it does not name reads as nothing — a slug never reaches a // face (the core's `fact_words` reads labels the same way). if let labels = column.labels, !column.multiple { return value.text.flatMap { labels[$0.trimmingCharacters(in: .whitespaces)] }.flatMap { $0.isEmpty ? nil : $0 } } // Their clock, said only when it is not this phone's own. if column.zone { return ZoneClock.short(zone: value.text, now: Date()) } // Several values: each, joined by the page's separator. if column.multiple { return values(value).nilIfEmpty?.joined(separator: " \u{00B7} ") } return value.text.map(firstLine) case .url: // The address as written: a face never shortens what a tap opens. return value.text case .longtext: return value.text // A place reads as its words, picked or kept. case .place: return value.text case .choice where column.format == .words: return value.text.flatMap(PlainWords.sentence) case .choice: if column.week { return week(value, column: column) } if column.multiple { guard let labels = column.labels else { return choiceLine(value) } let words = choices(value).map { labels[$0] ?? $0.replacingOccurrences(of: "_", with: " ") } return words.isEmpty ? nil : words.joined(separator: " \u{00B7} ") } // A choice's own words when the column names them ("perceptual // hash", "API key" for `api_key`), else the value read as words // with its first letter raised ("bank_statement" is "Bank // statement"). if let value = value.text, let label = column.labels?[value] ?? column.choiceNames?[value] { return label } return value.text.map(ChoiceWords.label) case .date: // Every other date is said by the core (`column_words`), drawn above. return nil case .time, .bytes, .number: // A clock, a size and a count are said by the core // (`column_words`), drawn above. return nil case .amount: // An amount is said by the core (`column_words`, the money // transform), drawn above; a face never spells money itself. return nil case .bool: return value.bool.map { $0 ? column.label : nil } ?? nil case .link: // Several targets (a list, or the JSON array an engine writes // into text): each one's title that is known, joined. var seen: Set = [] let ids = (column.multiple ? values(value) : linkIDs(value)).filter { seen.insert($0).inserted } let names = ids.compactMap { links[$0] } return names.isEmpty ? nil : names.joined(separator: " \u{00B7} ") case .photo: return nil case .file: if case .object(let file) = value { return file["name"]?.text } return nil } } /// Links are one id or a list of ids; the same face draws both. public static func linkIDs(_ value: RecordValue) -> [String] { if case .list(let values) = value { var seen: Set = [] return values.compactMap(\.text).filter { seen.insert($0).inserted } } return value.text.map { [$0] } ?? [] } /// The value as a slip or a card writes it: a long text's opening lines /// with its Markdown stripped — a slip is prose, never the markers typed /// into a page — and anything else as `line` writes it. public static func slipLine( _ value: RecordValue, words: ResolvedWords? = nil, column: ColumnDefinition?, links: [String: String] = [:], currency: String? = nil, calendar: Calendar = .current, locale: Locale = .current, readsPlaceholder: Bool = true, now: Date = Date(), unitWords: [String: String] = [:] ) -> String? { if column?.type == .longtext { return value.text.flatMap(opening) ?? (readsPlaceholder ? column?.placeholder : nil) } return line(value, words: words, column: column, links: links, currency: currency, calendar: calendar, locale: locale, readsPlaceholder: readsPlaceholder, now: now, unitWords: unitWords) } /// A long text's words without its Markdown (`MarkdownText.stripMarkdown`, /// the one stripper in the app), or nil when nothing but markers was /// written — the slip then draws no empty band. The face's line limit /// decides how much of it shows. public static func opening(_ text: String) -> String? { let prose = MarkdownText.stripMarkdown(text).trimmingCharacters(in: .whitespacesAndNewlines) return prose.isEmpty ? nil : prose } /// A month a value names on its own ("2027-11", a card's expiry): its /// first day in the calendar's zone, else nil. A month is drawn as the /// month and year, never as a day or a clock. static func month(_ iso: String, calendar: Calendar = .current) -> Date? { let parts = iso.split(separator: "-", omittingEmptySubsequences: false) guard iso.count == 7, parts.count == 2, parts[0].count == 4, parts[1].count == 2, let year = Int(parts[0]), let month = Int(parts[1]), (1...12).contains(month) else { return nil } return calendar.date(from: DateComponents(year: year, month: month, day: 1)) } /// An ISO 8601 date ("2026-10-01", read in the calendar's zone as that day) /// or date-time ("2026-10-01T09:30:00Z"). public static func parse(_ iso: String) -> (date: Date, hasTime: Bool)? { parse(iso, calendar: .current) } /// The same, a bare day or a zoneless stamp read in `calendar`. public static func parse(_ iso: String, calendar: Calendar) -> (date: Date, hasTime: Bool)? { if iso.count == 10 { let parts = iso.split(separator: "-").compactMap { Int($0) } guard parts.count == 3 else { return nil } var components = DateComponents() (components.year, components.month, components.day) = (parts[0], parts[1], parts[2]) // The day in the zone it is drawn in, so it never shifts to its neighbour. guard let date = calendar.date(from: components) else { return nil } return (date, false) } if let date = CottonDate.instant(iso) { return (date, true) } // A zoneless stamp is a wall clock read as written in any zone (an // edition's hour in the house's own time), never converted. if iso.contains("T"), let local = CottonDate.parse(iso, calendar: calendar) { return (local, true) } return nil } /// "yyyy-MM-dd" of a date column's value, for grouping by day. public static func dayKey(_ iso: String, calendar: Calendar = .current) -> String? { if iso.count == 10 { return CalendarDates.parseDateKey(iso, calendar: calendar) == nil ? nil : iso } guard let parsed = parse(iso, calendar: calendar) else { return nil } let c = calendar.dateComponents([.year, .month, .day], from: parsed.date) guard let y = c.year, let m = c.month, let d = c.day else { return nil } return String(format: "%04d-%02d-%02d", y, m, d) } static func firstLine(_ text: String) -> String { text.split(whereSeparator: \.isNewline).first.map(String.init) ?? text } } extension Array { /// Nil for an empty array, so a face writes nothing rather than "". var nilIfEmpty: Self? { isEmpty ? nil : self } }