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
+8 -1
View File
@@ -15,7 +15,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
NSApp.mainMenu = MainMenu.make()
let store: PageStore
do {
store = try PageStore()
store = try PageStore(pruneAt: Date())
} catch {
// No store means nothing can flush over the unreadable page file on quit.
showUnreadable(error)
@@ -23,6 +23,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
return
}
self.store = store
removeUnusedImages(of: store)
let controller = PageWindowController(store: store)
windowController = controller
controller.onHide = { [weak self] in self?.hidePlak() }
@@ -108,6 +109,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
}
/// Runs only when the page file holds the page: with no page file, or a failed write, it would delete used images.
private func removeUnusedImages(of store: PageStore) {
guard store.saveError == nil, FileManager.default.fileExists(atPath: store.url.path) else { return }
ImageStore(base: store.url.deletingLastPathComponent()).removeUnused(keeping: store.loaded.imagePaths)
}
private func showUnreadable(_ error: Error) {
let alert = NSAlert()
alert.alertStyle = .critical
+5 -3
View File
@@ -1,8 +1,10 @@
import Foundation
/// The lorem text that `#lorem` puts in the page: an opening sentence of 16 words, two paragraphs and a contact sample.
/// The lorem text that `#lorem` puts in the page: a bookmark, an opening sentence of 16 words, two paragraphs and a contact sample.
public struct LoremText: Equatable, Sendable {
public static let trigger = "#lorem"
/// The first line of the lorem text, so it shows in the bookmark index.
public static let bookmark = "=lorem"
public static let openingWords = 16
public static let paragraphSentences = 3...5
public static let resourceBundleName = "Plak_PlakCore.bundle"
@@ -17,9 +19,9 @@ public struct LoremText: Equatable, Sendable {
self.contacts = contacts
}
/// The sentence, the two paragraphs, the phones, the addresses and the e-mails, with a blank line between each.
/// The bookmark, the sentence, the two paragraphs, the phones, the addresses and the e-mails, with a blank line between each.
public var text: String {
([opening] + paragraphs.map { $0.joined(separator: " ") } + contacts.blocks).joined(separator: "\n\n")
([Self.bookmark, opening] + paragraphs.map { $0.joined(separator: " ") } + contacts.blocks).joined(separator: "\n\n")
}
public static func wordCount(_ sentence: String) -> Int {
+39
View File
@@ -0,0 +1,39 @@
import Foundation
extension PageFile {
/// The number of days a block stays in the page after its created date.
public static let keptDays = 14
/// The page without the blocks created more than `keptDays` calendar days before `now`, and without undated blocks.
///
/// A fenced block is one line, so it goes or stays whole. The blank lines above a removed block go with it.
public func pruned(now: Date, timeZone: TimeZone = .current) -> PageFile {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
guard let cutoff = calendar.date(byAdding: .day, value: -Self.keptDays, to: now) else { return self }
let blocks = self.blocks
let keeps = blocks.map { block in dates[block.lowerBound].map { $0 >= cutoff } ?? false }
guard keeps.contains(false) else { return self }
guard let first = blocks.first, let last = blocks.last, keeps.contains(true) else { return PageFile() }
var keptLines = Array(lines[..<first.lowerBound])
var keptDates: [Int: Date] = [:]
var hasBlock = false
for (index, block) in blocks.enumerated() where keeps[index] {
if hasBlock { keptLines += lines[blocks[index - 1].upperBound..<block.lowerBound] }
keptDates[keptLines.count] = dates[block.lowerBound]
keptLines += lines[block]
hasBlock = true
}
keptLines += lines[last.upperBound...]
return PageFile(lines: keptLines, dates: keptDates)
}
/// The paths of every image line, as `images/<name>`.
public var imagePaths: Set<String> {
Set(lines.compactMap { line in
if case let .image(path) = line { return path }
return nil
})
}
}
+21
View File
@@ -59,6 +59,27 @@ public struct ImageStore: Sendable {
return relativePath(target)
}
/// Deletes the image files in the image folder whose `images/<name>` path is not in `used`.
///
/// Only regular files directly in the folder go; a symbolic link, a folder or a hidden file stays, and a file
/// that cannot be deleted is skipped.
/// - Returns: the paths of the deleted files, sorted.
@discardableResult
public func removeUnused(keeping used: Set<String>) -> [String] {
let manager = FileManager.default
let keys: Set<URLResourceKey> = [.isRegularFileKey, .isSymbolicLinkKey]
guard (try? manager.attributesOfItem(atPath: folder.path)[.type] as? FileAttributeType) == .typeDirectory,
let urls = try? manager.contentsOfDirectory(at: folder, includingPropertiesForKeys: Array(keys), options: .skipsHiddenFiles)
else { return [] }
var removed: [String] = []
for url in urls where Self.isImageFile(url) && !used.contains(relativePath(url)) {
guard let values = try? url.resourceValues(forKeys: keys), values.isRegularFile == true, values.isSymbolicLink != true,
(try? manager.removeItem(at: url)) != nil else { continue }
removed.append(relativePath(url))
}
return removed.sorted()
}
/// The name for an image made now: `2026-10-16-085512-a3f0`.
public func name(ext: String) -> String {
var calendar = Calendar(identifier: .gregorian)
+15 -3
View File
@@ -20,7 +20,7 @@ public final class PageStore {
.appendingPathComponent("page.md")
}
/// The page file as read at launch; the first page when there was no file.
/// The page file as read at launch, after the pruning; the first page when there was no file.
public let loaded: PageFile
/// Makes the page file text when a save runs, so a keystroke costs no conversion; nil writes nothing.
@@ -36,12 +36,15 @@ public final class PageStore {
@ObservationIgnored private var isDirty = false
/// Reads the page file; a missing file gives `firstPage`, which the next flush writes unless it is empty.
///
/// With `pruneAt`, the old and undated blocks are left out and the page file is written at once when one was.
/// - Throws: `PageStoreError.unreadable` when the file exists but cannot be read.
public init(
url: URL = PageStore.defaultURL,
debounce: Duration = .milliseconds(500),
write: @escaping @Sendable (Data, URL) throws -> Void = PageStore.writeAtomically,
firstPage: @autoclosure () -> PageFile = WelcomeText.page(createdAt: Date())
firstPage: @autoclosure () -> PageFile = WelcomeText.page(createdAt: Date()),
pruneAt now: Date? = nil
) throws {
self.url = url
self.debounce = debounce
@@ -50,7 +53,16 @@ public final class PageStore {
guard let data = try? Data(contentsOf: url), let text = String(data: data, encoding: .utf8) else {
throw PageStoreError.unreadable(path: url.path)
}
loaded = PageFile(text: text)
let read = PageFile(text: text)
loaded = now.map { read.pruned(now: $0) } ?? read
if loaded != read {
do {
try write(Data(loaded.text().utf8), url)
} catch {
saveError = error.localizedDescription
isDirty = true
}
}
} else {
loaded = firstPage()
isDirty = !loaded.lines.isEmpty
+40 -2
View File
@@ -1,7 +1,11 @@
import AppKit
/// The bookmark index at the top left of the window: one line per bookmark, the last bookmarks of the page only.
/// The bookmark index at the top left of the window: one line per bookmark, the last bookmarks of the page only,
/// and the `end` entry below them.
final class BookmarkIndexView: NSScrollView {
/// The last entry, which jumps to the end of the page; it is no bookmark.
static let endLabel = "end"
let list = BookmarkIndexList()
/// A click on the entry at this index.
@@ -50,6 +54,9 @@ final class BookmarkIndexList: NSView {
private(set) var labels: [String] = []
private(set) var font = PlakFonts.mono(10)
var onSelect: ((Int) -> Void)?
/// The entry under the pointer; it draws in the accent colour.
private(set) var hoveredEntry: Int?
private var hoverTracking: NSTrackingArea?
override var isFlipped: Bool { true }
override var acceptsFirstResponder: Bool { false }
@@ -61,6 +68,7 @@ final class BookmarkIndexList: NSView {
guard labels != self.labels || font != self.font || width != frame.width else { return }
self.labels = labels
self.font = font
if let hoveredEntry, !labels.indices.contains(hoveredEntry) { self.hoveredEntry = nil }
setFrameSize(NSSize(width: width, height: CGFloat(labels.count) * lineHeight))
needsDisplay = true
window?.invalidateCursorRects(for: self)
@@ -79,12 +87,13 @@ final class BookmarkIndexList: NSView {
override func draw(_ dirtyRect: NSRect) {
let style = NSMutableParagraphStyle()
style.lineBreakMode = .byTruncatingTail
let attributes: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: Theme.inkMuted, .paragraphStyle: style]
var attributes: [NSAttributedString.Key: Any] = [.font: font, .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)
attributes[.foregroundColor] = index == hoveredEntry ? Theme.accent : Theme.inkMuted
NSAttributedString(string: label, attributes: attributes).draw(with: rect, options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine])
}
}
@@ -94,6 +103,35 @@ final class BookmarkIndexList: NSView {
onSelect?(index)
}
/// Always active: a click works on a window that is not key, so the hover shows there too.
override func updateTrackingAreas() {
super.updateTrackingAreas()
if let hoverTracking { removeTrackingArea(hoverTracking) }
let area = NSTrackingArea(rect: .zero, options: [.mouseMoved, .mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self)
addTrackingArea(area)
hoverTracking = area
}
override func mouseEntered(with event: NSEvent) {
hover(entry(at: convert(event.locationInWindow, from: nil)))
}
override func mouseMoved(with event: NSEvent) {
hover(entry(at: convert(event.locationInWindow, from: nil)))
}
override func mouseExited(with event: NSEvent) {
hover(nil)
}
/// Redraws only the entry that loses the hover and the one that gets it.
func hover(_ index: Int?) {
guard index != hoveredEntry else { return }
if let hoveredEntry { setNeedsDisplay(entryRect(hoveredEntry)) }
hoveredEntry = index
if let index { setNeedsDisplay(entryRect(index)) }
}
override func resetCursorRects() {
for index in labels.indices {
let rect = entryRect(index).intersection(visibleRect)
-2
View File
@@ -89,7 +89,6 @@ extension PageTextView {
layoutManager.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
layoutManager.invalidateDisplay(forCharacterRange: range)
sizeToFit()
invalidateBookmarks()
rect = objectRect(at: location)
}
editor.view.frame = NSRect(origin: rect.origin, size: size)
@@ -129,7 +128,6 @@ extension PageTextView {
newlineAdded = true
}
sizeToFit()
invalidateBookmarks()
guard let exit else { return }
let caret: Int
if let removedAt {
+123 -87
View File
@@ -15,14 +15,12 @@ struct PageBookmark: Equatable {
}
}
/// A drawn bookmark label and its rules.
struct BookmarkMark: Equatable {
var label: String
var rect: NSRect
var rules: [NSRect]
extension NSAttributedString.Key {
/// A bookmark line that shows in the bookmark look.
static let plakBookmarkLine = NSAttributedString.Key("plakBookmarkLine")
}
/// The one editable text view of the page, on TextKit 1: the reading column, the bookmark labels, paste and drop,
/// The one editable text view of the page, on TextKit 1: the reading column, the bookmark lines, paste and drop,
/// and the editors of code blocks and tables.
final class PageTextView: NSTextView {
let pageText: PageText
@@ -83,6 +81,7 @@ final class PageTextView: NSTextView {
selectedTextAttributes = [.backgroundColor: Theme.selection]
applyStyle()
updateDragTypeRegistration()
layout.delegate = self
}
@available(*, unavailable)
@@ -93,6 +92,7 @@ final class PageTextView: NSTextView {
}
/// Typing never carries a created date: the block it lands in gives one.
/// It is always page text, also next to a bookmark line in the bookmark look.
override var typingAttributes: [NSAttributedString.Key: Any] {
get { super.typingAttributes }
set {
@@ -100,6 +100,8 @@ final class PageTextView: NSTextView {
attributes[.plakCreated] = nil
attributes[.plakUndated] = nil
attributes[.attachment] = nil
attributes[.plakBookmarkLine] = nil
attributes.merge(pageTextLook) { _, page in page }
super.typingAttributes = attributes
}
}
@@ -147,12 +149,18 @@ final class PageTextView: NSTextView {
if length == 0 || (location >= length && !layoutManager.extraLineFragmentRect.isEmpty) {
rect = layoutManager.extraLineFragmentRect
} else {
let glyph = layoutManager.glyphIndexForCharacter(at: min(location, length - 1))
rect = layoutManager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
rect = layoutManager.lineFragmentRect(forGlyphAt: shownGlyph(at: min(location, length - 1)), effectiveRange: nil)
}
return rect.offsetBy(dx: textContainerOrigin.x, dy: textContainerOrigin.y)
}
/// The glyph of a character; for a hidden bookmark `=` the glyph of the title after it.
/// A null glyph has no line fragment and no place of its own.
func shownGlyph(at location: Int) -> Int {
guard let layoutManager else { return 0 }
return layoutManager.glyphIndexForCharacter(at: isHiddenBookmarkSign(at: location) ? location + 1 : location)
}
/// The bottom of the last line of text.
var textBottom: CGFloat {
lineRect(at: length).maxY
@@ -509,7 +517,7 @@ final class PageTextView: NSTextView {
let line = lineRect(at: location)
var x = line.minX
if let layoutManager, length > 0, location < length || layoutManager.extraLineFragmentRect.isEmpty {
let glyph = layoutManager.glyphIndexForCharacter(at: min(location, length - 1))
let glyph = shownGlyph(at: min(location, length - 1))
if location < length {
x += layoutManager.location(forGlyphAt: glyph).x
} else {
@@ -583,7 +591,10 @@ final class PageTextView: NSTextView {
/// The bookmarks of the page, as found at the last `reloadBookmarks`.
private(set) var bookmarks: [PageBookmark] = []
private var widestBookmarkLabel: CGFloat = 0
/// The width of the longest full bookmark label.
private(set) var widestBookmarkLabel: CGFloat = 0
/// True from a text change until `reloadBookmarks`: the bookmark ranges may point at other text then.
private var bookmarksAreStale = false
/// Finds the bookmarks again; call it after a change of text, created dates or text size.
func reloadBookmarks() {
@@ -597,32 +608,104 @@ final class PageTextView: NSTextView {
}
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
bookmarksAreStale = false
styleBookmarkLines()
}
/// The font of the bookmark index.
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]
/// The look of a bookmark line away from the selection.
var bookmarkLineAttributes: [NSAttributedString.Key: Any] {
let font = PlakFonts.monoBold(pageText.font.pointSize + PageMetrics.bookmarkLineGrowth)
return [
.font: font,
.foregroundColor: Theme.accent,
.baselineOffset: max(0, (pageText.lineHeight - PlakFonts.naturalLineHeight(font)) / 2),
.plakBookmarkLine: true,
]
}
/// NSTextView leaves the clip narrowed to the column after drawing, which would hide every label right of it.
/// The parts of the page look that a bookmark line changes.
private var pageTextLook: [NSAttributedString.Key: Any] {
pageText.attributes.filter { [NSAttributedString.Key.font, .foregroundColor, .baselineOffset].contains($0.key) }
}
override func shouldChangeText(in affectedCharRange: NSRange, replacementString: String?) -> Bool {
let allowed = super.shouldChangeText(in: affectedCharRange, replacementString: replacementString)
if allowed { bookmarksAreStale = true }
return allowed
}
override func setSelectedRanges(_ ranges: [NSValue], affinity: NSSelectionAffinity, stillSelecting: Bool) {
super.setSelectedRanges(ranges, affinity: affinity, stillSelecting: stillSelecting)
if !stillSelecting, !bookmarksAreStale { styleBookmarkLines() }
}
/// Shows each bookmark line in the bookmark look while the selection is off it, and as page text while it is on it.
/// Set straight on the text storage, so it adds no undo step and posts no text change: nothing is stamped or saved.
func styleBookmarkLines() {
guard let textStorage, textStorage.editedMask.isEmpty else { return }
let length = textStorage.length
let selection = selectedRanges.map(\.rangeValue)
let wanted = bookmarks.map(\.range).filter { $0.length > 0 && NSMaxRange($0) <= length && !Self.touches(selection, line: $0) }
let look = bookmarkLineAttributes
let font = look[.font] as? NSFont
var kept = Set<Int>()
var stale: [NSRange] = []
textStorage.enumerateAttribute(.plakBookmarkLine, in: NSRange(location: 0, length: length)) { value, run, _ in
guard value != nil else { return }
if wanted.contains(run), textStorage.attribute(.font, at: run.location, effectiveRange: nil) as? NSFont == font {
kept.insert(run.location)
} else {
stale.append(run)
}
}
let added = wanted.filter { !kept.contains($0.location) }
guard !stale.isEmpty || !added.isEmpty else { return }
let plain = pageTextLook
textStorage.beginEditing()
for range in stale {
textStorage.removeAttribute(.plakBookmarkLine, range: range)
forEachTextRun(in: range) { textStorage.addAttributes(plain, range: $0) }
}
for range in added {
forEachTextRun(in: range) { textStorage.addAttributes(look, range: $0) }
}
textStorage.endEditing()
for range in stale + added {
layoutManager?.invalidateGlyphs(forCharacterRange: NSRange(location: range.location, length: 1), changeInLength: 0, actualCharacterRange: nil)
layoutManager?.invalidateLayout(forCharacterRange: range, actualCharacterRange: nil)
}
}
/// True for the `=` of a bookmark line in the bookmark look, which is not shown.
func isHiddenBookmarkSign(at location: Int) -> Bool {
guard let textStorage, location < textStorage.length,
textStorage.attribute(.plakBookmarkLine, at: location, effectiveRange: nil) != nil else { return false }
let string = textStorage.string as NSString
return string.character(at: location) == 0x3D && (location == 0 || string.character(at: location - 1) == 0x0A)
}
/// The runs of `range` without an image or other object, which keep their own look.
private func forEachTextRun(in range: NSRange, _ body: (NSRange) -> Void) {
textStorage?.enumerateAttribute(.attachment, in: range) { value, run, _ in
if value == nil { body(run) }
}
}
/// True when a caret lies on `line`, its end included, or a selection overlaps it.
static func touches(_ selection: [NSRange], line: NSRange) -> Bool {
selection.contains { range in
range.length == 0
? range.location >= line.location && range.location <= NSMaxRange(line)
: range.location <= NSMaxRange(line) && NSMaxRange(range) > line.location
}
}
/// NSTextView leaves the clip narrowed to the column after drawing, which would cut off the drop caret.
override func draw(_ dirtyRect: NSRect) {
NSGraphicsContext.saveGraphicsState()
super.draw(dirtyRect)
@@ -631,67 +714,20 @@ final class PageTextView: NSTextView {
Theme.accent.setFill()
dropCaret.fill()
}
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 visible page: the labels right of the column are not looked after by the layout.
func invalidateBookmarks() {
setNeedsDisplay(visibleRect)
}
/// 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 width = ceil(size.width), height = ceil(size.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 marks
extension PageTextView: NSLayoutManagerDelegate {
/// Gives the hidden `=` of a bookmark line a null glyph: it stays in the text but takes no room.
func layoutManager(_ layoutManager: NSLayoutManager, shouldGenerateGlyphs glyphs: UnsafePointer<CGGlyph>,
properties: UnsafePointer<NSLayoutManager.GlyphProperty>, characterIndexes: UnsafePointer<Int>,
font: NSFont, forGlyphRange glyphRange: NSRange) -> Int {
let hidden = (0..<glyphRange.length).filter { isHiddenBookmarkSign(at: characterIndexes[$0]) }
guard !hidden.isEmpty else { return 0 }
var changed = Array(UnsafeBufferPointer(start: properties, count: glyphRange.length))
for index in hidden { changed[index] = .null }
layoutManager.setGlyphs(glyphs, properties: changed, characterIndexes: characterIndexes, font: font, forGlyphRange: glyphRange)
return glyphRange.length
}
}
+44 -22
View File
@@ -85,8 +85,7 @@ 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) }
bookmarkIndex.onSelect = { [weak self] index in self?.selectIndexEntry(index) }
textView.bookmarkIndex = bookmarkIndex
root.addSubview(scrollView)
@@ -216,8 +215,9 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
public func textDidChange(_ notification: Notification) {
stampBlocks()
store.changed()
let room = bookmarkIndexRoom
textView.reloadBookmarks()
if textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 {
if room != bookmarkIndexRoom || textView.topSpace > PageMetrics.topInset || textView.frame.height <= clip.bounds.height * 2 {
layoutPage()
} else {
layoutBookmarkIndex()
@@ -245,16 +245,25 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
// MARK: Layout
/// Puts the column in the middle; a short page gets more room on top so its end stays in the middle.
/// The room left of the column that the bookmark index needs.
private var bookmarkIndexRoom: CGFloat {
let end = NSAttributedString(string: BookmarkIndexView.endLabel, attributes: [.font: textView.bookmarkFont]).size().width
let gaps = PageMetrics.bookmarkIndexInset + PageMetrics.bookmarkGap * 2
return min(ceil(max(textView.widestBookmarkLabel, end)) + gaps, PageMetrics.bookmarkIndexRoomMaximum)
}
/// Puts the column in the middle, or further right when the bookmark index needs the room on its left.
/// A short page gets more room on top so its end stays in the middle.
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, characters: columnWidth.characters), visible.width - PageMetrics.sideMargin * 2))
var column = max(1, min(PageMetrics.columnWidth(bodySize: textSize.body, characters: columnWidth.characters), visible.width - PageMetrics.sideMargin * 2))
let side = max(floor((visible.width - column) / 2), bookmarkIndexRoom)
column = max(1, min(column, visible.width - side - PageMetrics.sideMargin))
if container.size.width != column {
container.size = NSSize(width: column, height: CGFloat.greatestFiniteMagnitude)
}
layoutManager.ensureLayout(for: container)
let side = floor((visible.width - column) / 2)
let bottom = round(visible.height / 2)
let endMid = textView.lineRect(at: textView.length).midY - textView.topSpace
let top = max(PageMetrics.topInset, round(visible.height / 2 - endMid))
@@ -266,24 +275,37 @@ public final class PageViewController: NSViewController, NSTextViewDelegate, NST
layoutBookmarkIndex()
}
/// Shows the bookmark index at the top left when bookmarks are wide, as wide as the side space.
/// Shows the bookmark index at the top left, as wide as the room left of the column.
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)
let labels = textView.bookmarks.suffix(PageMetrics.bookmarkIndexCount).map(\.label) + [BookmarkIndexView.endLabel]
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 entries stay in sight.
bookmarkIndex.contentView.scroll(to: NSPoint(x: 0, y: max(0, bookmarkIndex.contentHeight - height)))
bookmarkIndex.reflectScrolledClipView(bookmarkIndex.contentView)
view.window?.invalidateCursorRects(for: textView)
}
/// A click on an entry of the bookmark index: a bookmark, or `end` below them.
func selectIndexEntry(_ entry: Int) {
if entry == min(textView.bookmarks.count, PageMetrics.bookmarkIndexCount) {
showPageEnd()
} else {
showBookmark(entry: entry)
}
if wasHidden != bookmarkIndex.isHidden || !labels.isEmpty { view.window?.invalidateCursorRects(for: textView) }
}
/// Puts the caret at the end of the page and scrolls the end to the vertical middle, as ⌘↓ does.
func showPageEnd() {
closeEditor()
view.window?.makeFirstResponder(textView)
textView.setSelectedRange(NSRange(location: textView.length, length: 0))
scrollEndToMiddle()
}
/// Puts the caret at the end of the bookmark line and scrolls that line to the vertical middle.
+7 -1
View File
@@ -1,6 +1,6 @@
import AppKit
/// IBM Plex Mono for the page, code, tables and bookmarks, IBM Plex Sans for the banner; the system fonts when Plex is missing.
/// IBM Plex Mono for the page, code, tables, bookmark lines and the bookmark index, IBM Plex Sans for the banner; the system fonts when Plex is missing.
public enum PlakFonts {
public static func body(_ size: CGFloat) -> NSFont {
FontRegistry.registerBundledFonts()
@@ -12,6 +12,12 @@ public enum PlakFonts {
return NSFont(name: "IBMPlexMono-Regular", size: size) ?? NSFont.monospacedSystemFont(ofSize: size, weight: .regular)
}
/// IBM Plex Mono Bold (700), the boldest bundled mono weight.
public static func monoBold(_ size: CGFloat) -> NSFont {
FontRegistry.registerBundledFonts()
return NSFont(name: "IBMPlexMono-Bold", size: size) ?? NSFont.monospacedSystemFont(ofSize: size, weight: .bold)
}
/// The height of one line of this font with no paragraph style.
static func naturalLineHeight(_ font: NSFont) -> CGFloat {
ceil(font.ascender - font.descender + font.leading)
+7 -19
View File
@@ -6,16 +6,14 @@ public enum Theme {
public static let paper = NSColor(hex: 0x101720)
/// Text, also on the save error banner.
public static let ink = NSColor(hex: 0xE4E7E6)
/// Bookmark labels, the bookmark index, `image missing`.
/// The bookmark index, `image missing`.
public static let inkMuted = NSColor(hex: 0x6C7783)
/// The caret, the drop caret and the frame of the selected table cell.
/// The caret, the drop caret, the frame of the selected table cell, bookmark lines and the hovered entry of the bookmark index.
public static let accent = NSColor(hex: 0xE8913A)
/// The tint behind selected text.
public static let selection = NSColor(hex: 0xE8913A, alpha: 0.22)
/// The grid lines of a table.
public static let rule = NSColor(hex: 0x3A424C)
/// The hairline from a bookmark to its label.
public static let bookmarkRule = NSColor(hex: 0x6C7783)
/// The background of the save error banner.
public static let panel = NSColor(hex: 0x18202B)
/// The tint behind a code block.
@@ -92,16 +90,12 @@ public enum PageMetrics {
public static let bookmarkIndexInset: CGFloat = 8
/// The bookmark index shows only the last bookmarks of the page.
public static let bookmarkIndexCount = 10
/// Room between the column, a bookmark rule and a bookmark label.
/// Half the room between the bookmark index and the column.
public static let bookmarkGap: CGFloat = 8
/// The rule right of a bookmark label.
public static let bookmarkTail: CGFloat = 16
/// The shortest rule between the column and a bookmark label.
public static let bookmarkRuleMinimum: CGFloat = 24
/// Below this side space bookmarks are always narrow.
public static let bookmarkSideMinimum: CGFloat = 160
/// A label longer than this many characters never keeps bookmarks narrow; it is cut off with an ellipsis instead.
public static let bookmarkLabelCharacters = 40
/// A bookmark line away from the caret is this much bigger than the page text.
public static let bookmarkLineGrowth: CGFloat = 2
/// The most room left of the column that the bookmark index takes when it has to push the column to the right.
public static let bookmarkIndexRoomMaximum: CGFloat = 160
/// The size of code and tables against the body size; the same as the page text.
public static let codeScale: CGFloat = 1
/// Room around the code inside a code block.
@@ -111,12 +105,6 @@ public enum PageMetrics {
public static let tableColumnMaximum: CGFloat = 240
public static let tableCellPadding = NSSize(width: 6, height: 3)
/// The side space from which bookmarks are wide: room for the widest label, at most `reasonableLabel`, with its rules.
public static func bookmarkWideSide(widestLabel: CGFloat, reasonableLabel: CGFloat) -> CGFloat {
let label = ceil(min(widestLabel, reasonableLabel))
return max(bookmarkGap + bookmarkRuleMinimum + bookmarkGap + label + bookmarkGap + bookmarkTail, bookmarkSideMinimum)
}
/// The width of about `characters` characters of body text.
public static func columnWidth(bodySize: CGFloat, characters: Int) -> CGFloat {
let sample = String(String(repeating: "the quick brown fox jumps over a lazy dog ", count: 4).prefix(characters))