package eu.friedcutlet.yokan.services.system import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi /** * Hands [bytes] to the browser's download UI via a `Blob` object URL and a * synthetic anchor click. Bytes cross the JS boundary base64-encoded because * wasm `js()` parameters are limited to primitive/String types. */ @OptIn(ExperimentalEncodingApi::class) internal fun triggerBrowserDownload(bytes: ByteArray, fileName: String, mimeType: String): Boolean = runCatching { triggerBrowserDownloadJs(Base64.encode(bytes), fileName, mimeType) }.isSuccess @OptIn(kotlin.js.ExperimentalWasmJsInterop::class) private fun triggerBrowserDownloadJs(base64: String, fileName: String, mimeType: String) { js( """ { const binary = atob(base64); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); const blob = new Blob([bytes], { type: mimeType }); const url = URL.createObjectURL(blob); const anchor = document.createElement('a'); anchor.href = url; anchor.download = fileName; document.body.appendChild(anchor); anchor.click(); anchor.remove(); URL.revokeObjectURL(url); } """, ) }