Cotton code
319 lines · 16.9 KB · SwiftRaw
// A note made with + keeps its body and stands at the top of the deck (ship// walk, 29 Oct 2026, build 334 held): a new note's two sentences were// written, yet its card and its reader showed the title alone, and the deck// stayed on the note before at the old count until a search found the new// one at "37 / 37". The deck read itself again only on a sync event, which a// write to a served database need not raise; here no sync event comes at// all, as on that walk.//// Since afdf29b047 the deck reads its cards from the core (`shell.deck`), so// the notebook is the core too: it answers the deck's page as the core does// (`shell_deck.rs`), the newest first with each card's position, and Plus a// new note written by hand (`blank`, "New note"); since 10fc2ac761 Plus's// writing is the core's too (`shell.draft`, `shell.input`), which it answers// as `shell_input_tests.rs` holds. The unit tests' simulator// build links no Rust core, so the core here is the notebook's own answer.#if os(iOS)import CottonFacesimport CottonKitimport CottonValuesimport SwiftUIimport UIKitimport XCTest@testable import CottonUI@MainActorfinal class DeckNewNoteTests: XCTestCase {    /// RULE: a note made with + — its title in the short-text input, then its body on the whole screen, Done — stands first in a deck of the newest first, its card showing the body as written and the counter N+1 of N+1, every time, with no sync event to tell the deck; the store keeps the body.    func testANoteMadeWithPlusStandsFirstWithItsBody() async throws {        XCTAssertTrue(HostedAccessibility.enable(), "the hosted page's accessibility tree is read")        let table = "note-\(UUID().uuidString.prefix(8).lowercased())"        let note = try Self.note(table)        let store = NotebookRecords(note, titles: ["Seeds to buy", "Gate code", "Lamp repair"])        let editor = DeckEditor.standing()        let host = UIHostingController(rootView: AnyView(            DeckSurface(definition: note, filter: [:], view: nil)                .environment(\.records, store)                .environment(\.cottonCore, store)                .environment(\.deckEditor, editor)))        let window = try Self.window(host)        defer { window.isHidden = true }        _ = try await Self.until("the deck reads its three notes", in: host.view) { Self.position(in: host.view) == "1 / 3" ? true : nil }        let made = [("Spare key", "Under the blue pot. Ask Ravi first."),                    ("Train times", "The 7:40 is gone. Take the 8:05 instead."),                    ("Gift ideas", "A teapot for Amma. Books for the boys.")]        for (at, (title, body)) in made.enumerated() {            let count = 3 + at + 1            let plus = try XCTUnwrap(Self.element(labelled: "New note", in: host.view), "the deck's +, named by the definition's create")            XCTAssertTrue(plus.accessibilityActivate(), "the + answers")            _ = try await Self.until("the title's input") { editor.writing?.editor == .line ? true : nil }            editor.commit(title)            _ = try await Self.until("the body's editor, under \(title)") {                editor.writing?.editor == .page && editor.writing?.title == title ? true : nil            }            editor.commit(body)            _ = try await Self.until("the opened note keeps its body") {                editor.draft?.record["body"].text == body && editor.writing == nil ? true : nil            }            XCTAssertEqual(editor.draft?.record["title"].text, title)            XCTAssertTrue(editor.isEditing, "the new note stays open above its acts")            editor.close()            XCTAssertNil(editor.draft, "the hub closes the new note before its deck counter returns")            _ = try await Self.until("\(title) first, with its body, at 1 / \(count)", in: host.view) {                Self.position(in: host.view) == "1 / \(count)" && Self.shows(title, in: host.view)                    && Self.shows(body, in: host.view) ? true : nil            }            let kept = try await store.titled(title)            XCTAssertEqual(kept?["body"].text, body, "the store keeps \(title)'s body")        }    }    // MARK: Fixtures    /// A note on the torn page, its deck the newest first, as the kit's.    static func note(_ table: String) throws -> TableDefinition {        let json = """        {"id":"\(table)","name":"Note","plural":"Notes","builtin":false,         "columns":[{"key":"title","type":"text"},{"key":"body","type":"longtext"},                    {"key":"updated_at","type":"date","readonly":true}],         "title":"title","date":"updated_at","sort":{"column":"updated_at","descending":true},         "project":null,"order":null,         "slip":{"title":"title"},"tile":{"face":"slip-list"},"page":[],"commands":[],"tables":[],         "create":{"label":"New note"},         "card":{"face":"note.page","fields":[{"slot":"title","column":"title"},{"slot":"body","column":"body"}]}}        """        return try JSONDecoder().decode(TableDefinition.self, from: Data(json.utf8))    }    private static func window(_ root: UIViewController) throws -> UIWindow {        let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first,                                  "the host app has no window scene")        let window = UIWindow(windowScene: scene)        window.frame = CGRect(x: 0, y: 0, width: 402, height: 874)        window.rootViewController = root        window.makeKeyAndVisible()        return window    }    /// Polls `read` until it answers, or fails after a few seconds saying    /// what stood under `root`.    private static func until<T>(_ what: String, in root: UIView? = nil, _ read: () -> T?) async throws -> T {        let deadline = Date().addingTimeInterval(8)        while Date() < deadline {            if let found = read() { return found }            try await Task.sleep(for: .milliseconds(20))        }        let seen = root.map { nodes(under: $0).compactMap { node -> String? in            let id = (node as? UIAccessibilityIdentification)?.accessibilityIdentifier ?? ""            let label = node.accessibilityLabel ?? ""            return id.isEmpty && label.isEmpty ? nil : "\(id)=\(label.prefix(40))"        }.joined(separator: " | ") } ?? ""        return try XCTUnwrap(read(), "\(what): never; seen \(seen)")    }    /// Every accessibility node under `root`, depth first.    private static func nodes(under root: NSObject) -> [NSObject] {        var children: [NSObject] = (root.accessibilityElements as? [NSObject]) ?? []        let count = root.accessibilityElementCount()        if children.isEmpty, count > 0, count != NSNotFound {            children = (0..<count).compactMap { root.accessibilityElement(at: $0) as? NSObject }        }        if let view = root as? UIView { children += view.subviews }        return [root] + children.flatMap { nodes(under: $0) }    }    /// The node under `root` whose label is `label` (a hosted page's nodes    /// carry their labels, not their identifiers).    private static func element(labelled label: String, in root: UIView) -> NSObject? {        nodes(under: root).first { $0.accessibilityLabel == label }    }    /// The deck's counter ("2 / 5").    private static func position(in root: UIView) -> String? {        nodes(under: root).lazy.compactMap(\.accessibilityLabel).first { $0.wholeMatch(of: /\d+ \/ \d+/) != nil }    }    /// Whether some node under `root` reads `words`.    private static func shows(_ words: String, in root: UIView) -> Bool {        nodes(under: root).contains { $0.accessibilityLabel?.contains(words) == true }    }}/// A notebook as the core serves it: its notes the newest first, each read/// with its resolved card (`@card`), each write stamped later than the last;/// its deck's pages as `shell.deck` answers them, and nothing else asked of/// the core (refused, as an unknown method is).actor NotebookRecords: Records, CottonCalling {    private let definition: TableDefinition    private var notes: [TableRecord] = []    private var clock = 0    private var drafts = 0    private var changes = 0    init(_ definition: TableDefinition, titles: [String]) {        self.definition = definition        for title in titles.reversed() {            clock += 1            notes.append(TableRecord(id: UUID().uuidString, values: ["title": .text(title), "updated_at": .text(Self.stamp(clock))]))        }    }    private static func stamp(_ tick: Int) -> String {        String(format: "2026-10-29T21:%02d:%02dZ", tick / 60, tick % 60)    }    /// The record as read, with the card the core resolves for it.    private func read(_ record: TableRecord) -> TableRecord {        var record = record        var fields: [String: RecordValue] = ["title": record["title"]]        if let body = record["body"].text { fields["body"] = .text(body) }        record.values[DeckCard.key] = .object(["face": .text("note.page"), "fields": .object(fields)])        return record    }    func titled(_ title: String) -> TableRecord? {        notes.first { $0["title"].text == title }    }    private func change(before: TableRecord?, after: TableRecord?) -> ChangeRecord {        changes += 1        return ChangeRecord(id: "change-\(changes)", byline: "", before: before, after: after.map(read))    }    func tableDefinitions() async throws -> [TableDefinition] { [definition] }    func count(table: String) async throws -> Int { notes.count }    func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage {        var rows = notes.sorted { ($0["updated_at"].text ?? "") > ($1["updated_at"].text ?? "") }        if let query, !query.isEmpty { rows = rows.filter { $0["title"].text?.localizedCaseInsensitiveContains(query) == true } }        return RecordPage(records: page == 0 ? rows.map(read) : [], next: nil, total: rows.count)    }    func get(table: String, id: String) async throws -> TableRecord? {        notes.first { $0.id == id }.map(read)    }    func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord {        clock += 1        var values = data        values["updated_at"] = .text(Self.stamp(clock))        let record = TableRecord(id: UUID().uuidString, values: values)        notes.append(record)        return change(before: nil, after: record)    }    func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord {        guard let at = notes.firstIndex(where: { $0.id == id }) else { throw RecordsError.unknownRecord(id) }        let before = notes[at]        clock += 1        for (key, value) in patch { notes[at].values[key] = value }        notes[at].values["updated_at"] = .text(Self.stamp(clock))        return change(before: before, after: notes[at])    }    func delete(table: String, id: String) async throws -> ChangeRecord {        guard let at = notes.firstIndex(where: { $0.id == id }) else { throw RecordsError.unknownRecord(id) }        return change(before: notes.remove(at: at), after: nil)    }    func reorder(table: String, ids: [String]) async throws -> ChangeRecord { throw RecordsError.noOrderColumn(table) }    func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord {        throw RecordsError.unknownRecord(id)    }    func undo(change: String) async throws -> ChangeRecord { throw RecordsError.unknownChange(change) }    // MARK: The core    private struct DeckAsk: Decodable {        let table: String        let cursor: Int        let limit: Int    }    func callRaw(_ method: String, requestJSON: String) async throws -> String {        switch method {        case CottonMethod.shellDeck: return try deck(requestJSON)        case CottonMethod.shellDraft, CottonMethod.shellOpened, CottonMethod.shellInput: return try await input(method, requestJSON)        default: return #"{"ok":false,"error":{"code":"unknown_method","message":"Synthetic notebook answers the deck and its writing alone"}}"#        }    }    /// Plus's writing, as the core answers it (`shell_input_tests.rs`): a    /// draft begun, the title asked in the short-text input, the note made on    /// its commit with its body asked next on the whole screen (a torn page    /// tags no part, so the shell says `follows`), and the body written.    private func input(_ method: String, _ requestJSON: String) async throws -> String {        let ask = try JSONDecoder().decode(JSONValue.self, from: Data(requestJSON.utf8))        let answer: RecordValue        switch (method, ask["op"]?.string, ask["writes"]?["kind"]?.string) {        case (CottonMethod.shellDraft, _, _):            drafts += 1            answer = .object(["id": .text("draft-\(drafts)"), "table": .text(definition.id), "values": .object([:]), "card": .null, "made": .null])        case (CottonMethod.shellOpened, _, _):            answer = .object(["acts": .list([]), "parts": .object([:])])        case (CottonMethod.shellInput, "ask", _):            answer = .object(["editor": .text("line"), "words": .text(""), "keeps_words": .bool(true),                              "writes": .object(["kind": .text("new"), "table": .text(definition.id), "draft": ask["draft"].map(Self.value) ?? .null, "column": .text("title")])])        case (CottonMethod.shellInput, "commit", "new"):            let title = ask["words"]?.string ?? ""            let made = try await create(table: definition.id, data: ["title": .text(title)])            let id = made.after?.id ?? ""            answer = .object(["change": Self.wire(made), "made": .text(id), "record": record(id),                              "next": .object(["editor": .text("page"), "title": .text(title), "words": .text(""), "keeps_words": .bool(false),                                               "writes": .object(["kind": .text("column"), "table": .text(definition.id), "id": .text(id), "column": .text("body")])])])        case (CottonMethod.shellInput, "commit", "column"):            let id = ask["writes"]?["id"]?.string ?? ""            let column = ask["writes"]?["column"]?.string ?? ""            let written = try await update(table: definition.id, id: id, patch: [column: .text(ask["words"]?.string ?? "")])            answer = .object(["change": Self.wire(written), "record": record(id)])        default:            return #"{"ok":false,"error":{"code":"refused","message":"Synthetic notebook writes a new note alone"}}"#        }        let data = String(decoding: try JSONEncoder().encode(answer), as: UTF8.self)        return #"{"ok":true,"data":\#(data)}"#    }    private func record(_ id: String) -> RecordValue {        notes.first { $0.id == id }.map { .object(["id": .text($0.id), "data": .object($0.values)]) } ?? .null    }    private static func wire(_ change: ChangeRecord) -> RecordValue {        .object(["id": .text(change.id), "byline": .text("You"), "record_id": (change.after ?? change.before).map { .text($0.id) } ?? .null, "undoable": .bool(true)])    }    private static func value(_ json: JSONValue) -> RecordValue {        json.string.map(RecordValue.text) ?? .null    }    private func deck(_ requestJSON: String) throws -> String {        let ask = try JSONDecoder().decode(DeckAsk.self, from: Data(requestJSON.utf8))        let rows = notes.sorted { ($0["updated_at"].text ?? "") > ($1["updated_at"].text ?? "") }        let end = min(rows.count, ask.cursor + ask.limit)        let cards: [[String: RecordValue]] = rows.indices.filter { $0 >= ask.cursor && $0 < end }.map { at in            let note = rows[at]            var slots: [String: RecordValue] = ["title": note["title"]]            if let body = note["body"].text { slots["body"] = .text(body) }            return [                "id": .text(note.id), "face": .text("note.page"), "slots": .object(slots),                "reach": .object(["phones": .list([]), "emails": .list([]), "call": .bool(false), "message": .bool(false), "email": .bool(false)]),                "position": .text("\(at + 1) / \(rows.count)"), "tap": .object(["card": .text("open.reading")]),                "record": .object(["id": .text(note.id), "data": .object(note.values)]),            ]        }        let page: [String: RecordValue] = [            "table": .text(ask.table), "cards": .list(cards.map(RecordValue.object)), "acts": .object([:]),            "labels": .object(["by_slot": .object([:]), "by_column": .object([:])]),            "count": .number(Double(rows.count)), "hand": .list([]),            "plus": .object(["does": .text("blank"), "label": .text(definition.create?.label ?? ""), "doors": .list([])]),            "next": end < rows.count ? .number(Double(end)) : .null,        ]        let data = String(decoding: try JSONEncoder().encode(RecordValue.object(page)), as: UTF8.self)        return #"{"ok":true,"data":\#(data)}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {}    func close() async {}}#endif