refactor(webview): ios preload webview module

- Refactored WebViewManager to improve lifecycle management and state handling.
- Introduced a debug panel for monitoring WebView state and actions in development mode.
- Updated JavaScript injection methods to use a centralized dispatch system for better maintainability.
- Improved handling of local HTML loading and state replay after process termination.
- Added new functions for debugging, including state retrieval and flushing pending scripts.

This update aims to enhance the overall performance and usability of the WebView component, providing developers with better tools for debugging and state management.

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-08-26 22:20:57 +08:00
parent b0c4052632
commit a9bb77167e
19 changed files with 1949 additions and 438 deletions
@@ -13,131 +13,147 @@ let onImagePreview = "onImagePreview"
let onSeekAudio = "onSeekAudio"
public class SharedWebViewModule: Module {
private var pendingJavaScripts: [String] = []
private var cancellables = Set<AnyCancellable>()
private var cancellables = Set<AnyCancellable>()
public static var sharedWebView: WKWebView? {
WebViewManager.shared
public static var sharedWebView: WKWebView? {
WebViewManager.shared
}
public func definition() -> ModuleDefinition {
Name("FOSharedWebView")
Function("load") { (urlString: String) in
WebViewManager.load(urlString)
}
public func definition() -> ModuleDefinition {
Name("FOSharedWebView")
Function("load") { (urlString: String) in
DispatchQueue.main.async {
self.load(urlString: urlString)
}
}
Function("evaluateJavaScript") { (js: String) in
DispatchQueue.main.async {
WebViewManager.evaluateJavaScript(js)
}
}
View(WebViewView.self) {
Events("onContentHeightChange")
Events("onSeekAudio")
Prop("url") { (_: UIView, urlString: String) in
DispatchQueue.main.async {
self.load(urlString: urlString)
}
}
}
Events(onContentHeightChanged)
Events(onImagePreview)
Events(onSeekAudio)
OnStartObserving {
// Monitor content height changes
WebViewManager.state.$contentHeight
.receive(on: DispatchQueue.main)
.sink { [weak self] height in
self?.sendEvent(onContentHeightChanged, ["height": height])
}
.store(in: &self.cancellables)
// Monitor image preview events
WebViewManager.state.$imagePreviewEvent
.receive(on: DispatchQueue.main)
.compactMap { $0 } // Filter out nil values
.sink { [weak self] event in
self?.sendEvent(onImagePreview, ["imageUrls": event.imageUrls, "index": event.index])
}
.store(in: &self.cancellables)
WebViewManager.state.$audioSeekEvent
.receive(on: DispatchQueue.main)
.compactMap { $0 }
.sink { [weak self] event in
self?.sendEvent(onSeekAudio, ["time": event.time])
}
.store(in: &self.cancellables)
}
OnStopObserving {
self.cancellables.forEach { $0.cancel() }
self.cancellables.removeAll()
}
Function("evaluateJavaScript") { (js: String) in
// Prefer typed setters or dispatch to record state; avoid parsing free-form JS
WebViewManager.evaluateJavaScript(js)
}
private func load(urlString: String) {
guard let webView = SharedWebViewModule.sharedWebView else {
return
}
// Check is local file
let urlProtocol = "file://"
if urlString.starts(with: urlProtocol) {
let localHtml = self.getLocalHTML(from: urlString)
if let localHtml = localHtml {
webView.loadFileURL(
localHtml,
allowingReadAccessTo: localHtml.deletingLastPathComponent()
)
debugPrint("load local html: \(localHtml.absoluteString)")
return
}
}
if let url = URL(string: urlString) {
if url == webView.url {
return
}
debugPrint("load remote html: \(url.absoluteString)")
webView.load(URLRequest(url: url))
}
// Centralized dispatch to JS layer (native -> JS)
Function("dispatch") { (type: String, payload: String?) in
let payloadExpr: String
if let payload = payload {
// payload is JSON string; pass via JSON.parse to avoid double-escaping
payloadExpr = "JSON.parse(\(self.jsonString(payload)))"
} else {
payloadExpr = "null"
}
let js =
"(function(){ if (window.__FO_BRIDGE__ && typeof window.__FO_BRIDGE__.dispatch === 'function') { window.__FO_BRIDGE__.dispatch(\(self.jsonString(type)), \(payloadExpr)); } })()"
WebViewManager.recordJSON(key: type, payload: payload)
WebViewManager.evaluateJavaScript(js)
}
private func getLocalHTML(from fileURL: String) -> URL? {
if let url = URL(string: fileURL), url.scheme == "file" {
View(WebViewView.self) {
Events("onContentHeightChange")
Events("onSeekAudio")
let directoryPath = url.deletingLastPathComponent().absoluteString.replacingOccurrences(
of: "file://", with: ""
)
let fileName = url.lastPathComponent
let fileExtension = url.pathExtension
if let fileURL = Bundle.main
.url(
forResource: String(fileName.dropLast(Int(fileExtension.count) + 1)),
withExtension: fileExtension,
subdirectory: directoryPath
)
{
return fileURL
} else {
return nil
}
} else {
debugPrint("Invalidate url")
return nil
}
Prop("url") { (_: UIView, urlString: String) in
WebViewManager.load(urlString)
}
}
Events(onContentHeightChanged)
Events(onImagePreview)
Events(onSeekAudio)
OnCreate {
WebViewManager.initializeLifecycleObservers()
}
OnDestroy {
WebViewManager.cleanupLifecycleObservers()
}
OnStartObserving {
// Monitor content height changes
WebViewManager.state.$contentHeight
.receive(on: DispatchQueue.main)
.sink { [weak self] height in
self?.sendEvent(onContentHeightChanged, ["height": height])
}
.store(in: &self.cancellables)
// Monitor image preview events
WebViewManager.state.$imagePreviewEvent
.receive(on: DispatchQueue.main)
.compactMap { $0 } // Filter out nil values
.sink { [weak self] event in
self?.sendEvent(onImagePreview, ["imageUrls": event.imageUrls, "index": event.index])
}
.store(in: &self.cancellables)
WebViewManager.state.$audioSeekEvent
.receive(on: DispatchQueue.main)
.compactMap { $0 }
.sink { [weak self] event in
self?.sendEvent(onSeekAudio, ["time": event.time])
}
.store(in: &self.cancellables)
}
OnStopObserving {
self.cancellables.forEach { $0.cancel() }
self.cancellables.removeAll()
}
// Debug helpers
Function("getDebugState") { () -> [String: Any] in
WebViewManager.debugState()
}
Function("destroyForDebug") {
WebViewManager.destroyForDebug()
}
Function("reloadLastURL") {
WebViewManager.reloadLastURL()
}
Function("flushQueue") {
WebViewManager.flushForDebug()
}
}
private func getLocalHTML(from fileURL: String) -> URL? {
if let url = URL(string: fileURL), url.scheme == "file" {
let directoryPath = url.deletingLastPathComponent().absoluteString.replacingOccurrences(
of: "file://", with: ""
)
let fileName = url.lastPathComponent
let fileExtension = url.pathExtension
if let fileURL = Bundle.main
.url(
forResource: String(fileName.dropLast(Int(fileExtension.count) + 1)),
withExtension: fileExtension,
subdirectory: directoryPath
)
{
return fileURL
} else {
return nil
}
} else {
debugPrint("Invalidate url")
return nil
}
}
// Removed JS string parsing helpers; state is captured by typed setters or dispatch/setStateJSON
fileprivate func jsonString(_ value: String) -> String {
// Encode as JSON string literal
let data = try? JSONSerialization.data(withJSONObject: ["v": value], options: [])
if let data = data, let s = String(data: data, encoding: .utf8) {
if let range = s.range(of: ":") {
return String(s[range.upperBound..<s.index(before: s.endIndex)])
}
let escaped = value.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(
of: "\"", with: "\\\"")
return "\"\(escaped)\""
}
return ""
}
// recordDispatchState removed: dynamic state is recorded directly via WebViewManager.recordJSON
}