Cotton code
171 lines · 9.8 KB · SwiftRaw
// People as its table's list and page, with nothing the old screens showed// lost (rebuild item 4, the no-loss audit): the directory in name order with// its A–Z rail, the four-across polaroids and the list's "org · role · city"// and their clock, search over name, org and city, "Import contacts" and the// empty words, Archive on a long press and never Delete; the page's phones// and emails that open the hand-off sheet, the quiet Call and Message, the// birthday, their time, the project caps, "Same as …?" with Merge and// Different, the todos, notes and events linked to them with their tallies,// "Is this …?" with Yes and Not them, the summary's byline and its words when// blank, which way money runs between you, and everything else linked. Each is// a generic definition key drawn once in the faces and surfaces, never// People's own Swift. The faces to confirm (`/photos/people`) are People's// `face` table's list. Every record is invented.import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI@MainActorfinal class PeopleNoLossTests: XCTestCase {    private static var resources: Bundle? {        Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources"))    }    private func definitions() throws -> TableDefinitions {        let loaded = FixtureDefinitions.load(from: try XCTUnwrap(Self.resources))        XCTAssertEqual(loaded.failures, [])        return TableDefinitions(loaded.definitions)    }    private func table(_ id: String) throws -> TableDefinition {        try XCTUnwrap(try definitions()[id], "\(id) has no definition")    }    private func records(_ table: String) throws -> [TableRecord] {        try FixtureDefinitions.fixtureRecords(for: table, bundle: try XCTUnwrap(Self.resources))    }    private func record(_ table: String, _ id: String) throws -> TableRecord {        try XCTUnwrap(try records(table).first { $0.id == id }, "\(table) has no \(id)")    }    private func store() -> FixtureRecords { FixtureRecords.bundled(from: Self.resources) }    private let london = TimeZone(identifier: "Europe/London")!    private var utc: Calendar {        var calendar = Calendar(identifier: .gregorian)        calendar.timeZone = TimeZone(identifier: "UTC")!        calendar.locale = Locale(identifier: "en_GB")        return calendar    }    // ── The definition ─────────────────────────────────────────────────────    /// RULE: A defined section resolves its records and parent filter; a missing table stays named without drawing records.    func testSectionsDrawWhatIsDefinedAndNameTheRest() throws {        let person = try table("person")        let defined = try definitions()        var drawn: [String] = []        var waiting: [String] = []        for section in person.page.filter({ $0.list != nil }) {            let list = try XCTUnwrap(section.list)            if let sources = RecordsSection.sources(list, parent: "example-person-1", in: defined) {                drawn.append(list.table)                XCTAssertEqual(sources.first?.filter, [try XCTUnwrap(list.link): .text("example-person-1")])            } else {                waiting.append(list.table)            }        }        // This checks section resolution, independent of the page's visual order.        XCTAssertFalse(drawn.isEmpty)        for table in drawn { XCTAssertNotNil(defined[table], "\(table) is drawn because it is defined") }        for table in waiting { XCTAssertNil(defined[table], "\(table) waits only while it has no definition") }    }    /// RULE: The whole a merged capped section opens is the same section with no cap, so All n holds the n it counts (S6); only the cap is dropped.    func testAMergedSectionsWholeIsItselfUncapped() throws {        let notes = try XCTUnwrap(try table("person").page.filter { $0.list != nil }.first { $0.list?.limit != nil })        let whole = RecordsSection.uncapped(notes)        XCTAssertNil(whole.list?.limit)        XCTAssertEqual(whole.list?.with, notes.list?.with)        XCTAssertEqual(whole.list?.table, notes.list?.table)    }    // ── The directory ──────────────────────────────────────────────────────    /// RULE: The directory searches name, organisation and city by any part of a word — a city or an org finds its people — and never the role or the summary.    func testSearchFindsNameOrgAndCity() async throws {        func found(_ query: String) async throws -> [String] {            try await store().list(table: "person", project: nil, query: query, page: 0).records.map(\.id)        }        let town = try await found("example town")        XCTAssertEqual(town, ["example-person-1"])        let choir = try await found("choir")        XCTAssertEqual(choir, ["example-person-4"])        let neighbour = try await found("neighb")        XCTAssertEqual(neighbour, ["example-person-3"])        let role = try await found("gardener")        XCTAssertEqual(role, [], "the role is not searched, as before")    }    /// B7: a print cut from Photos is a face, not the archival picture.    /// Its tap opens the original photo's record; a hand-picked/contact print    /// has no Photos origin and retains the ordinary picture viewer.    func testAPhotosPrintOpensItsOriginalAndAHandPickedPrintHasNoInventedOrigin() throws {        let person = try table("person")        let original = TableRecord(id: "example-print", values: [            "full_name": .text("Example Gardener"), "avatar_key": .text("synthetic/people/print.jpg"),            "avatar_photo_id": .text("photo:synthetic-original"),        ])        let target = try XCTUnwrap(person.opening(original, column: "avatar_key"))        XCTAssertEqual(target.table, "photo")        XCTAssertEqual(target.id, "photo:synthetic-original")        XCTAssertTrue(try XCTUnwrap(person.column("avatar_photo_id")).readonly)        var picked = original        picked.values["avatar_photo_id"] = .null        XCTAssertNil(person.opening(picked, column: "avatar_key"))        picked.values["avatar_photo_id"] = .text("  ")        XCTAssertNil(person.opening(picked, column: "avatar_key"))    }    // ── The page ───────────────────────────────────────────────────────────    /// RULE: The todos, notes and events linked to the person are read through their `people` and `person_id` links — a record linked to several people found under each — the todos two across, four at most and a way in to all of them.    func testLinkedRecordsAreReadThroughTheirLinks() async throws {        let store = store()        let todos = try await store.list(table: "todo", project: nil, query: nil, page: 0, where: ["people": .text("example-person-1")])        XCTAssertEqual(todos.records.count, 5)        let shared = try await store.list(table: "todo", project: nil, query: nil, page: 0, where: ["people": .text("example-person-2")])        XCTAssertEqual(shared.records.map(\.id), ["example-todo-4"], "a todo linked to two people is under each")        let notes = try await store.list(table: "person_note", project: nil, query: nil, page: 0, where: ["person_id": .text("example-person-1")])        XCTAssertEqual(notes.records.count, 2)        let events = try await store.list(table: "event", project: nil, query: nil, page: 0, where: ["people": .text("example-person-1")])        XCTAssertEqual(events.records.map(\.id), ["example-event-3"])        XCTAssertTrue(try table("todo").column("people")?.readonly == true, "the engine's links, never an editor's")    }    // ── The routes ─────────────────────────────────────────────────────────    // ── The address-book acts: sheets over the list ──────────────────────    /// RULE: "Import contacts" is an act on the People list: it names its route, which is the People list itself with the import raised as a sheet over it — a list, never a page — taking the plain list's place rather than stacking; no link replaces the sheet while it is up; closing it leaves the plain list; and the + fan's Contact and the Imports list reach the same sheet. The address book is a source, never a sink: no act on People rewrites it.    func testImportIsAnActOnThePeopleList() throws {        let person = try table("person")        XCTAssertEqual(person.links.compactMap { $0.path.flatMap(Route.parse) }.filter { $0.listRoot == .peopleImport }, [.peopleImport],                       "the import is the one address-book flow over People")        let route = Route.peopleImport        XCTAssertEqual(route.tier, .list, route.path)        XCTAssertEqual(route.listRoot, route, route.path)        XCTAssertEqual(route.columnPath, [route], "the Mac draws \(route.path) as the list column, with no page beside it")        let navigator = Navigator()        navigator.push(.people)        navigator.push(.peopleImport)        XCTAssertEqual(navigator.stack, [.peopleImport], "the list's act raises the import over the same list")        navigator.push(.people)        navigator.open(.peopleImport)        XCTAssertEqual(navigator.stack, [.peopleImport], "a link never tears down a sheet that is up")        XCTAssertEqual(PeopleListFlow.leavingSheet(over: [.home, .peopleImport]), [.home, .people])        XCTAssertEqual(PeopleListFlow.leavingSheet(over: [.people, .peoplePerson(id: "example-person-1")]),                       [.people, .peoplePerson(id: "example-person-1")], "only a sheet's entry is spent")    }}