Cotton code
210 lines · 15.0 KB · SwiftRaw
import CottonKitimport Foundationimport XCTest@testable import CottonUI/// Messages' face is one stream of chats (`shell.stream`, 14 Nov 2026): the/// shell draws what the core answers — its order, its count, its marks, what/// the top button holds — and decides only which chat stands in front and/// which chats hold their messages. EVERY ROW IS SYNTHETIC.@MainActor final class ChatStreamTests: XCTestCase {    private static func stream(_ ids: [String], opens: String? = nil, unread: Int = 0) -> String {        let chats = ids.map { #"{"id":"\#($0)","name":"Invented \#($0)","unread":false,"mark":{"id":"whatsapp","label":"WhatsApp"},"replies":false}"# }.joined(separator: ",")        let line = unread > 0 ? #""\#(unread) unread""# : "null"        return #"{"table":"thread","chats":[\#(chats)],"opens":\#((opens ?? ids.first).map { "\"\($0)\"" } ?? "null"),"unread":\#(unread),"unread_line":\#(line),"top":[{"id":"account","label":"Account"},{"id":"new","label":"New chat","route":"/messages/new"}],"search":"Search chats","empty":"No chats yet."}"#    }    /// RULE (owner, 14 Nov 2026): the stream opens on the chat the core names (the newest unread), its count and top button as answered.    func testTheStreamOpensWhereTheCoreSays() async throws {        let core = ScriptedCore([CottonMethod.shellStream: .ok(Self.stream(["a", "b", "c"], opens: "a", unread: 2))])        let model = ChatStreamModel()        await model.read(core: core, table: "thread", query: "", ink: "")        XCTAssertEqual(model.front, "a")        XCTAssertEqual(model.answer?.unreadLine, "2 unread")        XCTAssertEqual(model.answer?.top.map(\.id), ["account", "new"])        XCTAssertEqual(model.answer?.top.last?.route, "/messages/new")        XCTAssertEqual(model.answer?.chats.first?.mark, .init(id: "whatsapp", label: "WhatsApp"))        let first = await core.calls.first        let asked = try XCTUnwrap(first)        XCTAssertFalse(asked.requestJSON.contains("standing"), "the first read stands on nothing: \(asked.requestJSON)")    }    /// RULE: a person standing in the stream hands the core the order they hold, and stays on the chat in front.    func testAStandingStreamHandsItsOrderAndKeepsItsFront() async throws {        let core = ScriptedCore([CottonMethod.shellStream: .ok(Self.stream(["a", "b", "c"]))])        let model = ChatStreamModel()        await model.read(core: core, table: "thread", query: "", ink: "")        model.front = "b"        await core.answer(CottonMethod.shellStream, .ok(Self.stream(["new", "a", "b", "c"], opens: "new")))        await model.read(core: core, table: "thread", query: "", ink: "")        XCTAssertEqual(model.front, "b", "a new chat in front of the stream does not take the hand off the chat it reads")        let last = await core.calls.last        let asked = try XCTUnwrap(last)        XCTAssertTrue(asked.requestJSON.contains(#""standing":["a","b","c"]"#), asked.requestJSON)    }    /// RULE: a search jumps to its first find, stands on nothing, and the chat found stays in front when the search is let go.    func testASearchJumpsAndTheFindStays() async throws {        let core = ScriptedCore([CottonMethod.shellStream: .ok(Self.stream(["a", "b", "c"]))])        let model = ChatStreamModel()        await model.read(core: core, table: "thread", query: "", ink: "")        await core.answer(CottonMethod.shellStream, .ok(Self.stream(["c"])))        await model.read(core: core, table: "thread", query: "", ink: "c")        XCTAssertEqual(model.front, "c")        var last = await core.calls.last        var asked = try XCTUnwrap(last)        XCTAssertTrue(asked.requestJSON.contains(#""ink":"c""#), asked.requestJSON)        XCTAssertFalse(asked.requestJSON.contains("standing"), asked.requestJSON)        await core.answer(CottonMethod.shellStream, .ok(Self.stream(["a", "b", "c"])))        await model.read(core: core, table: "thread", query: "", ink: "")        XCTAssertEqual(model.front, "c")        last = await core.calls.last        asked = try XCTUnwrap(last)        XCTAssertFalse(asked.requestJSON.contains("standing"), "the read after a search takes the stream's own order: \(asked.requestJSON)")    }    /// RULE: a chat that left the stream gives the front back to the core's `opens`; previous and next stop at the ends.    func testTheFrontFallsBackAndTheNeighboursStopAtTheEnds() async {        let core = ScriptedCore([CottonMethod.shellStream: .ok(Self.stream(["a", "b", "c"]))])        let model = ChatStreamModel()        await model.read(core: core, table: "thread", query: "", ink: "")        XCTAssertNil(model.neighbour(-1))        XCTAssertEqual(model.neighbour(1), "b")        model.front = "c"        XCTAssertEqual(model.neighbour(-1), "b")        XCTAssertNil(model.neighbour(1))        await core.answer(CottonMethod.shellStream, .ok(Self.stream(["a", "b"])))        await model.read(core: core, table: "thread", query: "", ink: "")        XCTAssertEqual(model.front, "a")    }    /// RULE: a chat just started holds no message and stands in no stream yet: turned to, it stands in front as a visitor until the stream holds it.    func testAChatJustStartedStandsInFrontUntilTheStreamHoldsIt() async {        let core = ScriptedCore([CottonMethod.shellStream: .ok(Self.stream(["a", "b"]))])        let model = ChatStreamModel()        await model.read(core: core, table: "thread", query: "", ink: "")        await model.turn(to: "new", core: core, table: "thread")        XCTAssertEqual(model.front, "new")        XCTAssertEqual(model.chats.map(\.id), ["new", "a", "b"])        XCTAssertEqual(model.neighbour(1), "a")        await model.read(core: core, table: "thread", query: "", ink: "")        XCTAssertEqual(model.front, "new", "a read that still holds no such chat leaves the visitor in front")        await core.answer(CottonMethod.shellStream, .ok(Self.stream(["new", "a", "b"])))        await model.read(core: core, table: "thread", query: "", ink: "")        XCTAssertNil(model.visitor)        XCTAssertEqual(model.chats.map(\.id), ["new", "a", "b"])        XCTAssertEqual(model.front, "new")        // A chat the stream holds is turned to where it stands.        await model.turn(to: "b", core: core, table: "thread")        XCTAssertEqual(model.front, "b")        XCTAssertNil(model.visitor)    }    /// RULE (paging): only the chat in front and its neighbours are loaded, however many chats stand in the stream.    func testOnlyTheFrontAndItsNeighboursAreInTheWindow() {        XCTAssertEqual(ChatStreamModel.window(at: 0, count: 300, reach: 1), [0, 1])        XCTAssertEqual(ChatStreamModel.window(at: 150, count: 300, reach: 1), [149, 150, 151])        XCTAssertEqual(ChatStreamModel.window(at: 299, count: 300, reach: 1), [298, 299])        XCTAssertEqual(ChatStreamModel.window(at: 0, count: 1, reach: 1), [0])        XCTAssertEqual(ChatStreamModel.window(at: 0, count: 0, reach: 1), [])    }    /// RULE: the flavour says the app is one stream (`fan.stream`), carried to the core as written; the fan's answer names its tool and table, and every other fan says none.    func testTheFlavourAndTheFanSayTheStream() throws {        let fan = try JSONDecoder().decode(FlavourManifest.Fan.self, from: Data(#"{"home":false,"tools":false,"opens":"messages","stream":true}"#.utf8))        XCTAssertTrue(fan.stream)        XCTAssertTrue(String(decoding: try JSONEncoder().encode(fan), as: UTF8.self).contains(#""stream":true"#))        XCTAssertFalse(FlavourManifest.Fan.cottons.stream)        XCTAssertFalse(String(decoding: try JSONEncoder().encode(FlavourManifest.Fan.cottons), as: UTF8.self).contains("stream"))        let answer = try JSONDecoder().decode(FanAnswer.self, from: Data(#"""        {"opens": {"tier": "views", "tool": "messages", "view": "all"}, "root": {"id": "views-messages", "cards": ["all"], "raised": "all"},         "tiles": [], "stream": {"tool": "messages", "table": "thread"}}        """#.utf8))        XCTAssertEqual(answer.stream, .init(tool: "messages", table: "thread"))        let plain = try JSONDecoder().decode(FanAnswer.self, from: Data(#"{"opens": {"tier": "tools", "tool": "home"}, "root": {"id": "tools", "cards": []}, "tiles": []}"#.utf8))        XCTAssertNil(plain.stream)    }    private func source(_ path: String) throws -> String {        SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/\(path)", ownedBy: "messages"))    }    /// RULE (owner, 15 Nov 2026): every move between chats is a plain cut — the tap on Previous or Next and the sideways swipe alike. The chat does not follow the finger and nothing slides; the swipe is the core's to read at the lift.    func testEveryMoveBetweenChatsIsAPlainCut() throws {        let code = try source("Messages/ChatStream.swift")        XCTAssertTrue(code.contains("withTransaction(SplashOverlay.cut) { model.front = id }"), "the chat changes in one frame")        XCTAssertFalse(code.contains("withAnimation"), "nothing in the stream slides to a chat")        XCTAssertFalse(code.contains("ScrollView(.horizontal)"), "no chat follows the finger sideways")        XCTAssertFalse(code.contains(".scrollTargetBehavior"), "nothing pages")        XCTAssertTrue(code.contains(#""ink.contest""#), "the swipe is read by the core")        XCTAssertFalse(code.contains("DragGesture"), "the stream decides no swipe of its own")    }    /// RULE (owner, 15 Nov 2026): ink is read anywhere on the chat; over the messages a stroke is the ink's once its box's narrower side is the core's `bend` and `bend_ratio` of the longer, so a scroll and a sideways swipe never are, however long.    func testAStrokeThatBendsIsTheInks() throws {        let knobs = try JSONDecoder().decode(InkKnobs.Values.self, from: Data(#"""        {"flavours": ["messages"], "tap_travel": 10, "hold_seconds": 0.3, "ink_width": 3, "ink_fade_seconds": 0.6, "doubtful_ink": 0.5,         "provisional_ink": 0.35, "keep_groups": 5000, "surfaces": {"stream": {"bend": 22, "bend_ratio": 0.5, "turn_back": 1.6, "swipe": 70, "swipe_level": 0.5}}}        """#.utf8))        let stream = try XCTUnwrap(knobs.surfaces?["stream"])        XCTAssertFalse(stream.claims(CGSize(width: 6, height: 300), travel: 300), "a scroll")        XCTAssertFalse(stream.claims(CGSize(width: 40, height: 300), travel: 300), "a long scroll on a thumb's arc")        XCTAssertFalse(stream.claims(CGSize(width: 4, height: 60), travel: 60), "an l is the scroll's")        XCTAssertFalse(stream.claims(CGSize(width: 200, height: 30), travel: 200), "a sideways swipe")        XCTAssertTrue(stream.claims(CGSize(width: 40, height: 60), travel: 60), "a c")        XCTAssertTrue(stream.claims(CGSize(width: 120, height: 60), travel: 120), "a tall scratch-out")        XCTAssertFalse(stream.claims(CGSize(width: 150, height: 20), travel: 150), "a flat scratch-out's first leg is a swipe so far")        XCTAssertTrue(stream.claims(CGSize(width: 150, height: 30), travel: 300), "doubled back across the chat: the ink's")        XCTAssertFalse(stream.claims(CGSize(width: 20, height: 200), travel: 420), "a scroll that turns back up is still the scroll's")        XCTAssertEqual(InkContest.travel([CGPoint(x: 0, y: 0), CGPoint(x: 30, y: 40), CGPoint(x: 0, y: 0)]), 100)        XCTAssertEqual(InkContest.box([CGPoint(x: 10, y: 20), CGPoint(x: 50, y: 5), CGPoint(x: 30, y: 80)]), CGSize(width: 40, height: 75))        // A core that names no contested surface (every other app's): nothing is contested.        let plain = try JSONDecoder().decode(InkKnobs.Values.self, from: Data(#"""        {"flavours": ["cotton"], "tap_travel": 10, "hold_seconds": 0.3, "ink_width": 3, "ink_fade_seconds": 0.6, "doubtful_ink": 0.5, "provisional_ink": 0.35, "keep_groups": 5000}        """#.utf8))        XCTAssertNil(plain.surfaces)        // Only the stream hands the ink a contest: a deck's strokes are all the ink's, as they were.        XCTAssertFalse(try source("Deck/DeckSurface.swift").contains("contest:"))        let code = try source("Messages/ChatStream.swift")        XCTAssertTrue(code.contains("reads: { $0.y >= ChatStreamKnobs.lineHeight && $0.y < footTop && $0.x < railLeft }"), "the whole chat above its typing line, left of its rail")        XCTAssertTrue(code.contains("contested: { $0.y > headFoot }"), "under the head a stroke is contested with the scroll")        XCTAssertTrue(code.contains(".scrollDisabled(inkHolds)"))    }    /// RULE (owner, 15 Nov 2026): a rail down the chat's right edge moves through it by date. The core answers a stop a day; the thumb is on the last stop at or above it; a touch on the rail is the rail's alone, never ink; Previous and Next stand at the rail's foot and no longer beside the typing line.    func testTheRailMovesThroughAChatByDate() async throws {        let answer = #"""        {"stops": [{"day": "2026-11-01", "label": "Sun 1 Nov", "at": 0, "message": "a"}, {"day": "2026-11-14", "label": "Yesterday", "at": 0.5, "message": "c"},                   {"day": "2026-11-15", "label": "Today", "at": 1, "message": "e"}],         "previous": "Previous chat", "next": "Next chat", "width": 30, "thumb": 44}        """#        let core = ScriptedCore(["shell.rail": .ok(answer)])        let rail = ChatRailModel()        let held = [ChatRailModel.Message(id: "a", day: "2026-11-01", label: "Sun 1 Nov"), ChatRailModel.Message(id: "b", day: nil, label: nil)]        await rail.read(core: core, messages: held)        XCTAssertEqual(rail.answer?.stops.map(\.label), ["Sun 1 Nov", "Yesterday", "Today"])        let first = await core.calls.first        let asked = try XCTUnwrap(first)        XCTAssertTrue(asked.requestJSON.contains(#""id":"a""#) && asked.requestJSON.contains(#""day":"2026-11-01""#), "the chat's messages and their days are handed to the core: \(asked.requestJSON)")        XCTAssertEqual(rail.stop(at: 0)?.message, "a")        XCTAssertEqual(rail.stop(at: 0.49)?.message, "a")        XCTAssertEqual(rail.stop(at: 0.5)?.message, "c")        XCTAssertEqual(rail.stop(at: 1)?.message, "e")        XCTAssertEqual(rail.stop(at: -1)?.message, "a")        rail.scrolled = 0.6        XCTAssertEqual(rail.stop(stepping: 1)?.label, "Today")        XCTAssertEqual(rail.stop(stepping: -1)?.label, "Sun 1 Nov")        // The same messages are not asked about twice.        await rail.read(core: core, messages: held)        let calls = await core.calls.count        XCTAssertEqual(calls, 1)        XCTAssertNil(ChatRailModel().stop(at: 0.5), "no rail until the core answers one")        let stream = try source("Messages/ChatStream.swift")        XCTAssertTrue(stream.contains("$0.x < railLeft"), "a stroke begun on the rail is never read as ink")        XCTAssertFalse(stream.contains("NavCircle(symbol: \"chevron.left\""), "the pair no longer stands beside the typing line")        let drawn = try source("Messages/ChatRail.swift")        XCTAssertTrue(drawn.contains(#""stream-previous""#) && drawn.contains(#""stream-next""#), "Previous and Next stand at the rail's foot")        XCTAssertTrue(drawn.contains(".gesture("), "the rail's drag is its own, above the chat's scroll")        XCTAssertFalse(drawn.contains("inkWriting"), "the rail reads no ink")    }}