// // OutlineEditorView.swift // Museion // // #109 (ADR-0013, #105 verdict — variant B): the outliner editing surface. // Chrome bullets + per-depth vertical rails; ONE promoted NSTextView on // the focused row (native undo/IME), static inline-markdown text // elsewhere. Tab/⇧Tab/⌥↑/⌥↓/Enter reshape whole subtrees through // OutlineTree; ↑/↓ hop visible blocks; folds are pure view state keyed by // node id — toggling them never serializes. Every text/structure edit // re-serializes into the existing EditorSession debounce/⌘S/conflict // machinery (`session.edit`) or the draft callbacks — the save path is // untouched. Reading mode keeps rendering the serialized markdown via the // apex surface (nested lists render natively there). // import AppKit import SwiftUI // MARK: - Pure projection (tested) /// The outliner's view-facing projection over `[OutlineNode]`: which rows /// are visible given the fold set, plus the chrome data each row renders /// from. Pure tree math — no UI. nonisolated enum OutlinePresenter { nonisolated struct Row: Equatable, Identifiable { let id: UUID var depth: Int var text: String /// 0 = leaf bullet (never foldable). Structure fact, not view state. var childCount: Int var isFolded: Bool /// Total nodes hidden under this row's fold ("⋯ N"); 0 unless folded. var foldedDescendantCount: Int } /// Preorder walk emitting one Row per visible node — a folded node's /// whole subtree is skipped and counted. static func visibleRows(_ nodes: [OutlineNode], folded: Set) -> [Row] { var rows: [Row] = [] walk(nodes, parent: [], depth: 0, folded: folded, into: &rows) return rows } private static func walk( _ nodes: [OutlineNode], parent: [Int], depth: Int, folded: Set, into rows: inout [Row], ) { for (index, node) in nodes.enumerated() { let path = parent + [index] let isFolded = folded.contains(node.id) rows.append( Row( id: node.id, depth: depth, text: node.text, childCount: node.children.count, isFolded: isFolded, foldedDescendantCount: isFolded ? countTree(node.children) : 0, ), ) if !isFolded { walk(node.children, parent: path, depth: depth + 1, folded: folded, into: &rows) } } } private static func countTree(_ nodes: [OutlineNode]) -> Int { nodes.reduce(0) { $0 + 1 + countTree($1.children) } } /// The visible-row ids from `from` to `to`, inclusive, in visible /// order; nil when either id isn't visible. Block-selection range /// math (⇧↑/⇧↓ anchor↔focus). static func rangeIDs(from: UUID, to: UUID, in nodes: [OutlineNode], folded: Set) -> [UUID]? { let rows = visibleRows(nodes, folded: folded) guard let startIdx = rows.firstIndex(where: { $0.id == from }), let endIdx = rows.firstIndex(where: { $0.id == to }) else { return nil } return rows[min(startIdx, endIdx) ... max(startIdx, endIdx)].map(\.id) } /// Structural ops that make sense on a block-selection run. enum BatchOp { case indent case outdent case moveUp case moveDown } /// Batch-apply a structural op to a run of visible-row ids (block /// selection), re-resolving each path by id after every move. Moves /// are SIBLING-ONLY here: a batch move never crosses a parent — /// if the run's leader is at a sibling boundary the whole batch /// no-ops (a run that crosses parents tears itself apart). Indent /// and outdent apply per node. /// ponytail: a mixed-level run can half-apply (leader moves, later /// member at boundary); two-pass dry-run is the upgrade if that /// ever bites. Returns whether anything changed. @discardableResult static func applyBatch(_ op: BatchOp, ids: [UUID], to nodes: inout [OutlineNode]) -> Bool { let ordered = (op == .moveDown || op == .outdent) ? ids.reversed() : ids var didChange = false for id in ordered { guard let path = path(of: id, in: nodes) else { continue } let moved: Bool = switch op { case .indent: OutlineTree.indent(&nodes, path: path) != nil case .outdent: OutlineTree.outdent(&nodes, path: path) != nil case .moveUp: OutlineTree.siblingMove(&nodes, path: path, up: true) case .moveDown: OutlineTree.siblingMove(&nodes, path: path, up: false) } if !moved, op == .moveUp || op == .moveDown { // Run moves as a unit; its leader is at a sibling // boundary. The leader runs first — nothing moved yet. return didChange } didChange = didChange || moved } return didChange } /// Find a node's path by identity. nil = not in the tree. static func path(of id: UUID, in nodes: [OutlineNode]) -> [Int]? { for (index, node) in nodes.enumerated() { if node.id == id { return [index] } if let deeper = path(of: id, in: node.children) { return [index] + deeper } } return nil } /// The node at a root→leaf index path — focus routing after structural /// ops return the moved node's new path. nil = path doesn't resolve. static func node(at path: [Int], in nodes: [OutlineNode]) -> OutlineNode? { guard let first = path.first, nodes.indices.contains(first) else { return nil } let current = nodes[first] return path.count == 1 ? current : node(at: Array(path.dropFirst()), in: current.children) } /// Replace one node's text by identity. False = id not in the tree. /// Single-line contract enforced HERE: pasted newlines become spaces /// (splitting into siblings needs anchor/caret math in the view; /// the space-join is the safe floor that can't lose content). @discardableResult static func setText(_ text: String, id: UUID, in nodes: inout [OutlineNode]) -> Bool { let sanitized = text.replacingOccurrences(of: "\r\n", with: " ") .replacingOccurrences(of: "\n", with: " ") .replacingOccurrences(of: "\r", with: " ") for index in nodes.indices { if nodes[index].id == id { nodes[index].text = sanitized return true } if setText(sanitized, id: id, in: &nodes[index].children) { return true } } return false } } // MARK: - The surface /// The outline editing surface (#109): rows of chrome (guide rails, /// bullets, fold counts) around one live caret row. Session mode re-parses /// on `loadGeneration` bumps (open / Yes-reload); draft mode seeds from /// `draftText` once and streams edits out through `onDraftEdit`. struct OutlineEditorView: View { var session: EditorSession? var onDraftEdit: ((String) -> Void)? /// Draft mode: the text at mount. Later values are ignored — after the /// seed the view's tree owns the document until the next mount. var draftText: String? @State private var preamble: [String] = [] @State private var nodes: [OutlineNode] = [] /// View state, keyed by node id; reset on every load (session-scoped). @State private var folded: Set = [] @State private var focusedID: UUID? /// Block-selection anchor (⇧↑/⇧↓). nil = no range selected; the range /// runs anchor↔focusedID over visible rows. View state, like folds. @State private var selectionAnchor: UUID? /// Caret (grapheme offset) the NEXT mounted row editor lands on; /// nil = end. Read at mount only — the live view owns the caret after. @State private var pendingCaret: Int? @State private var loadedGeneration = -1 /// Esc delivery: SwiftUI's hosting layer swallows Esc before the row /// textview's keyDown AND before .onExitCommand (probe-pinned — /// EscEventProbeTests). A local monitor sees the event first. @State private var escMonitor: Any? var body: some View { let rows = OutlinePresenter.visibleRows(nodes, folded: folded) Group { if rows.isEmpty { VStack(spacing: 10) { Image(systemName: "list.bullet") .font(.largeTitle) .foregroundStyle(DesignTokens.muted) Text("An empty outline — every line is a node.") .font(.callout) .foregroundStyle(DesignTokens.muted) } .frame(maxWidth: .infinity, maxHeight: .infinity) } else { ScrollView { LazyVStack(alignment: .leading, spacing: 0) { ForEach(rows) { row in rowView(row) } } .padding(.top, 24) .padding(.bottom, 80) } } } .onAppear { loadIfNeeded() installEscMonitor() } .onChange(of: session?.loadGeneration) { _, _ in loadIfNeeded() } .onDisappear { removeEscMonitor() } } /// Local monitor: the ONLY reliable Esc path into this surface /// (probe: sendEvent → hosted keyDown never fires for Esc). Fires /// only while the outliner's own row textview is first responder, /// swallows the event only when there's a selection to collapse. private func installEscMonitor() { guard escMonitor == nil else { return } escMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in guard event.keyCode == 53, // Esc (NSApp.keyWindow?.firstResponder as? RowTextView) != nil else { return event } if selectionAnchor != nil { selectionAnchor = nil return nil // swallowed — the selection was the target } return event } } private func removeEscMonitor() { if let escMonitor { NSEvent.removeMonitor(escMonitor) } escMonitor = nil } /// (Re)parse from the source of truth. Session: only when the load /// generation moved (open, Yes-reload) — never per keystroke, the view /// owns the live tree. Draft: seed once at mount. Every load resets /// folds — fresh open = all unfolded, never dirties the document. private func loadIfNeeded() { if let session { guard session.loadGeneration != loadedGeneration else { return } loadedGeneration = session.loadGeneration let parsed = OutlineTree.parse(session.text) preamble = parsed.preamble nodes = parsed.nodes } else { guard loadedGeneration < 0 else { return } loadedGeneration = 0 let parsed = OutlineTree.parse(draftText ?? "") preamble = parsed.preamble nodes = parsed.nodes } folded = [] focusedID = nodes.first?.id selectionAnchor = nil pendingCaret = nil } // MARK: Rows private func rowView(_ row: OutlinePresenter.Row) -> some View { HStack(alignment: .top, spacing: 0) { // Per-depth guide rails (prototype variant B: 1px hairline per // ancestor level at level*18+11, 18px indent per depth). Canvas { context, size in for level in 0 ..< row.depth { let railX = CGFloat(level) * 18 + 11 context.fill( Path(CGRect(x: railX, y: 0, width: 1, height: size.height)), with: .color(DesignTokens.border), ) } } .frame(width: CGFloat(row.depth) * 18) bullet(row) if row.id == focusedID { OutlineRowTextView( text: row.text, caret: pendingCaret, onEdit: { newText in selectionAnchor = nil // typing replaces block selection OutlinePresenter.setText(newText, id: row.id, in: &nodes) pushToDocument() }, onStructure: { op in apply(op) }, ) .padding(.vertical, 3) // same inset as staticText — no focus jump .frame(maxWidth: .infinity, alignment: .leading) .fixedSize(horizontal: false, vertical: true) } else { staticText(row) } if row.isFolded, row.foldedDescendantCount > 0 { Text("⋯ \(row.foldedDescendantCount)") .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.accent) .padding(.leading, 6) .padding(.top, 5) } } .padding(.horizontal, 20) // Block-selection highlight (⇧↑/⇧↓ range, anchor↔focus). .background(rowSelected(row) ? DesignTokens.accent.opacity(0.08) : Color.clear) } /// The bullet cell (22×27): fold toggle when the node has children /// ("●" ~7pt, folded → accent), leaf "◦" ~10pt; tapping a leaf focuses. @ViewBuilder private func bullet(_ row: OutlinePresenter.Row) -> some View { let foldable = row.childCount > 0 let glyph = Text(foldable ? "●" : "◦") .font(.system(size: foldable ? 7 : 10)) .foregroundStyle(row.isFolded ? DesignTokens.accent : DesignTokens.muted) if foldable { Button { toggleFold(row.id) } label: { glyph.frame(width: 22, height: 27) } .buttonStyle(.plain) .help("fold/unfold (⌘↑ / ⌘↓)") .accessibilityLabel(row.isFolded ? "Unfold \(row.text)" : "Fold \(row.text)") } else { glyph .frame(width: 22, height: 27) .contentShape(Rectangle()) .onTapGesture { focus(row.id) } } } /// Static row text: inert inline markdown; `[[wiki-links]]` stay /// literal (the plain-Text fallback keeps them so either way). /// Same NSFont as the live row (Valkyrie 17) — no face swap on focus. private func staticText(_ row: OutlinePresenter.Row) -> some View { Group { if row.text.isEmpty { Text(" ") .font(Font(ProseTypography.bodyFont)) .foregroundStyle(DesignTokens.border) } else if let attributed = try? AttributedString( markdown: row.text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace), ) { Text(attributed) .font(Font(ProseTypography.bodyFont)) .foregroundStyle(DesignTokens.foreground) } else { Text(row.text) .font(Font(ProseTypography.bodyFont)) .foregroundStyle(DesignTokens.foreground) } } .padding(.vertical, 3) .frame(maxWidth: .infinity, alignment: .leading) .contentShape(Rectangle()) // Clicking another row focuses it, caret at END. // ponytail: no click-position caret mapping in v1 — mid-word clicks // land at the row's end; a textview hit-test is the upgrade path. .onTapGesture { focus(row.id) } } // MARK: Focus + folds private func focus(_ id: UUID) { guard id != focusedID else { return } focusedID = id selectionAnchor = nil // a click is a fresh single focus pendingCaret = nil // caret at end } private func toggleFold(_ id: UUID) { // View state ONLY — never serializes, never session.edit/draftEdited. if folded.contains(id) { folded.remove(id) } else { folded.insert(id) } } // MARK: Structure /// One key from the focused row's textview. View-state keys mutate /// `folded`/focus directly; tree keys go through OutlineTree at the /// focused node's path. Node ids travel through every op, so focus /// follows the RESULT's node id, never the stale path. private func apply(_ op: OutlineRowTextView.StructureOp) { switch op { case .fold: // ⌘↑: fold the focused node when it has children. if let id = focusedID, childCount(of: id) > 0 { folded.insert(id) } case .unfold: if let id = focusedID { folded.remove(id) } case let .hop(direction): // ↑/↓ hop VISIBLE blocks — folded subtrees are skipped. let rows = OutlinePresenter.visibleRows(nodes, folded: folded) if let current = rows.firstIndex(where: { $0.id == focusedID }), rows.indices.contains(current + direction) { focusedID = rows[current + direction].id selectionAnchor = nil pendingCaret = nil // caret at end of the target row } case let .extend(direction): // ⇧↑/⇧↓: extend the block selection one visible row. First // press anchors at the focused row; a bare ↑/↓ or click clears. if selectionAnchor == nil { selectionAnchor = focusedID } let rows = OutlinePresenter.visibleRows(nodes, folded: folded) if let current = rows.firstIndex(where: { $0.id == focusedID }), rows.indices.contains(current + direction) { focusedID = rows[current + direction].id pendingCaret = nil } case .deselect: selectionAnchor = nil case .indent, .outdent, .moveUp, .moveDown, .enter: applyTree(op) } } /// Tree-mutating ops (indent/outdent/move/enter). Serialize + route /// focus only when something actually changed (boundary no-ops are /// nil and leave the document alone). private func applyTree(_ op: OutlineRowTextView.StructureOp) { guard let focusedID else { return } // Block selection + batchable op → run-wide apply. Moves treat // the run as a unit (boundary leader no-ops the whole batch). if let anchor = selectionAnchor, let range = selectedRangeIDs(anchor: anchor, focus: focusedID), range.count > 1, let batchOp = map(op) { if OutlinePresenter.applyBatch(batchOp, ids: range, to: &nodes) { pushToDocument() } return } guard let path = OutlinePresenter.path(of: focusedID, in: nodes) else { return } var didChange = false var newFocus: (id: UUID, caret: Int)? switch op { case .indent: didChange = OutlineTree.indent(&nodes, path: path) != nil case .outdent: didChange = OutlineTree.outdent(&nodes, path: path) != nil case .moveUp: didChange = OutlineTree.move(&nodes, path: path, up: true) != nil case .moveDown: didChange = OutlineTree.move(&nodes, path: path, up: false) != nil case let .enter(caretGraphemes): switch OutlineTree.enter(&nodes, path: path, caretOffset: caretGraphemes) { case .noOp: break case let .outdented(newPath): didChange = newPath != nil // nil = boundary no-op case let .newNode(newPath, caret): didChange = true if let id = OutlinePresenter.node(at: newPath, in: nodes)?.id { newFocus = (id, caret) } } case .fold, .unfold, .hop, .extend, .deselect: return // unreachable — apply(_:) routes those to view state } if didChange { if let newFocus { self.focusedID = newFocus.id pendingCaret = newFocus.caret } pushToDocument() } } /// The selected row ids in visible order (anchor↔focus, inclusive). private func selectedRangeIDs(anchor: UUID, focus: UUID) -> [UUID]? { OutlinePresenter.rangeIDs(from: anchor, to: focus, in: nodes, folded: folded) } /// Row background when inside the block selection. private func rowSelected(_ row: OutlinePresenter.Row) -> Bool { guard let anchor = selectionAnchor else { return false } return selectedRangeIDs(anchor: anchor, focus: focusedID ?? anchor)?.contains(row.id) ?? false } /// StructureOp → the batchable op for block-selection runs. private func map(_ op: OutlineRowTextView.StructureOp) -> OutlinePresenter.BatchOp? { switch op { case .indent: .indent case .outdent: .outdent case .moveUp: .moveUp case .moveDown: .moveDown default: nil // enter/fold/etc. never batch } } private func childCount(of id: UUID) -> Int { guard let path = OutlinePresenter.path(of: id, in: nodes) else { return 0 } return OutlinePresenter.node(at: path, in: nodes)?.children.count ?? 0 } /// Every text keystroke and structural op lands here: serialize the /// whole tree and hand it to the unchanged save machinery. private func pushToDocument() { let md = OutlineTree.serialize(preamble: preamble, nodes: nodes) if let session { session.edit(md) } else { onDraftEdit?(md) } } } // MARK: - The promoted row editor /// The focused row's live editor (#109): borderless plain NSTextView with /// native undo/IME and an accent caret, wrapping at the column width (no /// horizontal scroll). `keyDown` intercepts the structural key set; every /// intercepted branch returns WITHOUT super (swallow); unhandled keys → /// super (native IME/undo/text). The branch swap on focus change remounts /// it per row. struct OutlineRowTextView: NSViewRepresentable { enum StructureOp: Equatable { case indent case outdent case moveUp case moveDown case enter(caretGraphemes: Int) case fold case unfold /// -1 = previous visible row, +1 = next. case hop(direction: Int) /// ⇧↑/⇧↓: extend block selection one visible row from the anchor. case extend(direction: Int) /// Esc: collapse the block selection. case deselect } var text: String /// Grapheme offset for the caret at mount; nil = end. Never reapplied /// on update — the live view owns the caret after mount. var caret: Int? var onEdit: (String) -> Void var onStructure: (StructureOp) -> Void func makeNSView(context: Context) -> RowTextView { let tv = RowTextView() tv.bridge = context.coordinator tv.allowsUndo = true tv.isRichText = false tv.isAutomaticQuoteSubstitutionEnabled = false tv.isAutomaticDashSubstitutionEnabled = false tv.isAutomaticTextReplacementEnabled = false tv.isAutomaticSpellingCorrectionEnabled = false tv.backgroundColor = .clear tv.drawsBackground = false tv.insertionPointColor = NSColor(DesignTokens.accent) tv.typingAttributes = ProseTypography.outlineRowAttributes tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude) tv.textContainer?.widthTracksTextView = true tv.textContainer?.heightTracksTextView = false tv.textContainer?.lineFragmentPadding = 0 tv.textContainerInset = .zero tv.isHorizontallyResizable = false tv.isVerticallyResizable = true tv.minSize = .zero tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) tv.autoresizingMask = [.width] tv.string = text // Caret at mount: grapheme offset → UTF-16 for NSTextView. let head = String(text.prefix(caret.map { min(max($0, 0), text.count) } ?? text.count)) tv.setSelectedRange(NSRange(location: (head as NSString).length, length: 0)) tv.delegate = context.coordinator context.coordinator.lastLocalText = text DispatchQueue.main.async { [weak tv] in tv?.window?.makeFirstResponder(tv) } return tv } func updateNSView(_ tv: RowTextView, context: Context) { context.coordinator.onEdit = onEdit context.coordinator.onStructure = onStructure // Echo guard, ProseTextView-draft-mode pattern: our own keystrokes // round-trip byte-equal through the model, so only adopt when the // model's text differs from what this view last emitted — that's a // structural reshape or a reload. Caret parks at end (structural // changes that keep focus — outdent — move no text). if text != context.coordinator.lastLocalText, tv.string != text { tv.string = text tv.setSelectedRange(NSRange(location: (text as NSString).length, length: 0)) context.coordinator.lastLocalText = text } } /// The row wraps: height = laid-out height at the proposed width. func sizeThatFits(_ proposal: ProposedViewSize, nsView tv: RowTextView, context _: Context) -> CGSize? { guard let container = tv.textContainer, let layoutManager = tv.layoutManager else { return nil } let width = proposal.width ?? tv.bounds.width guard width > 0, width < .greatestFiniteMagnitude else { return nil } container.containerSize = NSSize(width: width, height: .greatestFiniteMagnitude) layoutManager.ensureLayout(for: container) // No vertical fudge: the row's .padding(.vertical, 3) mirrors staticText, // so focused and static baselines coincide. Floor 21 + 6 padding = 27: // the bullet cell's height — the row must not grow on focus. let height = layoutManager.usedRect(for: container).height return CGSize(width: width, height: max(height, 21)) } func makeCoordinator() -> Coordinator { Coordinator() } final class Coordinator: NSObject, NSTextViewDelegate { var onEdit: ((String) -> Void)? var onStructure: ((StructureOp) -> Void)? /// The text this view last emitted/saw — the echo-guard reference. var lastLocalText = "" func textDidChange(_ notification: Notification) { guard let tv = notification.object as? NSTextView else { return } lastLocalText = tv.string tv.typingAttributes = ProseTypography.outlineRowAttributes onEdit?(tv.string) } } } /// The row NSTextView: structural key interception. final class RowTextView: NSTextView { weak var bridge: OutlineRowTextView.Coordinator? override func keyDown(with event: NSEvent) { let key = event.charactersIgnoringModifiers ?? "" // Arrow matching traps: the character IS the function-key scalar // (String(NSUpArrowFunctionKey) would be its decimal description, // "63232"), and arrow events carry .function/.numericPad device // bits — strip them so == .command/.option/.shift can match. let upKey = "\u{F700}" // NSUpArrowFunctionKey let downKey = "\u{F701}" // NSDownArrowFunctionKey let modifiers = event.modifierFlags .intersection(.deviceIndependentFlagsMask) .subtracting([.function, .numericPad]) if key == upKey || key == downKey { let up = key == upKey switch modifiers { case .command: bridge?.onStructure?(up ? .fold : .unfold) case .option: bridge?.onStructure?(up ? .moveUp : .moveDown) case .shift: bridge?.onStructure?(.extend(direction: up ? -1 : 1)) default: bridge?.onStructure?(.hop(direction: up ? -1 : 1)) } return } if key == "\t" { bridge?.onStructure?(modifiers.contains(.shift) ? .outdent : .indent) return } if key == "\u{19}" { // NSBackTabCharacter — ⇧⇥ arrives as backtab, not " " + shift bridge?.onStructure?(.outdent) return } if key == "\u{1b}" { // Esc: collapse the block selection bridge?.onStructure?(.deselect) return } if key == "\r" || key == "\n" { // THE conversion (classic trap): selectedRange().location is a // UTF-16 offset; enter() counts GRAPHEME clusters. Passing the // raw number splits emoji/CJK clusters mid-grapheme. Clamp, // convert through String.Index, then count characters. let text = string let utf16Location = min(max(0, selectedRange().location), text.utf16.count) let index = String.Index(utf16Offset: utf16Location, in: text) let graphemes = text.distance(from: text.startIndex, to: index) bridge?.onStructure?(.enter(caretGraphemes: graphemes)) return } super.keyDown(with: event) } /// Some AppKit paths deliver ⇧⇥ here instead of keyDown. override func insertBacktab(_: Any?) { bridge?.onStructure?(.outdent) } /// Esc on NSTextView routes here (doCommandBy:), not always keyDown. override func cancelOperation(_: Any?) { bridge?.onStructure?(.deselect) } }