improvements on the ui

This commit is contained in:
2026-11-25 07:14:49 +01:00
parent 3afdb6d67f
commit b7c72b9e16
249 changed files with 19702 additions and 17358 deletions
+10 -9
View File
@@ -57,19 +57,20 @@ struct SeededGenerator: RandomNumberGenerator {
}
}
@Test("the text is six blocks: sentence, two paragraphs, phones, addresses, e-mails, each after one blank line")
@Test("the text is seven blocks: the =lorem bookmark, 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(parts.count == 7)
#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"))
#expect(parts[0] == "=lorem")
#expect(parts[1] == lorem.opening)
#expect(parts[2] == lorem.paragraphs[0].joined(separator: " "))
#expect(parts[3] == lorem.paragraphs[1].joined(separator: " "))
#expect(!parts[2].contains("\n") && !parts[3].contains("\n"))
#expect(parts[4] == lorem.contacts.phones.joined(separator: "\n"))
#expect(parts[5] == lorem.contacts.addresses.joined(separator: "\n"))
#expect(parts[6] == lorem.contacts.emails.joined(separator: "\n"))
}
}
+131
View File
@@ -0,0 +1,131 @@
import Foundation
import PlakCore
import Testing
@Suite struct PagePruningTests {
private let zone = TimeZone(identifier: "Europe/Amsterdam")!
private var now: Date {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = zone
return calendar.date(from: DateComponents(year: 2026, month: 11, day: 12, hour: 12, minute: 0))!
}
/// The page file text after pruning at `now`.
private func pruned(_ text: String) -> String {
PageFile(text: text, timeZone: zone).pruned(now: now, timeZone: zone).text(timeZone: zone)
}
@Test("a block of 13 days stays, a block of 15 days goes with the blank line above it")
func olderThan14Days() {
let text = """
<!-- 2026-10-30 12:00 -->
thirteen days
<!-- 2026-10-28 12:00 -->
fifteen days
<!-- 2026-11-12 11:00 -->
today
"""
#expect(pruned(text) == """
<!-- 2026-10-30 12:00 -->
thirteen days
<!-- 2026-11-12 11:00 -->
today
""")
}
@Test("a block of exactly 14 days stays, one minute older goes")
func boundary() {
let text = """
<!-- 2026-10-29 12:00 -->
exactly fourteen days
<!-- 2026-10-29 11:59 -->
one minute older
"""
#expect(pruned(text) == "<!-- 2026-10-29 12:00 -->\nexactly fourteen days\n")
}
@Test("a block without a date line goes")
func undated() {
let text = """
no date
<!-- 2026-11-10 09:00 -->
dated
"""
#expect(pruned(text) == "<!-- 2026-11-10 09:00 -->\ndated\n")
}
@Test("a fenced block with a blank line in it stays whole, or goes whole")
func fencedBlock() {
let text = """
<!-- 2026-11-01 10:00 -->
```php
<?php
echo 'kept';
```
<!-- 2026-10-01 10:00 -->
```json
{
"old": true
}
```
"""
let page = PageFile(text: text, timeZone: zone)
#expect(page.lines.count == 3)
#expect(pruned(text) == """
<!-- 2026-11-01 10:00 -->
```php
<?php
echo 'kept';
```
""")
}
@Test("an old bookmark block goes like any block")
func oldBookmark() {
let text = """
<!-- 2026-10-20 08:00 -->
=old bookmark
under it
<!-- 2026-11-11 08:00 -->
=new bookmark
"""
#expect(pruned(text) == "<!-- 2026-11-11 08:00 -->\n=new bookmark\n")
}
@Test("a page with nothing old comes back unchanged")
func nothingOld() {
let text = "\n<!-- 2026-11-01 10:00 -->\na\n\n\n<!-- 2026-11-12 11:59 -->\nb\n![](images/x.png)\n\n"
let page = PageFile(text: text, timeZone: zone)
#expect(page.pruned(now: now, timeZone: zone) == page)
#expect(pruned(text) == text)
}
@Test("a page with only old blocks becomes an empty page")
func allOld() {
#expect(PageFile(text: "<!-- 2026-01-01 10:00 -->\nold\n\nundated\n", timeZone: zone).pruned(now: now, timeZone: zone) == PageFile())
}
@Test("the image paths are those of the image lines")
func imagePaths() {
let page = PageFile(text: "![](images/a.png)\ntext images/b.png\n\n![](images/c.jpg)\n", timeZone: zone)
#expect(page.imagePaths == ["images/a.png", "images/c.jpg"])
}
}
@@ -85,6 +85,40 @@ import UniformTypeIdentifiers
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)
}
@Test("an image file no image line uses is deleted, a used one stays")
func removeUnused() throws {
let images = store()
try FileManager.default.createDirectory(at: images.folder, withIntermediateDirectories: true)
let png = try imageData(.png)
try png.write(to: images.folder.appendingPathComponent("used.png"))
try png.write(to: images.folder.appendingPathComponent("unused.png"))
#expect(images.removeUnused(keeping: ["images/used.png"]) == ["images/unused.png"])
#expect(FileManager.default.fileExists(atPath: images.folder.appendingPathComponent("used.png").path))
#expect(!FileManager.default.fileExists(atPath: images.folder.appendingPathComponent("unused.png").path))
}
@Test("a symbolic link, a hidden file and a file that is no image stay, and so does the file a link points to")
func removeUnusedTouchesOnlyImageFiles() throws {
let images = store()
let manager = FileManager.default
try manager.createDirectory(at: images.folder, withIntermediateDirectories: true)
let outside = base.appendingPathComponent("outside.png")
try imageData(.png).write(to: outside)
try manager.createSymbolicLink(at: images.folder.appendingPathComponent("link.png"), withDestinationURL: outside)
try Data().write(to: images.folder.appendingPathComponent(".hidden.png"))
try Data().write(to: images.folder.appendingPathComponent("notes.txt"))
#expect(images.removeUnused(keeping: []).isEmpty)
#expect(manager.fileExists(atPath: outside.path))
#expect((try? manager.destinationOfSymbolicLink(atPath: images.folder.appendingPathComponent("link.png").path)) != nil)
#expect(manager.fileExists(atPath: images.folder.appendingPathComponent(".hidden.png").path))
#expect(manager.fileExists(atPath: images.folder.appendingPathComponent("notes.txt").path))
}
@Test("a missing image folder deletes nothing")
func removeUnusedWithoutFolder() {
#expect(store().removeUnused(keeping: []).isEmpty)
}
}
private final class Counter: @unchecked Sendable {
@@ -96,6 +96,58 @@ private final class Page {
#expect(store.loaded.lines == [.text("a"), .text(""), .text(""), .text("b")])
}
@Test("pruning at launch writes the page file once, without the old and undated blocks")
func prunesOldBlocks() throws {
let now = Date()
let recent = CreatedDate.line(for: now.addingTimeInterval(-3_600))
let old = CreatedDate.line(for: now.addingTimeInterval(-15 * 86_400))
try PageStore.writeAtomically(Data("\(old)\nold\n\nundated\n\n\(recent)\nrecent\n".utf8), to: url)
let log = WriteLog()
let store = try PageStore(url: url, write: log.record, pruneAt: now)
#expect(store.loaded.lines == [.text("recent")])
#expect(log.texts == ["\(recent)\nrecent\n"])
store.flush()
#expect(log.texts.count == 1)
}
@Test("pruning with nothing old writes nothing")
func prunesNothing() throws {
let now = Date()
let text = "\(CreatedDate.line(for: now.addingTimeInterval(-13 * 86_400)))\nrecent\n"
try PageStore.writeAtomically(Data(text.utf8), to: url)
let log = WriteLog()
let store = try PageStore(url: url, write: log.record, pruneAt: now)
#expect(store.loaded.lines == [.text("recent")])
#expect(log.texts.isEmpty)
#expect(try String(contentsOf: url, encoding: .utf8) == text)
}
@Test("pruning every block leaves an empty page file, not the welcome text")
func prunesToEmpty() throws {
try PageStore.writeAtomically(Data("undated\n".utf8), to: url)
let log = WriteLog()
let store = try PageStore(url: url, write: log.record, pruneAt: Date())
#expect(store.loaded == PageFile())
#expect(log.texts == [""])
#expect(try Data(contentsOf: url).isEmpty)
}
@Test("a failed write of the pruned page is reported and tried again on flush")
func pruneWriteError() throws {
try PageStore.writeAtomically(Data("undated\n".utf8), to: url)
let failing = LockedFlag(true)
let store = try PageStore(url: url, write: { data, url in
if failing.value { throw DiskFull() }
try PageStore.writeAtomically(data, to: url)
}, pruneAt: Date())
#expect(store.saveError != nil)
failing.value = false
store.contents = { "" }
store.flush()
#expect(store.saveError == nil)
#expect(try Data(contentsOf: url).isEmpty)
}
@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)
+17 -6
View File
@@ -10,23 +10,34 @@ import Testing
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")
@Test("typing #lorem at the start of a line replaces it with lorem text in seven 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(parts(text).count == 7)
#expect(parts(text)[0] == "=lorem")
#expect(LoremText.wordCount(parts(text)[1]) == 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")
@Test("lorem text goes through the normal change path: its seven blocks, =lorem included, 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)
#expect(page.fileText.components(separatedBy: now).count - 1 == 7)
#expect(page.fileText.hasPrefix("\(now)\n=lorem\n\n\(now)\n"))
}
@Test("typed lorem text starts with the bookmark lorem, in the bookmark index with the date of its block")
func bookmark() throws {
let page = try TestPage()
page.type("#lorem")
#expect(page.textView.bookmarks.map(\.title) == ["lorem"])
#expect(page.textView.bookmarks.first?.range.location == 0)
#expect(page.page.bookmarkIndex.labels == ["lorem - 17 okt 10:00", "end"])
}
@Test("on a later line, with text after #lorem, the text stays after the lorem text")
@@ -38,7 +49,7 @@ import Testing
#expect(text.hasPrefix("first\n\n"))
#expect(text.hasSuffix("tail"))
#expect(!text.contains(LoremText.trigger))
#expect(parts(text).count == 7)
#expect(parts(text).count == 8)
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length - 4, length: 0))
}
+231 -76
View File
@@ -4,6 +4,12 @@ import PlakServices
@testable import PlakUI
import Testing
/// Counts text change notifications.
@MainActor
final class ChangeCounter {
var count = 0
}
/// The clock a test moves by hand.
@MainActor
final class Clock {
@@ -273,114 +279,231 @@ func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int)
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")
@Test("a wide window shows the bookmark index at the top left, left 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.labels == ["update on this - 16 okt 08:55", "no date here", "end"])
#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
private func render(_ view: NSView, _ rect: NSRect) throws -> (rep: NSBitmapImageRep, at: (NSPoint) -> NSColor?) {
let rep = try #require(view.bitmapImageRepForCachingDisplay(in: rect))
view.cacheDisplay(in: rect, to: rep)
let scale = CGFloat(rep.pixelsWide) / rect.width
return (rep, { point in
rep.colorAt(x: Int((point.x - visible.minX) * scale), y: Int((point.y - visible.minY) * scale))
rep.colorAt(x: Int((point.x - rect.minX) * scale), y: Int((point.y - rect.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
/// The pixels in `rect` that pass `test`, one sample per pixel.
private func count(in rect: NSRect, scale: CGFloat, of color: (NSPoint) -> NSColor?, where test: (NSColor) -> Bool) -> Int {
var found = 0
for x in stride(from: rect.minX, to: rect.maxX, by: 1 / scale) {
for y in stride(from: rect.minY, to: rect.maxY, by: 1 / scale) {
if let pixel = color(NSPoint(x: x, y: y)), test(pixel) { found += 1 }
}
}
#expect(labelPixels > 50, "the label right of the column is not drawn")
return found
}
@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)
/// An orange pixel of the accent colour, also when the bitmap gives it premultiplied.
private func isAccent(_ color: NSColor) -> Bool {
guard let rgb = color.usingColorSpace(.sRGB) else { return false }
return rgb.alphaComponent > 0.2 && rgb.redComponent > rgb.blueComponent * 2 && rgb.redComponent > 0.2
}
@Test("nothing is drawn right of the column beside a bookmark line, and the bookmark line itself draws in the accent colour")
func noBookmarkMarks() throws {
let page = try TestPage(bookmarkPage(), width: 1400)
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)))
let bookmark = try #require(view.bookmarks.first)
let line = view.lineRect(at: bookmark.range.location)
let right = try columnRight(page)
let visible = view.visibleRect
let (rep, color) = try render(view, visible)
let scale = CGFloat(rep.pixelsWide) / visible.width
let beside = NSRect(x: right + 1, y: line.minY, width: visible.maxX - right - 2, height: line.height)
let drawn = count(in: beside, scale: scale, of: color) { ($0.usingColorSpace(.sRGB)?.redComponent ?? 0) > 0.2 }
#expect(drawn == 0, "something is drawn right of the column")
let text = NSRect(x: view.textContainerOrigin.x, y: line.minY, width: right - view.textContainerOrigin.x, height: line.height)
#expect(count(in: text, scale: scale, of: color, where: isAccent) > 20, "the bookmark line is not drawn in the accent colour")
}
@Test("a narrow window hides the bookmark index and shows only the date, inside the column after the line")
@Test("a narrow window keeps the bookmark index and moves the column right of it")
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)
let index = page.page.bookmarkIndex
#expect(!index.isHidden)
#expect(index.labels == ["update on this - 16 okt 08:55", "no date here", "end"])
#expect(index.frame.maxX < view.textContainerOrigin.x)
#expect(try columnRight(page) <= view.bounds.maxX - PageMetrics.sideMargin + 0.5)
}
private func storedFont(_ page: TestPage, at location: Int) -> NSFont? {
page.textView.textStorage?.attribute(.font, at: location, effectiveRange: nil) as? NSFont
}
private func storedColor(_ page: TestPage, at location: Int) -> NSColor? {
page.textView.textStorage?.attribute(.foregroundColor, at: location, effectiveRange: nil) as? NSColor
}
@Test("a bookmark line away from the caret is bold IBM Plex Mono in the accent colour, 2 pt above the page text, over the whole line")
func bookmarkLineLook() throws {
let page = try TestPage(bookmarkPage(), width: 1400)
let view = page.textView
let storage = try #require(view.textStorage)
page.caret(0)
let line = view.bookmarks[0].range
let bold = try #require(storedFont(page, at: line.location))
#expect(bold.fontName == "IBMPlexMono-Bold")
#expect(bold.pointSize == TextSize.standard + PageMetrics.bookmarkLineGrowth)
#expect(storedColor(page, at: line.location + 3) == Theme.accent)
var run = NSRange()
_ = storage.attribute(.font, at: line.location, longestEffectiveRange: &run, in: NSRange(location: 0, length: storage.length))
#expect(run == line)
#expect(storedFont(page, at: NSMaxRange(line)) == view.pageText.font)
#expect(storage.attribute(.paragraphStyle, at: line.location, effectiveRange: nil) as? NSParagraphStyle
== view.pageText.attributes[.paragraphStyle] as? NSParagraphStyle)
#expect(storedFont(page, at: view.bookmarks[1].range.location) == bold)
#expect(storedFont(page, at: 0) == view.pageText.font)
page.page.makeTextBigger(nil)
#expect(storedFont(page, at: line.location)?.pointSize == TextSize.standard + TextSize.step + PageMetrics.bookmarkLineGrowth)
#expect(storedFont(page, at: line.location)?.fontName == "IBMPlexMono-Bold")
}
@Test("with the caret or a selection on a bookmark line it is page text; typing there is page text; off the line it is bold again")
func bookmarkLineUnderCaret() throws {
let page = try TestPage(bookmarkPage(), width: 1400)
let view = page.textView
let storage = try #require(view.textStorage)
let line = view.bookmarks[0].range
let other = view.bookmarks[1].range
let plain = view.pageText.font
page.caret(line.location + 2)
#expect(storedFont(page, at: line.location) == plain)
#expect(storedFont(page, at: NSMaxRange(line) - 1) == plain)
#expect(storedColor(page, at: line.location) == Theme.ink)
#expect(storage.attribute(.plakBookmarkLine, at: line.location, effectiveRange: nil) == nil)
#expect(storedFont(page, at: other.location)?.fontName == "IBMPlexMono-Bold")
page.caret(NSMaxRange(line) + 1)
#expect(storedFont(page, at: line.location)?.fontName == "IBMPlexMono-Bold")
page.caret(NSMaxRange(line))
#expect(storedFont(page, at: line.location) == plain)
#expect(view.typingAttributes[.font] as? NSFont == plain)
#expect(view.typingAttributes[.foregroundColor] as? NSColor == Theme.ink)
view.setSelectedRange(NSRange(location: line.location - 3, length: 4))
#expect(storedFont(page, at: line.location) == plain)
page.caret(NSMaxRange(line))
page.type("x")
#expect(view.bookmarks[0].title == "update on thisx")
#expect(storedFont(page, at: NSMaxRange(line)) == plain)
page.caret(0)
#expect(storedFont(page, at: NSMaxRange(line))?.fontName == "IBMPlexMono-Bold")
#expect(storedFont(page, at: line.location)?.fontName == "IBMPlexMono-Bold")
}
@Test("the = of a bookmark line in the bookmark look takes no room, so the title starts at the column; with the caret on it the = shows again")
func bookmarkSignHidden() throws {
let page = try TestPage(bookmarkPage(), width: 1400)
let view = page.textView
let layout = try #require(view.layoutManager)
page.caret(0)
let line = view.bookmarks[0].range
let sign = layout.glyphIndexForCharacter(at: line.location)
let title = layout.glyphIndexForCharacter(at: line.location + 1)
#expect(layout.propertyForGlyph(at: sign).contains(.null))
#expect(layout.location(forGlyphAt: title).x == 0)
#expect(view.string.contains("=update on this"))
#expect(page.fileText == bookmarkPage())
page.caret(NSMaxRange(line))
#expect(!layout.propertyForGlyph(at: layout.glyphIndexForCharacter(at: line.location)).contains(.null))
#expect(layout.location(forGlyphAt: layout.glyphIndexForCharacter(at: line.location + 1)).x > 0)
#expect(layout.location(forGlyphAt: layout.glyphIndexForCharacter(at: line.location)).x == 0)
}
@Test("the bookmark look adds no undo step, posts no text change and leaves the page file and its dates alone")
func bookmarkLookIsDisplayOnly() throws {
let text = bookmarkPage()
let page = try TestPage(text, width: 1400)
let view = page.textView
let undo = try #require(view.undoManager)
undo.removeAllActions()
let changes = ChangeCounter()
let observer = NotificationCenter.default.addObserver(forName: NSText.didChangeNotification, object: view, queue: nil) { _ in
MainActor.assumeIsolated { changes.count += 1 }
}
defer { NotificationCenter.default.removeObserver(observer) }
let line = view.bookmarks[0].range
page.caret(line.location)
page.caret(0)
page.caret(NSMaxRange(line))
page.caretAtEnd()
view.styleBookmarkLines()
page.page.makeTextBigger(nil)
page.page.makeTextStandardSize(nil)
#expect(changes.count == 0)
#expect(!undo.canUndo)
#expect(page.fileText == text)
#expect(storedFont(page, at: line.location)?.fontName == "IBMPlexMono-Bold")
}
@Test("the index entry under the pointer is the hovered one and draws in the accent colour, until the pointer leaves")
func indexHover() throws {
let page = try TestPage(bookmarkPage(), width: 1400)
let list = page.page.bookmarkIndex.list
#expect(list.hoveredEntry == nil)
let point = list.convert(NSPoint(x: 4, y: list.entryRect(1).midY), to: nil)
let windowNumber = list.window?.windowNumber ?? 0
let moved = try #require(NSEvent.mouseEvent(with: .mouseMoved, location: point, modifierFlags: [], timestamp: 0,
windowNumber: windowNumber, context: nil, eventNumber: 0, clickCount: 0, pressure: 0))
list.mouseMoved(with: moved)
#expect(list.hoveredEntry == 1)
let (rep, color) = try render(list, list.bounds)
let scale = CGFloat(rep.pixelsWide) / list.bounds.width
#expect(count(in: list.entryRect(1), scale: scale, of: color, where: isAccent) > 10, "the hovered entry is not drawn in the accent colour")
#expect(count(in: list.entryRect(0), scale: scale, of: color, where: isAccent) == 0, "an entry without the pointer is in the accent colour")
let outside = list.convert(NSPoint(x: 4, y: list.bounds.maxY + 40), to: nil)
let away = try #require(NSEvent.mouseEvent(with: .mouseMoved, location: outside, modifierFlags: [], timestamp: 0,
windowNumber: windowNumber, context: nil, eventNumber: 0, clickCount: 0, pressure: 0))
list.mouseMoved(with: away)
#expect(list.hoveredEntry == nil)
list.mouseMoved(with: moved)
let exited = try #require(NSEvent.enterExitEvent(with: .mouseExited, location: point, modifierFlags: [], timestamp: 0,
windowNumber: windowNumber, context: nil, eventNumber: 0, trackingNumber: 0, userData: nil))
list.mouseExited(with: exited)
#expect(list.hoveredEntry == nil)
}
@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"])
#expect(page.page.bookmarkIndex.labels == ["x", "end"])
let empty = try TestPage("=\n= \n", width: 1400)
#expect(empty.textView.bookmarks.isEmpty)
#expect(empty.page.bookmarkIndex.isHidden)
#expect(empty.page.bookmarkIndex.labels == ["end"])
}
@Test("12 bookmarks give an index of the last 10, in page order; a click on its first entry shows the third bookmark")
@@ -388,7 +511,7 @@ func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int)
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)" })
#expect(page.page.bookmarkIndex.labels == (3...12).map { "mark \($0)" } + ["end"])
page.page.showBookmark(entry: 0)
#expect(page.textView.selectedRange() == NSRange(location: NSMaxRange(page.textView.bookmarks[2].range), length: 0))
}
@@ -396,9 +519,42 @@ func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int)
@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)
#expect(page.page.bookmarkIndex.labels == ["end"])
page.type("=fresh")
#expect(page.page.bookmarkIndex.labels == ["fresh - 17 okt 10:00"])
#expect(page.page.bookmarkIndex.labels == ["fresh - 17 okt 10:00", "end"])
}
@Test("a page without bookmarks shows the index with only end; a click on end puts the caret at the page end, in the middle")
func indexEndEntry() throws {
let page = try TestPage((1...60).map { "Paragraph \($0) with words." }.joined(separator: "\n\n") + "\n", width: 1400)
let index = page.page.bookmarkIndex
#expect(page.textView.bookmarks.isEmpty)
#expect(!index.isHidden)
#expect(index.labels == ["end"])
#expect(index.frame.width > 0 && index.frame.maxX < page.textView.textContainerOrigin.x)
page.caret(0)
page.page.clip.scroll(to: .zero)
let list = index.list
let point = list.convert(NSPoint(x: 4, y: list.entryRect(0).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)
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length, length: 0))
#expect(page.endOffsetFromMiddle <= 1)
}
@Test("with 12 bookmarks the index holds the last 10 and end; end is no bookmark and jumps to the page end")
func indexEndAfterBookmarks() throws {
let text = (1...12).map { "=mark \($0)" }.joined(separator: "\n\n") + "\n\nlast words\n"
let page = try TestPage(text, width: 1400)
#expect(page.textView.bookmarks.count == 12)
#expect(page.page.bookmarkIndex.labels.count == 11)
page.caret(0)
page.page.selectIndexEntry(9)
#expect(page.textView.selectedRange() == NSRange(location: NSMaxRange(page.textView.bookmarks[11].range), length: 0))
page.page.selectIndexEntry(10)
#expect(page.textView.selectedRange() == NSRange(location: page.textView.length, length: 0))
}
@Test("a click on an index entry puts the caret at the end of that bookmark line and shows it in the middle")
@@ -420,13 +576,12 @@ func dateLine(_ year: Int, _ month: Int, _ day: Int, _ hour: Int, _ minute: Int)
#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")
@Test("the bookmark index uses 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))