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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,27 @@ In UIKit, set `isSelectable` on `TranscriptTextView`.

`TranscriptStyle` sets the body size, line, block and list spacing, indents, padding and the maximum image height.

To match an app's own type scale, give it fonts. Each `TranscriptFont` has a font name (nil for the system font), a
size, a weight for the system font, letter spacing and a line height. Headings take one font for each level, and
levels past the end use the last one. Inline code uses the code font's design at 0.9 times the size of the text
around it:

```swift
var style = TranscriptStyle()
style.bodyFont = TranscriptFont(size: 16, weight: 0, letterSpacing: -0.2, lineHeight: 24)
style.headingFonts = [
TranscriptFont(size: 28, weight: 0.4, lineHeight: 34),
TranscriptFont(size: 22, weight: 0.3, lineHeight: 28),
TranscriptFont(size: 18, weight: 0.3, lineHeight: 24),
]
style.codeFont = TranscriptFont(name: "Menlo-Regular", size: 14, lineHeight: 20)
style.scalesWithDynamicType = true
```

A line height replaces `lineSpacing` for that kind of text, and a line is never less tall than its font needs. With
`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:

Expand Down
28 changes: 20 additions & 8 deletions Sources/TranscriptKit/Layout/BlockLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,10 @@ final class BlockLayout: @unchecked Sendable {
// Only the tags on the lines laid out again; the others' lines are kept.
let decorated = hasDecorations ? DecoratedTags(block, from: restart) : nil

let fixedHeight = style.lineHeight(for: block.kind)
let gap = fixedHeight == nil ? style.lineSpacing : 0
func add(_ ctLine: CTLine, range: Range<Int>, indexBase: Int, leading: CGFloat = 0, text: NSAttributedString? = nil) {
let metrics = lineMetrics(ctLine, isEmpty: range.isEmpty, font: font)
let metrics = fitted(lineMetrics(ctLine, isEmpty: range.isEmpty, font: font), to: fixedHeight)
var decorations: LineDecorations?
if let decorated, let text {
decorations = LineDecorations.make(line: ctLine, range: range, indexBase: indexBase, visibleWidth: metrics.width,
Expand All @@ -195,7 +197,7 @@ final class BlockLayout: @unchecked Sendable {
baseline: y + metrics.ascent,
decorations: decorations
))
y += metrics.height + style.lineSpacing
y += metrics.height + gap
}

if restart < length {
Expand All @@ -219,7 +221,15 @@ final class BlockLayout: @unchecked Sendable {
let empty = CTLineCreateWithAttributedString(NSAttributedString(string: "", attributes: style.attributes(for: block.kind)))
add(empty, range: length..<length, indexBase: length)
}
return (lines, y - style.lineSpacing + insets.vertical)
return (lines, y - gap + insets.vertical)
}

/// Line metrics made `height` tall, with the text centred, when the app
/// set a line height. A line is never less tall than its text needs.
private static func fitted(_ metrics: (width: CGFloat, height: CGFloat, ascent: CGFloat),
to height: CGFloat?) -> (width: CGFloat, height: CGFloat, ascent: CGFloat) {
guard let height, height > metrics.height else { return metrics }
return (metrics.width, height, metrics.ascent + ((height - metrics.height) / 2).rounded())
}

private static func lineMetrics(_ ctLine: CTLine, isEmpty: Bool, font: CTFont) -> (width: CGFloat, height: CGFloat, ascent: CGFloat) {
Expand Down Expand Up @@ -256,9 +266,11 @@ final class BlockLayout: @unchecked Sendable {
let padding = style.tableCellPadding
let verticalPadding = (padding * 0.75).rounded()
let font = style.font(for: block.kind)
let fixedHeight = style.lineHeight(for: block.kind)
let gap = fixedHeight == nil ? style.lineSpacing : 0
let decorated = DecoratedTags(block)
let sizing = ImageSizing(store: images, maximumWidth: max(available / CGFloat(columns) - padding * 2, 20))
let minimumWidth = padding * 2 + style.bodySize
let minimumWidth = padding * 2 + style.effectiveBodySize

// Leading rows that are complete in the previous layout and unchanged.
var kept = 0
Expand Down Expand Up @@ -371,7 +383,7 @@ final class BlockLayout: @unchecked Sendable {
let textWidth = max(widths[column] - padding * 2, 1)
var y = top + verticalPadding
func add(_ ctLine: CTLine, range: Range<Int>) {
let metrics = lineMetrics(ctLine, isEmpty: range.isEmpty, font: font)
let metrics = fitted(lineMetrics(ctLine, isEmpty: range.isEmpty, font: font), to: fixedHeight)
let slack = max(textWidth - metrics.width, 0)
let offset: CGFloat
switch column < model.alignments.count ? model.alignments[column] : .leading {
Expand All @@ -396,7 +408,7 @@ final class BlockLayout: @unchecked Sendable {
baseline: y + metrics.ascent,
decorations: decorations
))
y += metrics.height + style.lineSpacing
y += metrics.height + gap
}
var start = 0
while start < cell.text.length {
Expand All @@ -410,7 +422,7 @@ final class BlockLayout: @unchecked Sendable {
let empty = CTLineCreateWithAttributedString(NSAttributedString(string: "", attributes: style.attributes(for: block.kind)))
add(empty, range: cell.range.lowerBound..<cell.range.lowerBound)
}
bottom = max(bottom, y - style.lineSpacing + verticalPadding)
bottom = max(bottom, y - gap + verticalPadding)
rowLines.append(first..<lines.count)
}
rowY.append(ceil(bottom))
Expand All @@ -429,7 +441,7 @@ final class BlockLayout: @unchecked Sendable {
let font = style.font(for: .paragraph)
switch kind {
case .task(let checked):
let side = (style.bodySize * 0.82).rounded()
let side = (style.effectiveBodySize * 0.82).rounded()
let middle = firstLine.baseline - CTFontGetCapHeight(font) / 2
return .checkbox(CGRect(x: gutterEnd - side - 6, y: (middle - side / 2).rounded(), width: side, height: side), checked: checked)
case .bullet, .number:
Expand Down
2 changes: 1 addition & 1 deletion Sources/TranscriptKit/Layout/DocumentLayout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public final class DocumentLayout: @unchecked Sendable {

public func caretRect(at offset: Int) -> CGRect {
guard let index = entryIndex(forOffset: offset) else {
return CGRect(x: 0, y: 0, width: 2, height: style.bodySize * 1.2)
return CGRect(x: 0, y: 0, width: 2, height: style.effectiveBodySize * 1.2)
}
let entry = entry(at: index)
let local = min(max(offset - entry.start, 0), entry.layout.length)
Expand Down
67 changes: 67 additions & 0 deletions Sources/TranscriptKit/Layout/TranscriptFont.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import CoreGraphics
import CoreText
import Foundation
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif

/// How one kind of text is set: its font, letter spacing and line height.
/// See `TranscriptStyle.bodyFont`, `headingFonts` and `codeFont`.
public struct TranscriptFont: Hashable, Sendable {
/// A PostScript font name, such as "Avenir-Book", or nil for the system font.
public var name: String?
public var size: CGFloat
/// The weight of the system font, from -1 to 1 as `UIFont.Weight`'s raw
/// values: 0 is regular, 0.23 medium, 0.3 semibold, 0.4 bold. A named
/// font has its own weight, so this is not used for it.
public var weight: CGFloat
/// The monospaced system font, for code. Not used for a named font.
public var monospaced: Bool
/// Extra space between characters, in points.
public var letterSpacing: CGFloat
/// The height of each line, in points, or nil for the font's own line
/// height plus `TranscriptStyle.lineSpacing`. A line is never less tall
/// than the font needs, and its text is centred in the line.
public var lineHeight: CGFloat?

public init(name: String? = nil, size: CGFloat, weight: CGFloat = 0, monospaced: Bool = false,
letterSpacing: CGFloat = 0, lineHeight: CGFloat? = nil) {
self.name = name
self.size = size
self.weight = weight
self.monospaced = monospaced
self.letterSpacing = letterSpacing
self.lineHeight = lineHeight
}

/// The font at `size`, or at its own size.
func makeFont(size: CGFloat? = nil) -> CTFont {
let size = size ?? self.size
if let name {
return CTFontCreateWithName(name as CFString, size, nil)
}
#if canImport(UIKit)
let font = monospaced
? UIFont.monospacedSystemFont(ofSize: size, weight: UIFont.Weight(rawValue: weight))
: UIFont.systemFont(ofSize: size, weight: UIFont.Weight(rawValue: weight))
return font as CTFont
#elseif canImport(AppKit)
let font = monospaced
? NSFont.monospacedSystemFont(ofSize: size, weight: NSFont.Weight(rawValue: weight))
: NSFont.systemFont(ofSize: size, weight: NSFont.Weight(rawValue: weight))
return font as CTFont
#else
return CTFontCreateUIFontForLanguage(monospaced ? .userFixedPitch : .system, size, nil)!
#endif
}

/// The same font with its size and line height passed through `scale`.
func scaled(_ scale: (CGFloat) -> CGFloat) -> TranscriptFont {
var copy = self
copy.size = scale(size)
copy.lineHeight = lineHeight.map(scale)
return copy
}
}
72 changes: 58 additions & 14 deletions Sources/TranscriptKit/Layout/TranscriptStyle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ import Foundation

/// Typography and spacing for a transcript.
public struct TranscriptStyle: Equatable, Sendable {
/// The font of paragraphs, list items, quotes and tables. Nil uses the
/// system font at `bodySize`.
public var bodyFont: TranscriptFont?
/// The fonts of headings: the first for level 1, the second for level 2,
/// and so on. Levels past the end use the last one. Empty uses the
/// emphasized system font at 1.5, 1.3 and 1.15 times `bodySize`.
public var headingFonts: [TranscriptFont] = []
/// The font of code blocks, and the design of inline code, which is set at
/// 0.9 times the size of the text around it. Nil uses the system's
/// monospaced font at 0.88 times `bodySize`.
public var codeFont: TranscriptFont?
/// Whether `TranscriptText` scales the sizes with Dynamic Type; see
/// `scaled(for:)`.
public var scalesWithDynamicType = false

public var bodySize: CGFloat = 17
public var lineSpacing: CGFloat = 3
public var blockSpacing: CGFloat = 14
Expand Down Expand Up @@ -67,6 +82,8 @@ public struct TranscriptStyle: Equatable, Sendable {
var role: Int
var size: CGFloat
var traits: Int
var font: TranscriptFont?
var code: TranscriptFont?
}

private let lock = NSLock()
Expand All @@ -91,26 +108,51 @@ public struct TranscriptStyle: Equatable, Sendable {
let role: Int
switch kind {
case .paragraph, .rule, .table: role = 0
case .heading(let level): role = min(max(level, 1), 3)
case .code: role = 4
case .heading(let level): role = min(max(level, 1), 6)
case .code: role = 7
}
let key = FontCache.Key(role: role, size: bodySize, traits: traits.rawValue)
let key = FontCache.Key(role: role, size: bodySize, traits: traits.rawValue, font: customFont(for: kind),
code: traits.contains(.code) ? codeFont : nil)
return Self.fontCache.font(for: key) { makeFont(for: kind, traits: traits) }
}

private func makeFont(for kind: TranscriptBlock.Kind, traits: InlineSpan.Traits) -> CTFont {
var font: CTFont
/// The font the app set for this kind of text, if any.
func customFont(for kind: TranscriptBlock.Kind) -> TranscriptFont? {
switch kind {
case .paragraph, .rule, .table:
font = CTFontCreateUIFontForLanguage(.system, bodySize, nil)!
case .paragraph, .rule, .table: return bodyFont
case .heading(let level):
let scale: CGFloat = level <= 1 ? 1.5 : (level == 2 ? 1.3 : 1.15)
font = CTFontCreateUIFontForLanguage(.emphasizedSystem, bodySize * scale, nil)!
case .code:
font = CTFontCreateUIFontForLanguage(.userFixedPitch, bodySize * 0.88, nil)!
guard !headingFonts.isEmpty else { return nil }
return headingFonts[min(max(level, 1), headingFonts.count) - 1]
case .code: return codeFont
}
}

/// The line height the app set for this kind of text, if any.
func lineHeight(for kind: TranscriptBlock.Kind) -> CGFloat? {
customFont(for: kind)?.lineHeight
}

/// 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 {
var font: CTFont
if let custom = customFont(for: kind) {
font = custom.makeFont()
} else {
switch kind {
case .paragraph, .rule, .table:
font = CTFontCreateUIFontForLanguage(.system, bodySize, nil)!
case .heading(let level):
let scale: CGFloat = level <= 1 ? 1.5 : (level == 2 ? 1.3 : 1.15)
font = CTFontCreateUIFontForLanguage(.emphasizedSystem, bodySize * scale, nil)!
case .code:
font = CTFontCreateUIFontForLanguage(.userFixedPitch, bodySize * 0.88, nil)!
}
}
if traits.contains(.code) {
font = CTFontCreateUIFontForLanguage(.userFixedPitch, CTFontGetSize(font) * 0.9, nil)!
let size = CTFontGetSize(font) * 0.9
font = codeFont?.makeFont(size: size) ?? CTFontCreateUIFontForLanguage(.userFixedPitch, size, nil)!
}
var symbolic: CTFontSymbolicTraits = []
if traits.contains(.bold) { symbolic.insert(.traitBold) }
Expand All @@ -137,11 +179,13 @@ public struct TranscriptStyle: Equatable, Sendable {
private static let kernKey = NSAttributedString.Key(kCTKernAttributeName as String)

func attributes(for kind: TranscriptBlock.Kind) -> [NSAttributedString.Key: Any] {
[
var attributes: [NSAttributedString.Key: Any] = [
Self.fontKey: font(for: kind),
// Text takes the context's fill color, so the view controls light/dark.
Self.colorFromContextKey: true,
]
if let spacing = customFont(for: kind)?.letterSpacing, spacing != 0 { attributes[Self.kernKey] = spacing }
return attributes
}

/// The styled text of `block` from UTF-16 offset `start` to its end.
Expand Down Expand Up @@ -222,7 +266,7 @@ public struct TranscriptStyle: Equatable, Sendable {
for (offset, kern) in kerns where offset >= start && offset < start + length {
// On the whole character, so a glyph made of several units keeps it.
let character = (result.string as NSString).rangeOfComposedCharacterSequence(at: offset - start)
result.addAttribute(Self.kernKey, value: kern, range: character)
result.addAttribute(Self.kernKey, value: kern + (customFont(for: block.kind)?.letterSpacing ?? 0), range: character)
}
return result
}
Expand Down
22 changes: 22 additions & 0 deletions Sources/TranscriptKit/iOS/TranscriptStyle+DynamicType.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#if canImport(UIKit) && !os(watchOS)
import UIKit

extension TranscriptStyle {
/// A copy with every text size and line height scaled for `category`, as
/// `UIFontMetrics` scales body text. Spacing and indents do not change.
/// `TranscriptText` applies it when `scalesWithDynamicType` is on. With
/// `TranscriptTextView`, set the scaled style yourself when the trait
/// collection's `preferredContentSizeCategory` changes.
public func scaled(for category: UIContentSizeCategory) -> TranscriptStyle {
let metrics = UIFontMetrics(forTextStyle: .body)
let traits = UITraitCollection(preferredContentSizeCategory: category)
let scale = { (size: CGFloat) in metrics.scaledValue(for: size, compatibleWith: traits) }
var copy = self
copy.bodySize = scale(bodySize)
copy.bodyFont = bodyFont?.scaled(scale)
copy.headingFonts = headingFonts.map { $0.scaled(scale) }
copy.codeFont = codeFont?.scaled(scale)
return copy
}
}
#endif
4 changes: 3 additions & 1 deletion Sources/TranscriptKit/iOS/TranscriptText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,9 @@ public struct TranscriptText: UIViewRepresentable {
}

public func updateUIView(_ view: TranscriptTextView, context: Context) {
view.style = style
view.style = style.scalesWithDynamicType
? style.scaled(for: UIContentSizeCategory(context.environment.dynamicTypeSize))
: style
view.animatesTags = animatesTags
view.tagAnimationTiming = animationTiming
view.isSelectable = isSelectable
Expand Down
Loading