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
17 changes: 14 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ TranscriptText(stream: stream)
```

In UIKit, set `codeHighlighter` on `TranscriptTextView`. Colors are `TranscriptColor`s, so give them a light and a dark
value when the theme has both.
value when the theme has both, and Increase Contrast values when it has them.

### Math

Expand Down Expand Up @@ -355,8 +355,19 @@ A line height replaces `lineSpacing` for that kind of text, and a line is never
`scalesWithDynamicType`, `TranscriptText` scales every text size and line height as `UIFontMetrics` scales body text.
With `TranscriptTextView`, set `style.scaled(for: traitCollection.preferredContentSizeCategory)` yourself.

It also sets the colors. Each one is a `TranscriptColor`, with a value for light and one for dark appearance, so the
text can be drawn off the main thread. A color that is nil uses the system color shown here:
The text follows the Bold Text setting. With Bold Text on, the view lays out the text again with heavier system fonts:
regular text becomes semibold, and bold text becomes heavy. The default code font takes its bold face, so bold code
then looks the same as the code around it. Set a system `codeFont`, such as
`TranscriptFont(size: 15, monospaced: true)`, to keep bold code heavier. A named font keeps its own weight. To stop the
view from making the fonts heavier, set `style.followsBoldText = false`. When you lay out a `DocumentLayout` yourself,
use `style.withBoldText(traitCollection.legibilityWeight == .bold)`, and lay out again when the setting changes. Draw
it with `highContrast: traitCollection.accessibilityContrast == .high` to use the Increase Contrast colors.

It also sets the colors. Each one is a `TranscriptColor`, with a value for light and one for dark appearance, and one
for each when Increase Contrast is on, so the text can be drawn off the main thread. `TranscriptColor(UIColor)` keeps
all four values of a dynamic color, and `TranscriptColor(light:dark:highContrastLight:highContrastDark:)` sets them
yourself. The view draws the text again when the appearance or the contrast changes. A color that is nil uses the
system color shown here:

```swift
var style = TranscriptStyle()
Expand Down
48 changes: 26 additions & 22 deletions Sources/TranscriptKit/Layout/DocumentLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -336,17 +336,19 @@ public final class DocumentLayout: @unchecked Sendable {
/// Draws the blocks intersecting `dirtyRect` into a top-left-origin context.
/// `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.
/// picks the dark values of the style's colors and custom tags' colors,
/// and `highContrast` their Increase Contrast values.
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)
dark: Bool = false, highContrast: Bool = false) {
draw(in: context, dirtyRect: dirtyRect, text: text, codeBackground: codeBackground, accent: accent, dark: dark,
highContrast: highContrast, hiding: .none)
}

/// - Parameter hiding: animated tags whose animation is playing, drawn
/// above the text instead (their glyphs and shapes are left out), or
/// waiting to play (their shapes are left out).
func draw(in context: CGContext, dirtyRect: CGRect, text: CGColor, codeBackground: CGColor, accent: CGColor,
dark: Bool, hiding: TagHiding) {
dark: Bool, highContrast: Bool, hiding: TagHiding) {
context.saveGState()
defer { context.restoreGState() }
// Core Text draws y-up; flip glyphs so they are upright in a y-down context.
Expand All @@ -362,7 +364,7 @@ public final class DocumentLayout: @unchecked Sendable {
guard let highlight = current else { return }
current = nil
context.saveGState()
context.setFillColor(highlight.color.cgColor(dark: dark))
context.setFillColor(highlight.color.cgColor(dark: dark, highContrast: highContrast))
let rect = highlight.rect.insetBy(dx: -1.5, dy: 0)
let radius = min(max(highlight.radius, 0), rect.width / 2, rect.height / 2)
context.addPath(CGPath(roundedRect: rect, cornerWidth: radius, cornerHeight: radius, transform: nil))
Expand Down Expand Up @@ -400,7 +402,7 @@ public final class DocumentLayout: @unchecked Sendable {
// indexes) are left out.
func drawLine(_ line: CTLine, at origin: CGPoint, hidden: [Range<Int>] = []) {
drawHighlights(CTLineGetGlyphRuns(line) as! [CTRun], at: origin)
Self.drawGlyphs(of: line, at: origin, hidden: hidden, in: context, text: text, dark: dark)
Self.drawGlyphs(of: line, at: origin, hidden: hidden, in: context, text: text, dark: dark, highContrast: highContrast)
}

func fill(_ rect: CGRect, radius: CGFloat, color: CGColor) {
Expand Down Expand Up @@ -429,7 +431,7 @@ public final class DocumentLayout: @unchecked Sendable {
context.interpolationQuality = .high
if let tint = item.image.tint {
context.clip(to: box, mask: item.image.image)
context.setFillColor(tint.cgColor(dark: dark))
context.setFillColor(tint.cgColor(dark: dark, highContrast: highContrast))
context.fill(box)
} else {
context.draw(item.image.image, in: box)
Expand All @@ -453,7 +455,7 @@ public final class DocumentLayout: @unchecked Sendable {
context.translateBy(x: line.frame.minX, y: entry.y + line.baseline)
for (index, path) in paths.enumerated() {
if !hiding.isEmpty, index < owners.count, let owner = owners[index], hiding.hidesShapes(of: owner) { continue }
path.draw(in: context, dark: dark)
path.draw(in: context, dark: dark, highContrast: highContrast)
}
context.restoreGState()
}
Expand All @@ -480,7 +482,7 @@ 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
let bar = style.quoteBarColor?.cgColor(dark: dark, highContrast: highContrast) ?? accent
var x: CGFloat = 0
for (depth, container) in block.containers.enumerated() {
if container == .quote {
Expand All @@ -501,7 +503,7 @@ public final class DocumentLayout: @unchecked Sendable {
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 {
let header = style.tableHeaderBackgroundColor?.cgColor(dark: dark) ?? codeBackground
let header = style.tableHeaderBackgroundColor?.cgColor(dark: dark, highContrast: highContrast) ?? codeBackground
drawGrid(table, top: entry.y, in: context, header: header, lines: accent)
}
case .paragraph, .heading:
Expand Down Expand Up @@ -545,8 +547,9 @@ public final class DocumentLayout: @unchecked Sendable {
drawLine(line, at: CGPoint(x: origin.x, y: entry.y + origin.y))
case .checkbox(let rect, let checked)?:
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)
let color = style.textColor(inside: block.containers[..<item])?.cgColor(dark: dark, highContrast: highContrast) ?? text
drawCheckbox(rect.offsetBy(dx: 0, dy: entry.y), checked: checked, in: context, text: color, dark: dark,
highContrast: highContrast)
case nil:
break
}
Expand All @@ -561,7 +564,7 @@ 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
let imageText = layout.attachments.isEmpty ? text : style.textColor(inside: block.containers)?.cgColor(dark: dark, highContrast: highContrast) ?? text
for attachment in layout.attachments {
let rect = attachment.rect.offsetBy(dx: 0, dy: entry.y)
guard rect.intersects(dirtyRect) else { continue }
Expand All @@ -574,24 +577,25 @@ public final class DocumentLayout: @unchecked Sendable {

/// The fill color a run's glyphs are drawn with: the tag's own color, or
/// the text's. A run with a color attribute (a link) uses that instead.
static func setGlyphColor(of attributes: NSDictionary, in context: CGContext, text: CGColor, dark: Bool) {
let custom = (attributes[foregroundKey] as? TranscriptColor)?.cgColor(dark: dark)
static func setGlyphColor(of attributes: NSDictionary, in context: CGContext, text: CGColor, dark: Bool, highContrast: Bool) {
let custom = (attributes[foregroundKey] as? TranscriptColor)?.cgColor(dark: dark, highContrast: highContrast)
context.setFillColor(custom ?? text)
}

/// Draws a line's glyphs, and their strikethrough and underline, leaving
/// out the characters in `hidden` (line string indexes). Images are left
/// to the caller. The context's text matrix must flip glyphs upright.
static func drawGlyphs(of line: CTLine, at origin: CGPoint, hidden: [Range<Int>], in context: CGContext, text: CGColor, dark: Bool) {
static func drawGlyphs(of line: CTLine, at origin: CGPoint, hidden: [Range<Int>], in context: CGContext, text: CGColor, dark: Bool,
highContrast: Bool) {
for run in CTLineGetGlyphRuns(line) as! [CTRun] {
let attributes = CTRunGetAttributes(run) as NSDictionary
if attributes[imageKey] != nil { continue }
let ranges = hidden.isEmpty ? [CFRange(location: 0, length: 0)] : glyphRanges(of: run, leavingOut: hidden)
guard !ranges.isEmpty else { continue }
setGlyphColor(of: attributes, in: context, text: text, dark: dark)
setGlyphColor(of: attributes, in: context, text: text, dark: dark, highContrast: highContrast)
context.textPosition = origin
for range in ranges { CTRunDraw(run, context, range) }
let custom = (attributes[foregroundKey] as? TranscriptColor)?.cgColor(dark: dark)
let custom = (attributes[foregroundKey] as? TranscriptColor)?.cgColor(dark: dark, highContrast: highContrast)
let strike = attributes[strikethroughKey] != nil
let underline = attributes[underlineKey] != nil
guard strike || underline, let font = attributes[kCTFontAttributeName].map({ $0 as! CTFont }) else { continue }
Expand Down Expand Up @@ -675,26 +679,26 @@ public final class DocumentLayout: @unchecked Sendable {
context.restoreGState()
}

private func drawCheckbox(_ rect: CGRect, checked: Bool, in context: CGContext, text: CGColor, dark: Bool) {
private func drawCheckbox(_ rect: CGRect, checked: Bool, in context: CGContext, text: CGColor, dark: Bool, highContrast: 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(style.taskCheckedColor?.cgColor(dark: dark) ?? CGColor(red: 0, green: 0.478, blue: 1, alpha: 1))
context.setFillColor(style.taskCheckedColor?.cgColor(dark: dark, highContrast: highContrast) ?? 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(style.taskCheckmarkColor?.cgColor(dark: dark) ?? CGColor(red: 1, green: 1, blue: 1, alpha: 1))
context.setStrokeColor(style.taskCheckmarkColor?.cgColor(dark: dark, highContrast: highContrast) ?? 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(style.taskUncheckedColor?.cgColor(dark: dark) ?? text.copy(alpha: 0.45) ?? text)
context.setStrokeColor(style.taskUncheckedColor?.cgColor(dark: dark, highContrast: highContrast) ?? text.copy(alpha: 0.45) ?? text)
context.setLineWidth(1.5)
context.strokePath()
}
Expand Down
5 changes: 3 additions & 2 deletions Sources/TranscriptKit/Layout/FadeRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ final class FadeRenderer {
/// starts; the oldest fade may start before it.
func render(_ layout: DocumentLayout, from: Int, fades: [Fade], colors: TailRenderer.Colors, scale: CGFloat,
playing: Set<TagKey>) -> FadeFrame? {
if scale != self.scale || self.colors.map({ $0.text != colors.text || $0.dark != colors.dark }) ?? true {
let colorsChanged = self.colors.map { $0.text != colors.text || $0.dark != colors.dark || $0.highContrast != colors.highContrast }
if scale != self.scale || colorsChanged ?? true {
drawn.removeAll()
self.colors = colors
self.scale = scale
Expand Down Expand Up @@ -153,7 +154,7 @@ final class FadeRenderer {
context.textMatrix = CGAffineTransform(scaleX: 1, y: -1)
DocumentLayout.drawGlyphs(of: line.ctLine, at: origin,
hidden: hidden.map { ($0.lowerBound - line.indexBase)..<($0.upperBound - line.indexBase) },
in: context, text: colors.text, dark: colors.dark)
in: context, text: colors.text, dark: colors.dark, highContrast: colors.highContrast)
return context.makeImage()
}

Expand Down
8 changes: 6 additions & 2 deletions Sources/TranscriptKit/Layout/LayoutEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -539,15 +539,19 @@ final class LayoutEngine: @unchecked Sendable {
/// Lays out the documents that arrive from now on at `width`, while the
/// view has no width of its own: SwiftUI measured it but has not placed
/// it, as a lazy stack does with a row of zero height. The width the view
/// gets when it is placed replaces this one.
/// gets when it is placed replaces this one. A new style at the same
/// width replaces the old one.
func layOutUntilPlaced(width: CGFloat, style: TranscriptStyle) {
guard width > 0 else { return }
queue.async {
guard self.width == 0 else { return }
let restyled = self.width == width && self.style != style
guard self.width == 0 || restyled else { return }
self.width = width
self.style = style
if let measured = self.measured, measured.width == width, measured.style == style {
self.base = measured
} else if restyled {
self.base = nil
}
}
}
Expand Down
7 changes: 5 additions & 2 deletions Sources/TranscriptKit/Layout/TagAnimationPlayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ enum TagAnimationPlayer {
var text: CGColor
/// Whether custom colors take their dark values.
var dark: Bool
/// Whether custom colors take their Increase Contrast values.
var highContrast = false
var scale: CGFloat
}

Expand Down Expand Up @@ -222,7 +224,8 @@ enum TagAnimationPlayer {
let ink = CGRect(x: x + box.minX, y: baseline - box.maxY, width: box.width, height: box.height).insetBy(dx: -2, dy: -2)
let frame = pixelAligned(ink, scale: appearance.scale)
guard let context = context(for: frame, scale: appearance.scale) else { return nil }
DocumentLayout.setGlyphColor(of: attributes, in: context, text: appearance.text, dark: appearance.dark)
DocumentLayout.setGlyphColor(of: attributes, in: context, text: appearance.text, dark: appearance.dark,
highContrast: appearance.highContrast)
context.textPosition = origin
CTRunDraw(run, context, CFRange(location: source.index, length: 1))
return context.makeImage().map { ($0, frame) }
Expand All @@ -234,7 +237,7 @@ enum TagAnimationPlayer {
let frame = pixelAligned(ink.offsetBy(dx: origin.x, dy: origin.y).insetBy(dx: -1, dy: -1), scale: appearance.scale)
guard let context = context(for: frame, scale: appearance.scale) else { return nil }
context.translateBy(x: origin.x, y: origin.y)
path.draw(in: context, dark: appearance.dark)
path.draw(in: context, dark: appearance.dark, highContrast: appearance.highContrast)
guard let image = context.makeImage() else { return nil }
// `anchor` carries the fragment's origin x, which the reveal mask
// needs to find the path's left edge.
Expand Down
4 changes: 3 additions & 1 deletion Sources/TranscriptKit/Layout/TailRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ final class TailRenderer {
var accent: CGColor
/// Whether custom tags' colors take their dark values.
var dark = false
/// Whether custom tags' colors take their Increase Contrast values.
var highContrast = false
}

/// One drawn tail: show `surface` at `top`, `TailRenderer.height` points tall.
Expand Down Expand Up @@ -160,7 +162,7 @@ final class TailRenderer {
context.clip(to: band)
context.clear(band)
layout.draw(in: context, dirtyRect: band, text: colors.text, codeBackground: colors.codeBackground, accent: colors.accent,
dark: colors.dark, hiding: hiding)
dark: colors.dark, highContrast: colors.highContrast, hiding: hiding)
context.restoreGState()
}
let firstRow = max(0, min(pixelHeight, Int(((start - currentTop) * scale).rounded(.down))))
Expand Down
16 changes: 16 additions & 0 deletions Sources/TranscriptKit/Layout/TranscriptFont.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,22 @@ public struct TranscriptFont: Hashable, Sendable {
#endif
}

/// The weights of the system font, lightest first, as `UIFont.Weight`'s
/// raw values: ultra light, thin, light, regular, medium, semibold, bold,
/// heavy and black.
static let systemWeights: [CGFloat] = [-0.8, -0.6, -0.4, 0, 0.23, 0.3, 0.4, 0.56, 0.62]

/// The weight that Bold Text gives a system font of `weight`. A weight
/// below semibold goes two steps up `systemWeights`, and a heavier one
/// goes one step, to at most black: regular becomes semibold, and bold
/// becomes heavy.
static func boldTextWeight(_ weight: CGFloat) -> CGFloat {
let steps = systemWeights
let index = steps.lastIndex { $0 <= weight + 0.01 } ?? 0
let target = steps[min(index + (steps[index] < 0.3 ? 2 : 1), steps.count - 1)]
return max(target, weight)
}

/// The same font with its size and line height passed through `scale`.
func scaled(_ scale: (CGFloat) -> CGFloat) -> TranscriptFont {
var copy = self
Expand Down
Loading
Loading