Cotton code
197 lines · 11.3 KB · SwiftRaw
// The plain face fits every shape its tables give it: what the front holds,// and what it turns to — the whole body, the card's long columns, the facts// it had no room for — so nothing is clipped and a card with nothing long is// one page. It wears the worn theme's faces.import CottonPaperimport CottonValuesimport ImageIOimport SwiftUIimport UniformTypeIdentifiersimport XCTest@testable import CottonUI@MainActorfinal class PlainFaceTests: XCTestCase {    /// The room inside a deck card 340 points wide (4:5), its rule and the    /// face's inset taken off.    static let card = CGSize(width: 340, height: 425)    static var room: CGSize {        let rule = CardPaperKnobs.contentInset(width: card.width) * 2        let inset = PlainFaceKnobs.inset        return CGSize(width: card.width - rule - inset.leading - inset.trailing,                      height: card.height - rule - inset.top - inset.bottom)    }    private func plan(_ card: DeckCard, pages: [CardPage] = [], theme: Theme = .paper, room: CGSize = room) -> PlainPlan {        PlainPlan.make(            title: card.text("title"), subtitle: card.text("subtitle"), body: card.text("body"),            picture: card.text("photo") != nil, facts: PlainFace(card: card).facts, columns: pages, room: room,            type: PlainType(theme))    }    /// RULE: A title is broken only between words — a file's name longer than the line at its own parts (after "-", "_", "."), never inside a word ("frankenstei / n.epub" on the 362 walk) — and every line the front gives stands inside the room, in the paper look and a business's.    func testATitleIsNeverBrokenInsideAWord() throws {        for title in ["mary-shelley_frankenstein.epub", "synthetic_extraordinarilylongfilenamewithoutanybreaks.mkv", "An invented title of several ordinary words"] {            for theme in [Theme.paper] {                let card = GalleryFaces.card("plain", ["title": .text(title), "subtitle": .text("Waiting for the Mac")])                let plan = self.plan(card, theme: theme)                let words = try XCTUnwrap(plan.titleWords, title)                XCTAssertEqual(words.replacingOccurrences(of: "\n", with: "").filter { $0 != " " }, title.filter { $0 != " " }, "nothing lost")                let type = PlainType(theme)                for line in words.split(separator: "\n") {                    XCTAssertTrue(InkFit.fits(String(line), face: type.heading, size: plan.titleSize, width: Self.room.width, lines: 1),                                  "\(title): '\(line)' at \(plan.titleSize) overruns the room")                }            }        }        let name = plan(GalleryFaces.card("plain", ["title": .text("mary-shelley_frankenstein.epub")]))        XCTAssertFalse(try XCTUnwrap(name.titleWords).split(separator: "\n").contains { $0.hasSuffix("frankenstei") }, "the word stands whole")    }    /// RULE: A plain card with nothing long is one page — no dots, nothing to turn to.    func testACardWithNothingLongIsOnePage() {        XCTAssertEqual(plan(PlainFaceCatalogue.setting).pages, [])        XCTAssertEqual(plan(PlainFaceCatalogue.customer).pages, [])        let order = plan(PlainFaceCatalogue.order)        XCTAssertEqual(order.pages, [])        XCTAssertEqual(order.shown, PlainFace(card: PlainFaceCatalogue.order).facts.count)        XCTAssertEqual(order.rows.joined().count, order.shown)    }    /// RULE: A card with little on it stands a little above the middle, not at the top of an empty sheet; a full one starts at the top.    func testLittleOnACardStandsNearTheMiddle() {        XCTAssertGreaterThan(plan(PlainFaceCatalogue.setting).lift, 0)        XCTAssertEqual(plan(PlainFaceCatalogue.chef, pages: PlainFaceCatalogue.chefPages).lift, 0)    }    /// RULE: A body longer than the front's room is cut on the front and turned to whole on a page; a column the card turns to that holds the body is that page, never a second copy.    func testALongBodyTurnsToItsWholeOnce() {        let bare = plan(PlainFaceCatalogue.chef)        XCTAssertEqual(bare.pages, [.words(label: nil, text: PlainFaceCatalogue.chefBio)])        XCTAssertGreaterThan(bare.bodyLines, 0, "the front keeps the body's first lines")        let paged = plan(PlainFaceCatalogue.chef, pages: PlainFaceCatalogue.chefPages)        XCTAssertEqual(paged.pages, [.words(label: "Bio", text: PlainFaceCatalogue.chefBio)])    }    /// RULE: A column the card turns to whose words the front already shows whole is no page; one it does not show is.    func testAColumnTheFrontShowsWhollyIsNoPage() {        let short = "An invented bio."        let chef = GalleryFaces.card("plain", ["title": .text("Invented chef"), "body": .text(short)])        XCTAssertEqual(plan(chef, pages: [CardPage(label: "Bio", text: short)]).pages, [])        let other = CardPage(label: "What buyers say", text: "Invented praise.")        XCTAssertEqual(plan(chef, pages: [other]).pages, [.words(label: other.label, text: other.text)])    }    /// RULE: Facts the front cannot hold go whole onto pages after it, in order, none lost and none cut mid-line.    func testFactsTheFrontCannotHoldGoOnPages() {        let facts: [RecordValue] = (1...24).map { PlainFaceCatalogue.fact("Invented fact \($0)", "An invented value long enough to wrap onto a second line \($0)") }        let card = GalleryFaces.card("plain", ["title": .text("Invented device"), "facts": .list(facts)])        let plan = self.plan(card)        let paged = plan.pages.flatMap { page -> [PlainFact] in            if case .facts(let rows) = page { return Array(rows.joined()) }            XCTFail("only facts pages: \(page)")            return []        }        let all = PlainFace(card: card).facts        XCTAssertGreaterThan(plan.shown, 0)        XCTAssertGreaterThan(plan.pages.count, 1, "24 two-line facts take more than one page past the front")        XCTAssertEqual(Array(all.prefix(plan.shown)) + paged, all)    }    /// RULE: A long title wraps to three lines before it is set smaller, and is set no smaller than its least before it is cut.    func testALongTitleWrapsThenShrinksThenCuts() {        let long = plan(PlainFaceCatalogue.longTitle)        XCTAssertEqual(long.titleLines, PlainFaceKnobs.titleLines)        XCTAssertLessThan(long.titleSize, PlainFaceKnobs.titleSize)        XCTAssertGreaterThanOrEqual(long.titleSize, PlainFaceKnobs.titleSize * PlainFaceKnobs.titleLeast)        let two = plan(GalleryFaces.card("plain", ["title": .text("An invented title over two lines of the card")]))        XCTAssertEqual(two.titleSize, PlainFaceKnobs.titleSize, "a title that wraps within three lines keeps its size")        XCTAssertGreaterThan(two.titleLines, 1)    }    /// RULE: Two facts whose words each say one line of half the card stand side by side; a fact whose words run longer stands alone, in as many lines as it needs.    func testShortFactsPairAndLongOnesStandAlone() {        XCTAssertEqual(plan(PlainFaceCatalogue.customer).rows.map(\.count), [2, 2, 1])        let machine = FactsMeasure(facts: PlainFace(card: PlainFaceCatalogue.machine).facts, width: Self.room.width,                                   type: PlainType(.paper), ruled: true)        XCTAssertTrue(machine.rows.contains { $0.count == 2 } && machine.rows.contains { $0.count == 1 },                      "short facts pair row by row, beside a long one alone: \(machine.rows.map(\.count))")        let place = plan(PlainFaceCatalogue.place)        let rows = place.rows + place.pages.flatMap { page -> [[PlainFact]] in            if case .facts(let rows) = page { return rows }            return []        }        XCTAssertEqual(rows.map(\.count), [1, 1, 1])    }    /// RULE: A place of another kind that says what one of the core's facts already says is said once.    func testAPlaceAFactAlreadySaysIsSaidOnce() {        let facts = PlainFace(card: PlainFaceCatalogue.order).facts        XCTAssertEqual(facts.map(\.said), ["\u{20B9}360", "2", "Thu 22 Oct"])        let unknown = PlainFace(card: PlainFaceCatalogue.unknownKind).facts        XCTAssertEqual(unknown.map(\.said), ["Sat 17 Oct", "Invented Hill Station", "3 photos", "Not confirmed"])    }    /// RULE: The plain face wears the worn theme's faces: the typewriter struck twice on paper, a business look's title face over its reading face.    func testItWearsTheLooksFaces() throws {        let paper = PlainType(.paper)        XCTAssertTrue(paper.struck)        XCTAssertEqual(paper.reading, Theme.paper.type.body)        let nancy = GalleryFaces.kitchen.theme        XCTAssertFalse(PlainType(nancy).struck)        XCTAssertEqual(PlainType(nancy).heading, nancy.type.title)        // Every shape fits in either look with nothing cut that has no page.        for shape in PlainFaceCatalogue.shapes {            for theme in [Theme.paper, nancy] {                let plan = self.plan(shape.card, pages: shape.pages, theme: theme)                let facts = PlainFace(card: shape.card).facts                let paged = plan.pages.reduce(0) { sum, page in                    if case .facts(let rows) = page { return sum + rows.joined().count }                    return sum                }                XCTAssertEqual(plan.shown + paged, facts.count, "\(shape.name) in \(theme.name) loses facts")            }        }    }    /// A capture utility, not a guard: with `PLAIN_CAPTURE=<dir>` (passed as    /// `TEST_RUNNER_PLAIN_CAPTURE`) it draws every shape's every page on the    /// deck's paper, on Cotton's and in Nancy's look, as PNGs. Without the    /// variable it skips.    func testCaptureTheShapes() throws {        guard let dir = ProcessInfo.processInfo.environment["PLAIN_CAPTURE"], !dir.isEmpty else {            throw XCTSkip("set TEST_RUNNER_PLAIN_CAPTURE=<dir> to capture")        }        let out = URL(fileURLWithPath: dir, isDirectory: true)        try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)        let looks: [(String, Theme)] = [("paper", .paper)]            + (GalleryFaces.kitchenLook.map { [("nancy", $0)] } ?? [])        for (look, theme) in looks {            for shape in PlainFaceCatalogue.shapes {                let count = 1 + plan(shape.card, pages: shape.pages, theme: theme).pages.count                for page in 0..<count {                    let face = PlainFace(card: shape.card, picture: shape.picture.map { AnyView(GalleryFaces.picture($0)) },                                         pages: shape.pages, page: page)                        .frame(width: Self.card.width, height: Self.card.height)                        .padding(12)                        .background(theme.colors.ground.color)                        .environment(\.theme, theme)                        .environment(\.colorScheme, .light)                    write(face, to: out.appendingPathComponent("\(look)-\(shape.name)-\(page + 1).png"))                }            }        }    }    private func write(_ view: some View, to url: URL) {        let renderer = ImageRenderer(content: view)        renderer.scale = 2        guard let image = renderer.cgImage,              let dest = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil)        else { return XCTFail("\(url.lastPathComponent) drew nothing") }        CGImageDestinationAddImage(dest, image, nil)        CGImageDestinationFinalize(dest)    }}