// // OutlineRowTextView.swift // Museion // // #109: the outliner's promoted row editor — the ONE live NSTextView on // the focused row (native undo/IME, rust caret, wrapping at the column // width), plus RowTextView's structural key interception. Extracted from // OutlineEditorView.swift in #112; the key set and AppKit traps are // documented at the keyDown head. // import AppKit import SwiftUI // 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. `FileDropTextView` /// base (27.2 routing): a file drag landing on a row bounces instead of /// pasting the path — images don't ingest into outlines (#141); text /// drags keep the stock drop. final class RowTextView: FileDropTextView { 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) } }