updates plug with all sorts of awesome improvements

This commit is contained in:
2026-11-09 13:09:09 +01:00
parent a92d6f8871
commit 3afdb6d67f
553 changed files with 22780 additions and 13155 deletions
+280 -56
View File
@@ -1,13 +1,28 @@
import AppKit
import PlakCore
/// A created date in the left margin: its label and where it is drawn.
struct MarginDate: Equatable {
var label: String
var rect: NSRect
/// A bookmark of the page with the created date of its block.
struct PageBookmark: Equatable {
var title: String
/// The created date label, nil when the block has no date.
var date: String?
/// The bookmark line, without its newline.
var range: NSRange
/// `title - date`, or the title alone.
var label: String {
date.map { "\(title) - \($0)" } ?? title
}
}
/// The one editable text view of the page, on TextKit 1: the reading column, the margin dates, paste and drop,
/// A drawn bookmark label and its rules.
struct BookmarkMark: Equatable {
var label: String
var rect: NSRect
var rules: [NSRect]
}
/// The one editable text view of the page, on TextKit 1: the reading column, the bookmark labels, paste and drop,
/// and the editors of code blocks and tables.
final class PageTextView: NSTextView {
let pageText: PageText
@@ -105,6 +120,7 @@ final class PageTextView: NSTextView {
}
textStorage.endEditing()
editor?.setFont(pageText.codeFont)
reloadBookmarks()
}
// MARK: Column and spaces
@@ -159,31 +175,131 @@ final class PageTextView: NSTextView {
return dragStrip.bounds.contains(dragStrip.convert(locationInWindow, from: nil))
}
/// Without super, so no I-beam rect lies under the strip.
/// The bookmark index over the left of the page; it sets its own pointer.
weak var bookmarkIndex: BookmarkIndexView?
/// The visible part of the bookmark index, in this view's coordinates.
var bookmarkIndexRect: NSRect? {
guard let bookmarkIndex, !bookmarkIndex.isHidden else { return nil }
let rect = convert(bookmarkIndex.bounds, from: bookmarkIndex).intersection(visibleRect)
return rect.isEmpty ? nil : rect
}
func isOverBookmarkIndex(_ locationInWindow: NSPoint) -> Bool {
guard let bookmarkIndex, !bookmarkIndex.isHidden else { return false }
return bookmarkIndex.bounds.contains(bookmarkIndex.convert(locationInWindow, from: nil))
}
/// Without super, so no I-beam rect lies under the strip or the bookmark index.
override func resetCursorRects() {
guard let strip = dragStripRect else { return super.resetCursorRects() }
let strip = dragStripRect
let index = bookmarkIndexRect
guard strip != nil || index != nil else { return super.resetCursorRects() }
let visible = visibleRect
addCursorRect(NSRect(x: visible.minX, y: strip.maxY, width: visible.width, height: max(0, visible.maxY - strip.maxY)), cursor: .iBeam)
addCursorRect(strip, cursor: .arrow)
let top = strip?.maxY ?? visible.minY
let text = NSRect(x: visible.minX, y: top, width: visible.width, height: max(0, visible.maxY - top))
for rect in text.subtracting(index) { addCursorRect(rect, cursor: .iBeam) }
if let strip { addCursorRect(strip, cursor: .arrow) }
}
override func cursorUpdate(with event: NSEvent) {
guard let window, isUnderDragStrip(window.mouseLocationOutsideOfEventStream) else { return super.cursorUpdate(with: event) }
NSCursor.arrow.set()
guard let window else { return super.cursorUpdate(with: event) }
let location = window.mouseLocationOutsideOfEventStream
if isUnderDragStrip(location) {
NSCursor.arrow.set()
} else if isOverBookmarkIndex(location) {
bookmarkIndex?.updateCursor(at: location)
} else if updateHoveredLink(at: location, modifiers: NSEvent.modifierFlags) {
NSCursor.pointingHand.set()
} else {
super.cursorUpdate(with: event)
}
}
override func mouseMoved(with event: NSEvent) {
guard isUnderDragStrip(event.locationInWindow) else { return super.mouseMoved(with: event) }
NSCursor.arrow.set()
let overLink = updateHoveredLink(at: event.locationInWindow, modifiers: event.modifierFlags)
guard !isUnderDragStrip(event.locationInWindow) else { return NSCursor.arrow.set() }
guard !isOverBookmarkIndex(event.locationInWindow) else { return bookmarkIndex?.updateCursor(at: event.locationInWindow) ?? () }
super.mouseMoved(with: event)
if overLink { NSCursor.pointingHand.set() }
}
override func mouseExited(with event: NSEvent) {
super.mouseExited(with: event)
updateHoveredLink(at: event.locationInWindow, modifiers: [])
}
/// ⌘ pressed or let go while the pointer rests on a link.
override func flagsChanged(with event: NSEvent) {
super.flagsChanged(with: event)
guard let window else { return }
let location = window.mouseLocationOutsideOfEventStream
let wasOverLink = hoveredLink != nil
if updateHoveredLink(at: location, modifiers: event.modifierFlags) {
NSCursor.pointingHand.set()
} else if wasOverLink {
NSCursor.iBeam.set()
}
}
// MARK: Links
/// Opens a ⌘-clicked link.
var openLink: (URL) -> Void = { NSWorkspace.shared.open($0) }
/// The link under the pointer while ⌘ is held; it shows underlined.
private(set) var hoveredLink: NSRange?
private var linkTracking: NSTrackingArea?
/// The link at `point`, only over its glyphs: the space past the end of a line holds no link.
func link(at point: NSPoint) -> (url: URL, range: NSRange)? {
guard let layoutManager, let textContainer, length > 0 else { return nil }
let inContainer = NSPoint(x: point.x - textContainerOrigin.x, y: point.y - textContainerOrigin.y)
let glyph = layoutManager.glyphIndex(for: inContainer, in: textContainer)
let glyphRect = layoutManager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: textContainer)
guard glyphRect.contains(inContainer) else { return nil }
return PageLink.link(in: string as NSString, at: layoutManager.characterIndexForGlyph(at: glyph))
}
/// Underlines the link under the pointer while ⌘ is held; true when there is one.
@discardableResult
func updateHoveredLink(at locationInWindow: NSPoint, modifiers: NSEvent.ModifierFlags) -> Bool {
var range: NSRange?
if modifiers.contains(.command), editor == nil, !isUnderDragStrip(locationInWindow) {
range = link(at: convert(locationInWindow, from: nil))?.range
}
guard range != hoveredLink, let layoutManager else { return range != nil }
// The text may have changed since the underline was set.
if let old = hoveredLink.map({ NSIntersectionRange($0, NSRange(location: 0, length: length)) }), old.length > 0 {
layoutManager.removeTemporaryAttribute(.underlineStyle, forCharacterRange: old)
}
if let range {
layoutManager.addTemporaryAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, forCharacterRange: range)
}
hoveredLink = range
return range != nil
}
/// NSTextView does not send every pointer move on its own.
override func updateTrackingAreas() {
super.updateTrackingAreas()
if let linkTracking { removeTrackingArea(linkTracking) }
let area = NSTrackingArea(rect: .zero, options: [.mouseMoved, .mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self)
addTrackingArea(area)
linkTracking = area
}
// MARK: Clicks
/// A plain click on a code block or table opens its editor; any click closes an open one first.
/// ⌘-click on a link opens it; a plain click on a code block or table opens its editor; any click closes an open editor first.
override func mouseDown(with event: NSEvent) {
if editor != nil { endEditing(nil) }
// Measured after the edit is put back: a removed object moves the text under the pointer.
let point = convert(event.locationInWindow, from: nil)
if event.modifierFlags.contains(.command), let link = link(at: point) {
updateHoveredLink(at: event.locationInWindow, modifiers: [])
openLink(link.url)
return
}
if event.modifierFlags.intersection([.shift, .command, .option, .control]).isEmpty, let location = object(at: point) {
openEditor(at: location, point: point)
return
@@ -213,6 +329,33 @@ final class PageTextView: NSTextView {
}
}
// MARK: Lorem
/// The sentences `#lorem` picks from.
var loremSentences: [String] = LoremText.sentences
override func insertText(_ string: Any, replacementRange: NSRange) {
super.insertText(string, replacementRange: replacementRange)
expandLorem()
}
/// Replaces a typed `#lorem` at the start of a line with lorem text, as an undo step of its own.
private func expandLorem() {
let caret = selectedRange()
let trigger = LoremText.trigger as NSString
guard caret.length == 0, !hasMarkedText(), caret.location >= trigger.length else { return }
let text = self.string as NSString
let range = NSRange(location: caret.location - trigger.length, length: trigger.length)
guard text.lineStart(at: caret.location) == range.location, text.substring(with: range) == LoremText.trigger,
let lorem = LoremText.pick(from: loremSentences) else { return }
// Grouping by event would undo the typed `m` together with the lorem text.
if let undoManager, undoManager.groupsByEvent, undoManager.groupingLevel == 1 {
undoManager.endUndoGrouping()
undoManager.beginUndoGrouping()
}
insert(pageText.plainString(lorem.text), replacing: range)
}
// MARK: Copy, paste, drop
override var writablePasteboardTypes: [NSPasteboard.PasteboardType] {
@@ -282,6 +425,19 @@ final class PageTextView: NSTextView {
}
}
/// Pastes at the end of the page as a new block, after a blank line.
func append(from pasteboard: NSPasteboard) {
guard canPaste(from: pasteboard) else { return }
let string = self.string
let end = NSRange(location: length, length: 0)
if string.hasSuffix("\n\n") || string.isEmpty {
setSelectedRange(end)
} else {
insert(pageText.plainString(string.hasSuffix("\n") ? "\n" : "\n\n"), replacing: end)
}
paste(from: pasteboard)
}
/// Text dropped from a drag, or brought by a service; only ⌘V turns text into an object.
override func readSelection(from pboard: NSPasteboard, type: NSPasteboard.PasteboardType) -> Bool {
guard canPaste(from: pboard) else { return false }
@@ -423,64 +579,132 @@ final class PageTextView: NSTextView {
isImageDrag ? endImageDrag() : super.concludeDragOperation(sender)
}
// MARK: Margin dates
// MARK: Bookmarks
var showsDates: Bool {
sideSpace >= PageMetrics.dateMarginMinimum
/// The bookmarks of the page, as found at the last `reloadBookmarks`.
private(set) var bookmarks: [PageBookmark] = []
private var widestBookmarkLabel: CGFloat = 0
/// Finds the bookmarks again; call it after a change of text, created dates or text size.
func reloadBookmarks() {
guard let textStorage else { return }
let string = textStorage.string as NSString
let now = now()
bookmarks = Bookmark.find(in: string).map { bookmark in
let start = string.blockStart(at: bookmark.range.location)
let created = textStorage.attribute(.plakCreated, at: start, effectiveRange: nil) as? Date
return PageBookmark(title: bookmark.title, date: created.map { CreatedDate.label(for: $0, now: now) }, range: bookmark.range)
}
let attributes: [NSAttributedString.Key: Any] = [.font: bookmarkFont]
widestBookmarkLabel = bookmarks.map { NSAttributedString(string: $0.label, attributes: attributes).size().width }.max() ?? 0
invalidateBookmarks()
}
/// True when the side space holds the bookmark index on the left and the full labels on the right.
var bookmarksAreWide: Bool {
!bookmarks.isEmpty && sideSpace >= PageMetrics.bookmarkWideSide(widestLabel: widestBookmarkLabel, reasonableLabel: reasonableBookmarkLabel)
}
/// The width of a label of `bookmarkLabelCharacters` characters.
var reasonableBookmarkLabel: CGFloat {
let sample = String(repeating: "0", count: PageMetrics.bookmarkLabelCharacters)
return NSAttributedString(string: sample, attributes: [.font: bookmarkFont]).size().width
}
var bookmarkFont: NSFont {
PlakFonts.mono(round(pageText.font.pointSize * PageMetrics.dateScale))
}
/// The look of a bookmark label; a label too long for its room ends in an ellipsis.
var bookmarkAttributes: [NSAttributedString.Key: Any] {
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byTruncatingTail
return [.font: bookmarkFont, .foregroundColor: Theme.inkMuted, .paragraphStyle: style]
}
/// NSTextView leaves the clip narrowed to the column after drawing, which would hide every label right of it.
override func draw(_ dirtyRect: NSRect) {
NSGraphicsContext.saveGraphicsState()
super.draw(dirtyRect)
NSGraphicsContext.restoreGraphicsState()
if let dropCaret, dropCaret.intersects(dirtyRect) {
Theme.accent.setFill()
dropCaret.fill()
}
let attributes: [NSAttributedString.Key: Any] = [.font: dateFont, .foregroundColor: Theme.inkMuted]
for date in marginDates(in: dirtyRect) {
NSAttributedString(string: date.label, attributes: attributes).draw(in: date.rect)
let attributes = bookmarkAttributes
for mark in bookmarkMarks(in: dirtyRect) {
Theme.bookmarkRule.setFill()
mark.rules.forEach { $0.fill() }
NSAttributedString(string: mark.label, attributes: attributes)
.draw(with: mark.rect, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])
}
}
/// Redraws the margin, where the layout does not look after the dates.
func invalidateMargin() {
let visible = visibleRect
setNeedsDisplay(NSRect(x: 0, y: visible.minY, width: sideSpace, height: visible.height))
/// Redraws the visible page: the labels right of the column are not looked after by the layout.
func invalidateBookmarks() {
setNeedsDisplay(visibleRect)
}
var dateFont: NSFont {
PlakFonts.body(round(pageText.font.pointSize * PageMetrics.dateScale))
}
/// The dates of the blocks whose first line lies in `rect`: right-aligned next to the column, at that line.
func marginDates(in rect: NSRect) -> [MarginDate] {
guard showsDates, let layoutManager, let textContainer, let textStorage, textStorage.length > 0 else { return [] }
let origin = textContainerOrigin
let lineHeight = pageText.lineHeight
let search = NSRect(x: 0, y: rect.minY - origin.y - lineHeight, width: textContainer.size.width, height: rect.height + lineHeight * 2)
let glyphs = layoutManager.glyphRange(forBoundingRect: search, in: textContainer)
let characters = layoutManager.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil)
let string = textStorage.string as NSString
let attributes: [NSAttributedString.Key: Any] = [.font: dateFont]
let now = now()
var dates: [MarginDate] = []
var location = string.lineStart(at: characters.location)
while location < min(NSMaxRange(characters) + 1, string.length) {
let end = string.lineEnd(from: location)
defer { location = end + 1 }
guard !string.isBlankLine(NSRange(location: location, length: end - location)) else { continue }
if location > 0 {
let previous = string.lineStart(at: location - 1)
guard string.isBlankLine(NSRange(location: previous, length: location - 1 - previous)) else { continue }
}
guard let created = textStorage.attribute(.plakCreated, at: location, effectiveRange: nil) as? Date else { continue }
let label = CreatedDate.label(for: created, now: now)
/// The labels and rules of the bookmarks whose line lies in `rect`.
func bookmarkMarks(in rect: NSRect) -> [BookmarkMark] {
guard !bookmarks.isEmpty, let layoutManager, let textContainer else { return [] }
let wide = bookmarksAreWide
let attributes: [NSAttributedString.Key: Any] = [.font: bookmarkFont]
let columnRight = textContainerOrigin.x + textContainer.size.width
let gap = PageMetrics.bookmarkGap
var marks: [BookmarkMark] = []
for bookmark in bookmarks {
let label = wide ? bookmark.label : bookmark.date
guard let label, NSMaxRange(bookmark.range) <= length else { continue }
let size = NSAttributedString(string: label, attributes: attributes).size()
let line = lineRect(at: location)
let midY = line.minY + min(line.height, lineHeight) / 2
let width = ceil(size.width), height = ceil(size.height)
let right = origin.x - PageMetrics.dateSpacing
dates.append(MarginDate(label: label, rect: NSRect(x: right - width, y: round(midY - height / 2), width: width, height: height)))
let lastCharacter = max(bookmark.range.location, NSMaxRange(bookmark.range) - 1)
let line = lineRect(at: wide ? bookmark.range.location : lastCharacter)
guard line.maxY >= rect.minY, line.minY <= rect.maxY else { continue }
let midY = line.minY + min(line.height, pageText.lineHeight) / 2
let labelY = round(midY - height / 2)
let ruleY = floor(midY)
if wide {
let ruleStart = columnRight + gap
let labelMaxX = bounds.maxX - PageMetrics.bookmarkTail - gap
let room = labelMaxX - (ruleStart + PageMetrics.bookmarkRuleMinimum + gap)
guard room > 0 else { continue }
let labelX = labelMaxX - min(width, room)
marks.append(BookmarkMark(
label: label,
rect: NSRect(x: labelX, y: labelY, width: labelMaxX - labelX, height: height),
rules: [
NSRect(x: ruleStart, y: ruleY, width: labelX - gap - ruleStart, height: 1),
NSRect(x: labelMaxX + gap, y: ruleY, width: bounds.maxX - labelMaxX - gap, height: 1),
]
))
} else {
let glyph = layoutManager.glyphIndexForCharacter(at: lastCharacter)
let textEnd = layoutManager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil).maxX + textContainerOrigin.x
let labelX = columnRight - width
guard labelX - gap > textEnd + gap else { continue }
var rules = [NSRect(x: textEnd + gap, y: ruleY, width: labelX - gap - textEnd - gap, height: 1)]
let tailEnd = min(columnRight + gap + PageMetrics.bookmarkTail, bounds.maxX)
if tailEnd - columnRight - gap >= 4 {
rules.append(NSRect(x: columnRight + gap, y: ruleY, width: tailEnd - columnRight - gap, height: 1))
}
marks.append(BookmarkMark(label: label, rect: NSRect(x: labelX, y: labelY, width: width, height: height), rules: rules))
}
}
return dates
return marks
}
}
private extension NSRect {
/// The parts of this rect outside `hole`: above, below, left and right of it.
func subtracting(_ hole: NSRect?) -> [NSRect] {
guard let hole, intersects(hole) else { return [self] }
let cut = intersection(hole)
return [
NSRect(x: minX, y: minY, width: width, height: cut.minY - minY),
NSRect(x: minX, y: cut.maxY, width: width, height: maxY - cut.maxY),
NSRect(x: minX, y: cut.minY, width: cut.minX - minX, height: cut.height),
NSRect(x: cut.maxX, y: cut.minY, width: maxX - cut.maxX, height: cut.height),
].filter { $0.width > 0 && $0.height > 0 }
}
}