feat(outline): outline type + outliner — S3 (#109)
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
Dedicated block surface (ADR-0013, #105 variant B): OutlineTree parses/serializes plain nested-bullet markdown leniently and normalizes on save; the outliner promotes one NSTextView over the focused row with LogSeq-style keys (Tab/⇧Tab, ⌥↑/⌥↓ subtree move, ↑/↓ hop, ⇧↑/⇧↓ block selection, ⌘↑/⌥↓ fold, Enter split), folds session-scoped by runtime node UUID. New Outline ⇧⌘N stages a type: outline draft through the existing autosave/conflict machinery; reading renders the serialized markdown unchanged. Outline rows use the body face at its natural line box — the prose CSS-1.8 lineHeightMultiple grew the focused row and detached the bullet (test-pinned). Finish-audit fixes included: paste-multiline sanitizing at setText, dead Enter disjunct, dead Row.path. Closes #109
This commit is contained in:
1 parent
e55747e7fe
commit
c23ee0f62f
21 files changed
+1809
-21
No files matched your search
+5
-3
@@ -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 `<project>` + 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/<name>/<id>/post.md` AND `archive/<name>/<id>/post.md` (archive → isArchived), same skip guards at both levels (no post.md = lazy folder, loose files, hidden dirs, symlinked dirs), `type` read leniently (absent/unknown → post), title-sorted; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
|
||||
- `PostStore.swift` — #18 write side (nonisolated), **#107/ADR-0012 re-root**: the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug(for:home:)` collision suffixes `-2`/`-3`… over the GLOBAL slug space (all entries under `projects/*/` AND `archive/*/` — an archived slug is never reused, restore can't collide; all comparisons through private `folded(_:)` = NFC + lowercase — the canonical compare key: APFS is case-insensitive and normalization-insensitive, and NFC-vs-NFD names (Hangul jamo, Finder-made folders) are one folder to the FS; Swift `==`/Set hashing already fold canonical equivalence, so `folded` is the explicit, tested contract with the lowercase load-bearing; `createProject`'s duplicate check uses the same fold), `folder(of:home:)` = the one id→folder resolver (projects/ before archive/, project names sorted — every write path derives its target from the id alone; nothing threads (project, id)), `writeNew(body:project:home:)` (lazy folder under `projects/<project>/` — 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>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; `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/<project>/` — default `posts`, the selected project flows in from PostsModel; #109: `type` param default `.post`, stamped first in the block — New Outline passes `.outline`; the returned Post carries it), `overwrite` (resolves via `folder(of:)`, preserves existing type/pass_state/origin, normalizes bare posts on save), `rename` = retitle + move WITHIN the same parent dir (piece stays in its project, stays archived if archived; file stays `post.md`; a title slugging to the current id only retitles), `trash` (resolves via `folder(of:)` + `FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing). **#22:** `openableTypes`/`isMarkdown` (.md/.markdown only, local file URLs — a dragged web link is not a document; shared `markdownExtensions` list), `importFile(at:origin:project:home:)` (copy never move; lands in the selected project else default; BOM stripped + CRLF→LF normalized at the boundary — in Swift a CRLF pair is one grapheme and every `\n` split sees one line, so the corpus machinery needs LF; external YAML keys kept verbatim with `type`/`pass_state`/`origin` set-overwritten via `mergedFrontmatter` — `type: post` wins even over an external `type: outline`; absent keys inserted before the closing `---`; empty block → fresh stamp shape; id = title slug at import, #60 collision machinery; private `materialize` is the one lazy-folder path `writeNew` shares). **#108:** `move(_:to:home:)` (projects→projects folder move; refuses archived pieces **via the resolved disk path** — never the scan snapshot's `isArchived` flag — and derives the current project from the same path, so a Finder-side move between scan and click can't misfile; validates the name via `validatedProject`, same-project confirm = no-op not an error, destination-exists = disk anomaly that throws — never clobbers), `archive(_:home:)`/`restore(_:home:)` (folder moves into/out of `archive/<project>/`, project disk-derived the same way), `unarchiveProject(_:home:)` (moves every child of `archive/<name>/` into `projects/<name>/` — one path covers fresh and merge; the source is removed only when the loop emptied it — dot-entries skipped by the move are not destroyed with the folder; duplicate-id collisions throw honestly), `createProject(named:home:)` (empty/slash/dot-prefix/`:`/control-char names + case-insensitive duplicates throw; lazily materializes `projects/<name>/`), private `relocate` behind them — post.md bytes are never rewritten by any of these; ops return Void (the rescan re-derives posts from disk).
|
||||
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save; #107: carries `project` — captured at `newPost()` from the selected non-archived post's project, else the default `posts`; #109: carries `type` too, default `.post` — `saveDraft` threads it into `writeNew`; `mountID` (UUID per staging) keys the editor's `.id` so every newly staged draft REMOUNTS the editor — the outliner seeds its tree once per mount, a same-identity draft swap would keep the stale tree; `newOutline()` is newPost's exact dismissal/selection path with a `"- "`/`.outline` draft instead; `importFiles` lands in the same target project); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on BOTH `projects/` and `archive/` (#107 — `PostsWatcher.start(urls:)` takes an array), rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `projects/` + `archive/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. **#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<UUID>`, reset on every load — never serializes, ADR-0013). Every text keystroke + structural op serializes the whole tree into the EXISTING machinery — `session.edit(md)` (debounce/⌘S/#67 conflict unchanged) or `onDraftEdit` for drafts; focus follows node IDs (they travel through ops), caret lands via `pendingCaret` at next mount. Routing: `PostEditorView.outline` flag swaps `editingSurface` to the outliner (⌘S/toolbar/conflict/reading toggle all keep working — reading renders the serialized markdown via apex unchanged); `PostsPaneView` passes `draft.type == .outline` for drafts and `lastDraftWasOutline || posts-lookup` for sessions (`PostsModel.lastDraftWasOutline` covers the rescan lag after a fresh save; cleared in newPost/select/openExternal wherever the draft dies).
|
||||
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
|
||||
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
|
||||
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<UUID>) -> [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<UUID>, 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>) -> [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<UUID> = []
|
||||
@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)
|
||||
}
|
||||
}
|
||||
@@ -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[..<split])
|
||||
var tail = String(text[split...])
|
||||
// Drop whitespace straddling the caret, tail-first (head end keeps its
|
||||
// shape when the caret sits after a word gap; the new node starts
|
||||
// clean where typing resumes).
|
||||
while tail.hasPrefix(" ") || tail.hasPrefix("\t") {
|
||||
tail.removeFirst()
|
||||
}
|
||||
while head.hasSuffix(" ") || head.hasSuffix("\t") {
|
||||
head.removeLast()
|
||||
}
|
||||
var newPath: [Int]?
|
||||
guard withSiblings(of: path, in: &nodes, { siblings, index in
|
||||
siblings[index].text = head
|
||||
siblings.insert(OutlineNode(text: tail), at: index + 1)
|
||||
newPath = Array(path.dropLast()) + [index + 1]
|
||||
return true
|
||||
}) else { return .noOp }
|
||||
return .newNode(path: newPath ?? path, caret: 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// What `enter` did, for the view to move focus accordingly.
|
||||
extension OutlineTree {
|
||||
nonisolated enum EnterResult: Equatable {
|
||||
case noOp
|
||||
case outdented(path: [Int]?)
|
||||
case newNode(path: [Int], caret: Int)
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,8 @@ struct PostEditorView: View {
|
||||
let draftText: String?
|
||||
var draftEdited: ((String) -> 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
|
||||
|
||||
+13
-7
@@ -143,15 +143,17 @@ nonisolated enum PostStore {
|
||||
}
|
||||
|
||||
/// First write (#62): lazily materialize `projects/<project>/<slug>/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/<project>/<slug>/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
|
||||
|
||||
@@ -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."
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user