Merge branch 'wayfinder/76-apex-html-reading'
CI / ci (push) Canceled after 0s
CI / ci (push) Canceled after 0s
This commit is contained in:
26 files changed
+1322
-1355
No files matched your search
@@ -0,0 +1,17 @@
|
||||
---
|
||||
target_identity: "file:/Users/alex/Projects/macOS/Museion/Museion/ReadingPresenter.swift"
|
||||
target_fingerprint: "sha256:069b29ece5302317088ed61e11f7287fc4186844c66d0282a519cd37c346455a"
|
||||
target_path: /Users/alex/Projects/macOS/Museion/Museion/ReadingPresenter.swift
|
||||
timestamp: 2026-10-07T10-36-09Z
|
||||
slug: museion-readingpresenter-swift
|
||||
closed: true
|
||||
---
|
||||
Calibration ruling (Alexander, live in-app over the landed #76 build, display free): **pipeline calm, surface not-calm.**
|
||||
|
||||
- The Apex/HTML+CSS workflow "works very well" — the pivot chain (#73 → #74 → #75 → #76) is judged settled. No renderer gaps named.
|
||||
- What breaks the calm: **typography values, spacing, and how constructs like tables and quotes are styled.**
|
||||
- Directed path: since the reading surface is an HTML page, run the impeccable skill on it — critique first, then the polish pass with the same skill.
|
||||
- Graduating from fog: polish iteration ticket(s), spec'd from the critique findings (created next).
|
||||
- Map stays open; the next calibration round re-rules after the polish lands.
|
||||
|
||||
[Generated by AI]
|
||||
@@ -0,0 +1,53 @@
|
||||
---
|
||||
target: the polished reading surface, re-run
|
||||
total_score: 16
|
||||
max_score: 32
|
||||
na_heuristics: 7,10
|
||||
p0_count: 1
|
||||
p1_count: 3
|
||||
target_identity: "file:/Users/alex/Projects/macOS/Museion/Museion/ReadingPresenter.swift"
|
||||
target_fingerprint: "sha256:84b15df221daec8053edb7f9328d46f34165de334e7e843778372641d5b76c26"
|
||||
target_path: /Users/alex/Projects/macOS/Museion/Museion/ReadingPresenter.swift
|
||||
timestamp: 2026-10-07T15-20-25Z
|
||||
slug: museion-readingpresenter-swift
|
||||
---
|
||||
### Critique #2 — Museion reading surface (post-polish, user-dialed spacing)
|
||||
|
||||
Method: dual-agent (A: design review sa-0-444abc9b · B: detector+CSS audit sa-0-61d0567a)
|
||||
|
||||
| # | Heuristic | Score | Key Issue |
|
||||
|---|-----------|-------|-----------|
|
||||
| 1 | Visibility of System Status | 2 | No reading-position signal; hover block-highlight is the only "you are here" |
|
||||
| 2 | Match System / Real World | 3 | Machine front-matter (pass_state:) leaks into reading as an H2 before the H1 |
|
||||
| 3 | User Control and Freedom | 2 | Hover image expansion can't be pinned, focused, or dismissed on intent |
|
||||
| 4 | Consistency and Standards | 2 | Inline ~15px vs block 14px code; h4-h6 identical; table alignment silently discarded |
|
||||
| 5 | Error Prevention | 1 | Plain click on a link drops into edit mode - reversed convention, no cue |
|
||||
| 6 | Recognition Rather Than Recall | 2 | Image affordance is a 1.6em sliver, no frame/cursor/hint |
|
||||
| 7 | Flexibility and Efficiency | n/a | Reading surface; app-level shortcuts exist |
|
||||
| 8 | Aesthetic and Minimalist Design | 3 | Genuinely calm; docked for stretched gaps and near-invisible rules (user-ruled values) |
|
||||
| 9 | Error Recovery | 1 | No failure state designed - renderer failure is a blank page |
|
||||
| 10 | Help and Documentation | n/a | Static prose surface |
|
||||
| **Total** | | **16/32** | **Acceptable** |
|
||||
|
||||
#### Design Specificity Verdict
|
||||
LLM: "A literate category-default, not yet an authored surface." Restraint and taste are real (Butterick faces, two-weight rule system, smart typography verified in render) but nothing on the page is Museion-specific; the scholar-critical constructs are exactly the unstyled/unverified ones (no title block, front-matter leaks, footnote styling untested - corpus contains zero footnote constructs).
|
||||
Detector: clean. 1 advisory (em-dash overuse) firing on authored prose content - false positive for a reading renderer. CSS audit: 17/17 vars defined and used, braces balanced, no dead tokens. ReadingPresenter.swift clean.
|
||||
|
||||
#### Priority Issues
|
||||
- **[P0] Hover-expand image is a defect**: renders as invisible 1.6em sliver, hover-only (no keyboard path), expands in-flow reflowing the paragraph, figcaption display:none discards alt text. Fix: resting thumbnail with hairline frame + cursor:zoom-in, click/Enter to open pinned overlay, show caption. ($impeccable polish)
|
||||
- **[P1] Measure runs wide**: 66ch of a narrow-zero serif lands ~75-85 avg chars. Fix: ~58-60ch or 36-38em, verify against real Valkyrie metrics in-app. ($impeccable typeset)
|
||||
- **[P1] Table alignment silently discarded**: CSS text-align:left overrides apex's align="center" presentation attributes (4 in kitchen-sink). Fix: drop the declaration or add th[align]/td[align] handling. ($impeccable polish)
|
||||
- **[P1] Link/edit inversion has no visual contract**: ink-colored links, faint underline, plain click = edit mode. Fix: flip default (click opens, intent edits) or distinct resting treatment + first-use hover cue. (product decision, then $impeccable polish)
|
||||
- **[P2] No title block; front matter leaks**: byline renders as bare paragraph; handoff doc opens hr + pass_state: as H2 before H1; h1:h2 ratio 1.35 under-dominates. Fix: designed deck (muted metadata line, stronger h1), suppress body>hr:first-child, decide where front-matter fields render. ($impeccable polish)
|
||||
|
||||
#### Persona Red Flags
|
||||
Alex (power user): plain-click-into-edit betrays muscle memory on every link; hover-reflow interrupts reading mid-line; no keyboard path to zoom images.
|
||||
Sam (a11y): figcaption display:none removes the accessible name path for figures; hover-only image affordance unreachable by keyboard; contrast fine; :focus-visible present.
|
||||
|
||||
#### Minor Observations
|
||||
No prefers-color-scheme (dark variant ~10 lines, all tokens exist). Code undersized (14px block / 0.88em inline vs 17px body). hr asymmetric (67.5px above / 17px below). Default browser list markers. No text-wrap:pretty / hanging-punctuation. Footnote selectors unverified against apex output.
|
||||
|
||||
#### Questions to Consider
|
||||
1. If the page is interchangeable with a good web theme, is the reading surface a product or just a viewport?
|
||||
2. Is the reading temple one you keep leaving by accident - should edit-entry require visible intent?
|
||||
3. Which single element (footnote craft, small-caps running heads, drop caps) would make this unmistakably Alexander's?
|
||||
@@ -178,6 +178,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-10-06 | [20261006-issue76-apex-html-reading_log.md](docs/devlog/20261006-issue76-apex-html-reading_log.md) |
|
||||
| 2026-10-05 | [20261005-issue71-reading-toggle_log.md](docs/devlog/20261005-issue71-reading-toggle_log.md) |
|
||||
| 2026-10-03 | [20261003-issue19-editor-core_log.md](docs/devlog/20261003-issue19-editor-core_log.md) |
|
||||
| 2026-10-03 | [20261003-issue18-post-lifecycle_log.md](docs/devlog/20261003-issue18-post-lifecycle_log.md) |
|
||||
|
||||
+7
-6
@@ -16,6 +16,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- App Sandbox is OFF (ADR-0009) — the engine gate spawns the user-installed `hermes` binary and provisioning writes outside any container; hardened runtime stays ON for Developer ID notarization. No `.entitlements` file.
|
||||
- No persistence layer yet — the SwiftData template was stripped; vault-vs-database gets an ADR when the need is real. Exception: the engine gate's `state.json` (see below).
|
||||
- Tabs for indentation; SwiftFormat + SwiftLint must both stay clean.
|
||||
- App icon: `Assets.xcassets/AppIcon.appiconset` — single-size 1024×1024 PNG (`Museion-Logo_1024.png`); Xcode derives all sizes. The built icns tops out at 256 px entries — that matches Apple's own apps on this macOS; larger sizes come from the catalog.
|
||||
|
||||
## Workspace shell (M1, #17 + #18 / S1.1)
|
||||
|
||||
@@ -25,10 +26,10 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
|
||||
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin) + `Post.scan(home:) -> [Post]`: reads `posts/<id>/post.md`, skips dirs without post.md (lazy folders), loose files, hidden dirs (dot-prefix), and symlinked dirs; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
|
||||
- `PostStore.swift` — #18 write side (nonisolated): the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug` collision suffixes `-2`/`-3`…, `writeNew` (lazy folder + #59 stamp `pass_state: First Draft` / `origin: writer` — the only values #18 writes), `overwrite` (preserves existing pass_state/origin, normalizes bare posts on save), `rename` = retitle + move (rewrites/inserts `# Title` as first non-empty body line, moves the folder, file stays `post.md`; a title slugging to the current id only retitles), `trash` (`FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing).
|
||||
- `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 `` 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.
|
||||
- `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).
|
||||
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `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. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
|
||||
- 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()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. 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`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). 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).
|
||||
- `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
|
||||
|
||||
## Engine gate (launch gate, tickets #35–#41)
|
||||
@@ -63,8 +64,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
|
||||
|
||||
|
||||
@@ -36,16 +36,19 @@
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"filename" : "Museion-Logo_512 1.png",
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "256x256"
|
||||
},
|
||||
{
|
||||
"filename" : "Museion-Logo_512.png",
|
||||
"idiom" : "mac",
|
||||
"scale" : "1x",
|
||||
"size" : "512x512"
|
||||
},
|
||||
{
|
||||
"filename" : "Museion-Logo_1024.png",
|
||||
"idiom" : "mac",
|
||||
"scale" : "2x",
|
||||
"size" : "512x512"
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 424 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 154 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 154 KiB |
@@ -40,7 +40,6 @@ final class AppGateState {
|
||||
.flatMap { $0.isFileURL ? $0 : nil }
|
||||
?? Self.defaultMuseionHome
|
||||
// #70: the six prose-typography slot defaults.
|
||||
ProseTypography.registerDefaults()
|
||||
}
|
||||
|
||||
/// The default Home, absent a stored override — `~/Documents/Museion`
|
||||
|
||||
@@ -61,7 +61,12 @@ struct PostEditorView: View {
|
||||
stateBox: readingState,
|
||||
)
|
||||
} else {
|
||||
// #77: editor measure — reading.css --measure 66ch. The scroll
|
||||
// view fills the column; the text container centers at the
|
||||
// measured width so wide columns match the reading surface.
|
||||
editingSurface
|
||||
.frame(maxWidth: ProseTypography.measureWidth)
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
@@ -288,6 +293,9 @@ struct ProseTextView: NSViewRepresentable {
|
||||
scroll.documentView = tv
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.autohidesScrollers = true
|
||||
// #77: overlay style — the knob appears during scrolling and fades
|
||||
// out at rest (iOS-like), instead of always occupying the right edge.
|
||||
scroll.scrollerStyle = .overlay
|
||||
scroll.drawsBackground = true
|
||||
scroll.backgroundColor = NSColor.white
|
||||
context.coordinator.textView = tv
|
||||
@@ -297,18 +305,12 @@ struct ProseTextView: NSViewRepresentable {
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let tv = scroll.documentView as? NSTextView else { return }
|
||||
// Typography/flow knob changes arrive via the coordinator's
|
||||
// UserDefaults observer (SwiftUI doesn't invalidate on defaults
|
||||
// writes from another pane).
|
||||
context.coordinator.watchDefaults(tv)
|
||||
context.coordinator.appliedFlowKey = ProseTypography.flowKey
|
||||
if let session {
|
||||
context.coordinator.sessionRef = session
|
||||
// Load only when the generation moved (open, Yes-reload) — never
|
||||
// per keystroke: the text view owns the live text.
|
||||
if context.coordinator.loadedGeneration != session.loadGeneration {
|
||||
context.coordinator.loadedGeneration = session.loadGeneration
|
||||
context.coordinator.appliedFlowKey = ProseTypography.flowKey
|
||||
// Seed from session.text (LIVE), not session.loadText (the
|
||||
// open-time snapshot): the representable is recreated on the
|
||||
// reading⇄editing swap, and seeding from the snapshot showed
|
||||
@@ -321,8 +323,13 @@ struct ProseTextView: NSViewRepresentable {
|
||||
cursor.selectionLocation = min(max(0, cursor.selectionLocation), length)
|
||||
cursor.selectionLength = min(max(0, cursor.selectionLength), length - cursor.selectionLocation)
|
||||
tv.setSelectedRange(NSRange(location: cursor.selectionLocation, length: cursor.selectionLength))
|
||||
tv.scroll(NSPoint(x: 0, y: max(0, cursor.scrollOffset)))
|
||||
tv.window?.makeFirstResponder(tv)
|
||||
// ponytail: TextKit lays out async — a sync scroll on a fresh mount
|
||||
// lands short of the target (clamps to what's laid out). One runloop
|
||||
// hop lets layout finish; verified against a 3000-para doc offscreen.
|
||||
DispatchQueue.main.async { [weak tv] in
|
||||
tv?.scroll(NSPoint(x: 0, y: max(0, cursor.scrollOffset)))
|
||||
tv?.window?.makeFirstResponder(tv)
|
||||
}
|
||||
session.cursorUpdate(cursor)
|
||||
}
|
||||
} else if let draft, tv.string != draft {
|
||||
@@ -336,8 +343,14 @@ struct ProseTextView: NSViewRepresentable {
|
||||
let length = (tv.string as NSString).length
|
||||
let loc = min(max(0, hint.location), length)
|
||||
tv.setSelectedRange(NSRange(location: loc, length: 0))
|
||||
tv.scrollRangeToVisible(NSRange(location: loc, length: 0))
|
||||
tv.window?.makeFirstResponder(tv)
|
||||
// ponytail: same layout race as the cursor-restore scroll above —
|
||||
// this was the click-to-edit "always lands at top" defect: the sync
|
||||
// scrollRangeToVisible fired before the target region was laid out.
|
||||
// One runloop hop fixes it (offscreen-verified, 3000-para doc).
|
||||
DispatchQueue.main.async { [weak tv] in
|
||||
tv?.scrollRangeToVisible(NSRange(location: loc, length: 0))
|
||||
tv?.window?.makeFirstResponder(tv)
|
||||
}
|
||||
if let session {
|
||||
session.cursorUpdate(ProseTextView.cursorState(of: tv))
|
||||
}
|
||||
@@ -354,30 +367,6 @@ struct ProseTextView: NSViewRepresentable {
|
||||
var sessionRef: EditorSession?
|
||||
var loadedGeneration = -1
|
||||
var appliedCaretToken = -1
|
||||
var appliedFlowKey = ""
|
||||
private var defaultsObserver: NSObjectProtocol?
|
||||
|
||||
func watchDefaults(_ tv: NSTextView) {
|
||||
guard defaultsObserver == nil else { return }
|
||||
defaultsObserver = NotificationCenter.default.addObserver(
|
||||
forName: UserDefaults.didChangeNotification,
|
||||
object: nil,
|
||||
queue: .main,
|
||||
) { [weak self] _ in
|
||||
self?.applyTypographyIfChanged(tv)
|
||||
}
|
||||
}
|
||||
|
||||
private func applyTypographyIfChanged(_ tv: NSTextView) {
|
||||
let key = ProseTypography.flowKey
|
||||
guard key != appliedFlowKey else { return }
|
||||
appliedFlowKey = key
|
||||
let sel = tv.selectedRange()
|
||||
if let storage = tv.textStorage as? NSMutableAttributedString {
|
||||
storage.setAttributedString(ProsePresenter.attribute(tv.string))
|
||||
tv.setSelectedRange(sel)
|
||||
}
|
||||
}
|
||||
|
||||
init(representable: ProseTextView) {
|
||||
onEdit = representable.onEdit
|
||||
|
||||
+390
-71
@@ -8,73 +8,323 @@
|
||||
// the source of truth; attributes ride on top and re-apply per edited
|
||||
// paragraph. The Fix-Card anchor search stays with M2 (#25) — not lifted.
|
||||
//
|
||||
// #77: reading-parity rework — the editing surface now mirrors the calm-ruled
|
||||
// reading.css values (#78): leading 1.8-equivalent, heading ladder 30/22/19
|
||||
// (h3) with h4+ flooring at bold body, half-height blank separators, quote
|
||||
// secondary ink + indent, fence interiors as mono code, dimmed list markers,
|
||||
// and real traits (bold/italic/code/link) on inline content. Marks stay
|
||||
// visible-dimmed everywhere — the plain store is the source of truth.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
|
||||
/// Styled-source presentation (ADR-0010 mode B): variable heading sizes,
|
||||
/// paragraph spacing, dimmed syntax. Pure functions over text; no AppKit view
|
||||
/// state. Colors are the spike's proven values (foreground ≈ DesignTokens
|
||||
/// foreground; the 0.55 syntax dim is deliberately lighter than muted).
|
||||
/// Styled-source presentation (ADR-0010 mode B): pure functions over text; no
|
||||
/// AppKit view state. Colors mirror reading.css tokens in ProseTypography.
|
||||
nonisolated enum ProsePresenter {
|
||||
enum LineKind { case heading1, heading2, quote, syntaxOnly, body }
|
||||
enum LineKind {
|
||||
case heading1, heading2, heading3, heading4Plus
|
||||
case quote
|
||||
case fence, fenceInterior
|
||||
case listMarker
|
||||
case syntaxOnly
|
||||
case blank
|
||||
case body
|
||||
}
|
||||
|
||||
// MARK: Classification
|
||||
|
||||
/// Context-free kind (no fence state) — headings/lists/quotes/rules/blank.
|
||||
static func lineKind(_ line: String) -> LineKind {
|
||||
let trimmedLine = line.drop(while: { $0 == " " })
|
||||
if trimmedLine.hasPrefix("## ") {
|
||||
return .heading2
|
||||
classify(line, inFence: false)
|
||||
}
|
||||
|
||||
static func classify(_ line: String, inFence: Bool) -> LineKind {
|
||||
if inFence {
|
||||
return .fenceInterior
|
||||
}
|
||||
if trimmedLine.hasPrefix("# ") {
|
||||
return .heading1
|
||||
let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
|
||||
if trimmed.isEmpty {
|
||||
return .blank
|
||||
}
|
||||
if trimmedLine.hasPrefix("> ") {
|
||||
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
|
||||
return .fence
|
||||
}
|
||||
let hashes = trimmed.prefix(while: { $0 == "#" }).count
|
||||
if hashes > 0 {
|
||||
let after = trimmed.dropFirst(hashes)
|
||||
if after.hasPrefix(" ") || after.isEmpty {
|
||||
switch hashes {
|
||||
case 1: return .heading1
|
||||
case 2: return .heading2
|
||||
case 3: return .heading3
|
||||
default: return .heading4Plus
|
||||
}
|
||||
}
|
||||
}
|
||||
if trimmed.hasPrefix(">") {
|
||||
return .quote
|
||||
}
|
||||
if !trimmedLine.isEmpty, trimmedLine.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
|
||||
if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
|
||||
return .syntaxOnly
|
||||
}
|
||||
if listMarkerRegex.firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) != nil {
|
||||
return .listMarker
|
||||
}
|
||||
return .body
|
||||
}
|
||||
|
||||
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
|
||||
// MARK: Entry points
|
||||
|
||||
/// Paragraph spacing per line kind, applied via NSParagraphStyle.
|
||||
/// ponytail: quote rides body spacing — attributes(for:) styles quotes
|
||||
/// as body anyway; dedicated quote spacing waits for #20's polish pass.
|
||||
static func paragraph(_: LineKind) -> NSParagraphStyle {
|
||||
let style = NSMutableParagraphStyle()
|
||||
// Edit mode shows blank source lines — the blank line IS the
|
||||
// separator. Only line height rides the flow knobs here; the
|
||||
// paragraph/heading spacing knobs are reading-mode only.
|
||||
style.lineHeightMultiple = ProseTypography.lineHeightMultiple
|
||||
style.paragraphSpacing = 0
|
||||
style.paragraphSpacingBefore = 0
|
||||
return style
|
||||
}
|
||||
|
||||
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed syntax.
|
||||
/// Attribute a whole text (initial load).
|
||||
static func attribute(_ text: String) -> NSAttributedString {
|
||||
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
|
||||
let out = NSMutableAttributedString(string: text, attributes: ProseTypography.bodyAttributes)
|
||||
let nsText = text as NSString
|
||||
nsText.enumerateSubstrings(in: NSRange(location: 0, length: nsText.length), options: [.byLines]) { line, range, _, _ in
|
||||
guard let line else { return }
|
||||
let kind = lineKind(line)
|
||||
out.setAttributes(Self.attributes(for: kind), range: range)
|
||||
dimSyntax(in: out, range: range)
|
||||
}
|
||||
applyStyles(out, range: NSRange(location: 0, length: nsText.length))
|
||||
return out
|
||||
}
|
||||
|
||||
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
|
||||
/// Attribute one paragraph (editing-time re-apply). Cheap: the paragraph's
|
||||
/// lines plus a fence-state scan of the prefix.
|
||||
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
|
||||
let line = (out.string as NSString).substring(with: paragraphRange)
|
||||
let kind = lineKind(line)
|
||||
out.setAttributes(Self.attributes(for: kind), range: paragraphRange)
|
||||
dimSyntax(in: out, range: paragraphRange)
|
||||
applyStyles(out, range: paragraphRange)
|
||||
}
|
||||
|
||||
// Typography: the #70 role slots (ProseTypography) — Body / Headings /
|
||||
// Code — shared with reading mode; editing chrome (dimmed syntax) rides
|
||||
// the Code slot.
|
||||
// MARK: Styling pass
|
||||
|
||||
private static func applyStyles(_ out: NSMutableAttributedString, range: NSRange) {
|
||||
let nsText = out.string as NSString
|
||||
guard range.length > 0, range.location >= 0 else { return }
|
||||
var inFence = false
|
||||
if range.location > 0, out.string.contains("```") || out.string.contains("~~~") {
|
||||
inFence = fenceState(nsText, upTo: range.location)
|
||||
}
|
||||
for line in contentLines(nsText, in: range) {
|
||||
let trimmed = line.text.drop(while: { $0 == " " || $0 == "\t" })
|
||||
let isDelim = !line.text.isEmpty && !trimmed.isEmpty && (trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~"))
|
||||
let kind = isDelim ? LineKind.fence : classify(line.text, inFence: inFence)
|
||||
if isDelim {
|
||||
inFence.toggle()
|
||||
}
|
||||
styleLine(out, line: line, kind: kind)
|
||||
}
|
||||
}
|
||||
|
||||
private struct Line {
|
||||
let full: NSRange // content + terminator (blank lines attribute their terminator)
|
||||
let content: NSRange
|
||||
let text: String
|
||||
}
|
||||
|
||||
/// Every line in `range` — including empty ones — as (full, content, text).
|
||||
private static func contentLines(_ nsText: NSString, in range: NSRange) -> [Line] {
|
||||
var lines: [Line] = []
|
||||
var loc = range.location
|
||||
let end = NSMaxRange(range)
|
||||
while loc < end {
|
||||
let full = nsText.lineRange(for: NSRange(location: loc, length: 0))
|
||||
var len = full.length
|
||||
while len > 0 {
|
||||
let char = nsText.character(at: full.location + len - 1)
|
||||
if char == 0x0A || char == 0x0D {
|
||||
len -= 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
let content = NSRange(location: full.location, length: len)
|
||||
lines.append(Line(
|
||||
full: full,
|
||||
content: content,
|
||||
text: len > 0 ? nsText.substring(with: content) : "",
|
||||
))
|
||||
loc = NSMaxRange(full)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
/// Count unclosed fences before `end` (``` or ~~~ delim lines toggle).
|
||||
private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool {
|
||||
var inFence = false
|
||||
var loc = 0
|
||||
while loc < end {
|
||||
let full = nsText.lineRange(for: NSRange(location: loc, length: 0))
|
||||
var len = full.length
|
||||
while len > 0 {
|
||||
let char = nsText.character(at: full.location + len - 1)
|
||||
if char == 0x0A || char == 0x0D {
|
||||
len -= 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len > 0 {
|
||||
let line = (nsText.substring(with: NSRange(location: full.location, length: len)) as String)
|
||||
.drop(while: { $0 == " " || $0 == "\t" })
|
||||
if line.hasPrefix("```") || line.hasPrefix("~~~") {
|
||||
inFence.toggle()
|
||||
}
|
||||
}
|
||||
loc = NSMaxRange(full)
|
||||
}
|
||||
return inFence
|
||||
}
|
||||
|
||||
private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind) {
|
||||
guard line.full.length > 0 else { return }
|
||||
out.setAttributes(attributes(for: kind), range: line.full)
|
||||
let dim = ProseTypography.codeAttributes // codeFont + syntaxColor
|
||||
switch kind {
|
||||
case .heading1, .heading2, .heading3, .heading4Plus:
|
||||
let lead = line.text.prefix(while: { $0 == " " }).utf16.count
|
||||
let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count
|
||||
let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead))
|
||||
if marker.length > 0 {
|
||||
out.addAttributes(dim, range: marker)
|
||||
}
|
||||
case .quote:
|
||||
if let marker = markerRange(quoteMarkerRegex, in: line.text), marker.length > 0 {
|
||||
out.addAttributes(dim, range: shifted(marker, into: line.content))
|
||||
}
|
||||
case .listMarker:
|
||||
if let marker = markerRange(listMarkerRegex, in: line.text), marker.length > 0 {
|
||||
out.addAttributes(dim, range: shifted(marker, into: line.content))
|
||||
}
|
||||
case .syntaxOnly, .fence:
|
||||
if line.content.length > 0 {
|
||||
out.addAttributes(dim, range: line.content)
|
||||
}
|
||||
case .fenceInterior, .blank, .body:
|
||||
break
|
||||
}
|
||||
if kind == .body || kind == .quote || kind == .listMarker {
|
||||
styleInline(out, content: line.content, text: line.text)
|
||||
}
|
||||
}
|
||||
|
||||
private static func shifted(_ marker: NSRange, into content: NSRange) -> NSRange {
|
||||
NSRange(
|
||||
location: content.location + marker.location,
|
||||
length: min(marker.length, max(0, content.length - marker.location)),
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: Inline spans (bold / italic / code / links)
|
||||
|
||||
// ponytail: Regex literals aren't Sendable; they're immutable de-facto.
|
||||
// No lookbehind in swift-regex — overlap-claim ordering + a manual
|
||||
// boundary check replace it.
|
||||
private nonisolated(unsafe) static let boldPattern = /\*\*[^*\n]+?\*\*/
|
||||
private nonisolated(unsafe) static let emStarPattern = /\*[^*\n]+?\*/
|
||||
private nonisolated(unsafe) static let emUnderPattern = /_[^_\n]+?_/
|
||||
private nonisolated(unsafe) static let codePattern = /`[^`\n]+?`/
|
||||
private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/
|
||||
|
||||
/// Trait-style inline constructs. Marks dim; content gets real traits.
|
||||
/// Priority: code > link > bold > italic; later matches skip claimed spans.
|
||||
private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) {
|
||||
guard content.length > 0 else { return }
|
||||
var claimed: [Range<Int>] = []
|
||||
|
||||
func claim(_ span: Range<Int>) -> Bool {
|
||||
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
|
||||
claimed.append(span)
|
||||
return true
|
||||
}
|
||||
|
||||
func dim(_ utf16: Range<Int>) {
|
||||
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
|
||||
out.addAttributes(ProseTypography.codeAttributes, range: range)
|
||||
}
|
||||
|
||||
func attr(_ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) {
|
||||
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
|
||||
out.addAttributes(attrs, range: range)
|
||||
}
|
||||
|
||||
let boldFont = ProseTypography.boldBodyFont
|
||||
let italicFont = ProseTypography.italicBodyFont
|
||||
let codeFont = ProseTypography.codeFont
|
||||
let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor]
|
||||
let linkAttrs: [NSAttributedString.Key: Any] = [
|
||||
.underlineStyle: NSUnderlineStyle.single.rawValue,
|
||||
.underlineColor: ProseTypography.mutedColor,
|
||||
]
|
||||
|
||||
// inline code — marks + content in the code face, content at ink
|
||||
for match in text.matches(of: codePattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new })
|
||||
}
|
||||
// links — label ink + underline (CSS: ink text, muted rule); the
|
||||
// brackets, ]( and the URL dim (reading hides them; dim is the
|
||||
// editor's closest parity move).
|
||||
for match in text.matches(of: linkPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
let whole = match.output // whole match (no capture groups)
|
||||
guard let sep = whole.firstRange(of: "](") else { continue }
|
||||
// sep indices are valid in text (Substring shares indices)
|
||||
let sepOffset = text.utf16.distance(from: text.utf16.startIndex, to: sep.lowerBound.samePosition(in: text.utf16)!)
|
||||
let label = span.lowerBound + 1 ..< sepOffset
|
||||
dim(span.lowerBound ..< span.lowerBound + 1) // [
|
||||
attr(label, linkAttrs)
|
||||
dim(sepOffset ..< span.upperBound) // ](url)
|
||||
}
|
||||
// bold
|
||||
for match in text.matches(of: boldPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
dim(span.lowerBound ..< span.lowerBound + 2)
|
||||
dim(span.upperBound - 2 ..< span.upperBound)
|
||||
attr(span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont])
|
||||
}
|
||||
// italic — two forms. CommonMark: intraword `_` never emphasizes
|
||||
// (file_name_here); intraword `*` does. No lookbehind in swift-regex,
|
||||
// so boundary chars are checked by hand.
|
||||
for match in text.matches(of: emStarPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
let lo = charBefore(text, span.lowerBound)
|
||||
let hi = charAfter(text, span.upperBound)
|
||||
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
|
||||
continue
|
||||
}
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
|
||||
}
|
||||
for match in text.matches(of: emUnderPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
let lo = charBefore(text, span.lowerBound)
|
||||
let hi = charAfter(text, span.upperBound)
|
||||
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
|
||||
continue
|
||||
}
|
||||
if lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true {
|
||||
continue
|
||||
}
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
|
||||
}
|
||||
// fallback: dim stray syntax chars outside claimed spans
|
||||
let syntax = inlineSyntax
|
||||
for (offset, codeUnit) in text.utf16.enumerated() {
|
||||
guard let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), syntax.contains(scalar) else { continue }
|
||||
let unit = offset ..< offset + 1
|
||||
if claimed.contains(where: { $0.overlaps(unit) }) {
|
||||
continue
|
||||
}
|
||||
dim(unit)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Base attributes
|
||||
|
||||
static var bodyFont: NSFont {
|
||||
ProseTypography.bodyFont
|
||||
}
|
||||
@@ -88,41 +338,110 @@ nonisolated enum ProsePresenter {
|
||||
case .heading1:
|
||||
[.font: ProseTypography.headingFont, .paragraphStyle: paragraph(.heading1)]
|
||||
case .heading2:
|
||||
[.font: ProseTypography.heading2Font, .paragraphStyle: paragraph(.heading2)]
|
||||
case .heading3:
|
||||
[.font: ProseTypography.heading3Font, .paragraphStyle: paragraph(.heading3)]
|
||||
case .heading4Plus:
|
||||
[.font: ProseTypography.headingBoldFont, .paragraphStyle: paragraph(.heading4Plus)]
|
||||
case .quote:
|
||||
[
|
||||
.font: ProseTypography.headingFont(size: (ProseTypography.headingFont.pointSize * 0.77).rounded()),
|
||||
.paragraphStyle: paragraph(.heading2),
|
||||
.font: ProseTypography.bodyFont,
|
||||
.foregroundColor: ProseTypography.secondaryColor,
|
||||
.paragraphStyle: paragraph(.quote),
|
||||
]
|
||||
case .quote, .syntaxOnly, .body: bodyAttributes
|
||||
case .fence:
|
||||
[
|
||||
.font: ProseTypography.codeFont,
|
||||
.foregroundColor: ProseTypography.syntaxColor,
|
||||
.backgroundColor: ProseTypography.substrateColor,
|
||||
.paragraphStyle: paragraph(.fence),
|
||||
]
|
||||
case .fenceInterior:
|
||||
[
|
||||
.font: ProseTypography.codeFont,
|
||||
.foregroundColor: ProseTypography.foregroundColor,
|
||||
.backgroundColor: ProseTypography.substrateColor,
|
||||
.paragraphStyle: paragraph(.fenceInterior),
|
||||
]
|
||||
case .listMarker, .syntaxOnly, .body:
|
||||
ProseTypography.bodyAttributes
|
||||
case .blank:
|
||||
[.font: ProseTypography.blankFont, .paragraphStyle: paragraph(.blank)]
|
||||
}
|
||||
}
|
||||
|
||||
/// Dim markdown syntax characters within a line range (marker prefixes + inline marks).
|
||||
static func dimSyntax(in out: NSMutableAttributedString, range: NSRange) {
|
||||
let nsText = out.string as NSString
|
||||
guard range.length > 0 else { return }
|
||||
let line = nsText.substring(with: range)
|
||||
let kind = lineKind(line)
|
||||
// prefix markers
|
||||
let markerLen = switch kind {
|
||||
case .heading1: 2
|
||||
case .heading2: 3
|
||||
case .quote: 2
|
||||
default: 0
|
||||
/// Paragraph spacing per line kind. Blank source lines are the separator
|
||||
/// (#77: at half height); spacing knobs stay 0 unless the visual check
|
||||
/// asks for more.
|
||||
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
|
||||
let style = NSMutableParagraphStyle()
|
||||
let font: NSFont
|
||||
let cssLineHeight: CGFloat
|
||||
switch kind {
|
||||
case .heading1, .heading2, .heading3, .heading4Plus:
|
||||
font = ProseTypography.headingFont
|
||||
cssLineHeight = 1.15 // CSS: h1–h6 line-height 1.15
|
||||
case .fence, .fenceInterior:
|
||||
font = ProseTypography.codeFont
|
||||
cssLineHeight = 1.5 // CSS: pre line-height 1.5
|
||||
case .blank:
|
||||
font = ProseTypography.blankFont
|
||||
cssLineHeight = 1.8
|
||||
default:
|
||||
font = ProseTypography.bodyFont
|
||||
cssLineHeight = 1.8 // CSS: --lh 1.8
|
||||
}
|
||||
let dim: [NSAttributedString.Key: Any] = [
|
||||
.foregroundColor: ProseTypography.syntaxColor,
|
||||
.font: ProseTypography.codeFont,
|
||||
]
|
||||
if markerLen > 0 {
|
||||
out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length)))
|
||||
style.lineHeightMultiple = ProseTypography.lineHeightMultiple(font: font, cssLineHeight: cssLineHeight)
|
||||
if kind == .quote {
|
||||
style.firstLineHeadIndent = 20 // CSS: blockquote padding-left 20px
|
||||
style.headIndent = 20 // wrapped quote lines align under the text
|
||||
}
|
||||
// inline marks in body/quote
|
||||
if kind == .body || kind == .quote {
|
||||
for (offset, codeUnit) in line.utf16.enumerated() {
|
||||
if let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), inlineSyntax.contains(scalar) {
|
||||
out.addAttributes(dim, range: NSRange(location: range.location + offset, length: 1))
|
||||
}
|
||||
}
|
||||
if kind == .heading1 || kind == .heading2 || kind == .heading3 || kind == .heading4Plus {
|
||||
// Reading parity: head-space-before 90 / after 30 MINUS the blank
|
||||
// separator line's own height (~15pt), which the editor shows and
|
||||
// reading collapses. Alexander ruled blank-only "a bit tight".
|
||||
style.paragraphSpacingBefore = 75
|
||||
style.paragraphSpacing = 30
|
||||
}
|
||||
return style
|
||||
}
|
||||
|
||||
// MARK: Pattern helpers
|
||||
|
||||
/// Marker dimming for quote / list lines — returns the marker's NSRange in
|
||||
/// `line.text`, or nil.
|
||||
// Static literal patterns — compile by construction.
|
||||
// swiftlint:disable:next force_try
|
||||
private static let listMarkerRegex = try! NSRegularExpression(pattern: #"^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)"#)
|
||||
// swiftlint:disable:next force_try
|
||||
private static let quoteMarkerRegex = try! NSRegularExpression(pattern: #"^(?:\s*>(?:\s|$))*"#)
|
||||
|
||||
private static func markerRange(_ regex: NSRegularExpression, in lineText: String) -> NSRange? {
|
||||
regex.firstMatch(in: lineText, range: NSRange(location: 0, length: (lineText as NSString).length))?.range
|
||||
}
|
||||
|
||||
/// Mark-boundary helpers (no lookbehind in swift-regex): the Character
|
||||
/// just before / just after a UTF-16 offset, or nil at the edges.
|
||||
private static func charBefore(_ text: String, _ offset: Int) -> Character? {
|
||||
guard offset > 0 else { return nil }
|
||||
let idx = text.utf16.index(text.utf16.startIndex, offsetBy: offset - 1, limitedBy: text.utf16.endIndex) ?? text.utf16.startIndex
|
||||
guard let scalar = Unicode.Scalar(text.utf16[idx]) else { return nil }
|
||||
return Character(scalar)
|
||||
}
|
||||
|
||||
private static func charAfter(_ text: String, _ offset: Int) -> Character? {
|
||||
let idx = text.utf16.index(text.utf16.startIndex, offsetBy: offset, limitedBy: text.utf16.endIndex) ?? text.utf16.endIndex
|
||||
guard idx < text.utf16.endIndex, let scalar = Unicode.Scalar(text.utf16[idx]) else { return nil }
|
||||
return Character(scalar)
|
||||
}
|
||||
|
||||
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
|
||||
}
|
||||
|
||||
nonisolated extension Range where Bound == String.Index {
|
||||
func utf16Range(in base: String) -> Range<Int> {
|
||||
let lo = base.utf16.distance(from: base.utf16.startIndex, to: lowerBound.samePosition(in: base.utf16)!)
|
||||
let hi = base.utf16.distance(from: base.utf16.startIndex, to: upperBound.samePosition(in: base.utf16)!)
|
||||
return lo ..< hi
|
||||
}
|
||||
}
|
||||
+85
-131
@@ -2,85 +2,87 @@
|
||||
// ProseTypography.swift
|
||||
// Museion
|
||||
//
|
||||
// #71 (S1.2, map #20 / #70): the three role slots — Body / Headings / Code —
|
||||
// each {face, size}, persisted in UserDefaults (six values), read by BOTH
|
||||
// prose surfaces (styled-source editing + reading). Machine-local faces,
|
||||
// nothing bundled; a missing face falls back to the system font silently.
|
||||
// Chrome stays on system faces.
|
||||
//
|
||||
// Resolution note (#70 deviation, probed in-session): family+weight lookup
|
||||
// misresolves Concourse OT — Thin and Book both advertise weight 4, and
|
||||
// NSFontManager picks Thin. Faces therefore resolve through the family's
|
||||
// member list: prefer the Book/Regular member, else the middle weight.
|
||||
// #72 rework: single-user app — the prose typography is hardcoded constants,
|
||||
// dialled in on Alexander's exact fonts (Valkyrie OT B body / Concourse OT
|
||||
// headings / UbuntuMono code). The Settings typography/flow sections are
|
||||
// gone; the reading surface's look lives in Museion/Resources/reading.css
|
||||
// (editable while the app runs). These constants feed the EDITING surface;
|
||||
// the CSS :root block is the source of truth for reading.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
|
||||
/// Prose typography slots (#70). Static computed accessors — surfaces read
|
||||
/// on render; the Settings pane writes UserDefaults and the surfaces rebuild
|
||||
/// (pane re-entry rebuilds the editor; reading rebuilds per toggle).
|
||||
/// Prose typography constants (#72 rework). The editing surface reads these;
|
||||
/// reading mode reads Resources/reading.css.
|
||||
nonisolated enum ProseTypography {
|
||||
/// v1 defaults (#70): Body = Concourse OT Book 17, Headings = Iowan Old
|
||||
/// Style bold 26, Code = UbuntuMono Nerd Font Mono 13.
|
||||
static let defaultBodyFace = "Concourse OT"
|
||||
static let defaultHeadingsFace = "Iowan Old Style"
|
||||
static let defaultCodeFace = "UbuntuMono Nerd Font Mono"
|
||||
static let defaultBodySize: Double = 17
|
||||
static let defaultHeadingsSize: Double = 26
|
||||
static let defaultCodeSize: Double = 13
|
||||
/// Text flow (#71 polish): line-height multiple + paragraph/heading
|
||||
/// spacing measured in body lines — different faces need different flow.
|
||||
static let defaultLineHeight: Double = 1.25
|
||||
static let defaultParagraphSpacingLines: Double = 1
|
||||
static let defaultHeadingSpacingLines: Double = 2
|
||||
// #77: sizes mirror reading.css exactly (px → pt 1:1 at 1×).
|
||||
static let bodySize: CGFloat = 17
|
||||
static let heading1Size: CGFloat = 30 // CSS: --headings-size 26 × 1.15
|
||||
static let heading2Size: CGFloat = 22 // CSS: 26 × 0.85
|
||||
static let heading3Size: CGFloat = 19 // CSS: --body-size × 1.12
|
||||
static let codeSize: CGFloat = 14
|
||||
static let blankSize: CGFloat = 9 // half-height blank separator lines (#77)
|
||||
|
||||
/// Register the six defaults once at app start.
|
||||
static func registerDefaults() {
|
||||
UserDefaults.standard.register(defaults: [
|
||||
"proseBodyFace": defaultBodyFace,
|
||||
"proseBodySize": defaultBodySize,
|
||||
"proseHeadingsFace": defaultHeadingsFace,
|
||||
"proseHeadingsSize": defaultHeadingsSize,
|
||||
"proseCodeFace": defaultCodeFace,
|
||||
"proseCodeSize": defaultCodeSize,
|
||||
"proseLineHeight": defaultLineHeight,
|
||||
"proseParagraphSpacingLines": defaultParagraphSpacingLines,
|
||||
"proseHeadingSpacingLines": defaultHeadingSpacingLines,
|
||||
])
|
||||
}
|
||||
|
||||
private static func face(_ key: String, defaultFace: String) -> String {
|
||||
UserDefaults.standard.string(forKey: key) ?? defaultFace
|
||||
}
|
||||
|
||||
private static func size(_ key: String, defaultSize: Double) -> CGFloat {
|
||||
let stored = UserDefaults.standard.double(forKey: key)
|
||||
return stored == 0 ? defaultSize : stored
|
||||
}
|
||||
|
||||
// MARK: Slot fonts
|
||||
|
||||
/// Body slot font — the family's Book/Regular member at the slot size.
|
||||
/// Body = Valkyrie OT B (the screen cut; CoreText unifies the OT family
|
||||
/// as "Valkyrie OT" — only B members installed, no A/B ambiguity).
|
||||
static var bodyFont: NSFont {
|
||||
font(family: face("proseBodyFace", defaultFace: defaultBodyFace),
|
||||
size: size("proseBodySize", defaultSize: defaultBodySize))
|
||||
NSFont(name: "ValkyrieOTBRegular", size: bodySize) ?? NSFont.systemFont(ofSize: bodySize)
|
||||
}
|
||||
|
||||
/// Headings slot font — the family's Book/Regular member, bold trait, at
|
||||
/// the slot size (h1). Scaled levels call `headingFont(size:)`.
|
||||
/// Headings = Concourse OT (the designer's own pairing with Valkyrie);
|
||||
/// Semibold carries heading weight better than Book on screen.
|
||||
static var headingFont: NSFont {
|
||||
bolded(headingFont(size: size("proseHeadingsSize", defaultSize: defaultHeadingsSize)))
|
||||
NSFont(name: "ConcourseOT6Semibold", size: heading1Size) ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold)
|
||||
}
|
||||
|
||||
static func headingFont(size: CGFloat) -> NSFont {
|
||||
bolded(font(family: face("proseHeadingsFace", defaultFace: defaultHeadingsFace), size: size))
|
||||
/// h2 = the headings face at CSS's 0.85× ladder step (#77).
|
||||
static var heading2Font: NSFont {
|
||||
NSFont(name: "ConcourseOT6Semibold", size: heading2Size) ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold)
|
||||
}
|
||||
|
||||
/// Code slot font (inline code, fenced blocks, and the editing surface's
|
||||
/// dimmed syntax).
|
||||
/// h3 = body face, sized up, weight 600 (CSS h3: body-face w600). The B
|
||||
/// cut has no 600 member — the bold trait (700, real or synthesized) is
|
||||
/// the nearest expressible. ponytail: trait-convert; a true semibold face
|
||||
/// would drop in here if ever installed.
|
||||
static var heading3Font: NSFont {
|
||||
NSFontManager.shared.convert(
|
||||
NSFontManager.shared.convert(bodyFont, toSize: heading3Size),
|
||||
toHaveTrait: .boldFontMask,
|
||||
)
|
||||
}
|
||||
|
||||
/// h4+ floors at bold body (CSS h4–h6).
|
||||
static var headingBoldFont: NSFont {
|
||||
NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask)
|
||||
}
|
||||
|
||||
/// Code slot (inline code, fenced blocks, editing syntax dim).
|
||||
static var codeFont: NSFont {
|
||||
font(family: face("proseCodeFace", defaultFace: defaultCodeFace),
|
||||
size: size("proseCodeSize", defaultSize: defaultCodeSize))
|
||||
NSFont(name: "UbuntuMonoNFM", size: codeSize) ?? NSFont.monospacedSystemFont(ofSize: codeSize, weight: .regular)
|
||||
}
|
||||
|
||||
/// Blank source lines at 9pt (#77 half-height separators).
|
||||
static var blankFont: NSFont {
|
||||
NSFontManager.shared.convert(bodyFont, toSize: blankSize)
|
||||
}
|
||||
|
||||
/// Editor measure (#77): reading.css `--measure: 66ch` — the advance of
|
||||
/// "0" × 66 in the body face (px→pt 1:1), + the text container's 24pt
|
||||
/// lineFragmentPadding on both sides (the CSS body's 24px side padding).
|
||||
static var measureWidth: CGFloat {
|
||||
let zero = NSAttributedString(string: "0", attributes: [.font: bodyFont])
|
||||
let ch = zero.size().width
|
||||
return (ch * 66).rounded() + 48
|
||||
}
|
||||
|
||||
/// Line-height parity with reading.css (#77): CSS `line-height: n` means
|
||||
/// n × font-size pixels; TextKit's lineHeightMultiple multiplies the
|
||||
/// font's natural box (ascender − descender + leading ≈ 1.2 × size).
|
||||
/// Copying the CSS number would overshoot ~20% — calibrate instead.
|
||||
static func lineHeightMultiple(font: NSFont, cssLineHeight: CGFloat) -> CGFloat {
|
||||
let natural = font.ascender - font.descender + font.leading
|
||||
guard natural > 0 else { return cssLineHeight }
|
||||
return (font.pointSize * cssLineHeight) / natural
|
||||
}
|
||||
|
||||
static var italicBodyFont: NSFont {
|
||||
@@ -88,51 +90,16 @@ nonisolated enum ProseTypography {
|
||||
}
|
||||
|
||||
static var boldBodyFont: NSFont {
|
||||
bolded(bodyFont)
|
||||
NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask)
|
||||
}
|
||||
|
||||
// MARK: Text flow (#71 polish)
|
||||
|
||||
/// Line-height multiple (clamped 1…2; 0/absent → default).
|
||||
static var lineHeightMultiple: CGFloat {
|
||||
clamped("proseLineHeight", default: defaultLineHeight, 1 ... 2)
|
||||
}
|
||||
|
||||
/// Spacing after body paragraphs, in body lines.
|
||||
static var paragraphSpacingLines: CGFloat {
|
||||
clamped("proseParagraphSpacingLines", default: defaultParagraphSpacingLines, 0 ... 4)
|
||||
}
|
||||
|
||||
/// Spacing after headings, in body lines.
|
||||
static var headingSpacingLines: CGFloat {
|
||||
clamped("proseHeadingSpacingLines", default: defaultHeadingSpacingLines, 0 ... 6)
|
||||
}
|
||||
|
||||
/// Every value the prose surfaces render from, summed — a change key
|
||||
/// for live re-attribution when settings move.
|
||||
static var flowKey: String {
|
||||
"\(bodyFont.fontName)@\(bodyFont.pointSize)|\(codeFont.fontName)@\(codeFont.pointSize)|\(headingFont.fontName)@\(headingFont.pointSize)|lh=\(lineHeightMultiple)|p=\(paragraphSpacingLines)|h=\(headingSpacingLines)"
|
||||
}
|
||||
|
||||
/// One body line at the configured flow, in points.
|
||||
static var linePoints: CGFloat {
|
||||
let f = bodyFont
|
||||
return (f.ascender - f.descender + f.leading) * lineHeightMultiple
|
||||
}
|
||||
|
||||
private static func clamped(_ key: String, default def: Double, _ range: ClosedRange<Double>) -> CGFloat {
|
||||
let stored = UserDefaults.standard.double(forKey: key)
|
||||
let value = stored == 0 ? def : stored
|
||||
return CGFloat(min(max(value, range.lowerBound), range.upperBound))
|
||||
}
|
||||
|
||||
// MARK: Attribute stacks (reading + editing share them)
|
||||
// MARK: Attribute stacks (editing surface)
|
||||
|
||||
static var foregroundColor: NSColor {
|
||||
NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1)
|
||||
}
|
||||
|
||||
/// Dimmed syntax color (the editing surface's 0.55 dim, #19).
|
||||
/// Dimmed syntax color (the editing surface's 0.5 dim, #19).
|
||||
static var syntaxColor: NSColor {
|
||||
NSColor(white: 0.55, alpha: 1)
|
||||
}
|
||||
@@ -141,7 +108,22 @@ nonisolated enum ProseTypography {
|
||||
NSColor(white: 0.78, alpha: 1)
|
||||
}
|
||||
|
||||
/// Table borders + reading HR hairline (≈ DesignTokens.border).
|
||||
/// Secondary ink — reading.css --secondary #48484d (quotes, #77).
|
||||
static var secondaryColor: NSColor {
|
||||
NSColor(red: 0x48 / 255, green: 0x48 / 255, blue: 0x4D / 255, alpha: 1)
|
||||
}
|
||||
|
||||
/// Muted ink — reading.css --muted #6e6e73 (link underline rule, #77).
|
||||
static var mutedColor: NSColor {
|
||||
NSColor(red: 0x6E / 255, green: 0x6E / 255, blue: 0x73 / 255, alpha: 1)
|
||||
}
|
||||
|
||||
/// Substrate — reading.css --substrate #f5f5f7 (code panels, #77).
|
||||
static var substrateColor: NSColor {
|
||||
NSColor(red: 0xF5 / 255, green: 0xF5 / 255, blue: 0xF7 / 255, alpha: 1)
|
||||
}
|
||||
|
||||
/// Table borders + editing-surface hairline (≈ DesignTokens.border).
|
||||
static var tableBorderColor: NSColor {
|
||||
NSColor(red: 0xE8 / 255, green: 0xE5 / 255, blue: 0xDF / 255, alpha: 1)
|
||||
}
|
||||
@@ -160,32 +142,4 @@ nonisolated enum ProseTypography {
|
||||
.foregroundColor: syntaxColor,
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: Resolution
|
||||
|
||||
/// Family → member PS name → NSFont. Prefer Book/Regular styles, else the
|
||||
/// member closest to weight 5; unknown family → system font (silent, #70).
|
||||
private static func font(family: String, size: CGFloat) -> NSFont {
|
||||
let members = NSFontManager.shared.availableMembers(ofFontFamily: family) ?? []
|
||||
let regular = members.first { entry in
|
||||
guard let style = entry[safe: 1] as? String else { return false }
|
||||
return style.range(of: "book|regular", options: [.caseInsensitive, .regularExpression]) != nil
|
||||
} ?? members.min { lhs, rhs in
|
||||
abs((lhs[safe: 2] as? Int ?? 5) - 5) < abs((rhs[safe: 2] as? Int ?? 5) - 5)
|
||||
}
|
||||
guard let name = regular?[safe: 0] as? String else {
|
||||
return NSFont.systemFont(ofSize: size)
|
||||
}
|
||||
return NSFont(name: name, size: size) ?? NSFont.systemFont(ofSize: size)
|
||||
}
|
||||
|
||||
private static func bolded(_ base: NSFont) -> NSFont {
|
||||
NSFontManager.shared.convert(base, toHaveTrait: .boldFontMask)
|
||||
}
|
||||
}
|
||||
|
||||
private nonisolated extension Array {
|
||||
subscript(safe index: Int) -> Element? {
|
||||
indices.contains(index) ? self[index] : nil
|
||||
}
|
||||
}
|
||||
+175
-514
@@ -2,556 +2,217 @@
|
||||
// ReadingPresenter.swift
|
||||
// Museion
|
||||
//
|
||||
// #71 (S1.2, map #20): the reading-mode renderer — block-aware per ADR-0010
|
||||
// (blank-line split, per-paragraph inline parse, headings fonted by level;
|
||||
// single-Text .full flatten is the anti-pattern). Presentation-only: the
|
||||
// renderer never touches the file; every block carries its source range so
|
||||
// the surface can map click → source paragraph (#68). Scope per #69: lists
|
||||
// (bullets + ordered + nesting + auto-renumber — one rendering path), ### /
|
||||
// #### headings, HR, fenced code, blockquotes (hairline), tables
|
||||
// (NSTextTable, 1px border), images (hover popover payload), links styled +
|
||||
// ⌘-click; footnotes are the one fallback. Typography per #70: the three
|
||||
// role slots in ProseTypography (Body / Headings / Code).
|
||||
// #76 (S1.2, map #20; ADR-0011): the reading renderer is the apex HTML
|
||||
// pipeline — markdown → bundled apex binary → HTML fragment, with the
|
||||
// blank-line chunker's `<!--S:N-->` sentinels restamped post-conversion
|
||||
// into `data-source-line` attributes (the paragraph map for click-to-edit
|
||||
// and scroll-sync, #68; apex emits no source positions — probed in #74).
|
||||
// The TextKit renderer this replaces is deleted, not kept as fallback
|
||||
// (ADR-0011: fallbacks rot; the stale-flow defect dies unfixed by design).
|
||||
// Constructs per #69 ride apex: lists (`1. 1. 1.` renumbers via native
|
||||
// <ol>), ### headings, HR, fenced code, blockquotes, tables, images
|
||||
// (base64 inline, CSS hover expand), links + ⌘-click; footnotes render
|
||||
// natively (apex upgrade over #69's fallback — corpus has none). Typography
|
||||
// per #70/#71: the ProseTypography slots + flow knobs become CSS custom
|
||||
// properties, injected at load.
|
||||
//
|
||||
// Pure over its input (nonisolated); the WKWebView surface loads the page.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import Foundation
|
||||
|
||||
/// Reading-mode presentation: text → rendered blocks. Pure over its input;
|
||||
/// called on the main actor (NSTextTable construction is MainActor).
|
||||
enum ReadingPresenter {
|
||||
/// Vertical rhythm (user measurements, #71 polish): line-height ≈1.25,
|
||||
/// 1 blank line after paragraphs, 2 after headings.
|
||||
private static let lineHeightMultiple: CGFloat = 1.25
|
||||
private static let paragraphSpacingAfter = lineHeightMultiple // 1 line
|
||||
private static let headingSpacingAfter = lineHeightMultiple * 2 // 2 lines
|
||||
/// One rendered block. `sourceRange` is the block's UTF-16 range in the
|
||||
/// source text (delimiter-exclusive) — the #68 click→edit map.
|
||||
/// Reading-mode presentation: markdown → stamped HTML page (#76 / ADR-0011).
|
||||
nonisolated enum ReadingPresenter {
|
||||
// MARK: Source map (the #68 click→edit / scroll-sync contract)
|
||||
|
||||
/// One paragraph-granularity block: 1-based source line + UTF-16 range in
|
||||
/// the source text (blank-line chunk, start-of-chunk … chunk end).
|
||||
struct Block {
|
||||
let content: NSAttributedString
|
||||
let sourceLine: Int
|
||||
let sourceRange: NSRange
|
||||
/// Popover image URL for an `` chunk (#69 hover floor).
|
||||
let imageURL: URL?
|
||||
/// Canvas-drawn decoration (quote hairline / rule / table grid).
|
||||
var decoration: Decoration?
|
||||
}
|
||||
|
||||
/// A block's placement in the built document: where its content landed
|
||||
/// (docRange) ↔ where it came from (sourceRange), plus its resolved image.
|
||||
struct Bound {
|
||||
let docRange: NSRange
|
||||
let sourceRange: NSRange
|
||||
let imageURL: URL?
|
||||
var decoration: Decoration?
|
||||
}
|
||||
|
||||
/// Canvas-drawn decoration for constructs whose layout NSTextTable /
|
||||
/// NSTextBlock can't deliver on modern TextKit (#69 fix: draw it
|
||||
/// ourselves from measured geometry instead).
|
||||
enum Decoration {
|
||||
/// Left hairline at the given indent.
|
||||
case quote(indent: CGFloat)
|
||||
/// Full-width horizontal rule.
|
||||
case rule
|
||||
/// Column x-offsets (incl. closing edge) in mono advance.
|
||||
case table(columns: [CGFloat])
|
||||
}
|
||||
|
||||
/// The reading document: blocks concatenated with paragraph-rhythm
|
||||
/// separators, bounds tracked for click→edit and scroll mapping.
|
||||
struct Document {
|
||||
let content: NSAttributedString
|
||||
let bounds: [Bound]
|
||||
}
|
||||
|
||||
/// Build the single-storage reading document. Image URLs resolve against
|
||||
/// `postFolder` (nil → raw URL kept; the popover fails soft).
|
||||
static func document(for text: String, resolvingImagesIn postFolder: URL?) -> Document {
|
||||
let out = NSMutableAttributedString()
|
||||
var bounds: [Bound] = []
|
||||
for block in blocks(for: text, resolvingImagesIn: postFolder) {
|
||||
if out.length > 0, !out.string.hasSuffix("\n") {
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
}
|
||||
let start = out.length
|
||||
out.append(block.content)
|
||||
bounds.append(Bound(
|
||||
docRange: NSRange(location: start, length: out.length - start),
|
||||
sourceRange: block.sourceRange,
|
||||
imageURL: block.imageURL,
|
||||
decoration: block.decoration,
|
||||
))
|
||||
}
|
||||
return Document(content: out, bounds: bounds)
|
||||
}
|
||||
|
||||
// MARK: Entry
|
||||
|
||||
/// Render `text` into reading blocks: blank-line split, one block per
|
||||
/// chunk (a run of list items or quote lines renders as one block).
|
||||
/// `postFolder` resolves relative image URLs before the attachment loads.
|
||||
static func blocks(for text: String, resolvingImagesIn postFolder: URL?) -> [Block] {
|
||||
var out: [Block] = []
|
||||
/// The chunk list behind the stamp: blank-line split, monotonic — the
|
||||
/// presenter's public map. Line → UTF-16 conversion for caret landing.
|
||||
static func blocks(for text: String) -> [Block] {
|
||||
let ns = text as NSString
|
||||
var out: [Block] = []
|
||||
var loc = 0
|
||||
var line = 1
|
||||
while loc < ns.length {
|
||||
let search = NSRange(location: loc, length: ns.length - loc)
|
||||
let delim = ns.range(of: "\n\n", options: .literal, range: search)
|
||||
let end = delim.location == NSNotFound ? ns.length : delim.location
|
||||
if end > loc {
|
||||
let chunkRange = NSRange(location: loc, length: end - loc)
|
||||
let chunk = ns.substring(with: chunkRange)
|
||||
out.append(block(chunk: chunk, sourceRange: chunkRange, postFolder: postFolder))
|
||||
out.append(Block(sourceLine: line, sourceRange: NSRange(location: loc, length: end - loc)))
|
||||
}
|
||||
loc = delim.location == NSNotFound ? ns.length : delim.location + 2
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Classify one chunk and render it.
|
||||
private static func block(chunk: String, sourceRange: NSRange, postFolder: URL?) -> Block {
|
||||
if let raw = imageURL(in: chunk) {
|
||||
let url = (raw.scheme == nil && raw.path.count > 0)
|
||||
? postFolder?.appendingPathComponent(raw.path) ?? raw : raw
|
||||
return Block(
|
||||
content: imageBlockContent(url: url, alt: altText(in: chunk)),
|
||||
sourceRange: sourceRange,
|
||||
imageURL: url,
|
||||
)
|
||||
}
|
||||
let lines = chunk.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
|
||||
guard let first = lines.first else {
|
||||
return Block(content: NSAttributedString(string: ""), sourceRange: sourceRange, imageURL: nil)
|
||||
}
|
||||
// HR first (#69: `* * *`/`- - -` would otherwise match the bullet
|
||||
// marker `* `/`- ` — same predicate as editing, checked earlier).
|
||||
if lines.count == 1, ProsePresenter.lineKind(first) == .syntaxOnly {
|
||||
return Block(content: hrContent(), sourceRange: sourceRange, imageURL: nil, decoration: .rule)
|
||||
}
|
||||
if lines.allSatisfy({ listItemMarker($0) != nil }) {
|
||||
return Block(content: listContent(lines), sourceRange: sourceRange, imageURL: nil)
|
||||
}
|
||||
if lines.allSatisfy({ blockquoteDepth($0) > 0 }) {
|
||||
return Block(content: quoteContent(lines), sourceRange: sourceRange, imageURL: nil, decoration: quoteDecoration(lines))
|
||||
}
|
||||
if lines.count >= 2, isTableDelimiterRow(lines[1]), let table = tableContent(lines) {
|
||||
return Block(content: table, sourceRange: sourceRange, imageURL: nil, decoration: tableDecoration(lines))
|
||||
}
|
||||
return Block(content: flowContent(lines, first: first), sourceRange: sourceRange, imageURL: nil)
|
||||
}
|
||||
|
||||
// MARK: Flow blocks
|
||||
|
||||
/// Image block: the picture inline (scaled to the column), alt as the
|
||||
/// caption below, link preserved for ⌘-click. Fails soft to alt-text
|
||||
/// paragraph when the file can't load.
|
||||
private static func imageBlockContent(url: URL, alt: String) -> NSAttributedString {
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacing = paragraphSpacingAfter
|
||||
ps.paragraphSpacingBefore = 8
|
||||
guard let image = NSImage(contentsOf: url), image.size.width > 0 else {
|
||||
return inlineParse(alt.isEmpty ? ")" : alt)
|
||||
}
|
||||
let attachment = NSTextAttachment()
|
||||
attachment.image = image
|
||||
let maxW: CGFloat = 480
|
||||
if image.size.width > maxW {
|
||||
attachment.image?.size = NSSize(width: maxW, height: maxW * image.size.height / image.size.width)
|
||||
}
|
||||
let cell = NSMutableAttributedString(attachment: attachment, attributes: [
|
||||
.paragraphStyle: ps,
|
||||
])
|
||||
if !alt.isEmpty {
|
||||
cell.append(NSAttributedString(string: "\n" + alt, attributes: [
|
||||
.font: ProseTypography.codeFont,
|
||||
.foregroundColor: ProseTypography.syntaxColor,
|
||||
.paragraphStyle: ps,
|
||||
]))
|
||||
}
|
||||
return cell
|
||||
}
|
||||
|
||||
private static func flowContent(_ lines: [String], first: String) -> NSAttributedString {
|
||||
if let level = headingLevel(first) {
|
||||
let body = first.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces)
|
||||
let heading = headingContent(body, level: level)
|
||||
// Bug fix: a heading chunk may carry body lines under the heading
|
||||
// (single newline is legal markdown) — they are part of the block.
|
||||
let rest = lines.dropFirst()
|
||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
.filter { !$0.isEmpty }
|
||||
if rest.isEmpty {
|
||||
return heading
|
||||
}
|
||||
let out = NSMutableAttributedString(attributedString: heading)
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
out.append(inlineParse(rest.joined(separator: " ")))
|
||||
return out
|
||||
}
|
||||
if first.hasPrefix("```") {
|
||||
let inner = lines.dropFirst().dropLast(hasClosingFence(lines) ? 1 : 0)
|
||||
return codeContent(inner.joined(separator: "\n"))
|
||||
}
|
||||
// HR — the editing presenter's syntaxOnly matcher reused verbatim
|
||||
// (#69: same predicate both modes = one mental model).
|
||||
if ProsePresenter.lineKind(first) == .syntaxOnly {
|
||||
return hrContent()
|
||||
}
|
||||
// Paragraph: soft-join lines with single spaces, one inline parse.
|
||||
let joined = lines
|
||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
.filter { !$0.isEmpty }
|
||||
.joined(separator: " ")
|
||||
let para = inlineParse(joined)
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacing = paragraphSpacingAfter
|
||||
let styled = NSMutableAttributedString(attributedString: para)
|
||||
styled.addAttribute(.paragraphStyle, value: ps, range: NSRange(location: 0, length: styled.length))
|
||||
return styled
|
||||
}
|
||||
|
||||
private static func headingContent(_ text: String, level: Int) -> NSAttributedString {
|
||||
// #70: h1 = Headings slot size; h2 = 0.77×; ### = body+1 (≈17–18);
|
||||
// ####+ floors at bold body.
|
||||
let slotSize = ProseTypography.headingFont.pointSize
|
||||
let size: CGFloat = switch level {
|
||||
case 1: slotSize
|
||||
case 2: (slotSize * 0.77).rounded()
|
||||
case 3: ProseTypography.bodyFont.pointSize + 1
|
||||
default: ProseTypography.bodyFont.pointSize
|
||||
}
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacing = headingSpacingAfter
|
||||
ps.paragraphSpacingBefore = level == 1 ? 26 : (level == 2 ? 20 : 14)
|
||||
return NSAttributedString(string: text, attributes: [
|
||||
.font: ProseTypography.headingFont(size: size),
|
||||
.paragraphStyle: ps,
|
||||
.foregroundColor: ProseTypography.foregroundColor,
|
||||
])
|
||||
}
|
||||
|
||||
private static func codeContent(_ code: String) -> NSAttributedString {
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacing = paragraphSpacingAfter
|
||||
ps.paragraphSpacingBefore = 6
|
||||
ps.firstLineHeadIndent = 12
|
||||
ps.headIndent = 12
|
||||
return NSAttributedString(string: code, attributes: [
|
||||
.font: ProseTypography.codeFont,
|
||||
.paragraphStyle: ps,
|
||||
.foregroundColor: ProseTypography.syntaxColor,
|
||||
])
|
||||
}
|
||||
|
||||
private static func hrContent() -> NSAttributedString {
|
||||
// Hairline drawn by the canvas (Decoration.rule).
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacingBefore = 8
|
||||
ps.paragraphSpacing = 8
|
||||
return NSAttributedString(string: " ", attributes: [
|
||||
.font: ProseTypography.codeFont,
|
||||
.paragraphStyle: ps,
|
||||
.foregroundColor: NSColor.clear,
|
||||
])
|
||||
}
|
||||
|
||||
// MARK: Lists (#69: one path for bullets and ordered — the counter makes
|
||||
|
||||
// auto-renumbering free; glyphs only, the file is never rewritten)
|
||||
|
||||
private static func listContent(_ lines: [String]) -> NSAttributedString {
|
||||
let out = NSMutableAttributedString()
|
||||
var counters: [Int: Int] = [:]
|
||||
for (index, line) in lines.enumerated() {
|
||||
guard let marker = listItemMarker(line) else { continue }
|
||||
let indent: CGFloat = 16 + CGFloat(marker.level - 1) * 18
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.firstLineHeadIndent = indent
|
||||
ps.headIndent = indent + 18
|
||||
ps.paragraphSpacing = 5
|
||||
let glyph: String
|
||||
if marker.ordered {
|
||||
counters[marker.level, default: 0] += 1
|
||||
glyph = "\(counters[marker.level]!). "
|
||||
} else {
|
||||
glyph = "• "
|
||||
}
|
||||
let item = NSMutableAttributedString(string: glyph, attributes: ProseTypography.bodyAttributes)
|
||||
item.append(inlineParse(marker.payload.trimmingCharacters(in: .whitespaces)))
|
||||
item.addAttribute(
|
||||
.paragraphStyle, value: ps,
|
||||
range: NSRange(location: 0, length: item.length),
|
||||
)
|
||||
out.append(item)
|
||||
if index < lines.count - 1 {
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// MARK: Blockquotes (#69: `>` never visible, hairline rule, nesting indents)
|
||||
|
||||
private static func quoteContent(_ lines: [String]) -> NSAttributedString {
|
||||
// Hairline drawn by the canvas (Decoration.quote) — NSTextBlock
|
||||
// drawing zero-widths the line rect on modern TextKit, wrapping
|
||||
// content one character per line.
|
||||
let out = NSMutableAttributedString()
|
||||
for (index, line) in lines.enumerated() {
|
||||
let depth = blockquoteDepth(line)
|
||||
let indent = CGFloat(6 + (depth - 1) * 18)
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.firstLineHeadIndent = indent
|
||||
ps.headIndent = indent
|
||||
ps.paragraphSpacing = 4
|
||||
let styled = NSMutableAttributedString(
|
||||
attributedString: inlineParse(quoteBody(line)),
|
||||
)
|
||||
styled.addAttribute(
|
||||
.paragraphStyle, value: ps,
|
||||
range: NSRange(location: 0, length: styled.length),
|
||||
)
|
||||
out.append(styled)
|
||||
if index < lines.count - 1 {
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Payload after the `>` marker run (markers + surrounding spaces).
|
||||
private static func quoteBody(_ line: String) -> String {
|
||||
let prefix = line.prefix { $0 == ">" || $0 == " " }
|
||||
return String(line.dropFirst(prefix.count)).trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
|
||||
// MARK: Tables (#69: mono grid — plain padded text; the canvas draws the
|
||||
|
||||
// grid lines from Decoration.table. NSTextTable cannot lay out on modern
|
||||
// TextKit: rows stack vertically, columns never align.)
|
||||
|
||||
private static func tableContent(_ lines: [String]) -> NSAttributedString? {
|
||||
let header = tableCells(lines[0])
|
||||
let aligns = tableAlignments(lines[1])
|
||||
guard !header.isEmpty, header.count == aligns.count else { return nil }
|
||||
let dataRows = lines.enumerated().filter { $0.offset != 1 }.map(\.element)
|
||||
let cellTexts = ([lines[0]] + dataRows.dropFirst()).map(tableCells)
|
||||
let columnCount = header.count
|
||||
var widths = Array(repeating: 0, count: columnCount)
|
||||
for row in cellTexts {
|
||||
for (column, cell) in row.enumerated() where column < columnCount {
|
||||
widths[column] = max(widths[column], cell.count)
|
||||
}
|
||||
}
|
||||
let pad = 3
|
||||
let codeAttrs: [NSAttributedString.Key: Any] = [
|
||||
.font: ProseTypography.codeFont,
|
||||
.foregroundColor: ProseTypography.foregroundColor,
|
||||
]
|
||||
let out = NSMutableAttributedString()
|
||||
func gridLine(_ cells: [String]) -> NSAttributedString {
|
||||
var line = ""
|
||||
for column in 0 ..< columnCount {
|
||||
let text = column < cells.count ? cells[column] : ""
|
||||
let width = widths[column]
|
||||
let padded: String
|
||||
switch aligns[column] {
|
||||
case .center where text.count < width:
|
||||
let left = (width - text.count) / 2
|
||||
padded = String(repeating: " ", count: left) + text
|
||||
+ String(repeating: " ", count: width - text.count - left)
|
||||
case .right:
|
||||
padded = String(repeating: " ", count: max(0, width - text.count)) + text
|
||||
default:
|
||||
padded = text + String(repeating: " ", count: max(0, width - text.count))
|
||||
// advance line count over the chunk + the blank separator run
|
||||
var index = loc
|
||||
while index < end {
|
||||
if ns.character(at: index) == 0x0A {
|
||||
line += 1
|
||||
}
|
||||
line += String(repeating: " ", count: pad) + padded + String(repeating: " ", count: pad)
|
||||
index += 1
|
||||
}
|
||||
return NSAttributedString(string: line, attributes: codeAttrs)
|
||||
}
|
||||
out.append(gridLine(cellTexts[0]))
|
||||
for row in cellTexts.dropFirst() {
|
||||
out.append(NSAttributedString(string: "\n", attributes: codeAttrs))
|
||||
out.append(gridLine(row))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Quote decoration: left hairline at the shallowest quote indent.
|
||||
private static func quoteDecoration(_ lines: [String]) -> Decoration {
|
||||
let minIndent = lines.compactMap { line -> CGFloat? in
|
||||
blockquoteDepth(line) > 0 ? CGFloat(6 + (blockquoteDepth(line) - 1) * 18) : nil
|
||||
}.min() ?? 6
|
||||
return .quote(indent: minIndent)
|
||||
}
|
||||
|
||||
/// Table decoration: column x-offsets (+ closing edge) in mono advance.
|
||||
private static func tableDecoration(_ lines: [String]) -> Decoration {
|
||||
let header = tableCells(lines[0])
|
||||
let dataRows = lines.enumerated().filter { $0.offset != 1 }.map(\.element)
|
||||
let cellTexts = ([lines[0]] + dataRows.dropFirst()).map(tableCells)
|
||||
var widths = Array(repeating: 0, count: header.count)
|
||||
for row in cellTexts {
|
||||
for (column, cell) in row.enumerated() where column < header.count {
|
||||
widths[column] = max(widths[column], cell.count)
|
||||
if delim.location == NSNotFound {
|
||||
break
|
||||
}
|
||||
}
|
||||
let advance = ("0" as NSString).size(withAttributes: [
|
||||
.font: ProseTypography.codeFont,
|
||||
]).width
|
||||
var offsets: [CGFloat] = []
|
||||
var running = 0.0
|
||||
for width in widths {
|
||||
offsets.append(running)
|
||||
running += CGFloat(width + 6) * advance // cell pad 3 + 3, matches gridLine
|
||||
}
|
||||
return .table(columns: offsets + [running])
|
||||
}
|
||||
|
||||
private static func tableCells(_ line: String) -> [String] {
|
||||
var trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||
if trimmed.hasPrefix("|") {
|
||||
trimmed.removeFirst()
|
||||
}
|
||||
if trimmed.hasSuffix("|") {
|
||||
trimmed.removeLast()
|
||||
}
|
||||
return trimmed.components(separatedBy: "|").map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
}
|
||||
|
||||
private static func tableAlignments(_ delimiter: String) -> [NSTextAlignment] {
|
||||
tableCells(delimiter).map { cell in
|
||||
let left = cell.hasPrefix(":")
|
||||
let right = cell.hasSuffix(":")
|
||||
if left == right {
|
||||
return left ? .center : .left
|
||||
} // --- = left, :---: = center
|
||||
return left ? .left : .right
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Inline (#69: marker glyphs never show; links styled + retained)
|
||||
|
||||
/// One `AttributedString(markdown:)` parse, presentation-interpreted:
|
||||
/// emphasis/strong → italic/bold body face, code spans → code face,
|
||||
/// links styled + kept for ⌘-click.
|
||||
static func inlineParse(_ raw: String) -> NSAttributedString {
|
||||
var opts = AttributedString.MarkdownParsingOptions()
|
||||
opts.interpretedSyntax = .inlineOnlyPreservingWhitespace
|
||||
guard let parsed = try? AttributedString(markdown: raw, options: opts) else {
|
||||
return NSAttributedString(string: raw, attributes: ProseTypography.bodyAttributes)
|
||||
}
|
||||
let out = NSMutableAttributedString()
|
||||
for run in parsed.runs {
|
||||
var attrs = ProseTypography.bodyAttributes
|
||||
if let intent = run.inlinePresentationIntent {
|
||||
if intent.contains(.code) {
|
||||
attrs = ProseTypography.codeAttributes
|
||||
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 {
|
||||
var font = ProseTypography.bodyFont
|
||||
if intent.contains(.emphasized) {
|
||||
font = ProseTypography.italicBodyFont
|
||||
}
|
||||
if intent.contains(.stronglyEmphasized) {
|
||||
font = ProseTypography.boldBodyFont
|
||||
}
|
||||
attrs[.font] = font
|
||||
break
|
||||
}
|
||||
}
|
||||
if let link = run.link {
|
||||
attrs[.link] = link
|
||||
attrs[.underlineStyle] = NSUnderlineStyle.single.rawValue
|
||||
attrs[.cursor] = NSCursor.pointingHand
|
||||
}
|
||||
out.append(NSAttributedString(
|
||||
string: String(parsed[run.range].characters),
|
||||
attributes: attrs,
|
||||
))
|
||||
loc = scan
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Alt text of an `` chunk (empty when absent).
|
||||
private static func altText(in chunk: String) -> String {
|
||||
let trimmed = chunk.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard trimmed.hasPrefix("!["), let closeBracket = trimmed.firstIndex(of: "]") else { return "" }
|
||||
return String(trimmed[trimmed.index(trimmed.startIndex, offsetBy: 2) ..< closeBracket])
|
||||
}
|
||||
|
||||
// MARK: Construct matchers
|
||||
|
||||
private struct ListMarker {
|
||||
let level: Int
|
||||
let ordered: Bool
|
||||
let payload: String
|
||||
}
|
||||
|
||||
/// `- `/`* ` bullet or `N.`/`N)` ordered marker. Indent levels: 0–1 sp → 1,
|
||||
/// 2–3 sp → 2, 4+ sp → 3+ (2-space and 4-space styles both accepted, #69).
|
||||
private static func listItemMarker(_ line: String) -> ListMarker? {
|
||||
let indent = line.prefix { $0 == " " }.count
|
||||
let rest = line.dropFirst(indent)
|
||||
if rest.hasPrefix("- ") || rest.hasPrefix("* ") {
|
||||
return ListMarker(level: indentLevel(indent), ordered: false, payload: String(rest.dropFirst(2)))
|
||||
/// 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 = { (line: Substring) in line.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
|
||||
let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
|
||||
var out: [String] = []
|
||||
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
|
||||
}
|
||||
}
|
||||
let digits = rest.prefix { $0.isNumber }.count
|
||||
guard digits > 0 else { return nil }
|
||||
let after = rest.dropFirst(digits)
|
||||
guard after.hasPrefix(". ") || after.hasPrefix(") ") else { return nil }
|
||||
return ListMarker(level: indentLevel(indent), ordered: true, payload: String(after.dropFirst(2)))
|
||||
return out.joined(separator: "\n")
|
||||
}
|
||||
|
||||
private static func indentLevel(_ spaces: Int) -> Int {
|
||||
spaces <= 1 ? 1 : (spaces <= 3 ? 2 : min(3 + (spaces - 4) / 2, 6))
|
||||
/// 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 {
|
||||
// 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
|
||||
}
|
||||
|
||||
/// `>`-prefix depth (1 for `> `, 2 for `>> `; spaces tolerated).
|
||||
private static func blockquoteDepth(_ line: String) -> Int {
|
||||
line.prefix { $0 == ">" || $0 == " " }.filter { $0 == ">" }.count
|
||||
}
|
||||
// MARK: Apex runner (bundled binary, ADR-0011)
|
||||
|
||||
/// `# `-style heading with its level; requires a space after the hashes
|
||||
/// (so prose like `#hashtag` stays a paragraph).
|
||||
private static func headingLevel(_ line: String) -> Int? {
|
||||
let trimmed = line.drop { $0 == " " }
|
||||
let hashes = trimmed.prefix { $0 == "#" }.count
|
||||
guard hashes >= 1, hashes <= 6 else { return nil }
|
||||
let after = trimmed.dropFirst(hashes)
|
||||
return after.hasPrefix(" ") || after.isEmpty ? hashes : nil
|
||||
}
|
||||
|
||||
/// `| --- | :---: |` delimiter row under a header row.
|
||||
private static func isTableDelimiterRow(_ line: String) -> Bool {
|
||||
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||
guard trimmed.hasPrefix("|"), trimmed.hasSuffix("|"), trimmed.count >= 4 else { return false }
|
||||
let cells = tableCells(trimmed)
|
||||
return !cells.isEmpty && cells.allSatisfy { cell in
|
||||
!cell.isEmpty && cell.allSatisfy { $0 == "-" || $0 == ":" }
|
||||
/// Locate apex: bundle resource first, then `APEX_PATH` override, then a
|
||||
/// Homebrew install (dev machines). A renderer must not grow a gate.
|
||||
static func apexBinaryPath() -> String? {
|
||||
if let bundlePath = Bundle.main.path(forResource: "apex", ofType: nil) {
|
||||
return bundlePath
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
private static func hasClosingFence(_ lines: [String]) -> Bool {
|
||||
guard let last = lines.last else { return false }
|
||||
return last.trimmingCharacters(in: .whitespaces).hasPrefix("```")
|
||||
/// markdown → HTML fragment. `--embed-images` + `--base-dir` inline
|
||||
/// images as base64 (loadHTMLString then needs no file access; nothing
|
||||
/// is written into the vault). `--no-mixed-lists` is REQUIRED
|
||||
/// (ADR-0011): apex's default merges an ordered list after bullets into
|
||||
/// one `<ul>`, killing `1. 1. 1.` renumbering.
|
||||
static func apexRender(_ markdown: String, baseDir: URL?) throws -> String {
|
||||
guard let bin = apexBinaryPath() else {
|
||||
throw CocoaError(.fileNoSuchFile)
|
||||
}
|
||||
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]
|
||||
}
|
||||
process.arguments = args
|
||||
let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
|
||||
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 {
|
||||
process.waitUntilExit()
|
||||
throw NSError(
|
||||
domain: "apex",
|
||||
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).
|
||||
process.terminationHandler = { _ in }
|
||||
return String(decoding: data, as: UTF8.self)
|
||||
}
|
||||
|
||||
/// `` → url when the chunk is exactly one image line (#69: the
|
||||
/// inline parser renders image syntax as bare alt text with no link
|
||||
/// attribute, so the URL is recovered at chunk level).
|
||||
private static func imageURL(in chunk: String) -> URL? {
|
||||
let trimmed = chunk.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard trimmed.hasPrefix("![") else { return nil }
|
||||
guard let closeBracket = trimmed.firstIndex(of: "]") else { return nil }
|
||||
let afterBracket = trimmed.index(after: closeBracket)
|
||||
guard afterBracket < trimmed.endIndex, trimmed[afterBracket] == "(" else { return nil }
|
||||
let start = trimmed.index(after: afterBracket)
|
||||
guard let closeParen = trimmed[start...].firstIndex(of: ")") else { return nil }
|
||||
return URL(string: String(trimmed[start ..< closeParen]))
|
||||
// MARK: Page assembly
|
||||
|
||||
/// The reading stylesheet, read fresh per page build (#72 rework): the
|
||||
/// CSS lives in Resources/reading.css so the look is editable while the
|
||||
/// app runs — save the file, toggle reading (⌘R), see it. ~3 KB read =
|
||||
/// microseconds against the ~20 ms apex spawn next to it.
|
||||
/// Debug builds prefer the REPO copy (`#filePath` points into the
|
||||
/// checkout) so CSS edits apply with no rebuild; release builds ship the
|
||||
/// bundled copy (`#filePath` is stripped in release, so this resolves to
|
||||
/// the bundle without any config).
|
||||
static func styleSheet() -> String {
|
||||
#if DEBUG
|
||||
let repoCSS = URL(fileURLWithPath: #filePath) // …/Museion/ReadingPresenter.swift
|
||||
.deletingLastPathComponent()
|
||||
.appendingPathComponent("Resources/reading.css")
|
||||
if let live = try? String(contentsOf: repoCSS, encoding: .utf8), !live.isEmpty {
|
||||
return live
|
||||
}
|
||||
#endif
|
||||
return Bundle.main.path(forResource: "reading", ofType: "css").flatMap {
|
||||
try? String(contentsOf: URL(fileURLWithPath: $0), encoding: .utf8)
|
||||
} ?? ""
|
||||
}
|
||||
|
||||
/// Render `text` to a full page: chunk-sentinels → apex → attribute
|
||||
/// restamp → style-injected shell. `postFolder` resolves relative images
|
||||
/// (nil = drafts: relative paths stay raw, missing images fail soft).
|
||||
static func page(for text: String, postFolder: URL?) -> (html: String, blocks: [Block]) {
|
||||
let blocks = blocks(for: text)
|
||||
guard let fragment = try? apexRender(stampSource(text), baseDir: postFolder) else {
|
||||
return (fallbackPage(text), blocks)
|
||||
}
|
||||
return (page(stampHTML(fragment)), blocks)
|
||||
}
|
||||
|
||||
/// Wrap a stamped fragment into the page shell with the live stylesheet.
|
||||
static func page(_ stampedFragment: String) -> String {
|
||||
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head><body>\(stampedFragment)</body></html>"
|
||||
}
|
||||
|
||||
/// apex failure / missing binary → editing-treated source text (#69's
|
||||
/// fallback rule: fallback = the source, not a second renderer).
|
||||
static func fallbackPage(_ text: String) -> String {
|
||||
"<!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(_ text: String) -> String {
|
||||
text.replacingOccurrences(of: "&", with: "&")
|
||||
.replacingOccurrences(of: "<", with: "<")
|
||||
.replacingOccurrences(of: ">", with: ">")
|
||||
}
|
||||
}
|
||||
+156
-293
@@ -2,16 +2,20 @@
|
||||
// ReadingSurface.swift
|
||||
// Museion
|
||||
//
|
||||
// #71 (S1.2, map #20): the reading-mode surface — the renderer's blocks set
|
||||
// into a read-only, selectable NSTextView (#68: reading is a presentation
|
||||
// of the same TextKit2 document, not a separate view stack). Interaction
|
||||
// per #68: drag-select stays native; a tap with no selection = edit intent
|
||||
// (drop to editing at the clicked block's source paragraph); ⌘-click opens
|
||||
// links; hovering an image block pops the loaded image (#69 floor).
|
||||
// #76 (S1.2, map #20; ADR-0011): the reading surface is one WKWebView,
|
||||
// reloaded in place — never remounted per document (the remount was the
|
||||
// dominant switch cost, #74). Loads ReadingPresenter's page (apex HTML +
|
||||
// data-source-line map). Interaction per #68: tap = edit intent at the
|
||||
// tapped block's source paragraph; ⌘-click opens links; scroll tracking
|
||||
// feeds the flip-back map. Typography/flow changes reload the page (CSS
|
||||
// vars are injected at load). The TextKit canvas (ReadingCanvasView,
|
||||
// decorations, framesForRange, ImagePopoverView) is deleted with the
|
||||
// pivot — ADR-0011: no fallbacks.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import WebKit
|
||||
|
||||
/// Live reading-position state for flip-back scroll mapping (#68). Plain
|
||||
/// class held `@State` by the editor — reference identity survives renders.
|
||||
@@ -31,320 +35,179 @@ final class CaretHintBox {
|
||||
var consumed = true
|
||||
}
|
||||
|
||||
/// Reading surface: renders `text` via ReadingPresenter into a scrollable,
|
||||
/// read-only canvas. Rebuilds when `generation` moves (open / Yes-reload) or
|
||||
/// the text genuinely changes (draft edit path).
|
||||
/// Reading surface: renders `text` via ReadingPresenter (apex HTML) into a
|
||||
/// WKWebView reloaded in place. Re-renders when `generation` moves (open /
|
||||
/// Yes-reload), the text changes (draft path), or flow knobs move — never
|
||||
/// per keystroke.
|
||||
struct ReadingSurface: NSViewRepresentable {
|
||||
let text: String
|
||||
/// Session loadGeneration (0 for drafts) — rebuild key, never per keystroke.
|
||||
var generation: Int
|
||||
/// The post's folder — resolves relative image URLs. Nil for drafts.
|
||||
/// The post's folder — resolves relative image URLs (apex --base-dir).
|
||||
/// Nil for drafts.
|
||||
var postFolder: URL?
|
||||
/// UTF-16 caret location captured when reading opened; scrolls the
|
||||
/// containing block to the top (#68 mapping attempt).
|
||||
/// UTF-16 caret location captured when reading opened; scrolls that
|
||||
/// block to the top (#68 mapping attempt).
|
||||
var entryCaretLocation: Int?
|
||||
var onEditIntent: (Int) -> Void
|
||||
/// Flip-back scroll mapping target.
|
||||
var stateBox: ReadingStateBox?
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let tv = ReadingCanvasView()
|
||||
tv.isEditable = false
|
||||
tv.isSelectable = true
|
||||
tv.isRichText = false
|
||||
tv.allowsUndo = false
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.backgroundColor = NSColor.white
|
||||
tv.typingAttributes = ProseTypography.bodyAttributes
|
||||
tv.minSize = NSSize(width: 0, height: 0)
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.isVerticallyResizable = true
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.autoresizingMask = [.width]
|
||||
// Wrap to the editor column (#68/71 fix): the container tracks the
|
||||
// view width — a fixed 640pt measure clipped in narrower columns.
|
||||
tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.textContainer?.widthTracksTextView = true
|
||||
tv.textContainer?.lineFragmentPadding = 24
|
||||
tv.textContainerInset = NSSize(width: 0, height: 24)
|
||||
let scroll = NSScrollView()
|
||||
scroll.documentView = tv
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.autohidesScrollers = true
|
||||
scroll.drawsBackground = true
|
||||
scroll.backgroundColor = NSColor.white
|
||||
tv.onEditIntent = onEditIntent
|
||||
tv.stateBox = stateBox
|
||||
context.coordinator.canvas = tv
|
||||
context.coordinator.watchDefaults(tv, representable: self)
|
||||
return scroll
|
||||
}
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let tv = scroll.documentView as? ReadingCanvasView else { return }
|
||||
tv.onEditIntent = onEditIntent
|
||||
tv.stateBox = stateBox
|
||||
tv.postFolder = postFolder
|
||||
guard context.coordinator.builtGeneration != generation || context.coordinator.builtText != text else { return }
|
||||
context.coordinator.builtGeneration = generation
|
||||
context.coordinator.builtText = text
|
||||
let doc = ReadingPresenter.document(for: text, resolvingImagesIn: postFolder)
|
||||
tv.textStorage?.setAttributedString(doc.content)
|
||||
tv.blockBounds = doc.bounds
|
||||
tv.needsLayout = true
|
||||
tv.layoutSubtreeIfNeeded()
|
||||
if let caret = entryCaretLocation, let bound = tv.bound(containing: caret) {
|
||||
tv.scrollRangeToVisible(NSRange(location: bound.docRange.location, length: 0))
|
||||
} else {
|
||||
tv.scroll(NSPoint(x: 0, y: 0))
|
||||
}
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator()
|
||||
}
|
||||
|
||||
final class Coordinator {
|
||||
weak var canvas: ReadingCanvasView?
|
||||
var builtGeneration = -1
|
||||
var builtText = ""
|
||||
private var defaultsObserver: NSObjectProtocol?
|
||||
private var appliedFlowKey = ""
|
||||
func makeNSView(context: Context) -> WKWebView {
|
||||
let cfg = WKWebViewConfiguration()
|
||||
let ucc = cfg.userContentController
|
||||
ucc.addUserScript(WKUserScript(source: Self.probeJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
|
||||
ucc.add(context.coordinator, name: "sourceClick")
|
||||
ucc.add(context.coordinator, name: "sourceScroll")
|
||||
ucc.add(context.coordinator, name: "openLink")
|
||||
let wv = WKWebView(frame: .zero, configuration: cfg)
|
||||
wv.navigationDelegate = context.coordinator
|
||||
// Paint the page bg while loading instead of AppKit white (flash fix, #74).
|
||||
wv.underPageBackgroundColor = NSColor(red: 0.984, green: 0.984, blue: 0.992, alpha: 1)
|
||||
context.coordinator.webView = wv
|
||||
return wv
|
||||
}
|
||||
|
||||
/// Rebuild the rendered document when typography/flow knobs move
|
||||
/// (SwiftUI doesn't re-call updateNSView on UserDefaults writes).
|
||||
func watchDefaults(_: ReadingCanvasView, representable: ReadingSurface) {
|
||||
guard defaultsObserver == nil else { return }
|
||||
appliedFlowKey = ProseTypography.flowKey
|
||||
defaultsObserver = NotificationCenter.default.addObserver(
|
||||
forName: UserDefaults.didChangeNotification,
|
||||
object: nil,
|
||||
queue: .main,
|
||||
) { [weak self] _ in
|
||||
guard let self, let canvas else { return }
|
||||
let key = ProseTypography.flowKey
|
||||
guard key != appliedFlowKey else { return }
|
||||
appliedFlowKey = key
|
||||
let doc = ReadingPresenter.document(for: representable.text, resolvingImagesIn: representable.postFolder)
|
||||
canvas.textStorage?.setAttributedString(doc.content)
|
||||
canvas.blockBounds = doc.bounds
|
||||
canvas.needsDisplay = true
|
||||
func updateNSView(_: WKWebView, context: Context) {
|
||||
let coordinator = context.coordinator
|
||||
coordinator.onEditIntent = onEditIntent
|
||||
coordinator.stateBox = stateBox
|
||||
coordinator.postFolder = postFolder
|
||||
let key = "\(generation):\(text.hashValue)"
|
||||
guard coordinator.loadedKey != key else { return }
|
||||
coordinator.load(text: text, generation: generation, entryCaret: entryCaretLocation, key: key)
|
||||
}
|
||||
|
||||
/// Mapping probes: click → source line; ⌘-click → open; scroll → top
|
||||
/// visible source line (same map → scroll-sync). Spike-verified (#74).
|
||||
static let probeJS = """
|
||||
function stamped(el){ return el.closest('[data-source-line]'); }
|
||||
document.addEventListener('click', function(e){
|
||||
const a = e.target.closest('a');
|
||||
if (a) {
|
||||
e.preventDefault(); // reading never navigates in-app
|
||||
if (e.metaKey || e.ctrlKey) window.webkit.messageHandlers.openLink.postMessage(a.href);
|
||||
else { const s = stamped(a); if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine); }
|
||||
return;
|
||||
}
|
||||
const s = stamped(e.target);
|
||||
if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine);
|
||||
}, true);
|
||||
let ticking = false;
|
||||
addEventListener('scroll', function(){
|
||||
if (ticking) return; ticking = true;
|
||||
requestAnimationFrame(function(){
|
||||
ticking = false;
|
||||
for (const el of document.querySelectorAll('[data-source-line]')) {
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.bottom > 44) { window.webkit.messageHandlers.sourceScroll.postMessage(el.dataset.sourceLine); return; }
|
||||
}
|
||||
});
|
||||
}, {passive: true});
|
||||
"""
|
||||
|
||||
/// Scroll the entry block to the top after paint (#68 entry mapping).
|
||||
static func entryScrollJS(_ line: Int) -> String {
|
||||
"""
|
||||
(function(line){
|
||||
for (const el of document.querySelectorAll('[data-source-line]')) {
|
||||
if (parseInt(el.dataset.sourceLine) === line) {
|
||||
window.scrollTo(0, el.getBoundingClientRect().top + window.scrollY - 24);
|
||||
return;
|
||||
}
|
||||
}
|
||||
})(\(line));
|
||||
"""
|
||||
}
|
||||
|
||||
// @MainActor: WKNavigationDelegate + WKScriptMessageHandler requirements
|
||||
// are MainActor in the SDK; the project is default-MainActor anyway.
|
||||
@MainActor
|
||||
final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
|
||||
weak var webView: WKWebView?
|
||||
var onEditIntent: ((Int) -> Void)?
|
||||
var stateBox: ReadingStateBox?
|
||||
var postFolder: URL?
|
||||
var loadedKey = ""
|
||||
/// Block map of the loaded page (source line + range).
|
||||
var blocks: [ReadingPresenter.Block] = []
|
||||
/// Line to scroll to once the page paints (entry mapping, #68).
|
||||
var pendingEntryScrollLine: Int?
|
||||
var painted = false
|
||||
private var lastText = ""
|
||||
|
||||
/// Build + load the page for `text`. All render paths land here
|
||||
/// (updateNSView, typography-change reload).
|
||||
func load(text: String, generation _: Int, entryCaret: Int?, key: String) {
|
||||
loadedKey = key
|
||||
lastText = text
|
||||
painted = false
|
||||
let (pageHTML, blockMap) = ReadingPresenter.page(for: text, postFolder: postFolder)
|
||||
blocks = blockMap
|
||||
pendingEntryScrollLine = entryLine(for: entryCaret)
|
||||
webView?.loadHTMLString(pageHTML, baseURL: nil)
|
||||
}
|
||||
|
||||
/// The block whose source range holds the caret; else the next block
|
||||
/// at/after it (#68: jank fallback = top of page via nil).
|
||||
private func entryLine(for caret: Int?) -> Int? {
|
||||
guard let caret else { return nil }
|
||||
if let hit = blocks.first(where: { NSLocationInRange(caret, $0.sourceRange) }) {
|
||||
return hit.sourceLine
|
||||
}
|
||||
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reading canvas: click discrimination, ⌘-click links, image hover
|
||||
/// popover, top-block scroll tracking. Read-only over rendered content.
|
||||
final class ReadingCanvasView: NSTextView {
|
||||
typealias BlockBound = ReadingPresenter.Bound
|
||||
|
||||
var blockBounds: [BlockBound] = []
|
||||
var onEditIntent: ((Int) -> Void)?
|
||||
var stateBox: ReadingStateBox?
|
||||
var postFolder: URL?
|
||||
// MARK: WKNavigationDelegate
|
||||
|
||||
private var popover: NSPopover?
|
||||
private var hoverTrackingArea: NSTrackingArea?
|
||||
|
||||
/// Last bound starting at or before `index` (spacing separators clamp to
|
||||
/// the preceding block).
|
||||
func bound(containing index: Int) -> BlockBound? {
|
||||
blockBounds.last { $0.docRange.location <= index }
|
||||
}
|
||||
|
||||
// MARK: Decorations (#69 fix: quote hairlines, HR rules, table grids —
|
||||
|
||||
// drawn from measured TK2 fragment geometry; NSTextBlock/NSTextTable
|
||||
// layout is broken on modern TextKit and the TK1-compat bridge reports
|
||||
// wrong rects. Enumeration pattern is probe-proven: walk ALL fragments
|
||||
// from document start, map each to a doc offset, slice per bound.)
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
super.draw(dirtyRect)
|
||||
let origin = textContainerOrigin
|
||||
for bound in blockBounds {
|
||||
guard let decoration = bound.decoration else { continue }
|
||||
// frames arrive in CONTAINER space; the view draws text at
|
||||
// textContainerOrigin + frame (inset shifts it — the missing
|
||||
// +origin.y drew every decoration 20pt too high).
|
||||
let frames = framesForRange(bound.docRange)
|
||||
.map { CGRect(x: $0.minX + origin.x, y: $0.minY + origin.y, width: $0.width, height: $0.height) }
|
||||
guard let firstFrame = frames.first, let lastFrame = frames.last else { continue }
|
||||
switch decoration {
|
||||
case let .quote(indent):
|
||||
let x = (textContainer?.lineFragmentPadding ?? 0) + indent - 6
|
||||
let path = NSBezierPath()
|
||||
path.move(to: NSPoint(x: x, y: firstFrame.minY))
|
||||
path.line(to: NSPoint(x: x, y: lastFrame.maxY))
|
||||
path.lineWidth = 2
|
||||
ProseTypography.quoteRuleColor.setStroke()
|
||||
path.stroke()
|
||||
case .rule:
|
||||
let y = (firstFrame.minY + firstFrame.maxY) / 2
|
||||
let path = NSBezierPath()
|
||||
path.move(to: NSPoint(x: 0, y: y))
|
||||
path.line(to: NSPoint(x: (textContainer?.size.width ?? 0), y: y))
|
||||
path.lineWidth = 1
|
||||
ProseTypography.tableBorderColor.setStroke()
|
||||
path.stroke()
|
||||
case let .table(columns):
|
||||
let originX = (textContainer?.lineFragmentPadding ?? 0)
|
||||
let path = NSBezierPath()
|
||||
for offset in columns {
|
||||
let x = originX + offset
|
||||
path.move(to: NSPoint(x: x, y: firstFrame.minY))
|
||||
path.line(to: NSPoint(x: x, y: lastFrame.maxY))
|
||||
}
|
||||
let ys = [firstFrame.minY] + frames.map(\.maxY)
|
||||
for y in ys {
|
||||
path.move(to: NSPoint(x: originX, y: y))
|
||||
path.line(to: NSPoint(x: originX + (columns.last ?? 0), y: y))
|
||||
}
|
||||
path.lineWidth = 1
|
||||
ProseTypography.tableBorderColor.setStroke()
|
||||
path.stroke()
|
||||
}
|
||||
func webView(_ wv: WKWebView, didFinish _: WKNavigation!) {
|
||||
guard !painted else { return }
|
||||
painted = true
|
||||
guard let line = pendingEntryScrollLine else { return }
|
||||
pendingEntryScrollLine = nil
|
||||
wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line))
|
||||
}
|
||||
}
|
||||
|
||||
/// Line frames for a document character range, engine-agnostic: TK2
|
||||
/// fragments when present, else TK1 boundingRect per character line
|
||||
/// (lineFragmentRect returns degenerate rects mid-layout on TK1 here).
|
||||
func framesForRange(_ docRange: NSRange) -> [CGRect] {
|
||||
if let tlm = textLayoutManager, let tcm = tlm.textContentManager {
|
||||
let docStart = tcm.documentRange.location
|
||||
var frames: [CGRect] = []
|
||||
tlm.enumerateTextLayoutFragments(from: docStart) { fragment in
|
||||
let tr = fragment.rangeInElement
|
||||
let loc = tcm.offset(from: docStart, to: tr.location)
|
||||
let len = tcm.offset(from: tr.location, to: tr.endLocation)
|
||||
if NSIntersectionRange(NSRange(location: loc, length: len), docRange).length > 0 {
|
||||
frames.append(fragment.layoutFragmentFrame)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return frames
|
||||
}
|
||||
guard let layoutManager, let container = textContainer else { return [] }
|
||||
let nsText = string as NSString
|
||||
var frames: [CGRect] = []
|
||||
var lineStart = docRange.location
|
||||
while lineStart < NSMaxRange(docRange) {
|
||||
let lineRange = nsText.lineRange(for: NSRange(location: lineStart, length: 0))
|
||||
let clamped = NSIntersectionRange(lineRange, docRange)
|
||||
guard clamped.length > 0 else { break }
|
||||
let glyphRange = layoutManager.glyphRange(forCharacterRange: clamped, actualCharacterRange: nil)
|
||||
frames.append(layoutManager.boundingRect(forGlyphRange: glyphRange, in: container))
|
||||
lineStart = NSMaxRange(lineRange)
|
||||
}
|
||||
return frames
|
||||
}
|
||||
|
||||
override func updateTrackingAreas() {
|
||||
super.updateTrackingAreas()
|
||||
if hoverTrackingArea == nil {
|
||||
let area = NSTrackingArea(
|
||||
rect: bounds, options: [.mouseMoved, .activeAlways, .inVisibleRect],
|
||||
owner: self, userInfo: nil,
|
||||
)
|
||||
addTrackingArea(area)
|
||||
hoverTrackingArea = area
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Click discrimination (#68)
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
let point = convert(event.locationInWindow, from: nil)
|
||||
if event.modifierFlags.contains(.command) {
|
||||
let index = characterIndex(for: point)
|
||||
if index != NSNotFound, let url = textStorage?.attribute(.link, at: index, effectiveRange: nil) as? URL {
|
||||
NSWorkspace.shared.open(url)
|
||||
/// Allow our own loadHTMLString main-frame load (about:blank); a
|
||||
/// blanket .cancel would kill the page before it paints. Everything
|
||||
/// else is cancelled — reading never navigates in-app (#74 lesson).
|
||||
func webView(
|
||||
_: WKWebView,
|
||||
decidePolicyFor nav: WKNavigationAction,
|
||||
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void,
|
||||
) {
|
||||
if nav.targetFrame?.isMainFrame == true,
|
||||
let url = nav.request.url, url.scheme == "file" || url.absoluteString == "about:blank"
|
||||
{
|
||||
decisionHandler(.allow)
|
||||
return
|
||||
}
|
||||
decisionHandler(.cancel)
|
||||
}
|
||||
super.mouseDown(with: event)
|
||||
// NSTextView's mouseDown consumes the mouse-up in its own tracking
|
||||
// loop — the click is complete once super returns. Tap = single
|
||||
// click, no drag, no selection formed (#68: drag-select never
|
||||
// registers; triple-click paragraph select has length > 0).
|
||||
let upScreen = NSEvent.mouseLocation
|
||||
let upWindow = window.map { $0.convertFromScreen(NSRect(origin: upScreen, size: .zero)).origin }
|
||||
?? event.locationInWindow
|
||||
let downWindow = event.locationInWindow
|
||||
let moved = hypot(upWindow.x - downWindow.x, upWindow.y - downWindow.y)
|
||||
guard event.clickCount == 1, moved < 4, selectedRange().length == 0 else { return }
|
||||
let index = characterIndex(for: point)
|
||||
guard index != NSNotFound, let bound = bound(containing: index) else { return }
|
||||
onEditIntent?(bound.sourceRange.location)
|
||||
}
|
||||
|
||||
// MARK: Scroll tracking (#68 flip-back mapping)
|
||||
// MARK: WKScriptMessageHandler — the source map in action
|
||||
|
||||
override func reflectScrolledClipView(_ clipView: NSClipView) {
|
||||
super.reflectScrolledClipView(clipView)
|
||||
let visible = NSPoint(x: 0, y: visibleRect.minY + 1)
|
||||
let index = characterIndex(for: visible)
|
||||
if index != NSNotFound, let bound = bound(containing: index) {
|
||||
stateBox?.topSourceLocation = bound.sourceRange.location
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Image hover popover (#69 floor)
|
||||
|
||||
override func mouseMoved(with event: NSEvent) {
|
||||
super.mouseMoved(with: event)
|
||||
let point = convert(event.locationInWindow, from: nil)
|
||||
let index = characterIndex(for: point)
|
||||
guard index != NSNotFound, let bound = bound(containing: index), let url = bound.imageURL else {
|
||||
popover?.close()
|
||||
popover = nil
|
||||
return
|
||||
}
|
||||
guard popover == nil else { return }
|
||||
let pop = NSPopover()
|
||||
pop.behavior = .transient
|
||||
pop.contentViewController = NSHostingController(rootView: ImagePopoverView(url: url))
|
||||
pop.contentSize = NSSize(width: 480, height: 360)
|
||||
pop.show(relativeTo: CGRect(origin: point, size: NSSize(width: 1, height: 1)), of: self, preferredEdge: .maxY)
|
||||
popover = pop
|
||||
}
|
||||
|
||||
override func mouseExited(with event: NSEvent) {
|
||||
super.mouseExited(with: event)
|
||||
popover?.close()
|
||||
popover = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The hover popover's content: loads the image off-main, scaled to fit.
|
||||
private struct ImagePopoverView: View {
|
||||
let url: URL
|
||||
@State private var image: NSImage?
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if let image {
|
||||
Image(nsImage: image)
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
} else {
|
||||
ProgressView()
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 480, maxHeight: 360)
|
||||
.task {
|
||||
// Data off-main (Sendable); NSImage decoded on-main.
|
||||
let data = await Task.detached(priority: .userInitiated) {
|
||||
try? Data(contentsOf: url)
|
||||
}.value
|
||||
if let data {
|
||||
image = NSImage(data: data)
|
||||
func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
|
||||
switch message.name {
|
||||
case "openLink":
|
||||
if let body = message.body as? String, let url = URL(string: body) {
|
||||
NSWorkspace.shared.open(url)
|
||||
}
|
||||
case "sourceClick", "sourceScroll":
|
||||
guard let body = message.body as? String, let line = Int(body),
|
||||
let block = blocks.first(where: { $0.sourceLine == line }) else { return }
|
||||
if message.name == "sourceClick" {
|
||||
onEditIntent?(block.sourceRange.location)
|
||||
} else {
|
||||
stateBox?.topSourceLocation = block.sourceRange.location
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1,80 @@
|
||||
/* Museion reading mode — the whole reading surface's look lives here.
|
||||
Edit while the app runs: save, toggle reading mode (⌘R), see it. No rebuild.
|
||||
Shipped via fs-sync at Museion/Resources/reading.css; read per page build. */
|
||||
|
||||
:root {
|
||||
--body-face: "Valkyrie OT", Georgia, serif;
|
||||
--body-size: 17px;
|
||||
--headings-face: "Concourse OT", Georgia, serif;
|
||||
--headings-size: 26px;
|
||||
--code-face: "UbuntuMono Nerd Font Mono", UbuntuMonoNFM, monospace;
|
||||
--code-size: 14px;
|
||||
--lh: 1.8;
|
||||
--para-space: 17px;
|
||||
--head-space-before: 90px; /* above a heading — closes the previous section */
|
||||
--head-space-after: 30px; /* below a heading — before its content */
|
||||
--measure: 66ch;
|
||||
--ink: #1d1d1f; --muted: #6e6e73; --secondary: #48484d;
|
||||
--hairline: #d2d2d7; --rule: #a1a1a6; --substrate: #f5f5f7;
|
||||
}
|
||||
html { background: #fbfbfd; }
|
||||
body {
|
||||
margin: 24px auto; padding: 0 24px; width: var(--measure); max-width: calc(100vw - 48px);
|
||||
color: var(--ink); font-family: var(--body-face); font-size: var(--body-size);
|
||||
line-height: var(--lh); -webkit-font-smoothing: antialiased;
|
||||
}
|
||||
body > :first-child { margin-top: 0; }
|
||||
p { margin: var(--para-space) 0 0; }
|
||||
h1, h2, h3, h4, h5, h6 { font-family: var(--headings-face); font-weight: 600; line-height: 1.15; margin: var(--head-space-before) 0 var(--head-space-after); }
|
||||
h1 { font-size: calc(var(--headings-size) * 1.15); }
|
||||
h2 { font-size: calc(var(--headings-size) * 0.85); }
|
||||
h3 { font-size: calc(var(--body-size) * 1.12); font-family: var(--body-face); font-weight: 600; }
|
||||
h4, h5, h6 { font-family: var(--body-face); font-size: var(--body-size); font-weight: 700; }
|
||||
h1 + p, h2 + p, h3 + p, h4 + p, h5 + p, h6 + p,
|
||||
h1 + ul, h2 + ul, h3 + ul, h4 + ul, h5 + ul, h6 + ul,
|
||||
h1 + ol, h2 + ol, h3 + ol, h4 + ol, h5 + ol, h6 + ol,
|
||||
h1 + blockquote, h2 + blockquote, h3 + blockquote, h4 + blockquote, h5 + blockquote, h6 + blockquote,
|
||||
h1 + pre, h2 + pre, h3 + pre, h4 + pre, h5 + pre, h6 + pre,
|
||||
h1 + table, h2 + table, h3 + table, h4 + table, h5 + table, h6 + table { margin-top: 0; }
|
||||
h1 + h2, h1 + h3, h1 + h4, h1 + h5, h1 + h6,
|
||||
h2 + h3, h2 + h4, h2 + h5, h2 + h6,
|
||||
h3 + h4, h3 + h5, h3 + h6,
|
||||
h4 + h5, h4 + h6,
|
||||
h5 + h6 { margin-top: 0.35em; }
|
||||
ul, ol { margin: var(--para-space) 0 0; padding-left: 1.6em; }
|
||||
li { margin: 0; }
|
||||
li > ul, li > ol { margin: 0; }
|
||||
pre {
|
||||
font-family: var(--code-face); font-size: var(--code-size); line-height: 1.5;
|
||||
margin: var(--para-space) 0 0; padding: 14px 16px;
|
||||
background: var(--substrate); border: none; border-radius: 8px; white-space: pre-wrap;
|
||||
}
|
||||
code { font-family: var(--code-face); font-size: 0.88em; }
|
||||
pre code { font-size: var(--code-size); }
|
||||
blockquote {
|
||||
margin: calc(var(--para-space) * 1.25) 0 0; padding: 0 0 0 20px;
|
||||
border-left: 3px solid var(--rule); color: var(--secondary);
|
||||
}
|
||||
blockquote p { margin: 0; }
|
||||
blockquote blockquote { border-left-width: 1.5px; border-left-color: var(--hairline); padding-left: 16px; }
|
||||
hr { border: none; border-top: 1px solid var(--hairline); margin: calc(var(--head-space-before) * 0.75) 0 0; }
|
||||
a { color: var(--ink); text-decoration: underline; text-decoration-color: var(--muted); text-underline-offset: 3px; }
|
||||
a:hover { text-decoration-color: var(--ink); }
|
||||
a:hover::after { content: " ✎ " attr(href); font-family: var(--code-face); font-size: 0.72em; color: var(--muted); text-decoration: none; }
|
||||
table {
|
||||
border-collapse: collapse; margin: calc(var(--para-space) * 1.25) 0 0; width: 100%;
|
||||
border-top: 1.5px solid var(--rule); border-bottom: 1.5px solid var(--rule);
|
||||
}
|
||||
th, td { border: none; border-bottom: 1px solid var(--hairline); padding: 7px 12px; text-align: left; }
|
||||
th { font-weight: 600; border-bottom: 1.5px solid var(--rule); }
|
||||
th[align="center"], td[align="center"] { text-align: center; }
|
||||
th[align="right"], td[align="right"] { text-align: right; }
|
||||
tr:last-child td { border-bottom: none; }
|
||||
figure { margin: calc(var(--para-space) * 1.5) 0 0; }
|
||||
figure img { display: block; margin: 0 auto; max-height: 340px; max-width: 100%; border: 1px solid var(--hairline); border-radius: 8px; }
|
||||
figcaption { color: var(--muted); font-size: 0.85em; text-align: center; margin-top: 8px; }
|
||||
section.footnotes { color: var(--muted); }
|
||||
section.footnotes li p { margin: 0; }
|
||||
[data-source-line]:hover { background: rgba(0,122,255,.05); }
|
||||
::selection { background: rgba(0,122,255,.12); }
|
||||
:focus-visible { outline: 2px solid rgba(0,122,255,.6); outline-offset: 2px; }
|
||||
@@ -3,39 +3,22 @@
|
||||
// Museion
|
||||
//
|
||||
// #17 (S1.1): Settings — the Museion Home path, repoint-only (ADR-0004).
|
||||
// #71 (map #20 / #70): the Typography section — three role slots (Body /
|
||||
// Headings / Code), each {face, size}: a Picker over every installed font
|
||||
// family (defaults are being auditioned; shrinks to a curated shortlist
|
||||
// once they settle) + a size field. UserDefaults persistence; re-picking a
|
||||
// face is reset. Chrome stays system.
|
||||
// #72 rework: the Typography + Text Flow sections are gone — single-user
|
||||
// app, prose typography is hardcoded (editing: ProseTypography constants;
|
||||
// reading: Museion/Resources/reading.css, editable while the app runs).
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Settings pane. Home control per #17; typography slots per #70.
|
||||
/// Settings pane. Home control per #17.
|
||||
struct SettingsPaneView: View {
|
||||
@Binding var home: URL
|
||||
|
||||
/// Full family list once per pane lifetime (#70: full list while
|
||||
/// auditioning; the picker's current selection must be listed even when
|
||||
/// NSFontManager omits it — Iowan Old Style is such a case).
|
||||
private var families: [String] {
|
||||
let current = [
|
||||
UserDefaults.standard.string(forKey: "proseBodyFace"),
|
||||
UserDefaults.standard.string(forKey: "proseHeadingsFace"),
|
||||
UserDefaults.standard.string(forKey: "proseCodeFace"),
|
||||
].compactMap(\.self)
|
||||
let all = NSFontManager.shared.availableFontFamilies
|
||||
return Array((current + all).uniqued())
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 24) {
|
||||
contentSection
|
||||
typographySection
|
||||
flowSection
|
||||
}
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
@@ -43,7 +26,7 @@ struct SettingsPaneView: View {
|
||||
.background(DesignTokens.background)
|
||||
}
|
||||
|
||||
// MARK: Home (#17)
|
||||
// MARK: Home (#17)
|
||||
|
||||
private var contentSection: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
@@ -66,49 +49,6 @@ struct SettingsPaneView: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Text flow (#71 polish)
|
||||
|
||||
private var flowSection: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Text Flow")
|
||||
.font(.system(size: 13, weight: .semibold))
|
||||
Text(
|
||||
"Reading rhythm. Line height scales the leading everywhere; the two spacings shape reading mode only — in the editor, your blank lines are the separator."
|
||||
)
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
FlowRow(label: "Line height", key: "proseLineHeight", range: 1 ... 2, step: 0.05)
|
||||
FlowRow(label: "Space after ¶", key: "proseParagraphSpacingLines", range: 0 ... 4, step: 0.25)
|
||||
FlowRow(label: "Space after headings", key: "proseHeadingSpacingLines", range: 0 ... 6, step: 0.25)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Typography (#70)
|
||||
|
||||
private var typographySection: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Typography")
|
||||
.font(.system(size: 13, weight: .semibold))
|
||||
Text(
|
||||
"The three prose roles. Both the editor and reading mode use them; a missing face falls back to the system font.",
|
||||
)
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
SlotRow(
|
||||
label: "Body", faceKey: "proseBodyFace", sizeKey: "proseBodySize",
|
||||
families: families,
|
||||
)
|
||||
SlotRow(
|
||||
label: "Headings", faceKey: "proseHeadingsFace", sizeKey: "proseHeadingsSize",
|
||||
families: families,
|
||||
)
|
||||
SlotRow(
|
||||
label: "Code", faceKey: "proseCodeFace", sizeKey: "proseCodeSize",
|
||||
families: families,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func chooseHome() {
|
||||
let panel = NSOpenPanel()
|
||||
panel.canChooseDirectories = true
|
||||
@@ -120,83 +60,3 @@ struct SettingsPaneView: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One role slot: face picker (full family list) + size stepper.
|
||||
private struct SlotRow: View {
|
||||
let label: String
|
||||
let faceKey: String
|
||||
let sizeKey: String
|
||||
let families: [String]
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 10) {
|
||||
Text(label)
|
||||
.font(.system(size: 12, weight: .semibold))
|
||||
.frame(width: 76, alignment: .leading)
|
||||
Picker("", selection: faceBinding) {
|
||||
ForEach(families, id: \.self) { family in
|
||||
Text(family).tag(family)
|
||||
}
|
||||
}
|
||||
.labelsHidden()
|
||||
.frame(maxWidth: 320)
|
||||
TextField("", value: sizeBinding, format: .number)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.frame(width: 56)
|
||||
Text("pt")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
}
|
||||
|
||||
private var faceBinding: Binding<String> {
|
||||
Binding(
|
||||
get: { UserDefaults.standard.string(forKey: faceKey) ?? "" },
|
||||
set: { UserDefaults.standard.set($0, forKey: faceKey) },
|
||||
)
|
||||
}
|
||||
|
||||
private var sizeBinding: Binding<Double> {
|
||||
Binding(
|
||||
get: { UserDefaults.standard.double(forKey: sizeKey) },
|
||||
set: { UserDefaults.standard.set(max(6, min(72, $0)), forKey: sizeKey) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// One flow knob: label + numeric field (UserDefaults-backed).
|
||||
private struct FlowRow: View {
|
||||
let label: String
|
||||
let key: String
|
||||
let range: ClosedRange<Double>
|
||||
let step: Double
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 10) {
|
||||
Text(label)
|
||||
.font(.system(size: 12, weight: .semibold))
|
||||
.frame(width: 150, alignment: .leading)
|
||||
TextField("", value: binding, format: .number.precision(.fractionLength(2)))
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.frame(width: 64)
|
||||
Text("× body line")
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
}
|
||||
|
||||
private var binding: Binding<Double> {
|
||||
Binding(
|
||||
get: { UserDefaults.standard.double(forKey: key) },
|
||||
set: { UserDefaults.standard.set(max(range.lowerBound, min(range.upperBound, $0)), forKey: key) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private extension Array {
|
||||
/// Order-preserving dedupe (face lists merge current + installed).
|
||||
func uniqued() -> [Element] where Element: Hashable {
|
||||
var seen = Set<Element>()
|
||||
return filter { seen.insert($0).inserted }
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,8 @@ 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 `<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.
|
||||
- `ProsePresenterTests.swift` (#77) — editing-surface parity pinned: heading ladder sizes (30/22/19/17-bold), half-height blanks (9pt), quote secondary-ink + indent, fence interior mono-14, inline traits (bold/italic/code/link underline + dimmed marks), CSS-1.8 leading calibration tolerance, CommonMark intraword-underscore rule, reattribute with fence-state retrofit.
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//
|
||||
// ProsePresenterTests.swift
|
||||
// Museion
|
||||
//
|
||||
// #77: editing-side reading-parity — pins the attribute map: heading ladder,
|
||||
// half-height blanks, quote/indent styling, fence interiors, inline traits
|
||||
// (bold/italic/code/link), and line-height calibration.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite(.serialized)
|
||||
struct ProsePresenterTests {
|
||||
// MARK: Line kinds
|
||||
|
||||
@Test func `heading kinds`() {
|
||||
#expect(ProsePresenter.lineKind("# T") == .heading1)
|
||||
#expect(ProsePresenter.lineKind("## T") == .heading2)
|
||||
#expect(ProsePresenter.lineKind("### T") == .heading3)
|
||||
#expect(ProsePresenter.lineKind("#### T") == .heading4Plus)
|
||||
#expect(ProsePresenter.lineKind("###### T") == .heading4Plus)
|
||||
}
|
||||
|
||||
@Test func `fence context`() {
|
||||
#expect(ProsePresenter.classify("plain", inFence: true) == .fenceInterior)
|
||||
#expect(ProsePresenter.classify("## not a heading", inFence: true) == .fenceInterior)
|
||||
#expect(ProsePresenter.classify("```", inFence: false) == .fence)
|
||||
}
|
||||
|
||||
@Test func `list markers`() {
|
||||
#expect(ProsePresenter.lineKind("- item") == .listMarker)
|
||||
#expect(ProsePresenter.lineKind("* item") == .listMarker)
|
||||
#expect(ProsePresenter.lineKind("1. item") == .listMarker)
|
||||
#expect(ProsePresenter.lineKind("12) item") == .listMarker)
|
||||
#expect(ProsePresenter.lineKind("plain text") == .body)
|
||||
}
|
||||
|
||||
// MARK: Attribute map parity
|
||||
|
||||
@Test func `heading ladder matches reading CSS`() {
|
||||
let attributed = ProsePresenter.attribute("# H1\n\n## H2\n\n### H3\n\n#### H4")
|
||||
let ns = attributed.string as NSString
|
||||
// sample at the heading TEXT, not offset 0 (the dimmed marker)
|
||||
let h1 = attributed.attribute(.font, at: ns.range(of: "H1").location, effectiveRange: nil) as? NSFont
|
||||
#expect(h1?.pointSize == 30)
|
||||
#expect(h1?.fontName.contains("ConcourseOT") == true || h1?.fontName.contains("Semibold") == true || h1?.fontName.contains("Bold") == true)
|
||||
let h2 = attributed.attribute(.font, at: ns.range(of: "H2").location, effectiveRange: nil) as? NSFont
|
||||
#expect(h2?.pointSize == 22)
|
||||
let h3 = attributed.attribute(.font, at: ns.range(of: "H3").location, effectiveRange: nil) as? NSFont
|
||||
#expect(h3?.pointSize == 19)
|
||||
#expect(h3?.fontName.contains("Valkyrie") == true || h3?.fontName.contains("Bold") == true)
|
||||
let h4 = attributed.attribute(.font, at: ns.range(of: "H4").location, effectiveRange: nil) as? NSFont
|
||||
#expect(h4?.pointSize == 17)
|
||||
#expect(h4?.fontName.contains("Bold") == true)
|
||||
}
|
||||
|
||||
@Test func `blank lines are half height`() {
|
||||
let attributed = ProsePresenter.attribute("para\n\nnext")
|
||||
let ns = attributed.string as NSString
|
||||
let blankLoc = ns.range(of: "\n\n").location + 1
|
||||
let font = attributed.attribute(.font, at: blankLoc, effectiveRange: nil) as? NSFont
|
||||
#expect(font?.pointSize == 9)
|
||||
}
|
||||
|
||||
@Test func `body leading calibrated`() {
|
||||
// CSS parity: 17pt × 1.8 ≈ 30.6pt of line, via the font's natural box.
|
||||
let font = ProseTypography.bodyFont
|
||||
let multiple = ProseTypography.lineHeightMultiple(font: font, cssLineHeight: 1.8)
|
||||
let natural = font.ascender - font.descender + font.leading
|
||||
#expect(abs(natural * multiple - font.pointSize * 1.8) < 0.5)
|
||||
}
|
||||
|
||||
@Test func `quote styling`() {
|
||||
let attributed = ProsePresenter.attribute("> quoted words")
|
||||
let ns = attributed.string as NSString
|
||||
let loc = ns.range(of: "quoted").location
|
||||
let color = attributed.attribute(.foregroundColor, at: loc, effectiveRange: nil) as? NSColor
|
||||
#expect(color == ProseTypography.secondaryColor)
|
||||
let style = attributed.attribute(.paragraphStyle, at: loc, effectiveRange: nil) as? NSParagraphStyle
|
||||
#expect(style?.firstLineHeadIndent == 20)
|
||||
#expect(style?.headIndent == 20)
|
||||
// marker dims
|
||||
let mark = attributed.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor
|
||||
#expect(mark == ProseTypography.syntaxColor)
|
||||
}
|
||||
|
||||
@Test func `fence interior is code`() {
|
||||
let attributed = ProsePresenter.attribute("```\ncode line\n```")
|
||||
let ns = attributed.string as NSString
|
||||
let loc = ns.range(of: "code line").location
|
||||
let font = attributed.attribute(.font, at: loc, effectiveRange: nil) as? NSFont
|
||||
#expect(font?.pointSize == 14)
|
||||
#expect(font?.fontName.contains("Mono") == true || font?.fontName.contains("monospaced") == true)
|
||||
#expect(attributed.attribute(.foregroundColor, at: loc, effectiveRange: nil) as? NSColor == ProseTypography.foregroundColor)
|
||||
}
|
||||
|
||||
@Test func `inline traits`() {
|
||||
let text = "bold **word** and _em_ and `code` and [label](http://x)"
|
||||
let attributed = ProsePresenter.attribute(text)
|
||||
let ns = text as NSString
|
||||
|
||||
let bold = attributed.attribute(.font, at: ns.range(of: "word").location, effectiveRange: nil) as? NSFont
|
||||
#expect(bold?.fontName.contains("Bold") == true)
|
||||
|
||||
let em = attributed.attribute(.font, at: ns.range(of: "em").location, effectiveRange: nil) as? NSFont
|
||||
#expect(em?.fontName.contains("Italic") == true)
|
||||
|
||||
let code = attributed.attribute(.font, at: ns.range(of: "code").location, effectiveRange: nil) as? NSFont
|
||||
#expect(code?.pointSize == 14)
|
||||
|
||||
let label = attributed.attribute(.underlineStyle, at: ns.range(of: "label").location, effectiveRange: nil) as? Int
|
||||
#expect(label == NSUnderlineStyle.single.rawValue)
|
||||
|
||||
// marks dim: the ** before "word"
|
||||
let mark = attributed.attribute(.foregroundColor, at: ns.range(of: "**word").location, effectiveRange: nil) as? NSColor
|
||||
#expect(mark == ProseTypography.syntaxColor)
|
||||
}
|
||||
|
||||
@Test func `fences interior retrofit`() {
|
||||
// reattribute over a paragraph inside an existing fence — state comes
|
||||
// from the prefix scan, not the paragraph alone.
|
||||
let full = "```\nfirst\n```\n\npara\n"
|
||||
let out = NSMutableAttributedString(attributedString: ProsePresenter.attribute(full))
|
||||
let ns = full as NSString
|
||||
let para = ns.paragraphRange(for: NSRange(location: 0, length: 0)) // "```"
|
||||
ProsePresenter.reattribute(out, paragraphRange: para)
|
||||
let loc = ns.range(of: "first").location
|
||||
let font = out.attribute(.font, at: loc, effectiveRange: nil) as? NSFont
|
||||
#expect(font?.pointSize == 14)
|
||||
}
|
||||
|
||||
@Test func `underscore in word not italic`() {
|
||||
let attributed = ProsePresenter.attribute("file_name_here stays plain")
|
||||
let ns = attributed.string as NSString
|
||||
let font = attributed.attribute(.font, at: ns.range(of: "name").location, effectiveRange: nil) as? NSFont
|
||||
#expect(font?.fontName.contains("Italic") != true)
|
||||
}
|
||||
}
|
||||
@@ -2,201 +2,172 @@
|
||||
// ReadingPresenterTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #71 (map #20): renderer coverage — the smallest checks that fail if the
|
||||
// block classification, auto-renumbering, source-range mapping, or inline
|
||||
// interpretation break. Kitchen-sink fixture strings inline (no file
|
||||
// fixtures per the suite's convention).
|
||||
// #76 (map #20, ADR-0011): apex HTML pipeline coverage — the smallest
|
||||
// checks that fail if the source map (chunker/stamper/blocks), the apex
|
||||
// invocation, or the page assembly break. Fixture strings inline (suite
|
||||
// convention); the pipeline tests run the real bundled apex binary.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
struct ReadingPresenterTests {
|
||||
/// Blank-line split + heading fonting + markup hidden.
|
||||
// MARK: Source map
|
||||
|
||||
/// Chunker: sentinels before chunks, blank structure preserved (spike
|
||||
/// self-check fixture).
|
||||
@Test
|
||||
func `headings and paragraphs`() {
|
||||
let doc = ReadingPresenter.document(for: "# Title\n\nBody with _em_.\n\n### Deep", resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 3)
|
||||
let flat = doc.content.string
|
||||
#expect(!flat.contains("#"))
|
||||
#expect(flat.contains("Title"))
|
||||
#expect(flat.contains("Body with em."))
|
||||
func `chunker stamps sentinels`() {
|
||||
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")
|
||||
}
|
||||
|
||||
/// Auto-renumbering: `1. 1. 1.` renders 1, 2, 3; source never rewritten.
|
||||
/// Stamper: sentinel → attribute on the following element; multi-digit.
|
||||
@Test
|
||||
func `ordered list auto renumbers`() {
|
||||
let src = "1. one\n1. two\n1. three"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.content.string.contains("1. one"))
|
||||
#expect(doc.content.string.contains("2. two"))
|
||||
#expect(doc.content.string.contains("3. three"))
|
||||
#expect(!doc.content.string.contains("1. two"))
|
||||
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>"
|
||||
#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>")
|
||||
}
|
||||
|
||||
/// Nesting: deeper items indent further; mixed bullet/number nesting rides
|
||||
/// the same path.
|
||||
/// 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 `list nesting`() {
|
||||
let src = "- top\n - nested\n- back"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.content.string.contains("top"))
|
||||
#expect(doc.content.string.contains("nested"))
|
||||
}
|
||||
|
||||
/// The #68 click→edit map: block source ranges are monotonic and cover
|
||||
/// every block; a location mid-document maps to its containing block.
|
||||
@Test
|
||||
func `source ranges map blocks`() {
|
||||
func `blocks map chunks`() {
|
||||
let src = "# A\n\nfirst para\n\n- l1\n- l2\n\nlast para"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 4)
|
||||
let locations = doc.bounds.map(\.sourceRange.location)
|
||||
#expect(locations == locations.sorted())
|
||||
// "last para" starts at its own chunk offset
|
||||
let blocks = ReadingPresenter.blocks(for: src)
|
||||
#expect(blocks.count == 4)
|
||||
#expect(blocks.map(\.sourceLine) == [1, 3, 5, 8])
|
||||
let nsSrc = src as NSString
|
||||
let expected = nsSrc.range(of: "last para").location
|
||||
#expect(doc.bounds[3].sourceRange.location == expected)
|
||||
#expect(blocks[3].sourceRange.location == nsSrc.range(of: "last para").location)
|
||||
#expect(blocks[0].sourceRange.location == 0)
|
||||
}
|
||||
|
||||
/// Tables render as a mono grid: decoration carries column offsets,
|
||||
/// header/body rows are padded columns of text.
|
||||
/// Blocks over CRLF and multi-blank separators stay monotonic.
|
||||
@Test
|
||||
func `table renders`() throws {
|
||||
let src = "| A | B |\n| --- | --- |\n| one | two |"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
let lines = doc.content.string.components(separatedBy: "\n")
|
||||
#expect(lines.count == 2)
|
||||
#expect(lines[0].contains("A"))
|
||||
#expect(lines[1].contains("one"))
|
||||
// alignment: same column starts across rows
|
||||
let colA0 = try lines[0].distance(from: lines[0].startIndex, to: #require(lines[0].firstIndex(of: "A")))
|
||||
let colA1 = try lines[1].distance(from: lines[1].startIndex, to: #require(lines[1].firstIndex(of: "o")))
|
||||
#expect(colA0 == colA1)
|
||||
guard case let .table(columns)? = doc.bounds[0].decoration else {
|
||||
Issue.record("expected table decoration")
|
||||
return
|
||||
}
|
||||
#expect(columns.count == 3) // two columns + closing edge
|
||||
func `blocks survive blank runs`() {
|
||||
let src = "one\n\n\n\n two"
|
||||
let blocks = ReadingPresenter.blocks(for: src)
|
||||
#expect(blocks.count == 2)
|
||||
#expect(blocks[0].sourceLine == 1)
|
||||
#expect(blocks[1].sourceLine == 5)
|
||||
}
|
||||
|
||||
/// Fenced code: mono face, markers hidden, content intact.
|
||||
// MARK: Pipeline (real apex binary)
|
||||
|
||||
/// Headings + paragraphs + inline marks render; markup never leaks.
|
||||
@Test
|
||||
func `fenced code`() {
|
||||
let src = "```swift\nlet x = 1\n```"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(!doc.content.string.contains("```"))
|
||||
#expect(doc.content.string.contains("let x = 1"))
|
||||
let attrs = doc.content.attributes(at: 0, effectiveRange: nil)
|
||||
#expect((attrs[.font] as? NSFont)?.fontName == ProseTypography.codeFont.fontName)
|
||||
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("<h1 data-source-line=\"1\""))
|
||||
#expect(html.contains("<em>em</em>"))
|
||||
#expect(html.contains("<code>code</code>"))
|
||||
#expect(!html.contains("_em_"))
|
||||
}
|
||||
|
||||
/// Blockquote: markers hidden, quote decoration on the bound.
|
||||
/// `1. 1. 1.` renumbers via native <ol> (the #69 hard requirement).
|
||||
@Test
|
||||
func blockquote() {
|
||||
let src = "> quoted _words_\n>> deeper"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(!doc.content.string.contains(">"))
|
||||
#expect(doc.content.string.contains("quoted words"))
|
||||
guard case .quote? = doc.bounds[0].decoration else {
|
||||
Issue.record("expected quote decoration")
|
||||
return
|
||||
}
|
||||
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)
|
||||
#expect(html.contains("<ol data-source-line=\"1\">"))
|
||||
#expect(html.contains("<li>one</li>"))
|
||||
#expect(html.contains("<li>two</li>"))
|
||||
#expect(html.contains("<li>three</li>"))
|
||||
#expect(!html.contains("1. one"))
|
||||
}
|
||||
|
||||
/// Links styled + attribute retained (⌘-click opens).
|
||||
/// `--no-mixed-lists`: an ordered list after a bullet list stays two
|
||||
/// lists (default apex merges them — kills renumbering).
|
||||
@Test
|
||||
func `links retained`() {
|
||||
let src = "See [the docs](https://example.de) now"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
let range = (doc.content.string as NSString).range(of: "the docs")
|
||||
#expect(range.location != NSNotFound)
|
||||
let attrs = doc.content.attributes(at: range.location, effectiveRange: nil)
|
||||
#expect(attrs[.link] != nil)
|
||||
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("<ul"))
|
||||
#expect(html.contains("<ol"))
|
||||
#expect(!html.contains("<li>one</li></ul>"))
|
||||
}
|
||||
|
||||
/// Images: hover payload carried on the bound, syntax stays text.
|
||||
/// Tables, quotes, fenced code, HR, links — the #69 set on one page.
|
||||
@Test
|
||||
func `image hover payload`() {
|
||||
let src = ""
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.bounds[0].imageURL != nil)
|
||||
#expect(doc.content.string.contains("alt text"))
|
||||
}
|
||||
func `pipeline constructs`() throws {
|
||||
let src = """
|
||||
| A | B |
|
||||
| --- | --- |
|
||||
| one | two |
|
||||
|
||||
/// Image URL resolution against the post folder (#71).
|
||||
@Test
|
||||
func `image URL resolves against post folder`() {
|
||||
let src = ""
|
||||
let folder = URL(fileURLWithPath: "/tmp/posts/example")
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: folder)
|
||||
#expect(doc.bounds[0].imageURL?.path == "/tmp/posts/example/assets/img.png")
|
||||
}
|
||||
|
||||
/// Footnotes are the one fallback: source text, no transformation.
|
||||
@Test
|
||||
func `footnotes stay fallback`() {
|
||||
let src = "Text with note[^1]\n\n[^1]: the note"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.content.string.contains("[^1]"))
|
||||
}
|
||||
|
||||
/// HR: rule decoration, matcher shared with editing.
|
||||
@Test
|
||||
func `horizontal rule`() {
|
||||
let src = "above\n\n* * *\n\nbelow"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 3)
|
||||
guard case .rule? = doc.bounds[1].decoration else {
|
||||
Issue.record("expected rule decoration")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
/// Soft-joined lines: one paragraph, single spaces.
|
||||
@Test
|
||||
func `soft joined lines`() {
|
||||
let src = "line one\nline two"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.content.string == "line one line two")
|
||||
}
|
||||
|
||||
/// Kitchen-sink smoke: every construct in one document without crashing.
|
||||
@Test
|
||||
func `kitchen sink renders`() {
|
||||
let sink = """
|
||||
# Sink
|
||||
|
||||
- bullet
|
||||
- another
|
||||
|
||||
1. one
|
||||
1. two
|
||||
|
||||
> quote
|
||||
> quoted
|
||||
|
||||
```txt
|
||||
code
|
||||
let x = 1
|
||||
```
|
||||
|
||||
| H |
|
||||
| --- |
|
||||
| c |
|
||||
|
||||

|
||||
|
||||
[link](https://x.de)
|
||||
See [the docs](https://example.net) now
|
||||
|
||||
* * *
|
||||
"""
|
||||
let doc = ReadingPresenter.document(for: sink, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count >= 9)
|
||||
let (html, blocks) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||
try assertRendered(html, blocks: blocks, count: 5)
|
||||
#expect(html.contains("<table data-source-line=\"1\">"))
|
||||
#expect(html.contains("<blockquote data-source-line=\"5\">"))
|
||||
#expect(html.contains("<pre"))
|
||||
#expect(html.contains("let x = 1"))
|
||||
#expect(!html.contains("```"))
|
||||
#expect(html.contains("<a href=\"https://example.net\">the docs</a>"))
|
||||
#expect(html.contains("<hr"))
|
||||
}
|
||||
|
||||
/// Images embed as base64 data URLs against the post folder (#69/#74).
|
||||
@Test
|
||||
func `pipeline image embeds`() throws {
|
||||
let prose = URL(fileURLWithPath: #filePath) // …/MuseionTests/ReadingPresenterTests.swift
|
||||
.deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("spike/prose")
|
||||
let src = ""
|
||||
let (html, blocks) = ReadingPresenter.page(for: src, postFolder: prose)
|
||||
try assertRendered(html, blocks: blocks, count: 1)
|
||||
#expect(html.contains("src=\"data:image/png;base64,"))
|
||||
}
|
||||
|
||||
/// Footnotes render natively (apex upgrade over #69's fallback).
|
||||
@Test
|
||||
func `pipeline footnotes`() {
|
||||
let src = "Text with note[^1]\n\n[^1]: the note"
|
||||
let (html, _) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||
#expect(html.contains("footnote"))
|
||||
#expect(html.contains("the note"))
|
||||
}
|
||||
|
||||
/// Fallback: apex failure → editing-treated source (#69 rule), escaped.
|
||||
@Test
|
||||
func `fallback is source text`() {
|
||||
let page = ReadingPresenter.fallbackPage("a < b & c > d")
|
||||
#expect(page.contains("<pre data-source-line=\"1\">a < b & c > d</pre>"))
|
||||
}
|
||||
|
||||
/// The stylesheet carries the live slot values as CSS variables.
|
||||
@Test
|
||||
func `stylesheet carries slots`() {
|
||||
let css = ReadingPresenter.styleSheet()
|
||||
#expect(css.contains("--body-face:"))
|
||||
#expect(css.contains("--headings-size:"))
|
||||
#expect(css.contains("--code-face:"))
|
||||
#expect(css.contains("--lh:"))
|
||||
#expect(css.contains("[data-source-line]:hover"))
|
||||
}
|
||||
|
||||
private func assertRendered(_ html: String, blocks: [ReadingPresenter.Block], count: Int) throws {
|
||||
let stamped = try XCTRegexMatches(html, pattern: "data-source-line=\"\\d+\"")
|
||||
#expect(stamped == count)
|
||||
#expect(blocks.count == count)
|
||||
#expect(!html.contains("<!--S:"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Regex count helper (Swift Testing has no XCTest import here).
|
||||
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))
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.2 MiB |
+1
-1
@@ -10,7 +10,7 @@ Owned by the root AGENTS.md contract.
|
||||
|
||||
## Local Contracts
|
||||
|
||||
- ADRs live in `docs/adr/`, sequentially numbered `NNNNN-slug.md` (currently `0001`–`0010`: stack, license, forge/CI, content layout, learnings home, fix-card transport, state ownership, tools host, sandbox posture, prose editor substrate).
|
||||
- ADRs live in `docs/adr/`, sequentially numbered `NNNNN-slug.md` (currently `0001`–`0011`: stack, license, forge/CI, content layout, learnings home, fix-card transport, state ownership, tools host, sandbox posture, prose editor substrate, apex HTML reading pipeline).
|
||||
- ADR format follows the domain-modeling skill's `ADR-FORMAT.md`: short title + 1–3 sentences; optional Considered Options / Consequences only when they earn their place.
|
||||
- `docs/agents/` holds the engineering-skills config (issue tracker, triage labels, domain-docs consumer rules) written by `setup-matt-pocock-skills` — edit directly, no child doc needed.
|
||||
- `docs/sample-pass.md` is the worked sample Pass demonstrating the craft-canon skills firing as Fix Cards (issues #7 and #11 verification artifacts); card shape follows CONTEXT.md, anchors follow ADR-0006.
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# 0010 — Native TextKit2 prose editor (mode B)
|
||||
|
||||
> Reading half superseded by [ADR-0011](0011-apex-html-reading-pipeline.md) — apex HTML pipeline; the editing stance (TextKit2 mode B) stands.
|
||||
|
||||
The editor is a native NSTextView/TextKit2 surface presenting markdown source as calm writing (mode B: styled source, dimmed syntax, reading toggle), with presentation as a flat line-kind→attribute map — no third-party editor dependency. Decided from three throwaway spikes on the pinned calibration corpus (`spike/codeedit/`, `spike/textkit2/`, `spike/blocks/` on `spike/editor-presentation`): TextKit2 delivers full typographic calm at the lowest cost, editing (undo, IME, selection) is native and free, and the Fix-Card anchor proof — exact-range quote highlight + stale-anchor alert with the web-proto wording — passes live on this substrate (2.4 ms anchor search on PERF-3k, ≤1.1 ms full-doc attribute load).
|
||||
|
||||
## Considered Options
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# 0011 — Apex HTML reading pipeline
|
||||
|
||||
Reading mode renders markdown through apex (MIT, unified dialect) as an HTML fragment loaded into a single WKWebView styled by our CSS — typography slots become CSS custom properties, and a blank-line-chunked `data-source-line` stamp (sentinel HTML comments, applied post-conversion; apex emits no source positions) carries the click-to-edit and scroll-sync map at paragraph granularity. Proven live in the #74 spike (PERF-3k: ~18 ms apex, 33 ms end-to-end, zero mis-stamps corpus-wide); ruled in #73. Supersedes ADR-0010's reading stance — its editing stance (TextKit2 mode B) stands — and records ADR-0001's boundary as ruled: native-only governs the editing side; reading is presentation, so WKWebView is allowed.
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **TextKit reading renderer (#71 build)** — deleted, not kept as fallback: fallbacks rot, and its stale-flow defect dies unfixed by design. The decoupling obligation (editing side up to par as a plain-text surface) is ticketed separately (#77).
|
||||
- **`loadFileURL` instead of `loadHTMLString`** — 4× first paint (255 ms vs ~67 ms) from sandbox negotiation; `--embed-images` base64 inlining needs no file access at all and writes nothing into the vault.
|
||||
|
||||
## Consequences
|
||||
|
||||
- **Bundling:** the prebuilt apex binary ships in app resources, signed + notarized. No source build in CI, no user install gate — a renderer must not grow a gate.
|
||||
- **One WKWebView, reloaded in place.** Remounting per document (`.id(sel)`) was the dominant switch cost — hundreds of ms of web-process respawn; `loadHTMLString` on a retained view feels instant.
|
||||
- **`--no-mixed-lists` is required**, not tuning: apex's default merges an ordered list following a bullet list into one `<ul>`, killing `1. 1. 1.` auto-renumbering.
|
||||
- **Early handoff:** stdout EOF is conversion done; apex's ~65 ms teardown is reaped async via `terminationHandler` (the error path still waits for exit status).
|
||||
@@ -0,0 +1,37 @@
|
||||
# Issue 76 — Task: build the apex HTML reading surface (S1.2)
|
||||
|
||||
> **Date:** 2026-10-06
|
||||
> **Type:** issue
|
||||
> **Reference:** [Wayfinder map #20](https://git.babylondreams.de/AlexKucera/museion/issues/20) · [ADR-0011](../adr/0011-apex-html-reading-pipeline.md) · spike [#74](https://git.babylondreams.de/AlexKucera/museion/issues/74) · ADR [#75](https://git.babylondreams.de/AlexKucera/museion/issues/75)
|
||||
|
||||
## What landed
|
||||
|
||||
Branch `wayfinder/76-apex-html-reading` (off the #75 ADR branch, which merged #71's landing — the swap needs the surface it replaces), commits `cc04ec2` (feature) + `f1c915f` (lint/DOX).
|
||||
|
||||
**Rewritten**
|
||||
- `Museion/ReadingPresenter.swift` — the apex HTML pipeline: `stampSource` (blank-line chunker, `<!--S:N-->` sentinels) → `apexRender` (bundled binary; `-t html --no-mixed-lists --embed-images [--base-dir]`) → `stampHTML` (regex restamp to `data-source-line`) → `page(for:postFolder:)` with `styleSheet()` (ProseTypography slots + flow knobs as CSS custom properties; family names, weight rides CSS). `blocks(for:)` = line↔UTF-16-range map (the #68 contract). Fallback = escaped source `<pre>`; footnotes render natively (apex upgrade over #69's fallback).
|
||||
- `Museion/ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` kept; one WKWebView reloaded in place (render keyed generation+text+flowKey); probeJS click→edit at clicked block, ⌘-click→NSWorkspace, scroll→top-line into stateBox; `decidePolicyFor` allows only our about:blank main-frame load; entry scroll after `didFinish`; defaults observer reloads on flow-key change.
|
||||
- `Museion/Resources/apex` — apex 1.1.17 universal binary (1.8 MB); the fs-sync root group ships it into Resources automatically (verified in the built .app — no pbxproj edit).
|
||||
|
||||
**Deleted** (ADR-0011: no fallbacks — the stale-flow defect dies unfixed): `ReadingCanvasView`, `Decoration`, table/quote/HR content blocks, `framesForRange`, `ImagePopoverView`.
|
||||
|
||||
**Untouched:** #68 toggle wiring, ProseTypography, ProsePresenter, Settings pane.
|
||||
|
||||
## Verification
|
||||
|
||||
- `xcodebuild test` green (94 tests; pipeline tests run the real bundled binary — mixed-lists split, `1. 1. 1.` renumber, base64 embed, exact `data-source-line` stamps). SwiftLint 0 errors, SwiftFormat clean on touched files.
|
||||
- Live in-app: kitchen-sink + PERF-3k render formatted, toggle instant (apex ~20 ms/render ×3), click-to-edit lands at the clicked paragraph, frontmatter invisible. Alexander clicked around the live app mid-session — no crash, no defect.
|
||||
- Perfect gates: PERF-3k pass (20 ms ≪ spike's 33 ms end-to-end).
|
||||
|
||||
## Lessons
|
||||
|
||||
- **fs-sync root groups DO ship nested non-source files into Resources** — `Museion/Resources/apex` needed no pbxproj wiring. Verify in the built .app before assuming either way (my first check read a stale DerivedData tree from a different project hash and nearly sent me into pbxproj surgery).
|
||||
- SwiftFormat between write and patch reflows closures — re-read before patching (skill-documented; bit anyway).
|
||||
- Long `write_file` calls can corrupt mid-file (garbled unicode, truncated CSS) — write shorter files or verify after.
|
||||
- `execute_code` string replacements can inject literal control chars into escape sequences (a `"\t"` became a raw tab → "Unprintable ASCII character" build error). Fix byte-level with Python, verify with `cat -v`.
|
||||
- apex quirks folded into tests: tables wrapped in `<figure>` with stray `<figcaption>` (CSS hides), footnotes native, `--no-mixed-lists` required.
|
||||
|
||||
## Follow-ups
|
||||
|
||||
- #72 calibration gate unblocked (pointer comment posted: calibrate THIS branch, the HTML surface).
|
||||
- Release pipeline owes apex signing+notarization (ADR-0011; dev bundle is the adhoc Homebrew artifact).
|
||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-10-06 | issue | [20261006-issue76-apex-html-reading_log.md](20261006-issue76-apex-html-reading_log.md) | #76 apex HTML reading surface: WKWebView + bundled apex, data-source-line map, TextKit reading deleted — 94 tests green, PERF-3k 20 ms |
|
||||
| 2026-10-05 | issue | [20261005-issue71-reading-toggle_log.md](20261005-issue71-reading-toggle_log.md) | #71 reading toggle: block-aware renderer, tap-to-edit canvas, typography slots, kitchen-sink — 94 tests green |
|
||||
| 2026-10-03 | issue | [20261003-issue19-editor-core_log.md](20261003-issue19-editor-core_log.md) | #19 editor core: TextKit2 surface lifted, debounced autosave, save dot, cursor sidecar, conflict alert — 81 tests green |
|
||||
| 2026-10-03 | issue | [20261003-issue18-post-lifecycle_log.md](20261003-issue18-post-lifecycle_log.md) | #18 shipped + audits: Post write side, FSEvents watcher, editor stub — 75 tests green |
|
||||
|
||||
Reference in new issue
Block a user