Tests/OrgEditorAppKitTests/EditorTests.swift
282 lines · 12016 bytes
1import AppKit
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgEditorAppKit
6
7/// An editor in an offscreen window, laid out.
8@MainActor
9final class Harness {
10 let editor: OrgEditor
11 let window: NSWindow
12
13 convenience init(_ text: String) {
14 self.init(DocumentState(bytes: Array(text.utf8)))
15 drainStyling()
16 layout()
17 }
18
19 /// The editor as a window would show it first: background styling not yet run.
20 init(_ document: DocumentState, layout: Bool = true) {
21 _ = NSApplication.shared
22 editor = OrgEditor(document: document)
23 window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 800), styleMask: [.titled], backing: .buffered, defer: false)
24 window.contentView = editor.makeScrollView()
25 window.makeFirstResponder(editor.textView)
26 if layout { self.layout() }
27 }
28
29 func drainStyling() {
30 editor.finishStyling()
31 }
32
33 var textView: NSTextView { editor.textView }
34 var string: String { textView.string }
35
36 func layout() {
37 let manager = editor.textLayoutManager
38 manager.ensureLayout(for: manager.documentRange)
39 }
40
41 /// Text of each laid-out paragraph.
42 var visibleLines: [String] {
43 layout()
44 let manager = editor.textLayoutManager
45 var lines: [String] = []
46 manager.enumerateTextLayoutFragments(from: manager.documentRange.location, options: [.ensuresLayout]) { fragment in
47 let content = manager.textContentManager!
48 let start = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location)
49 let end = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.endLocation)
50 lines.append((self.string as NSString).substring(with: NSRange(location: start, length: end - start)))
51 return true
52 }
53 return lines.filter { !$0.isEmpty }
54 }
55
56 func caret(at offset: Int) {
57 textView.setSelectedRange(NSRange(location: offset, length: 0))
58 }
59
60 var caret: Int { textView.selectedRange().location }
61
62 func offset(of line: String) -> Int {
63 (string as NSString).range(of: line).location
64 }
65
66 func checkInSync() {
67 #expect(editor.document.text == string)
68 #expect(editor.document.tree.green == OrgParser.parse(string).green)
69 }
70}
71
72let outline = "* a\nbody\n** b\nmore\n* c\ntext\n"
73
74@MainActor
75struct FoldingTests {
76 @Test func foldingHidesTheSubtree() {
77 let h = Harness(outline)
78 #expect(h.visibleLines == ["* a\n", "body\n", "** b\n", "more\n", "* c\n", "text\n"])
79 h.caret(at: 1)
80 #expect(h.editor.toggleFoldAtCaret())
81 #expect(h.visibleLines == ["* a\n", "* c\n", "text\n"])
82 h.editor.toggleFoldAtCaret()
83 #expect(h.visibleLines.count == 6)
84 }
85
86 @Test func tabFoldsOnlyOnHeadings() {
87 let h = Harness(outline)
88 h.caret(at: 5)
89 #expect(!h.editor.toggleFoldAtCaret())
90 h.textView.doCommand(by: #selector(NSResponder.insertBacktab(_:)))
91 #expect(h.visibleLines == ["* a\n", "* c\n"])
92 }
93
94 @Test func caretMovesOverFoldedText() {
95 let h = Harness(outline)
96 h.caret(at: 1)
97 h.editor.toggleFoldAtCaret()
98 h.caret(at: 0)
99 h.textView.moveDown(nil)
100 #expect(h.caret >= h.offset(of: "* c") && h.caret < h.offset(of: "text"))
101 h.caret(at: 3)
102 h.textView.moveRight(nil)
103 #expect(h.caret == h.offset(of: "* c"))
104 h.textView.moveLeft(nil)
105 #expect(h.caret == 3)
106 }
107
108 @Test func copyingAcrossAFoldIncludesHiddenText() {
109 let h = Harness(outline)
110 h.caret(at: 1)
111 h.editor.toggleFoldAtCaret()
112 h.textView.setSelectedRange(NSRange(location: 0, length: h.offset(of: "text")))
113 let pasteboard = NSPasteboard(name: NSPasteboard.Name("orgstar-test-\(UUID().uuidString)"))
114 defer { pasteboard.releaseGlobally() }
115 #expect(h.textView.writeSelection(to: pasteboard, types: h.textView.writablePasteboardTypes))
116 #expect(pasteboard.string(forType: .string) == "* a\nbody\n** b\nmore\n* c\n")
117 }
118
119 @Test func foldsFollowEdits() {
120 let h = Harness(outline)
121 h.caret(at: h.offset(of: "* c") + 1)
122 h.editor.toggleFoldAtCaret()
123 h.caret(at: 0)
124 h.textView.insertText("new ", replacementRange: NSRange(location: 2, length: 0))
125 #expect(h.visibleLines == ["* new a\n", "body\n", "** b\n", "more\n", "* c\n"])
126 h.checkInSync()
127 }
128}
129
130@MainActor
131struct EditingTests {
132 @Test func typingKeepsTheDocumentInSync() {
133 let h = Harness(outline)
134 h.caret(at: h.offset(of: "body") + 4)
135 h.textView.insertText(" *bold*", replacementRange: h.textView.selectedRange())
136 h.textView.insertNewline(nil)
137 h.textView.insertText("* new heading", replacementRange: h.textView.selectedRange())
138 h.textView.deleteBackward(nil)
139 h.checkInSync()
140 #expect(h.editor.document.isDirty)
141 }
142
143 @Test func inputMethodComposition() {
144 let h = Harness("* a\n")
145 h.caret(at: 3)
146 h.textView.setMarkedText("か", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
147 #expect(h.textView.hasMarkedText())
148 h.textView.setMarkedText("かん", selectedRange: NSRange(location: 2, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
149 h.textView.insertText("漢", replacementRange: NSRange(location: NSNotFound, length: 0))
150 #expect(!h.textView.hasMarkedText())
151 #expect(h.string == "* a漢\n")
152 h.checkInSync()
153 }
154
155 @Test func undoKeepsTheDocumentInSync() {
156 let h = Harness(outline)
157 h.caret(at: 3)
158 h.textView.insertText("xyz", replacementRange: h.textView.selectedRange())
159 h.textView.breakUndoCoalescing()
160 h.textView.undoManager?.undo()
161 #expect(h.string == outline)
162 h.checkInSync()
163 }
164
165 @Test func styling() throws {
166 let h = Harness("** b\nbody\n")
167 let storage = try #require(h.textView.textStorage)
168 #expect(storage.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor == .clear)
169 let style = try #require(storage.attribute(.paragraphStyle, at: 6, effectiveRange: nil) as? NSParagraphStyle)
170 #expect(style.firstLineHeadIndent == 3 * h.editor.theme.column)
171 h.caret(at: 0)
172 h.textView.insertText("*", replacementRange: NSRange(location: 0, length: 0))
173 let deeper = try #require(storage.attribute(.paragraphStyle, at: 7, effectiveRange: nil) as? NSParagraphStyle)
174 #expect(deeper.firstLineHeadIndent == 4 * h.editor.theme.column)
175 }
176
177 @Test func accessibilityReadsTheWholeText() {
178 let h = Harness(outline)
179 h.caret(at: 1)
180 h.editor.toggleFoldAtCaret()
181 #expect(h.textView.accessibilityValue() as? String == outline)
182 h.textView.setSelectedRange(NSRange(location: 0, length: 3))
183 #expect(h.textView.accessibilitySelectedText() == "* a")
184 #expect(h.textView.accessibilityLine(for: h.offset(of: "* c")) >= 1)
185 }
186
187 @Test func saveWritesAndClearsDirty() throws {
188 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
189 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
190 defer { try? FileManager.default.removeItem(at: folder) }
191 let file = folder.appendingPathComponent("a.org")
192 try Data(outline.utf8).write(to: file)
193 let h = Harness(outline)
194 h.textView.insertText("x", replacementRange: NSRange(location: 0, length: 0))
195 let saver = Saver(fileSystem: CoordinatedFileSystem(), recovery: FileRecoveryStore(directory: folder.appendingPathComponent("r")))
196 #expect(try h.editor.save(using: saver, to: file) == .saved)
197 #expect(!h.editor.document.isDirty)
198 #expect(try String(contentsOf: file, encoding: .utf8) == "x" + outline)
199 }
200}
201
202@MainActor
203struct RestyleTests {
204 func indent(_ h: Harness, at line: String) -> CGFloat? {
205 let style = h.textView.textStorage?.attribute(.paragraphStyle, at: h.offset(of: line), effectiveRange: nil) as? NSParagraphStyle
206 return style.map { $0.firstLineHeadIndent / h.editor.theme.column }
207 }
208
209 @Test func newHeadingReindentsTheLinesItTakesOver() {
210 let h = Harness("* a\none\ntwo\nthree\n")
211 h.textView.insertText("** b\n", replacementRange: NSRange(location: h.offset(of: "two"), length: 0))
212 #expect(indent(h, at: "one") == 2)
213 #expect(indent(h, at: "three") == 3)
214 h.checkInSync()
215 }
216
217 @Test func joiningAwayAHeadingReindentsItsBody() {
218 let h = Harness("* a\none\n** b\ntwo\nthree\n")
219 h.textView.insertText("", replacementRange: NSRange(location: h.offset(of: "** b") - 1, length: 1))
220 #expect(indent(h, at: "three") == 2)
221 h.checkInSync()
222 }
223
224 @Test func typingASpaceAfterAStarMakesAHeading() {
225 let h = Harness("* a\n*x\nbody\nmore\n")
226 h.textView.insertText(" ", replacementRange: NSRange(location: h.offset(of: "*x") + 1, length: 0))
227 #expect(indent(h, at: "more") == 2)
228 h.checkInSync()
229 }
230}
231
232@MainActor
233struct RestyleFuzzTests {
234 /// After each random edit, the restyled text must equal a fresh editor's full styling. Set
235 /// `ORGSTAR_RESTYLE_EDITS` and `ORGSTAR_FUZZ_SEED` for longer runs.
236 @Test func incrementalRestyleEqualsFullRestyle() throws {
237 let environment = ProcessInfo.processInfo.environment
238 var state = UInt64(environment["ORGSTAR_FUZZ_SEED"] ?? "") ?? 20261006
239 let count = Int(environment["ORGSTAR_RESTYLE_EDITS"] ?? "") ?? 300
240 func next(_ bound: Int) -> Int {
241 state = state &* 6364136223846793005 &+ 1442695040888963407
242 return Int((state >> 33) % UInt64(bound))
243 }
244 let pieces = ["* ", "** ", "*", " ", "\n", "x", "*b*", "TODO ", "- ", "| a |", "#+begin_src\n", "#+end_src\n", ":PROPERTIES:\n", ":END:\n", "[[l][d]]", "<2026-10-04 Sun>"]
245 let h = Harness("* a\nbody *b*\n** b\n- item\nmore\n* c\ntext\n")
246 for n in 0..<count {
247 let length = (h.string as NSString).length
248 let start = next(length + 1)
249 let end = min(length, start + next(4))
250 let replacement = next(3) == 0 ? "" : pieces[next(pieces.count)]
251 h.textView.insertText(replacement, replacementRange: NSRange(location: start, length: end - start))
252 let fresh = Harness(h.string)
253 let same = h.textView.textStorage!.isEqual(to: fresh.textView.textStorage!)
254 #expect(same, "edit \(n): \(start)..<\(end) \(replacement.debugDescription) -> \(h.string.debugDescription)")
255 if !same { break }
256 }
257 h.checkInSync()
258 }
259}
260
261@MainActor
262struct InitialStylingTests {
263 @Test func stylesTheFirstScreenThenTheRest() throws {
264 let line = "* heading *bold*\nbody text\n"
265 let text = String(repeating: line, count: 4_000)
266 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
267 let length = (text as NSString).length
268 #expect(h.editor.styledUpTo >= OrgEditor.firstStyleChunk && h.editor.styledUpTo < length)
269 h.textView.insertText("x", replacementRange: NSRange(location: length - 3, length: 0))
270 h.drainStyling()
271 #expect(h.editor.styledUpTo == length + 1)
272 #expect(h.textView.textStorage!.isEqual(to: Harness(h.string).textView.textStorage!))
273 }
274
275 @Test func editsBeforeTheWatermarkShiftIt() {
276 let text = String(repeating: "line of text\n", count: 5_000)
277 let h = Harness(DocumentState(bytes: Array(text.utf8)), layout: false)
278 let before = h.editor.styledUpTo
279 h.textView.insertText("abc", replacementRange: NSRange(location: 0, length: 0))
280 #expect(h.editor.styledUpTo == before + 3)
281 }
282}