feat(outline): outline type + outliner — S3 (#109)
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:
AlexKucera committed 2026-10-15 13:09:31 +02:00
1 parent e55747e7fe
commit c23ee0f62f
21 files changed
+1809 -21

No files matched your search

+6 -2
View File
@@ -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 `<binaryDir>/profiles/<name>` (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/<name>/<id>/` + `archive/<name>/<id>/` (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/<name>/<id>/` + #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/<name>/<id>/` + #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/<project>/<id>/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 `<ol>`, 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/<id>/post.md` (#107).
- `OutlineTreeTests.swift` (#109) — the tree model's 10 pins: canonical + nested round-trips, lenient inputs (star markers, 4-space siblings, 8-space clamp, tab indent), preamble verbatim + stray-prose drop, serialize∘parse idempotence, indent/outdent/move semantics incl. boundary nils and parent-crossing (first-child ⌥↑ lifts out before the parent, last-child ⌥↓ lands after it, depth-2 path rewrites), id travel through ops, and `enter`'s three behaviors (split at caret incl. boundary-whitespace drop, empty depth>0 outdent, empty root new-sibling).
- `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 `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
## Verification
+85
View File
@@ -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) {}
}
+173
View File
@@ -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 })
}
}
+257
View File
@@ -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", "", ""])
}
}
+25
View File
@@ -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)
+40
View File
@@ -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
+13
View File
@@ -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
+17
View File
@@ -90,6 +90,23 @@ struct ReadingPresenterTests {
#expect(!html.contains("<li>one</li></ul>"))
}
/// #109: an outline body (canonical nested bullets, exactly what
/// OutlineTree.serialize emits) renders as NESTED <ul> 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("<ul data-source-line=\"1\">"))
// apex emits bare <li>intro + a nested <ul> for the children
#expect(html.contains("<li>intro\n<ul>"))
#expect(html.contains("<li>deep evidence</li>"))
#expect(html.contains("<li>second point</li>"))
#expect(html.contains("<li>outro</li>"))
}
/// Tables, quotes, fenced code, HR, links — the #69 set on one page.
@Test
func `pipeline constructs`() throws {