Cotton code
261 lines · 11.3 KB · SwiftRaw
// The rest of the design system's behaviour: the type scale, the reorder// maths, the receipt's window and the projects rule.//// The type scale (the RATCHET's rule survives the rewrite, its grep over// JavaScript does not), the reorder maths and the projects sheet's pure half.//// DROPPED, with reasons:////   • Every render assertion over the previous app's components. They asserted//     against a view tree and a router mock, both of which die with the old//     runtime (design P20). What was BEHAVIOUR in them is re-proved here//     against the model — the reorder maths, the toast window, the projects//     rule; what was PRESENTATION (a testID exists, a class is applied) is//     verified on the device, per this repo's own rule that layout is not//     tested automatically.//   • the type ratchet's five greps. Four of them ban things that cannot exist//     here (a font loader, a downloaded font package, tailwind font-family//     utilities, tailwind text-size utilities). The fifth — "renders text only//     through the primitive" — survives as `testEveryRoleIsReachableOnlyByName`//     plus the colour guard, which together are what made the ratchet worth//     having.//   • the toast's `toastTopOffset` cases. The offset existed because the old//     toast library pinned to window top 0 with no safe-area awareness;//     SwiftUI's safe area is not optional, so the constant and its four tests//     go with the library.import Foundationimport SwiftUIimport XCTest@testable import CottonUIfinal class TypeScaleTests: XCTestCase {}final class ReorderTests: XCTestCase {    private let even: [CGFloat] = [50, 50, 50, 50]    private let mixed: [CGFloat] = [40, 80, 30, 60]    func testRowOffsetsAreTheRunningTops() {        XCTAssertEqual(Reorder.rowOffsets(mixed), [0, 40, 120, 150])        XCTAssertEqual(Reorder.rowOffsets([]), [])    }    func testAnUnmovedRowStaysWhereItIs() {        // Stable at zero translation: a gap-closed model re-seats a tall row        // over a short neighbour the instant it is picked up.        for index in 0..<mixed.count {            XCTAssertEqual(Reorder.dropIndex(heights: mixed, from: index, translationY: 0), index)        }    }    func testCentrePassesCentreDraggingDown() {        // Row 0 is 50 tall; row 1's resting centre is at 75. The first swap        // needs half of this row plus half of the next.        XCTAssertEqual(Reorder.dropIndex(heights: even, from: 0, translationY: 49), 0)        XCTAssertEqual(Reorder.dropIndex(heights: even, from: 0, translationY: 51), 1)        XCTAssertEqual(Reorder.dropIndex(heights: even, from: 0, translationY: 120), 2)    }    func testCentrePassesCentreDraggingUp() {        XCTAssertEqual(Reorder.dropIndex(heights: even, from: 3, translationY: -49), 3)        XCTAssertEqual(Reorder.dropIndex(heights: even, from: 3, translationY: -51), 2)        XCTAssertEqual(Reorder.dropIndex(heights: even, from: 3, translationY: -120), 1)    }    func testTheAnswerIsMonotoneSoItCannotOscillate() {        var last = 0        for step in stride(from: CGFloat(0), through: 200, by: 5) {            let to = Reorder.dropIndex(heights: mixed, from: 0, translationY: step)            XCTAssertGreaterThanOrEqual(to, last, "went backwards at \(step)")            last = to        }    }    func testAnIndexOutsideTheListIsReturnedUntouched() {        XCTAssertEqual(Reorder.dropIndex(heights: even, from: -1, translationY: 100), -1)        XCTAssertEqual(Reorder.dropIndex(heights: even, from: 9, translationY: 100), 9)    }    func testPassiveRowsSlideOneActiveHeightToKeepTheGapOpen() {        // Dragging DOWN from 0 to 2: rows 1 and 2 move up by the active height.        XCTAssertEqual(Reorder.passiveShift(index: 1, from: 0, to: 2, activeHeight: 50), -50)        XCTAssertEqual(Reorder.passiveShift(index: 2, from: 0, to: 2, activeHeight: 50), -50)        XCTAssertEqual(Reorder.passiveShift(index: 3, from: 0, to: 2, activeHeight: 50), 0)        // Dragging UP from 3 to 1: rows 1 and 2 move down.        XCTAssertEqual(Reorder.passiveShift(index: 1, from: 3, to: 1, activeHeight: 50), 50)        XCTAssertEqual(Reorder.passiveShift(index: 2, from: 3, to: 1, activeHeight: 50), 50)        XCTAssertEqual(Reorder.passiveShift(index: 0, from: 3, to: 1, activeHeight: 50), 0)    }    func testTheActiveRowAndANoOpNeverShift() {        XCTAssertEqual(Reorder.passiveShift(index: 2, from: 2, to: 0, activeHeight: 50), 0)        XCTAssertEqual(Reorder.passiveShift(index: 1, from: 2, to: 2, activeHeight: 50), 0)    }    func testReorderedMovesTheRowAndLeavesTheInputAlone() {        let items = ["a", "b", "c", "d"]        XCTAssertEqual(Reorder.reordered(items, from: 0, to: 2), ["b", "c", "a", "d"])        XCTAssertEqual(Reorder.reordered(items, from: 3, to: 1), ["a", "d", "b", "c"])        XCTAssertEqual(items, ["a", "b", "c", "d"], "the input was mutated")    }    func testReorderedRefusesANoOpOrAnIndexOutsideTheList() {        let items = ["a", "b", "c"]        XCTAssertEqual(Reorder.reordered(items, from: 1, to: 1), items)        XCTAssertEqual(Reorder.reordered(items, from: -1, to: 1), items)        XCTAssertEqual(Reorder.reordered(items, from: 1, to: 9), items)    }}/// A scheduler a test drives. It never sleeps: `advance()` is what makes the/// window pass, so a three-second receipt costs no wall time and the test can/// prove what happens BEFORE the window ends as easily as after.final class ManualToastScheduler: ToastScheduler, @unchecked Sendable {    private final class Pending: ToastTicket, @unchecked Sendable {        var isCancelled = false        let after: TimeInterval        let work: @MainActor () -> Void        init(after: TimeInterval, work: @escaping @MainActor () -> Void) {            self.after = after            self.work = work        }        func cancel() { isCancelled = true }    }    private var pending: [Pending] = []    private(set) var scheduledWindows: [TimeInterval] = []    func schedule(after seconds: TimeInterval, _ work: @escaping @MainActor () -> Void) -> any ToastTicket {        let ticket = Pending(after: seconds, work: work)        pending.append(ticket)        scheduledWindows.append(seconds)        return ticket    }    /// Fire everything whose window has passed and was not called off.    @MainActor func advance() {        let due = pending        pending = []        for ticket in due where !ticket.isCancelled { ticket.work() }    }    var liveCount: Int { pending.filter { !$0.isCancelled }.count }}@MainActorfinal class ToastTests: XCTestCase {    func testAReceiptStandsForThreeSecondsAndThenIsGone() {        let clock = ManualToastScheduler()        let toasts = ToastCenter(scheduler: clock)        toasts.show("Filed under Nilgiri Notes")        XCTAssertEqual(clock.scheduledWindows, [3])        XCTAssertEqual(toasts.current?.message, "Filed under Nilgiri Notes")        clock.advance()        XCTAssertNil(toasts.current)    }    func testTheWINDOWFOLLOWSTheUndo() {        // A receipt CARRYING an undo takes the row-undo window without anyone        // asking: the verb took something out of view, and the person has to        // notice it went, read what happened and reach the word. Defaulting        // both to three seconds made the longer window a constant nobody        // passed.        let clock = ManualToastScheduler()        let toasts = ToastCenter(scheduler: clock)        toasts.show("Bin: Pay the water bill", undo: {})        XCTAssertEqual(clock.scheduledWindows, [ToastWindow.rowUndo])        let plain = ManualToastScheduler()        ToastCenter(scheduler: plain).show("Added todo: call Priya Example, Friday")        XCTAssertEqual(plain.scheduledWindows, [ToastWindow.receipt])        // And a caller who knows better still wins.        let asked = ManualToastScheduler()        ToastCenter(scheduler: asked).show("Uploading", window: 12, undo: {})        XCTAssertEqual(asked.scheduledWindows, [12])    }    /// RULE: A line shown until the next tap has no window: no timer clears it, a tap does, and a tap clears nothing else.    func testALineUntilTheNextTapStandsUntilATap() {        let clock = ManualToastScheduler()        let toasts = ToastCenter(scheduler: clock)        toasts.show("Sign in to find books by name", window: ToastWindow.untilTap)        XCTAssertEqual(clock.scheduledWindows, [], "no timer is armed")        clock.advance()        XCTAssertEqual(toasts.current?.message, "Sign in to find books by name")        toasts.tapped()        XCTAssertNil(toasts.current)        toasts.show("Filed under Nilgiri Notes")        toasts.tapped()        XCTAssertEqual(toasts.current?.message, "Filed under Nilgiri Notes", "a receipt keeps its own window")    }    func testASecondReceiptRestartsTheFullWindowAndReplacesTheFirst() {        let clock = ManualToastScheduler()        let toasts = ToastCenter(scheduler: clock)        toasts.show("first")        toasts.show("second")        XCTAssertEqual(toasts.current?.message, "second")        XCTAssertEqual(clock.liveCount, 1, "the first window was called off, not left running")        XCTAssertEqual(clock.scheduledWindows, [3, 3], "the second got a FULL window, not the remainder")    }    func testUndoRunsTheActAndDropsTheReceipt() {        let clock = ManualToastScheduler()        let toasts = ToastCenter(scheduler: clock)        var undone = 0        toasts.show("Filed under Nilgiri Notes", undo: { undone += 1 })        toasts.undo()        XCTAssertEqual(undone, 1)        XCTAssertNil(toasts.current)        clock.advance()        XCTAssertEqual(undone, 1, "the window fired again after the undo")    }    func testUndoDoesNothingWhenTheReceiptCarriesNone() {        let toasts = ToastCenter(scheduler: ManualToastScheduler())        toasts.show("That document could not be read.", tone: .error)        toasts.undo()        XCTAssertNotNil(toasts.current, "a receipt with no undo is a sentence, and undo must not clear it")    }    func testAStragglerCannotClearItsReplacement() {        // The rule the sync loop learned the hard way, at receipt scale: only        // the flight that armed a window may clear it.        let clock = ManualToastScheduler()        let toasts = ToastCenter(scheduler: clock)        toasts.show("first")        toasts.show("second")        clock.advance()        // The first ticket was cancelled, so only the second's window fired.        XCTAssertNil(toasts.current)        toasts.show("third")        XCTAssertEqual(toasts.current?.message, "third")    }}final class ProjectsSheetRuleTests: XCTestCase {    private let projects: [ProjectsSheetOption] = [        .init(id: "a", name: "Nilgiri Notes", status: .active),        .init(id: "b", name: "Terrace Rebuild", status: .active),        .init(id: "c", name: "Old Ledger", status: .archived),        .init(id: "d", name: "Closed Season", status: .archived),    ]    func testOffersOnlyActiveProjects() {        // An archived project is not a working context.        let offered = offeredProjects(projects, links: [])        XCTAssertEqual(offered.map(\.id), ["a", "b"])    }    func testKeepsAnArchivedProjectThisRecordIsStillIn() {        // Hiding it would hide a membership that exists.        let offered = offeredProjects(projects, links: [.init(projectId: "c")])        XCTAssertEqual(offered.map(\.id), ["a", "b", "c"])    }}