Skip to content

Commit

Permalink
Merge pull request #4 from cybozu/fix-infinite-loop-3
Browse files Browse the repository at this point in the history
Fix infinite loop due to `objectWillChange` firing
  • Loading branch information
Kyome22 committed May 15, 2024
2 parents 670d400 + 7340f9f commit fae50c0
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 14 deletions.
22 changes: 22 additions & 0 deletions Sources/WebUI/SetUpWebViewProxyAction.swift
Original file line number Diff line number Diff line change
@@ -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 }
}
}

4 changes: 2 additions & 2 deletions Sources/WebUI/WebView+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ extension WebView: View {
}

struct _WebView: ViewRepresentable {
@Environment(\.webViewProxy) private var proxy: WebViewProxy
@Environment(\.setUpWebViewProxy) private var setUpWebViewProxy

let parent: WebView

@MainActor
private func makeEnhancedWKWebView() -> EnhancedWKWebView {
let webView = EnhancedWKWebView(frame: .zero, configuration: parent.configuration)
proxy.setUp(webView)
setUpWebViewProxy(webView)
parent.applyModifiers(to: webView)
parent.loadInitialURL(in: webView)
return webView
Expand Down
11 changes: 0 additions & 11 deletions Sources/WebUI/WebViewProxy.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
}
2 changes: 1 addition & 1 deletion Sources/WebUI/WebViewReader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ public struct WebViewReader<Content: View>: View {
/// The content and behavior of the view.
public var body: some View {
content(proxy)
.environment(\.webViewProxy, proxy)
.environment(\.setUpWebViewProxy, SetUpWebViewProxyAction(action: proxy.setUp))
}
}

0 comments on commit fae50c0

Please sign in to comment.