diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift index a9a2638..bee19bb 100644 --- a/Museion/ReadingPresenter.swift +++ b/Museion/ReadingPresenter.swift @@ -26,6 +26,8 @@ enum ReadingPresenter { let sourceRange: NSRange /// Popover image URL for an `![alt](url)` chunk (#69 hover floor). let imageURL: URL? + /// Canvas-drawn decoration (quote hairline / rule / table grid). + var decoration: Decoration? } /// A block's placement in the built document: where its content landed @@ -34,6 +36,19 @@ enum ReadingPresenter { let docRange: NSRange let sourceRange: NSRange let imageURL: URL? + var decoration: Decoration? + } + + /// Canvas-drawn decoration for constructs whose layout NSTextTable / + /// NSTextBlock can't deliver on modern TextKit (#69 fix: draw it + /// ourselves from measured geometry instead). + enum Decoration { + /// Left hairline at the given indent. + case quote(indent: CGFloat) + /// Full-width horizontal rule. + case rule + /// Column x-offsets (incl. closing edge) in mono advance. + case table(columns: [CGFloat]) } /// The reading document: blocks concatenated with paragraph-rhythm @@ -62,6 +77,7 @@ enum ReadingPresenter { docRange: NSRange(location: start, length: out.length - start), sourceRange: block.sourceRange, imageURL: image, + decoration: block.decoration, )) } return Document(content: out, bounds: bounds) @@ -101,13 +117,16 @@ enum ReadingPresenter { // 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) + return Block(content: hrContent(), sourceRange: sourceRange, imageURL: nil, decoration: .rule) } if lines.allSatisfy({ listItemMarker($0) != nil }) { return Block(content: listContent(lines), sourceRange: sourceRange, imageURL: nil) } if lines.allSatisfy({ blockquoteDepth($0) > 0 }) { - return Block(content: quoteContent(lines), sourceRange: sourceRange, imageURL: nil) + return Block(content: quoteContent(lines), sourceRange: sourceRange, imageURL: nil, decoration: quoteDecoration(lines)) + } + if lines.count >= 2, isTableDelimiterRow(lines[1]), let table = tableContent(lines) { + return Block(content: table, sourceRange: sourceRange, imageURL: nil, decoration: tableDecoration(lines)) } return Block(content: flowContent(lines, first: first), sourceRange: sourceRange, imageURL: nil) } @@ -135,9 +154,6 @@ enum ReadingPresenter { 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 { @@ -185,8 +201,8 @@ enum ReadingPresenter { } private static func hrContent() -> NSAttributedString { + // Hairline drawn by the canvas (Decoration.rule). let ps = NSMutableParagraphStyle() - ps.textBlocks = [RuleTextBlock()] ps.paragraphSpacingBefore = 8 ps.paragraphSpacing = 8 return NSAttributedString(string: " ", attributes: [ @@ -234,13 +250,14 @@ enum ReadingPresenter { // MARK: Blockquotes (#69: `>` never visible, hairline rule, nesting indents) private static func quoteContent(_ lines: [String]) -> NSAttributedString { + // Hairline drawn by the canvas (Decoration.quote) — NSTextBlock + // drawing zero-widths the line rect on modern TextKit, wrapping + // content one character per line. let out = NSMutableAttributedString() - 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 @@ -265,51 +282,89 @@ enum ReadingPresenter { return String(line.dropFirst(prefix.count)).trimmingCharacters(in: .whitespaces) } - // MARK: Tables (#69: simple 1px-bordered NSTextTable; delimiter-row + // MARK: Tables (#69: mono grid — plain padded text; the canvas draws the - // alignment honored — cheap once the delimiter is parsed anyway) + // grid lines from Decoration.table. NSTextTable cannot lay out on modern + // TextKit: rows stack vertically, columns never align.) private static func tableContent(_ lines: [String]) -> NSAttributedString? { let header = tableCells(lines[0]) let aligns = tableAlignments(lines[1]) guard !header.isEmpty, header.count == aligns.count else { return nil } - let 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, - )) + let dataRows = lines.enumerated().filter { $0.offset != 1 }.map(\.element) + let cellTexts = ([lines[0]] + dataRows.dropFirst()).map(tableCells) + let columnCount = header.count + var widths = Array(repeating: 0, count: columnCount) + for row in cellTexts { + for (column, cell) in row.enumerated() where column < columnCount { + widths[column] = max(widths[column], cell.count) } - row += 1 + } + let pad = 2 + let codeAttrs: [NSAttributedString.Key: Any] = [ + .font: ProseTypography.codeFont, + .foregroundColor: ProseTypography.foregroundColor, + ] + let out = NSMutableAttributedString() + func gridLine(_ cells: [String]) -> NSAttributedString { + var line = "" + for column in 0 ..< columnCount { + let text = column < cells.count ? cells[column] : "" + let width = widths[column] + let padded: String + switch aligns[column] { + case .center where text.count < width: + let left = (width - text.count) / 2 + padded = String(repeating: " ", count: left) + text + + String(repeating: " ", count: width - text.count - left) + case .right: + padded = String(repeating: " ", count: max(0, width - text.count)) + text + default: + padded = text + String(repeating: " ", count: max(0, width - text.count)) + } + line += String(repeating: " ", count: pad) + padded + String(repeating: " ", count: pad) + } + return NSAttributedString(string: line, attributes: codeAttrs) + } + out.append(gridLine(cellTexts[0])) + for row in cellTexts.dropFirst() { + out.append(NSAttributedString(string: "\n", attributes: codeAttrs)) + out.append(gridLine(row)) } return out } + /// Quote decoration: left hairline at the shallowest quote indent. + private static func quoteDecoration(_ lines: [String]) -> Decoration { + let minIndent = lines.compactMap { line -> CGFloat? in + blockquoteDepth(line) > 0 ? CGFloat(6 + (blockquoteDepth(line) - 1) * 18) : nil + }.min() ?? 6 + return .quote(indent: minIndent) + } + + /// Table decoration: column x-offsets (+ closing edge) in mono advance. + private static func tableDecoration(_ lines: [String]) -> Decoration { + let header = tableCells(lines[0]) + let dataRows = lines.enumerated().filter { $0.offset != 1 }.map(\.element) + let cellTexts = ([lines[0]] + dataRows.dropFirst()).map(tableCells) + var widths = Array(repeating: 0, count: header.count) + for row in cellTexts { + for (column, cell) in row.enumerated() where column < header.count { + widths[column] = max(widths[column], cell.count) + } + } + let advance = ("0" as NSString).size(withAttributes: [ + .font: ProseTypography.codeFont, + ]).width + var offsets: [CGFloat] = [] + var running = 0.0 + for width in widths { + offsets.append(running) + running += CGFloat(width + 4) * advance + } + return .table(columns: offsets + [running]) + } + private static func tableCells(_ line: String) -> [String] { var trimmed = line.trimmingCharacters(in: .whitespaces) if trimmed.hasPrefix("|") { @@ -444,34 +499,3 @@ enum ReadingPresenter { 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() - } -} diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index ecdffc4..1b94d62 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -64,10 +64,6 @@ struct ReadingSurface: NSViewRepresentable { tv.isVerticallyResizable = true tv.isHorizontallyResizable = false tv.autoresizingMask = [.width] - // Tables (#69) lay out correctly under TextKit1 only — TK2 stacks - // NSTextTable rows vertically (probed). The canvas is read-only, so - // nothing editing-grade is lost by forcing the TK1 bridge. - tv.textContainer?.replaceLayoutManager(NSLayoutManager()) // Wrap to the editor column (#68/71 fix): the container tracks the // view width — a fixed 640pt measure clipped in narrower columns. tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude) @@ -136,6 +132,72 @@ final class ReadingCanvasView: NSTextView { blockBounds.last { $0.docRange.location <= index } } + // MARK: Decorations (#69 fix: quote hairlines, HR rules, table grids — + + // drawn from measured geometry; NSTextBlock/NSTextTable layout is + // broken on modern TextKit) + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + guard let layoutManager, let container = textContainer else { return } + for bound in blockBounds { + guard let decoration = bound.decoration else { continue } + let glyphRange = layoutManager.glyphRange( + forCharacterRange: bound.docRange, actualCharacterRange: nil, + ) + switch decoration { + case let .quote(indent): + let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) + let x = textContainerOrigin.x + container.lineFragmentPadding + indent - 6 + let path = NSBezierPath() + path.move(to: NSPoint(x: x, y: rect.minY)) + path.line(to: NSPoint(x: x, y: rect.maxY)) + path.lineWidth = 2 + ProseTypography.quoteRuleColor.setStroke() + path.stroke() + case .rule: + let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) + let y = rect.midY + let path = NSBezierPath() + path.move(to: NSPoint(x: textContainerOrigin.x, y: y)) + path.line(to: NSPoint(x: textContainerOrigin.x + container.size.width, y: y)) + path.lineWidth = 1 + ProseTypography.tableBorderColor.setStroke() + path.stroke() + case let .table(columns): + let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) + let originX = textContainerOrigin.x + container.lineFragmentPadding + let path = NSBezierPath() + for offset in columns { + let x = originX + offset + path.move(to: NSPoint(x: x, y: rect.minY)) + path.line(to: NSPoint(x: x, y: rect.maxY)) + } + var lineStart = glyphRange.location + var rowLines: [CGFloat] = [] + while lineStart < NSMaxRange(glyphRange) { + var effective = NSRange(location: 0, length: 0) + let lineRect = layoutManager.lineFragmentRect( + forGlyphAt: lineStart, effectiveRange: &effective, + withoutAdditionalLayout: true, + ) + if effective.length == 0 { + break + } + rowLines.append(lineRect.maxY) + lineStart = NSMaxRange(effective) + } + for y in rowLines { + path.move(to: NSPoint(x: originX, y: y)) + path.line(to: NSPoint(x: originX + (columns.last ?? 0), y: y)) + } + path.lineWidth = 1 + ProseTypography.tableBorderColor.setStroke() + path.stroke() + } + } + } + override func updateTrackingAreas() { super.updateTrackingAreas() if hoverTrackingArea == nil { diff --git a/MuseionTests/ReadingPresenterTests.swift b/MuseionTests/ReadingPresenterTests.swift index e36049b..d9defac 100644 --- a/MuseionTests/ReadingPresenterTests.swift +++ b/MuseionTests/ReadingPresenterTests.swift @@ -63,32 +63,26 @@ struct ReadingPresenterTests { #expect(doc.bounds[3].sourceRange.location == expected) } - /// Tables render as NSTextTable blocks with header bold. + /// Tables render as a mono grid: decoration carries column offsets, + /// header/body rows are padded columns of text. @Test - func `table renders`() { + func `table renders`() throws { let src = "| A | B |\n| --- | --- |\n| one | two |" let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil) #expect(doc.bounds.count == 1) - #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 - } + let lines = doc.content.string.components(separatedBy: "\n") + #expect(lines.count == 2) + #expect(lines[0].contains("A")) + #expect(lines[1].contains("one")) + // alignment: same column starts across rows + let colA0 = try lines[0].distance(from: lines[0].startIndex, to: #require(lines[0].firstIndex(of: "A"))) + let colA1 = try lines[1].distance(from: lines[1].startIndex, to: #require(lines[1].firstIndex(of: "o"))) + #expect(colA0 == colA1) + guard case let .table(columns)? = doc.bounds[0].decoration else { + Issue.record("expected table decoration") + return } - _ = 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) + #expect(columns.count == 3) // two columns + closing edge } /// Fenced code: mono face, markers hidden, content intact. @@ -102,22 +96,17 @@ struct ReadingPresenterTests { #expect((attrs[.font] as? NSFont)?.fontName == ProseTypography.codeFont.fontName) } - /// Blockquote: markers hidden, hairline block attached. + /// Blockquote: markers hidden, quote decoration on the bound. @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 - } + guard case .quote? = doc.bounds[0].decoration else { + Issue.record("expected quote decoration") + return } - #expect(foundQuoteBlock) } /// Links styled + attribute retained (⌘-click opens). @@ -158,21 +147,16 @@ struct ReadingPresenterTests { #expect(doc.content.string.contains("[^1]")) } - /// HR: hairline block, matcher shared with editing. + /// HR: rule decoration, matcher shared with editing. @Test func `horizontal rule`() { let src = "above\n\n* * *\n\nbelow" let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil) #expect(doc.bounds.count == 3) - 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 - } + guard case .rule? = doc.bounds[1].decoration else { + Issue.record("expected rule decoration") + return } - #expect(foundRule) } /// Soft-joined lines: one paragraph, single spaces.