Cotton code
209 lines · 12.7 KB · SwiftRaw
// Photos as its tables' lists and pages, with nothing the old screens showed// lost (rebuild item 4, the no-loss audit ~/m5b17-audit-photos.md): the library// of pictures AND films as prints three across in months counted "40 photos ·// 2 videos", "No date" last, a film's print with its play mark and length, the// contact sheet, all · photos · videos, its own search and empty words, Select// and its one Delete in the library's words, the menu's Albums, Duplicates and// People to confirm with their counts and the red "N to review", a list drawn// at once from its last read; albums as prints of their covers with "N// pictures", their days, "suggested" in red and Keep / Not this, the dismissed// never listed; an album's page with its cover, its facts line, its decision,// its pictures as prints opening each by kind, Add photos and Select → Remove// from album; the add picker; duplicates as KEEP and COPY side by side with// their facts, the distance line, Keep this one / They are different, grouped// under their keep; a photo's page with its hero from the largest copy and its// caption in the margin, the viewer, the hand line, its albums as tags, "What// Cotton saw", the review with Keep and Delete, "Seen in", the details footer// and Delete's words with no Undo.//// Each is a generic definition key or surface drawn once, never Photos' own// Swift. People to confirm (/photos/people) is People's face table (who-is-who,// PeopleNoLossTests); a photo's "People" lists those faces found in it. Every// record is invented.import CottonKitimport CottonValuesimport Foundationimport SwiftUIimport XCTest@testable import CottonUI@MainActorfinal class PhotosNoLossTests: XCTestCase {    private static var resources: Bundle? {        Bundle(url: SourceSweep.iosSources.appendingPathComponent("CottonUI/Resources"))    }    private func definitions() throws -> [String: TableDefinition] {        let loaded = FixtureDefinitions.load(from: try XCTUnwrap(Self.resources))        XCTAssertEqual(loaded.failures, [])        return Dictionary(uniqueKeysWithValues: loaded.definitions.map { ($0.id, $0) })    }    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)).map { record in            guard let said = Self.said[table]?[record.id] else { return record }            return CoreSaid.read(record, days: said.days, words: said.words)        }    }    /// What the core attaches to each fixture record a read hands over    /// (`CoreSaid`): its days' parts and its typed columns' words. Swift    /// spells neither; these tests check where it draws them.    private static let said: [String: [String: (days: [String: RecordValue], words: [String: String])]] = [        "media": [            "example-photo-1": (["taken_at": CoreSaid.day("2026-09-12", monthTitle: "September")], [:]),            "example-video-1": (["taken_at": CoreSaid.day("2026-09-11", monthTitle: "September")], ["duration_ms": "0:42"]),            "example-photo-2": (["taken_at": CoreSaid.day("2026-09-11", monthTitle: "September")], [:]),            "example-video-2": (["taken_at": CoreSaid.day("2026-08-20", monthTitle: "August")], [:]),            "example-photo-3": (["taken_at": CoreSaid.day("2026-08-02", monthTitle: "August")], [:]),        ],        "album": [            "example-album-1": (["starts_at": CoreSaid.day("2026-09-10", range: "10 Sep \u{2013} 12 Sep 2026")], ["member_count": "3 pictures"]),            "example-album-2": (["starts_at": CoreSaid.day("2026-08-02", range: "2 August 2026")], ["member_count": "1 picture"]),        ],        "photo": [            "example-photo-1": (["taken_at": CoreSaid.day("2026-09-12", dayLong: "12 September 2026")], ["size_bytes": "2.2 MB"]),            "example-photo-2": (["taken_at": CoreSaid.day("2026-09-11", dayLong: "11 September 2026")], ["size_bytes": "1.8 MB"]),        ],    ]    private func record(_ table: String, _ id: String) throws -> TableRecord {        try XCTUnwrap(try records(table).first { $0.id == id }, "\(table) has no \(id)")    }    private func code(_ path: String) throws -> String {        SourceSweep.withoutComments(            try String(contentsOf: SourceSweep.iosSources.appendingPathComponent("CottonUI/\(path)"), encoding: .utf8))    }    private func store() throws -> FixtureRecords {        FixtureRecords.bundled(from: try XCTUnwrap(Self.resources))    }    // ── The keys ──────────────────────────────────────────────────────────    // ── The library (/photos) ────────────────────────────────────────────    /// RULE: Hiding filter tabs does not widen a list: Photos and Videos still narrow by kind, and absent tabs keeps the existing filter behavior.    func testTheFilterNarrowsByKindWithoutTabs() throws {        let old = try JSONDecoder().decode(ListFilter.self, from: Data(#"{"column":"kind","words":{"photo":"Photos","video":"Videos"}}"#.utf8))        XCTAssertTrue(old.tabs)        let hidden = try JSONDecoder().decode(ListFilter.self, from: Data(#"{"column":"kind","tabs":false,"words":{"photo":"Photos","video":"Videos"}}"#.utf8))        XCTAssertFalse(try JSONDecoder().decode(ListFilter.self, from: JSONEncoder().encode(hidden)).tabs)    }    /// RULE: (library 9) Select deletes several one at a time, Undo on the receipt, the refused staying picked.    func testSelectDeletesInTheLibrarysWords() async throws {        let media = try table("media")        XCTAssertEqual(media.select, ListSelect(verb: .delete))        XCTAssertEqual(media.deletion?.undo, true)        XCTAssertTrue(TableDefinition.selectOutcome(deleted: 4, failed: 0).contains("4"))        let partial = TableDefinition.selectOutcome(deleted: 3, failed: 1)        XCTAssertTrue(partial.contains("1") && partial.contains("4"), "the refused said out of the whole")        let refusing = RefusingDeletes(try store(), refusing: ["example-photo-2"])        let model = RecordListModel(definition: media, store: refusing, core: ListCoreFake(), seeds: ListSeeds())        await model.reload(project: nil, query: "")        let outcome = await model.delete(ids: ["example-photo-1", "example-photo-2"])        XCTAssertEqual(outcome.deleted, ["example-photo-1"])        XCTAssertEqual(outcome.failed, ["example-photo-2"])        XCTAssertFalse(model.records.contains { $0.id == "example-photo-1" })        XCTAssertTrue(model.records.contains { $0.id == "example-photo-2" }, "a refused delete keeps its record")        let list = try code("Surfaces/RecordListSurface.swift")        XCTAssertTrue(list.contains("picked = outcome.failed"), "the refused stay picked")    }    /// RULE: (library 14, amended by walker 294 row G, 17 Oct 2026) A list draws what it last read at once while it reads again, and a first read that FAILS keeps that frame — the seed's rows stay, still kept for the next launch — with the definition's could-not-read line beside them, never the error's own words.    func testAListDrawsItsLastReadAndAFailureKeepsIt() async throws {        let media = try table("media")        let seeds = ListSeeds()        let first = RecordListModel(definition: media, store: try store(), core: ListCoreFake(), seeds: seeds)        await first.reload(project: nil, query: "")        let key = ListSeeds.Key(table: "media", filter: [:], project: nil, archived: false)        XCTAssertEqual(seeds.answer(for: key)?.rows.count, first.records.count)        let failing = RecordListModel(            definition: media, store: RefusingDeletes(try store(), refusing: [], failsLists: true), core: ListCoreFake(), seeds: seeds)        await failing.reload(project: nil, query: "")        XCTAssertEqual(failing.phase, .loaded, "the frame it drew stays")        XCTAssertEqual(failing.records, first.records, "the seed's rows stay")        XCTAssertNotNil(failing.readProblem, "the rows say the read failed")        XCTAssertEqual(seeds.answer(for: key)?.rows.count, first.records.count, "the seed is kept")    }    // ── Albums ─────────────────────────────────────────────────────────────    // ── One album ──────────────────────────────────────────────────────────    /// RULE: (add 1) The add picker is the photo list always ticking, narrowed to what the album may still take, its tick putting each picked picture in the album (one album_item each), then back, with "Nothing left to add." when there is nothing.    func testTheAddPickerPutsPicturesInTheAlbum() async throws {        let fixtures = try store()        let model = RecordListModel(definition: try table("photo"), store: fixtures, core: ListCoreFake(), seeds: ListSeeds())        let made = await model.create(in: "album_item", column: "record_id", preset: ["album_id": .text("example-album-2")], ids: ["example-photo-1"])        XCTAssertEqual(made.made, ["example-photo-1"])        let members = try await fixtures.list(table: "album_item", project: nil, query: nil, page: 0, where: ["album_id": .text("example-album-2")])        XCTAssertTrue(members.records.contains { $0["record_id"].text == "example-photo-1" })    }    // ── Duplicates ─────────────────────────────────────────────────────────    // ── A photo's page ─────────────────────────────────────────────────────    /// RULE: The people named in a picture stand on its page as person tags — the face questions leave once answered, so the people column is the page's record of who is in it, and every id in it is named.    func testThePeopleNamedInThePictureAreTagsOnItsPage() throws {        let photo = try table("photo")        let named = TableRecord(id: "p", values: ["people": .list([.text("person-1"), .text("person-2")])])        XCTAssertEqual(            Set(photo.links(in: [named]).filter { $0.table == "person" }.map(\.id)), ["person-1", "person-2"],            "every person in a many-link column is asked for its name")    }    // ── The old screens are gone ───────────────────────────────────────────}/// The fixture verbs, refusing some deletes — and every list read, when asked.private actor RefusingDeletes: Records {    private let base: FixtureRecords    private let refusing: Set<String>    private let failsLists: Bool    init(_ base: FixtureRecords, refusing: Set<String>, failsLists: Bool = false) {        self.base = base        self.refusing = refusing        self.failsLists = failsLists    }    func tableDefinitions() async throws -> [TableDefinition] { try await base.tableDefinitions() }    func count(table: String) async throws -> Int { try await base.count(table: table) }    func list(table: String, project: String?, query: String?, page: Int, where filter: [String: RecordValue]) async throws -> RecordPage {        if failsLists { throw RecordsError.unknownTable(table) }        return try await base.list(table: table, project: project, query: query, page: page, where: filter)    }    func get(table: String, id: String) async throws -> TableRecord? { try await base.get(table: table, id: id) }    func create(table: String, data: [String: RecordValue]) async throws -> ChangeRecord { try await base.create(table: table, data: data) }    func update(table: String, id: String, patch: [String: RecordValue]) async throws -> ChangeRecord {        try await base.update(table: table, id: id, patch: patch)    }    func delete(table: String, id: String) async throws -> ChangeRecord {        if refusing.contains(id) { throw RecordsError.unknownRecord(id) }        return try await base.delete(table: table, id: id)    }    func reorder(table: String, ids: [String]) async throws -> ChangeRecord { try await base.reorder(table: table, ids: ids) }    func link(table: String, id: String, column: String, target: String) async throws -> ChangeRecord {        try await base.link(table: table, id: id, column: column, target: target)    }    func undo(change: String) async throws -> ChangeRecord { try await base.undo(change: change) }}