feat(reading): polish typography, externalize CSS

Critique-directed polish of the reading surface (#72 ruling: pipeline
calm, surface not-calm) plus the single-user typography rework:

- Flow: leading 1.5, paragraph gap tightened; heading ladder rescaled
  (h1 1.15x / h2 0.85x / h3 body-face semibold) with cling margins,
  hN+hN suppression, no title dead space
- Constructs: confident blockquote (near-ink text, 3px rail, nesting
  degrades), booktabs tables, tinted code panels, relative inline code
- Fonts hardcoded for Alexander's faces: Valkyrie OT B 17 body,
  Concourse OT Semibold headings, UbuntuMono 14 code; 66ch measure
- Stylesheet moved to Museion/Resources/reading.css, read fresh per
  page build — Debug builds load the repo copy (#filePath), so CSS
  edits hot-reload on the next reading toggle
- Settings Typography/Text Flow sections and all flow-key plumbing
  deleted (56 insertions, 417 deletions)

Refs #72, #78. Detector: 192 findings -> 0. Build + 93 tests green.

[Generated by AI]
This commit is contained in:
AlexKucera committed 2026-10-07 17:02:10 +02:00
1 parent eae86dd2ef
commit 4cb753d17f
9 files changed
+134 -417

No files matched your search

+4 -4
View File
@@ -25,10 +25,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 (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — ProseTypography slots + flow knobs as CSS custom properties (`--body-face/--headings-size/--lh/...`, family names not member PS names; weight rides CSS). Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; defaults observer reloads on flow-key change (CSS vars injected at load). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error). `ProseTypography.registerDefaults()` rides the same init (#71).
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — the lifted spike presenter: line-kind → attributes map (fonts via ProseTypography constants — #72 rework: Valkyrie OT B 17 body, Concourse OT Semibold 26/20 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. #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)
-1
View File
@@ -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`
+1 -31
View File
@@ -297,19 +297,13 @@ 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
// 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
// pre-edit text — then session.edit on the stale view would
@@ -354,30 +348,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
+1 -1
View File
@@ -89,7 +89,7 @@ nonisolated enum ProsePresenter {
[.font: ProseTypography.headingFont, .paragraphStyle: paragraph(.heading1)]
case .heading2:
[
.font: ProseTypography.headingFont(size: (ProseTypography.headingFont.pointSize * 0.77).rounded()),
.font: NSFont(name: "ConcourseOT6Semibold", size: (ProseTypography.headingFont.pointSize * 0.77).rounded()) ?? ProseTypography.headingFont,
.paragraphStyle: paragraph(.heading2),
]
case .quote, .syntaxOnly, .body: bodyAttributes
+22 -139
View File
@@ -2,137 +2,48 @@
// 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
/// 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 { NSFont(name: "ValkyrieOTBRegular", size: 17) ?? NSFont.systemFont(ofSize: 17) }
/// 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,
])
}
/// Headings = Concourse OT (the designer's own pairing with Valkyrie);
/// Semibold carries heading weight better than Book on screen.
static var headingFont: NSFont { NSFont(name: "ConcourseOT6Semibold", size: 26) ?? NSFont.systemFont(ofSize: 26, weight: .semibold) }
private static func face(_ key: String, defaultFace: String) -> String {
UserDefaults.standard.string(forKey: key) ?? defaultFace
}
/// Code slot (inline code, fenced blocks, editing syntax dim).
static var codeFont: NSFont { NSFont(name: "UbuntuMonoNFM", size: 14) ?? NSFont.monospacedSystemFont(ofSize: 14, weight: .regular) }
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.
static var bodyFont: NSFont {
font(family: face("proseBodyFace", defaultFace: defaultBodyFace),
size: size("proseBodySize", defaultSize: defaultBodySize))
}
/// Headings slot font — the family's Book/Regular member, bold trait, at
/// the slot size (h1). Scaled levels call `headingFont(size:)`.
static var headingFont: NSFont {
bolded(headingFont(size: size("proseHeadingsSize", defaultSize: defaultHeadingsSize)))
}
static func headingFont(size: CGFloat) -> NSFont {
bolded(font(family: face("proseHeadingsFace", defaultFace: defaultHeadingsFace), size: size))
}
/// Code slot font (inline code, fenced blocks, and the editing surface's
/// dimmed syntax).
static var codeFont: NSFont {
font(family: face("proseCodeFace", defaultFace: defaultCodeFace),
size: size("proseCodeSize", defaultSize: defaultCodeSize))
}
/// Editing-surface leading (blank source lines are the separator there).
static let lineHeightMultiple: CGFloat = 1.5
static var italicBodyFont: NSFont {
NSFontManager.shared.convert(bodyFont, toHaveTrait: .italicFontMask)
}
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 +52,7 @@ nonisolated enum ProseTypography {
NSColor(white: 0.78, alpha: 1)
}
/// Table borders + reading HR hairline (≈ DesignTokens.border).
/// 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 +71,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
}
}
+22 -63
View File
@@ -166,6 +166,28 @@ nonisolated enum ReadingPresenter {
// 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).
@@ -193,67 +215,4 @@ nonisolated enum ReadingPresenter {
.replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;")
}
// MARK: Stylesheet — ProseTypography slots + flow knobs as CSS variables
/// Variables from the live slot values (UserDefaults-driven, #70/#71) +
/// the spike's fixed rules (proven live, #74). `familyName` (not the
/// member PS name) is what CSS font matching wants; weight rides CSS.
static func styleSheet() -> String {
func family(_ font: NSFont) -> String {
"\"\(font.familyName ?? (font.displayName ?? ""))\""
}
func px(_ value: Double) -> String {
"\(String(format: "%.0f", value))px"
}
let body = ProseTypography.bodyFont
let head = ProseTypography.headingFont
let code = ProseTypography.codeFont
let line = ProseTypography.linePoints
return """
:root {
--body-face: \(family(body)), Georgia, serif;
--body-size: \(px(body.pointSize));
--headings-face: \(family(head)), Georgia, serif;
--headings-size: \(px(head.pointSize));
--code-face: \(family(code)), UbuntuMonoNFM, monospace;
--code-size: \(px(code.pointSize));
--lh: \(String(format: "%.2f", ProseTypography.lineHeightMultiple));
--para-space: \(px(Double(line * ProseTypography.paragraphSpacingLines)));
--head-space: \(px(Double(line * ProseTypography.headingSpacingLines)));
--measure: 640px;
--ink: #1d1d1f; --muted: #6e6e73; --hairline: #d2d2d7;
}
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;
}
p { margin: var(--para-space) 0 0; }
h1, h2, h3, h4, h5, h6 { font-family: var(--headings-face); font-weight: 700; line-height: 1.15; margin: var(--head-space) 0 0; }
h1 { font-size: var(--headings-size); }
h2 { font-size: calc(var(--headings-size) * 0.77); }
h3 { font-size: calc(var(--body-size) + 1px); }
h4, h5, h6 { font-family: var(--body-face); font-size: var(--body-size); font-weight: 700; }
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); margin: var(--para-space) 0 0;
padding: 8px 12px; border: 1px solid var(--hairline); border-radius: 6px; white-space: pre-wrap; }
code { font-family: var(--code-face); font-size: var(--code-size); }
blockquote { margin: var(--para-space) 0 0; padding-left: 14px; border-left: 1.5px solid var(--hairline); color: var(--muted); }
blockquote p { margin: 0; }
hr { border: none; border-top: 1px solid var(--hairline); margin: var(--head-space) 0 0; }
a { color: var(--ink); text-decoration: underline; text-decoration-color: var(--hairline); text-underline-offset: 3px; }
table { border-collapse: collapse; margin: var(--para-space) 0 0; }
th, td { border: 1px solid var(--hairline); padding: 4px 10px; text-align: left; }
figure { margin: var(--para-space) 0 0; }
figure img { max-height: 1.6em; transition: max-height .25s ease; vertical-align: middle; }
figure:hover img { max-height: 420px; }
figcaption { display: none; }
section.footnotes { color: var(--muted); }
[data-source-line]:hover { background: rgba(0,122,255,.05); }
"""
}
}
+1 -33
View File
@@ -69,7 +69,6 @@ struct ReadingSurface: NSViewRepresentable {
// 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
context.coordinator.watchDefaults()
return wv
}
@@ -78,7 +77,7 @@ struct ReadingSurface: NSViewRepresentable {
coordinator.onEditIntent = onEditIntent
coordinator.stateBox = stateBox
coordinator.postFolder = postFolder
let key = "\(generation):\(text.hashValue):\(ProseTypography.flowKey)"
let key = "\(generation):\(text.hashValue)"
guard coordinator.loadedKey != key else { return }
coordinator.load(text: text, generation: generation, entryCaret: entryCaretLocation, key: key)
}
@@ -140,8 +139,6 @@ struct ReadingSurface: NSViewRepresentable {
var pendingEntryScrollLine: Int?
var painted = false
private var lastText = ""
private var defaultsObserver: NSObjectProtocol?
private var appliedFlowKey = ""
/// Build + load the page for `text`. All render paths land here
/// (updateNSView, typography-change reload).
@@ -165,35 +162,6 @@ struct ReadingSurface: NSViewRepresentable {
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
}
/// Typography/flow knob moves reload the page (CSS vars are injected
/// at load; SwiftUI doesn't re-call updateNSView on UserDefaults
/// writes).
func watchDefaults() {
guard defaultsObserver == nil else { return }
appliedFlowKey = ProseTypography.flowKey
defaultsObserver = NotificationCenter.default.addObserver(
forName: UserDefaults.didChangeNotification,
object: nil,
queue: .main,
) { [weak self] _ in
Task { @MainActor [weak self] in
guard let self else { return }
let key = ProseTypography.flowKey
guard key != appliedFlowKey else { return }
appliedFlowKey = key
load(
text: lastText,
generation: 0,
entryCaret: nil,
key: "\(loadedKey)|flow",
)
}
}
}
// ponytail: observer registration lives for the coordinator's
// lifetime (app-scoped defaults notifications, same as ProseTextView's
// coordinator — no removal, matching the codebase convention).
// MARK: WKNavigationDelegate
+78
View File
@@ -0,0 +1,78 @@
/* 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(--rule); text-underline-offset: 3px; }
a:hover { text-decoration-color: var(--ink); }
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); }
tr:last-child td { border-bottom: none; }
figure { margin: var(--para-space) 0 0; }
figure img { max-height: 1.6em; transition: max-height .25s ease; vertical-align: middle; }
figure:hover img { max-height: 420px; }
figcaption { display: none; }
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; }
+5 -145
View File
@@ -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 }
}
}