feat(reading): swap reading surface to apex HTML pipeline (#76)

ReadingPresenter becomes markdown -> bundled apex -> HTML fragment with
data-source-line stamps (chunker sentinels + regex restamp, #74-proven);
ReadingSurface becomes one WKWebView reloaded in place (no remount), CSS
vars from ProseTypography slots + flow knobs. TextKit reading machinery
deleted (ADR-0011: no fallbacks; stale-flow defect dies unfixed).
Footnotes now render natively (apex upgrade over #69's fallback). Tests
re-targeted at HTML string asserts incl. real-bundled-binary pipeline runs.

Closes-nothing: wayfinder #76 on map #20; branch wayfinder/76-apex-html-reading.
This commit is contained in:
AlexKucera committed 2026-10-06 18:26:22 +02:00
1 parent fffcb0a059
commit cc04ec236e
4 files changed
+505 -965

No files matched your search

+177 -285
View File
@@ -2,16 +2,20 @@
// 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).
// #76 (S1.2, map #20; ADR-0011): the reading surface is one WKWebView,
// reloaded in place — never remounted per document (the remount was the
// dominant switch cost, #74). Loads ReadingPresenter's page (apex HTML +
// data-source-line map). Interaction per #68: tap = edit intent at the
// tapped block's source paragraph; ⌘-click opens links; scroll tracking
// feeds the flip-back map. Typography/flow changes reload the page (CSS
// vars are injected at load). The TextKit canvas (ReadingCanvasView,
// decorations, framesForRange, ImagePopoverView) is deleted with the
// pivot — ADR-0011: no fallbacks.
//
import AppKit
import SwiftUI
import WebKit
/// Live reading-position state for flip-back scroll mapping (#68). Plain
/// class held `@State` by the editor — reference identity survives renders.
@@ -31,320 +35,208 @@ final class CaretHintBox {
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).
/// Reading surface: renders `text` via ReadingPresenter (apex HTML) into a
/// WKWebView reloaded in place. Re-renders when `generation` moves (open /
/// Yes-reload), the text changes (draft path), or flow knobs move — never
/// per keystroke.
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.
/// The post's folder — resolves relative image URLs (apex --base-dir).
/// Nil for drafts.
var postFolder: URL?
/// UTF-16 caret location captured when reading opened; scrolls the
/// containing block to the top (#68 mapping attempt).
/// UTF-16 caret location captured when reading opened; scrolls that
/// 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]
// 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 = 24
tv.textContainerInset = NSSize(width: 0, height: 24)
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
context.coordinator.watchDefaults(tv, representable: self)
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 = ""
func makeNSView(context: Context) -> WKWebView {
let cfg = WKWebViewConfiguration()
let ucc = cfg.userContentController
ucc.addUserScript(WKUserScript(source: Self.probeJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
ucc.add(context.coordinator, name: "sourceClick")
ucc.add(context.coordinator, name: "sourceScroll")
ucc.add(context.coordinator, name: "openLink")
let wv = WKWebView(frame: .zero, configuration: cfg)
wv.navigationDelegate = context.coordinator
// Paint the page bg while loading instead of AppKit white (flash fix, #74).
wv.underPageBackgroundColor = NSColor(red: 0.984, green: 0.984, blue: 0.992, alpha: 1)
context.coordinator.webView = wv
context.coordinator.watchDefaults()
return wv
}
func updateNSView(_ wv: WKWebView, context: Context) {
let c = context.coordinator
c.onEditIntent = onEditIntent
c.stateBox = stateBox
c.postFolder = postFolder
let key = "\(generation):\(text.hashValue):\(ProseTypography.flowKey)"
guard c.loadedKey != key else { return }
c.load(text: text, generation: generation, entryCaret: entryCaretLocation, key: key)
}
// Mapping probes: click → source line; ⌘-click → open; scroll → top
// visible source line (same map → scroll-sync). Spike-verified (#74).
static let probeJS = """
function stamped(el){ return el.closest('[data-source-line]'); }
document.addEventListener('click', function(e){
const a = e.target.closest('a');
if (a) {
e.preventDefault(); // reading never navigates in-app
if (e.metaKey || e.ctrlKey) window.webkit.messageHandlers.openLink.postMessage(a.href);
else { const s = stamped(a); if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine); }
return;
}
const s = stamped(e.target);
if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine);
}, true);
let ticking = false;
addEventListener('scroll', function(){
if (ticking) return; ticking = true;
requestAnimationFrame(function(){
ticking = false;
for (const el of document.querySelectorAll('[data-source-line]')) {
const r = el.getBoundingClientRect();
if (r.bottom > 44) { window.webkit.messageHandlers.sourceScroll.postMessage(el.dataset.sourceLine); return; }
}
});
}, {passive: true});
"""
/// Scroll the entry block to the top after paint (#68 entry mapping).
static func entryScrollJS(_ line: Int) -> String {
"""
(function(line){
for (const el of document.querySelectorAll('[data-source-line]')) {
if (parseInt(el.dataset.sourceLine) === line) {
window.scrollTo(0, el.getBoundingClientRect().top + window.scrollY - 24);
return;
}
}
})(\(line));
"""
}
// @MainActor: WKNavigationDelegate + WKScriptMessageHandler requirements
// are MainActor in the SDK; the project is default-MainActor anyway.
@MainActor
final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
weak var webView: WKWebView?
var onEditIntent: ((Int) -> Void)?
var stateBox: ReadingStateBox?
var postFolder: URL?
var loadedKey = ""
/// Block map of the loaded page (source line + range).
var blocks: [ReadingPresenter.Block] = []
/// Line to scroll to once the page paints (entry mapping, #68).
var pendingEntryScrollLine: Int?
var painted = false
private var lastText = ""
private var defaultsObserver: NSObjectProtocol?
private var appliedFlowKey = ""
/// Rebuild the rendered document when typography/flow knobs move
/// (SwiftUI doesn't re-call updateNSView on UserDefaults writes).
func watchDefaults(_: ReadingCanvasView, representable: ReadingSurface) {
/// Build + load the page for `text`. All render paths land here
/// (updateNSView, typography-change reload).
func load(text: String, generation: Int, entryCaret: Int?, key: String) {
loadedKey = key
lastText = text
painted = false
let (pageHTML, blockMap) = ReadingPresenter.page(for: text, postFolder: postFolder)
blocks = blockMap
pendingEntryScrollLine = entryLine(for: entryCaret)
webView?.loadHTMLString(pageHTML, baseURL: nil)
}
/// The block whose source range holds the caret; else the next block
/// at/after it (#68: jank fallback = top of page via nil).
private func entryLine(for caret: Int?) -> Int? {
guard let caret else { return nil }
if let hit = blocks.first(where: { NSLocationInRange(caret, $0.sourceRange) }) {
return hit.sourceLine
}
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
}
/// Typography/flow knob moves reload the page (CSS vars are injected
/// at load; SwiftUI doesn't re-call updateNSView on UserDefaults
/// writes).
func watchDefaults() {
guard defaultsObserver == nil else { return }
appliedFlowKey = ProseTypography.flowKey
defaultsObserver = NotificationCenter.default.addObserver(
forName: UserDefaults.didChangeNotification,
object: nil,
queue: .main,
queue: .main
) { [weak self] _ in
guard let self, let canvas else { return }
let key = ProseTypography.flowKey
guard key != appliedFlowKey else { return }
appliedFlowKey = key
let doc = ReadingPresenter.document(for: representable.text, resolvingImagesIn: representable.postFolder)
canvas.textStorage?.setAttributedString(doc.content)
canvas.blockBounds = doc.bounds
canvas.needsDisplay = true
Task { @MainActor [weak self] in
guard let self else { return }
let key = ProseTypography.flowKey
guard key != appliedFlowKey else { return }
appliedFlowKey = key
self.load(
text: lastText,
generation: 0,
entryCaret: nil,
key: "\(loadedKey)|flow"
)
}
}
}
}
}
/// 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
// ponytail: observer registration lives for the coordinator's
// lifetime (app-scoped defaults notifications, same as ProseTextView's
// coordinator — no removal, matching the codebase convention).
var blockBounds: [BlockBound] = []
var onEditIntent: ((Int) -> Void)?
var stateBox: ReadingStateBox?
var postFolder: URL?
// MARK: WKNavigationDelegate
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 }
}
// MARK: Decorations (#69 fix: quote hairlines, HR rules, table grids —
// drawn from measured TK2 fragment geometry; NSTextBlock/NSTextTable
// layout is broken on modern TextKit and the TK1-compat bridge reports
// wrong rects. Enumeration pattern is probe-proven: walk ALL fragments
// from document start, map each to a doc offset, slice per bound.)
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let origin = textContainerOrigin
for bound in blockBounds {
guard let decoration = bound.decoration else { continue }
// frames arrive in CONTAINER space; the view draws text at
// textContainerOrigin + frame (inset shifts it — the missing
// +origin.y drew every decoration 20pt too high).
let frames = framesForRange(bound.docRange)
.map { CGRect(x: $0.minX + origin.x, y: $0.minY + origin.y, width: $0.width, height: $0.height) }
guard let firstFrame = frames.first, let lastFrame = frames.last else { continue }
switch decoration {
case let .quote(indent):
let x = (textContainer?.lineFragmentPadding ?? 0) + indent - 6
let path = NSBezierPath()
path.move(to: NSPoint(x: x, y: firstFrame.minY))
path.line(to: NSPoint(x: x, y: lastFrame.maxY))
path.lineWidth = 2
ProseTypography.quoteRuleColor.setStroke()
path.stroke()
case .rule:
let y = (firstFrame.minY + firstFrame.maxY) / 2
let path = NSBezierPath()
path.move(to: NSPoint(x: 0, y: y))
path.line(to: NSPoint(x: (textContainer?.size.width ?? 0), y: y))
path.lineWidth = 1
ProseTypography.tableBorderColor.setStroke()
path.stroke()
case let .table(columns):
let originX = (textContainer?.lineFragmentPadding ?? 0)
let path = NSBezierPath()
for offset in columns {
let x = originX + offset
path.move(to: NSPoint(x: x, y: firstFrame.minY))
path.line(to: NSPoint(x: x, y: lastFrame.maxY))
}
let ys = [firstFrame.minY] + frames.map(\.maxY)
for y in ys {
path.move(to: NSPoint(x: originX, y: y))
path.line(to: NSPoint(x: originX + (columns.last ?? 0), y: y))
}
path.lineWidth = 1
ProseTypography.tableBorderColor.setStroke()
path.stroke()
}
func webView(_ wv: WKWebView, didFinish nav: WKNavigation!) {
guard !painted else { return }
painted = true
guard let line = pendingEntryScrollLine else { return }
pendingEntryScrollLine = nil
wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line))
}
}
/// Line frames for a document character range, engine-agnostic: TK2
/// fragments when present, else TK1 boundingRect per character line
/// (lineFragmentRect returns degenerate rects mid-layout on TK1 here).
func framesForRange(_ docRange: NSRange) -> [CGRect] {
if let tlm = textLayoutManager, let tcm = tlm.textContentManager {
let docStart = tcm.documentRange.location
var frames: [CGRect] = []
tlm.enumerateTextLayoutFragments(from: docStart) { fragment in
let tr = fragment.rangeInElement
let loc = tcm.offset(from: docStart, to: tr.location)
let len = tcm.offset(from: tr.location, to: tr.endLocation)
if NSIntersectionRange(NSRange(location: loc, length: len), docRange).length > 0 {
frames.append(fragment.layoutFragmentFrame)
}
return true
}
return frames
}
guard let layoutManager, let container = textContainer else { return [] }
let nsText = string as NSString
var frames: [CGRect] = []
var lineStart = docRange.location
while lineStart < NSMaxRange(docRange) {
let lineRange = nsText.lineRange(for: NSRange(location: lineStart, length: 0))
let clamped = NSIntersectionRange(lineRange, docRange)
guard clamped.length > 0 else { break }
let glyphRange = layoutManager.glyphRange(forCharacterRange: clamped, actualCharacterRange: nil)
frames.append(layoutManager.boundingRect(forGlyphRange: glyphRange, in: container))
lineStart = NSMaxRange(lineRange)
}
return frames
}
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)
// Allow our own loadHTMLString main-frame load (about:blank); a
// blanket .cancel would kill the page before it paints. Everything
// else is cancelled — reading never navigates in-app (#74 lesson).
func webView(
_ wv: WKWebView,
decidePolicyFor nav: WKNavigationAction,
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void
) {
if nav.targetFrame?.isMainFrame == true,
let u = nav.request.url, u.scheme == "file" || u.absoluteString == "about:blank" {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
}
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)
// MARK: WKScriptMessageHandler — the source map in action
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)
func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
case "openLink":
if let s = message.body as? String, let url = URL(string: s) { NSWorkspace.shared.open(url) }
case "sourceClick", "sourceScroll":
guard let s = message.body as? String, let line = Int(s),
let block = blocks.first(where: { $0.sourceLine == line }) else { return }
if message.name == "sourceClick" {
onEditIntent?(block.sourceRange.location)
} else {
stateBox?.topSourceLocation = block.sourceRange.location
}
default:
break
}
}
}