// // 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") } /// 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[..