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

+5 -3
View File
@@ -12,7 +12,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- Entry point: `MuseionApp.swift` (`@main`, `WindowGroup` scene + `about` window; `AppGateState` holds app-scoped gate state). **#22:** File ▸ Open… (⌘O) + Import… (⇧⌘O) via `CommandGroup(after: .newItem)` — `OpenExternalButton` / `ImportFilesButton` over one shared `pickMarkdown` NSOpenPanel helper (.md/.markdown via `PostStore.openableTypes`); never `CommandMenu("File")` (#84 trap). `FocusModeToggle` arms for the external guest too. **#108:** the same group leads with New Post ⌘N (`NewPostButton`, the library + button's draft path), New Outline ⇧⌘N (#109: `NewOutlineButton` → `PostsModel.newOutline()` — same draft path, outline type) and New Project… ⌥⌘N (`NewProjectButton` → `PostsModel.stageNewProject()`; WorkspaceView presents the `NewProjectSheet` — commands can't present sheets, the pendingImportURLs pattern: create succeeds → `newProjectPending` sets the draft's target project + opens the draft; failure keeps the sheet up with the reason inline; note ⌘N may be swallowed by the stock new-window item on some builds — the menu item always fires).
- `AppMetadata` is the single source for the displayed app name and tagline; members are `nonisolated` (default-MainActor project).
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 26.5; bundle id `com.babylondreams.Museion`.
- Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 27.0 (bumped from 26.5 with the Xcode 27 settings pass — all six project configs, tests included, stay aligned or the test targets can't link the app module); bundle id `com.babylondreams.Museion`.
- App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file.
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exception: the engine gate's `state.json` (see below).
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
@@ -26,8 +26,10 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was moved." to the flush-routed reason, never replacing it; the session stays up dirty), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(hLine truncated
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. Folds live in the view, keyed by node UUID — never modeled here.
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` (borderless NSTextView subclass, native undo/IME, rust caret) on the focused row, static inline-markdown text elsewhere (tap focuses, caret at end — v1 ceiling, ponytail-marked); typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box — the prose CSS-1.8 `lineHeightMultiple` is deliberately absent: an inflated fragment grows the focused row and detaches the bullet; test-pinned), static rows render the same NSFont (no face swap on focus), the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — exactly the bullet-cell height, no focus jump. Key set (AppKit traps documented at the `keyDown` head: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop VISIBLE blocks · ⇧↑/⇧↓ extend block selection (anchor↔focus highlight, batch structural ops; bare arrows/click/typing clear) · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Folds are session-scoped view state (`folded: Set<UUID>`, reset on every load — never serializes, ADR-0013). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` (debounce/⌘S/#67 conflict unchanged) or `onDraftEdit` for drafts; focus follows node IDs (they travel through ops), caret lands via `pendingCaret` at next mount. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner (⌘S/toolbar/conflict/reading toggle all keep working — reading renders the serialized markdown via apex unchanged); `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions (`PostsModel.lastDraftWasOutline` covers the rescan lag after a fresh save; cleared in newPost/select/openExternal wherever the draft dies).
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. **#112 drag primitives:** `extract(_:path:)` (remove + return a whole subtree) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append) over private `withChildren` — id-preserving like every op; the presenter sequences them for drops. Folds live in the view, keyed by node UUID — never modeled here.
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
+484
View File
@@ -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
}
}
+372 -242
View File
@@ -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)
}
}
+196
View File
@@ -0,0 +1,196 @@
//
// OutlineRowTextView.swift
// Museion
//
// #109: the outliner's promoted row editor — the ONE live NSTextView on
// the focused row (native undo/IME, rust caret, wrapping at the column
// width), plus RowTextView's structural key interception. Extracted from
// OutlineEditorView.swift in #112; the key set and AppKit traps are
// documented at the keyDown head.
//
import AppKit
import SwiftUI
// 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)
}
}
+43
View File
@@ -170,6 +170,49 @@ nonisolated enum OutlineTree {
return moved
}
/// #112 drag primitive: remove and return the whole subtree at `path`
/// (nil when the path doesn't resolve). The drag engine pulls moving
/// blocks out one at a time, re-resolving paths by id between pulls.
static func extract(_ nodes: inout [OutlineNode], path: [Int]) -> OutlineNode? {
var extracted: OutlineNode?
_ = withSiblings(of: path, in: &nodes) { siblings, index in
extracted = siblings.remove(at: index)
return true
}
return extracted
}
/// #112 drag primitive: insert `run` as consecutive siblings at `index`
/// in the children of `parentPath` (empty = the root array). The index
/// clamps to count (append); empty runs are refused. False when the
/// parent doesn't resolve.
@discardableResult
static func insertRun(
_ run: [OutlineNode], parentPath: [Int], index: Int, in nodes: inout [OutlineNode],
) -> Bool {
guard !run.isEmpty else { return false }
return withChildren(of: parentPath, in: &nodes) { siblings in
let slot = min(max(index, 0), siblings.count)
siblings.insert(contentsOf: run, at: slot)
return true
}
}
/// Runs `body` on the children array of the node at `path` (the root
/// array for an empty path). False when the path doesn't resolve.
private static func withChildren(
of path: [Int], in nodes: inout [OutlineNode], _ body: (inout [OutlineNode]) -> Bool,
) -> Bool {
if path.isEmpty {
return body(&nodes)
}
guard let first = path.first, nodes.indices.contains(first) else { return false }
let rest = Array(path.dropFirst())
return rest.isEmpty
? body(&nodes[first].children)
: withChildren(of: rest, in: &nodes[first].children, body)
}
/// Tab. Node at `path` becomes the LAST child of its previous sibling.
/// No previous sibling → no-op, returns nil.
static func indent(_ nodes: inout [OutlineNode], path: [Int]) -> [Int]? {