updates plug with all sorts of awesome improvements
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
import AppKit
|
||||
|
||||
/// The bookmark index at the top left of the window: one line per bookmark, the last bookmarks of the page only.
|
||||
final class BookmarkIndexView: NSScrollView {
|
||||
let list = BookmarkIndexList()
|
||||
|
||||
/// A click on the entry at this index.
|
||||
var onSelect: ((Int) -> Void)? {
|
||||
get { list.onSelect }
|
||||
set { list.onSelect = newValue }
|
||||
}
|
||||
|
||||
var labels: [String] { list.labels }
|
||||
|
||||
/// The height of all entries.
|
||||
var contentHeight: CGFloat { list.frame.height }
|
||||
|
||||
init() {
|
||||
super.init(frame: .zero)
|
||||
drawsBackground = false
|
||||
borderType = .noBorder
|
||||
hasVerticalScroller = true
|
||||
hasHorizontalScroller = false
|
||||
autohidesScrollers = true
|
||||
scrollerStyle = .overlay
|
||||
automaticallyAdjustsContentInsets = false
|
||||
contentInsets = NSEdgeInsetsZero
|
||||
contentView.drawsBackground = false
|
||||
documentView = list
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
|
||||
|
||||
func show(labels: [String], font: NSFont, width: CGFloat) {
|
||||
list.update(labels: labels, font: font, width: width)
|
||||
}
|
||||
|
||||
/// The pointing hand over an entry, the arrow elsewhere.
|
||||
func updateCursor(at locationInWindow: NSPoint) {
|
||||
let point = list.convert(locationInWindow, from: nil)
|
||||
(list.entry(at: point) != nil ? NSCursor.pointingHand : NSCursor.arrow).set()
|
||||
}
|
||||
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
}
|
||||
|
||||
/// The entries of the bookmark index, top to bottom.
|
||||
final class BookmarkIndexList: NSView {
|
||||
private(set) var labels: [String] = []
|
||||
private(set) var font = PlakFonts.mono(10)
|
||||
var onSelect: ((Int) -> Void)?
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
override var acceptsFirstResponder: Bool { false }
|
||||
override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
|
||||
|
||||
var lineHeight: CGFloat { PageMetrics.lineHeight(font) }
|
||||
|
||||
func update(labels: [String], font: NSFont, width: CGFloat) {
|
||||
guard labels != self.labels || font != self.font || width != frame.width else { return }
|
||||
self.labels = labels
|
||||
self.font = font
|
||||
setFrameSize(NSSize(width: width, height: CGFloat(labels.count) * lineHeight))
|
||||
needsDisplay = true
|
||||
window?.invalidateCursorRects(for: self)
|
||||
}
|
||||
|
||||
func entryRect(_ index: Int) -> NSRect {
|
||||
NSRect(x: 0, y: CGFloat(index) * lineHeight, width: bounds.width, height: lineHeight)
|
||||
}
|
||||
|
||||
func entry(at point: NSPoint) -> Int? {
|
||||
guard bounds.contains(point) else { return nil }
|
||||
let index = Int(point.y / lineHeight)
|
||||
return labels.indices.contains(index) ? index : nil
|
||||
}
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
let style = NSMutableParagraphStyle()
|
||||
style.lineBreakMode = .byTruncatingTail
|
||||
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: Theme.inkMuted, .paragraphStyle: style]
|
||||
let natural = PlakFonts.naturalLineHeight(font)
|
||||
for (index, label) in labels.enumerated() {
|
||||
let row = entryRect(index)
|
||||
guard row.intersects(dirtyRect) else { continue }
|
||||
let rect = NSRect(x: row.minX, y: row.minY + floor((row.height - natural) / 2), width: row.width, height: natural)
|
||||
NSAttributedString(string: label, attributes: attributes).draw(with: rect, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])
|
||||
}
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
guard let index = entry(at: convert(event.locationInWindow, from: nil)) else { return }
|
||||
onSelect?(index)
|
||||
}
|
||||
|
||||
override func resetCursorRects() {
|
||||
for index in labels.indices {
|
||||
let rect = entryRect(index).intersection(visibleRect)
|
||||
if !rect.isEmpty { addCursorRect(rect, cursor: .pointingHand) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ extension PageTextView {
|
||||
layoutManager.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
|
||||
layoutManager.invalidateDisplay(forCharacterRange: range)
|
||||
sizeToFit()
|
||||
invalidateMargin()
|
||||
invalidateBookmarks()
|
||||
rect = objectRect(at: location)
|
||||
}
|
||||
editor.view.frame = NSRect(origin: rect.origin, size: size)
|
||||
@@ -129,7 +129,7 @@ extension PageTextView {
|
||||
newlineAdded = true
|
||||
}
|
||||
sizeToFit()
|
||||
invalidateMargin()
|
||||
invalidateBookmarks()
|
||||
guard let exit else { return }
|
||||
let caret: Int
|
||||
if let removedAt {
|
||||
|
||||
@@ -23,14 +23,14 @@ final class PageText {
|
||||
init(imageBase: URL, images: ImageCache = ImageCache(), bodySize: CGFloat = TextSize.standard) {
|
||||
self.imageBase = imageBase
|
||||
self.images = images
|
||||
font = PlakFonts.body(bodySize)
|
||||
font = PlakFonts.mono(bodySize)
|
||||
codeFont = PlakFonts.mono(round(bodySize * PageMetrics.codeScale))
|
||||
setBodySize(bodySize)
|
||||
}
|
||||
|
||||
/// The minimum line height lets a line with an image grow to the image.
|
||||
func setBodySize(_ size: CGFloat) {
|
||||
font = PlakFonts.body(size)
|
||||
font = PlakFonts.mono(size)
|
||||
codeFont = PlakFonts.mono(round(size * PageMetrics.codeScale))
|
||||
lineHeight = PageMetrics.lineHeight(font)
|
||||
let style = NSMutableParagraphStyle()
|
||||
@@ -314,6 +314,17 @@ extension NSString {
|
||||
PageFile.isBlank(substring(with: range))
|
||||
}
|
||||
|
||||
/// The start of the first line of the block that holds the line at `location`.
|
||||
func blockStart(at location: Int) -> Int {
|
||||
var start = lineStart(at: location)
|
||||
while start > 0 {
|
||||
let previous = lineStart(at: start - 1)
|
||||
if isBlankLine(NSRange(location: previous, length: start - 1 - previous)) { break }
|
||||
start = previous
|
||||
}
|
||||
return start
|
||||
}
|
||||
|
||||
/// The lines of the blocks an edit touches; an edit in blank lines also takes the block above and below.
|
||||
func blockRegion(around edit: NSRange) -> NSRange {
|
||||
var start = lineStart(at: edit.location)
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,8 +22,10 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
let scrollView = NSScrollView()
|
||||
let textView: PageTextView
|
||||
let dragStrip = DragStripView()
|
||||
let bookmarkIndex = BookmarkIndexView()
|
||||
private let banner = NSTextField(labelWithString: "")
|
||||
private var textSize = TextSize()
|
||||
private var columnWidth = ColumnWidth()
|
||||
private var isLoading = false
|
||||
/// The characters edited since the last stamp of created dates.
|
||||
private var unstamped: NSRange?
|
||||
@@ -69,10 +71,10 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
textView.onEditorChange = { [weak self] in self?.store.changed() }
|
||||
textView.textStorage?.delegate = self
|
||||
|
||||
banner.font = .systemFont(ofSize: 12)
|
||||
banner.font = PlakFonts.body(12)
|
||||
banner.textColor = Theme.ink
|
||||
banner.drawsBackground = true
|
||||
banner.backgroundColor = Theme.selection
|
||||
banner.backgroundColor = Theme.panel
|
||||
banner.alignment = .center
|
||||
banner.isHidden = true
|
||||
banner.translatesAutoresizingMaskIntoConstraints = false
|
||||
@@ -83,7 +85,12 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
dragStrip.setDropTarget(textView)
|
||||
textView.dragStrip = dragStrip
|
||||
|
||||
bookmarkIndex.isHidden = true
|
||||
bookmarkIndex.onSelect = { [weak self] index in self?.showBookmark(entry: index) }
|
||||
textView.bookmarkIndex = bookmarkIndex
|
||||
|
||||
root.addSubview(scrollView)
|
||||
root.addSubview(bookmarkIndex)
|
||||
root.addSubview(dragStrip)
|
||||
root.addSubview(banner)
|
||||
NSLayoutConstraint.activate([
|
||||
@@ -102,6 +109,7 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
textView.textStorage?.setAttributedString(textView.pageText.attributedString(file))
|
||||
isLoading = false
|
||||
textView.undoManager?.removeAllActions()
|
||||
textView.reloadBookmarks()
|
||||
}
|
||||
|
||||
/// The page file text of the page as it is now, with the edit of an open editor in it.
|
||||
@@ -126,6 +134,13 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
scrollEndToMiddle()
|
||||
}
|
||||
|
||||
/// Pastes at the end of the page as a new block, then shows the end in the middle.
|
||||
public func append(from pasteboard: NSPasteboard) {
|
||||
closeEditor()
|
||||
textView.append(from: pasteboard)
|
||||
showEnd()
|
||||
}
|
||||
|
||||
// MARK: Images
|
||||
|
||||
/// Saves each image in the image folder and puts it in the text; a failed image is skipped.
|
||||
@@ -173,6 +188,23 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
textView.scrollRangeToVisible(textView.selectedRange())
|
||||
}
|
||||
|
||||
// MARK: Column width
|
||||
|
||||
@objc public func makeColumnWider(_ sender: Any?) {
|
||||
columnWidth.wider()
|
||||
applyColumnWidth()
|
||||
}
|
||||
|
||||
@objc public func makeColumnNarrower(_ sender: Any?) {
|
||||
columnWidth.narrower()
|
||||
applyColumnWidth()
|
||||
}
|
||||
|
||||
private func applyColumnWidth() {
|
||||
layoutPage()
|
||||
textView.scrollRangeToVisible(textView.selectedRange())
|
||||
}
|
||||
|
||||
// MARK: Text changes
|
||||
|
||||
public func textStorage(_ textStorage: NSTextStorage, willProcessEditing editedMask: NSTextStorageEditActions,
|
||||
@@ -184,8 +216,12 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
public func textDidChange(_ notification: Notification) {
|
||||
stampBlocks()
|
||||
store.changed()
|
||||
textView.invalidateMargin()
|
||||
if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 { layoutPage() }
|
||||
textView.reloadBookmarks()
|
||||
if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 {
|
||||
layoutPage()
|
||||
} else {
|
||||
layoutBookmarkIndex()
|
||||
}
|
||||
if !textView.isReplacingObject { keepCaretAboveFloor() }
|
||||
}
|
||||
|
||||
@@ -213,7 +249,7 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
private func layoutPage() {
|
||||
let visible = clip.bounds.size
|
||||
guard visible.width > 0, let container = textView.textContainer, let layoutManager = textView.layoutManager else { return }
|
||||
let column = max(1, min(PageMetrics.columnWidth(bodySize: textSize.body), visible.width - PageMetrics.sideMargin * 2))
|
||||
let column = max(1, min(PageMetrics.columnWidth(bodySize: textSize.body, characters: columnWidth.characters), visible.width - PageMetrics.sideMargin * 2))
|
||||
if container.size.width != column {
|
||||
container.size = NSSize(width: column, height: CGFloat.greatestFiniteMagnitude)
|
||||
}
|
||||
@@ -227,6 +263,40 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
|
||||
if textView.frame.width != visible.width { textView.setFrameSize(NSSize(width: visible.width, height: textView.frame.height)) }
|
||||
textView.sizeToFit()
|
||||
textView.positionEditor()
|
||||
layoutBookmarkIndex()
|
||||
}
|
||||
|
||||
/// Shows the bookmark index at the top left when bookmarks are wide, as wide as the side space.
|
||||
private func layoutBookmarkIndex() {
|
||||
let labels = textView.bookmarksAreWide ? textView.bookmarks.suffix(PageMetrics.bookmarkIndexCount).map(\.label) : []
|
||||
let wasHidden = bookmarkIndex.isHidden
|
||||
bookmarkIndex.isHidden = labels.isEmpty
|
||||
if !labels.isEmpty {
|
||||
let inset = PageMetrics.bookmarkIndexInset
|
||||
let width = max(0, textView.sideSpace - inset - PageMetrics.bookmarkGap * 2)
|
||||
bookmarkIndex.show(labels: labels, font: textView.bookmarkFont, width: width)
|
||||
let top = view.bounds.height - PageMetrics.topInset
|
||||
let height = max(0, min(bookmarkIndex.contentHeight, top - inset))
|
||||
let frame = NSRect(x: inset, y: top - height, width: width, height: height)
|
||||
if bookmarkIndex.frame != frame { bookmarkIndex.frame = frame }
|
||||
// When the entries do not fit, the lowest bookmarks stay in sight.
|
||||
bookmarkIndex.contentView.scroll(to: NSPoint(x: 0, y: max(0, bookmarkIndex.contentHeight - height)))
|
||||
bookmarkIndex.reflectScrolledClipView(bookmarkIndex.contentView)
|
||||
}
|
||||
if wasHidden != bookmarkIndex.isHidden || !labels.isEmpty { view.window?.invalidateCursorRects(for: textView) }
|
||||
}
|
||||
|
||||
/// Puts the caret at the end of the bookmark line and scrolls that line to the vertical middle.
|
||||
/// `entry` counts from the first entry of the index, which holds only the last bookmarks.
|
||||
func showBookmark(entry: Int) {
|
||||
let shown = textView.bookmarks.suffix(PageMetrics.bookmarkIndexCount)
|
||||
let index = shown.startIndex + entry
|
||||
closeEditor()
|
||||
guard textView.bookmarks.indices.contains(index) else { return }
|
||||
let end = NSMaxRange(textView.bookmarks[index].range)
|
||||
view.window?.makeFirstResponder(textView)
|
||||
textView.setSelectedRange(NSRange(location: end, length: 0))
|
||||
scroll(toY: textView.lineRect(at: end).midY - clip.bounds.height / 2)
|
||||
}
|
||||
|
||||
@objc private func clipFrameChanged(_ notification: Notification) {
|
||||
|
||||
@@ -79,7 +79,7 @@ struct TableLayout {
|
||||
let last = max(first, min(rowCount - 1, Int((visible.maxY - origin.y) / rowHeight)))
|
||||
let top = origin.y + CGFloat(first) * rowHeight
|
||||
let bottom = origin.y + CGFloat(last + 1) * rowHeight
|
||||
Theme.selection.setFill()
|
||||
Theme.rule.setFill()
|
||||
var x = origin.x
|
||||
for width in columnWidths + [0] {
|
||||
NSRect(x: x, y: top, width: line, height: bottom - top + line).fill()
|
||||
|
||||
Reference in New Issue
Block a user