diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index 7307c03..1adb17d 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -317,6 +317,7 @@ struct ProseTextView: NSViewRepresentable { // pre-edit text — then session.edit on the stale view would // have flushed it over the user's real content (#71 fix). tv.textStorage?.setAttributedString(ProsePresenter.attribute(session.text)) + context.coordinator.fenceDelims = ProsePresenter.fenceDelimCount(session.text) // #66: restore cursor (clamped) + scroll. let length = (tv.string as NSString).length var cursor = session.restoreCursor ?? PostStore.CursorState() @@ -367,6 +368,10 @@ struct ProseTextView: NSViewRepresentable { var sessionRef: EditorSession? var loadedGeneration = -1 var appliedCaretToken = -1 + /// #77: fence delimiter count — the cross-paragraph fence state + /// fingerprint. A moved count means a ``` was typed/deleted and every + /// line until the matching delimiter changed kind. + var fenceDelims = 0 init(representable: ProseTextView) { onEdit = representable.onEdit @@ -375,9 +380,19 @@ struct ProseTextView: NSViewRepresentable { func textDidChange(_ notification: Notification) { guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return } let sel = tv.selectedRange() - // 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) + let delims = ProsePresenter.fenceDelimCount(storage.string) + if delims == fenceDelims { + // 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) + } else { + // Delimiter typed/deleted: fence state flipped downstream — + // restyle the whole document, keeping the caret put. + fenceDelims = delims + let selected = tv.selectedRange() + tv.textStorage?.setAttributedString(ProsePresenter.attribute(storage.string)) + tv.setSelectedRange(selected) + } tv.typingAttributes = ProseTypography.bodyAttributes if let sessionRef { sessionRef.edit(storage.string) diff --git a/Museion/ProsePresenter.swift b/Museion/ProsePresenter.swift index bff5ffc..098ab31 100644 --- a/Museion/ProsePresenter.swift +++ b/Museion/ProsePresenter.swift @@ -38,10 +38,10 @@ nonisolated enum ProsePresenter { classify(line, inFence: false) } + /// Delimiter lines are fences even inside a fence (they close it) — so the + /// delim test runs before the inFence shortcut and `applyStyles` toggles + /// on `kind == .fence` instead of re-deriving the prefix. static func classify(_ line: String, inFence: Bool) -> LineKind { - if inFence { - return .fenceInterior - } let trimmed = line.drop(while: { $0 == " " || $0 == "\t" }) if trimmed.isEmpty { return .blank @@ -49,8 +49,11 @@ nonisolated enum ProsePresenter { if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { return .fence } + if inFence { + return .fenceInterior + } let hashes = trimmed.prefix(while: { $0 == "#" }).count - if hashes > 0 { + if hashes > 0, hashes <= 6 { // CommonMark caps at 6; 7+ is body let after = trimmed.dropFirst(hashes) if after.hasPrefix(" ") || after.isEmpty { switch hashes { @@ -67,7 +70,7 @@ nonisolated enum ProsePresenter { if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) { return .syntaxOnly } - if listMarkerRegex.firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) != nil { + if line.firstMatch(of: listMarkerPattern) != nil { return .listMarker } return .body @@ -85,10 +88,27 @@ nonisolated enum ProsePresenter { /// Attribute one paragraph (editing-time re-apply). Cheap: the paragraph's /// lines plus a fence-state scan of the prefix. + /// NOTE fence state crosses paragraphs: the coordinator (PostEditorView) + /// compares the delimiter count per edit and routes to a full-document + /// `attribute` pass when it moved — typing/deleting a ``` flips every line + /// until the matching delimiter. static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) { applyStyles(out, range: paragraphRange) } + /// Number of fence delimiter lines (``` or ~~~ prefixes) — the cheap + /// fingerprint the coordinator compares per edit. + static func fenceDelimCount(_ text: String) -> Int { + var count = 0 + for line in text.split(separator: "\n", omittingEmptySubsequences: false) { + let trimmed = line.drop(while: { $0 == " " || $0 == "\t" }) + if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") { + count += 1 + } + } + return count + } + // MARK: Styling pass private static func applyStyles(_ out: NSMutableAttributedString, range: NSRange) { @@ -99,10 +119,8 @@ nonisolated enum ProsePresenter { inFence = fenceState(nsText, upTo: range.location) } for line in contentLines(nsText, in: range) { - let trimmed = line.text.drop(while: { $0 == " " || $0 == "\t" }) - let isDelim = !line.text.isEmpty && !trimmed.isEmpty && (trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~")) - let kind = isDelim ? LineKind.fence : classify(line.text, inFence: inFence) - if isDelim { + let kind = classify(line.text, inFence: inFence) + if kind == .fence { inFence.toggle() } styleLine(out, line: line, kind: kind) @@ -145,26 +163,10 @@ nonisolated enum ProsePresenter { /// Count unclosed fences before `end` (``` or ~~~ delim lines toggle). private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool { var inFence = false - var loc = 0 - while loc < end { - let full = nsText.lineRange(for: NSRange(location: loc, length: 0)) - var len = full.length - while len > 0 { - let char = nsText.character(at: full.location + len - 1) - if char == 0x0A || char == 0x0D { - len -= 1 - } else { - break - } + for line in contentLines(nsText, in: NSRange(location: 0, length: min(end, nsText.length))) { + if classify(line.text, inFence: inFence) == .fence { + inFence.toggle() } - if len > 0 { - let line = (nsText.substring(with: NSRange(location: full.location, length: len)) as String) - .drop(while: { $0 == " " || $0 == "\t" }) - if line.hasPrefix("```") || line.hasPrefix("~~~") { - inFence.toggle() - } - } - loc = NSMaxRange(full) } return inFence } @@ -175,24 +177,26 @@ nonisolated enum ProsePresenter { let dim = ProseTypography.codeAttributes // codeFont + syntaxColor switch kind { case .heading1, .heading2, .heading3, .heading4Plus: - let lead = line.text.prefix(while: { $0 == " " }).utf16.count + let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead)) if marker.length > 0 { out.addAttributes(dim, range: marker) } case .quote: - if let marker = markerRange(quoteMarkerRegex, in: line.text), marker.length > 0 { + if let marker = markerRangeUTF16(quoteMarkerPattern, in: line.text), marker.length > 0 { out.addAttributes(dim, range: shifted(marker, into: line.content)) } case .listMarker: - if let marker = markerRange(listMarkerRegex, in: line.text), marker.length > 0 { + if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 { out.addAttributes(dim, range: shifted(marker, into: line.content)) } - case .syntaxOnly, .fence: + case .syntaxOnly: if line.content.length > 0 { out.addAttributes(dim, range: line.content) } + case .fence: + break // attributes(for: .fence) already carries codeFont + syntaxColor case .fenceInterior, .blank, .body: break } @@ -325,14 +329,6 @@ nonisolated enum ProsePresenter { // MARK: Base attributes - static var bodyFont: NSFont { - ProseTypography.bodyFont - } - - static var bodyAttributes: [NSAttributedString.Key: Any] { - ProseTypography.bodyAttributes - } - static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] { switch kind { case .heading1: @@ -408,16 +404,15 @@ nonisolated enum ProsePresenter { // MARK: Pattern helpers - /// Marker dimming for quote / list lines — returns the marker's NSRange in - /// `line.text`, or nil. - // Static literal patterns — compile by construction. - // swiftlint:disable:next force_try - private static let listMarkerRegex = try! NSRegularExpression(pattern: #"^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)"#) - // swiftlint:disable:next force_try - private static let quoteMarkerRegex = try! NSRegularExpression(pattern: #"^(?:\s*>(?:\s|$))*"#) + // Marker patterns (regex literals, like the inline ones below). + private nonisolated(unsafe) static let listMarkerPattern = /^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)/ + private nonisolated(unsafe) static let quoteMarkerPattern = /^(?:\s*>(?:\s|$))*/ - private static func markerRange(_ regex: NSRegularExpression, in lineText: String) -> NSRange? { - regex.firstMatch(in: lineText, range: NSRange(location: 0, length: (lineText as NSString).length))?.range + /// UTF-16 NSRange of the marker in `lineText`, or nil. + private static func markerRangeUTF16(_ pattern: Regex, in lineText: String) -> NSRange? { + guard let match = lineText.firstMatch(of: pattern) else { return nil } + let utf16 = match.range.utf16Range(in: lineText) + return NSRange(location: utf16.lowerBound, length: utf16.count) } /// Mark-boundary helpers (no lookbehind in swift-regex): the Character diff --git a/Museion/ProseTypography.swift b/Museion/ProseTypography.swift index b2f2b34..45eb663 100644 --- a/Museion/ProseTypography.swift +++ b/Museion/ProseTypography.swift @@ -25,55 +25,43 @@ nonisolated enum ProseTypography { /// 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: bodySize) ?? NSFont.systemFont(ofSize: bodySize) - } + /// ponytail: nonisolated(unsafe) — NSFont isn't Sendable; the cached + /// instances are never mutated after creation. + nonisolated(unsafe) static let bodyFont: NSFont = .init(name: "ValkyrieOTBRegular", size: bodySize) ?? NSFont.systemFont(ofSize: bodySize) /// 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: heading1Size) ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold) - } + nonisolated(unsafe) static let headingFont: NSFont = .init(name: "ConcourseOT6Semibold", size: heading1Size) ?? NSFont.systemFont(ofSize: heading1Size, weight: .semibold) /// h2 = the headings face at CSS's 0.85× ladder step (#77). - static var heading2Font: NSFont { - NSFont(name: "ConcourseOT6Semibold", size: heading2Size) ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold) - } + nonisolated(unsafe) static let heading2Font: NSFont = .init(name: "ConcourseOT6Semibold", size: heading2Size) ?? NSFont.systemFont(ofSize: heading2Size, weight: .semibold) /// h3 = body face, sized up, weight 600 (CSS h3: body-face w600). The B /// cut has no 600 member — the bold trait (700, real or synthesized) is /// the nearest expressible. ponytail: trait-convert; a true semibold face /// would drop in here if ever installed. - static var heading3Font: NSFont { - NSFontManager.shared.convert( - NSFontManager.shared.convert(bodyFont, toSize: heading3Size), - toHaveTrait: .boldFontMask, - ) - } + nonisolated(unsafe) static let heading3Font: NSFont = NSFontManager.shared.convert( + NSFontManager.shared.convert(bodyFont, toSize: heading3Size), + toHaveTrait: .boldFontMask, + ) /// h4+ floors at bold body (CSS h4–h6). - static var headingBoldFont: NSFont { - NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask) - } + nonisolated(unsafe) static let headingBoldFont: NSFont = NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask) /// Code slot (inline code, fenced blocks, editing syntax dim). - static var codeFont: NSFont { - NSFont(name: "UbuntuMonoNFM", size: codeSize) ?? NSFont.monospacedSystemFont(ofSize: codeSize, weight: .regular) - } + nonisolated(unsafe) static let codeFont: NSFont = .init(name: "UbuntuMonoNFM", size: codeSize) ?? NSFont.monospacedSystemFont(ofSize: codeSize, weight: .regular) /// Blank source lines at 9pt (#77 half-height separators). - static var blankFont: NSFont { - NSFontManager.shared.convert(bodyFont, toSize: blankSize) - } + nonisolated(unsafe) static let blankFont: NSFont = NSFontManager.shared.convert(bodyFont, toSize: blankSize) /// Editor measure (#77): reading.css `--measure: 66ch` — the advance of /// "0" × 66 in the body face (px→pt 1:1), + the text container's 24pt /// lineFragmentPadding on both sides (the CSS body's 24px side padding). - static var measureWidth: CGFloat { + static let measureWidth: CGFloat = { let zero = NSAttributedString(string: "0", attributes: [.font: bodyFont]) let ch = zero.size().width return (ch * 66).rounded() + 48 - } + }() /// Line-height parity with reading.css (#77): CSS `line-height: n` means /// n × font-size pixels; TextKit's lineHeightMultiple multiplies the @@ -85,13 +73,9 @@ nonisolated enum ProseTypography { return (font.pointSize * cssLineHeight) / natural } - static var italicBodyFont: NSFont { - NSFontManager.shared.convert(bodyFont, toHaveTrait: .italicFontMask) - } + nonisolated(unsafe) static let italicBodyFont: NSFont = NSFontManager.shared.convert(bodyFont, toHaveTrait: .italicFontMask) - static var boldBodyFont: NSFont { - NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask) - } + nonisolated(unsafe) static let boldBodyFont: NSFont = NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask) // MARK: Attribute stacks (editing surface) @@ -104,10 +88,6 @@ nonisolated enum ProseTypography { NSColor(white: 0.55, alpha: 1) } - static var quoteRuleColor: NSColor { - NSColor(white: 0.78, alpha: 1) - } - /// Secondary ink — reading.css --secondary #48484d (quotes, #77). static var secondaryColor: NSColor { NSColor(red: 0x48 / 255, green: 0x48 / 255, blue: 0x4D / 255, alpha: 1) @@ -123,11 +103,6 @@ nonisolated enum ProseTypography { NSColor(red: 0xF5 / 255, green: 0xF5 / 255, blue: 0xF7 / 255, alpha: 1) } - /// Table borders + editing-surface hairline (≈ DesignTokens.border). - static var tableBorderColor: NSColor { - NSColor(red: 0xE8 / 255, green: 0xE5 / 255, blue: 0xDF / 255, alpha: 1) - } - static var bodyAttributes: [NSAttributedString.Key: Any] { [ .font: bodyFont, diff --git a/MuseionTests/ProsePresenterTests.swift b/MuseionTests/ProsePresenterTests.swift index 8feefeb..2d6fcee 100644 --- a/MuseionTests/ProsePresenterTests.swift +++ b/MuseionTests/ProsePresenterTests.swift @@ -119,16 +119,34 @@ struct ProsePresenterTests { } @Test func `fences interior retrofit`() { - // reattribute over a paragraph inside an existing fence — state comes - // from the prefix scan, not the paragraph alone. - let full = "```\nfirst\n```\n\npara\n" + // Reattribute a paragraph INSIDE a fence at location > 0 — the + // fence state must come from the prefix scan, not the paragraph. + let full = "para before\n\n```\nfirst code\n```\n\nafter" let out = NSMutableAttributedString(attributedString: ProsePresenter.attribute(full)) let ns = full as NSString - let para = ns.paragraphRange(for: NSRange(location: 0, length: 0)) // "```" + let firstRange = ns.range(of: "first code") + // clobber the line to body, then reattribute its paragraph + out.setAttributes(ProseTypography.bodyAttributes, range: firstRange) + let para = ns.paragraphRange(for: NSRange(location: firstRange.location, length: 0)) ProsePresenter.reattribute(out, paragraphRange: para) - let loc = ns.range(of: "first").location - let font = out.attribute(.font, at: loc, effectiveRange: nil) as? NSFont + let font = out.attribute(.font, at: firstRange.location, effectiveRange: nil) as? NSFont #expect(font?.pointSize == 14) + + // Outside the fence (prefix scan returns false): body styling. + let afterRange = ns.range(of: "after") + out.setAttributes([.font: ProseTypography.codeFont], range: afterRange) + let afterPara = ns.paragraphRange(for: NSRange(location: afterRange.location, length: 0)) + ProsePresenter.reattribute(out, paragraphRange: afterPara) + let afterFont = out.attribute(.font, at: afterRange.location, effectiveRange: nil) as? NSFont + #expect(afterFont?.pointSize == 17) + } + + @Test func `fence delim count tracks delimiters`() { + #expect(ProsePresenter.fenceDelimCount("plain") == 0) + #expect(ProsePresenter.fenceDelimCount("```\ncode\n```") == 2) + #expect(ProsePresenter.fenceDelimCount("~~~\ncode\n```") == 2) + #expect(ProsePresenter.fenceDelimCount("```js\nlet x = 1\n```") == 2) + #expect(ProsePresenter.fenceDelimCount("not ``` inline, a fence needs line start") == 0) } @Test func `underscore in word not italic`() {