perf(editor): scope fold re-key to the edit (#142)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
With a fold open, every keystroke re-scanned the buffer, rebuilt the full attributed string through setAttributedString (invalidating TextKit layout for the ENTIRE document — O(n²) typing on folded documents), and rasterized a chrome image the size of the document (~35M pixels on a 700×50,000pt doc) to paint a handful of chevrons. Single-line edits now re-key folds in place: a shouldChangeText override records the edit (range + UTF-16 delta) and a pure rekey function shifts surviving folds, kills folds whose marker line was edited (un-hiding just that scope), and re-hides a line edited inside a hidden scope — no parents rescan, no storage swap. Structural edits, multi-line pastes, and wholesale loads keep the full pass; a font probe at each survivor's scope head falls back to it whenever hidden styling was wiped (the fence-flip restyle self-heals this way). Chrome renders as one tiny cached layer per list parent (same glyph rasters at ~15×18pt, geometry-flipped into the existing document-space overlay) instead of the document-sized bitmap; an edit at/after every parent line skips the rebuild outright, so writing at the document end does zero geometry queries. Full-buffer scans per keystroke drop from 2–3 to one. Finish-audit hardening: the single-line gate checks Character.isNewline (a literal newline compare passes CRLF — one grapheme equal to neither scalar), and apply() clears the recorded edit so structural indent/ outdent always takes the full pass (a childless unterminated block's shift-tab is a single-line replacement that would otherwise keep a dead fold's scope hidden — apparent line loss). Closes #142
This commit is contained in:
1 parent
de1154dacd
commit
cc317b65b9
9 files changed
+687
-114
No files matched your search
+304
-110
@@ -15,6 +15,15 @@
|
||||
// folded parent shows "⋯ N" after its line. Folding never dirties the
|
||||
// document (ADR-0013's posture, carried to prose).
|
||||
//
|
||||
// #142 (F1/F2): per-keystroke cost is paragraph-scoped. A single-line
|
||||
// edit re-keys folds in place (`rekey` — delta shift, marker-line death,
|
||||
// scope re-hide) with no parents rescan and no storage swap; the full
|
||||
// `refreshFoldRendering` stays for structural edits and wholesale loads
|
||||
// (and self-heals in via the hidden-styling probe when a fence-flip
|
||||
// restyle wiped the folded attributes). Chrome renders as per-parent
|
||||
// tiny layers in the overlay — never a document-sized bitmap — and an
|
||||
// edit below every parent skips the rebuild outright.
|
||||
//
|
||||
// Key-delivery facts: arrows arrive as the function-key scalars
|
||||
// \u{F700}/\u{F701} carrying .function/.numericPad device bits (strip
|
||||
// before comparing modifiers); ⇧⇥ arrives as backtab \u{19}, sometimes
|
||||
@@ -25,9 +34,14 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// The chrome overlay: a click-through layer-host whose `contents` image the
|
||||
/// text view renders offscreen (SwiftUI-hosted TextKit2 views never reliably
|
||||
/// route through draw(_:) — layer contents sidestep the whole question).
|
||||
/// The chrome overlay: a click-through layer-host that paints the list
|
||||
/// chrome as one tiny CALayer per chevron/⋯N (SwiftUI-hosted TextKit2
|
||||
/// views never reliably route through draw(_:) — layer contents sidestep
|
||||
/// the whole question; #115 field finding). #142: per-parent layers in
|
||||
/// document space replaced the old document-sized bitmap — a 700×50,000pt
|
||||
/// doc used to rasterize ~35M pixels per keystroke to paint a handful of
|
||||
/// chevrons; now it rasterizes ~15×18pt per glyph. The overlay rides the
|
||||
/// scroll view with the text, so scrolling needs no refresh.
|
||||
final class ProseChromeView: NSView {
|
||||
weak var owner: ProseListTextView?
|
||||
|
||||
@@ -35,23 +49,17 @@ final class ProseChromeView: NSView {
|
||||
nil
|
||||
} // clicks reach the text view
|
||||
|
||||
/// Re-render the owner's chrome into a fresh image and install it as the
|
||||
/// layer's contents. Deferred one main-queue tick: refresh points fire
|
||||
/// inside textDidChange, after TextKit2 invalidated layout but before
|
||||
/// re-layout — querying fragments synchronously finds none (#115).
|
||||
func refresh() {
|
||||
/// Rebuild the owner's chrome layers. Deferred one main-queue tick:
|
||||
/// refresh points fire inside textDidChange, after TextKit2
|
||||
/// invalidated layout but before re-layout — querying fragments
|
||||
/// synchronously finds none (#115). `skipIfParentsAbove`: an edit
|
||||
/// whose location sits at/after every parent line can't have moved
|
||||
/// any chevron — keep the painted layers and do nothing.
|
||||
func refresh(skipIfParentsAbove: NSRange? = nil) {
|
||||
guard bounds.width > 0, bounds.height > 0 else { return }
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self, let owner else { return }
|
||||
// No parents anywhere and nothing painted → skip the raster.
|
||||
// ponytail: the image is document-sized per refresh — rasterize the
|
||||
// visible height instead if tall docs measurably chug.
|
||||
if owner.proseParentCount == 0, layer?.contents == nil {
|
||||
return
|
||||
}
|
||||
guard let image = owner.renderChromeImage(size: bounds.size) else { return }
|
||||
wantsLayer = true
|
||||
layer?.contents = image
|
||||
owner.rebuildChromeLayers(skipIfParentsAbove: skipIfParentsAbove)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,14 +73,37 @@ final class ProseChromeView: NSView {
|
||||
|
||||
final class ProseListTextView: NSTextView {
|
||||
/// A fold: the marker line's buffer position + its text (the re-key
|
||||
/// identity when an edit above shifts offsets).
|
||||
struct Fold: Equatable {
|
||||
/// identity when an edit above shifts offsets) + the hidden scope
|
||||
/// (shift-maintained by the #142 cheap path; the full pass re-derives
|
||||
/// it from `parents`).
|
||||
nonisolated struct Fold: Equatable {
|
||||
let key: Int
|
||||
let lineText: String
|
||||
let scope: NSRange
|
||||
}
|
||||
|
||||
var folds: [Fold] = []
|
||||
|
||||
/// #142: the last accepted single-line edit (old-coords range + UTF-16
|
||||
/// length delta), recorded in shouldChangeText while the storage still
|
||||
/// holds the old text. Consumed by refreshFolds; nil (multi-line,
|
||||
/// rejected, or none) → the full pass.
|
||||
var pendingPlainEdit: (range: NSRange, delta: Int)?
|
||||
|
||||
override func shouldChangeText(in affectedRange: NSRange, replacementString: String?) -> Bool {
|
||||
let accepted = super.shouldChangeText(in: affectedRange, replacementString: replacementString)
|
||||
pendingPlainEdit = nil
|
||||
if accepted, let replacement = replacementString {
|
||||
let old = (string as NSString).substring(with: affectedRange)
|
||||
// \.isNewline, never == "\n"/"\r": "\r\n" is ONE grapheme equal to
|
||||
// neither — a CRLF-carrying edit must reach the full pass (#142 audit).
|
||||
if !replacement.contains(where: \.isNewline), !old.contains(where: \.isNewline) {
|
||||
pendingPlainEdit = (affectedRange, replacement.utf16.count - affectedRange.length)
|
||||
}
|
||||
}
|
||||
return accepted
|
||||
}
|
||||
|
||||
// MARK: Structural keys
|
||||
|
||||
override func keyDown(with event: NSEvent) {
|
||||
@@ -127,7 +158,10 @@ final class ProseListTextView: NSTextView {
|
||||
apply(edit)
|
||||
}
|
||||
|
||||
private func performOutdent(_ item: ProseList.Item) {
|
||||
/// ⇧Tab: remove up to 2 columns from every line of the block. The caret
|
||||
/// rides its line's shift (parks at the new line start inside it).
|
||||
/// Internal for the #142 audit pin (drives apply's structural routing).
|
||||
func performOutdent(_ item: ProseList.Item) {
|
||||
guard let edit = ProseList.outdent(item, caret: selectedRange().location, in: string) else { return }
|
||||
apply(edit)
|
||||
}
|
||||
@@ -144,6 +178,10 @@ final class ProseListTextView: NSTextView {
|
||||
/// folds are open, where the post-edit fold refresh already does it.
|
||||
private func apply(_ edit: ProseList.Edit) {
|
||||
guard shouldChangeText(in: edit.range, replacementString: edit.replacement) else { return }
|
||||
// Structural edits reshape blocks — always the full pass. A childless
|
||||
// unterminated block's outdent is a SINGLE-line replacement, and the
|
||||
// cheap path would keep the dead fold's scope hidden (#142 audit).
|
||||
pendingPlainEdit = nil
|
||||
textStorage?.replaceCharacters(in: edit.range, with: edit.replacement)
|
||||
didChangeText()
|
||||
let length = (string as NSString).length
|
||||
@@ -160,9 +198,15 @@ final class ProseListTextView: NSTextView {
|
||||
/// textDidChange calls it LAST (after its paragraph reattribute and
|
||||
/// session.edit, so hidden styling lands on top of the refreshed
|
||||
/// presentation) and the wholesale content swaps (generation load, draft
|
||||
/// echo — no textDidChange fires for those) call it directly. No folds →
|
||||
/// chrome-only refresh; refreshFoldRendering ends in its own refresh.
|
||||
/// echo — no textDidChange fires for those) call it directly. #142: a
|
||||
/// recorded single-line edit takes the in-place re-key (no rescan, no
|
||||
/// storage swap); no folds → chrome-only refresh, everything else → the
|
||||
/// full pass.
|
||||
func refreshFolds() {
|
||||
defer { pendingPlainEdit = nil }
|
||||
if let edit = pendingPlainEdit, !folds.isEmpty, rekeyAfterPlainEdit(edit) {
|
||||
return
|
||||
}
|
||||
guard !folds.isEmpty else {
|
||||
chrome.refresh()
|
||||
return
|
||||
@@ -174,7 +218,7 @@ final class ProseListTextView: NSTextView {
|
||||
if let idx = folds.firstIndex(where: { $0.key == parent.markerLine.location }) {
|
||||
folds.remove(at: idx)
|
||||
} else {
|
||||
folds.append(Fold(key: parent.markerLine.location, lineText: lineText(of: parent.markerLine)))
|
||||
folds.append(Fold(key: parent.markerLine.location, lineText: lineText(of: parent.markerLine), scope: parent.foldScope))
|
||||
}
|
||||
refreshFoldRendering()
|
||||
}
|
||||
@@ -192,7 +236,7 @@ final class ProseListTextView: NSTextView {
|
||||
parents
|
||||
.filter { lineText(of: $0.markerLine) == fold.lineText }
|
||||
.min { abs($0.markerLine.location - fold.key) < abs($1.markerLine.location - fold.key) }
|
||||
.map { Fold(key: $0.markerLine.location, lineText: fold.lineText) }
|
||||
.map { Fold(key: $0.markerLine.location, lineText: fold.lineText, scope: $0.foldScope) }
|
||||
}.filter { seenKeys.insert($0.key).inserted } // two folds can't land on one parent
|
||||
let sel = selectedRange()
|
||||
textStorage?.setAttributedString(ProsePresenter.attribute(string))
|
||||
@@ -396,102 +440,24 @@ final class ProseListTextView: NSTextView {
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: hide)
|
||||
}
|
||||
|
||||
// MARK: Chrome (chevron + ⋯ N)
|
||||
|
||||
/// Plain overlay sibling that owns the chrome drawing — TextKit2 views hosted
|
||||
/// under SwiftUI never route through NSTextView.draw(_:), but a plain NSView
|
||||
/// subview always draws. Click-through (hitTest nil); document-coordinate
|
||||
/// space, so it rides the scroll view with the text.
|
||||
private let chrome = ProseChromeView()
|
||||
|
||||
/// Install the overlay once the view reaches a window — the inherited
|
||||
/// NSTextView inits (which build the full TextKit stack) stay untouched.
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
guard window != nil, chrome.superview == nil else { return }
|
||||
chrome.owner = self
|
||||
chrome.frame = bounds
|
||||
chrome.autoresizingMask = [.width, .height]
|
||||
addSubview(chrome, positioned: .above, relativeTo: nil)
|
||||
chrome.refresh()
|
||||
}
|
||||
|
||||
/// Parents count for the chrome's no-parents raster skip.
|
||||
var proseParentCount: Int {
|
||||
ProseList.parents(in: string).count
|
||||
}
|
||||
|
||||
/// Render the whole chrome (chevrons + ⋯ N) into an image in the layer.
|
||||
/// Top-left flipped coordinates — same space as lineRect's output.
|
||||
func renderChromeImage(size: NSSize) -> NSImage? {
|
||||
guard let window else { return nil }
|
||||
let image = NSImage(size: size)
|
||||
image.lockFocusFlipped(true)
|
||||
drawListChrome()
|
||||
image.unlockFocus()
|
||||
return image
|
||||
}
|
||||
|
||||
/// Parents whose marker line is not hidden inside another fold's scope —
|
||||
/// hidden ones collapse to ~zero height and would paint phantom chevrons.
|
||||
private var visibleParents: [ProseList.ParentHint] {
|
||||
let parents = ProseList.parents(in: string)
|
||||
let hiddenScopes = folds.compactMap { fold in
|
||||
parents.first(where: { $0.markerLine.location == fold.key })?.foldScope
|
||||
}
|
||||
return parents.filter { parent in
|
||||
!hiddenScopes.contains { NSLocationInRange(parent.markerLine.location, $0) }
|
||||
}
|
||||
}
|
||||
|
||||
func drawListChrome() {
|
||||
for parent in visibleParents {
|
||||
guard let startRect = lineRect(ofOffset: parent.markerLine.location) else { continue }
|
||||
let folded = folds.contains { $0.key == parent.markerLine.location }
|
||||
drawChrome(folded ? "▸" : "▾", folded: folded,
|
||||
at: NSPoint(x: startRect.minX - 14, y: startRect.midY - chromeSize * 0.62))
|
||||
if folded {
|
||||
// ⋯ N after the parent's visible line text, not after the marker.
|
||||
let text = lineText(of: parent.markerLine) as NSString
|
||||
let lastChar = parent.markerLine.location + max(0, text.length - 1)
|
||||
if let endRect = lineRect(ofOffset: lastChar) {
|
||||
drawChrome("⋯ \(parent.hiddenLineCount)", folded: true,
|
||||
at: NSPoint(x: endRect.maxX + 6, y: endRect.midY - chromeSize * 0.62))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
// Plain single-clicks only — shift-click extends selection, double/
|
||||
// triple-click select word/paragraph; neither toggles a fold.
|
||||
if !event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.capsLock).isEmpty || event.clickCount > 1 {
|
||||
super.mouseDown(with: event)
|
||||
return
|
||||
}
|
||||
let point = convert(event.locationInWindow, from: nil)
|
||||
for parent in visibleParents {
|
||||
guard let rect = lineRect(ofOffset: parent.markerLine.location) else { continue }
|
||||
// Toggle zone: the gutter through the marker span ("- ", "1. ")
|
||||
// of the marker line's first visual line.
|
||||
if point.y >= rect.minY - 1, point.y <= rect.maxY + 1, point.x < rect.minX + 12 {
|
||||
toggleFold(parent)
|
||||
return
|
||||
}
|
||||
}
|
||||
super.mouseDown(with: event)
|
||||
}
|
||||
|
||||
/// mono-11 chrome, rust when folded, muted open (the outliner's
|
||||
/// "⋯ N" vocabulary carried to prose).
|
||||
private let chromeSize: CGFloat = 11
|
||||
|
||||
private func drawChrome(_ glyph: String, folded: Bool, at point: NSPoint) {
|
||||
NSAttributedString(string: glyph, attributes: [
|
||||
.font: NSFont.monospacedSystemFont(ofSize: chromeSize, weight: .regular),
|
||||
.foregroundColor: folded ? NSColor(DesignTokens.accent) : NSColor(DesignTokens.muted),
|
||||
]).draw(at: point)
|
||||
}
|
||||
/// #142 audit: glyph rasters cached by string — only ▸/▾ plus one per
|
||||
/// distinct ⋯ N label exist, so a 50k-parent document shares a handful
|
||||
/// of images instead of re-rasterizing every glyph per keystroke.
|
||||
/// ponytail: layers are still built for every parent (scroll fires no
|
||||
/// refresh, so viewport-culled parents would never gain a chevron);
|
||||
/// cull to the visible band + refresh on scroll if pathological
|
||||
/// parent counts still chug.
|
||||
private var chromeGlyphImages: [String: NSImage] = [:]
|
||||
|
||||
// MARK: Geometry (TextKit2)
|
||||
|
||||
@@ -513,3 +479,231 @@ final class ProseListTextView: NSTextView {
|
||||
return convert(windowRect, from: nil)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - #142 in-place re-key (single-line edits)
|
||||
|
||||
extension ProseListTextView {
|
||||
/// One `rekey` pass: survivors (shifted), dead scopes to un-hide, the
|
||||
/// span needing re-hide, the caret park target.
|
||||
nonisolated struct RekeyOutcome: Equatable {
|
||||
let folds: [Fold]
|
||||
let diedScopes: [NSRange]
|
||||
let rehide: NSRange?
|
||||
let park: Int?
|
||||
}
|
||||
|
||||
/// The cheap path's view glue: apply the pure re-key, un-hide dead
|
||||
/// scopes, re-hide the edited line, park a caret stranded inside a
|
||||
/// hidden scope. Guarded by a probe — hidden styling must still be IN
|
||||
/// the storage (a wholesale restyle, e.g. the fence-flip's full
|
||||
/// attribute pass, wipes it); damaged → false and the caller falls
|
||||
/// back to the full pass.
|
||||
func rekeyAfterPlainEdit(_ edit: (range: NSRange, delta: Int)) -> Bool {
|
||||
let result = Self.rekey(folds: folds, edit: edit.range, delta: edit.delta, in: string)
|
||||
let buffer = string as NSString
|
||||
for fold in result.folds {
|
||||
guard fold.scope.length > 0, fold.scope.location < buffer.length,
|
||||
let font = textStorage?.attribute(.font, at: fold.scope.location, effectiveRange: nil) as? NSFont,
|
||||
font.pointSize < 1
|
||||
else { return false }
|
||||
}
|
||||
folds = result.folds
|
||||
if let storage = textStorage {
|
||||
for scope in result.diedScopes {
|
||||
// #142 audit: bounds-harden the sink — a shift can't push a
|
||||
// scope out of the buffer on any reachable path, but
|
||||
// reattribute's paragraph scan would trap if it ever did.
|
||||
guard scope.location >= 0, scope.length > 0, NSMaxRange(scope) <= buffer.length else { continue }
|
||||
ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: scope)
|
||||
}
|
||||
if let rehide = result.rehide, rehide.length > 0 {
|
||||
storage.setAttributes(ProseTypography.foldedAttributes, range: rehide)
|
||||
}
|
||||
}
|
||||
if let park = result.park {
|
||||
setSelectedRange(NSRange(location: min(park, buffer.length), length: 0))
|
||||
}
|
||||
// A fold death changes chevron state — only an all-survivor edit may
|
||||
// skip the rebuild when every parent line sits above it.
|
||||
chrome.refresh(skipIfParentsAbove: result.diedScopes.isEmpty ? edit.range : nil)
|
||||
return true
|
||||
}
|
||||
|
||||
/// #142: pure re-key math for a single-line edit. Per fold: an edit
|
||||
/// entirely above shifts key + scope by delta; an edit touching the
|
||||
/// marker line's content kills the fold (the full re-key's stored-
|
||||
/// lineText match could no longer find it — same death, minus the
|
||||
/// jump-to-duplicate-markers fuzz); an edit inside the scope grows or
|
||||
/// shrinks it and flags the edited line for re-hiding (the
|
||||
/// coordinator's paragraph reattribute just un-hid it) plus a caret
|
||||
/// park at the marker end. Multi-line/structural edits stay on the
|
||||
/// full pass. `lineText` stays fresh on survivors by construction —
|
||||
/// only edits outside the marker line leave a fold alive.
|
||||
nonisolated static func rekey(
|
||||
folds: [Fold],
|
||||
edit: NSRange,
|
||||
delta: Int,
|
||||
in text: String,
|
||||
) -> RekeyOutcome {
|
||||
let buffer = text as NSString
|
||||
var survivors: [Fold] = []
|
||||
var diedScopes: [NSRange] = []
|
||||
var rehide: NSRange?
|
||||
var park: Int?
|
||||
let editEnd = NSMaxRange(edit)
|
||||
for fold in folds {
|
||||
// Old marker-content span [key, key+lineText): a zero-length edit
|
||||
// "touches" it even at either boundary (an insertion at the head
|
||||
// or at the caret-park position changes the line's text → death,
|
||||
// full-pass parity).
|
||||
let contentEnd = fold.key + fold.lineText.utf16.count
|
||||
let touchedMarker = (edit.location < contentEnd && editEnd > fold.key)
|
||||
|| (edit.length == 0 && fold.key <= edit.location && edit.location <= contentEnd)
|
||||
// Scope shift, old-coords rules: translate when the edit is above,
|
||||
// grow/shrink when inside (a single-line edit can't span across).
|
||||
var scope = fold.scope
|
||||
if edit.location < scope.location {
|
||||
scope.location += delta
|
||||
} else if edit.location < NSMaxRange(fold.scope) {
|
||||
scope.length = max(0, scope.length + delta)
|
||||
}
|
||||
guard buffer.length > 0, !touchedMarker else {
|
||||
diedScopes.append(scope) // shifted above for the un-hide pass
|
||||
continue
|
||||
}
|
||||
if edit.location < fold.key {
|
||||
survivors.append(Fold(key: fold.key + delta, lineText: fold.lineText, scope: scope))
|
||||
continue
|
||||
}
|
||||
if edit.location < NSMaxRange(scope) {
|
||||
// Edit inside the hidden scope: the edited line needs re-hiding
|
||||
// and the caret (which sits at the edit) parks at the marker end.
|
||||
let line = buffer.lineRange(for: NSRange(location: min(edit.location, buffer.length - 1), length: 1))
|
||||
rehide = NSIntersectionRange(line, scope)
|
||||
park = fold.key + fold.lineText.utf16.count
|
||||
}
|
||||
survivors.append(Fold(key: fold.key, lineText: fold.lineText, scope: scope))
|
||||
}
|
||||
return RekeyOutcome(folds: survivors, diedScopes: diedScopes, rehide: rehide, park: park)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Chrome (chevron + ⋯ N)
|
||||
|
||||
extension ProseListTextView {
|
||||
/// Install the overlay once the view reaches a window — the inherited
|
||||
/// NSTextView inits (which build the full TextKit stack) stay untouched.
|
||||
/// #142: layer-hosting from the start; sublayer geometry is flipped
|
||||
/// inside the rebuild to match lineRect's top-left y.
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
guard window != nil, chrome.superview == nil else { return }
|
||||
chrome.owner = self
|
||||
chrome.wantsLayer = true
|
||||
chrome.frame = bounds
|
||||
chrome.autoresizingMask = [.width, .height]
|
||||
addSubview(chrome, positioned: .above, relativeTo: nil)
|
||||
chrome.refresh()
|
||||
}
|
||||
|
||||
/// #142: rebuild the chrome as one tiny layer per visible parent —
|
||||
/// same glyph rasters as the bitmap era (drawChrome into a small
|
||||
/// flipped image), positioned in the overlay's document space.
|
||||
/// `skipIfParentsAbove`: an edit at/after every parent line moves no
|
||||
/// chevron — keep the painted layers untouched (typing at the end of a
|
||||
/// long document skips every lineRect query).
|
||||
func rebuildChromeLayers(skipIfParentsAbove: NSRange? = nil) {
|
||||
guard let overlay = chrome.layer else { return }
|
||||
overlay.isGeometryFlipped = true // sublayer frames speak lineRect's top-left y
|
||||
let parents = ProseList.parents(in: string)
|
||||
if parentsUnmoved(parents, below: skipIfParentsAbove) {
|
||||
return // chevrons can't have moved — keep the painted layers
|
||||
}
|
||||
let visible = visibleParents(parents)
|
||||
var layers: [CALayer] = []
|
||||
for parent in visible {
|
||||
guard let startRect = lineRect(ofOffset: parent.markerLine.location) else { continue }
|
||||
let folded = folds.contains { $0.key == parent.markerLine.location }
|
||||
layers.append(chromeGlyphLayer(folded ? "▸" : "▾", folded: folded,
|
||||
at: NSPoint(x: startRect.minX - 14, y: startRect.midY - chromeSize * 0.62)))
|
||||
if folded {
|
||||
// ⋯ N after the parent's visible line text, not after the marker.
|
||||
let text = lineText(of: parent.markerLine) as NSString
|
||||
let lastChar = parent.markerLine.location + max(0, text.length - 1)
|
||||
if let endRect = lineRect(ofOffset: lastChar) {
|
||||
layers.append(chromeGlyphLayer("⋯ \(parent.hiddenLineCount)", folded: true,
|
||||
at: NSPoint(x: endRect.maxX + 6, y: endRect.midY - chromeSize * 0.62)))
|
||||
}
|
||||
}
|
||||
}
|
||||
overlay.sublayers = layers
|
||||
}
|
||||
|
||||
/// True when the edit sits at/after every parent line and layers are
|
||||
/// already painted — no chevron can have moved, so the rebuild may
|
||||
/// skip every lineRect query.
|
||||
private func parentsUnmoved(_ parents: [ProseList.ParentHint], below edit: NSRange?) -> Bool {
|
||||
guard let edit, let painted = chrome.layer?.sublayers, !painted.isEmpty else { return false }
|
||||
return parents.allSatisfy { NSMaxRange($0.markerLine) <= edit.location }
|
||||
}
|
||||
|
||||
/// One small raster per glyph, contents-pinned to the layer — the
|
||||
/// bitmap era's drawing calls at ~15×18pt instead of document size.
|
||||
/// Box fixed wide; glyphs draw left-aligned from the box's top-left,
|
||||
/// matching draw(at:)'s geometry in the flipped overlay.
|
||||
private func chromeGlyphLayer(_ glyph: String, folded: Bool, at point: NSPoint) -> CALayer {
|
||||
let size = NSSize(width: 64, height: chromeSize * 1.6)
|
||||
if chromeGlyphImages[glyph] == nil {
|
||||
let image = NSImage(size: size)
|
||||
image.lockFocusFlipped(true)
|
||||
drawChrome(glyph, folded: folded, at: .zero)
|
||||
image.unlockFocus()
|
||||
chromeGlyphImages[glyph] = image
|
||||
}
|
||||
let layer = CALayer()
|
||||
layer.contents = chromeGlyphImages[glyph]
|
||||
layer.contentsScale = window?.backingScaleFactor ?? 2
|
||||
layer.frame = NSRect(origin: point, size: size)
|
||||
return layer
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
// Plain single-clicks only — shift-click extends selection, double/
|
||||
// triple-click select word/paragraph; neither toggles a fold.
|
||||
if !event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.capsLock).isEmpty || event.clickCount > 1 {
|
||||
super.mouseDown(with: event)
|
||||
return
|
||||
}
|
||||
let point = convert(event.locationInWindow, from: nil)
|
||||
for parent in visibleParents(ProseList.parents(in: string)) {
|
||||
guard let rect = lineRect(ofOffset: parent.markerLine.location) else { continue }
|
||||
// Toggle zone: the gutter through the marker span ("- ", "1. ")
|
||||
// of the marker line's first visual line.
|
||||
if point.y >= rect.minY - 1, point.y <= rect.maxY + 1, point.x < rect.minX + 12 {
|
||||
toggleFold(parent)
|
||||
return
|
||||
}
|
||||
}
|
||||
super.mouseDown(with: event)
|
||||
}
|
||||
|
||||
/// Parents whose marker line is not hidden inside another fold's scope —
|
||||
/// hidden ones collapse to ~zero height and would paint phantom chevrons.
|
||||
/// Takes the caller's scan (#142): mouseDown pays one, the chrome rebuild
|
||||
/// reuses its own.
|
||||
private func visibleParents(_ parents: [ProseList.ParentHint]) -> [ProseList.ParentHint] {
|
||||
let hiddenScopes = folds.compactMap { fold in
|
||||
parents.first(where: { $0.markerLine.location == fold.key })?.foldScope
|
||||
}
|
||||
return parents.filter { parent in
|
||||
!hiddenScopes.contains { NSLocationInRange(parent.markerLine.location, $0) }
|
||||
}
|
||||
}
|
||||
|
||||
private func drawChrome(_ glyph: String, folded: Bool, at point: NSPoint) {
|
||||
NSAttributedString(string: glyph, attributes: [
|
||||
.font: NSFont.monospacedSystemFont(ofSize: chromeSize, weight: .regular),
|
||||
.foregroundColor: folded ? NSColor(DesignTokens.accent) : NSColor(DesignTokens.muted),
|
||||
]).draw(at: point)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user