feat(editor): reading-parity presentation for the editing surface (#77)
ProsePresenter rewritten to mirror the calm-ruled reading surface (#78): - leading calibrated to CSS 1.8 via font metrics (not the raw number) - heading ladder 30/22/19-w600, h4+ bold body, new h3/h4+/fence/blank kinds - half-height blank separators (9pt) - quotes secondary-ink + 20pt indent; fence interiors mono-14 on substrate - inline traits: bold, italic (CommonMark intraword _ rule), code, links (label ink + underline, marks dim); list markers dim - 11 new tests pin the ladder, blanks, quote, fence, traits
This commit is contained in:
1 parent
1a5f04c9f4
commit
8fe5f48e0e
3 files changed
+593
-77
No files matched your search
+386
-72
@@ -8,73 +8,323 @@
|
||||
// the source of truth; attributes ride on top and re-apply per edited
|
||||
// paragraph. The Fix-Card anchor search stays with M2 (#25) — not lifted.
|
||||
//
|
||||
// #77: reading-parity rework — the editing surface now mirrors the calm-ruled
|
||||
// reading.css values (#78): leading 1.8-equivalent, heading ladder 30/22/19
|
||||
// (h3) with h4+ flooring at bold body, half-height blank separators, quote
|
||||
// secondary ink + indent, fence interiors as mono code, dimmed list markers,
|
||||
// and real traits (bold/italic/code/link) on inline content. Marks stay
|
||||
// visible-dimmed everywhere — the plain store is the source of truth.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
|
||||
/// Styled-source presentation (ADR-0010 mode B): variable heading sizes,
|
||||
/// paragraph spacing, dimmed syntax. Pure functions over text; no AppKit view
|
||||
/// state. Colors are the spike's proven values (foreground ≈ DesignTokens
|
||||
/// foreground; the 0.55 syntax dim is deliberately lighter than muted).
|
||||
/// Styled-source presentation (ADR-0010 mode B): pure functions over text; no
|
||||
/// AppKit view state. Colors mirror reading.css tokens in ProseTypography.
|
||||
nonisolated enum ProsePresenter {
|
||||
enum LineKind { case heading1, heading2, quote, syntaxOnly, body }
|
||||
enum LineKind {
|
||||
case heading1, heading2, heading3, heading4Plus
|
||||
case quote
|
||||
case fence, fenceInterior
|
||||
case listMarker
|
||||
case syntaxOnly
|
||||
case blank
|
||||
case body
|
||||
}
|
||||
|
||||
// MARK: Classification
|
||||
|
||||
/// Context-free kind (no fence state) — headings/lists/quotes/rules/blank.
|
||||
static func lineKind(_ line: String) -> LineKind {
|
||||
let trimmedLine = line.drop(while: { $0 == " " })
|
||||
if trimmedLine.hasPrefix("## ") {
|
||||
return .heading2
|
||||
classify(line, inFence: false)
|
||||
}
|
||||
|
||||
static func classify(_ line: String, inFence: Bool) -> LineKind {
|
||||
if inFence {
|
||||
return .fenceInterior
|
||||
}
|
||||
if trimmedLine.hasPrefix("# ") {
|
||||
return .heading1
|
||||
let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
|
||||
if trimmed.isEmpty {
|
||||
return .blank
|
||||
}
|
||||
if trimmedLine.hasPrefix("> ") {
|
||||
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
|
||||
return .fence
|
||||
}
|
||||
let hashes = trimmed.prefix(while: { $0 == "#" }).count
|
||||
if hashes > 0 {
|
||||
let after = trimmed.dropFirst(hashes)
|
||||
if after.hasPrefix(" ") || after.isEmpty {
|
||||
switch hashes {
|
||||
case 1: return .heading1
|
||||
case 2: return .heading2
|
||||
case 3: return .heading3
|
||||
default: return .heading4Plus
|
||||
}
|
||||
}
|
||||
}
|
||||
if trimmed.hasPrefix(">") {
|
||||
return .quote
|
||||
}
|
||||
if !trimmedLine.isEmpty, trimmedLine.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
|
||||
if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
|
||||
return .syntaxOnly
|
||||
}
|
||||
if listMarkerRegex.firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) != nil {
|
||||
return .listMarker
|
||||
}
|
||||
return .body
|
||||
}
|
||||
|
||||
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
|
||||
// MARK: Entry points
|
||||
|
||||
/// Paragraph spacing per line kind, applied via NSParagraphStyle.
|
||||
/// ponytail: quote rides body spacing — attributes(for:) styles quotes
|
||||
/// as body anyway; dedicated quote spacing waits for #20's polish pass.
|
||||
static func paragraph(_: LineKind) -> NSParagraphStyle {
|
||||
let style = NSMutableParagraphStyle()
|
||||
// Edit mode shows blank source lines — the blank line IS the
|
||||
// separator. Only line height rides the flow knobs here; the
|
||||
// paragraph/heading spacing knobs are reading-mode only.
|
||||
style.lineHeightMultiple = ProseTypography.lineHeightMultiple
|
||||
style.paragraphSpacing = 0
|
||||
style.paragraphSpacingBefore = 0
|
||||
return style
|
||||
}
|
||||
|
||||
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed syntax.
|
||||
/// Attribute a whole text (initial load).
|
||||
static func attribute(_ text: String) -> NSAttributedString {
|
||||
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
|
||||
let out = NSMutableAttributedString(string: text, attributes: ProseTypography.bodyAttributes)
|
||||
let nsText = text as NSString
|
||||
nsText.enumerateSubstrings(in: NSRange(location: 0, length: nsText.length), options: [.byLines]) { line, range, _, _ in
|
||||
guard let line else { return }
|
||||
let kind = lineKind(line)
|
||||
out.setAttributes(Self.attributes(for: kind), range: range)
|
||||
dimSyntax(in: out, range: range)
|
||||
}
|
||||
applyStyles(out, range: NSRange(location: 0, length: nsText.length))
|
||||
return out
|
||||
}
|
||||
|
||||
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
|
||||
/// Attribute one paragraph (editing-time re-apply). Cheap: the paragraph's
|
||||
/// lines plus a fence-state scan of the prefix.
|
||||
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
|
||||
let line = (out.string as NSString).substring(with: paragraphRange)
|
||||
let kind = lineKind(line)
|
||||
out.setAttributes(Self.attributes(for: kind), range: paragraphRange)
|
||||
dimSyntax(in: out, range: paragraphRange)
|
||||
applyStyles(out, range: paragraphRange)
|
||||
}
|
||||
|
||||
// Typography: the #70 role slots (ProseTypography) — Body / Headings /
|
||||
// Code — shared with reading mode; editing chrome (dimmed syntax) rides
|
||||
// the Code slot.
|
||||
// MARK: Styling pass
|
||||
|
||||
private static func applyStyles(_ out: NSMutableAttributedString, range: NSRange) {
|
||||
let nsText = out.string as NSString
|
||||
guard range.length > 0, range.location >= 0 else { return }
|
||||
var inFence = false
|
||||
if range.location > 0, out.string.contains("```") || out.string.contains("~~~") {
|
||||
inFence = fenceState(nsText, upTo: range.location)
|
||||
}
|
||||
for line in contentLines(nsText, in: range) {
|
||||
let trimmed = line.text.drop(while: { $0 == " " || $0 == "\t" })
|
||||
let isDelim = !line.text.isEmpty && !trimmed.isEmpty && (trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~"))
|
||||
let kind = isDelim ? LineKind.fence : classify(line.text, inFence: inFence)
|
||||
if isDelim {
|
||||
inFence.toggle()
|
||||
}
|
||||
styleLine(out, line: line, kind: kind)
|
||||
}
|
||||
}
|
||||
|
||||
private struct Line {
|
||||
let full: NSRange // content + terminator (blank lines attribute their terminator)
|
||||
let content: NSRange
|
||||
let text: String
|
||||
}
|
||||
|
||||
/// Every line in `range` — including empty ones — as (full, content, text).
|
||||
private static func contentLines(_ nsText: NSString, in range: NSRange) -> [Line] {
|
||||
var lines: [Line] = []
|
||||
var loc = range.location
|
||||
let end = NSMaxRange(range)
|
||||
while loc < end {
|
||||
let full = nsText.lineRange(for: NSRange(location: loc, length: 0))
|
||||
var len = full.length
|
||||
while len > 0 {
|
||||
let char = nsText.character(at: full.location + len - 1)
|
||||
if char == 0x0A || char == 0x0D {
|
||||
len -= 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
let content = NSRange(location: full.location, length: len)
|
||||
lines.append(Line(
|
||||
full: full,
|
||||
content: content,
|
||||
text: len > 0 ? nsText.substring(with: content) : "",
|
||||
))
|
||||
loc = NSMaxRange(full)
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
/// Count unclosed fences before `end` (``` or ~~~ delim lines toggle).
|
||||
private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool {
|
||||
var inFence = false
|
||||
var loc = 0
|
||||
while loc < end {
|
||||
let full = nsText.lineRange(for: NSRange(location: loc, length: 0))
|
||||
var len = full.length
|
||||
while len > 0 {
|
||||
let char = nsText.character(at: full.location + len - 1)
|
||||
if char == 0x0A || char == 0x0D {
|
||||
len -= 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if len > 0 {
|
||||
let line = (nsText.substring(with: NSRange(location: full.location, length: len)) as String)
|
||||
.drop(while: { $0 == " " || $0 == "\t" })
|
||||
if line.hasPrefix("```") || line.hasPrefix("~~~") {
|
||||
inFence.toggle()
|
||||
}
|
||||
}
|
||||
loc = NSMaxRange(full)
|
||||
}
|
||||
return inFence
|
||||
}
|
||||
|
||||
private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind) {
|
||||
guard line.full.length > 0 else { return }
|
||||
out.setAttributes(attributes(for: kind), range: line.full)
|
||||
let dim = ProseTypography.codeAttributes // codeFont + syntaxColor
|
||||
switch kind {
|
||||
case .heading1, .heading2, .heading3, .heading4Plus:
|
||||
let lead = line.text.prefix(while: { $0 == " " }).utf16.count
|
||||
let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count
|
||||
let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead))
|
||||
if marker.length > 0 {
|
||||
out.addAttributes(dim, range: marker)
|
||||
}
|
||||
case .quote:
|
||||
if let marker = markerRange(quoteMarkerRegex, in: line.text), marker.length > 0 {
|
||||
out.addAttributes(dim, range: shifted(marker, into: line.content))
|
||||
}
|
||||
case .listMarker:
|
||||
if let marker = markerRange(listMarkerRegex, in: line.text), marker.length > 0 {
|
||||
out.addAttributes(dim, range: shifted(marker, into: line.content))
|
||||
}
|
||||
case .syntaxOnly, .fence:
|
||||
if line.content.length > 0 {
|
||||
out.addAttributes(dim, range: line.content)
|
||||
}
|
||||
case .fenceInterior, .blank, .body:
|
||||
break
|
||||
}
|
||||
if kind == .body || kind == .quote || kind == .listMarker {
|
||||
styleInline(out, content: line.content, text: line.text)
|
||||
}
|
||||
}
|
||||
|
||||
private static func shifted(_ marker: NSRange, into content: NSRange) -> NSRange {
|
||||
NSRange(
|
||||
location: content.location + marker.location,
|
||||
length: min(marker.length, max(0, content.length - marker.location)),
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: Inline spans (bold / italic / code / links)
|
||||
|
||||
// ponytail: Regex literals aren't Sendable; they're immutable de-facto.
|
||||
// No lookbehind in swift-regex — overlap-claim ordering + a manual
|
||||
// boundary check replace it.
|
||||
private nonisolated(unsafe) static let boldPattern = /\*\*[^*\n]+?\*\*/
|
||||
private nonisolated(unsafe) static let emStarPattern = /\*[^*\n]+?\*/
|
||||
private nonisolated(unsafe) static let emUnderPattern = /_[^_\n]+?_/
|
||||
private nonisolated(unsafe) static let codePattern = /`[^`\n]+?`/
|
||||
private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/
|
||||
|
||||
/// Trait-style inline constructs. Marks dim; content gets real traits.
|
||||
/// Priority: code > link > bold > italic; later matches skip claimed spans.
|
||||
private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) {
|
||||
guard content.length > 0 else { return }
|
||||
var claimed: [Range<Int>] = []
|
||||
|
||||
func claim(_ span: Range<Int>) -> Bool {
|
||||
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
|
||||
claimed.append(span)
|
||||
return true
|
||||
}
|
||||
|
||||
func dim(_ utf16: Range<Int>) {
|
||||
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
|
||||
out.addAttributes(ProseTypography.codeAttributes, range: range)
|
||||
}
|
||||
|
||||
func attr(_ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) {
|
||||
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
|
||||
out.addAttributes(attrs, range: range)
|
||||
}
|
||||
|
||||
let boldFont = ProseTypography.boldBodyFont
|
||||
let italicFont = ProseTypography.italicBodyFont
|
||||
let codeFont = ProseTypography.codeFont
|
||||
let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor]
|
||||
let linkAttrs: [NSAttributedString.Key: Any] = [
|
||||
.underlineStyle: NSUnderlineStyle.single.rawValue,
|
||||
.underlineColor: ProseTypography.mutedColor,
|
||||
]
|
||||
|
||||
// inline code — marks + content in the code face, content at ink
|
||||
for match in text.matches(of: codePattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new })
|
||||
}
|
||||
// links — label ink + underline (CSS: ink text, muted rule); the
|
||||
// brackets, ]( and the URL dim (reading hides them; dim is the
|
||||
// editor's closest parity move).
|
||||
for match in text.matches(of: linkPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
let whole = match.output // whole match (no capture groups)
|
||||
guard let sep = whole.firstRange(of: "](") else { continue }
|
||||
// sep indices are valid in text (Substring shares indices)
|
||||
let sepOffset = text.utf16.distance(from: text.utf16.startIndex, to: sep.lowerBound.samePosition(in: text.utf16)!)
|
||||
let label = span.lowerBound + 1 ..< sepOffset
|
||||
dim(span.lowerBound ..< span.lowerBound + 1) // [
|
||||
attr(label, linkAttrs)
|
||||
dim(sepOffset ..< span.upperBound) // ](url)
|
||||
}
|
||||
// bold
|
||||
for match in text.matches(of: boldPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
dim(span.lowerBound ..< span.lowerBound + 2)
|
||||
dim(span.upperBound - 2 ..< span.upperBound)
|
||||
attr(span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont])
|
||||
}
|
||||
// italic — two forms. CommonMark: intraword `_` never emphasizes
|
||||
// (file_name_here); intraword `*` does. No lookbehind in swift-regex,
|
||||
// so boundary chars are checked by hand.
|
||||
for match in text.matches(of: emStarPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
let lo = charBefore(text, span.lowerBound)
|
||||
let hi = charAfter(text, span.upperBound)
|
||||
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
|
||||
continue
|
||||
}
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
|
||||
}
|
||||
for match in text.matches(of: emUnderPattern) {
|
||||
let span = match.range.utf16Range(in: text)
|
||||
guard claim(span) else { continue }
|
||||
let lo = charBefore(text, span.lowerBound)
|
||||
let hi = charAfter(text, span.upperBound)
|
||||
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
|
||||
continue
|
||||
}
|
||||
if lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true {
|
||||
continue
|
||||
}
|
||||
dim(span.lowerBound ..< span.lowerBound + 1)
|
||||
dim(span.upperBound - 1 ..< span.upperBound)
|
||||
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
|
||||
}
|
||||
// fallback: dim stray syntax chars outside claimed spans
|
||||
let syntax = inlineSyntax
|
||||
for (offset, codeUnit) in text.utf16.enumerated() {
|
||||
guard let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), syntax.contains(scalar) else { continue }
|
||||
let unit = offset ..< offset + 1
|
||||
if claimed.contains(where: { $0.overlaps(unit) }) {
|
||||
continue
|
||||
}
|
||||
dim(unit)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Base attributes
|
||||
|
||||
static var bodyFont: NSFont {
|
||||
ProseTypography.bodyFont
|
||||
}
|
||||
@@ -88,41 +338,105 @@ nonisolated enum ProsePresenter {
|
||||
case .heading1:
|
||||
[.font: ProseTypography.headingFont, .paragraphStyle: paragraph(.heading1)]
|
||||
case .heading2:
|
||||
[.font: ProseTypography.heading2Font, .paragraphStyle: paragraph(.heading2)]
|
||||
case .heading3:
|
||||
[.font: ProseTypography.heading3Font, .paragraphStyle: paragraph(.heading3)]
|
||||
case .heading4Plus:
|
||||
[.font: ProseTypography.headingBoldFont, .paragraphStyle: paragraph(.heading4Plus)]
|
||||
case .quote:
|
||||
[
|
||||
.font: NSFont(name: "ConcourseOT6Semibold", size: (ProseTypography.headingFont.pointSize * 0.77).rounded()) ?? ProseTypography.headingFont,
|
||||
.paragraphStyle: paragraph(.heading2),
|
||||
.font: ProseTypography.bodyFont,
|
||||
.foregroundColor: ProseTypography.secondaryColor,
|
||||
.paragraphStyle: paragraph(.quote),
|
||||
]
|
||||
case .quote, .syntaxOnly, .body: bodyAttributes
|
||||
case .fence:
|
||||
[
|
||||
.font: ProseTypography.codeFont,
|
||||
.foregroundColor: ProseTypography.syntaxColor,
|
||||
.backgroundColor: ProseTypography.substrateColor,
|
||||
.paragraphStyle: paragraph(.fence),
|
||||
]
|
||||
case .fenceInterior:
|
||||
[
|
||||
.font: ProseTypography.codeFont,
|
||||
.foregroundColor: ProseTypography.foregroundColor,
|
||||
.backgroundColor: ProseTypography.substrateColor,
|
||||
.paragraphStyle: paragraph(.fenceInterior),
|
||||
]
|
||||
case .listMarker, .syntaxOnly, .body:
|
||||
ProseTypography.bodyAttributes
|
||||
case .blank:
|
||||
[.font: ProseTypography.blankFont, .paragraphStyle: paragraph(.blank)]
|
||||
}
|
||||
}
|
||||
|
||||
/// Dim markdown syntax characters within a line range (marker prefixes + inline marks).
|
||||
static func dimSyntax(in out: NSMutableAttributedString, range: NSRange) {
|
||||
let nsText = out.string as NSString
|
||||
guard range.length > 0 else { return }
|
||||
let line = nsText.substring(with: range)
|
||||
let kind = lineKind(line)
|
||||
// prefix markers
|
||||
let markerLen = switch kind {
|
||||
case .heading1: 2
|
||||
case .heading2: 3
|
||||
case .quote: 2
|
||||
default: 0
|
||||
/// Paragraph spacing per line kind. Blank source lines are the separator
|
||||
/// (#77: at half height); spacing knobs stay 0 unless the visual check
|
||||
/// asks for more.
|
||||
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
|
||||
let style = NSMutableParagraphStyle()
|
||||
let font: NSFont
|
||||
let cssLineHeight: CGFloat
|
||||
switch kind {
|
||||
case .heading1, .heading2, .heading3, .heading4Plus:
|
||||
font = ProseTypography.headingFont
|
||||
cssLineHeight = 1.15 // CSS: h1–h6 line-height 1.15
|
||||
case .fence, .fenceInterior:
|
||||
font = ProseTypography.codeFont
|
||||
cssLineHeight = 1.5 // CSS: pre line-height 1.5
|
||||
case .blank:
|
||||
font = ProseTypography.blankFont
|
||||
cssLineHeight = 1.8
|
||||
default:
|
||||
font = ProseTypography.bodyFont
|
||||
cssLineHeight = 1.8 // CSS: --lh 1.8
|
||||
}
|
||||
let dim: [NSAttributedString.Key: Any] = [
|
||||
.foregroundColor: ProseTypography.syntaxColor,
|
||||
.font: ProseTypography.codeFont,
|
||||
]
|
||||
if markerLen > 0 {
|
||||
out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length)))
|
||||
}
|
||||
// inline marks in body/quote
|
||||
if kind == .body || kind == .quote {
|
||||
for (offset, codeUnit) in line.utf16.enumerated() {
|
||||
if let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), inlineSyntax.contains(scalar) {
|
||||
out.addAttributes(dim, range: NSRange(location: range.location + offset, length: 1))
|
||||
}
|
||||
}
|
||||
style.lineHeightMultiple = ProseTypography.lineHeightMultiple(font: font, cssLineHeight: cssLineHeight)
|
||||
if kind == .quote {
|
||||
style.firstLineHeadIndent = 20 // CSS: blockquote padding-left 20px
|
||||
style.headIndent = 20 // wrapped quote lines align under the text
|
||||
}
|
||||
style.paragraphSpacing = 0
|
||||
style.paragraphSpacingBefore = 0
|
||||
return style
|
||||
}
|
||||
|
||||
// MARK: Pattern helpers
|
||||
|
||||
/// Marker dimming for quote / list lines — returns the marker's NSRange in
|
||||
/// `line.text`, or nil.
|
||||
// Static literal patterns — compile by construction.
|
||||
// swiftlint:disable:next force_try
|
||||
private static let listMarkerRegex = try! NSRegularExpression(pattern: #"^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)"#)
|
||||
// swiftlint:disable:next force_try
|
||||
private static let quoteMarkerRegex = try! NSRegularExpression(pattern: #"^(?:\s*>(?:\s|$))*"#)
|
||||
|
||||
private static func markerRange(_ regex: NSRegularExpression, in lineText: String) -> NSRange? {
|
||||
regex.firstMatch(in: lineText, range: NSRange(location: 0, length: (lineText as NSString).length))?.range
|
||||
}
|
||||
|
||||
/// Mark-boundary helpers (no lookbehind in swift-regex): the Character
|
||||
/// just before / just after a UTF-16 offset, or nil at the edges.
|
||||
private static func charBefore(_ text: String, _ offset: Int) -> Character? {
|
||||
guard offset > 0 else { return nil }
|
||||
let idx = text.utf16.index(text.utf16.startIndex, offsetBy: offset - 1, limitedBy: text.utf16.endIndex) ?? text.utf16.startIndex
|
||||
guard let scalar = Unicode.Scalar(text.utf16[idx]) else { return nil }
|
||||
return Character(scalar)
|
||||
}
|
||||
|
||||
private static func charAfter(_ text: String, _ offset: Int) -> Character? {
|
||||
let idx = text.utf16.index(text.utf16.startIndex, offsetBy: offset, limitedBy: text.utf16.endIndex) ?? text.utf16.endIndex
|
||||
guard idx < text.utf16.endIndex, let scalar = Unicode.Scalar(text.utf16[idx]) else { return nil }
|
||||
return Character(scalar)
|
||||
}
|
||||
|
||||
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
|
||||
}
|
||||
|
||||
nonisolated extension Range where Bound == String.Index {
|
||||
func utf16Range(in base: String) -> Range<Int> {
|
||||
let lo = base.utf16.distance(from: base.utf16.startIndex, to: lowerBound.samePosition(in: base.utf16)!)
|
||||
let hi = base.utf16.distance(from: base.utf16.startIndex, to: upperBound.samePosition(in: base.utf16)!)
|
||||
return lo ..< hi
|
||||
}
|
||||
}
|
||||
@@ -15,19 +15,66 @@ import AppKit
|
||||
/// Prose typography constants (#72 rework). The editing surface reads these;
|
||||
/// reading mode reads Resources/reading.css.
|
||||
nonisolated enum ProseTypography {
|
||||
// #77: sizes mirror reading.css exactly (px → pt 1:1 at 1×).
|
||||
static let bodySize: CGFloat = 17
|
||||
static let heading1Size: CGFloat = 30 // CSS: --headings-size 26 × 1.15
|
||||
static let heading2Size: CGFloat = 22 // CSS: 26 × 0.85
|
||||
static let heading3Size: CGFloat = 19 // CSS: --body-size × 1.12
|
||||
static let codeSize: CGFloat = 14
|
||||
static let blankSize: CGFloat = 9 // half-height blank separator lines (#77)
|
||||
|
||||
/// 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) }
|
||||
static var bodyFont: NSFont {
|
||||
NSFont(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: 26) ?? NSFont.systemFont(ofSize: 26, weight: .semibold) }
|
||||
static var headingFont: NSFont {
|
||||
NSFont(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)
|
||||
}
|
||||
|
||||
/// h3 = body face, sized up, weight 600 (CSS h3: body-face w600). The B
|
||||
/// cut has no 600 member — the bold trait (700, real or synthesized) is
|
||||
/// the nearest expressible. ponytail: trait-convert; a true semibold face
|
||||
/// would drop in here if ever installed.
|
||||
static var heading3Font: NSFont {
|
||||
NSFontManager.shared.convert(
|
||||
NSFontManager.shared.convert(bodyFont, toSize: heading3Size),
|
||||
toHaveTrait: .boldFontMask,
|
||||
)
|
||||
}
|
||||
|
||||
/// h4+ floors at bold body (CSS h4–h6).
|
||||
static var headingBoldFont: NSFont {
|
||||
NSFontManager.shared.convert(bodyFont, toHaveTrait: .boldFontMask)
|
||||
}
|
||||
|
||||
/// Code slot (inline code, fenced blocks, editing syntax dim).
|
||||
static var codeFont: NSFont { NSFont(name: "UbuntuMonoNFM", size: 14) ?? NSFont.monospacedSystemFont(ofSize: 14, weight: .regular) }
|
||||
static var codeFont: NSFont {
|
||||
NSFont(name: "UbuntuMonoNFM", size: codeSize) ?? NSFont.monospacedSystemFont(ofSize: codeSize, weight: .regular)
|
||||
}
|
||||
|
||||
/// Editing-surface leading (blank source lines are the separator there).
|
||||
static let lineHeightMultiple: CGFloat = 1.5
|
||||
/// Blank source lines at 9pt (#77 half-height separators).
|
||||
static var blankFont: NSFont {
|
||||
NSFontManager.shared.convert(bodyFont, toSize: blankSize)
|
||||
}
|
||||
|
||||
/// Line-height parity with reading.css (#77): CSS `line-height: n` means
|
||||
/// n × font-size pixels; TextKit's lineHeightMultiple multiplies the
|
||||
/// font's natural box (ascender − descender + leading ≈ 1.2 × size).
|
||||
/// Copying the CSS number would overshoot ~20% — calibrate instead.
|
||||
static func lineHeightMultiple(font: NSFont, cssLineHeight: CGFloat) -> CGFloat {
|
||||
let natural = font.ascender - font.descender + font.leading
|
||||
guard natural > 0 else { return cssLineHeight }
|
||||
return (font.pointSize * cssLineHeight) / natural
|
||||
}
|
||||
|
||||
static var italicBodyFont: NSFont {
|
||||
NSFontManager.shared.convert(bodyFont, toHaveTrait: .italicFontMask)
|
||||
@@ -52,6 +99,21 @@ nonisolated enum ProseTypography {
|
||||
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)
|
||||
}
|
||||
|
||||
/// Muted ink — reading.css --muted #6e6e73 (link underline rule, #77).
|
||||
static var mutedColor: NSColor {
|
||||
NSColor(red: 0x6E / 255, green: 0x6E / 255, blue: 0x73 / 255, alpha: 1)
|
||||
}
|
||||
|
||||
/// Substrate — reading.css --substrate #f5f5f7 (code panels, #77).
|
||||
static var substrateColor: NSColor {
|
||||
NSColor(red: 0xF5 / 255, green: 0xF5 / 255, blue: 0xF7 / 255, alpha: 1)
|
||||
}
|
||||
|
||||
/// Table borders + editing-surface hairline (≈ DesignTokens.border).
|
||||
static var tableBorderColor: NSColor {
|
||||
NSColor(red: 0xE8 / 255, green: 0xE5 / 255, blue: 0xDF / 255, alpha: 1)
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//
|
||||
// ProsePresenterTests.swift
|
||||
// Museion
|
||||
//
|
||||
// #77: editing-side reading-parity — pins the attribute map: heading ladder,
|
||||
// half-height blanks, quote/indent styling, fence interiors, inline traits
|
||||
// (bold/italic/code/link), and line-height calibration.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@Suite(.serialized)
|
||||
struct ProsePresenterTests {
|
||||
// MARK: Line kinds
|
||||
|
||||
@Test func `heading kinds`() {
|
||||
#expect(ProsePresenter.lineKind("# T") == .heading1)
|
||||
#expect(ProsePresenter.lineKind("## T") == .heading2)
|
||||
#expect(ProsePresenter.lineKind("### T") == .heading3)
|
||||
#expect(ProsePresenter.lineKind("#### T") == .heading4Plus)
|
||||
#expect(ProsePresenter.lineKind("###### T") == .heading4Plus)
|
||||
}
|
||||
|
||||
@Test func `fence context`() {
|
||||
#expect(ProsePresenter.classify("plain", inFence: true) == .fenceInterior)
|
||||
#expect(ProsePresenter.classify("## not a heading", inFence: true) == .fenceInterior)
|
||||
#expect(ProsePresenter.classify("```", inFence: false) == .fence)
|
||||
}
|
||||
|
||||
@Test func `list markers`() {
|
||||
#expect(ProsePresenter.lineKind("- item") == .listMarker)
|
||||
#expect(ProsePresenter.lineKind("* item") == .listMarker)
|
||||
#expect(ProsePresenter.lineKind("1. item") == .listMarker)
|
||||
#expect(ProsePresenter.lineKind("12) item") == .listMarker)
|
||||
#expect(ProsePresenter.lineKind("plain text") == .body)
|
||||
}
|
||||
|
||||
// MARK: Attribute map parity
|
||||
|
||||
@Test func `heading ladder matches reading CSS`() {
|
||||
let attributed = ProsePresenter.attribute("# H1\n\n## H2\n\n### H3\n\n#### H4")
|
||||
let ns = attributed.string as NSString
|
||||
// sample at the heading TEXT, not offset 0 (the dimmed marker)
|
||||
let h1 = attributed.attribute(.font, at: ns.range(of: "H1").location, effectiveRange: nil) as? NSFont
|
||||
#expect(h1?.pointSize == 30)
|
||||
#expect(h1?.fontName.contains("ConcourseOT") == true || h1?.fontName.contains("Semibold") == true || h1?.fontName.contains("Bold") == true)
|
||||
let h2 = attributed.attribute(.font, at: ns.range(of: "H2").location, effectiveRange: nil) as? NSFont
|
||||
#expect(h2?.pointSize == 22)
|
||||
let h3 = attributed.attribute(.font, at: ns.range(of: "H3").location, effectiveRange: nil) as? NSFont
|
||||
#expect(h3?.pointSize == 19)
|
||||
#expect(h3?.fontName.contains("Valkyrie") == true || h3?.fontName.contains("Bold") == true)
|
||||
let h4 = attributed.attribute(.font, at: ns.range(of: "H4").location, effectiveRange: nil) as? NSFont
|
||||
#expect(h4?.pointSize == 17)
|
||||
#expect(h4?.fontName.contains("Bold") == true)
|
||||
}
|
||||
|
||||
@Test func `blank lines are half height`() {
|
||||
let attributed = ProsePresenter.attribute("para\n\nnext")
|
||||
let ns = attributed.string as NSString
|
||||
let blankLoc = ns.range(of: "\n\n").location + 1
|
||||
let font = attributed.attribute(.font, at: blankLoc, effectiveRange: nil) as? NSFont
|
||||
#expect(font?.pointSize == 9)
|
||||
}
|
||||
|
||||
@Test func `body leading calibrated`() {
|
||||
// CSS parity: 17pt × 1.8 ≈ 30.6pt of line, via the font's natural box.
|
||||
let font = ProseTypography.bodyFont
|
||||
let multiple = ProseTypography.lineHeightMultiple(font: font, cssLineHeight: 1.8)
|
||||
let natural = font.ascender - font.descender + font.leading
|
||||
#expect(abs(natural * multiple - font.pointSize * 1.8) < 0.5)
|
||||
}
|
||||
|
||||
@Test func `quote styling`() {
|
||||
let attributed = ProsePresenter.attribute("> quoted words")
|
||||
let ns = attributed.string as NSString
|
||||
let loc = ns.range(of: "quoted").location
|
||||
let color = attributed.attribute(.foregroundColor, at: loc, effectiveRange: nil) as? NSColor
|
||||
#expect(color == ProseTypography.secondaryColor)
|
||||
let style = attributed.attribute(.paragraphStyle, at: loc, effectiveRange: nil) as? NSParagraphStyle
|
||||
#expect(style?.firstLineHeadIndent == 20)
|
||||
#expect(style?.headIndent == 20)
|
||||
// marker dims
|
||||
let mark = attributed.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor
|
||||
#expect(mark == ProseTypography.syntaxColor)
|
||||
}
|
||||
|
||||
@Test func `fence interior is code`() {
|
||||
let attributed = ProsePresenter.attribute("```\ncode line\n```")
|
||||
let ns = attributed.string as NSString
|
||||
let loc = ns.range(of: "code line").location
|
||||
let font = attributed.attribute(.font, at: loc, effectiveRange: nil) as? NSFont
|
||||
#expect(font?.pointSize == 14)
|
||||
#expect(font?.fontName.contains("Mono") == true || font?.fontName.contains("monospaced") == true)
|
||||
#expect(attributed.attribute(.foregroundColor, at: loc, effectiveRange: nil) as? NSColor == ProseTypography.foregroundColor)
|
||||
}
|
||||
|
||||
@Test func `inline traits`() {
|
||||
let text = "bold **word** and _em_ and `code` and [label](http://x)"
|
||||
let attributed = ProsePresenter.attribute(text)
|
||||
let ns = text as NSString
|
||||
|
||||
let bold = attributed.attribute(.font, at: ns.range(of: "word").location, effectiveRange: nil) as? NSFont
|
||||
#expect(bold?.fontName.contains("Bold") == true)
|
||||
|
||||
let em = attributed.attribute(.font, at: ns.range(of: "em").location, effectiveRange: nil) as? NSFont
|
||||
#expect(em?.fontName.contains("Italic") == true)
|
||||
|
||||
let code = attributed.attribute(.font, at: ns.range(of: "code").location, effectiveRange: nil) as? NSFont
|
||||
#expect(code?.pointSize == 14)
|
||||
|
||||
let label = attributed.attribute(.underlineStyle, at: ns.range(of: "label").location, effectiveRange: nil) as? Int
|
||||
#expect(label == NSUnderlineStyle.single.rawValue)
|
||||
|
||||
// marks dim: the ** before "word"
|
||||
let mark = attributed.attribute(.foregroundColor, at: ns.range(of: "**word").location, effectiveRange: nil) as? NSColor
|
||||
#expect(mark == ProseTypography.syntaxColor)
|
||||
}
|
||||
|
||||
@Test func `fences interior retrofit`() {
|
||||
// reattribute over a paragraph inside an existing fence — state comes
|
||||
// from the prefix scan, not the paragraph alone.
|
||||
let full = "```\nfirst\n```\n\npara\n"
|
||||
let out = NSMutableAttributedString(attributedString: ProsePresenter.attribute(full))
|
||||
let ns = full as NSString
|
||||
let para = ns.paragraphRange(for: NSRange(location: 0, length: 0)) // "```"
|
||||
ProsePresenter.reattribute(out, paragraphRange: para)
|
||||
let loc = ns.range(of: "first").location
|
||||
let font = out.attribute(.font, at: loc, effectiveRange: nil) as? NSFont
|
||||
#expect(font?.pointSize == 14)
|
||||
}
|
||||
|
||||
@Test func `underscore in word not italic`() {
|
||||
let attributed = ProsePresenter.attribute("file_name_here stays plain")
|
||||
let ns = attributed.string as NSString
|
||||
let font = attributed.attribute(.font, at: ns.range(of: "name").location, effectiveRange: nil) as? NSFont
|
||||
#expect(font?.fontName.contains("Italic") != true)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user