From 256091f1b07bf384d1a68bbd71331c8f2310801f Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 28 Nov 2026 20:49:26 +0800 Subject: [PATCH 1/3] fix(hosting): propagate environment traits to nested UIKit views Fixes #1270 --- .../COpenSwiftUI/Shims/UIKit/UIKit_Private.h | 1 + .../Platform/PlatformViewHost.swift | 11 +++ ...mViewRepresentableCompatibilityTests.swift | 69 +++++++++++++++++++ 3 files changed, 81 insertions(+) create mode 100644 Tests/OpenSwiftUICompatibilityTests/Integration/Representable/PlatformViewRepresentableCompatibilityTests.swift diff --git a/Sources/COpenSwiftUI/Shims/UIKit/UIKit_Private.h b/Sources/COpenSwiftUI/Shims/UIKit/UIKit_Private.h index 92d5aad99..91e6a202b 100644 --- a/Sources/COpenSwiftUI/Shims/UIKit/UIKit_Private.h +++ b/Sources/COpenSwiftUI/Shims/UIKit/UIKit_Private.h @@ -55,6 +55,7 @@ OPENSWIFTUI_ASSUME_NONNULL_BEGIN @end @interface UIView (OpenSwiftUI_SPI) +- (UITraitCollection *)_traitCollectionForChildEnvironment:(id)childEnvironment OPENSWIFTUI_SWIFT_NAME(_traitCollection(forChildEnvironment:)); - (void)_noteTraitsDidChangeRecursively_openswiftui_safe_wrapper OPENSWIFTUI_SWIFT_NAME(_noteTraitsDidChangeRecursively()); @property(nonatomic, readonly, nullable) UIResponder *firstResponder_openswiftui_safe_wrapper OPENSWIFTUI_SWIFT_NAME(firstResponder); - (nullable id)_largeContentViewerItemAtPoint:(CGPoint)point OPENSWIFTUI_SWIFT_NAME(_largeContentViewerItem(at:)); diff --git a/Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewHost.swift b/Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewHost.swift index 721fe5149..d26cfadb8 100644 --- a/Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewHost.swift +++ b/Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewHost.swift @@ -286,6 +286,17 @@ where Content: PlatformViewRepresentable { } #if os(iOS) || os(visionOS) + override func _traitCollection(forChildEnvironment childEnvironment: UITraitEnvironment) -> UITraitCollection { + if Content.isViewController, host?.as(UIViewControllerProvider.self)?.uiViewController != nil { + return super._traitCollection(forChildEnvironment: childEnvironment) + } + return traitCollection.byOverriding( + with: environment, + viewPhase: viewPhase, + focusedValues: focusedValues + ) + } + override func didAddSubview(_ subview: PlatformView) { super.didAddSubview(subview) guard let viewController = representedViewProvider as? PlatformViewController else { diff --git a/Tests/OpenSwiftUICompatibilityTests/Integration/Representable/PlatformViewRepresentableCompatibilityTests.swift b/Tests/OpenSwiftUICompatibilityTests/Integration/Representable/PlatformViewRepresentableCompatibilityTests.swift new file mode 100644 index 000000000..f345f100f --- /dev/null +++ b/Tests/OpenSwiftUICompatibilityTests/Integration/Representable/PlatformViewRepresentableCompatibilityTests.swift @@ -0,0 +1,69 @@ +// +// PlatformViewRepresentableCompatibilityTests.swift +// OpenSwiftUICompatibilityTests + +#if os(iOS) || os(macOS) || os(visionOS) +import OpenSwiftUITestsSupport +import Testing +#if os(iOS) || os(visionOS) +import UIKit +#else +import AppKit +#endif + +@MainActor +struct PlatformViewRepresentableCompatibilityTests { + @Test + func nestedHostingViewInheritsFontChanges() { + var inheritedFont: Font? + #if os(macOS) + _ = NSApplication.shared + #endif + let child = PlatformHostingController(rootView: FontReader { inheritedFont = $0 }) + let content = RepresentedView(controller: child) + let host = PlatformHostingController(rootView: content.font(.system(size: 21))) + let frame = CGRect(x: 0, y: 0, width: 100, height: 100) + #if os(macOS) + let window = NSWindow(contentRect: frame, styleMask: .borderless, backing: .buffered, defer: false) + window.contentViewController = host + defer { window.contentViewController = nil } + func layout() { host.view.layoutSubtreeIfNeeded() } + #else + let window = UIWindow(frame: frame) + window.rootViewController = host + window.isHidden = false + defer { window.isHidden = true } + func layout() { window.layoutIfNeeded() } + #endif + + layout() + #expect(inheritedFont == .system(size: 21)) + + host.rootView = content.font(.system(size: 28)) + layout() + #expect(inheritedFont == .system(size: 28)) + } + + private struct RepresentedView: PlatformViewRepresentable { + let controller: PlatformViewController + + #if os(macOS) + func makeNSView(context: Context) -> NSView { controller.view } + func updateNSView(_ nsView: NSView, context: Context) {} + #else + func makeUIView(context: Context) -> UIView { controller.view } + func updateUIView(_ uiView: UIView, context: Context) {} + #endif + } + + private struct FontReader: View { + @Environment(\.font) private var font + var read: (Font?) -> Void + + var body: some View { + let _ = read(font) + Color.clear + } + } +} +#endif From fdf3de3b5ff6132fd49dcc73aa8a4b452ee39365 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 28 Nov 2026 22:09:25 +0800 Subject: [PATCH 2/3] fix(hosting): inherit representable environments in NSHostingView --- .../Hosting/AppKit/View/NSHostingView.swift | 14 +++++--------- .../Platform/AnyPlatformViewHost.swift | 5 +++++ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Sources/OpenSwiftUI/Integration/Hosting/AppKit/View/NSHostingView.swift b/Sources/OpenSwiftUI/Integration/Hosting/AppKit/View/NSHostingView.swift index 571bb0c39..5f3115f6c 100644 --- a/Sources/OpenSwiftUI/Integration/Hosting/AppKit/View/NSHostingView.swift +++ b/Sources/OpenSwiftUI/Integration/Hosting/AppKit/View/NSHostingView.swift @@ -1319,15 +1319,11 @@ extension NSHostingView: HitTestingLeafPlatformView { extension NSHostingView: ViewRendererHost { // FIXME package func updateEnvironment() { - var environment: EnvironmentValues - if let inheritedEnvironment { - environment = inheritedEnvironment - } else if let initialInheritedEnvironment { - environment = initialInheritedEnvironment - } else { - environment = EnvironmentValues() - environment.configureForRoot() - } + let superviews = sequence(first: self as NSView, next: \.superview).dropFirst() + var environment = inheritedEnvironment + ?? superviews.first(ofType: AnyPlatformViewHost.self)?.environment + ?? initialInheritedEnvironment + ?? EnvironmentValues().configuredForRoot() if let environmentOverride { environment.plist.override(with: environmentOverride.plist) } diff --git a/Sources/OpenSwiftUI/Integration/Representable/Platform/AnyPlatformViewHost.swift b/Sources/OpenSwiftUI/Integration/Representable/Platform/AnyPlatformViewHost.swift index 790b259e8..7783f2eb0 100644 --- a/Sources/OpenSwiftUI/Integration/Representable/Platform/AnyPlatformViewHost.swift +++ b/Sources/OpenSwiftUI/Integration/Representable/Platform/AnyPlatformViewHost.swift @@ -13,6 +13,11 @@ import OpenAttributeGraphShims protocol AnyPlatformViewHost: AnyObject { var responder: PlatformViewResponder? { get } + #if os(macOS) + var environment: EnvironmentValues { get } + var viewPhase: _GraphInputs.Phase { get } + var focusedValues: FocusedValues { get } + #endif } // MARK: - AnyPlatformViewProviderHost From 16502a8296ca31cb8e0349b815fd7d78c194074a Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 28 Nov 2026 22:26:12 +0800 Subject: [PATCH 3/3] fix(hosting): apply _overrideSizeThatFits to default representable sizing Fixes #1272 --- .../Platform/PlatformViewRepresentable.swift | 7 +- ...mViewRepresentableCompatibilityTests.swift | 203 +++++++++++++++--- 2 files changed, 183 insertions(+), 27 deletions(-) diff --git a/Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewRepresentable.swift b/Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewRepresentable.swift index 6d71e75a8..33b8cc0fd 100644 --- a/Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewRepresentable.swift +++ b/Sources/OpenSwiftUI/Integration/Representable/Platform/PlatformViewRepresentable.swift @@ -540,7 +540,7 @@ struct ViewLeafView: PrimitiveView, UnaryView where Content: PlatformVi transaction: .init(), environmentStorage: .lazy(environment, context) ) - let result: CGSize + var result: CGSize if let fittingSize = content.sizeThatFits( .init(proposedSize), provider: representedViewProvider, @@ -556,6 +556,11 @@ struct ViewLeafView: PrimitiveView, UnaryView where Content: PlatformVi .fixingUnspecifiedDimensions(at: traits.idealSize) .clamped(to: traits) } + content.overrideSizeThatFits( + &result, + in: proposedSize, + platformView: representedViewProvider + ) } size = result } diff --git a/Tests/OpenSwiftUICompatibilityTests/Integration/Representable/PlatformViewRepresentableCompatibilityTests.swift b/Tests/OpenSwiftUICompatibilityTests/Integration/Representable/PlatformViewRepresentableCompatibilityTests.swift index f345f100f..4ab5d62b1 100644 --- a/Tests/OpenSwiftUICompatibilityTests/Integration/Representable/PlatformViewRepresentableCompatibilityTests.swift +++ b/Tests/OpenSwiftUICompatibilityTests/Integration/Representable/PlatformViewRepresentableCompatibilityTests.swift @@ -7,44 +7,184 @@ import OpenSwiftUITestsSupport import Testing #if os(iOS) || os(visionOS) import UIKit -#else +#elseif os(macOS) import AppKit #endif @MainActor struct PlatformViewRepresentableCompatibilityTests { @Test - func nestedHostingViewInheritsFontChanges() { - var inheritedFont: Font? - #if os(macOS) - _ = NSApplication.shared - #endif - let child = PlatformHostingController(rootView: FontReader { inheritedFont = $0 }) - let content = RepresentedView(controller: child) - let host = PlatformHostingController(rootView: content.font(.system(size: 21))) - let frame = CGRect(x: 0, y: 0, width: 100, height: 100) + func nestedHostingViewInheritsFontChanges() async throws { + var inheritedFonts: [Font?] = [] + + struct ContentView: View { + let child: PlatformViewController + @State private var fontSize: CGFloat = 21 + + var body: some View { + RepresentedControllerView(controller: child) + .font(.system(size: fontSize)) + .onAppear { + DispatchQueue.main.async { + fontSize = 28 + } + } + } + } + + try await triggerLayoutWithWindow { continuation in + var resumed = false + let child = PlatformHostingController( + rootView: FontReader { font in + inheritedFonts.append(font) + if font == .system(size: 28), !resumed { + resumed = true + continuation.resume() + } + } + ) + return PlatformHostingController(rootView: ContentView(child: child)) + } + #expect(inheritedFonts.first == .system(size: 21)) + #expect(inheritedFonts.last == .system(size: 28)) + } + + @Test + func overrideSizeThatFitsAdjustsDefaultSize() async throws { + let recorder = SizingRecorder() + var measuredSizes: [CGSize] = [] + + struct ContentView: View { + let recorder: SizingRecorder + let onMeasure: (CGSize) -> Void + @State private var expanded = false + + var body: some View { + SizingRepresentedView( + explicitSize: nil, + overrideSize: CGSize(width: expanded ? 190 : 174, height: 36), + recorder: recorder + ) + .readSize(onMeasure) + .frame(width: expanded ? 220 : 200, height: 80) + .onAppear { + DispatchQueue.main.async { + expanded = true + } + } + } + } + + try await triggerLayoutWithWindow { continuation in + var resumed = false + return PlatformHostingController( + rootView: ContentView(recorder: recorder) { size in + measuredSizes.append(size) + if size == CGSize(width: 190, height: 36), !resumed { + resumed = true + continuation.resume() + } + } + ) + } + #expect(recorder.initialSizes.contains(CGSize(width: 80, height: 24))) + #expect(measuredSizes.contains(CGSize(width: 174, height: 36))) + #expect(measuredSizes.last == CGSize(width: 190, height: 36)) + #expect(recorder.proposals.first != recorder.proposals.last) + } + + @Test + func explicitSizeThatFitsBypassesOverrideSizeThatFits() async throws { + let recorder = SizingRecorder() + var measuredSize: CGSize = .zero + let root = SizingRepresentedView( + explicitSize: CGSize(width: 120, height: 30), + overrideSize: CGSize(width: 174, height: 36), + recorder: recorder + ) + .readSize { measuredSize = $0 } + .frame(width: 200, height: 80) + + try await triggerLayoutWithWindow(expectedCount: 0) { _ in + PlatformHostingController(rootView: root) + } + #expect(recorder.initialSizes.isEmpty) + #expect(measuredSize == CGSize(width: 120, height: 30)) + } + + private final class SizingRecorder { + var initialSizes: [CGSize] = [] + var proposals: [_ProposedSize] = [] + } + + private final class IntrinsicSizedView: PlatformView { + override var intrinsicContentSize: CGSize { + CGSize(width: 80, height: 24) + } + } + + private struct SizingRepresentedView: PlatformViewRepresentable { + let explicitSize: CGSize? + let overrideSize: CGSize + let recorder: SizingRecorder + + private func makeView() -> IntrinsicSizedView { + let view = IntrinsicSizedView(frame: .zero) + view.setContentHuggingPriority(.defaultHigh, for: .horizontal) + view.setContentHuggingPriority(.defaultHigh, for: .vertical) + view.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) + view.setContentCompressionResistancePriority(.defaultHigh, for: .vertical) + return view + } + + private func recordOverride(_ size: inout CGSize, in proposedSize: _ProposedSize) { + recorder.initialSizes.append(size) + recorder.proposals.append(proposedSize) + size = overrideSize + } + #if os(macOS) - let window = NSWindow(contentRect: frame, styleMask: .borderless, backing: .buffered, defer: false) - window.contentViewController = host - defer { window.contentViewController = nil } - func layout() { host.view.layoutSubtreeIfNeeded() } + func makeNSView(context: Context) -> IntrinsicSizedView { makeView() } + func updateNSView(_ nsView: IntrinsicSizedView, context: Context) {} + + func sizeThatFits( + _ proposal: ProposedViewSize, + nsView: IntrinsicSizedView, + context: Context + ) -> CGSize? { + explicitSize + } + + func _overrideSizeThatFits( + _ size: inout CGSize, + in proposedSize: _ProposedSize, + nsView: IntrinsicSizedView + ) { + recordOverride(&size, in: proposedSize) + } #else - let window = UIWindow(frame: frame) - window.rootViewController = host - window.isHidden = false - defer { window.isHidden = true } - func layout() { window.layoutIfNeeded() } - #endif + func makeUIView(context: Context) -> IntrinsicSizedView { makeView() } + func updateUIView(_ uiView: IntrinsicSizedView, context: Context) {} - layout() - #expect(inheritedFont == .system(size: 21)) + func sizeThatFits( + _ proposal: ProposedViewSize, + uiView: IntrinsicSizedView, + context: Context + ) -> CGSize? { + explicitSize + } - host.rootView = content.font(.system(size: 28)) - layout() - #expect(inheritedFont == .system(size: 28)) + func _overrideSizeThatFits( + _ size: inout CGSize, + in proposedSize: _ProposedSize, + uiView: IntrinsicSizedView + ) { + recordOverride(&size, in: proposedSize) + } + #endif } - private struct RepresentedView: PlatformViewRepresentable { + private struct RepresentedControllerView: PlatformViewRepresentable { let controller: PlatformViewController #if os(macOS) @@ -66,4 +206,15 @@ struct PlatformViewRepresentableCompatibilityTests { } } } + +extension View { + fileprivate func readSize(_ perform: @escaping (CGSize) -> Void) -> some View { + background { + GeometryReader { proxy in + let _ = perform(proxy.size) + Color.clear + } + } + } +} #endif