From fbc56c4c08370c609dccc019037088dd4fcdfdf3 Mon Sep 17 00:00:00 2001 From: ichiho-ojima Date: Sun, 12 May 2024 00:49:01 +0900 Subject: [PATCH] Stop having WebViewProxy as an Environment Property in ViewRepresentable. --- Sources/WebUI/SetUpWebViewProxyAction.swift | 22 +++++++++++++++++++++ Sources/WebUI/WebView+Extension.swift | 4 ++-- Sources/WebUI/WebViewProxy.swift | 11 ----------- Sources/WebUI/WebViewReader.swift | 2 +- 4 files changed, 25 insertions(+), 14 deletions(-) create mode 100644 Sources/WebUI/SetUpWebViewProxyAction.swift diff --git a/Sources/WebUI/SetUpWebViewProxyAction.swift b/Sources/WebUI/SetUpWebViewProxyAction.swift new file mode 100644 index 0000000..93deacb --- /dev/null +++ b/Sources/WebUI/SetUpWebViewProxyAction.swift @@ -0,0 +1,22 @@ +import SwiftUI +import WebKit + +struct SetUpWebViewProxyAction { + let action: (WKWebView) -> Void + + func callAsFunction(_ webView: WKWebView) { + action(webView) + } +} + +private struct SetUpWebViewProxyActionKey: EnvironmentKey { + static var defaultValue = SetUpWebViewProxyAction(action: { _ in }) +} + +extension EnvironmentValues { + var setUpWebViewProxy: SetUpWebViewProxyAction { + get { self[SetUpWebViewProxyActionKey.self] } + set { self[SetUpWebViewProxyActionKey.self] = newValue } + } +} + diff --git a/Sources/WebUI/WebView+Extension.swift b/Sources/WebUI/WebView+Extension.swift index 01ce3c2..3c9acb8 100644 --- a/Sources/WebUI/WebView+Extension.swift +++ b/Sources/WebUI/WebView+Extension.swift @@ -13,7 +13,7 @@ extension WebView: View { } struct _WebView: ViewRepresentable { - @Environment(\.webViewProxy) private var proxy: WebViewProxy + @Environment(\.setUpWebViewProxy) private var setUpWebViewProxy let parent: WebView @@ -21,7 +21,7 @@ extension WebView: View { private func makeEnhancedWKWebView() -> EnhancedWKWebView { let webView = EnhancedWKWebView(frame: .zero, configuration: parent.configuration) parent.applyModifiers(to: webView) - proxy.setUp(webView) + setUpWebViewProxy(webView) return webView } diff --git a/Sources/WebUI/WebViewProxy.swift b/Sources/WebUI/WebViewProxy.swift index 77fcc36..33147bb 100644 --- a/Sources/WebUI/WebViewProxy.swift +++ b/Sources/WebUI/WebViewProxy.swift @@ -140,14 +140,3 @@ public final class WebViewProxy: ObservableObject { } } } - -private struct WebViewProxyKey: EnvironmentKey { - static let defaultValue = WebViewProxy() -} - -extension EnvironmentValues { - var webViewProxy: WebViewProxy { - get { self[WebViewProxyKey.self] } - set { self[WebViewProxyKey.self] = newValue } - } -} diff --git a/Sources/WebUI/WebViewReader.swift b/Sources/WebUI/WebViewReader.swift index bd89101..8b425d6 100644 --- a/Sources/WebUI/WebViewReader.swift +++ b/Sources/WebUI/WebViewReader.swift @@ -34,6 +34,6 @@ public struct WebViewReader: View { /// The content and behavior of the view. public var body: some View { content(proxy) - .environment(\.webViewProxy, proxy) + .environment(\.setUpWebViewProxy, SetUpWebViewProxyAction(action: proxy.setUp)) } }