// Faces draw from the card alone (faces plain, 28 Oct 2026): the deck puts on // the card what its record and table say beyond the core's words // (`DeckCardFill`), and draws every face by its id from Loom's registry, // through no adapter of its own. #if os(iOS) import CottonKit import CottonPaper import CottonValues import SwiftUI import XCTest import UIKit @testable import CottonFaces @testable import CottonUI @MainActor final class DeckCardFillTests: XCTestCase { func testRelatedCountsUseTheDefinitionAndTheWholeFilteredCount() async throws { let parent = TableRecord(id: "person-test", values: [:]) var definition = try TableDefinition.decode(Data(contentsOf: SourceSweep.repoRoot.appendingPathComponent("crates/cotton-core/kits/personal/tables/person.json"))) definition.related = [RelatedRecords(label: "photos", table: "photo", column: "people")] let photo = try TableDefinition.decode(Data(contentsOf: SourceSweep.repoRoot.appendingPathComponent("crates/cotton-core/kits/personal/tables/photo.json"))) let store = FixtureRecords(definitions: [photo], records: ["photo": [ TableRecord(id: "a", values: ["people": .list([.text(parent.id)])]), TableRecord(id: "b", values: ["people": .list([.text(parent.id)])]), TableRecord(id: "c", values: ["people": .list([.text("another-person")])]), ]]) let core = ScriptedCore([CottonMethod.countWords: .ok(#"{"words":"2 photos"}"#)]) let counts = try await DeckCardFill.relatedCounts(parent, definition: definition, store: store, core: core) XCTAssertEqual(counts, [CardRelatedCount(id: "photo", said: "2 photos", count: 2)]) let calls = await core.calls let asked = try XCTUnwrap(calls.first { $0.method == CottonMethod.countWords }) let request = try JSONDecoder().decode([String: JSONValue].self, from: Data(asked.requestJSON.utf8)) XCTAssertEqual(request["set"], .string("cards")) XCTAssertEqual(request["line"], .string("opened.related.photo"), "the table's own line, with its plural forms") XCTAssertEqual(request["n"], .number(2)) } /// RULE: a related list's count is said by the core in its table's line /// with its plural forms ("1 photo"), never built in Swift ("1 photos"); /// a list whose table has no line is said in its own label. func testEveryRelatedListOfTheKitHasItsCountLine() throws { let kits = SourceSweep.repoRoot.appendingPathComponent("crates/cotton-core/kits") var counted = 0 for kit in try FileManager.default.contentsOfDirectory(at: kits, includingPropertiesForKeys: nil) { let tables = kit.appendingPathComponent("tables") for file in (try? FileManager.default.contentsOfDirectory(at: tables, includingPropertiesForKeys: nil)) ?? [] where file.pathExtension == "json" { guard let definition = try? TableDefinition.decode(Data(contentsOf: file)) else { continue } for related in definition.related ?? [] where related.column != nil { XCTAssertNotNil(ShellLines.shipped("cards", "opened.related.\(related.table).one"), "\(definition.id) › \(related.table)") XCTAssertNotNil(ShellLines.shipped("cards", "opened.related.\(related.table).other"), "\(definition.id) › \(related.table)") counted += 1 } } } XCTAssertGreaterThanOrEqual(counted, 6) XCTAssertEqual(ShellLines.shipped("cards", "opened.related.labelled", ["label": "Stories", "n": "1"]), "Stories: 1") XCTAssertNil(ShellLines.shipped("cards", "opened.related.count.one"), "removed: it said 1 threads") let face = try SourceSweep.mustRead("apps/loom/Sources/CottonFaces/Cotton/RolodexFace.swift", ownedBy: "faces") XCTAssertTrue(face.contains("Text(group.said)")) } func testOnlyOpenedContentSetsTheFaceEnvironment() async throws { let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) for opened in [false, true] { let appeared = expectation(description: "environment probe") let probe = FaceOpenedProbe { value in XCTAssertEqual(value, opened) appeared.fulfill() } let content = Group { if opened { OpenedCardContent { probe } acts: { EmptyView() } } else { probe } } let previousKeyWindow = scene.keyWindow let window = UIWindow(windowScene: scene) window.rootViewController = UIHostingController(rootView: content) window.makeKeyAndVisible() await fulfillment(of: [appeared], timeout: 5) window.isHidden = true window.rootViewController = nil previousKeyWindow?.makeKeyAndVisible() } } func testTheStampUsesTheCardsExplicitLabel() throws { let table = try TableDefinition.decode(Data(contentsOf: SourceSweep.repoRoot .appendingPathComponent("crates/cotton-core/kits/personal/tables/todo.json"))) let field = try XCTUnwrap(table.card?.fields.first(where: { $0.slot.rawValue == "check" })) let path = try XCTUnwrap(field.label) let labels = DeckCardFill.labels(table) XCTAssertEqual(labels[slot: "check"], ShellLines.line("cards", path)) XCTAssertNotEqual(labels[slot: "check"], table.column("status")?.label) } func testAnEmptyPictureIsAbsentForEveryFace() { let row = TableRecord(id: "portrait-test", values: [:]) for face in FaceRegistry.all { for absent in ["", " \n"] { let card = DeckCard(face: face.id, corner: nil, pressing: false, pace: nil, plate: nil, fields: ["photo": .text(absent)]) let filled = DeckCardFill.filled(card, record: row, definition: nil) XCTAssertNil(filled.fields["photo"], face.id) } let card = DeckCard(face: face.id, corner: nil, pressing: false, pace: nil, plate: nil, fields: ["photo": .text("fixture-key")]) let filled = DeckCardFill.filled(card, record: row, definition: nil) XCTAssertEqual(filled.text("photo"), "fixture-key", face.id) } } /// RULE: the card the deck hands a face carries its record's id, the pages its card turns to, its places under their labels, a rating, the values stored under its places, a delivery's states, the ways its person is reached and its file — read off the record and the table its card target names. func testTheCardCarriesWhatItsRecordAndTableSay() throws { let definition = try KitchenFacesTests.delivery() let row = TableRecord(id: "d-1", values: [ "name": .text("Invented lunch"), "address": .text("Invented flat"), "delivered": .bool(true), "subscription": .text("sub-1"), "phones": .list([.text("+91 98450 00000")]), "emails": .list([.text("not an address"), .text("cook@example.com")]), "thread_channel": .text("whatsapp"), ]) let card = DeckCard(face: .nancyDelivery, fields: ["title": .text("Invented lunch")]) let filled = DeckCardFill.filled(card, record: row, definition: definition) XCTAssertEqual(filled.record, "d-1") XCTAssertEqual(filled.fields, card.fields, "the core's words are the core's") XCTAssertEqual(filled.labels[slot: "body"], "Address") XCTAssertEqual(filled.labels[column: "subscription"], "Plan") XCTAssertEqual(filled.stored["body"], "Invented flat") XCTAssertEqual(filled.delivery, KitchenDeliveryState(delivered: true, paid: false, onPlan: true)) XCTAssertEqual(filled.reach, CardReach(phones: ["+91 98450 00000"], emails: ["cook@example.com"], channel: "whatsapp", call: true, message: true, email: true)) XCTAssertNil(filled.stars, "the card's facts name no rating") let bare = DeckCardFill.filled(card, record: row, definition: nil) XCTAssertEqual(bare.labels, CardLabels(), "with no table, no labels") XCTAssertEqual(bare.pages, [], "with no table, no pages") XCTAssertEqual(bare.stored, [:]) } /// RULE: Both thread faces receive the core's history on their first /// draw; mounting the deck must neither read it nor erase it. func testBothThreadFacesHaveTheirHistoryOnFirstDraw() async throws { let history = ThreadHistory(count: "8 messages since 2020", earlier: [ .init(id: "m-2", words: "Invented earlier", mine: false, time: "Fri 8:30 am", sender: "Invented writer") ], last: .init(id: "m-7", words: "Invented last", mine: true, time: "8:37 am", sender: "You")) let payload = try JSONDecoder().decode(RecordValue.self, from: JSONEncoder().encode(history)) let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first) for face in ["thread.slips", "thread"] { let received = expectation(description: "\(face) is whole on first appearance") let raw = RecordValue.object(["face": .text(face), "fields": .object(["body": .text("Preview")]), "thread": payload]) let card = try XCTUnwrap(DeckCard.read(raw)).get() XCTAssertEqual(card.thread, history) let row = TableRecord(id: "t-1", values: ["kind": .text("group")]) var first: ThreadHistory? let view = DeckFilledCard(card: card, record: row) { filled in Color.clear.onAppear { first = filled.thread received.fulfill() } } XCTAssertNil(view.reading(card), "thread history needs no asynchronous deck fill") let host = UIHostingController(rootView: view .environment(\.tableDefinitions, TableDefinitions([])) .environment(\.records, FixtureRecords(definitions: [], records: [:]))) let previousKeyWindow = scene.keyWindow let window = UIWindow(windowScene: scene) window.frame = scene.screen.bounds window.rootViewController = host window.makeKeyAndVisible() host.view.layoutIfNeeded() defer { window.isHidden = true; window.rootViewController = nil; previousKeyWindow?.makeKeyAndVisible() } await fulfillment(of: [received], timeout: 5) XCTAssertEqual(first, history) } guard case .failure(.invalidThread)? = DeckCard.read(.object(["face": .text("thread.slips"), "thread": .text("broken")])) else { return XCTFail("malformed core history must be refused") } } private static func stamp(near: String? = "Today", recent: String = "8:30 am", dated: String = "30 Oct", weekday: String = "Fri 30 Oct") -> RecordValue { .object([ "day": .text("2026-10-30"), "dated": .text(dated), "near": near.map(RecordValue.text) ?? .null, "weekday_date": .text(weekday), "weekday_name": .text("Friday"), "day_long": .text("30 October"), "heading": .text("Today"), "recent": .text(recent), "under_day": .text("8:30 am"), "clock": .text("8:30 am"), "month": .text("2026-10"), "month_title": .text("October"), "leaf_day": .number(30), "leaf_month": .text("OCT"), ]) } /// RULE: the deck draws every face from Loom's registry by its id — it keeps no adapter of its own, and the faces that read the store or the player take what they read on their card or through the hooks the deck installs. func testTheDeckDrawsEveryFaceFromTheRegistry() throws { let face = SourceSweep.withoutComments(try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Deck/DeckFace.swift", ownedBy: "loom")) XCTAssertFalse(face.contains("adapted"), "the deck still adapts a face") XCTAssertTrue(face.contains("DeckFace.registered(card)")) XCTAssertTrue(face.contains(".environment(\\.faceFilePage, DeckFirstPage.drawer)")) XCTAssertTrue(face.contains(".environment(\\.faceTrackPlayer, DeckPlaying.player)")) for id in FaceRegistry.ids { XCTAssertEqual(DeckFace.registered(DeckCard(face: id, corner: nil, pressing: false, pace: nil, plate: nil, fields: [:]))?.id, id) } } } private struct FaceOpenedProbe: View { @Environment(\.faceOpened) private var opened let read: (Bool) -> Void var body: some View { Color.clear.onAppear { read(opened) } } } #endif