feat(outline): drag-reorder + zoom — S6 (#112)
CI / ci (push) Canceled after 0s

Pointer drag of a block run into any sibling seam or onto a block to
nest as its child (wf113 variant A: fat-gap 30/40/30 bands, seam
line at the future bullet column); the block selection rides the
drag, the moved run becomes the selection, and Esc cancels mid-gesture.
Double-click any bullet zooms to its children with breadcrumbs back
out. New OutlineTree extract/insertRun splice subtrees id-preserving;
the live row's NSTextView moved to OutlineRowTextView.

Audit round: the gesture is self-contained from arm time (strong
window + callback captures — a mid-drag scroll that drops the origin
row cannot strand drag state), a second arming cancels a stuck
predecessor, rowFrames prefers the grip frame, hitTestDrop is y-up
only, and the rails read DropGeometry. Pinned in OutlineDragTests
(monitors fire on sendEvent with a real window number).

[Generated by AI]
This commit is contained in:
AlexKucera committed 2026-10-16 14:49:57 +02:00
1 parent d722820fc8
commit 21e2f27450
14 files changed
+2196 -256

No files matched your search

+4 -3
View File
@@ -28,9 +28,10 @@ Owned by the root AGENTS.md contract.
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
- `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0.
- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts/<id>/post.md` (#107).
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet.
- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting).
- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (the monitor itself can't run in the test host — no running NSApp loop).
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet. **#112:** extract/insertRun pins — subtree pull by path (ids travel, bad paths nil), sibling splices at any parent (index clamp-to-append, contiguous run order, unresolvable parent false + untouched, empty run refused).
- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting). **#112 (S6):** nine pins — `draggedIDs` dedup (selection rides, ancestor carries descendants, unselected/no-selection go solo), `isValidDrop` (ref moving / inside moving subtree / own-parent-legal / unknown), precise `before`/`afterLast`/`lastChild` landings (incl. the seam-below-a-deeper-follower FIRST-child nest and cross-parent extraction that keyboard batches refuse), contiguous deduped batch landing with id travel, origin no-ops + invalid refusals (snapshot equality — storage untouched), zoom projection (children rooted, depths re-based, zoom root's fold ignored, inner folds still hide, unknown id → whole doc), `rangeIDs` nil across the zoom boundary, and `hitTestDrop` fat-gap bands (30/40/30, ±6 into edge rows, window-space y-up frames, empty rows nil).
- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (monitors DO fire in the host on `NSApp.sendEvent`, but only for events carrying a real window number — see `OutlineDragTests`).
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
## Verification
+105
View File
@@ -0,0 +1,105 @@
//
// OutlineDragTests.swift
// MuseionTests
//
// #112 pins for the drag plumbing's lifetime + geometry contracts.
// The gesture must be self-contained from arm time on: the tracker
// holds its own copies of the callbacks (nothing reads the catcher's
// state at fire time), so a mid-drag scroll that drops the origin row
// out of the lazy stack cannot strand the surface's drag state.
// (The dealloc itself can't be reproduced in this harness — AppKit
// keeps extra internal retains on any once-installed view — so the
// pin swaps the callbacks AFTER arming: only an arm-time snapshot
// fires.) Also pinned: rowFrames reports the grip catcher's full-row
// frame (not the body catcher's text-only frame) regardless of
// subview order, and arming a second drag cancels a stuck
// predecessor instead of stacking trackers. Monitors fire on
// NSApp.sendEvent — but only for events carrying a real window
// number (window-0 events never reach monitors; probe-pinned).
//
import AppKit
@testable import Museion
import Testing
@MainActor
@Suite(.serialized)
struct OutlineDragTests {
private func makeWindow() -> NSWindow {
NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 300),
styleMask: [.titled], backing: .buffered, defer: false)
}
private func mouseEvent(_ type: NSEvent.EventType, in window: NSWindow) -> NSEvent? {
NSEvent.mouseEvent(with: type, location: NSPoint(x: 20, y: 280), modifierFlags: [],
timestamp: 0, windowNumber: window.windowNumber, context: nil,
eventNumber: 0, clickCount: 1, pressure: 1)
}
@Test func `the tracker holds its own callbacks - a post-arm swap never fires`() throws {
let window = makeWindow()
var armTime = 0
var swappedIn = 0
let catcher = CatcherView()
catcher.kind = .grip // grip drags always arm — no selection dance
catcher.frame = NSRect(x: 0, y: 273, width: 300, height: 27)
catcher.onDragEnded = { _, _ in armTime += 1 }
window.contentView?.addSubview(catcher)
// arm (installs the tracker; its monitors retain it)
try catcher.mouseDown(with: #require(mouseEvent(.leftMouseDown, in: window)))
// the origin row dematerializes and SwiftUI re-sets the catcher's
// closures — a gesture that read live view state at fire time
// would now target the wrong (or gone) row
catcher.onDragEnded = { _, _ in swappedIn += 1 }
// mouse-up must end the gesture through the ARM-TIME callbacks
try NSApp.sendEvent(#require(mouseEvent(.leftMouseUp, in: window)))
#expect(armTime == 1)
#expect(swappedIn == 0)
}
@Test func `arming a second drag cancels a stuck predecessor`() throws {
let window = makeWindow()
var firstEnded = 0
let first = CatcherView()
first.kind = .grip
first.onDragEnded = { _, _ in firstEnded += 1 }
window.contentView?.addSubview(first)
try first.mouseDown(with: #require(mouseEvent(.leftMouseDown, in: window)))
let second = CatcherView()
second.kind = .grip
window.contentView?.addSubview(second)
try second.mouseDown(with: #require(mouseEvent(.leftMouseDown, in: window)))
// the predecessor resolved as a cancel instead of stacking
#expect(firstEnded == 1)
// end the live gesture so no monitors outlive the test
try NSApp.sendEvent(#require(mouseEvent(.leftMouseUp, in: window)))
}
@Test func `rowFrames prefers the grip frame regardless of subview order`() {
let window = makeWindow()
let id = UUID()
let grip = CatcherView()
grip.kind = .grip
grip.rowID = id
grip.frame = NSRect(x: 0, y: 0, width: 300, height: 27) // full row
let body = CatcherView()
body.kind = .body
body.rowID = id
body.frame = NSRect(x: 0, y: 2, width: 300, height: 23) // text only
window.contentView?.addSubview(body) // reverse of declaration order
window.contentView?.addSubview(grip)
#expect(CatcherView.rowFrames(in: window)[id] == grip.convert(grip.bounds, to: nil))
grip.removeFromSuperview()
body.removeFromSuperview()
window.contentView?.addSubview(grip) // declaration order
window.contentView?.addSubview(body)
#expect(CatcherView.rowFrames(in: window)[id] == grip.convert(grip.bounds, to: nil))
}
}
+197
View File
@@ -7,6 +7,7 @@
// through deep trees, and setText mutation by node identity.
//
import CoreGraphics
import Foundation
@testable import Museion
import Testing
@@ -170,4 +171,200 @@ struct OutlinePresenterTests {
#expect(outNodes.map(\.text) == ["a", "a1", "a2", "a3"])
#expect(outNodes[1...].allSatisfy { node in node.children.isEmpty })
}
// #112 (S6): drag-reorder + zoom over the presenter.
@Test func `draggedIDs rides the selection deduped or goes solo`() {
let tree = [node("a", [node("a1", [node("a1x")]), node("a2")]), node("b"), node("c")]
// grab a selected row → the whole selection rides, preorder order,
// a selected ancestor carries its selected descendants
let sel = [tree[0].id, tree[0].children[0].id, tree[2].id]
#expect(
OutlinePresenter.draggedIDs(grabbing: tree[0].id, selected: sel, in: tree)
== [tree[0].id, tree[2].id],
)
// grab an UNselected row while a selection exists → solo
#expect(
OutlinePresenter.draggedIDs(grabbing: tree[1].id, selected: sel, in: tree)
== [tree[1].id],
)
// no selection at all → solo, works at any depth
#expect(
OutlinePresenter.draggedIDs(grabbing: tree[0].children[1].id, selected: nil, in: tree)
== [tree[0].children[1].id],
)
}
@Test func `isValidDrop rejects refs at or inside the moving run`() {
let tree = [node("a", [node("a1", [node("a1x")]), node("a2")]), node("b")]
// the ref itself moves
#expect(!OutlinePresenter.isValidDrop(moving: [tree[1].id], target: .before(tree[1].id), in: tree))
// the ref sits inside a moving subtree (any depth)
#expect(!OutlinePresenter.isValidDrop(moving: [tree[0].id], target: .lastChild(tree[0].children[0].id), in: tree))
#expect(!OutlinePresenter.isValidDrop(
moving: [tree[0].children[0].id],
target: .before(tree[0].children[0].children[0].id),
in: tree,
))
// dropping back into one's own PARENT as its last child is legal —
// extraction happens first, the target never ends up inside the run
#expect(OutlinePresenter.isValidDrop(moving: [tree[0].children[0].id], target: .lastChild(tree[0].id), in: tree))
// an unrelated row is fine
#expect(OutlinePresenter.isValidDrop(moving: [tree[0].id], target: .before(tree[1].id), in: tree))
// unknown ref → invalid
#expect(!OutlinePresenter.isValidDrop(moving: [tree[0].id], target: .before(UUID()), in: tree))
}
@Test func `applyDrop lands before afterLast and lastChild precisely`() {
// before: b moves up, directly before a
var beforeNodes = OutlineTree.parse("- a\n- b\n- c").nodes
#expect(OutlinePresenter.applyDrop(.before(beforeNodes[0].id), moving: [beforeNodes[1].id], in: &beforeNodes))
#expect(beforeNodes.map(\.text) == ["b", "a", "c"])
// afterLast: the end-of-list seam — lands after the LAST row at
// its depth, subtree pulled whole
var afterNodes = OutlineTree.parse("- a\n- b\n - b1\n- c").nodes
let movingID = afterNodes[0].id
#expect(OutlinePresenter.applyDrop(.afterLast(afterNodes[2].id), moving: [movingID], in: &afterNodes))
#expect(afterNodes.map(\.text) == ["b", "c", "a"])
// lastChild: onto — appended AFTER existing children (never first)
var ontoNodes = OutlineTree.parse("- a\n - a1\n- b").nodes
let bID = ontoNodes[1].id
#expect(OutlinePresenter.applyDrop(.lastChild(ontoNodes[0].id), moving: [bID], in: &ontoNodes))
#expect(ontoNodes.map(\.text) == ["a"])
#expect(ontoNodes[0].children.map(\.text) == ["a1", "b"])
// a seam below a deeper follower nests: dropping before a's first
// child (the seam between a and a1) makes it the FIRST child
var nestNodes = OutlineTree.parse("- a\n - a1\n- b").nodes
let a1ID = nestNodes[0].children[0].id
#expect(OutlinePresenter.applyDrop(.before(a1ID), moving: [nestNodes[1].id], in: &nestNodes))
#expect(nestNodes.map(\.text) == ["a"])
#expect(nestNodes[0].children.map(\.text) == ["b", "a1"])
}
@Test func `applyDrop moves a deduped batch as one contiguous run`() {
// a (with a1) and c selected together → they land adjacent, a
// before c, a's subtree riding inside
var nodes = OutlineTree.parse("- a\n - a1\n- b\n- c").nodes
let aID = nodes[0].id
let cID = nodes[2].id
#expect(OutlinePresenter.applyDrop(.afterLast(nodes[1].id), moving: [aID, cID], in: &nodes))
#expect(nodes.map(\.text) == ["b", "a", "c"])
#expect(nodes[1].children.map(\.text) == ["a1"])
// ids travel — focus/selection can follow the run
#expect(nodes[1].id == aID && nodes[2].id == cID)
}
@Test func `applyDrop no-ops a drop back at origin and refuses invalid targets`() {
// b is ALREADY immediately before c — extract + insert-before-c
// reproduces the tree → no-op, storage untouched
var nodes = OutlineTree.parse("- a\n- b\n- c").nodes
let snapshot = nodes
#expect(!OutlinePresenter.applyDrop(.before(nodes[2].id), moving: [nodes[1].id], in: &nodes))
#expect(nodes == snapshot) // storage untouched
// onto own subtree — invalid, dashed-indicator case
var selfNodes = OutlineTree.parse("- a\n - a1").nodes
let selfSnapshot = selfNodes
#expect(!OutlinePresenter.applyDrop(.lastChild(selfNodes[0].children[0].id), moving: [selfNodes[0].id], in: &selfNodes))
#expect(selfNodes == selfSnapshot)
// dropping onto one's own parent when ALREADY its last child → no-op
var tailNodes = OutlineTree.parse("- a\n - a1\n - a2").nodes
let tailSnapshot = tailNodes
#expect(!OutlinePresenter.applyDrop(.lastChild(tailNodes[0].id), moving: [tailNodes[0].children[1].id], in: &tailNodes))
#expect(tailNodes == tailSnapshot)
}
@Test func `applyDrop crosses parents through a drag`() {
// keyboard batch moves stay sibling-only; a drag is atomic
// extract+splice, so a1 can leave a and land among the roots
var nodes = OutlineTree.parse("- a\n - a1\n- b").nodes
let a1ID = nodes[0].children[0].id
#expect(OutlinePresenter.applyDrop(.before(nodes[1].id), moving: [a1ID], in: &nodes))
#expect(nodes.map(\.text) == ["a", "a1", "b"])
#expect(nodes[0].children.isEmpty)
}
@Test func `visibleRows zoom roots at the node with depths rebased`() {
let tree = [node("a", [node("a1", [node("a1x")]), node("a2")]), node("b")]
let rows = OutlinePresenter.visibleRows(tree, folded: [], zoomRootID: tree[0].id)
#expect(rows.map(\.text) == ["a1", "a1x", "a2"])
#expect(rows.map(\.depth) == [0, 1, 0]) // depth 2 re-based to 0
// the zoom root's own fold is ignored while it IS the root —
// its children are the document now
let folded = OutlinePresenter.visibleRows(tree, folded: [tree[0].id], zoomRootID: tree[0].id)
#expect(folded.map(\.text) == ["a1", "a1x", "a2"])
// folding INSIDE the zoom still hides
let inner = OutlinePresenter.visibleRows(tree, folded: [tree[0].children[0].id], zoomRootID: tree[0].id)
#expect(inner.map(\.text) == ["a1", "a2"])
#expect(inner[0].foldedDescendantCount == 1)
// unknown zoom id → the whole document
#expect(
OutlinePresenter.visibleRows(tree, folded: [], zoomRootID: UUID()).map(\.text)
== ["a", "a1", "a1x", "a2", "b"],
)
}
@Test func `rangeIDs under zoom is nil across the zoom boundary`() {
let tree = [node("a", [node("a1")]), node("b")]
// a is outside the zoom rooted at a — invisible → nil
#expect(OutlinePresenter.rangeIDs(
from: tree[0].id,
to: tree[1].id,
in: tree,
folded: [],
zoomRootID: tree[0].id,
) == nil)
// both ends inside → the span still works
#expect(OutlinePresenter.rangeIDs(
from: tree[0].children[0].id,
to: tree[0].children[0].id,
in: tree,
folded: [],
zoomRootID: tree[0].id,
) == [tree[0].children[0].id])
}
@Test func `hitTestDrop follows the fat-gap bands`() {
// window-space y-up frames (the only orientation both callers
// feed): a highest at y 60–90, c lowest at 0–30
let rowA = OutlineNode(text: "a")
let rowB = OutlineNode(text: "b")
let rowC = OutlineNode(text: "c")
let rows = OutlinePresenter.visibleRows([rowA, rowB, rowC], folded: [])
let frames: [UUID: CGRect] = [
rowA.id: CGRect(x: 0, y: 60, width: 400, height: 30),
rowB.id: CGRect(x: 0, y: 30, width: 400, height: 30),
rowC.id: CGRect(x: 0, y: 0, width: 400, height: 30),
]
let pairs = rows.compactMap { row in frames[row.id].map { (row, $0) } }
// pointer visually above a (y 95) → before a
#expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 95), rows: pairs) == .before(rowA.id))
// top 30% of b (y 55, rel 1/6 from the top) → the seam above b
#expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 55), rows: pairs) == .before(rowB.id))
// middle 40% of b (y 45) → onto (last child, ring)
#expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 45), rows: pairs) == .lastChild(rowB.id))
// bottom 30% of b (y 35) → the seam below → before the FOLLOWING row
#expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 35), rows: pairs) == .before(rowC.id))
// below c (y -10) → after c (end-of-list seam)
#expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: -10), rows: pairs) == .afterLast(rowC.id))
// rows without frames are simply unreachable
#expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 45), rows: []) == nil)
}
}
+37
View File
@@ -270,4 +270,41 @@ struct OutlineTreeTests {
#expect(!OutlineTree.parsesWithLoss("- one\n\n- two\n"))
#expect(!OutlineTree.parsesWithLoss(""))
}
// #112 (S6): the drag primitives — extract + insertRun.
@Test func `extract removes and returns the whole subtree by path`() {
var nodes = OutlineTree.parse("- a\n - a1\n- b").nodes
let extracted = OutlineTree.extract(&nodes, path: [0])
#expect(extracted?.text == "a")
#expect(extracted?.children.map(\.text) == ["a1"])
#expect(nodes.map(\.text) == ["b"])
// ids travel — the drag run re-inserts the same identities
#expect(extracted?.children[0].id != nil)
// unresolvable paths are nil no-ops
#expect(OutlineTree.extract(&nodes, path: [5]) == nil)
#expect(nodes.map(\.text) == ["b"])
}
@Test func `insertRun splices siblings at any parent and clamps the index`() {
var nodes = OutlineTree.parse("- a\n - a1\n- b").nodes
// into the root, before b
#expect(OutlineTree.insertRun([OutlineNode(text: "x")], parentPath: [], index: 1, in: &nodes))
#expect(nodes.map(\.text) == ["a", "x", "b"])
// a nested parent; index clamps to count (append)
#expect(OutlineTree.insertRun([OutlineNode(text: "a2")], parentPath: [0], index: 99, in: &nodes))
#expect(nodes[0].children.map(\.text) == ["a1", "a2"])
// a whole run lands contiguous, in order
let run = [OutlineNode(text: "r1"), OutlineNode(text: "r2")]
#expect(OutlineTree.insertRun(run, parentPath: [], index: 0, in: &nodes))
#expect(nodes.map(\.text) == ["r1", "r2", "a", "x", "b"])
// unresolvable parent → false, untouched; empty run refused
#expect(!OutlineTree.insertRun([OutlineNode(text: "z")], parentPath: [7], index: 0, in: &nodes))
#expect(!OutlineTree.insertRun([], parentPath: [], index: 0, in: &nodes))
#expect(nodes.map(\.text) == ["r1", "r2", "a", "x", "b"])
}
}