chore(reading): lint-clean lift — local renames, tab escape, DOX pass (#76)

Spike-locals renamed at lift time (identifier_name), literal tab in a
string escape fixed (unprintable-ASCII build error), swiftlint
force_try disable for the static regex. AGENTS.md reading-mode section
rewritten for the apex HTML pipeline; native-only Work Guidance line
rescoped to the editing side per ADR-0011.
This commit is contained in:
AlexKucera committed 2026-10-06 18:30:21 +02:00
1 parent cc04ec236e
commit f1c915fed1
5 files changed
+111 -83

No files matched your search

+3 -3
View File
@@ -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/<id>/` 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/<id>/.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 `<!--S:N-->` 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 <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, 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 `<pre>` (#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
+66 -41
View File
@@ -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 `<!--S:N-->` (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("<!--S:\(i + 1)-->")
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("<!--S:\(index + 1)-->")
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 `<!--S:N-->` 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:(\d+)-->\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:(\d+)-->\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 {
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head><body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
}
static func escapeHTML(_ s: String) -> String {
s.replacingOccurrences(of: "&", with: "&amp;")
static func escapeHTML(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;")
.replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;")
}
@@ -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
+26 -23
View File
@@ -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)