updates plug with all sorts of awesome improvements
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import Foundation
|
||||
import PlakCore
|
||||
import Testing
|
||||
|
||||
@Suite struct BookmarkTests {
|
||||
@Test("a line that starts with = directly followed by a title is a bookmark, with the trimmed title and the range of the line")
|
||||
func finds() {
|
||||
let text = "=update on this\nsome text\n=second one \n" as NSString
|
||||
#expect(Bookmark.find(in: text) == [
|
||||
Bookmark(title: "update on this", range: NSRange(location: 0, length: 15)),
|
||||
Bookmark(title: "second one", range: NSRange(location: 26, length: 13)),
|
||||
])
|
||||
}
|
||||
|
||||
@Test("a bookmark on the last line, without a newline, runs to the end of the text")
|
||||
func lastLine() {
|
||||
let text = "a\n\n=end" as NSString
|
||||
#expect(Bookmark.find(in: text) == [Bookmark(title: "end", range: NSRange(location: 3, length: 4))])
|
||||
}
|
||||
|
||||
@Test("= alone, = with a space before the title, an = inside a line and an indented = are no bookmarks")
|
||||
func none() {
|
||||
for text in ["=", "= ", "= \n", "= title", "=\ttitle", "a = b", " =title", "x\n=\n= \t\n"] {
|
||||
#expect(Bookmark.find(in: text as NSString).isEmpty, "text: \(text)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("a line that starts with two = is no bookmark, so a == title == line is none")
|
||||
func doubleEquals() {
|
||||
for text in ["==twice", "== Contact ==", "== Contact, eerdere versie (entry 974, 1 okt 2026) ==\n=real"] {
|
||||
#expect(Bookmark.find(in: text as NSString).map(\.title) == (text.hasSuffix("=real") ? ["real"] : []), "text: \(text)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import Foundation
|
||||
import PlakCore
|
||||
import Testing
|
||||
|
||||
@Suite struct HelpTextTests {
|
||||
private let page = PageFile(text: HelpText.text)
|
||||
|
||||
private func fenced(_ page: PageFile, _ kind: FenceKind) -> [String] {
|
||||
page.lines.compactMap { line in
|
||||
if case let .fenced(found, body) = line, found == kind { return body }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@Test("help.md loads and holds the json code block and the csv table as fenced blocks")
|
||||
func fileLoads() throws {
|
||||
#expect(LoremText.fileURL(named: "help.md") != nil)
|
||||
#expect(!page.lines.isEmpty)
|
||||
#expect(fenced(page, .json).count == 1)
|
||||
#expect(fenced(page, .csv).count == 1)
|
||||
#expect(!page.lines.contains { if case let .text(text) = $0 { text.hasPrefix("```") } else { false } })
|
||||
}
|
||||
|
||||
@Test("the table has 11 rows of 2 columns, with ⌘. / ⌘, as one value")
|
||||
func table() throws {
|
||||
let body = try #require(fenced(page, .csv).first)
|
||||
let table = CSVTable(text: body)
|
||||
#expect(table.rows.count == 11)
|
||||
#expect(table.rows.allSatisfy { $0.count == 2 })
|
||||
#expect(table.rows.contains(["⌘. / ⌘,", "column wider / narrower"]))
|
||||
}
|
||||
|
||||
@Test("the bookmarks include welcome to plak and shortcuts")
|
||||
func bookmarks() {
|
||||
let titles = Bookmark.find(in: HelpText.text as NSString).map(\.title)
|
||||
#expect(titles.first == "welcome to plak")
|
||||
#expect(titles.contains("shortcuts"))
|
||||
}
|
||||
|
||||
@Test("the help text, every block dated, reads back unchanged from its page file text")
|
||||
func roundTrip() {
|
||||
var dated = page
|
||||
let now = Date(timeIntervalSince1970: 1_793_000_040)
|
||||
dated.dates = Dictionary(uniqueKeysWithValues: dated.blocks.map { ($0.lowerBound, now) })
|
||||
#expect(dated.blocks.count > 1)
|
||||
#expect(PageFile(text: dated.text()) == dated)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import Foundation
|
||||
import PlakCore
|
||||
import Testing
|
||||
|
||||
/// A repeatable generator, so a failing seed can be run again.
|
||||
struct SeededGenerator: RandomNumberGenerator {
|
||||
var state: UInt64
|
||||
|
||||
mutating func next() -> UInt64 {
|
||||
state &+= 0x9E37_79B9_7F4A_7C15
|
||||
var z = state
|
||||
z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
|
||||
z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
|
||||
return z ^ (z >> 31)
|
||||
}
|
||||
}
|
||||
|
||||
@Suite struct LoremTextTests {
|
||||
private func picks(_ count: Int = 200) throws -> [LoremText] {
|
||||
let sentences = LoremText.sentences
|
||||
return try (0..<UInt64(count)).map { seed in
|
||||
var generator = SeededGenerator(state: seed)
|
||||
return try #require(LoremText.pick(from: sentences, using: &generator), "seed: \(seed)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("lorem.txt loads from the resource bundle with at least 200 lines, some of exactly 16 words")
|
||||
func fileLoads() {
|
||||
#expect(LoremText.fileURL() != nil)
|
||||
#expect(LoremText.sentences.count >= 200)
|
||||
#expect(LoremText.sentences.contains { LoremText.wordCount($0) == 16 })
|
||||
}
|
||||
|
||||
@Test("the opening sentence has exactly 16 words")
|
||||
func openingWords() throws {
|
||||
for lorem in try picks() {
|
||||
#expect(LoremText.wordCount(lorem.opening) == 16)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("there are two paragraphs of 3 to 5 sentences each")
|
||||
func paragraphSizes() throws {
|
||||
for lorem in try picks() {
|
||||
#expect(lorem.paragraphs.count == 2)
|
||||
for paragraph in lorem.paragraphs {
|
||||
#expect((3...5).contains(paragraph.count))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test("no line of the file shows twice in one insertion")
|
||||
func noRepeats() throws {
|
||||
for lorem in try picks() {
|
||||
let all = [lorem.opening] + lorem.paragraphs.flatMap { $0 }
|
||||
#expect(Set(all).count == all.count)
|
||||
#expect(all.allSatisfy(LoremText.sentences.contains))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("the text is six blocks: sentence, two paragraphs, phones, addresses, e-mails, each after one blank line")
|
||||
func layout() throws {
|
||||
for lorem in try picks(50) {
|
||||
let parts = lorem.text.components(separatedBy: "\n\n")
|
||||
#expect(parts.count == 6)
|
||||
#expect(!lorem.text.contains("\n\n\n"))
|
||||
#expect(parts[0] == lorem.opening)
|
||||
#expect(parts[1] == lorem.paragraphs[0].joined(separator: " "))
|
||||
#expect(parts[2] == lorem.paragraphs[1].joined(separator: " "))
|
||||
#expect(!parts[1].contains("\n") && !parts[2].contains("\n"))
|
||||
#expect(parts[3] == lorem.contacts.phones.joined(separator: "\n"))
|
||||
#expect(parts[4] == lorem.contacts.addresses.joined(separator: "\n"))
|
||||
#expect(parts[5] == lorem.contacts.emails.joined(separator: "\n"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test("contacts.json loads with streets, cities, first names and last names")
|
||||
func namesLoad() {
|
||||
let names = ContactNames.bundled
|
||||
#expect(names.streets.count >= 50)
|
||||
#expect(names.cities.count >= 30)
|
||||
#expect(names.firstNames.count >= 50)
|
||||
#expect(names.lastNames.count >= 50)
|
||||
}
|
||||
|
||||
@Test("each contact group has 4 items and no duplicates")
|
||||
func contactCounts() throws {
|
||||
for lorem in try picks() {
|
||||
for group in [lorem.contacts.phones, lorem.contacts.addresses, lorem.contacts.emails] {
|
||||
#expect(group.count == 4)
|
||||
#expect(Set(group).count == group.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test("phones are Dutch numbers, mobile and landline mixed")
|
||||
func phones() throws {
|
||||
let mobile = /^(06-[1-9]\d{7}|\+31 6 [1-9]\d{7})$/
|
||||
let landline = /^(0[1-9]\d-[1-9]\d{6}|0[1-9]\d{2}-[1-9]\d{5})$/
|
||||
for lorem in try picks() {
|
||||
for phone in lorem.contacts.phones {
|
||||
#expect(phone.wholeMatch(of: mobile) != nil || phone.wholeMatch(of: landline) != nil, "\(phone)")
|
||||
}
|
||||
#expect(lorem.contacts.phones.contains { $0.wholeMatch(of: mobile) != nil })
|
||||
#expect(lorem.contacts.phones.contains { $0.wholeMatch(of: landline) != nil })
|
||||
}
|
||||
}
|
||||
|
||||
@Test("addresses are one line: street, number, postcode without SS, SD or SA, city")
|
||||
func addresses() throws {
|
||||
let pattern = /^.+ (\d{1,3})[a-z]?, (\d{4}) ([A-Z]{2}) .+$/
|
||||
for lorem in try picks() {
|
||||
for address in lorem.contacts.addresses {
|
||||
let match = try #require(address.wholeMatch(of: pattern), "\(address)")
|
||||
#expect((1...250).contains(Int(match.output.1) ?? 0))
|
||||
#expect((1000...9999).contains(Int(match.output.2) ?? 0))
|
||||
#expect(!["SS", "SD", "SA"].contains(String(match.output.3)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test("e-mails are lower case ASCII on a reserved example domain")
|
||||
func emails() throws {
|
||||
let pattern = /^[a-z]+\.[a-z]+@example\.(nl|com|org)$/
|
||||
for lorem in try picks() {
|
||||
for email in lorem.contacts.emails {
|
||||
#expect(email.wholeMatch(of: pattern) != nil, "\(email)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test("a name with a tussenvoegsel or an accent becomes plain letters in an e-mail")
|
||||
func mailPart() throws {
|
||||
let one = ContactNames(streets: ["Kerkstraat"], cities: ["Gouda"], firstNames: ["Zoë"], lastNames: ["van den Berg"])
|
||||
var generator = SeededGenerator(state: 3)
|
||||
#expect(ContactSample.pick(from: one, using: &generator) == nil)
|
||||
let two = ContactNames(streets: ["Kerkstraat"], cities: ["Gouda"], firstNames: ["Zoë", "René"], lastNames: ["van den Berg", "de Wit"])
|
||||
let sample = try #require(ContactSample.pick(from: two, using: &generator))
|
||||
let expected: Set = ["zoe.vandenberg", "zoe.dewit", "rene.vandenberg", "rene.dewit"]
|
||||
#expect(sample.emails.allSatisfy { expected.contains($0.components(separatedBy: "@")[0]) })
|
||||
}
|
||||
|
||||
@Test("the same seed gives the same pick; another seed gives another one")
|
||||
func injectedGenerator() {
|
||||
var first = SeededGenerator(state: 7)
|
||||
var again = SeededGenerator(state: 7)
|
||||
let sentences = LoremText.sentences
|
||||
#expect(LoremText.pick(from: sentences, using: &first) == LoremText.pick(from: sentences, using: &again))
|
||||
let others = (100..<110).map { seed -> LoremText? in
|
||||
var generator = SeededGenerator(state: UInt64(seed))
|
||||
return LoremText.pick(from: sentences, using: &generator)
|
||||
}
|
||||
#expect(Set(others.compactMap { $0?.text }).count > 1)
|
||||
}
|
||||
|
||||
@Test("without a line of 16 words, or with too few lines, there is no pick")
|
||||
func notEnough() {
|
||||
let short = (1...20).map { "w\($0) two three." }
|
||||
let words16 = Array(repeating: "w", count: 16).joined(separator: " ")
|
||||
var generator = SeededGenerator(state: 1)
|
||||
#expect(LoremText.pick(from: short, using: &generator) == nil)
|
||||
#expect(LoremText.pick(from: [words16, "a.", "b."], using: &generator) == nil)
|
||||
#expect(LoremText.pick(from: [words16] + short, using: &generator) != nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import Foundation
|
||||
import PlakCore
|
||||
import Testing
|
||||
|
||||
@Suite struct PageLinkTests {
|
||||
private let text = "see https://plak.app/a?b=1 and\nmail jo@example.com\nplain words" as NSString
|
||||
|
||||
@Test("an index inside a web address gives the address and its range")
|
||||
func web() throws {
|
||||
let link = try #require(PageLink.link(in: text, at: 10))
|
||||
#expect(link.url.absoluteString == "https://plak.app/a?b=1")
|
||||
#expect(link.range == NSRange(location: 4, length: 22))
|
||||
}
|
||||
|
||||
@Test("a mail address on a later line is a mailto link")
|
||||
func mail() throws {
|
||||
let link = try #require(PageLink.link(in: text, at: 40))
|
||||
#expect(link.url.absoluteString == "mailto:jo@example.com")
|
||||
}
|
||||
|
||||
@Test("an index outside an address, or out of the text, gives no link")
|
||||
func none() {
|
||||
#expect(PageLink.link(in: text, at: 1) == nil)
|
||||
#expect(PageLink.link(in: text, at: text.length - 2) == nil)
|
||||
#expect(PageLink.link(in: text, at: text.length) == nil)
|
||||
#expect(PageLink.link(in: text, at: -1) == nil)
|
||||
}
|
||||
}
|
||||
@@ -43,4 +43,15 @@ import Testing
|
||||
#expect(PasteKind("just text") == .text)
|
||||
#expect(PasteKind(" \n ") == .text)
|
||||
}
|
||||
|
||||
@Test("nginx config and CSS split evenly on semicolons but hold braces, so they stay text")
|
||||
func bracesStayText() {
|
||||
let nginx = """
|
||||
location = /favicon.svg { try_files $uri /index.php?$query_string; access_log off; log_not_found off; }
|
||||
location = /favicon.ico { try_files $uri /index.php?$query_string; access_log off; log_not_found off; }
|
||||
location = /robots.txt { try_files $uri /index.php?$query_string; access_log off; log_not_found off; }
|
||||
"""
|
||||
#expect(PasteKind(nginx) == .text)
|
||||
#expect(PasteKind("a { color: red; margin: 0; }\nb { color: blue; margin: 1; }") == .text)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import Foundation
|
||||
import PlakCore
|
||||
import Testing
|
||||
|
||||
@Suite struct URLCommandTests {
|
||||
private func command(_ string: String) throws -> URLCommand? {
|
||||
URLCommand(try #require(URL(string: string)))
|
||||
}
|
||||
|
||||
@Test("append takes the percent-decoded text; a + stays a +")
|
||||
func append() throws {
|
||||
#expect(try command("plak://append?text=hello%20world") == .append("hello world"))
|
||||
#expect(try command("plak://append?text=1+1") == .append("1+1"))
|
||||
#expect(try command("PLAK://append?text=a") == .append("a"))
|
||||
}
|
||||
|
||||
@Test("append keeps newlines and unicode")
|
||||
func appendMultiline() throws {
|
||||
#expect(try command("plak://append?text=one%0Atwo%0A%0Ad%C3%A9j%C3%A0%20%F0%9F%93%8B") == .append("one\ntwo\n\ndéjà 📋"))
|
||||
}
|
||||
|
||||
@Test("append without text, or with an empty one, appends the empty text")
|
||||
func appendWithoutText() throws {
|
||||
#expect(try command("plak://append") == .append(""))
|
||||
#expect(try command("plak://append?text=") == .append(""))
|
||||
}
|
||||
|
||||
@Test("paste appends the pasteboard")
|
||||
func paste() throws {
|
||||
#expect(try command("plak://paste") == .paste)
|
||||
}
|
||||
|
||||
@Test("an unknown host or another scheme is no command")
|
||||
func unknown() throws {
|
||||
#expect(try command("plak://delete") == nil)
|
||||
#expect(try command("plak:") == nil)
|
||||
#expect(try command("https://append?text=a") == nil)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import Foundation
|
||||
import PlakCore
|
||||
import Testing
|
||||
|
||||
@Suite struct WelcomeTextTests {
|
||||
@Test("the welcome page is the one welcome line in one block, created at the given date")
|
||||
func page() {
|
||||
let now = Date(timeIntervalSince1970: 1_793_000_000)
|
||||
let page = WelcomeText.page(createdAt: now)
|
||||
#expect(page.lines == [.text("Welcome to plak. For the docs, the tricks and the shortcuts, choose Plak Help in the menu bar icon.")])
|
||||
#expect(page.blocks.count == 1)
|
||||
#expect(page.dates == [0: now])
|
||||
}
|
||||
}
|
||||
@@ -29,8 +29,8 @@ private final class Page {
|
||||
var url: URL { folder.appendingPathComponent("plak/page.md") }
|
||||
|
||||
private func makeStore(debounce: Duration = .seconds(60), write: @escaping @Sendable (Data, URL) throws -> Void = PageStore.writeAtomically,
|
||||
page: Page) throws -> PageStore {
|
||||
let store = try PageStore(url: url, debounce: debounce, write: write)
|
||||
page: Page, firstPage: PageFile = PageFile()) throws -> PageStore {
|
||||
let store = try PageStore(url: url, debounce: debounce, write: write, firstPage: firstPage)
|
||||
store.contents = { page.text }
|
||||
return store
|
||||
}
|
||||
@@ -51,17 +51,42 @@ private final class Page {
|
||||
#expect(try String(contentsOf: url, encoding: .utf8) == "change 5\n")
|
||||
}
|
||||
|
||||
@Test("a missing page file gives an empty page, and the first save creates it")
|
||||
@Test("a missing page file gives the welcome text, and the first flush writes it")
|
||||
func missingFile() throws {
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
let now = Date(timeIntervalSince1970: 1_793_000_000)
|
||||
let welcome = WelcomeText.page(createdAt: now)
|
||||
let log = WriteLog()
|
||||
let page = Page()
|
||||
let store = try makeStore(page: page)
|
||||
#expect(store.loaded == PageFile())
|
||||
let store = try makeStore(write: log.record, page: page, firstPage: welcome)
|
||||
#expect(store.loaded == welcome)
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
page.text = "hello\n"
|
||||
store.changed()
|
||||
page.text = store.loaded.text()
|
||||
store.flush()
|
||||
#expect(try String(contentsOf: url, encoding: .utf8) == "hello\n")
|
||||
let expected = "\(CreatedDate.line(for: now))\n\(WelcomeText.text)\n"
|
||||
#expect(log.texts == [expected])
|
||||
#expect(try String(contentsOf: url, encoding: .utf8) == expected)
|
||||
store.flush()
|
||||
#expect(log.texts.count == 1)
|
||||
}
|
||||
|
||||
@Test("by default a missing page file gives the welcome text")
|
||||
func missingFileDefault() throws {
|
||||
let store = try PageStore(url: url, write: { _, _ in })
|
||||
#expect(store.loaded.lines == [.text(WelcomeText.text)])
|
||||
#expect(store.loaded.dates.count == 1)
|
||||
}
|
||||
|
||||
@Test("an existing empty page file stays empty, and nothing is written")
|
||||
func emptyFile() throws {
|
||||
try PageStore.writeAtomically(Data(), to: url)
|
||||
let log = WriteLog()
|
||||
let store = try PageStore(url: url, write: log.record)
|
||||
store.contents = { "should not be written\n" }
|
||||
#expect(store.loaded == PageFile())
|
||||
store.flush()
|
||||
#expect(log.texts.isEmpty)
|
||||
#expect(try Data(contentsOf: url).isEmpty)
|
||||
}
|
||||
|
||||
@Test("an existing page file is read into lines and dates")
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import AppKit
|
||||
import PlakCore
|
||||
@testable import PlakUI
|
||||
import Testing
|
||||
|
||||
/// Append from other apps: a new block at the end of the page.
|
||||
@MainActor
|
||||
@Suite struct AppendTests {
|
||||
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
|
||||
}
|
||||
|
||||
@Test("on an empty page the text becomes the page, dated now, with the end in the middle")
|
||||
func emptyPage() throws {
|
||||
let page = try TestPage()
|
||||
let board = pasteboard("new")
|
||||
defer { board.releaseGlobally() }
|
||||
page.page.append(from: board)
|
||||
#expect(page.fileText == "\(dateLine(2026, 10, 17, 10, 0))\nnew\n")
|
||||
#expect(page.endOffsetFromMiddle <= 1)
|
||||
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length, length: 0))
|
||||
}
|
||||
|
||||
@Test("after a block the text comes after a blank line, as a new block with its own date line")
|
||||
func afterBlock() throws {
|
||||
let old = dateLine(2026, 10, 16, 8, 55)
|
||||
let page = try TestPage("\(old)\na\n")
|
||||
let board = pasteboard("new\nline")
|
||||
defer { board.releaseGlobally() }
|
||||
page.caret(0)
|
||||
page.page.append(from: board)
|
||||
#expect(page.fileText == "\(old)\na\n\n\(dateLine(2026, 10, 17, 10, 0))\nnew\nline\n")
|
||||
}
|
||||
|
||||
@Test("appended JSON becomes a fenced json code block at the end")
|
||||
func json() throws {
|
||||
let page = try TestPage("a\n")
|
||||
let board = pasteboard(#"{"b":1}"#)
|
||||
defer { board.releaseGlobally() }
|
||||
page.page.append(from: board)
|
||||
#expect(page.textView.string == "a\n\n\u{FFFC}")
|
||||
#expect(page.fileText == "a\n\n\(dateLine(2026, 10, 17, 10, 0))\n```json\n{\n \"b\": 1\n}\n```\n")
|
||||
}
|
||||
|
||||
@Test("after text that ends with a newline only one more newline is added")
|
||||
func endsWithNewline() throws {
|
||||
let page = try TestPage("a\n")
|
||||
page.caretAtEnd()
|
||||
page.type("\n")
|
||||
let board = pasteboard("b")
|
||||
defer { board.releaseGlobally() }
|
||||
page.page.append(from: board)
|
||||
#expect(page.textView.string == "a\n\nb")
|
||||
#expect(page.fileText == "a\n\n\(dateLine(2026, 10, 17, 10, 0))\nb\n")
|
||||
}
|
||||
|
||||
@Test("every block of a text with several blocks gets the created date of the append")
|
||||
func severalBlocks() throws {
|
||||
let old = dateLine(2026, 10, 16, 8, 55)
|
||||
let page = try TestPage("\(old)\na\n")
|
||||
let board = pasteboard("one\n\n=two\nline\n\n\nthree")
|
||||
defer { board.releaseGlobally() }
|
||||
page.page.append(from: board)
|
||||
let now = dateLine(2026, 10, 17, 10, 0)
|
||||
#expect(page.fileText == "\(old)\na\n\n\(now)\none\n\n\(now)\n=two\nline\n\n\n\(now)\nthree\n")
|
||||
}
|
||||
|
||||
@Test("the help text appends with a date on every block, its json and csv as objects")
|
||||
func helpText() throws {
|
||||
let page = try TestPage("a\n")
|
||||
let board = pasteboard(HelpText.text)
|
||||
defer { board.releaseGlobally() }
|
||||
page.page.append(from: board)
|
||||
let help = PageFile(text: HelpText.text)
|
||||
let now = dateLine(2026, 10, 17, 10, 0)
|
||||
#expect(page.fileText.components(separatedBy: now).count - 1 == help.blocks.count)
|
||||
#expect(page.fileText.contains("\(now)\n=shortcuts\n```csv\n"))
|
||||
#expect(page.textView.string.filter { $0 == "\u{FFFC}" }.count == 2)
|
||||
#expect(page.endOffsetFromMiddle <= 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import AppKit
|
||||
import PlakCore
|
||||
@testable import PlakUI
|
||||
import Testing
|
||||
|
||||
/// `#lorem` typed at the start of a line becomes lorem text.
|
||||
@MainActor
|
||||
@Suite struct LoremTests {
|
||||
private func parts(_ text: String) -> [String] {
|
||||
text.components(separatedBy: "\n\n")
|
||||
}
|
||||
|
||||
@Test("typing #lorem at the start of a line replaces it with lorem text in six blocks, caret at the end")
|
||||
func typedAtLineStart() throws {
|
||||
let page = try TestPage()
|
||||
page.type("#lorem")
|
||||
let text = page.textView.string
|
||||
#expect(!text.contains(LoremText.trigger))
|
||||
#expect(parts(text).count == 6)
|
||||
#expect(LoremText.wordCount(parts(text)[0]) == 16)
|
||||
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length, length: 0))
|
||||
}
|
||||
|
||||
@Test("lorem text goes through the normal change path: its six blocks get a created date")
|
||||
func stampsDates() throws {
|
||||
let page = try TestPage()
|
||||
page.type("#lorem")
|
||||
let now = dateLine(2026, 10, 17, 10, 0)
|
||||
#expect(page.fileText.components(separatedBy: now).count - 1 == 6)
|
||||
}
|
||||
|
||||
@Test("on a later line, with text after #lorem, the text stays after the lorem text")
|
||||
func keepsTextAfter() throws {
|
||||
let page = try TestPage("first\n\ntail")
|
||||
page.caret(7)
|
||||
page.type("#lorem")
|
||||
let text = page.textView.string
|
||||
#expect(text.hasPrefix("first\n\n"))
|
||||
#expect(text.hasSuffix("tail"))
|
||||
#expect(!text.contains(LoremText.trigger))
|
||||
#expect(parts(text).count == 7)
|
||||
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length - 4, length: 0))
|
||||
}
|
||||
|
||||
@Test("#lorem after other text on the line stays as typed")
|
||||
func notAtLineStart() throws {
|
||||
let page = try TestPage()
|
||||
page.type("a #lorem")
|
||||
#expect(page.textView.string == "a #lorem")
|
||||
page.type("\n #lorem")
|
||||
#expect(page.textView.string == "a #lorem\n #lorem")
|
||||
}
|
||||
|
||||
@Test("pasting #lorem stays as pasted")
|
||||
func pasteStays() throws {
|
||||
let page = try TestPage()
|
||||
let board = NSPasteboard(name: NSPasteboard.Name("plak-tests-\(UUID().uuidString)"))
|
||||
defer { board.releaseGlobally() }
|
||||
board.clearContents()
|
||||
board.setString("#lorem", forType: .string)
|
||||
page.textView.paste(from: board)
|
||||
#expect(page.textView.string == "#lorem")
|
||||
}
|
||||
|
||||
@Test("one undo brings back #lorem")
|
||||
func undoRestoresTrigger() throws {
|
||||
let page = try TestPage()
|
||||
page.type("#lorem")
|
||||
#expect(page.textView.string != "#lorem")
|
||||
try #require(page.textView.undoManager).undo()
|
||||
#expect(page.textView.string == "#lorem")
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,7 @@ struct TestPage {
|
||||
}
|
||||
let url = folder.appendingPathComponent("page.md")
|
||||
if !text.isEmpty { try PageStore.writeAtomically(Data(text.utf8), to: url) }
|
||||
let store = try PageStore(url: url, debounce: .seconds(60), write: { _, _ in })
|
||||
let store = try PageStore(url: url, debounce: .seconds(60), write: { _, _ in }, firstPage: PageFile())
|
||||
let clock = Clock(now)
|
||||
self.clock = clock
|
||||
controller = PageWindowController(store: store, now: { clock.now })
|
||||
@@ -119,7 +119,7 @@ func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int)
|
||||
func column() throws {
|
||||
let page = try TestPage(longPage(), width: 1400)
|
||||
let container = try #require(page.textView.textContainer)
|
||||
#expect(container.size.width == PageMetrics.columnWidth(bodySize: TextSize.standard))
|
||||
#expect(container.size.width == PageMetrics.columnWidth(bodySize: TextSize.standard, characters: ColumnWidth.standard))
|
||||
let side = page.textView.textContainerOrigin.x
|
||||
#expect(abs(side * 2 + container.size.width - page.page.clip.bounds.width) <= 1)
|
||||
#expect(page.textView.frame.maxY - page.textView.textBottom >= page.page.clip.bounds.height / 2 - 1)
|
||||
@@ -265,21 +265,171 @@ func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int)
|
||||
#expect(attachments.map(\.isMissing) == [false, true])
|
||||
}
|
||||
|
||||
@Test("the dates show in a wide margin next to the first line of each dated block, and none in a narrow one")
|
||||
func marginDates() throws {
|
||||
let text = "\(dateLine(2026, 10, 16, 8, 55))\none\ntwo\n\nundated\n\n\(dateLine(2025, 3, 3, 14, 2))\nthree\n"
|
||||
let wide = try TestPage(text, width: 1400)
|
||||
let dates = wide.textView.marginDates(in: wide.textView.bounds)
|
||||
#expect(dates.map(\.label) == ["16 okt 08:55", "3 mrt 2025 14:02"])
|
||||
let first = wide.textView.lineRect(at: 0)
|
||||
let date = try #require(dates.first)
|
||||
#expect(date.rect.maxX < wide.textView.textContainerOrigin.x)
|
||||
#expect(date.rect.maxX > wide.textView.textContainerOrigin.x - 40)
|
||||
#expect(date.rect.midY > first.minY && date.rect.midY < first.maxY)
|
||||
private func bookmarkPage() -> String {
|
||||
"\(dateLine(2026, 10, 16, 8, 55))\nintro\n=update on this\nmore\n\nundated words\n=no date here\n"
|
||||
}
|
||||
|
||||
let narrow = try TestPage(text, width: 600)
|
||||
#expect(!narrow.textView.showsDates)
|
||||
#expect(narrow.textView.marginDates(in: narrow.textView.bounds).isEmpty)
|
||||
private func columnRight(_ page: TestPage) throws -> CGFloat {
|
||||
page.textView.textContainerOrigin.x + (try #require(page.textView.textContainer)).size.width
|
||||
}
|
||||
|
||||
@Test("a wide window shows the bookmark index at the top left and the full labels right of the column")
|
||||
func wideBookmarks() throws {
|
||||
let page = try TestPage(bookmarkPage(), width: 1400)
|
||||
let view = page.textView
|
||||
let index = page.page.bookmarkIndex
|
||||
#expect(view.bookmarksAreWide)
|
||||
#expect(!index.isHidden)
|
||||
#expect(index.labels == ["update on this - 16 okt 08:55", "no date here"])
|
||||
#expect(index.frame.minX == PageMetrics.bookmarkIndexInset)
|
||||
#expect(index.frame.maxY == page.page.view.bounds.height - PageMetrics.topInset)
|
||||
#expect(index.frame.maxX < view.textContainerOrigin.x)
|
||||
|
||||
let marks = view.bookmarkMarks(in: view.bounds)
|
||||
#expect(marks.map(\.label) == ["update on this - 16 okt 08:55", "no date here"])
|
||||
let mark = try #require(marks.first)
|
||||
let line = view.lineRect(at: view.bookmarks[0].range.location)
|
||||
#expect(mark.rect.minX > (try columnRight(page)))
|
||||
#expect(mark.rect.midY > line.minY && mark.rect.midY < line.maxY)
|
||||
#expect(mark.rules.count == 2)
|
||||
#expect(mark.rules[0].minX > (try columnRight(page)) && mark.rules[0].maxX < mark.rect.minX)
|
||||
#expect(mark.rules[1].minX > mark.rect.maxX && abs(mark.rules[1].maxX - view.bounds.maxX) <= 0.5)
|
||||
|
||||
let frame = index.frame
|
||||
page.page.clip.scroll(to: .zero)
|
||||
#expect(index.frame == frame)
|
||||
}
|
||||
|
||||
/// The page as the window shows it: drawn through the view, not only measured.
|
||||
private func render(_ view: PageTextView) throws -> (rep: NSBitmapImageRep, at: (NSPoint) -> NSColor?) {
|
||||
let visible = view.visibleRect
|
||||
let rep = try #require(view.bitmapImageRepForCachingDisplay(in: visible))
|
||||
view.cacheDisplay(in: visible, to: rep)
|
||||
let scale = CGFloat(rep.pixelsWide) / visible.width
|
||||
return (rep, { point in
|
||||
rep.colorAt(x: Int((point.x - visible.minX) * scale), y: Int((point.y - visible.minY) * scale))
|
||||
})
|
||||
}
|
||||
|
||||
@Test("a wide window draws the rule and the label right of the column, also next to long == lines and wide tables")
|
||||
func wideBookmarksAreDrawn() throws {
|
||||
let row = (1...12).map { "a fairly long value \($0)" }.joined(separator: ",")
|
||||
let text = "\(dateLine(2026, 10, 2, 13, 53))\n== Contact, eerdere versie (entry 974, 1 okt 2026) ==\nname\n\n"
|
||||
+ "```csv\n\(row)\n\(row)\n```\n\n\(dateLine(2026, 10, 4, 7, 58))\n=update on this\n\nmore\n"
|
||||
let page = try TestPage(text, width: 1700)
|
||||
let view = page.textView
|
||||
#expect(view.bookmarks.map(\.title) == ["update on this"])
|
||||
#expect(view.bookmarksAreWide)
|
||||
#expect(!page.page.bookmarkIndex.isHidden)
|
||||
let mark = try #require(view.bookmarkMarks(in: view.visibleRect).first)
|
||||
#expect(mark.label == "update on this - 4 okt 07:58")
|
||||
let (rep, color) = try render(view)
|
||||
let rule = mark.rules[0]
|
||||
let ruleColor = try #require(color(NSPoint(x: rule.midX, y: rule.minY + 0.5)))
|
||||
#expect(ruleColor.redComponent > 0.3, "the rule right of the column is not drawn")
|
||||
let tail = mark.rules[1]
|
||||
#expect((color(NSPoint(x: tail.midX, y: tail.minY + 0.5))?.redComponent ?? 0) > 0.3, "the tail is not drawn")
|
||||
let scale = CGFloat(rep.pixelsWide) / view.visibleRect.width
|
||||
var labelPixels = 0
|
||||
for x in stride(from: mark.rect.minX, to: mark.rect.maxX, by: 1 / scale) {
|
||||
for y in stride(from: mark.rect.minY, to: mark.rect.maxY, by: 1 / scale) where (color(NSPoint(x: x, y: y))?.redComponent ?? 0) > 0.2 {
|
||||
labelPixels += 1
|
||||
}
|
||||
}
|
||||
#expect(labelPixels > 50, "the label right of the column is not drawn")
|
||||
}
|
||||
|
||||
@Test("one very long title does not keep a window narrow that has room for a label of 40 characters; it ends in an ellipsis")
|
||||
func longTitleStaysWide() throws {
|
||||
let column = PageMetrics.columnWidth(bodySize: TextSize.standard, characters: ColumnWidth.standard)
|
||||
let reasonable = NSAttributedString(string: String(repeating: "0", count: PageMetrics.bookmarkLabelCharacters),
|
||||
attributes: [.font: PlakFonts.mono(round(TextSize.standard * PageMetrics.dateScale))]).size().width
|
||||
let side = PageMetrics.bookmarkWideSide(widestLabel: .infinity, reasonableLabel: reasonable) + 2
|
||||
let long = String(repeating: "a very long bookmark title ", count: 8)
|
||||
let page = try TestPage("\(dateLine(2026, 10, 16, 8, 55))\n=\(long)\n\n=short\n", width: column + side * 2)
|
||||
let view = page.textView
|
||||
#expect(view.sideSpace >= side - 1 && view.sideSpace < side + 1)
|
||||
#expect(view.bookmarksAreWide)
|
||||
#expect(!page.page.bookmarkIndex.isHidden)
|
||||
let mark = try #require(view.bookmarkMarks(in: view.bounds).first)
|
||||
let natural = NSAttributedString(string: mark.label, attributes: [.font: view.bookmarkFont]).size().width
|
||||
#expect(mark.rect.width < natural)
|
||||
#expect(mark.rect.minX > (try columnRight(page)))
|
||||
}
|
||||
|
||||
@Test("a narrow window hides the bookmark index and shows only the date, inside the column after the line")
|
||||
func narrowBookmarks() throws {
|
||||
let page = try TestPage(bookmarkPage(), width: 600)
|
||||
let view = page.textView
|
||||
#expect(!view.bookmarksAreWide)
|
||||
#expect(page.page.bookmarkIndex.isHidden)
|
||||
let marks = view.bookmarkMarks(in: view.bounds)
|
||||
#expect(marks.map(\.label) == ["16 okt 08:55"])
|
||||
let mark = try #require(marks.first)
|
||||
let right = try columnRight(page)
|
||||
#expect(abs(mark.rect.maxX - right) <= 0.5)
|
||||
let rule = try #require(mark.rules.first)
|
||||
#expect(rule.maxX < mark.rect.minX)
|
||||
#expect(rule.minX > view.textContainerOrigin.x)
|
||||
}
|
||||
|
||||
@Test("= alone, = with a space and == are no bookmarks; = directly followed by a title is")
|
||||
func notABookmark() throws {
|
||||
let page = try TestPage("=\n= \n= title\n==twice\n== Contact ==\n=x\n", width: 1400)
|
||||
#expect(page.textView.bookmarks.map(\.title) == ["x"])
|
||||
#expect(page.page.bookmarkIndex.labels == ["x"])
|
||||
let empty = try TestPage("=\n= \n", width: 1400)
|
||||
#expect(empty.textView.bookmarks.isEmpty)
|
||||
#expect(empty.page.bookmarkIndex.isHidden)
|
||||
}
|
||||
|
||||
@Test("12 bookmarks give an index of the last 10, in page order; a click on its first entry shows the third bookmark")
|
||||
func indexShowsLastTen() throws {
|
||||
let text = (1...12).map { "=mark \($0)" }.joined(separator: "\n\n") + "\n"
|
||||
let page = try TestPage(text, width: 1400)
|
||||
#expect(page.textView.bookmarks.count == 12)
|
||||
#expect(page.page.bookmarkIndex.labels == (3...12).map { "mark \($0)" })
|
||||
page.page.showBookmark(entry: 0)
|
||||
#expect(page.textView.selectedRange() == NSRange(location: NSMaxRange(page.textView.bookmarks[2].range), length: 0))
|
||||
}
|
||||
|
||||
@Test("a bookmark typed on the page shows up in the index at once")
|
||||
func typedBookmark() throws {
|
||||
let page = try TestPage("", width: 1400)
|
||||
#expect(page.page.bookmarkIndex.isHidden)
|
||||
page.type("=fresh")
|
||||
#expect(page.page.bookmarkIndex.labels == ["fresh - 17 okt 10:00"])
|
||||
}
|
||||
|
||||
@Test("a click on an index entry puts the caret at the end of that bookmark line and shows it in the middle")
|
||||
func clickIndexEntry() throws {
|
||||
let before = (1...30).map { "Paragraph \($0) with words." }.joined(separator: "\n\n")
|
||||
let after = (31...60).map { "Paragraph \($0) with words." }.joined(separator: "\n\n")
|
||||
let page = try TestPage("\(before)\n\n=middle mark\n\n\(after)\n", width: 1400)
|
||||
let list = page.page.bookmarkIndex.list
|
||||
let bookmark = try #require(page.textView.bookmarks.first)
|
||||
let entry = list.entryRect(0)
|
||||
let point = list.convert(NSPoint(x: 4, y: entry.midY), to: nil)
|
||||
let event = try #require(NSEvent.mouseEvent(with: .leftMouseDown, location: point, modifierFlags: [], timestamp: 0,
|
||||
windowNumber: list.window?.windowNumber ?? 0, context: nil,
|
||||
eventNumber: 0, clickCount: 1, pressure: 1))
|
||||
list.mouseDown(with: event)
|
||||
let end = NSMaxRange(bookmark.range)
|
||||
#expect(page.textView.selectedRange() == NSRange(location: end, length: 0))
|
||||
let clip = page.page.clip.bounds
|
||||
#expect(abs(page.textView.lineRect(at: end).midY - clip.midY) <= 1)
|
||||
}
|
||||
|
||||
@Test("bookmark labels and the index use IBM Plex Mono at the date scale of the text size")
|
||||
func bookmarkFont() throws {
|
||||
let page = try TestPage(bookmarkPage(), width: 1400)
|
||||
let font = page.textView.bookmarkFont
|
||||
#expect(font.fontName == "IBMPlexMono-Regular")
|
||||
#expect(font.pointSize == round(TextSize.standard * PageMetrics.dateScale))
|
||||
#expect(page.textView.bookmarkAttributes[.font] as? NSFont == font)
|
||||
#expect(page.page.bookmarkIndex.list.font == font)
|
||||
page.page.makeTextBigger(nil)
|
||||
#expect(page.textView.bookmarkFont.pointSize == round((TextSize.standard + TextSize.step) * PageMetrics.dateScale))
|
||||
}
|
||||
|
||||
@Test("Select All does nothing: selectAll leaves the selection as it is and its menu item is disabled")
|
||||
@@ -305,6 +455,35 @@ func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int)
|
||||
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length, length: 0))
|
||||
}
|
||||
|
||||
@Test("with ⌘ held a link underlines under the pointer, and a ⌘-click opens it without moving the caret")
|
||||
func commandClickLink() throws {
|
||||
let text = "go to https://plak.app now\n"
|
||||
let page = try TestPage(text)
|
||||
page.caret(0)
|
||||
let view = page.textView
|
||||
let layout = try #require(view.layoutManager)
|
||||
let glyphRect = layout.boundingRect(forGlyphRange: NSRange(location: 10, length: 1), in: try #require(view.textContainer))
|
||||
let point = view.convert(NSPoint(x: glyphRect.midX + view.textContainerOrigin.x, y: glyphRect.midY + view.textContainerOrigin.y), to: nil)
|
||||
let linkRange = NSRange(location: 6, length: 16)
|
||||
|
||||
#expect(!view.updateHoveredLink(at: point, modifiers: []))
|
||||
#expect(view.updateHoveredLink(at: point, modifiers: .command))
|
||||
#expect(view.hoveredLink == linkRange)
|
||||
#expect(layout.temporaryAttribute(.underlineStyle, atCharacterIndex: 10, effectiveRange: nil) != nil)
|
||||
#expect(!view.updateHoveredLink(at: point, modifiers: []))
|
||||
#expect(layout.temporaryAttribute(.underlineStyle, atCharacterIndex: 10, effectiveRange: nil) == nil)
|
||||
|
||||
var opened: [URL] = []
|
||||
view.openLink = { opened.append($0) }
|
||||
let event = try #require(NSEvent.mouseEvent(with: .leftMouseDown, location: point, modifierFlags: .command, timestamp: 0,
|
||||
windowNumber: view.window?.windowNumber ?? 0, context: nil,
|
||||
eventNumber: 0, clickCount: 1, pressure: 1))
|
||||
view.mouseDown(with: event)
|
||||
#expect(opened.map(\.absoluteString) == ["https://plak.app"])
|
||||
#expect(view.selectedRange() == NSRange(location: 0, length: 0))
|
||||
#expect(page.fileText.hasSuffix(text))
|
||||
}
|
||||
|
||||
@Test("a bigger text size changes the look, not the page file")
|
||||
func textSize() throws {
|
||||
let text = "\(dateLine(2026, 10, 16, 8, 55))\none\n"
|
||||
@@ -316,4 +495,46 @@ func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int)
|
||||
page.page.makeTextStandardSize(nil)
|
||||
#expect(page.textView.pageText.font.pointSize == TextSize.standard)
|
||||
}
|
||||
|
||||
@Test("a wider and a narrower column change the width of the text container by one step")
|
||||
func columnWidth() throws {
|
||||
let page = try TestPage(longPage(), width: 1400)
|
||||
let container = try #require(page.textView.textContainer)
|
||||
page.page.makeColumnWider(nil)
|
||||
let wider = ColumnWidth.standard + ColumnWidth.step
|
||||
#expect(container.size.width == PageMetrics.columnWidth(bodySize: TextSize.standard, characters: wider))
|
||||
page.page.makeColumnNarrower(nil)
|
||||
page.page.makeColumnNarrower(nil)
|
||||
let narrower = ColumnWidth.standard - ColumnWidth.step
|
||||
#expect(container.size.width == PageMetrics.columnWidth(bodySize: TextSize.standard, characters: narrower))
|
||||
}
|
||||
|
||||
@Test("the column width stops at the ends of its range, and the window width still caps it")
|
||||
func columnWidthClamps() throws {
|
||||
let page = try TestPage(longPage(), width: 1400)
|
||||
let container = try #require(page.textView.textContainer)
|
||||
for _ in 0..<30 { page.page.makeColumnNarrower(nil) }
|
||||
let narrowest = PageMetrics.columnWidth(bodySize: TextSize.standard, characters: ColumnWidth.range.lowerBound)
|
||||
#expect(container.size.width == narrowest)
|
||||
for _ in 0..<30 { page.page.makeColumnWider(nil) }
|
||||
let widest = PageMetrics.columnWidth(bodySize: TextSize.standard, characters: ColumnWidth.range.upperBound)
|
||||
let room = page.page.clip.bounds.width - PageMetrics.sideMargin * 2
|
||||
#expect(container.size.width == max(1, min(widest, room)))
|
||||
#expect(widest > PageMetrics.columnWidth(bodySize: TextSize.standard, characters: ColumnWidth.range.upperBound - ColumnWidth.step))
|
||||
}
|
||||
|
||||
@Test("the column width stays in 40...160 characters, in steps of 8")
|
||||
func columnWidthMath() {
|
||||
var width = ColumnWidth()
|
||||
#expect(width.characters == 68)
|
||||
width.wider()
|
||||
#expect(width.characters == 76)
|
||||
width.narrower()
|
||||
width.narrower()
|
||||
#expect(width.characters == 60)
|
||||
width.reset()
|
||||
#expect(width.characters == ColumnWidth.standard)
|
||||
#expect(ColumnWidth(characters: 999).characters == 160)
|
||||
#expect(ColumnWidth(characters: 0).characters == 40)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user