Files
museion/Museion/OutlineTree.swift
T
AlexKucera c0513aae85
CI / ci (push) Canceled after 0s
feat(outline): convert to post — S4 (#114)
In-place outline→post conversion on the piece: id, folder, Pass
State, origin kept, type frontmatter flips to post, body transforms
once. The ask picks the transform — Verbatim Bullets (default,
lossless) or Headings ladder (roots ##, stepping to the ###### floor,
deeper stays bullets), with a warning when the ladder would drop
paragraph lines between bullets.

The open session flushes first, then reopens routed to prose via
proseOverridePostID (lastDraftWasOutline's machinery reversed).
An outline that went lossy on disk behind an unwarned ask aborts
the convert; an unanswered #67 conflict aborts every flush-first
op (shared flushOrAbort seam); rescan no longer hands a same-id
reopened session its predecessor's stale disk text; a held #111
guard ask dies with the outline it pointed at.

Audit round (finish-audit, three reviewers) included: 13 new pins,
206 tests green, pin discrimination verified. Record:
docs/devlog/20261016-issue114-convert-to-post_log.md
2026-10-16 18:03:41 +02:00

369 lines
14 KiB
Swift

//
// 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 {
/// #111: would parse drop content? True when any NON-BLANK line after
/// the first item isn't an item line — the prose the outliner can't
/// show and the next save would silently drop. Blank lines don't count:
/// they're formatting, not prose, and normalize quietly.
static func parsesWithLoss(_ markdown: String) -> Bool {
var sawItem = false
for line in markdown.split(separator: "\n", omittingEmptySubsequences: false) {
if parseItem(String(line)) != nil {
sawItem = true
} else if sawItem, !line.trimmed().isEmpty {
return true
}
}
return false
}
/// 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")
}
/// #114 (S4): the headings-ladder conversion body — outline body in,
/// post body out. Roots become `##`, each deeper level steps one
/// heading down to the `######` floor; deeper levels stay bullets
/// (indent re-based so the first bullet level sits flush under the
/// floor). Preamble rides verbatim above — `# Title` survives.
/// Mixed content: parse drops prose lines (the convert ask warns).
static func headingsLadderBody(_ markdown: String) -> String {
let (preamble, items) = scan(markdown)
var lines = preamble
for (depth, text) in items {
if depth <= 4 {
lines.append(String(repeating: "#", count: depth + 2) + " " + text)
} else {
lines.append(String(repeating: " ", count: depth - 5) + "- " + text)
}
}
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
}
/// #112 drag primitive: remove and return the whole subtree at `path`
/// (nil when the path doesn't resolve). The drag engine pulls moving
/// blocks out one at a time, re-resolving paths by id between pulls.
static func extract(_ nodes: inout [OutlineNode], path: [Int]) -> OutlineNode? {
var extracted: OutlineNode?
_ = withSiblings(of: path, in: &nodes) { siblings, index in
extracted = siblings.remove(at: index)
return true
}
return extracted
}
/// #112 drag primitive: insert `run` as consecutive siblings at `index`
/// in the children of `parentPath` (empty = the root array). The index
/// clamps to count (append); empty runs are refused. False when the
/// parent doesn't resolve.
@discardableResult
static func insertRun(
_ run: [OutlineNode], parentPath: [Int], index: Int, in nodes: inout [OutlineNode],
) -> Bool {
guard !run.isEmpty else { return false }
return withChildren(of: parentPath, in: &nodes) { siblings in
let slot = min(max(index, 0), siblings.count)
siblings.insert(contentsOf: run, at: slot)
return true
}
}
/// Runs `body` on the children array of the node at `path` (the root
/// array for an empty path). False when the path doesn't resolve.
private static func withChildren(
of path: [Int], in nodes: inout [OutlineNode], _ body: (inout [OutlineNode]) -> Bool,
) -> Bool {
if path.isEmpty {
return body(&nodes)
}
guard let first = path.first, nodes.indices.contains(first) else { return false }
let rest = Array(path.dropFirst())
return rest.isEmpty
? body(&nodes[first].children)
: withChildren(of: rest, in: &nodes[first].children, body)
}
/// Tab. Node at `path` becomes the LAST child of its previous sibling.
/// No previous sibling → no-op, returns nil.
static func indent(_ nodes: inout [OutlineNode], path: [Int]) -> [Int]? {
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)
}
}