Cotton code
132 lines · 8.7 KB · SwiftRaw
// A tier tile's words are never cut (the coordinator, 4 Nov 2026: Books'// Plus tier read "Find a bo…" and "Bring Goo…"): they wrap to two lines,// then set smaller, as the fan's view cards' words wrap.#if os(iOS)import CottonPaperimport ImageIOimport SwiftUIimport UniformTypeIdentifiersimport XCTest@testable import CottonUI@MainActorfinal class FanTierWordsTests: XCTestCase {    /// Long act, door and choice names, synthetic and the kits' own.    private let long = [        "Find a book", "Add a file", "Bring Goodreads in", "Connect Google Calendar", "Connect Spotify",        "Take an order", "Subscriptions", "Back up now", "Start reading", "Synthetic extraordinarily long act",    ]    private var cardWidth: Double { FanGeometry(scale: Theme.paper.scale).tileWidth }    /// RULE: every tier tile's words stand whole inside the label's box in at most two lines, at the size `FanTierWords` sets them.    func testLongActNamesFitWhole() {        let width = CGFloat(cardWidth * FanGeometry.labelWidthRatio)        for words in long {            let size = FanTierWords.size(words, cardWidth: cardWidth)            XCTAssertTrue(InkFit.fits(words, face: .courier, size: size, width: width, lines: FanTierWords.lines),                          "\(words) stands whole at \(size)")            XCTAssertLessThanOrEqual(size, CGFloat(cardWidth * FanTierWords.word))        }    }    /// RULE: words that fit on two lines at the tile's own size are never set smaller: "Find a book" wraps, it does not shrink.    func testWrappingComesBeforeShrinking() {        let preferred = CGFloat(cardWidth * FanTierWords.word)        XCTAssertEqual(FanTierWords.size("Find a book", cardWidth: cardWidth), preferred, accuracy: 0.001)        XCTAssertEqual(FanTierWords.size("Add a file", cardWidth: cardWidth), preferred, accuracy: 0.001)        let laid = InkFit.laid("Find a book", face: .courier, size: preferred,                               width: CGFloat(cardWidth * FanGeometry.labelWidthRatio))        XCTAssertEqual(laid?.count, 2, "Find a book wraps to two lines")    }    /// RULE: a tile's words go to the Text as they are while any break it may choose stands whole ("Find a book"), and with their break given when moving a word down would cut it ("Add / a fi…" at the largest text size, books build 3 walk, 5 Nov 2026).    func testTheBreakIsGivenWhenATextWouldCut() {        let width = CGFloat(cardWidth * FanGeometry.labelWidthRatio)        let preferred = CGFloat(cardWidth * FanTierWords.word)        XCTAssertEqual(FanTierWords.broken("Find a book", size: preferred, cardWidth: cardWidth), "Find a book")        for words in long {            let given = FanTierWords.broken(words, size: FanTierWords.size(words, cardWidth: cardWidth), cardWidth: cardWidth)            for line in given.split(separator: "\n") where given != words {                XCTAssertTrue(InkFit.fits(String(line), face: .courier, size: FanTierWords.size(words, cardWidth: cardWidth), width: width, lines: 1),                              "\(words): '\(line)' stands whole")            }        }        // The first size at which "a file" no longer stands on one line.        var size = preferred        while InkFit.fits("a file", face: .courier, size: size, width: width, lines: 1) { size += 0.25 }        XCTAssertTrue(InkFit.fits("Add a", face: .courier, size: size, width: width, lines: 1))        XCTAssertEqual(FanTierWords.broken("Add a file", size: size, cardWidth: cardWidth), "Add a\nfile")    }    /// RULE: every Books door and view tile's words, read from the kit, stand whole at every text size up to the largest (the growth `@TextGrowth(.footnote)` reaches at Accessibility XXXL, 44 / 13): the size each tile sets them at lays them in at most two lines inside its label's box, never breaking a word, and the break given to the Text keeps every line whole ("Add a fi…" on the Books 1.0.0 (3) and (4) walks, 7 Nov 2026).    func testEveryBooksDoorAndViewTileStandsWholeAtEveryTextSize() throws {        let kits = SourceSweep.repoRoot.appendingPathComponent("crates/cotton-core/kits/personal")        let book = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: kits.appendingPathComponent("tables/book.json"))) as? [String: Any])        let doors = try XCTUnwrap((book["create"] as? [String: Any])?["doors"] as? [[String: Any]]).compactMap { $0["label"] as? String }        let manifest = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: kits.appendingPathComponent("tools/books/manifest.json"))) as? [String: Any])        let views = try XCTUnwrap(manifest["views"] as? [[String: Any]]).compactMap { $0["label"] as? String }        XCTAssertEqual(doors, ["Find a book", "Add a file", "Add a folder", "Bring Goodreads in"], "the kit's doors are read")        XCTAssertTrue(views.contains("Want to read") && views.contains("On this phone"), "the kit's views are read: \(views)")        let width = CGFloat(cardWidth * FanGeometry.labelWidthRatio)        // A door's share (`FanTierWords.word`), a painted view tile's (`ViewTileKnobs.name`), a plain view card's (13 pt).        let shares: [(String, [String], Double)] = [("door", doors, FanTierWords.word), ("view", views, ViewTileKnobs.name), ("plain view", views, 13 / cardWidth)]        for (kind, labels, share) in shares {            for growth in stride(from: 1.0, through: 44.0 / 13.0, by: 0.05) {                for words in labels {                    let size = FanTierWords.size(words, cardWidth: cardWidth, preferred: share * growth)                    let given = FanTierWords.broken(words, size: size, cardWidth: cardWidth)                    XCTAssertTrue(InkFit.fits(words, face: .courier, size: size, width: width, lines: FanTierWords.lines),                                  "\(kind) '\(words)' at growth \(growth): whole in two lines at \(size)")                    let lines = given.split(separator: "\n").map(String.init)                    XCTAssertLessThanOrEqual(lines.count, FanTierWords.lines)                    XCTAssertEqual(lines.joined(separator: " "), words, "\(kind) '\(words)': the break falls between words")                    for line in lines where lines.count > 1 {                        XCTAssertTrue(InkFit.fits(line, face: .courier, size: size, width: width, lines: 1),                                      "\(kind) '\(words)' at growth \(growth): '\(line)' stands on its line")                    }                }            }        }    }    /// RULE: the tier card draws no truncating text: its words are sized by `FanTierWords`, never by `minimumScaleFactor` or a tail cut.    func testTheTierCardNeverTruncates() throws {        let source = SourceSweep.withoutComments(            try SourceSweep.mustRead("apps/cotton/Sources/CottonUI/Surfaces/Board/FanTiers.swift", ownedBy: "fan"))        let card = try XCTUnwrap(source.components(separatedBy: "struct FanTierCard").last?            .components(separatedBy: "struct FanSwatchCard").first)        XCTAssertFalse(card.contains(".truncationMode(.tail)"))        XCTAssertFalse(card.contains("minimumScaleFactor"))        XCTAssertTrue(card.contains("FanTierWords.size("))    }    /// RULE: a tier of long act names draws at the largest text size, each tile's words whole; with `FAN_TIER_SHOTS_OUT` set the tiles are written as PNGs to look at.    func testLongActNamesDrawAtTheLargestTextSize() throws {        let geometry = FanGeometry(scale: Theme.paper.scale)        let tiles = HStack(spacing: 12) {            ForEach(long, id: \.self) { words in                let item = EditingItem(id: words, word: words, picture: "act-slip", does: .offered(words))                FanTierCard(look: .init(card: FanTier.Card(item: item, object: "act-slip", style: .object, red: false, primary: false),                                        raised: false, width: geometry.tileWidth, height: geometry.tileHeight))            }        }        .padding(16)        .background(Theme.paper.colors.ground.color)        .environment(\.theme, Theme.paper)        .dynamicTypeSize(.accessibility5)        let renderer = ImageRenderer(content: tiles)        renderer.scale = 3        let image = try XCTUnwrap(renderer.cgImage)        XCTAssertGreaterThan(image.width, 0)        if let dir = ProcessInfo.processInfo.environment["FAN_TIER_SHOTS_OUT"], !dir.isEmpty {            let url = URL(fileURLWithPath: dir).appendingPathComponent("tier-long-acts-ax5.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, image, nil)            XCTAssertTrue(CGImageDestinationFinalize(dest))        }    }}#endif