Cotton code
577 lines · 27.8 KB · SwiftRaw
// What a conversation page holds while it is on screen: the thread's// messages — the records of the definition's `conversation.table` whose link// columns name the thread — oldest first, and the one write the page makes,// a message sent from its input. The send goes through the act the layout// names (`send`) where it names one, else through the `create` verb like every// other write, and the list is read again after it.//// The messages are read narrowed by the `list` verb's `where`, once per link// column (a message names its thread on any of them, and `where` matches all// it is given), and the reads are merged by record id. Only the latest page// of messages is read at first; older history is read a page at a time on// request, and no more than a thousand messages are ever held.//// A definition's `also` tables (a session's turns beside its messages) are// read the same way and merged into one stream, `items`: by moment, a turn// before a message at the same instant, each table keeping its own order on a// tie — the order `SessionFacts.chat` drew a session's transcript in. Nothing// is ever sent into an `also` table. An `also` table whose face is `slip`// (a session's runs) takes its place in the same stream by its moment and is// drawn as its own table's slip, between the notes.import CottonValuesimport Foundationimport Observation@MainActor@Observablepublic final class ConversationModel {    public enum Phase: Equatable {        case loading        case loaded        case failed    }    public let layout: ConversationLayout    /// The thread's record id.    public let thread: String    public private(set) var messages: [TableRecord] = []    /// The messages and every `also` table's records, merged into the one    /// stream the page draws.    public private(set) var items: [ConversationItem] = []    public private(set) var phase: Phase = .loading    /// A send on its way: the input waits for it.    public private(set) var sending = false    public private(set) var retrying: Set<String> = []    public private(set) var binning: Set<String> = []    public var threadRecord: TableRecord?    /// The message a Cotton chat's next message answers, while the composer says so.    public var replyingTo: TableRecord?    /// The newest message sent from this page, for its receipt, until it is    /// dismissed or the next send replaces it.    public private(set) var lastChange: ChangeRecord?    /// The change the receipt took back, so a receipt drawn again for it    /// reads as undone rather than offering its Undo a second time.    private var undoneChange: String?    /// Whether `lastChange` was taken back by its receipt.    public var lastChangeUndone: Bool { lastChange.map { $0.id == undoneChange } ?? false }    private let store: any Records    private var generation = 0    private var nextPages: [String: Int] = [:]    private var loadingMore = false    /// The `also` tables' records as last read, so a page of older messages    /// merges into the same stream.    private var others: [[TableRecord]] = []    /// The message table's definition, which words a note whose body is blank.    private let wording: TableDefinition?    /// The older pages the reader asked for (`loadMore`), kept across a read again.    private var paged: [TableRecord] = []    public var hasMore: Bool { !nextPages.isEmpty && messages.count < 1000 }    public init(        layout: ConversationLayout, thread: String, store: any Records, threadRecord: TableRecord? = nil,        wording: TableDefinition? = nil    ) {        self.wording = wording        self.layout = layout        self.thread = thread        self.store = store        self.threadRecord = threadRecord    }    /// Reads the latest page of the thread's messages, leaving older history    /// for an explicit request (`loadMore`), and every `also` table's records,    /// replacing what is shown. A read that fails after messages were shown    /// keeps them. `anchor`, the message the page opens on, is read too when    /// the latest page does not hold it.    public func load(anchor: String? = nil) async {        generation += 1        let mine = generation        do {            var found: [TableRecord] = []            var next: [String: Int] = [:]            for link in layout.links {                let read = try await store.list(table: layout.table, project: nil, query: nil,                    page: 0, where: [link: .text(thread)])                found.append(contentsOf: read.records)                if let page = read.next { next[link] = page }            }            if let anchor, !found.contains(where: { $0.id == anchor }),                let target = try await store.get(table: layout.table, id: anchor),                layout.links.contains(where: { target[$0].text == thread }) {                found.append(target)            }            guard mine == generation, !Task.isCancelled else { return }            // A read again (a sync, a live cadence) keeps the older pages the            // reader already asked for: only the latest page was read, and            // dropping the rest would throw the reader back to the foot.            let all = paged.isEmpty ? merged(found) : merged(found + paged)            // Nothing moved: nothing is published, so the page is not redrawn            // under a reader who has scrolled up.            if all != messages { messages = all }            if paged.isEmpty { nextPages = next }            // The newest page is drawn now, beside the `also` records last            // read: a session's turns, every page of them, fill in after and            // never hold its messages back.            publish()            guard !layout.also.isEmpty else { return }            var others: [[TableRecord]] = []            for source in layout.also {                others.append(try await read(source.table, links: source.links))            }            guard mine == generation, !Task.isCancelled else { return }            if others != self.others { self.others = others }            publish()        } catch {            guard mine == generation, !(error is CancellationError) else { return }            if messages.isEmpty && items.isEmpty { phase = .failed }        }    }    /// The one stream the page draws, from the messages and `also` records held.    private func publish() {        let drawn = layout.merged(messages: messages, also: others, wording: wording)        if drawn != items { items = drawn }        if phase != .loaded { phase = .loaded }    }    /// Older history is paged, with the previous screen's thousand-message cap.    public func loadMore() async {        guard hasMore, !loadingMore else { return }        loadingMore = true        defer { loadingMore = false }        do {            var found: [TableRecord] = []            var next = nextPages            for (link, page) in nextPages.sorted(by: { $0.key < $1.key }) {                let read = try await store.list(table: layout.table, project: nil, query: nil,                    page: page, where: [link: .text(thread)])                found.append(contentsOf: read.records)                next[link] = read.next            }            // A read again that landed meanwhile does not throw the older            // page away: it is merged into whatever is shown now.            guard !Task.isCancelled else { return }            paged.append(contentsOf: found)            messages = merged(messages + found)            nextPages = next            items = layout.merged(messages: messages, also: others, wording: wording)        } catch { /* A failed older-page read retains the current messages and cursor. */ }    }    private func merged(_ records: [TableRecord]) -> [TableRecord] {        var seen: Set<String> = []        return Array(layout.ordered(records.filter { seen.insert($0.id).inserted }).suffix(1000))    }    /// Every record of `table` naming the thread on any of `links`, merged by    /// id, in the order the reads answered.    private func read(_ table: String, links: [String]) async throws -> [TableRecord] {        var found: [TableRecord] = []        var seen: Set<String> = []        for link in links {            var page: Int? = 0            while let current = page {                let read = try await store.list(                    table: table, project: nil, query: nil, page: current, where: [link: .text(thread)])                for record in read.records where seen.insert(record.id).inserted { found.append(record) }                page = read.next            }        }        return found    }    /// Writes `words` as the owner's message to the thread and reads the    /// thread again; nil when there is nothing to send or a send is already    /// on its way.    @discardableResult    public func send(_ words: String) async throws -> ChangeRecord? {        guard let data = layout.sent(words, thread: thread, record: threadRecord), !sending else { return nil }        sending = true        defer { sending = false }        let change = try await store.create(table: layout.table, data: data)        if layout.usesLocalQueue {            receive(change, words: words.trimmingCharacters(in: .whitespacesAndNewlines))            lastChange = nil        } else { lastChange = change }        await load()        return change    }    /// Failure actions require an unbinned local outgoing slip and conversation.    public func canRetryOrBin(_ message: TableRecord) -> Bool {        if let threadRecord, !threadRecord["trashed_at"].isNull { return false }        guard layout.usesLocalQueue, message["trashed_at"].isNull,              case .failed? = MessageDelivery(message) else { return false }        return true    }    /// Retry the same failed slip. The engine validates the transition and    /// owns the attempt count and external id; no new message is created.    @discardableResult    public func retry(_ message: TableRecord) async throws -> ChangeRecord? {        guard canRetryOrBin(message), !binning.contains(message.id),              !retrying.contains(message.id) else { return nil }        retrying.insert(message.id)        defer { retrying.remove(message.id) }        let change = try await store.update(table: layout.table, id: message.id,            patch: ["send_state": .text("queued")])        receive(change)        lastChange = nil        await load()        return change    }    /// The local engine puts only failed outgoing messages in the bin.    /// Remove this slip and its paged copy as soon as the write is accepted.    @discardableResult    public func binFailed(_ message: TableRecord) async throws -> ChangeRecord? {        guard canRetryOrBin(message), !retrying.contains(message.id),              !binning.contains(message.id) else { return nil }        binning.insert(message.id)        defer { binning.remove(message.id) }        let change = try await store.delete(table: layout.table, id: message.id)        messages.removeAll { $0.id == message.id }        paged.removeAll { $0.id == message.id }        items = layout.merged(messages: messages, also: others, wording: wording)        lastChange = change        await load()        return change    }    private func receive(_ change: ChangeRecord, words: String? = nil) {        guard let after = change.after else { return }        var shown = messages.first { $0.id == after.id } ?? after        shown.values.merge(after.values) { _, updated in updated }        // A write can answer raw columns before its computed display words        // are read. These are the words just accepted by the local engine.        if let words, shown[layout.body].isNull { shown.values[layout.body] = .text(words) }        messages = merged(messages.filter { $0.id != after.id } + [shown])        items = layout.merged(messages: messages, also: others, wording: wording)        phase = .loaded    }    /// The receipt took the sent message `change` (the newest, when nil) back    /// through the verbs itself: remember it and read the thread again. The    /// change stays, so its receipt reads as undone — even drawn again, when    /// the page went and came back.    public func undone(_ change: ChangeRecord? = nil) async {        undoneChange = (change ?? lastChange)?.id        await load()    }    /// Lets go of the receipt without undoing it.    public func dismissChange() {        lastChange = nil    }    /// Takes back a message this page sent, through the `undo` verb, and    /// reads the thread again.    public func undo(_ change: ChangeRecord) async throws {        _ = try await store.undo(change: change.id)        await load()    }}extension ConversationLayout {    /// Whether the owner wrote it.    public func isMine(_ message: TableRecord) -> Bool {        message[mine.column].text.map(mine.values.contains) ?? false    }    /// Oldest first by `at`; a message with no moment goes last, and ties keep    /// the order they were read in.    public func ordered(_ messages: [TableRecord]) -> [TableRecord] {        Self.oldestFirst(messages) { moment(of: $0) }    }    /// A delayed acknowledgement must not reorder a Cotton-sent note.    /// The parts of the day `moment` names.    func day(of message: TableRecord) -> DayParts? {        if usesLocalQueue, MessageDelivery(message) != nil, message["created_at"].text != nil { return message.dayParts("created_at") }        return message.dayParts(at)    }    public func moment(of message: TableRecord) -> String? {        if usesLocalQueue, MessageDelivery(message) != nil,           let created = message["created_at"].text { return created }        return message[at].text    }    /// Oldest first by `moment`; one with no moment goes last, and ties —    /// two moments that are the same instant, however each is written — keep    /// the order they were given in.    static func oldestFirst<T>(_ items: [T], moment: (T) -> String?) -> [T] {        items.enumerated().sorted { a, b in            switch (moment(a.element), moment(b.element)) {            case let (x?, y?) where x != y:                // As moments where both read as one; as text otherwise (an                // ISO instant sorts as its moment within one zone).                if let p = FaceText.parse(x)?.date, let q = FaceText.parse(y)?.date {                    return p == q ? a.offset < b.offset : p < q                }                return x < y            case (_?, nil): return true            case (nil, _?): return false            default: return a.offset < b.offset            }        }.map(\.element)    }    /// The thread's one stream: the `also` tables' records first, each table    /// in the order it was read, then the messages, all put oldest first —    /// so at the same instant a turn comes before a message, and turns keep    /// their own order.    public func merged(messages: [TableRecord], also others: [[TableRecord]], wording: TableDefinition? = nil) -> [ConversationItem] {        var items: [ConversationItem] = []        for (source, records) in zip(also, others) {            for record in records {                items.append(ConversationItem(                    id: "\(source.table):\(record.id)", table: source.table, record: record,                    words: source.body.flatMap { record[$0].text } ?? "",                    mine: source.mine.flatMap { mine in record[mine.column].text.map(mine.values.contains) } ?? false,                    at: record[source.at].text, isMessage: false, media: [], slip: source.face == .slip,                    day: record.dayParts(source.at)))            }        }        for record in messages {            items.append(ConversationItem(                id: "\(table):\(record.id)", table: table, record: record,                words: words(of: record, messages: wording), mine: isMine(record), at: moment(of: record),                isMessage: true, media: mediaKeys(of: record), day: day(of: record)))        }        return Self.oldestFirst(items) { $0.at }    }    /// A message's words: its body, or where that is blank the `blank_body`    /// column as the message definition words it.    public func words(of message: TableRecord, messages: TableDefinition?) -> String {        let said = message[body].text ?? ""        guard said.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, let key = blankBody,            let words = FaceText.line(message[key], words: message.columnWords(key), column: messages?.column(key))        else { return said }        return words    }    /// The media keys a message carries in the `media` column, one a line.    public func mediaKeys(of message: TableRecord) -> [String] {        guard let media = self.media, let text = message[media].text else { return [] }        return text.split(whereSeparator: \.isNewline)            .map { $0.trimmingCharacters(in: .whitespaces) }            .filter { !$0.isEmpty }    }    /// What is handwritten under a note: a message's `footer` column when it    /// holds words; else its status word when it is past the column's first    /// choice (an open message says nothing), then its time. A record of an    /// `also` table has its time alone. `messages` is the message table's    /// definition, for its status column's words.    ///    /// The definition's `footer` names one message column (a session's: its    /// words are the whole line) or several (an imported chat's reactions,    /// delivery and edits: their words go before the status and the time).    /// An envelope's one line (`header_columns`): who it is from — the first    /// envelope column that says something — and its time. The rest of the    /// envelope waits behind a tap (`envelopeLines`).    /// `day` says the day before the time (mail, whose sheets have no day    /// lines between them); `time: false` says who alone.    public func envelopeHead(of message: TableRecord, messages: TableDefinition?, day: Bool = false, time: Bool = true) -> String? {        // No envelope where the message says none of its columns (a        // session's `header_columns` are the thread's own, not a message's).        guard let who = envelopeWho(of: message, messages: messages)?.words else { return nil }        guard time else { return who }        let parts = message.dayParts(at)        let clock = parts?.clock        // A mail's day in the form its page head says it ("Thu 15 Oct,        // 2:00 pm"), never "Yesterday" under a head that wrote the date        // (walker pass 2: one email, three date forms).        let date = parts?.weekdayDate        let when = day ? [date, clock].compactMap { $0 }.joined(separator: ", ") : clock        return [who, when].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " \u{00B7} ")    }    private func envelopeWho(of message: TableRecord, messages: TableDefinition?) -> (key: String, words: String)? {        for key in headerColumns {            if let words = FaceText.line(message[key], words: message.columnWords(key), column: messages?.column(key)), !words.isEmpty { return (key, words) }        }        return nil    }    /// The rest of an envelope, each line named: every column that says    /// something, bar the one the head said and a subject the thread's own    /// head already says (replies' "Re:" set aside).    public func envelopeLines(of message: TableRecord, messages: TableDefinition?, threadTitle: String?) -> [String] {        let said = envelopeWho(of: message, messages: messages)?.key        return headerColumns.compactMap { key in            guard key != said, let column = messages?.column(key),                let line = FaceText.line(message[key], words: message.columnWords(key), column: column), !line.isEmpty            else { return nil }            if let threadTitle, Self.bareSubject(line) == Self.bareSubject(threadTitle) { return nil }            return "\(column.name ?? key): \(line)"        }    }    /// A subject without its reply and forward marks, for telling one    /// conversation's subject from another's.    static func bareSubject(_ subject: String) -> String {        var rest = subject.trimmingCharacters(in: .whitespaces)        while let mark = ["re:", "fwd:", "fw:"].first(where: { rest.lowercased().hasPrefix($0) }) {            rest = String(rest.dropFirst(mark.count)).trimmingCharacters(in: .whitespaces)        }        return rest.lowercased()    }    public func footer(of item: ConversationItem, messages: TableDefinition?, time: Bool = true) -> String? {        let delivery = item.isMessage && usesLocalQueue ? MessageDelivery(item.record) : nil        if let delivery {            guard delivery.isConfirmed else { return nil }            // The declared footer includes the native Sent from Cotton byline.            // Keep it alongside the time after the Mac confirms acceptance.        }        if item.isMessage, case .one(let key)? = self.footer, let words = item.record[key].text,            !words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty        {            return words        }        var parts: [String] = []        if item.isMessage, case .several(let keys)? = self.footer,            let words = metadata(keys, of: item.record, messages: messages)        {            parts.append(words)        }        if item.isMessage, let key = status, let column = messages?.column(key),            let value = item.record[key].text, value != column.choices?.first,            let word = FaceText.line(item.record[key], words: item.record.columnWords(key), column: column)        {            parts.append(word.lowercased())        }        // Queue time keeps the row in place; the footer says when the Mac sent it.        let stamp = item.isMessage ? slipDay(of: item.record) : item.day        if time, let clock = stamp?.clock { parts.append(clock) }        return parts.isEmpty ? nil : parts.joined(separator: " \u{00B7} ")    }    /// The clock under the chat's slip and the deck's slip is the same:    /// an imported moment, or the confirmed send time for a queued message.    private func slipDay(of message: TableRecord) -> DayParts? {        if usesLocalQueue, let delivery = MessageDelivery(message) {            return delivery.isConfirmed ? message.dayParts(at) : nil        }        return day(of: message)    }    /// Who wrote a message, for telling one run of notes from the next: the    /// `color_by` column's value (a group's sender); nil where it holds none.    public func writer(of message: TableRecord) -> String? {        guard let name = message[colorBy].text?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty        else { return nil }        return name    }    /// The key of a message's sender's picture, where the layout names a    /// `photo` column and the message holds one.    public func photoKey(of message: TableRecord) -> String? {        guard let key = photo, let value = message[key].text, !value.isEmpty else { return nil }        return value    }    /// Message columns' words as a face writes them, joined by a dot; nil    /// when none of them holds anything.    public func metadata(_ keys: [String]?, of message: TableRecord, messages: TableDefinition?) -> String? {        // The header can also name the thread's description. When that key        // is the message body, its note already owns the words.        let parts = (keys ?? []).filter { $0 != body }.compactMap { key in FaceText.line(message[key], words: message.columnWords(key), column: messages?.column(key)) }        return parts.isEmpty ? nil : parts.joined(separator: " \u{00B7} ")    }    /// The `header` columns as the page draws them, in order: a line in    /// pencil for each, and a long text — a pull request's description, its    /// reviewers, its checks — whole, read as Markdown, so what the thread is    /// about stands at its top rather than behind "Details". A column with    /// nothing in it is left out.    public func headerPieces(of thread: TableRecord, in definition: TableDefinition) -> [ConversationHeaderPiece] {        header.compactMap { key in            let column = definition.column(key)            guard let text = FaceText.line(thread[key], words: thread.columnWords(key), column: column)?.trimmingCharacters(in: .whitespacesAndNewlines),                !text.isEmpty            else { return nil }            return column?.type == .longtext ? .markdown(text) : .line(text)        }    }    /// "started on mac-b · owner@example.com · 9:04 am" once the thread's    /// `started.at` holds a moment — the `started.words` that hold a value,    /// then the time; nil without one.    public func startedLine(of thread: TableRecord) -> String? {        guard let started = self.started, !RecordValue.isBlank(thread[started.at]) else { return nil }        let words = started.words.compactMap { key -> String? in            guard let text = thread[key].text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else {                return nil            }            return text        }        let time = thread.dayParts(started.at)?.clock ?? ""        var line = words.isEmpty ? ShellLines.line("conversation", "started") : ShellLines.line("conversation", "started_on", ["where": words.joined(separator: " \u{00B7} ")])        if !time.isEmpty { line += " \u{00B7} \(time)" }        return line    }    /// The record a message sent from the input is created with: the fixed    /// `sends` values, the owner as its writer, the words and the thread on    /// the first link column. Nil for words that are only whitespace.    public func sent(_ words: String, thread: String, record: TableRecord? = nil) -> [String: RecordValue]? {        let text = words.trimmingCharacters(in: .whitespacesAndNewlines)        guard sendGate.allows(record), !text.isEmpty, let link = links.first,              record.map(takesWords(on:)) ?? true else { return nil }        if let input = localQueueInput(words: text, thread: thread) { return input }        var data = sends        if data[mine.column] == nil, let owner = mine.values.first { data[mine.column] = .text(owner) }        data[body] = .text(text)        data[link] = .text(thread)        return data    }    /// Whether the thread takes words from here: its layout sends, and the    /// thread has not ended — an ended session has no one to read them.    public func takesWords(on thread: TableRecord) -> Bool {        sendGate.allows(thread) && (ended.map { RecordValue.isBlank(thread[$0]) } ?? true)    }    /// "ended · 6:12 pm" once the thread's `ended` column holds a moment; nil    /// before.    public func endedLine(of thread: TableRecord) -> String? {        guard let ended, !RecordValue.isBlank(thread[ended]) else { return nil }        let time = thread.dayParts(ended)?.clock ?? ""        return time.isEmpty ? "ended" : "ended \u{00B7} \(time)"    }}/// One note of a conversation: a message, or a record of one of the/// definition's `also` tables (a session's turn).public struct ConversationItem: Identifiable, Equatable, Sendable {    /// The table and the record's id, so two tables' ids never meet.    public let id: String    public let table: String    public let record: TableRecord    public let words: String    public let mine: Bool    public let at: String?    /// A record of the conversation's own table, not an `also` one.    public let isMessage: Bool    /// Media keys drawn as prints above the words.    public let media: [String]    /// Drawn as its own table's slip rather than a note (an `also` table    /// whose face is `slip`).    public var slip: Bool = false    /// Its moment's day as the core said it: the conversation's day lines    /// and their grouping read this, never a calendar.    public var day: DayParts? = nil}/// One piece of a conversation's header: a handwritten line, or a long text/// read as Markdown.public enum ConversationHeaderPiece: Equatable, Sendable {    case line(String)    case markdown(String)}