You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
2.3 KiB
60 lines
2.3 KiB
/* |
|
* Copyright 2020-2022 JetBrains s.r.o. and respective authors and developers. |
|
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. |
|
*/ |
|
|
|
package org.jetbrains.compose.resources |
|
|
|
import org.jetbrains.compose.resources.vector.xmldom.Element |
|
import org.jetbrains.compose.resources.vector.xmldom.ElementImpl |
|
import org.jetbrains.compose.resources.vector.xmldom.MalformedXMLException |
|
import org.khronos.webgl.ArrayBuffer |
|
import org.khronos.webgl.Int8Array |
|
import org.w3c.dom.parsing.DOMParser |
|
import org.w3c.xhr.ARRAYBUFFER |
|
import org.w3c.xhr.XMLHttpRequest |
|
import org.w3c.xhr.XMLHttpRequestResponseType |
|
import kotlin.coroutines.resume |
|
import kotlin.coroutines.resumeWithException |
|
import kotlin.coroutines.suspendCoroutine |
|
|
|
@ExperimentalResourceApi |
|
actual fun resource(path: String): Resource = JSResourceImpl(path) |
|
|
|
@ExperimentalResourceApi |
|
private class JSResourceImpl(path: String) : AbstractResourceImpl(path) { |
|
override suspend fun readBytes(): ByteArray { |
|
return suspendCoroutine { continuation -> |
|
val req = XMLHttpRequest() |
|
req.open("GET", "/$path", true) |
|
req.responseType = XMLHttpRequestResponseType.ARRAYBUFFER |
|
|
|
req.onload = { event -> |
|
val arrayBuffer = req.response |
|
if (arrayBuffer is ArrayBuffer) { |
|
continuation.resume(arrayBuffer.toByteArray()) |
|
} else { |
|
continuation.resumeWithException(MissingResourceException(path)) |
|
} |
|
} |
|
req.send(null) |
|
} |
|
} |
|
} |
|
|
|
private fun ArrayBuffer.toByteArray() = Int8Array(this, 0, byteLength).unsafeCast<ByteArray>() |
|
|
|
internal actual class MissingResourceException actual constructor(path: String) : |
|
Exception("Missing resource with path: $path") |
|
|
|
internal actual fun parseXML(byteArray: ByteArray): Element { |
|
val xmlString = byteArray.decodeToString() |
|
val xmlDom = DOMParser().parseFromString(xmlString, "application/xml") |
|
val domElement = xmlDom.documentElement ?: throw MalformedXMLException("missing documentElement") |
|
return ElementImpl(domElement) |
|
} |
|
|
|
internal actual fun isSyncResourceLoadingSupported() = false |
|
|
|
@OptIn(ExperimentalResourceApi::class) |
|
internal actual fun Resource.readBytesSync(): ByteArray = throw UnsupportedOperationException() |