Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 15 additions & 6 deletions Sources/TranscriptKit/Layout/BlockLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -365,8 +365,11 @@ final class BlockLayout: @unchecked Sendable {

typealias Cell = (text: NSAttributedString, typesetter: CTTypesetter, range: Range<Int>)
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)
}
Expand Down Expand Up @@ -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[..<item])
let font = style.font(for: .paragraph)
switch kind {
case .task(let checked):
Expand All @@ -527,13 +531,18 @@ final class BlockLayout: @unchecked Sendable {
return .checkbox(CGRect(x: gutterEnd - side - 6, y: (middle - side / 2).rounded(), width: side, height: side), checked: checked)
case .bullet, .number:
let text: String
var attributes: [NSAttributedString.Key: Any]
if case .number(let number) = kind {
text = number
text = style.listNumberFormat.text(for: number)
attributes = style.attributes(for: .paragraph, weight: style.listNumberWeight)
if let color = style.listNumberColor ?? quoteColor { attributes[TranscriptStyle.foregroundKey] = color }
} else {
let depth = block.listLevel
text = depth <= 1 ? "•" : (depth == 2 ? "◦" : "▪")
let bullet = style.bullet(at: block.listLevel)
text = bullet.text
attributes = style.attributes(for: .paragraph)
if let color = bullet.color ?? quoteColor { attributes[TranscriptStyle.foregroundKey] = color }
}
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: style.attributes(for: .paragraph)))
let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: attributes))
let markerWidth = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))
return .text(line, origin: CGPoint(x: max(gutterEnd - markerWidth - 7, 0), y: firstLine.baseline))
}
Expand Down
51 changes: 32 additions & 19 deletions Sources/TranscriptKit/Layout/DocumentLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -333,8 +333,9 @@ public final class DocumentLayout: @unchecked Sendable {
// MARK: Drawing

/// Draws the blocks intersecting `dirtyRect` into a top-left-origin context.
/// `accent` colors quote bars and rules. `dark` picks the dark values of
/// custom tags' colors.
/// `accent` colors quote bars and rules, and `codeBackground` code blocks
/// and table headers, unless the style sets their own colors. `dark`
/// picks the dark values of the style's colors and custom tags' colors.
public func draw(in context: CGContext, dirtyRect: CGRect, text: CGColor, codeBackground: CGColor, accent: CGColor,
dark: Bool = false) {
draw(in: context, dirtyRect: dirtyRect, text: text, codeBackground: codeBackground, accent: accent, dark: dark, hiding: .none)
Expand All @@ -350,38 +351,42 @@ public final class DocumentLayout: @unchecked Sendable {
// Core Text draws y-up; flip glyphs so they are upright in a y-down context.
context.textMatrix = CGAffineTransform(scaleX: 1, y: -1)

// Custom tags' highlights, behind the whole line's glyphs. Runs next
// to each other with the same color share one highlight, and it stays
// within the line, so drawing a band of lines never cuts one off.
// Custom tags' highlights and inline code fills, behind the whole
// line's glyphs. Runs next to each other with the same fill share one
// highlight, and it stays within the line, so drawing a band of lines
// never cuts one off.
func drawHighlights(_ runs: [CTRun], at origin: CGPoint) {
var current: (rect: CGRect, color: TranscriptColor)?
var current: (rect: CGRect, color: TranscriptColor, radius: CGFloat)?
func flush() {
guard let highlight = current else { return }
current = nil
context.saveGState()
context.setFillColor(highlight.color.cgColor(dark: dark))
let rect = highlight.rect.insetBy(dx: -1.5, dy: 0)
context.addPath(CGPath(roundedRect: rect, cornerWidth: 3, cornerHeight: 3, transform: nil))
let radius = min(max(highlight.radius, 0), rect.width / 2, rect.height / 2)
context.addPath(CGPath(roundedRect: rect, cornerWidth: radius, cornerHeight: radius, transform: nil))
context.fillPath()
context.restoreGState()
}
for run in runs {
let attributes = CTRunGetAttributes(run) as NSDictionary
guard let color = attributes[Self.backgroundKey] as? TranscriptColor, attributes[Self.imageKey] == nil,
let tag = attributes[Self.backgroundKey] as? TranscriptColor
guard let color = tag ?? attributes[Self.inlineCodeBackgroundKey] as? TranscriptColor, attributes[Self.imageKey] == nil,
let font = attributes[kCTFontAttributeName].map({ $0 as! CTFont }) else {
flush()
continue
}
let radius: CGFloat = tag != nil ? 3 : style.inlineCodeCornerRadius
var position = CGPoint.zero
CTRunGetPositions(run, CFRange(location: 0, length: 1), &position)
let width = CGFloat(CTRunGetTypographicBounds(run, CFRange(location: 0, length: 0), nil, nil, nil))
let ascent = CTFontGetAscent(font)
let rect = CGRect(x: origin.x + position.x, y: origin.y - ascent, width: width, height: ascent + CTFontGetDescent(font))
if let highlight = current, highlight.color == color, abs(highlight.rect.maxX - rect.minX) < 0.5 {
current = (highlight.rect.union(rect), color)
if let highlight = current, highlight.color == color, highlight.radius == radius, abs(highlight.rect.maxX - rect.minX) < 0.5 {
current = (highlight.rect.union(rect), color, radius)
} else {
flush()
current = (rect, color)
current = (rect, color, radius)
}
}
flush()
Expand Down Expand Up @@ -474,13 +479,14 @@ public final class DocumentLayout: @unchecked Sendable {
// Quote bars, run on through the gap from the block above when it
// is in the same quote.
let above = index > 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)
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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[..<item])?.cgColor(dark: dark) ?? text
drawCheckbox(rect.offsetBy(dx: 0, dy: entry.y), checked: checked, in: context, text: color, dark: dark)
case nil:
break
}
Expand All @@ -549,10 +560,11 @@ public final class DocumentLayout: @unchecked Sendable {
hidden: hidden.map { ($0.lowerBound - line.indexBase)..<($0.upperBound - line.indexBase) })
}

let imageText = layout.attachments.isEmpty ? text : style.textColor(inside: block.containers)?.cgColor(dark: dark) ?? text
for attachment in layout.attachments {
let rect = attachment.rect.offsetBy(dx: 0, dy: entry.y)
guard rect.intersects(dirtyRect) else { continue }
drawImage(attachment.attachment, in: rect, context: context, text: text, background: codeBackground)
drawImage(attachment.attachment, in: rect, context: context, text: imageText, background: codeBackground)
}

for index in visible { drawShapes(of: lines[index], in: entry, over: true) }
Expand Down Expand Up @@ -632,6 +644,7 @@ public final class DocumentLayout: @unchecked Sendable {
private static let underlineKey = TranscriptStyle.underlineKey.rawValue
private static let foregroundKey = TranscriptStyle.foregroundKey.rawValue
private static let backgroundKey = TranscriptStyle.backgroundKey.rawValue
private static let inlineCodeBackgroundKey = TranscriptStyle.inlineCodeBackgroundKey.rawValue

private func drawGrid(_ table: BlockLayout.Table, top: CGFloat, in context: CGContext, header: CGColor, lines: CGColor) {
let frame = table.frame.offsetBy(dx: 0, dy: top)
Expand Down Expand Up @@ -661,26 +674,26 @@ public final class DocumentLayout: @unchecked Sendable {
context.restoreGState()
}

private func drawCheckbox(_ rect: CGRect, checked: Bool, in context: CGContext, stroke: CGColor) {
private func drawCheckbox(_ rect: CGRect, checked: Bool, in context: CGContext, text: CGColor, dark: Bool) {
context.saveGState()
let box = CGPath(roundedRect: rect.insetBy(dx: 0.75, dy: 0.75), cornerWidth: 4, cornerHeight: 4, transform: nil)
if checked {
context.setFillColor(CGColor(red: 0, green: 0.478, blue: 1, alpha: 1))
context.setFillColor(style.taskCheckedColor?.cgColor(dark: dark) ?? CGColor(red: 0, green: 0.478, blue: 1, alpha: 1))
context.addPath(box)
context.fillPath()
let check = CGMutablePath()
check.move(to: CGPoint(x: rect.minX + rect.width * 0.25, y: rect.minY + rect.height * 0.52))
check.addLine(to: CGPoint(x: rect.minX + rect.width * 0.43, y: rect.minY + rect.height * 0.7))
check.addLine(to: CGPoint(x: rect.minX + rect.width * 0.76, y: rect.minY + rect.height * 0.32))
context.addPath(check)
context.setStrokeColor(CGColor(red: 1, green: 1, blue: 1, alpha: 1))
context.setStrokeColor(style.taskCheckmarkColor?.cgColor(dark: dark) ?? CGColor(red: 1, green: 1, blue: 1, alpha: 1))
context.setLineWidth(max(rect.width * 0.12, 1.5))
context.setLineCap(.round)
context.setLineJoin(.round)
context.strokePath()
} else {
context.addPath(box)
context.setStrokeColor(stroke.copy(alpha: 0.45) ?? stroke)
context.setStrokeColor(style.taskUncheckedColor?.cgColor(dark: dark) ?? text.copy(alpha: 0.45) ?? text)
context.setLineWidth(1.5)
context.strokePath()
}
Expand Down
Loading
Loading