Files
museion/Museion/OutlineEditorView.swift
T
AlexKucera d7fd11cf0d
CI / ci (push) Canceled after 0s
chore(lint): repo-wide green becomes the contract
Close the lint arc #194-#197: deliberate-style rule disables with
rationales (#194), filter-safe test renames + --test-case-name-format
preserve (#195), every surviving warning fixed through the sanctioned
lint-stable shapes (#196), and the docs now state the true contract
(#197): bare swiftlint . reports zero violations and swiftformat .
reformats nothing, while push gates stay scoped to the push's own
files (settled #190 design) — the pre-push hook's stale 'pre-existing
violations' rationale blocks refreshed, gate logic untouched.

Also in the sweep: quiesce the FSEvent-burst watcher race in
LibrarySearchTests (two rescans double-count one shared PostScanCache
miss; benign revision over-bump), pin the learnings scan's symlink-skip
contract (flip-verified — defended in depth by the lstat guard AND
contentsOfDirectory's own symlink refusal), reorder that scan's guard
so cheap rejections precede the directory listing, and park the roster
chmod window with a ceiling comment.

Finish-audit: 3 reviewers, 0 blocking; the one code finding was
disproved by probe (&& out-binds ?? — the guard was correct). Suite
693/693 via scripts/full-test.sh; swiftlint 0 violations; swiftformat
0/141; hook rig 23/23.

Closes #197
2026-11-17 16:29:46 +01:00

963 lines
36 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// OutlineEditorView.swift
// Museion
//
// #109 (ADR-0013, #105 verdict — variant B): the outliner editing surface.
// Chrome bullets + per-depth vertical rails; ONE promoted NSTextView on
// the focused row (native undo/IME), static inline-markdown text
// elsewhere. Tab/⇧Tab/⌥↑/⌥↓/Enter reshape whole subtrees through
// OutlineTree; ↑/↓ hop visible blocks; folds are pure view state keyed by
// node id — toggling them never serializes. Every text/structure edit
// re-serializes into the existing EditorSession debounce/⌘S/conflict
// machinery (`session.edit`) or the draft callbacks — the save path is
// untouched. Reading mode keeps rendering the serialized markdown via the
// apex surface (nested lists render natively there).
//
// #112 (S6, wf113 verdict — variant A "fat gaps"): drag-reorder + zoom.
// Drag: a ⋮⋮ grip in the left margin drags (batch when the row is in the
// block selection, solo when not; a selected row's body drags too);
// seams between rows insert at the following row's depth (the indicator
// line's left edge = the future bullet column), a row's middle band
// nests as its last child (ring); invalid targets (own subtree) show a
// dashed indicator and no-op; after a drop the moved run IS the
// selection. Zoom: double-click a bullet roots the projection at that
// node (depths re-based), breadcrumb/Esc climb back out. The plumbing
// lives in OutlineDrag.swift; the drop math in OutlinePresenter.
//
import AppKit
import SwiftUI
// MARK: - Pure projection (tested)
/// The outliner's view-facing projection over `[OutlineNode]`: which rows
/// are visible given the fold set, plus the chrome data each row renders
/// from. Pure tree math — no UI.
nonisolated enum OutlinePresenter {
nonisolated struct Row: Equatable, Identifiable {
let id: UUID
var depth: Int
var text: String
/// 0 = leaf bullet (never foldable). Structure fact, not view state.
var childCount: Int
var isFolded: Bool
/// Total nodes hidden under this row's fold ("⋯ N"); 0 unless folded.
var foldedDescendantCount: Int
}
/// Preorder walk emitting one Row per visible node — a folded node's
/// whole subtree is skipped and counted. #112 zoom: a resolvable
/// `zoomRootID` roots the projection at that node's CHILDREN (the node
/// itself becomes the breadcrumb), depths re-based to 0, and the zoom
/// root's own fold is ignored while it is the root. An unknown id
/// falls back to the whole document.
static func visibleRows(
_ nodes: [OutlineNode], folded: Set<UUID>, zoomRootID: UUID? = nil,
) -> [Row] {
var rows: [Row] = []
if let zoomRootID, let rootPath = path(of: zoomRootID, in: nodes), let root = node(at: rootPath, in: nodes) {
walk(root.children, parent: rootPath, depth: 0, folded: folded, into: &rows)
} else {
walk(nodes, parent: [], depth: 0, folded: folded, into: &rows)
}
return rows
}
private static func walk(
_ nodes: [OutlineNode], parent: [Int], depth: Int, folded: Set<UUID>, into rows: inout [Row],
) {
for (index, node) in nodes.enumerated() {
let path = parent + [index]
let isFolded = folded.contains(node.id)
rows.append(
Row(
id: node.id,
depth: depth,
text: node.text,
childCount: node.children.count,
isFolded: isFolded,
foldedDescendantCount: isFolded ? countTree(node.children) : 0,
),
)
if !isFolded {
walk(node.children, parent: path, depth: depth + 1, folded: folded, into: &rows)
}
}
}
private static func countTree(_ nodes: [OutlineNode]) -> Int {
nodes.reduce(0) { $0 + 1 + countTree($1.children) }
}
/// Top padding per visible row id — the branch rhythm
/// (`ProseTypography.outlineBranchSpacing`) before a row that opens a
/// top-level parent group (#ui-r5 argon#14) or FOLLOWS A DEEPER row:
/// a nested block just closed, and its transition back to the parent
/// level reads the SAME gap whatever follows — parent or leaf, any
/// depth (#ui-r8 argon#7: the gap after one nested sublist read ~38px,
/// after another ~28px, because only a parent follower carried the
/// padding). Pure over the projection; zoom's re-based depths included.
static func spacingBefore(rows: [Row]) -> [UUID: CGFloat] {
var out: [UUID: CGFloat] = [:]
for (index, row) in rows.enumerated() {
let opensBranch = row.depth == 0 && row.childCount > 0
let closesNested = index > 0 && rows[index - 1].depth > row.depth
if opensBranch || closesNested {
out[row.id] = ProseTypography.outlineBranchSpacing
}
}
return out
}
/// The visible-row ids from `from` to `to`, inclusive, in visible
/// order; nil when either id isn't visible. Block-selection range
/// math (⇧↑/⇧↓ anchor↔focus). #112: zoom-aware — ids outside the
/// zoomed projection are invisible.
static func rangeIDs(
from: UUID, to: UUID, in nodes: [OutlineNode], folded: Set<UUID>, zoomRootID: UUID? = nil,
) -> [UUID]? {
let rows = visibleRows(nodes, folded: folded, zoomRootID: zoomRootID)
guard let startIdx = rows.firstIndex(where: { $0.id == from }),
let endIdx = rows.firstIndex(where: { $0.id == to })
else { return nil }
return rows[min(startIdx, endIdx) ... max(startIdx, endIdx)].map(\.id)
}
/// Structural ops that make sense on a block-selection run.
enum BatchOp {
case indent
case outdent
case moveUp
case moveDown
}
/// Batch-apply a structural op to a run of visible-row ids (block
/// selection), re-resolving each path by id after every move. Moves
/// are SIBLING-ONLY here: a batch move never crosses a parent —
/// if the run's leader is at a sibling boundary the whole batch
/// no-ops (a run that crosses parents tears itself apart). Indent
/// and outdent apply per node.
/// ponytail: a mixed-level run can half-apply (leader moves, later
/// member at boundary); two-pass dry-run is the upgrade if that
/// ever bites. Returns whether anything changed.
@discardableResult
static func applyBatch(_ op: BatchOp, ids: [UUID], to nodes: inout [OutlineNode]) -> Bool {
let ordered = (op == .moveDown || op == .outdent) ? ids.reversed() : ids
var didChange = false
for id in ordered {
guard let path = path(of: id, in: nodes) else { continue }
let moved: Bool = switch op {
case .indent: OutlineTree.indent(&nodes, path: path) != nil
case .outdent: OutlineTree.outdent(&nodes, path: path) != nil
case .moveUp: OutlineTree.siblingMove(&nodes, path: path, up: true)
case .moveDown: OutlineTree.siblingMove(&nodes, path: path, up: false)
}
if !moved, op == .moveUp || op == .moveDown {
// Run moves as a unit; its leader is at a sibling
// boundary. The leader runs first — nothing moved yet.
return didChange
}
didChange = didChange || moved
}
return didChange
}
/// Find a node's path by identity. nil = not in the tree.
static func path(of id: UUID, in nodes: [OutlineNode]) -> [Int]? {
for (index, node) in nodes.enumerated() {
if node.id == id {
return [index]
}
if let deeper = path(of: id, in: node.children) {
return [index] + deeper
}
}
return nil
}
/// The node at a root→leaf index path — focus routing after structural
/// ops return the moved node's new path. nil = path doesn't resolve.
static func node(at path: [Int], in nodes: [OutlineNode]) -> OutlineNode? {
guard let first = path.first, nodes.indices.contains(first) else { return nil }
let current = nodes[first]
return path.count == 1 ? current : node(at: Array(path.dropFirst()), in: current.children)
}
/// Replace one node's text by identity. False = id not in the tree.
/// Single-line contract enforced HERE: pasted newlines become spaces
/// (splitting into siblings needs anchor/caret math in the view;
/// the space-join is the safe floor that can't lose content).
@discardableResult
static func setText(_ text: String, id: UUID, in nodes: inout [OutlineNode]) -> Bool {
let sanitized = text.replacingOccurrences(of: "\r\n", with: " ")
.replacingOccurrences(of: "\n", with: " ")
.replacingOccurrences(of: "\r", with: " ")
for index in nodes.indices {
if nodes[index].id == id {
nodes[index].text = sanitized
return true
}
if setText(sanitized, id: id, in: &nodes[index].children) {
return true
}
}
return false
}
}
// MARK: - The surface
/// #ui-r4 (mercury#28): nesting geometry — 30px per level (r3's 18px
/// read flat; judges asked 28–32). #ui-r5 (argon#1): guide rails sit on
/// the PARENT bullet's center column, the drop seam on the child bullet
/// column. DropGeometry (OutlineDrag.swift) still owns the 20pt grip
/// margin; its 18-based rail constants are no longer read by this chrome.
private enum NestGeometry {
static let unit: CGFloat = 30
/// The bullet cell's width (bullet() frames its glyph 22×27).
static let bulletCell: CGFloat = 22
/// A depth-d row's TEXT column, from the row's leading edge.
static func textColumn(depth: Int) -> CGFloat {
DropGeometry.gripWidth + CGFloat(depth) * unit + bulletCell
}
/// The bullet CENTER column — the drop seam's left edge.
static func bulletColumn(depth: Int) -> CGFloat {
textColumn(depth: depth) - DropGeometry.bulletCenter
}
}
/// The outline editing surface (#109): rows of chrome (guide rails,
/// bullets, fold counts) around one live caret row. Session mode re-parses
/// on `loadGeneration` bumps (open / Yes-reload); draft mode seeds from
/// `draftText` once and streams edits out through `onDraftEdit`.
struct OutlineEditorView: View {
var session: EditorSession?
var onDraftEdit: ((String) -> Void)?
/// Draft mode: the text at mount. Later values are ignored — after the
/// seed the view's tree owns the document until the next mount.
var draftText: String?
@State private var preamble: [String] = []
@State private var nodes: [OutlineNode] = []
/// View state, keyed by node id; reset on every load (session-scoped).
@State private var folded: Set<UUID> = []
@State private var focusedID: UUID?
/// Block-selection anchor (⇧↑/⇧↓). nil = no range selected; the range
/// runs anchor↔focusedID over visible rows. View state, like folds.
@State private var selectionAnchor: UUID?
/// Caret (grapheme offset) the NEXT mounted row editor lands on;
/// nil = end. Read at mount only — the live view owns the caret after.
@State private var pendingCaret: Int?
@State private var loadedGeneration = -1
/// #112 zoom: nested zoom roots, last = current. View state only —
/// never serializes; reset on every load.
@State private var zoomStack: [UUID] = []
/// #112 drag: the live session (moving run + hit target). nil = idle.
@State private var drag: DragInfo?
/// #112 drag: hover-revealed grip row.
@State private var hoverID: UUID?
/// Esc delivery: SwiftUI's hosting layer swallows Esc before the row
/// textview's keyDown AND before .onExitCommand (probe-pinned —
/// EscEventProbeTests). A local monitor sees the event first.
@State private var escMonitor: Any?
var body: some View {
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
let rowSpacing = OutlinePresenter.spacingBefore(rows: rows)
VStack(alignment: .leading, spacing: 0) {
if !zoomStack.isEmpty {
breadcrumb
.padding(.horizontal, 20)
.padding(.top, 12)
.padding(.bottom, 4)
}
Group {
if rows.isEmpty {
VStack(spacing: 10) {
Image(systemName: "list.bullet")
.font(.largeTitle)
.foregroundStyle(DesignTokens.muted)
Text("An empty outline — every line is a node.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 0) {
outlineTitleHeader
ForEach(rows) { row in
rowView(row)
// #ui-r5 (argon#14) + #ui-r8 (argon#7): the
// branch rhythm — a top-level parent group
// separates from siblings, and every nested
// block's close reads the SAME gap whatever
// follows (parent or leaf, any depth).
.padding(.top, rowSpacing[row.id] ?? 0)
}
}
.padding(.top, 24)
.padding(.bottom, 80)
}
}
}
}
.onAppear {
loadIfNeeded()
installEscMonitor()
}
.onChange(of: session?.loadGeneration) { _, _ in loadIfNeeded() }
.onDisappear { removeEscMonitor() }
}
/// Local monitor: the ONLY reliable Esc path into this surface
/// (probe: sendEvent → hosted keyDown never fires for Esc). Fires
/// only while the outliner's own row textview is first responder,
/// swallows the event only when there's a selection to collapse or a
/// zoom level to climb out of. (#112: a live drag owns Esc itself —
/// its own monitor is installed later, so it runs first.)
private func installEscMonitor() {
guard escMonitor == nil else { return }
escMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
guard event.keyCode == 53, // Esc
(NSApp.keyWindow?.firstResponder as? RowTextView) != nil
else { return event }
if handleEscape() {
return nil // swallowed — selection or zoom was the target
}
return event
}
}
private func removeEscMonitor() {
if let escMonitor {
NSEvent.removeMonitor(escMonitor)
}
escMonitor = nil
}
/// (Re)parse from the source of truth. Session: only when the load
/// generation moved (open, Yes-reload) — never per keystroke, the view
/// owns the live tree. Draft: seed once at mount. Every load resets
/// folds — fresh open = all unfolded, never dirties the document.
private func loadIfNeeded() {
if let session {
guard session.loadGeneration != loadedGeneration else { return }
loadedGeneration = session.loadGeneration
let parsed = OutlineTree.parse(session.text)
preamble = parsed.preamble
nodes = parsed.nodes
} else {
guard loadedGeneration < 0 else { return }
loadedGeneration = 0
let parsed = OutlineTree.parse(draftText ?? "")
preamble = parsed.preamble
nodes = parsed.nodes
}
folded = []
focusedID = nodes.first?.id
selectionAnchor = nil
pendingCaret = nil
zoomStack = [] // fresh open = whole document, never dirties it
}
// MARK: Rows
/// #112: the drag grip owns the 20pt left margin — hover-revealed ⋮⋮
/// glyph over the transparent catcher (OutlineDrag.swift). It fills
/// the row's height so its frame reads as row geometry for the
/// drag-time view-tree walk.
private func gripCell(_ row: OutlinePresenter.Row) -> some View {
ZStack {
Text("⋮⋮")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.opacity(hoverID == row.id ? 0.85 : 0)
dragCatcher(kind: .grip, row: row)
}
.frame(width: DropGeometry.gripWidth)
.frame(maxHeight: .infinity)
}
private func rowView(_ row: OutlinePresenter.Row) -> some View {
HStack(alignment: .top, spacing: 0) {
gripCell(row)
// #ui-r4 (mercury#28): the per-level indent is a plain spacer —
// the guide rails moved to the row background (rails(depth:)),
// where a stroke can sit on the CHILD text column, right of the
// child bullet; the old in-stack canvas could never reach past
// the indent region.
Color.clear
.frame(width: CGFloat(row.depth) * NestGeometry.unit)
bullet(row)
if row.id == focusedID {
OutlineRowTextView(
text: row.text,
caret: pendingCaret,
onEdit: { newText in
selectionAnchor = nil // typing replaces block selection
OutlinePresenter.setText(newText, id: row.id, in: &nodes)
pushToDocument()
},
onStructure: { op in apply(op) },
)
.padding(.vertical, 3) // same inset as staticText — no focus jump
.frame(maxWidth: .infinity, alignment: .leading)
.fixedSize(horizontal: false, vertical: true)
} else {
staticText(row)
// #112: click focuses, ⇧click extends, drag runs when
// the row is inside the block selection.
.overlay {
dragCatcher(kind: .body, row: row)
}
}
if row.isFolded, row.foldedDescendantCount > 0 {
Text("⋯ \(row.foldedDescendantCount)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
.padding(.leading, 6)
.padding(.top, 5)
}
}
.padding(.trailing, 20)
// #ui-r4 (mercury#28): guide rails behind the selection wash.
.background { rails(depth: row.depth) }
// Block-selection highlight (⇧↑/⇧↓ / ⇧click range, anchor↔focus).
.background(rowSelected(row) ? DesignTokens.accent.opacity(0.08) : Color.clear)
// #112: the moving run lifts (prototype .lifted) while a drag runs.
.opacity(drag?.moving.contains(row.id) == true ? 0.3 : 1)
.overlay {
dropIndicator(row)
}
.onHover { hovering in
if hovering {
hoverID = row.id
} else if hoverID == row.id {
hoverID = nil
}
}
}
/// #112 drag indicator chrome (wf113 verdict): a 2px seam line whose
/// left edge sits at the future bullet column, or a 2px ring around
/// an onto target; dashed + muted when the target is invalid.
@ViewBuilder
private func dropIndicator(_ row: OutlinePresenter.Row) -> some View {
if let drag, let target = drag.target {
switch target {
case let .before(ref) where ref == row.id:
seamLine(depth: row.depth, valid: drag.valid)
.frame(maxHeight: .infinity, alignment: .top)
case let .afterLast(ref) where ref == row.id:
seamLine(depth: row.depth, valid: drag.valid)
.frame(maxHeight: .infinity, alignment: .bottom)
case let .lastChild(ref) where ref == row.id:
RoundedRectangle(cornerRadius: 4, style: .continuous)
.stroke(
drag.valid ? DesignTokens.accent : DesignTokens.muted,
style: drag.valid
? StrokeStyle(lineWidth: 2)
: StrokeStyle(lineWidth: 2, dash: [5, 3]),
)
.padding(1)
default:
EmptyView()
}
}
}
/// The seam line: left edge at the dropped block's future bullet
/// column (bulletCenter + d·30 + the 20pt margin), running to the
/// row's end. The spacer is height-pinned to 2 — a flexible one expands the
/// HStack to the row height and CENTERS the bar, drawing every seam
/// half a row off (the row's own frame alignment then has nothing
/// to align).
private func seamLine(depth: Int, valid: Bool) -> some View {
HStack(spacing: 0) {
Color.clear
.frame(width: NestGeometry.bulletColumn(depth: depth), height: 2)
Group {
if valid {
Rectangle().fill(DesignTokens.accent)
} else {
HLine()
.stroke(DesignTokens.muted, style: StrokeStyle(lineWidth: 2, dash: [5, 3]))
}
}
.frame(height: 2)
.frame(maxWidth: .infinity)
}
.padding(.vertical, -1)
.allowsHitTesting(false)
}
/// The bullet cell (22×27): marker by DEPTH (#ui-r2, sol#12/argon#20/
/// mercury#32) — every top-level row the SAME filled 10pt disc, every
/// nested level the single smaller 7pt dot. Parent-vs-leaf no longer
/// changes the glyph (the r1 ring-vs-dot pair still read as
/// inconsistent same-rank markers); hierarchy reads from indentation
/// + children presence. Ink one step darker (#ui-r2, sol#45):
/// foreground at 0.8, not muted — markers belong to their text.
/// The fold toggle stays on rows with children ("●" button, folded =
/// accent + "⋯ N" count); tapping a leaf focuses.
/// #112: double-click any bullet zooms in. The two clicks of the
/// double-click round-trip the fold toggle (fold→unfold), so the
/// zoomed-in projection opens with the node's fold state unchanged.
@ViewBuilder
private func bullet(_ row: OutlinePresenter.Row) -> some View {
let foldable = row.childCount > 0
let glyph = Text("●")
.font(.system(size: row.depth == 0 ? 10 : 7))
.foregroundStyle(row.isFolded ? DesignTokens.accent : DesignTokens.foreground.opacity(0.8))
Group {
if foldable {
Button {
toggleFold(row.id)
} label: {
glyph.frame(width: NestGeometry.bulletCell, height: 27)
}
.buttonStyle(.plain)
.help("fold/unfold (⌘↑ / ⌘↓) · double-click: zoom in")
.accessibilityLabel(row.isFolded ? "Unfold \(row.text)" : "Fold \(row.text)")
} else {
glyph
.frame(width: NestGeometry.bulletCell, height: 27)
.contentShape(Rectangle())
.onTapGesture { focus(row.id) }
.help("double-click: zoom in")
}
}
.contentShape(Rectangle())
.onTapGesture(count: 2) { zoomIn(to: row.id) }
}
/// Static row text: inert inline markdown; `[[wiki-links]]` stay
/// literal (the plain-Text fallback keeps them so either way).
/// Same NSFont as the live row (Valkyrie 17) — no face swap on focus.
/// Clicks land in the #112 body catcher overlay (click focuses,
/// ⇧click extends, drag when selected).
private func staticText(_ row: OutlinePresenter.Row) -> some View {
Group {
if row.text.isEmpty {
Text(" ")
.font(Font(ProseTypography.bodyFont))
.foregroundStyle(DesignTokens.border)
} else if let attributed = try? AttributedString(
markdown: row.text,
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace),
) {
Text(attributed)
.font(Font(ProseTypography.bodyFont))
.foregroundStyle(DesignTokens.foreground)
} else {
Text(row.text)
.font(Font(ProseTypography.bodyFont))
.foregroundStyle(DesignTokens.foreground)
}
}
.padding(.vertical, 3)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
// MARK: - Zoom + drag handlers (#112 — same-file extension: private
// view state stays file-scoped, the type body stays under swiftlint)
extension OutlineEditorView {
/// #112 zoom chrome: ⟵ full out, one crumb per zoom level — clicking
/// a crumb zooms to that node, the current level ("here") is inert.
/// Esc climbs out one level.
private var breadcrumb: some View {
HStack(spacing: 4) {
Button("⟵ zoom out") { zoomOutAll() }
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.accent)
Text("/")
.foregroundStyle(DesignTokens.muted)
Button("outline") { zoomOutAll() }
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
ForEach(zoomStack.indices, id: \.self) { level in
Text("/")
.foregroundStyle(DesignTokens.muted)
let isHere = level == zoomStack.count - 1
let crumb = crumbText(level)
if isHere {
Text(crumb)
.foregroundStyle(DesignTokens.accent)
.lineLimit(1)
} else {
Button(crumb) {
zoomStack = Array(zoomStack.prefix(level + 1))
reconcileAfterZoomChange()
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
.lineLimit(1)
}
}
}
.font(.system(size: 12, design: DesignTokens.mono))
.help("double-click a bullet zooms in · Esc zooms out one level")
}
/// The breadcrumb label for zoom level `level` — the zoom root's
/// text, clamped like the prototype's crumbs.
private func crumbText(_ level: Int) -> String {
guard let path = OutlinePresenter.path(of: zoomStack[level], in: nodes),
let node = OutlinePresenter.node(at: path, in: nodes) else { return "?" }
let text = node.text.isEmpty ? "(empty)" : node.text
return text.count > 26 ? String(text.prefix(25)) + "…" : text
}
/// ⇧click / ⇧↑ / ⇧↓ semantics shared by catcher and keys: first
/// extension anchors at the current focus, then the focus moves to
/// `id` — the anchor↔focus range IS the block selection.
private func extendSelection(to id: UUID) {
selectionAnchor = selectionAnchor ?? focusedID ?? id
guard id != focusedID || selectionAnchor != id else { return }
focusedID = id
pendingCaret = nil
}
private func zoomIn(to id: UUID) {
guard zoomStack.last != id else { return }
zoomStack.append(id)
reconcileAfterZoomChange()
}
private func zoomOutAll() {
guard !zoomStack.isEmpty else { return }
zoomStack = []
reconcileAfterZoomChange()
}
private func zoomOutOne() {
guard !zoomStack.isEmpty else { return }
zoomStack.removeLast()
reconcileAfterZoomChange()
}
/// After any zoom change: the selection survives only when the whole
/// anchor↔focus range stays visible (wf113), the focus falls to the
/// projection's first row when it leaves it.
private func reconcileAfterZoomChange() {
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
let visible = Set(rows.map(\.id))
if let anchor = selectionAnchor {
let range = selectedRangeIDs(anchor: anchor, focus: focusedID ?? anchor) ?? []
if range.isEmpty || !range.allSatisfy({ visible.contains($0) }) {
selectionAnchor = nil
}
}
if let current = focusedID, !visible.contains(current) {
focusedID = rows.first?.id
pendingCaret = nil
}
}
/// Esc's ordered targets: collapse the block selection first, then
/// climb out of a zoom level. True = swallowed. (A live drag's own
/// monitor runs before this one and cancels itself.)
private func handleEscape() -> Bool {
if selectionAnchor != nil {
selectionAnchor = nil
return true
}
if !zoomStack.isEmpty {
zoomOutOne()
return true
}
return false
}
/// The catcher (grip or body) for one row, wired to this surface.
/// The catcher supplies live window-space row frames with every
/// pointer event — it reads them from the real AppKit view tree, so
/// they can never go stale mid-scroll.
private func dragCatcher(kind: OutlineDragCatcher.Kind, row: OutlinePresenter.Row) -> OutlineDragCatcher {
OutlineDragCatcher(
kind: kind,
rowID: row.id,
isInSelection: { rowSelected(row) },
payload: { draggedRun(grabbing: row.id) },
onClick: { focus(row.id) },
onShiftClick: { extendSelection(to: row.id) },
onDragBegan: { run in drag = DragInfo(moving: run, target: nil, valid: false) },
onDragMoved: { point, frames in dragMoved(to: point, frames: frames) },
onDragEnded: { point, frames in endDrag(at: point, frames: frames) },
)
}
/// The run a grab drags: the block selection when the grabbed row is
/// inside it (deduped — an ancestor carries its descendants), else
/// the grabbed row alone.
private func draggedRun(grabbing id: UUID) -> [UUID] {
let selected: [UUID]? = selectionAnchor.map { anchor in
selectedRangeIDs(anchor: anchor, focus: focusedID ?? anchor) ?? []
}
return OutlinePresenter.draggedIDs(grabbing: id, selected: selected, in: nodes)
}
/// Visible rows that have geometry — lazy rows outside the viewport
/// have no materialized catcher, and the pointer can't be over them.
private func materializedRows(frames: [UUID: CGRect]) -> [(row: OutlinePresenter.Row, frame: CGRect)] {
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
return rows.compactMap { row in frames[row.id].map { (row, $0) } }
}
private func dragMoved(to point: CGPoint, frames: [UUID: CGRect]) {
guard drag != nil else { return }
let materialized = materializedRows(frames: frames)
let target = OutlinePresenter.hitTestDrop(point: point, rows: materialized)
let moving = drag?.moving ?? []
let valid = target.map { OutlinePresenter.isValidDrop(moving: moving, target: $0, in: nodes) } ?? false
drag?.target = target
drag?.valid = valid
}
/// Drop (window point + live frames) or cancel (nil point). Invalid
/// and no-op drops leave the document untouched; a successful drop
/// makes the moved run the selection (anchor = first, focus = last).
private func endDrag(at point: CGPoint?, frames: [UUID: CGRect]?) {
let info = drag
drag = nil
guard let point, let info, let frames,
let target = OutlinePresenter.hitTestDrop(point: point, rows: materializedRows(frames: frames)),
OutlinePresenter.applyDrop(target, moving: info.moving, in: &nodes)
else { return }
selectionAnchor = info.moving.first
focusedID = info.moving.last
pendingCaret = nil
pushToDocument()
}
// MARK: Focus + folds
private func focus(_ id: UUID) {
guard id != focusedID else { return }
focusedID = id
selectionAnchor = nil // a click is a fresh single focus
pendingCaret = nil // caret at end
}
private func toggleFold(_ id: UUID) {
// View state ONLY — never serializes, never session.edit/draftEdited.
if folded.contains(id) {
folded.remove(id)
} else {
folded.insert(id)
}
}
// MARK: Structure
/// One key from the focused row's textview. View-state keys mutate
/// `folded`/focus directly; tree keys go through OutlineTree at the
/// focused node's path. Node ids travel through every op, so focus
/// follows the RESULT's node id, never the stale path.
private func apply(_ op: OutlineRowTextView.StructureOp) {
switch op {
case .fold:
// ⌘↑: fold the focused node when it has children.
if let id = focusedID, childCount(of: id) > 0 {
folded.insert(id)
}
case .unfold:
if let id = focusedID {
folded.remove(id)
}
case let .hop(direction):
// ↑/↓ hop VISIBLE blocks — folded subtrees are skipped.
hopFocus(direction, clearsAnchor: true)
case let .extend(direction):
// ⇧↑/⇧↓: extend the block selection one visible row. First
// press anchors at the focused row; a bare ↑/↓ or click clears.
if let focusedID {
extendSelection(to: focusedID) // arm the anchor at the current focus
}
hopFocus(direction, clearsAnchor: false)
case .deselect:
_ = handleEscape() // selection first, then zoom — same order as the monitor
case .indent, .outdent, .moveUp, .moveDown, .enter:
applyTree(op)
}
}
/// Move focus `direction` visible rows from its current position (nil at
/// the list edges — folded subtrees are skipped). `clearsAnchor`
/// distinguishes hop (clears the block-selection anchor) from extend.
private func hopFocus(_ direction: Int, clearsAnchor: Bool) {
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
guard let current = rows.firstIndex(where: { $0.id == focusedID }),
rows.indices.contains(current + direction)
else { return }
focusedID = rows[current + direction].id
if clearsAnchor {
selectionAnchor = nil
}
pendingCaret = nil // caret at end of the target row
}
/// Tree-mutating ops (indent/outdent/move/enter). Serialize + route
/// focus only when something actually changed (boundary no-ops are
/// nil and leave the document alone).
private func applyTree(_ op: OutlineRowTextView.StructureOp) {
guard let focusedID else { return }
if applyBatchIfPossible(op, focus: focusedID) {
return
}
guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return }
var didChange = false
var newFocus: (id: UUID, caret: Int)?
switch op {
case .indent:
didChange = OutlineTree.indent(&nodes, path: path) != nil
case .outdent:
didChange = OutlineTree.outdent(&nodes, path: path) != nil
case .moveUp:
didChange = OutlineTree.move(&nodes, path: path, up: true) != nil
case .moveDown:
didChange = OutlineTree.move(&nodes, path: path, up: false) != nil
case let .enter(caretGraphemes):
let enter = applyEnter(caretGraphemes: caretGraphemes, path: path)
didChange = enter.didChange
newFocus = enter.focus
case .fold, .unfold, .hop, .extend, .deselect:
return // unreachable — apply(_:) routes those to view state
}
commitIfChanged(didChange, newFocus)
}
/// Serialize + route focus only when something actually changed.
private func commitIfChanged(_ didChange: Bool, _ newFocus: (id: UUID, caret: Int)?) {
guard didChange else { return }
if let newFocus {
focusedID = newFocus.id
pendingCaret = newFocus.caret
}
pushToDocument()
}
/// Block-selection fast path: a batchable op over a multi-row run
/// (moves treat the run as a unit — a boundary leader no-ops the whole
/// batch). Returns true when the batch ran (caller stops here).
private func applyBatchIfPossible(_ op: OutlineRowTextView.StructureOp, focus: UUID) -> Bool {
guard let anchor = selectionAnchor,
let range = selectedRangeIDs(anchor: anchor, focus: focus), range.count > 1,
let batchOp = map(op)
else { return false }
if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) {
pushToDocument()
}
return true
}
/// Split (⏎) at `path`: serialize through OutlineTree.enter; focus
/// follows the NEW node when one was created (nil path = boundary
/// no-op).
private func applyEnter(caretGraphemes: Int, path: [Int]) -> (didChange: Bool, focus: (id: UUID, caret: Int)?) {
switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) {
case .noOp:
return (false, nil)
case let .outdented(newPath):
return (newPath != nil, nil) // nil = boundary no-op
case let .newNode(newPath, caret):
let id = OutlinePresenter.node(at: newPath, in: nodes)?.id
return (true, id.map { ($0, caret) })
}
}
/// The selected row ids in visible order (anchor↔focus, inclusive).
private func selectedRangeIDs(anchor: UUID, focus: UUID) -> [UUID]? {
OutlinePresenter.rangeIDs(from: anchor, to: focus, in: nodes, folded: folded, zoomRootID: zoomStack.last)
}
/// Row background when inside the block selection.
private func rowSelected(_ row: OutlinePresenter.Row) -> Bool {
guard let anchor = selectionAnchor else { return false }
return selectedRangeIDs(anchor: anchor, focus: focusedID ?? anchor)?.contains(row.id) ?? false
}
/// StructureOp → the batchable op for block-selection runs.
private func map(_ op: OutlineRowTextView.StructureOp) -> OutlinePresenter.BatchOp? {
switch op {
case .indent: .indent
case .outdent: .outdent
case .moveUp: .moveUp
case .moveDown: .moveDown
default: nil // enter/fold/etc. never batch
}
}
private func childCount(of id: UUID) -> Int {
guard let path = OutlinePresenter.path(of: id, in: nodes) else { return 0 }
return OutlinePresenter.node(at: path, in: nodes)?.children.count ?? 0
}
/// Every text keystroke and structural op lands here: serialize the
/// whole tree and hand it to the unchanged save machinery.
private func pushToDocument() {
let md = OutlineTree.serialize(preamble: preamble, nodes: nodes)
if let session {
session.edit(md)
} else {
onDraftEdit?(md)
}
}
/// #ui-r5 (argon#14): the piece's title at the prose editor's title
/// rung (serif, 22) — the outline opens as a page, not a bare bullet
/// list. The title text comes from `outlineTitle` below.
@ViewBuilder
private var outlineTitleHeader: some View {
if let title = outlineTitle {
Text(title)
.font(Font(ProseTypography.titleFont))
.foregroundStyle(DesignTokens.foreground)
.padding(.leading, DropGeometry.gripWidth)
.padding(.bottom, 14)
}
}
/// #ui-r5 (argon#14): the piece's title — the first non-blank preamble
/// line with heading markers stripped (Post.scan's title rule; the same
/// line the library row shows). Rendered above the tree; the remaining
/// preamble lines stay byte-preserved in the document but unshown, as
/// before. Lives here, not in the struct body — the type sits at
/// swiftlint's type_body_length ceiling.
private var outlineTitle: String? {
guard let raw = preamble.first(where: { !$0.trimmingCharacters(in: .whitespaces).isEmpty }) else {
return nil
}
let stripped = raw.drop(while: { $0 == "#" }).trimmingCharacters(in: .whitespaces)
return stripped.isEmpty ? nil : stripped
}
/// #ui-r5 (argon#1/sol#7 — r4 REGRESSION): one hairline rail per
/// ancestor level, at the PARENT bullet's CENTER column — directly
/// under the parent's bullet dot, LEFT of the child's marker, in the
/// indentation gutter. r4 put the stroke on the child TEXT column
/// (`textColumn(depth: level + 1)`), where it read as a stray caret
/// flush to the child's first letter. Full-row background so
/// consecutive siblings' segments join. Lives in this extension like
/// the other chrome helpers — the struct body sits at swiftlint's
/// type_body_length ceiling.
private func rails(depth: Int) -> some View {
Canvas { context, size in
for level in 0 ..< depth {
let railX = NestGeometry.bulletColumn(depth: level)
context.fill(
Path(CGRect(x: railX, y: 0, width: 1, height: size.height)),
with: .color(DesignTokens.border),
)
}
}
.allowsHitTesting(false)
}
}