From 444a47327c0a41fe009bc1d0c6005c7b4ff7e9b5 Mon Sep 17 00:00:00 2001 From: Shadowfacts Date: Sun, 21 Jul 2024 19:38:18 -0700 Subject: [PATCH] Fix AttributedStringConverter producing non-Dynamic Type fonts --- Sources/HTMLStreamer/AttributedStringConverter.swift | 10 +++++++++- .../AttributedStringConverterTests.swift | 10 ++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/Sources/HTMLStreamer/AttributedStringConverter.swift b/Sources/HTMLStreamer/AttributedStringConverter.swift index 393e6d0..f58da8d 100644 --- a/Sources/HTMLStreamer/AttributedStringConverter.swift +++ b/Sources/HTMLStreamer/AttributedStringConverter.swift @@ -357,8 +357,14 @@ public class AttributedStringConverter { descriptor = italic } let font = PlatformFont(descriptor: descriptor, size: 0) + #if os(iOS) || os(visionOS) + let scaled = configuration.fontMetrics.scaledFont(for: font) + fontCache[traits] = scaled + return scaled + #else fontCache[traits] = font return font + #endif } } @@ -366,6 +372,7 @@ public struct AttributedStringConverterConfiguration { #if os(iOS) || os(visionOS) public var font: UIFont public var monospaceFont: UIFont + public var fontMetrics: UIFontMetrics public var color: UIColor #elseif os(macOS) public var font: NSFont @@ -375,9 +382,10 @@ public struct AttributedStringConverterConfiguration { public var paragraphStyle: NSParagraphStyle #if os(iOS) || os(visionOS) - public init(font: UIFont, monospaceFont: UIFont, color: UIColor, paragraphStyle: NSParagraphStyle) { + public init(font: UIFont, monospaceFont: UIFont, fontMetrics: UIFontMetrics, color: UIColor, paragraphStyle: NSParagraphStyle) { self.font = font self.monospaceFont = monospaceFont + self.fontMetrics = fontMetrics self.color = color self.paragraphStyle = paragraphStyle } diff --git a/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift b/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift index 87f1856..8ebb723 100644 --- a/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift +++ b/Tests/HTMLStreamerTests/AttributedStringConverterTests.swift @@ -44,12 +44,22 @@ final class AttributedStringConverterTests: XCTestCase { } private func convert(_ html: String, callbacks _: Callbacks.Type = Callbacks.self) -> NSAttributedString { + #if os(iOS) || os(visionOS) + let config = AttributedStringConverterConfiguration( + font: font, + monospaceFont: monospaceFont, + fontMetrics: .default, + color: color, + paragraphStyle: .default + ) + #else let config = AttributedStringConverterConfiguration( font: font, monospaceFont: monospaceFont, color: color, paragraphStyle: .default ) + #endif let converter = AttributedStringConverter(configuration: config) return converter.convert(html: html) }