CI / ci (push) Canceled after 0s
The repo contract "SwiftFormat + SwiftLint must both stay clean" had five error spots left beyond #146's PostsModel split, all mechanical. PostStore's enum body spanned 354 against 350 — the cursor-sidecar group (#66: CursorState + stateURL/readCursor/writeCursor, already its own MARK section) moves verbatim into a same-file nonisolated extension slotted chronologically before the #141 ingest MARK; the enum body lands at 334 and PostStore.CursorState keeps its qualified name, so no caller changes. Six single-char locals in ProseListTextView's dropIndex/rectY/isGap get real names (plus lo/hi in the same function — same violation class), one in ImageIngestTests' bandedRectY. The 194-char guard in ProseList.indent and the 221-char guard in OutlineEditorView.endDrag wrap in the house else-carries-the-brace form (#142 landmine avoided). PostStoreTests crossed its 1000-line ceiling at 1061 — split at the Pass substrate MARK per the MicropubModelTests precedent: the pass-adjacent write sides (#24/#29/#31) move byte-identical into PostStorePassTests.swift, shared helpers storeHome/readPost/readPiece stay internal in the original, and the #29 scenario header travels with its tests. 63 tests in, 63 out. The split's new parallel schedule exposed two latent test races, reproduced idle (~50% for the first) and fixed at the root: EditorSessionTests' sidecar poll inherited loop 1's deadline and timed out holding flush 1's default-zero sidecar (zeros, never nil — the telltale) — each loop now arms its own. SessionLifecycleTests' three stderrTail asserts raced the client's main-queue stderr drain (the #30 class) — a drainStderr bounded poll now precedes each. swiftlint reports zero errors on both targets; residual warning-tier notices match the standing #146 posture (the error tier is the bar; the one new notice is PostStorePassTests at 473/400 — a 1070-line suite cannot split into two files both under 400). swiftformat clean. Full suite 574/574 by xcresult executed count (573 unit + 1 UI smoke), twice consecutively plus the finish-up rerun. Closes #147
846 lines
30 KiB
Swift
846 lines
30 KiB
Swift
//
|
||
// 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) }
|
||
}
|
||
|
||
/// 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
|
||
|
||
/// 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)
|
||
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) {
|
||
ForEach(rows) { row in
|
||
rowView(row)
|
||
}
|
||
}
|
||
.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)
|
||
// Per-depth guide rails (prototype variant B: 1px hairline per
|
||
// ancestor level, at DropGeometry's bulletCenter + level·railUnit
|
||
// — same constants the drop seam uses, so rails and seam
|
||
// cannot drift apart).
|
||
Canvas { context, size in
|
||
for level in 0 ..< row.depth {
|
||
let railX = DropGeometry.bulletCenter + CGFloat(level) * DropGeometry.railUnit
|
||
context.fill(
|
||
Path(CGRect(x: railX, y: 0, width: 1, height: size.height)),
|
||
with: .color(DesignTokens.border),
|
||
)
|
||
}
|
||
}
|
||
.frame(width: CGFloat(row.depth) * DropGeometry.railUnit)
|
||
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)
|
||
// 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 (11 + d·18 + 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: DropGeometry.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): fold toggle when the node has children
|
||
/// ("●" ~7pt, folded → accent), leaf "◦" ~10pt; 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(foldable ? "●" : "◦")
|
||
.font(.system(size: foldable ? 7 : 10))
|
||
.foregroundStyle(row.isFolded ? DesignTokens.accent : DesignTokens.muted)
|
||
Group {
|
||
if foldable {
|
||
Button {
|
||
toggleFold(row.id)
|
||
} label: {
|
||
glyph.frame(width: 22, height: 27)
|
||
}
|
||
.buttonStyle(.plain)
|
||
.help("fold/unfold (⌘↑ / ⌘↓) · double-click: zoom in")
|
||
.accessibilityLabel(row.isFolded ? "Unfold \(row.text)" : "Fold \(row.text)")
|
||
} else {
|
||
glyph
|
||
.frame(width: 22, 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.
|
||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
|
||
if let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||
rows.indices.contains(current + direction)
|
||
{
|
||
focusedID = rows[current + direction].id
|
||
selectionAnchor = nil
|
||
pendingCaret = nil // caret at end of the target row
|
||
}
|
||
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
|
||
}
|
||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
|
||
if let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||
rows.indices.contains(current + direction)
|
||
{
|
||
focusedID = rows[current + direction].id
|
||
pendingCaret = nil
|
||
}
|
||
case .deselect:
|
||
_ = handleEscape() // selection first, then zoom — same order as the monitor
|
||
case .indent, .outdent, .moveUp, .moveDown, .enter:
|
||
applyTree(op)
|
||
}
|
||
}
|
||
|
||
/// 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 }
|
||
// Block selection + batchable op → run-wide apply. Moves treat
|
||
// the run as a unit (boundary leader no-ops the whole batch).
|
||
if let anchor = selectionAnchor,
|
||
let range = selectedRangeIDs(anchor: anchor, focus: focusedID), range.count > 1,
|
||
let batchOp = map(op)
|
||
{
|
||
if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) {
|
||
pushToDocument()
|
||
}
|
||
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):
|
||
switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) {
|
||
case .noOp:
|
||
break
|
||
case let .outdented(newPath):
|
||
didChange = newPath != nil // nil = boundary no-op
|
||
case let .newNode(newPath, caret):
|
||
didChange = true
|
||
if let id = OutlinePresenter.node(at: newPath, in: nodes)?.id {
|
||
newFocus = (id, caret)
|
||
}
|
||
}
|
||
case .fold, .unfold, .hop, .extend, .deselect:
|
||
return // unreachable — apply(_:) routes those to view state
|
||
}
|
||
if didChange {
|
||
if let newFocus {
|
||
self.focusedID = newFocus.id
|
||
pendingCaret = newFocus.caret
|
||
}
|
||
pushToDocument()
|
||
}
|
||
}
|
||
|
||
/// 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)
|
||
}
|
||
}
|
||
}
|