package eu.friedcutlet.yokan.services.files import eu.friedcutlet.yokan.services.system.triggerBrowserDownload import kotlin.coroutines.resume import kotlinx.browser.document import kotlinx.coroutines.suspendCancellableCoroutine import org.khronos.webgl.ArrayBuffer import org.khronos.webgl.Uint8Array import org.khronos.webgl.get import org.w3c.dom.HTMLInputElement import org.w3c.files.FileReader // Browsers do not expose a user-visible folder picker. actual suspend fun pickFolder(initial: String?): String? = null @OptIn(kotlin.js.ExperimentalWasmJsInterop::class) actual suspend fun pickFile(extensions: List, initial: String?): String? { val body = document.body ?: return null val input = document.createElement("input") as HTMLInputElement input.type = "file" input.hidden = true input.accept = extensions .filter(String::isNotBlank) .joinToString(",") { if (it.startsWith(".")) it else ".$it" } body.appendChild(input) var selectedFileName = "" val file = suspendCancellableCoroutine { continuation -> val reader = FileReader() var finished = false fun cleanup() { input.onchange = null input.oncancel = null reader.onload = null reader.onerror = null reader.onabort = null input.remove() } fun finish(bytes: ByteArray?) { if (finished) return finished = true cleanup() if (continuation.isActive) continuation.resume(bytes) } input.onchange = { val selected = input.files?.item(0) if (selected == null) { finish(null) } else { selectedFileName = selected.name reader.onload = { val buffer = reader.result as? ArrayBuffer if (buffer == null) { finish(null) } else { val data = Uint8Array(buffer) finish(ByteArray(data.length) { data[it] }) } } reader.onerror = { finish(null) } reader.onabort = { finish(null) } reader.readAsArrayBuffer(selected) } } input.oncancel = { finish(null) } continuation.invokeOnCancellation { if (!finished) { finished = true cleanup() if (reader.readyState == FileReader.LOADING) reader.abort() } } input.click() } return file?.let { bytes -> WasmSelectedFileStore.put(bytes, selectedFileName) } } /** Exports route through the browser's download UI instead of a save dialog. */ actual suspend fun exportFile( bytes: ByteArray, suggestedName: String, mimeType: String, initial: String?, ): String? = if (triggerBrowserDownload(bytes, suggestedName, mimeType)) suggestedName else null