diff --git a/README.md b/README.md index 39fbb22..5408c98 100644 --- a/README.md +++ b/README.md @@ -327,6 +327,34 @@ style.codeBackgroundColor = TranscriptColor(UIColor.secondarySystemFill) // cod style.accentColor = TranscriptColor(UIColor.tertiaryLabel) // quote bars, rules, table lines ``` +To match an existing Markdown look, set how lists, task boxes, quotes, inline code and table headers look. The +defaults keep the look of today. A color that is nil uses the text color (the quote text color in a block quote), or +the value in the comment: + +```swift +var style = TranscriptStyle() +style.listNumberFormat = .period // "1." where the Markdown wrote "1)"; .asWritten by default +style.listNumberWeight = 0.3 // as TranscriptFont.weight; nil uses the body weight +style.listNumberColor = TranscriptColor(UIColor.secondaryLabel) +style.bullets = ["•", "–"] // by level; levels past the end use the last one +style.bulletColors = [TranscriptColor(UIColor.secondaryLabel)] +style.taskCheckedColor = TranscriptColor(UIColor.systemGreen) // nil: blue +style.taskCheckmarkColor = TranscriptColor(UIColor.white) // nil: white +style.taskUncheckedColor = TranscriptColor(UIColor.tertiaryLabel) // nil: the text color at 45% opacity +style.quoteBarColor = TranscriptColor(UIColor.systemOrange) // nil: accentColor +style.quoteBarWidth = 4 // 3 by default; keep it less than quoteIndent +style.quoteTextColor = TranscriptColor(UIColor.secondaryLabel) +style.inlineCodeBackgroundColor = TranscriptColor(UIColor.tertiarySystemFill) // nil: no fill +style.inlineCodeCornerRadius = 4 +style.tableHeaderBackgroundColor = TranscriptColor(UIColor.systemGray5) // nil: codeBackgroundColor +style.tableHeaderWeight = 0.3 // nil: the bold body font +``` + +A named body font has its own weight, so a weight does not change it. For such a font, a weight of 0.3 or more uses its +bold face. Inline code in a table header uses its bold face at a header weight of 0.3 or more. Links, code colors and +custom tags' colors win over the quote text color. A custom tag's highlight wins over the inline code fill. The inline +code fill does not change where lines break. + ### Reading the selection `onSelectionChange` tells the app when the selection changes. The range is in the document's flat UTF-16 offset diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index bc0291d..77da123 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -365,8 +365,11 @@ final class BlockLayout: @unchecked Sendable { typealias Cell = (text: NSAttributedString, typesetter: CTTypesetter, range: Range) func makeCells(_ row: Int) -> [Cell] { - model.rows[row].prefix(columns).map { range in - let text = style.attributedString(for: block, range: range, extraTraits: row == 0 ? .bold : [], images: sizing, + let header = row == 0 + let weight = header ? style.tableHeaderWeight : nil + let traits: InlineSpan.Traits = header && weight == nil ? .bold : [] + return model.rows[row].prefix(columns).map { range in + let text = style.attributedString(for: block, range: range, extraTraits: traits, weight: weight, images: sizing, definitions: definitions, kerns: decorated?.kerns ?? [:]) return (text, CTTypesetterCreateWithAttributedString(text), range) } @@ -519,6 +522,7 @@ final class BlockLayout: @unchecked Sendable { guard let kind = block.marker, let firstLine, let item = block.containers.lastIndex(of: .listItem) else { return nil } // The marker sits in the gutter of the innermost list item. let gutterEnd = style.contentLeading(for: Array(block.containers[...item])) + let quoteColor = style.textColor(inside: block.containers[.. 0 ? self.entry(at: index - 1) : nil + let bar = style.quoteBarColor?.cgColor(dark: dark) ?? accent var x: CGFloat = 0 for (depth, container) in block.containers.enumerated() { if container == .quote { var top = frame.minY if let above, Self.shareQuote(above.layout.block, block, at: depth) { top = above.frame.maxY } // Square ends, so that segments of one bar meet cleanly. - fill(CGRect(x: x, y: top, width: 3, height: frame.maxY - top), radius: 0, color: accent) + fill(CGRect(x: x, y: top, width: max(style.quoteBarWidth, 0), height: frame.maxY - top), radius: 0, color: bar) } x += style.width(of: container) } @@ -493,7 +499,10 @@ public final class DocumentLayout: @unchecked Sendable { case .rule: fill(CGRect(x: box.minX, y: frame.midY - 0.5, width: box.width, height: 1), radius: 0, color: accent) case .table: - if let table = layout.table { drawGrid(table, top: entry.y, in: context, header: codeBackground, lines: accent) } + if let table = layout.table { + let header = style.tableHeaderBackgroundColor?.cgColor(dark: dark) ?? codeBackground + drawGrid(table, top: entry.y, in: context, header: header, lines: accent) + } case .paragraph, .heading: break } @@ -534,7 +543,9 @@ public final class DocumentLayout: @unchecked Sendable { case .text(let line, let origin)?: drawLine(line, at: CGPoint(x: origin.x, y: entry.y + origin.y)) case .checkbox(let rect, let checked)?: - drawCheckbox(rect.offsetBy(dx: 0, dy: entry.y), checked: checked, in: context, stroke: text) + let item = block.containers.lastIndex(of: .listItem) ?? 0 + let color = style.textColor(inside: block.containers[.. String { + guard case .custom(let prefix, let suffix) = self else { return written } + let number = written.prefix { $0.isASCII && $0.isNumber } + return prefix + number + suffix + } +} + /// Typography and spacing for a transcript. public struct TranscriptStyle: Equatable, Sendable { /// The font of paragraphs, list items, quotes and tables. Nil uses the @@ -46,12 +66,61 @@ public struct TranscriptStyle: Equatable, Sendable { /// The color of links and their underlines. A custom tag's color wins over it. public var linkColor = TranscriptColor(red: 0, green: 0.478, blue: 1) /// Behind code blocks, table headers and image placeholders. Nil uses the - /// system's secondary fill color. + /// system's secondary fill color. `tableHeaderBackgroundColor` wins over + /// it for table headers. public var codeBackgroundColor: TranscriptColor? /// Quote bars, thematic breaks and table lines. Nil uses the system's - /// tertiary label color. + /// tertiary label color. `quoteBarColor` wins over it for quote bars. public var accentColor: TranscriptColor? + /// How the numbers of ordered list items are written. + public var listNumberFormat: TranscriptListNumberFormat = .asWritten + /// The weight of the numbers of ordered list items, from -1 to 1 as + /// `TranscriptFont.weight`. Nil uses the weight of the body text. A named + /// body font has its own weight: a weight of 0.3 or more uses its bold + /// face, and a lower weight uses the font as it is. + public var listNumberWeight: CGFloat? + /// The color of the numbers of ordered list items. Nil uses the text + /// color, or `quoteTextColor` in a block quote. + public var listNumberColor: TranscriptColor? + /// The bullets of unordered list items: the first for level 1, the + /// second for level 2, and so on. Levels past the end use the last one. + /// Empty uses "•", "◦" and "▪". + public var bullets: [String] = TranscriptStyle.defaultBullets + /// The colors of the bullets, by level as `bullets`. Empty uses the text + /// color, or `quoteTextColor` in a block quote. + public var bulletColors: [TranscriptColor] = [] + /// The fill of a task box that is checked. Nil uses a system-like blue. + public var taskCheckedColor: TranscriptColor? + /// The check mark in a task box that is checked. Nil uses white. + public var taskCheckmarkColor: TranscriptColor? + /// The outline of a task box that is not checked. Nil uses the text color, + /// or `quoteTextColor` in a block quote, at 45% opacity. + public var taskUncheckedColor: TranscriptColor? + /// The color of the bar at the left of a block quote. Nil uses + /// `accentColor`. + public var quoteBarColor: TranscriptColor? + /// The width of the bar at the left of a block quote. Keep it less than + /// `quoteIndent`, or the bar covers the text. + public var quoteBarWidth: CGFloat = 3 + /// The color of the text in block quotes. Nil uses the text color. Links, + /// code colors and custom tags' colors win over it. + public var quoteTextColor: TranscriptColor? + /// The fill behind inline code. Nil draws no fill. A custom tag's + /// highlight wins over it. + public var inlineCodeBackgroundColor: TranscriptColor? + /// The corner radius of the fill behind inline code. + public var inlineCodeCornerRadius: CGFloat = 4 + /// The fill behind the header row of a table. Nil uses + /// `codeBackgroundColor`. + public var tableHeaderBackgroundColor: TranscriptColor? + /// The weight of the text in the header row of a table, from -1 to 1 as + /// `TranscriptFont.weight`. Nil uses the bold body font. A named body font + /// has its own weight: a weight of 0.3 or more uses its bold face, and a + /// lower weight uses the font as it is. Inline code in the header row uses + /// its bold face at a weight of 0.3 or more. + public var tableHeaderWeight: CGFloat? + public init() {} /// The most lines to show, or nil for all of them. When text is left out, @@ -75,6 +144,22 @@ public struct TranscriptStyle: Equatable, Sendable { } } + /// The color of text inside `containers`, outermost first: the quote text + /// color when one of them is a block quote, or else nil for the text color. + func textColor(inside containers: Containers) -> TranscriptColor? + where Containers.Element == TranscriptBlock.Container { + containers.contains(.quote) ? quoteTextColor : nil + } + + static let defaultBullets = ["•", "◦", "▪"] + + /// The bullet of a list item at `level`, from 1, and its color. + func bullet(at level: Int) -> (text: String, color: TranscriptColor?) { + let shapes = bullets.isEmpty ? Self.defaultBullets : bullets + let color = bulletColors.isEmpty ? nil : bulletColors[min(max(level, 1), bulletColors.count) - 1] + return (shapes[min(max(level, 1), shapes.count) - 1], color) + } + /// Where the block's own box starts: after the indents of its containers. func contentLeading(for containers: [TranscriptBlock.Container]) -> CGFloat { containers.reduce(0) { $0 + width(of: $1) } @@ -97,6 +182,7 @@ public struct TranscriptStyle: Equatable, Sendable { var role: Int var size: CGFloat var traits: Int + var weight: CGFloat? var font: TranscriptFont? var code: TranscriptFont? } @@ -118,17 +204,24 @@ public struct TranscriptStyle: Equatable, Sendable { /// The traits that change the font; the others are drawn. private static let fontTraits: InlineSpan.Traits = [.bold, .italic, .code] - func font(for kind: TranscriptBlock.Kind, traits: InlineSpan.Traits = []) -> CTFont { + /// - Parameter weight: for body text, a weight as `TranscriptFont.weight` + /// instead of the body font's own. + func font(for kind: TranscriptBlock.Kind, traits: InlineSpan.Traits = [], weight: CGFloat? = nil) -> CTFont { let traits = traits.intersection(Self.fontTraits) + var weight = weight let role: Int switch kind { case .paragraph, .rule, .table: role = 0 - case .heading(let level): role = min(max(level, 1), 6) - case .code: role = 7 + case .heading(let level): + role = min(max(level, 1), 6) + weight = nil + case .code: + role = 7 + weight = nil } - let key = FontCache.Key(role: role, size: bodySize, traits: traits.rawValue, font: customFont(for: kind), + let key = FontCache.Key(role: role, size: bodySize, traits: traits.rawValue, weight: weight, font: customFont(for: kind), code: traits.contains(.code) ? codeFont : nil) - return Self.fontCache.font(for: key) { makeFont(for: kind, traits: traits) } + return Self.fontCache.font(for: key) { makeFont(for: kind, traits: traits, weight: weight) } } /// The font the app set for this kind of text, if any. @@ -150,9 +243,21 @@ public struct TranscriptStyle: Equatable, Sendable { /// The size of body text: the body font's, or `bodySize`. var effectiveBodySize: CGFloat { bodyFont?.size ?? bodySize } - private func makeFont(for kind: TranscriptBlock.Kind, traits: InlineSpan.Traits) -> CTFont { + private func makeFont(for kind: TranscriptBlock.Kind, traits: InlineSpan.Traits, weight: CGFloat?) -> CTFont { var font: CTFont - if let custom = customFont(for: kind) { + var traits = traits + if let weight { + if let custom = customFont(for: kind), custom.name != nil { + font = custom.makeFont() + if weight >= 0.3 { traits.insert(.bold) } + } else { + var custom = customFont(for: kind) ?? TranscriptFont(size: bodySize) + custom.weight = weight + font = custom.makeFont() + // The code font below replaces this font and its weight. + if weight >= 0.3, traits.contains(.code) { traits.insert(.bold) } + } + } else if let custom = customFont(for: kind) { font = custom.makeFont() } else { switch kind { @@ -191,11 +296,13 @@ public struct TranscriptStyle: Equatable, Sendable { /// resolved for light or dark when drawn, by `DocumentLayout`. static let foregroundKey = NSAttributedString.Key("TranscriptKit.foreground") static let backgroundKey = NSAttributedString.Key("TranscriptKit.background") + /// The fill behind inline code, a `TranscriptColor`, drawn like a highlight. + static let inlineCodeBackgroundKey = NSAttributedString.Key("TranscriptKit.inlineCodeBackground") private static let kernKey = NSAttributedString.Key(kCTKernAttributeName as String) - func attributes(for kind: TranscriptBlock.Kind) -> [NSAttributedString.Key: Any] { + func attributes(for kind: TranscriptBlock.Kind, weight: CGFloat? = nil) -> [NSAttributedString.Key: Any] { var attributes: [NSAttributedString.Key: Any] = [ - Self.fontKey: font(for: kind), + Self.fontKey: font(for: kind, weight: weight), // Text takes the context's fill color, so the view controls light/dark. Self.colorFromContextKey: true, ] @@ -209,17 +316,19 @@ public struct TranscriptStyle: Equatable, Sendable { attributedString(for: block, range: start.., extraTraits: InlineSpan.Traits = [], + func attributedString(for block: TranscriptBlock, range: Range, extraTraits: InlineSpan.Traits = [], weight: CGFloat? = nil, images: ImageSizing? = nil, definitions: [String: String] = [:], kerns: [Int: CGFloat] = [:]) -> NSAttributedString { let start = range.lowerBound let text = range == 0.. DocumentLayout { + DocumentLayout(document: MarkdownStreamParser.document(from: markdown), width: width, style: style) +} + +/// The text marker of the block at `index`: its line, and the attributes of its first run. +private func textMarker(_ layout: DocumentLayout, at index: Int) -> (line: CTLine, attributes: NSDictionary)? { + guard case .text(let line, _)? = layout.entry(at: index).layout.marker, + let run = (CTLineGetGlyphRuns(line) as! [CTRun]).first else { return nil } + return (line, CTRunGetAttributes(run) as NSDictionary) +} + +private func weight(of attributes: NSDictionary) -> CGFloat { + let font = attributes[kCTFontAttributeName] as! CTFont + let traits = CTFontCopyTraits(font) as NSDictionary + return (traits[kCTFontWeightTrait] as? NSNumber).map { CGFloat($0.doubleValue) } ?? 0 +} + +private func color(of attributes: NSDictionary) -> TranscriptColor? { + attributes[TranscriptStyle.foregroundKey.rawValue] as? TranscriptColor +} + +/// RGBA pixels of a layout drawn at 2x on white, in black text. +private struct Drawing { + let pixels: [UInt8] + let width: Int + let height: Int + static let scale: CGFloat = 2 + + init(_ layout: DocumentLayout, dark: Bool = false) { + let width = Int((layout.width * Self.scale).rounded()) + let height = Int(((layout.height + 4) * Self.scale).rounded()) + var pixels = [UInt8](repeating: 0, count: width * height * 4) + pixels.withUnsafeMutableBytes { buffer in + let context = CGContext(data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, + space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! + context.translateBy(x: 0, y: CGFloat(height)) + context.scaleBy(x: Self.scale, y: -Self.scale) + let all = CGRect(x: 0, y: 0, width: layout.width, height: layout.height + 4) + context.setFillColor(CGColor(gray: 1, alpha: 1)) + context.fill(all) + layout.draw(in: context, dirtyRect: all, text: CGColor(gray: 0, alpha: 1), codeBackground: CGColor(gray: 0.9, alpha: 1), + accent: CGColor(gray: 0.6, alpha: 1), dark: dark) + } + self.pixels = pixels + self.width = width + self.height = height + } + + /// How many pixels in a rect, in layout points, are close to an RGB color (0 to 255). + func count(in rect: CGRect, near rgb: (Int, Int, Int), tolerance: Int = 40) -> Int { + let minX = max(Int(rect.minX * Self.scale), 0), maxX = min(Int(rect.maxX * Self.scale), width) + let minY = max(Int(rect.minY * Self.scale), 0), maxY = min(Int(rect.maxY * Self.scale), height) + var count = 0 + for y in minY.. weight(of: plain.attributes)) +} + +@Test func aNamedBodyFontTakesItsBoldFaceForHeavyNumbers() throws { + var style = TranscriptStyle() + style.bodyFont = TranscriptFont(name: "Helvetica", size: 16) + style.listNumberWeight = 0.4 + let marker = try #require(textMarker(layout("1. first", style: style), at: 0)) + let font = marker.attributes[kCTFontAttributeName] as! CTFont + #expect(CTFontGetSymbolicTraits(font).contains(.traitBold)) + #expect(CTFontGetSize(font) == 16) +} + +// MARK: Bullets + +@Test func bulletsTakeTheirShapeAndColorByLevel() throws { + let style = TranscriptStyle() + #expect(style.bullet(at: 1).text == "•") + #expect(style.bullet(at: 2).text == "◦") + #expect(style.bullet(at: 5).text == "▪") + #expect(style.bullet(at: 1).color == nil) + + var custom = TranscriptStyle() + let red = TranscriptColor(red: 1, green: 0, blue: 0) + let blue = TranscriptColor(red: 0, green: 0, blue: 1) + custom.bullets = ["–", "→ "] + custom.bulletColors = [red, blue] + #expect(custom.bullet(at: 1).text == "–") + #expect(custom.bullet(at: 4).text == "→ ") + #expect(custom.bullet(at: 1).color == red) + #expect(custom.bullet(at: 3).color == blue) + custom.bullets = [] + #expect(custom.bullet(at: 2).text == "◦") + + custom.bullets = ["–", "→ "] + let drawn = layout("- one\n - two", style: custom) + let outer = try #require(textMarker(drawn, at: 0)) + let inner = try #require(textMarker(drawn, at: 1)) + #expect(CTLineGetGlyphCount(outer.line) == 1) + #expect(CTLineGetGlyphCount(inner.line) == 2) + #expect(color(of: outer.attributes) == red) + #expect(color(of: inner.attributes) == blue) +} + +// MARK: Task boxes + +/// The checked and the unchecked task box of a two-item task list, in layout points. +private func taskBoxes(_ layout: DocumentLayout) -> (checked: CGRect, unchecked: CGRect)? { + guard case .checkbox(let checked, true)? = layout.entry(at: 0).layout.marker, + case .checkbox(let unchecked, false)? = layout.entry(at: 1).layout.marker else { return nil } + return (checked.offsetBy(dx: 0, dy: layout.entry(at: 0).y), unchecked.offsetBy(dx: 0, dy: layout.entry(at: 1).y)) +} + +@Test func taskBoxesTakeTheirColors() throws { + let markdown = "- [x] done\n- [ ] open" + let plain = layout(markdown) + let plainBoxes = try #require(taskBoxes(plain)) + let before = Drawing(plain) + #expect(before.count(in: plainBoxes.checked, near: (0, 122, 255)) > 20) + #expect(before.count(in: plainBoxes.checked, near: (255, 0, 0)) == 0) + #expect(before.count(in: plainBoxes.unchecked, near: (0, 0, 255)) == 0) + + var style = TranscriptStyle() + style.taskCheckedColor = TranscriptColor(red: 1, green: 0, blue: 0) + style.taskCheckmarkColor = TranscriptColor(red: 0, green: 1, blue: 0) + style.taskUncheckedColor = TranscriptColor(red: 0, green: 0, blue: 1) + let styled = layout(markdown, style: style) + let styledBoxes = try #require(taskBoxes(styled)) + let after = Drawing(styled) + #expect(after.count(in: styledBoxes.checked, near: (0, 122, 255)) == 0) + #expect(after.count(in: styledBoxes.checked, near: (255, 0, 0)) > 20) + #expect(after.count(in: styledBoxes.checked, near: (0, 255, 0)) > 4) + #expect(after.count(in: styledBoxes.unchecked, near: (0, 0, 255)) > 10) +} + +// MARK: Quotes + +@Test func quoteTextTakesTheQuoteTextColor() throws { + var style = TranscriptStyle() + let gray = TranscriptColor(red: 0.5, green: 0.5, blue: 0.5) + style.quoteTextColor = gray + let blocks = MarkdownStreamParser.document(from: "Outside.\n\n> Inside [a link](https://x.y).\n> - item").blocks + let outside = style.attributedString(for: blocks[0]) + #expect(outside.attribute(TranscriptStyle.foregroundKey, at: 0, effectiveRange: nil) == nil) + let inside = style.attributedString(for: blocks[1]) + #expect(inside.attribute(TranscriptStyle.foregroundKey, at: 0, effectiveRange: nil) as? TranscriptColor == gray) + let link = (inside.string as NSString).range(of: "a link") + #expect(inside.attribute(TranscriptStyle.foregroundKey, at: link.location, effectiveRange: nil) as? TranscriptColor == style.linkColor) + + let drawn = DocumentLayout(document: MarkdownStreamParser.document(from: "> - item\n\n- > not quoted marker"), width: 300, style: style) + let quotedBullet = try #require(textMarker(drawn, at: 0)) + #expect(color(of: quotedBullet.attributes) == gray) + let plainBullet = try #require(textMarker(drawn, at: 1)) + #expect(color(of: plainBullet.attributes) == nil) +} + +@Test func quoteBarsTakeTheirColorAndWidth() { + let markdown = "> quoted text" + let plain = layout(markdown) + let before = Drawing(plain) + let frame = plain.entry(at: 0).frame + // One row of pixels across the bar. + let row = CGRect(x: 0, y: frame.midY, width: 10, height: 0.5) + // The bar of today: 3 points wide, in the accent gray (gray 0.6, drawn as 169 in sRGB). + #expect(before.count(in: row, near: (169, 169, 169), tolerance: 8) == 6) + + var style = TranscriptStyle() + style.quoteBarColor = TranscriptColor(red: 1, green: 0, blue: 0) + style.quoteBarWidth = 6 + let styled = layout(markdown, style: style) + let after = Drawing(styled) + #expect(after.count(in: row, near: (169, 169, 169), tolerance: 8) == 0) + #expect(after.count(in: row, near: (255, 0, 0), tolerance: 8) == 12) +} + +@Test func aNegativeQuoteBarWidthDrawsNoBar() { + var style = TranscriptStyle() + style.quoteBarColor = TranscriptColor(red: 1, green: 0, blue: 0) + style.quoteBarWidth = -6 + let drawn = layout("> > quoted text", style: style) + let all = CGRect(x: 0, y: 0, width: drawn.width, height: drawn.height) + #expect(Drawing(drawn).count(in: all, near: (255, 0, 0), tolerance: 8) == 0) +} + +// MARK: Inline code + +@Test func inlineCodeTakesItsFill() { + let markdown = "Run `make all` now." + let block = MarkdownStreamParser.document(from: markdown).blocks[0] + let code = (block.text as NSString).range(of: "make all") + let plainText = TranscriptStyle().attributedString(for: block) + #expect(plainText.attribute(TranscriptStyle.inlineCodeBackgroundKey, at: code.location, effectiveRange: nil) == nil) + + var style = TranscriptStyle() + let red = TranscriptColor(red: 1, green: 0, blue: 0) + style.inlineCodeBackgroundColor = red + style.inlineCodeCornerRadius = 2 + let styledText = style.attributedString(for: block) + #expect(styledText.attribute(TranscriptStyle.inlineCodeBackgroundKey, at: code.location, effectiveRange: nil) as? TranscriptColor == red) + #expect(styledText.attribute(TranscriptStyle.inlineCodeBackgroundKey, at: 0, effectiveRange: nil) == nil) + + let plain = layout(markdown) + let styled = layout(markdown, style: style) + let line = styled.entry(at: 0).layout.lines[0] + let box = line.frame.offsetBy(dx: 0, dy: styled.entry(at: 0).y) + #expect(Drawing(plain).count(in: box, near: (255, 0, 0)) == 0) + #expect(Drawing(styled).count(in: box, near: (255, 0, 0)) > 200) +} + +@Test func aTagHighlightWinsOverTheInlineCodeFill() { + let yellow = TranscriptColor(red: 1, green: 1, blue: 0) + let tag = TranscriptTag("mark", TranscriptDecoration(background: yellow)) + var style = TranscriptStyle() + style.inlineCodeBackgroundColor = TranscriptColor(red: 1, green: 0, blue: 0) + let block = MarkdownStreamParser.document(from: "`code`", tags: [tag]).blocks[0] + let text = style.attributedString(for: block) + #expect(text.attribute(TranscriptStyle.backgroundKey, at: 0, effectiveRange: nil) as? TranscriptColor == yellow) + #expect(text.attribute(TranscriptStyle.inlineCodeBackgroundKey, at: 0, effectiveRange: nil) == nil) +} + +// MARK: Table headers + +@Test func tableHeadersTakeTheirWeight() throws { + let markdown = "| Name | Value |\n| --- | --- |\n| a | 1 |" + func headerFont(_ style: TranscriptStyle) -> CTFont { + let table = layout(markdown, style: style).entry(at: 0).layout + let run = (CTLineGetGlyphRuns(table.lines[0].ctLine) as! [CTRun])[0] + return (CTRunGetAttributes(run) as NSDictionary)[kCTFontAttributeName] as! CTFont + } + let plain = headerFont(TranscriptStyle()) + #expect(CTFontGetSymbolicTraits(plain).contains(.traitBold)) + + var style = TranscriptStyle() + style.tableHeaderWeight = 0 + let regular = headerFont(style) + #expect(!CTFontGetSymbolicTraits(regular).contains(.traitBold)) + style.tableHeaderWeight = 0.23 + let medium = headerFont(style) + let weights = [plain, regular, medium].map { font -> CGFloat in + let traits = CTFontCopyTraits(font) as NSDictionary + return CGFloat((traits[kCTFontWeightTrait] as? NSNumber)?.doubleValue ?? 0) + } + #expect(weights[1] < weights[2] && weights[2] < weights[0]) + + // The weight changes how wide the text is, so the columns are measured with it. + let bold = layout(markdown).entry(at: 0).layout.lines[0].frame.width + #expect(layout(markdown, style: style).entry(at: 0).layout.lines[0].frame.width < bold) +} + +@Test func codeInATableHeaderKeepsTheHeaderWeight() throws { + let markdown = "| `a` | b |\n| --- | --- |\n| c | d |" + func codeFont(_ style: TranscriptStyle) throws -> CTFont { + let table = layout(markdown, style: style).entry(at: 0).layout + let run = try #require((CTLineGetGlyphRuns(table.lines[0].ctLine) as! [CTRun]).first) + let font = (CTRunGetAttributes(run) as NSDictionary)[kCTFontAttributeName] as! CTFont + #expect(CTFontGetSymbolicTraits(font).contains(.traitMonoSpace)) + return font + } + func isBold(_ font: CTFont) -> Bool { CTFontGetSymbolicTraits(font).contains(.traitBold) } + #expect(isBold(try codeFont(TranscriptStyle()))) + + var style = TranscriptStyle() + style.tableHeaderWeight = 0.4 + #expect(isBold(try codeFont(style))) + style.tableHeaderWeight = 0 + #expect(!isBold(try codeFont(style))) +} + +@Test func tableHeadersTakeTheirFill() throws { + let markdown = "| Name | Value |\n| --- | --- |\n| a | 1 |" + let plain = layout(markdown) + let table = try #require(plain.entry(at: 0).layout.table) + let header = CGRect(x: table.columnX[0] + 2, y: plain.entry(at: 0).y + table.rowY[0] + 2, + width: table.columnX[1] - table.columnX[0] - 4, height: table.rowY[1] - table.rowY[0] - 4) + // Gray 0.9 is drawn as 232 in sRGB. + let before = Drawing(plain) + #expect(before.count(in: header, near: (232, 232, 232), tolerance: 4) > 100) + + var style = TranscriptStyle() + style.tableHeaderBackgroundColor = TranscriptColor(red: 1, green: 0, blue: 0) + let after = Drawing(layout(markdown, style: style)) + #expect(after.count(in: header, near: (232, 232, 232), tolerance: 4) == 0) + #expect(after.count(in: header, near: (255, 0, 0), tolerance: 8) > 100) +} + +// MARK: Dark appearance + +@Test func shapeColorsTakeTheirDarkValues() throws { + let markdown = "> quoted\n\n- [x] done\n- [ ] open\n\n| Name | Value |\n| --- | --- |\n| a | 1 |" + let red = TranscriptColor(red: 1, green: 0, blue: 0) + let green = TranscriptColor(red: 0, green: 1, blue: 0) + var style = TranscriptStyle() + style.quoteBarColor = TranscriptColor(light: red, dark: green) + style.taskCheckedColor = TranscriptColor(light: red, dark: green) + style.tableHeaderBackgroundColor = TranscriptColor(light: red, dark: green) + let drawn = layout(markdown, style: style) + let quote = drawn.entry(at: 0).frame + let bar = CGRect(x: 0, y: quote.midY, width: 10, height: 0.5) + guard case .checkbox(let box, true)? = drawn.entry(at: 1).layout.marker else { + Issue.record("A checked task has a checkbox") + return + } + let checked = box.offsetBy(dx: 0, dy: drawn.entry(at: 1).y) + let table = try #require(drawn.entry(at: 3).layout.table) + let header = CGRect(x: table.columnX[0] + 2, y: drawn.entry(at: 3).y + table.rowY[0] + 2, + width: table.columnX[1] - table.columnX[0] - 4, height: table.rowY[1] - table.rowY[0] - 4) + for (dark, expected, other) in [(false, (255, 0, 0), (0, 255, 0)), (true, (0, 255, 0), (255, 0, 0))] { + let pixels = Drawing(drawn, dark: dark) + #expect(pixels.count(in: bar, near: expected, tolerance: 8) == 6, "dark: \(dark)") + #expect(pixels.count(in: bar, near: other, tolerance: 8) == 0, "dark: \(dark)") + #expect(pixels.count(in: checked, near: expected) > 20, "dark: \(dark)") + #expect(pixels.count(in: checked, near: other) == 0, "dark: \(dark)") + #expect(pixels.count(in: header, near: expected, tolerance: 8) > 100, "dark: \(dark)") + #expect(pixels.count(in: header, near: other, tolerance: 8) == 0, "dark: \(dark)") + } +}