Skip to content

Commit

Permalink
💥 Rename update and scrollTo parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
phatblat committed Feb 6, 2022
1 parent b61934e commit e92f295
Showing 1 changed file with 34 additions and 17 deletions.
51 changes: 34 additions & 17 deletions Sources/WebView/WebViewStore.swift
Original file line number Diff line number Diff line change
@@ -1,28 +1,44 @@
import WebKit
import Combine

/// Provides access to webview data.
public class WebViewStore: ObservableObject {
private var observers = Set<NSKeyValueObservation>()

@Published public var webView: WKWebView {
@Published
public var webView: WKWebView {
didSet {
setupObservers()
}
}

/// Initializes a new WebView.
/// - Parameter webView: Optional custom webview. Default WKWebView will be constructed if not provided.
public init(webView: WKWebView = .init()) {
self.webView = webView

#if DEBUG
self.webView
.configuration
.preferences
.setValue(true, forKey: "developerExtrasEnabled")
.configuration
.preferences
.setValue(true, forKey: "developerExtrasEnabled")
#endif

setupObservers()
}

deinit {
observers.forEach {
// Not even sure if this is required?
// Probably wont be needed in future betas?
$0.invalidate()
}
}
}

/// Private methods
fileprivate extension WebViewStore {
/// Description
private func setupObservers() {
func subscriber<Value>(for keyPath: KeyPath<WKWebView, Value>) -> NSKeyValueObservation {
return webView.observe(keyPath, options: [.prior]) { _, change in
Expand All @@ -44,29 +60,30 @@ public class WebViewStore: ObservableObject {
subscriber(for: \.canGoForward)
]
}

deinit {
observers.forEach {
// Not even sure if this is required?
// Probably wont be needed in future betas?
$0.invalidate()
}
}
}

/// DOM manipulation and scrolling.
extension WebViewStore {
func update(_ HTML: String, baseURL: URL) {
/// Loads a new document and scrolls to the same Y offset.
/// - Parameters:
/// - html: HTML string of the new document.
/// - baseURL: Optional base URL.
func update(_ html: String, baseURL: URL? = nil) {
webView.evaluateJavaScript("window.pageYOffset") { [weak self] object, error in
self?.webView.loadHTMLString(HTML, baseURL: baseURL)
guard let strongSelf = self else { return }

strongSelf.webView.loadHTMLString(html, baseURL: baseURL)

if let offset = object as? Int {
self?.scrollTo(offset)
strongSelf.scrollTo(offset)
}
}
}

private func scrollTo(_ YOffset: Int) {
let script = "window.scrollTo(0, \(YOffset));"
/// Instructs the webview to scroll the viewport.
/// - Parameter yOffset: Vertical offset to scroll to.
private func scrollTo(_ yOffset: Int) {
let script = "window.scrollTo(0, \(yOffset));"
let scrollScript = WKUserScript(source: script, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
webView.configuration.userContentController.addUserScript(scrollScript)
}
Expand Down

0 comments on commit e92f295

Please sign in to comment.