import Foundation import RastrilloApple import XCTest @testable import DocsKit /// The four deferred-flush triggers (spec 2026-11-22 ยง7 Design 6, finding /// 2; inputPaused and didRender are not triggers, see the spec): /// a publication arrives while something stops the text view taking it, /// and *no later publication* follows. When that something clears, its /// event alone must bring the storage to a whole render of the newest /// projection. The production `DocsModel` and replica, an in-memory /// server, and a real `DocsTextView`; the live stream is closed after open, /// so nothing else publishes. @MainActor final class FlushTriggerTests: XCTestCase { private var server: LoopServer! private var model: DocsModel! private var text: DocsTextView! override func setUp() async throws { DocsFonts.register() server = LoopServer() try await server.seed(LoopFixture.everything) model = DocsModel(client: server) text = DocsTextView(frame: CGRect(x: 0, y: 0, width: 640, height: 800)) model.surface.attach(text) await model.open("doc") model.suspendLiveUpdates() } override func tearDown() async throws { await model?.stop() model = nil; text = nil; server = nil } private var shown: NSAttributedString { model.surface.content } private func assertDrawn(_ what: String, file: StaticString = #filePath, line: UInt = #line) throws { let projection = try XCTUnwrap(model.projection, file: file, line: line) SurfaceFixture.assertMatchesWholeRender(shown, projection, images: [:], what, file: file, line: line) } private func until(_ what: String, _ condition: () -> Bool) async throws { let deadline = ContinuousClock.now + .seconds(5) while !condition() { guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") } try await Task.sleep(for: .milliseconds(2)) } } private func typeInTheMiddle(_ characters: String) { let line = (shown.string as NSString).range(of: LoopFixture.middle) Keyboard.select(NSRange(location: NSMaxRange(line), length: 0), in: text) Keyboard.type(characters, in: text) } /// A publication the replica did not make: block `index` changed. private func fabricated(generation: UInt64, changing index: Int) throws -> DocumentSurface.Publication { var projection = try XCTUnwrap(model.projection) let node = projection.children[index] projection.children[index] = SurfaceFixture.paragraph(node.id, "Changed while waiting.") return DocumentSurface.Publication(generation: generation, projection: projection, revision: model.surface.appliedRevision + 1, dirty: [node.id]) } /// (a) A publication applied, nothing in the way: drawn at once. func testAPublicationIsDrawnWhenItArrives() throws { try assertDrawn("open") let publication = try fabricated(generation: model.projectionGeneration, changing: 1) model.surface.apply(publication) SurfaceFixture.assertMatchesWholeRender(shown, publication.projection, "a publication with nothing in the way") } /// (b) The publication from typing arrives while the edit queue is /// still draining; the queue's end alone draws it. A Return, so the /// publication differs from what the text view shows optimistically: /// the new paragraph gets its own block id only from it. func testTheEditQueueDrainingDrawsTheWaitingPublication() async throws { var deferred = 0 model.surface.willApply = { [unowned self] _ in if model.hasPendingInput { deferred = model.surface.publicationsReceived } } typeInTheMiddle(" typed\nNew") try await until("the queue drained") { !model.hasPendingInput } XCTAssertGreaterThan(deferred, 0, "a publication arrived while input was pending") XCTAssertEqual(model.surface.publicationsReceived, deferred, "no later publication") try assertDrawn("after the queue drained") XCTAssertTrue(shown.string.contains(LoopFixture.middle + " typed\nNew")) } /// (c) Composition starts as a publication arrives; ending it (with no /// text, so nothing is sent) alone draws the publication. func testCompositionEndingDrawsTheWaitingPublication() async throws { var composed = false model.surface.willApply = { [unowned self] _ in guard !composed else { return } composed = true Self.mark("", in: text) } typeInTheMiddle("x") try await until("the queue drained") { !model.hasPendingInput } XCTAssertTrue(composed) let received = model.surface.publicationsReceived let waiting = try XCTUnwrap(model.surface.newest) XCTAssertGreaterThan(waiting.revision, model.surface.appliedRevision, "the publication waits for the composition") text.unmarkText() XCTAssertEqual(model.surface.publicationsReceived, received, "no later publication") XCTAssertEqual(model.surface.appliedRevision, waiting.revision) try assertDrawn("after the composition ended") } /// (d) A publication for a generation the model has not reached waits; /// the generation catching up alone draws it. func testTheGenerationCatchingUpDrawsTheWaitingPublication() throws { let next = model.projectionGeneration + 1 let publication = try fabricated(generation: next, changing: 1) model.surface.apply(publication) XCTAssertLessThan(model.surface.appliedRevision, publication.revision, "not the current generation yet") model.projectionGeneration = next SurfaceFixture.assertMatchesWholeRender(shown, publication.projection, "after the generation caught up") } static func mark(_ word: String, in text: DocsTextView) { #if os(macOS) text.setMarkedText(word, selectedRange: NSRange(location: word.utf16.count, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0)) #else text.setMarkedText(word, selectedRange: NSRange(location: word.utf16.count, length: 0)) #endif } }