diff --git a/AGENTS.md b/AGENTS.md index 93c4e06..63100c3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -129,7 +129,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do # GitNexus — Code Intelligence -This project is indexed by GitNexus as **museion** (2654 symbols, 7109 relationships, 192 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. +This project is indexed by GitNexus as **museion** (2945 symbols, 8292 relationships, 223 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely. > Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939). @@ -177,6 +177,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | Date | Log | |------|-----| +| 2026-10-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-issue107-storage-substrate-projects-archive_log.md](docs/devlog/20261013-issue107-storage-substrate-projects-archive_log.md) | | 2026-10-12 | [20261012-issue22-import-external_log.md](docs/devlog/20261012-issue22-import-external_log.md) | diff --git a/CHANGELOG.md b/CHANGELOG.md index cc76dac..0080b4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format ### Added +- **outline:** 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) + - **library:** projects & archive UI (v1.1 S2, variant B per #104) — the library column groups pieces by project under serif lowercase section heads (collapse toggle, `· N` counts, Pass-State groups inside); Move to Project / Move to Archive / Move Back / whole-project Unarchive as folder moves (post.md bytes untouched, never clobbering, ids globally unique); an Archive rail destination lists archived pieces grouped by project with row-click back to Posts; File ▸ New Post ⌘N and New Project… ⌥⌘N; New Project opens a draft targeted at it, and every folder move flushes pending edits first — a failed write aborts the move with nothing relocated (issue #108) - **library:** projects & archive storage substrate (v1.1 S1) — pieces live under `projects///post.md` with finished work folding into `archive//` (ADR-0012): the library scans both roots, New Piece and Import land in the selected project (else the default `posts`), slugs stay globally unique across projects and archive so an archived name is never reused, and every piece carries `type: post` frontmatter (absent or unknown types read as post; the file stays `post.md` for every type) (issue #107) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index a4c806b..f4b47e7 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -10,7 +10,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro ## Local Contracts -- 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) 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). - Swift language mode 6, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`; deployment target 26.5; 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. @@ -24,8 +24,10 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border. **#22:** window-level `.dropDestination(for: URL.self)` (markdown only via `PostStore.isMarkdown`, first match — same guest slot as ⌘O), the `OriginAskSheet` (ONE ask per import batch — "Who wrote this?", writer default / ai, immutability line; Cancel drops the batch), and pane auto-switch to Posts when a guest buffer opens or an import's post opens. **#108:** rail gains the Archive destination (archivebox icon, above Settings — the #104 verdict: a destination, not a library disclosure); `ArchivePaneView` = list-only pane over archived pieces grouped by project (same section-head voice as the library + mono-11 Unarchive button per project → `PostsModel.unarchiveProject`), rows reuse `LibraryPostRow` with Move Back to `` + Rename…, row-click selects + hops to Posts (`onOpenPiece` closure — the pane can't reach the rail selection); empty state names how things arrive. The New Project ask presents here too (`newProjectAskBinding`, the OriginAsk pattern). - `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`). **#92:** the editor column renders the external guest (`model.externalSession`) ahead of the post session — one guest at a time, mentor column stays. **#108 (variant B, `ref/prototypes/wf104-library-ui-prototype.html`):** `PostsLibraryColumn` regroups — serif-15 semibold project section heads (lowercased in display — #108 live verdict; small caps rejected as a UI treatment for project names) + mono-11 `· N` count, Pass-State groups inside (10px mono, 0.8 opacity, leading-22 indent), collapse restored per the prototype's toggle (click the head — chevron rotates; per-view state, not persisted); `LibraryPostRow` (extracted, internal — Archive reuses it): always-2px leading strip (accent when selected — no layout shift; `UnevenRoundedRectangle` 0/8/8/0 per `.vB .post-row`), ✳ suffix on outline pieces (row-level help — a Text span isn't individually hoverable); row menu = Rename… · Move to Project… (`MoveToProjectSheet`, radio list of non-archived projects, Move disabled when unchanged) · Move to Archive · Move to Trash; `RenamePostSheet` internal for the Archive pane's reuse. - `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin + #107 type/project/isArchived; `ContentType` post|outline) + `Post.scan(home:) -> [Post]`: **#107/ADR-0012 two-level scan** — enumerates `projects///post.md` AND `archive///post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel). -- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; stamp now `type: post` + `pass_state: First Draft` + `origin: writer`), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). -- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; `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. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was moved." to the flush-routed reason, never replacing it; the session stays up dirty), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). +- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:type:home:)` (lazy folder under `projects//` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive//`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive//` into `projects//` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects//`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk). +- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#22:** `externalSession` guest slot (#92 — one at a time, transient per launch, takes the editor column; `openExternal(url:)` refuses non-file URLs, resolves symlinks (an atomic write renames over a symlink — the link would be severed), flushes and replaces, opening any Post/draft dismisses it flush-first via `dismissExternal`; `select`/`newPost` both route through the dismissal), a second `PostsWatcher` on the external file's folder (#93 — its events re-read the file and feed the session's `diskDidChange`, the #67 conflict check reused verbatim), `shutdown()` also flushes the guest (#96.3), and the import path: `stageImport`/`cancelImport` hold `pendingImportURLs` for the ONE Origin ask, `importFiles(origin:home:)` copies each via `PostStore.importFile`, continues past per-file failures into `lastError`, opens the last success, `wireSession()` routes both sessions' `onError` into the same strip. **#108:** project ops behind the variant-B library + Archive pane — `pendingProject` (the explicit target for the NEXT new piece, set by New Project, outranks selection, cleared when the draft lands, on `select`, and on `openExternal` — anywhere the draft dies), `targetProject` = pending ?? selected-non-archived ?? default, `flushOrAbort` (audit: `EditorSession.flush()` returns Bool — a failed write aborts the op and appends "— nothing was moved." to the flush-routed reason, never replacing it; the session stays up dirty), `moveToProject`/`archivePost`/`restorePost`/`rename`/`unarchiveProject` (all flush-first — audit 2 closed the rename + unarchive gaps; `unarchiveProject`'s membership check is disk-derived via `folder(of:)`, captured before the move, not the posts snapshot), `restorePost` (reopens the session off the archive path — `select` alone would keep the init-time `folderURL`; a cold restore still selects), `moveTargets(home:)` (audit 2: every project on disk + the default, localized-sorted — piece-derived keys hid empty projects), `createProject(named:) -> String?` (nil = success; the failure reason shows inline in the sheet, never double-messaged into `lastError`), `stageNewProject`/`cancelNewProject`/`askNewProject` (the New Project ask, pendingImportURLs pattern), `newProjectPending` (no re-validation — the sheet trimmed, `createProject` validated). +- `OutlineTree.swift` — #109 (ADR-0013) the Outline tree model (nonisolated, pure): `OutlineNode` (id = runtime UUID, regenerated per parse — fold keys in the view, never serialized; text is inert single-line markdown) + `OutlineTree` parse/serialize over the ONE-file plain nested-bullet format. Lenient parse, canonical serialize, normalize on save: `-`/`*` + space markers, any whitespace indent (tab = 2), repeated indent widths keep their established level while jumps clamp to prev+1 (4-space files parse as siblings, 8-space jumps don't orphan); lines before the first item are a verbatim preamble (`# Title` from the renamer survives above the tree), non-item lines after it drop; serialize emits `" " * depth + "- " + text`, no trailing newline. Structural ops are path-addressed (`[Int]`), move whole subtrees, preserve node UUIDs, and return the moved node's new path (nil = boundary no-op): `indent` (last child of previous sibling), `outdent` (right after parent), `move(up:)` (sibling swap; at a sibling boundary the block CROSSES ITS PARENT LogSeq-style — up lands directly before the parent, down directly after, one visible row per press; root boundary nil), `enter(caretOffset:)` (empty+depth>0 → outdent; empty root → new empty sibling below; else split at caret — whitespace at the split boundary rides off the tail's head, "hello world"@5 → "hello"+"world") with `EnterResult` for focus routing. Folds live in the view, keyed by node UUID — never modeled here. +- `OutlineEditorView.swift` — #109 the outliner editing surface (#105 verdict, variant B): `OutlinePresenter` (nonisolated, pure, tested) projects the tree into visible `Row`s (preorder, fold-skipping, per-row childCount + foldedDescendantCount), resolves id↔path/node + `setText` by identity, `rangeIDs` (block-selection span, ⇧↑/⇧↓ anchor↔focus) and `applyBatch` (block-selection structural ops: indent/outdent per-node, moves SIBLING-ONLY via `OutlineTree.siblingMove` with boundary-leader no-op — batch runs never cross parents, a crossing run tears itself apart; single-node ⌥↑/⌥↓ DOES cross parents, LogSeq-style). `OutlineEditorView` (SwiftUI): chrome bullets (fold toggle "●" when children, leaf "◦"; folded → accent + "⋯ N" mono-11 rust count) + per-depth 1px vertical rails (Canvas, 18px/level); ONE promoted `OutlineRowTextView` (borderless NSTextView subclass, native undo/IME, rust caret) on the focused row, static inline-markdown text elsewhere (tap focuses, caret at end — v1 ceiling, ponytail-marked); typography contract: live rows carry `ProseTypography.outlineRowAttributes` (body face, NATURAL line box — the prose CSS-1.8 `lineHeightMultiple` is deliberately absent: an inflated fragment grows the focused row and detaches the bullet; test-pinned), static rows render the same NSFont (no face swap on focus), the live row mirrors staticText's `.padding(.vertical, 3)`, and `sizeThatFits` floors at 21 so textview + padding = 27 — exactly the bullet-cell height, no focus jump. Key set (AppKit traps documented at the `keyDown` head: function-key scalars `"\u{F700}"`/`"\u{F701}"` — `String(NSUpArrowFunctionKey)` is its decimal description; `.function`/`.numericPad` bits stripped before modifier compare; ⇧⇥ = backtab `\u{19}` with an `insertBacktab` override; Esc via a local `NSEvent` keyDown monitor — SwiftUI's hosting layer swallows Esc before keyDown AND before `.onExitCommand`, probe-pinned in EscEventProbeTests): Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree · ↑/↓ hop VISIBLE blocks · ⇧↑/⇧↓ extend block selection (anchor↔focus highlight, batch structural ops; bare arrows/click/typing clear) · ⌘↑/⌘↓ fold/unfold · Enter → `enter` (UTF-16→grapheme caret conversion). Folds are session-scoped view state (`folded: Set`, reset on every load — never serializes, ADR-0013). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` (debounce/⌘S/#67 conflict unchanged) or `onDraftEdit` for drafts; focus follows node IDs (they travel through ops), caret lands via `pendingCaret` at next mount. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner (⌘S/toolbar/conflict/reading toggle all keep working — reading renders the serialized markdown via apex unchanged); `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions (`PostsModel.lastDraftWasOutline` covers the rescan lag after a fresh save; cleared in newPost/select/openExternal wherever the draft dies). - Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save). - `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css). - Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line. diff --git a/Museion/MuseionApp.swift b/Museion/MuseionApp.swift index e26b5dd..181e110 100644 --- a/Museion/MuseionApp.swift +++ b/Museion/MuseionApp.swift @@ -88,9 +88,11 @@ struct MuseionApp: App { // File menu after New — never CommandMenu("File"), which doubles // it (#84 trap). CommandGroup(after: .newItem) { - // #108: New Post / New Project… go FIRST in the group — the - // menu reads New Post / New Project… / Open… / Import… + // #108/#109: New Post / New Outline / New Project… go FIRST in + // the group — the menu reads New Post / New Outline / + // New Project… / Open… / Import… NewPostButton(gate: gate) + NewOutlineButton(gate: gate) NewProjectButton(gate: gate) OpenExternalButton(gate: gate) ImportFilesButton(gate: gate) @@ -176,6 +178,17 @@ private struct NewPostButton: View { } } +/// #109: File ▸ New Outline (⇧⌘N) — newPost's draft path with an outline +/// draft (body "- ", type .outline); the outline surface parses the seed. +private struct NewOutlineButton: View { + let gate: AppGateState + + var body: some View { + Button("New Outline") { gate.posts.newOutline() } + .keyboardShortcut("n", modifiers: [.command, .shift]) + } +} + /// #108: File ▸ New Project… (⌥⌘N) — stages the ask; WorkspaceView presents /// the sheet (commands views can't; the pendingImportURLs pattern, #94). private struct NewProjectButton: View { diff --git a/Museion/OutlineEditorView.swift b/Museion/OutlineEditorView.swift new file mode 100644 index 0000000..5135753 --- /dev/null +++ b/Museion/OutlineEditorView.swift @@ -0,0 +1,716 @@ +// +// OutlineEditorView.swift +// Museion +// +// #109 (ADR-0013, #105 verdict — variant B): the outliner editing surface. +// Chrome bullets + per-depth vertical rails; ONE promoted NSTextView on +// the focused row (native undo/IME), static inline-markdown text +// elsewhere. Tab/⇧Tab/⌥↑/⌥↓/Enter reshape whole subtrees through +// OutlineTree; ↑/↓ hop visible blocks; folds are pure view state keyed by +// node id — toggling them never serializes. Every text/structure edit +// re-serializes into the existing EditorSession debounce/⌘S/conflict +// machinery (`session.edit`) or the draft callbacks — the save path is +// untouched. Reading mode keeps rendering the serialized markdown via the +// apex surface (nested lists render natively there). +// + +import AppKit +import SwiftUI + +// MARK: - Pure projection (tested) + +/// The outliner's view-facing projection over `[OutlineNode]`: which rows +/// are visible given the fold set, plus the chrome data each row renders +/// from. Pure tree math — no UI. +nonisolated enum OutlinePresenter { + nonisolated struct Row: Equatable, Identifiable { + let id: UUID + var depth: Int + var text: String + /// 0 = leaf bullet (never foldable). Structure fact, not view state. + var childCount: Int + var isFolded: Bool + /// Total nodes hidden under this row's fold ("⋯ N"); 0 unless folded. + var foldedDescendantCount: Int + } + + /// Preorder walk emitting one Row per visible node — a folded node's + /// whole subtree is skipped and counted. + static func visibleRows(_ nodes: [OutlineNode], folded: Set) -> [Row] { + var rows: [Row] = [] + walk(nodes, parent: [], depth: 0, folded: folded, into: &rows) + return rows + } + + private static func walk( + _ nodes: [OutlineNode], parent: [Int], depth: Int, folded: Set, into rows: inout [Row], + ) { + for (index, node) in nodes.enumerated() { + let path = parent + [index] + let isFolded = folded.contains(node.id) + rows.append( + Row( + id: node.id, + depth: depth, + text: node.text, + childCount: node.children.count, + isFolded: isFolded, + foldedDescendantCount: isFolded ? countTree(node.children) : 0, + ), + ) + if !isFolded { + walk(node.children, parent: path, depth: depth + 1, folded: folded, into: &rows) + } + } + } + + private static func countTree(_ nodes: [OutlineNode]) -> Int { + nodes.reduce(0) { $0 + 1 + countTree($1.children) } + } + + /// The visible-row ids from `from` to `to`, inclusive, in visible + /// order; nil when either id isn't visible. Block-selection range + /// math (⇧↑/⇧↓ anchor↔focus). + static func rangeIDs(from: UUID, to: UUID, in nodes: [OutlineNode], folded: Set) -> [UUID]? { + let rows = visibleRows(nodes, folded: folded) + guard let startIdx = rows.firstIndex(where: { $0.id == from }), + let endIdx = rows.firstIndex(where: { $0.id == to }) + else { return nil } + return rows[min(startIdx, endIdx) ... max(startIdx, endIdx)].map(\.id) + } + + /// Structural ops that make sense on a block-selection run. + enum BatchOp { + case indent + case outdent + case moveUp + case moveDown + } + + /// Batch-apply a structural op to a run of visible-row ids (block + /// selection), re-resolving each path by id after every move. Moves + /// are SIBLING-ONLY here: a batch move never crosses a parent — + /// if the run's leader is at a sibling boundary the whole batch + /// no-ops (a run that crosses parents tears itself apart). Indent + /// and outdent apply per node. + /// ponytail: a mixed-level run can half-apply (leader moves, later + /// member at boundary); two-pass dry-run is the upgrade if that + /// ever bites. Returns whether anything changed. + @discardableResult + static func applyBatch(_ op: BatchOp, ids: [UUID], to nodes: inout [OutlineNode]) -> Bool { + let ordered = (op == .moveDown || op == .outdent) ? ids.reversed() : ids + var didChange = false + for id in ordered { + guard let path = path(of: id, in: nodes) else { continue } + let moved: Bool = switch op { + case .indent: OutlineTree.indent(&nodes, path: path) != nil + case .outdent: OutlineTree.outdent(&nodes, path: path) != nil + case .moveUp: OutlineTree.siblingMove(&nodes, path: path, up: true) + case .moveDown: OutlineTree.siblingMove(&nodes, path: path, up: false) + } + if !moved, op == .moveUp || op == .moveDown { + // Run moves as a unit; its leader is at a sibling + // boundary. The leader runs first — nothing moved yet. + return didChange + } + didChange = didChange || moved + } + return didChange + } + + /// Find a node's path by identity. nil = not in the tree. + static func path(of id: UUID, in nodes: [OutlineNode]) -> [Int]? { + for (index, node) in nodes.enumerated() { + if node.id == id { + return [index] + } + if let deeper = path(of: id, in: node.children) { + return [index] + deeper + } + } + return nil + } + + /// The node at a root→leaf index path — focus routing after structural + /// ops return the moved node's new path. nil = path doesn't resolve. + static func node(at path: [Int], in nodes: [OutlineNode]) -> OutlineNode? { + guard let first = path.first, nodes.indices.contains(first) else { return nil } + let current = nodes[first] + return path.count == 1 ? current : node(at: Array(path.dropFirst()), in: current.children) + } + + /// Replace one node's text by identity. False = id not in the tree. + /// Single-line contract enforced HERE: pasted newlines become spaces + /// (splitting into siblings needs anchor/caret math in the view; + /// the space-join is the safe floor that can't lose content). + @discardableResult + static func setText(_ text: String, id: UUID, in nodes: inout [OutlineNode]) -> Bool { + let sanitized = text.replacingOccurrences(of: "\r\n", with: " ") + .replacingOccurrences(of: "\n", with: " ") + .replacingOccurrences(of: "\r", with: " ") + for index in nodes.indices { + if nodes[index].id == id { + nodes[index].text = sanitized + return true + } + if setText(sanitized, id: id, in: &nodes[index].children) { + return true + } + } + return false + } +} + +// MARK: - The surface + +/// The outline editing surface (#109): rows of chrome (guide rails, +/// bullets, fold counts) around one live caret row. Session mode re-parses +/// on `loadGeneration` bumps (open / Yes-reload); draft mode seeds from +/// `draftText` once and streams edits out through `onDraftEdit`. +struct OutlineEditorView: View { + var session: EditorSession? + var onDraftEdit: ((String) -> Void)? + /// Draft mode: the text at mount. Later values are ignored — after the + /// seed the view's tree owns the document until the next mount. + var draftText: String? + + @State private var preamble: [String] = [] + @State private var nodes: [OutlineNode] = [] + /// View state, keyed by node id; reset on every load (session-scoped). + @State private var folded: Set = [] + @State private var focusedID: UUID? + /// Block-selection anchor (⇧↑/⇧↓). nil = no range selected; the range + /// runs anchor↔focusedID over visible rows. View state, like folds. + @State private var selectionAnchor: UUID? + /// Caret (grapheme offset) the NEXT mounted row editor lands on; + /// nil = end. Read at mount only — the live view owns the caret after. + @State private var pendingCaret: Int? + @State private var loadedGeneration = -1 + /// Esc delivery: SwiftUI's hosting layer swallows Esc before the row + /// textview's keyDown AND before .onExitCommand (probe-pinned — + /// EscEventProbeTests). A local monitor sees the event first. + @State private var escMonitor: Any? + + var body: some View { + let rows = OutlinePresenter.visibleRows(nodes, folded: folded) + Group { + if rows.isEmpty { + VStack(spacing: 10) { + Image(systemName: "list.bullet") + .font(.largeTitle) + .foregroundStyle(DesignTokens.muted) + Text("An empty outline — every line is a node.") + .font(.callout) + .foregroundStyle(DesignTokens.muted) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + ScrollView { + LazyVStack(alignment: .leading, spacing: 0) { + ForEach(rows) { row in + rowView(row) + } + } + .padding(.top, 24) + .padding(.bottom, 80) + } + } + } + .onAppear { + loadIfNeeded() + installEscMonitor() + } + .onChange(of: session?.loadGeneration) { _, _ in loadIfNeeded() } + .onDisappear { removeEscMonitor() } + } + + /// Local monitor: the ONLY reliable Esc path into this surface + /// (probe: sendEvent → hosted keyDown never fires for Esc). Fires + /// only while the outliner's own row textview is first responder, + /// swallows the event only when there's a selection to collapse. + private func installEscMonitor() { + guard escMonitor == nil else { return } + escMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in + guard event.keyCode == 53, // Esc + (NSApp.keyWindow?.firstResponder as? RowTextView) != nil + else { return event } + if selectionAnchor != nil { + selectionAnchor = nil + return nil // swallowed — the selection was the target + } + return event + } + } + + private func removeEscMonitor() { + if let escMonitor { + NSEvent.removeMonitor(escMonitor) + } + escMonitor = nil + } + + /// (Re)parse from the source of truth. Session: only when the load + /// generation moved (open, Yes-reload) — never per keystroke, the view + /// owns the live tree. Draft: seed once at mount. Every load resets + /// folds — fresh open = all unfolded, never dirties the document. + private func loadIfNeeded() { + if let session { + guard session.loadGeneration != loadedGeneration else { return } + loadedGeneration = session.loadGeneration + let parsed = OutlineTree.parse(session.text) + preamble = parsed.preamble + nodes = parsed.nodes + } else { + guard loadedGeneration < 0 else { return } + loadedGeneration = 0 + let parsed = OutlineTree.parse(draftText ?? "") + preamble = parsed.preamble + nodes = parsed.nodes + } + folded = [] + focusedID = nodes.first?.id + selectionAnchor = nil + pendingCaret = nil + } + + // MARK: Rows + + private func rowView(_ row: OutlinePresenter.Row) -> some View { + HStack(alignment: .top, spacing: 0) { + // Per-depth guide rails (prototype variant B: 1px hairline per + // ancestor level at level*18+11, 18px indent per depth). + Canvas { context, size in + for level in 0 ..< row.depth { + let railX = CGFloat(level) * 18 + 11 + context.fill( + Path(CGRect(x: railX, y: 0, width: 1, height: size.height)), + with: .color(DesignTokens.border), + ) + } + } + .frame(width: CGFloat(row.depth) * 18) + bullet(row) + if row.id == focusedID { + OutlineRowTextView( + text: row.text, + caret: pendingCaret, + onEdit: { newText in + selectionAnchor = nil // typing replaces block selection + OutlinePresenter.setText(newText, id: row.id, in: &nodes) + pushToDocument() + }, + onStructure: { op in apply(op) }, + ) + .padding(.vertical, 3) // same inset as staticText — no focus jump + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + } else { + staticText(row) + } + if row.isFolded, row.foldedDescendantCount > 0 { + Text("⋯ \(row.foldedDescendantCount)") + .font(.system(size: 11, design: DesignTokens.mono)) + .foregroundStyle(DesignTokens.accent) + .padding(.leading, 6) + .padding(.top, 5) + } + } + .padding(.horizontal, 20) + // Block-selection highlight (⇧↑/⇧↓ range, anchor↔focus). + .background(rowSelected(row) ? DesignTokens.accent.opacity(0.08) : Color.clear) + } + + /// The bullet cell (22×27): fold toggle when the node has children + /// ("●" ~7pt, folded → accent), leaf "◦" ~10pt; tapping a leaf focuses. + @ViewBuilder + private func bullet(_ row: OutlinePresenter.Row) -> some View { + let foldable = row.childCount > 0 + let glyph = Text(foldable ? "●" : "◦") + .font(.system(size: foldable ? 7 : 10)) + .foregroundStyle(row.isFolded ? DesignTokens.accent : DesignTokens.muted) + if foldable { + Button { + toggleFold(row.id) + } label: { + glyph.frame(width: 22, height: 27) + } + .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) } + } + } + + /// Static row text: inert inline markdown; `[[wiki-links]]` stay + /// literal (the plain-Text fallback keeps them so either way). + /// Same NSFont as the live row (Valkyrie 17) — no face swap on focus. + private func staticText(_ row: OutlinePresenter.Row) -> some View { + Group { + if row.text.isEmpty { + Text(" ") + .font(Font(ProseTypography.bodyFont)) + .foregroundStyle(DesignTokens.border) + } else if let attributed = try? AttributedString( + markdown: row.text, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace), + ) { + Text(attributed) + .font(Font(ProseTypography.bodyFont)) + .foregroundStyle(DesignTokens.foreground) + } else { + Text(row.text) + .font(Font(ProseTypography.bodyFont)) + .foregroundStyle(DesignTokens.foreground) + } + } + .padding(.vertical, 3) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + // Clicking another row focuses it, caret at END. + // ponytail: no click-position caret mapping in v1 — mid-word clicks + // land at the row's end; a textview hit-test is the upgrade path. + .onTapGesture { focus(row.id) } + } + + // MARK: Focus + folds + + private func focus(_ id: UUID) { + guard id != focusedID else { return } + focusedID = id + selectionAnchor = nil // a click is a fresh single focus + pendingCaret = nil // caret at end + } + + private func toggleFold(_ id: UUID) { + // View state ONLY — never serializes, never session.edit/draftEdited. + if folded.contains(id) { + folded.remove(id) + } else { + folded.insert(id) + } + } + + // MARK: Structure + + /// One key from the focused row's textview. View-state keys mutate + /// `folded`/focus directly; tree keys go through OutlineTree at the + /// focused node's path. Node ids travel through every op, so focus + /// follows the RESULT's node id, never the stale path. + private func apply(_ op: OutlineRowTextView.StructureOp) { + switch op { + case .fold: + // ⌘↑: fold the focused node when it has children. + if let id = focusedID, childCount(of: id) > 0 { + folded.insert(id) + } + case .unfold: + if let id = focusedID { + folded.remove(id) + } + case let .hop(direction): + // ↑/↓ hop VISIBLE blocks — folded subtrees are skipped. + let rows = OutlinePresenter.visibleRows(nodes, folded: folded) + if let current = rows.firstIndex(where: { $0.id == focusedID }), + rows.indices.contains(current + direction) + { + focusedID = rows[current + direction].id + selectionAnchor = nil + pendingCaret = nil // caret at end of the target row + } + case let .extend(direction): + // ⇧↑/⇧↓: extend the block selection one visible row. First + // press anchors at the focused row; a bare ↑/↓ or click clears. + if selectionAnchor == nil { + selectionAnchor = focusedID + } + let rows = OutlinePresenter.visibleRows(nodes, folded: folded) + if let current = rows.firstIndex(where: { $0.id == focusedID }), + rows.indices.contains(current + direction) + { + focusedID = rows[current + direction].id + pendingCaret = nil + } + case .deselect: + selectionAnchor = nil + case .indent, .outdent, .moveUp, .moveDown, .enter: + applyTree(op) + } + } + + /// Tree-mutating ops (indent/outdent/move/enter). Serialize + route + /// focus only when something actually changed (boundary no-ops are + /// nil and leave the document alone). + private func applyTree(_ op: OutlineRowTextView.StructureOp) { + guard let focusedID else { return } + // Block selection + batchable op → run-wide apply. Moves treat + // the run as a unit (boundary leader no-ops the whole batch). + if let anchor = selectionAnchor, + let range = selectedRangeIDs(anchor: anchor, focus: focusedID), range.count > 1, + let batchOp = map(op) + { + if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) { + pushToDocument() + } + return + } + guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return } + var didChange = false + var newFocus: (id: UUID, caret: Int)? + switch op { + case .indent: + didChange = OutlineTree.indent(&nodes, path: path) != nil + case .outdent: + didChange = OutlineTree.outdent(&nodes, path: path) != nil + case .moveUp: + didChange = OutlineTree.move(&nodes, path: path, up: true) != nil + case .moveDown: + didChange = OutlineTree.move(&nodes, path: path, up: false) != nil + case let .enter(caretGraphemes): + switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) { + case .noOp: + break + case let .outdented(newPath): + didChange = newPath != nil // nil = boundary no-op + case let .newNode(newPath, caret): + didChange = true + if let id = OutlinePresenter.node(at: newPath, in: nodes)?.id { + newFocus = (id, caret) + } + } + case .fold, .unfold, .hop, .extend, .deselect: + return // unreachable — apply(_:) routes those to view state + } + if didChange { + if let newFocus { + self.focusedID = newFocus.id + pendingCaret = newFocus.caret + } + pushToDocument() + } + } + + /// The selected row ids in visible order (anchor↔focus, inclusive). + private func selectedRangeIDs(anchor: UUID, focus: UUID) -> [UUID]? { + OutlinePresenter.rangeIDs(from: anchor, to: focus, in: nodes, folded: folded) + } + + /// Row background when inside the block selection. + private func rowSelected(_ row: OutlinePresenter.Row) -> Bool { + guard let anchor = selectionAnchor else { return false } + return selectedRangeIDs(anchor: anchor, focus: focusedID ?? anchor)?.contains(row.id) ?? false + } + + /// StructureOp → the batchable op for block-selection runs. + private func map(_ op: OutlineRowTextView.StructureOp) -> OutlinePresenter.BatchOp? { + switch op { + case .indent: .indent + case .outdent: .outdent + case .moveUp: .moveUp + case .moveDown: .moveDown + default: nil // enter/fold/etc. never batch + } + } + + private func childCount(of id: UUID) -> Int { + guard let path = OutlinePresenter.path(of: id, in: nodes) else { return 0 } + return OutlinePresenter.node(at: path, in: nodes)?.children.count ?? 0 + } + + /// Every text keystroke and structural op lands here: serialize the + /// whole tree and hand it to the unchanged save machinery. + private func pushToDocument() { + let md = OutlineTree.serialize(preamble: preamble, nodes: nodes) + if let session { + session.edit(md) + } else { + onDraftEdit?(md) + } + } +} + +// MARK: - The promoted row editor + +/// The focused row's live editor (#109): borderless plain NSTextView with +/// native undo/IME and an accent caret, wrapping at the column width (no +/// horizontal scroll). `keyDown` intercepts the structural key set; every +/// intercepted branch returns WITHOUT super (swallow); unhandled keys → +/// super (native IME/undo/text). The branch swap on focus change remounts +/// it per row. +struct OutlineRowTextView: NSViewRepresentable { + enum StructureOp: Equatable { + case indent + case outdent + case moveUp + case moveDown + case enter(caretGraphemes: Int) + case fold + case unfold + /// -1 = previous visible row, +1 = next. + case hop(direction: Int) + /// ⇧↑/⇧↓: extend block selection one visible row from the anchor. + case extend(direction: Int) + /// Esc: collapse the block selection. + case deselect + } + + var text: String + /// Grapheme offset for the caret at mount; nil = end. Never reapplied + /// on update — the live view owns the caret after mount. + var caret: Int? + var onEdit: (String) -> Void + var onStructure: (StructureOp) -> Void + + func makeNSView(context: Context) -> RowTextView { + let tv = RowTextView() + tv.bridge = context.coordinator + tv.allowsUndo = true + tv.isRichText = false + tv.isAutomaticQuoteSubstitutionEnabled = false + tv.isAutomaticDashSubstitutionEnabled = false + tv.isAutomaticTextReplacementEnabled = false + tv.isAutomaticSpellingCorrectionEnabled = false + tv.backgroundColor = .clear + tv.drawsBackground = false + tv.insertionPointColor = NSColor(DesignTokens.accent) + tv.typingAttributes = ProseTypography.outlineRowAttributes + tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude) + tv.textContainer?.widthTracksTextView = true + tv.textContainer?.heightTracksTextView = false + tv.textContainer?.lineFragmentPadding = 0 + tv.textContainerInset = .zero + tv.isHorizontallyResizable = false + tv.isVerticallyResizable = true + tv.minSize = .zero + tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) + tv.autoresizingMask = [.width] + tv.string = text + // Caret at mount: grapheme offset → UTF-16 for NSTextView. + let head = String(text.prefix(caret.map { min(max($0, 0), text.count) } ?? text.count)) + tv.setSelectedRange(NSRange(location: (head as NSString).length, length: 0)) + tv.delegate = context.coordinator + context.coordinator.lastLocalText = text + DispatchQueue.main.async { [weak tv] in + tv?.window?.makeFirstResponder(tv) + } + return tv + } + + func updateNSView(_ tv: RowTextView, context: Context) { + context.coordinator.onEdit = onEdit + context.coordinator.onStructure = onStructure + // Echo guard, ProseTextView-draft-mode pattern: our own keystrokes + // round-trip byte-equal through the model, so only adopt when the + // model's text differs from what this view last emitted — that's a + // structural reshape or a reload. Caret parks at end (structural + // changes that keep focus — outdent — move no text). + if text != context.coordinator.lastLocalText, tv.string != text { + tv.string = text + tv.setSelectedRange(NSRange(location: (text as NSString).length, length: 0)) + context.coordinator.lastLocalText = text + } + } + + /// The row wraps: height = laid-out height at the proposed width. + func sizeThatFits(_ proposal: ProposedViewSize, nsView tv: RowTextView, context _: Context) -> CGSize? { + guard let container = tv.textContainer, let layoutManager = tv.layoutManager else { return nil } + let width = proposal.width ?? tv.bounds.width + guard width > 0, width < .greatestFiniteMagnitude else { return nil } + container.containerSize = NSSize(width: width, height: .greatestFiniteMagnitude) + layoutManager.ensureLayout(for: container) + // No vertical fudge: the row's .padding(.vertical, 3) mirrors staticText, + // so focused and static baselines coincide. Floor 21 + 6 padding = 27: + // the bullet cell's height — the row must not grow on focus. + let height = layoutManager.usedRect(for: container).height + return CGSize(width: width, height: max(height, 21)) + } + + func makeCoordinator() -> Coordinator { + Coordinator() + } + + final class Coordinator: NSObject, NSTextViewDelegate { + var onEdit: ((String) -> Void)? + var onStructure: ((StructureOp) -> Void)? + /// The text this view last emitted/saw — the echo-guard reference. + var lastLocalText = "" + + func textDidChange(_ notification: Notification) { + guard let tv = notification.object as? NSTextView else { return } + lastLocalText = tv.string + tv.typingAttributes = ProseTypography.outlineRowAttributes + onEdit?(tv.string) + } + } +} + +/// The row NSTextView: structural key interception. +final class RowTextView: NSTextView { + weak var bridge: OutlineRowTextView.Coordinator? + + override func keyDown(with event: NSEvent) { + let key = event.charactersIgnoringModifiers ?? "" + // Arrow matching traps: the character IS the function-key scalar + // (String(NSUpArrowFunctionKey) would be its decimal description, + // "63232"), and arrow events carry .function/.numericPad device + // bits — strip them so == .command/.option/.shift can match. + let upKey = "\u{F700}" // NSUpArrowFunctionKey + let downKey = "\u{F701}" // NSDownArrowFunctionKey + let modifiers = event.modifierFlags + .intersection(.deviceIndependentFlagsMask) + .subtracting([.function, .numericPad]) + + if key == upKey || key == downKey { + let up = key == upKey + switch modifiers { + case .command: + bridge?.onStructure?(up ? .fold : .unfold) + case .option: + bridge?.onStructure?(up ? .moveUp : .moveDown) + case .shift: + bridge?.onStructure?(.extend(direction: up ? -1 : 1)) + default: + bridge?.onStructure?(.hop(direction: up ? -1 : 1)) + } + return + } + if key == "\t" { + bridge?.onStructure?(modifiers.contains(.shift) ? .outdent : .indent) + return + } + if key == "\u{19}" { // NSBackTabCharacter — ⇧⇥ arrives as backtab, not " " + shift + bridge?.onStructure?(.outdent) + return + } + if key == "\u{1b}" { // Esc: collapse the block selection + bridge?.onStructure?(.deselect) + return + } + if key == "\r" || key == "\n" { + // THE conversion (classic trap): selectedRange().location is a + // UTF-16 offset; enter() counts GRAPHEME clusters. Passing the + // raw number splits emoji/CJK clusters mid-grapheme. Clamp, + // convert through String.Index, then count characters. + let text = string + let utf16Location = min(max(0, selectedRange().location), text.utf16.count) + let index = String.Index(utf16Offset: utf16Location, in: text) + let graphemes = text.distance(from: text.startIndex, to: index) + bridge?.onStructure?(.enter(caretGraphemes: graphemes)) + return + } + super.keyDown(with: event) + } + + /// Some AppKit paths deliver ⇧⇥ here instead of keyDown. + override func insertBacktab(_: Any?) { + bridge?.onStructure?(.outdent) + } + + /// Esc on NSTextView routes here (doCommandBy:), not always keyDown. + override func cancelOperation(_: Any?) { + bridge?.onStructure?(.deselect) + } +} diff --git a/Museion/OutlineTree.swift b/Museion/OutlineTree.swift new file mode 100644 index 0000000..70f17da --- /dev/null +++ b/Museion/OutlineTree.swift @@ -0,0 +1,290 @@ +// +// OutlineTree.swift +// Museion +// +// #109 (ADR-0013/ADR-0012): the Outline tree model. Plain nested-bullet +// markdown is the whole storage format — indentation = nesting, node text +// is inert inline markdown, no node ids on disk. Lenient parse, canonical +// serialize, normalize on save: `-`/`*` markers, any whitespace indent +// (tab = 2 spaces), depth clamps to previous + 1; everything comes back +// out as 2-space + `- ` canonical form. Node ids are runtime identity +// only — they ride the nodes through every structural op so view state +// (folds) keyed by UUID survives edits. +// + +import Foundation + +/// One outline row: single-line text (never contains "\n") plus nested +/// children. `id` is runtime identity, regenerated per parse. +nonisolated struct OutlineNode: Identifiable, Equatable { + let id: UUID + var text: String + var children: [OutlineNode] + + init(text: String = "", children: [OutlineNode] = []) { + id = UUID() + self.text = text + self.children = children + } +} + +/// Parse/serialize + whole-subtree structural operations over `[OutlineNode]`. +/// All ops are path-addressed (`[Int]` root→leaf indices) and return the +/// moved node's new path, or nil when the op is a boundary no-op. +nonisolated enum OutlineTree { + /// Lenient parse. Returns verbatim preamble lines (before the first item) + /// + the node tree. `-`/`*` markers followed by whitespace, any indent + /// (tab = 2 spaces, depth = width/2), depth clamps to previous + 1; + /// non-item lines after the first item are dropped (normalize on save). + static func parse(_ markdown: String) -> (preamble: [String], nodes: [OutlineNode]) { + let (preamble, items) = scan(markdown) + return (preamble, build(items, from: 0, depth: 0).nodes) + } + + /// Canonical serialize: preamble lines verbatim, then preorder walk + /// emitting `" " * depth + "- " + text` per node, joined by "\n". + /// NO trailing newline. Empty everything → "". + static func serialize(preamble: [String], nodes: [OutlineNode]) -> String { + var lines = preamble + func walk(_ nodes: [OutlineNode], depth: Int) { + for node in nodes { + lines.append(String(repeating: " ", count: depth) + "- " + node.text) + walk(node.children, depth: depth + 1) + } + } + walk(nodes, depth: 0) + return lines.joined(separator: "\n") + } + + /// Lines → (verbatim preamble, flat clamped items). Trailing blank lines + /// are noise — dropping them makes "" parse to ([], []). + private static func scan(_ markdown: String) -> (preamble: [String], items: [(depth: Int, text: String)]) { + var lines = markdown.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + while lines.last?.isEmpty == true { + lines.removeLast() + } + var preamble: [String] = [] + var items: [(depth: Int, text: String)] = [] + var prevDepth = -1 + // Raw indent width → established depth: a repeated width keeps its + // level (the 4-space file's siblings), never above prev + 1 (no + // orphans — the 8-space jump clamps). + var widthDepths: [Int: Int] = [:] + for line in lines { + guard let item = parseItem(line) else { + if items.isEmpty { + preamble.append(line) + } // else: non-item after content → dropped + continue + } + let depth = min(widthDepths[item.width] ?? item.width, prevDepth + 1) + widthDepths[item.width] = depth + items.append((depth, item.text)) + prevDepth = depth + } + return (preamble, items) + } + + /// One item line → (indent width in 2-space units, text): leading + /// whitespace (tab = 2 spaces), then `-`/`*` + separator. nil = not an + /// item line. + private static func parseItem(_ line: String) -> (width: Int, text: String)? { + let scalars = Array(line.unicodeScalars) + var index = 0 + var width = 0 + while index < scalars.count, scalars[index] != "-", scalars[index] != "*" { + let scalar = scalars[index] + guard scalar == "\t" || CharacterSet.whitespaces.contains(scalar) else { return nil } + width += scalar == "\t" ? 2 : 1 + index += 1 + } + guard index + 1 < scalars.count, scalars[index] == "-" || scalars[index] == "*", + scalars[index + 1] == " " || scalars[index + 1] == "\t" + else { return nil } + return (width / 2, String(String.UnicodeScalarView(scalars[(index + 2)...]))) + } + + /// Flat clamped items → nested nodes. Clamping keeps depths contiguous, + /// so every deeper item is a child of the nearest shallower one. + private static func build( + _ items: [(depth: Int, text: String)], from index: Int, depth: Int, + ) -> (nodes: [OutlineNode], next: Int) { + var nodes: [OutlineNode] = [] + var cursor = index + while cursor < items.count, items[cursor].depth == depth { + let (children, next) = build(items, from: cursor + 1, depth: depth + 1) + nodes.append(OutlineNode(text: items[cursor].text, children: children)) + cursor = next + } + return (nodes, cursor) + } + + // MARK: Structural ops + + /// Runs `body` on the sibling array holding `path`'s target (the children + /// of `path.dropLast()`; the root array for single-segment paths). + /// False when the path doesn't resolve — `body` always gets a valid index. + @discardableResult + private static func withSiblings( + of path: [Int], in nodes: inout [OutlineNode], _ body: (inout [OutlineNode], Int) -> Bool, + ) -> Bool { + guard let last = path.last, last >= 0 else { return false } + let parent = Array(path.dropLast()) + guard parent.isEmpty else { + return withSiblings(of: parent, in: &nodes) { parentChildren, parentIndex in + guard parentIndex < parentChildren.count else { return false } + return body(&parentChildren[parentIndex].children, last) + } + } + guard last < nodes.count else { return false } + return body(&nodes, last) + } + + /// Sibling-only move (the pre-parent-crossing semantics) for batch + /// runs: swap with prev/next sibling, false at the boundary. + static func siblingMove(_ nodes: inout [OutlineNode], path: [Int], up: Bool) -> Bool { + var moved = false + withSiblings(of: path, in: &nodes) { siblings, index in + let target = up ? index - 1 : index + 1 + guard siblings.indices.contains(target) else { return false } + siblings.swapAt(index, target) + moved = true + return true + } + return moved + } + + /// Tab. Node at `path` becomes the LAST child of its previous sibling. + /// No previous sibling → no-op, returns nil. + static func indent(_ nodes: inout [OutlineNode], path: [Int]) -> [Int]? { + guard let last = path.last, last > 0 else { return nil } + var newPath: [Int]? + let moved = withSiblings(of: path, in: &nodes) { siblings, index in + let node = siblings.remove(at: index) + siblings[index - 1].children.append(node) + newPath = Array(path.dropLast()) + [index - 1, siblings[index - 1].children.count - 1] + return true + } + return moved ? newPath : nil + } + + /// ⇧Tab. Node moves to sit right AFTER its parent among the parent's + /// siblings. Root level → no-op, returns nil. Children travel. + static func outdent(_ nodes: inout [OutlineNode], path: [Int]) -> [Int]? { + guard path.count >= 2, let last = path.last, last >= 0 else { return nil } + var moved: OutlineNode? + guard withSiblings(of: path, in: &nodes, { siblings, index in + moved = siblings.remove(at: index) + return true + }), let node = moved else { return nil } + let parentIndex = path[path.count - 2] + var newPath: [Int]? + guard withSiblings(of: Array(path.dropLast()), in: &nodes, { parentSiblings, _ in + guard parentIndex < parentSiblings.count else { return false } + parentSiblings.insert(node, at: parentIndex + 1) + newPath = Array(path.dropLast(2)) + [parentIndex + 1] + return true + }) else { return nil } + return newPath + } + + /// ⌥↑/⌥↓. Swap with previous/next sibling, subtree travels as a unit. + /// At a sibling boundary the block CROSSES ITS PARENT (LogSeq): up → + /// lands directly before the parent, down → directly after it (one + /// visible row per press, never skipping uncles). Root boundary → + /// no-op, returns nil. + // swiftlint:disable:next identifier_name + static func move(_ nodes: inout [OutlineNode], path: [Int], up: Bool) -> [Int]? { + var newPath: [Int]? + let moved = withSiblings(of: path, in: &nodes) { siblings, index in + let target = up ? index - 1 : index + 1 + guard siblings.indices.contains(target) else { return false } + siblings.swapAt(index, target) + newPath = Array(path.dropLast()) + [target] + return true + } + if moved { + return newPath + } + guard path.count >= 2 else { return nil } // root boundary + + // Parent-crossing: pull the node out, insert at the grandparent level. + var extracted: OutlineNode? + _ = withSiblings(of: path, in: &nodes) { siblings, index in + extracted = siblings.remove(at: index) + return true + } + guard let node = extracted else { return nil } + let parentIndex = path[path.count - 2] + var insertedPath: [Int]? + _ = withSiblings(of: Array(path.dropLast()), in: &nodes) { parentSiblings, _ in + // up → directly before the parent; down → directly after it + // (parentIndex + 1 == count appends — the last-child case). + let slot = up ? parentIndex : parentIndex + 1 + parentSiblings.insert(node, at: slot) + insertedPath = Array(path.dropLast(2)) + [slot] + return true + } + return insertedPath + } + + /// Enter. Empty (whitespace-only) node at depth > 0 outdents; empty root + /// node gets a new empty sibling below; otherwise split at the caret — + /// the node keeps the head, a new sibling right below carries the tail. + /// `caretOffset` is in grapheme clusters, clamped to the text length. + static func enter(_ nodes: inout [OutlineNode], path: [Int], caretOffset: Int) -> EnterResult { + var nodeText: String? + guard withSiblings(of: path, in: &nodes, { siblings, index in + nodeText = siblings[index].text + return true + }), let text = nodeText else { return .noOp } + + if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + guard path.count >= 2 else { // empty root node → new empty sibling below + var newPath: [Int]? + _ = withSiblings(of: path, in: &nodes) { siblings, index in + siblings.insert(OutlineNode(text: ""), at: index + 1) + newPath = Array(path.dropLast()) + [index + 1] + return true + } + return .newNode(path: newPath ?? path, caret: 0) + } + return .outdented(path: outdent(&nodes, path: path)) + } + + // Split at the caret: node keeps the head, new sibling right below + // carries the tail (caret at end → empty new sibling). Whitespace at + // the split boundary drops off the tail's head — "hello world" @5 is + // "hello"+"world" (the pinned example), not "hello"+" world". + let offset = min(max(caretOffset, 0), text.count) + let split = text.index(text.startIndex, offsetBy: offset) + var head = String(text[.. Void)? var draftSave: (() -> Void)? + /// #109: render the outline editing surface instead of prose. + var outline = false @State private var closeObserver: AnyCancellable? @State private var toggleObserver: AnyCancellable? @@ -159,7 +161,17 @@ struct PostEditorView: View { @ViewBuilder private var editingSurface: some View { - if let session { + if outline { + // #109: the outliner — same session/draft duality as prose. + // Draft mode keeps the mirror current via draftEdited so the + // reading surface renders the serialized outline; the outline + // view seeds from draftText once and owns the tree after. + OutlineEditorView( + session: session, + onDraftEdit: session == nil ? { draftMirror = $0; draftEdited?($0) } : nil, + draftText: session == nil ? draftText : nil, + ) + } else if let session { ProseTextView(session: session, spellChecking: gate.spellChecking, focused: gate.isFocused, caretHint: flipBackCaret) } else { ProseTextView(draft: draftMirror, spellChecking: gate.spellChecking, focused: gate.isFocused, onEdit: { newText in diff --git a/Museion/PostStore.swift b/Museion/PostStore.swift index 9696b83..b753602 100644 --- a/Museion/PostStore.swift +++ b/Museion/PostStore.swift @@ -143,15 +143,17 @@ nonisolated enum PostStore { } /// First write (#62): lazily materialize `projects///post.md` - /// with the #59 block stamped (plus `type: post`, #107). Pass State First + /// with the #59 block stamped (plus `type`, #107). Pass State First /// Draft, origin writer — the only values #18 writes; the folder appears - /// here, never on New Post. - static func writeNew(body: String, project: String = Post.defaultProject, home: URL) throws -> Post { + /// here, never on New Post. #109: `type` lets the outliner birth outline + /// pieces; prose pieces keep the default. + static func writeNew(body: String, project: String = Post.defaultProject, type: Post.ContentType = .post, home: URL) throws -> Post { try materialize( - text: stamped(body: body, passState: .firstDraft, origin: .writer), + text: stamped(body: body, passState: .firstDraft, origin: .writer, type: type), title: Post.title(of: body), origin: .writer, project: project, + type: type, home: home, ) } @@ -181,6 +183,7 @@ nonisolated enum PostStore { title: Post.title(of: body), origin: origin, project: project, + type: .post, // #95: our keys win — external `type: outline` still imports as post home: home, ) } @@ -230,8 +233,11 @@ nonisolated enum PostStore { /// #62/#95: lazily materialize `projects///post.md` with /// the given (already stamped/merged) text. Shared by `writeNew` and /// `importFile` — one lazy-folder path, TOCTOU-guarded, never clobbering. - /// Returns the created Post (id, title, First Draft, origin). - private static func materialize(text: String, title: String, origin: Post.Origin, project: String, home: URL) throws -> Post { + /// Returns the created Post (id, title, First Draft, origin, type). + // swiftlint:disable:next function_parameter_count + private static func materialize( + text: String, title: String, origin: Post.Origin, project: String, type: Post.ContentType, home: URL, + ) throws -> Post { let projectsRoot = home.appendingPathComponent("projects", isDirectory: true) try FileManager.default.createDirectory( at: projectsRoot.appendingPathComponent(project, isDirectory: true), @@ -257,7 +263,7 @@ nonisolated enum PostStore { } throw error } - return Post(id: id, title: title, passState: .firstDraft, origin: origin, type: .post, project: project, isArchived: false) + return Post(id: id, title: title, passState: .firstDraft, origin: origin, type: type, project: project, isArchived: false) } /// Save an existing Post: body-only text in, file normalized out. The diff --git a/Museion/PostsModel.swift b/Museion/PostsModel.swift index 0011718..67a9d5c 100644 --- a/Museion/PostsModel.swift +++ b/Museion/PostsModel.swift @@ -16,9 +16,17 @@ import Observation /// The New Post draft: body text only, no folder until first save (#62). /// #107: remembers the project the piece will land in when first saved. +/// #109: remembers the content type too (post default; .outline for New +/// Outline) so saveDraft stamps the right frontmatter. struct PostDraft { var text = "# Untitled\n\n" let project: String + var type = Post.ContentType.post + /// Mount identity: bumped on every stage (newPost/newOutline) so the + /// editor view REMOUNTS per draft — the outliner's one-shot seed + /// (`guard loadedGeneration < 0`) would otherwise keep a stale tree + /// when a new draft replaces the old without a hierarchy change. + let mountID = UUID() } /// Recursive FSEvents stream on one or more directories (#61): file-level @@ -108,9 +116,14 @@ final class PostsModel { /// presents (the pendingImportURLs pattern, #94). private(set) var askNewProject = false + /// #109: the just-saved outline draft's afterglow — the posts list + /// lags one rescan (the FSEvents window), so the freshly-opened + /// session can't read its type from the scan yet and would flash the + /// prose editor. True only between saveDraft and the next selection. + private(set) var lastDraftWasOutline = false + /// Last failed-op message surfaced in the editor (nil = clean). private(set) var lastError: String? - /// Home the watcher is bound to; also the rescan target. private var watchedHome: URL? private var watcher = PostsWatcher() @@ -204,6 +217,20 @@ final class PostsModel { session?.teardown(flushFirst: true) // #64: selection change flushes session = nil draft = PostDraft(project: target) + lastDraftWasOutline = false // #109: the afterglow died with the draft + selectedPostID = nil + } + + /// #109: New Outline — newPost's draft path with an outline draft instead: + /// body seeds one empty root node ("- "), the outline surface parses it. + /// Title keeps prose semantics (raw first line). + func newOutline() { + let target = targetProject + dismissExternal() + session?.teardown(flushFirst: true) + session = nil + draft = PostDraft(text: "- ", project: target, type: .outline) + lastDraftWasOutline = false // #109: a new draft resets the afterglow selectedPostID = nil } @@ -223,7 +250,8 @@ final class PostsModel { func saveDraft(home: URL) { guard let draft else { return } do { - let post = try PostStore.writeNew(body: draft.text, project: draft.project, home: home) + let post = try PostStore.writeNew(body: draft.text, project: draft.project, type: draft.type, home: home) + lastDraftWasOutline = draft.type == .outline // #109: covers the lagging rescan self.draft = nil pendingProject = nil // #108: the explicit target landed with the draft selectedPostID = post.id @@ -251,6 +279,7 @@ final class PostsModel { // #108: abandoning the draft kills its explicit project target too — // a later New Post must not silently land in the abandoned project. pendingProject = nil + lastDraftWasOutline = false // #109: opening a post is a fresh context selectedPostID = id wireSession() } @@ -475,6 +504,7 @@ final class PostsModel { session = nil draft = nil pendingProject = nil // #108 audit: the draft died here too — its target dies with it + lastDraftWasOutline = false // #109: same death, same clearing externalSession = EditorSession(target: .externalFile(target)) if externalSession?.loadFailed == true { lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed." diff --git a/Museion/PostsPaneView.swift b/Museion/PostsPaneView.swift index 6d970dd..9f8dd7b 100644 --- a/Museion/PostsPaneView.swift +++ b/Museion/PostsPaneView.swift @@ -88,16 +88,27 @@ struct PostsPaneView: View { draftSave: { model.saveDraft(home: home) }, + outline: draft.type == .outline, ) - .id("draft") + // #109: identity = "draft" + mountID — remounts per staged + // draft (the outliner seeds once per mount). + .id("draft-\(draft.mountID.uuidString)") } else if let external = model.externalSession { // #92: the guest slot — an external file in the editor column; // one at a time, transient per launch. PostEditorView(session: external, draftText: nil) .id(external.fileURL?.absoluteString ?? "external") } else if let session = model.session, session.postID == model.selectedPostID { - PostEditorView(session: session, draftText: nil) - .id(session.postID ?? "post") + // #109: outline routing — the scan's type when the list knows the + // piece, plus the just-saved-draft afterglow (the posts list lags + // one rescan; without the flag the fresh outline flashes prose). + PostEditorView( + session: session, + draftText: nil, + outline: model.lastDraftWasOutline + || model.posts.first(where: { $0.id == session.postID })?.type == .outline, + ) + .id(session.postID ?? "post") } else { VStack(spacing: 10) { Image(systemName: "square.and.pencil") diff --git a/Museion/ProseTypography.swift b/Museion/ProseTypography.swift index 45eb663..d5ef276 100644 --- a/Museion/ProseTypography.swift +++ b/Museion/ProseTypography.swift @@ -111,6 +111,18 @@ nonisolated enum ProseTypography { ] } + /// Outline rows (#109): the body face at its NATURAL line box — no CSS + /// 1.8 lineHeightMultiple. The outliner chrome (27pt bullet cells) assumes + /// one row height; a live-row fragment inflated by the prose multiple + /// grows the row, parks the glyphs at the fragment bottom, and detaches + /// the bullet. Editing parity lives in the FACE, not the leading. + static var outlineRowAttributes: [NSAttributedString.Key: Any] { + [ + .font: bodyFont, + .foregroundColor: foregroundColor, + ] + } + static var codeAttributes: [NSAttributedString.Key: Any] { [ .font: codeFont, diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 2cc01e9..c4f2562 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -21,13 +21,17 @@ Owned by the root AGENTS.md contract. - `ACPClientTests.swift` extends it into a full fake ACP *server*: a zsh script speaking real NDJSON JSON-RPC over stdio (`makeFakeACP`), with a per-binary mode file (`crashAfterHandshake`, `hangOnPrompt`, default full) and a base64-encoded fix-card payload — shell quoting can never break the wire JSON. Only `acpTempDir` remains as a helper; crash assertions use Swift Testing's `confirmation` (hook the callback BEFORE triggering the crash). `makeStrictFakeACP` (same file) guards `session/new` the way adapter ≥0.21.5 does — rejecting a missing `mcpServers` with `-32602` — pinning the wire contract the lenient fake can't catch. - `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `/profiles/` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests. - `PostLibraryTests.swift` (#17, #107) — throwaway Homes via `makeHome`/`writePiece`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`/`type`), two-level scan across `projects///` + `archive///` (project/isArchived stamped, noise at both levels), lazy folders / hidden dirs / symlinks not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`. -- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects///` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path. **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). -- `PostsModelTests.swift` (#108 audits) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included). +- `PostStoreTests.swift` (#18, #107) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write into `projects///` + #59 stamp (type first) round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes over the GLOBAL slug space (projects + archive; archived slugs never reused), `writeNew(project:)` routing, rename (retitle + move within the same project, archived stays archived, insert-title path, same-slug retitle-only, collision -2), trash removes from projects/ and archive/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-project failure path, writeNew outline stamping (#109: `type: outline` first line, `projects///post.md` placement, scan round-trip; default `.post` pinned). **#108:** project moves — `readPiece(home:root:project:id:)` path-aware helper; move (byte-identity, same-project no-op), archive/restore round-trip, archived-move refusal, `unarchiveProject` fresh + merge cases (dot-entries skipped), `createProject` validation matrix (duplicate case-insensitive + NFD twin, empty/slash/dot/`:` rejected), hidden user folders survive unarchive (source removed only when emptied), `unarchiveProject` model test (dirty open piece flushes before the move). **Fold pin:** decomposed-jamo folder on disk vs a precomposed title → `-2` (Swift `==`/Set already fold canonical equivalence — the premise asserts byte inequality; `folded` is the explicit, tested contract). +- `PostsModelTests.swift` (#108 audits, #109) — the model-layer lifecycle the store tests can't see, via `makeModelHome` (direct `@MainActor` model over a temp home): archive-open-piece clears selection+session, moveToProject reopens the session at the new `folderURL`, restore reopens off the archive path, New Project's draft lands in the named project, abandoning a draft for an external file drops `pendingProject`, unarchive of a dirty open piece flushes before the folder move, `moveTargets` lists empty projects from disk (default included); #109: `newOutline()` stages a `"- "`/`.outline` draft (selected project targeting waits for the bind rescan, default-project fallback), `saveDraft` of it materializes with `type: outline` and opens the session. - `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry. - `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `
    `, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars. - `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit. - `FocusModeTests.swift` (#21, map #21) — soft-centering band math pinned: in-band no-op, below-band recenter down, above-band recenter up, document-bottom clamp (parks, then no-ops while parked — no jump), short-document floor at 0. - `ImportExternalTests.swift` (#22, map #22) — import + external buffer via `importHome`/`writeExternal` (temp-dir convention): #95 frontmatter merge (external keys verbatim, our keys win — external `type: outline` overwritten to `type: post`, original untouched), CRLF file normalized at the boundary (block detected, keys stamped, LF body), bare file → fresh block + #60 collision suffixes, empty file → `untitled`, unreadable file (UTF-16) → `loadFailed`, nothing written, original untouched, external session saves in place with NO sidecar (#93), #67 conflict raised on a foreign write + Yes-reload. Imports land at `projects/posts//post.md` (#107). +- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling). +- `OutlinePresenterTests.swift` (#109) — the surface's pure projection: preorder visible-rows walk with depths/paths/childCounts, fold skipping + hidden-descendant counts (nested folds), id→path lookup + `node(at:)` inverse through deep trees, `setText` by identity, `rangeIDs` block-selection span (forward/backward anchors, fold-hidden → nil), `applyBatch` composition (moveUp forward / moveDown reversed, boundary-leader no-op — run never scatters — indent per-node into one parent, outdent reversed un-nesting). +- `EscEventProbeTests.swift` (#109) — the Esc delivery probe: a real Esc NSEvent reaches `RowTextView.keyDown` in a plain AppKit window (control), but the SAME textview behind SwiftUI's NSHostingView gets neither keyDown nor `.onExitCommand` — pinned. This is why `OutlineEditorView` ships a local `NSEvent` keyDown monitor as the Esc path (the monitor itself can't run in the test host — no running NSApp loop). +- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `
      ` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013). ## Verification diff --git a/MuseionTests/EscEventProbeTests.swift b/MuseionTests/EscEventProbeTests.swift new file mode 100644 index 0000000..f0a962d --- /dev/null +++ b/MuseionTests/EscEventProbeTests.swift @@ -0,0 +1,85 @@ +// +// EscEventProbeTests.swift +// MuseionTests +// +// #109 probe: WHY Esc needs the local monitor. Plain AppKit window → +// the row textview's keyDown fires (control). The SAME textview behind +// SwiftUI's NSHostingView → neither keyDown nor .onExitCommand fires: +// the hosting layer swallows Esc before the responder chain. Hence +// NSEvent.addLocalMonitorForEvents in OutlineEditorView — the monitor +// sees queue events before SwiftUI does. (The monitor path itself +// can't run in this harness — no running NSApp loop means no dequeue — +// so it's smoke-tested live in the app.) +// +import AppKit +@testable import Museion +import SwiftUI +import Testing + +@MainActor +@Suite(.serialized) +struct EscEventProbeTests { + private func makeEscEvent(window: NSWindow) -> NSEvent? { + NSEvent.keyEvent(with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: 0, + windowNumber: window.windowNumber, + context: nil, + characters: "\u{1b}", + charactersIgnoringModifiers: "\u{1b}", + isARepeat: false, + keyCode: 53) + } + + @Test func `esc reaches the row textview in a plain AppKit window (control)`() throws { + let tv = RowTextView(frame: NSRect(x: 0, y: 0, width: 200, height: 27)) + let bridge = OutlineRowTextView.Coordinator() + var received: [OutlineRowTextView.StructureOp] = [] + bridge.onStructure = { received.append($0) } + tv.bridge = bridge + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 100), + styleMask: [.titled], backing: .buffered, defer: false) + window.contentView?.addSubview(tv) + window.makeKeyAndOrderFront(nil) + window.makeFirstResponder(tv) + try NSApp.sendEvent(#require(makeEscEvent(window: window))) + #expect(received.contains(.deselect)) + } + + @Test func `esc dies in SwiftUI hosting - keyDown and onExitCommand never fire`() throws { + let tv = RowTextView(frame: NSRect(x: 0, y: 0, width: 200, height: 27)) + let bridge = OutlineRowTextView.Coordinator() + var received: [OutlineRowTextView.StructureOp] = [] + bridge.onStructure = { received.append($0) } + tv.bridge = bridge + + var exitFired = false + let hosted = HostProbe(textView: tv) + .onExitCommand { exitFired = true } + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 300, height: 100), + styleMask: [.titled], backing: .buffered, defer: false) + window.contentView = NSHostingView(rootView: hosted) + window.makeKeyAndOrderFront(nil) + window.makeFirstResponder(tv) + window.layoutIfNeeded() + + try NSApp.sendEvent(#require(makeEscEvent(window: window))) + + // The pinned failure mode: SwiftUI ate it. (If this expectation + // ever flips after an OS update, the monitor can be dropped.) + #expect(!received.contains(.deselect)) + #expect(!exitFired) + } +} + +/// Wraps an arbitrary NSView in SwiftUI so the probe can host RowTextView +/// behind a real NSHostingView like the app does. +private struct HostProbe: NSViewRepresentable { + let textView: NSView + func makeNSView(context _: Context) -> NSView { + textView + } + + func updateNSView(_: NSView, context _: Context) {} +} diff --git a/MuseionTests/OutlinePresenterTests.swift b/MuseionTests/OutlinePresenterTests.swift new file mode 100644 index 0000000..52ac17e --- /dev/null +++ b/MuseionTests/OutlinePresenterTests.swift @@ -0,0 +1,173 @@ +// +// OutlinePresenterTests.swift +// MuseionTests +// +// #109: the outliner surface's pure layer — visible-row projection +// (preorder, fold skipping, hidden-descendant counts), id→path lookup +// through deep trees, and setText mutation by node identity. +// + +import Foundation +@testable import Museion +import Testing + +struct OutlinePresenterTests { + private func node(_ text: String, _ children: [OutlineNode] = []) -> OutlineNode { + OutlineNode(text: text, children: children) + } + + @Test func `visibleRows walks preorder with depths paths and child counts`() { + let tree = [node("a", [node("a1", [node("a1x")]), node("a2")]), node("b")] + let rows = OutlinePresenter.visibleRows(tree, folded: []) + + #expect(rows.map(\.text) == ["a", "a1", "a1x", "a2", "b"]) + #expect(rows.map(\.depth) == [0, 1, 2, 1, 0]) + #expect(rows.map(\.childCount) == [2, 1, 0, 0, 0]) + #expect(rows.allSatisfy { !$0.isFolded && $0.foldedDescendantCount == 0 }) + // ids are the nodes' own — fold/view state keys on them + #expect(rows.map(\.id) == [ + tree[0].id, + tree[0].children[0].id, + tree[0].children[0].children[0].id, + tree[0].children[1].id, + tree[1].id, + ]) + } + + @Test func `visibleRows skips folded subtrees and counts hidden descendants`() { + let tree = [node("a", [node("a1", [node("a1x")]), node("a2")]), node("b")] + + // fold "a": a1, a1x, a2 (3 nodes) hide behind the fold + var rows = OutlinePresenter.visibleRows(tree, folded: [tree[0].id]) + #expect(rows.map(\.text) == ["a", "b"]) + #expect(rows[0].isFolded) + #expect(rows[0].foldedDescendantCount == 3) + #expect(rows[0].childCount == 2) // structure unchanged — folds are view state + #expect(!rows[1].isFolded) + + // fold the inner "a1" only: just a1x hides + rows = OutlinePresenter.visibleRows(tree, folded: [tree[0].children[0].id]) + #expect(rows.map(\.text) == ["a", "a1", "a2", "b"]) + #expect(rows[1].foldedDescendantCount == 1) + + // nested folds: the outer fold already hides the inner head + rows = OutlinePresenter.visibleRows(tree, folded: [tree[0].id, tree[0].children[0].id]) + #expect(rows.map(\.text) == ["a", "b"]) + #expect(rows[0].foldedDescendantCount == 3) + } + + @Test func `path resolves by id through deep trees and node at inverts it`() { + let parsed = OutlineTree.parse("- a\n - a1\n - a1x\n- b") + let deep = parsed.nodes[0].children[0].children[0] + #expect(OutlinePresenter.path(of: deep.id, in: parsed.nodes) == [0, 0, 0]) + #expect(OutlinePresenter.path(of: parsed.nodes[1].id, in: parsed.nodes) == [1]) + #expect(OutlinePresenter.path(of: parsed.nodes[0].id, in: []) == nil) + #expect(OutlinePresenter.path(of: UUID(), in: parsed.nodes) == nil) + + // node(at:) is the inverse — focus routing after structural ops + #expect(OutlinePresenter.node(at: [0, 0, 0], in: parsed.nodes)?.id == deep.id) + #expect(OutlinePresenter.node(at: [0, 1], in: parsed.nodes) == nil) + #expect(OutlinePresenter.node(at: [2], in: parsed.nodes) == nil) + } + + @Test func `setText mutates the node with the id`() { + var parsed = OutlineTree.parse("- a\n - a1") + let child = parsed.nodes[0].children[0] + + #expect(OutlinePresenter.setText("a1 edited", id: child.id, in: &parsed.nodes)) + #expect(parsed.nodes[0].children[0].text == "a1 edited") + #expect(parsed.nodes[0].text == "a") + + #expect(!OutlinePresenter.setText("ghost", id: UUID(), in: &parsed.nodes)) + #expect(OutlinePresenter.setText("", id: child.id, in: &parsed.nodes)) + #expect(parsed.nodes[0].children[0].text.isEmpty) + } + + @Test func `setText flattens pasted newlines - round-trip can't drop content`() { + // HIGH-1 pin: paste "l1\nl2\nl3" into a row → the node stays + // single-line (space-joined), so serialize→parse keeps every word. + var nodes = [OutlineNode(text: "row")] + #expect(OutlinePresenter.setText("l1\nl2\r\nl3", id: nodes[0].id, in: &nodes)) + #expect(nodes[0].text == "l1 l2 l3") + #expect(!nodes[0].text.contains("\n") && !nodes[0].text.contains("\r")) + + // the loss this prevents: an embedded \n serializes as one item + + // stray prose lines, and the NEXT parse drops the strays + let bad = OutlineTree.parse(OutlineTree.serialize(preamble: [], nodes: [OutlineNode(text: "l1\nl2")])) + #expect(bad.nodes.count == 1) + #expect(bad.nodes[0].text == "l1") + } + + @Test func `rangeIDs returns the inclusive visible span in order`() { + let tree = [node("a"), node("b"), node("c"), node("d")] + + // forward and backward anchors both give visible order + #expect(OutlinePresenter.rangeIDs(from: tree[0].id, to: tree[2].id, in: tree, folded: []) == + [tree[0].id, tree[1].id, tree[2].id]) + #expect(OutlinePresenter.rangeIDs(from: tree[2].id, to: tree[0].id, in: tree, folded: []) == + [tree[0].id, tree[1].id, tree[2].id]) + #expect(OutlinePresenter.rangeIDs(from: tree[1].id, to: tree[1].id, in: tree, folded: []) == [tree[1].id]) + + // an id hidden by a fold is invisible → nil + let nested = [node("a", [node("a1")]), node("b")] + #expect(OutlinePresenter.rangeIDs(from: nested[0].id, to: nested[0].children[0].id, in: nested, folded: [nested[0].id]) == nil) + #expect(OutlinePresenter.rangeIDs(from: nested[0].id, to: nested[1].id, in: nested, folded: []) != nil) + } + + @Test func `batch structural ops compose in the right order`() { + // moveUp: run as a unit, forward composes (run excludes the first + // row — a boundary leader no-ops the whole batch) + var upNodes = OutlineTree.parse("- a\n- b\n- c\n- d").nodes + let upIds = [upNodes[1].id, upNodes[2].id, upNodes[3].id] + #expect(OutlinePresenter.applyBatch(.moveUp, ids: upIds, to: &upNodes)) + #expect(upNodes.map(\.text) == ["b", "c", "d", "a"]) + + // moveDown: run as a unit, reversed composes (run excludes the + // last row — a boundary leader no-ops the whole batch) + var downNodes = OutlineTree.parse("- a\n- b\n- c\n- d").nodes + let downIds = [downNodes[0].id, downNodes[1].id, downNodes[2].id] + #expect(OutlinePresenter.applyBatch(.moveDown, ids: downIds, to: &downNodes)) + #expect(downNodes.map(\.text) == ["d", "a", "b", "c"]) + + // run touching the bottom boundary → no-op, never scatters + var bottomNodes = OutlineTree.parse("- a\n- b\n- c\n- d").nodes + let bottomIds = [bottomNodes[1].id, bottomNodes[2].id, bottomNodes[3].id] + #expect(!OutlinePresenter.applyBatch(.moveDown, ids: bottomIds, to: &bottomNodes)) + #expect(bottomNodes.map(\.text) == ["a", "b", "c", "d"]) + + // boundary leader → whole batch no-ops (run must not scatter) + var boundaryNodes = OutlineTree.parse("- a\n- b\n- c").nodes + let boundaryIds = [boundaryNodes[0].id, boundaryNodes[1].id] + #expect(!OutlinePresenter.applyBatch(.moveUp, ids: boundaryIds, to: &boundaryNodes)) + #expect(boundaryNodes.map(\.text) == ["a", "b", "c"]) + + // batch moves are sibling-only: a run whose members sit at + // different depths never crosses parents (regression pin — + // parent-crossing move tore such runs apart) + var mixed = OutlineTree.parse("- a\n- b\n - b1\n - b2\n- c").nodes + let mixedIds = [ + mixed[1].children[0].id, // b1 (depth 1) + mixed[1].children[0].children[0].id, // b2 (depth 2) + mixed[2].id, // c (depth 0) + ] + #expect(!OutlinePresenter.applyBatch(.moveUp, ids: mixedIds, to: &mixed)) + #expect(mixed.map(\.text) == ["a", "b", "c"]) + #expect(mixed[1].children.map(\.text) == ["b1"]) + #expect(mixed[1].children[0].children.map(\.text) == ["b2"]) + + // indent: per-node, run keeps its internal order (both land + // under a, in order — the earlier move doesn't strand the later) + var inNodes = OutlineTree.parse("- a\n- b\n- c").nodes + let inIds = [inNodes[1].id, inNodes[2].id] + #expect(OutlinePresenter.applyBatch(.indent, ids: inIds, to: &inNodes)) + #expect(inNodes.map(\.text) == ["a"]) + #expect(inNodes[0].children.map(\.text) == ["b", "c"]) + + // outdent: reversed composes (bottom→top un-nests the run) + var outNodes = OutlineTree.parse("- a\n - a1\n - a2\n - a3").nodes + let outIds = [outNodes[0].children[0].id, outNodes[0].children[1].id, outNodes[0].children[2].id] + #expect(OutlinePresenter.applyBatch(.outdent, ids: outIds, to: &outNodes)) + #expect(outNodes.map(\.text) == ["a", "a1", "a2", "a3"]) + #expect(outNodes[1...].allSatisfy { node in node.children.isEmpty }) + } +} diff --git a/MuseionTests/OutlineTreeTests.swift b/MuseionTests/OutlineTreeTests.swift new file mode 100644 index 0000000..c933f90 --- /dev/null +++ b/MuseionTests/OutlineTreeTests.swift @@ -0,0 +1,257 @@ +// +// OutlineTreeTests.swift +// MuseionTests +// +// #109: the Outline tree model — lenient parse (markers, indents, clamping, +// preamble), canonical-serialize round-trips, and the structural ops +// (indent/outdent/move/enter) as whole-subtree rearrangements with stable +// node ids. +// + +@testable import Museion +import Testing + +struct OutlineTreeTests { + @Test func `canonical round trip flat and nested`() { + let flat = "- a\n- b" + let parsedFlat = OutlineTree.parse(flat) + #expect(parsedFlat.preamble.isEmpty) + #expect(parsedFlat.nodes.map(\.text) == ["a", "b"]) + #expect(parsedFlat.nodes.map(\.children.count) == [0, 0]) + #expect(OutlineTree.serialize(preamble: parsedFlat.preamble, nodes: parsedFlat.nodes) == flat) + + let nested = "- a\n - a1\n - a1x\n- b" + let parsed = OutlineTree.parse(nested) + #expect(parsed.preamble.isEmpty) + #expect(parsed.nodes.count == 2) + #expect(parsed.nodes[0].text == "a") + #expect(parsed.nodes[0].children.map(\.text) == ["a1"]) + #expect(parsed.nodes[0].children[0].children.map(\.text) == ["a1x"]) + #expect(parsed.nodes[1].text == "b") + #expect(OutlineTree.serialize(preamble: parsed.preamble, nodes: parsed.nodes) == nested) + } + + @Test func `lenient markers indents and depth clamping`() { + // `*` markers parse; canonical `- ` comes back out. + let star = OutlineTree.parse("* a\n* b") + #expect(star.nodes.map(\.text) == ["a", "b"]) + #expect(OutlineTree.serialize(preamble: [], nodes: star.nodes) == "- a\n- b") + + // 4-space file: floor(4/2) = 2 would orphan — clamp makes children. + let four = OutlineTree.parse("- a\n - a1\n - a2") + #expect(four.nodes.count == 1) + #expect(four.nodes[0].text == "a") + #expect(four.nodes[0].children.map(\.text) == ["a1", "a2"]) + + // 8-space jump clamps to prevDepth + 1, not +4. + let jump = OutlineTree.parse("- a\n - a1\n - deep") + #expect(jump.nodes[0].children[0].children.map(\.text) == ["deep"]) + #expect(OutlineTree.serialize(preamble: [], nodes: jump.nodes) == "- a\n - a1\n - deep") + + // Tab counts as 2 spaces (single tab = depth 1, mixed tab+space too). + let tabbed = OutlineTree.parse("- a\n\t- a1\n\t - a1x") + #expect(tabbed.nodes[0].children.map(\.text) == ["a1"]) + #expect(tabbed.nodes[0].children[0].children.map(\.text) == ["a1x"]) + } + + @Test func `preamble kept verbatim and post item prose dropped`() { + let titled = OutlineTree.parse("# Title\n\n- a\n - a1") + #expect(titled.preamble == ["# Title", ""]) + #expect(titled.nodes.map(\.text) == ["a"]) + #expect(titled.nodes[0].children.map(\.text) == ["a1"]) + #expect(OutlineTree.serialize(preamble: titled.preamble, nodes: titled.nodes) == "# Title\n\n- a\n - a1") + + // Non-item lines AFTER the first item are dropped (normalize on save). + let stray = OutlineTree.parse("- a\nprose\n- b") + #expect(stray.preamble.isEmpty) + #expect(stray.nodes.map(\.text) == ["a", "b"]) + #expect(OutlineTree.serialize(preamble: stray.preamble, nodes: stray.nodes) == "- a\n- b") + } + + @Test func `round trip is idempotent and empty parses to empty`() { + #expect(OutlineTree.parse("") == ([], [])) + #expect(OutlineTree.serialize(preamble: [], nodes: []) == "") + + for source in ["- a\n- b", "- a\n - a1\n - a1x\n- b", "# T\n\n- a\n - a1", "* a\n* b"] { + let first = OutlineTree.parse(source) + let canon = OutlineTree.serialize(preamble: first.preamble, nodes: first.nodes) + let second = OutlineTree.parse(canon) + #expect(OutlineTree.serialize(preamble: second.preamble, nodes: second.nodes) == canon) + #expect(second.nodes.map(\.text) == first.nodes.map(\.text)) + } + } + + @Test func `indent nests node under previous sibling`() { + var nodes = [ + OutlineNode(text: "a", children: [OutlineNode(text: "a1")]), + OutlineNode(text: "b"), + ] + let bID = nodes[1].id + + let newPath = OutlineTree.indent(&nodes, path: [1]) + #expect(newPath == [0, 1]) // after a's existing child + #expect(nodes.count == 1) + #expect(nodes[0].children.map(\.text) == ["a1", "b"]) + #expect(nodes[0].children[1].id == bID) // id travels + + // First sibling has no previous → no-op. + #expect(OutlineTree.indent(&nodes, path: [0]) == nil) + #expect(nodes[0].children.map(\.text) == ["a1", "b"]) // untouched + + // Children travel with the moved node. + var deep = [ + OutlineNode(text: "a"), + OutlineNode(text: "b", children: [OutlineNode(text: "b1"), OutlineNode(text: "b2")]), + OutlineNode(text: "c"), + ] + let b1ID = deep[1].children[0].id + let indented = OutlineTree.indent(&deep, path: [1]) + #expect(indented == [0, 0]) + #expect(deep.count == 2) + #expect(deep[0].children.map(\.text) == ["b"]) + #expect(deep[0].children[0].children.map(\.text) == ["b1", "b2"]) + #expect(deep[0].children[0].children[0].id == b1ID) + } + + @Test func `outdent lands after parent with subtree intact`() { + var nodes = [ + OutlineNode(text: "a", children: [OutlineNode(text: "a1", children: [OutlineNode(text: "a1x")])]), + OutlineNode(text: "b"), + ] + let a1ID = nodes[0].children[0].id + + // Root → no-op. + #expect(OutlineTree.outdent(&nodes, path: [0]) == nil) + #expect(nodes.count == 2) + + let newPath = OutlineTree.outdent(&nodes, path: [0, 0]) + #expect(newPath == [1]) // right after its parent + #expect(nodes.map(\.text) == ["a", "a1", "b"]) + #expect(nodes[1].id == a1ID) + #expect(nodes[1].children.map(\.text) == ["a1x"]) // deep subtree travels + #expect(OutlineTree.serialize(preamble: [], nodes: nodes) == "- a\n- a1\n - a1x\n- b") + } + + @Test func `move swaps with sibling as a unit`() { + var nodes = [ + OutlineNode(text: "a"), + OutlineNode(text: "b", children: [OutlineNode(text: "b1")]), + OutlineNode(text: "c"), + ] + let bID = nodes[1].id + let b1ID = nodes[1].children[0].id + + #expect(OutlineTree.move(&nodes, path: [0], up: true) == nil) // boundary + #expect(OutlineTree.move(&nodes, path: [2], up: false) == nil) // boundary + + let down = OutlineTree.move(&nodes, path: [1], up: false) + #expect(down == [2]) + #expect(nodes.map(\.text) == ["a", "c", "b"]) + #expect(nodes[2].children.map(\.text) == ["b1"]) // subtree travels + #expect(nodes[2].id == bID && nodes[2].children[0].id == b1ID) + + let movedUp = OutlineTree.move(&nodes, path: [2], up: true) + #expect(movedUp == [1]) + #expect(nodes.map(\.text) == ["a", "b", "c"]) + } + + @Test func `move crosses its parent at a sibling boundary`() { + // test / second / third-level nest — the user's exact case: + // ⌥↑ on "third level" (first child, no previous sibling) lifts it + // OUT to sit directly before its parent. + var nodes = [ + OutlineNode(text: "test"), + OutlineNode(text: "second level", children: [OutlineNode(text: "third level")]), + OutlineNode(text: "after"), + ] + let thirdID = nodes[1].children[0].id + #expect(OutlineTree.move(&nodes, path: [1, 0], up: true) == [1]) + #expect(nodes.map(\.text) == ["test", "third level", "second level", "after"]) + #expect(nodes[1].id == thirdID) + + // down across the boundary: LAST child lands directly after parent + var last = [ + OutlineNode(text: "a"), + OutlineNode(text: "parent", children: [OutlineNode(text: "kid")]), + ] + #expect(OutlineTree.move(&last, path: [1, 0], up: false) == [2]) + #expect(last.map(\.text) == ["a", "parent", "kid"]) + + // down with an uncle below: lands between parent and uncle — + // one visible row per press, never skips + var uncle = [ + OutlineNode(text: "a"), + OutlineNode(text: "parent", children: [OutlineNode(text: "kid")]), + OutlineNode(text: "uncle", children: [OutlineNode(text: "nephew")]), + ] + #expect(OutlineTree.move(&uncle, path: [1, 0], up: false) == [2]) + #expect(uncle.map(\.text) == ["a", "parent", "kid", "uncle"]) + #expect(uncle[3].children.map(\.text) == ["nephew"]) + + // deeper nesting: crossing from depth 2 keeps the remaining path + var deep = [ + OutlineNode(text: "root", children: [ + OutlineNode(text: "mid", children: [OutlineNode(text: "leaf")]), + ]), + ] + #expect(OutlineTree.move(&deep, path: [0, 0, 0], up: true) == [0, 0]) + #expect(deep[0].children.map(\.text) == ["leaf", "mid"]) + } + + @Test func `enter splits at caret`() { + // Split mid-text: whitespace at the split boundary rides the tail's + // head off (pinned example: "hello world" @5 → "hello" + "world"). + var nodes = [OutlineNode(text: "hello world")] + let result = OutlineTree.enter(&nodes, path: [0], caretOffset: 5) + #expect(result == .newNode(path: [1], caret: 0)) + #expect(nodes.map(\.text) == ["hello", "world"]) + + // Caret at end → empty new sibling, focused at 0. + var endSplit = [OutlineNode(text: "done")] + let endResult = OutlineTree.enter(&endSplit, path: [0], caretOffset: 4) + #expect(endResult == .newNode(path: [1], caret: 0)) + #expect(endSplit.map(\.text) == ["done", ""]) + + // Offset clamps both ways (negative / beyond length). + var over = [OutlineNode(text: "abc")] + _ = OutlineTree.enter(&over, path: [0], caretOffset: 99) + #expect(over.map(\.text) == ["abc", ""]) + + // Split inside a nested run: new sibling lands right below, in place. + var nested = [ + OutlineNode(text: "a", children: [ + OutlineNode(text: "one two"), + OutlineNode(text: "tail"), + ]), + OutlineNode(text: "b"), + ] + let nestedResult = OutlineTree.enter(&nested, path: [0, 0], caretOffset: 3) + #expect(nestedResult == .newNode(path: [0, 1], caret: 0)) + #expect(nested[0].children.map(\.text) == ["one", "two", "tail"]) + } + + @Test func `enter on empty node outdents or siblings`() { + // Empty node at depth > 0 → outdented, right after its parent. + var nested = [ + OutlineNode(text: "a", children: [OutlineNode(text: "")]), + OutlineNode(text: "b"), + ] + let out = OutlineTree.enter(&nested, path: [0, 0], caretOffset: 0) + #expect(out == .outdented(path: [1])) + #expect(nested.map(\.text) == ["a", "", "b"]) + + // Whitespace-only counts as empty. + var spaced = [ + OutlineNode(text: "a", children: [OutlineNode(text: " ")]), + ] + let spacedOut = OutlineTree.enter(&spaced, path: [0, 0], caretOffset: 0) + #expect(spacedOut == .outdented(path: [1])) + #expect(spaced.map(\.text) == ["a", " "]) + + // Empty node at root → new empty sibling below, focused. + var rooted = [OutlineNode(text: "a"), OutlineNode(text: "")] + let rootResult = OutlineTree.enter(&rooted, path: [1], caretOffset: 0) + #expect(rootResult == .newNode(path: [2], caret: 0)) + #expect(rooted.map(\.text) == ["a", "", ""]) + } +} diff --git a/MuseionTests/PostStoreTests.swift b/MuseionTests/PostStoreTests.swift index 284231c..a5760bb 100644 --- a/MuseionTests/PostStoreTests.swift +++ b/MuseionTests/PostStoreTests.swift @@ -115,6 +115,31 @@ private func readPost(_ home: URL, _ id: String) throws -> String { #expect(scanned.first?.project == "essays") } +@Test func `writeNew with type outline stamps scans back and lands in the project`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "- Root\n\t- Child", project: "essays", type: .outline, home: home) + + #expect(post.type == .outline) + #expect(post.id == "root") + #expect(post.project == "essays") + #expect(FileManager.default.fileExists(atPath: home.appendingPathComponent("projects/essays/root/post.md").path)) + // #59 stamp with type first, outline rawValue. + #expect(try readPiece(home, root: "projects", project: "essays", post.id) + == "---\ntype: outline\npass_state: First Draft\norigin: writer\n---\n- Root\n\t- Child") + + // The #17 reader round-trips the outline type and the project. + let scanned = try #require(Post.scan(home: home).first) + #expect(scanned.type == .outline) + #expect(scanned.project == "essays") +} + +@Test func `writeNew default still stamps type post`() throws { + let home = try storeHome() + let post = try PostStore.writeNew(body: "# Plain\n", home: home) + #expect(post.type == .post) + #expect(try readPost(home, post.id).hasPrefix("---\ntype: post\n")) +} + @Test func `rename retitles moves folder and keeps frontmatter`() throws { let home = try storeHome() let original = try PostStore.writeNew(body: "# Old Name\n\nBody.", home: home) diff --git a/MuseionTests/PostsModelTests.swift b/MuseionTests/PostsModelTests.swift index 3236977..ba10e4a 100644 --- a/MuseionTests/PostsModelTests.swift +++ b/MuseionTests/PostsModelTests.swift @@ -112,6 +112,46 @@ private func makeModelHome() throws -> (PostsModel, URL) { #expect(model.session?.folderURL.path.contains("projects/posts/\(post.id)") == true) } +@Test @MainActor func `newOutline stages an outline draft in the target project`() async throws { + let (model, home) = try makeModelHome() + let post = try PostStore.writeNew(body: "# Seed\n", project: "essays", home: home) + // targetProject reads `posts` — wait for the bind rescan to surface the + // piece (the watcher path; saveDraft would trigger it too, too late here). + for _ in 0 ..< 250 where !model.posts.contains(where: { $0.id == post.id }) { + try await Task.sleep(nanoseconds: 20_000_000) + } + model.select(post.id, home: home) + + model.newOutline() + + #expect(model.draft?.text == "- ") + #expect(model.draft?.type == .outline) + #expect(model.draft?.project == "essays") // selected non-archived post's project + #expect(model.selectedPostID == nil) + #expect(model.session == nil) +} + +@Test @MainActor func `newOutline draft falls back to the default project`() throws { + let (model, _) = try makeModelHome() + model.newOutline() + #expect(model.draft?.project == Post.defaultProject) +} + +@Test @MainActor func `saveDraft materializes an outline and opens the session on it`() throws { + let (model, home) = try makeModelHome() + + model.newOutline() + model.saveDraft(home: home) + + #expect(model.draft == nil) + #expect(model.lastError == nil) + #expect(model.session?.postID == "untitled") // "- " slugs to untitled + #expect(model.selectedPostID == "untitled") + let scanned = try #require(Post.scan(home: home).first) + #expect(scanned.type == .outline) + #expect(scanned.title == "-") // prose semantics: first line, trimmed — "- " +} + @Test @MainActor func `moveTargets lists empty projects from disk`() throws { let (model, home) = try makeModelHome() try PostStore.createProject(named: "essays", home: home) // empty — no pieces diff --git a/MuseionTests/ProsePresenterTests.swift b/MuseionTests/ProsePresenterTests.swift index 2d6fcee..69a4c60 100644 --- a/MuseionTests/ProsePresenterTests.swift +++ b/MuseionTests/ProsePresenterTests.swift @@ -39,6 +39,19 @@ struct ProsePresenterTests { // MARK: Attribute map parity + @Test func `outline rows use the body face at its natural line box`() { + // #109 cursor-jank fix: the live outline row must NOT carry the prose + // 1.8 lineHeightMultiple — an inflated fragment grows the focused row + // and detaches the bullet. Natural box, body face, nothing else. + let attrs = ProseTypography.outlineRowAttributes + let font = attrs[.font] as? NSFont + #expect(font === ProseTypography.bodyFont) + guard let style = attrs[.paragraphStyle] as? NSParagraphStyle else { + return // no paragraph style = natural line box — the point + } + #expect(style.lineHeightMultiple == 0) // set → would inflate the row + } + @Test func `heading ladder matches reading CSS`() { let attributed = ProsePresenter.attribute("# H1\n\n## H2\n\n### H3\n\n#### H4") let ns = attributed.string as NSString diff --git a/MuseionTests/ReadingPresenterTests.swift b/MuseionTests/ReadingPresenterTests.swift index 22b1c5d..c3fc526 100644 --- a/MuseionTests/ReadingPresenterTests.swift +++ b/MuseionTests/ReadingPresenterTests.swift @@ -90,6 +90,23 @@ struct ReadingPresenterTests { #expect(!html.contains("
    • one
    ")) } + /// #109: an outline body (canonical nested bullets, exactly what + /// OutlineTree.serialize emits) renders as NESTED
      through the + /// unchanged apex pipeline — reading mode needs no outline-specific + /// surface (ADR-0013: "nested lists already render"). + @Test + func `pipeline nested bullets render nested lists`() throws { + let src = "- intro\n - first point\n - deep evidence\n - second point\n- outro" + let (html, blocks) = ReadingPresenter.page(for: src, postFolder: nil) + try assertRendered(html, blocks: blocks, count: 1) + #expect(html.contains("
        ")) + // apex emits bare
      • intro + a nested
          for the children + #expect(html.contains("
        • intro\n
            ")) + #expect(html.contains("
          • deep evidence
          • ")) + #expect(html.contains("
          • second point
          • ")) + #expect(html.contains("
          • outro
          • ")) + } + /// Tables, quotes, fenced code, HR, links — the #69 set on one page. @Test func `pipeline constructs`() throws { diff --git a/docs/devlog/20261015-issue109-outline-type-outliner_log.md b/docs/devlog/20261015-issue109-outline-type-outliner_log.md new file mode 100644 index 0000000..10677bd --- /dev/null +++ b/docs/devlog/20261015-issue109-outline-type-outliner_log.md @@ -0,0 +1,78 @@ +# Issue #109 — Outline type + outliner: block tree, LogSeq keys + +> **Date:** 2026-10-15 +> **Type:** issue +> **Reference:** Gitea AlexKucera/Museion issue #109 (map #97; ADR-0013; #105 verdict variant B) + +## Goal + +Build S3 of the outliner: an outline content type (`type: outline` frontmatter) and a dedicated block outliner surface with LogSeq-style keys — parse/serialize a plain nested-bullet markdown file, structural ops (indent/outdent/move/enter), fold, block selection, and routing through the existing draft/session machinery. + +## What Was Done + +- **`Museion/OutlineTree.swift`** (new, nonisolated pure) — `OutlineNode` (runtime UUID identity, single-line text, children) + `OutlineTree.parse/serialize` over the one-file plain nested-bullet format. Lenient parse (`-`/`*` markers, any whitespace indent, tab = 2 spaces, depth jump clamps to prev+1, verbatim preamble before first item), canonical serialize (2-space + `- `, no trailing newline). Path-addressed structural ops returning new path or nil on boundary no-op: `indent`, `outdent`, `move(up:)` with parent-crossing (LogSeq-style: up lands before the parent, down after), `siblingMove(up:)` (sibling-only, for batches), `enter(caretOffset:)` with `EnterResult` (split at caret / empty-at-depth outdents / empty-root new sibling). +- **`Museion/OutlineEditorView.swift`** (new) — `OutlinePresenter` (nonisolated pure: visible-rows projection with fold skipping, id↔path/node, `setText` by identity with newline sanitizing, `rangeIDs` block-selection span, `applyBatch` sibling-only batch ops with boundary-leader no-op) + `OutlineEditorView` (SwiftUI chrome: fold-toggle bullets, per-depth 1px rails, "⋯ N" fold counts, rust caret) + `OutlineRowTextView`/`RowTextView` (ONE promoted borderless NSTextView on the focused row; structural key interception in `keyDown`). +- **Key set** — Tab/⇧Tab indent/outdent · ⌥↑/⌥↓ move subtree (single-node crosses parents; batches sibling-only) · ↑/↓ hop visible blocks · ⇧↑/⇧↓ extend block selection · ⌘↑/⌘↓ fold/unfold · Enter split/outdent/sibling · Esc collapses block selection (via local NSEvent monitor — SwiftUI hosting swallows Esc; probe-pinned). +- **Substrate threading** — `PostStore.writeNew(body:project:type:home:)` (default `.post`; `importFile` explicit `.post`), `PostDraft.type` + `newOutline()` staging a `"- "`/`.outline` draft, `NewOutlineButton` (⇧⌘N) in the File menu, `PostEditorView.outline` flag routing to the outliner, `PostsPaneView` passing `draft.type == .outline` / `lastDraftWasOutline || posts-lookup` for sessions. +- **Tests** — `OutlineTreeTests` (10 pins), `OutlinePresenterTests` (6), `EscEventProbeTests` (the SwiftUI Esc-swallow probe), `PostStore`/`PostsModel`/`ReadingPresenter` extensions (nested-bullet reading pin: apex emits bare `
          • intro\n
              ` — no `

              ` wrappers). +- **Finish-audit fixes** — paste-multiline data loss (setText flattens `\r\n`/`\n`/`\r` to single space at the one seam; round-trip pin), dead `String(NSCarriageReturnCharacter)` Enter disjunct (evaluates to `"13"` — never matches), dead `Row.path` field removed, duplicate DOX bullet removed. +- **Polish round (user-reported visual jank)** — the live row was reusing the prose paragraph style (CSS `--lh 1.8` calibrated `lineHeightMultiple`), inflating the focused row's line box: oversized caret, row growth 27→37, glyphs parked at fragment bottom, bullet detached. Now: `ProseTypography.outlineRowAttributes` (body face, natural line box), static rows on the same NSFont (no face swap on focus), live row mirrors staticText's `.padding(.vertical, 3)`, `sizeThatFits` floor 21 so textview+padding = 27 = bullet-cell height — no focus jump. User-verified in three rounds ("perfect"). +- **DOX** — root/Museion/MuseionTests AGENTS.md entries for every new file and contract. + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Dedicated block surface (variant B), not markdown-mode | #105 verdict; prototype `ref/prototypes/wf105-outline-editor-prototype.html`; ADR-0013 | +| Lenient parse / canonical serialize / normalize on save | User-confirmed grilling verdict: hand-edited files parse; our writes are canonical | +| Fold = runtime UUIDs, session-scoped, never persisted | Fresh open = all unfolded; folding never dirties the document | +| Text-only undo, block-granular selection | #105 verdict; structural undo excluded from v1 | +| Batch moves sibling-only; single-node ⌥ moves cross parents | User-requested LogSeq behavior; a crossing batch tears itself apart — run-as-unit guard | +| `PostDraft.mountID` remount | Outliner seeds its tree once per mount; same-identity draft swap kept a stale tree | +| Natural line box for outline rows (no CSS 1.8 multiple) | Outliner chrome assumes one row height; an inflated fragment grows the focused row and detaches the bullet. Editing parity lives in the face, not the leading | +| Esc = drop block-selection highlight | Agent's design call (ticket silent); fold is ⌘↑/⌘↓ | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| Oversized caret, row growth, bullet detach on focus | Live NSTextView carried the prose CSS-1.8 `lineHeightMultiple` | `outlineRowAttributes` — natural line box; test-pinned | +| Text face swapped on focus | Static rows used `.system(size: 17, design: .serif)`, live row Valkyrie | Both render `ProseTypography.bodyFont` | +| Text jumped up ~3pt on focus | Live row had `+6` fudge in `sizeThatFits`, static rows `.padding(.vertical, 3)`, HStack top-aligned | Same `.padding(.vertical, 3)` on the live row, fudge removed | +| Whole line jumped on focus | Row totaled 27 floor + 6 padding = 33 vs static 27 | Floor 21 → total exactly 27 | +| Pasted multiline text silently lost lines | Embedded `\n` serialized as stray prose; next parse drops strays | setText flattens CRLF/LF/CR to a space at the seam | +| Dead Enter disjunct `String(NSCarriageReturnCharacter)` | Evaluates to `"13"` (decimal-description trap, same as arrows) | Match `"\r"`/`"\n"` literals | +| Swift Testing compile error in `#expect(outNodes[1...].allSatisfy(\.children.isEmpty))` | Macro + keypath-as-function on a slice infers throwing | Named-parameter closure `{ node in node.children.isEmpty }` | +| ⇧⌘N keystroke unreliable in automation | macOS system handling | Menu item "New Outline" works; smoke via File menu | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `Museion/OutlineTree.swift` | new — tree model, parse/serialize, structural ops | +| `Museion/OutlineEditorView.swift` | new — presenter, SwiftUI surface, RowTextView key interception | +| `Museion/ProseTypography.swift` | `outlineRowAttributes` (natural line box) | +| `Museion/PostStore.swift` | `writeNew` type param, stamped first in block | +| `Museion/PostsModel.swift` | `PostDraft.type`/`mountID`, `newOutline()`, `lastDraftWasOutline` | +| `Museion/MuseionApp.swift` | `NewOutlineButton` ⇧⌘N | +| `Museion/PostEditorView.swift` | `outline` flag → surface swap | +| `Museion/PostsPaneView.swift` | draft/session outline routing | +| `MuseionTests/OutlineTreeTests.swift` | new — 10 tree pins | +| `MuseionTests/OutlinePresenterTests.swift` | new — 6 presenter pins | +| `MuseionTests/EscEventProbeTests.swift` | new — Esc delivery probe | +| `MuseionTests/PostStoreTests.swift` | writeNew type, import-stays-post pins | +| `MuseionTests/PostsModelTests.swift` | newOutline/saveDraft lifecycle pins | +| `MuseionTests/ReadingPresenterTests.swift` | apex nested-bullet list pin | +| `MuseionTests/ProsePresenterTests.swift` | natural-line-box pin | +| `AGENTS.md`, `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX entries | + +## Open Items & Next Steps + +- [ ] Second map (#102): drag-reorder, zoom-into-block — explicitly out of v1 scope +- [ ] MEDIUM-2 (deferred, audit): external mixed-content outline files lose non-bullet lines on next in-app edit — needs a product decision; follow-up on map #97 +- [ ] Mixed-depth batch run half-apply ceiling — ponytail-marked in code with two-pass dry-run upgrade path +- [ ] Mid-word click caret mapping — v1 ceiling (caret lands at end), ponytail-marked + +--- + +*Log written by write-log skill* diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 5fc206b..57f87e2 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | Date | Type | File | Summary | |------|------|------|---------| +| 2026-10-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-issue107-storage-substrate-projects-archive_log.md](20261013-issue107-storage-substrate-projects-archive_log.md) | #107 S1: pieces re-rooted to projects/ + archive/, global slugs, type frontmatter; audit dedupe fix | | 2026-10-12 | issue | [20261012-issue22-import-external_log.md](20261012-issue22-import-external_log.md) | #22 import & external markdown: SessionTarget, guest slot, Origin ask, drag-drop — full suite green |