diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index b05e056..5860c00 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -27,7 +27,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro - `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on `posts/`, rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `posts/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip. - Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — the lifted spike presenter: line-kind → attributes map (Iowan Old Style 17 body, 26/20 bold headings, quote spacing, `***`-rule syntaxOnly), dimmed syntax (marker prefixes + inline marks, mono 13 at 0.55 white), pure functions; full-doc `attribute` on load, per-paragraph `reattribute` on edit. `EditorSession.swift` — @MainActor @Observable session per open post: `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` writes `PostStore.overwrite` + the cursor sidecar, tracks `saveState` Saved→Saving…→Saved (+ Save failed in accent, #65, routed to `lastError` too); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local; `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads the sidecar; `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); `folderURL` exposes `posts//` for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too). `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in `posts//.museion-state.json` — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save). - `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. Typography section (#71/#70): three role slots — Body / Headings / Code — each a `SlotRow` (family Picker over all installed families with the current faces prepended — `availableFontFamilies` omits e.g. Iowan Old Style — plus a size field), UserDefaults-backed, re-picking is reset. -- Reading mode (#71 / S1.2, map #20; decisions #68/#69/#70): `ReadingPresenter.swift` — the reading renderer, pure over its input: blank-line split → one block per chunk; classification order HR (editing's `syntaxOnly` predicate) → list run → quote run → flow (heading/fence/table/paragraph); lists render bullets + ordered in ONE path (per-level sequential counters make `1. 1. 1.` → 1, 2, 3 — glyphs only, file never rewritten); nesting by indent (0–1 sp → L1, 2–3 → L2, 4+ → L3+); headings h1 = Headings slot size, h2 = 0.77×, ### = body+1, #### floors at bold body; fenced code mono; blockquotes via `QuoteTextBlock` (hairline draw override), HR via `RuleTextBlock`; tables via `NSTextTable` (1px border, delimiter-row alignment honored); images ride alone as hover-payload blocks (URL recovered at chunk level — the inline parser renders `![alt](url)` as bare alt text); links styled + `.link` retained; footnotes the one fallback (source text); `document(for:resolvingImagesIn:)` concatenates blocks + `\n` separators into one storage with per-block `Bound{docRange, sourceRange, imageURL}` — the click→edit and scroll maps. `ReadingSurface.swift` — `ReadingCanvasView` (read-only selectable NSTextView, 640pt measure, builds keyed by session `loadGeneration`/text): tap-to-edit runs AFTER `super.mouseDown` returns (NSTextView's tracking loop consumes the mouse-up — a `mouseUp` override never fires); single click + no selection + <4pt move = edit intent → `onEditIntent(sourceLocation)`; ⌘-click opens `.link` URLs; `reflectScrolledClipView` tracks the top visible block into `ReadingStateBox` (flip-back mapping); image hover NSPopover (`ImagePopoverView`, loads off-main). `PostEditorView` toggle (#68): Read⇄Edit toolbar button far left + View menu "Toggle Reading Mode" + ⌘R (`.toggleReadingMode` notification — SwiftUI CommandMenu posts, the visible editor listens); reading state transient per open (`@State reading`, no persistence — fresh open = editing); drafts included (`draftMirror`); entry mapping scrolls the caret's block to top; flip-back lands the caret via `caretHint(location, token)` applied once per token in `ProseTextView.updateNSView`. `ProseTypography.swift` (#70) — the three role slots: UserDefaults `proseBodyFace/Size`, `proseHeadingsFace/Size`, `proseCodeFace/Size` (defaults Concourse OT Book 17 / Iowan Old Style bold 26 / UbuntuMono Nerd Font Mono 13; registered in `AppGateState.init`); fonts resolve through the family MEMBER list (`availableMembers(ofFontFamily:)`, prefer Book/Regular style names, else closest to weight 5 — family+weight lookup misresolves Concourse: Thin and Book both advertise weight 4); missing face → silent system font; both prose surfaces + the editing presenter's headings/dimmed-syntax read the slots; chrome stays system faces. +- Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir ]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one
    , killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — ProseTypography slots + flow knobs as CSS custom properties (`--body-face/--headings-size/--lh/...`, family names not member PS names; weight rides CSS). Fallback on apex failure = escaped source in a `
    ` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; defaults observer reloads on flow-key change (CSS vars injected at load). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
     - `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error). `ProseTypography.registerDefaults()` rides the same init (#71).
     - `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
     
    @@ -63,8 +63,8 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
     
     ## Work Guidance
     
    -- Native SwiftUI only — no web-editor embedding, no Electron-style components (ADR-0001).
    -- Text editing gets built on TextKit 2 / SwiftUI directly; no CodeMirror/ProseMirror-class dependencies.
    +- Native SwiftUI only on the editing side — no web-editor embedding, no Electron-style components (ADR-0001; reading-mode WKWebView is allowed per ADR-0011: reading is presentation).
    +- Text editing gets built on TextKit 2 / SwiftUI directly; no CodeEdit/CodeMirror/ProseMirror-class editing dependencies.
     
     ## Verification
     
    diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift
    index 1ec0525..ebc8c6b 100644
    --- a/Museion/ReadingPresenter.swift
    +++ b/Museion/ReadingPresenter.swift
    @@ -48,18 +48,28 @@ nonisolated enum ReadingPresenter {
     				out.append(Block(sourceLine: line, sourceRange: NSRange(location: loc, length: end - loc)))
     			}
     			// advance line count over the chunk + the blank separator run
    -			var i = loc
    -			while i < end {
    -				if ns.character(at: i) == 0x0A { line += 1 }
    -				i += 1
    +			var index = loc
    +			while index < end {
    +				if ns.character(at: index) == 0x0A {
    +					line += 1
    +				}
    +				index += 1
     			}
    -			if delim.location == NSNotFound { break }
    -			var j = delim.location
    -			while j < ns.length {
    -				let c = ns.character(at: j)
    -				if c == 0x0A { line += 1; j += 1 } else if c == 0x0D { j += 1 } else { break }
    +			if delim.location == NSNotFound {
    +				break
     			}
    -			loc = j
    +			var scan = delim.location
    +			while scan < ns.length {
    +				let char = ns.character(at: scan)
    +				if char == 0x0A {
    +					line += 1; scan += 1
    +				} else if char == 0x0D {
    +					scan += 1
    +				} else {
    +					break
    +				}
    +			}
    +			loc = scan
     		}
     		return out
     	}
    @@ -67,15 +77,21 @@ nonisolated enum ReadingPresenter {
     	/// Prepend `` (N = 1-based source line) before every blank-line
     	/// chunk — apex passes HTML comments through verbatim (#74).
     	static func stampSource(_ source: String) -> String {
    -		let isBlank = { (l: Substring) in l.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
    +		let isBlank = { (line: Substring) in line.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
     		let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
     		var out: [String] = []
    -		var i = 0
    -		while i < lines.count {
    -			if isBlank(lines[i]) { i += 1; continue }
    -			if !out.isEmpty { out.append("") }
    -			out.append("")
    -			while i < lines.count && !isBlank(lines[i]) { out.append(String(lines[i])); i += 1 }
    +		var index = 0
    +		while index < lines.count {
    +			if isBlank(lines[index]) {
    +				index += 1; continue
    +			}
    +			if !out.isEmpty {
    +				out.append("")
    +			}
    +			out.append("")
    +			while index < lines.count, !isBlank(lines[index]) {
    +				out.append(String(lines[index])); index += 1
    +			}
     		}
     		return out.joined(separator: "\n")
     	}
    @@ -83,10 +99,13 @@ nonisolated enum ReadingPresenter {
     	/// Rewrite `` into `data-source-line="N"` on the element that
     	/// follows (spike regex, 0 mis-stamps corpus-wide, #74).
     	static func stampHTML(_ html: String) -> String {
    -		let re = try! NSRegularExpression(pattern: #"\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
    -		let ms = NSMutableString(string: html)
    -		re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"")
    -		return ms as String
    +		// Static literal pattern — compiles by construction; a failure would
    +		// crash at first render and every test with it.
    +		// swiftlint:disable:next force_try
    +		let regex = try! NSRegularExpression(pattern: #"\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
    +		let mutable = NSMutableString(string: html)
    +		regex.replaceMatches(in: mutable, range: NSMakeRange(0, mutable.length), withTemplate: "<$2 data-source-line=\"$1\"")
    +		return mutable as String
     	}
     
     	// MARK: Apex runner (bundled binary, ADR-0011)
    @@ -97,9 +116,11 @@ nonisolated enum ReadingPresenter {
     		if let bundlePath = Bundle.main.path(forResource: "apex", ofType: nil) {
     			return bundlePath
     		}
    -		if let env = ProcessInfo.processInfo.environment["APEX_PATH"] { return env }
    -		for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) {
    -			return p
    +		if let env = ProcessInfo.processInfo.environment["APEX_PATH"] {
    +			return env
    +		}
    +		for path in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: path) {
    +			return path
     		}
     		return nil
     	}
    @@ -113,31 +134,33 @@ nonisolated enum ReadingPresenter {
     		guard let bin = apexBinaryPath() else {
     			throw CocoaError(.fileNoSuchFile)
     		}
    -		let p = Process()
    -		p.executableURL = URL(fileURLWithPath: bin)
    +		let process = Process()
    +		process.executableURL = URL(fileURLWithPath: bin)
     		var args = ["-t", "html", "--no-mixed-lists", "--embed-images"]
    -		if let baseDir { args += ["--base-dir", baseDir.path] }
    -		p.arguments = args
    +		if let baseDir {
    +			args += ["--base-dir", baseDir.path]
    +		}
    +		process.arguments = args
     		let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
    -		p.standardInput = stdin
    -		p.standardOutput = stdout
    -		p.standardError = stderr
    -		try p.run()
    +		process.standardInput = stdin
    +		process.standardOutput = stdout
    +		process.standardError = stderr
    +		try process.run()
     		// Sequential post-exit reads; output is bounded by the document.
     		stdin.fileHandleForWriting.write(Data(markdown.utf8))
     		stdin.fileHandleForWriting.closeFile()
     		let data = stdout.fileHandleForReading.readDataToEndOfFile()
     		guard !data.isEmpty else {
    -			p.waitUntilExit()
    +			process.waitUntilExit()
     			throw NSError(
     				domain: "apex",
    -				code: Int(p.terminationStatus),
    -				userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"]
    +				code: Int(process.terminationStatus),
    +				userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"],
     			)
     		}
     		// stdout EOF = conversion done (~18 ms). The ~65 ms teardown after is
     		// apex's own — reap async, hand the HTML over immediately (#74).
    -		p.terminationHandler = { _ in }
    +		process.terminationHandler = { _ in }
     		return String(decoding: data, as: UTF8.self)
     	}
     
    @@ -165,8 +188,8 @@ nonisolated enum ReadingPresenter {
     		"
    \(escapeHTML(text))
    " } - static func escapeHTML(_ s: String) -> String { - s.replacingOccurrences(of: "&", with: "&") + static func escapeHTML(_ text: String) -> String { + text.replacingOccurrences(of: "&", with: "&") .replacingOccurrences(of: "<", with: "<") .replacingOccurrences(of: ">", with: ">") } @@ -177,10 +200,12 @@ nonisolated enum ReadingPresenter { /// the spike's fixed rules (proven live, #74). `familyName` (not the /// member PS name) is what CSS font matching wants; weight rides CSS. static func styleSheet() -> String { - func family(_ f: NSFont) -> String { - "\"\(f.familyName ?? (f.displayName ?? ""))\"" + func family(_ font: NSFont) -> String { + "\"\(font.familyName ?? (font.displayName ?? ""))\"" + } + func px(_ value: Double) -> String { + "\(String(format: "%.0f", value))px" } - func px(_ v: Double) -> String { "\(String(format: "%.0f", v))px" } let body = ProseTypography.bodyFont let head = ProseTypography.headingFont let code = ProseTypography.codeFont diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index 06077fa..4e458ae 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -73,18 +73,18 @@ struct ReadingSurface: NSViewRepresentable { return wv } - func updateNSView(_ wv: WKWebView, context: Context) { - let c = context.coordinator - c.onEditIntent = onEditIntent - c.stateBox = stateBox - c.postFolder = postFolder + func updateNSView(_: WKWebView, context: Context) { + let coordinator = context.coordinator + coordinator.onEditIntent = onEditIntent + coordinator.stateBox = stateBox + coordinator.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) + 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). + /// 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){ @@ -145,7 +145,7 @@ struct ReadingSurface: NSViewRepresentable { /// 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) { + func load(text: String, generation _: Int, entryCaret: Int?, key: String) { loadedKey = key lastText = text painted = false @@ -174,18 +174,18 @@ struct ReadingSurface: NSViewRepresentable { defaultsObserver = NotificationCenter.default.addObserver( forName: UserDefaults.didChangeNotification, object: nil, - queue: .main + queue: .main, ) { [weak self] _ in Task { @MainActor [weak self] in guard let self else { return } let key = ProseTypography.flowKey guard key != appliedFlowKey else { return } appliedFlowKey = key - self.load( + load( text: lastText, generation: 0, entryCaret: nil, - key: "\(loadedKey)|flow" + key: "\(loadedKey)|flow", ) } } @@ -197,7 +197,7 @@ struct ReadingSurface: NSViewRepresentable { // MARK: WKNavigationDelegate - func webView(_ wv: WKWebView, didFinish nav: WKNavigation!) { + func webView(_ wv: WKWebView, didFinish _: WKNavigation!) { guard !painted else { return } painted = true guard let line = pendingEntryScrollLine else { return } @@ -205,16 +205,17 @@ struct ReadingSurface: NSViewRepresentable { wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line)) } - // 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). + /// 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, + _: WKWebView, decidePolicyFor nav: WKNavigationAction, - decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void + decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void, ) { if nav.targetFrame?.isMainFrame == true, - let u = nav.request.url, u.scheme == "file" || u.absoluteString == "about:blank" { + let url = nav.request.url, url.scheme == "file" || url.absoluteString == "about:blank" + { decisionHandler(.allow) return } @@ -223,12 +224,14 @@ struct ReadingSurface: NSViewRepresentable { // MARK: WKScriptMessageHandler — the source map in action - func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) { + func userContentController(_: 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) } + if let body = message.body as? String, let url = URL(string: body) { + NSWorkspace.shared.open(url) + } case "sourceClick", "sourceScroll": - guard let s = message.body as? String, let line = Int(s), + 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) diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index 5752de1..5969a72 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -23,7 +23,7 @@ Owned by the root AGENTS.md contract. - `PostLibraryTests.swift` (#17) — throwaway Homes via `makeHome`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`), lazy folders / hidden dirs / symlinks / noise not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`. - `PostStoreTests.swift` (#18) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write + #59 stamp round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes, rename (retitle + move, insert-title path, same-slug retitle-only, collision -2), trash removes from posts/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-posts failure path. - `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry. -- `ReadingPresenterTests.swift` (#71) — renderer coverage with inline fixture strings (no file fixtures): headings/paragraph split + markup hidden, auto-renumber (`1. 1. 1.` → 1/2/3), nesting, source-range monotonicity + exact chunk offsets (the click→edit map), table/quote/HR attribute presence (`NSTextTableBlock`/`QuoteTextBlock`/`RuleTextBlock` via paragraphStyle `textBlocks`), fenced-code font, link retention, image payload + post-folder resolution, footnote fallback, soft-joined lines, kitchen-sink smoke. +- `ReadingPresenterTests.swift` (#76, ADR-0011) — apex HTML pipeline coverage with inline fixture strings: chunker sentinel stamping, stamper attribute rewrite (multi-digit), `blocks(for:)` line↔range map (monotonic, 1-based lines, exact chunk offsets — the click→edit map), pipeline tests running the REAL bundled apex binary (headings/inline marks, `1. 1. 1.` renumber via native `
      `, mixed-lists stay split, table/quote/fence/link/HR constructs with exact `data-source-line` stamps, base64 image embed against `spike/prose`, native footnotes), fallback = escaped source, stylesheet carries the slot CSS vars. ## Verification diff --git a/MuseionTests/ReadingPresenterTests.swift b/MuseionTests/ReadingPresenterTests.swift index f11dcef..22b1c5d 100644 --- a/MuseionTests/ReadingPresenterTests.swift +++ b/MuseionTests/ReadingPresenterTests.swift @@ -18,14 +18,14 @@ struct ReadingPresenterTests { /// Chunker: sentinels before chunks, blank structure preserved (spike /// self-check fixture). @Test - func chunkerStampsSentinels() { + func `chunker stamps sentinels`() { let md = "# T\n\nA\n\nB\n1. x\n\n\nC" #expect(ReadingPresenter.stampSource(md) == "\n# T\n\n\nA\n\n\nB\n1. x\n\n\nC") } /// Stamper: sentinel → attribute on the following element; multi-digit. @Test - func stamperRewritesAttributes() { + func `stamper rewrites attributes`() { let html = "

      T

      \n\n

      A

      \n\n
        \n
      • B
      • \n
      " #expect(ReadingPresenter.stampHTML(html) == "

      T

      \n

      A

      \n
        \n
      • B
      • \n
      ") } @@ -33,7 +33,7 @@ struct ReadingPresenterTests { /// The #68 click→edit map: blocks are monotonic, lines are 1-based, and /// ranges point at the exact chunk offsets in the source. @Test - func blocksMapChunks() { + func `blocks map chunks`() { let src = "# A\n\nfirst para\n\n- l1\n- l2\n\nlast para" let blocks = ReadingPresenter.blocks(for: src) #expect(blocks.count == 4) @@ -45,7 +45,7 @@ struct ReadingPresenterTests { /// Blocks over CRLF and multi-blank separators stay monotonic. @Test - func blocksSurviveBlankRuns() { + func `blocks survive blank runs`() { let src = "one\n\n\n\n two" let blocks = ReadingPresenter.blocks(for: src) #expect(blocks.count == 2) @@ -57,7 +57,7 @@ struct ReadingPresenterTests { /// Headings + paragraphs + inline marks render; markup never leaks. @Test - func pipelineHeadingsAndInline() throws { + func `pipeline headings and inline`() throws { let (html, blocks) = ReadingPresenter.page(for: "# Title\n\nBody with _em_ and `code`.", postFolder: nil) try assertRendered(html, blocks: blocks, count: 2) #expect(html.contains("

      (the #69 hard requirement). @Test - func pipelineOrderedRenumber() throws { + func `pipeline ordered renumber`() throws { let src = "1. one\n1. two\n1. three" let (html, blocks) = ReadingPresenter.page(for: src, postFolder: nil) try assertRendered(html, blocks: blocks, count: 1) @@ -82,7 +82,7 @@ struct ReadingPresenterTests { /// `--no-mixed-lists`: an ordered list after a bullet list stays two /// lists (default apex merges them — kills renumbering). @Test - func pipelineMixedListsStaySplit() throws { + func `pipeline mixed lists stay split`() { let src = "- bullet\n- another\n\n1. one\n1. two" let (html, _) = ReadingPresenter.page(for: src, postFolder: nil) #expect(html.contains(" d") #expect(page.contains("
      a < b & c > d
      ")) } /// The stylesheet carries the live slot values as CSS variables. @Test - func stylesheetCarriesSlots() { + func `stylesheet carries slots`() { let css = ReadingPresenter.styleSheet() #expect(css.contains("--body-face:")) #expect(css.contains("--headings-size:")) @@ -167,7 +167,7 @@ struct ReadingPresenterTests { } /// Regex count helper (Swift Testing has no XCTest import here). -private func XCTRegexMatches(_ s: String, pattern: String) throws -> Int { - let re = try NSRegularExpression(pattern: pattern) - return re.numberOfMatches(in: s, range: NSRange(s.startIndex..., in: s)) +private func XCTRegexMatches(_ text: String, pattern: String) throws -> Int { + let regex = try NSRegularExpression(pattern: pattern) + return regex.numberOfMatches(in: text, range: NSRange(text.startIndex..., in: text)) }