// // ProseRekeyTests.swift // Museion // // #142 (F1): "a keystroke beside a fold re-keys it in place" — Given a // folded list and the caret elsewhere, When a single-line edit lands, // Then the fold survives with key + hidden scope shifted by the edit // delta (no whole-document rescan or restyle), and a fold whose marker // line was edited dies with its scope restored to view. // // Two suites: the view-level pipeline (shouldChangeText records → // storage mutates → refreshFolds re-keys in place) and the pure // `rekey` math. // import AppKit @testable import Museion import Testing @MainActor struct ProseFoldRekeyTests { private func makeView(_ text: String) -> ProseListTextView { let textView = ProseListTextView() textView.isRichText = false textView.textStorage?.setAttributedString(ProsePresenter.attribute(text)) return textView } /// The coordinator's keystroke pipeline — shouldChangeText records the /// single-line edit, the storage mutates, refreshFolds re-keys in place. private func type( _ replacement: String, in range: NSRange, of textView: ProseListTextView, ) { textView.shouldChangeText(in: range, replacementString: replacement) textView.textStorage?.replaceCharacters(in: range, with: replacement) textView.refreshFolds() } @Test func `single-line edit above rekeys fold in place`() throws { let text = "intro\n\n- parent\n - child\n" let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) type("xx", in: NSRange(location: 0, length: 0), of: textView) // in the intro line #expect(textView.folds == [ ProseListTextView.Fold( key: parent.markerLine.location + 2, lineText: "- parent", scope: NSRange(location: parent.foldScope.location + 2, length: parent.foldScope.length), ), ]) // the shifted scope is still hidden — nothing swapped it away let font = try #require( textView.textStorage?.attribute(.font, at: parent.foldScope.location + 2, effectiveRange: nil) as? NSFont, ) #expect(font.pointSize < 1) } @Test func `typing on the marker line kills the fold and restores its scope`() throws { let text = "- parent\n - child\n" let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) type("x", in: NSRange(location: 0, length: 0), of: textView) // at the line head #expect(textView.folds.isEmpty) let font = try #require( textView.textStorage?.attribute(.font, at: parent.foldScope.location + 1, effectiveRange: nil) as? NSFont, ) #expect(font.pointSize > 10) // the dead scope is visible again } @Test func `multi-line edit still takes the full pass`() throws { let text = "- parent\n - child\n" let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) type("x\n\n", in: NSRange(location: 0, length: 0), of: textView) #expect(textView.folds == [ ProseListTextView.Fold( key: parent.markerLine.location + 3, lineText: "- parent", scope: NSRange(location: parent.foldScope.location + 3, length: parent.foldScope.length), ), ]) } @Test func `newline deletion routes to the full pass`() throws { // Forward-delete at the parked caret removes the marker line's \n and // merges the child into it — the OLD text contains a line break, so // the edit must NOT take the cheap path. The cheap path's delta math // would keep the fold alive on a no-longer-parent line; the full pass // re-scans and kills it. Pins the isSingleLine(old) guard. let text = "intro\n\n- parent\n - child\n" let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) type("", in: NSRange(location: 15, length: 1), of: textView) // delete the \n #expect(textView.string == "intro\n\n- parent - child\n") #expect(textView.folds.isEmpty) // merged line has no children → fold dies } @Test func `crlf in the edited text routes to the full pass`() throws { // "\r\n" is ONE Swift grapheme equal to neither "\n" nor "\r" — a // literal line-break compare lets this deletion ride the cheap path, // keeping a stale fold whose hidden scope eats half the merged line. // The isNewline gate must route it to the full pass (the #142 audit's // converged finding). let text = "intro\r\n\r\n- parent\r\n - child\r\n" let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) type("", in: NSRange(location: 17, length: 2), of: textView) // delete the CRLF after "- parent" #expect(textView.string == "intro\r\n\r\n- parent - child\r\n") #expect(textView.folds.isEmpty) // merged line has no children → fold dies let font = try #require( textView.textStorage?.attribute(.font, at: 17, effectiveRange: nil) as? NSFont, ) #expect(font.pointSize > 10) // the merged line is fully visible } @Test func `structural outdent always takes the full pass`() throws { // #142 audit: a childless UNTERMINATED block's outdent is a single-line // replacement — apply() must clear pendingPlainEdit or the cheap path // keeps the dead fold's scope hidden (the line appears lost). let text = "- p\n - c1" let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) let child = try #require(ProseList.item(at: 6, in: text)) textView.setSelectedRange(NSRange(location: 6, length: 0)) textView.performOutdent(child) textView.refreshFolds() // the coordinator's tail — no delegate headless #expect(textView.string == "- p\n- c1") #expect(textView.folds.isEmpty) // "- p" lost its only child → fold dies let font = try #require( textView.textStorage?.attribute(.font, at: 4, effectiveRange: nil) as? NSFont, ) #expect(font.pointSize > 10) // the outdented line is visible } @Test func `scope interior edit rehides the line and parks the caret`() throws { // The cheap path's view glue, with the coordinator simulated: the // paragraph reattribute un-hides the edited hidden line, then // refreshFolds must re-hide it and park the caret at the marker end. // The edit lands in the SECOND hidden line — the scope-head probe // can't catch this damage (the first hidden line is untouched), so // only the rehide glue covers it. let text = "intro\n\n- parent\n - c1\n - c2\n" let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) let edit = NSRange(location: 25, length: 0) // inside the second hidden line " - c2" textView.setSelectedRange(edit) textView.shouldChangeText(in: edit, replacementString: "x") textView.textStorage?.replaceCharacters(in: edit, with: "x") // the coordinator's paragraph reattribute (PostEditorView order) let paragraph = (textView.string as NSString).paragraphRange(for: textView.selectedRange()) try ProsePresenter.reattribute(#require(textView.textStorage as? NSMutableAttributedString), paragraphRange: paragraph) textView.refreshFolds() #expect(textView.folds == [ ProseListTextView.Fold(key: 7, lineText: "- parent", scope: NSRange(location: 16, length: 15)), ]) let font = try #require( textView.textStorage?.attribute(.font, at: 25, effectiveRange: nil) as? NSFont, ) #expect(font.pointSize < 1) // re-hidden by the glue #expect(textView.selectedRange().location == 15) // parked at the marker end } @Test func `wholesale restyle self-heals into the full pass`() throws { // The fence-flip branch replaces the whole storage AFTER the edit was // recorded — the cheap path's probe must notice the hidden styling is // gone and fall back, or the fold would render open-but-invisible. // (Edit lands in the intro line, above the fold, so the fold itself // survives the re-key and only the probe can catch the damage.) let text = "intro\n\n- parent\n - child\n" let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x") textView.textStorage?.setAttributedString(ProsePresenter.attribute(textView.string)) textView.refreshFolds() #expect(textView.folds.count == 1) let font = try #require( textView.textStorage?.attribute(.font, at: textView.folds[0].scope.location, effectiveRange: nil) as? NSFont, ) #expect(font.pointSize < 1) // re-hidden by the full pass } } @MainActor struct ProseRekeyMathTests { /// intro | blank | parent + two children | tail — one foldable parent. private let text = "intro\n\n- parent\n - child one\n - child two\n- tail\n" // layout: marker line (7,9), content end 15, scope (16,28), tail at 44. private func makeFold() throws -> ProseListTextView.Fold { let parent = try #require(ProseList.parents(in: text).first) return ProseListTextView.Fold(key: parent.markerLine.location, lineText: "- parent", scope: parent.foldScope) } @Test func `edit above shifts key and scope`() throws { let fold = try makeFold() let result = ProseListTextView.rekey( folds: [fold], edit: NSRange(location: 0, length: 0), delta: 2, in: "xx" + text, ) #expect(result.folds == [ProseListTextView.Fold(key: 9, lineText: "- parent", scope: NSRange(location: 18, length: 28))]) #expect(result.diedScopes.isEmpty) #expect(result.rehide == nil) #expect(result.park == nil) } @Test func `edit below the scope leaves the fold untouched`() throws { let fold = try makeFold() let result = ProseListTextView.rekey( folds: [fold], edit: NSRange(location: 44, length: 0), delta: 1, in: text + "z", ) #expect(result.folds == [fold]) #expect(result.diedScopes.isEmpty) #expect(result.rehide == nil) } @Test func `editing the marker line kills the fold`() throws { let fold = try makeFold() let result = ProseListTextView.rekey( folds: [fold], edit: NSRange(location: 7, length: 8), delta: -3, in: "intro\n\n- god\n - child one\n - child two\n- tail\n", ) #expect(result.folds.isEmpty) #expect(result.diedScopes == [NSRange(location: 13, length: 28)]) // translated for the un-hide #expect(result.rehide == nil) #expect(result.park == nil) } @Test func `insertions at either marker-content boundary kill too`() throws { let fold = try makeFold() // at the head (el == key) and at the park position (el == contentEnd) for location in [7, 15] { let result = ProseListTextView.rekey( folds: [fold], edit: NSRange(location: location, length: 0), delta: 1, in: "intro\n\n- parentx\n - child one\n - child two\n- tail\n", ) #expect(result.folds.isEmpty, "insertion at \(location) should kill the fold") #expect(result.diedScopes.count == 1) } } @Test func `deletion inside the scope shrinks it and flags a re-hide`() throws { let fold = try makeFold() // delete "one" (26,3) inside the first hidden line let result = ProseListTextView.rekey( folds: [fold], edit: NSRange(location: 26, length: 3), delta: -3, in: "intro\n\n- parent\n - child \n - child two\n- tail\n", ) #expect(result.folds == [ProseListTextView.Fold(key: 7, lineText: "- parent", scope: NSRange(location: 16, length: 25))]) #expect(result.diedScopes.isEmpty) // the edited line, clipped to the scope — the paragraph reattribute // un-hid it and it must go back under #expect(result.rehide == NSRange(location: 16, length: 11)) #expect(result.park == 15) // caret parks at the marker line's content end } } // MARK: - #142 typing budget (brief-24: fold-typing-budget-pin) /// The typing-cost guard the landed re-key optimization never had: a quiet /// regression that routes single-line typing edits back to the full pass /// would keep every correctness pin above green (the full pass re-derives /// CORRECT folds — it is only O(buffer) per keystroke). These pins count /// scanned LINES through the real keystroke pipeline (shouldChangeText → /// storage mutate → refreshFolds) — an operation count, never wall-time — /// and hold the budget flat as the buffer doubles: the cheap path's cost /// rides the fold count, not the document size. extension ProseFoldRekeyTests { /// One folded list + `filler` plain lines below it. Plain filler lines /// are not list markers, so they add buffer without adding parents. private func budgetText(filler: Int) -> String { "intro\n\n- parent\n - child\n" + (0 ..< filler).map { "filler line \($0)\n" }.joined() } /// Type one character through the real pipeline at N and 2N filler lines /// and return each run's scanned-line total. private func typingScans(filler: Int) -> Int { let text = budgetText(filler: filler) let textView = makeView(text) guard let parent = ProseList.parents(in: text).first else { preconditionFailure("fixture must arm a parent") } textView.toggleFold(parent) var scanned = 0 // The coordinator's keystroke tail with the budget instrument armed. textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x") textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x") textView.refreshFolds { scanned += $0 } return scanned } @Test func `typing beside a fold scans zero lines at N and 2N`() { let atN = typingScans(filler: 200) let at2N = typingScans(filler: 400) #expect(atN == 0, "single-line typing edit took the full pass at N: \(atN) lines scanned") #expect(at2N == 0, "single-line typing edit took the full pass at 2N: \(at2N) lines scanned") // The budget itself: doubling the buffer must not move it. #expect(atN == at2N) } @Test func `coordinator keystroke pipeline scans zero lines beside a fold`() throws { // The through-seam pin (aegis ruling): the REAL entry — insertText // through the PostEditorView coordinator's delegate tail // (shouldChangeText → storage → textDidChange → refreshFolds) — // never a direct test call. The instance hook (onLineScan) is the // budget window for paths that call refreshFolds() bare. let text = budgetText(filler: 200) let textView = makeView(text) let parent = try #require(ProseList.parents(in: text).first) textView.toggleFold(parent) var scanned = 0 textView.onLineScan = { scanned += $0 } let session = EditorSession( target: .externalFile(URL(fileURLWithPath: "/dev/null")), debounce: .seconds(3600), ) let coordinator = ProseTextView.Coordinator( representable: ProseTextView(session: session, dropBridge: ProseDropBridge(), routeDrop: { _ in false }), ) textView.delegate = coordinator // production wiring (PostEditorView) textView.setSelectedRange(NSRange(location: 0, length: 0)) textView.insertText("x", replacementRange: NSRange(location: 0, length: 0)) #expect(scanned == 0, "real keystroke took the full pass: \(scanned) lines") #expect(textView.folds.count == 1) // and the fold survived the real pipeline // Liveness in the same harness: a structural insert through the same // coordinator MUST scan the whole buffer (206 — see the control's // arithmetic) — proving the instance window counts real work. scanned = 0 textView.setSelectedRange(NSRange(location: 0, length: 0)) textView.insertText("y\n\n", replacementRange: NSRange(location: 0, length: 0)) #expect(scanned == 206, "instance window lost exact accounting: \(scanned)") } @Test func `full pass scans scale with the buffer at N and 2N`() { /// The control that keeps the zero-pin honest: route the SAME edit /// shape to the full pass (a multi-line replacement — structural /// edits never take the cheap path) and the instrument must report /// the whole buffer, growing with it. If the observer ever goes /// dead (unwired, wrong seam), this fails — the zero-pin above can /// never pass vacuously. func fullPassScans(filler: Int) -> Int { let text = budgetText(filler: filler) let textView = makeView(text) guard let parent = ProseList.parents(in: text).first else { preconditionFailure("fixture must arm a parent") } textView.toggleFold(parent) var scanned = 0 textView.shouldChangeText(in: NSRange(location: 0, length: 0), replacementString: "x\n\n") textView.textStorage?.replaceCharacters(in: NSRange(location: 0, length: 0), with: "x\n\n") textView.refreshFolds { scanned += $0 } return scanned } let atN = fullPassScans(filler: 200) let at2N = fullPassScans(filler: 400) // 4 fixture lines + filler + 2 from the split intro line ("x\n\n" // turns intro into three lines) — exactly the buffer's line count. #expect(atN == 206, "control lost exact line accounting: \(atN)") #expect(at2N == 406, "control lost exact line accounting: \(at2N)") #expect(at2N > atN, "the instrument must scale with the buffer") } }