diff --git a/filekit-core/src/jsMain/kotlin/io/github/vinceglb/filekit/FileKit.js.kt b/filekit-core/src/jsMain/kotlin/io/github/vinceglb/filekit/FileKit.js.kt index 4faa19cf3..a38403831 100644 --- a/filekit-core/src/jsMain/kotlin/io/github/vinceglb/filekit/FileKit.js.kt +++ b/filekit-core/src/jsMain/kotlin/io/github/vinceglb/filekit/FileKit.js.kt @@ -1,11 +1,8 @@ package io.github.vinceglb.filekit import io.github.vinceglb.filekit.utils.toBitsArray -import kotlinx.browser.document import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import org.w3c.dom.HTMLAnchorElement -import org.w3c.dom.url.URL import org.w3c.files.File public actual object FileKit @@ -26,11 +23,5 @@ public actual suspend fun FileKit.download( fileName = fileName, ) - // Create a element - val a = document.createElement("a") as HTMLAnchorElement - a.href = URL.createObjectURL(file) - a.download = fileName - - // Trigger the download - a.click() + downloadBlob(blob = file, fileName = fileName) } diff --git a/filekit-core/src/wasmJsMain/kotlin/io/github/vinceglb/filekit/FileKit.wasmJs.kt b/filekit-core/src/wasmJsMain/kotlin/io/github/vinceglb/filekit/FileKit.wasmJs.kt index caf03a4dc..743729078 100644 --- a/filekit-core/src/wasmJsMain/kotlin/io/github/vinceglb/filekit/FileKit.wasmJs.kt +++ b/filekit-core/src/wasmJsMain/kotlin/io/github/vinceglb/filekit/FileKit.wasmJs.kt @@ -1,11 +1,8 @@ package io.github.vinceglb.filekit import io.github.vinceglb.filekit.utils.toJsArray -import kotlinx.browser.document import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext -import org.w3c.dom.HTMLAnchorElement -import org.w3c.dom.url.URL import org.w3c.files.File public actual object FileKit @@ -27,11 +24,5 @@ public actual suspend fun FileKit.download( fileName = fileName, ) - // Create a element - val a = document.createElement("a") as HTMLAnchorElement - a.href = URL.createObjectURL(file) - a.download = fileName - - // Trigger the download - a.click() + downloadBlob(blob = file, fileName = fileName) } diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/BlobDownload.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/BlobDownload.web.kt new file mode 100644 index 000000000..045965768 --- /dev/null +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/BlobDownload.web.kt @@ -0,0 +1,51 @@ +package io.github.vinceglb.filekit + +import kotlinx.browser.document +import kotlinx.browser.window +import org.w3c.dom.HTMLAnchorElement +import org.w3c.dom.url.URL +import org.w3c.files.Blob +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds + +/** + * How long the object URL of a download stays alive after the download link is clicked. + * + * The click only starts the download. Some browsers (Firefox, older Safari) read the blob + * asynchronously afterwards, and revoking the URL too early makes the download fail. 40 seconds + * matches FileSaver.js, the reference implementation of this pattern. The cost is that the blob + * stays in memory for about 40 seconds after each download (longer if the browser throttles + * timers, for example in a background tab) instead of until the page unloads. + */ +internal val DOWNLOAD_OBJECT_URL_REVOKE_DELAY: Duration = 40.seconds + +/** + * Triggers a browser download of [blob] named [fileName] through a temporary object URL. + * + * The object URL is revoked after [revokeDelay], or right away if triggering the download throws. + */ +internal fun downloadBlob( + blob: Blob, + fileName: String, + revokeDelay: Duration = DOWNLOAD_OBJECT_URL_REVOKE_DELAY, +) { + val anchor = document.createElement("a") as HTMLAnchorElement + anchor.download = fileName + + val url = URL.createObjectURL(blob) + try { + anchor.href = url + anchor.click() + } catch (e: Throwable) { + URL.revokeObjectURL(url) + throw e + } + + window.setTimeout( + handler = { + URL.revokeObjectURL(url) + null + }, + timeout = revokeDelay.inWholeMilliseconds.toInt(), + ) +} diff --git a/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/FileKitDownloadWebTest.kt b/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/FileKitDownloadWebTest.kt new file mode 100644 index 000000000..aa0b842ea --- /dev/null +++ b/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/FileKitDownloadWebTest.kt @@ -0,0 +1,144 @@ +package io.github.vinceglb.filekit + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withContext +import org.w3c.files.Blob +import kotlin.js.ExperimentalWasmJsInterop +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFails +import kotlin.time.Duration +import kotlin.time.Duration.Companion.milliseconds + +class FileKitDownloadWebTest { + @BeforeTest + fun setUp() { + installObjectUrlProbe() + } + + @AfterTest + fun tearDown() { + uninstallObjectUrlProbe() + } + + @Test + fun downloadBlob_afterRevokeDelay_revokesEveryObjectUrl() = runTest { + repeat(3) { index -> + downloadBlob( + blob = Blob(), + fileName = "hello-$index.txt", + revokeDelay = 10.milliseconds, + ) + } + assertEquals(3, createdObjectUrlCount()) + + waitRealTime(200.milliseconds) + + assertEquals(0, activeObjectUrlCount()) + } + + @Test + fun download_afterClick_keepsObjectUrlAlive() = runTest { + FileKit.download( + bytes = "Hello, World!".encodeToByteArray(), + fileName = "hello.txt", + ) + assertEquals(1, createdObjectUrlCount()) + assertEquals(1, activeObjectUrlCount()) + + // Revoking right after the click can cancel the download in some browsers. + waitRealTime(200.milliseconds) + + assertEquals(1, activeObjectUrlCount()) + } + + @Test + fun downloadBlob_clickThrows_revokesObjectUrlAndRethrows() { + makeAnchorClickThrow() + try { + assertFails { + downloadBlob(blob = Blob(), fileName = "hello.txt") + } + } finally { + restoreAnchorClick() + } + + assertEquals(1, createdObjectUrlCount()) + assertEquals(0, activeObjectUrlCount()) + } +} + +// runTest skips delays in virtual time, so switch to a real dispatcher to let browser timers run. +private suspend fun waitRealTime(duration: Duration) { + withContext(Dispatchers.Default) { delay(duration) } +} + +// Wraps URL.createObjectURL and URL.revokeObjectURL to record every URL created and revoked. +@OptIn(ExperimentalWasmJsInterop::class) +private fun installObjectUrlProbe(): Unit = js( + """ + (() => { + const probe = { + created: [], + revoked: [], + originalCreate: URL.createObjectURL, + originalRevoke: URL.revokeObjectURL, + }; + URL.createObjectURL = function (obj) { + const url = probe.originalCreate.call(URL, obj); + probe.created.push(url); + return url; + }; + URL.revokeObjectURL = function (url) { + probe.revoked.push(url); + return probe.originalRevoke.call(URL, url); + }; + globalThis.filekitObjectUrlProbe = probe; + })() + """, +) + +@OptIn(ExperimentalWasmJsInterop::class) +private fun uninstallObjectUrlProbe(): Unit = js( + """ + (() => { + const probe = globalThis.filekitObjectUrlProbe; + if (probe) { + URL.createObjectURL = probe.originalCreate; + URL.revokeObjectURL = probe.originalRevoke; + delete globalThis.filekitObjectUrlProbe; + } + })() + """, +) + +@OptIn(ExperimentalWasmJsInterop::class) +private fun createdObjectUrlCount(): Int = js("globalThis.filekitObjectUrlProbe.created.length") + +@OptIn(ExperimentalWasmJsInterop::class) +private fun activeObjectUrlCount(): Int = js( + """ + globalThis.filekitObjectUrlProbe.created + .filter((url) => !globalThis.filekitObjectUrlProbe.revoked.includes(url)) + .length + """, +) + +// Shadows the inherited HTMLElement.prototype.click for anchors only. +@OptIn(ExperimentalWasmJsInterop::class) +private fun makeAnchorClickThrow(): Unit = js( + """ + (() => { + HTMLAnchorElement.prototype.click = function () { + throw new Error("click failed"); + }; + })() + """, +) + +@OptIn(ExperimentalWasmJsInterop::class) +private fun restoreAnchorClick(): Unit = js("(() => { delete HTMLAnchorElement.prototype.click; })()")