Repository Public License
1import SwiftUI2import WebKit34#if canImport(AppKit)5import AppKit6#elseif canImport(UIKit)7import UIKit8#endif910/// How a `WebEngineView` lays its web view out.11public struct WebEngineViewOptions: Equatable, Sendable {12 /// Browser chrome drawn over the web view (floating dock, translucent toolbar). The page lays out under it13 /// but keeps its content clear of it. Uses `obscuredContentInsets` on OS 26+, and the scroll view's content14 /// inset on earlier iOS; ignored on earlier macOS.15 public var obscuredInsets: EdgeInsets16 /// Smallest and largest insets the page will experience while the chrome collapses and expands, so that17 /// viewport units (`svh`, `lvh`) are stable during the animation.18 public var minimumViewportInsets: EdgeInsets?19 public var maximumViewportInsets: EdgeInsets?20 /// iOS: let the web view extend under the system safe areas instead of being inset by them.21 public var ignoresSafeArea: Bool22 /// iOS: report native scroll offsets to `WebEngine.scroll` / `scrollDirection` (collapsing dock). When off,23 /// the values come from the page script.24 public var observesScrollView: Bool25 public var allowsBackForwardGestures: Bool26 /// iOS: dismiss the keyboard when the page is dragged.27 public var dismissesKeyboardOnDrag: Bool2829 public init(obscuredInsets: EdgeInsets = EdgeInsets(), minimumViewportInsets: EdgeInsets? = nil,30 maximumViewportInsets: EdgeInsets? = nil, ignoresSafeArea: Bool = false, observesScrollView: Bool = true,31 allowsBackForwardGestures: Bool = true, dismissesKeyboardOnDrag: Bool = true) {32 self.obscuredInsets = obscuredInsets; self.minimumViewportInsets = minimumViewportInsets33 self.maximumViewportInsets = maximumViewportInsets; self.ignoresSafeArea = ignoresSafeArea34 self.observesScrollView = observesScrollView; self.allowsBackForwardGestures = allowsBackForwardGestures35 self.dismissesKeyboardOnDrag = dismissesKeyboardOnDrag36 }37}3839/// Shows the web view of a `WebEngine`.40///41/// The view never creates a `WKWebView`: it re-parents the one the engine owns into a plain container, so42/// SwiftUI updates, tab switches and split-view rearrangements keep the same page alive. When the engine has no43/// web view (dormant or suspended tab) the container is empty; draw the thumbnail behind it.44public struct WebEngineView: View {45 private let engine: WebEngine46 private let options: WebEngineViewOptions4748 public init(engine: WebEngine, options: WebEngineViewOptions = WebEngineViewOptions()) {49 self.engine = engine50 self.options = options51 }5253 public var body: some View {54 // Reading `engine.webView` here subscribes the view to its replacement (suspend / resume).55 let host = WebViewHost(engine: engine, webView: engine.webView, options: options)56 #if os(iOS)57 if options.ignoresSafeArea { host.ignoresSafeArea() } else { host }58 #else59 host60 #endif61 }62}6364@MainActor65private func platformInsets(_ insets: EdgeInsets, layoutDirection: LayoutDirection) -> (top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) {66 let rightToLeft = layoutDirection == .rightToLeft67 return (insets.top, rightToLeft ? insets.trailing : insets.leading, insets.bottom, rightToLeft ? insets.leading : insets.trailing)68}6970#if os(macOS)7172/// Plain container: the web view is its only subview and follows its bounds.73public final class WebViewContainerView: NSView {74 private(set) weak var hostedWebView: WKWebView?7576 func host(_ webView: WKWebView?) {77 guard hostedWebView !== webView || (webView != nil && webView?.superview !== self) else { return }78 // During element fullscreen WebKit moves the web view into its own window and leaves a placeholder here;79 // re-parenting it now would tear the fullscreen presentation down.80 if let webView, webView.fullscreenState != .notInFullscreen { return }81 if let old = hostedWebView, old !== webView, old.superview === self { old.removeFromSuperview() }82 hostedWebView = webView83 guard let webView else { return }84 webView.frame = bounds85 webView.autoresizingMask = [.width, .height]86 addSubview(webView)87 }8889 func release() {90 if let old = hostedWebView, old.superview === self { old.removeFromSuperview() }91 hostedWebView = nil92 }93}9495private struct WebViewHost: NSViewRepresentable {96 let engine: WebEngine97 let webView: NavigatorWebView?98 let options: WebEngineViewOptions99100 func makeNSView(context: Context) -> WebViewContainerView { WebViewContainerView() }101102 func updateNSView(_ container: WebViewContainerView, context: Context) {103 container.host(webView)104 guard let webView else { return }105 webView.allowsBackForwardNavigationGestures = options.allowsBackForwardGestures106 let direction = context.environment.layoutDirection107 let obscured = platformInsets(options.obscuredInsets, layoutDirection: direction)108 if #available(macOS 26.0, *) {109 let insets = NSEdgeInsets(top: obscured.top, left: obscured.left, bottom: obscured.bottom, right: obscured.right)110 if !NSEdgeInsetsEqual(webView.obscuredContentInsets, insets) { webView.obscuredContentInsets = insets }111 }112 if let minimum = options.minimumViewportInsets, let maximum = options.maximumViewportInsets {113 let low = platformInsets(minimum, layoutDirection: direction), high = platformInsets(maximum, layoutDirection: direction)114 webView.setMinimumViewportInset(NSEdgeInsets(top: low.top, left: low.left, bottom: low.bottom, right: low.right),115 maximumViewportInset: NSEdgeInsets(top: high.top, left: high.left, bottom: high.bottom, right: high.right))116 }117 }118119 static func dismantleNSView(_ container: WebViewContainerView, coordinator: ()) {120 // The web view belongs to the engine: detach it, never destroy it.121 container.release()122 }123}124125#elseif os(iOS)126127public final class WebViewContainerView: UIView {128 private(set) weak var hostedWebView: WKWebView?129 private var offsetObservation: NSKeyValueObservation?130 private var sizeObservation: NSKeyValueObservation?131 weak var engine: WebEngine?132133 func host(_ webView: WKWebView?, observingScroll: Bool) {134 let changed = hostedWebView !== webView || (webView != nil && webView?.superview !== self)135 if changed {136 if let webView, webView.fullscreenState != .notInFullscreen { return }137 if let old = hostedWebView, old !== webView, old.superview === self { old.removeFromSuperview() }138 stopObserving()139 hostedWebView = webView140 if let webView {141 webView.frame = bounds142 webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]143 addSubview(webView)144 }145 }146 if observingScroll, offsetObservation == nil, let webView { startObserving(webView.scrollView) }147 if !observingScroll { stopObserving() }148 }149150 func release() {151 stopObserving()152 if let old = hostedWebView, old.superview === self { old.removeFromSuperview() }153 hostedWebView = nil154 }155156 /// KVO rather than `UIScrollViewDelegate`: WebKit and the page's own features use the delegate slot.157 private func startObserving(_ scrollView: UIScrollView) {158 engine?.usesNativeScrollObservation = true159 let report: @Sendable (UIScrollView) -> Void = { [weak self] scrollView in160 MainActor.assumeIsolated {161 guard let self, let engine = self.engine else { return }162 let inset = scrollView.adjustedContentInset163 engine.updateScroll(ScrollMetrics(x: scrollView.contentOffset.x + inset.left,164 y: scrollView.contentOffset.y + inset.top,165 contentWidth: scrollView.contentSize.width,166 contentHeight: scrollView.contentSize.height,167 viewportWidth: scrollView.bounds.width - inset.left - inset.right,168 viewportHeight: scrollView.bounds.height - inset.top - inset.bottom))169 }170 }171 offsetObservation = scrollView.observe(\.contentOffset, options: [.new]) { scrollView, _ in report(scrollView) }172 sizeObservation = scrollView.observe(\.contentSize, options: [.new]) { scrollView, _ in report(scrollView) }173 }174175 private func stopObserving() {176 offsetObservation?.invalidate()177 sizeObservation?.invalidate()178 offsetObservation = nil179 sizeObservation = nil180 engine?.usesNativeScrollObservation = false181 }182}183184private struct WebViewHost: UIViewRepresentable {185 let engine: WebEngine186 let webView: NavigatorWebView?187 let options: WebEngineViewOptions188189 func makeUIView(context: Context) -> WebViewContainerView {190 let container = WebViewContainerView()191 container.engine = engine192 return container193 }194195 func updateUIView(_ container: WebViewContainerView, context: Context) {196 container.engine = engine197 container.host(webView, observingScroll: options.observesScrollView)198 guard let webView else { return }199 webView.allowsBackForwardNavigationGestures = options.allowsBackForwardGestures200 let scrollView = webView.scrollView201 scrollView.keyboardDismissMode = options.dismissesKeyboardOnDrag ? .interactive : .none202 scrollView.contentInsetAdjustmentBehavior = options.ignoresSafeArea ? .never : .automatic203 let direction = context.environment.layoutDirection204 let obscured = platformInsets(options.obscuredInsets, layoutDirection: direction)205 let insets = UIEdgeInsets(top: obscured.top, left: obscured.left, bottom: obscured.bottom, right: obscured.right)206 if #available(iOS 26.0, *) {207 if webView.obscuredContentInsets != insets { webView.obscuredContentInsets = insets }208 } else if scrollView.contentInset != insets {209 scrollView.contentInset = insets210 scrollView.verticalScrollIndicatorInsets = insets211 scrollView.horizontalScrollIndicatorInsets = insets212 }213 if let minimum = options.minimumViewportInsets, let maximum = options.maximumViewportInsets {214 let low = platformInsets(minimum, layoutDirection: direction), high = platformInsets(maximum, layoutDirection: direction)215 webView.setMinimumViewportInset(UIEdgeInsets(top: low.top, left: low.left, bottom: low.bottom, right: low.right),216 maximumViewportInset: UIEdgeInsets(top: high.top, left: high.left, bottom: high.bottom, right: high.right))217 }218 }219220 static func dismantleUIView(_ container: WebViewContainerView, coordinator: ()) {221 container.release()222 }223}224225#endif226