Cotton code
151 lines · 9.2 KB · SwiftRaw
// A list's fan tile, made from what it holds (5 Nov 2026): the person's own// picture pinned when it is on this phone, else a stack of its first members'// pictures, else three blank sheets — on the view tiles' own card, its name// and count typed beneath, never the blank card.#if os(iOS)import CottonPaperimport ImageIOimport SwiftUIimport UniformTypeIdentifiersimport XCTest@testable import CottonUI@MainActorfinal class ListTileTests: XCTestCase {    private let blue = ListTileTests.swatch(.systemBlue)    private let green = ListTileTests.swatch(.systemGreen)    private let orange = ListTileTests.swatch(.systemOrange)    /// RULE (5 Nov 2026): the core's `shell.fan` says a list's stack and its own picture, and the fan deals a list (and only a list) its list tile with them.    func testTheCoreSaysAListsPicturesAndTheFanDealsThem() throws {        struct Answer: Decodable { let views: [ToolView] }        let json = #"""        {"views": [          {"id": "all", "label": "All", "count": 3, "picture": "book_pile", "read": {"table": "book"}},          {"id": "group:g1", "label": "Synthetic shelf", "count": 4, "stack": ["db/photos/a.jpg", "db/photos/c.jpg"], "cover": "db/documents/e.png", "read": {"table": "book"}},          {"id": "group:g2", "label": "Synthetic empty shelf", "count": 0, "stack": [], "cover": null, "read": {"table": "book"}}        ]}        """#        let views = try JSONDecoder().decode(Answer.self, from: Data(json.utf8)).views        let tier = ViewTier.make(tool: "books", views: views, current: nil)        XCTAssertEqual(tier.cards.map(\.list), [            nil,            ListTilePictures(cover: "db/documents/e.png", stack: ["db/photos/a.jpg", "db/photos/c.jpg"]),            ListTilePictures(cover: nil, stack: []),        ])        XCTAssertEqual(tier.cards[0].painted, "view-book_pile")    }    /// RULE (5 Nov 2026): the person's own picture wins when it is on this phone; else the members' pictures that are, in order, at most three; else the blank sheets.    func testTheThreeStates() {        XCTAssertEqual(ListTileArt.drawn(own: blue, stack: [green, nil, orange]).name, "own")        XCTAssertEqual(ListTileArt.drawn(own: nil, stack: [green, nil, orange]).name, "stack 2", "a cover not on this phone yet is left out")        XCTAssertEqual(ListTileArt.drawn(own: nil, stack: [green, orange, blue, green]).name, "stack 3")        XCTAssertEqual(ListTileArt.drawn(own: nil, stack: [nil, nil, nil]).name, "plain", "no picture in hand: the default tile")        XCTAssertEqual(ListTileArt.drawn(own: nil, stack: []).name, "plain")        guard case .stack(let laid) = ListTileArt.drawn(own: nil, stack: [nil, orange, green]) else { return XCTFail("a stack") }        XCTAssertTrue(laid[0] === orange && laid[1] === green, "the list's order")    }    /// RULE (5 Nov 2026): every state is drawn on the list's card — the ground is bundled and is the card at the foot — and each puts its own thing in the object place: the own picture's colour, the first cover's colour, or the blank sheets where the plain view card is bare. The specimen: with `VIEW_TILE_SHOTS_OUT` set, the three states are written as one PNG.    func testEachStateIsDrawnOnTheListsCard() throws {        XCTAssertNotNil(CottonMedia.image(ListTile.ground), "the list's card is in the bundled catalogue")        let geometry = FanGeometry(scale: Theme.paper.scale)        let (width, height) = (geometry.tileWidth, geometry.tileHeight)        func tile(_ drawn: ListTileArt.Drawn) -> some View {            ZStack(alignment: .top) {                ViewTile(painted: ListTile.ground, label: "Synthetic shelf", count: 4, width: width, height: height)                ListTileArt(drawn: drawn, width: width, height: height)            }            .frame(width: width, height: height)            .environment(\.theme, Theme.paper)        }        let own = try render(tile(.own(blue)))        let stack = try render(tile(.stack([green, orange, blue])))        let plain = try render(tile(.plain))        // The object place's middle: the print, the top cover, a blank sheet.        let head = (x: 0.5, y: ListTileKnobs.centre)        let ownHead = try XCTUnwrap(pixel(own, at: head))        let stackHead = try XCTUnwrap(pixel(stack, at: head))        let plainHead = try XCTUnwrap(pixel(plain, at: head))        XCTAssertGreaterThan(Int(ownHead[2]), Int(ownHead[0]) + 60, "the own picture (blue) is pinned there: \(ownHead)")        XCTAssertGreaterThan(Int(stackHead[1]), Int(stackHead[0]) + 40, "the first cover (green) is on top: \(stackHead)")        XCTAssertLessThan(abs(Int(plainHead[0]) - Int(plainHead[1])), 40, "a cream sheet: \(plainHead)")        // The card's foot is the same cream in all three: the card stays.        let foot = (x: 0.5, y: 0.95)        XCTAssertEqual(pixel(own, at: foot), pixel(plain, at: foot))        guard let dir = ProcessInfo.processInfo.environment["VIEW_TILE_SHOTS_OUT"], !dir.isEmpty else { return }        let sheet = HStack(spacing: 14) {            tile(.own(blue))            tile(.stack([green, orange, blue]))            tile(.plain)        }        .padding(24)        .background(Color(red: 0.06, green: 0.08, blue: 0.16))        let url = URL(fileURLWithPath: dir).appendingPathComponent("list-tiles.png")        try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)        let dest = try XCTUnwrap(CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil))        CGImageDestinationAddImage(dest, try render(sheet), nil)        XCTAssertTrue(CGImageDestinationFinalize(dest))    }    /// RULE (5 Nov 2026): a fan tile is printed, never live, so the list tile draws the pictures the arc decoded into the cache: none held, the default; the stack's held; the own picture once it is held.    func testTheTileDrawsWhatTheCacheHolds() throws {        let geometry = FanGeometry(scale: Theme.paper.scale)        let keys = (cover: "walk/documents/\(UUID().uuidString).png", first: "walk/photos/\(UUID().uuidString).jpg")        let pictures = ListTilePictures(cover: keys.cover, stack: [keys.first])        func drawn() throws -> [UInt8] {            let tile = ListTile(pictures: pictures, label: "Synthetic shelf", count: 1, width: geometry.tileWidth, height: geometry.tileHeight)                .environment(\.theme, Theme.paper)            return try XCTUnwrap(pixel(try render(tile), at: (x: 0.5, y: ListTileKnobs.centre)))        }        XCTAssertEqual(ListTilePictureCache.missing(pictures), [keys.cover, keys.first])        let plain = try drawn()        XCTAssertLessThan(abs(Int(plain[0]) - Int(plain[1])), 40, "nothing held: the cream sheets \(plain)")        ListTilePictureCache.keep(green, as: keys.first)        let stack = try drawn()        XCTAssertGreaterThan(Int(stack[1]), Int(stack[0]) + 40, "the held cover is stacked: \(stack)")        ListTilePictureCache.keep(blue, as: keys.cover)        let own = try drawn()        XCTAssertGreaterThan(Int(own[2]), Int(own[0]) + 60, "the own picture is pinned: \(own)")        XCTAssertEqual(ListTilePictureCache.missing(pictures), [])    }    /// RULE (5 Nov 2026): a list's Set picture from Photos answers the photo picker for that list; Music has no picker act (its songs come in by the deck's doors).    func testSetPictureOpensThePhotoPickerForItsList() throws {        func platform(_ json: String) throws -> RecordPlatformAction? {            try JSONDecoder().decode(ToolActAnswer.self, from: Data(json.utf8)).platform        }        XCTAssertEqual(try platform(#"{"platform_action": "open_picker", "picker": "photos", "for": "list", "group": "g1"}"#), .pickListPicture(group: "g1"))        XCTAssertThrowsError(try platform(#"{"platform_action": "open_picker", "picker": "folder", "for": "music"}"#))        let act = try JSONDecoder().decode(CardAction.self, from: Data(#"{"id": "list_set_picture", "label": "Set picture from Photos", "kind": "tool", "tool": "books", "group": "g1"}"#.utf8))        XCTAssertEqual(act.group, "g1")    }    private static func swatch(_ color: UIColor) -> UIImage {        UIGraphicsImageRenderer(size: CGSize(width: 64, height: 96)).image { context in            color.setFill()            context.fill(CGRect(x: 0, y: 0, width: 64, height: 96))        }    }    private func render(_ view: some View) throws -> CGImage {        let renderer = ImageRenderer(content: view)        renderer.scale = 3        return try XCTUnwrap(renderer.cgImage)    }    /// The RGBA bytes at a point given as shares of the image's size.    private func pixel(_ image: CGImage, at point: (x: Double, y: Double)) -> [UInt8]? {        let space = CGColorSpaceCreateDeviceRGB()        var bytes = [UInt8](repeating: 0, count: 4)        guard let context = CGContext(data: &bytes, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: space,                                      bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }        let x = Double(image.width) * point.x, y = Double(image.height) * (1 - point.y)        context.draw(image, in: CGRect(x: -x, y: -y, width: Double(image.width), height: Double(image.height)))        return bytes    }}#endif