feat(outline): drag-reorder + zoom — S6 (#112)
CI / ci (push) Canceled after 0s
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:
1 parent
d722820fc8
commit
21e2f27450
14 files changed
+2196
-256
No files matched your search
@@ -0,0 +1,484 @@
|
||||
//
|
||||
// OutlineDrag.swift
|
||||
// Museion
|
||||
//
|
||||
// #112 (S6, map #110 — wf113 verdict, variant A "fat gaps"): the
|
||||
// outliner's drag plumbing. One small transparent NSView per row —
|
||||
// `.grip` owns the 20pt left margin (click focuses, drag always runs:
|
||||
// batch when the row is inside the block selection, solo when not),
|
||||
// `.body` overlays static row text (click focuses, ⇧click extends,
|
||||
// drag only when the row is already selected — the live NSTextView row
|
||||
// keeps its native text-selection drag).
|
||||
//
|
||||
// A 4px threshold separates clicks from drags. Past it, a DragTracker
|
||||
// owns the gesture through NSEvent monitors — local for dragged/up/Esc,
|
||||
// global for dragged/up outside the app (mouse capture without a system
|
||||
// dragging session). No session means no destination dance and no
|
||||
// way for an Esc-cancel to resolve as a drop: moved → target updates,
|
||||
// Esc → cancel with no drop, mouse-up anywhere → drop at the point.
|
||||
// The gesture outlives its origin row (strong captures at arm time —
|
||||
// a mid-drag scroll can drop the catcher out of the lazy stack), and
|
||||
// a second arming cancels a stuck predecessor.
|
||||
// The drop math (fat-gap bands, validity, the splice) lives in
|
||||
// OutlinePresenter; the chrome in OutlineEditorView.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// The per-row drag/click catcher (see file header). Transparent,
|
||||
/// never first responder, draws nothing — it only turns mouse events
|
||||
/// into callbacks. Closures are re-set on every SwiftUI update, so they
|
||||
/// always read the surface's current state.
|
||||
struct OutlineDragCatcher: NSViewRepresentable {
|
||||
enum Kind {
|
||||
/// The left-margin grip: drag always available, click focuses.
|
||||
case grip
|
||||
/// Over static row text: ⇧click extends, drag only when the row
|
||||
/// is inside the block selection, click focuses.
|
||||
case body
|
||||
}
|
||||
|
||||
var kind: Kind
|
||||
var rowID: UUID
|
||||
/// .body only: is the row inside the current block selection?
|
||||
var isInSelection: () -> Bool
|
||||
/// The moving run for a grab of this row (deduped selection or solo).
|
||||
var payload: () -> [UUID]
|
||||
var onClick: () -> Void
|
||||
var onShiftClick: () -> Void
|
||||
var onDragBegan: ([UUID]) -> Void
|
||||
/// Window-space pointer position + live window-space row frames (one
|
||||
/// entry per materialized catcher — grip catchers fill the row's
|
||||
/// height, so their frames ARE row geometry). Fires while the drag
|
||||
/// runs.
|
||||
var onDragMoved: (CGPoint, [UUID: CGRect]) -> Void
|
||||
/// Cancelled drags pass a nil point — no drop is resolved.
|
||||
var onDragEnded: (CGPoint?, [UUID: CGRect]?) -> Void
|
||||
|
||||
func makeNSView(context _: Context) -> CatcherView {
|
||||
let view = CatcherView()
|
||||
apply(to: view)
|
||||
return view
|
||||
}
|
||||
|
||||
func updateNSView(_ view: CatcherView, context _: Context) {
|
||||
apply(to: view)
|
||||
}
|
||||
|
||||
private func apply(to view: CatcherView) {
|
||||
view.kind = kind
|
||||
view.rowID = rowID
|
||||
view.isInSelection = isInSelection
|
||||
view.payload = payload
|
||||
view.onClick = onClick
|
||||
view.onShiftClick = onShiftClick
|
||||
view.onDragBegan = onDragBegan
|
||||
view.onDragMoved = onDragMoved
|
||||
view.onDragEnded = onDragEnded
|
||||
}
|
||||
}
|
||||
|
||||
/// The NSView half of the catcher.
|
||||
final class CatcherView: NSView {
|
||||
var kind: OutlineDragCatcher.Kind = .grip
|
||||
var rowID = UUID()
|
||||
var isInSelection: () -> Bool = { false }
|
||||
var payload: () -> [UUID] = { [] }
|
||||
var onClick: () -> Void = {}
|
||||
var onShiftClick: () -> Void = {}
|
||||
var onDragBegan: ([UUID]) -> Void = { _ in }
|
||||
var onDragMoved: (CGPoint, [UUID: CGRect]) -> Void = { _, _ in }
|
||||
var onDragEnded: (CGPoint?, [UUID: CGRect]?) -> Void = { _, _ in }
|
||||
|
||||
override var acceptsFirstResponder: Bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Live window-space frames of every materialized catcher in the
|
||||
/// window, keyed by row id. Walking the real view tree reads CURRENT
|
||||
/// geometry: cached SwiftUI frames go stale on scroll, and the
|
||||
/// SDK's SwiftUI coordinate spaces shift between versions — AppKit's
|
||||
/// convert-to-window is the stable truth. The grip fills its row's
|
||||
/// height, so the GRIP frame is row geometry — it wins over the
|
||||
/// body catcher (text-only frame) regardless of visit order.
|
||||
static func rowFrames(in window: NSWindow) -> [UUID: CGRect] {
|
||||
guard let contentView = window.contentView else { return [:] }
|
||||
var frames: [UUID: CGRect] = [:]
|
||||
var stack: [NSView] = [contentView]
|
||||
while let view = stack.popLast() {
|
||||
if let catcher = view as? CatcherView, catcher.kind == .grip || frames[catcher.rowID] == nil {
|
||||
frames[catcher.rowID] = catcher.convert(catcher.bounds, to: nil)
|
||||
}
|
||||
stack.append(contentsOf: view.subviews)
|
||||
}
|
||||
return frames
|
||||
}
|
||||
|
||||
override func resetCursorRects() {
|
||||
// The grip advertises grabbability; the body stays an arrow.
|
||||
if kind == .grip {
|
||||
addCursorRect(bounds, cursor: .openHand)
|
||||
}
|
||||
}
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
|
||||
if kind == .body {
|
||||
if flags.contains(.shift) {
|
||||
onShiftClick()
|
||||
return
|
||||
}
|
||||
// Body-drag exists only on already-selected rows (wf113);
|
||||
// anywhere else a plain click just focuses the row.
|
||||
guard isInSelection() else {
|
||||
onClick()
|
||||
return
|
||||
}
|
||||
}
|
||||
armDrag()
|
||||
}
|
||||
|
||||
/// Hand the gesture to a DragTracker anchored at the current mouse
|
||||
/// position. Screen points convert to window space here, and every
|
||||
/// moved event carries a fresh frame walk. The window and the
|
||||
/// callbacks are captured STRONGLY — a mid-drag scroll can drop the
|
||||
/// origin row (and this catcher with it) out of the lazy stack, and
|
||||
/// the gesture must still end cleanly at mouse-up or the surface's
|
||||
/// drag state sticks (lifted rows, stale chrome). The callbacks read
|
||||
/// live @State through the struct copy, so capture time is harmless.
|
||||
private func armDrag() {
|
||||
guard let window else { return }
|
||||
let tracker = DragTracker(start: NSEvent.mouseLocation)
|
||||
let payload = payload
|
||||
let onDragBegan = onDragBegan
|
||||
let onDragMoved = onDragMoved
|
||||
let onDragEnded = onDragEnded
|
||||
let onClick = onClick
|
||||
tracker.onActivate = {
|
||||
let run = payload()
|
||||
guard !run.isEmpty else { return false }
|
||||
onDragBegan(run)
|
||||
return true
|
||||
}
|
||||
tracker.onMoved = { screenPoint in
|
||||
onDragMoved(
|
||||
window.convertPoint(fromScreen: screenPoint),
|
||||
Self.rowFrames(in: window),
|
||||
)
|
||||
}
|
||||
tracker.onEnded = { screenPoint in
|
||||
onDragEnded(
|
||||
screenPoint.map { window.convertPoint(fromScreen: $0) },
|
||||
Self.rowFrames(in: window),
|
||||
)
|
||||
}
|
||||
tracker.onClicked = { onClick() }
|
||||
tracker.install()
|
||||
}
|
||||
}
|
||||
|
||||
/// Monitor-owned drag tracking (#112): a 4px threshold promotes the
|
||||
/// held button to a drag; from then on dragged events update the
|
||||
/// target, Esc cancels (no drop), and mouse-up anywhere — including
|
||||
/// outside the app, via the global monitor — ends the gesture.
|
||||
/// The monitor closures retain the tracker, so the gesture always ends
|
||||
/// in finish() → teardown → release; there is no path that leaks.
|
||||
/// A second install() finishes a never-ended predecessor as a cancel,
|
||||
/// so trackers can never stack.
|
||||
/// ponytail: no auto-scroll mid-drag; the upgrade is an edge timer
|
||||
/// driving the same target math.
|
||||
private final class DragTracker {
|
||||
let start: NSPoint
|
||||
/// Threshold crossing: report the moving run, false = nothing
|
||||
/// draggable, the gesture ends quietly.
|
||||
var onActivate: () -> Bool = { false }
|
||||
var onMoved: (NSPoint) -> Void = { _ in }
|
||||
/// nil = cancelled (Esc / activation failure) — no drop.
|
||||
var onEnded: (NSPoint?) -> Void = { _ in }
|
||||
var onClicked: () -> Void = {}
|
||||
|
||||
private var active = false
|
||||
private var finished = false
|
||||
private var monitors: [Any] = []
|
||||
/// The one gesture that may own the monitors; install() cancels a
|
||||
/// stuck predecessor instead of stacking a second tracker.
|
||||
private static var current: DragTracker?
|
||||
|
||||
init(start: NSPoint) {
|
||||
self.start = start
|
||||
}
|
||||
|
||||
func install() {
|
||||
Self.current?.finish(nil)
|
||||
Self.current = self
|
||||
// Strong self-capture: NSEvent → closure → tracker keeps the
|
||||
// gesture alive until finish() removes the monitors. The local
|
||||
// monitor may swallow (nil); the global one only observes —
|
||||
// those events belong to another app.
|
||||
let local = NSEvent.addLocalMonitorForEvents(
|
||||
matching: [.leftMouseDragged, .leftMouseUp, .keyDown],
|
||||
) { event in
|
||||
self.handle(event)
|
||||
}
|
||||
let global = NSEvent.addGlobalMonitorForEvents(
|
||||
matching: [.leftMouseDragged, .leftMouseUp],
|
||||
) { event in
|
||||
_ = self.handle(event)
|
||||
}
|
||||
monitors = [local, global].compactMap(\.self)
|
||||
}
|
||||
|
||||
private func handle(_ event: NSEvent) -> NSEvent? {
|
||||
guard !finished else { return event }
|
||||
switch event.type {
|
||||
case .keyDown:
|
||||
// Esc cancels an ACTIVE drag only — before the threshold the
|
||||
// key belongs to whoever had focus.
|
||||
guard active, event.keyCode == 53 else { return event }
|
||||
finish(nil)
|
||||
return nil
|
||||
case .leftMouseDragged:
|
||||
guard active else {
|
||||
let now = NSEvent.mouseLocation
|
||||
guard hypot(now.x - start.x, now.y - start.y) >= 4 else { return nil }
|
||||
if onActivate() {
|
||||
active = true
|
||||
return nil
|
||||
}
|
||||
finish(nil)
|
||||
return nil
|
||||
}
|
||||
onMoved(NSEvent.mouseLocation)
|
||||
return nil
|
||||
case .leftMouseUp:
|
||||
if active {
|
||||
finish(NSEvent.mouseLocation)
|
||||
} else {
|
||||
finish(nil)
|
||||
onClicked()
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return event
|
||||
}
|
||||
}
|
||||
|
||||
private func finish(_ screenPoint: NSPoint?) {
|
||||
guard !finished else { return }
|
||||
finished = true
|
||||
if Self.current === self {
|
||||
Self.current = nil
|
||||
}
|
||||
teardown()
|
||||
onEnded(screenPoint)
|
||||
}
|
||||
|
||||
private func teardown() {
|
||||
monitors.forEach { NSEvent.removeMonitor($0) }
|
||||
monitors = []
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Drop math (pure, tested — #112)
|
||||
|
||||
nonisolated extension OutlinePresenter {
|
||||
/// #112 drag engine — where a grabbed run would land, referenced by
|
||||
/// node id and resolved against the tree AFTER extraction (the
|
||||
/// applyBatch re-resolve discipline). Line-insertion semantics: a
|
||||
/// drop can never steal siblings.
|
||||
enum DropTarget: Equatable {
|
||||
/// Seam: previous sibling of `ref`, at ref's own depth.
|
||||
case before(UUID)
|
||||
/// Seam below the last visible row: next sibling of `ref`, after
|
||||
/// its whole subtree.
|
||||
case afterLast(UUID)
|
||||
/// Block middle (ring): appended as `ref`'s last child.
|
||||
case lastChild(UUID)
|
||||
|
||||
/// The id every case references.
|
||||
var refID: UUID {
|
||||
switch self {
|
||||
case let .before(id), let .afterLast(id), let .lastChild(id): id
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The run a grab of `grabbing` drags (#112, wf113 verdict): when the
|
||||
/// grabbed row sits inside the block selection the whole selection
|
||||
/// rides — preorder order, descendants of selected ancestors deduped
|
||||
/// (the ancestor carries them); otherwise the grabbed row alone.
|
||||
static func draggedIDs(grabbing: UUID, selected: [UUID]?, in nodes: [OutlineNode]) -> [UUID] {
|
||||
guard let selected, selected.contains(grabbing) else { return [grabbing] }
|
||||
let sel = Set(selected)
|
||||
var run: [UUID] = []
|
||||
func walk(_ nodes: [OutlineNode], under selectedAncestor: Bool) {
|
||||
for node in nodes {
|
||||
let hit = sel.contains(node.id)
|
||||
if hit, !selectedAncestor {
|
||||
run.append(node.id)
|
||||
}
|
||||
walk(node.children, under: selectedAncestor || hit)
|
||||
}
|
||||
}
|
||||
walk(nodes, under: false)
|
||||
return run
|
||||
}
|
||||
|
||||
/// A drop is invalid when its reference IS a moving block or sits
|
||||
/// inside one (own-subtree). Everything else is a real position in
|
||||
/// the current tree.
|
||||
static func isValidDrop(moving: [UUID], target: DropTarget, in nodes: [OutlineNode]) -> Bool {
|
||||
guard let refPath = path(of: target.refID, in: nodes) else { return false }
|
||||
if moving.contains(target.refID) {
|
||||
return false
|
||||
}
|
||||
let movingSet = Set(moving)
|
||||
// every strict prefix of the ref path is an ancestor — if one
|
||||
// moves, the target sits inside a moved subtree
|
||||
for length in 1 ..< refPath.count {
|
||||
let ancestorPath = Array(refPath.prefix(length))
|
||||
if let ancestor = node(at: ancestorPath, in: nodes), movingSet.contains(ancestor.id) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Apply a drop: extract the moving run (reverse document order, so
|
||||
/// earlier paths stay valid), re-resolve the target's reference by id
|
||||
/// in the mutated tree, splice the run in as one contiguous block.
|
||||
/// False — tree untouched — for invalid targets and for no-ops (a
|
||||
/// drop back at the origin leaves the document alone).
|
||||
@discardableResult
|
||||
static func applyDrop(
|
||||
_ target: DropTarget, moving: [UUID], in nodes: inout [OutlineNode],
|
||||
) -> Bool {
|
||||
guard !moving.isEmpty, isValidDrop(moving: moving, target: target, in: nodes) else {
|
||||
return false
|
||||
}
|
||||
let snapshot = nodes
|
||||
guard moving.allSatisfy({ path(of: $0, in: nodes) != nil }) else { return false }
|
||||
|
||||
// extract in reverse document order — later removals never shift
|
||||
// earlier paths; the collected run reverses back to doc order
|
||||
let resolved: [(id: UUID, path: [Int])] = moving.compactMap { id in
|
||||
path(of: id, in: nodes).map { (id, $0) }
|
||||
}
|
||||
var run: [OutlineNode] = []
|
||||
for entry in resolved.sorted(by: { $0.path.lexicographicallyPrecedes($1.path) }).reversed() {
|
||||
guard let current = path(of: entry.id, in: nodes),
|
||||
let extracted = OutlineTree.extract(&nodes, path: current) else { continue }
|
||||
run.append(extracted)
|
||||
}
|
||||
run.reverse()
|
||||
guard !run.isEmpty,
|
||||
let refPath = path(of: target.refID, in: nodes),
|
||||
let refIndex = refPath.last
|
||||
else {
|
||||
nodes = snapshot
|
||||
return false
|
||||
}
|
||||
|
||||
let inserted: Bool = switch target {
|
||||
case .before:
|
||||
OutlineTree.insertRun(
|
||||
run, parentPath: Array(refPath.dropLast()), index: refIndex, in: &nodes,
|
||||
)
|
||||
case .afterLast:
|
||||
OutlineTree.insertRun(
|
||||
run, parentPath: Array(refPath.dropLast()), index: refIndex + 1, in: &nodes,
|
||||
)
|
||||
case .lastChild:
|
||||
OutlineTree.insertRun(run, parentPath: refPath, index: .max, in: &nodes)
|
||||
}
|
||||
guard inserted, nodes != snapshot else {
|
||||
nodes = snapshot
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/// Fat-gap hit test (wf113 variant A, the calibrated verdict): per
|
||||
/// visible row the top 30% is the seam above (insert before this
|
||||
/// row), the middle 40% is onto (last child), the bottom 30% the seam
|
||||
/// below (insert before the NEXT visible row at its depth — none
|
||||
/// means after the last row). Above the first row → before it; below
|
||||
/// the last → after it. `rows` in visible order with window-space
|
||||
/// frames (y-up — both callers feed window geometry; the former
|
||||
/// y-down auto-detect was prototype carryover); the point in the
|
||||
/// same space. Rows without a frame (unmaterialized lazy rows)
|
||||
/// are skipped.
|
||||
// ponytail: no auto-scroll mid-drag — keep the doc in view; the
|
||||
// app-side upgrade is a scroll-edge timer driving the same math.
|
||||
static func hitTestDrop(
|
||||
point: CGPoint, rows: [(row: Row, frame: CGRect)],
|
||||
) -> DropTarget? {
|
||||
guard let first = rows.first, let last = rows.last else { return nil }
|
||||
// window coords are y-up: the first visible row sits highest.
|
||||
// The ±6 tolerance reaches INTO the edge row (prototype:
|
||||
// `py < first.top + 6`), so the band never dead-ends.
|
||||
let pointY = point.y
|
||||
if pointY > first.frame.maxY - 6 {
|
||||
return .before(first.row.id)
|
||||
}
|
||||
if pointY < last.frame.minY + 6 {
|
||||
return .afterLast(last.row.id)
|
||||
}
|
||||
for (index, entry) in rows.enumerated() {
|
||||
let frame = entry.frame
|
||||
guard pointY >= frame.minY, pointY <= frame.maxY else { continue }
|
||||
let rel = abs(pointY - frame.maxY) / max(frame.height, 1)
|
||||
if rel < 0.30 {
|
||||
return .before(entry.row.id) // seam above = before this row, at its depth
|
||||
}
|
||||
if rel > 0.70 {
|
||||
// seam below = before the following row at ITS depth
|
||||
// (a deeper follower nests under the row above);
|
||||
// no follower → after this row
|
||||
guard index + 1 < rows.count else { return .afterLast(entry.row.id) }
|
||||
return .before(rows[index + 1].row.id)
|
||||
}
|
||||
return .lastChild(entry.row.id)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - #112 drag + zoom support types
|
||||
|
||||
/// Live drag state: the moving run (deduped selection ids) + the
|
||||
/// currently hit target and its validity.
|
||||
struct DragInfo: Equatable {
|
||||
let moving: [UUID]
|
||||
var target: OutlinePresenter.DropTarget?
|
||||
var valid: Bool
|
||||
}
|
||||
|
||||
/// Row geometry constants shared by the chrome: the 20pt left margin the
|
||||
/// grip owns, 18px per depth level, the bullet cell's center at 11pt —
|
||||
/// the seam indicator's left edge lands on the dropped block's future
|
||||
/// bullet column (wf113: 11 + d·18 from the row's content edge). The
|
||||
/// guide-rail Canvas reads the same constants — seam and rails must
|
||||
/// not drift apart.
|
||||
enum DropGeometry {
|
||||
static let gripWidth: CGFloat = 20
|
||||
static let railUnit: CGFloat = 18
|
||||
static let bulletCenter: CGFloat = 11
|
||||
|
||||
/// The bullet column in chrome space (from the row's leading edge,
|
||||
/// margin included).
|
||||
static func bulletColumn(depth: Int) -> CGFloat {
|
||||
gripWidth + CGFloat(depth) * railUnit + bulletCenter
|
||||
}
|
||||
}
|
||||
|
||||
/// A horizontal rule for the dashed invalid-seam indicator.
|
||||
nonisolated struct HLine: Shape {
|
||||
func path(in rect: CGRect) -> Path {
|
||||
var path = Path()
|
||||
path.move(to: CGPoint(x: 0, y: rect.midY))
|
||||
path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
|
||||
return path
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user