Skip to content

Commit

Permalink
changes (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
NicoHinderling authored Aug 5, 2024
1 parent 1e011cc commit fe3803b
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 4 deletions.
35 changes: 35 additions & 0 deletions Sources/SnapshotPreviewsCore/Orientation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#if canImport(UIKit) && !os(watchOS) && !os(visionOS) && !os(tvOS)
import Foundation
import UIKit
import SwiftUI

extension UIInterfaceOrientation {
func toInterfaceOrientationMask() -> UIInterfaceOrientationMask {
switch self {
case .portraitUpsideDown:
return .portraitUpsideDown
case .landscapeLeft:
return .landscapeLeft
case .landscapeRight:
return .landscapeRight
default:
return .portrait
}
}
}

extension InterfaceOrientation {
func toInterfaceOrientation() -> UIInterfaceOrientation {
switch self {
case .portraitUpsideDown:
return .portraitUpsideDown
case .landscapeLeft:
return .landscapeLeft
case .landscapeRight:
return .landscapeRight
default:
return .portrait
}
}
}
#endif
43 changes: 39 additions & 4 deletions Sources/SnapshotPreviewsCore/UIKitRenderingStrategy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,51 @@ public class UIKitRenderingStrategy: RenderingStrategy {
self.window = window
}

public var windowScene: UIWindowScene? {
private var windowScene: UIWindowScene? {
window.windowScene
}

private let window: UIWindow

@MainActor public func render(
@MainActor
public func render(
preview: SnapshotPreviewsCore.Preview,
completion: @escaping (SnapshotResult) -> Void)
{
completion: @escaping (SnapshotResult) -> Void
) {
let previewOrientation = preview.orientation.toInterfaceOrientation()
if windowScene!.interfaceOrientation != previewOrientation {
var rotationError: (any Error)? = nil
if #available(iOS 16.0, *) {
windowScene!.requestGeometryUpdate(.iOS(interfaceOrientations: previewOrientation.toInterfaceOrientationMask())) { error in
NSLog("Rotation error handler: \(error) \(self.windowScene!.interfaceOrientation)")
rotationError = error
}
}

// Wait for rotation to complete or timeout
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
if let error = rotationError {
let result = SnapshotResult(
image: .failure(error),
precision: nil,
accessibilityEnabled: nil,
accessibilityMarkers: nil,
colorScheme: nil
)
completion(result)
} else {
self?.performRender(preview: preview, completion: completion)
}
}
} else {
performRender(preview: preview, completion: completion)
}
}

@MainActor private func performRender(
preview: SnapshotPreviewsCore.Preview,
completion: @escaping (SnapshotResult) -> Void
) {
UIView.setAnimationsEnabled(false)
let view = preview.view()
let controller = view.makeExpandingView(layout: preview.layout, window: window)
Expand Down

0 comments on commit fe3803b

Please sign in to comment.