diff --git a/README.md b/README.md index 09af85c..eacec07 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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() diff --git a/Sources/TranscriptKit/Layout/DocumentLayout.swift b/Sources/TranscriptKit/Layout/DocumentLayout.swift index 5167e77..ead2eda 100644 --- a/Sources/TranscriptKit/Layout/DocumentLayout.swift +++ b/Sources/TranscriptKit/Layout/DocumentLayout.swift @@ -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. @@ -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)) @@ -400,7 +402,7 @@ public final class DocumentLayout: @unchecked Sendable { // indexes) are left out. func drawLine(_ line: CTLine, at origin: CGPoint, hidden: [Range] = []) { 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) { @@ -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) @@ -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() } @@ -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 { @@ -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: @@ -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[..], in context: CGContext, text: CGColor, dark: Bool) { + static func drawGlyphs(of line: CTLine, at origin: CGPoint, hidden: [Range], 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 } @@ -675,11 +679,11 @@ 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() @@ -687,14 +691,14 @@ public final class DocumentLayout: @unchecked Sendable { 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() } diff --git a/Sources/TranscriptKit/Layout/FadeRenderer.swift b/Sources/TranscriptKit/Layout/FadeRenderer.swift index a77c58d..252c30b 100644 --- a/Sources/TranscriptKit/Layout/FadeRenderer.swift +++ b/Sources/TranscriptKit/Layout/FadeRenderer.swift @@ -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) -> 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 @@ -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() } diff --git a/Sources/TranscriptKit/Layout/LayoutEngine.swift b/Sources/TranscriptKit/Layout/LayoutEngine.swift index bf3a32b..d394f55 100644 --- a/Sources/TranscriptKit/Layout/LayoutEngine.swift +++ b/Sources/TranscriptKit/Layout/LayoutEngine.swift @@ -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 } } } diff --git a/Sources/TranscriptKit/Layout/TagAnimationPlayer.swift b/Sources/TranscriptKit/Layout/TagAnimationPlayer.swift index c286b1d..d2df5a8 100644 --- a/Sources/TranscriptKit/Layout/TagAnimationPlayer.swift +++ b/Sources/TranscriptKit/Layout/TagAnimationPlayer.swift @@ -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 } @@ -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) } @@ -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. diff --git a/Sources/TranscriptKit/Layout/TailRenderer.swift b/Sources/TranscriptKit/Layout/TailRenderer.swift index 42566d6..0691df9 100644 --- a/Sources/TranscriptKit/Layout/TailRenderer.swift +++ b/Sources/TranscriptKit/Layout/TailRenderer.swift @@ -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. @@ -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)))) diff --git a/Sources/TranscriptKit/Layout/TranscriptFont.swift b/Sources/TranscriptKit/Layout/TranscriptFont.swift index da18f4b..9e7cccc 100644 --- a/Sources/TranscriptKit/Layout/TranscriptFont.swift +++ b/Sources/TranscriptKit/Layout/TranscriptFont.swift @@ -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 diff --git a/Sources/TranscriptKit/Layout/TranscriptStyle.swift b/Sources/TranscriptKit/Layout/TranscriptStyle.swift index f148919..4b05fa7 100644 --- a/Sources/TranscriptKit/Layout/TranscriptStyle.swift +++ b/Sources/TranscriptKit/Layout/TranscriptStyle.swift @@ -45,6 +45,17 @@ public struct TranscriptStyle: Equatable, Sendable { /// Whether `TranscriptText` scales the sizes with Dynamic Type; see /// `scaled(for:)`. public var scalesWithDynamicType = false + /// Whether the view sets the text heavier when the Bold Text setting is + /// on. On by default. Regular text becomes semibold, and bold text + /// becomes heavy. A named font, such as "Avenir-Book", keeps its own + /// weight. The default code font takes its bold face, so bold code then + /// looks the same as the code around it. Off, the view does not make the + /// fonts heavier itself. See `withBoldText(_:)`. + public var followsBoldText = true + /// Whether the Bold Text setting is on, as `withBoldText(_:)` sets it. + var isBoldTextOn = false + /// Whether layout makes the fonts heavier for Bold Text. + var usesBoldText: Bool { isBoldTextOn && followsBoldText } public var bodySize: CGFloat = 17 public var lineSpacing: CGFloat = 3 @@ -185,6 +196,8 @@ public struct TranscriptStyle: Equatable, Sendable { var weight: CGFloat? var font: TranscriptFont? var code: TranscriptFont? + var boldText: Bool + var followsBoldText: Bool } private let lock = NSLock() @@ -220,10 +233,22 @@ public struct TranscriptStyle: Equatable, Sendable { weight = nil } let key = FontCache.Key(role: role, size: bodySize, traits: traits.rawValue, weight: weight, font: customFont(for: kind), - code: traits.contains(.code) ? codeFont : nil) + code: traits.contains(.code) ? codeFont : nil, boldText: isBoldTextOn, + followsBoldText: followsBoldText) return Self.fontCache.font(for: key) { makeFont(for: kind, traits: traits, weight: weight) } } + /// The font that a formula's LaTeX is shown in until it is drawn: the + /// code font at `size`. + func mathFallbackFont(size: CGFloat) -> CTFont { + let key = FontCache.Key(role: 8, size: size, traits: 0, weight: nil, font: nil, code: codeFont, boldText: isBoldTextOn, + followsBoldText: followsBoldText) + return Self.fontCache.font(for: key) { + adjustedForBoldText(codeFont?.makeFont(size: size) ?? CTFontCreateUIFontForLanguage(.userFixedPitch, size, nil)!, + source: codeFont, defaultWeight: nil, traits: []) + } + } + /// The font the app set for this kind of text, if any. func customFont(for kind: TranscriptBlock.Kind) -> TranscriptFont? { switch kind { @@ -246,6 +271,7 @@ public struct TranscriptStyle: Equatable, Sendable { private func makeFont(for kind: TranscriptBlock.Kind, traits: InlineSpan.Traits, weight: CGFloat?) -> CTFont { var font: CTFont var traits = traits + var source = customFont(for: kind) if let weight { if let custom = customFont(for: kind), custom.name != nil { font = custom.makeFont() @@ -254,6 +280,7 @@ public struct TranscriptStyle: Equatable, Sendable { var custom = customFont(for: kind) ?? TranscriptFont(size: bodySize) custom.weight = weight font = custom.makeFont() + source = custom // The code font below replaces this font and its weight. if weight >= 0.3, traits.contains(.code) { traits.insert(.bold) } } @@ -280,7 +307,57 @@ public struct TranscriptStyle: Equatable, Sendable { if !symbolic.isEmpty, let styled = CTFontCreateCopyWithSymbolicTraits(font, 0, nil, symbolic, symbolic) { font = styled } - return font + if traits.contains(.code) { source = codeFont } + let defaultWeight: CGFloat? = switch kind { + case _ where traits.contains(.code): nil + case .paragraph, .rule, .table: 0 + case .heading: 0.4 + case .code: nil + } + return adjustedForBoldText(font, source: source, defaultWeight: defaultWeight, traits: traits) + } + + /// A copy for when the Bold Text setting is `isOn`. With + /// `followsBoldText`, its system fonts are heavier when `isOn` is true. + /// `TranscriptTextView` applies it from the trait collection's + /// `legibilityWeight`. With a `DocumentLayout` of your own, lay out with + /// the copy, and lay out again when the setting changes. + public func withBoldText(_ isOn: Bool) -> TranscriptStyle { + var copy = self + copy.isBoldTextOn = isOn + return copy + } + + /// `font` as Bold Text sets it, when `usesBoldText` is on. + /// + /// - Parameters: + /// - source: the app's font that `font` was made from, or nil for a + /// default one. + /// - defaultWeight: the weight of the default system font, or nil if + /// the default is the fixed-pitch font. + func adjustedForBoldText(_ font: CTFont, source: TranscriptFont?, defaultWeight: CGFloat?, + traits: InlineSpan.Traits) -> CTFont { + guard usesBoldText else { return font } + if let source, source.name != nil { return font } + guard let declared = source?.weight ?? defaultWeight else { + if CTFontGetSymbolicTraits(font).contains(.traitBold) { return font } + return CTFontCreateCopyWithSymbolicTraits(font, 0, nil, .traitBold, .traitBold) ?? font + } + // From the weight asked for, not the weight measured: the system + // may already give a heavier font for Bold Text, and that font is + // then kept as it is. + let target = TranscriptFont.boldTextWeight(traits.contains(.bold) ? max(declared, 0.4) : declared) + guard Self.weight(of: font) < target - 0.01 else { return font } + var heavier = TranscriptFont(size: CTFontGetSize(font), weight: target, monospaced: source?.monospaced ?? false).makeFont() + if traits.contains(.italic), let styled = CTFontCreateCopyWithSymbolicTraits(heavier, 0, nil, .traitItalic, .traitItalic) { + heavier = styled + } + return heavier + } + + static func weight(of font: CTFont) -> CGFloat { + let traits = CTFontCopyTraits(font) as NSDictionary + return (traits[kCTFontWeightTrait] as? NSNumber).map { CGFloat($0.doubleValue) } ?? 0 } static let fontKey = NSAttributedString.Key(kCTFontAttributeName as String) @@ -486,7 +563,7 @@ final class ImageAttachment: @unchecked Sendable { (self.size, self.ascent) = Self.reservedSpace(for: math, font: font, maximumWidth: maximumWidth) } else { let size = CTFontGetSize(font) * 0.85 - let code = style.codeFont?.makeFont(size: size) ?? CTFontCreateUIFontForLanguage(.userFixedPitch, size, nil)! + let code = style.mathFallbackFont(size: size) let attributes: [NSAttributedString.Key: Any] = [ TranscriptStyle.fontKey: code, NSAttributedString.Key(kCTForegroundColorFromContextAttributeName as String): true, diff --git a/Sources/TranscriptKit/Model/TranscriptShapes.swift b/Sources/TranscriptKit/Model/TranscriptShapes.swift index fa5951b..0a10374 100644 --- a/Sources/TranscriptKit/Model/TranscriptShapes.swift +++ b/Sources/TranscriptKit/Model/TranscriptShapes.swift @@ -158,15 +158,15 @@ public struct TranscriptPath: @unchecked Sendable { return stroke == nil ? bounds : bounds.insetBy(dx: -lineWidth / 2, dy: -lineWidth / 2) } - func draw(in context: CGContext, dark: Bool) { + func draw(in context: CGContext, dark: Bool, highContrast: Bool) { if let fill { context.addPath(path) - context.setFillColor(fill.cgColor(dark: dark)) + context.setFillColor(fill.cgColor(dark: dark, highContrast: highContrast)) context.fillPath() } if let stroke { context.addPath(path) - context.setStrokeColor(stroke.cgColor(dark: dark)) + context.setStrokeColor(stroke.cgColor(dark: dark, highContrast: highContrast)) context.setLineWidth(lineWidth) context.setLineCap(lineCap) context.setLineJoin(lineJoin) diff --git a/Sources/TranscriptKit/Model/TranscriptTag.swift b/Sources/TranscriptKit/Model/TranscriptTag.swift index 0293481..589b61f 100644 --- a/Sources/TranscriptKit/Model/TranscriptTag.swift +++ b/Sources/TranscriptKit/Model/TranscriptTag.swift @@ -152,8 +152,9 @@ public struct TranscriptTagImage: Equatable, @unchecked Sendable { } /// A color for decorations, with a value for light and one for dark -/// appearance. Text is drawn off the main thread too, where dynamic UIKit -/// colors can't be resolved, so both values are kept. +/// appearance, and one for each when Increase Contrast is on. Text is drawn +/// off the main thread too, where dynamic UIKit colors can't be resolved, so +/// all four values are kept. public struct TranscriptColor: Hashable, Sendable { struct Components: Hashable, Sendable { var red: CGFloat @@ -164,41 +165,58 @@ public struct TranscriptColor: Hashable, Sendable { var light: Components var dark: Components + var highContrastLight: Components + var highContrastDark: Components - /// Extended sRGB components, the same in light and dark appearance. + /// Extended sRGB components, the same in every appearance. public init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 1) { - light = Components(red: red, green: green, blue: blue, alpha: alpha) - dark = light + self.init(all: Components(red: red, green: green, blue: blue, alpha: alpha)) } - public init(light: TranscriptColor, dark: TranscriptColor) { + /// The light value of `light` and the dark value of `dark`. With + /// Increase Contrast on, the light value of `highContrastLight` and the + /// dark value of `highContrastDark`; nil keeps the high-contrast values + /// of `light` and `dark`. + public init(light: TranscriptColor, dark: TranscriptColor, + highContrastLight: TranscriptColor? = nil, highContrastDark: TranscriptColor? = nil) { self.light = light.light self.dark = dark.dark + self.highContrastLight = highContrastLight?.light ?? light.highContrastLight + self.highContrastDark = highContrastDark?.dark ?? dark.highContrastDark } - /// The same color in light and dark appearance. Nil if it can't be - /// converted to sRGB (a pattern, say). + /// The same color in every appearance. Nil if it can't be converted to + /// sRGB (a pattern, say). public init?(_ color: CGColor) { guard let components = Self.components(of: color) else { return nil } + self.init(all: components) + } + + private init(all components: Components) { light = components dark = components + highContrastLight = components + highContrastDark = components } #if canImport(UIKit) && !os(watchOS) - /// A UIKit color, resolved for light and for dark appearance: dynamic - /// colors such as `.systemBlue` keep both of their values. + /// A UIKit color, resolved for light and for dark appearance, with + /// Increase Contrast off and on: dynamic colors such as `.systemBlue` + /// keep all four of their values. public init(_ color: UIColor) { - func resolved(_ style: UIUserInterfaceStyle) -> Components { - let cgColor = color.resolvedColor(with: UITraitCollection(userInterfaceStyle: style)).cgColor - return Self.components(of: cgColor) ?? Components(red: 0, green: 0, blue: 0, alpha: 1) + func resolved(_ style: UIUserInterfaceStyle, _ contrast: UIAccessibilityContrast) -> Components { + let traits = UITraitCollection(userInterfaceStyle: style).replacing(UITraitAccessibilityContrast.self, value: contrast) + return Self.components(of: color.resolvedColor(with: traits).cgColor) ?? Components(red: 0, green: 0, blue: 0, alpha: 1) } - light = resolved(.light) - dark = resolved(.dark) + light = resolved(.light, .normal) + dark = resolved(.dark, .normal) + highContrastLight = resolved(.light, .high) + highContrastDark = resolved(.dark, .high) } #endif - func cgColor(dark isDark: Bool) -> CGColor { - let value = isDark ? dark : light + func cgColor(dark isDark: Bool, highContrast: Bool) -> CGColor { + let value = highContrast ? (isDark ? highContrastDark : highContrastLight) : (isDark ? dark : light) return CGColor(colorSpace: Self.space, components: [value.red, value.green, value.blue, value.alpha]) ?? CGColor(red: value.red, green: value.green, blue: value.blue, alpha: value.alpha) } diff --git a/Sources/TranscriptKit/iOS/TranscriptTextView.swift b/Sources/TranscriptKit/iOS/TranscriptTextView.swift index 192965a..43e01cf 100644 --- a/Sources/TranscriptKit/iOS/TranscriptTextView.swift +++ b/Sources/TranscriptKit/iOS/TranscriptTextView.swift @@ -92,10 +92,24 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public var style = TranscriptStyle() { didSet { guard style != oldValue else { return } - relayoutNow() - updateTailStyle() - updateFadeDuration() + styleChanged() + } + } + + /// `style` as layout uses it, with the Bold Text setting of the trait + /// collection. + private var layoutStyle: TranscriptStyle { + style.withBoldText(traitCollection.legibilityWeight == .bold) + } + + private func styleChanged() { + emptyLayout = DocumentLayout(document: TranscriptDocument(), width: 1, style: layoutStyle) + if bounds.width == 0, unsizedWidth > 0 { + engine.layOutUntilPlaced(width: unsizedWidth, style: layoutStyle) } + relayoutNow() + updateTailStyle() + updateFadeDuration() } /// How long text takes to fade in as it streams in, or nil to show it at @@ -266,7 +280,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// What is on screen. Drawing, hit testing and every `UITextInput` /// answer come from this layout and its document. private var installed: DocumentLayout? - private lazy var emptyLayout = DocumentLayout(document: TranscriptDocument(), width: 1, style: style) + private lazy var emptyLayout = DocumentLayout(document: TranscriptDocument(), width: 1, style: layoutStyle) private var currentLayout: DocumentLayout { installed ?? emptyLayout } /// The document on screen, which can be a little behind `document`. private var shownDocument: TranscriptDocument { currentLayout.document } @@ -401,7 +415,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD linkTap.delegate = self addGestureRecognizer(linkTap) self.linkTap = linkTap - registerForTraitChanges([UITraitUserInterfaceStyle.self, UITraitDisplayScale.self]) { (view: TranscriptTextView, _) in + let colorTraits: [UITrait] = [UITraitUserInterfaceStyle.self, UITraitAccessibilityContrast.self, UITraitDisplayScale.self] + registerForTraitChanges(colorTraits) { (view: TranscriptTextView, _) in // The tiles take over everything, in the new colours; the tail // starts again, in them too, with the next append. Animations, // drawn in the old ones, end. @@ -411,6 +426,17 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD view.handTailToTiles() view.tiles.values.forEach { $0.setNeedsDisplay() } } + registerForTraitChanges([UITraitLegibilityWeight.self]) { (view: TranscriptTextView, previous: UITraitCollection) in + guard view.style.withBoldText(previous.legibilityWeight == .bold) != view.layoutStyle else { return } + view.styleChanged() + // Later: the trait can change during a SwiftUI update, which must + // not change SwiftUI state. + if view.bounds.width == 0, view.unsizedWidth > 0 { + DispatchQueue.main.async { [weak view] in + MainActor.assumeIsolated { view?.onHeightChangeWhileUnsized?() } + } + } + } } // MARK: Links @@ -668,17 +694,21 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } let colors = resolvedColors() currentLayout.draw(in: context, dirtyRect: rect, text: colors.text, codeBackground: colors.codeBackground, accent: colors.accent, - dark: colors.dark, hiding: hiding) + dark: colors.dark, highContrast: colors.highContrast, hiding: hiding) } private func resolvedColors() -> TailRenderer.Colors { let dark = traitCollection.userInterfaceStyle == .dark + let highContrast = traitCollection.accessibilityContrast == .high return TailRenderer.Colors( - text: style.textColor?.cgColor(dark: dark) ?? UIColor.label.resolvedColor(with: traitCollection).cgColor, - codeBackground: style.codeBackgroundColor?.cgColor(dark: dark) + text: style.textColor?.cgColor(dark: dark, highContrast: highContrast) + ?? UIColor.label.resolvedColor(with: traitCollection).cgColor, + codeBackground: style.codeBackgroundColor?.cgColor(dark: dark, highContrast: highContrast) ?? UIColor.secondarySystemFill.resolvedColor(with: traitCollection).cgColor, - accent: style.accentColor?.cgColor(dark: dark) ?? UIColor.tertiaryLabel.resolvedColor(with: traitCollection).cgColor, - dark: dark + accent: style.accentColor?.cgColor(dark: dark, highContrast: highContrast) + ?? UIColor.tertiaryLabel.resolvedColor(with: traitCollection).cgColor, + dark: dark, + highContrast: highContrast ) } @@ -774,14 +804,14 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD } } if bounds.width == 0, unsizedWidth > 0, output.source == source, output.layout.width == unsizedWidth, - output.layout.style == style { + output.layout.style == layoutStyle { // Not placed yet: nothing to show, but SwiftUI must hear that the height changed. engine.settleAnimations(output.started + output.waiting) if ceil(output.layout.height) != unsizedHeight { onHeightChangeWhileUnsized?() } return } - guard output.source == source, output.layout.width == bounds.width, output.layout.style == style else { - if output.source < source, output.layout.width == bounds.width, output.layout.style == style { + guard output.source == source, output.layout.width == bounds.width, output.layout.style == layoutStyle else { + if output.source < source, output.layout.width == bounds.width, output.layout.style == layoutStyle { // From the source just replaced: kept in case the next // layout, from the new one, builds on it. skippedOutput = output @@ -811,7 +841,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD /// block's colors. private func relayoutNow(keepingFades: Bool = false) { guard bounds.width > 0, - let result = engine.relayout(width: bounds.width, style: style, keepingFades: keepingFades) else { return } + let result = engine.relayout(width: bounds.width, style: layoutStyle, keepingFades: keepingFades) else { return } skippedOutput = nil guard result.source == source else { return } install(result.layout, changedTop: nil, tail: nil, keptFadingFrom: result.fadingFrom, isFinished: result.isFinished) @@ -1136,7 +1166,8 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD let colors = resolvedColors() let scale = traitCollection.displayScale let sprites = TagAnimationPlayer.sprites(for: tag, animation: animation, - appearance: .init(text: colors.text, dark: colors.dark, scale: scale)) + appearance: .init(text: colors.text, dark: colors.dark, + highContrast: colors.highContrast, scale: scale)) let start = CACurrentMediaTime() // No transaction of its own: the layers go to the screen in the same // commit as the tiles and the tail that stop drawing the tag. (An @@ -1230,7 +1261,7 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD animationLayer.frame = canvas.bounds fadeLayer.frame = canvas.bounds if bounds.width > 0 { unsizedWidth = 0 } - if bounds.width > 0, installed?.width != bounds.width { + if bounds.width > 0, installed?.width != bounds.width || installed?.style != layoutStyle { relayoutNow() refreshSelectionDisplay() } @@ -1249,15 +1280,15 @@ public final class TranscriptTextView: UIView, UITextInput, UIGestureRecognizerD public override func sizeThatFits(_ size: CGSize) -> CGSize { let width = size.width.isFinite && size.width > 0 ? size.width : max(bounds.width, 1) - if let installed, installed.width == width { + if let installed, installed.width == width, installed.style == layoutStyle { return CGSize(width: width, height: ceil(installed.height)) } // Kept by the engine, so the relayout when the view takes this width is free. - let height = ceil(engine.measure(width: width, style: style)) + let height = ceil(engine.measure(width: width, style: layoutStyle)) if bounds.width == 0, onHeightChangeWhileUnsized != nil, size.width.isFinite, size.width > 0 { unsizedWidth = width unsizedHeight = height - engine.layOutUntilPlaced(width: width, style: style) + engine.layOutUntilPlaced(width: width, style: layoutStyle) } return CGSize(width: width, height: height) } diff --git a/Tests/TranscriptKitTests/CustomTagTests.swift b/Tests/TranscriptKitTests/CustomTagTests.swift index 10a5023..4398533 100644 --- a/Tests/TranscriptKitTests/CustomTagTests.swift +++ b/Tests/TranscriptKitTests/CustomTagTests.swift @@ -208,7 +208,7 @@ private func layout(_ markdown: String, width: CGFloat = 320) -> DocumentLayout private let textColor = CGColor(gray: 0, alpha: 1) /// `layout` drawn on white, as RGBA bytes. -private func render(_ layout: DocumentLayout, dark: Bool, scale: CGFloat = 2) -> (bytes: [UInt8], width: Int) { +private func render(_ layout: DocumentLayout, dark: Bool, highContrast: Bool = false, scale: CGFloat = 2) -> (bytes: [UInt8], width: Int) { let width = Int((layout.width * scale).rounded()) let height = Int((max(layout.height, 1) * scale).rounded()) let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, @@ -220,7 +220,7 @@ private func render(_ layout: DocumentLayout, dark: Bool, scale: CGFloat = 2) -> context.scaleBy(x: scale, y: -scale) let all = CGRect(x: 0, y: 0, width: layout.width, height: layout.height) layout.draw(in: context, dirtyRect: all, text: textColor, codeBackground: CGColor(gray: 0.9, alpha: 1), - accent: CGColor(gray: 0.6, alpha: 1), dark: dark) + accent: CGColor(gray: 0.6, alpha: 1), dark: dark, highContrast: highContrast) return (Array(UnsafeRawBufferPointer(start: context.data!, count: width * height * 4)), width) } @@ -256,6 +256,23 @@ private func count(_ bytes: [UInt8], near color: (UInt8, UInt8, UInt8)) -> Int { #expect(count(light, near: (0, 0, 0)) > 100) } +@Test func highlightsAreDrawnInTheirIncreaseContrastColors() { + let green = TranscriptColor(red: 0, green: 1, blue: 0) + let color = TranscriptColor(light: yellow, dark: blue, highContrastLight: red, highContrastDark: green) + var parser = MarkdownStreamParser(tags: [TranscriptTag("mark", TranscriptDecoration(background: color))]) + parser.append("Some highlighted words here.") + let marked = DocumentLayout(document: parser.document, width: 320, style: TranscriptStyle()) + let normal = render(marked, dark: false).bytes + let light = render(marked, dark: false, highContrast: true).bytes + let dark = render(marked, dark: true, highContrast: true).bytes + #expect(count(normal, near: (255, 255, 0)) > 500) + #expect(count(normal, near: (255, 0, 0)) == 0) + #expect(count(light, near: (255, 0, 0)) > 500) + #expect(count(light, near: (255, 255, 0)) == 0) + #expect(count(dark, near: (0, 255, 0)) > 500) + #expect(count(dark, near: (0, 0, 255)) == 0) +} + /// Text parsed again with another look for a tag (the way to re-theme it) /// is drawn in the new look, also where the layout reuses earlier lines. @Test func reparsingWithNewDecorationsRedrawsReusedLines() { diff --git a/Tests/TranscriptKitTests/FadeTests.swift b/Tests/TranscriptKitTests/FadeTests.swift index 2a8b437..77dc2bf 100644 --- a/Tests/TranscriptKitTests/FadeTests.swift +++ b/Tests/TranscriptKitTests/FadeTests.swift @@ -116,7 +116,7 @@ private func documentDifference(_ output: LayoutEngine.Output, scale: CGFloat) - context.translateBy(x: margin, y: -top) context.clip(to: band) layout.draw(in: context, dirtyRect: band, text: colors.text, codeBackground: colors.codeBackground, accent: colors.accent, - dark: false, hiding: hiding) + dark: false, highContrast: false, hiding: hiding) context.restoreGState() return context } diff --git a/Tests/TranscriptKitTests/StreamTests.swift b/Tests/TranscriptKitTests/StreamTests.swift index 3dd3a0f..23bdc80 100644 --- a/Tests/TranscriptKitTests/StreamTests.swift +++ b/Tests/TranscriptKitTests/StreamTests.swift @@ -208,6 +208,27 @@ private final class Recorder: @unchecked Sendable { #expect(result.layout.reusedBlockCount == 1) } +@Test func aNewStyleReachesTheEngineBeforeTheViewIsPlaced() throws { + let engine = LayoutEngine() + let style = TranscriptStyle() + let boldText = style.withBoldText(true) + engine.layOutUntilPlaced(width: 120, style: style) + engine.layOutUntilPlaced(width: 120, style: boldText) + engine.submit(.init(document: MarkdownStreamParser.document(from: "Some text that wraps at narrow widths."), source: 1, sequence: 1)) + engine.drainNow() + let output = try #require(engine.takeOutput()) + #expect(output.layout.width == 120) + #expect(output.layout.style == boldText) + + // Another width waits for the view to be placed. + engine.layOutUntilPlaced(width: 200, style: style) + engine.submit(.init(document: MarkdownStreamParser.document(from: "More text."), source: 1, sequence: 2)) + engine.drainNow() + let next = try #require(engine.takeOutput()) + #expect(next.layout.width == 120) + #expect(next.layout.style == boldText) +} + /// Blocks without their ids, which depend on the parser instance. private func content(_ document: TranscriptDocument) -> [String] { document.blocks.map { "\($0.kind)|\($0.text)|\($0.spans)" } diff --git a/Tests/TranscriptKitTests/StyleColorTests.swift b/Tests/TranscriptKitTests/StyleColorTests.swift index 71d7cd4..bc262a4 100644 --- a/Tests/TranscriptKitTests/StyleColorTests.swift +++ b/Tests/TranscriptKitTests/StyleColorTests.swift @@ -1,3 +1,4 @@ +import CoreGraphics import Foundation import Testing @testable import TranscriptKit @@ -25,3 +26,40 @@ import Testing let color = text.attribute(TranscriptStyle.foregroundKey, at: 0, effectiveRange: nil) as? TranscriptColor #expect(color == TranscriptColor(red: 0, green: 0, blue: 1)) } + +private func components(_ color: CGColor) -> [CGFloat] { + (color.components ?? []).map { ($0 * 1000).rounded() / 1000 } +} + +@Test func aColorKeepsAValueForEachAppearanceAndContrast() { + let red = TranscriptColor(red: 1, green: 0, blue: 0) + let green = TranscriptColor(red: 0, green: 1, blue: 0) + let blue = TranscriptColor(red: 0, green: 0, blue: 1) + let white = TranscriptColor(red: 1, green: 1, blue: 1) + for dark in [false, true] { + for highContrast in [false, true] { + #expect(components(red.cgColor(dark: dark, highContrast: highContrast)) == [1, 0, 0, 1]) + } + } + let color = TranscriptColor(light: red, dark: green, highContrastLight: blue, highContrastDark: white) + #expect(components(color.cgColor(dark: false, highContrast: false)) == [1, 0, 0, 1]) + #expect(components(color.cgColor(dark: true, highContrast: false)) == [0, 1, 0, 1]) + #expect(components(color.cgColor(dark: false, highContrast: true)) == [0, 0, 1, 1]) + #expect(components(color.cgColor(dark: true, highContrast: true)) == [1, 1, 1, 1]) +} + +@Test func aColorMadeOfTwoKeepsTheirIncreaseContrastValues() { + let red = TranscriptColor(red: 1, green: 0, blue: 0) + let green = TranscriptColor(red: 0, green: 1, blue: 0) + let blue = TranscriptColor(red: 0, green: 0, blue: 1) + let white = TranscriptColor(red: 1, green: 1, blue: 1) + let first = TranscriptColor(light: red, dark: red, highContrastLight: blue, highContrastDark: blue) + let second = TranscriptColor(light: green, dark: green, highContrastLight: white, highContrastDark: white) + let both = TranscriptColor(light: first, dark: second) + #expect(components(both.cgColor(dark: false, highContrast: false)) == [1, 0, 0, 1]) + #expect(components(both.cgColor(dark: false, highContrast: true)) == [0, 0, 1, 1]) + #expect(components(both.cgColor(dark: true, highContrast: false)) == [0, 1, 0, 1]) + #expect(components(both.cgColor(dark: true, highContrast: true)) == [1, 1, 1, 1]) + #expect(both != TranscriptColor(light: red, dark: green)) + #expect(TranscriptColor(light: red, dark: green) == TranscriptColor(light: red, dark: green, highContrastLight: red, highContrastDark: green)) +} diff --git a/Tests/TranscriptKitTests/StyleFontTests.swift b/Tests/TranscriptKitTests/StyleFontTests.swift index 36fdf14..231a4c8 100644 --- a/Tests/TranscriptKitTests/StyleFontTests.swift +++ b/Tests/TranscriptKitTests/StyleFontTests.swift @@ -80,3 +80,116 @@ private func weight(_ font: CTFont) -> CGFloat { let lines = DocumentLayout(document: document, width: 200, style: tight).entry(at: 0).layout.lines #expect(lines[0].frame.height > 15) } + +@Test func boldTextMakesEachSystemWeightHeavier() { + let expected: [(CGFloat, CGFloat)] = [ + (-0.8, -0.4), (-0.6, 0), (-0.4, 0.23), (0, 0.3), (0.23, 0.4), + (0.3, 0.4), (0.4, 0.56), (0.56, 0.62), (0.62, 0.62), (0.7, 0.7), + ] + for (weight, heavier) in expected { + #expect(TranscriptFont.boldTextWeight(weight) == heavier) + } +} + +private func boldTextStyle(_ configure: (inout TranscriptStyle) -> Void = { _ in }) -> (off: TranscriptStyle, on: TranscriptStyle) { + var off = TranscriptStyle() + configure(&off) + var on = off + on.isBoldTextOn = true + return (off, on) +} + +@Test func boldTextMakesTheDefaultFontsHeavier() { + let styles = boldTextStyle() + #expect(styles.off != styles.on) + let body = weight(styles.on.font(for: .paragraph)) + #expect(abs(body - 0.3) < 0.05) + #expect(weight(styles.off.font(for: .paragraph)) < 0.05) + #expect(weight(styles.on.font(for: .heading(level: 1))) > weight(styles.off.font(for: .heading(level: 1))) + 0.1) + #expect(CTFontGetSize(styles.on.font(for: .heading(level: 1))) == CTFontGetSize(styles.off.font(for: .heading(level: 1)))) + let code = styles.on.font(for: .code(language: nil)) + #expect(CTFontGetSymbolicTraits(code).contains(.traitBold)) + #expect(!CTFontGetSymbolicTraits(styles.off.font(for: .code(language: nil))).contains(.traitBold)) + #expect(CTFontGetSymbolicTraits(styles.on.font(for: .paragraph, traits: .code)).contains(.traitBold)) +} + +@Test func boldTextKeepsBoldSpansHeavierThanTheText() { + let styles = boldTextStyle() + let body = weight(styles.on.font(for: .paragraph)) + let bold = weight(styles.on.font(for: .paragraph, traits: .bold)) + #expect(bold > body + 0.15) + #expect(bold > weight(styles.off.font(for: .paragraph, traits: .bold))) + let italic = styles.on.font(for: .paragraph, traits: [.bold, .italic]) + #expect(CTFontGetSymbolicTraits(italic).contains(.traitItalic)) + #expect(abs(weight(italic) - bold) < 0.05) +} + +@Test func boldTextUsesTheWeightOfTheAppsSystemFont() { + let styles = boldTextStyle { $0.bodyFont = TranscriptFont(size: 20, weight: 0.23, monospaced: true) } + let font = styles.on.font(for: .paragraph) + #expect(abs(weight(font) - 0.4) < 0.05) + #expect(CTFontGetSize(font) == 20) + #expect(CTFontGetSymbolicTraits(font).contains(.traitMonoSpace)) +} + +@Test func boldTextLeavesANamedFontAsItIs() { + let styles = boldTextStyle { + $0.bodyFont = TranscriptFont(name: "Courier", size: 20) + $0.codeFont = TranscriptFont(name: "Menlo-Regular", size: 14) + } + #expect(postScriptName(styles.on.font(for: .paragraph)) == "Courier") + #expect(postScriptName(styles.on.font(for: .code(language: nil))) == "Menlo-Regular") + #expect(postScriptName(styles.on.font(for: .paragraph, traits: .code)) == "Menlo-Regular") +} + +@Test func boldTextIsFollowedUnlessTheStyleTurnsItOff() { + var style = TranscriptStyle() + #expect(!style.usesBoldText) + #expect(style.withBoldText(true).usesBoldText) + #expect(!style.withBoldText(false).usesBoldText) + #expect(style.withBoldText(false) == style) + style.followsBoldText = false + #expect(!style.withBoldText(true).usesBoldText) + #expect(style.withBoldText(true) != style) + let on = style.withBoldText(true).font(for: .paragraph, traits: .bold) + let off = style.font(for: .paragraph, traits: .bold) + #expect(postScriptName(on) == postScriptName(off)) + #expect(weight(on) == weight(off)) +} + +@Test func boldTextKeepsAFontThatIsAlreadyHeavyEnough() { + var style = TranscriptStyle() + style.isBoldTextOn = true + let source = TranscriptFont(size: 17) + let semibold = TranscriptFont(size: 17, weight: 0.3).makeFont() + #expect(style.adjustedForBoldText(semibold, source: source, defaultWeight: 0, traits: []) === semibold) + let regular = source.makeFont() + #expect(abs(weight(style.adjustedForBoldText(regular, source: source, defaultWeight: 0, traits: [])) - 0.3) < 0.05) + let heavy = TranscriptFont(size: 17, weight: 0.56).makeFont() + #expect(style.adjustedForBoldText(heavy, source: nil, defaultWeight: 0, traits: .bold) === heavy) +} + +@Test func theFallbackFontOfAFormulaIsCachedAndFollowsBoldText() { + let styles = boldTextStyle() + #expect(styles.on.mathFallbackFont(size: 14) === styles.on.mathFallbackFont(size: 14)) + #expect(CTFontGetSymbolicTraits(styles.on.mathFallbackFont(size: 14)).contains(.traitBold)) + #expect(!CTFontGetSymbolicTraits(styles.off.mathFallbackFont(size: 14)).contains(.traitBold)) + #expect(CTFontGetSize(styles.on.mathFallbackFont(size: 12)) == 12) +} + +@Test func boldTextKeepsBoldCodeHeavierInASystemCodeFont() { + let styles = boldTextStyle { $0.codeFont = TranscriptFont(size: 15, monospaced: true) } + let code = styles.on.font(for: .code(language: nil)) + let bold = styles.on.font(for: .code(language: nil), traits: .bold) + #expect(weight(bold) > weight(code) + 0.15) + #expect(weight(styles.on.font(for: .paragraph, traits: [.bold, .code])) > weight(styles.on.font(for: .paragraph, traits: .code)) + 0.15) +} + +@Test func boldTextStartsFromTheWeightOfListNumbersAndTableHeaders() { + let styles = boldTextStyle() + #expect(abs(weight(styles.on.font(for: .paragraph, weight: 0.4)) - 0.56) < 0.05) + #expect(abs(weight(styles.on.font(for: .paragraph, weight: 0.23)) - 0.4) < 0.05) + #expect(abs(weight(styles.off.font(for: .paragraph, weight: 0.4)) - 0.4) < 0.05) + let named = boldTextStyle { $0.bodyFont = TranscriptFont(name: "Courier", size: 20) } + #expect(postScriptName(named.on.font(for: .paragraph, weight: 0.4)) == postScriptName(named.off.font(for: .paragraph, weight: 0.4))) +} diff --git a/Tests/TranscriptKitTests/TagAnimationTests.swift b/Tests/TranscriptKitTests/TagAnimationTests.swift index 9523a02..f884ae1 100644 --- a/Tests/TranscriptKitTests/TagAnimationTests.swift +++ b/Tests/TranscriptKitTests/TagAnimationTests.swift @@ -194,7 +194,7 @@ private func render(_ layout: DocumentLayout, hiding: TagHiding = .none, sprites context.setFillColor(CGColor(gray: 1, alpha: 1)) context.fill(all) layout.draw(in: context, dirtyRect: all, text: colors.text, codeBackground: colors.codeBackground, accent: colors.accent, - dark: false, hiding: hiding) + dark: false, highContrast: false, hiding: hiding) // Sprites at rest, as their layers show them: upright, at their frames. for sprite in sprites { context.saveGState() @@ -298,7 +298,7 @@ func spritesAtRestRedrawTheTagExactly(scale: CGFloat) throws { context.translateBy(x: TailRenderer.sideMargin, y: -tail.top) final.draw(in: context, dirtyRect: CGRect(x: -TailRenderer.sideMargin, y: tail.top, width: final.width + 2 * TailRenderer.sideMargin, height: TailRenderer.height), - text: colors.text, codeBackground: colors.codeBackground, accent: colors.accent, dark: false, hiding: TagHiding(playing: [key])) + text: colors.text, codeBackground: colors.codeBackground, accent: colors.accent, dark: false, highContrast: false, hiding: TagHiding(playing: [key])) let expected = Array(UnsafeRawBufferPointer(start: context.data!, count: width * height * 4)) #expect(zip(pixels, expected).allSatisfy { abs(Int($0) - Int($1)) <= 2 }) }