improves plak

This commit is contained in:
2026-10-17 17:33:13 +02:00
parent 7b891819b0
commit a92d6f8871
633 changed files with 17623 additions and 7556 deletions
+59
View File
@@ -0,0 +1,59 @@
import PlakCore
import Testing
@Suite struct CSVTableTests {
@Test("quotes hold delimiters, doubled quotes and newlines; empty lines are skipped")
func parse() {
let text = "name,note\n\"Smith, J\",\"say \"\"hi\"\"\nthere\"\n\n\"\",x\n"
let table = CSVTable(text: text)
#expect(table.delimiter == ",")
#expect(table.rows == [["name", "note"], ["Smith, J", "say \"hi\"\nthere"], ["", "x"]])
}
@Test("an open quote is no table")
func openQuote() {
#expect(CSVTable.records("a,\"b\n1,2", delimiter: ",").closed == false)
#expect(CSVTable.detect("a,\"b\n1,2") == nil)
}
@Test("the delimiter is the one that gives every row the same count: semicolon over comma, tab first")
func delimiter() {
#expect(CSVTable(text: "1,5;2\n3,1;4").delimiter == ";")
#expect(CSVTable(text: "a\tb,c\nd\te,f").delimiter == "\t")
#expect(CSVTable(text: "a;b\n1;2").rows == [["a", "b"], ["1", "2"]])
}
@Test("written back with its own delimiter, quoting only fields with a delimiter, a quote or a newline")
func serialise() {
let table = CSVTable(rows: [["a;b", "c"], ["say \"hi\"", "two\nlines"], ["plain", ""]], delimiter: ";")
#expect(table.text() == "\"a;b\";c\n\"say \"\"hi\"\"\";\"two\nlines\"\nplain;")
#expect(CSVTable(text: table.text()) == table)
#expect(CSVTable(rows: [["a,b"]], delimiter: ";").text() == "\"a,b\"")
#expect(CSVTable(rows: [["x"], [""]]).text() == "x\n\"\"")
}
@Test("a value with any delimiter in it is quoted, so a table reads back with its own delimiter")
func otherDelimitersQuoted() {
let comma = CSVTable(rows: [["a;b", "c\td"], ["e", "f"]], delimiter: ",")
#expect(comma.text() == "\"a;b\",\"c\td\"\ne,f")
#expect(CSVTable(text: comma.text()) == comma)
let column = CSVTable(rows: [["a;b"], ["c,d"]], delimiter: ",")
#expect(column.text() == "\"a;b\"\n\"c,d\"")
#expect(CSVTable(text: column.text()).rows == column.rows)
}
@Test("rows and columns are added empty and removed; no cells left is an empty table")
func edits() {
var table = CSVTable(text: "a,b\n1,2")
table.addColumn()
table.addRow()
table[2, 2] = "x"
#expect(table.text() == "a,b,\n1,2,\n,,x")
table.removeColumn(at: 0)
table.removeRow(at: 0)
#expect(table.rows == [["2", ""], ["", "x"]])
table.removeColumn(at: 0)
table.removeColumn(at: 0)
#expect(table.isEmpty)
}
}
+97
View File
@@ -0,0 +1,97 @@
import Foundation
import PlakCore
import Testing
@Suite struct CodeBlockTests {
private let zone = TimeZone(identifier: "Europe/Amsterdam")!
private func date(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int) -> Date {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = zone
return calendar.date(from: DateComponents(year: year, month: month, day: day, hour: hour, minute: minute))!
}
private func roundTrip(_ text: String) -> String {
PageFile(text: text, timeZone: zone).text(timeZone: zone)
}
@Test("fenced blocks with a date line, blank lines in the body and a longer fence read and write back byte for byte")
func roundTripExact() {
let text = """
<!-- 2026-10-16 08:55 -->
```php
<?php
echo 1;
```
under the code
````xml
```not a fence
````
```csv
a,b
"x, y",2
```
"""
#expect(roundTrip(text) == text)
}
@Test("a fenced block is one line of the page file, and the date line above it dates it")
func oneLine() {
let file = PageFile(text: "<!-- 2026-10-16 08:55 -->\n```json\n{\n\n}\n```\nnext\n", timeZone: zone)
#expect(file.lines == [.fenced(.json, "{\n\n}"), .text("next")])
#expect(file.dates == [0: date(2026, 10, 16, 8, 55)])
#expect(file.blocks == [0..<2])
}
@Test("the fence is longer than any run of backticks that starts a body line")
func longerFence() {
#expect(PageFile.fencedBlock(.php, "echo 1;") == "```php\necho 1;\n```")
#expect(PageFile.fencedBlock(.xml, "```x\n````") == "`````xml\n```x\n````\n`````")
#expect(PageFile(text: PageFile.fencedBlock(.xml, "```x\n````") + "\n").lines == [.fenced(.xml, "```x\n````")])
}
@Test("a CR or CRLF in a body counts as a line break for the fence length")
func lineEndings() {
#expect(PageFile.fencedBlock(.php, "x\r\n```y").hasPrefix("````php\n"))
#expect(PageFile.unixNewlines("a\r\nb\rc\n") == "a\nb\nc\n")
}
@Test("a fence whose body holds a date line after a blank line stays text, so it cannot swallow dated blocks")
func dateLineInBody() {
let text = "```php\nstray\n\n<!-- 2026-10-16 08:55 -->\nnext block\n```\n"
let file = PageFile(text: text, timeZone: zone)
#expect(file.lines.first == .text("```php"))
#expect(file.dates == [3: date(2026, 10, 16, 8, 55)])
#expect(file.text(timeZone: zone) == text)
let inside = "```php\na\n<!-- 2026-10-16 08:55 -->\n```\n"
#expect(PageFile(text: inside, timeZone: zone).lines == [.fenced(.php, "a\n<!-- 2026-10-16 08:55 -->")])
}
@Test("an unclosed fence, an unknown kind, an empty body or a fence longer than needed stays text")
func staysText() {
let texts = [
"```php\necho 1;\n",
"```ruby\nputs 1\n```\n",
"```PHP\necho 1;\n```\n",
"``` php\necho 1;\n```\n",
"```php\n```\n",
"````php\necho 1;\n````\n",
"```php\necho 1;\n```` \n",
]
for text in texts {
let file = PageFile(text: text)
#expect(!file.lines.contains { if case .fenced = $0 { return true } else { return false } }, "\(text)")
#expect(file.text() == text)
}
}
@Test("pasted lines turn fenced blocks and image lines into objects, and a date line stays text")
func pastedLines() {
let lines = PageFile.lines(pasted: "<!-- 2026-10-16 08:55 -->\n```csv\na,b\n```\n![](images/x.png)\n")
#expect(lines == [.text("<!-- 2026-10-16 08:55 -->"), .fenced(.csv, "a,b"), .image("images/x.png"), .text("")])
}
}
@@ -0,0 +1,50 @@
import PlakCore
import Testing
@Suite struct CodeHighlighterTests {
/// The tokens of `body` as (kind, text) pairs.
private func pieces(_ body: String, _ kind: FenceKind) -> [(CodeTokenKind, String)] {
let units = Array(body.utf16)
return CodeHighlighter.tokens(body, kind: kind).map { token in
(token.kind, String(decoding: units[token.range], as: UTF16.self))
}
}
private func expect(_ body: String, _ kind: FenceKind, _ expected: [(CodeTokenKind, String)]) {
let found = pieces(body, kind)
#expect(found.map(\.0) == expected.map(\.0), "\(found)")
#expect(found.map(\.1) == expected.map(\.1), "\(found)")
}
@Test("PHP: tags, comments, variables, strings, numbers, keywords and a heredoc")
func php() {
let body = "<?php\n// note\n$total = \"a\\\"b\" . 12; # end\n/* block */ function f() { return <<<EOT\n hi $x\n EOT; }"
expect(body, .php, [
(.tag, "<?php"), (.comment, "// note"), (.variable, "$total"), (.string, "\"a\\\"b\""), (.number, "12"),
(.comment, "# end"), (.comment, "/* block */"), (.keyword, "function"), (.keyword, "return"),
(.string, "<<<EOT\n hi $x\n EOT"),
])
}
@Test("JSON: keys apart from string values, numbers and literals")
func json() {
expect(#"{"key": "value", "n": -1.5e3, "ok": true, "none": null}"#, .json, [
(.attribute, "\"key\""), (.string, "\"value\""), (.attribute, "\"n\""), (.number, "-1.5e3"),
(.attribute, "\"ok\""), (.keyword, "true"), (.attribute, "\"none\""), (.keyword, "null"),
])
}
@Test("XML: tags, attribute names and values, comments and CDATA")
func xml() {
expect(#"<!-- c --><a b='1' c:d="2"><![CDATA[x < y]]></a>"#, .xml, [
(.comment, "<!-- c -->"), (.tag, "<a"), (.attribute, "b"), (.string, "'1'"), (.attribute, "c:d"),
(.string, "\"2\""), (.tag, ">"), (.string, "<![CDATA[x < y]]>"), (.tag, "</a"), (.tag, ">"),
])
}
@Test("ranges count UTF-16 units, so text before a token can hold any character")
func utf16() {
let tokens = CodeHighlighter.tokens("{\"é😀\": 1}", kind: .json)
#expect(tokens.map(\.range) == [1..<6, 8..<9])
}
}
@@ -0,0 +1,26 @@
import PlakCore
import Testing
@Suite struct JSONFormatterTests {
@Test("pretty-printing keeps the key order and the spelling of numbers and strings")
func keepsOrder() {
let pretty = JSONFormatter.pretty(#"{"z":1.50,"a":[2e3,-0.1],"m":{"q":"a, b: \"c\" {"}}"#)
#expect(pretty == """
{
"z": 1.50,
"a": [
2e3,
-0.1
],
"m": {
"q": "a, b: \\"c\\" {"
}
}
""")
}
@Test("empty objects and arrays stay on one line, and spaces outside strings go")
func empty() {
#expect(JSONFormatter.pretty(#"[ {}, [ ], "a b" ]"#) == "[\n {},\n [],\n \"a b\"\n]")
}
}
+46
View File
@@ -0,0 +1,46 @@
import PlakCore
import Testing
@Suite struct PasteKindTests {
@Test("PHP starts with <?php or <?=, trimmed")
func php() {
#expect(PasteKind("\n <?php\necho 1;\n\n") == .object(.php, "<?php\necho 1;"))
#expect(PasteKind("<?= $name ?>") == .object(.php, "<?= $name ?>"))
}
@Test("JSON that parses is JSON; on one line it comes pretty-printed, on several lines as pasted")
func json() {
#expect(PasteKind(#"{"b":1,"a":[true,null]}"#) == .object(.json, "{\n \"b\": 1,\n \"a\": [\n true,\n null\n ]\n}"))
#expect(PasteKind("[1,\n2]") == .object(.json, "[1,\n2]"))
}
@Test("XML that parses is XML")
func xml() {
#expect(PasteKind(#"<a x="1"><b/></a>"#) == .object(.xml, #"<a x="1"><b/></a>"#))
#expect(PasteKind("<?xml version=\"1.0\"?>\n<r/>") == .object(.xml, "<?xml version=\"1.0\"?>\n<r/>"))
}
@Test("CSV needs two or more lines with the same field count, by comma, semicolon or tab")
func csv() {
#expect(PasteKind("a,b\n1,2\n") == .object(.csv, "a,b\n1,2"))
#expect(PasteKind("a;b\n1;2") == .object(.csv, "a;b\n1;2"))
#expect(PasteKind("a\tb\n1\t2") == .object(.csv, "a\tb\n1\t2"))
}
@Test("tab-separated text keeps its edge tabs, so an empty corner or last cell still makes a table")
func tsvEdges() {
#expect(PasteKind("\n\tQ1\tQ2\nA\t1\t\n") == .object(.csv, "\tQ1\tQ2\nA\t1\t"))
}
@Test("a sentence with commas, one CSV line, uneven lines, invalid JSON and broken XML stay text")
func negatives() {
#expect(PasteKind("Hello, world, this is a sentence.") == .text)
#expect(PasteKind("a,b,c") == .text)
#expect(PasteKind("a,b\n1,2,3") == .text)
#expect(PasteKind("{\"a\": }") == .text)
#expect(PasteKind("[1, 2") == .text)
#expect(PasteKind("<b>bold</b> and more") == .text)
#expect(PasteKind("just text") == .text)
#expect(PasteKind(" \n ") == .text)
}
}
+464
View File
@@ -0,0 +1,464 @@
import AppKit
import PlakCore
@testable import PlakUI
import Testing
/// Code blocks and tables: page file, paste and copy, and their editors.
@MainActor
@Suite struct ObjectTests {
private func pasteboard(_ text: String) -> NSPasteboard {
let board = NSPasteboard(name: NSPasteboard.Name("plak-tests-\(UUID().uuidString)"))
board.clearContents()
board.setString(text, forType: .string)
return board
}
private func objects(_ page: TestPage) -> [(location: Int, attachment: NSTextAttachment)] {
guard let storage = page.textView.textStorage else { return [] }
var found: [(Int, NSTextAttachment)] = []
storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, range, _ in
if let attachment = value as? NSTextAttachment { found.append((range.location, attachment)) }
}
return found
}
private func key(_ code: UInt16, _ characters: String, _ flags: NSEvent.ModifierFlags) throws -> NSEvent {
try #require(NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: 0, context: nil,
characters: characters, charactersIgnoringModifiers: characters, isARepeat: false, keyCode: code))
}
private func grid(_ page: TestPage, at location: Int) throws -> TableGridView {
page.textView.openEditor(at: location)
return try #require(page.textView.editor as? TableGridView)
}
private func codeEditor(_ page: TestPage, at location: Int) throws -> CodeEditorView {
page.textView.openEditor(at: location)
return try #require(page.textView.editor as? CodeEditorView)
}
// MARK: Page file
@Test("a page file with a code block and a table loads and saves back byte for byte, dates in place")
func loadAndSave() throws {
let text = """
\(dateLine(2026, 10, 16, 8, 55))
```php
<?php
echo 1;
```
under the code
\(dateLine(2025, 3, 3, 14, 2))
```csv
a,b
"x, y",2
```
"""
let page = try TestPage(text)
#expect(page.fileText == text)
#expect(page.textView.string == "\u{FFFC}\nunder the code\n\n\u{FFFC}")
let found = objects(page).map(\.attachment)
let code = try #require(found.first as? CodeAttachment)
let table = try #require(found.last as? TableAttachment)
#expect(code.kind == .php && code.body == "<?php\n\necho 1;")
#expect(table.table.rows == [["a", "b"], ["x, y", "2"]])
}
@Test("a code block spans the column and a table is never wider than it")
func sizes() throws {
let wide = (1...30).map { "column\($0)" }.joined(separator: ",")
let page = try TestPage("```json\n{\"a\": 1}\n```\n\n```csv\n\(wide)\n1,2\n```\n")
let column = try #require(page.textView.textContainer).size.width
let code = page.textView.objectRect(at: 0)
#expect(code.width == floor(column) && code.height > page.textView.pageText.lineHeight)
let table = page.textView.objectRect(at: 3)
#expect(table.width <= column && table.width >= column - 1)
}
// MARK: Paste and copy
@Test("⌘V of JSON on one line puts one pretty-printed code block at the caret, on its own line")
func pasteJSON() throws {
let page = try TestPage("one two\n")
let board = pasteboard(#"{"b":1,"a":2}"#)
defer { board.releaseGlobally() }
page.caret(3)
page.textView.paste(from: board)
#expect(page.textView.string == "one\n\u{FFFC}\n two")
#expect(page.fileText.contains("one\n```json\n{\n \"b\": 1,\n \"a\": 2\n}\n```\n two\n"))
}
@Test("⌘V of PHP, XML and CSV gives a code block, a code block and a table")
func pasteKinds() throws {
let page = try TestPage("start\n")
for text in ["<?php echo 1;", "<a><b/></a>", "x;y\n1;2"] {
let board = pasteboard(text)
defer { board.releaseGlobally() }
page.caretAtEnd()
page.type("\n\n")
page.textView.paste(from: board)
}
let found = objects(page).map(\.attachment)
#expect(found.count == 3)
#expect((found[0] as? CodeAttachment)?.kind == .php)
#expect((found[1] as? CodeAttachment)?.kind == .xml)
#expect((found[2] as? TableAttachment)?.table.delimiter == ";")
#expect(page.fileText.hasSuffix("```csv\nx;y\n1;2\n```\n"))
}
@Test("Paste as Plain Text keeps JSON, fences and image lines as text; a sentence with commas stays text")
func plainPaste() throws {
let page = try TestPage("a\n", images: ["a.png": NSSize(width: 4, height: 4)])
let json = pasteboard(#"{"a":1}"#)
defer { json.releaseGlobally() }
page.textView.pasteboard = json
page.caretAtEnd()
page.textView.pasteAsPlainText(nil)
let sentence = pasteboard("Hello, world, and more")
defer { sentence.releaseGlobally() }
page.textView.paste(from: sentence)
let fenced = pasteboard("\n```php\n<?php\n```\n![](images/a.png)")
defer { fenced.releaseGlobally() }
page.textView.pasteboard = fenced
page.textView.pasteAsPlainText(nil)
#expect(objects(page).isEmpty)
#expect(page.textView.string == "a{\"a\":1}Hello, world, and more\n```php\n<?php\n```\n![](images/a.png)")
}
@Test("copy of a selection with an object gives its fenced text; pasting that text recreates the object")
func copyAndPaste() throws {
let page = try TestPage("a\n```xml\n<r/>\n```\nb\n")
let board = NSPasteboard(name: NSPasteboard.Name("plak-tests-\(UUID().uuidString)"))
defer { board.releaseGlobally() }
page.textView.setSelectedRange(NSRange(location: 0, length: page.textView.length))
#expect(page.textView.writeSelection(to: board, types: [.string]))
#expect(board.string(forType: .string) == "a\n```xml\n<r/>\n```\nb")
page.caretAtEnd()
page.type("\n\n")
page.textView.paste(from: board)
let found = objects(page).compactMap { $0.attachment as? CodeAttachment }
#expect(found.map(\.body) == ["<r/>", "<r/>"])
#expect(page.fileText.hasSuffix("\na\n```xml\n<r/>\n```\nb\n"))
}
// MARK: Code editor
@Test("a click on a code block opens its editor exactly over the block, with the keys")
func clickOpensEditor() throws {
let page = try TestPage("a\n```php\n<?php echo 1;\n```\nb\n")
let rect = page.textView.objectRect(at: 2)
let point = page.textView.convert(NSPoint(x: rect.midX, y: rect.midY), to: nil)
let event = try #require(NSEvent.mouseEvent(with: .leftMouseDown, location: point, modifierFlags: [], timestamp: 0,
windowNumber: page.textView.window?.windowNumber ?? 0, context: nil,
eventNumber: 0, clickCount: 1, pressure: 1))
page.textView.mouseDown(with: event)
let editor = try #require(page.textView.editor as? CodeEditorView)
#expect(editor.frame == page.textView.objectRect(at: 2))
#expect(editor.frame.size == rect.size)
#expect(editor.window?.firstResponder === editor)
#expect(editor.string == "<?php echo 1;")
}
@Test("a code edit goes back as one change: ⌘Z on the page undoes all of it")
func codeEditAndUndo() throws {
let text = "a\n\n```php\n<?php echo 1;\n```\n\nb\n"
let page = try TestPage(text)
let editor = try codeEditor(page, at: 3)
editor.setSelectedRange(NSRange(location: (editor.string as NSString).length, length: 0))
editor.insertText(" // one", replacementRange: editor.selectedRange())
editor.insertTab(nil)
editor.insertText("two", replacementRange: editor.selectedRange())
#expect(page.fileText.contains("<?php echo 1; // one two\n"))
editor.cancelOperation(nil)
#expect(page.textView.editor == nil)
#expect(page.fileText == "a\n\n```php\n<?php echo 1; // one two\n```\n\nb\n")
#expect(page.textView.selectedRange() == NSRange(location: 4, length: 0))
page.textView.undoManager?.undo()
#expect(page.fileText == text)
}
@Test("a code block whose body becomes empty is removed with its line")
func emptyCodeRemoved() throws {
let page = try TestPage("a\n```json\n{}\n```\nb\n")
let editor = try codeEditor(page, at: 2)
editor.setSelectedRange(NSRange(location: 0, length: (editor.string as NSString).length))
editor.deleteBackward(nil)
editor.cancelOperation(nil)
#expect(page.fileText == "a\nb\n")
#expect(objects(page).isEmpty)
}
@Test("↑ on the first line and ↓ on the last line leave the code editor to the text above and below")
func codeArrowsLeave() throws {
let page = try TestPage("above\n```php\none\ntwo\n```\nbelow\n")
var editor = try codeEditor(page, at: 6)
editor.setSelectedRange(NSRange(location: 5, length: 0))
editor.moveUp(nil)
#expect(page.textView.editor === editor)
editor.moveUp(nil)
#expect(page.textView.editor == nil)
#expect(page.textView.selectedRange() == NSRange(location: 5, length: 0))
editor = try codeEditor(page, at: 6)
editor.setSelectedRange(NSRange(location: 1, length: 0))
editor.moveDown(nil)
editor.moveDown(nil)
#expect(page.textView.editor == nil)
#expect(page.textView.selectedRange() == NSRange(location: 8, length: 0))
}
@Test("Esc in the code editor, the grid or a cell edit never hides Plak; Esc after that does")
func escInEditors() throws {
let page = try TestPage("```php\n<?php\n```\n\n```csv\na,b\nc,d\n```\n")
var hides = 0
page.controller.onHide = { hides += 1 }
let editor = try codeEditor(page, at: 0)
editor.cancelOperation(nil)
#expect(page.textView.editor == nil && hides == 0)
let table = try grid(page, at: 3)
table.beginCellEdit(keepingValue: true)
try #require(table.cellEditor).cancelOperation(nil)
#expect(table.cellEditor == nil && page.textView.editor === table && hides == 0)
table.cancelOperation(nil)
#expect(page.textView.editor == nil && hides == 0)
#expect(page.textView.window?.firstResponder === page.textView)
page.textView.cancelOperation(nil)
#expect(hides == 1)
}
@Test("hiding Plak puts an open edit in the page first, and a save while editing holds the edit")
func hideCommits() throws {
let page = try TestPage("```php\n<?php\n```\n")
var hides = 0
page.controller.onHide = { hides += 1 }
let editor = try codeEditor(page, at: 0)
editor.setSelectedRange(NSRange(location: 5, length: 0))
editor.insertText(" echo 2;", replacementRange: editor.selectedRange())
#expect(page.fileText == "```php\n<?php echo 2;\n```\n")
#expect(page.textView.editor != nil)
let window = try #require(page.controller.window)
#expect(!page.controller.windowShouldClose(window))
#expect(hides == 1 && page.textView.editor == nil)
#expect((objects(page).first?.attachment as? CodeAttachment)?.body == "<?php echo 2;")
}
@Test("a bigger text size makes code bigger too, also in an open editor")
func textSize() throws {
let page = try TestPage("```php\n<?php\necho 1;\n```\n")
let before = page.textView.objectRect(at: 0).height
let editor = try codeEditor(page, at: 0)
page.page.makeTextBigger(nil)
#expect(page.textView.pageText.codeFont.pointSize == round((TextSize.standard + TextSize.step) * PageMetrics.codeScale))
#expect(editor.textStorage?.attribute(.font, at: 0, effectiveRange: nil) as? NSFont == page.textView.pageText.codeFont)
#expect(editor.frame.height > before)
editor.cancelOperation(nil)
#expect(page.textView.objectRect(at: 0).height > before)
}
@Test("a CR or CRLF typed or pasted into code is saved as LF, so the fence stays whole")
func codeLineEndings() throws {
let page = try TestPage("```php\n<?php\n```\nb\n")
let editor = try codeEditor(page, at: 0)
editor.setSelectedRange(NSRange(location: 5, length: 0))
editor.insertText("\r\n```\recho 1;", replacementRange: editor.selectedRange())
editor.cancelOperation(nil)
#expect(page.fileText == "````php\n<?php\n```\necho 1;\n````\nb\n")
}
@Test("leaving the last object of the page with Esc or ↓ puts the caret on a new line of its own")
func exitAtEnd() throws {
let page = try TestPage("a\n```json\n{}\n```\n")
let editor = try codeEditor(page, at: 2)
editor.cancelOperation(nil)
#expect(page.textView.string == "a\n\u{FFFC}\n")
#expect(page.textView.selectedRange() == NSRange(location: 4, length: 0))
let again = try codeEditor(page, at: 2)
again.moveDown(nil)
#expect(page.textView.string == "a\n\u{FFFC}\n")
#expect(page.textView.selectedRange() == NSRange(location: 4, length: 0))
}
@Test("a save while editing holds the edit without a new object; an edit that empties the block drops its line")
func draftSave() throws {
let page = try TestPage("a\n```php\n<?php\n```\nb\n")
let before = try #require(objects(page).first?.attachment)
let editor = try codeEditor(page, at: 2)
editor.setSelectedRange(NSRange(location: 5, length: 0))
editor.insertText(" echo 2;", replacementRange: editor.selectedRange())
#expect(page.fileText == "a\n```php\n<?php echo 2;\n```\nb\n")
#expect(objects(page).first?.attachment === before)
editor.setSelectedRange(NSRange(location: 0, length: (editor.string as NSString).length))
editor.deleteBackward(nil)
#expect(page.fileText == "a\nb\n")
}
@Test("the editor follows its object when the text above it changes, and puts the edit back there")
func editorFollowsObject() throws {
let page = try TestPage("a\n```php\n<?php\n```\nb\n")
let editor = try codeEditor(page, at: 2)
let storage = try #require(page.textView.textStorage)
storage.replaceCharacters(in: NSRange(location: 0, length: 0), with: NSAttributedString(string: "top\n", attributes: page.textView.pageText.attributes))
page.textView.positionEditor()
#expect(page.textView.editorLocation == 6)
#expect(editor.frame.origin == page.textView.objectRect(at: 6).origin)
editor.setSelectedRange(NSRange(location: 5, length: 0))
editor.insertText(" echo 3;", replacementRange: editor.selectedRange())
editor.cancelOperation(nil)
#expect(page.fileText == "top\na\n```php\n<?php echo 3;\n```\nb\n")
}
@Test("a key command the code editor or the grid does not know never reaches the page")
func unknownCommandsStay() throws {
let page = try TestPage("before\n```csv\na,b\n```\nafter\n")
let table = try grid(page, at: 7)
for selector in [#selector(NSResponder.deleteWordBackward(_:)), #selector(NSResponder.deleteToEndOfLine(_:)),
#selector(NSResponder.moveToEndOfDocument(_:)), #selector(NSResponder.insertNewlineIgnoringFieldEditor(_:))] {
table.doCommand(by: selector)
}
table.pasteAsPlainText(nil)
#expect(page.textView.string == "before\n\u{FFFC}\nafter")
#expect(page.textView.editor === table)
}
@Test("drawing with an empty clip, a clip beside the objects or a null clip never traps")
func emptyClips() throws {
let page = try TestPage("```csv\na,b\nc,d\n```\n\n```php\n<?php\n```\n")
let textView = page.textView
let rep = try #require(textView.bitmapImageRepForCachingDisplay(in: textView.bounds))
let context = try #require(NSGraphicsContext(bitmapImageRep: rep))
NSGraphicsContext.saveGraphicsState()
defer { NSGraphicsContext.restoreGraphicsState() }
NSGraphicsContext.current = context
let object = textView.objectRect(at: 0)
for clip in [NSRect.zero, NSRect(x: 0, y: textView.bounds.maxY - 10, width: 10, height: 10)] {
context.saveGraphicsState()
clip.clip()
#expect(drawingClip(within: object) == nil)
textView.draw(textView.bounds)
context.restoreGraphicsState()
}
let table = try #require(objects(page).first?.attachment as? TableAttachment)
let font = textView.pageText.codeFont
TableLayout(table.table, font: font).draw(table.table, at: .zero, clip: .null, scale: 2)
TableLayout(table.table, font: font).draw(table.table, at: .zero, clip: .zero, scale: 2)
#expect(TableLayout(table.table, font: font).position(at: NSPoint(x: CGFloat.nan, y: CGFloat.infinity)) == nil)
let code = CodeLayout()
code.set("<?php", kind: .php, font: font)
code.draw(in: NSRect(x: 0, y: 0, width: 300, height: 100), clip: .null)
#expect(!NSRect.null.isFiniteArea)
}
// MARK: Table grid
@Test("typing in a cell saves while the cell is still open")
func cellTypingSaves() throws {
let page = try TestPage("```csv\na,b\nc,d\n```\nend\n")
var changes = 0
page.textView.onEditorChange = { changes += 1 }
let table = try grid(page, at: 0)
table.insertText("x")
try #require(table.cellEditor).insertText("y", replacementRange: try #require(table.cellEditor).selectedRange())
#expect(changes >= 2)
#expect(page.fileText == "```csv\nxy,b\nc,d\n```\nend\n")
}
@Test("the arrows and Tab move the selected cell; ↑ on the first row leaves to the text above")
func gridMoves() throws {
let page = try TestPage("above\n```csv\na,b\nc,d\n```\n")
let table = try grid(page, at: 6)
#expect(table.selected == TablePosition(row: 0, column: 0))
table.moveRight(nil)
table.moveRight(nil)
#expect(table.selected == TablePosition(row: 0, column: 1))
table.moveDown(nil)
table.insertBacktab(nil)
#expect(table.selected == TablePosition(row: 1, column: 0))
table.insertTab(nil)
table.moveLeft(nil)
table.moveUp(nil)
#expect(table.selected == TablePosition(row: 0, column: 0))
table.moveUp(nil)
#expect(page.textView.editor == nil)
#expect(page.textView.selectedRange() == NSRange(location: 5, length: 0))
#expect(page.fileText == "above\n```csv\na,b\nc,d\n```\n")
}
@Test("typing a character replaces the value; Enter or F2 edits it keeping the value; Esc cancels the cell edit")
func gridTyping() throws {
let page = try TestPage("```csv\nab,cd\nef,gh\n```\n")
let table = try grid(page, at: 0)
table.insertText("x")
#expect(table.cellEditor?.string == "x")
try #require(table.cellEditor).insertNewline(nil)
#expect(table.table[0, 0] == "x" && table.selected == TablePosition(row: 1, column: 0))
table.insertNewline(nil)
let editor = try #require(table.cellEditor)
#expect(editor.string == "ef" && editor.selectedRange() == NSRange(location: 2, length: 0))
editor.insertText("!", replacementRange: editor.selectedRange())
editor.cancelOperation(nil)
#expect(table.table[1, 0] == "ef" && table.cellEditor == nil)
table.keyDown(with: try key(120, String(UnicodeScalar(UInt16(NSF2FunctionKey))!), [.function]))
#expect(table.cellEditor?.string == "ef")
try #require(table.cellEditor).insertTab(nil)
#expect(table.selected == TablePosition(row: 1, column: 1))
table.cancelOperation(nil)
#expect(page.fileText == "```csv\nx,cd\nef,gh\n```\n\n")
}
@Test("Enter on the last row adds a row, Tab on the last column adds a column")
func gridGrows() throws {
let page = try TestPage("```csv\na,b\nc,d\n```\n")
let table = try grid(page, at: 0)
let height = table.view.frame.height
table.select(TablePosition(row: 1, column: 0))
table.insertText("z")
try #require(table.cellEditor).insertNewline(nil)
#expect(table.table.rows.count == 3 && table.selected == TablePosition(row: 2, column: 0))
#expect(table.view.frame.height > height)
table.select(TablePosition(row: 0, column: 1))
table.insertTab(nil)
#expect(table.table.columnCount == 3 && table.selected == TablePosition(row: 0, column: 2))
table.cancelOperation(nil)
#expect(page.fileText == "```csv\na,b,\nz,d,\n,,\n```\n\n")
}
@Test("⌘⌫ deletes the row, ⌥⌘⌫ the column, Backspace clears the cell; with no cells left the table goes")
func gridDeletes() throws {
let page = try TestPage("a\n```csv\n1,2,3\n4,5,6\n```\nb\n")
let table = try grid(page, at: 2)
table.select(TablePosition(row: 1, column: 1))
table.keyDown(with: try key(51, "\u{7F}", [.command]))
#expect(table.table.rows == [["1", "2", "3"]] && table.selected == TablePosition(row: 0, column: 1))
table.keyDown(with: try key(51, "\u{7F}", [.command, .option]))
#expect(table.table.rows == [["1", "3"]])
table.deleteBackward(nil)
#expect(table.table.rows == [["1", ""]])
table.cancelOperation(nil)
#expect(page.fileText == "a\n```csv\n1,\n```\nb\n")
let again = try grid(page, at: 2)
again.keyDown(with: try key(51, "\u{7F}", [.command]))
#expect(page.textView.editor == nil)
#expect(page.fileText == "a\nb\n")
}
@Test("a click on a table cell opens grid mode with that cell selected")
func clickSelectsCell() throws {
let page = try TestPage("```csv\nfirst,second\nthird,fourth\n```\n")
let rect = page.textView.objectRect(at: 0)
let layout = TableLayout(CSVTable(text: "first,second\nthird,fourth"), font: page.textView.pageText.codeFont)
let cell = layout.rect(TablePosition(row: 1, column: 1))
page.textView.openEditor(at: 0, point: NSPoint(x: rect.minX + cell.midX, y: rect.minY + cell.midY))
let table = try #require(page.textView.editor as? TableGridView)
#expect(table.selected == TablePosition(row: 1, column: 1))
#expect(table.view.frame.origin == rect.origin)
}
}