Pickers.wasm.kt
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/files/Pickers.wasm.kt
1package eu.friedcutlet.yokan.services.files23import eu.friedcutlet.yokan.services.system.triggerBrowserDownload4import kotlin.coroutines.resume5import kotlinx.browser.document6import kotlinx.coroutines.suspendCancellableCoroutine7import org.khronos.webgl.ArrayBuffer8import org.khronos.webgl.Uint8Array9import org.khronos.webgl.get10import org.w3c.dom.HTMLInputElement11import org.w3c.files.FileReader1213// Browsers do not expose a user-visible folder picker.14actual suspend fun pickFolder(initial: String?): String? = null1516@OptIn(kotlin.js.ExperimentalWasmJsInterop::class)17actual suspend fun pickFile(extensions: List<String>, initial: String?): String? {18 val body = document.body ?: return null19 val input = document.createElement("input") as HTMLInputElement20 input.type = "file"21 input.hidden = true22 input.accept = extensions23 .filter(String::isNotBlank)24 .joinToString(",") { if (it.startsWith(".")) it else ".$it" }25 body.appendChild(input)2627 var selectedFileName = ""28 val file = suspendCancellableCoroutine<ByteArray?> { continuation ->29 val reader = FileReader()30 var finished = false3132 fun cleanup() {33 input.onchange = null34 input.oncancel = null35 reader.onload = null36 reader.onerror = null37 reader.onabort = null38 input.remove()39 }4041 fun finish(bytes: ByteArray?) {42 if (finished) return43 finished = true44 cleanup()45 if (continuation.isActive) continuation.resume(bytes)46 }4748 input.onchange = {49 val selected = input.files?.item(0)50 if (selected == null) {51 finish(null)52 } else {53 selectedFileName = selected.name54 reader.onload = {55 val buffer = reader.result as? ArrayBuffer56 if (buffer == null) {57 finish(null)58 } else {59 val data = Uint8Array(buffer)60 finish(ByteArray(data.length) { data[it] })61 }62 }63 reader.onerror = { finish(null) }64 reader.onabort = { finish(null) }65 reader.readAsArrayBuffer(selected)66 }67 }68 input.oncancel = { finish(null) }69 continuation.invokeOnCancellation {70 if (!finished) {71 finished = true72 cleanup()73 if (reader.readyState == FileReader.LOADING) reader.abort()74 }75 }76 input.click()77 }7879 return file?.let { bytes ->80 WasmSelectedFileStore.put(bytes, selectedFileName)81 }82}8384/** Exports route through the browser's download UI instead of a save dialog. */85actual suspend fun exportFile(86 bytes: ByteArray,87 suggestedName: String,88 mimeType: String,89 initial: String?,90): String? = if (triggerBrowserDownload(bytes, suggestedName, mimeType)) suggestedName else null91