696 lines
34 KiB
Swift
696 lines
34 KiB
Swift
import AppKit
|
|
import PlakCore
|
|
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 {
|
|
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 }, firstPage: PageFile())
|
|
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, 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)
|
|
#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
|
|

|
|
|
|
|
|
|
|
undated **bold**
|
|
<!-- a comment -->
|
|
|
|
\(dateLine(2025, 3, 3, 14, 2))
|
|

|
|
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])
|
|
}
|
|
|
|
private func bookmarkPage() -> String {
|
|
"\(dateLine(2026, 10, 16, 8, 55))\nintro\n=update on this\nmore\n\nundated words\n=no date here\n"
|
|
}
|
|
|
|
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, left of the column")
|
|
func wideBookmarks() throws {
|
|
let page = try TestPage(bookmarkPage(), width: 1400)
|
|
let view = page.textView
|
|
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.minX == PageMetrics.bookmarkIndexInset)
|
|
#expect(index.frame.maxY == page.page.view.bounds.height - PageMetrics.topInset)
|
|
#expect(index.frame.maxX < view.textContainerOrigin.x)
|
|
|
|
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: 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 - rect.minX) * scale), y: Int((point.y - rect.minY) * scale))
|
|
})
|
|
}
|
|
|
|
/// 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 }
|
|
}
|
|
}
|
|
return found
|
|
}
|
|
|
|
/// 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
|
|
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 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
|
|
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", "end"])
|
|
let empty = try TestPage("=\n= \n", width: 1400)
|
|
#expect(empty.textView.bookmarks.isEmpty)
|
|
#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")
|
|
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)" } + ["end"])
|
|
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.labels == ["end"])
|
|
page.type("=fresh")
|
|
#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")
|
|
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("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.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")
|
|
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("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"
|
|
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)
|
|
}
|
|
|
|
@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)
|
|
}
|
|
}
|