importCottonKitimportCottonValuesimportFoundationimport XCTest@testable importCottonUI/// A tool's views as an outer ring of slips about the fan's pivot (views/// programme, master note 57th–58th amendments). Every view and count is/// invented.@MainActorfinalclassViewRingTests: XCTestCase {func testAnEmptyViewSaysItsOwnWordsWithTheOtherViewsReadCounts() throws {let read = try JSONDecoder().decode(ToolView.Read.self, from: Data(#"{"table":"todo","empty":{"line":"empty_views.todos.today","counts":{"late":"empty_views.todo_late_count"}}}"#.utf8))let late = ToolView(id: "late", label: "Late", count: 7, read: .init(table: "todo"))let upcoming = ToolView(id: "upcoming", label: "Upcoming", count: 16, read: .init(table: "todo")) XCTAssertEqual(read.empty?.line(views: [late, upcoming]), "Nothing due today. 7 late.") XCTAssertEqual(read.emptyLine(views: []), "Nothing due today.") XCTAssertEqual(read.emptyLine(views: [late, upcoming]), "Nothing due today. 7 late.")let fresh = try JSONDecoder().decode(ToolView.Read.self, from: Data(#"{"table":"todo","empty":{"line":"empty_views.todos.today","total":0}}"#.utf8)) XCTAssertNil(fresh.emptyLine(views: [late]), "only the whole-table count decides whether the table is empty")let counted = try JSONDecoder().decode(ToolView.Read.self, from: Data(#"{"table":"todo","empty":{"line":"empty_views.todos.today","total":150}}"#.utf8)) XCTAssertEqual(counted.emptyLine(views: []), "Nothing due today.")var linked = read linked.name = "todos/today" XCTAssertNil(linked.emptyLine(views: [ToolView(id: "today", label: "Today", count: 0, read: fresh)]),"a linked view uses the same whole-table total as its tool's ring") }/// The fan as the core answers it: one tool, its views as given.staticfunc answer(_ tool: String, views: String, current: String? = nil) -> String {let at = current.map { #""\#($0)""# } ?? "null"return #"{"opens":{"tier":"tools","tool":"\#(tool)"},"root":{"id":"tools","cards":["\#(tool)"],"raised":"\#(tool)"},"tiles":[{"key":"\#(tool)","name":"Synthetic","kind":"tool","tool":"\#(tool)","ringed":true,"poster":false,"counted":true,"current":\#(at),"views":\#(views)}]}"# }private actor AnswerCore: CottonCalling {var answers: [String]var asked: [String] = []var gate: CheckedContinuation<Void, Never>?var held = falseinit(_ answers: [String]) { self.answers = answers }func hold() { held = true }func release() { held = false; gate?.resume(); gate = nil }func callRaw(_ method: String, requestJSON: String) asyncthrows -> String { asked.append(requestJSON)if held { await withCheckedContinuation { gate = $0 } }return #"{"ok":true,"data":\#(answers.removeFirst())}"# }func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}func close() {} }/// RULE: only the read last asked lands, and only while its database is the one shown: a read of the database shown before never stands over what is drawn (Settings views came from the previous database, 3b8327e9ce).func testAReadOfTheDatabaseShownBeforeNeverLands() asyncthrows {let views = ToolViews() views.show("synthetic-one")let core = AnswerCore([Self.answer("todos", views: #"[{"id":"late","label":"Late","count":9,"default":true,"read":{"table":"todo"}}]"#)])await core.hold()let reading = Task { tryawait views.reload(core: core, database: "synthetic-one") }whileawait core.asked.isEmpty { awaitTask.yield() } views.show("synthetic-two")await core.release()tryawait reading.value XCTAssertNil(views.answer, "a read of the database shown before never lands") }/// RULE (Cinemas leftovers, 7 Nov 2026: a fresh install stood ~10 s on a tools tier of one tile): a read asked of the database the window shows lands though the window names that database only after the read was asked — the read carries its database, never the one last shown — and its answer stands once the window does name it.func testAReadOfTheDatabaseAboutToBeShownLands() asyncthrows {let views = ToolViews()let core = AnswerCore([Self.answer("cinemas", views: #"[{"id":"films","label":"Films","count":2,"default":true,"read":{"table":"film"}}]"#)])await core.hold()let reading = Task { tryawait views.reload(core: core, database: "synthetic-fresh", standing: "cinemas") }whileawait core.asked.isEmpty { awaitTask.yield() } views.show("synthetic-fresh")await core.release()tryawait reading.value XCTAssertEqual(views.views(of: "cinemas").map(\.id), ["films"], "the read of the database shown landed") views.show("synthetic-fresh") XCTAssertNotNil(views.answer, "and the window naming it again keeps it")let first = await core.asked.first XCTAssertTrue(try XCTUnwrap(first).contains(#""tool":"cinemas""#), "asked standing on the tile it was asked for") }/// RULE: a fan read that fails says so to its caller, never kept quiet.func testAFailedFanReadThrows() async {let views = ToolViews()do {tryawait views.reload(core: ScriptedCore([:]), database: "synthetic-copy") XCTFail("the failed read was kept quiet") } catch {} }/// RULE: the fan asks the core with the views chosen and the tile it stands on, and draws the view the core says each stands on until one is chosen here.func testTheChoiceAndTheTileStoodOnAreAsked() asyncthrows {let views = ToolViews()let core = AnswerCore([Self.answer("todos", views: #"[{"id":"today","label":"Today","count":1,"default":true,"read":{"table":"todo"}},{"id":"all","label":"All","count":3,"read":{"table":"todo"}}]"#, current: "today")]) views.show("synthetic-copy") views.choose("all", of: "todos")tryawait views.reload(core: core, database: "synthetic-copy", standing: "todos")let first = await core.asked.firstlet asked = try XCTUnwrap(first) XCTAssertTrue(asked.contains(#""chosen":{"todos":"all"}"#), asked) XCTAssertTrue(asked.contains(#""tool":"todos""#), asked) XCTAssertEqual(views.current(of: "todos")?.id, "all", "chosen here stands") views.choose("gone", of: "todos") XCTAssertEqual(views.current(of: "todos")?.id, "today", "a choice no longer the tool's: the core's") XCTAssertEqual(views.neighbour(of: "todos", step: 1)?.id, "all") XCTAssertNil(views.neighbour(of: "todos", step: -1)) }func testASetUsesTheLandedListTotalForItsChip() throws {let views = ToolViews() views.take(try JSONDecoder().decode(FanAnswer.self, from: Data(Self.answer("todos", views: #"[{"id":"late","label":"Late","count":5,"read":{"table":"todo","section":"late"}}]"#).utf8)))var read = ToolView.Read(table: "todo", name: "todos/late") read.section = "late" views.counted(150, for: read) XCTAssertEqual(views.views(of: "todos").first?.count, 150) views.counted(149, for: read) XCTAssertEqual(views.views(of: "todos").first?.count, 149) views.counted(1, for: .init(table: "todo", name: "todos/today")) XCTAssertEqual(views.views(of: "todos").first?.count, 149) }func testAReadAfterRowsMoveRefreshesChipsAndRelatedEmptyWordsTogether() asyncthrows {let ring = { (late: Int) inSelf.answer("todos", views: #"[{"id":"today","label":"Today","count":0,"default":true,"read":{"table":"todo","empty":{"line":"empty_views.todos.today","counts":{"late":"empty_views.todo_late_count"},"total":\#(late)}}},{"id":"late","label":"Late","count":\#(late),"read":{"table":"todo"}}]"#) }let core = AnswerCore([ring(150), ring(0)])let views = ToolViews() views.show("synthetic-copy")tryawait views.reload(core: core, database: "synthetic-copy")let first = views.views(of: "todos") XCTAssertEqual(first[1].count, 150) XCTAssertEqual(ViewTier.make(tool: "todos", views: first, current: nil).cards.first(where: { $0.id == first[1].id })?.count, 150) XCTAssertEqual(first[0].read.emptyLine(views: first), "Nothing due today. 150 late.")tryawait views.reload(core: core, database: "synthetic-copy")let fresh = views.views(of: "todos") XCTAssertEqual(fresh[1].count, 0) XCTAssertEqual(ViewTier.make(tool: "todos", views: fresh, current: nil).cards.first(where: { $0.id == fresh[1].id })?.count, 0) XCTAssertNil(fresh[0].read.emptyLine(views: fresh)) }/// RULE: every view is a counted leaf on the shared fan, in the order the core answers them, the current raised.func testViewsAreLeavesOnTheSameTierInTheAnsweredOrder() {var views = Self.viewsfor index in views.indices { views[index].count = index * 7 }let tier = ViewTier.make(tool: "todos", views: views, current: "all") XCTAssertEqual(tier.id, "views-todos") XCTAssertEqual(tier.cards.map(\.id), ["today", "done", "all", "group:g1"]) XCTAssertEqual(tier.cards.map(\.label), ["Today", "Done", "All", "Errands"]) XCTAssertEqual(tier.cards.map(\.count), [0, 7, 14, 21]) XCTAssertTrue(tier.cards.allSatisfy { $0.style == .leaf }) XCTAssertEqual(tier.raised, "all") }privatestaticlet views = [ToolView(id: "today", label: "Today", isDefault: true, read: .init(table: "todo", section: "today")),ToolView(id: "done", label: "Done", read: .init(table: "todo", section: "done")),ToolView(id: "all", label: "All", read: .init(table: "todo")),ToolView(id: "group:g1", label: "Errands", read: .init(table: "todo", filter: ["group": .text("g1")])), ]/// RULE: The ring reads the core's `shell.fan` views as the core writes them — each view's id, label, count, default and its `records.list` read with its section or its columns — and knows a generated group's view by its id.func testTheCoreAnswerDecodesIntoViews() throws {let json = #"{"tool":"todos","views":[{"id":"late","label":"Late","visibility":"owner","count":3,"default":false,"read":{"table":"todo","section":"late","today":"2026-10-20","timezone":"Area/City"}},{"id":"group:g1","label":"Errands","visibility":"owner","count":2,"default":false,"read":{"table":"todo","where":{"group":"g1"},"today":"2026-10-20","timezone":"Area/City"}}]}"#structAnswer: Decodable { let views: [ToolView] }let views = try JSONDecoder().decode(Answer.self, from: Data(json.utf8)).views XCTAssertEqual(views.map(\.id), ["late", "group:g1"]) XCTAssertEqual(views[0].read, ToolView.Read(table: "todo", section: "late")) XCTAssertEqual(views[0].count, 3) XCTAssertNil(views[0].group) XCTAssertEqual(views[1].group, "g1") XCTAssertEqual(views[1].read.filter, ["group": .text("g1")]) }/// RULE: A view kept to its next day says that day's weekday on its slip ("Monday" on a Friday), from the day the core answers, in the person's own language; with no day answered (no later row) it keeps its declared label.func testANextDayViewSaysItsWeekday() throws {var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(identifier: "Asia/Kolkata")! XCTAssertEqual(CottonDate.weekday(of: "2026-10-26", locale: Locale(identifier: "en_US"), calendar: calendar), "Monday") XCTAssertEqual(CottonDate.weekday(of: "2026-10-26", locale: Locale(identifier: "fr_FR"), calendar: calendar), "lundi") XCTAssertNil(CottonDate.weekday(of: "next week", calendar: calendar))let json = #"{"views":[{"id":"next","label":"Nextclass day","count":2,"default":false,"day":"2026-10-26","read":{"table":"yoga_session","period":"next_day","today":"2026-10-23"}},{"id":"none","label":"Nextclass day","count":0,"default":false,"read":{"table":"yoga_session","period":"next_day","today":"2026-10-23"}}]}"#structAnswer: Decodable { let views: [ToolView] }let views = try JSONDecoder().decode(Answer.self, from: Data(json.utf8)).views XCTAssertEqual(views[0].day, "2026-10-26") XCTAssertEqual(views[0].label, CottonDate.weekday(of: "2026-10-26")) XCTAssertNotEqual(views[0].label, "Next class day") XCTAssertNil(views[1].day) XCTAssertEqual(views[1].label, "Next class day", "no later class: the declared label") }/// RULE: A business's view kept to its next day — the shell's Schedule tile — says that day's weekday as the staff's slip does; with no day answered it keeps its label.func testABusinessNextDayViewSaysItsWeekday() throws {let json = #"[{"id":"next","label":"Nextclass day","table":"yoga_session","day":"2026-10-26","rows":[]},{"id":"week","label":"This week","table":"yoga_session","rows":[]}]"#let views = try JSONDecoder().decode([BusinessView].self, from: Data(json.utf8)) XCTAssertEqual(views[0].label, CottonDate.weekday(of: "2026-10-26")) XCTAssertEqual(views[0].day, "2026-10-26") XCTAssertEqual(views[1].label, "This week") XCTAssertNil(views[1].day) }}