|
@@ -8,6 +8,7 @@ import android.webkit.WebView
|
|
import com.google.gson.Gson
|
|
import com.google.gson.Gson
|
|
import com.google.gson.JsonElement
|
|
import com.google.gson.JsonElement
|
|
import com.hzliuzhi.applet.core.shared.Event
|
|
import com.hzliuzhi.applet.core.shared.Event
|
|
|
|
+import com.hzliuzhi.applet.core.shared.Message
|
|
import com.hzliuzhi.applet.core.shared.SharedFlowHub
|
|
import com.hzliuzhi.applet.core.shared.SharedFlowHub
|
|
import com.hzliuzhi.applet.core.shared.SharedFlowHub.cast
|
|
import com.hzliuzhi.applet.core.shared.SharedFlowHub.cast
|
|
import kotlinx.coroutines.CoroutineScope
|
|
import kotlinx.coroutines.CoroutineScope
|
|
@@ -21,32 +22,6 @@ import org.json.JSONObject
|
|
import java.io.InputStreamReader
|
|
import java.io.InputStreamReader
|
|
|
|
|
|
class WebViewBridge(private val coroutineScope: CoroutineScope) {
|
|
class WebViewBridge(private val coroutineScope: CoroutineScope) {
|
|
- data class Message(
|
|
|
|
- val type: String,
|
|
|
|
- val payload: JsonElement? = Gson().toJsonTree(""),
|
|
|
|
- val callbackId: String? = null,
|
|
|
|
- ) {
|
|
|
|
- companion object {
|
|
|
|
- fun fromJson(json: String) = try {
|
|
|
|
- Gson().fromJson(json, Message::class.java)
|
|
|
|
- } catch (_: Throwable) {
|
|
|
|
- null
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- fun toJson(message: Message) = try {
|
|
|
|
- Gson().toJson(message)
|
|
|
|
- } catch (_: Throwable) {
|
|
|
|
- null
|
|
|
|
- }
|
|
|
|
- }
|
|
|
|
-
|
|
|
|
- fun toEvent() = Event<Message, String>(
|
|
|
|
- type = "${SharedFlowHub.WEBVIEW_BRIDGE_EVENT}:js",
|
|
|
|
- payload = this
|
|
|
|
- )
|
|
|
|
-
|
|
|
|
- val isPayloadNull: Boolean get() = payload?.isJsonNull ?: true
|
|
|
|
- }
|
|
|
|
|
|
|
|
|
|
|
|
private var lastScriptText: String? = null
|
|
private var lastScriptText: String? = null
|
|
@@ -85,7 +60,7 @@ class WebViewBridge(private val coroutineScope: CoroutineScope) {
|
|
type = message.type,
|
|
type = message.type,
|
|
payload = webview.createPrintDocumentAdapter("WebViewDocument"),
|
|
payload = webview.createPrintDocumentAdapter("WebViewDocument"),
|
|
callback = { payload ->
|
|
callback = { payload ->
|
|
- val event = message.copy(payload = payload).toEvent()
|
|
|
|
|
|
+ val event = message.copy(payload = payload).toWebEvent()
|
|
emit(event)
|
|
emit(event)
|
|
}
|
|
}
|
|
).also { emit(it) }
|
|
).also { emit(it) }
|
|
@@ -94,7 +69,7 @@ class WebViewBridge(private val coroutineScope: CoroutineScope) {
|
|
type = "$WEBVIEW_BRIDGE_EVENT:${message.type}",
|
|
type = "$WEBVIEW_BRIDGE_EVENT:${message.type}",
|
|
payload = message.payload,
|
|
payload = message.payload,
|
|
callback = { payload ->
|
|
callback = { payload ->
|
|
- val event = message.copy(payload = payload).toEvent()
|
|
|
|
|
|
+ val event = message.copy(payload = payload).toWebEvent()
|
|
emit(event)
|
|
emit(event)
|
|
}
|
|
}
|
|
).also { emit(it) }
|
|
).also { emit(it) }
|