// // ReadingSurface.swift // Museion // // #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. 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 (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 (apex --base-dir). /// Nil for drafts. var postFolder: URL? /// 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 makeCoordinator() -> Coordinator { Coordinator() } 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 return wv } func updateNSView(_: WKWebView, context: Context) { let coordinator = context.coordinator coordinator.onEditIntent = onEditIntent coordinator.stateBox = stateBox coordinator.postFolder = postFolder let key = "\(generation):\(text.hashValue)" guard coordinator.loadedKey != key else { return } coordinator.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 = "" /// 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 } // MARK: WKNavigationDelegate func webView(_ wv: WKWebView, didFinish _: WKNavigation!) { guard !painted else { return } painted = true guard let line = pendingEntryScrollLine else { return } pendingEntryScrollLine = nil wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line)) } /// True for our own loadHTMLString main-frame load (file URL or /// about:blank) — the only navigation reading allows in-app. private func isOwnMainFrameLoad(_ nav: WKNavigationAction) -> Bool { guard nav.targetFrame?.isMainFrame == true, let url = nav.request.url else { return false } return url.scheme == "file" || url.absoluteString == "about:blank" } /// 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( _: WKWebView, decidePolicyFor nav: WKNavigationAction, decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void, ) { if isOwnMainFrameLoad(nav) { decisionHandler(.allow) return } decisionHandler(.cancel) } // MARK: WKScriptMessageHandler — the source map in action func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) { switch message.name { case "openLink": if let body = message.body as? String, let url = URL(string: body) { NSWorkspace.shared.open(url) } case "sourceClick", "sourceScroll": guard let body = message.body as? String, let line = Int(body), 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 } } } }