adds first version of the app

This commit is contained in:
2026-10-17 14:33:43 +02:00
parent ab1abadcd1
commit 7b891819b0
3066 changed files with 29585 additions and 0 deletions
@@ -0,0 +1,29 @@
import Foundation
import PlakCore
import Testing
@Suite struct CreatedDateTests {
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))!
}
@Test("the label is day, short Dutch month and time, with the year only when it is not this year")
func label() {
let now = date(2026, 10, 16, 12, 0)
#expect(CreatedDate.label(for: date(2026, 10, 16, 8, 55), now: now, timeZone: zone) == "16 okt 08:55")
#expect(CreatedDate.label(for: date(2025, 3, 3, 14, 2), now: now, timeZone: zone) == "3 mrt 2025 14:02")
#expect(CreatedDate.label(for: date(2026, 5, 1, 0, 7), now: now, timeZone: zone) == "1 mei 00:07")
let months = (1...12).map { CreatedDate.label(for: date(2026, $0, 9, 9, 9), now: now, timeZone: zone) }
#expect(months.map { $0.split(separator: " ")[1] } == ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"])
}
@Test("the date line is local time to the minute")
func line() {
#expect(CreatedDate.line(for: date(2026, 10, 16, 8, 55).addingTimeInterval(42), timeZone: zone) == "<!-- 2026-10-16 08:55 -->")
#expect(CreatedDate.date(fromLine: "<!-- 2026-10-16 08:55 -->", timeZone: zone) == date(2026, 10, 16, 8, 55))
}
}
+130
View File
@@ -0,0 +1,130 @@
import Foundation
import PlakCore
import Testing
@Suite struct PageFileTests {
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("text, runs of blank lines, date lines and image lines read and write back byte for byte")
func roundTripExact() {
let text = """
\n\n<!-- 2026-10-16 08:55 -->
# title
**bold** stays as typed
no date
\t
![](images/2026-10-16-085512-a3f0.png)
<!-- 2025-03-03 14:02 -->
![](images/b.jpg)
under the image
<!-- 2026-10-16 08:55 -->
<!-- note -->
"""
#expect(roundTrip(text) == text)
}
@Test("only the trailing newline and CRLF are normalised")
func normalised() {
#expect(roundTrip("a\r\n\r\nb\r\n") == "a\n\nb\n")
#expect(roundTrip("a") == "a\n")
#expect(roundTrip("a\n\n\n") == "a\n\n\n")
#expect(roundTrip("") == "")
#expect(roundTrip("a\rb\n") == "a\rb\n")
}
@Test("date lines become block dates and image lines become images")
func reads() {
let file = PageFile(text: "<!-- 2026-10-16 08:55 -->\none\n![](images/x.png)\n\n\ntwo\n", timeZone: zone)
#expect(file.lines == [.text("one"), .image("images/x.png"), .text(""), .text(""), .text("two")])
#expect(file.dates == [0: date(2026, 10, 16, 8, 55)])
}
@Test("three paragraphs give three blocks; a run of blank lines is one separator")
func blocks() {
let file = PageFile(text: "one\nline two\n\ntwo\n\n\n\nthree\n")
#expect(file.blocks == [0..<2, 3..<4, 7..<8])
#expect(PageFile(text: "\n\n").blocks.isEmpty)
#expect(PageFile(text: "a\n \nb\n").blocks.count == 2)
}
@Test("a date line that does not match the exact pattern stays text")
func otherCommentsStayText() {
let comments = [
"<!-- 2026-10-16 8:55 -->",
"<!--2026-10-16 08:55-->",
"<!-- 2026-10-16 08:55 --> ",
" <!-- 2026-10-16 08:55 -->",
"<!-- note -->",
"<!-- 2026-02-30 08:00 -->",
"<!-- 2026-10-16 08:55:12 -->",
]
for comment in comments {
let text = "\(comment)\npara\n"
let file = PageFile(text: text, timeZone: zone)
#expect(file.dates.isEmpty, "\(comment)")
#expect(file.lines == [.text(comment), .text("para")])
#expect(file.text(timeZone: zone) == text)
}
}
@Test("a date line inside a block, or with no line under it, stays text")
func dateLineOutOfPlace() {
let line = "<!-- 2026-10-16 08:55 -->"
let text = "a\n\(line)\n\n\(line)\n\nb\n\n\(line)\n"
let file = PageFile(text: text, timeZone: zone)
#expect(file.dates.isEmpty)
#expect(file.lines.count == 8)
#expect(file.text(timeZone: zone) == text)
}
@Test("a second date line under a date line is the first line of the block")
func twoDateLines() {
let text = "<!-- 2026-10-16 08:55 -->\n<!-- 2026-10-17 09:00 -->\nx\n"
let file = PageFile(text: text, timeZone: zone)
#expect(file.dates == [0: date(2026, 10, 16, 8, 55)])
#expect(file.lines.first == .text("<!-- 2026-10-17 09:00 -->"))
#expect(file.text(timeZone: zone) == text)
}
@Test("a line that is not exactly an image line stays text")
func otherImagesStayText() {
let lines = [
"![a cat](images/x.png)",
" ![](images/x.png)",
"![](images/x.png) ",
"![](other/x.png)",
"![](images/a/b.png)",
"![](images/a b.png)",
"![](https://example.com/x.png)",
"see ![](images/x.png)",
"![](images/)",
]
for line in lines {
#expect(PageFile(text: line + "\n").lines == [.text(line)], "\(line)")
}
#expect(PageFile(text: "![](images/2026-10-16-085512-a3f0.heic)\n").lines == [.image("images/2026-10-16-085512-a3f0.heic")])
}
@Test("a dated block writes its date line directly above its first line, a date elsewhere is not written")
func writesDates() {
let created = date(2026, 1, 2, 3, 4)
let file = PageFile(lines: [.text("a"), .text("b"), .text(""), .image("images/x.png")], dates: [0: created, 1: created, 3: created])
#expect(file.text(timeZone: zone) == "<!-- 2026-01-02 03:04 -->\na\nb\n\n<!-- 2026-01-02 03:04 -->\n![](images/x.png)\n")
}
}
@@ -0,0 +1,100 @@
import Foundation
import ImageIO
@testable import PlakServices
import Testing
import UniformTypeIdentifiers
@Suite struct ImageStoreTests {
let base = FileManager.default.temporaryDirectory.appendingPathComponent("plak-image-tests-\(UUID().uuidString)")
private let zone = TimeZone(identifier: "Europe/Amsterdam")!
private var moment: Date {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = zone
return calendar.date(from: DateComponents(year: 2026, month: 10, day: 16, hour: 8, minute: 55, second: 12))!
}
private func store(random: UInt16 = 0xA3F0) -> ImageStore {
let moment = moment
return ImageStore(base: base, now: { moment }, random: { random }, timeZone: zone)
}
/// A 2×1 image in the given type, made with ImageIO.
private func imageData(_ type: UTType) throws -> Data {
let context = try #require(CGContext(data: nil, width: 2, height: 1, bitsPerComponent: 8, bytesPerRow: 0,
space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))
context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)
context.fill(CGRect(x: 0, y: 0, width: 2, height: 1))
let image = try #require(context.makeImage())
let out = NSMutableData()
let destination = try #require(CGImageDestinationCreateWithData(out, type.identifier as CFString, 1, nil))
CGImageDestinationAddImage(destination, image, nil)
#expect(CGImageDestinationFinalize(destination))
return out as Data
}
@Test("a file is copied into images/ with its own extension, and the folder is made when missing")
func copyFile() throws {
let source = base.appendingPathComponent("drop/Photo.JPG")
try FileManager.default.createDirectory(at: source.deletingLastPathComponent(), withIntermediateDirectories: true)
let data = try imageData(.jpeg)
try data.write(to: source)
#expect(!FileManager.default.fileExists(atPath: base.appendingPathComponent("images").path))
let path = try store().copy(file: source)
#expect(path == "images/2026-10-16-085512-a3f0.jpg")
#expect(try Data(contentsOf: base.appendingPathComponent(path)) == data)
}
@Test("raw image data is written as PNG")
func writeData() throws {
let path = try store(random: 0x00B1).write(imageData: imageData(.tiff))
#expect(path == "images/2026-10-16-085512-00b1.png")
let written = try Data(contentsOf: base.appendingPathComponent(path))
#expect(written.starts(with: [0x89, 0x50, 0x4E, 0x47]))
}
@Test("PNG data is written as it is")
func writePNG() throws {
let png = try imageData(.png)
let path = try store().write(imageData: png)
#expect(try Data(contentsOf: base.appendingPathComponent(path)) == png)
}
@Test("a file that is not one of the image types is refused")
func rejectsOtherTypes() throws {
let source = base.appendingPathComponent("notes.pdf")
try FileManager.default.createDirectory(at: base, withIntermediateDirectories: true)
try Data("x".utf8).write(to: source)
#expect(throws: ImageStoreError.unsupportedType("pdf")) { try store().copy(file: source) }
#expect(throws: ImageStoreError.unreadableImage) { try store().write(imageData: Data("no image".utf8)) }
}
@Test("a name that is taken gets a new random part")
func takenName() throws {
let counter = Counter()
let moment = moment
let store = ImageStore(base: base, now: { moment }, random: { counter.next() }, timeZone: zone)
let png = try imageData(.png)
#expect(try store.write(imageData: png) == "images/2026-10-16-085512-0000.png")
#expect(try store.write(imageData: png) == "images/2026-10-16-085512-0001.png")
}
@Test("names follow yyyy-MM-dd-HHmmss-<4 hex>.<ext>")
func namePattern() {
let name = ImageStore(base: base).name(ext: "webp")
#expect(name.wholeMatch(of: /\d{4}-\d{2}-\d{2}-\d{6}-[0-9a-f]{4}\.webp/) != nil)
}
}
private final class Counter: @unchecked Sendable {
private let lock = NSLock()
private var value: UInt16 = 0
func next() -> UInt16 {
lock.withLock {
defer { value += 1 }
return value
}
}
}
@@ -0,0 +1,119 @@
import Foundation
import PlakCore
@testable import PlakServices
import Testing
/// Counts writes and keeps the last one, then writes for real.
private final class WriteLog: @unchecked Sendable {
private let lock = NSLock()
private var _texts: [String] = []
var texts: [String] { lock.withLock { _texts } }
func record(_ data: Data, _ url: URL) throws {
lock.withLock { _texts.append(String(decoding: data, as: UTF8.self)) }
try PageStore.writeAtomically(data, to: url)
}
}
private struct DiskFull: Error {}
/// The page text a test changes; the store reads it when a save runs.
@MainActor
private final class Page {
var text = ""
}
@MainActor
@Suite struct PageStoreTests {
let folder = FileManager.default.temporaryDirectory.appendingPathComponent("plak-tests-\(UUID().uuidString)")
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)
store.contents = { page.text }
return store
}
@Test("a burst of changes writes once, with the latest text")
func debounce() async throws {
let log = WriteLog()
let page = Page()
let store = try makeStore(debounce: .milliseconds(50), write: log.record, page: page)
for n in 1...5 {
page.text = "change \(n)\n"
store.changed()
try await Task.sleep(for: .milliseconds(5))
}
#expect(log.texts.isEmpty)
try await Task.sleep(for: .milliseconds(300))
#expect(log.texts == ["change 5\n"])
#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")
func missingFile() throws {
#expect(!FileManager.default.fileExists(atPath: url.path))
let page = Page()
let store = try makeStore(page: page)
#expect(store.loaded == PageFile())
#expect(!FileManager.default.fileExists(atPath: url.path))
page.text = "hello\n"
store.changed()
store.flush()
#expect(try String(contentsOf: url, encoding: .utf8) == "hello\n")
}
@Test("an existing page file is read into lines and dates")
func readsFile() throws {
try PageStore.writeAtomically(Data("a\n\n\nb\n".utf8), to: url)
let store = try PageStore(url: url)
#expect(store.loaded.lines == [.text("a"), .text(""), .text(""), .text("b")])
}
@Test("a page file that is not UTF-8 is not read, so it is never saved over")
func unreadableFile() throws {
try PageStore.writeAtomically(Data([0xFF, 0xFE, 0x00, 0xD8]), to: url)
#expect(throws: PageStoreError.unreadable(path: url.path)) { try PageStore(url: url) }
}
@Test("flush without a change does not write, nor does a change without contents")
func flushClean() throws {
let log = WriteLog()
let store = try makeStore(write: log.record, page: Page())
store.flush()
#expect(log.texts.isEmpty)
store.contents = { nil }
store.changed()
store.flush()
#expect(log.texts.isEmpty)
}
@Test("a failed write keeps the page, reports it, and succeeds on a later try")
func writeError() throws {
let failing = LockedFlag(true)
let page = Page()
page.text = "keep me\n"
let store = try makeStore(write: { data, url in
if failing.value { throw DiskFull() }
try PageStore.writeAtomically(data, to: url)
}, page: page)
store.changed()
store.flush()
#expect(store.saveError != nil)
failing.value = false
store.flush()
#expect(store.saveError == nil)
#expect(try String(contentsOf: url, encoding: .utf8) == "keep me\n")
}
}
private final class LockedFlag: @unchecked Sendable {
private let lock = NSLock()
private var _value: Bool
init(_ value: Bool) { _value = value }
var value: Bool {
get { lock.withLock { _value } }
set { lock.withLock { _value = newValue } }
}
}
+220
View File
@@ -0,0 +1,220 @@
import AppKit
import PlakCore
import PlakServices
@testable import PlakUI
import Testing
@MainActor
@Suite struct ImageTests {
private func pasteboard() -> NSPasteboard {
let board = NSPasteboard(name: NSPasteboard.Name("plak-tests-\(UUID().uuidString)"))
board.clearContents()
return board
}
private func attachments(_ page: TestPage) -> [(location: Int, image: ImageAttachment)] {
guard let storage = page.textView.textStorage else { return [] }
var found: [(Int, ImageAttachment)] = []
storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: storage.length)) { value, range, _ in
if let image = value as? ImageAttachment { found.append((range.location, image)) }
}
return found
}
private func laidOutSize(_ page: TestPage, at location: Int) throws -> NSSize {
let layout = try #require(page.textView.layoutManager)
layout.ensureLayout(for: try #require(page.textView.textContainer))
return layout.attachmentSize(forGlyphAt: layout.glyphIndexForCharacter(at: location))
}
@Test("an image is never wider than the column and keeps its aspect ratio; a small image keeps its size")
func scaling() throws {
let page = try TestPage("![](images/wide.png)\n\n![](images/small.png)\n",
images: ["wide.png": NSSize(width: 2000, height: 500), "small.png": NSSize(width: 120, height: 80)])
let column = try #require(page.textView.textContainer).size.width
let wide = try laidOutSize(page, at: 0)
#expect(wide.width <= column && wide.width >= column - 1)
#expect(abs(wide.height - wide.width / 4) <= 1)
#expect(try laidOutSize(page, at: 3) == NSSize(width: 120, height: 80))
}
@Test("a missing file shows image missing in inkMuted and saves back as the same line")
func missing() throws {
let text = "before\n![](images/gone.png)\nafter\n"
let page = try TestPage(text)
let image = try #require(attachments(page).first?.image)
let cell = try #require(image.attachmentCell as? MissingImageCell)
#expect(cell.text.string == "image missing")
#expect(cell.text.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor == Theme.inkMuted)
#expect(page.fileText == text)
}
@Test("copy of a selection with an image gives its image line as plain text; pasting it gives the image again")
func copyAndPaste() throws {
let page = try TestPage("a\n![](images/a.png)\nb\n", images: ["a.png": NSSize(width: 10, height: 10)])
let board = pasteboard()
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![](images/a.png)\nb")
#expect(board.types?.contains(.rtf) == false && board.types?.contains(.string) == true)
page.caretAtEnd()
page.type("\n\n")
page.textView.paste(from: board)
#expect(attachments(page).map(\.image.path) == ["images/a.png", "images/a.png"])
#expect(page.fileText.hasSuffix("\na\n![](images/a.png)\nb\n"))
board.clearContents()
board.setString("![](images/none.png)", forType: .string)
page.textView.paste(from: board)
#expect(attachments(page).count == 2)
#expect(page.textView.string.hasSuffix("![](images/none.png)"))
}
@Test("a pasted image is written to images/ and lands at the caret on a line of its own, in a dated block")
func pasteImage() throws {
let page = try TestPage("one two\n")
let source = page.folder.appendingPathComponent("shot.png")
try TestPage.writeImage(source, size: NSSize(width: 8, height: 8))
let board = pasteboard()
defer { board.releaseGlobally() }
board.setData(try Data(contentsOf: source), forType: .png)
page.caret(3)
page.textView.paste(from: board)
#expect(page.textView.string == "one\n\u{FFFC}\n two")
let image = try #require(attachments(page).first?.image)
#expect(image.path.wholeMatch(of: /images\/\d{4}-\d{2}-\d{2}-\d{6}-[0-9a-f]{4}\.png/) != nil)
#expect(FileManager.default.fileExists(atPath: page.folder.appendingPathComponent(image.path).path))
#expect(!image.isMissing)
#expect(page.textView.selectedRange().location == 6)
}
@Test("dropped image files are copied with their type and each lands on its own line at the drop place")
func dropFiles() throws {
let page = try TestPage("one\n\ntwo\n")
let first = page.folder.appendingPathComponent("drop/a.png"), second = page.folder.appendingPathComponent("drop/b.png")
try TestPage.writeImage(first, size: NSSize(width: 4, height: 4))
try TestPage.writeImage(second, size: NSSize(width: 4, height: 4))
page.page.insertImages([.file(first), .file(second)], replacing: NSRange(location: 4, length: 0))
#expect(page.textView.string == "one\n\u{FFFC}\n\u{FFFC}\n\ntwo")
let lines = page.fileText.components(separatedBy: "\n")
#expect(lines.count == 6 && lines[0] == "one" && lines[3] == "" && lines[4] == "two")
#expect(lines[1].hasPrefix("![](images/") && lines[1].hasSuffix(".png)") && lines[2] != lines[1])
}
@Test("⌘V is enabled for an image-only pasteboard, and paste(_:) puts PNG data and a copied file in as images")
func pasteEntryPoint() throws {
let page = try TestPage("one\n")
let png = page.folder.appendingPathComponent("drop/shot.png")
try TestPage.writeImage(png, size: NSSize(width: 6, height: 6))
let item = NSMenuItem(title: "Paste", action: #selector(NSText.paste(_:)), keyEquivalent: "v")
let data = pasteboard()
defer { data.releaseGlobally() }
data.setData(try Data(contentsOf: png), forType: .png)
page.textView.pasteboard = data
#expect(data.availableType(from: page.textView.readablePasteboardTypes) != nil)
#expect(page.textView.validateUserInterfaceItem(item))
page.caretAtEnd()
page.textView.paste(nil)
let file = pasteboard()
defer { file.releaseGlobally() }
file.writeObjects([png as NSURL])
page.textView.pasteboard = file
#expect(page.textView.validateUserInterfaceItem(item))
page.textView.paste(nil)
let images = attachments(page).map(\.image)
#expect(images.count == 2)
#expect(images.last?.path.hasSuffix(".png") == true && images.first?.path != images.last?.path)
for image in images {
#expect(FileManager.default.fileExists(atPath: page.folder.appendingPathComponent(image.path).path))
#expect(!image.isMissing)
}
#expect(page.textView.string == "one\n\u{FFFC}\n\u{FFFC}")
}
@Test("the text view takes image file drags, and the drop path saves the file and inserts it")
func dropEntryPoint() throws {
let page = try TestPage("one\ntwo\n")
let registered = Set(page.textView.registeredDraggedTypes)
#expect(registered.isSuperset(of: [.fileURL, .png, .tiff, .string]))
let png = page.folder.appendingPathComponent("drop/a.png")
try TestPage.writeImage(png, size: NSSize(width: 4, height: 4))
let drop = try #require(page.textView.onImages)
drop([.file(png)], NSRange(location: 4, length: 0))
let image = try #require(attachments(page).first?.image)
#expect(page.textView.string == "one\n\u{FFFC}\ntwo")
#expect(FileManager.default.fileExists(atPath: page.folder.appendingPathComponent(image.path).path))
#expect(FileManager.default.fileExists(atPath: page.folder.appendingPathComponent("images").path))
}
@Test("the drop place and the drop caret come from the point alone, without a drag session")
func dropPlace() throws {
let page = try TestPage("one\ntwo\n")
let tv = page.textView
let second = tv.lineRect(at: 4)
let start = tv.imageDrop(at: NSPoint(x: second.minX + 1, y: second.midY))
#expect(start.location == 4)
#expect(start.caret == NSRect(x: round(second.minX) - 1, y: second.minY, width: 2, height: second.height))
let first = tv.lineRect(at: 0)
let end = tv.imageDrop(at: NSPoint(x: first.maxX - 1, y: first.midY))
#expect(end.location == 3)
#expect(end.caret.minX > first.minX + 4 && end.caret.width == 2 && end.caret.minY == first.minY)
#expect(end.location == min(tv.characterIndexForInsertion(at: NSPoint(x: first.maxX - 1, y: first.midY)), tv.length))
tv.showDropCaret(start.caret)
#expect(tv.dropCaret == start.caret)
tv.showDropCaret(nil)
#expect(tv.dropCaret == nil)
}
@Test("an image drop lands at once in a window that is not key, and leaves no drop caret")
func dropInBackground() throws {
let page = try TestPage("one\ntwo\n")
let window = try #require(page.controller.window)
window.makeFirstResponder(nil)
#expect(!window.isKeyWindow && window.firstResponder !== page.textView)
let png = page.folder.appendingPathComponent("drop/a.png")
try TestPage.writeImage(png, size: NSSize(width: 4, height: 4))
let line = page.textView.lineRect(at: 4)
page.textView.showDropCaret(page.textView.dropCaretRect(at: 4))
page.textView.dropImages([.file(png)], at: NSPoint(x: line.minX + 1, y: line.midY))
#expect(page.textView.string == "one\n\u{FFFC}\ntwo")
#expect(attachments(page).first.map { !$0.image.isMissing } == true)
#expect(page.textView.dropCaret == nil)
}
@Test("image files win over the icon TIFF that Finder adds, other files are left out")
func pasteboardFiles() {
let board = pasteboard()
defer { board.releaseGlobally() }
let image = URL(fileURLWithPath: "/tmp/a.png"), other = URL(fileURLWithPath: "/tmp/b.txt")
board.writeObjects([image as NSURL, other as NSURL])
board.addTypes([.tiff], owner: nil)
board.setData(Data([1, 2, 3]), forType: .tiff)
#expect(PasteboardImages.read(board) == [.file(image)])
#expect(PasteboardImages.contains(board))
}
@Test("raw image data is read, rich text and plain text are not images")
func pasteboardData() {
let board = pasteboard()
defer { board.releaseGlobally() }
board.setData(Data([9]), forType: .png)
#expect(PasteboardImages.read(board) == [.data(Data([9]))])
board.clearContents()
board.setString("plain", forType: .string)
#expect(PasteboardImages.read(board).isEmpty)
#expect(!PasteboardImages.contains(board))
board.clearContents()
board.setData(Data("{\\rtf1 x}".utf8), forType: .rtf)
board.setData(Data([9]), forType: .tiff)
#expect(PasteboardImages.read(board).isEmpty)
}
}
+319
View File
@@ -0,0 +1,319 @@
import AppKit
import PlakCore
import PlakServices
@testable import PlakUI
import Testing
/// The clock a test moves by hand.
@MainActor
final class Clock {
var now: Date
init(_ now: Date) {
self.now = now
}
}
/// A page in an offscreen window, on a page file in a temp folder.
@MainActor
struct TestPage {
let folder: URL
let controller: PageWindowController
let clock: Clock
var page: PageViewController { controller.page }
var textView: PageTextView { controller.page.textView }
var fileText: String { page.pageFileText() }
init(_ text: String = "", width: CGFloat = 900, now: Date = TestPage.moment(2026, 10, 17, 10, 0), images: [String: NSSize] = [:]) throws {
folder = FileManager.default.temporaryDirectory.appendingPathComponent("plak-ui-tests-\(UUID().uuidString)")
for (name, size) in images {
try TestPage.writeImage(folder.appendingPathComponent("images/\(name)"), size: size)
}
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 clock = Clock(now)
self.clock = clock
controller = PageWindowController(store: store, now: { clock.now })
controller.window?.setFrame(NSRect(x: 0, y: 0, width: width, height: 700), display: false)
controller.page.showEnd()
}
nonisolated static func moment(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int) -> Date {
Calendar(identifier: .gregorian).date(from: DateComponents(year: year, month: month, day: day, hour: hour, minute: minute))!
}
nonisolated static func writeImage(_ url: URL, size: NSSize) throws {
let rep = try #require(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height),
bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0))
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try #require(rep.representation(using: .png, properties: [:])).write(to: url)
}
/// Types like the keyboard: a newline is Return.
func type(_ text: String) {
for character in text {
if character == "\n" {
textView.insertNewline(nil)
} else {
textView.insertText(String(character), replacementRange: textView.selectedRange())
}
}
}
func caret(_ location: Int) {
textView.setSelectedRange(NSRange(location: location, length: 0))
}
func caretAtEnd() {
caret(textView.length)
}
var endOffsetFromMiddle: CGFloat {
abs(textView.lineRect(at: textView.length).midY - page.clip.bounds.minY - page.clip.bounds.height / 2)
}
}
func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int) -> String {
CreatedDate.line(for: TestPage.moment(year, month, day, hour, minute))
}
/// Drives the page view in an offscreen window.
@MainActor
@Suite struct PageViewTests {
private func longPage() -> String {
(1...60).map { "Paragraph \($0) with **some** words in it." }.joined(separator: "\n\n") + "\n"
}
@Test("an empty, a short and a long page all open with the end in the vertical middle and the caret there")
func endInMiddle() throws {
for text in ["", "short\n", longPage()] {
let page = try TestPage(text)
#expect(page.endOffsetFromMiddle <= 1, "text: \(text.prefix(20))")
#expect(page.textView.window?.firstResponder === page.textView)
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length, length: 0))
}
}
@Test("a reopen shows the end again, from hidden and from visible; reveal keeps the scroll position")
func reopenShowsEnd() throws {
let page = try TestPage(longPage())
defer { page.controller.window?.orderOut(nil) }
for visible in [false, true] {
page.page.clip.scroll(to: .zero)
page.caret(0)
if visible { page.controller.reveal() } else { page.controller.window?.orderOut(nil) }
page.controller.showAtEnd()
#expect(page.endOffsetFromMiddle <= 1, "visible: \(visible)")
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length, length: 0))
}
page.page.clip.scroll(to: .zero)
page.controller.window?.orderOut(nil)
page.controller.reveal()
#expect(page.page.clip.bounds.minY == 0)
}
@Test("the column is about 68 characters wide in the middle, with half a window of room below the text")
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))
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)
#expect(page.textView.string.hasPrefix("Paragraph 1 with **some** words"))
}
@Test("the typing scroll leaves a caret above the 80% line alone and puts a lower one on it")
func typingScrollMath() {
#expect(TypingScroll.scrollY(caretBottom: 500, visibleTop: 0, visibleHeight: 700) == nil)
#expect(TypingScroll.scrollY(caretBottom: 1260, visibleTop: 700, visibleHeight: 700) == nil)
#expect(TypingScroll.scrollY(caretBottom: 600, visibleTop: 0, visibleHeight: 700) == 40)
#expect(TypingScroll.scrollY(caretBottom: 2000, visibleTop: 700, visibleHeight: 700) == 1440)
}
@Test("typing at the end scrolls only once the caret reaches the 80% line, and keeps it there")
func typingScroll() throws {
let page = try TestPage(longPage())
let clip = page.page.clip
let start = clip.bounds.minY
page.type("\nmore")
#expect(clip.bounds.minY == start)
for _ in 0..<20 { page.type("\nmore") }
let caret = page.textView.lineRect(at: page.textView.length)
#expect(clip.bounds.minY > start)
#expect(abs(caret.maxY - clip.bounds.minY - clip.bounds.height * 0.8) <= 1)
}
@Test("a new block typed at the end is stamped with now; typing inside a block adds no date")
func stampsNewBlock() throws {
let old = dateLine(2026, 10, 16, 8, 55)
let page = try TestPage("\(old)\nold\n")
page.type("\n\nnew")
let now = dateLine(2026, 10, 17, 10, 0)
#expect(page.fileText == "\(old)\nold\n\n\(now)\nnew\n")
page.clock.now = TestPage.moment(2026, 10, 18, 9, 0)
page.caret(1)
page.type("x")
page.caretAtEnd()
page.type(" more\nline")
#expect(page.fileText == "\(old)\noxld\n\n\(now)\nnew more\nline\n")
}
@Test("a block read without a date stays undated when you type in it")
func undatedStaysUndated() throws {
let page = try TestPage("old\n\n\n")
page.caret(2)
page.type("x")
#expect(page.fileText == "olxd\n\n\n")
page.caretAtEnd()
page.type("new")
#expect(page.fileText == "olxd\n\n\(dateLine(2026, 10, 17, 10, 0))\nnew\n")
}
@Test("a blank line typed inside a dated block gives two blocks with its date; deleting it gives one")
func splitAndJoin() throws {
let created = dateLine(2026, 10, 16, 8, 55)
let page = try TestPage("\(created)\nabcd\n")
page.caret(2)
page.type("\n\n")
#expect(page.fileText == "\(created)\nab\n\n\(created)\ncd\n")
page.textView.deleteBackward(nil)
page.textView.deleteBackward(nil)
#expect(page.fileText == "\(created)\nabcd\n")
}
@Test("joining two dated blocks keeps the date of the upper block")
func joinKeepsUpperDate() throws {
let upper = dateLine(2026, 10, 16, 8, 55), lower = dateLine(2026, 10, 16, 9, 30)
let page = try TestPage("\(upper)\na\n\n\(lower)\nb\n")
page.caret(3)
page.textView.deleteBackward(nil)
#expect(page.fileText == "\(upper)\na\nb\n")
page.type("\n")
#expect(page.fileText == "\(upper)\na\n\n\(upper)\nb\n")
}
@Test("text pasted into a block gets no own date; a paste that starts a block dates it")
func pasteDates() throws {
let created = dateLine(2026, 10, 16, 8, 55)
let page = try TestPage("\(created)\nold\n")
let board = NSPasteboard(name: NSPasteboard.Name("plak-tests-\(UUID().uuidString)"))
defer { board.releaseGlobally() }
board.clearContents()
board.setString("p1\n\np2", forType: .string)
page.caret(1)
page.textView.paste(from: board)
#expect(page.fileText == "\(created)\nop1\n\n\(created)\np2ld\n")
page.caretAtEnd()
page.type("\n\n")
page.textView.paste(from: board)
let now = dateLine(2026, 10, 17, 10, 0)
#expect(page.fileText.hasSuffix("p2ld\n\n\(now)\np1\n\n\(now)\np2\n"))
}
@Test("rich text pastes as plain text in the page font")
func richTextPaste() throws {
let page = try TestPage("a\n")
let board = NSPasteboard(name: NSPasteboard.Name("plak-tests-\(UUID().uuidString)"))
defer { board.releaseGlobally() }
board.clearContents()
let rich = NSAttributedString(string: "styled", attributes: [.font: NSFont.boldSystemFont(ofSize: 30), .foregroundColor: NSColor.red])
board.setData(try rich.data(from: NSRange(location: 0, length: rich.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf]),
forType: .rtf)
board.setString("styled", forType: .string)
page.textView.paste(from: board)
let storage = try #require(page.textView.textStorage)
let font = storage.attribute(.font, at: 2, effectiveRange: nil) as? NSFont
#expect(page.textView.string == "astyled")
#expect(font == page.textView.pageText.font)
#expect(storage.attribute(.foregroundColor, at: 2, effectiveRange: nil) as? NSColor == Theme.ink)
}
@Test("a page file loaded into the page and saved back is the same, with images and dates in place")
func loadAndSave() throws {
let text = """
\(dateLine(2026, 10, 16, 8, 55))
# title
![](images/a.png)
undated **bold**
<!-- a comment -->
\(dateLine(2025, 3, 3, 14, 2))
![](images/gone.png)
under the missing image
"""
let page = try TestPage(text, images: ["a.png": NSSize(width: 40, height: 20)])
#expect(page.fileText == text)
#expect(!page.textView.string.contains("<!-- 2026"))
#expect(page.textView.string.contains("# title\n\u{FFFC}\n\n\n\nundated **bold**"))
let storage = try #require(page.textView.textStorage)
let images = (page.textView.string as NSString)
var attachments: [ImageAttachment] = []
storage.enumerateAttribute(.attachment, in: NSRange(location: 0, length: images.length)) { value, _, _ in
if let image = value as? ImageAttachment { attachments.append(image) }
}
#expect(attachments.map(\.path) == ["images/a.png", "images/gone.png"])
#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)
let narrow = try TestPage(text, width: 600)
#expect(!narrow.textView.showsDates)
#expect(narrow.textView.marginDates(in: narrow.textView.bounds).isEmpty)
}
@Test("Select All does nothing: selectAll leaves the selection as it is and its menu item is disabled")
func noSelectAll() throws {
let page = try TestPage("one\ntwo\n")
page.caret(2)
page.textView.selectAll(nil)
#expect(page.textView.selectedRange() == NSRange(location: 2, length: 0))
let item = NSMenuItem(title: "Select All", action: #selector(NSText.selectAll(_:)), keyEquivalent: "a")
#expect(!page.textView.validateMenuItem(item))
#expect(!page.textView.validateUserInterfaceItem(item))
}
@Test("a click below the text puts the caret at the end")
func clickBelowText() throws {
let page = try TestPage("one\n\ntwo\n")
page.caret(0)
let point = page.textView.convert(NSPoint(x: 300, y: page.textView.textBottom + 40), 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)
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length, length: 0))
}
@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"
let page = try TestPage(text)
page.page.makeTextBigger(nil)
let font = page.textView.textStorage?.attribute(.font, at: 0, effectiveRange: nil) as? NSFont
#expect(font?.pointSize == TextSize.standard + TextSize.step)
#expect(page.fileText == text)
page.page.makeTextStandardSize(nil)
#expect(page.textView.pageText.font.pointSize == TextSize.standard)
}
}
+95
View File
@@ -0,0 +1,95 @@
import AppKit
@testable import PlakUI
import Testing
@MainActor
@Suite struct WindowTests {
@Test("the title bar double-click setting: Minimize minimises, None does nothing, anything else zooms")
func doubleClickSetting() {
#expect(TitleBarDoubleClick(setting: "Minimize") == .minimize)
#expect(TitleBarDoubleClick(setting: "None") == .none)
#expect(TitleBarDoubleClick(setting: "Maximize") == .zoom)
#expect(TitleBarDoubleClick(setting: nil) == .zoom)
}
@Test("the drag strip covers the top 28 pt over the full width, above the text, also after a resize")
func stripFrame() throws {
let page = try TestPage("one\n")
let strip = page.page.dragStrip
let root = page.page.view
for width: CGFloat in [900, 520] {
page.controller.window?.setFrame(NSRect(x: 0, y: 0, width: width, height: 640), display: false)
root.layoutSubtreeIfNeeded()
#expect(strip.frame == NSRect(x: 0, y: root.bounds.height - 28, width: root.bounds.width, height: 28))
#expect(root.hitTest(NSPoint(x: root.bounds.midX, y: root.bounds.height - 10)) === strip)
#expect(root.hitTest(NSPoint(x: root.bounds.midX, y: root.bounds.height - 40)) !== strip)
}
#expect(strip.scrollTarget === page.page.scrollView)
#expect(!strip.acceptsFirstResponder)
}
@Test("the drag strip leaves the window buttons alone and hands drops to the text view")
func stripPassesThrough() throws {
let page = try TestPage("one\n")
let strip = page.page.dragStrip
let root = page.page.view
let button = try #require(page.controller.window?.standardWindowButton(.closeButton))
let center = root.convert(NSPoint(x: button.frame.midX, y: button.frame.midY), from: button.superview)
#expect(strip.hitTest(center) == nil)
#expect(strip.dropTarget === page.textView)
#expect(Set(strip.registeredDraggedTypes).isSuperset(of: [.fileURL, .png, .tiff, .string]))
}
@Test("the pointer is the arrow over the drag strip and the I-beam below it, also after a resize")
func stripPointer() throws {
let page = try TestPage("one\n")
let root = page.page.view
let textView = page.textView
#expect(textView.dragStrip === page.page.dragStrip)
for width: CGFloat in [900, 520] {
page.controller.window?.setFrame(NSRect(x: 0, y: 0, width: width, height: 640), display: false)
root.layoutSubtreeIfNeeded()
for x in [4, root.bounds.midX, root.bounds.maxX - 4] {
#expect(textView.isUnderDragStrip(root.convert(NSPoint(x: x, y: root.bounds.height - 2), to: nil)))
#expect(textView.isUnderDragStrip(root.convert(NSPoint(x: x, y: root.bounds.height - 27), to: nil)))
#expect(!textView.isUnderDragStrip(root.convert(NSPoint(x: x, y: root.bounds.height - 29), to: nil)))
}
let strip = try #require(textView.dragStripRect)
#expect(strip.minY == textView.visibleRect.minY)
#expect(strip.height == 28)
}
}
@Test("the window follows you to the active desktop and shows over a fullscreen app")
func followsSpaces() throws {
let page = try TestPage("one\n")
let behavior = try #require(page.controller.window?.collectionBehavior)
#expect(behavior.contains(.moveToActiveSpace))
#expect(behavior.contains(.fullScreenAuxiliary))
}
@Test("Esc hides Plak, but during an input-method composition it only cancels the composition")
func escHides() throws {
let page = try TestPage("one\n")
var hides = 0
page.controller.onHide = { hides += 1 }
page.caretAtEnd()
page.textView.setMarkedText("ka", selectedRange: NSRange(location: 2, length: 0), replacementRange: page.textView.selectedRange())
#expect(page.textView.hasMarkedText())
page.textView.cancelOperation(nil)
#expect(hides == 0)
#expect(!page.textView.hasMarkedText())
page.textView.cancelOperation(nil)
#expect(hides == 1)
}
@Test("the close button and ⌘W hide Plak the same way as Esc")
func closeHides() throws {
let page = try TestPage("one\n")
var hides = 0
page.controller.onHide = { hides += 1 }
let window = try #require(page.controller.window)
#expect(!page.controller.windowShouldClose(window))
#expect(hides == 1)
}
}