feat(outline): drag-reorder + zoom — S6 (#112)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Pointer drag of a block run into any sibling seam or onto a block to nest as its child (wf113 variant A: fat-gap 30/40/30 bands, seam line at the future bullet column); the block selection rides the drag, the moved run becomes the selection, and Esc cancels mid-gesture. Double-click any bullet zooms to its children with breadcrumbs back out. New OutlineTree extract/insertRun splice subtrees id-preserving; the live row's NSTextView moved to OutlineRowTextView. Audit round: the gesture is self-contained from arm time (strong window + callback captures — a mid-drag scroll that drops the origin row cannot strand drag state), a second arming cancels a stuck predecessor, rowFrames prefers the grip frame, hitTestDrop is y-up only, and the rails read DropGeometry. Pinned in OutlineDragTests (monitors fire on sendEvent with a real window number). [Generated by AI]
This commit is contained in:
1 parent
d722820fc8
commit
21e2f27450
14 files changed
+2196
-256
No files matched your search
@@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
|
|||||||
<!-- gitnexus:start -->
|
<!-- gitnexus:start -->
|
||||||
# GitNexus — Code Intelligence
|
# 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).
|
> 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
|
|||||||
<!-- write-log: window-start -->
|
<!-- write-log: window-start -->
|
||||||
| Date | Log |
|
| 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-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-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) |
|
| 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-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-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-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) |<!-- write-log: window-end -->
|
| 2026-09-25 | [20260925-issue50-profile-backup-s2-6_log.md](docs/devlog/20260925-issue50-profile-backup-s2-6_log.md) |<!-- write-log: window-end -->
|
||||||
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
|
|||||||
|
|
||||||
### Added
|
### 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:** 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)
|
- **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)
|
||||||
|
|||||||
+5
-3
@@ -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).
|
- 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).
|
- `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.
|
- 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).
|
- 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.
|
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
|
||||||
@@ -26,8 +26,10 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
|||||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
|
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
|
||||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
|
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
|
||||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was moved." to the flush-routed reason, never replacing it; the session stays up dirty), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(hLine truncated
|
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#111 (S7) mixed-content outline guard:** `select` on a `type: outline` piece whose body `OutlineTree.parsesWithLoss` flags ends the old session, nils the new one, and holds the open (`outlineGuardPieceID`) — the `OutlineGuardSheet` ask (WorkspaceView, house binding pattern) presents over an EMPTY editor so nothing can normalize on ⌘S before the choice; a RESELECT of the already-open piece is a no-op (early return — the guard must never re-fire over a prior answer, which would nil the session without teardown and let the armed debounce flush mid-ask); answers `openGuardedOutlineInProse(home:)` (sets `proseOverridePostID` — a routing override with `lastDraftWasOutline`'s exact lifecycle, cleared in newPost/newOutline/select/openExternal) / `openGuardedOutlineAsOutline(home:)` (consented drop on save) / `cancelOutlineGuard()` (no session, selection cleared; still guarded next open); `outlineGuardPieceID` also dies in newPost/newOutline/openExternal (a draft/guest displaces a held ask — audit); select's tail routes through `openUnguarded` (the one open body; it clears the hold too); `isGuardedOutline` does ONE disk read deriving type (scan-known, else frontmatter) + body via `splitFrontmatter`; guard members live in a file-scope `extension PostsModel` (type_body_length posture). Routing: PostsPaneView suppresses outline for `proseOverridePostID` and renders an inert notice while a guard hold is up. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was moved." to the flush-routed reason, never replacing it; the session stays up dirty), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(hLine truncated
|
||||||
- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. **#111:** `parsesWithLoss(_:)` — true when any non-blank non-item line follows the first item (the drop the mixed-content guard asks about; shares `parseItem` so detector and parser never disagree). Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. Folds live in the view, keyed by node UUID — never modeled here.
|
- `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), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` (borderless NSTextView subclass, native undo/IME, rust caret) on the focused row, static inline-markdown text elsewhere (tap focuses, caret at end — v1 ceiling, ponytail-marked); typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box — the prose CSS-1.8 `lineHeightMultiple` is deliberately absent: an inflated fragment grows the focused row and detaches the bullet; test-pinned), static rows render the same NSFont (no face swap on focus), the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — exactly the bullet-cell height, no focus jump. Key set (AppKit traps documented at the `keyDown` head: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop VISIBLE blocks · ⇧↑/⇧↓ extend block selection (anchor↔focus highlight, batch structural ops; bare arrows/click/typing clear) · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Folds are session-scoped view state (`folded: Set<UUID>`, reset on every load — never serializes, ADR-0013). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` (debounce/⌘S/#67 conflict unchanged) or `onDraftEdit` for drafts; focus follows node IDs (they travel through ops), caret lands via `pendingCaret` at next mount. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner (⌘S/toolbar/conflict/reading toggle all keep working — reading renders the serialized markdown via apex unchanged); `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions (`PostsModel.lastDraftWasOutline` covers the rescan lag after a fresh save; cleared in newPost/select/openExternal wherever the draft dies).
|
- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount; **#112:** `zoomRootID` roots the projection at that node's CHILDREN with depths re-based to 0 — the zoom root's own fold is ignored while it is the root, unknown ids fall back to the whole document; `rangeIDs` is zoom-aware), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count; **#112:** double-click ANY bullet zooms in — the two clicks round-trip the fold toggle, net state unchanged) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` on the focused row (see its own file), static inline-markdown text elsewhere. **#112 (S6, wf113 verdict — variant A "fat gaps"):** the 20pt left margin is a hover-revealed ⋮⋮ grip cell (fills the row height so its frame reads as row geometry); static rows carry a body catcher (click focuses, ⇧click extends the block selection, drag runs when the row is in it); drop chrome = 2px rust seam line with its left edge at the future bullet column (20 + depth·18 + 11) or a 2px ring for onto, dashed + muted when the target is invalid; the moving run lifts to 0.3 opacity; after a drop the moved run IS the selection (anchor = first, focus = last). Zoom chrome = breadcrumb above the rows ("⟵ zoom out" = full out, ancestor crumbs zoom to that node, current crumb inert); Esc stack = drag-cancel → selection-collapse → zoom-out-one (the drag's own monitor runs first — last installed wins); zoom survives only fully-visible selections, focus falls to the projection's first row when it leaves. Zoom/drag state is view-only — never serializes, reset on every load. Key set (AppKit traps documented at the `keyDown` head in OutlineRowTextView.swift: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box), static rows render the same NSFont, the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — the bullet-cell height, no focus jump. The zoom+drag+structure handlers live in a same-file `extension OutlineEditorView` (type_body_length posture — private state stays file-scoped). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` or `onDraftEdit` for drafts; focus follows node IDs; folds are session-scoped view state. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner; `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions.
|
||||||
|
- `OutlineDrag.swift` — #112 (S6) the drag plumbing + drop math: `OutlineDragCatcher`/`CatcherView` (one transparent NSView per row — `.grip` owns the left margin, click focuses / drag always runs; `.body` overlays static row text, ⇧click extends / drag only when the row is in the block selection). 4px threshold separates clicks from drags; past it `DragTracker` owns the gesture via NSEvent monitors (local for dragged/up/Esc, GLOBAL for dragged/up outside the app — mouse capture without a system dragging session, and an Esc-cancel can never resolve as a drop). The gesture is self-contained from arm time: window + callbacks captured STRONGLY in `armDrag` — a mid-drag scroll can drop the origin row's catcher out of the lazy stack, and mouse-up must still clear the surface's drag state (no weak reads of the view at fire time); a `static current` guard finishes a never-ended predecessor as a cancel instead of stacking trackers. Live row geometry = `CatcherView.rowFrames(in:)`, a view-tree walk reading CURRENT window-space frames per pointer event — SwiftUI 27 removed the `.window` coordinate space and cached frames go stale on scroll; AppKit's convert-to-window is the stable truth; the GRIP frame (full row height) wins over the body catcher's text-only frame regardless of visit order. The pure drop math rides here as a `nonisolated extension OutlinePresenter`: `DropTarget` (`.before`/`.afterLast`/`.lastChild`, id-referenced, resolved AFTER extraction — the applyBatch re-resolve discipline; line-insertion semantics mean a drop can never steal siblings), `draggedIDs` (selection rides deduped — a selected ancestor carries its selected descendants), `isValidDrop` (ref at/inside the moving run), `applyDrop` (extract reverse-doc-order → re-resolve anchor by id → splice contiguous; no-op drops restore the snapshot), `hitTestDrop` (fat-gap 30/40/30 bands, ±6 tolerance INTO the edge rows, window-space y-up only — both callers feed window geometry). Plus `DragInfo`, `DropGeometry` (grip 20 / rail 18 / bullet-center 11 = the indicator's bullet-column math; the guide-rail Canvas reads the same constants — seam and rails cannot drift), `HLine` (dashed invalid seam).
|
||||||
|
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
|
||||||
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
|
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
|
||||||
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
|
- `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.
|
- 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.
|
||||||
|
|||||||
@@ -0,0 +1,484 @@
|
|||||||
|
//
|
||||||
|
// OutlineDrag.swift
|
||||||
|
// Museion
|
||||||
|
//
|
||||||
|
// #112 (S6, map #110 — wf113 verdict, variant A "fat gaps"): the
|
||||||
|
// outliner's drag plumbing. One small transparent NSView per row —
|
||||||
|
// `.grip` owns the 20pt left margin (click focuses, drag always runs:
|
||||||
|
// batch when the row is inside the block selection, solo when not),
|
||||||
|
// `.body` overlays static row text (click focuses, ⇧click extends,
|
||||||
|
// drag only when the row is already selected — the live NSTextView row
|
||||||
|
// keeps its native text-selection drag).
|
||||||
|
//
|
||||||
|
// A 4px threshold separates clicks from drags. Past it, a DragTracker
|
||||||
|
// owns the gesture through NSEvent monitors — local for dragged/up/Esc,
|
||||||
|
// global for dragged/up outside the app (mouse capture without a system
|
||||||
|
// dragging session). No session means no destination dance and no
|
||||||
|
// way for an Esc-cancel to resolve as a drop: moved → target updates,
|
||||||
|
// Esc → cancel with no drop, mouse-up anywhere → drop at the point.
|
||||||
|
// The gesture outlives its origin row (strong captures at arm time —
|
||||||
|
// a mid-drag scroll can drop the catcher out of the lazy stack), and
|
||||||
|
// a second arming cancels a stuck predecessor.
|
||||||
|
// The drop math (fat-gap bands, validity, the splice) lives in
|
||||||
|
// OutlinePresenter; the chrome in OutlineEditorView.
|
||||||
|
//
|
||||||
|
|
||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// The per-row drag/click catcher (see file header). Transparent,
|
||||||
|
/// never first responder, draws nothing — it only turns mouse events
|
||||||
|
/// into callbacks. Closures are re-set on every SwiftUI update, so they
|
||||||
|
/// always read the surface's current state.
|
||||||
|
struct OutlineDragCatcher: NSViewRepresentable {
|
||||||
|
enum Kind {
|
||||||
|
/// The left-margin grip: drag always available, click focuses.
|
||||||
|
case grip
|
||||||
|
/// Over static row text: ⇧click extends, drag only when the row
|
||||||
|
/// is inside the block selection, click focuses.
|
||||||
|
case body
|
||||||
|
}
|
||||||
|
|
||||||
|
var kind: Kind
|
||||||
|
var rowID: UUID
|
||||||
|
/// .body only: is the row inside the current block selection?
|
||||||
|
var isInSelection: () -> Bool
|
||||||
|
/// The moving run for a grab of this row (deduped selection or solo).
|
||||||
|
var payload: () -> [UUID]
|
||||||
|
var onClick: () -> Void
|
||||||
|
var onShiftClick: () -> Void
|
||||||
|
var onDragBegan: ([UUID]) -> Void
|
||||||
|
/// Window-space pointer position + live window-space row frames (one
|
||||||
|
/// entry per materialized catcher — grip catchers fill the row's
|
||||||
|
/// height, so their frames ARE row geometry). Fires while the drag
|
||||||
|
/// runs.
|
||||||
|
var onDragMoved: (CGPoint, [UUID: CGRect]) -> Void
|
||||||
|
/// Cancelled drags pass a nil point — no drop is resolved.
|
||||||
|
var onDragEnded: (CGPoint?, [UUID: CGRect]?) -> Void
|
||||||
|
|
||||||
|
func makeNSView(context _: Context) -> CatcherView {
|
||||||
|
let view = CatcherView()
|
||||||
|
apply(to: view)
|
||||||
|
return view
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ view: CatcherView, context _: Context) {
|
||||||
|
apply(to: view)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func apply(to view: CatcherView) {
|
||||||
|
view.kind = kind
|
||||||
|
view.rowID = rowID
|
||||||
|
view.isInSelection = isInSelection
|
||||||
|
view.payload = payload
|
||||||
|
view.onClick = onClick
|
||||||
|
view.onShiftClick = onShiftClick
|
||||||
|
view.onDragBegan = onDragBegan
|
||||||
|
view.onDragMoved = onDragMoved
|
||||||
|
view.onDragEnded = onDragEnded
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The NSView half of the catcher.
|
||||||
|
final class CatcherView: NSView {
|
||||||
|
var kind: OutlineDragCatcher.Kind = .grip
|
||||||
|
var rowID = UUID()
|
||||||
|
var isInSelection: () -> Bool = { false }
|
||||||
|
var payload: () -> [UUID] = { [] }
|
||||||
|
var onClick: () -> Void = {}
|
||||||
|
var onShiftClick: () -> Void = {}
|
||||||
|
var onDragBegan: ([UUID]) -> Void = { _ in }
|
||||||
|
var onDragMoved: (CGPoint, [UUID: CGRect]) -> Void = { _, _ in }
|
||||||
|
var onDragEnded: (CGPoint?, [UUID: CGRect]?) -> Void = { _, _ in }
|
||||||
|
|
||||||
|
override var acceptsFirstResponder: Bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Live window-space frames of every materialized catcher in the
|
||||||
|
/// window, keyed by row id. Walking the real view tree reads CURRENT
|
||||||
|
/// geometry: cached SwiftUI frames go stale on scroll, and the
|
||||||
|
/// SDK's SwiftUI coordinate spaces shift between versions — AppKit's
|
||||||
|
/// convert-to-window is the stable truth. The grip fills its row's
|
||||||
|
/// height, so the GRIP frame is row geometry — it wins over the
|
||||||
|
/// body catcher (text-only frame) regardless of visit order.
|
||||||
|
static func rowFrames(in window: NSWindow) -> [UUID: CGRect] {
|
||||||
|
guard let contentView = window.contentView else { return [:] }
|
||||||
|
var frames: [UUID: CGRect] = [:]
|
||||||
|
var stack: [NSView] = [contentView]
|
||||||
|
while let view = stack.popLast() {
|
||||||
|
if let catcher = view as? CatcherView, catcher.kind == .grip || frames[catcher.rowID] == nil {
|
||||||
|
frames[catcher.rowID] = catcher.convert(catcher.bounds, to: nil)
|
||||||
|
}
|
||||||
|
stack.append(contentsOf: view.subviews)
|
||||||
|
}
|
||||||
|
return frames
|
||||||
|
}
|
||||||
|
|
||||||
|
override func resetCursorRects() {
|
||||||
|
// The grip advertises grabbability; the body stays an arrow.
|
||||||
|
if kind == .grip {
|
||||||
|
addCursorRect(bounds, cursor: .openHand)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override func mouseDown(with event: NSEvent) {
|
||||||
|
let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
|
||||||
|
if kind == .body {
|
||||||
|
if flags.contains(.shift) {
|
||||||
|
onShiftClick()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Body-drag exists only on already-selected rows (wf113);
|
||||||
|
// anywhere else a plain click just focuses the row.
|
||||||
|
guard isInSelection() else {
|
||||||
|
onClick()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
armDrag()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hand the gesture to a DragTracker anchored at the current mouse
|
||||||
|
/// position. Screen points convert to window space here, and every
|
||||||
|
/// moved event carries a fresh frame walk. The window and the
|
||||||
|
/// callbacks are captured STRONGLY — a mid-drag scroll can drop the
|
||||||
|
/// origin row (and this catcher with it) out of the lazy stack, and
|
||||||
|
/// the gesture must still end cleanly at mouse-up or the surface's
|
||||||
|
/// drag state sticks (lifted rows, stale chrome). The callbacks read
|
||||||
|
/// live @State through the struct copy, so capture time is harmless.
|
||||||
|
private func armDrag() {
|
||||||
|
guard let window else { return }
|
||||||
|
let tracker = DragTracker(start: NSEvent.mouseLocation)
|
||||||
|
let payload = payload
|
||||||
|
let onDragBegan = onDragBegan
|
||||||
|
let onDragMoved = onDragMoved
|
||||||
|
let onDragEnded = onDragEnded
|
||||||
|
let onClick = onClick
|
||||||
|
tracker.onActivate = {
|
||||||
|
let run = payload()
|
||||||
|
guard !run.isEmpty else { return false }
|
||||||
|
onDragBegan(run)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
tracker.onMoved = { screenPoint in
|
||||||
|
onDragMoved(
|
||||||
|
window.convertPoint(fromScreen: screenPoint),
|
||||||
|
Self.rowFrames(in: window),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
tracker.onEnded = { screenPoint in
|
||||||
|
onDragEnded(
|
||||||
|
screenPoint.map { window.convertPoint(fromScreen: $0) },
|
||||||
|
Self.rowFrames(in: window),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
tracker.onClicked = { onClick() }
|
||||||
|
tracker.install()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Monitor-owned drag tracking (#112): a 4px threshold promotes the
|
||||||
|
/// held button to a drag; from then on dragged events update the
|
||||||
|
/// target, Esc cancels (no drop), and mouse-up anywhere — including
|
||||||
|
/// outside the app, via the global monitor — ends the gesture.
|
||||||
|
/// The monitor closures retain the tracker, so the gesture always ends
|
||||||
|
/// in finish() → teardown → release; there is no path that leaks.
|
||||||
|
/// A second install() finishes a never-ended predecessor as a cancel,
|
||||||
|
/// so trackers can never stack.
|
||||||
|
/// ponytail: no auto-scroll mid-drag; the upgrade is an edge timer
|
||||||
|
/// driving the same target math.
|
||||||
|
private final class DragTracker {
|
||||||
|
let start: NSPoint
|
||||||
|
/// Threshold crossing: report the moving run, false = nothing
|
||||||
|
/// draggable, the gesture ends quietly.
|
||||||
|
var onActivate: () -> Bool = { false }
|
||||||
|
var onMoved: (NSPoint) -> Void = { _ in }
|
||||||
|
/// nil = cancelled (Esc / activation failure) — no drop.
|
||||||
|
var onEnded: (NSPoint?) -> Void = { _ in }
|
||||||
|
var onClicked: () -> Void = {}
|
||||||
|
|
||||||
|
private var active = false
|
||||||
|
private var finished = false
|
||||||
|
private var monitors: [Any] = []
|
||||||
|
/// The one gesture that may own the monitors; install() cancels a
|
||||||
|
/// stuck predecessor instead of stacking a second tracker.
|
||||||
|
private static var current: DragTracker?
|
||||||
|
|
||||||
|
init(start: NSPoint) {
|
||||||
|
self.start = start
|
||||||
|
}
|
||||||
|
|
||||||
|
func install() {
|
||||||
|
Self.current?.finish(nil)
|
||||||
|
Self.current = self
|
||||||
|
// Strong self-capture: NSEvent → closure → tracker keeps the
|
||||||
|
// gesture alive until finish() removes the monitors. The local
|
||||||
|
// monitor may swallow (nil); the global one only observes —
|
||||||
|
// those events belong to another app.
|
||||||
|
let local = NSEvent.addLocalMonitorForEvents(
|
||||||
|
matching: [.leftMouseDragged, .leftMouseUp, .keyDown],
|
||||||
|
) { event in
|
||||||
|
self.handle(event)
|
||||||
|
}
|
||||||
|
let global = NSEvent.addGlobalMonitorForEvents(
|
||||||
|
matching: [.leftMouseDragged, .leftMouseUp],
|
||||||
|
) { event in
|
||||||
|
_ = self.handle(event)
|
||||||
|
}
|
||||||
|
monitors = [local, global].compactMap(\.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func handle(_ event: NSEvent) -> NSEvent? {
|
||||||
|
guard !finished else { return event }
|
||||||
|
switch event.type {
|
||||||
|
case .keyDown:
|
||||||
|
// Esc cancels an ACTIVE drag only — before the threshold the
|
||||||
|
// key belongs to whoever had focus.
|
||||||
|
guard active, event.keyCode == 53 else { return event }
|
||||||
|
finish(nil)
|
||||||
|
return nil
|
||||||
|
case .leftMouseDragged:
|
||||||
|
guard active else {
|
||||||
|
let now = NSEvent.mouseLocation
|
||||||
|
guard hypot(now.x - start.x, now.y - start.y) >= 4 else { return nil }
|
||||||
|
if onActivate() {
|
||||||
|
active = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
finish(nil)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
onMoved(NSEvent.mouseLocation)
|
||||||
|
return nil
|
||||||
|
case .leftMouseUp:
|
||||||
|
if active {
|
||||||
|
finish(NSEvent.mouseLocation)
|
||||||
|
} else {
|
||||||
|
finish(nil)
|
||||||
|
onClicked()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return event
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func finish(_ screenPoint: NSPoint?) {
|
||||||
|
guard !finished else { return }
|
||||||
|
finished = true
|
||||||
|
if Self.current === self {
|
||||||
|
Self.current = nil
|
||||||
|
}
|
||||||
|
teardown()
|
||||||
|
onEnded(screenPoint)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func teardown() {
|
||||||
|
monitors.forEach { NSEvent.removeMonitor($0) }
|
||||||
|
monitors = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Drop math (pure, tested — #112)
|
||||||
|
|
||||||
|
nonisolated extension OutlinePresenter {
|
||||||
|
/// #112 drag engine — where a grabbed run would land, referenced by
|
||||||
|
/// node id and resolved against the tree AFTER extraction (the
|
||||||
|
/// applyBatch re-resolve discipline). Line-insertion semantics: a
|
||||||
|
/// drop can never steal siblings.
|
||||||
|
enum DropTarget: Equatable {
|
||||||
|
/// Seam: previous sibling of `ref`, at ref's own depth.
|
||||||
|
case before(UUID)
|
||||||
|
/// Seam below the last visible row: next sibling of `ref`, after
|
||||||
|
/// its whole subtree.
|
||||||
|
case afterLast(UUID)
|
||||||
|
/// Block middle (ring): appended as `ref`'s last child.
|
||||||
|
case lastChild(UUID)
|
||||||
|
|
||||||
|
/// The id every case references.
|
||||||
|
var refID: UUID {
|
||||||
|
switch self {
|
||||||
|
case let .before(id), let .afterLast(id), let .lastChild(id): id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The run a grab of `grabbing` drags (#112, wf113 verdict): when the
|
||||||
|
/// grabbed row sits inside the block selection the whole selection
|
||||||
|
/// rides — preorder order, descendants of selected ancestors deduped
|
||||||
|
/// (the ancestor carries them); otherwise the grabbed row alone.
|
||||||
|
static func draggedIDs(grabbing: UUID, selected: [UUID]?, in nodes: [OutlineNode]) -> [UUID] {
|
||||||
|
guard let selected, selected.contains(grabbing) else { return [grabbing] }
|
||||||
|
let sel = Set(selected)
|
||||||
|
var run: [UUID] = []
|
||||||
|
func walk(_ nodes: [OutlineNode], under selectedAncestor: Bool) {
|
||||||
|
for node in nodes {
|
||||||
|
let hit = sel.contains(node.id)
|
||||||
|
if hit, !selectedAncestor {
|
||||||
|
run.append(node.id)
|
||||||
|
}
|
||||||
|
walk(node.children, under: selectedAncestor || hit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(nodes, under: false)
|
||||||
|
return run
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A drop is invalid when its reference IS a moving block or sits
|
||||||
|
/// inside one (own-subtree). Everything else is a real position in
|
||||||
|
/// the current tree.
|
||||||
|
static func isValidDrop(moving: [UUID], target: DropTarget, in nodes: [OutlineNode]) -> Bool {
|
||||||
|
guard let refPath = path(of: target.refID, in: nodes) else { return false }
|
||||||
|
if moving.contains(target.refID) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
let movingSet = Set(moving)
|
||||||
|
// every strict prefix of the ref path is an ancestor — if one
|
||||||
|
// moves, the target sits inside a moved subtree
|
||||||
|
for length in 1 ..< refPath.count {
|
||||||
|
let ancestorPath = Array(refPath.prefix(length))
|
||||||
|
if let ancestor = node(at: ancestorPath, in: nodes), movingSet.contains(ancestor.id) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply a drop: extract the moving run (reverse document order, so
|
||||||
|
/// earlier paths stay valid), re-resolve the target's reference by id
|
||||||
|
/// in the mutated tree, splice the run in as one contiguous block.
|
||||||
|
/// False — tree untouched — for invalid targets and for no-ops (a
|
||||||
|
/// drop back at the origin leaves the document alone).
|
||||||
|
@discardableResult
|
||||||
|
static func applyDrop(
|
||||||
|
_ target: DropTarget, moving: [UUID], in nodes: inout [OutlineNode],
|
||||||
|
) -> Bool {
|
||||||
|
guard !moving.isEmpty, isValidDrop(moving: moving, target: target, in: nodes) else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
let snapshot = nodes
|
||||||
|
guard moving.allSatisfy({ path(of: $0, in: nodes) != nil }) else { return false }
|
||||||
|
|
||||||
|
// extract in reverse document order — later removals never shift
|
||||||
|
// earlier paths; the collected run reverses back to doc order
|
||||||
|
let resolved: [(id: UUID, path: [Int])] = moving.compactMap { id in
|
||||||
|
path(of: id, in: nodes).map { (id, $0) }
|
||||||
|
}
|
||||||
|
var run: [OutlineNode] = []
|
||||||
|
for entry in resolved.sorted(by: { $0.path.lexicographicallyPrecedes($1.path) }).reversed() {
|
||||||
|
guard let current = path(of: entry.id, in: nodes),
|
||||||
|
let extracted = OutlineTree.extract(&nodes, path: current) else { continue }
|
||||||
|
run.append(extracted)
|
||||||
|
}
|
||||||
|
run.reverse()
|
||||||
|
guard !run.isEmpty,
|
||||||
|
let refPath = path(of: target.refID, in: nodes),
|
||||||
|
let refIndex = refPath.last
|
||||||
|
else {
|
||||||
|
nodes = snapshot
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
let inserted: Bool = switch target {
|
||||||
|
case .before:
|
||||||
|
OutlineTree.insertRun(
|
||||||
|
run, parentPath: Array(refPath.dropLast()), index: refIndex, in: &nodes,
|
||||||
|
)
|
||||||
|
case .afterLast:
|
||||||
|
OutlineTree.insertRun(
|
||||||
|
run, parentPath: Array(refPath.dropLast()), index: refIndex + 1, in: &nodes,
|
||||||
|
)
|
||||||
|
case .lastChild:
|
||||||
|
OutlineTree.insertRun(run, parentPath: refPath, index: .max, in: &nodes)
|
||||||
|
}
|
||||||
|
guard inserted, nodes != snapshot else {
|
||||||
|
nodes = snapshot
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fat-gap hit test (wf113 variant A, the calibrated verdict): per
|
||||||
|
/// visible row the top 30% is the seam above (insert before this
|
||||||
|
/// row), the middle 40% is onto (last child), the bottom 30% the seam
|
||||||
|
/// below (insert before the NEXT visible row at its depth — none
|
||||||
|
/// means after the last row). Above the first row → before it; below
|
||||||
|
/// the last → after it. `rows` in visible order with window-space
|
||||||
|
/// frames (y-up — both callers feed window geometry; the former
|
||||||
|
/// y-down auto-detect was prototype carryover); the point in the
|
||||||
|
/// same space. Rows without a frame (unmaterialized lazy rows)
|
||||||
|
/// are skipped.
|
||||||
|
// ponytail: no auto-scroll mid-drag — keep the doc in view; the
|
||||||
|
// app-side upgrade is a scroll-edge timer driving the same math.
|
||||||
|
static func hitTestDrop(
|
||||||
|
point: CGPoint, rows: [(row: Row, frame: CGRect)],
|
||||||
|
) -> DropTarget? {
|
||||||
|
guard let first = rows.first, let last = rows.last else { return nil }
|
||||||
|
// window coords are y-up: the first visible row sits highest.
|
||||||
|
// The ±6 tolerance reaches INTO the edge row (prototype:
|
||||||
|
// `py < first.top + 6`), so the band never dead-ends.
|
||||||
|
let pointY = point.y
|
||||||
|
if pointY > first.frame.maxY - 6 {
|
||||||
|
return .before(first.row.id)
|
||||||
|
}
|
||||||
|
if pointY < last.frame.minY + 6 {
|
||||||
|
return .afterLast(last.row.id)
|
||||||
|
}
|
||||||
|
for (index, entry) in rows.enumerated() {
|
||||||
|
let frame = entry.frame
|
||||||
|
guard pointY >= frame.minY, pointY <= frame.maxY else { continue }
|
||||||
|
let rel = abs(pointY - frame.maxY) / max(frame.height, 1)
|
||||||
|
if rel < 0.30 {
|
||||||
|
return .before(entry.row.id) // seam above = before this row, at its depth
|
||||||
|
}
|
||||||
|
if rel > 0.70 {
|
||||||
|
// seam below = before the following row at ITS depth
|
||||||
|
// (a deeper follower nests under the row above);
|
||||||
|
// no follower → after this row
|
||||||
|
guard index + 1 < rows.count else { return .afterLast(entry.row.id) }
|
||||||
|
return .before(rows[index + 1].row.id)
|
||||||
|
}
|
||||||
|
return .lastChild(entry.row.id)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - #112 drag + zoom support types
|
||||||
|
|
||||||
|
/// Live drag state: the moving run (deduped selection ids) + the
|
||||||
|
/// currently hit target and its validity.
|
||||||
|
struct DragInfo: Equatable {
|
||||||
|
let moving: [UUID]
|
||||||
|
var target: OutlinePresenter.DropTarget?
|
||||||
|
var valid: Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Row geometry constants shared by the chrome: the 20pt left margin the
|
||||||
|
/// grip owns, 18px per depth level, the bullet cell's center at 11pt —
|
||||||
|
/// the seam indicator's left edge lands on the dropped block's future
|
||||||
|
/// bullet column (wf113: 11 + d·18 from the row's content edge). The
|
||||||
|
/// guide-rail Canvas reads the same constants — seam and rails must
|
||||||
|
/// not drift apart.
|
||||||
|
enum DropGeometry {
|
||||||
|
static let gripWidth: CGFloat = 20
|
||||||
|
static let railUnit: CGFloat = 18
|
||||||
|
static let bulletCenter: CGFloat = 11
|
||||||
|
|
||||||
|
/// The bullet column in chrome space (from the row's leading edge,
|
||||||
|
/// margin included).
|
||||||
|
static func bulletColumn(depth: Int) -> CGFloat {
|
||||||
|
gripWidth + CGFloat(depth) * railUnit + bulletCenter
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A horizontal rule for the dashed invalid-seam indicator.
|
||||||
|
nonisolated struct HLine: Shape {
|
||||||
|
func path(in rect: CGRect) -> Path {
|
||||||
|
var path = Path()
|
||||||
|
path.move(to: CGPoint(x: 0, y: rect.midY))
|
||||||
|
path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
}
|
||||||
+372
-242
@@ -13,6 +13,17 @@
|
|||||||
// untouched. Reading mode keeps rendering the serialized markdown via the
|
// untouched. Reading mode keeps rendering the serialized markdown via the
|
||||||
// apex surface (nested lists render natively there).
|
// 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 AppKit
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
@@ -35,10 +46,23 @@ nonisolated enum OutlinePresenter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Preorder walk emitting one Row per visible node — a folded node's
|
/// Preorder walk emitting one Row per visible node — a folded node's
|
||||||
/// whole subtree is skipped and counted.
|
/// whole subtree is skipped and counted. #112 zoom: a resolvable
|
||||||
static func visibleRows(_ nodes: [OutlineNode], folded: Set<UUID>) -> [Row] {
|
/// `zoomRootID` roots the projection at that node's CHILDREN (the node
|
||||||
|
/// itself becomes the breadcrumb), depths re-based to 0, and the zoom
|
||||||
|
/// root's own fold is ignored while it is the root. An unknown id
|
||||||
|
/// falls back to the whole document.
|
||||||
|
static func visibleRows(
|
||||||
|
_ nodes: [OutlineNode], folded: Set<UUID>, zoomRootID: UUID? = nil,
|
||||||
|
) -> [Row] {
|
||||||
var rows: [Row] = []
|
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
|
return rows
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,9 +94,12 @@ nonisolated enum OutlinePresenter {
|
|||||||
|
|
||||||
/// The visible-row ids from `from` to `to`, inclusive, in visible
|
/// The visible-row ids from `from` to `to`, inclusive, in visible
|
||||||
/// order; nil when either id isn't visible. Block-selection range
|
/// order; nil when either id isn't visible. Block-selection range
|
||||||
/// math (⇧↑/⇧↓ anchor↔focus).
|
/// math (⇧↑/⇧↓ anchor↔focus). #112: zoom-aware — ids outside the
|
||||||
static func rangeIDs(from: UUID, to: UUID, in nodes: [OutlineNode], folded: Set<UUID>) -> [UUID]? {
|
/// zoomed projection are invisible.
|
||||||
let rows = visibleRows(nodes, folded: folded)
|
static func rangeIDs(
|
||||||
|
from: UUID, to: UUID, in nodes: [OutlineNode], folded: Set<UUID>, zoomRootID: UUID? = nil,
|
||||||
|
) -> [UUID]? {
|
||||||
|
let rows = visibleRows(nodes, folded: folded, zoomRootID: zoomRootID)
|
||||||
guard let startIdx = rows.firstIndex(where: { $0.id == from }),
|
guard let startIdx = rows.firstIndex(where: { $0.id == from }),
|
||||||
let endIdx = rows.firstIndex(where: { $0.id == to })
|
let endIdx = rows.firstIndex(where: { $0.id == to })
|
||||||
else { return nil }
|
else { return nil }
|
||||||
@@ -186,33 +213,48 @@ struct OutlineEditorView: View {
|
|||||||
/// nil = end. Read at mount only — the live view owns the caret after.
|
/// nil = end. Read at mount only — the live view owns the caret after.
|
||||||
@State private var pendingCaret: Int?
|
@State private var pendingCaret: Int?
|
||||||
@State private var loadedGeneration = -1
|
@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
|
/// Esc delivery: SwiftUI's hosting layer swallows Esc before the row
|
||||||
/// textview's keyDown AND before .onExitCommand (probe-pinned —
|
/// textview's keyDown AND before .onExitCommand (probe-pinned —
|
||||||
/// EscEventProbeTests). A local monitor sees the event first.
|
/// EscEventProbeTests). A local monitor sees the event first.
|
||||||
@State private var escMonitor: Any?
|
@State private var escMonitor: Any?
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
let rows = OutlinePresenter.visibleRows(nodes, folded: folded)
|
let rows = OutlinePresenter.visibleRows(nodes, folded: folded, zoomRootID: zoomStack.last)
|
||||||
Group {
|
VStack(alignment: .leading, spacing: 0) {
|
||||||
if rows.isEmpty {
|
if !zoomStack.isEmpty {
|
||||||
VStack(spacing: 10) {
|
breadcrumb
|
||||||
Image(systemName: "list.bullet")
|
.padding(.horizontal, 20)
|
||||||
.font(.largeTitle)
|
.padding(.top, 12)
|
||||||
.foregroundStyle(DesignTokens.muted)
|
.padding(.bottom, 4)
|
||||||
Text("An empty outline — every line is a node.")
|
}
|
||||||
.font(.callout)
|
Group {
|
||||||
.foregroundStyle(DesignTokens.muted)
|
if rows.isEmpty {
|
||||||
}
|
VStack(spacing: 10) {
|
||||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
Image(systemName: "list.bullet")
|
||||||
} else {
|
.font(.largeTitle)
|
||||||
ScrollView {
|
.foregroundStyle(DesignTokens.muted)
|
||||||
LazyVStack(alignment: .leading, spacing: 0) {
|
Text("An empty outline — every line is a node.")
|
||||||
ForEach(rows) { row in
|
.font(.callout)
|
||||||
rowView(row)
|
.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
|
/// Local monitor: the ONLY reliable Esc path into this surface
|
||||||
/// (probe: sendEvent → hosted keyDown never fires for Esc). Fires
|
/// (probe: sendEvent → hosted keyDown never fires for Esc). Fires
|
||||||
/// only while the outliner's own row textview is first responder,
|
/// 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() {
|
private func installEscMonitor() {
|
||||||
guard escMonitor == nil else { return }
|
guard escMonitor == nil else { return }
|
||||||
escMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
|
escMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
|
||||||
guard event.keyCode == 53, // Esc
|
guard event.keyCode == 53, // Esc
|
||||||
(NSApp.keyWindow?.firstResponder as? RowTextView) != nil
|
(NSApp.keyWindow?.firstResponder as? RowTextView) != nil
|
||||||
else { return event }
|
else { return event }
|
||||||
if selectionAnchor != nil {
|
if handleEscape() {
|
||||||
selectionAnchor = nil
|
return nil // swallowed — selection or zoom was the target
|
||||||
return nil // swallowed — the selection was the target
|
|
||||||
}
|
}
|
||||||
return event
|
return event
|
||||||
}
|
}
|
||||||
@@ -271,24 +314,44 @@ struct OutlineEditorView: View {
|
|||||||
focusedID = nodes.first?.id
|
focusedID = nodes.first?.id
|
||||||
selectionAnchor = nil
|
selectionAnchor = nil
|
||||||
pendingCaret = nil
|
pendingCaret = nil
|
||||||
|
zoomStack = [] // fresh open = whole document, never dirties it
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: Rows
|
// 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 {
|
private func rowView(_ row: OutlinePresenter.Row) -> some View {
|
||||||
HStack(alignment: .top, spacing: 0) {
|
HStack(alignment: .top, spacing: 0) {
|
||||||
|
gripCell(row)
|
||||||
// Per-depth guide rails (prototype variant B: 1px hairline per
|
// 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
|
Canvas { context, size in
|
||||||
for level in 0 ..< row.depth {
|
for level in 0 ..< row.depth {
|
||||||
let railX = CGFloat(level) * 18 + 11
|
let railX = DropGeometry.bulletCenter + CGFloat(level) * DropGeometry.railUnit
|
||||||
context.fill(
|
context.fill(
|
||||||
Path(CGRect(x: railX, y: 0, width: 1, height: size.height)),
|
Path(CGRect(x: railX, y: 0, width: 1, height: size.height)),
|
||||||
with: .color(DesignTokens.border),
|
with: .color(DesignTokens.border),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(width: CGFloat(row.depth) * 18)
|
.frame(width: CGFloat(row.depth) * DropGeometry.railUnit)
|
||||||
bullet(row)
|
bullet(row)
|
||||||
if row.id == focusedID {
|
if row.id == focusedID {
|
||||||
OutlineRowTextView(
|
OutlineRowTextView(
|
||||||
@@ -306,6 +369,11 @@ struct OutlineEditorView: View {
|
|||||||
.fixedSize(horizontal: false, vertical: true)
|
.fixedSize(horizontal: false, vertical: true)
|
||||||
} else {
|
} else {
|
||||||
staticText(row)
|
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 {
|
if row.isFolded, row.foldedDescendantCount > 0 {
|
||||||
Text("⋯ \(row.foldedDescendantCount)")
|
Text("⋯ \(row.foldedDescendantCount)")
|
||||||
@@ -315,39 +383,114 @@ struct OutlineEditorView: View {
|
|||||||
.padding(.top, 5)
|
.padding(.top, 5)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.padding(.horizontal, 20)
|
.padding(.trailing, 20)
|
||||||
// Block-selection highlight (⇧↑/⇧↓ range, anchor↔focus).
|
// Block-selection highlight (⇧↑/⇧↓ / ⇧click range, anchor↔focus).
|
||||||
.background(rowSelected(row) ? DesignTokens.accent.opacity(0.08) : Color.clear)
|
.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
|
/// The bullet cell (22×27): fold toggle when the node has children
|
||||||
/// ("●" ~7pt, folded → accent), leaf "◦" ~10pt; tapping a leaf focuses.
|
/// ("●" ~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
|
@ViewBuilder
|
||||||
private func bullet(_ row: OutlinePresenter.Row) -> some View {
|
private func bullet(_ row: OutlinePresenter.Row) -> some View {
|
||||||
let foldable = row.childCount > 0
|
let foldable = row.childCount > 0
|
||||||
let glyph = Text(foldable ? "●" : "◦")
|
let glyph = Text(foldable ? "●" : "◦")
|
||||||
.font(.system(size: foldable ? 7 : 10))
|
.font(.system(size: foldable ? 7 : 10))
|
||||||
.foregroundStyle(row.isFolded ? DesignTokens.accent : DesignTokens.muted)
|
.foregroundStyle(row.isFolded ? DesignTokens.accent : DesignTokens.muted)
|
||||||
if foldable {
|
Group {
|
||||||
Button {
|
if foldable {
|
||||||
toggleFold(row.id)
|
Button {
|
||||||
} label: {
|
toggleFold(row.id)
|
||||||
glyph.frame(width: 22, height: 27)
|
} 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
|
/// Static row text: inert inline markdown; `[[wiki-links]]` stay
|
||||||
/// literal (the plain-Text fallback keeps them so either way).
|
/// literal (the plain-Text fallback keeps them so either way).
|
||||||
/// Same NSFont as the live row (Valkyrie 17) — no face swap on focus.
|
/// 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 {
|
private func staticText(_ row: OutlinePresenter.Row) -> some View {
|
||||||
Group {
|
Group {
|
||||||
if row.text.isEmpty {
|
if row.text.isEmpty {
|
||||||
@@ -369,11 +512,181 @@ struct OutlineEditorView: View {
|
|||||||
}
|
}
|
||||||
.padding(.vertical, 3)
|
.padding(.vertical, 3)
|
||||||
.frame(maxWidth: .infinity, alignment: .leading)
|
.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.
|
// MARK: - Zoom + drag handlers (#112 — same-file extension: private
|
||||||
.onTapGesture { focus(row.id) }
|
|
||||||
|
// 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
|
// MARK: Focus + folds
|
||||||
@@ -413,7 +726,7 @@ struct OutlineEditorView: View {
|
|||||||
}
|
}
|
||||||
case let .hop(direction):
|
case let .hop(direction):
|
||||||
// ↑/↓ hop VISIBLE blocks — folded subtrees are skipped.
|
// ↑/↓ 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 }),
|
if let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||||||
rows.indices.contains(current + direction)
|
rows.indices.contains(current + direction)
|
||||||
{
|
{
|
||||||
@@ -424,10 +737,10 @@ struct OutlineEditorView: View {
|
|||||||
case let .extend(direction):
|
case let .extend(direction):
|
||||||
// ⇧↑/⇧↓: extend the block selection one visible row. First
|
// ⇧↑/⇧↓: extend the block selection one visible row. First
|
||||||
// press anchors at the focused row; a bare ↑/↓ or click clears.
|
// press anchors at the focused row; a bare ↑/↓ or click clears.
|
||||||
if selectionAnchor == nil {
|
if let focusedID {
|
||||||
selectionAnchor = 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 }),
|
if let current = rows.firstIndex(where: { $0.id == focusedID }),
|
||||||
rows.indices.contains(current + direction)
|
rows.indices.contains(current + direction)
|
||||||
{
|
{
|
||||||
@@ -435,7 +748,7 @@ struct OutlineEditorView: View {
|
|||||||
pendingCaret = nil
|
pendingCaret = nil
|
||||||
}
|
}
|
||||||
case .deselect:
|
case .deselect:
|
||||||
selectionAnchor = nil
|
_ = handleEscape() // selection first, then zoom — same order as the monitor
|
||||||
case .indent, .outdent, .moveUp, .moveDown, .enter:
|
case .indent, .outdent, .moveUp, .moveDown, .enter:
|
||||||
applyTree(op)
|
applyTree(op)
|
||||||
}
|
}
|
||||||
@@ -495,7 +808,7 @@ struct OutlineEditorView: View {
|
|||||||
|
|
||||||
/// The selected row ids in visible order (anchor↔focus, inclusive).
|
/// The selected row ids in visible order (anchor↔focus, inclusive).
|
||||||
private func selectedRangeIDs(anchor: UUID, focus: UUID) -> [UUID]? {
|
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.
|
/// 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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -170,6 +170,49 @@ nonisolated enum OutlineTree {
|
|||||||
return moved
|
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.
|
/// Tab. Node at `path` becomes the LAST child of its previous sibling.
|
||||||
/// No previous sibling → no-op, returns nil.
|
/// No previous sibling → no-op, returns nil.
|
||||||
static func indent(_ nodes: inout [OutlineNode], path: [Int]) -> [Int]? {
|
static func indent(_ nodes: inout [OutlineNode], path: [Int]) -> [Int]? {
|
||||||
|
|||||||
@@ -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.
|
- `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.
|
- `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0.
|
||||||
- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts/<id>/post.md` (#107).
|
- `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts/<id>/post.md` (#107).
|
||||||
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). **#111:** `parsesWithLoss` pin — prose between bullets flags, deep prose flags, clean/preamble/blank/empty stay quiet.
|
- `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).
|
- `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 (the monitor itself can't run in the test host — no running NSApp loop).
|
- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (monitors DO fire in the host on `NSApp.sendEvent`, but only for events carrying a real window number — see `OutlineDragTests`).
|
||||||
|
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
|
||||||
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
|
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
|
||||||
|
|
||||||
## Verification
|
## Verification
|
||||||
|
|||||||
@@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
// through deep trees, and setText mutation by node identity.
|
// through deep trees, and setText mutation by node identity.
|
||||||
//
|
//
|
||||||
|
|
||||||
|
import CoreGraphics
|
||||||
import Foundation
|
import Foundation
|
||||||
@testable import Museion
|
@testable import Museion
|
||||||
import Testing
|
import Testing
|
||||||
@@ -170,4 +171,200 @@ struct OutlinePresenterTests {
|
|||||||
#expect(outNodes.map(\.text) == ["a", "a1", "a2", "a3"])
|
#expect(outNodes.map(\.text) == ["a", "a1", "a2", "a3"])
|
||||||
#expect(outNodes[1...].allSatisfy { node in node.children.isEmpty })
|
#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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -270,4 +270,41 @@ struct OutlineTreeTests {
|
|||||||
#expect(!OutlineTree.parsesWithLoss("- one\n\n- two\n"))
|
#expect(!OutlineTree.parsesWithLoss("- one\n\n- two\n"))
|
||||||
#expect(!OutlineTree.parsesWithLoss(""))
|
#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"])
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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*
|
||||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
|||||||
<!-- write-log: full-index -->
|
<!-- write-log: full-index -->
|
||||||
| Date | Type | File | Summary |
|
| 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-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-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 |
|
| 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 |
|
||||||
|
|||||||
@@ -0,0 +1,666 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<!--
|
||||||
|
PROTOTYPE — throwaway. Wayfinder ticket #113 (map #110): drag + zoom interaction prototype.
|
||||||
|
Feeds S6 (#112) its interaction parameters; calibrated live with Alexander.
|
||||||
|
Substrate = the landed outliner (ADR-0013, wf105 verdict "B"): a real tree of blocks,
|
||||||
|
chrome bullets + per-level vertical rules, block-granular selection, storage = nested-bullet
|
||||||
|
markdown (#101). This file reuses wf105's visual language so calibration is about the NEW
|
||||||
|
interactions only.
|
||||||
|
|
||||||
|
Stated assumptions (not calibration axes):
|
||||||
|
- Rows are static text. Editing, Enter-split, Tab/⌥ keys are SETTLED (#105/S3) — not exercised.
|
||||||
|
- Folds are skipped entirely (session-scoped per ADR-0013, orthogonal to drag/zoom;
|
||||||
|
drag-onto-a-folded-block = last child is an S6 implementation detail, noted).
|
||||||
|
- Selection mirrors the app's anchor↔focus model, mapped to mouse: click = single select,
|
||||||
|
⇧click = extend; ↑/↓ single-select, ⇧↑/⇧↓ extend. No ⌘click (not in the app).
|
||||||
|
|
||||||
|
The ONE variant axis — how the drop zone is signalled and who picks the landing depth:
|
||||||
|
A "Fat gaps" — seams between blocks insert (depth auto = following block's depth,
|
||||||
|
shown by the line's left edge); block-middle = drop as LAST child (ring).
|
||||||
|
Context-driven depth: shallow-biased.
|
||||||
|
B "Row bands" — every row split in thirds: top edge = insert before (at row's depth),
|
||||||
|
bottom edge = insert after row's subtree (at row's depth), middle = last
|
||||||
|
child. Row-driven depth: precise, every row offers both moves.
|
||||||
|
C "X-nest" — seams insert like A, but the pointer's X picks the landing depth within the
|
||||||
|
seam: shallow end = sibling of the following block; dragging right walks down
|
||||||
|
the real position ladder (each level = one step deeper) to the deepest legal
|
||||||
|
spot = last child of the block above. The line's indent IS the preview.
|
||||||
|
No sibling-stealing: every dial position is a place in the CURRENT tree
|
||||||
|
(line-insertion semantics — a drop can never absorb blocks).
|
||||||
|
|
||||||
|
Fixed defaults for the common machinery (calibration probes in the aside):
|
||||||
|
drag = subtree travels; grip ⋮⋮ drags (batch if the row is selected, solo if not);
|
||||||
|
body-drag works on already-selected rows; after a drop the moved run IS the selection;
|
||||||
|
zoom-in = double-click a bullet, zoom-out = breadcrumb click or Esc; invalid targets
|
||||||
|
(own subtree, relative-to-moving-block) show a dashed indicator and no-op.
|
||||||
|
|
||||||
|
Ceilings (ponytail: named, upgrade path in the app): hit-testing reads cached row rects
|
||||||
|
(no scroll-mid-drag compensation — keep the doc short); pointer events only, no HTML5 DnD;
|
||||||
|
no animation on the indicator (the app calibrates spring feel natively).
|
||||||
|
NOTE: all innerHTML writes receive esc()-escaped text first — no untrusted HTML enters the DOM.
|
||||||
|
-->
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>wf113 — drag + zoom prototype</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--chrome: #FAF9F3; --paper: #FFFEFB; --ink: #26251F; --muted: #8A867A;
|
||||||
|
--hairline: rgba(38,37,31,.12); --rust: #C96442;
|
||||||
|
--serif: "Valkyrie OT", "Iowan Old Style", Georgia, serif;
|
||||||
|
--mono: "Ubuntu Mono", "SF Mono", Menlo, monospace;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
html, body { margin: 0; height: 100%; }
|
||||||
|
body { background: var(--chrome); color: var(--ink); font-family: var(--serif); font-size: 17px; line-height: 1.5; }
|
||||||
|
|
||||||
|
.layout { display: grid; grid-template-columns: 1fr 340px; height: 100vh; }
|
||||||
|
main { display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.docwrap { flex: 1; display: flex; justify-content: center; overflow: auto; padding: 28px 24px 120px; }
|
||||||
|
.doc { width: 100%; max-width: 640px; background: var(--paper); border: 1px solid var(--hairline);
|
||||||
|
border-radius: 10px; padding: 36px 40px 60px; box-shadow: 0 1px 2px rgba(38,37,31,.04); }
|
||||||
|
|
||||||
|
h1 { font-size: 22px; font-weight: 600; margin: 0 0 2px; }
|
||||||
|
.meta { font-family: var(--mono); font-size: 11px; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; margin-bottom: 10px; }
|
||||||
|
|
||||||
|
/* breadcrumb (zoom chrome) */
|
||||||
|
#crumbs { display: none; font-family: var(--mono); font-size: 12px; color: var(--muted);
|
||||||
|
margin: 0 0 16px; line-height: 1.6; }
|
||||||
|
#crumbs.on { display: block; }
|
||||||
|
#crumbs .crumb { cursor: pointer; border-bottom: 1px dotted transparent; padding: 1px 2px; }
|
||||||
|
#crumbs .crumb:hover { color: var(--ink); border-bottom-color: var(--muted); }
|
||||||
|
#crumbs .here { color: var(--rust); cursor: default; }
|
||||||
|
#crumbs .here:hover { color: var(--rust); border-bottom-color: transparent; }
|
||||||
|
#crumbs .sep { margin: 0 5px; opacity: .6; }
|
||||||
|
#crumbs .out { color: var(--rust); cursor: pointer; margin-right: 8px; }
|
||||||
|
#crumbs .out:hover { color: var(--ink); }
|
||||||
|
|
||||||
|
/* ---------- rows (wf105 variant B language = the landed ADR-0013 surface) ---------- */
|
||||||
|
.rows { position: relative; user-select: none; }
|
||||||
|
.row { display: flex; align-items: flex-start; padding: 0 0 1px; position: relative; border-radius: 4px; }
|
||||||
|
.row .pad { flex: none; }
|
||||||
|
.bullet { flex: none; width: 22px; height: 27px; display: flex; align-items: center; justify-content: center;
|
||||||
|
color: var(--muted); cursor: default; border-radius: 4px; }
|
||||||
|
.bullet:hover { color: var(--ink); background: rgba(196,175,138,.15); }
|
||||||
|
.bullet.foldable::before { content: "●"; font-size: 7px; }
|
||||||
|
.bullet.leaf::before { content: "◦"; font-size: 10px; }
|
||||||
|
.row .txt { flex: 1; min-width: 0; padding: 3px 0; }
|
||||||
|
.b-code { font-family: var(--mono); font-size: 14px; background: rgba(38,37,31,.05); border-radius: 3px; padding: 0 3px; }
|
||||||
|
.row .txt strong { font-weight: 640; }
|
||||||
|
.wikichip { font-family: var(--mono); font-size: 13px; color: var(--muted); border-bottom: 1px dotted var(--muted); }
|
||||||
|
.guide { position: absolute; top: 0; bottom: 0; width: 1px; background: var(--hairline); }
|
||||||
|
|
||||||
|
/* grip — the drag affordance, left margin, appears on row hover */
|
||||||
|
.grip { position: absolute; left: -26px; top: 2px; width: 20px; height: 22px; display: flex; align-items: center;
|
||||||
|
justify-content: center; font-family: var(--mono); font-size: 12px; color: var(--muted);
|
||||||
|
opacity: 0; cursor: grab; border-radius: 4px; }
|
||||||
|
.row:hover .grip { opacity: .85; }
|
||||||
|
.grip:hover { color: var(--ink); background: rgba(196,175,138,.2); }
|
||||||
|
|
||||||
|
/* block selection (app's anchor↔focus highlight, mapped to mouse) */
|
||||||
|
.row.sel { background: rgba(196,175,138,.16); box-shadow: inset 2px 0 0 var(--rust); }
|
||||||
|
.row.lifted { opacity: .3; }
|
||||||
|
|
||||||
|
/* ---------- drop indicators ---------- */
|
||||||
|
#dropline { position: absolute; height: 0; border-top: 2px solid var(--rust); border-radius: 2px;
|
||||||
|
pointer-events: none; display: none; }
|
||||||
|
#dropline.bad { border-top-style: dashed; border-top-color: var(--muted); }
|
||||||
|
.row.ring { outline: 2px solid var(--rust); outline-offset: -2px; background: rgba(201,100,66,.08); }
|
||||||
|
.row.ring.bad { outline-style: dashed; outline-color: var(--muted); background: transparent; }
|
||||||
|
|
||||||
|
/* ghost */
|
||||||
|
#ghost { position: fixed; top: 0; left: 0; z-index: 40; pointer-events: none; display: none; max-width: 320px;
|
||||||
|
background: var(--paper); border: 1px solid var(--rust); border-radius: 8px;
|
||||||
|
box-shadow: 0 10px 26px rgba(38,37,31,.22); padding: 8px 12px; font-size: 14px; line-height: 1.45; }
|
||||||
|
#ghost .gchip { font-family: var(--mono); font-size: 10.5px; color: var(--rust); margin-bottom: 3px; }
|
||||||
|
#ghost .gline { color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
#ghost .gline.sub { color: var(--muted); font-size: 13px; }
|
||||||
|
|
||||||
|
/* ---------- rail, notes (house pattern) ---------- */
|
||||||
|
aside { border-left: 1px solid var(--hairline); background: var(--chrome); padding: 20px 18px; overflow: auto; }
|
||||||
|
aside h2 { font-family: var(--mono); font-size: 11px; text-transform: uppercase; letter-spacing: .06em;
|
||||||
|
color: var(--muted); font-weight: 400; margin: 0 0 10px; }
|
||||||
|
#rail { font-family: var(--mono); font-size: 11.5px; line-height: 1.7; white-space: pre-wrap; color: var(--ink);
|
||||||
|
background: var(--paper); border: 1px solid var(--hairline); border-radius: 8px; padding: 12px; }
|
||||||
|
#railnote { font-family: var(--mono); font-size: 11px; color: var(--rust); min-height: 16px; margin-top: 8px; }
|
||||||
|
.keys { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 14px; }
|
||||||
|
.key { font-family: var(--mono); font-size: 11px; color: var(--muted); border: 1px solid var(--hairline);
|
||||||
|
border-radius: 99px; padding: 2px 9px; background: var(--paper); }
|
||||||
|
.verdictq { margin-top: 18px; font-size: 13px; line-height: 1.55; color: var(--ink); }
|
||||||
|
.verdictq em { color: var(--rust); font-style: normal; }
|
||||||
|
.notes { font-size: 12.5px; color: var(--muted); margin-top: 12px; line-height: 1.55; }
|
||||||
|
.diffhead { font-family: var(--mono); font-size: 10.5px; text-transform: uppercase; letter-spacing: .05em; color: var(--rust); margin: 16px 0 4px; }
|
||||||
|
button.reset { font-family: var(--mono); font-size: 11px; margin-top: 16px; padding: 4px 10px; border: 1px solid var(--hairline);
|
||||||
|
border-radius: 6px; background: var(--paper); color: var(--muted); cursor: pointer; }
|
||||||
|
|
||||||
|
/* ---------- floating variant switcher ---------- */
|
||||||
|
#switcher { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); display: flex; align-items: center; gap: 10px;
|
||||||
|
background: #1F1E1A; color: #F5F2E8; border-radius: 99px; padding: 8px 14px; font-family: var(--mono); font-size: 12px;
|
||||||
|
box-shadow: 0 6px 18px rgba(0,0,0,.25); z-index: 10; }
|
||||||
|
#switcher button { background: none; border: none; color: #F5F2E8; font-size: 14px; cursor: pointer; padding: 0 4px; }
|
||||||
|
#switcher .vlabel b { color: #E8A587; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="layout">
|
||||||
|
<main>
|
||||||
|
<div class="docwrap"><div class="doc">
|
||||||
|
<h1>The Long Desk — quarterly essay</h1>
|
||||||
|
<div class="meta">type: outline · prototype wf113 · <span id="vname"></span></div>
|
||||||
|
<div id="crumbs"></div>
|
||||||
|
<div id="stage" class="rows"></div>
|
||||||
|
</div></div>
|
||||||
|
</main>
|
||||||
|
<aside>
|
||||||
|
<h2>Live markdown (storage)</h2>
|
||||||
|
<div id="rail"></div>
|
||||||
|
<div id="railnote"></div>
|
||||||
|
<div class="keys" id="keyrow"></div>
|
||||||
|
<div class="diffhead" id="diffhead"></div>
|
||||||
|
<div class="notes" id="diffnotes"></div>
|
||||||
|
<div class="verdictq" id="verdictq"></div>
|
||||||
|
<button class="reset" id="reset">reset document</button>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
<div id="switcher">
|
||||||
|
<button id="prev" title="previous variant">←</button>
|
||||||
|
<span class="vlabel">variant <b id="vkey">A</b> — <span id="vtitle"></span></span>
|
||||||
|
<button id="next" title="next variant">→</button>
|
||||||
|
</div>
|
||||||
|
<div id="ghost"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
// ---------- shared: the document (same SAMPLE as wf105) ----------
|
||||||
|
const SAMPLE = [
|
||||||
|
"- thesis",
|
||||||
|
" - the desk is not furniture, it is a **promise about time**",
|
||||||
|
" - long desks outlast the projects they were built for",
|
||||||
|
" - evidence",
|
||||||
|
" - the monastery scriptorium: standing desks, chained books, silence as infrastructure",
|
||||||
|
" - Darwin's study at Down House — same desk for forty years, the Beagle voyage compressed into a room (this line is deliberately long so you can feel subtree moves over wrapped text)",
|
||||||
|
" - [[drafts/sand-walk]] as the walking counterpart",
|
||||||
|
" - counterargument",
|
||||||
|
" - standing desks as fashion, not discipline",
|
||||||
|
" - reply: fashion fades, the `posture` persists",
|
||||||
|
"- structure",
|
||||||
|
" - open on the physical object, close on the habit",
|
||||||
|
" - three movements, one per century",
|
||||||
|
"- cuts from the first draft",
|
||||||
|
" - the `typewriter` paragraph — keep for the epigraph file",
|
||||||
|
" - everything about [[reading-rooms]]",
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
const UNITS = 2;
|
||||||
|
const esc = s => s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""");
|
||||||
|
function inlineMD(s){
|
||||||
|
return esc(s)
|
||||||
|
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
||||||
|
.replace(/`([^`]+)`/g, '<span class="b-code">$1</span>')
|
||||||
|
.replace(/\[\[([^\]]+)\]\]/g, '<span class="wikichip">[[$1]]</span>');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- tree model (wf105 B machinery; ops are path-addressed like the real OutlineTree) ----------
|
||||||
|
let root = null, uid = 0;
|
||||||
|
function parse(){
|
||||||
|
root = { id: uid++, text: "", children: [] };
|
||||||
|
const stack = [{ d: -1, n: root }];
|
||||||
|
for (const l of SAMPLE.split("\n")){
|
||||||
|
const m = l.match(/^(\s*)[-*] (.*)$/); if (!m) continue;
|
||||||
|
const d = Math.floor(m[1].length / UNITS);
|
||||||
|
const node = { id: uid++, text: m[2], children: [] };
|
||||||
|
while (stack[stack.length - 1].d >= d) stack.pop();
|
||||||
|
stack[stack.length - 1].n.children.push(node);
|
||||||
|
stack.push({ d, n: node });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function serialize(){
|
||||||
|
const out = [];
|
||||||
|
(function walk(nodes, d){
|
||||||
|
for (const n of nodes){ out.push(" ".repeat(d * UNITS) + "- " + n.text); walk(n.children, d + 1); }
|
||||||
|
})(root.children, 0);
|
||||||
|
return out.join("\n");
|
||||||
|
}
|
||||||
|
function findNode(id){ // → {node, parentArray, index} | null
|
||||||
|
const stack = [{ arr: root.children, node: null }];
|
||||||
|
// DFS with explicit frame
|
||||||
|
const rec = (arr) => { for (let k = 0; k < arr.length; k++){ if (arr[k].id === id) return { node: arr[k], parentArray: arr, index: k }; const r = rec(arr[k].children); if (r) return r; } return null; };
|
||||||
|
return rec(root.children);
|
||||||
|
}
|
||||||
|
function ancestorsOf(id){ // node chain from root.children level down to the node's parent []
|
||||||
|
const chain = [];
|
||||||
|
(function walk(nodes){
|
||||||
|
for (const n of nodes){
|
||||||
|
if (n.id === id) return true;
|
||||||
|
chain.push(n);
|
||||||
|
if (walk(n.children)) return true;
|
||||||
|
chain.pop();
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
})(root.children);
|
||||||
|
return chain;
|
||||||
|
}
|
||||||
|
function preorderIds(nodes, out){
|
||||||
|
for (const n of nodes){ out.push(n.id); preorderIds(n.children, out); }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- projection (zoom = presenter rooted at a node) ----------
|
||||||
|
let zoomId = null; // null = whole document
|
||||||
|
let rows = []; // visible projection: {id, node, d (display depth), el, rect, parentArray, index}
|
||||||
|
function project(){
|
||||||
|
rows = [];
|
||||||
|
const base = zoomId == null ? root : findNode(zoomId)?.node;
|
||||||
|
if (!base){ zoomId = null; return project(); }
|
||||||
|
(function walk(nodes, d, parentArray){
|
||||||
|
for (let k = 0; k < nodes.length; k++){
|
||||||
|
const n = nodes[k];
|
||||||
|
rows.push({ id: n.id, node: n, d, el: null, rect: null, parentArray: nodes, index: k });
|
||||||
|
walk(n.children, d + 1, n.children);
|
||||||
|
}
|
||||||
|
})(base.children, 0, base.children);
|
||||||
|
}
|
||||||
|
const rowOf = id => rows.find(r => r.id === id);
|
||||||
|
const visibleIds = () => rows.map(r => r.id);
|
||||||
|
|
||||||
|
// ---------- selection (the app's anchor↔focus, mapped to mouse) ----------
|
||||||
|
let selection = new Set(), anchorId = null, focusId = null;
|
||||||
|
function selectSingle(id){ selection = new Set([id]); anchorId = id; focusId = id; }
|
||||||
|
function extendTo(id){
|
||||||
|
if (anchorId == null || !rowOf(anchorId)){ selectSingle(id); return; }
|
||||||
|
const vis = visibleIds();
|
||||||
|
const a = vis.indexOf(anchorId), f = vis.indexOf(id);
|
||||||
|
if (a < 0 || f < 0) return;
|
||||||
|
const [lo, hi] = a < f ? [a, f] : [f, a];
|
||||||
|
selection = new Set(vis.slice(lo, hi + 1));
|
||||||
|
focusId = id;
|
||||||
|
}
|
||||||
|
function clearSelection(){ selection = new Set(); anchorId = null; focusId = null; }
|
||||||
|
|
||||||
|
// ---------- render ----------
|
||||||
|
let stage = null, dropline = null;
|
||||||
|
function render(){
|
||||||
|
stage.innerHTML = "";
|
||||||
|
for (const r of rows){
|
||||||
|
const row = document.createElement("div");
|
||||||
|
row.className = "row" + (selection.has(r.id) ? " sel" : "");
|
||||||
|
for (let g = 0; g < r.d; g++){
|
||||||
|
const guide = document.createElement("div"); guide.className = "guide";
|
||||||
|
guide.style.left = (g * UNITS * 9 + 11) + "px"; row.appendChild(guide);
|
||||||
|
}
|
||||||
|
const pad = document.createElement("div"); pad.className = "pad"; pad.style.width = (r.d * UNITS * 9) + "px"; row.appendChild(pad);
|
||||||
|
const grip = document.createElement("div"); grip.className = "grip"; grip.textContent = "⋮⋮"; grip.title = "drag block (with subtree)";
|
||||||
|
row.appendChild(grip);
|
||||||
|
const bullet = document.createElement("div");
|
||||||
|
bullet.className = "bullet " + (r.node.children.length ? "foldable" : "leaf");
|
||||||
|
bullet.title = "double-click: zoom in";
|
||||||
|
row.appendChild(bullet);
|
||||||
|
const txt = document.createElement("div"); txt.className = "txt"; txt.innerHTML = inlineMD(r.node.text);
|
||||||
|
row.appendChild(txt);
|
||||||
|
stage.appendChild(row);
|
||||||
|
r.el = row;
|
||||||
|
}
|
||||||
|
stage.appendChild(dropline); // absolute-positioned against .rows (position:relative)
|
||||||
|
// measure rects relative to the rows container
|
||||||
|
const baseRect = stage.getBoundingClientRect();
|
||||||
|
for (const r of rows) r.rect = { top: r.el.getBoundingClientRect().top - baseRect.top,
|
||||||
|
bottom: r.el.getBoundingClientRect().bottom - baseRect.top,
|
||||||
|
rowLeft: r.el.getBoundingClientRect().left, h: r.el.getBoundingClientRect().height };
|
||||||
|
drawCrumbs();
|
||||||
|
rail();
|
||||||
|
}
|
||||||
|
function drawCrumbs(){
|
||||||
|
const c = document.getElementById("crumbs");
|
||||||
|
if (zoomId == null){ c.className = ""; c.innerHTML = ""; return; }
|
||||||
|
const chain = ancestorsOf(zoomId);
|
||||||
|
const here = findNode(zoomId)?.node;
|
||||||
|
let html = `<span class="out" data-zoom="root" title="zoom all the way out">⟵ zoom out</span>`;
|
||||||
|
html += `<span class="crumb" data-zoom="root">The Long Desk</span>`;
|
||||||
|
for (const n of chain) html += `<span class="sep">/</span><span class="crumb" data-zoom="${n.id}">${esc(short(n.text))}</span>`;
|
||||||
|
if (here) html += `<span class="sep">/</span><span class="here">${esc(short(here.text))}</span>`;
|
||||||
|
c.className = "on"; c.innerHTML = html;
|
||||||
|
}
|
||||||
|
const short = t => { t = t.replace(/[*`[\]]/g, ""); return t.length > 26 ? t.slice(0, 25) + "…" : t; };
|
||||||
|
function rail(){ document.getElementById("rail").textContent = serialize(); }
|
||||||
|
function note(msg){ document.getElementById("railnote").textContent = msg; }
|
||||||
|
|
||||||
|
// ---------- zoom ----------
|
||||||
|
function zoomTo(id){
|
||||||
|
zoomId = id;
|
||||||
|
project();
|
||||||
|
// selection survives only if fully visible
|
||||||
|
const vis = new Set(visibleIds());
|
||||||
|
for (const sid of [...selection]) if (!vis.has(sid)) { clearSelection(); break; }
|
||||||
|
render();
|
||||||
|
note(id == null ? "zoom: whole document" : `zoom: rooted at “${short(findNode(id).node.text)}” — depths re-based, breadcrumb above`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- drag ----------
|
||||||
|
let drag = null; // {ids, ghostEl, target, bad}
|
||||||
|
function draggedSet(fromId){
|
||||||
|
let ids;
|
||||||
|
if (selection.has(fromId)){
|
||||||
|
// the selection rides: preorder order, descendants of selected ancestors deduped
|
||||||
|
const sel = selection;
|
||||||
|
ids = [];
|
||||||
|
(function walk(nodes, under){
|
||||||
|
for (const n of nodes){
|
||||||
|
const hit = sel.has(n.id);
|
||||||
|
if (hit && !under){ ids.push(n.id); }
|
||||||
|
walk(n.children, under || hit);
|
||||||
|
}
|
||||||
|
})(root.children, false);
|
||||||
|
} else ids = [fromId];
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
function startDrag(ids, x, y){
|
||||||
|
drag = { ids, target: null, bad: false };
|
||||||
|
for (const r of rows) if (drag.ids.includes(r.id)) r.el.classList.add("lifted");
|
||||||
|
const g = document.getElementById("ghost");
|
||||||
|
let desc = 0;
|
||||||
|
for (const id of ids){ const f = findNode(id); desc += preorderIds(f.node.children, []).length; }
|
||||||
|
g.innerHTML = `<div class="gchip">${ids.length} block${ids.length > 1 ? "s" : ""}${desc ? " · " + desc + " descendant" + (desc > 1 ? "s" : "") : ""}</div>` +
|
||||||
|
ids.slice(0, 3).map((id, k) => `<div class="gline${k ? " sub" : ""}">${esc(short(findNode(id).node.text))}</div>`).join("") +
|
||||||
|
(ids.length > 3 ? `<div class="gline sub">…</div>` : "");
|
||||||
|
g.style.display = "block";
|
||||||
|
moveGhost(x, y);
|
||||||
|
note(`dragging ${ids.length} block${ids.length > 1 ? "s" : ""} (+${desc}) — Esc cancels`);
|
||||||
|
}
|
||||||
|
function moveGhost(x, y){
|
||||||
|
const g = document.getElementById("ghost");
|
||||||
|
g.style.transform = `translate(${x + 14}px, ${y + 12}px)`;
|
||||||
|
}
|
||||||
|
function endDragVisual(){
|
||||||
|
document.getElementById("ghost").style.display = "none";
|
||||||
|
dropline.style.display = "none";
|
||||||
|
document.querySelectorAll(".row.ring, .row.absorb").forEach(el => el.classList.remove("ring", "absorb", "bad"));
|
||||||
|
document.querySelectorAll(".row.lifted").forEach(el => el.classList.remove("lifted"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- hit testing: pointer → target, per-variant policy -----
|
||||||
|
// target vocabulary (references by NODE ID, resolved AFTER extraction — the app's re-resolve-by-id discipline):
|
||||||
|
// {kind:"before", ref} insert before ref (as sibling) — depth shown = ref's depth
|
||||||
|
// {kind:"after", ref} insert after ref's subtree (as next sibling)
|
||||||
|
// {kind:"onto", ref} last child of ref
|
||||||
|
// walk up the REAL ancestor chain of the row's node: nearest row above at display depth d that is an ancestor
|
||||||
|
function ancestorRowAt(rowId, d){
|
||||||
|
const r = rowOf(rowId); if (!r) return null;
|
||||||
|
if (r.d === d) return r;
|
||||||
|
for (let i = rows.indexOf(r) - 1; i >= 0; i--){
|
||||||
|
if (rows[i].d === d && isAncestor(rows[i].id, rowId)) return rows[i];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
function isAncestor(maybeAnc, id){
|
||||||
|
return ancestorsOf(id).some(n => n.id === maybeAnc);
|
||||||
|
}
|
||||||
|
|
||||||
|
function hitTest(px, py){
|
||||||
|
// py relative to rows container; px absolute (client)
|
||||||
|
if (!rows.length) return null;
|
||||||
|
const first = rows[0], last = rows[rows.length - 1];
|
||||||
|
if (py < first.rect.top + 6) return seamTarget(null, rows[0]); // above the first block
|
||||||
|
if (py > last.rect.bottom - 6) return seamTarget(rows[rows.length - 1], null); // below the last
|
||||||
|
for (const r of rows){
|
||||||
|
const { top, bottom, h } = r.rect;
|
||||||
|
if (py < top || py >= bottom) continue;
|
||||||
|
const rel = (py - top) / h;
|
||||||
|
if (VARIANT === "A"){
|
||||||
|
if (rel < 0.30){ const i = rows.indexOf(r); return seamTarget(rows[i - 1] || null, r); }
|
||||||
|
if (rel > 0.70){ const i = rows.indexOf(r); return seamTarget(r, rows[i + 1] || null); }
|
||||||
|
return { kind: "onto", ref: r.id };
|
||||||
|
} else if (VARIANT === "B"){
|
||||||
|
if (rel < 0.33){ return { kind: "before", ref: r.id }; }
|
||||||
|
if (rel > 0.67){ return { kind: "after", ref: r.id }; }
|
||||||
|
return { kind: "onto", ref: r.id };
|
||||||
|
} else { // C — A's bands (seam / onto / seam), but seams resolve through the x-dial ladder
|
||||||
|
const i = rows.indexOf(r);
|
||||||
|
const seam = rel < 0.30
|
||||||
|
? xDepth(seamTarget(rows[i - 1] || null, r), px)
|
||||||
|
: (rel > 0.70 ? xDepth(seamTarget(r, rows[i + 1] || null), px) : null);
|
||||||
|
return seam || { kind: "onto", ref: r.id };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// seam (U,L) → A-rule target: insert before L at L's depth; end seam → after U; top seam → before first
|
||||||
|
function seamTarget(U, L){
|
||||||
|
if (L) return { kind: "before", ref: L.id };
|
||||||
|
if (U) return { kind: "after", ref: U.id };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// C-rule: the seam between U and L offers a LADDER of real positions: rung 0 = insert before L;
|
||||||
|
// each next rung = LAST CHILD of the next node on U's ancestor chain (C1 = child of L's-level
|
||||||
|
// ancestor containing U, down to U itself). Pointer x walks the rungs; every rung is a real
|
||||||
|
// spot in the current tree — a drop can never steal siblings (line-insertion semantics).
|
||||||
|
function xDepth(seam, px){
|
||||||
|
if (!seam) return null;
|
||||||
|
if (seam.kind !== "before") return seam; // end seam: fixed position
|
||||||
|
const L = rowOf(seam.ref); if (!L) return seam;
|
||||||
|
const U = rows[rows.indexOf(L) - 1] || null;
|
||||||
|
if (!U) return { kind: "before", ref: L.id };
|
||||||
|
const rungs = [{ kind: "before", ref: L.id }];
|
||||||
|
for (let k = L.d + 1; k <= U.d; k++){
|
||||||
|
const node = ancestorRowAt(U.id, k); // k = U.d → U itself
|
||||||
|
if (node) rungs.push({ kind: "onto", ref: node.id });
|
||||||
|
}
|
||||||
|
const baseX = L.rect.rowLeft + 11 + L.d * UNITS * 9; // L's marker column; +18px per rung
|
||||||
|
let idx = Math.round((px - baseX) / (UNITS * 9));
|
||||||
|
idx = Math.max(0, Math.min(rungs.length - 1, idx));
|
||||||
|
return rungs[idx];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- target → narration + indicator geometry -----
|
||||||
|
function describeTarget(t){
|
||||||
|
if (!t) return { text: "", bad: false };
|
||||||
|
const name = id => short(findNode(id)?.node?.text || "?");
|
||||||
|
const bad = targetIsInvalid(t);
|
||||||
|
let text;
|
||||||
|
if (t.kind === "before") text = `drop: insert before “${name(t.ref)}” · depth ${rowOf(t.ref)?.d ?? "?"}`;
|
||||||
|
else if (t.kind === "after") text = `drop: insert after “${name(t.ref)}” subtree · depth ${rowOf(t.ref)?.d ?? "?"}`;
|
||||||
|
else text = `drop: last child of “${name(t.ref)}”${findNode(t.ref)?.node.children.length ? "" : " (empty — first child)"}`;
|
||||||
|
return { text: bad ? text + " ✕ inside moved subtree — no-op" : text, bad };
|
||||||
|
}
|
||||||
|
function targetIsInvalid(t){
|
||||||
|
if (!t) return false;
|
||||||
|
const ids = drag ? drag.ids : [];
|
||||||
|
if (!ids.length) return false;
|
||||||
|
// target relative to a moving block, or inside one?
|
||||||
|
if (["before", "after", "onto"].includes(t.kind) && ids.includes(t.ref)) return true;
|
||||||
|
if (ancestorsOf(t.ref).some(n => ids.includes(n.id))) return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showTarget(t, bad){
|
||||||
|
dropline.style.display = "none";
|
||||||
|
document.querySelectorAll(".row.ring, .row.absorb").forEach(el => el.classList.remove("ring", "absorb", "bad"));
|
||||||
|
if (!t) return;
|
||||||
|
if (t.kind === "onto"){
|
||||||
|
const r = rowOf(t.ref);
|
||||||
|
if (r){ r.el.classList.add("ring"); if (bad) r.el.classList.add("bad"); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let y, d;
|
||||||
|
if (t.kind === "before" || t.kind === "after"){
|
||||||
|
const r = rowOf(t.ref); if (!r) return;
|
||||||
|
y = t.kind === "before" ? r.rect.top : r.rect.bottom;
|
||||||
|
d = r.d;
|
||||||
|
}
|
||||||
|
const leftPx = 11 + d * UNITS * 9; // the dropped block's bullet column at the resulting depth
|
||||||
|
const w = stage.clientWidth;
|
||||||
|
dropline.style.display = "block";
|
||||||
|
dropline.style.top = (y - 1) + "px";
|
||||||
|
dropline.style.left = leftPx + "px";
|
||||||
|
dropline.style.width = (w - leftPx - 4) + "px";
|
||||||
|
dropline.className = bad ? "bad" : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- the drop: extract moved subtrees, re-resolve refs by id, splice -----
|
||||||
|
function drop(){
|
||||||
|
const t = drag.target;
|
||||||
|
const ids = drag.ids;
|
||||||
|
if (!t || targetIsInvalid(t)){ endDragVisual(); note(t ? "drop cancelled — target inside the moved subtree" : "drop cancelled"); drag = null; return; }
|
||||||
|
|
||||||
|
// capture semantics BEFORE extraction
|
||||||
|
const ontoNode = t.kind === "onto" ? findNode(t.ref).node : null;
|
||||||
|
|
||||||
|
// extract the moved subtrees (preorder)
|
||||||
|
const moved = [];
|
||||||
|
for (const id of ids){
|
||||||
|
const f = findNode(id);
|
||||||
|
if (f){ f.parentArray.splice(f.index, 1); moved.push(f.node); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const land = (arr, idx) => arr.splice(idx, 0, ...moved);
|
||||||
|
|
||||||
|
let msg = "";
|
||||||
|
if (ontoNode){ land(ontoNode.children, ontoNode.children.length); msg = `child of “${short(ontoNode.text)}”`; }
|
||||||
|
else if (t.kind === "before"){
|
||||||
|
const f = findNode(t.ref); if (!f){ restore(moved); return; }
|
||||||
|
land(f.parentArray, f.index); msg = `before “${short(f.node.text)}”`;
|
||||||
|
}
|
||||||
|
else if (t.kind === "after"){
|
||||||
|
const f = findNode(t.ref); if (!f){ restore(moved); return; }
|
||||||
|
land(f.parentArray, f.index + 1); msg = `after “${short(f.node.text)}”`;
|
||||||
|
}
|
||||||
|
|
||||||
|
project();
|
||||||
|
// selection = the moved run (drop hands the run to the next op)
|
||||||
|
selection = new Set(moved.map(n => n.id));
|
||||||
|
anchorId = moved[0]?.id ?? null; focusId = anchorId;
|
||||||
|
render();
|
||||||
|
endDragVisual();
|
||||||
|
drag = null;
|
||||||
|
note(`drop: ${ids.length} block${ids.length > 1 ? "s" : ""} → ${msg} — selection = the moved run; storage rail moved`);
|
||||||
|
}
|
||||||
|
function restore(moved){ root.children.push(...moved); project(); render(); note("drop failed — restored"); }
|
||||||
|
|
||||||
|
// ---------- pointer plumbing ----------
|
||||||
|
function armDrag(e, id, fromGrip){
|
||||||
|
const startX = e.clientX, startY = e.clientY;
|
||||||
|
let active = false;
|
||||||
|
const ids = draggedSet(id);
|
||||||
|
const move = ev => {
|
||||||
|
if (!active){
|
||||||
|
if (Math.hypot(ev.clientX - startX, ev.clientY - startY) < 4) return;
|
||||||
|
active = true;
|
||||||
|
startDrag(ids, ev.clientX, ev.clientY);
|
||||||
|
}
|
||||||
|
ev.preventDefault();
|
||||||
|
moveGhost(ev.clientX, ev.clientY);
|
||||||
|
const stageRect = stage.getBoundingClientRect();
|
||||||
|
const t = hitTest(ev.clientX, ev.clientY - stageRect.top);
|
||||||
|
const { text, bad } = describeTarget(t);
|
||||||
|
drag.target = t;
|
||||||
|
showTarget(t, bad);
|
||||||
|
note(text || "dragging — no target");
|
||||||
|
};
|
||||||
|
const up = ev => {
|
||||||
|
window.removeEventListener("pointermove", move);
|
||||||
|
window.removeEventListener("pointerup", up);
|
||||||
|
if (active){ if (drag) drop(); }
|
||||||
|
else if (!fromGrip){ /* plain click on row: handled by click listener */ }
|
||||||
|
};
|
||||||
|
window.addEventListener("pointermove", move);
|
||||||
|
window.addEventListener("pointerup", up);
|
||||||
|
}
|
||||||
|
|
||||||
|
function wire(){
|
||||||
|
stage.addEventListener("pointerdown", e => {
|
||||||
|
const rowEl = e.target.closest(".row"); if (!rowEl) return;
|
||||||
|
const r = rows.find(x => x.el === rowEl); if (!r) return;
|
||||||
|
const onGrip = e.target.closest(".grip");
|
||||||
|
if (e.button !== 0) return;
|
||||||
|
if (onGrip){ e.preventDefault(); armDrag(e, r.id, true); return; }
|
||||||
|
if (e.shiftKey){ e.preventDefault(); extendTo(r.id); render(); return; }
|
||||||
|
if (selection.has(r.id)){ armDrag(e, r.id, false); return; } // body-drag on a selected row
|
||||||
|
selectSingle(r.id); render(); // click = fresh single select
|
||||||
|
});
|
||||||
|
stage.addEventListener("dblclick", e => {
|
||||||
|
if (e.target.closest(".bullet")){
|
||||||
|
const rowEl = e.target.closest(".row");
|
||||||
|
const r = rows.find(x => x.el === rowEl);
|
||||||
|
if (r) zoomTo(r.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
document.getElementById("crumbs").addEventListener("click", e => {
|
||||||
|
const c = e.target.closest(".crumb, .out"); if (!c) return;
|
||||||
|
zoomTo(c.dataset.zoom === "root" ? null : +c.dataset.zoom);
|
||||||
|
});
|
||||||
|
document.addEventListener("keydown", e => {
|
||||||
|
if (e.key === "Escape"){
|
||||||
|
if (drag){ endDragVisual(); drag = null; note("drag cancelled (Esc)"); return; }
|
||||||
|
if (selection.size){ clearSelection(); render(); note("selection cleared"); return; }
|
||||||
|
if (zoomId != null){ zoomTo(ancestorsOf(zoomId).pop()?.id ?? null); return; }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (drag) return; // no variant cycling / selection keys mid-drag
|
||||||
|
if (e.key === "ArrowUp" || e.key === "ArrowDown"){
|
||||||
|
const dir = e.key === "ArrowUp" ? -1 : 1;
|
||||||
|
const vis = visibleIds();
|
||||||
|
const i = focusId != null ? vis.indexOf(focusId) : -1;
|
||||||
|
let j = i < 0 ? (dir > 0 ? 0 : vis.length - 1) : Math.max(0, Math.min(vis.length - 1, i + dir));
|
||||||
|
if (i === j) return;
|
||||||
|
e.preventDefault();
|
||||||
|
if (e.shiftKey) extendTo(vis[j]); else selectSingle(vis[j]);
|
||||||
|
render();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!(e.target.isContentEditable || e.target.tagName === "INPUT")){
|
||||||
|
if (e.key === "ArrowLeft" || e.key === "ArrowRight") cycle(e.key === "ArrowRight" ? 1 : -1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- variant plumbing ----------
|
||||||
|
const VARIANTS = ["A", "B", "C"];
|
||||||
|
let VARIANT = new URLSearchParams(location.search).get("variant") || "A";
|
||||||
|
if (!VARIANTS.includes(VARIANT)) VARIANT = "A";
|
||||||
|
const META = {
|
||||||
|
A: {
|
||||||
|
title: "Fat gaps",
|
||||||
|
keys: `click select · ⇧click extend · drag ⋮⋮ (batch if selected) · drag a selected row · dblclick ● zoom in · crumb/Esc out · ←/→ variant`,
|
||||||
|
diff: `Seams between blocks insert; the landing depth is picked FOR you (the following block's depth — context-biased shallow) and shown by the line's left edge. The middle band of a block = drop as last child (ring). Never absorbs. Simplest mental model: <em>the seam inserts, the block nests</em>.`,
|
||||||
|
q: `A — enough control? Feel the seam between a deep block and a shallow one: you always land shallow.`
|
||||||
|
},
|
||||||
|
B: {
|
||||||
|
title: "Row bands",
|
||||||
|
keys: `click select · ⇧click extend · drag ⋮⋮ (batch if selected) · drag a selected row · dblclick ● zoom in · crumb/Esc out · ←/→ variant`,
|
||||||
|
diff: `Every row is three bands: top edge = insert before at the row's depth, bottom edge = insert after its subtree, middle = last child. No seams to hunt — precision comes from the row you hover. Never absorbs. Row-biased: bottom of a deep row lands you deep.`,
|
||||||
|
q: `B — are the thirds discoverable without being told? Twitchy or precise?`
|
||||||
|
},
|
||||||
|
C: {
|
||||||
|
title: "X-nest (depth dial)",
|
||||||
|
keys: `click select · ⇧click extend · drag ⋮⋮ (batch if selected) · drag a selected row · dblclick ● zoom in · crumb/Esc out · ←/→ variant · drag RIGHT in a seam to nest`,
|
||||||
|
diff: `Like A, but the pointer's X is a depth dial inside the seam: shallow end = sibling of the block below; drag right and the line walks down one real level at a time to the deepest legal spot — last child of the block above. Every dial position is a place in the current tree: a drop can <em>never</em> steal siblings (line-insertion semantics), so the line's indent is the whole truth.`,
|
||||||
|
q: `C — is the dial worth the x-sensitivity? Feel the ladder between two same-level blocks vs the seam above a deep subtree.`
|
||||||
|
}
|
||||||
|
};
|
||||||
|
function showVariant(v){
|
||||||
|
VARIANT = v;
|
||||||
|
const url = new URL(location.href); url.searchParams.set("variant", v); history.replaceState(null, "", url);
|
||||||
|
document.getElementById("vkey").textContent = v;
|
||||||
|
document.getElementById("vtitle").textContent = META[v].title;
|
||||||
|
document.getElementById("vname").textContent = `variant ${v} — ${META[v].title}`;
|
||||||
|
document.getElementById("diffhead").textContent = `drop model ${v}`;
|
||||||
|
document.getElementById("diffnotes").innerHTML = META[v].diff;
|
||||||
|
document.getElementById("verdictq").innerHTML = `<em>calibration probes:</em> drop model A/B/C? · line-at-resulting-depth + live rail note = enough auto-nest feedback? · grip = batch-when-selected, solo-when-not — right? · body-drag on selected rows — keep? · zoom: dblclick-bullet in, crumb/Esc out — or single-click? · dashed = no-op, enough? — then: <em>${META[v].q}</em>`;
|
||||||
|
document.getElementById("keyrow").innerHTML = META[v].keys.split("·").map(k => `<span class="key">${k.trim()}</span>`).join("");
|
||||||
|
note("");
|
||||||
|
parse(); project(); clearSelection(); zoomId = null; render();
|
||||||
|
}
|
||||||
|
const cycle = d => { const i = VARIANTS.indexOf(VARIANT); showVariant(VARIANTS[(i + d + VARIANTS.length) % VARIANTS.length]); };
|
||||||
|
document.getElementById("prev").onclick = () => cycle(-1);
|
||||||
|
document.getElementById("next").onclick = () => cycle(1);
|
||||||
|
document.getElementById("reset").onclick = () => { note("reset"); parse(); project(); clearSelection(); render(); };
|
||||||
|
|
||||||
|
// ---------- boot ----------
|
||||||
|
stage = document.getElementById("stage");
|
||||||
|
dropline = document.createElement("div");
|
||||||
|
dropline.id = "dropline";
|
||||||
|
wire();
|
||||||
|
showVariant(VARIANT);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in new issue
Block a user