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:
1 parent
cc04ec236e
commit
f1c915fed1
5 files changed
+111
-83
No files matched your search
+3
-3
@@ -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.
|
- `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).
|
- 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.
|
- `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 `` 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).
|
- `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.
|
- `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
|
## Work Guidance
|
||||||
|
|
||||||
- Native SwiftUI only — no web-editor embedding, no Electron-style components (ADR-0001).
|
- 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 CodeMirror/ProseMirror-class dependencies.
|
- Text editing gets built on TextKit 2 / SwiftUI directly; no CodeEdit/CodeMirror/ProseMirror-class editing dependencies.
|
||||||
|
|
||||||
## Verification
|
## Verification
|
||||||
|
|
||||||
|
|||||||
@@ -48,18 +48,28 @@ nonisolated enum ReadingPresenter {
|
|||||||
out.append(Block(sourceLine: line, sourceRange: NSRange(location: loc, length: end - loc)))
|
out.append(Block(sourceLine: line, sourceRange: NSRange(location: loc, length: end - loc)))
|
||||||
}
|
}
|
||||||
// advance line count over the chunk + the blank separator run
|
// advance line count over the chunk + the blank separator run
|
||||||
var i = loc
|
var index = loc
|
||||||
while i < end {
|
while index < end {
|
||||||
if ns.character(at: i) == 0x0A { line += 1 }
|
if ns.character(at: index) == 0x0A {
|
||||||
i += 1
|
line += 1
|
||||||
|
}
|
||||||
|
index += 1
|
||||||
}
|
}
|
||||||
if delim.location == NSNotFound { break }
|
if delim.location == NSNotFound {
|
||||||
var j = delim.location
|
break
|
||||||
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 }
|
|
||||||
}
|
}
|
||||||
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
|
return out
|
||||||
}
|
}
|
||||||
@@ -67,15 +77,21 @@ nonisolated enum ReadingPresenter {
|
|||||||
/// Prepend `<!--S:N-->` (N = 1-based source line) before every blank-line
|
/// Prepend `<!--S:N-->` (N = 1-based source line) before every blank-line
|
||||||
/// chunk — apex passes HTML comments through verbatim (#74).
|
/// chunk — apex passes HTML comments through verbatim (#74).
|
||||||
static func stampSource(_ source: String) -> String {
|
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)
|
let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
|
||||||
var out: [String] = []
|
var out: [String] = []
|
||||||
var i = 0
|
var index = 0
|
||||||
while i < lines.count {
|
while index < lines.count {
|
||||||
if isBlank(lines[i]) { i += 1; continue }
|
if isBlank(lines[index]) {
|
||||||
if !out.isEmpty { out.append("") }
|
index += 1; continue
|
||||||
out.append("<!--S:\(i + 1)-->")
|
}
|
||||||
while i < lines.count && !isBlank(lines[i]) { out.append(String(lines[i])); i += 1 }
|
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")
|
return out.joined(separator: "\n")
|
||||||
}
|
}
|
||||||
@@ -83,10 +99,13 @@ nonisolated enum ReadingPresenter {
|
|||||||
/// Rewrite `<!--S:N-->` into `data-source-line="N"` on the element that
|
/// Rewrite `<!--S:N-->` into `data-source-line="N"` on the element that
|
||||||
/// follows (spike regex, 0 mis-stamps corpus-wide, #74).
|
/// follows (spike regex, 0 mis-stamps corpus-wide, #74).
|
||||||
static func stampHTML(_ html: String) -> String {
|
static func stampHTML(_ html: String) -> String {
|
||||||
let re = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
|
// Static literal pattern — compiles by construction; a failure would
|
||||||
let ms = NSMutableString(string: html)
|
// crash at first render and every test with it.
|
||||||
re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"")
|
// swiftlint:disable:next force_try
|
||||||
return ms as String
|
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)
|
// MARK: Apex runner (bundled binary, ADR-0011)
|
||||||
@@ -97,9 +116,11 @@ nonisolated enum ReadingPresenter {
|
|||||||
if let bundlePath = Bundle.main.path(forResource: "apex", ofType: nil) {
|
if let bundlePath = Bundle.main.path(forResource: "apex", ofType: nil) {
|
||||||
return bundlePath
|
return bundlePath
|
||||||
}
|
}
|
||||||
if let env = ProcessInfo.processInfo.environment["APEX_PATH"] { return env }
|
if let env = ProcessInfo.processInfo.environment["APEX_PATH"] {
|
||||||
for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) {
|
return env
|
||||||
return p
|
}
|
||||||
|
for path in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: path) {
|
||||||
|
return path
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -113,31 +134,33 @@ nonisolated enum ReadingPresenter {
|
|||||||
guard let bin = apexBinaryPath() else {
|
guard let bin = apexBinaryPath() else {
|
||||||
throw CocoaError(.fileNoSuchFile)
|
throw CocoaError(.fileNoSuchFile)
|
||||||
}
|
}
|
||||||
let p = Process()
|
let process = Process()
|
||||||
p.executableURL = URL(fileURLWithPath: bin)
|
process.executableURL = URL(fileURLWithPath: bin)
|
||||||
var args = ["-t", "html", "--no-mixed-lists", "--embed-images"]
|
var args = ["-t", "html", "--no-mixed-lists", "--embed-images"]
|
||||||
if let baseDir { args += ["--base-dir", baseDir.path] }
|
if let baseDir {
|
||||||
p.arguments = args
|
args += ["--base-dir", baseDir.path]
|
||||||
|
}
|
||||||
|
process.arguments = args
|
||||||
let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
|
let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
|
||||||
p.standardInput = stdin
|
process.standardInput = stdin
|
||||||
p.standardOutput = stdout
|
process.standardOutput = stdout
|
||||||
p.standardError = stderr
|
process.standardError = stderr
|
||||||
try p.run()
|
try process.run()
|
||||||
// Sequential post-exit reads; output is bounded by the document.
|
// Sequential post-exit reads; output is bounded by the document.
|
||||||
stdin.fileHandleForWriting.write(Data(markdown.utf8))
|
stdin.fileHandleForWriting.write(Data(markdown.utf8))
|
||||||
stdin.fileHandleForWriting.closeFile()
|
stdin.fileHandleForWriting.closeFile()
|
||||||
let data = stdout.fileHandleForReading.readDataToEndOfFile()
|
let data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||||
guard !data.isEmpty else {
|
guard !data.isEmpty else {
|
||||||
p.waitUntilExit()
|
process.waitUntilExit()
|
||||||
throw NSError(
|
throw NSError(
|
||||||
domain: "apex",
|
domain: "apex",
|
||||||
code: Int(p.terminationStatus),
|
code: Int(process.terminationStatus),
|
||||||
userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"]
|
userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"],
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
// stdout EOF = conversion done (~18 ms). The ~65 ms teardown after is
|
// stdout EOF = conversion done (~18 ms). The ~65 ms teardown after is
|
||||||
// apex's own — reap async, hand the HTML over immediately (#74).
|
// apex's own — reap async, hand the HTML over immediately (#74).
|
||||||
p.terminationHandler = { _ in }
|
process.terminationHandler = { _ in }
|
||||||
return String(decoding: data, as: UTF8.self)
|
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>"
|
"<!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 {
|
static func escapeHTML(_ text: String) -> String {
|
||||||
s.replacingOccurrences(of: "&", with: "&")
|
text.replacingOccurrences(of: "&", with: "&")
|
||||||
.replacingOccurrences(of: "<", with: "<")
|
.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
|
/// the spike's fixed rules (proven live, #74). `familyName` (not the
|
||||||
/// member PS name) is what CSS font matching wants; weight rides CSS.
|
/// member PS name) is what CSS font matching wants; weight rides CSS.
|
||||||
static func styleSheet() -> String {
|
static func styleSheet() -> String {
|
||||||
func family(_ f: NSFont) -> String {
|
func family(_ font: NSFont) -> String {
|
||||||
"\"\(f.familyName ?? (f.displayName ?? ""))\""
|
"\"\(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 body = ProseTypography.bodyFont
|
||||||
let head = ProseTypography.headingFont
|
let head = ProseTypography.headingFont
|
||||||
let code = ProseTypography.codeFont
|
let code = ProseTypography.codeFont
|
||||||
|
|||||||
@@ -73,18 +73,18 @@ struct ReadingSurface: NSViewRepresentable {
|
|||||||
return wv
|
return wv
|
||||||
}
|
}
|
||||||
|
|
||||||
func updateNSView(_ wv: WKWebView, context: Context) {
|
func updateNSView(_: WKWebView, context: Context) {
|
||||||
let c = context.coordinator
|
let coordinator = context.coordinator
|
||||||
c.onEditIntent = onEditIntent
|
coordinator.onEditIntent = onEditIntent
|
||||||
c.stateBox = stateBox
|
coordinator.stateBox = stateBox
|
||||||
c.postFolder = postFolder
|
coordinator.postFolder = postFolder
|
||||||
let key = "\(generation):\(text.hashValue):\(ProseTypography.flowKey)"
|
let key = "\(generation):\(text.hashValue):\(ProseTypography.flowKey)"
|
||||||
guard c.loadedKey != key else { return }
|
guard coordinator.loadedKey != key else { return }
|
||||||
c.load(text: text, generation: generation, entryCaret: entryCaretLocation, key: key)
|
coordinator.load(text: text, generation: generation, entryCaret: entryCaretLocation, key: key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mapping probes: click → source line; ⌘-click → open; scroll → top
|
/// Mapping probes: click → source line; ⌘-click → open; scroll → top
|
||||||
// visible source line (same map → scroll-sync). Spike-verified (#74).
|
/// visible source line (same map → scroll-sync). Spike-verified (#74).
|
||||||
static let probeJS = """
|
static let probeJS = """
|
||||||
function stamped(el){ return el.closest('[data-source-line]'); }
|
function stamped(el){ return el.closest('[data-source-line]'); }
|
||||||
document.addEventListener('click', function(e){
|
document.addEventListener('click', function(e){
|
||||||
@@ -145,7 +145,7 @@ struct ReadingSurface: NSViewRepresentable {
|
|||||||
|
|
||||||
/// Build + load the page for `text`. All render paths land here
|
/// Build + load the page for `text`. All render paths land here
|
||||||
/// (updateNSView, typography-change reload).
|
/// (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
|
loadedKey = key
|
||||||
lastText = text
|
lastText = text
|
||||||
painted = false
|
painted = false
|
||||||
@@ -174,18 +174,18 @@ struct ReadingSurface: NSViewRepresentable {
|
|||||||
defaultsObserver = NotificationCenter.default.addObserver(
|
defaultsObserver = NotificationCenter.default.addObserver(
|
||||||
forName: UserDefaults.didChangeNotification,
|
forName: UserDefaults.didChangeNotification,
|
||||||
object: nil,
|
object: nil,
|
||||||
queue: .main
|
queue: .main,
|
||||||
) { [weak self] _ in
|
) { [weak self] _ in
|
||||||
Task { @MainActor [weak self] in
|
Task { @MainActor [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
let key = ProseTypography.flowKey
|
let key = ProseTypography.flowKey
|
||||||
guard key != appliedFlowKey else { return }
|
guard key != appliedFlowKey else { return }
|
||||||
appliedFlowKey = key
|
appliedFlowKey = key
|
||||||
self.load(
|
load(
|
||||||
text: lastText,
|
text: lastText,
|
||||||
generation: 0,
|
generation: 0,
|
||||||
entryCaret: nil,
|
entryCaret: nil,
|
||||||
key: "\(loadedKey)|flow"
|
key: "\(loadedKey)|flow",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -197,7 +197,7 @@ struct ReadingSurface: NSViewRepresentable {
|
|||||||
|
|
||||||
// MARK: WKNavigationDelegate
|
// MARK: WKNavigationDelegate
|
||||||
|
|
||||||
func webView(_ wv: WKWebView, didFinish nav: WKNavigation!) {
|
func webView(_ wv: WKWebView, didFinish _: WKNavigation!) {
|
||||||
guard !painted else { return }
|
guard !painted else { return }
|
||||||
painted = true
|
painted = true
|
||||||
guard let line = pendingEntryScrollLine else { return }
|
guard let line = pendingEntryScrollLine else { return }
|
||||||
@@ -205,16 +205,17 @@ struct ReadingSurface: NSViewRepresentable {
|
|||||||
wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line))
|
wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Allow our own loadHTMLString main-frame load (about:blank); a
|
/// Allow our own loadHTMLString main-frame load (about:blank); a
|
||||||
// blanket .cancel would kill the page before it paints. Everything
|
/// blanket .cancel would kill the page before it paints. Everything
|
||||||
// else is cancelled — reading never navigates in-app (#74 lesson).
|
/// else is cancelled — reading never navigates in-app (#74 lesson).
|
||||||
func webView(
|
func webView(
|
||||||
_ wv: WKWebView,
|
_: WKWebView,
|
||||||
decidePolicyFor nav: WKNavigationAction,
|
decidePolicyFor nav: WKNavigationAction,
|
||||||
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void
|
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void,
|
||||||
) {
|
) {
|
||||||
if nav.targetFrame?.isMainFrame == true,
|
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)
|
decisionHandler(.allow)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -223,12 +224,14 @@ struct ReadingSurface: NSViewRepresentable {
|
|||||||
|
|
||||||
// MARK: WKScriptMessageHandler — the source map in action
|
// MARK: WKScriptMessageHandler — the source map in action
|
||||||
|
|
||||||
func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
|
func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
|
||||||
switch message.name {
|
switch message.name {
|
||||||
case "openLink":
|
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":
|
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 }
|
let block = blocks.first(where: { $0.sourceLine == line }) else { return }
|
||||||
if message.name == "sourceClick" {
|
if message.name == "sourceClick" {
|
||||||
onEditIntent?(block.sourceRange.location)
|
onEditIntent?(block.sourceRange.location)
|
||||||
|
|||||||
@@ -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`.
|
- `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.
|
- `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.
|
- `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 `<ol>`, 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
|
## Verification
|
||||||
|
|
||||||
|
|||||||
@@ -18,14 +18,14 @@ struct ReadingPresenterTests {
|
|||||||
/// Chunker: sentinels before chunks, blank structure preserved (spike
|
/// Chunker: sentinels before chunks, blank structure preserved (spike
|
||||||
/// self-check fixture).
|
/// self-check fixture).
|
||||||
@Test
|
@Test
|
||||||
func chunkerStampsSentinels() {
|
func `chunker stamps sentinels`() {
|
||||||
let md = "# T\n\nA\n\nB\n1. x\n\n\nC"
|
let md = "# T\n\nA\n\nB\n1. x\n\n\nC"
|
||||||
#expect(ReadingPresenter.stampSource(md) == "<!--S:1-->\n# T\n\n<!--S:3-->\nA\n\n<!--S:5-->\nB\n1. x\n\n<!--S:9-->\nC")
|
#expect(ReadingPresenter.stampSource(md) == "<!--S:1-->\n# T\n\n<!--S:3-->\nA\n\n<!--S:5-->\nB\n1. x\n\n<!--S:9-->\nC")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Stamper: sentinel → attribute on the following element; multi-digit.
|
/// Stamper: sentinel → attribute on the following element; multi-digit.
|
||||||
@Test
|
@Test
|
||||||
func stamperRewritesAttributes() {
|
func `stamper rewrites attributes`() {
|
||||||
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
|
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
|
||||||
#expect(ReadingPresenter.stampHTML(html) == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>")
|
#expect(ReadingPresenter.stampHTML(html) == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>")
|
||||||
}
|
}
|
||||||
@@ -33,7 +33,7 @@ struct ReadingPresenterTests {
|
|||||||
/// The #68 click→edit map: blocks are monotonic, lines are 1-based, and
|
/// The #68 click→edit map: blocks are monotonic, lines are 1-based, and
|
||||||
/// ranges point at the exact chunk offsets in the source.
|
/// ranges point at the exact chunk offsets in the source.
|
||||||
@Test
|
@Test
|
||||||
func blocksMapChunks() {
|
func `blocks map chunks`() {
|
||||||
let src = "# A\n\nfirst para\n\n- l1\n- l2\n\nlast para"
|
let src = "# A\n\nfirst para\n\n- l1\n- l2\n\nlast para"
|
||||||
let blocks = ReadingPresenter.blocks(for: src)
|
let blocks = ReadingPresenter.blocks(for: src)
|
||||||
#expect(blocks.count == 4)
|
#expect(blocks.count == 4)
|
||||||
@@ -45,7 +45,7 @@ struct ReadingPresenterTests {
|
|||||||
|
|
||||||
/// Blocks over CRLF and multi-blank separators stay monotonic.
|
/// Blocks over CRLF and multi-blank separators stay monotonic.
|
||||||
@Test
|
@Test
|
||||||
func blocksSurviveBlankRuns() {
|
func `blocks survive blank runs`() {
|
||||||
let src = "one\n\n\n\n two"
|
let src = "one\n\n\n\n two"
|
||||||
let blocks = ReadingPresenter.blocks(for: src)
|
let blocks = ReadingPresenter.blocks(for: src)
|
||||||
#expect(blocks.count == 2)
|
#expect(blocks.count == 2)
|
||||||
@@ -57,7 +57,7 @@ struct ReadingPresenterTests {
|
|||||||
|
|
||||||
/// Headings + paragraphs + inline marks render; markup never leaks.
|
/// Headings + paragraphs + inline marks render; markup never leaks.
|
||||||
@Test
|
@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)
|
let (html, blocks) = ReadingPresenter.page(for: "# Title\n\nBody with _em_ and `code`.", postFolder: nil)
|
||||||
try assertRendered(html, blocks: blocks, count: 2)
|
try assertRendered(html, blocks: blocks, count: 2)
|
||||||
#expect(html.contains("<h1 data-source-line=\"1\""))
|
#expect(html.contains("<h1 data-source-line=\"1\""))
|
||||||
@@ -68,7 +68,7 @@ struct ReadingPresenterTests {
|
|||||||
|
|
||||||
/// `1. 1. 1.` renumbers via native <ol> (the #69 hard requirement).
|
/// `1. 1. 1.` renumbers via native <ol> (the #69 hard requirement).
|
||||||
@Test
|
@Test
|
||||||
func pipelineOrderedRenumber() throws {
|
func `pipeline ordered renumber`() throws {
|
||||||
let src = "1. one\n1. two\n1. three"
|
let src = "1. one\n1. two\n1. three"
|
||||||
let (html, blocks) = ReadingPresenter.page(for: src, postFolder: nil)
|
let (html, blocks) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||||
try assertRendered(html, blocks: blocks, count: 1)
|
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
|
/// `--no-mixed-lists`: an ordered list after a bullet list stays two
|
||||||
/// lists (default apex merges them — kills renumbering).
|
/// lists (default apex merges them — kills renumbering).
|
||||||
@Test
|
@Test
|
||||||
func pipelineMixedListsStaySplit() throws {
|
func `pipeline mixed lists stay split`() {
|
||||||
let src = "- bullet\n- another\n\n1. one\n1. two"
|
let src = "- bullet\n- another\n\n1. one\n1. two"
|
||||||
let (html, _) = ReadingPresenter.page(for: src, postFolder: nil)
|
let (html, _) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||||
#expect(html.contains("<ul"))
|
#expect(html.contains("<ul"))
|
||||||
@@ -92,7 +92,7 @@ struct ReadingPresenterTests {
|
|||||||
|
|
||||||
/// Tables, quotes, fenced code, HR, links — the #69 set on one page.
|
/// Tables, quotes, fenced code, HR, links — the #69 set on one page.
|
||||||
@Test
|
@Test
|
||||||
func pipelineConstructs() throws {
|
func `pipeline constructs`() throws {
|
||||||
let src = """
|
let src = """
|
||||||
| A | B |
|
| A | B |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -121,7 +121,7 @@ struct ReadingPresenterTests {
|
|||||||
|
|
||||||
/// Images embed as base64 data URLs against the post folder (#69/#74).
|
/// Images embed as base64 data URLs against the post folder (#69/#74).
|
||||||
@Test
|
@Test
|
||||||
func pipelineImageEmbeds() throws {
|
func `pipeline image embeds`() throws {
|
||||||
let prose = URL(fileURLWithPath: #filePath) // …/MuseionTests/ReadingPresenterTests.swift
|
let prose = URL(fileURLWithPath: #filePath) // …/MuseionTests/ReadingPresenterTests.swift
|
||||||
.deletingLastPathComponent().deletingLastPathComponent()
|
.deletingLastPathComponent().deletingLastPathComponent()
|
||||||
.appendingPathComponent("spike/prose")
|
.appendingPathComponent("spike/prose")
|
||||||
@@ -133,7 +133,7 @@ struct ReadingPresenterTests {
|
|||||||
|
|
||||||
/// Footnotes render natively (apex upgrade over #69's fallback).
|
/// Footnotes render natively (apex upgrade over #69's fallback).
|
||||||
@Test
|
@Test
|
||||||
func pipelineFootnotes() throws {
|
func `pipeline footnotes`() {
|
||||||
let src = "Text with note[^1]\n\n[^1]: the note"
|
let src = "Text with note[^1]\n\n[^1]: the note"
|
||||||
let (html, _) = ReadingPresenter.page(for: src, postFolder: nil)
|
let (html, _) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||||
#expect(html.contains("footnote"))
|
#expect(html.contains("footnote"))
|
||||||
@@ -142,14 +142,14 @@ struct ReadingPresenterTests {
|
|||||||
|
|
||||||
/// Fallback: apex failure → editing-treated source (#69 rule), escaped.
|
/// Fallback: apex failure → editing-treated source (#69 rule), escaped.
|
||||||
@Test
|
@Test
|
||||||
func fallbackIsSourceText() {
|
func `fallback is source text`() {
|
||||||
let page = ReadingPresenter.fallbackPage("a < b & c > d")
|
let page = ReadingPresenter.fallbackPage("a < b & c > d")
|
||||||
#expect(page.contains("<pre data-source-line=\"1\">a < b & c > d</pre>"))
|
#expect(page.contains("<pre data-source-line=\"1\">a < b & c > d</pre>"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The stylesheet carries the live slot values as CSS variables.
|
/// The stylesheet carries the live slot values as CSS variables.
|
||||||
@Test
|
@Test
|
||||||
func stylesheetCarriesSlots() {
|
func `stylesheet carries slots`() {
|
||||||
let css = ReadingPresenter.styleSheet()
|
let css = ReadingPresenter.styleSheet()
|
||||||
#expect(css.contains("--body-face:"))
|
#expect(css.contains("--body-face:"))
|
||||||
#expect(css.contains("--headings-size:"))
|
#expect(css.contains("--headings-size:"))
|
||||||
@@ -167,7 +167,7 @@ struct ReadingPresenterTests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Regex count helper (Swift Testing has no XCTest import here).
|
/// Regex count helper (Swift Testing has no XCTest import here).
|
||||||
private func XCTRegexMatches(_ s: String, pattern: String) throws -> Int {
|
private func XCTRegexMatches(_ text: String, pattern: String) throws -> Int {
|
||||||
let re = try NSRegularExpression(pattern: pattern)
|
let regex = try NSRegularExpression(pattern: pattern)
|
||||||
return re.numberOfMatches(in: s, range: NSRange(s.startIndex..., in: s))
|
return regex.numberOfMatches(in: text, range: NSRange(text.startIndex..., in: text))
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user