Cotton code
129 lines · 8.0 KB · SwiftRaw
import CoreGraphicsimport CottonValuesimport Foundationimport PDFKitimport XCTest@testable import CottonUI/// One full-screen viewer for photos, videos and documents (lane viewer,/// 15 Oct 2026). Before it there were four — a photo's overlay, the chat's/// gallery sheet, the attachments pager, the document sheet — and an inline/// film player, each with its own zoom, its own close and its own idea of/// what a swipe did. These guards keep it one.final class OneViewerTests: XCTestCase {    private static let viewerFolder = "CottonUI/Viewer/"    /// An app with its own look and its own viewer (the redesigns, 20 Nov 2026: each app is its own object,    /// nothing shared between apps). One file, one drawer each; a row whose file stops drawing it fails.    static let ownViewers: [String: (pattern: String, reason: String)] = [        "CottonUI/Chat/ChatViewer.swift": (            #"\bAVPlayerViewController\b"#,            "Comms draws a bubble's films in its own viewer, in its own look (assets/design/chat/DECISIONS.md: nothing from the old shared look on any screen); the system's player plays them"),        "CottonUI/Notes/NotesFileViewer.swift": (            #"\bPDFView\b"#,            "Words opens the files a note carries read-only in its own reader, in its own look (assets/design/notes/DECISIONS.md, Files a note carries, read-only: owner 22 Nov 2026; 7eac12cb78): PDFKit draws a PDF's pages"),    ]    func testViewerActsUseTheDeckFanWithoutOpeningAnotherDeck() throws {        let code = try AppSources.all().first { $0.0 == "CottonUI/Viewer/MediaViewer.swift" }?.1 ?? ""        XCTAssertTrue(code.contains("EditingFan(editor: editor"))        XCTAssertTrue(code.contains("editor.openActs("))        XCTAssertFalse(code.contains("TablePageRoute("))    }    /// A document owns its scroll, irrespective of speed, distance or    /// direction. Only a picture/film can use the upward Details shortcut.    func testDocumentDragsNeverOpenTheRecordCard() {        for translation in [CGSize(width: 0, height: -120), CGSize(width: 8, height: -600),                            CGSize(width: 0, height: 400), CGSize(width: 400, height: -200)] {            XCTAssertFalse(ViewerDetailsGesture.opens(kind: .document, zoomed: false, translation: translation))        }        for kind in [ViewerItem.Kind.photo, .video] {            XCTAssertTrue(ViewerDetailsGesture.opens(kind: kind, zoomed: false, translation: CGSize(width: 0, height: -120)))            XCTAssertFalse(ViewerDetailsGesture.opens(kind: kind, zoomed: true, translation: CGSize(width: 0, height: -120)))            XCTAssertFalse(ViewerDetailsGesture.opens(kind: kind, zoomed: false, translation: CGSize(width: 300, height: -120)))        }    }    /// RULE: Only the viewer (CottonUI/Viewer) draws media full screen — PDFKit's views, a film's layer or player, Quick Look — so every opener routes to the one viewer and no second full-screen media view grows back.    func testOnlyTheViewerDrawsMediaWhole() throws {        let sources = try AppSources.all()        XCTAssertFalse(sources.isEmpty, "the sweep read no sources")        let drawers = [#"\bPDFView\b"#, #"\bPDFThumbnailView\b"#, #"\bAVPlayerLayer\b"#, #"\bVideoPlayer\("#,                       #"\bAVPlayerViewController\b"#, #"\bQLPreviewController\b"#, #"\bQLPreviewView\b"#]        var offenders: [String] = []        var ownTripped: Set<String> = []        for (name, text) in sources where !name.hasPrefix(Self.viewerFolder) {            let code = SourceSweep.withoutComments(text)            for pattern in drawers where try !SourceSweep.matches(pattern, in: code).isEmpty {                if Self.ownViewers[name]?.pattern == pattern {                    ownTripped.insert(name)                    continue                }                offenders.append("\(name): \(pattern)")            }        }        XCTAssertEqual(offenders, [], "media drawn whole outside the one viewer — open it through `viewerPresenter` instead")        for (name, own) in Self.ownViewers {            XCTAssertTrue(ownTripped.contains(name), "\(name) no longer draws \(own.pattern) (\(own.reason)) — take its row out")        }    }    /// RULE: Every line the viewer says is the media definition's `viewer.words`, so a rewording is data: no file under CottonUI/Viewer writes a sentence of its own into a Text or a Button.    func testTheViewerSaysOnlyTheDefinitionsWords() throws {        let kit = TableDefinitions(FixtureDefinitions.load(from: try TestResources.bundle()).definitions)        let words = try XCTUnwrap(ViewerWords.reading(kit), "the kit's media definition carries the viewer's words")        XCTAssertFalse(words.close.isEmpty)        for (name, text) in try AppSources.all() where name.hasPrefix(Self.viewerFolder) {            let code = SourceSweep.withoutComments(text)            XCTAssertTrue(try SourceSweep.matches(#"\b(Text|Button|TextField)\("[A-Za-z]"#, in: code).isEmpty, "\(name) writes its own words")        }    }    /// RULE: A 40-page PDF opens to its first page drawn at screen size in under 300 ms: PDFKit reads the file's table and one page, never the whole document.    @MainActor    func testAFortyPagePDFOpensToItsFirstPageQuickly() async throws {        let url = FileManager.default.temporaryDirectory.appendingPathComponent("viewer-budget-\(UUID().uuidString).pdf")        defer { try? FileManager.default.removeItem(at: url) }        try Self.writePDF(pages: 40, to: url)        let started = Date()        let opened = await ViewerPDFModel.open(url)        let document = try XCTUnwrap(opened)        let first = try XCTUnwrap(document.page(at: 0))        _ = first.thumbnail(of: CGSize(width: 1179, height: 1668), for: .mediaBox)        let took = Date().timeIntervalSince(started)        XCTAssertEqual(document.pageCount, 40)        XCTAssertLessThan(took, 0.3, "the first page took \(Int(took * 1000)) ms")    }    /// The whole set, opened on the place tapped: a thread's pictures and films in order, each captioned with its own message's words.    func testAThreadOpensOnThePictureTapped() throws {        let photo: RecordValue = .list([.object(["key": .text("a"), "contentType": .text("image/jpeg")]), .object(["key": .text("b"), "contentType": .text("audio/mp4"), "kind": .text("voice")])])        let film: RecordValue = .list([.object(["key": .text("c"), "contentType": .text("video/mp4")])])        let set = try XCTUnwrap(ViewerThread.set(of: [            ViewerThread.Message(id: "m1", media: photo, words: "lunch"),            ViewerThread.Message(id: "m2", media: film, words: "the walk"),        ], opening: ViewerThread.itemID("m2", 0)))        XCTAssertEqual(set.items.map(\.id), [ViewerThread.itemID("m1", 0), ViewerThread.itemID("m2", 0)], "a voice note is not swiped through")        XCTAssertEqual(set.start, 1)        XCTAssertEqual(set.items.map(\.caption), ["lunch", "the walk"], "a swipe shows the next message's words, not the opened one's")        XCTAssertEqual(set.items[1].kind, .video)        XCTAssertNil(set.items[0].record, "with no table named, a chat picture has no record — Details shows its facts")        let filed = try XCTUnwrap(ViewerThread.set(of: [ViewerThread.Message(id: "m1", media: photo, words: nil, table: "message")], opening: ViewerThread.itemID("m1", 0)))        XCTAssertEqual(filed.items[0].record, ViewerRecord(table: "message", id: "m1"), "a thread's picture raises its message as Details")    }    private static func writePDF(pages: Int, to url: URL) throws {        var box = CGRect(x: 0, y: 0, width: 612, height: 792)        guard let context = CGContext(url as CFURL, mediaBox: &box, nil) else { throw CocoaError(.fileWriteUnknown) }        for page in 0..<pages {            context.beginPDFPage(nil)            context.setFillColor(CGColor(gray: Double(page % 5) / 5, alpha: 1))            for line in 0..<40 { context.fill(CGRect(x: 40, y: 40 + line * 18, width: 400 + (line * 7 % 120), height: 10)) }            context.endPDFPage()        }        context.closePDF()    }}