Cotton code
416 lines · 18.3 KB · SwiftRaw
// A built-in tool's table, edited from the tool's own page (architect STEP 2a,// piece 4): its picture (a photo in this database, or the shipped one),// its look (the slip's title and how much of it shows, its lines// under it and its trailing word), its stacks (groups on or off, and the face their piles are drawn// with), its acts (the lines of its list's menu, shown, hidden and// reordered — only the ones the table already offers) and its columns (the// person's own added, shipped ones hidden; a shipped column is FIXED: its// engine reads it, so the editor never offers to retype or remove one).//// ONE WRITE, the core's: `definitions.saveTable`, which is `update_definition`// — the same keys and refusals an assistant gets — answered with the receipt// and the undo that puts back what was drawn. The editor sends only the keys// it changed, a shipped column named by its key alone, and draws whatever the// core then answers; it decides nothing the core decides.//// What it starts from is the table as the database draws it now// (its row in `definitions.catalogue`) beside the row this app ships for it// (its acts, so a hidden one can be shown again).import CottonKitimport CottonValuesimport Foundationimport Observation@MainActor@Observablefinal class TableEditorModel {    /// One line of the list's menu the table offers (`links` or `menu`).    struct Act: Identifiable, Equatable {        /// What makes it the same act across files (the core's identity).        let id: String        /// `links` or `menu`.        let key: String        let label: String        var shown: Bool        let raw: JSONValue    }    /// A shipped column: fixed — only hidden or shown.    struct FixedColumn: Identifiable, Equatable {        let key: String        let name: String        let type: String        var hidden: Bool        let isTitle: Bool        var id: String { key }    }    /// A column the person added (`own_…`).    struct OwnColumn: Identifiable, Equatable {        let key: String        var name: String        var type: String        var choices: [String]        var hidden: Bool        var id: String { key }    }    /// What an added column may be (the core's `OWN_COLUMN_TYPES`).    nonisolated static let ownTypes = ["text", "longtext", "date", "time", "number", "amount", "choice", "bool", "url"]    /// What a slip's title may show: the face's own (nil), a few lines, or    /// all of it (0).    nonisolated static let titleLineChoices: [Int?] = [nil, 1, 2, 3, 0]    /// The faces a stack is piled from (`TableGroups.Stack`).    nonisolated static let faces = TableGroups.Stack.allCases.map(\.rawValue)    /// The column types a slip's words are read from.    nonisolated static let slipTypes: Set<String> = ["text", "longtext", "choice", "date", "time", "number", "amount", "url"]    let table: String    private let core: any CottonCalling    private let toasts: ToastCenter?    private let shipped: JSONValue?    private(set) var name = ""    private(set) var isLoaded = false    private(set) var isSaving = false    /// The core's refusal of the last read or save, in its words.    private(set) var refusal: String?    private(set) var picture: JSONValue = .null    private var pictureChange: JSONValue?    var acts: [Act] = []    var stacked = false    var face = TableGroups.Stack.slips.rawValue    var slipTitle = ""    var slipSubtitle: [String] = []    var slipTrailing: String?    /// How many lines of the title a slip shows: nil the face's own, 0 all.    var slipTitleLines: Int?    /// False when the slip's lines are not a plain list of columns (a    /// sentence), which this editor leaves as it is.    private(set) var subtitleEditable = true    var fixed: [FixedColumn] = []    var own: [OwnColumn] = []    /// The table as it was drawn when read, and the state read from it.    private var drawn: JSONValue = .null    private var start: Snapshot?    private struct Snapshot: Equatable {        var acts: [Act]        var stacked: Bool        var face: String        var slipTitle: String        var slipSubtitle: [String]        var slipTrailing: String?        var slipTitleLines: Int?        var fixed: [FixedColumn]        var own: [OwnColumn]    }    init(table: String, core: any CottonCalling, toasts: ToastCenter? = nil, shipped: JSONValue? = nil) {        self.table = table        self.core = core        self.toasts = toasts        self.shipped = shipped    }    /// The built-in tool a Tools-screen key opens, as this app ships it: the    /// table whose `tool.key` it is (`people` → `person`).    nonisolated static func table(forTool key: String, in definitions: [TableDefinition]) -> TableDefinition? {        definitions.first { $0.tool?.key == key }    }    // ── reading ────────────────────────────────────────────────────────────    func load() async {        do {            // The database's catalogue, asked fresh: an edit just saved is what this reads.            let rows = try await DefinitionCatalogues.ask(core).tables.compactMap { try? JSONDecoder().decode(JSONValue.self, from: $0) }            guard let row = rows.first(where: { $0["id"]?.string == table }) else {                refusal = ShellLines.line("editing", "table.this_table_is_not")                return            }            read(row)            refusal = nil        } catch let error as CottonCallError {            refusal = error.message        } catch let error as CatalogueRefusal {            refusal = error.description        } catch {            refusal = error.localizedDescription        }    }    private func read(_ row: JSONValue) {        drawn = row        picture = row["picture"] ?? shipped?["picture"] ?? .null        pictureChange = nil        name = row["plural"]?.string ?? table        let title = row["title"]?.string ?? ""        let columns = row["columns"]?.array ?? []        let shippedKeys = Set((shipped?["columns"]?.array ?? columns).compactMap { $0["key"]?.string })        fixed = columns.compactMap { column in            guard let key = column["key"]?.string, !key.hasPrefix(ColumnDefinition.ownPrefix), shippedKeys.contains(key) else { return nil }            return FixedColumn(                key: key, name: column["name"]?.string ?? Self.words(key), type: column["type"]?.string ?? "text",                hidden: column["hidden"]?.bool == true, isTitle: key == title)        }        own = columns.compactMap { column in            guard let key = column["key"]?.string, key.hasPrefix(ColumnDefinition.ownPrefix) else { return nil }            return OwnColumn(                key: key, name: column["name"]?.string ?? Self.words(key), type: column["type"]?.string ?? "text",                choices: column["choices"]?.strings ?? [], hidden: column["hidden"]?.bool == true)        }        acts = Self.acts(drawn: row, shipped: shipped ?? row, key: "links") + Self.acts(drawn: row, shipped: shipped ?? row, key: "menu")        if let groups = row["groups"], case .object = groups {            stacked = true            face = groups["stack"]?.string ?? face        } else {            stacked = false            face = shipped?["groups"]?["stack"]?.string ?? TableGroups.Stack.slips.rawValue        }        let slip = row["slip"] ?? .null        slipTitle = slip["title"]?.string ?? title        switch slip["subtitle"] {        case .string(let one)?: slipSubtitle = [one]; subtitleEditable = true        case .array?: slipSubtitle = slip["subtitle"]?.strings ?? []; subtitleEditable = slip["subtitle"]?.strings != nil        case nil, .null?: slipSubtitle = []; subtitleEditable = true        default: slipSubtitle = []; subtitleEditable = false        }        slipTrailing = slip["trailing"]?.string        slipTitleLines = slip["title_lines"]?.int        start = snapshot        isLoaded = true    }    /// The acts the table offers under `key`: the ones drawn now, in their    /// order and shown, then the ones its file offers that are hidden.    private static func acts(drawn: JSONValue, shipped: JSONValue, key: String) -> [Act] {        let now = drawn[key]?.array ?? []        let offered = shipped[key]?.array ?? []        let act = { (raw: JSONValue, shown: Bool) in            Act(id: identity(key, raw), key: key, label: raw["label"]?.string ?? "", shown: shown, raw: raw)        }        let drawnActs = now.map { act($0, true) }        let hidden = offered.filter { raw in !drawnActs.contains { $0.id == identity(key, raw) } }.map { act($0, false) }        return drawnActs + hidden    }    /// The core's identity of an act: a link's table, route and filter; a    /// menu line's route.    nonisolated static func identity(_ key: String, _ raw: JSONValue) -> String {        let parts: JSONValue = key == "links"            ? .array([raw["table"] ?? .null, raw["path"] ?? .null, raw["where"] ?? .null])            : raw["path"] ?? .null        let encoder = JSONEncoder()        encoder.outputFormatting = .sortedKeys        return (try? encoder.encode(parts)).flatMap { String(data: $0, encoding: .utf8) } ?? ""    }    /// A title-lines choice in words: "As drawn", "2 lines", "All of it".    nonisolated static func titleLinesWords(_ lines: Int?) -> String {        switch lines {        case nil: ShellLines.line("editing", "table.as_drawn")        case 0?: ShellLines.line("editing", "table.all_of_it")        case 1?: "1 line"        case let count?: "\(count) lines"        }    }    nonisolated static func words(_ key: String) -> String {        let spaced = key.replacingOccurrences(of: ColumnDefinition.ownPrefix, with: "").replacingOccurrences(of: "_", with: " ")        return spaced.prefix(1).uppercased() + spaced.dropFirst()    }    private var snapshot: Snapshot {        Snapshot(            acts: acts, stacked: stacked, face: face, slipTitle: slipTitle, slipSubtitle: slipSubtitle,            slipTrailing: slipTrailing, slipTitleLines: slipTitleLines, fixed: fixed, own: own)    }    // ── editing ────────────────────────────────────────────────────────────    /// The columns a slip's words can be read from: shown, of a type a line    /// says, the person's own included.    var slipColumns: [(key: String, name: String)] {        fixed.filter { !$0.hidden && Self.slipTypes.contains($0.type) }.map { ($0.key, $0.name) }            + own.filter { !$0.hidden && Self.slipTypes.contains($0.type) }.map { ($0.key, $0.name) }    }    /// The text columns a slip's title can be.    var titleColumns: [(key: String, name: String)] {        fixed.filter { $0.type == "text" }.map { ($0.key, $0.name) } + own.filter { $0.type == "text" }.map { ($0.key, $0.name) }    }    func moveAct(_ id: String, by offset: Int) {        guard let at = acts.firstIndex(where: { $0.id == id }) else { return }        let to = at + offset        guard acts.indices.contains(to), acts[to].key == acts[at].key else { return }        acts.swapAt(at, to)    }    func toggleSubtitle(_ key: String) {        if let at = slipSubtitle.firstIndex(of: key) { slipSubtitle.remove(at: at) } else { slipSubtitle.append(key) }    }    /// Add a column of the person's own; false (and a refusal) when the name    /// says nothing or names one already there, or a choice has no choices.    @discardableResult    func addColumn(name: String, type: String, choices: [String] = []) -> Bool {        let words = name.trimmingCharacters(in: .whitespacesAndNewlines)        let slug = words.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "_" }.joined()            .split(separator: "_").joined(separator: "_")        let ascii = slug.unicodeScalars.allSatisfy { $0.isASCII }        let key = ColumnDefinition.ownPrefix + slug        let picked = choices.map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }        guard !slug.isEmpty, ascii, slug.first?.isLetter == true else {            refusal = ShellLines.line("editing", "table.name_the_column_in")            return false        }        guard !own.contains(where: { $0.key == key }), !fixed.contains(where: { $0.key == key }) else {            refusal = ShellLines.line("editing", "table.is_already_a_column", ["words": "\(words)"])            return false        }        guard Self.ownTypes.contains(type), type != "choice" || !picked.isEmpty else {            refusal = ShellLines.line("editing", "table.a_choice_column_needs")            return false        }        own.append(OwnColumn(key: key, name: words, type: type, choices: type == "choice" ? picked : [], hidden: false))        refusal = nil        return true    }    func removeOwn(_ key: String) {        own.removeAll { $0.key == key }        slipSubtitle.removeAll { $0 == key }        if slipTrailing == key { slipTrailing = nil }    }    var hasOwnPicture: Bool { picture != (shipped?["picture"] ?? .null) }    var picturePhoto: String? { picture["object"] == nil ? picture["photo"]?.string : nil }    var drawnPicture: ToolPicture? {        guard picture != .null, let data = try? JSONEncoder().encode(picture) else { return nil }        return (try? JSONDecoder().decode(DefinitionToolPicture.self, from: data))?.drawn    }    func choosePicture(_ photo: String) {        picture = .object(["photo": .string(photo)])        pictureChange = picture == drawn["picture"] ? nil : picture    }    func clearPicture() {        picture = shipped?["picture"] ?? .null        pictureChange = picture == drawn["picture"] ? nil : .null    }    var hasChanges: Bool { start != nil && (snapshot != start || pictureChange != nil) }    /// The write's arguments: the table and each key that changed.    var request: [String: JSONValue] {        guard let start else { return [:] }        var request: [String: JSONValue] = ["table": .string(table)]        if let pictureChange { request["picture"] = pictureChange }        if fixed != start.fixed || own != start.own {            let shipped: [JSONValue] = fixed.map { column in                column.hidden ? .object(["key": .string(column.key), "hidden": .bool(true)]) : .object(["key": .string(column.key)])            }            let added: [JSONValue] = own.map { column in                var object: [String: JSONValue] = [                    "key": .string(column.key), "name": .string(column.name), "type": .string(column.type),                ]                if column.type == "choice" { object["choices"] = .array(column.choices.map(JSONValue.string)) }                if column.hidden { object["hidden"] = .bool(true) }                return .object(object)            }            request["columns"] = .array(shipped + added)        }        for key in ["links", "menu"] {            let now = acts.filter { $0.key == key }            let was = start.acts.filter { $0.key == key }            if now.map(\.id) != was.map(\.id) || now.map(\.shown) != was.map(\.shown) {                request[key] = .array(now.filter(\.shown).map(\.raw))            }        }        if stacked != start.stacked || face != start.face {            if stacked {                var groups: [String: JSONValue]                if case .object(let held)? = drawn["groups"] { groups = held }                else if case .object(let offered)? = shipped?["groups"] { groups = offered }                else { groups = [:] }                groups["stack"] = .string(face)                request["groups"] = .object(groups)            } else {                request["groups"] = .null            }        }        if slipTitle != start.slipTitle || slipSubtitle != start.slipSubtitle || slipTrailing != start.slipTrailing            || slipTitleLines != start.slipTitleLines        {            var slip: [String: JSONValue]            if case .object(let held)? = drawn["slip"] { slip = held } else { slip = [:] }            slip["title"] = .string(slipTitle)            if subtitleEditable {                slip["subtitle"] = slipSubtitle.isEmpty ? .null : .array(slipSubtitle.map(JSONValue.string))            }            slip["trailing"] = slipTrailing.map(JSONValue.string) ?? .null            slip["title_lines"] = slipTitleLines.map { JSONValue.number(Double($0)) } ?? .null            request["slip"] = .object(slip)        }        return request    }    // ── writing ────────────────────────────────────────────────────────────    /// Write what changed, as one act; the receipt carries its Undo. True    /// when it was written (or there was nothing to write).    @discardableResult    func save() async -> Bool {        let request = request        guard request.count > 1 else { return true }        isSaving = true        defer { isSaving = false }        do {            let act = try await core.pageAct(CottonMethod.definitionsSaveTable, JSONValue.object(request))            refusal = nil            DefinitionCatalogues.shared.invalidate(core)            Self.tablesChanged()            if let toasts {                let undo = act.undo                toasts.show(act.receipt ?? "Saved", undo: undo.map { undo in { Task { await self.takeBack(undo) } } })            }            await load()            return true        } catch let error as CottonCallError {            refusal = error.message        } catch {            refusal = error.localizedDescription        }        return false    }    /// Put back what the save changed.    func takeBack(_ undo: ActUndo) async {        do {            let act = try await core.takeBack(undo)            DefinitionCatalogues.shared.invalidate(core)            Self.tablesChanged()            toasts?.show(act.receipt ?? "Undone")            await load()        } catch let error as CottonCallError {            toasts?.show(error.message, tone: .error)        } catch {            toasts?.show(error.localizedDescription, tone: .error)        }    }    /// The window's lists read the definitions again (the core's own `data`    /// event says so too; this is the editor not waiting for it).    private nonisolated static func tablesChanged() {        NotificationCenter.default.post(name: .toolPackagesChanged, object: nil)    }}