feat(editor): land reading toggle — render, interact, typography slots (S1.2 #71)
Map #20 execution child, built per decisions #68/#69/#70: - ReadingPresenter: block-aware renderer (ADR-0010 stance) — blank-line split, one block per chunk; lists (bullets + ordered + nesting + auto-renumber via per-level counters — one rendering path), headings by level (h1 = slot size, h2 = 0.77x, ### = body+1, #### floors at bold body), HR via the editing syntaxOnly predicate, fenced code, blockquotes (QuoteTextBlock hairline), tables (NSTextTable 1px border, delimiter-row alignment), images (hover payload), links styled + retained. Footnotes stay fallback. Source ranges ride every block (click→edit map). - ReadingSurface: read-only selectable NSTextView canvas (#68: a presentation of the same TextKit2 document). Tap with no selection after mouseDown returns = edit intent at the clicked block (the tracking-loop fix); ⌘-click opens links; scroll tracking feeds the flip-back caret; image hover NSPopover loads off-main. - ProseTypography (#70): three role slots — Body / Headings / Code — each {face, size}, UserDefaults six values, member-based font resolution (family+weight lookup misresolves Concourse Book→Thin), silent system fallback; both prose surfaces read them; editing presenter's headings + dimmed syntax rewired through the slots. - PostEditorView: Read⇄Edit toolbar button (far left) + View menu "Toggle Reading Mode" + ⌘R; reading state transient per open; drafts included (draft mirror); flip-back caret hint applied once per token. - SettingsPaneView: Typography section — three slot rows (family picker incl. current face not in the installed list + size field). - kitchen-sink.md (+png): corpus piece exercising constructs absent from the eight posts, per #69. Verified: 94 unit tests (renderer classification, renumbering, source ranges, fallbacks) + UI smoke; PERF-3k renders 128 blocks in ~17 ms; live-app probe — Read renders kitchen-sink markers-hidden, renumbered, byte-stable file after full round-trip; click-to-edit flips at the clicked paragraph; typography ladder pixel-verified (20/15 ink px).
This commit is contained in:
1 parent
f2953ee07e
commit
4c91733e78
12 files changed
+1393
-33
No files matched your search
@@ -44,6 +44,10 @@ _Avoid_: convert, migrate
|
||||
The authorship record of a Post: writer or ai. Immutable; only writer-origin First Drafts are ever stats-eligible.
|
||||
_Avoid_: source, mode
|
||||
|
||||
**Reading Mode**:
|
||||
The rendered presentation of a Piece's text: view-and-select, never editing. Toggled explicitly; clicking the text drops into editing at that spot. Distinct from a Pass, which critiques rather than presents.
|
||||
_Avoid_: preview, read mode
|
||||
|
||||
### The Mentor Loop
|
||||
|
||||
**Mentor**:
|
||||
|
||||
@@ -28,6 +28,13 @@ final class EditorSession {
|
||||
private let home: URL
|
||||
private let debounce: Duration
|
||||
|
||||
/// The post's folder (`<home>/posts/<id>`) — reading resolves relative
|
||||
/// image URLs against it (#71).
|
||||
var folderURL: URL {
|
||||
home.appendingPathComponent("posts", isDirectory: true)
|
||||
.appendingPathComponent(postID, isDirectory: true)
|
||||
}
|
||||
|
||||
/// Current body text (live, per keystroke).
|
||||
private(set) var text: String
|
||||
/// The save-state indicator (#65).
|
||||
|
||||
@@ -39,6 +39,8 @@ final class AppGateState {
|
||||
.flatMap(URL.init(string:))
|
||||
.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`
|
||||
@@ -73,6 +75,13 @@ struct MuseionApp: App {
|
||||
CommandGroup(replacing: .appInfo) {
|
||||
OpenAboutButton()
|
||||
}
|
||||
// #68: View menu reading toggle — reaches the visible editor.
|
||||
CommandMenu("View") {
|
||||
Button("Toggle Reading Mode") {
|
||||
NotificationCenter.default.post(name: .toggleReadingMode, object: nil)
|
||||
}
|
||||
.keyboardShortcut("r", modifiers: .command)
|
||||
}
|
||||
// #50: reveal the snapshots folder in Finder (restore = manual
|
||||
// copy-back, documented in the bundled help doc).
|
||||
CommandMenu("Help") {
|
||||
|
||||
+112
-10
@@ -7,12 +7,23 @@
|
||||
// attributes re-applied per edited paragraph; native undo/IME/find. Session
|
||||
// mode autosaves via EditorSession (#64–#67); draft mode stays #62's
|
||||
// explicit-⌘S path. The #18 stub's Save button died here (#65).
|
||||
// #71 (map #20): the reading toggle (#68) — Read⇄Edit toolbar button (far
|
||||
// left, before the crumb) + View menu item + ⌘R; reading renders
|
||||
// ReadingPresenter output in a read-only canvas; a tap with no selection
|
||||
// drops to editing at that paragraph; drafts included; no persistence —
|
||||
// every fresh open lands in editing.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import Combine
|
||||
import SwiftUI
|
||||
|
||||
extension Notification.Name {
|
||||
/// #68: the View menu's "Toggle Reading Mode" item — the visible editor
|
||||
/// listens (one editor column exists at a time).
|
||||
static let toggleReadingMode = Notification.Name("museion.toggleReadingMode")
|
||||
}
|
||||
|
||||
/// Editor column content: toolbar row (crumb + save-state widget) + surface.
|
||||
/// `session` nil = draft mode (crumb + ⌘S first-write, no autosave, no dot).
|
||||
struct PostEditorView: View {
|
||||
@@ -23,29 +34,58 @@ struct PostEditorView: View {
|
||||
var draftSave: (() -> Void)?
|
||||
|
||||
@State private var closeObserver: AnyCancellable?
|
||||
@State private var toggleObserver: AnyCancellable?
|
||||
/// #68: reading is a transient act of inspection — no persistence; a
|
||||
/// fresh open always lands in editing.
|
||||
@State private var reading = false
|
||||
/// Flip-back caret (#68): source location + a token so repeated flips to
|
||||
/// the same location re-apply. Consumed by ProseTextView's coordinator.
|
||||
@State private var flipBackCaret: (location: Int, token: Int)?
|
||||
@State private var flipToken = 0
|
||||
/// Reading scroll state (#68 mapping): entry caret + live top block.
|
||||
@State private var readingState = ReadingStateBox()
|
||||
/// Draft text mirror — reading renders it; edits flow back via onEdit.
|
||||
@State private var draftMirror = ""
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
toolbar
|
||||
Rectangle().fill(DesignTokens.border).frame(height: 1)
|
||||
if let session {
|
||||
ProseTextView(session: session)
|
||||
if reading {
|
||||
ReadingSurface(
|
||||
text: renderText,
|
||||
generation: session?.loadGeneration ?? 0,
|
||||
postFolder: session?.folderURL,
|
||||
entryCaretLocation: readingState.entryLocation,
|
||||
onEditIntent: { loc in exitReading(caret: loc) },
|
||||
stateBox: readingState,
|
||||
)
|
||||
} else {
|
||||
ProseTextView(draft: draftText ?? "", onEdit: { draftEdited?($0) })
|
||||
editingSurface
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(DesignTokens.surface)
|
||||
// #64: flush on window close (app quit rides willTerminate in MuseionApp).
|
||||
// ponytail: no object filter — flush is idempotent; any-window close is fine.
|
||||
.onAppear {
|
||||
if draftMirror.isEmpty {
|
||||
draftMirror = draftText ?? ""
|
||||
}
|
||||
closeObserver = NotificationCenter.default.publisher(
|
||||
for: NSWindow.willCloseNotification,
|
||||
).sink { _ in
|
||||
session?.flush()
|
||||
}
|
||||
// #68: View menu / ⌘R reaches the visible editor.
|
||||
toggleObserver = NotificationCenter.default.publisher(
|
||||
for: .toggleReadingMode,
|
||||
).sink { [weak session] _ in
|
||||
toggleReading()
|
||||
_ = session
|
||||
}
|
||||
}
|
||||
// #67: explicit alert — never silent in either direction.
|
||||
// #67: explicit alert — never silent in either direction. It hangs
|
||||
// above the surface swap, so it shows while reading too; Yes-reload
|
||||
// bumps loadGeneration and the reading surface re-renders (#68 Q6).
|
||||
.alert("File on Disk changed", isPresented: conflictBinding) {
|
||||
Button("Reload") { session?.reloadFromDisk() }
|
||||
Button("Keep Local") { session?.keepLocal() }
|
||||
@@ -54,6 +94,43 @@ struct PostEditorView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The text reading renders: live session text or the draft mirror.
|
||||
private var renderText: String {
|
||||
session?.text ?? draftMirror
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private var editingSurface: some View {
|
||||
if let session {
|
||||
ProseTextView(session: session, caretHint: flipBackCaret)
|
||||
} else {
|
||||
ProseTextView(draft: draftMirror, onEdit: { newText in
|
||||
draftMirror = newText
|
||||
draftEdited?(newText)
|
||||
}, caretHint: flipBackCaret)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Reading toggle (#68)
|
||||
|
||||
private func toggleReading() {
|
||||
if reading {
|
||||
exitReading(caret: nil)
|
||||
} else {
|
||||
// Entry mapping: the editing caret's block scrolls to the top.
|
||||
readingState.entryLocation = session?.cursor.selectionLocation
|
||||
reading = true
|
||||
}
|
||||
}
|
||||
|
||||
private func exitReading(caret: Int?) {
|
||||
flipToken += 1
|
||||
// Toggle-back maps the reading scroll back (top visible block);
|
||||
// click-to-edit lands at the clicked paragraph (survives always).
|
||||
flipBackCaret = (caret ?? readingState.topSourceLocation ?? 0, flipToken)
|
||||
reading = false
|
||||
}
|
||||
|
||||
/// Extracted binding (SwiftFormat/SwiftLint closure_position peace).
|
||||
/// Dismissal without a button (Esc) = keep-local semantics, same as No.
|
||||
private var conflictBinding: Binding<Bool> {
|
||||
@@ -72,6 +149,9 @@ struct PostEditorView: View {
|
||||
|
||||
private var toolbar: some View {
|
||||
HStack {
|
||||
// #68: labeled toggle, far left, before the crumb.
|
||||
Button(reading ? "Edit" : "Read") { toggleReading() }
|
||||
.help(reading ? "Return to editing (⌘R)" : "Render this post (⌘R)")
|
||||
Text(crumb)
|
||||
.font(.system(size: 11, design: DesignTokens.mono))
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
@@ -147,18 +227,27 @@ private struct SaveStateDot: View {
|
||||
/// NSTextView in a scroll view; attributes are presentation-only over a plain
|
||||
/// store. Session mode: edits → session.edit (debounce), cursor → session,
|
||||
/// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
|
||||
/// #71: `caretHint` (location + token) lands the caret after a flip back
|
||||
/// from reading — applied once per token, after any generation load.
|
||||
struct ProseTextView: NSViewRepresentable {
|
||||
var session: EditorSession?
|
||||
var draft: String?
|
||||
var onEdit: ((String) -> Void)?
|
||||
var caretHint: (location: Int, token: Int)?
|
||||
|
||||
init(session: EditorSession) {
|
||||
init(session: EditorSession, caretHint: (location: Int, token: Int)? = nil) {
|
||||
self.session = session
|
||||
self.caretHint = caretHint
|
||||
}
|
||||
|
||||
init(draft: String, onEdit: @escaping (String) -> Void) {
|
||||
init(
|
||||
draft: String,
|
||||
onEdit: @escaping (String) -> Void,
|
||||
caretHint: (location: Int, token: Int)? = nil,
|
||||
) {
|
||||
self.draft = draft
|
||||
self.onEdit = onEdit
|
||||
self.caretHint = caretHint
|
||||
}
|
||||
|
||||
/// Cursor state snapshot from the live view (#66).
|
||||
@@ -181,7 +270,7 @@ struct ProseTextView: NSViewRepresentable {
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.usesFindBar = true
|
||||
tv.backgroundColor = NSColor.white
|
||||
tv.typingAttributes = ProsePresenter.bodyAttributes
|
||||
tv.typingAttributes = ProseTypography.bodyAttributes
|
||||
tv.delegate = context.coordinator
|
||||
tv.layoutManager?.allowsNonContiguousLayout = true
|
||||
tv.minSize = NSSize(width: 0, height: 0)
|
||||
@@ -228,6 +317,18 @@ struct ProseTextView: NSViewRepresentable {
|
||||
// only reload when the textview genuinely diverges (new draft).
|
||||
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
|
||||
}
|
||||
// #71: flip-back caret — apply once per token, after any load above.
|
||||
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
|
||||
context.coordinator.appliedCaretToken = hint.token
|
||||
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)
|
||||
if let session {
|
||||
session.cursorUpdate(ProseTextView.cursorState(of: tv))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
@@ -239,6 +340,7 @@ struct ProseTextView: NSViewRepresentable {
|
||||
weak var textView: NSTextView?
|
||||
var sessionRef: EditorSession?
|
||||
var loadedGeneration = -1
|
||||
var appliedCaretToken = -1
|
||||
|
||||
init(representable: ProseTextView) {
|
||||
onEdit = representable.onEdit
|
||||
@@ -250,7 +352,7 @@ struct ProseTextView: NSViewRepresentable {
|
||||
// Re-attribute the paragraph(s) touching the selection — one pass.
|
||||
let paragraphRange = (storage.string as NSString).paragraphRange(for: sel)
|
||||
ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: paragraphRange)
|
||||
tv.typingAttributes = ProsePresenter.bodyAttributes
|
||||
tv.typingAttributes = ProseTypography.bodyAttributes
|
||||
if let sessionRef {
|
||||
sessionRef.edit(storage.string)
|
||||
} else {
|
||||
|
||||
@@ -71,30 +71,27 @@ nonisolated enum ProsePresenter {
|
||||
dimSyntax(in: out, range: paragraphRange)
|
||||
}
|
||||
|
||||
// Typography: Iowan Old Style prose stance (the export's stack), 17pt body,
|
||||
// scaled headings.
|
||||
// Typography: the #70 role slots (ProseTypography) — Body / Headings /
|
||||
// Code — shared with reading mode; editing chrome (dimmed syntax) rides
|
||||
// the Code slot.
|
||||
static var bodyFont: NSFont {
|
||||
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
|
||||
?? NSFont.systemFont(ofSize: 17)
|
||||
ProseTypography.bodyFont
|
||||
}
|
||||
|
||||
static var bodyAttributes: [NSAttributedString.Key: Any] {
|
||||
[
|
||||
.font: bodyFont,
|
||||
.paragraphStyle: paragraph(.body),
|
||||
.foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
|
||||
]
|
||||
ProseTypography.bodyAttributes
|
||||
}
|
||||
|
||||
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
|
||||
func headingFont(size: CGFloat, weight: Int) -> NSFont {
|
||||
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: weight, size: size)
|
||||
?? .boldSystemFont(ofSize: size)
|
||||
}
|
||||
switch kind {
|
||||
case .heading1: return [.font: headingFont(size: 26, weight: 9), .paragraphStyle: paragraph(.heading1)]
|
||||
case .heading2: return [.font: headingFont(size: 20, weight: 8), .paragraphStyle: paragraph(.heading2)]
|
||||
case .quote, .syntaxOnly, .body: return bodyAttributes
|
||||
case .heading1:
|
||||
[.font: ProseTypography.headingFont, .paragraphStyle: paragraph(.heading1)]
|
||||
case .heading2:
|
||||
[
|
||||
.font: ProseTypography.headingFont(size: (ProseTypography.headingFont.pointSize * 0.77).rounded()),
|
||||
.paragraphStyle: paragraph(.heading2),
|
||||
]
|
||||
case .quote, .syntaxOnly, .body: bodyAttributes
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,7 +108,10 @@ nonisolated enum ProsePresenter {
|
||||
case .quote: 2
|
||||
default: 0
|
||||
}
|
||||
let dim: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor(white: 0.55, alpha: 1), .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)]
|
||||
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)))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
|
||||
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).
|
||||
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
|
||||
|
||||
/// 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,
|
||||
])
|
||||
}
|
||||
|
||||
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.
|
||||
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))
|
||||
}
|
||||
|
||||
static var italicBodyFont: NSFont {
|
||||
NSFontManager.shared.convert(bodyFont, toHaveTrait: .italicFontMask)
|
||||
}
|
||||
|
||||
static var boldBodyFont: NSFont {
|
||||
bolded(bodyFont)
|
||||
}
|
||||
|
||||
// MARK: Attribute stacks (reading + editing share them)
|
||||
|
||||
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).
|
||||
static var syntaxColor: NSColor {
|
||||
NSColor(white: 0.55, alpha: 1)
|
||||
}
|
||||
|
||||
static var quoteRuleColor: NSColor {
|
||||
NSColor(white: 0.78, alpha: 1)
|
||||
}
|
||||
|
||||
/// Table borders + reading HR hairline (≈ DesignTokens.border).
|
||||
static var tableBorderColor: NSColor {
|
||||
NSColor(red: 0xE8 / 255, green: 0xE5 / 255, blue: 0xDF / 255, alpha: 1)
|
||||
}
|
||||
|
||||
static var bodyAttributes: [NSAttributedString.Key: Any] {
|
||||
[
|
||||
.font: bodyFont,
|
||||
.paragraphStyle: ProsePresenter.paragraph(.body),
|
||||
.foregroundColor: foregroundColor,
|
||||
]
|
||||
}
|
||||
|
||||
static var codeAttributes: [NSAttributedString.Key: Any] {
|
||||
[
|
||||
.font: codeFont,
|
||||
.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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
//
|
||||
// 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).
|
||||
//
|
||||
|
||||
import AppKit
|
||||
|
||||
/// Reading-mode presentation: text → rendered blocks. Pure over its input;
|
||||
/// called on the main actor (NSTextTable construction is MainActor).
|
||||
enum ReadingPresenter {
|
||||
/// One rendered block. `sourceRange` is the block's UTF-16 range in the
|
||||
/// source text (delimiter-exclusive) — the #68 click→edit map.
|
||||
struct Block {
|
||||
let content: NSAttributedString
|
||||
let sourceRange: NSRange
|
||||
/// Popover image URL for an `` chunk (#69 hover floor).
|
||||
let imageURL: URL?
|
||||
}
|
||||
|
||||
/// 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?
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
if out.length > 0, !out.string.hasSuffix("\n") {
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
}
|
||||
let start = out.length
|
||||
out.append(block.content)
|
||||
let image = block.imageURL.flatMap { raw -> URL? in
|
||||
guard raw.scheme == nil, let postFolder else { return raw }
|
||||
return postFolder.appendingPathComponent(raw.path)
|
||||
}
|
||||
bounds.append(Bound(
|
||||
docRange: NSRange(location: start, length: out.length - start),
|
||||
sourceRange: block.sourceRange,
|
||||
imageURL: image,
|
||||
))
|
||||
}
|
||||
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).
|
||||
static func blocks(for text: String) -> [Block] {
|
||||
var out: [Block] = []
|
||||
let ns = text as NSString
|
||||
var loc = 0
|
||||
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))
|
||||
}
|
||||
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) -> Block {
|
||||
if let url = imageURL(in: chunk) {
|
||||
return Block(content: inlineParse(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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
return Block(content: flowContent(lines, first: first), sourceRange: sourceRange, imageURL: nil)
|
||||
}
|
||||
|
||||
// MARK: Flow blocks
|
||||
|
||||
private static func flowContent(_ lines: [String], first: String) -> NSAttributedString {
|
||||
if let level = headingLevel(first) {
|
||||
let body = first.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces)
|
||||
return headingContent(body, level: level)
|
||||
}
|
||||
if first.hasPrefix("```") {
|
||||
let inner = lines.dropFirst().dropLast(hasClosingFence(lines) ? 1 : 0)
|
||||
return codeContent(inner.joined(separator: "\n"))
|
||||
}
|
||||
if lines.count >= 2, isTableDelimiterRow(lines[1]), let table = tableContent(lines) {
|
||||
return table
|
||||
}
|
||||
// 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: " ")
|
||||
return inlineParse(joined)
|
||||
}
|
||||
|
||||
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.paragraphSpacing = level <= 2 ? 10 : 8
|
||||
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.paragraphSpacing = 10
|
||||
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 {
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.textBlocks = [RuleTextBlock()]
|
||||
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.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 {
|
||||
let out = NSMutableAttributedString()
|
||||
let quoteBlock = QuoteTextBlock()
|
||||
for (index, line) in lines.enumerated() {
|
||||
let depth = blockquoteDepth(line)
|
||||
let indent = CGFloat(6 + (depth - 1) * 18)
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.textBlocks = [quoteBlock]
|
||||
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: simple 1px-bordered NSTextTable; delimiter-row
|
||||
|
||||
// alignment honored — cheap once the delimiter is parsed anyway)
|
||||
|
||||
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 table = NSTextTable()
|
||||
table.numberOfColumns = header.count
|
||||
table.collapsesBorders = true
|
||||
table.setBorderColor(ProseTypography.tableBorderColor)
|
||||
table.setWidth(1, type: .absolute, for: .border)
|
||||
let out = NSMutableAttributedString()
|
||||
var row = 0
|
||||
for (index, line) in lines.enumerated() {
|
||||
if index == 1 {
|
||||
continue
|
||||
} // delimiter row
|
||||
let cells = tableCells(line)
|
||||
for column in 0 ..< header.count {
|
||||
let text = column < cells.count ? cells[column] : ""
|
||||
let cell = NSTextTableBlock(
|
||||
table: table, startingRow: row, rowSpan: 1,
|
||||
startingColumn: column, columnSpan: 1
|
||||
)
|
||||
cell.setWidth(1, type: .absolute, for: .border)
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.textBlocks = [cell]
|
||||
ps.alignment = aligns[column]
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: row == 0 ? ProseTypography.boldBodyFont : ProseTypography.bodyFont,
|
||||
.paragraphStyle: ps,
|
||||
.foregroundColor: ProseTypography.foregroundColor,
|
||||
]
|
||||
out.append(NSAttributedString(
|
||||
string: text + (column == header.count - 1 ? "\n" : ""),
|
||||
attributes: attrs
|
||||
))
|
||||
}
|
||||
row += 1
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
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
|
||||
} else {
|
||||
var font = ProseTypography.bodyFont
|
||||
if intent.contains(.emphasized) {
|
||||
font = ProseTypography.italicBodyFont
|
||||
}
|
||||
if intent.contains(.stronglyEmphasized) {
|
||||
font = ProseTypography.boldBodyFont
|
||||
}
|
||||
attrs[.font] = font
|
||||
}
|
||||
}
|
||||
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,
|
||||
))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// 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)))
|
||||
}
|
||||
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)))
|
||||
}
|
||||
|
||||
private static func indentLevel(_ spaces: Int) -> Int {
|
||||
spaces <= 1 ? 1 : (spaces <= 3 ? 2 : min(3 + (spaces - 4) / 2, 6))
|
||||
}
|
||||
|
||||
/// `>`-prefix depth (1 for `> `, 2 for `>> `; spaces tolerated).
|
||||
private static func blockquoteDepth(_ line: String) -> Int {
|
||||
line.prefix { $0 == ">" || $0 == " " }.filter { $0 == ">" }.count
|
||||
}
|
||||
|
||||
/// `# `-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 == ":" }
|
||||
}
|
||||
}
|
||||
|
||||
private static func hasClosingFence(_ lines: [String]) -> Bool {
|
||||
guard let last = lines.last else { return false }
|
||||
return last.trimmingCharacters(in: .whitespaces).hasPrefix("```")
|
||||
}
|
||||
|
||||
/// `` → 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]))
|
||||
}
|
||||
}
|
||||
|
||||
/// Hairline-left text block for blockquotes (#69).
|
||||
final nonisolated class QuoteTextBlock: NSTextBlock {
|
||||
override func drawBackground(
|
||||
withFrame frameRect: NSRect, in _: NSView?,
|
||||
characterRange _: NSRange, layoutManager _: NSLayoutManager,
|
||||
) {
|
||||
let path = NSBezierPath()
|
||||
path.move(to: NSPoint(x: frameRect.minX + 2, y: frameRect.minY))
|
||||
path.line(to: NSPoint(x: frameRect.minX + 2, y: frameRect.maxY))
|
||||
path.lineWidth = 2
|
||||
ProseTypography.quoteRuleColor.setStroke()
|
||||
path.stroke()
|
||||
}
|
||||
}
|
||||
|
||||
/// Full-width hairline text block for horizontal rules (#69).
|
||||
final nonisolated class RuleTextBlock: NSTextBlock {
|
||||
override func drawBackground(
|
||||
withFrame frameRect: NSRect, in _: NSView?,
|
||||
characterRange _: NSRange, layoutManager _: NSLayoutManager,
|
||||
) {
|
||||
let midY = frameRect.midY
|
||||
let path = NSBezierPath()
|
||||
path.move(to: NSPoint(x: frameRect.minX, y: midY))
|
||||
path.line(to: NSPoint(x: frameRect.maxX, y: midY))
|
||||
path.lineWidth = 1
|
||||
ProseTypography.tableBorderColor.setStroke()
|
||||
path.stroke()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//
|
||||
// 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).
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Live reading-position state for flip-back scroll mapping (#68). Plain
|
||||
/// class held `@State` by the editor — reference identity survives renders.
|
||||
final class ReadingStateBox {
|
||||
/// Source caret location when reading opened — scrolls that block to the
|
||||
/// top (#68 entry mapping).
|
||||
var entryLocation: Int?
|
||||
/// Source location of the top visible block; updated as reading scrolls
|
||||
/// (#68 flip-back mapping).
|
||||
var topSourceLocation: Int?
|
||||
}
|
||||
|
||||
/// One-shot caret placement for the editing surface (#68): set when reading
|
||||
/// flips back (click-to-edit or toggle-back), consumed by ProseTextView.
|
||||
final class CaretHintBox {
|
||||
var location: Int?
|
||||
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).
|
||||
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.
|
||||
var postFolder: URL?
|
||||
/// UTF-16 caret location captured when reading opened; scrolls the
|
||||
/// containing 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]
|
||||
tv.textContainer?.containerSize = NSSize(width: 640, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.textContainer?.widthTracksTextView = false
|
||||
tv.textContainer?.lineFragmentPadding = 12
|
||||
tv.textContainerInset = NSSize(width: 0, height: 20)
|
||||
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
|
||||
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 = ""
|
||||
}
|
||||
}
|
||||
|
||||
/// 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?
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
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)
|
||||
return
|
||||
}
|
||||
}
|
||||
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)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,48 @@
|
||||
// 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.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Settings pane. #17 scope: the Home control only — further settings arrive
|
||||
/// with their tickets. Choosing a folder repoints Museion at that root;
|
||||
/// content is never moved.
|
||||
/// Settings pane. Home control per #17; typography slots per #70.
|
||||
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
|
||||
}
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
}
|
||||
.background(DesignTokens.background)
|
||||
}
|
||||
|
||||
// MARK: Home (#17)
|
||||
|
||||
private var contentSection: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Content")
|
||||
.font(.system(size: 13, weight: .semibold))
|
||||
@@ -33,9 +63,32 @@ struct SettingsPaneView: View {
|
||||
.font(.callout)
|
||||
.foregroundStyle(DesignTokens.muted)
|
||||
}
|
||||
.padding(24)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
.background(DesignTokens.background)
|
||||
}
|
||||
|
||||
// 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() {
|
||||
@@ -49,3 +102,54 @@ 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) },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//
|
||||
// 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).
|
||||
//
|
||||
|
||||
import AppKit
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
struct ReadingPresenterTests {
|
||||
/// Blank-line split + heading fonting + markup hidden.
|
||||
@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."))
|
||||
}
|
||||
|
||||
/// Auto-renumbering: `1. 1. 1.` renders 1, 2, 3; source never rewritten.
|
||||
@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"))
|
||||
}
|
||||
|
||||
/// Nesting: deeper items indent further; mixed bullet/number nesting rides
|
||||
/// the same path.
|
||||
@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`() {
|
||||
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 nsSrc = src as NSString
|
||||
let expected = nsSrc.range(of: "last para").location
|
||||
#expect(doc.bounds[3].sourceRange.location == expected)
|
||||
}
|
||||
|
||||
/// Tables render as NSTextTable blocks with header bold.
|
||||
@Test
|
||||
func `table renders`() {
|
||||
let src = "| A | B |\n| --- | --- |\n| one | two |"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.content.string.contains("one"))
|
||||
#expect(doc.content.string.contains("two"))
|
||||
let hasTableBlock = doc.content.enumerateAttribute(
|
||||
.paragraphStyle, in: NSRange(location: 0, length: doc.content.length),
|
||||
) { value, _, stop in
|
||||
if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is NSTextTableBlock }) {
|
||||
stop.pointee = true
|
||||
}
|
||||
}
|
||||
_ = hasTableBlock // enumerate returns Void; assertion below is the check
|
||||
// direct check: at least one NSTextTableBlock anywhere
|
||||
var found = false
|
||||
doc.content.enumerateAttribute(
|
||||
.paragraphStyle, in: NSRange(location: 0, length: doc.content.length),
|
||||
) { value, _, _ in
|
||||
if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is NSTextTableBlock }) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
#expect(found)
|
||||
}
|
||||
|
||||
/// Fenced code: mono face, markers hidden, content intact.
|
||||
@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)
|
||||
}
|
||||
|
||||
/// Blockquote: markers hidden, hairline block attached.
|
||||
@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"))
|
||||
var foundQuoteBlock = false
|
||||
doc.content.enumerateAttribute(
|
||||
.paragraphStyle, in: NSRange(location: 0, length: doc.content.length),
|
||||
) { value, _, _ in
|
||||
if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is QuoteTextBlock }) {
|
||||
foundQuoteBlock = true
|
||||
}
|
||||
}
|
||||
#expect(foundQuoteBlock)
|
||||
}
|
||||
|
||||
/// Links styled + attribute retained (⌘-click opens).
|
||||
@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)
|
||||
}
|
||||
|
||||
/// Images: hover payload carried on the bound, syntax stays text.
|
||||
@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"))
|
||||
}
|
||||
|
||||
/// 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: hairline block, 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)
|
||||
var foundRule = false
|
||||
doc.content.enumerateAttribute(
|
||||
.paragraphStyle, in: NSRange(location: 0, length: doc.content.length),
|
||||
) { value, _, _ in
|
||||
if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is RuleTextBlock }) {
|
||||
foundRule = true
|
||||
}
|
||||
}
|
||||
#expect(foundRule)
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
```txt
|
||||
code
|
||||
```
|
||||
|
||||
| H |
|
||||
| --- |
|
||||
| c |
|
||||
|
||||

|
||||
|
||||
[link](https://x.de)
|
||||
|
||||
* * *
|
||||
"""
|
||||
let doc = ReadingPresenter.document(for: sink, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count >= 9)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 651 B |
@@ -0,0 +1,66 @@
|
||||
# Kitchen sink
|
||||
|
||||
This post exercises every construct the reading renderer must render — one of each, plus the nesting and auto-numbering cases. Not for reading pleasure; for calibration of constructs absent from the corpus.
|
||||
|
||||
## Lists
|
||||
|
||||
Bulleted, ordered, nested, and deliberately mis-numbered source (`1. 1. 1.` must read 1, 2, 3):
|
||||
|
||||
- top bullet one
|
||||
- top bullet two
|
||||
- nested bullet two-one
|
||||
- nested bullet two-two
|
||||
- deeper nesting, four-space style
|
||||
- back to top level
|
||||
|
||||
1. first
|
||||
1. second, source says 1
|
||||
1. third, source still says 1
|
||||
|
||||
1. outer one
|
||||
1. inner one
|
||||
1. inner two
|
||||
2. outer two
|
||||
|
||||
Mixed nesting:
|
||||
|
||||
2. numbered top
|
||||
- bullet under a number
|
||||
- bullet deeper
|
||||
|
||||
## Table
|
||||
|
||||
| Construct | State | Notes |
|
||||
| --- | :---: | --- |
|
||||
| bullets | rendered | hanging indent |
|
||||
| ordered | rendered | auto-renumbered |
|
||||
| table | rendered | 1px border, centred `---:` cell |
|
||||
|
||||
## Quote
|
||||
|
||||
> A blockquote line carrying _italic_ and `code`.
|
||||
|
||||
>> Nested quote: one level deeper via the doubled marker.
|
||||
|
||||
## Code
|
||||
|
||||
```swift
|
||||
let calm = true
|
||||
// fenced block: mono face, no inline parse
|
||||
```
|
||||
|
||||
## Image
|
||||
|
||||
Hover shows the picture; the line itself stays text:
|
||||
|
||||

|
||||
|
||||
## Inline
|
||||
|
||||
A paragraph with _emphasis_, **strong**, `inline code`, and a [link](https://babylondreams.de) — plain click drops to editing per #68; ⌘-click opens.
|
||||
|
||||
## Rule
|
||||
|
||||
* * *
|
||||
|
||||
End of the sink.
|
||||
Reference in new issue
Block a user