Cotton code
159 lines · 9.6 KB · SwiftRaw
import CottonKitimport CottonValuesimport CryptoKitimport ImageIOimport SwiftUIimport UniformTypeIdentifiersimport XCTest@testable import CottonUI/// A capture utility, not a guard: with `COTTON_LOOK_CAPTURE=<dir>` set it/// draws every bundled tool's faces from its synthetic records — Home's tile at/// each size, a slip list, the page, the cover — at scale 1.0 into `<dir>` as/// PNGs plus `manifest.txt` (one SHA-256 of the raw pixels per screen), so a/// change that must not move a pixel (a literal becoming a theme key) is proved/// by two manifests that are equal (`scripts/look-diff.py`). Without the/// variable it skips.@MainActorfinal class LookCaptureTests: XCTestCase {    func testCaptureTheReviewSet() async throws {        guard let dir = ProcessInfo.processInfo.environment["COTTON_LOOK_CAPTURE"], !dir.isEmpty else {            throw XCTSkip("set COTTON_LOOK_CAPTURE=<dir> to capture")        }        let out = URL(fileURLWithPath: dir, isDirectory: true)        try FileManager.default.createDirectory(at: out, withIntermediateDirectories: true)        let bundle = try TestResources.bundle()        let definitions = FixtureDefinitions.load(from: bundle).definitions.sorted { $0.id < $1.id }        let now = Date(timeIntervalSince1970: 1_791_590_400)        var manifest: [String] = []        func shoot(_ name: String, _ view: some View, width: CGFloat) {            guard let (size, bytes) = pixels(view, width: width) else { manifest.append("\(name) EMPTY"); return }            let hash = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()            // A face that draws differently twice in one run (a few do) proves            // nothing either way: it is named UNSTABLE, and look-diff lists it            // apart instead of passing or failing it.            let again = pixels(view, width: width).map { SHA256.hash(data: $0.1).map { String(format: "%02x", $0) }.joined() }            manifest.append("\(name) \(Int(size.width))x\(Int(size.height)) \(again == hash ? hash : "UNSTABLE")")            write(bytes, size: size, to: out.appendingPathComponent("\(name).png"))        }        for definition in definitions {            guard let records = try? FixtureDefinitions.fixtureRecords(for: definition.id, bundle: bundle),                  let first = records.first else { continue }            for size in TileSize.allCases {                shoot("\(definition.id)-tile-\(size.rawValue)",                      BoardTile(definition: definition, records: records, size: size, now: now)                        .frame(height: size.canvas.height),                      width: size.canvas.width)            }            shoot("\(definition.id)-list", VStack(spacing: 12) {                ForEach(records.prefix(4), id: \.id) { SlipFace(definition: definition, record: $0) }            }, width: 360)            shoot("\(definition.id)-card", RecordCardFace(definition: definition, record: first), width: 393)            // The phone's width the owner reviews on.            shoot("\(definition.id)-card-390", RecordCardFace(definition: definition, record: first), width: 390)            shoot("\(definition.id)-cover", CoverFace(definition: definition, record: first, width: 360), width: 360)        }        // A title longer than the card's two lines (architect, 13 Oct 2026):        // its first whole words, then an ellipsis — never cut mid-word.        if let todo = definitions.first(where: { $0.id == "todo" }),           var record = try? FixtureDefinitions.fixtureRecords(for: "todo", bundle: bundle).first {            record.values[todo.title] = .text("Fix the window and the AC water drainage issue with the downstairs neighbours before the monsoon comes back this year")            shoot("todo-card-long-title-390", RecordCardFace(definition: todo, record: record), width: 390)        }        // Home's own pieces: the head in its states, the tool row, the grid.        shoot("board-head", BoardHead(name: "Cotton", who: "Asha and 2 others", asked: 3, done: 2,                                      syncLine: "Catching up · 40%", syncFraction: 0.4,                                      onChange: {}, onAsked: {}, onDone: {}, onWho: {}), width: 393)        shoot("board-head-bare", BoardHead(name: "A very long database name that wraps", who: "", asked: 0, done: 0,                                           onChange: nil, onAsked: {}, onDone: {}, onWho: {}), width: 393)        let tiles = [GridTile.home, GridTile.tools]        shoot("board-tool-row", HomeToolRow(tiles: tiles, onOpen: { _ in }), width: 393)        for columns in [2, 4] {            for size in [BoardToolsSize.large, .small] {                shoot("board-tool-grid-\(columns)-\(size)", BoardToolGrid(tiles: tiles, columns: columns, size: size,                                                                       faint: [GridTile.home.key], onOpen: { _ in }), width: 393)            }        }        // The rows as the core words them (`shell.today`'s `parts.asked`).        let asked = AskedKey.allCases.map {            AskedItem(key: $0, count: 2, label: Self.askedWords[$0] ?? $0.rawValue, path: $0 == .assistantsAsked ? "/decide" : "/")        }        for count in [2, asked.count] {            shoot("board-asked-\(count)", AskedBand(items: Array(asked.prefix(count)), onOpen: { _ in }), width: 393)        }        // Home's bands as the shipped Home board declares them, over a read        // that has something for each: the notices, Asked of you, Done for you.        let home = HomeModel(            core: ScriptedCore([CottonMethod.shellToday: .ok(Self.homeAnswer)]),            toasts: ToastCenter(scheduler: ManualToastScheduler()))        await home.load()        let context = BoardHome(model: home, databaseName: "Cotton", project: nil, now: now)        var notices = try BoardEntry.noticesForTests()        notices.notices = home.answer?.parts.notices ?? []        for width in [393, 390] as [CGFloat] {            shoot("board-notices-\(Int(width))", BoardNotices(context: context, entry: notices), width: width)            shoot("board-asked-list-\(Int(width))", BoardAskedList(home: home, items: home.askedItems), width: width)            shoot("board-done-list-\(Int(width))", BoardDoneList(home: home, now: now, items: home.doneItems), width: width)        }        try manifest.joined(separator: "\n").appending("\n")            .write(to: out.appendingPathComponent("manifest.txt"), atomically: true, encoding: .utf8)    }    /// Asked of you's rows in the core's words, two of each.    private static let askedWords: [AskedKey: String] = [        .joinRequests: "2 devices asking to join", .assistantsAsked: "2 questions from assistants",        .invites: "2 invites to answer", .passwords: "2 passwords to look at",        .aiAccess: "2 assistants asking for access",    ]    /// A Home answer with something for every band: two assistants' questions    /// and an invite, a filed thought and a junk day, and work in hand.    private static var homeAnswer: String {        TodayAnswerJSON.answer(            asked: [                TodayAnswerJSON.asked("assistantsAsked", count: 2, label: "2 questions from assistants", path: "/decide"),                TodayAnswerJSON.asked("invites", count: 1, label: "1 invite to answer", path: "/calendar?show=invites"),            ],            done: [                TodayAnswerJSON.done("filed", id: "t-1", label: "Filed as a todo", text: "Buy invented milk", when: "2 h ago"),                TodayAnswerJSON.done(                    "junkFiled", id: "2026-10-08", label: "Filed 3 senders as junk", text: "Invented Deals", when: "yesterday",                    action: "change"),            ],            notices: [TodayAnswerJSON.notice("workingOn", words: "Working on 2 · Invented errand")])    }    /// Rasterised by Core Graphics into one CPU bitmap, as `ThemeSnapshotTests`    /// does, so the same view is the same bytes every time.    private func pixels(_ view: some View, width: CGFloat) -> (CGSize, Data)? {        let renderer = ImageRenderer(content: view            .environment(Navigator())            .environment(\.colorScheme, .light)            .frame(width: width))        var drawn: (CGSize, Data)?        renderer.render(rasterizationScale: 1) { size, draw in            let w = Int(size.width.rounded(.up)), h = Int(size.height.rounded(.up))            guard w > 0, h > 0, let context = CGContext(                data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,                space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue),                let data = context.data else { return }            draw(context)            drawn = (CGSize(width: w, height: h), Data(bytes: data, count: context.bytesPerRow * h))        }        return drawn    }    private func write(_ bytes: Data, size: CGSize, to url: URL) {        let w = Int(size.width), h = Int(size.height)        guard let provider = CGDataProvider(data: bytes as CFData),              let image = CGImage(width: w, height: h, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: w * 4,                                  space: CGColorSpaceCreateDeviceRGB(),                                  bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),                                  provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent),              let dest = CGImageDestinationCreateWithURL(url as CFURL, UTType.png.identifier as CFString, 1, nil)        else { return }        CGImageDestinationAddImage(dest, image, nil)        CGImageDestinationFinalize(dest)    }}