Cotton code
350 lines · 16.2 KB · SwiftRaw
// What the one input does with a line of words: the core reads it// (`shell.input {op: "line"}`, crates/cotton-ffi/src/methods/shell_input.rs:// where it stands, a date, a time, a project's or person's name, a leading// verb, which record a command names) into the writes its commit takes, and// the shell only hands them on. This model takes the words, asks the core// what they write, commits `writes` as they are (`{op: "commit"}`), says the// core's `said` or `refusal`, offers a `which` ask's candidates for a pick// (the chosen record is sent again with the same words), and follows// `opens`. A `model` ask is not sent anywhere: the session inbox is gone// (Nov 2026), and the change the words made is the whole answer. What the "+" attached goes// onto a thought said here, through the store (`attach`).//// A create the store answers with a question rather than a record ("From// which one?", `CreateQuestion`) is answered with `answer`.import CottonKitimport CottonValuesimport Foundationimport Observation/// What one line of words came to — the change it wrote, and/// what the input has to say about it. All nil: nothing was done (blank words).public struct OneInputResult: Equatable, Sendable {    /// What the input's note says: why nothing was written, or what to know    /// about what was.    public enum Said: Equatable, Sendable {        /// They were understood and not done: refused, read-only, already so.        case notDone        /// Written, with a line beside it (kept as a todo, words not used).        case aside    }    /// The words as sent.    public var words: String    /// The one write the words made, for the surface's receipt.    public var change: ChangeRecord?    /// The table the change was written to.    public var table: TableDefinition?    /// The store's question before it would make the record; nothing was    /// made, and the words stay in the bar until an answer makes it.    public var question: CreateQuestion?    /// The records the words could name, two or more: the person picks one,    /// and the words are sent again with it (`submit(record:)`).    public var which: [Candidate]?    /// Where a spoken "open …" / "go to …" takes the person; nothing was    /// written.    public var open: Route?    /// The note's lines ("No todos matched “milk”"), joined.    public var said: String?    public var saidKind: Said?    public init(        words: String, change: ChangeRecord? = nil, table: TableDefinition? = nil,        which: [Candidate]? = nil, said: String? = nil, saidKind: Said? = nil, question: CreateQuestion? = nil,        open: Route? = nil    ) {        self.which = which        self.question = question        self.open = open        self.words = words        self.change = change        self.table = table        self.said = said        self.saidKind = said == nil ? nil : saidKind    }    /// One record a `which` ask offers.    public struct Candidate: Decodable, Equatable, Sendable {        public let table: String        public let id: String        public let title: String    }    static func notDone(_ words: String, _ line: String) -> OneInputResult {        OneInputResult(words: words, said: line, saidKind: .notDone)    }}@MainActor@Observablepublic final class OneInputModel {    /// Where the input stands.    public enum Place: Equatable, Sendable {        /// The board, with the switcher's project (nil is All).        case board(project: String?)        /// One table's list, with the switcher's project; `holding` is the        /// link every record of a narrowed list holds (a parent's        /// records), which a record added here is made with.        case list(table: TableDefinition, project: String?, holding: [String: RecordValue] = [:])        /// One record's page; `project` is the switcher's.        case page(table: TableDefinition, id: String, project: String?)        /// A blank page of one table, before its record exists: `preset` is        /// what the page shows and the record is created with.        case blank(table: TableDefinition, preset: [String: RecordValue], project: String?)        /// A thought ABOUT one record, from its page's menu ("Add a thought        /// about this"): the page wears no box (an imported chat, an email        /// thread — a box there reads as a reply box), and whatever is said        /// is kept as a thought on that record, never read as a change.        case about(table: TableDefinition, id: String)    }    public var place: Place    /// A line is on its way: a second send waits for it.    public private(set) var isSending = false    private let core: any CottonCalling    private let records: any Records    private let definitions: TableDefinitions    private let now: () -> Date    private let timeZone: TimeZone    public init(        place: Place, core: any CottonCalling, records: any Records, definitions: TableDefinitions,        now: @escaping () -> Date = Date.init, timeZone: TimeZone = .current    ) {        self.place = place        self.core = core        self.records = records        self.definitions = definitions        self.now = now        self.timeZone = timeZone    }    static var stillSending: String { ShellLines.line("input", "model.still_sending") }    /// The words, read by the core where the input stands and written as    /// it answers. What the "+" attached (`attaching`) goes with the words    /// onto a thought said here, and the words are then never read.    /// - Parameters:    ///   - spoken: the words were dictated: a command or a thought, never a    ///     record (the core's rule).    ///   - record: the candidate the person chose from a `which` ask.    public func submit(        _ text: String, attaching pictures: [CapturedPicture] = [], spoken: Bool = false, record: String? = nil    ) async -> OneInputResult {        let words = text.trimmingCharacters(in: .whitespacesAndNewlines)        guard !words.isEmpty else { return OneInputResult(words: words) }        guard !isSending else { return .notDone(words, Self.stillSending) }        isSending = true        defer { isSending = false }        if !pictures.isEmpty { return await attach(pictures, saying: words) }        let read: LineRead        do {            read = try await core.call(CottonMethod.shellInput, lineAsk(words, spoken: spoken, record: record), as: LineRead.self)        } catch {            return .notDone(words, Self.unsaved(error))        }        if let refusal = read.refusal { return .notDone(words, read.said ?? refusal) }        if let which = read.asks?.first(where: { $0.kind == "which" })?.candidates, !which.isEmpty {            return OneInputResult(words: words, which: which, said: read.said, saidKind: .notDone)        }        var result = OneInputResult(words: words, said: read.said, saidKind: .aside)        if let opens = read.opens {            result.open = opens.id.map { .tableRecord(table: opens.table, id: $0) } ?? BoardLayout.listRoute(forTable: opens.table)        }        guard case .array(let writes) = read.writes, !writes.isEmpty else { return result }        let committed: InputCommitted        do {            committed = try await core.call(CottonMethod.shellInput, commitAsk(read.writes, words: words), as: InputCommitted.self)        } catch {            return .notDone(words, Self.unsaved(error))        }        if let refusal = committed.refusal { return .notDone(words, refusal) }        let last = writes.last        result.change = committed.written        result.table = last?["kind"]?.string == "thought" ? definitions.playing(.thought) : definitions[last?["table"]?.string ?? ""]        if let said = last?["said"]?.string, result.change != nil {            result.change?.said = ChangeSaid(kind: "added", said: said)        }        return result    }    /// `shell.input {op: line}`'s request: where the input stands, the words.    private func lineAsk(_ words: String, spoken: Bool, record: String?) -> JSONValue {        var ask: [String: JSONValue] = [            "op": "line", "at": at, "words": .string(words), "timezone": .string(timeZone.identifier),            "now": .string(ISO8601DateFormatter().string(from: now())),        ]        if spoken { ask["spoken"] = .bool(true) }        if let record { ask["record"] = .string(record) }        return .object(ask)    }    private func commitAsk(_ writes: JSONValue, words: String) -> JSONValue {        .object(["op": "commit", "writes": writes, "words": .string(words), "timezone": .string(timeZone.identifier)])    }    /// Where the input stands, as the line op takes it.    private var at: JSONValue {        func place(_ fields: [String: JSONValue?]) -> JSONValue { .object(fields.compactMapValues { $0 }) }        let project = { (id: String?) in id.map(JSONValue.string) }        switch self.place {        case .board(let id):            return .object(["board": place(["project": project(id)])])        case .list(let table, let id, let holding):            return .object(["list": place(["table": .string(table.id), "project": project(id),                                           "holding": holding.isEmpty ? nil : DeckEditor.json(holding)])])        case .page(let table, let record, let id):            return .object(["page": place(["table": .string(table.id), "id": .string(record), "project": project(id)])])        case .blank(let table, let preset, let id):            return .object(["page": place(["table": .string(table.id), "preset": DeckEditor.json(preset), "project": project(id)])])        case .about(let table, let record):            return .object(["about": place(["table": .string(table.id), "id": .string(record)])])        }    }    /// `shell.input {op: line}`'s answer.    struct LineRead: Decodable {        let writes: JSONValue        let asks: [Ask]?        let opens: Opens?        let refusal: String?        let said: String?        struct Ask: Decodable {            let kind: String            let candidates: [OneInputResult.Candidate]?        }        struct Opens: Decodable {            let table: String            let id: String?        }    }    // ── A thought, with where it was said ──    /// Keeps the words as a thought said in `definition`'s tool — on the    /// record when there is one. Its receipt says so (`said`, else where it    /// was kept), with Undo.    private func keep(        _ words: String, in definition: TableDefinition?, recordId: String?,        attachments: [CaptureAttachment] = [], said: String? = nil    ) async -> OneInputResult {        guard let keeper = records as? any ThoughtKeepingRecords,            definition.map({ keeper.keepsThoughts(table: $0.id) }) ?? true        else {            return .notDone(words, ThoughtKept.nowhere)        }        do {            var change = try await keeper.keepThought(                words, table: definition?.id, recordId: recordId, attachments: attachments)            let kept = definition.map { recordId == nil ? ThoughtKept.among($0) : ThoughtKept.on($0) } ?? ThoughtKept.saved            change.said = ChangeSaid(kind: "added", said: said ?? kept)            return OneInputResult(words: words, change: change, table: definitions.playing(.thought))        } catch {            return .notDone(words, Self.unsaved(error))        }    }    /// What the "+" attached, with the words beside it, onto a thought said    /// here (architect 6 Oct 07:25Z: one attach act everywhere): on a page,    /// on that record, which shows it; on a list, in that tool — except a    /// list that takes files, where the words are the files' caption.    private func attach(_ pictures: [CapturedPicture], saying words: String) async -> OneInputResult {        let attachments = pictures.map(\.attachment)        let kinds = pictures.map(\.kind)        switch place {        case .list(let table, _, _) where Self.takesFiles(table):            return await caption(pictures, saying: words, on: table)        case .list(let table, _, _):            return await keep(                words, in: table, recordId: nil, attachments: attachments,                said: ThoughtKept.added(kinds, to: table.plural))        case .page(let table, let id, _), .about(let table, let id):            let record = (try? await records.get(table: table.id, id: id)) ?? nil            let title = record?.said?.slip.name ?? "this \(table.name.lowercased())"            return await keep(                words, in: table, recordId: id, attachments: attachments, said: ThoughtKept.added(kinds, to: title))        case .board, .blank:            return .notDone(words, ThoughtKept.nowhere)        }    }    /// Photos, Videos and Documents: the lists whose records ARE the files    /// the "+" picks (`takes_files`).    static func takesFiles(_ table: TableDefinition) -> Bool {        table.takesFiles    }    /// The pick already made each file's own record (`captureMedia`), so on a    /// list that takes files the words beside it are that record's caption —    /// its table's title column — never a thought kept there (ruling 6 Oct).    /// The receipt is the "+"'s; it offers no Undo, as the files stay, and    /// one is taken off from its own page.    private func caption(_ pictures: [CapturedPicture], saying words: String, on table: TableDefinition) async        -> OneInputResult    {        var last: ChangeRecord?        do {            for picture in pictures {                guard let own = definitions[picture.kind.rawValue], let column = own.column(own.title), !column.readonly                else { return .notDone(words, Self.uncaptioned(picture.kind)) }                last = try await records.update(table: own.id, id: picture.recordId, patch: [column.key: .text(words)])            }        } catch {            return .notDone(words, Self.unsaved(error))        }        guard var change = last else { return .notDone(words, ThoughtKept.nowhere) }        change.said = ChangeSaid(kind: "added", said: ThoughtKept.added(pictures.map(\.kind), to: table.plural))        change.undoable = false        return OneInputResult(words: words, change: change, table: definitions[pictures.last?.kind.rawValue ?? ""] ?? table)    }    /// A picked file whose table gives it no caption to write.    static func uncaptioned(_ kind: CaptureMediaKind) -> String {        let what = switch kind {        case .photo: ShellLines.line("input", "attached.photo")        case .video: ShellLines.line("input", "attached.video")        case .document: ShellLines.line("input", "attached.file")        }        return ShellLines.line("input", "caption_unwritable", ["what": "\(what)"])    }    // ── The store's question ──    /// Re-sends the create `asked` was asked about with `option` in its    /// column: the record it makes, another question, or why not.    public static func answer(        _ asked: CreateQuestion, _ option: CreateQuestion.Option, records: any Records, definitions: TableDefinitions    ) async -> OneInputResult {        do {            var change = try await records.create(table: asked.table, data: asked.answered(option))            if asked.openCreated, let row = change.after {                change.created = RecordLink(table: asked.table, id: row.id)            }            return OneInputResult(words: asked.words, change: change, table: definitions[asked.table])        } catch var again as CreateQuestion {            again.words = asked.words            again.openCreated = asked.openCreated            if again.table.isEmpty {                again.table = asked.table                again.data = asked.answered(option)            }            return OneInputResult(words: asked.words, question: again)        } catch {            var refused = OneInputResult.notDone(asked.words, unsaved(error))            refused.question = asked            return refused        }    }    static func unsaved(_ error: Error) -> String {        // The core's own sentence, never a raw error (R6: a failure never        // prints a table, a column or a type name to the person).        if let refused = error as? CottonCallError { return ShellLines.line("input", "not_saved_said", ["message": "\(refused.message)"]) }        return ShellLines.line("input", "not_saved")    }}