Browse Source

Download skiko asynchronously

with_mpp_example
Shagen Ogandzhanian 3 years ago
parent
commit
a53c54433d
  1. 2
      examples/web-skia/src/jsMain/resources/index.html
  2. 59
      web/core/src/jsMain/kotlin/org/jetbrains/compose/skiko/skiko.kt

2
examples/web-skia/src/jsMain/resources/index.html

@ -13,6 +13,6 @@
<body>
<div id="root"/>
</body>
<script src="skiko.js"></script>
<!-- <script src="skiko.js"></script>-->
<script src="compose-skia.js"></script>
</html>

59
web/core/src/jsMain/kotlin/org/jetbrains/compose/skiko/skiko.kt

@ -7,22 +7,67 @@ package org.jetbrains.compose.web.skiko
import androidx.compose.runtime.Composable
import androidx.compose.ui.window.ComposeCanvas
import kotlinx.browser.document
import org.jetbrains.compose.web.dom.ElementScope
import org.jetbrains.skiko.wasm.onWasmReady
import org.w3c.dom.HTMLCanvasElement
import org.w3c.dom.HTMLScriptElement
import kotlin.js.Promise
private class ScriptInserter() {
private val requested = mutableMapOf<String, Promise<String>>()
private fun attach(src: String, callback: () -> Unit) {
val script = document.createElement("script") as HTMLScriptElement
script.src = src
script.type = "text/javascript"
script.async = true
val root = document.documentElement?.firstChild
script.asDynamic().onerror = {
console.error("failed to attach script ${src}")
requested.remove(src)
}
script.onload = {
callback()
}
root?.appendChild(script)
}
fun load(src: String): Promise<String> {
return requested.getOrPut(src) {
Promise { resolve, reject ->
attach(src) {
resolve(src)
}
}
}
}
}
private val scriptInserter = ScriptInserter()
@Composable
fun ElementScope<HTMLCanvasElement>.skiko(block: @Composable () -> Unit) {
DomSideEffect { canvas ->
var skikoCanvas: ComposeCanvas? = null
scriptInserter.load("/skiko.js").then { src ->
onWasmReady {
var skikoCanvas: ComposeCanvas? = null
onWasmReady {
skikoCanvas = ComposeCanvas(canvas)
skikoCanvas?.setContent(block)
}
onWasmReady {
skikoCanvas = ComposeCanvas(canvas)
skikoCanvas?.setContent(block)
}
onDispose {
skikoCanvas?.dispose()
}
onDispose {
skikoCanvas?.dispose()
}
}
}
}
Loading…
Cancel
Save