import SwiftUI import XCTest @testable import OldFella @MainActor final class NavigationTitleFontTests: XCTestCase { func testTitleKeepsSelectedFontDuringDataUpdates() async throws { AppFont.registerBundledFonts() for style in [UIUserInterfaceStyle.light, .dark] { var renderedFonts = Set() for font in AppFont.allCases { let fixture = try await TitleFixture(font: font, style: style) defer { fixture.close() } let firstTitle = try fixture.titleImage() XCTAssertTrue(renderedFonts.insert(firstTitle).inserted, "Each font must render a different title.") let attachment = XCTAttachment(image: fixture.image()) attachment.name = "First layout \(font.title) \(style == .dark ? "dark" : "light")" attachment.lifetime = .keepAlways add(attachment) for refresh in 1...4 { let before = fixture.image().pngData() fixture.data.rows = Array((refresh * 20)..<(refresh * 20 + 20)) for frame in 0..<6 { XCTAssertEqual( try fixture.titleImage(), firstTitle, "\(font.title), \(style), refresh \(refresh), frame \(frame)") try await Task.sleep(for: .milliseconds(16)) } if refresh == 1 { let refreshed = XCTAttachment(image: fixture.image()) refreshed.name = "Refreshed \(font.title) \(style.rawValue)" refreshed.lifetime = .keepAlways add(refreshed) } XCTAssertNotEqual(fixture.image().pngData(), before, "The list must display the new rows.") } } } } func testFontChangesRestoreSystemTitle() async throws { AppFont.registerBundledFonts() let fixture = try await TitleFixture(font: .system, style: .light) defer { fixture.close() } let systemTitle = try fixture.titleImage() let initial = XCTAttachment(image: fixture.image()) initial.name = "Initial system title" initial.lifetime = .keepAlways add(initial) for font in [AppFont.atkinson, .iosevka, .paperMono, .system] { fixture.defaults.set(font.rawValue, forKey: "appFont") try await Task.sleep(for: .milliseconds(32)) let title = try fixture.titleImage() let attachment = XCTAttachment(image: fixture.image()) attachment.name = "Changed to \(font.title)" attachment.lifetime = .keepAlways add(attachment) if font == .system { // Native layout can shift glyphs by part of a point after a font change. XCTAssertLessThan(try titleDifference(title, systemTitle), 0.02) } else { XCTAssertGreaterThan(try titleDifference(title, systemTitle), 0.02) } for _ in 0..<4 { XCTAssertEqual(try fixture.titleImage(), title) try await Task.sleep(for: .milliseconds(16)) } } } func testTitleRespondsToDynamicType() async throws { AppFont.registerBundledFonts() for font in AppFont.allCases { let normal = try await TitleFixture(font: font, style: .light) let normalTitle = try normal.titleImage() normal.close() let enlarged = try await TitleFixture(font: font, style: .light, size: .accessibility3) defer { enlarged.close() } XCTAssertNotEqual(try enlarged.titleImage(), normalTitle, font.title) let attachment = XCTAttachment(image: enlarged.image()) attachment.name = "Large text \(font.title)" attachment.lifetime = .keepAlways add(attachment) } } private func titleDifference(_ first: Data, _ second: Data) throws -> Double { func pixels(_ data: Data) throws -> [UInt8] { let image = try XCTUnwrap(UIImage(data: data)?.cgImage) var result = [UInt8](repeating: 0, count: image.width * image.height) try result.withUnsafeMutableBytes { bytes in let context = try XCTUnwrap( CGContext( data: bytes.baseAddress, width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: image.width, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue)) context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) } return result } let firstPixels = try pixels(first) let secondPixels = try pixels(second) guard firstPixels.count == secondPixels.count else { return 1 } let difference = zip(firstPixels, secondPixels).reduce(0) { $0 + abs(Int($1.0) - Int($1.1)) } return Double(difference) / Double(firstPixels.count * 255) } } @MainActor @Observable private final class TitleData { var rows = Array(0..<20) } private struct RefreshingTitleView: View { let data: TitleData var body: some View { NavigationStack { List(data.rows, id: \.self) { index in Text("Row \(index)") } .listStyle(.plain) .appNavigationTitle("Following") } } } @MainActor private final class TitleFixture { let data = TitleData() let defaults: UserDefaults private let suite = "NavigationTitleFontTests.\(UUID().uuidString)" private let window: UIWindow init(font: AppFont, style: UIUserInterfaceStyle, size: DynamicTypeSize = .large) async throws { defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) defaults.set(font.rawValue, forKey: "appFont") let host = UIHostingController( rootView: RefreshingTitleView(data: data) .defaultAppStorage(defaults) .environment(\.dynamicTypeSize, size)) let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.first as? UIWindowScene) window = UIWindow(windowScene: scene) window.frame = CGRect(x: 0, y: 0, width: 402, height: 874) window.overrideUserInterfaceStyle = style window.rootViewController = host window.makeKeyAndVisible() window.layoutIfNeeded() for _ in 0..<3 { try await Task.sleep(for: .milliseconds(16)) window.layoutIfNeeded() } } func close() { window.isHidden = true defaults.removePersistentDomain(forName: suite) } func image() -> UIImage { window.layoutIfNeeded() let format = UIGraphicsImageRendererFormat() format.scale = 1 return UIGraphicsImageRenderer(bounds: window.bounds, format: format).image { context in window.layer.render(in: context.cgContext) } } func titleImage() throws -> Data { let bar = try XCTUnwrap(navigationBar(in: window)) let barFrame = bar.convert(bar.bounds, to: window) let bounds = CGRect( x: barFrame.midX - 60, y: barFrame.minY + 1, width: 120, height: barFrame.height - 2).integral let crop = try XCTUnwrap(image().cgImage?.cropping(to: bounds)) return try XCTUnwrap(UIImage(cgImage: crop).pngData()) } private func navigationBar(in view: UIView) -> UINavigationBar? { if let bar = view as? UINavigationBar { return bar } return view.subviews.lazy.compactMap { self.navigationBar(in: $0) }.first } }