diff --git a/README.md b/README.md index 762146d..bce5826 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/Sources/TranscriptKit/Layout/BlockLayout.swift b/Sources/TranscriptKit/Layout/BlockLayout.swift index 262978f..664b1f4 100644 --- a/Sources/TranscriptKit/Layout/BlockLayout.swift +++ b/Sources/TranscriptKit/Layout/BlockLayout.swift @@ -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, 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, @@ -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 { @@ -219,7 +221,15 @@ final class BlockLayout: @unchecked Sendable { let empty = CTLineCreateWithAttributedString(NSAttributedString(string: "", attributes: style.attributes(for: block.kind))) add(empty, range: length.. (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) { @@ -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 @@ -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) { - 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 { @@ -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 { @@ -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.. 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) diff --git a/Sources/TranscriptKit/Layout/TranscriptFont.swift b/Sources/TranscriptKit/Layout/TranscriptFont.swift new file mode 100644 index 0000000..da18f4b --- /dev/null +++ b/Sources/TranscriptKit/Layout/TranscriptFont.swift @@ -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 + } +} diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index 0aa7378..1415c8a 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -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 @@ -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() @@ -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) } @@ -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. @@ -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 } diff --git a/Sources/TranscriptKit/iOS/TranscriptStyle+DynamicType.swift b/Sources/TranscriptKit/iOS/TranscriptStyle+DynamicType.swift new file mode 100644 index 0000000..70fa0d0 --- /dev/null +++ b/Sources/TranscriptKit/iOS/TranscriptStyle+DynamicType.swift @@ -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 diff --git a/Sources/TranscriptKit/iOS/TranscriptText.swift b/Sources/TranscriptKit/iOS/TranscriptText.swift index 79ce070..4782577 100644 --- a/Sources/TranscriptKit/iOS/TranscriptText.swift +++ b/Sources/TranscriptKit/iOS/TranscriptText.swift @@ -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 diff --git a/Tests/TranscriptKitTests/StyleFontTests.swift b/Tests/TranscriptKitTests/StyleFontTests.swift new file mode 100644 index 0000000..36fdf14 --- /dev/null +++ b/Tests/TranscriptKitTests/StyleFontTests.swift @@ -0,0 +1,82 @@ +import CoreText +import Foundation +import Testing +@testable import TranscriptKit + +private func postScriptName(_ font: CTFont) -> String { + CTFontCopyPostScriptName(font) as String +} + +private func weight(_ font: CTFont) -> CGFloat { + let traits = CTFontCopyTraits(font) as NSDictionary + return (traits[kCTFontWeightTrait] as? NSNumber).map { CGFloat($0.doubleValue) } ?? 0 +} + +@Test func aNamedBodyFontIsUsed() { + var style = TranscriptStyle() + style.bodyFont = TranscriptFont(name: "Courier", size: 20) + let font = style.font(for: .paragraph) + #expect(postScriptName(font) == "Courier") + #expect(CTFontGetSize(font) == 20) + #expect(style.effectiveBodySize == 20) +} + +@Test func theSystemFontTakesItsWeight() { + var regular = TranscriptStyle() + regular.bodyFont = TranscriptFont(size: 17) + var heavy = TranscriptStyle() + heavy.bodyFont = TranscriptFont(size: 17, weight: 0.4) + #expect(weight(heavy.font(for: .paragraph)) > weight(regular.font(for: .paragraph)) + 0.2) +} + +@Test func headingLevelsPastTheEndUseTheLastFont() { + var style = TranscriptStyle() + style.headingFonts = [TranscriptFont(size: 30, weight: 0.3), TranscriptFont(size: 24, weight: 0.3)] + #expect(CTFontGetSize(style.font(for: .heading(level: 1))) == 30) + #expect(CTFontGetSize(style.font(for: .heading(level: 2))) == 24) + #expect(CTFontGetSize(style.font(for: .heading(level: 5))) == 24) +} + +@Test func inlineCodeUsesTheCodeFontDesign() { + var style = TranscriptStyle() + style.bodyFont = TranscriptFont(size: 20) + style.codeFont = TranscriptFont(name: "Menlo-Regular", size: 14) + let font = style.font(for: .paragraph, traits: .code) + #expect(postScriptName(font) == "Menlo-Regular") + #expect(abs(CTFontGetSize(font) - 18) < 0.01) + #expect(postScriptName(style.font(for: .code(language: nil))) == "Menlo-Regular") +} + +@Test func letterSpacingIsSetOnTheText() { + var style = TranscriptStyle() + style.bodyFont = TranscriptFont(size: 17, letterSpacing: 1.5) + let block = MarkdownStreamParser.document(from: "Spaced *out* text").blocks[0] + let text = style.attributedString(for: block) + let kern = NSAttributedString.Key(kCTKernAttributeName as String) + #expect(text.attribute(kern, at: 0, effectiveRange: nil) as? CGFloat == 1.5) + #expect(text.attribute(kern, at: 8, effectiveRange: nil) as? CGFloat == 1.5) +} + +@Test func aLineHeightSetsTheDistanceBetweenLines() { + let text = String(repeating: "Words that wrap onto several lines. ", count: 6) + let document = MarkdownStreamParser.document(from: text) + var style = TranscriptStyle() + style.bodyFont = TranscriptFont(size: 17, lineHeight: 40) + let layout = DocumentLayout(document: document, width: 200, style: style) + let lines = layout.entry(at: 0).layout.lines + #expect(lines.count > 2) + for index in 1.. 15) +}