feat(prose): list shortcuts — S5 (#115)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Markdown lists in the prose editor become structural: Tab/⇧Tab indent/outdent the item under the caret (wrapped lines ride along, caret follows), ⌥↑/⌥↓ move the item with its subtree among siblings. Every structural edit is one range replacement — a single undo step over the plain mode-B store (ADR-0010 stands). List parents fold visually: a gutter chevron collapses children to near-zero height with a rust ▸ and a "⋯ N" summary after the parent's line. Folding is view state — the buffer never changes (ADR-0013's posture carried to prose). Field findings baked in: SwiftUI-hosted TextKit2 never calls NSTextView.draw(_:) and every NSTextLayoutManager fragment query returns empty, so the chrome renders offscreen into a layer-contents image and geometry comes from firstRect(forCharacterRange:) (screen → window → view). Includes the finish-audit round: sibling block-for- block ⌥-move swap (was stealing the sibling's subtree), blank-line indent dirt, fold-key dedupe, hidden-parent chevron filtering, plain-click-only hit zone, no-parents raster skip. Closes #115 [Generated by AI]
This commit is contained in:
1 parent
c0513aae85
commit
c5c8749df4
12 files changed
+1142
-6
No files matched your search
@@ -31,6 +31,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
|
||||
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
|
||||
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
|
||||
- Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting.
|
||||
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
|
||||
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
|
||||
- Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
|
||||
|
||||
@@ -347,7 +347,7 @@ struct ProseTextView: NSViewRepresentable {
|
||||
}
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let tv = NSTextView()
|
||||
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
|
||||
tv.isRichText = false // plain source of truth; attributes are presentation
|
||||
tv.allowsUndo = true
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
@@ -391,7 +391,7 @@ struct ProseTextView: NSViewRepresentable {
|
||||
}
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let tv = scroll.documentView as? NSTextView else { return }
|
||||
guard let tv = scroll.documentView as? ProseListTextView else { return }
|
||||
// #77: posture toggle while editing — cheap idempotent set.
|
||||
tv.isContinuousSpellCheckingEnabled = spellChecking
|
||||
// #21: the ground follows focus in/out without a remount.
|
||||
@@ -414,6 +414,7 @@ struct ProseTextView: NSViewRepresentable {
|
||||
// have flushed it over the user's real content (#71 fix).
|
||||
tv.textStorage?.setAttributedString(ProsePresenter.attribute(session.text))
|
||||
context.coordinator.fenceDelims = ProsePresenter.fenceDelimCount(session.text)
|
||||
tv.refreshFolds() // #115: re-key folds over the swapped content
|
||||
// #66: restore cursor (clamped) + scroll.
|
||||
let length = (tv.string as NSString).length
|
||||
var cursor = session.restoreCursor ?? PostStore.CursorState()
|
||||
@@ -433,6 +434,7 @@ struct ProseTextView: NSViewRepresentable {
|
||||
// Echo guard: our own keystroke round-trips through the model —
|
||||
// only reload when the textview genuinely diverges (new draft).
|
||||
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
|
||||
tv.refreshFolds() // #115: re-key folds over the swapped content
|
||||
}
|
||||
// #71: flip-back caret — apply once per token, after any load above.
|
||||
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
|
||||
@@ -499,6 +501,8 @@ struct ProseTextView: NSViewRepresentable {
|
||||
} else {
|
||||
onEdit?(storage.string)
|
||||
}
|
||||
// #115: fold maintenance LAST — hidden styling over the refreshed presentation.
|
||||
(tv as? ProseListTextView)?.refreshFolds()
|
||||
}
|
||||
|
||||
func textViewDidChangeSelection(_ notification: Notification) {
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
//
|
||||
// ProseList.swift
|
||||
// Museion
|
||||
//
|
||||
// #115 (S5): prose-list model — pure, UTF-16-safe scan and structural
|
||||
// edits over the ONE plain buffer (ADR-0010 mode B: no secondary model).
|
||||
// A list "item" is its marker line plus wrapped lines and nested list
|
||||
// lines (indent > the item's). Tab/⇧Tab re-indent, ⌥↑/⌥↓ swap with an
|
||||
// adjacent sibling — each ONE range replacement, one undo step. Honest
|
||||
// v1: indent unit = the previous sibling's content column (never a
|
||||
// blind 2); moves are sibling-adjacent; fences end a block.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
nonisolated enum ProseList {
|
||||
// MARK: Scan
|
||||
|
||||
struct Line {
|
||||
let range: NSRange // content + terminator
|
||||
let content: NSRange
|
||||
let text: String
|
||||
let indent: Int // leading whitespace columns (tab = 2)
|
||||
let isList: Bool
|
||||
let isBlank: Bool
|
||||
var end: Int {
|
||||
range.location + range.length
|
||||
}
|
||||
}
|
||||
|
||||
struct Item: Equatable {
|
||||
/// The marker line incl. terminator — its `location` is the fold key.
|
||||
let markerLine: NSRange
|
||||
/// End of the marker line's content (caret park when its subtree folds).
|
||||
let markerEnd: Int
|
||||
let contentOffset: Int // UTF-16 offset of the first content column
|
||||
/// Marker line through the last subtree line's terminator.
|
||||
let block: NSRange
|
||||
/// The fold-hidden range; nil = no children.
|
||||
let foldScope: NSRange?
|
||||
let hiddenLineCount: Int
|
||||
let indent: Int
|
||||
}
|
||||
|
||||
/// One scan into lines, fence-aware via the presenter's classifier
|
||||
/// (list lines inside a fence are never .listMarker).
|
||||
static func lines(in text: String) -> [Line] {
|
||||
let buffer = text as NSString
|
||||
var out: [Line] = []
|
||||
var loc = 0
|
||||
let total = buffer.length
|
||||
var inFence = false
|
||||
while loc < total {
|
||||
let full = buffer.lineRange(for: NSRange(location: loc, length: 0))
|
||||
if full.length == 0 {
|
||||
break
|
||||
}
|
||||
var len = full.length
|
||||
while len > 0 {
|
||||
let unit = buffer.character(at: full.location + len - 1)
|
||||
if unit == 0x0A || unit == 0x0D {
|
||||
len -= 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
let content = NSRange(location: full.location, length: len)
|
||||
let lineText = len > 0 ? buffer.substring(with: content) : ""
|
||||
let kind = ProsePresenter.classify(lineText, inFence: inFence)
|
||||
if kind == .fence {
|
||||
inFence.toggle()
|
||||
}
|
||||
out.append(Line(
|
||||
range: full,
|
||||
content: content,
|
||||
text: lineText,
|
||||
indent: leadingColumns(lineText),
|
||||
isList: kind == .listMarker,
|
||||
isBlank: kind == .blank,
|
||||
))
|
||||
loc = full.location + full.length
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
static func item(at caret: Int, in text: String) -> Item? {
|
||||
let buffer = text as NSString
|
||||
guard buffer.length > 0 else { return nil }
|
||||
let scanned = lines(in: text)
|
||||
let caretLoc = min(max(0, caret), buffer.length - 1)
|
||||
guard let idx = scanned.firstIndex(where: { NSLocationInRange(caretLoc, $0.range) }) else { return nil }
|
||||
guard scanned[idx].isList else { return nil }
|
||||
let indent = scanned[idx].indent
|
||||
let bounds = blockBounds(scanned, from: idx, indent: indent)
|
||||
let blockEnd = scanned[bounds.end].end
|
||||
let block = NSRange(location: scanned[idx].range.location, length: blockEnd - scanned[idx].range.location)
|
||||
let scope: NSRange?
|
||||
var hidden = 0
|
||||
if let foldStart = bounds.foldStart, let scopeStartIdx = bounds.scopeStartIdx {
|
||||
scope = NSRange(location: foldStart, length: blockEnd - foldStart)
|
||||
hidden = bounds.end - scopeStartIdx + 1
|
||||
} else {
|
||||
scope = nil
|
||||
}
|
||||
return Item(
|
||||
markerLine: scanned[idx].range,
|
||||
markerEnd: scanned[idx].content.location + scanned[idx].content.length,
|
||||
contentOffset: contentOffset(of: scanned[idx]),
|
||||
block: block,
|
||||
foldScope: scope,
|
||||
hiddenLineCount: hidden,
|
||||
indent: indent,
|
||||
)
|
||||
}
|
||||
|
||||
/// Every list line that has children (the fold chevron targets).
|
||||
struct ParentHint: Equatable {
|
||||
let markerLine: NSRange
|
||||
let markerEnd: Int
|
||||
let contentOffset: Int
|
||||
let foldScope: NSRange
|
||||
let hiddenLineCount: Int
|
||||
}
|
||||
|
||||
static func parents(in text: String) -> [ParentHint] {
|
||||
let scanned = lines(in: text)
|
||||
var out: [ParentHint] = []
|
||||
for (idx, line) in scanned.enumerated() where line.isList {
|
||||
let bounds = blockBounds(scanned, from: idx, indent: line.indent)
|
||||
guard let foldStart = bounds.foldStart, let scopeStartIdx = bounds.scopeStartIdx else { continue }
|
||||
let blockEnd = scanned[bounds.end].end
|
||||
out.append(ParentHint(
|
||||
markerLine: line.range,
|
||||
markerEnd: line.content.location + line.content.length,
|
||||
contentOffset: contentOffset(of: line),
|
||||
foldScope: NSRange(location: foldStart, length: blockEnd - foldStart),
|
||||
hiddenLineCount: bounds.end - scopeStartIdx + 1,
|
||||
))
|
||||
}
|
||||
return out
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated extension ProseList {
|
||||
// MARK: Edits (one range replacement each — one undo step)
|
||||
|
||||
struct Edit: Equatable {
|
||||
let range: NSRange
|
||||
let replacement: String
|
||||
let caret: Int
|
||||
}
|
||||
|
||||
/// Tab: nest under the previous sibling — delta = its content column
|
||||
/// minus our indent. No previous sibling → nil (boundary no-op).
|
||||
static func indent(_ item: Item, caret: Int, in text: String) -> Edit? {
|
||||
let scanned = lines(in: text)
|
||||
guard let idx = lineIndex(of: item.markerLine.location, in: scanned) else { return nil }
|
||||
guard let sibIdx = adjacentSiblingLine(scanned, from: idx, through: idx, indent: item.indent, direction: -1) else { return nil }
|
||||
let delta = contentColumn(scanned[sibIdx].text) - item.indent
|
||||
guard delta > 0 else { return nil }
|
||||
let body = blockBody(text, item.block)
|
||||
let terminated = body.terminated
|
||||
let shifted = body.lines.map { $0.isEmpty ? $0 : String(repeating: " ", count: delta) + $0 }.joined(separator: "\n")
|
||||
+ (terminated ? "\n" : "")
|
||||
return Edit(range: item.block, replacement: shifted, caret: caret + delta)
|
||||
}
|
||||
|
||||
/// ⇧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).
|
||||
static func outdent(_ item: Item, caret: Int, in text: String) -> Edit? {
|
||||
guard item.indent > 0 else { return nil }
|
||||
let stripWidth = min(2, item.indent)
|
||||
let body = blockBody(text, item.block)
|
||||
var outLines: [String] = []
|
||||
var lineStart = item.block.location // utf16 start of this line in the OLD text
|
||||
var caretShift = 0
|
||||
var found = false
|
||||
for line in body.lines {
|
||||
let (removed, rest) = stripLeading(line, columns: stripWidth)
|
||||
let into = caret - lineStart
|
||||
if !found, into >= 0, into <= line.utf16.count {
|
||||
caretShift = -min(removed.utf16.count, max(0, into))
|
||||
found = true
|
||||
}
|
||||
outLines.append(rest)
|
||||
lineStart += line.utf16.count + 1 // +1 for the joined \n
|
||||
}
|
||||
let replacement = outLines.joined(separator: "\n") + (body.terminated ? "\n" : "")
|
||||
let newCaret = max(item.block.location, caret + caretShift)
|
||||
return Edit(range: item.block, replacement: replacement, caret: newCaret)
|
||||
}
|
||||
|
||||
/// ⌥↑/⌥↓: swap the item's block with the adjacent sibling's BLOCK
|
||||
/// (children and continuations ride WITH their own item — a marker-line
|
||||
/// swap would steal the sibling's subtree, #115 audit); the text between
|
||||
/// rides unchanged. Boundary or paragraph-interrupted → nil.
|
||||
static func move(_ item: Item, caret: Int, direction: Int, in text: String) -> Edit? {
|
||||
let scanned = lines(in: text)
|
||||
guard let idx = lineIndex(of: item.markerLine.location, in: scanned) else { return nil }
|
||||
let bounds = blockBounds(scanned, from: idx, indent: item.indent)
|
||||
guard
|
||||
let sibIdx = adjacentSiblingLine(scanned, from: idx, through: bounds.end, indent: item.indent, direction: direction)
|
||||
else { return nil }
|
||||
let sibStart = scanned[sibIdx].range.location
|
||||
let sibEnd = NSMaxRange(scanned[blockBounds(scanned, from: sibIdx, indent: item.indent).end].range)
|
||||
let sib = NSRange(location: sibStart, length: sibEnd - sibStart)
|
||||
let itemText = substring(text, item.block)
|
||||
let sibText = substring(text, sib)
|
||||
if direction > 0 {
|
||||
let range = NSRange(location: item.block.location, length: NSMaxRange(sib) - item.block.location)
|
||||
let between = substring(text, NSRange(location: NSMaxRange(item.block), length: sib.location - NSMaxRange(item.block)))
|
||||
let replacement = sibText + between + itemText
|
||||
// the item lands after the sibling + the between-text
|
||||
let newCaret = range.location + sibText.utf16.count + between.utf16.count + (caret - item.block.location)
|
||||
return Edit(range: range, replacement: replacement, caret: newCaret)
|
||||
} else {
|
||||
let range = NSRange(location: sib.location, length: NSMaxRange(item.block) - sib.location)
|
||||
let between = substring(text, NSRange(location: NSMaxRange(sib), length: item.block.location - NSMaxRange(sib)))
|
||||
let replacement = itemText + between + sibText
|
||||
let newCaret = sib.location + (caret - item.block.location)
|
||||
return Edit(range: range, replacement: replacement, caret: newCaret)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Block geometry
|
||||
|
||||
/// blockBounds result: last belonging line, fold-scope start (nil = no
|
||||
/// children), and the scope-start line's index.
|
||||
private struct BlockBounds {
|
||||
let end: Int
|
||||
let foldStart: Int?
|
||||
let scopeStartIdx: Int?
|
||||
}
|
||||
|
||||
/// Block walk from the marker line: lines belong while deeper (any
|
||||
/// kind) or a lazy continuation (prose, no blank between); blanks ride
|
||||
/// inside only when a belonging line follows.
|
||||
private static func blockBounds(_ scanned: [Line], from idx: Int, indent: Int) -> BlockBounds {
|
||||
var end = idx
|
||||
var pendingBlanks = 0
|
||||
var scanIndex = idx + 1
|
||||
while scanIndex < scanned.count {
|
||||
let candidate = scanned[scanIndex]
|
||||
if candidate.isBlank {
|
||||
pendingBlanks += 1
|
||||
scanIndex += 1
|
||||
continue
|
||||
}
|
||||
let deep = candidate.indent > indent
|
||||
// ponytail: lazy continuation treats ANY non-list line as item content —
|
||||
// CommonMark restricts it to paragraphs, so a heading/fence after an
|
||||
// item rides its block; exclude those kinds if fidelity bites.
|
||||
let lazy = !candidate.isList && pendingBlanks == 0
|
||||
if deep || lazy {
|
||||
end = scanIndex
|
||||
pendingBlanks = 0
|
||||
scanIndex += 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
var foldStart: Int?
|
||||
var scopeStartIdx: Int?
|
||||
var probeIndex = idx + 1
|
||||
while probeIndex <= end {
|
||||
if scanned[probeIndex].indent > indent {
|
||||
var source = probeIndex
|
||||
while source - 1 > idx, scanned[source - 1].isBlank {
|
||||
source -= 1
|
||||
} // blanks before the first child hide too
|
||||
foldStart = scanned[source].range.location
|
||||
scopeStartIdx = source
|
||||
break
|
||||
}
|
||||
probeIndex += 1
|
||||
}
|
||||
return BlockBounds(end: end, foldStart: foldStart, scopeStartIdx: scopeStartIdx)
|
||||
}
|
||||
|
||||
// MARK: Sibling searches
|
||||
|
||||
/// Adjacent sibling LINE INDEX at the same indent (direction -1 = previous,
|
||||
/// +1 = next), or nil at any boundary. Backward: skip blanks, deeper
|
||||
/// list lines (the sibling's subtree), and lazy prose; a standalone
|
||||
/// paragraph or a shallower list line is a boundary. Forward: prose
|
||||
/// always ends the walk (adjacent prose would be inside the block).
|
||||
private static func adjacentSiblingLine(_ scanned: [Line], from idx: Int, through end: Int, indent: Int, direction: Int) -> Int? {
|
||||
if direction < 0 {
|
||||
var pendingBlanks = 0
|
||||
var probeIndex = idx - 1
|
||||
while probeIndex >= 0 {
|
||||
let candidate = scanned[probeIndex]
|
||||
if candidate.isBlank {
|
||||
pendingBlanks += 1; probeIndex -= 1; continue
|
||||
}
|
||||
if candidate.isList {
|
||||
if candidate.indent == indent {
|
||||
return probeIndex
|
||||
}
|
||||
if candidate.indent < indent {
|
||||
return nil
|
||||
}
|
||||
probeIndex -= 1 // deeper: subtree of the sibling, keep walking
|
||||
continue
|
||||
}
|
||||
if pendingBlanks > 0 || (probeIndex - 1 >= 0 && scanned[probeIndex - 1].isBlank) {
|
||||
return nil
|
||||
}
|
||||
probeIndex -= 1
|
||||
}
|
||||
return nil
|
||||
}
|
||||
var probeIndex = end + 1
|
||||
while probeIndex < scanned.count {
|
||||
let candidate = scanned[probeIndex]
|
||||
if candidate.isBlank {
|
||||
probeIndex += 1; continue
|
||||
}
|
||||
if candidate.isList, candidate.indent == indent {
|
||||
return probeIndex
|
||||
}
|
||||
return nil // prose, or a list at another indent: boundary
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MARK: Helpers
|
||||
|
||||
private static func lineIndex(of location: Int, in scanned: [Line]) -> Int? {
|
||||
scanned.firstIndex { $0.range.location == location }
|
||||
}
|
||||
|
||||
/// Leading whitespace columns (space = 1, tab = 2 — OutlineTree's rule).
|
||||
private static func leadingColumns(_ source: String) -> Int {
|
||||
var cols = 0
|
||||
for unit in source {
|
||||
if unit == " " {
|
||||
cols += 1
|
||||
} else if unit == "\t" {
|
||||
cols += 2
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return cols
|
||||
}
|
||||
|
||||
/// Content column of a list line: indent + marker + following whitespace.
|
||||
/// CommonMark's nesting anchor ("1. " → 3, "10. " → 4).
|
||||
private static func contentColumn(_ source: String) -> Int {
|
||||
var cols = 0
|
||||
var scanIndex = source.startIndex
|
||||
while scanIndex < source.endIndex, source[scanIndex] == " " || source[scanIndex] == "\t" {
|
||||
cols += source[scanIndex] == "\t" ? 2 : 1
|
||||
scanIndex = source.index(after: scanIndex)
|
||||
}
|
||||
while scanIndex < source.endIndex, source[scanIndex] != " ", source[scanIndex] != "\t" {
|
||||
cols += 1
|
||||
scanIndex = source.index(after: scanIndex)
|
||||
}
|
||||
while scanIndex < source.endIndex, source[scanIndex] == " " || source[scanIndex] == "\t" {
|
||||
cols += source[scanIndex] == "\t" ? 2 : 1
|
||||
scanIndex = source.index(after: scanIndex)
|
||||
}
|
||||
return cols
|
||||
}
|
||||
|
||||
/// UTF-16 offset of the first content character (after "\source*marker\source+").
|
||||
private static func contentOffset(of line: Line) -> Int {
|
||||
guard let match = line.text.firstMatch(of: ProsePresenter.listMarkerPattern) else { return line.range.location }
|
||||
let utf16 = match.range.utf16Range(in: line.text)
|
||||
return line.range.location + min(utf16.upperBound, line.content.length)
|
||||
}
|
||||
|
||||
private static func substring(_ text: String, _ range: NSRange) -> String {
|
||||
(text as NSString).substring(with: range)
|
||||
}
|
||||
|
||||
/// Block text split into lines; `terminated` = block ends with \n.
|
||||
private static func blockBody(_ text: String, _ block: NSRange) -> (lines: [String], terminated: Bool) {
|
||||
let raw = substring(text, block)
|
||||
let terminated = raw.hasSuffix("\n")
|
||||
let body = terminated ? String(raw.dropLast()) : raw
|
||||
let lines = body.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
|
||||
return (lines, terminated)
|
||||
}
|
||||
|
||||
/// Remove up to `columns` of leading whitespace (tab = 2, consumed
|
||||
/// whole). Returns (removed prefix, rest).
|
||||
private static func stripLeading(_ line: String, columns: Int) -> (removed: Substring, rest: String) {
|
||||
var removed = 0
|
||||
var scanIndex = line.startIndex
|
||||
while scanIndex < line.endIndex, removed < columns {
|
||||
let unit = line[scanIndex]
|
||||
if unit == " " {
|
||||
removed += 1
|
||||
} else if unit == "\t" {
|
||||
removed += 2
|
||||
} else {
|
||||
break
|
||||
}
|
||||
scanIndex = line.index(after: scanIndex)
|
||||
}
|
||||
return (line[..<scanIndex], String(line[scanIndex...]))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//
|
||||
// ProseListTextView.swift
|
||||
// Museion
|
||||
//
|
||||
// #115 (S5): the prose editor's list machinery — an NSTextView subclass
|
||||
// ProseTextView installs in place of the plain stock view. Tab/⇧Tab
|
||||
// indent/outdent the list item under the caret, ⌥↑/⌥↓ move it among
|
||||
// siblings (ProseList does the math; every edit is ONE undoable range
|
||||
// replacement through the plain mode-B store — ADR-0010 stands, no
|
||||
// secondary model). Lists get visual collapse: fold state is VIEW state
|
||||
// keyed by the marker line's buffer position (re-derived on edit —
|
||||
// simplest honest rule: nearest parent line with the same marker text),
|
||||
// hidden scopes are styled to near-zero height (ProseTypography.folded
|
||||
// Attributes), a chevron in the left gutter toggles by click, and a
|
||||
// folded parent shows "⋯ N" after its line. Folding never dirties the
|
||||
// document (ADR-0013's posture, carried to prose).
|
||||
//
|
||||
// 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
|
||||
// via insertBacktab instead of keyDown — both paths are covered (the
|
||||
// outliner's RowTextView proved the set behind NSHostingView).
|
||||
//
|
||||
|
||||
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).
|
||||
final class ProseChromeView: NSView {
|
||||
weak var owner: ProseListTextView?
|
||||
|
||||
override func hitTest(_: NSPoint) -> 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() {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
override func setFrameSize(_ newSize: NSSize) {
|
||||
super.setFrameSize(newSize)
|
||||
if newSize != .zero {
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
let key: Int
|
||||
let lineText: String
|
||||
}
|
||||
|
||||
var folds: [Fold] = []
|
||||
|
||||
// MARK: Structural keys
|
||||
|
||||
override func keyDown(with event: NSEvent) {
|
||||
let key = event.charactersIgnoringModifiers ?? ""
|
||||
let modifiers = event.modifierFlags
|
||||
.intersection(.deviceIndependentFlagsMask)
|
||||
.subtracting([.function, .numericPad])
|
||||
let upKey = "\u{F700}" // NSUpArrowFunctionKey
|
||||
let downKey = "\u{F701}" // NSDownArrowFunctionKey
|
||||
|
||||
if key == upKey || key == downKey {
|
||||
if modifiers == .option, let item = currentItem() {
|
||||
performMove(item, direction: key == downKey ? 1 : -1)
|
||||
return
|
||||
}
|
||||
super.keyDown(with: event)
|
||||
return
|
||||
}
|
||||
if key == "\t" || key == "\u{19}" { // NSBackTabCharacter
|
||||
if let item = currentItem() {
|
||||
if key == "\u{19}" || modifiers.contains(.shift) {
|
||||
performOutdent(item)
|
||||
} else {
|
||||
performIndent(item)
|
||||
}
|
||||
return
|
||||
}
|
||||
super.keyDown(with: event)
|
||||
return
|
||||
}
|
||||
super.keyDown(with: event)
|
||||
}
|
||||
|
||||
/// Some AppKit paths deliver ⇧⇥ here instead of keyDown.
|
||||
override func insertBacktab(_: Any?) {
|
||||
if let item = currentItem() {
|
||||
performOutdent(item)
|
||||
} else {
|
||||
super.insertBacktab(nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func currentItem() -> ProseList.Item? {
|
||||
guard (string as NSString).length > 0 else { return nil }
|
||||
return ProseList.item(at: selectedRange().location, in: string)
|
||||
}
|
||||
|
||||
// MARK: Edit application (one undo step each)
|
||||
|
||||
private func performIndent(_ item: ProseList.Item) {
|
||||
guard let edit = ProseList.indent(item, caret: selectedRange().location, in: string) else { return }
|
||||
apply(edit)
|
||||
}
|
||||
|
||||
private func performOutdent(_ item: ProseList.Item) {
|
||||
guard let edit = ProseList.outdent(item, caret: selectedRange().location, in: string) else { return }
|
||||
apply(edit)
|
||||
}
|
||||
|
||||
private func performMove(_ item: ProseList.Item, direction: Int) {
|
||||
guard let edit = ProseList.move(item, caret: selectedRange().location, direction: direction, in: string) else { return }
|
||||
apply(edit)
|
||||
}
|
||||
|
||||
/// One range replacement through the text stack: shouldChangeText
|
||||
/// registers undo, didChangeText drives the delegate (paragraph
|
||||
/// reattribute + session edit). Multi-line replacements span more than
|
||||
/// the caret's paragraph, so a full presentation pass follows — unless
|
||||
/// 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 }
|
||||
textStorage?.replaceCharacters(in: edit.range, with: edit.replacement)
|
||||
didChangeText()
|
||||
let length = (string as NSString).length
|
||||
setSelectedRange(NSRange(location: min(max(0, edit.caret), length), length: 0))
|
||||
guard folds.isEmpty else { return } // textDidChange refreshed everything
|
||||
let sel = selectedRange()
|
||||
textStorage?.setAttributedString(ProsePresenter.attribute(string))
|
||||
setSelectedRange(sel)
|
||||
}
|
||||
|
||||
// MARK: Fold maintenance
|
||||
|
||||
/// One maintenance entry point for every refresh path — the coordinator's
|
||||
/// 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.
|
||||
func refreshFolds() {
|
||||
guard !folds.isEmpty else {
|
||||
chrome.refresh()
|
||||
return
|
||||
}
|
||||
refreshFoldRendering()
|
||||
}
|
||||
|
||||
func toggleFold(_ parent: ProseList.ParentHint) {
|
||||
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)))
|
||||
}
|
||||
refreshFoldRendering()
|
||||
}
|
||||
|
||||
/// Re-key folds against the current text (nearest parent line with the
|
||||
/// same marker text; no match → the fold dies), restyle the document,
|
||||
/// re-hide every live scope, and park a caret that landed inside a
|
||||
/// hidden scope at its parent's marker end.
|
||||
func refreshFoldRendering() {
|
||||
let parents = ProseList.parents(in: string)
|
||||
// ponytail: nearest-same-marker re-key can move a fold across duplicate
|
||||
// marker texts — track the edit delta in shouldChangeText if that bites.
|
||||
var seenKeys = Set<Int>()
|
||||
folds = folds.compactMap { fold in
|
||||
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) }
|
||||
}.filter { seenKeys.insert($0.key).inserted } // two folds can't land on one parent
|
||||
let sel = selectedRange()
|
||||
textStorage?.setAttributedString(ProsePresenter.attribute(string))
|
||||
for fold in folds {
|
||||
guard let parent = parents.first(where: { $0.markerLine.location == fold.key }) else { continue }
|
||||
textStorage?.setAttributes(ProseTypography.foldedAttributes, range: parent.foldScope)
|
||||
if NSLocationInRange(sel.location, parent.foldScope) {
|
||||
setSelectedRange(NSRange(location: min(parent.markerEnd, (string as NSString).length), length: 0))
|
||||
}
|
||||
}
|
||||
chrome.refresh()
|
||||
}
|
||||
|
||||
/// The marker line's text without its terminator.
|
||||
private func lineText(of line: NSRange) -> String {
|
||||
let buffer = string as NSString
|
||||
guard line.length > 0 else { return "" }
|
||||
var len = line.length
|
||||
while len > 0 {
|
||||
let terminator = buffer.character(at: line.location + len - 1)
|
||||
if terminator == 0x0A || terminator == 0x0D {
|
||||
len -= 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return len > 0 ? buffer.substring(with: NSRange(location: line.location, length: len)) : ""
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
|
||||
// MARK: Geometry (TextKit2)
|
||||
|
||||
/// View-space rect of the character at `offset` via the selection system
|
||||
/// — `selectionRects(for:)` is TextKit-version-agnostic NSTextView API and
|
||||
/// geometry the caret already renders from (#115 field finding: every
|
||||
/// NSTextLayoutManager fragment query — bridge, lookup, enumeration —
|
||||
/// yields nothing under SwiftUI-hosted viewport layout).
|
||||
private func lineRect(ofOffset offset: Int) -> NSRect? {
|
||||
let length = (string as NSString).length
|
||||
guard length > 0 else { return nil }
|
||||
let clamped = min(max(0, offset), length - 1)
|
||||
var actual = NSRange()
|
||||
// NSTextInputClient returns SCREEN coordinates (IME positioning);
|
||||
// screen → window → view before using it as geometry.
|
||||
let screenRect = firstRect(forCharacterRange: NSRange(location: clamped, length: 1), actualRange: &actual)
|
||||
guard screenRect != .zero else { return nil }
|
||||
let windowRect = window?.convertFromScreen(screenRect) ?? screenRect
|
||||
return convert(windowRect, from: nil)
|
||||
}
|
||||
}
|
||||
@@ -405,7 +405,9 @@ nonisolated enum ProsePresenter {
|
||||
// MARK: Pattern helpers
|
||||
|
||||
// Marker patterns (regex literals, like the inline ones below).
|
||||
private nonisolated(unsafe) static let listMarkerPattern = /^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)/
|
||||
// listMarkerPattern is internal — ProseList's marker math must agree
|
||||
// with classify()'s list detection (#115).
|
||||
nonisolated(unsafe) static let listMarkerPattern = /^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)/
|
||||
private nonisolated(unsafe) static let quoteMarkerPattern = /^(?:\s*>(?:\s|$))*/
|
||||
|
||||
/// UTF-16 NSRange of the marker in `lineText`, or nil.
|
||||
|
||||
@@ -129,4 +129,20 @@ nonisolated enum ProseTypography {
|
||||
.foregroundColor: syntaxColor,
|
||||
]
|
||||
}
|
||||
|
||||
/// #115: fold-hidden lines. The buffer keeps every byte (mode B — folding
|
||||
/// is rendering, never a text edit); hidden scopes style to near-zero
|
||||
/// height so the lines vanish (spike-verified: 14pt line → ~0). The text
|
||||
/// stays selectable/undoable underneath, and reading mode renders it.
|
||||
nonisolated(unsafe) static let foldedAttributes: [NSAttributedString.Key: Any] = {
|
||||
let style = NSMutableParagraphStyle()
|
||||
style.lineHeightMultiple = 0.01
|
||||
style.paragraphSpacing = 0
|
||||
style.paragraphSpacingBefore = 0
|
||||
return [
|
||||
.font: NSFont.systemFont(ofSize: 0.1),
|
||||
.foregroundColor: NSColor.clear,
|
||||
.paragraphStyle: style,
|
||||
]
|
||||
}()
|
||||
}
|
||||
Reference in new issue
Block a user