// // ProseListTextView.swift // Museion // // #115 (S5): the prose editor's list machinery — an NSTextView subclass // ProseTextView installs in place of the plain stock view. Tab/⇧Tab // indent/outdent the list item under the caret, ⌥↑/⌥↓ move it among // siblings (ProseList does the math; every edit is ONE undoable range // replacement through the plain mode-B store — ADR-0010 stands, no // secondary model). Lists get visual collapse: fold state is VIEW state // keyed by the marker line's buffer position (re-derived on edit — // simplest honest rule: nearest parent line with the same marker text), // hidden scopes are styled to near-zero height (ProseTypography.folded // Attributes), a chevron in the left gutter toggles by click, and a // folded parent shows "⋯ N" after its line. Folding never dirties the // document (ADR-0013's posture, carried to prose). // // Key-delivery facts: arrows arrive as the function-key scalars // \u{F700}/\u{F701} carrying .function/.numericPad device bits (strip // before comparing modifiers); ⇧⇥ arrives as backtab \u{19}, sometimes // via insertBacktab instead of keyDown — both paths are covered (the // outliner's RowTextView proved the set behind NSHostingView). // import AppKit import SwiftUI /// The chrome overlay: a click-through layer-host whose `contents` image the /// text view renders offscreen (SwiftUI-hosted TextKit2 views never reliably /// route through draw(_:) — layer contents sidestep the whole question). final class ProseChromeView: NSView { weak var owner: ProseListTextView? override func hitTest(_: NSPoint) -> NSView? { nil } // clicks reach the text view /// Re-render the owner's chrome into a fresh image and install it as the /// layer's contents. Deferred one main-queue tick: refresh points fire /// inside textDidChange, after TextKit2 invalidated layout but before /// re-layout — querying fragments synchronously finds none (#115). func refresh() { guard bounds.width > 0, bounds.height > 0 else { return } DispatchQueue.main.async { [weak self] in guard let self, let owner else { return } // No parents anywhere and nothing painted → skip the raster. // ponytail: the image is document-sized per refresh — rasterize the // visible height instead if tall docs measurably chug. if owner.proseParentCount == 0, layer?.contents == nil { return } guard let image = owner.renderChromeImage(size: bounds.size) else { return } wantsLayer = true layer?.contents = image } } override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(newSize) if newSize != .zero { refresh() } } } final class ProseListTextView: NSTextView { /// A fold: the marker line's buffer position + its text (the re-key /// identity when an edit above shifts offsets). struct Fold: Equatable { let key: Int let lineText: String } var folds: [Fold] = [] // MARK: Structural keys override func keyDown(with event: NSEvent) { let key = event.charactersIgnoringModifiers ?? "" let modifiers = event.modifierFlags .intersection(.deviceIndependentFlagsMask) .subtracting([.function, .numericPad]) let upKey = "\u{F700}" // NSUpArrowFunctionKey let downKey = "\u{F701}" // NSDownArrowFunctionKey if key == upKey || key == downKey { if modifiers == .option, let item = currentItem() { performMove(item, direction: key == downKey ? 1 : -1) return } super.keyDown(with: event) return } if key == "\t" || key == "\u{19}" { // NSBackTabCharacter if let item = currentItem() { if key == "\u{19}" || modifiers.contains(.shift) { performOutdent(item) } else { performIndent(item) } return } super.keyDown(with: event) return } super.keyDown(with: event) } /// Some AppKit paths deliver ⇧⇥ here instead of keyDown. override func insertBacktab(_: Any?) { if let item = currentItem() { performOutdent(item) } else { super.insertBacktab(nil) } } private func currentItem() -> ProseList.Item? { guard (string as NSString).length > 0 else { return nil } return ProseList.item(at: selectedRange().location, in: string) } // MARK: Edit application (one undo step each) private func performIndent(_ item: ProseList.Item) { guard let edit = ProseList.indent(item, caret: selectedRange().location, in: string) else { return } apply(edit) } private func performOutdent(_ item: ProseList.Item) { guard let edit = ProseList.outdent(item, caret: selectedRange().location, in: string) else { return } apply(edit) } private func performMove(_ item: ProseList.Item, direction: Int) { guard let edit = ProseList.move(item, caret: selectedRange().location, direction: direction, in: string) else { return } apply(edit) } /// One range replacement through the text stack: shouldChangeText /// registers undo, didChangeText drives the delegate (paragraph /// reattribute + session edit). Multi-line replacements span more than /// the caret's paragraph, so a full presentation pass follows — unless /// folds are open, where the post-edit fold refresh already does it. private func apply(_ edit: ProseList.Edit) { guard shouldChangeText(in: edit.range, replacementString: edit.replacement) else { return } textStorage?.replaceCharacters(in: edit.range, with: edit.replacement) didChangeText() let length = (string as NSString).length setSelectedRange(NSRange(location: min(max(0, edit.caret), length), length: 0)) guard folds.isEmpty else { return } // textDidChange refreshed everything let sel = selectedRange() textStorage?.setAttributedString(ProsePresenter.attribute(string)) setSelectedRange(sel) } // MARK: Fold maintenance /// One maintenance entry point for every refresh path — the coordinator's /// textDidChange calls it LAST (after its paragraph reattribute and /// session.edit, so hidden styling lands on top of the refreshed /// presentation) and the wholesale content swaps (generation load, draft /// echo — no textDidChange fires for those) call it directly. No folds → /// chrome-only refresh; refreshFoldRendering ends in its own refresh. func refreshFolds() { guard !folds.isEmpty else { chrome.refresh() return } refreshFoldRendering() } func toggleFold(_ parent: ProseList.ParentHint) { if let idx = folds.firstIndex(where: { $0.key == parent.markerLine.location }) { folds.remove(at: idx) } else { folds.append(Fold(key: parent.markerLine.location, lineText: lineText(of: parent.markerLine))) } refreshFoldRendering() } /// Re-key folds against the current text (nearest parent line with the /// same marker text; no match → the fold dies), restyle the document, /// re-hide every live scope, and park a caret that landed inside a /// hidden scope at its parent's marker end. func refreshFoldRendering() { let parents = ProseList.parents(in: string) // ponytail: nearest-same-marker re-key can move a fold across duplicate // marker texts — track the edit delta in shouldChangeText if that bites. var seenKeys = Set() folds = folds.compactMap { fold in parents .filter { lineText(of: $0.markerLine) == fold.lineText } .min { abs($0.markerLine.location - fold.key) < abs($1.markerLine.location - fold.key) } .map { Fold(key: $0.markerLine.location, lineText: fold.lineText) } }.filter { seenKeys.insert($0.key).inserted } // two folds can't land on one parent let sel = selectedRange() textStorage?.setAttributedString(ProsePresenter.attribute(string)) for fold in folds { guard let parent = parents.first(where: { $0.markerLine.location == fold.key }) else { continue } textStorage?.setAttributes(ProseTypography.foldedAttributes, range: parent.foldScope) if NSLocationInRange(sel.location, parent.foldScope) { setSelectedRange(NSRange(location: min(parent.markerEnd, (string as NSString).length), length: 0)) } } chrome.refresh() } /// The marker line's text without its terminator. private func lineText(of line: NSRange) -> String { let buffer = string as NSString guard line.length > 0 else { return "" } var len = line.length while len > 0 { let terminator = buffer.character(at: line.location + len - 1) if terminator == 0x0A || terminator == 0x0D { len -= 1 } else { break } } return len > 0 ? buffer.substring(with: NSRange(location: line.location, length: len)) : "" } // MARK: Image ingest (#141) /// #141: the piece folder dropped images ingest into — non-nil only /// on a saved post's prose surface (drafts and the external guest /// carry nil; image drags then refuse loudly). Set by ProseTextView /// when the session is known. var ingestFolder: URL? /// #141's drop-point solve, pure for tests (#115 field finding: under /// SwiftUI hosting the TextKit2 point→character APIs misanswer — invert /// the one geometry source that DOES answer, `firstRect`, whose y is /// bottom-up screen coords like mouseLocation and DECREASES with index). /// Non-contiguous layout makes OFF-SCREEN chars lie (zero/stale rects, /// dogfood 2026-11-02) — so sample the document, keep only rects inside /// the viewport band (plain NSView geometry — trusted), bracket the drop /// between two in-band samples, binary-search the bracket. Pointer above /// every in-band sample → the first visible char; below all → the last /// in-band sample; no in-band evidence at all (viewless/garbage) → 0. nonisolated static func dropIndex( length: Int, targetY: CGFloat, bandMinY: CGFloat, bandMaxY: CGFloat, sampleCount: Int = 512, rectY: (Int) -> CGFloat, ) -> Int { guard length > 0 else { return 0 } var lastAbove: Int? var firstInBand = -1 for s in 0 ... sampleCount { let i = min(length - 1, s * length / sampleCount) let y = rectY(i) guard y >= bandMinY, y <= bandMaxY else { continue } if firstInBand < 0 { firstInBand = i } if y >= targetY { lastAbove = i // at-or-above the drop on screen } else if let above = lastAbove, above < i { // Bracket [above, i] straddles the drop; both ends are // in-band (laid out, monotone) so the search probes real rects. var lo = above var hi = i while lo < hi { let mid = (lo + hi) / 2 if rectY(mid) >= targetY { lo = mid + 1 } else { hi = mid } } return min(lo, length) } } return min(lastAbove ?? max(firstInBand, 0), length) } private func rectY(_ i: Int, of length: Int) -> CGFloat { guard window != nil, i >= 0, i < length else { return -1 } // viewless (tests): land at index 0 return firstRect(forCharacterRange: NSRange(location: i, length: 1), actualRange: nil).midY } /// #141's SwiftUI entry — the window `.dropDestination`'s perform /// routes here after markdown forwarding is ruled out upstream. /// The drop point is read from the live pointer (NSEvent.mouseLocation /// — the SwiftUI closure's location proved unusable, dogfood 2026-11-02). /// Gates: saved piece, every file publishable (#34's mimeType set) — /// refuse loudly otherwise; then copy each file into assets/ and /// insert the refs at the drop point, `alt` selected for type-over. /// One shouldChangeText step = one undo; didChangeText drives the /// delegate (reattribute + session.edit + folds). func ingestDrop(_ urls: [URL]) -> Bool { guard let ingestFolder else { showIngestNotice("Illustrations only land in a saved post's prose editor.") return false } // The publish-able set IS #34's mimeType gate — nothing the rail // can't ship ever enters assets/. A mixed md+image set refuses // here too (only pure-markdown sets are forwarded upstream). guard urls.allSatisfy({ Micropub.mimeType(forDestination: $0.lastPathComponent) != nil }) else { showIngestNotice("Drop images (PNG, JPEG, GIF, WebP, SVG) or markdown — one kind at a time.") return false } let length = (string as NSString).length let mouse = NSEvent.mouseLocation let screenVisible = window?.convertToScreen(convert(visibleRect, to: nil)) ?? .zero var index = Self.dropIndex( length: length, targetY: mouse.y, bandMinY: screenVisible.minY, bandMaxY: screenVisible.maxY, ) { i in rectY(i, of: length) } // Never splice inside a word or link — slide to the next gap // (a drop ON an existing ref appends after it, dogfood 2026-11-02). let buffer = string as NSString func isGap(_ c: unichar) -> Bool { guard let scalar = Unicode.Scalar(Int(c)) else { return false } return CharacterSet.whitespacesAndNewlines.contains(scalar) } if index > 0, index < length, !isGap(buffer.character(at: index - 1)), !isGap(buffer.character(at: index)) { while index < length, !isGap(buffer.character(at: index)) { index += 1 } } do { // ponytail: multi-image ingest is non-atomic — if file N // fails mid-loop, earlier copies orphan in assets/ (harmless: // never referenced, never shipped; the collision suffix // absorbs them on retry). Pre-flight all sources if it bites. let snippet = try urls.map { try PostStore.illustrationRef(PostStore.ingestImage(from: $0, pieceFolder: ingestFolder)) }.joined(separator: " ") guard shouldChangeText(in: NSRange(location: index, length: 0), replacementString: snippet) else { return false } textStorage?.replaceCharacters(in: NSRange(location: index, length: 0), with: snippet) didChangeText() // The first ref's `alt` (offset +2, length 3): one keystroke // replaces it with the real description. let alt = NSRange(location: index + 2, length: 3) setSelectedRange(alt) // Leave the scroll stack as a keystroke would (dogfood // 2026-11-02: without this the inset was out of sync and the // editor froze scrolling until the next keypress). CaretCentering.syncTypewriterInset(textView: self) scrollRangeToVisible(alt) return true } catch { showIngestNotice("Couldn't ingest the image — \(error.localizedDescription)") return false // refused honestly: the drop bounces + the strip names why } } /// The transient refusal strip — mono-11 rust on a surface pill /// (focusChip voice), pinned to the scroll view's top-center so it /// never scrolls with the document. Auto-hides ~4 s after the last /// refusal. private var ingestNotice: NSTextField? private var ingestNoticeHide: DispatchWorkItem? private func showIngestNotice(_ text: String) { let strip: NSTextField if let ingestNotice { strip = ingestNotice } else { strip = NSTextField(labelWithString: "") strip.font = NSFont.monospacedSystemFont(ofSize: 11, weight: .regular) strip.textColor = NSColor(DesignTokens.accent) strip.alignment = .center strip.lineBreakMode = .byTruncatingMiddle strip.cell?.truncatesLastVisibleLine = true strip.wantsLayer = true strip.layer?.cornerRadius = DesignTokens.radius strip.layer?.masksToBounds = true strip.layer?.backgroundColor = NSColor(DesignTokens.surface).withAlphaComponent(0.96).cgColor ingestNotice = strip } strip.stringValue = text guard let host = enclosingScrollView ?? window?.contentView else { return } if strip.superview !== host { host.addSubview(strip) } strip.sizeToFit() let width = min(strip.frame.width + 28, host.bounds.width - 24) strip.frame = NSRect(x: (host.bounds.width - width) / 2, y: host.bounds.height - 36, width: width, height: 26) ingestNoticeHide?.cancel() let hide = DispatchWorkItem { [weak strip] in strip?.removeFromSuperview() } ingestNoticeHide = hide DispatchQueue.main.asyncAfter(deadline: .now() + 4, execute: hide) } // MARK: Chrome (chevron + ⋯ N) /// Plain overlay sibling that owns the chrome drawing — TextKit2 views hosted /// under SwiftUI never route through NSTextView.draw(_:), but a plain NSView /// subview always draws. Click-through (hitTest nil); document-coordinate /// space, so it rides the scroll view with the text. private let chrome = ProseChromeView() /// Install the overlay once the view reaches a window — the inherited /// NSTextView inits (which build the full TextKit stack) stay untouched. override func viewDidMoveToWindow() { super.viewDidMoveToWindow() guard window != nil, chrome.superview == nil else { return } chrome.owner = self chrome.frame = bounds chrome.autoresizingMask = [.width, .height] addSubview(chrome, positioned: .above, relativeTo: nil) chrome.refresh() } /// Parents count for the chrome's no-parents raster skip. var proseParentCount: Int { ProseList.parents(in: string).count } /// Render the whole chrome (chevrons + ⋯ N) into an image in the layer. /// Top-left flipped coordinates — same space as lineRect's output. func renderChromeImage(size: NSSize) -> NSImage? { guard let window else { return nil } let image = NSImage(size: size) image.lockFocusFlipped(true) drawListChrome() image.unlockFocus() return image } /// Parents whose marker line is not hidden inside another fold's scope — /// hidden ones collapse to ~zero height and would paint phantom chevrons. private var visibleParents: [ProseList.ParentHint] { let parents = ProseList.parents(in: string) let hiddenScopes = folds.compactMap { fold in parents.first(where: { $0.markerLine.location == fold.key })?.foldScope } return parents.filter { parent in !hiddenScopes.contains { NSLocationInRange(parent.markerLine.location, $0) } } } func drawListChrome() { for parent in visibleParents { guard let startRect = lineRect(ofOffset: parent.markerLine.location) else { continue } let folded = folds.contains { $0.key == parent.markerLine.location } drawChrome(folded ? "▸" : "▾", folded: folded, at: NSPoint(x: startRect.minX - 14, y: startRect.midY - chromeSize * 0.62)) if folded { // ⋯ N after the parent's visible line text, not after the marker. let text = lineText(of: parent.markerLine) as NSString let lastChar = parent.markerLine.location + max(0, text.length - 1) if let endRect = lineRect(ofOffset: lastChar) { drawChrome("⋯ \(parent.hiddenLineCount)", folded: true, at: NSPoint(x: endRect.maxX + 6, y: endRect.midY - chromeSize * 0.62)) } } } } override func mouseDown(with event: NSEvent) { // Plain single-clicks only — shift-click extends selection, double/ // triple-click select word/paragraph; neither toggles a fold. if !event.modifierFlags.intersection(.deviceIndependentFlagsMask).subtracting(.capsLock).isEmpty || event.clickCount > 1 { super.mouseDown(with: event) return } let point = convert(event.locationInWindow, from: nil) for parent in visibleParents { guard let rect = lineRect(ofOffset: parent.markerLine.location) else { continue } // Toggle zone: the gutter through the marker span ("- ", "1. ") // of the marker line's first visual line. if point.y >= rect.minY - 1, point.y <= rect.maxY + 1, point.x < rect.minX + 12 { toggleFold(parent) return } } super.mouseDown(with: event) } /// mono-11 chrome, rust when folded, muted open (the outliner's /// "⋯ N" vocabulary carried to prose). private let chromeSize: CGFloat = 11 private func drawChrome(_ glyph: String, folded: Bool, at point: NSPoint) { NSAttributedString(string: glyph, attributes: [ .font: NSFont.monospacedSystemFont(ofSize: chromeSize, weight: .regular), .foregroundColor: folded ? NSColor(DesignTokens.accent) : NSColor(DesignTokens.muted), ]).draw(at: point) } // MARK: Geometry (TextKit2) /// View-space rect of the character at `offset` via the selection system /// — `selectionRects(for:)` is TextKit-version-agnostic NSTextView API and /// geometry the caret already renders from (#115 field finding: every /// NSTextLayoutManager fragment query — bridge, lookup, enumeration — /// yields nothing under SwiftUI-hosted viewport layout). private func lineRect(ofOffset offset: Int) -> NSRect? { let length = (string as NSString).length guard length > 0 else { return nil } let clamped = min(max(0, offset), length - 1) var actual = NSRange() // NSTextInputClient returns SCREEN coordinates (IME positioning); // screen → window → view before using it as geometry. let screenRect = firstRect(forCharacterRange: NSRange(location: clamped, length: 1), actualRange: &actual) guard screenRect != .zero else { return nil } let windowRect = window?.convertFromScreen(screenRect) ?? screenRect return convert(windowRect, from: nil) } }