Five root causes behind Alexander's calibration findings: - Wrap to column: both canvases had a fixed 640pt text container — clipped instead of wrapping when the editor column is narrower (library + mentor open). widthTracksTextView = true now; measure polish can return with calibration. - Tables: TextKit2 stacks NSTextTable rows vertically (each row its own content-width fragment — no grid). The reading canvas forces the TextKit1 bridge (replaceLayoutManager); probe-verified grid + column borders. Read-only canvas — nothing editing-grade lost. - Heading-tail: a chunk like "# Title" followed by body lines (single newline, legal markdown) dropped everything after line one. The heading now renders, then the remaining lines as a soft-joined paragraph. - Stale reload (data-loss vector): ProseTextView seeded from session.loadText (open-time snapshot) — after a reading⇄editing swap the recreated editor showed the pre-paste text, and a keystroke there flushed stale content over the user's real edits. Seeds from session.text (live) now. - Quote one-char-per-line: did not reproduce after the layout fixes; root cause was the broken layout state above. EditorSessionTests debounce flake (50ms margin under parallel load) passed on both re-runs — timing margin, not a regression. Full suite green (94 unit + UI smoke); lint clean.
244 lines
8.5 KiB
Swift
244 lines
8.5 KiB
Swift
//
|
|
// ReadingSurface.swift
|
|
// Museion
|
|
//
|
|
// #71 (S1.2, map #20): the reading-mode surface — the renderer's blocks set
|
|
// into a read-only, selectable NSTextView (#68: reading is a presentation
|
|
// of the same TextKit2 document, not a separate view stack). Interaction
|
|
// per #68: drag-select stays native; a tap with no selection = edit intent
|
|
// (drop to editing at the clicked block's source paragraph); ⌘-click opens
|
|
// links; hovering an image block pops the loaded image (#69 floor).
|
|
//
|
|
|
|
import AppKit
|
|
import SwiftUI
|
|
|
|
/// Live reading-position state for flip-back scroll mapping (#68). Plain
|
|
/// class held `@State` by the editor — reference identity survives renders.
|
|
final class ReadingStateBox {
|
|
/// Source caret location when reading opened — scrolls that block to the
|
|
/// top (#68 entry mapping).
|
|
var entryLocation: Int?
|
|
/// Source location of the top visible block; updated as reading scrolls
|
|
/// (#68 flip-back mapping).
|
|
var topSourceLocation: Int?
|
|
}
|
|
|
|
/// One-shot caret placement for the editing surface (#68): set when reading
|
|
/// flips back (click-to-edit or toggle-back), consumed by ProseTextView.
|
|
final class CaretHintBox {
|
|
var location: Int?
|
|
var consumed = true
|
|
}
|
|
|
|
/// Reading surface: renders `text` via ReadingPresenter into a scrollable,
|
|
/// read-only canvas. Rebuilds when `generation` moves (open / Yes-reload) or
|
|
/// the text genuinely changes (draft edit path).
|
|
struct ReadingSurface: NSViewRepresentable {
|
|
let text: String
|
|
/// Session loadGeneration (0 for drafts) — rebuild key, never per keystroke.
|
|
var generation: Int
|
|
/// The post's folder — resolves relative image URLs. Nil for drafts.
|
|
var postFolder: URL?
|
|
/// UTF-16 caret location captured when reading opened; scrolls the
|
|
/// containing block to the top (#68 mapping attempt).
|
|
var entryCaretLocation: Int?
|
|
var onEditIntent: (Int) -> Void
|
|
/// Flip-back scroll mapping target.
|
|
var stateBox: ReadingStateBox?
|
|
|
|
func makeNSView(context: Context) -> NSScrollView {
|
|
let tv = ReadingCanvasView()
|
|
tv.isEditable = false
|
|
tv.isSelectable = true
|
|
tv.isRichText = false
|
|
tv.allowsUndo = false
|
|
tv.isAutomaticQuoteSubstitutionEnabled = false
|
|
tv.isAutomaticDashSubstitutionEnabled = false
|
|
tv.isAutomaticTextReplacementEnabled = false
|
|
tv.isAutomaticSpellingCorrectionEnabled = false
|
|
tv.backgroundColor = NSColor.white
|
|
tv.typingAttributes = ProseTypography.bodyAttributes
|
|
tv.minSize = NSSize(width: 0, height: 0)
|
|
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
|
tv.isVerticallyResizable = true
|
|
tv.isHorizontallyResizable = false
|
|
tv.autoresizingMask = [.width]
|
|
// Tables (#69) lay out correctly under TextKit1 only — TK2 stacks
|
|
// NSTextTable rows vertically (probed). The canvas is read-only, so
|
|
// nothing editing-grade is lost by forcing the TK1 bridge.
|
|
tv.textContainer?.replaceLayoutManager(NSLayoutManager())
|
|
// Wrap to the editor column (#68/71 fix): the container tracks the
|
|
// view width — a fixed 640pt measure clipped in narrower columns.
|
|
tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)
|
|
tv.textContainer?.widthTracksTextView = true
|
|
tv.textContainer?.lineFragmentPadding = 12
|
|
tv.textContainerInset = NSSize(width: 0, height: 20)
|
|
let scroll = NSScrollView()
|
|
scroll.documentView = tv
|
|
scroll.hasVerticalScroller = true
|
|
scroll.autohidesScrollers = true
|
|
scroll.drawsBackground = true
|
|
scroll.backgroundColor = NSColor.white
|
|
tv.onEditIntent = onEditIntent
|
|
tv.stateBox = stateBox
|
|
context.coordinator.canvas = tv
|
|
return scroll
|
|
}
|
|
|
|
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
|
guard let tv = scroll.documentView as? ReadingCanvasView else { return }
|
|
tv.onEditIntent = onEditIntent
|
|
tv.stateBox = stateBox
|
|
tv.postFolder = postFolder
|
|
guard context.coordinator.builtGeneration != generation || context.coordinator.builtText != text else { return }
|
|
context.coordinator.builtGeneration = generation
|
|
context.coordinator.builtText = text
|
|
let doc = ReadingPresenter.document(for: text, resolvingImagesIn: postFolder)
|
|
tv.textStorage?.setAttributedString(doc.content)
|
|
tv.blockBounds = doc.bounds
|
|
tv.needsLayout = true
|
|
tv.layoutSubtreeIfNeeded()
|
|
if let caret = entryCaretLocation, let bound = tv.bound(containing: caret) {
|
|
tv.scrollRangeToVisible(NSRange(location: bound.docRange.location, length: 0))
|
|
} else {
|
|
tv.scroll(NSPoint(x: 0, y: 0))
|
|
}
|
|
}
|
|
|
|
func makeCoordinator() -> Coordinator {
|
|
Coordinator()
|
|
}
|
|
|
|
final class Coordinator {
|
|
weak var canvas: ReadingCanvasView?
|
|
var builtGeneration = -1
|
|
var builtText = ""
|
|
}
|
|
}
|
|
|
|
/// The reading canvas: click discrimination, ⌘-click links, image hover
|
|
/// popover, top-block scroll tracking. Read-only over rendered content.
|
|
final class ReadingCanvasView: NSTextView {
|
|
typealias BlockBound = ReadingPresenter.Bound
|
|
|
|
var blockBounds: [BlockBound] = []
|
|
var onEditIntent: ((Int) -> Void)?
|
|
var stateBox: ReadingStateBox?
|
|
var postFolder: URL?
|
|
|
|
private var popover: NSPopover?
|
|
private var hoverTrackingArea: NSTrackingArea?
|
|
|
|
/// Last bound starting at or before `index` (spacing separators clamp to
|
|
/// the preceding block).
|
|
func bound(containing index: Int) -> BlockBound? {
|
|
blockBounds.last { $0.docRange.location <= index }
|
|
}
|
|
|
|
override func updateTrackingAreas() {
|
|
super.updateTrackingAreas()
|
|
if hoverTrackingArea == nil {
|
|
let area = NSTrackingArea(
|
|
rect: bounds, options: [.mouseMoved, .activeAlways, .inVisibleRect],
|
|
owner: self, userInfo: nil,
|
|
)
|
|
addTrackingArea(area)
|
|
hoverTrackingArea = area
|
|
}
|
|
}
|
|
|
|
// MARK: Click discrimination (#68)
|
|
|
|
override func mouseDown(with event: NSEvent) {
|
|
let point = convert(event.locationInWindow, from: nil)
|
|
if event.modifierFlags.contains(.command) {
|
|
let index = characterIndex(for: point)
|
|
if index != NSNotFound, let url = textStorage?.attribute(.link, at: index, effectiveRange: nil) as? URL {
|
|
NSWorkspace.shared.open(url)
|
|
return
|
|
}
|
|
}
|
|
super.mouseDown(with: event)
|
|
// NSTextView's mouseDown consumes the mouse-up in its own tracking
|
|
// loop — the click is complete once super returns. Tap = single
|
|
// click, no drag, no selection formed (#68: drag-select never
|
|
// registers; triple-click paragraph select has length > 0).
|
|
let upScreen = NSEvent.mouseLocation
|
|
let upWindow = window.map { $0.convertFromScreen(NSRect(origin: upScreen, size: .zero)).origin }
|
|
?? event.locationInWindow
|
|
let downWindow = event.locationInWindow
|
|
let moved = hypot(upWindow.x - downWindow.x, upWindow.y - downWindow.y)
|
|
guard event.clickCount == 1, moved < 4, selectedRange().length == 0 else { return }
|
|
let index = characterIndex(for: point)
|
|
guard index != NSNotFound, let bound = bound(containing: index) else { return }
|
|
onEditIntent?(bound.sourceRange.location)
|
|
}
|
|
|
|
// MARK: Scroll tracking (#68 flip-back mapping)
|
|
|
|
override func reflectScrolledClipView(_ clipView: NSClipView) {
|
|
super.reflectScrolledClipView(clipView)
|
|
let visible = NSPoint(x: 0, y: visibleRect.minY + 1)
|
|
let index = characterIndex(for: visible)
|
|
if index != NSNotFound, let bound = bound(containing: index) {
|
|
stateBox?.topSourceLocation = bound.sourceRange.location
|
|
}
|
|
}
|
|
|
|
// MARK: Image hover popover (#69 floor)
|
|
|
|
override func mouseMoved(with event: NSEvent) {
|
|
super.mouseMoved(with: event)
|
|
let point = convert(event.locationInWindow, from: nil)
|
|
let index = characterIndex(for: point)
|
|
guard index != NSNotFound, let bound = bound(containing: index), let url = bound.imageURL else {
|
|
popover?.close()
|
|
popover = nil
|
|
return
|
|
}
|
|
guard popover == nil else { return }
|
|
let pop = NSPopover()
|
|
pop.behavior = .transient
|
|
pop.contentViewController = NSHostingController(rootView: ImagePopoverView(url: url))
|
|
pop.contentSize = NSSize(width: 480, height: 360)
|
|
pop.show(relativeTo: CGRect(origin: point, size: NSSize(width: 1, height: 1)), of: self, preferredEdge: .maxY)
|
|
popover = pop
|
|
}
|
|
|
|
override func mouseExited(with event: NSEvent) {
|
|
super.mouseExited(with: event)
|
|
popover?.close()
|
|
popover = nil
|
|
}
|
|
}
|
|
|
|
/// The hover popover's content: loads the image off-main, scaled to fit.
|
|
private struct ImagePopoverView: View {
|
|
let url: URL
|
|
@State private var image: NSImage?
|
|
|
|
var body: some View {
|
|
Group {
|
|
if let image {
|
|
Image(nsImage: image)
|
|
.resizable()
|
|
.scaledToFit()
|
|
} else {
|
|
ProgressView()
|
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
|
}
|
|
}
|
|
.frame(maxWidth: 480, maxHeight: 360)
|
|
.task {
|
|
// Data off-main (Sendable); NSImage decoded on-main.
|
|
let data = await Task.detached(priority: .userInitiated) {
|
|
try? Data(contentsOf: url)
|
|
}.value
|
|
if let data {
|
|
image = NSImage(data: data)
|
|
}
|
|
}
|
|
}
|
|
}
|