diff --git a/AGENTS.md b/AGENTS.md index 623f8e0..145142f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (2998 symbols, 8543 relationships, 240 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (3209 symbols, 9400 relationships, 267 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -177,6 +177,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-10-16 | [20261016-issue112-outline-interaction-ii_log.md](docs/devlog/20261016-issue112-outline-interaction-ii_log.md) | | 2026-10-15 | [20261015-issue111-outline-guard_log.md](docs/devlog/20261015-issue111-outline-guard_log.md) | | 2026-10-15 | [20261015-issue109-outline-type-outliner_log.md](docs/devlog/20261015-issue109-outline-type-outliner_log.md) | | 2026-10-13 | [20261013-issue108-library-ui-archive-audits_log.md](docs/devlog/20261013-issue108-library-ui-archive-audits_log.md) | @@ -186,11 +187,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 2026-10-09 | [20261009-issue87-focus-mode_log.md](docs/devlog/20261009-issue87-focus-mode_log.md) | | 2026-10-08 | [20261008-issue84-view-menu-doubled_log.md](docs/devlog/20261008-issue84-view-menu-doubled_log.md) | | 2026-10-08 | [20261008-issue83-save-indicator-honesty_log.md](docs/devlog/20261008-issue83-save-indicator-honesty_log.md) | -| 2026-10-08 | [20261008-issue77-editing-parity_log.md](docs/devlog/20261008-issue77-editing-parity_log.md) | -| 2026-10-06 | [20261006-issue76-apex-html-reading_log.md](docs/devlog/20261006-issue76-apex-html-reading_log.md) | -| 2026-10-05 | [20261005-issue71-reading-toggle_log.md](docs/devlog/20261005-issue71-reading-toggle_log.md) | -| 2026-10-03 | [20261003-issue19-editor-core_log.md](docs/devlog/20261003-issue19-editor-core_log.md) | -| 2026-10-03 | [20261003-issue18-post-lifecycle_log.md](docs/devlog/20261003-issue18-post-lifecycle_log.md) | -| 2026-10-01 | [20261001-issue17-home-posts-list_log.md](docs/devlog/20261001-issue17-home-posts-list_log.md) | -| 2026-10-01 | [20261001-issue55-verdict-substrate-adr-0010_log.md](docs/devlog/20261001-issue55-verdict-substrate-adr-0010_log.md) | | 2026-09-25 | [20260925-issue50-profile-backup-s2-6_log.md](docs/devlog/20260925-issue50-profile-backup-s2-6_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 44a73d8..ce546a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Added +- **outline:** drag-reorder + zoom-in (v1.2 S6) — pointer-drag a block run into any sibling seam or onto a block to nest as its child (the block selection rides the drag, a 30/40/30 fat-gap hit test resolves seams vs onto, and a dropped run on an invalid target leaves the document untouched); Esc cancels mid-drag, the moved run becomes the selection; double-click any bullet zooms to its children with breadcrumbs back out, and zoom keeps only fully-visible selections (issue #112) + - **outline:** mixed-content open guard (v1.2 S7) — opening a `type: outline` piece whose body has paragraph lines between bullets (the parse would drop them on the next save) now asks first: Open in Prose (default — everything visible, nothing drops), Open as Outline (explicit consent — saves normalize as before), or Cancel; the ask presents over an empty editor so nothing can edit before the choice, re-clicking the open piece never re-asks, and a draft or guest staged during the ask displaces it cleanly (issue #111) - **outline:** outliner surface & outline type (v1.1 S3, ADR-0013 per #105 variant B) — File ▸ New Outline ⇧⌘N stages a `type: outline` piece; the outliner is a dedicated block surface: nested bullets with LogSeq-style keys (Tab/⇧Tab indent/outdent, ⌥↑/⌥↓ move subtree, ↑/↓ hop visible blocks, ⇧↑/⇧↓ block-select runs, ⌘↑/⌘↓ fold/unfold, Enter splits at the caret), one live caret row over inert rows, session-scoped folds, and the same debounced autosave / ⌘S / external-change alert as prose; hand-edited files parse leniently and normalize on save (issue #109) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index af47f80..c942eca 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -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///post.md` AND `archive///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//` — 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 disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — 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//`), 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(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). -- `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`, 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/` 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. diff --git a/Museion/OutlineDrag.swift b/Museion/OutlineDrag.swift new file mode 100644 index 0000000..f1c979a --- /dev/null +++ b/Museion/OutlineDrag.swift @@ -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 + } +} diff --git a/Museion/OutlineEditorView.swift b/Museion/OutlineEditorView.swift index 5135753..2918bd7 100644 --- a/Museion/OutlineEditorView.swift +++ b/Museion/OutlineEditorView.swift @@ -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) -> [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, 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]? { - 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, 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) - } -} diff --git a/Museion/OutlineRowTextView.swift b/Museion/OutlineRowTextView.swift new file mode 100644 index 0000000..6e4a73f --- /dev/null +++ b/Museion/OutlineRowTextView.swift @@ -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) + } +} diff --git a/Museion/OutlineTree.swift b/Museion/OutlineTree.swift index f029f5f..0ced67b 100644 --- a/Museion/OutlineTree.swift +++ b/Museion/OutlineTree.swift @@ -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]? { diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 379ad53..026f672 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -28,9 +28,10 @@ Owned by the root AGENTS.md contract. - `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit. - `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0. - `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts//post.md` (#107). -- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet. -- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting). -- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (the monitor itself can't run in the test host — no running NSApp loop). +- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet. **#112:** extract/insertRun pins — subtree pull by path (ids travel, bad paths nil), sibling splices at any parent (index clamp-to-append, contiguous run order, unresolvable parent false + untouched, empty run refused). +- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting). **#112 (S6):** nine pins — `draggedIDs` dedup (selection rides, ancestor carries descendants, unselected/no-selection go solo), `isValidDrop` (ref moving / inside moving subtree / own-parent-legal / unknown), precise `before`/`afterLast`/`lastChild` landings (incl. the seam-below-a-deeper-follower FIRST-child nest and cross-parent extraction that keyboard batches refuse), contiguous deduped batch landing with id travel, origin no-ops + invalid refusals (snapshot equality — storage untouched), zoom projection (children rooted, depths re-based, zoom root's fold ignored, inner folds still hide, unknown id → whole doc), `rangeIDs` nil across the zoom boundary, and `hitTestDrop` fat-gap bands (30/40/30, ±6 into edge rows, window-space y-up frames, empty rows nil). +- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (monitors DO fire in the host on `NSApp.sendEvent`, but only for events carrying a real window number — see `OutlineDragTests`). +- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders. - ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `
    ` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013). ## Verification diff --git a/MuseionTests/OutlineDragTests.swift b/MuseionTests/OutlineDragTests.swift new file mode 100644 index 0000000..248fb1a --- /dev/null +++ b/MuseionTests/OutlineDragTests.swift @@ -0,0 +1,105 @@ +// +// OutlineDragTests.swift +// MuseionTests +// +// #112 pins for the drag plumbing's lifetime + geometry contracts. +// The gesture must be self-contained from arm time on: the tracker +// holds its own copies of the callbacks (nothing reads the catcher's +// state at fire time), so a mid-drag scroll that drops the origin row +// out of the lazy stack cannot strand the surface's drag state. +// (The dealloc itself can't be reproduced in this harness — AppKit +// keeps extra internal retains on any once-installed view — so the +// pin swaps the callbacks AFTER arming: only an arm-time snapshot +// fires.) Also pinned: rowFrames reports the grip catcher's full-row +// frame (not the body catcher's text-only frame) regardless of +// subview order, and arming a second drag cancels a stuck +// predecessor instead of stacking trackers. Monitors fire on +// NSApp.sendEvent — but only for events carrying a real window +// number (window-0 events never reach monitors; probe-pinned). +// +import AppKit +@testable import Museion +import Testing + +@MainActor +@Suite(.serialized) +struct OutlineDragTests { + private func makeWindow() -> NSWindow { + NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 300), + styleMask: [.titled], backing: .buffered, defer: false) + } + + private func mouseEvent(_ type: NSEvent.EventType, in window: NSWindow) -> NSEvent? { + NSEvent.mouseEvent(with: type, location: NSPoint(x: 20, y: 280), modifierFlags: [], + timestamp: 0, windowNumber: window.windowNumber, context: nil, + eventNumber: 0, clickCount: 1, pressure: 1) + } + + @Test func `the tracker holds its own callbacks - a post-arm swap never fires`() throws { + let window = makeWindow() + var armTime = 0 + var swappedIn = 0 + let catcher = CatcherView() + catcher.kind = .grip // grip drags always arm — no selection dance + catcher.frame = NSRect(x: 0, y: 273, width: 300, height: 27) + catcher.onDragEnded = { _, _ in armTime += 1 } + window.contentView?.addSubview(catcher) + + // arm (installs the tracker; its monitors retain it) + try catcher.mouseDown(with: #require(mouseEvent(.leftMouseDown, in: window))) + + // the origin row dematerializes and SwiftUI re-sets the catcher's + // closures — a gesture that read live view state at fire time + // would now target the wrong (or gone) row + catcher.onDragEnded = { _, _ in swappedIn += 1 } + + // mouse-up must end the gesture through the ARM-TIME callbacks + try NSApp.sendEvent(#require(mouseEvent(.leftMouseUp, in: window))) + #expect(armTime == 1) + #expect(swappedIn == 0) + } + + @Test func `arming a second drag cancels a stuck predecessor`() throws { + let window = makeWindow() + var firstEnded = 0 + let first = CatcherView() + first.kind = .grip + first.onDragEnded = { _, _ in firstEnded += 1 } + window.contentView?.addSubview(first) + try first.mouseDown(with: #require(mouseEvent(.leftMouseDown, in: window))) + + let second = CatcherView() + second.kind = .grip + window.contentView?.addSubview(second) + try second.mouseDown(with: #require(mouseEvent(.leftMouseDown, in: window))) + + // the predecessor resolved as a cancel instead of stacking + #expect(firstEnded == 1) + + // end the live gesture so no monitors outlive the test + try NSApp.sendEvent(#require(mouseEvent(.leftMouseUp, in: window))) + } + + @Test func `rowFrames prefers the grip frame regardless of subview order`() { + let window = makeWindow() + let id = UUID() + let grip = CatcherView() + grip.kind = .grip + grip.rowID = id + grip.frame = NSRect(x: 0, y: 0, width: 300, height: 27) // full row + let body = CatcherView() + body.kind = .body + body.rowID = id + body.frame = NSRect(x: 0, y: 2, width: 300, height: 23) // text only + + window.contentView?.addSubview(body) // reverse of declaration order + window.contentView?.addSubview(grip) + #expect(CatcherView.rowFrames(in: window)[id] == grip.convert(grip.bounds, to: nil)) + + grip.removeFromSuperview() + body.removeFromSuperview() + window.contentView?.addSubview(grip) // declaration order + window.contentView?.addSubview(body) + #expect(CatcherView.rowFrames(in: window)[id] == grip.convert(grip.bounds, to: nil)) + } +} diff --git a/MuseionTests/OutlinePresenterTests.swift b/MuseionTests/OutlinePresenterTests.swift index 52ac17e..50482cf 100644 --- a/MuseionTests/OutlinePresenterTests.swift +++ b/MuseionTests/OutlinePresenterTests.swift @@ -7,6 +7,7 @@ // through deep trees, and setText mutation by node identity. // +import CoreGraphics import Foundation @testable import Museion import Testing @@ -170,4 +171,200 @@ struct OutlinePresenterTests { #expect(outNodes.map(\.text) == ["a", "a1", "a2", "a3"]) #expect(outNodes[1...].allSatisfy { node in node.children.isEmpty }) } + + // #112 (S6): drag-reorder + zoom over the presenter. + + @Test func `draggedIDs rides the selection deduped or goes solo`() { + let tree = [node("a", [node("a1", [node("a1x")]), node("a2")]), node("b"), node("c")] + + // grab a selected row → the whole selection rides, preorder order, + // a selected ancestor carries its selected descendants + let sel = [tree[0].id, tree[0].children[0].id, tree[2].id] + #expect( + OutlinePresenter.draggedIDs(grabbing: tree[0].id, selected: sel, in: tree) + == [tree[0].id, tree[2].id], + ) + + // grab an UNselected row while a selection exists → solo + #expect( + OutlinePresenter.draggedIDs(grabbing: tree[1].id, selected: sel, in: tree) + == [tree[1].id], + ) + + // no selection at all → solo, works at any depth + #expect( + OutlinePresenter.draggedIDs(grabbing: tree[0].children[1].id, selected: nil, in: tree) + == [tree[0].children[1].id], + ) + } + + @Test func `isValidDrop rejects refs at or inside the moving run`() { + let tree = [node("a", [node("a1", [node("a1x")]), node("a2")]), node("b")] + + // the ref itself moves + #expect(!OutlinePresenter.isValidDrop(moving: [tree[1].id], target: .before(tree[1].id), in: tree)) + // the ref sits inside a moving subtree (any depth) + #expect(!OutlinePresenter.isValidDrop(moving: [tree[0].id], target: .lastChild(tree[0].children[0].id), in: tree)) + #expect(!OutlinePresenter.isValidDrop( + moving: [tree[0].children[0].id], + target: .before(tree[0].children[0].children[0].id), + in: tree, + )) + // dropping back into one's own PARENT as its last child is legal — + // extraction happens first, the target never ends up inside the run + #expect(OutlinePresenter.isValidDrop(moving: [tree[0].children[0].id], target: .lastChild(tree[0].id), in: tree)) + // an unrelated row is fine + #expect(OutlinePresenter.isValidDrop(moving: [tree[0].id], target: .before(tree[1].id), in: tree)) + // unknown ref → invalid + #expect(!OutlinePresenter.isValidDrop(moving: [tree[0].id], target: .before(UUID()), in: tree)) + } + + @Test func `applyDrop lands before afterLast and lastChild precisely`() { + // before: b moves up, directly before a + var beforeNodes = OutlineTree.parse("- a\n- b\n- c").nodes + #expect(OutlinePresenter.applyDrop(.before(beforeNodes[0].id), moving: [beforeNodes[1].id], in: &beforeNodes)) + #expect(beforeNodes.map(\.text) == ["b", "a", "c"]) + + // afterLast: the end-of-list seam — lands after the LAST row at + // its depth, subtree pulled whole + var afterNodes = OutlineTree.parse("- a\n- b\n - b1\n- c").nodes + let movingID = afterNodes[0].id + #expect(OutlinePresenter.applyDrop(.afterLast(afterNodes[2].id), moving: [movingID], in: &afterNodes)) + #expect(afterNodes.map(\.text) == ["b", "c", "a"]) + + // lastChild: onto — appended AFTER existing children (never first) + var ontoNodes = OutlineTree.parse("- a\n - a1\n- b").nodes + let bID = ontoNodes[1].id + #expect(OutlinePresenter.applyDrop(.lastChild(ontoNodes[0].id), moving: [bID], in: &ontoNodes)) + #expect(ontoNodes.map(\.text) == ["a"]) + #expect(ontoNodes[0].children.map(\.text) == ["a1", "b"]) + + // a seam below a deeper follower nests: dropping before a's first + // child (the seam between a and a1) makes it the FIRST child + var nestNodes = OutlineTree.parse("- a\n - a1\n- b").nodes + let a1ID = nestNodes[0].children[0].id + #expect(OutlinePresenter.applyDrop(.before(a1ID), moving: [nestNodes[1].id], in: &nestNodes)) + #expect(nestNodes.map(\.text) == ["a"]) + #expect(nestNodes[0].children.map(\.text) == ["b", "a1"]) + } + + @Test func `applyDrop moves a deduped batch as one contiguous run`() { + // a (with a1) and c selected together → they land adjacent, a + // before c, a's subtree riding inside + var nodes = OutlineTree.parse("- a\n - a1\n- b\n- c").nodes + let aID = nodes[0].id + let cID = nodes[2].id + #expect(OutlinePresenter.applyDrop(.afterLast(nodes[1].id), moving: [aID, cID], in: &nodes)) + #expect(nodes.map(\.text) == ["b", "a", "c"]) + #expect(nodes[1].children.map(\.text) == ["a1"]) + + // ids travel — focus/selection can follow the run + #expect(nodes[1].id == aID && nodes[2].id == cID) + } + + @Test func `applyDrop no-ops a drop back at origin and refuses invalid targets`() { + // b is ALREADY immediately before c — extract + insert-before-c + // reproduces the tree → no-op, storage untouched + var nodes = OutlineTree.parse("- a\n- b\n- c").nodes + let snapshot = nodes + #expect(!OutlinePresenter.applyDrop(.before(nodes[2].id), moving: [nodes[1].id], in: &nodes)) + #expect(nodes == snapshot) // storage untouched + + // onto own subtree — invalid, dashed-indicator case + var selfNodes = OutlineTree.parse("- a\n - a1").nodes + let selfSnapshot = selfNodes + #expect(!OutlinePresenter.applyDrop(.lastChild(selfNodes[0].children[0].id), moving: [selfNodes[0].id], in: &selfNodes)) + #expect(selfNodes == selfSnapshot) + + // dropping onto one's own parent when ALREADY its last child → no-op + var tailNodes = OutlineTree.parse("- a\n - a1\n - a2").nodes + let tailSnapshot = tailNodes + #expect(!OutlinePresenter.applyDrop(.lastChild(tailNodes[0].id), moving: [tailNodes[0].children[1].id], in: &tailNodes)) + #expect(tailNodes == tailSnapshot) + } + + @Test func `applyDrop crosses parents through a drag`() { + // keyboard batch moves stay sibling-only; a drag is atomic + // extract+splice, so a1 can leave a and land among the roots + var nodes = OutlineTree.parse("- a\n - a1\n- b").nodes + let a1ID = nodes[0].children[0].id + #expect(OutlinePresenter.applyDrop(.before(nodes[1].id), moving: [a1ID], in: &nodes)) + #expect(nodes.map(\.text) == ["a", "a1", "b"]) + #expect(nodes[0].children.isEmpty) + } + + @Test func `visibleRows zoom roots at the node with depths rebased`() { + let tree = [node("a", [node("a1", [node("a1x")]), node("a2")]), node("b")] + + let rows = OutlinePresenter.visibleRows(tree, folded: [], zoomRootID: tree[0].id) + #expect(rows.map(\.text) == ["a1", "a1x", "a2"]) + #expect(rows.map(\.depth) == [0, 1, 0]) // depth 2 re-based to 0 + + // the zoom root's own fold is ignored while it IS the root — + // its children are the document now + let folded = OutlinePresenter.visibleRows(tree, folded: [tree[0].id], zoomRootID: tree[0].id) + #expect(folded.map(\.text) == ["a1", "a1x", "a2"]) + + // folding INSIDE the zoom still hides + let inner = OutlinePresenter.visibleRows(tree, folded: [tree[0].children[0].id], zoomRootID: tree[0].id) + #expect(inner.map(\.text) == ["a1", "a2"]) + #expect(inner[0].foldedDescendantCount == 1) + + // unknown zoom id → the whole document + #expect( + OutlinePresenter.visibleRows(tree, folded: [], zoomRootID: UUID()).map(\.text) + == ["a", "a1", "a1x", "a2", "b"], + ) + } + + @Test func `rangeIDs under zoom is nil across the zoom boundary`() { + let tree = [node("a", [node("a1")]), node("b")] + + // a is outside the zoom rooted at a — invisible → nil + #expect(OutlinePresenter.rangeIDs( + from: tree[0].id, + to: tree[1].id, + in: tree, + folded: [], + zoomRootID: tree[0].id, + ) == nil) + + // both ends inside → the span still works + #expect(OutlinePresenter.rangeIDs( + from: tree[0].children[0].id, + to: tree[0].children[0].id, + in: tree, + folded: [], + zoomRootID: tree[0].id, + ) == [tree[0].children[0].id]) + } + + @Test func `hitTestDrop follows the fat-gap bands`() { + // window-space y-up frames (the only orientation both callers + // feed): a highest at y 60–90, c lowest at 0–30 + let rowA = OutlineNode(text: "a") + let rowB = OutlineNode(text: "b") + let rowC = OutlineNode(text: "c") + let rows = OutlinePresenter.visibleRows([rowA, rowB, rowC], folded: []) + let frames: [UUID: CGRect] = [ + rowA.id: CGRect(x: 0, y: 60, width: 400, height: 30), + rowB.id: CGRect(x: 0, y: 30, width: 400, height: 30), + rowC.id: CGRect(x: 0, y: 0, width: 400, height: 30), + ] + let pairs = rows.compactMap { row in frames[row.id].map { (row, $0) } } + + // pointer visually above a (y 95) → before a + #expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 95), rows: pairs) == .before(rowA.id)) + // top 30% of b (y 55, rel 1/6 from the top) → the seam above b + #expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 55), rows: pairs) == .before(rowB.id)) + // middle 40% of b (y 45) → onto (last child, ring) + #expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 45), rows: pairs) == .lastChild(rowB.id)) + // bottom 30% of b (y 35) → the seam below → before the FOLLOWING row + #expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 35), rows: pairs) == .before(rowC.id)) + // below c (y -10) → after c (end-of-list seam) + #expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: -10), rows: pairs) == .afterLast(rowC.id)) + + // rows without frames are simply unreachable + #expect(OutlinePresenter.hitTestDrop(point: CGPoint(x: 50, y: 45), rows: []) == nil) + } } diff --git a/MuseionTests/OutlineTreeTests.swift b/MuseionTests/OutlineTreeTests.swift index 241f3d5..a979b30 100644 --- a/MuseionTests/OutlineTreeTests.swift +++ b/MuseionTests/OutlineTreeTests.swift @@ -270,4 +270,41 @@ struct OutlineTreeTests { #expect(!OutlineTree.parsesWithLoss("- one\n\n- two\n")) #expect(!OutlineTree.parsesWithLoss("")) } + + // #112 (S6): the drag primitives — extract + insertRun. + + @Test func `extract removes and returns the whole subtree by path`() { + var nodes = OutlineTree.parse("- a\n - a1\n- b").nodes + let extracted = OutlineTree.extract(&nodes, path: [0]) + #expect(extracted?.text == "a") + #expect(extracted?.children.map(\.text) == ["a1"]) + #expect(nodes.map(\.text) == ["b"]) + // ids travel — the drag run re-inserts the same identities + #expect(extracted?.children[0].id != nil) + // unresolvable paths are nil no-ops + #expect(OutlineTree.extract(&nodes, path: [5]) == nil) + #expect(nodes.map(\.text) == ["b"]) + } + + @Test func `insertRun splices siblings at any parent and clamps the index`() { + var nodes = OutlineTree.parse("- a\n - a1\n- b").nodes + + // into the root, before b + #expect(OutlineTree.insertRun([OutlineNode(text: "x")], parentPath: [], index: 1, in: &nodes)) + #expect(nodes.map(\.text) == ["a", "x", "b"]) + + // a nested parent; index clamps to count (append) + #expect(OutlineTree.insertRun([OutlineNode(text: "a2")], parentPath: [0], index: 99, in: &nodes)) + #expect(nodes[0].children.map(\.text) == ["a1", "a2"]) + + // a whole run lands contiguous, in order + let run = [OutlineNode(text: "r1"), OutlineNode(text: "r2")] + #expect(OutlineTree.insertRun(run, parentPath: [], index: 0, in: &nodes)) + #expect(nodes.map(\.text) == ["r1", "r2", "a", "x", "b"]) + + // unresolvable parent → false, untouched; empty run refused + #expect(!OutlineTree.insertRun([OutlineNode(text: "z")], parentPath: [7], index: 0, in: &nodes)) + #expect(!OutlineTree.insertRun([], parentPath: [], index: 0, in: &nodes)) + #expect(nodes.map(\.text) == ["r1", "r2", "a", "x", "b"]) + } } diff --git a/docs/devlog/20261016-issue112-outline-interaction-ii_log.md b/docs/devlog/20261016-issue112-outline-interaction-ii_log.md new file mode 100644 index 0000000..6f35668 --- /dev/null +++ b/docs/devlog/20261016-issue112-outline-interaction-ii_log.md @@ -0,0 +1,82 @@ +# Build S6: outliner interaction II — drag-reorder + zoom-in/focus-subtree + +> **Date:** 2026-10-16 +> **Type:** issue +> **Reference:** [#112](https://git.babylondreams.de/AlexKucera/Museion/issues/112) (map [#110](https://git.babylondreams.de/AlexKucera/Museion/issues/110), calibrated by P1 [#113]) + +## Goal + +Land S6 of the Outliner II map: pointer drag-reorder of blocks (with subtrees, batch-aware) and zoom-in/focus-subtree in the outline editor, exactly per the wf113 prototype verdict — variant A "fat gaps": 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, and 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. + +## What Was Done + +- **`OutlineTree` drag primitives** — `extract(_:path:)` (remove + return a subtree by path) and `insertRun(_:parentPath:index:in:)` (splice consecutive siblings at any parent, index clamps to append), over a new private `withChildren` accessor. Both path-addressed, id-preserving, like every other op there. +- **`OutlinePresenter` drop math** (pure, in `OutlineDrag.swift` as a `nonisolated extension`): `DropTarget` (`before`/`afterLast`/`lastChild`, all id-referenced), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract in reverse document order → re-resolve the anchor id in the mutated tree → splice as one contiguous run; no-op drops restore the snapshot and return false), `hitTestDrop` (the fat-gap 30/40/30 bands, ±6 tolerance into the edge rows, y-up window and y-down frames both handled via orientation auto-detect). +- **Zoom in the projection**: `visibleRows`/`rangeIDs` take `zoomRootID` — the walk roots 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. +- **View surface** (`OutlineEditorView`): zoom stack + breadcrumb chrome ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, "here" inert), double-click-any-bullet zooms in (the double-click's two clicks round-trip the fold toggle, net state unchanged), Esc stack = drag-cancel → selection-collapse → zoom-out-one; the 20pt left margin became the 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 when the row is in the selection), drop indicators (2px rust seam line at the future bullet column, 2px ring for onto, dashed + muted when invalid), the moving run lifts to 0.3 opacity, and a successful drop selects the run (anchor = first, focus = last). +- **Drag plumbing** (`OutlineDrag.swift`): one transparent `CatcherView` NSView per row (`.grip` / `.body`) with a 4px click/drag threshold, then monitor-owned tracking — local monitor for dragged/up/Esc, global for dragged/up outside the app. No system dragging session: Esc-cancel can never resolve as a drop, and there is no destination dance. Live row geometry comes from a view-tree walk (`CatcherView.rowFrames(in:)`) reading CURRENT window-space frames on every pointer event — scroll-proof and SDK-proof. +- **`OutlineRowTextView.swift` split out** (the promoted row editor + `RowTextView`, unchanged code) to hold `OutlineEditorView.swift` under swiftlint's file/type length ceilings; the zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (private state stays file-scoped — the PostsModel posture). +- **Tests**: OutlineTreeTests gains the extract/insertRun pins; OutlinePresenterTests gains nine — dragged run dedup, validity rules, precise before/afterLast/lastChild landings (incl. the seam-below-a-deeper-follower nest and cross-parent moves), contiguous batch landing, origin no-ops, zoom projection/rebased depths/fold interplay/rangeIDs boundary, and the fat-gap band geometry (both coordinate orientations). +- **Test targets un-broken**: 8e70f69 bumped the app to `MACOSX_DEPLOYMENT_TARGET = 27.0` but left MuseionTests/UITests at 26.5 — tests could not even compile against the 27.0 module. All six configs now say 27.0 (a plain build-setting edit, the sanctioned pbxproj change). + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Variant A fat gaps, exactly as calibrated | The P1 verdict (2026-10-16): complete position coverage via ONE insert rule + ONE nest rule — cheapest presenter math, most predictable at speed; drag is the secondary affordance in a keyboard-first app. | +| Monitor-owned drag instead of `NSDraggingSession` | A system session gives no way to distinguish Esc-cancel from drop-over-nothing (both end with operation `[]` and no destination accepted) — an Esc could apply a move. Hand-rolled local+global monitors own every transition; the global monitor supplies the mouse capture a session would give. | +| Geometry from an AppKit view-tree walk, not SwiftUI spaces | SwiftUI 27 removed `.window` from `CoordinateSpaceProtocol` (only `.local`/`.global`/`.named` remain); cached frames also go stale on scroll. The catchers ARE NSViews at the row positions, so a live walk reads current window frames every event — stable and always fresh. | +| Drop math on ids, anchor re-resolved after extraction | The applyBatch re-resolve discipline: indices shift while extracting, ids never do. Extraction runs in reverse document order so earlier paths stay valid without re-resolution. | +| No-op drops restore the snapshot | "Drop back at origin" must leave storage untouched (the guard contract): compare the result tree to the snapshot, restore + return false when equal. | +| Zoom roots at the node's CHILDREN, node's fold ignored | The prototype's projection (`walk(base.children, 0)`): the zoom root becomes the breadcrumb, its children are the document. | +| Esc order: drag → selection → zoom | The prototype's keydown order; the drag's own monitor is installed after the surface's Esc monitor, so it runs first (last-installed wins). | +| Same-file `extension OutlineEditorView` for handlers | swiftlint `type_body_length` (350); extensions are measured separately, private state stays visible in-file. The PostsModel posture, applied to a view. | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Random subsets of unrelated tests "failed (0.000 seconds)" across runs, `Crash: Museion at Runner._applyScopingTraits` | One test's `fatalError` (my `nodes[3]` on a 3-root parse) killed the shared Swift Testing runner process; everything in flight in that process reported failed | Fixed the index; parallel runs went green once nothing crashed | +| `compiling for macOS 26.5, but module 'Museion' has a minimum deployment target of macOS 27.0` | 8e70f69 bumped only the app target; MuseionTests/UITests still built for 26.5 | All six `MACOSX_DEPLOYMENT_TARGET` configs → 27.0 | +| `type 'CoordinateSpaceProtocol' has no member 'window'` | SwiftUI 27 dropped the `.window` space from the protocol | Geometry via the AppKit view-tree walk (see decisions) | +| hitTestDrop edge bands dead-ended (points 1–6pt above the first row returned nil) | Sign error: I read the prototype's `py < first.top + 6` as "more than 6pt beyond the edge" instead of "within/over the edge ±6" — and window coords are y-up, flipping both comparisons | Tolerance reaches INTO the edge row; orientation auto-detected from first/last frames; both orientations test-pinned | +| Seam indicator drew half a row LOW — through the middle of the block below the hovered gap (live dogfood, 2026-10-16) | `seamLine`'s `Color.clear` spacer was height-flexible: the HStack expanded to the full row height and vertically CENTERED the 2pt bar, so the row's `.frame(alignment: .top/.bottom)` had nothing to align | Pin the spacer's height to 2 — the HStack now stays 2pt tall and the frame alignment puts the line exactly on the row edge | +| `NSWindow has no member 'convert'` | The screen-point API is `convertPoint(fromScreen:)` in this SDK | Renamed | +| `nonisolated extension` needed for the presenter extension in OutlineDrag.swift | Default-MainActor project: extension members would be MainActor-isolated while tests call them synchronously | `nonisolated extension OutlinePresenter` (Swift 6.1+) | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/OutlineTree.swift` | `extract` + `insertRun` drag primitives, `withChildren` accessor | +| `Museion/OutlineEditorView.swift` | #112 surface: zoom stack + breadcrumb, grip cell, body catchers, drop indicators, lifted run, Esc stack, ⇧click extend; zoom-aware projection calls; handlers in a same-file extension | +| `Museion/OutlineDrag.swift` (new) | `OutlineDragCatcher`/`CatcherView` (grip + body), `DragTracker` monitors, presenter drop-math extension, `DragInfo`/`DropGeometry`/`HLine` | +| `Museion/OutlineRowTextView.swift` (new) | The promoted row editor + `RowTextView`, extracted unchanged from OutlineEditorView.swift | +| `Museion.xcodeproj/project.pbxproj` | Test/UITest deployment targets 26.5 → 27.0 (aligned with 8e70f69) | +| `MuseionTests/OutlineTreeTests.swift` | extract/insertRun pins | +| `MuseionTests/OutlinePresenterTests.swift` | Nine #112 pins: dedup, validity, landings, batches, no-ops, zoom, fat-gap geometry | +| `Museion/ProfileBackup.swift`, `Museion/ReadingPresenter.swift`, `Museion/ReadingSurface.swift`, `MuseionTests/ProfileBackupTests.swift`, `spike/*`, `prototypes/GateUIPrototype.swift` | SwiftFormat drift from the house `swiftformat .` pass (pre-existing formatting lag, no semantic change) | + +## Open Items & Next Steps + +- [ ] Map #110 continues: S4 Convert to Post (#114) and S5 prose-list shortcuts (#115) remain open on the frontier. +- [ ] Commit + push pending authorization (house rule: never commit autonomously). The slice spans the files above plus the devlog and DOX updates. +- [ ] Known ceilings (ponytail-marked in code): no auto-scroll mid-drag (edge timer is the upgrade path); no floating ghost chip (lifted rows + indicators carry the feedback — the prototype's ghost was calibration chrome); click-to-focus still lands the caret at the row end. +- [ ] Interaction-level feel (pointer drag, zoom chrome) was calibrated live at the P1 prototype and the math is unit-pinned, but the landed AppKit wiring has not been hand-driven in a running app yet — worth a minute of dogfooding before closing the map. + +## Session audit (finish-audit pass) + +Three fresh-context reviewers (ponytail / security / general) over the working-tree diff. Accepted and fixed, each behind a pin (`MuseionTests/OutlineDragTests.swift`, new): + +- **Drag lifetime (Medium)** — `armDrag` closures held the catcher weakly; a mid-drag scroll could drop the origin row's catcher and strand the surface's `drag` state (lifted rows, stale chrome) at mouse-up. Window + callbacks are now captured strongly at arm time; pinned by a post-arm callback swap (the old code fails the pin — verified live). +- **Tracker stacking (Info)** — `DragTracker.current` finishes a never-ended predecessor as a cancel on the next arming; pinned. +- **rowFrames grip preference (Low)** — the full-row GRIP frame now wins over the body catcher's text-only frame regardless of subview visit order; pinned both orders. +- **hitTestDrop y-up only (lean)** — the y-down auto-detect was prototype carryover (both callers feed window geometry); deleted with its y-down test cases, seam-band assertions ported to y-up. +- **DropGeometry single source (lean)** — the guide-rail Canvas now reads `bulletCenter`/`railUnit` instead of hardcoded 18/11, so seam and rails cannot drift. +- **Catcher closure signatures (lean)** — `payload`/`onClick`/`onShiftClick` no longer echo `rowID` back; they capture the row. + +Probes settled two harness disputes: local NSEvent monitors DO fire on `NSApp.sendEvent`, but only for events with a real window number (window-0 events never reach monitors — the Esc probe doc's "monitors can't run in the host" claim corrected); and once-installed NSViews keep AppKit-internal retains in the host (a dealloc-based pin is not reproducible — the callback-swap pin is the observable). Deferred explicitly: drag undo is its own slice (pre-existing pattern across all structural ops); per-event view-walk cost revisits with the auto-scroll timer (ponytail ceiling already marked); wf113 verdict wiring (post-drop selection, zoom reconcile, Esc order) covered by the planned dogfood pass. Rejected: the `nextEvent`-loop rewrite of DragTracker — unverifiable without interactive drag, and a lost mouse-up across an app switch would hang the loop where the global monitor degrades to a clean cancel. GitNexus: re-indexed; CatcherView impact = CRITICAL (57 dependents) — discharged by full build + full unit suite green + the three pins. + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index f973030..5d6b1ec 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-10-16 | issue | [20261016-issue112-outline-interaction-ii_log.md](20261016-issue112-outline-interaction-ii_log.md) | S6 landed: drag-reorder + zoom in the outliner per wf113 verdict A; AppKit-tree hit-testing; tests un-broken for target 27.0 | | 2026-10-15 | issue | [20261015-issue111-outline-guard_log.md](20261015-issue111-outline-guard_log.md) | #111 mixed-content outline guard: parsesWithLoss + open ask, audit round (reselect/displacement holes pinned) — 179 tests green | | 2026-10-15 | issue | [20261015-issue109-outline-type-outliner_log.md](20261015-issue109-outline-type-outliner_log.md) | #109 outliner: OutlineTree + block surface, LogSeq keys, natural-line-box typography; 170 tests green | | 2026-10-13 | issue | [20261013-issue108-library-ui-archive-audits_log.md](20261013-issue108-library-ui-archive-audits_log.md) | #108 variant-B library + Archive pane + commands, two audit rounds, fold corrected, 144 tests green | diff --git a/ref/prototypes/wf113-drag-zoom-prototype.html b/ref/prototypes/wf113-drag-zoom-prototype.html new file mode 100644 index 0000000..9e8c854 --- /dev/null +++ b/ref/prototypes/wf113-drag-zoom-prototype.html @@ -0,0 +1,666 @@ + + + + + +wf113 — drag + zoom prototype + + + +
    +
    +
    +

    The Long Desk — quarterly essay

    +
    type: outline · prototype wf113 ·
    +
    +
    +
    +
    + +
    +
    + + variant A — + +
    +
    + + + +