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
+372
-242
@@ -13,6 +13,17 @@
|
||||
// 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
|
||||
@@ -35,10 +46,23 @@ nonisolated enum OutlinePresenter {
|
||||
}
|
||||
|
||||
/// Preorder walk emitting one Row per visible node — a folded node's
|
||||
/// whole subtree is skipped and counted.
|
||||
static func visibleRows(_ nodes: [OutlineNode], folded: Set<UUID>) -> [Row] {
|
||||
/// 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] = []
|
||||
walk(nodes, parent: [], depth: 0, folded: folded, into: &rows)
|
||||
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
|
||||
}
|
||||
|
||||
@@ -70,9 +94,12 @@ nonisolated enum OutlinePresenter {
|
||||
|
||||
/// 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).
|
||||
static func rangeIDs(from: UUID, to: UUID, in nodes: [OutlineNode], folded: Set<UUID>) -> [UUID]? {
|
||||
let rows = visibleRows(nodes, folded: folded)
|
||||
/// 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 }
|
||||
@@ -186,33 +213,48 @@ struct OutlineEditorView: View {
|
||||
/// 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)
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
.padding(.top, 24)
|
||||
.padding(.bottom, 80)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,16 +269,17 @@ struct OutlineEditorView: View {
|
||||
/// 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.
|
||||
/// 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 selectionAnchor != nil {
|
||||
selectionAnchor = nil
|
||||
return nil // swallowed — the selection was the target
|
||||
if handleEscape() {
|
||||
return nil // swallowed — selection or zoom was the target
|
||||
}
|
||||
return event
|
||||
}
|
||||
@@ -271,24 +314,44 @@ struct OutlineEditorView: View {
|
||||
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 level*18+11, 18px indent per depth).
|
||||
// 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 = CGFloat(level) * 18 + 11
|
||||
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) * 18)
|
||||
.frame(width: CGFloat(row.depth) * DropGeometry.railUnit)
|
||||
bullet(row)
|
||||
if row.id == focusedID {
|
||||
OutlineRowTextView(
|
||||
@@ -306,6 +369,11 @@ struct OutlineEditorView: View {
|
||||
.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)")
|
||||
@@ -315,39 +383,114 @@ struct OutlineEditorView: View {
|
||||
.padding(.top, 5)
|
||||
}
|
||||
}
|
||||
.padding(.horizontal, 20)
|
||||
// Block-selection highlight (⇧↑/⇧↓ range, anchor↔focus).
|
||||
.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)
|
||||
if foldable {
|
||||
Button {
|
||||
toggleFold(row.id)
|
||||
} label: {
|
||||
glyph.frame(width: 22, height: 27)
|
||||
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")
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("fold/unfold (⌘↑ / ⌘↓)")
|
||||
.accessibilityLabel(row.isFolded ? "Unfold \(row.text)" : "Fold \(row.text)")
|
||||
} else {
|
||||
glyph
|
||||
.frame(width: 22, height: 27)
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { focus(row.id) }
|
||||
}
|
||||
.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 {
|
||||
@@ -369,11 +512,181 @@ struct OutlineEditorView: View {
|
||||
}
|
||||
.padding(.vertical, 3)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.contentShape(Rectangle())
|
||||
// Clicking another row focuses it, caret at END.
|
||||
// ponytail: no click-position caret mapping in v1 — mid-word clicks
|
||||
// land at the row's end; a textview hit-test is the upgrade path.
|
||||
.onTapGesture { focus(row.id) }
|
||||
}
|
||||
}
|
||||
|
||||
// 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 else { return }
|
||||
guard let target = OutlinePresenter.hitTestDrop(point: point, rows: materializedRows(frames: frames)) else {
|
||||
return
|
||||
}
|
||||
guard OutlinePresenter.applyDrop(target, moving: info.moving, in: &nodes) else { return }
|
||||
selectionAnchor = info.moving.first
|
||||
focusedID = info.moving.last
|
||||
pendingCaret = nil
|
||||
pushToDocument()
|
||||
}
|
||||
|
||||
// MARK: Focus + folds
|
||||
@@ -413,7 +726,7 @@ struct OutlineEditorView: View {
|
||||
}
|
||||
case let .hop(direction):
|
||||
// ↑/↓ hop VISIBLE blocks — folded subtrees are skipped.
|
||||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded)
|
||||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
|
||||
if let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||||
rows.indices.contains(current + direction)
|
||||
{
|
||||
@@ -424,10 +737,10 @@ struct OutlineEditorView: View {
|
||||
case let .extend(direction):
|
||||
// ⇧↑/⇧↓: extend the block selection one visible row. First
|
||||
// press anchors at the focused row; a bare ↑/↓ or click clears.
|
||||
if selectionAnchor == nil {
|
||||
selectionAnchor = focusedID
|
||||
if let focusedID {
|
||||
extendSelection(to: focusedID) // arm the anchor at the current focus
|
||||
}
|
||||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded)
|
||||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
|
||||
if let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||||
rows.indices.contains(current + direction)
|
||||
{
|
||||
@@ -435,7 +748,7 @@ struct OutlineEditorView: View {
|
||||
pendingCaret = nil
|
||||
}
|
||||
case .deselect:
|
||||
selectionAnchor = nil
|
||||
_ = handleEscape() // selection first, then zoom — same order as the monitor
|
||||
case .indent, .outdent, .moveUp, .moveDown, .enter:
|
||||
applyTree(op)
|
||||
}
|
||||
@@ -495,7 +808,7 @@ struct OutlineEditorView: View {
|
||||
|
||||
/// 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)
|
||||
OutlinePresenter.rangeIDs(from: anchor, to: focus, in: nodes, folded: folded, zoomRootID: zoomStack.last)
|
||||
}
|
||||
|
||||
/// Row background when inside the block selection.
|
||||
@@ -531,186 +844,3 @@ struct OutlineEditorView: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - The promoted row editor
|
||||
|
||||
/// The focused row's live editor (#109): borderless plain NSTextView with
|
||||
/// native undo/IME and an accent caret, wrapping at the column width (no
|
||||
/// horizontal scroll). `keyDown` intercepts the structural key set; every
|
||||
/// intercepted branch returns WITHOUT super (swallow); unhandled keys →
|
||||
/// super (native IME/undo/text). The branch swap on focus change remounts
|
||||
/// it per row.
|
||||
struct OutlineRowTextView: NSViewRepresentable {
|
||||
enum StructureOp: Equatable {
|
||||
case indent
|
||||
case outdent
|
||||
case moveUp
|
||||
case moveDown
|
||||
case enter(caretGraphemes: Int)
|
||||
case fold
|
||||
case unfold
|
||||
/// -1 = previous visible row, +1 = next.
|
||||
case hop(direction: Int)
|
||||
/// ⇧↑/⇧↓: extend block selection one visible row from the anchor.
|
||||
case extend(direction: Int)
|
||||
/// Esc: collapse the block selection.
|
||||
case deselect
|
||||
}
|
||||
|
||||
var text: String
|
||||
/// Grapheme offset for the caret at mount; nil = end. Never reapplied
|
||||
/// on update — the live view owns the caret after mount.
|
||||
var caret: Int?
|
||||
var onEdit: (String) -> Void
|
||||
var onStructure: (StructureOp) -> Void
|
||||
|
||||
func makeNSView(context: Context) -> RowTextView {
|
||||
let tv = RowTextView()
|
||||
tv.bridge = context.coordinator
|
||||
tv.allowsUndo = true
|
||||
tv.isRichText = false
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.backgroundColor = .clear
|
||||
tv.drawsBackground = false
|
||||
tv.insertionPointColor = NSColor(DesignTokens.accent)
|
||||
tv.typingAttributes = ProseTypography.outlineRowAttributes
|
||||
tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.textContainer?.widthTracksTextView = true
|
||||
tv.textContainer?.heightTracksTextView = false
|
||||
tv.textContainer?.lineFragmentPadding = 0
|
||||
tv.textContainerInset = .zero
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.isVerticallyResizable = true
|
||||
tv.minSize = .zero
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.autoresizingMask = [.width]
|
||||
tv.string = text
|
||||
// Caret at mount: grapheme offset → UTF-16 for NSTextView.
|
||||
let head = String(text.prefix(caret.map { min(max($0, 0), text.count) } ?? text.count))
|
||||
tv.setSelectedRange(NSRange(location: (head as NSString).length, length: 0))
|
||||
tv.delegate = context.coordinator
|
||||
context.coordinator.lastLocalText = text
|
||||
DispatchQueue.main.async { [weak tv] in
|
||||
tv?.window?.makeFirstResponder(tv)
|
||||
}
|
||||
return tv
|
||||
}
|
||||
|
||||
func updateNSView(_ tv: RowTextView, context: Context) {
|
||||
context.coordinator.onEdit = onEdit
|
||||
context.coordinator.onStructure = onStructure
|
||||
// Echo guard, ProseTextView-draft-mode pattern: our own keystrokes
|
||||
// round-trip byte-equal through the model, so only adopt when the
|
||||
// model's text differs from what this view last emitted — that's a
|
||||
// structural reshape or a reload. Caret parks at end (structural
|
||||
// changes that keep focus — outdent — move no text).
|
||||
if text != context.coordinator.lastLocalText, tv.string != text {
|
||||
tv.string = text
|
||||
tv.setSelectedRange(NSRange(location: (text as NSString).length, length: 0))
|
||||
context.coordinator.lastLocalText = text
|
||||
}
|
||||
}
|
||||
|
||||
/// The row wraps: height = laid-out height at the proposed width.
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView tv: RowTextView, context _: Context) -> CGSize? {
|
||||
guard let container = tv.textContainer, let layoutManager = tv.layoutManager else { return nil }
|
||||
let width = proposal.width ?? tv.bounds.width
|
||||
guard width > 0, width < .greatestFiniteMagnitude else { return nil }
|
||||
container.containerSize = NSSize(width: width, height: .greatestFiniteMagnitude)
|
||||
layoutManager.ensureLayout(for: container)
|
||||
// No vertical fudge: the row's .padding(.vertical, 3) mirrors staticText,
|
||||
// so focused and static baselines coincide. Floor 21 + 6 padding = 27:
|
||||
// the bullet cell's height — the row must not grow on focus.
|
||||
let height = layoutManager.usedRect(for: container).height
|
||||
return CGSize(width: width, height: max(height, 21))
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator()
|
||||
}
|
||||
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
var onEdit: ((String) -> Void)?
|
||||
var onStructure: ((StructureOp) -> Void)?
|
||||
/// The text this view last emitted/saw — the echo-guard reference.
|
||||
var lastLocalText = ""
|
||||
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv = notification.object as? NSTextView else { return }
|
||||
lastLocalText = tv.string
|
||||
tv.typingAttributes = ProseTypography.outlineRowAttributes
|
||||
onEdit?(tv.string)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The row NSTextView: structural key interception.
|
||||
final class RowTextView: NSTextView {
|
||||
weak var bridge: OutlineRowTextView.Coordinator?
|
||||
|
||||
override func keyDown(with event: NSEvent) {
|
||||
let key = event.charactersIgnoringModifiers ?? ""
|
||||
// Arrow matching traps: the character IS the function-key scalar
|
||||
// (String(NSUpArrowFunctionKey) would be its decimal description,
|
||||
// "63232"), and arrow events carry .function/.numericPad device
|
||||
// bits — strip them so == .command/.option/.shift can match.
|
||||
let upKey = "\u{F700}" // NSUpArrowFunctionKey
|
||||
let downKey = "\u{F701}" // NSDownArrowFunctionKey
|
||||
let modifiers = event.modifierFlags
|
||||
.intersection(.deviceIndependentFlagsMask)
|
||||
.subtracting([.function, .numericPad])
|
||||
|
||||
if key == upKey || key == downKey {
|
||||
let up = key == upKey
|
||||
switch modifiers {
|
||||
case .command:
|
||||
bridge?.onStructure?(up ? .fold : .unfold)
|
||||
case .option:
|
||||
bridge?.onStructure?(up ? .moveUp : .moveDown)
|
||||
case .shift:
|
||||
bridge?.onStructure?(.extend(direction: up ? -1 : 1))
|
||||
default:
|
||||
bridge?.onStructure?(.hop(direction: up ? -1 : 1))
|
||||
}
|
||||
return
|
||||
}
|
||||
if key == "\t" {
|
||||
bridge?.onStructure?(modifiers.contains(.shift) ? .outdent : .indent)
|
||||
return
|
||||
}
|
||||
if key == "\u{19}" { // NSBackTabCharacter — ⇧⇥ arrives as backtab, not " " + shift
|
||||
bridge?.onStructure?(.outdent)
|
||||
return
|
||||
}
|
||||
if key == "\u{1b}" { // Esc: collapse the block selection
|
||||
bridge?.onStructure?(.deselect)
|
||||
return
|
||||
}
|
||||
if key == "\r" || key == "\n" {
|
||||
// THE conversion (classic trap): selectedRange().location is a
|
||||
// UTF-16 offset; enter() counts GRAPHEME clusters. Passing the
|
||||
// raw number splits emoji/CJK clusters mid-grapheme. Clamp,
|
||||
// convert through String.Index, then count characters.
|
||||
let text = string
|
||||
let utf16Location = min(max(0, selectedRange().location), text.utf16.count)
|
||||
let index = String.Index(utf16Offset: utf16Location, in: text)
|
||||
let graphemes = text.distance(from: text.startIndex, to: index)
|
||||
bridge?.onStructure?(.enter(caretGraphemes: graphemes))
|
||||
return
|
||||
}
|
||||
super.keyDown(with: event)
|
||||
}
|
||||
|
||||
/// Some AppKit paths deliver ⇧⇥ here instead of keyDown.
|
||||
override func insertBacktab(_: Any?) {
|
||||
bridge?.onStructure?(.outdent)
|
||||
}
|
||||
|
||||
/// Esc on NSTextView routes here (doCommandBy:), not always keyDown.
|
||||
override func cancelOperation(_: Any?) {
|
||||
bridge?.onStructure?(.deselect)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user