From d1923b38b07d211eb449fb418fc07eb515f24393 Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Wed, 18 Nov 2026 10:09:53 +0800 Subject: [PATCH 1/9] =?UTF-8?q?=E2=9C=A8=20Added=20Web=20file-saving=20fun?= =?UTF-8?q?ctionality,=20supporting=20file=20writing=20and=20downloading?= =?UTF-8?q?=20via=20the=20Browser=20File=20System=20Access=20API.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../filekit/FileKitCoreInternalApi.kt | 13 +++++ .../filekit/OriginPrivateFileSystem.web.kt | 18 +++++- .../vinceglb/filekit/PlatformFile.web.kt | 34 +++++++++-- .../vinceglb/filekit/SaveDestination.web.kt | 26 +++++++++ .../io/github/vinceglb/filekit/WebFile.web.kt | 58 +++++++++++++++++++ .../filekit/OriginPrivateFileSystemTest.kt | 40 ++++++++++++- 6 files changed, 181 insertions(+), 8 deletions(-) create mode 100644 filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt create mode 100644 filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt diff --git a/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt b/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt new file mode 100644 index 00000000..ba9e2558 --- /dev/null +++ b/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt @@ -0,0 +1,13 @@ +package io.github.vinceglb.filekit + +/** + * Marks APIs used for coordination between FileKit modules. + * + * These APIs are public only because they cross module boundaries and may change without notice. + */ +@RequiresOptIn( + message = "This API is internal to FileKit modules and may change without notice.", + level = RequiresOptIn.Level.WARNING, +) +@Retention(AnnotationRetention.BINARY) +public annotation class FileKitCoreInternalApi \ No newline at end of file diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystem.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystem.web.kt index a525c598..ea85ee91 100644 --- a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystem.web.kt +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystem.web.kt @@ -170,13 +170,29 @@ private suspend fun WebFile.OriginPrivateDirectory.directory( */ @OptIn(ExperimentalWasmJsInterop::class) internal suspend fun WebFile.OriginPrivateFile.write(bytes: ByteArray) { + updateSnapshot(writeFile(handle, bytes)) +} + +@OptIn(ExperimentalWasmJsInterop::class) +internal suspend fun WebFile.SaveDestination.write(bytes: ByteArray) { + val fileHandle = handle + if (fileHandle == null) { + FileKit.download(bytes, name) + updateDownloaded(bytes) + } else { + updateSnapshot(writeFile(fileHandle, bytes)) + } +} + +@OptIn(ExperimentalWasmJsInterop::class) +private suspend fun writeFile(handle: FileSystemFileHandle, bytes: ByteArray): BrowserFile { val writable = handle.createWritable().await() try { writable.write(bytes.toWebBytes()).await() } finally { writable.close().await() } - updateSnapshot(handle.getFile().await()) + return handle.getFile().await() } @OptIn(ExperimentalWasmJsInterop::class) diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/PlatformFile.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/PlatformFile.web.kt index 31662a18..c91abb7f 100644 --- a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/PlatformFile.web.kt +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/PlatformFile.web.kt @@ -78,6 +78,7 @@ public actual val PlatformFile.name: String is WebFile.DirectoryWrapper -> file.name is WebFile.OriginPrivateFile -> file.name is WebFile.OriginPrivateDirectory -> file.name + is WebFile.SaveDestination -> file.name } public actual val PlatformFile.extension: String @@ -86,6 +87,7 @@ public actual val PlatformFile.extension: String is WebFile.DirectoryWrapper -> "" is WebFile.OriginPrivateFile -> name.substringAfterLast(".", "") is WebFile.OriginPrivateDirectory -> "" + is WebFile.SaveDestination -> name.substringAfterLast(".", "") } public actual val PlatformFile.nameWithoutExtension: String @@ -94,6 +96,7 @@ public actual val PlatformFile.nameWithoutExtension: String is WebFile.DirectoryWrapper -> name is WebFile.OriginPrivateFile -> name.substringBeforeLast(".", name) is WebFile.OriginPrivateDirectory -> name + is WebFile.SaveDestination -> name.substringBeforeLast(".", name) } public actual fun PlatformFile.size(): Long = when (val file = webFile) { @@ -101,6 +104,7 @@ public actual fun PlatformFile.size(): Long = when (val file = webFile) { is WebFile.DirectoryWrapper -> 0 is WebFile.OriginPrivateFile -> file.size is WebFile.OriginPrivateDirectory -> 0 + is WebFile.SaveDestination -> file.size } public actual val PlatformFile.path: String @@ -109,6 +113,7 @@ public actual val PlatformFile.path: String is WebFile.DirectoryWrapper -> file.path is WebFile.OriginPrivateFile -> file.path is WebFile.OriginPrivateDirectory -> file.path + is WebFile.SaveDestination -> file.name } public actual fun PlatformFile.mimeType(): MimeType? = when (val file = webFile) { @@ -131,6 +136,12 @@ public actual fun PlatformFile.mimeType(): MimeType? = when (val file = webFile) is WebFile.OriginPrivateDirectory -> { null } + + is WebFile.SaveDestination -> { + file.type + .takeIf { it.isNotBlank() } + ?.let { MimeType.parse(it) } + } } public actual fun PlatformFile.lastModified(): Instant = when (val file = webFile) { @@ -138,6 +149,7 @@ public actual fun PlatformFile.lastModified(): Instant = when (val file = webFil is WebFile.DirectoryWrapper -> file.lastModified is WebFile.OriginPrivateFile -> file.lastModified is WebFile.OriginPrivateDirectory -> WEB_DIRECTORY_LAST_MODIFIED + is WebFile.SaveDestination -> file.lastModified } public actual fun PlatformFile.parent(): PlatformFile? = when (val file = webFile) { @@ -145,10 +157,11 @@ public actual fun PlatformFile.parent(): PlatformFile? = when (val file = webFil is WebFile.DirectoryWrapper -> file.parent?.toPlatformFile() is WebFile.OriginPrivateFile -> file.parent?.toPlatformFile() is WebFile.OriginPrivateDirectory -> file.parent?.toPlatformFile() + is WebFile.SaveDestination -> null } public actual fun PlatformFile.isRegularFile(): Boolean = - webFile is WebFile.FileWrapper || webFile is WebFile.OriginPrivateFile + webFile is WebFile.FileWrapper || webFile is WebFile.OriginPrivateFile || webFile is WebFile.SaveDestination public actual fun PlatformFile.isDirectory(): Boolean = webFile is WebFile.DirectoryWrapper || webFile is WebFile.OriginPrivateDirectory @@ -170,6 +183,10 @@ public actual fun PlatformFile.list(): List = when (val file = web throw FileKitException("Cannot list a regular file") } + is WebFile.SaveDestination -> { + throw FileKitException("Cannot list a regular file") + } + is WebFile.OriginPrivateDirectory -> { throw FileKitException("Origin private file system directories must be listed with listEntries()") } @@ -196,6 +213,10 @@ public actual suspend fun PlatformFile.readBytes(): ByteArray = when (val file = .readBytes() } + is WebFile.SaveDestination -> { + file.readBytes() + } + is WebFile.OriginPrivateDirectory -> { throw FileKitException("Cannot read bytes from a directory") } @@ -209,7 +230,7 @@ public actual suspend fun PlatformFile.sizeRecursively(): Long = computeSizeRecu internal actual fun PlatformFile.isSymbolicLink(): Boolean = false @OptIn(ExperimentalWasmJsInterop::class) -private suspend fun BrowserFile.readBytes(): ByteArray = withContext(Dispatchers.Main) { +internal suspend fun BrowserFile.readBytes(): ByteArray = withContext(Dispatchers.Main) { suspendCancellableCoroutine { continuation -> val reader = FileReader() reader.onload = { event -> @@ -238,10 +259,10 @@ private suspend fun BrowserFile.readBytes(): ByteArray = withContext(Dispatchers } /** - * Replaces the contents of this origin private file system (OPFS) file with [bytes]. + * Replaces the contents of this OPFS file or web save destination with [bytes]. * - * Only files obtained from [FileKit.originPrivateDir] can be written. Files returned by - * browser pickers are read-only snapshots. + * Files obtained from [FileKit.originPrivateDir] and the web file saver can be written. Files + * returned by browser open-file pickers are read-only snapshots. * * @param bytes The bytes to write. */ @@ -249,7 +270,8 @@ private suspend fun BrowserFile.readBytes(): ByteArray = withContext(Dispatchers public suspend infix fun PlatformFile.write(bytes: ByteArray) { when (val file = webFile) { is WebFile.OriginPrivateFile -> file.write(bytes) - else -> throw FileKitException("Only origin private file system files can be written") + is WebFile.SaveDestination -> file.write(bytes) + else -> throw FileKitException("Only origin private file system files and save destinations can be written") } } diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt new file mode 100644 index 00000000..9b2d28c0 --- /dev/null +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt @@ -0,0 +1,26 @@ +@file:OptIn(ExperimentalFileKitApi::class) + +package io.github.vinceglb.filekit + +import kotlin.js.ExperimentalWasmJsInterop +import kotlin.js.JsAny +import kotlin.js.unsafeCast + +/** + * Creates a web save destination for use by FileKit modules. + * + * This is public only to allow `filekit-dialogs` to pass the browser's opaque file handle to core. + * Applications should obtain save destinations through the dialogs API. + * + * @param handle The `FileSystemFileHandle`, or `null` to use browser download behavior. + * @param name The suggested file name. + */ +@FileKitCoreInternalApi +@OptIn(ExperimentalWasmJsInterop::class) +public fun createSaveDestination(handle: JsAny?, name: String): PlatformFile = + PlatformFile( + WebFile.SaveDestination( + handle = handle?.unsafeCast(), + name = name, + ), + ) \ No newline at end of file diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt index 77e7a0c5..6eafa257 100644 --- a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt @@ -3,6 +3,7 @@ package io.github.vinceglb.filekit import kotlinx.coroutines.await import kotlin.js.ExperimentalWasmJsInterop import kotlin.js.toDouble +import kotlin.js.unsafeCast import kotlin.time.Instant /** @@ -109,6 +110,63 @@ public sealed class WebFile { override fun hashCode(): Int = path.hashCode() } + + /** + * A destination returned by the web file saver. + * + * When the browser supports the File System Access API, writes go to [handle]. Otherwise, + * writes trigger a browser download and remain readable from this instance. + */ + @ExperimentalFileKitApi + @OptIn(ExperimentalWasmJsInterop::class) + public class SaveDestination internal constructor( + internal val handle: FileSystemFileHandle?, + public val name: String, + ) : WebFile() { + private var fileSnapshot: BrowserFile? = null + private var downloadedBytes: ByteArray? = null + + public val isDownload: Boolean + get() = handle == null + + public val type: String + get() = fileSnapshot?.type.orEmpty() + + public val size: Long + get() = fileSnapshot?.size?.toDouble()?.toLong() ?: downloadedBytes?.size?.toLong() ?: 0 + + @Suppress("REDUNDANT_CALL_OF_CONVERSION_METHOD") + public val lastModified: Instant + get() = fileSnapshot?.lastModified + ?.toDouble() + ?.toLong() + ?.let(Instant::fromEpochMilliseconds) + ?: WEB_DIRECTORY_LAST_MODIFIED + + internal fun updateSnapshot(fileSnapshot: BrowserFile) { + this.fileSnapshot = fileSnapshot + downloadedBytes = null + } + + internal fun updateDownloaded(bytes: ByteArray) { + downloadedBytes = bytes.copyOf() + fileSnapshot = BrowserFile( + fileBits = listOf(bytes.toWebBytes()).toJsArray(), + fileName = name, + options = filePropertyBag(type = ""), + ) + } + + internal suspend fun readBytes(): ByteArray { + val fileHandle = handle + if (fileHandle != null) { + val file = fileHandle.getFile().await() + updateSnapshot(file) + return file.readBytes() + } + return downloadedBytes?.copyOf() ?: ByteArray(0) + } + } } internal val WEB_DIRECTORY_LAST_MODIFIED: Instant = Instant.fromEpochMilliseconds(0) diff --git a/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystemTest.kt b/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystemTest.kt index ddf6f840..f410e9a9 100644 --- a/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystemTest.kt +++ b/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystemTest.kt @@ -1,5 +1,9 @@ @file:Suppress("ktlint:standard:function-naming", "TestFunctionName") -@file:OptIn(ExperimentalFileKitApi::class) +@file:OptIn( + ExperimentalFileKitApi::class, + FileKitCoreInternalApi::class, + kotlin.js.ExperimentalWasmJsInterop::class, +) package io.github.vinceglb.filekit @@ -56,6 +60,40 @@ class OriginPrivateFileSystemTest { } } + @Test + fun PlatformFile_writeSaveDestinationWithoutHandle_downloadsAndKeepsLastContentReadable() = runTest { + val destination = createSaveDestination(handle = null, name = "report.txt") + + assertTrue(destination.isRegularFile()) + assertFalse(destination.isDirectory()) + assertNull(destination.parent()) + assertTrue(destination.readBytes().isEmpty()) + + destination.writeString("Saved content") + + assertEquals("Saved content", destination.readString()) + assertEquals(13L, destination.size()) + assertTrue(destination.lastModified() > Instant.fromEpochMilliseconds(0)) + } + + @Test + fun PlatformFile_writeSaveDestinationWithHandle_updatesContentAndMetadata() = runTest { + val directory = createTestDirectory("save-destination") + try { + val selectedFile = directory.resolveFile("report.txt", create = true) + val handle = (selectedFile.webFile as WebFile.OriginPrivateFile).handle + val destination = createSaveDestination(handle = handle, name = selectedFile.name) + + destination.writeString("Saved content") + + assertEquals("Saved content", destination.readString()) + assertEquals(13L, destination.size()) + assertTrue(destination.lastModified() > Instant.fromEpochMilliseconds(0)) + } finally { + directory.delete(recursively = true) + } + } + @Test fun PlatformFile_resolveFile_nestedPathWithCreate_createsParentDirectories() = runTest { val directory = createTestDirectory("nested") From b3d9d97c75b2c5fc17a22e1e341b99e0aa95dd32 Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Wed, 18 Nov 2026 10:09:53 +0800 Subject: [PATCH 2/9] =?UTF-8?q?=E2=9C=A8=20Added=20Web=20file-saving=20fun?= =?UTF-8?q?ctionality,=20supporting=20file=20writing=20and=20downloading?= =?UTF-8?q?=20via=20the=20Browser=20File=20System=20Access=20API.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../filekit/FileKitCoreInternalApi.kt | 13 +++++ .../filekit/OriginPrivateFileSystem.web.kt | 18 +++++- .../vinceglb/filekit/PlatformFile.web.kt | 34 +++++++++-- .../vinceglb/filekit/SaveDestination.web.kt | 26 +++++++++ .../io/github/vinceglb/filekit/WebFile.web.kt | 58 +++++++++++++++++++ .../filekit/OriginPrivateFileSystemTest.kt | 40 ++++++++++++- 6 files changed, 181 insertions(+), 8 deletions(-) create mode 100644 filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt create mode 100644 filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt diff --git a/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt b/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt new file mode 100644 index 00000000..ba9e2558 --- /dev/null +++ b/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt @@ -0,0 +1,13 @@ +package io.github.vinceglb.filekit + +/** + * Marks APIs used for coordination between FileKit modules. + * + * These APIs are public only because they cross module boundaries and may change without notice. + */ +@RequiresOptIn( + message = "This API is internal to FileKit modules and may change without notice.", + level = RequiresOptIn.Level.WARNING, +) +@Retention(AnnotationRetention.BINARY) +public annotation class FileKitCoreInternalApi \ No newline at end of file diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystem.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystem.web.kt index a525c598..ea85ee91 100644 --- a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystem.web.kt +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystem.web.kt @@ -170,13 +170,29 @@ private suspend fun WebFile.OriginPrivateDirectory.directory( */ @OptIn(ExperimentalWasmJsInterop::class) internal suspend fun WebFile.OriginPrivateFile.write(bytes: ByteArray) { + updateSnapshot(writeFile(handle, bytes)) +} + +@OptIn(ExperimentalWasmJsInterop::class) +internal suspend fun WebFile.SaveDestination.write(bytes: ByteArray) { + val fileHandle = handle + if (fileHandle == null) { + FileKit.download(bytes, name) + updateDownloaded(bytes) + } else { + updateSnapshot(writeFile(fileHandle, bytes)) + } +} + +@OptIn(ExperimentalWasmJsInterop::class) +private suspend fun writeFile(handle: FileSystemFileHandle, bytes: ByteArray): BrowserFile { val writable = handle.createWritable().await() try { writable.write(bytes.toWebBytes()).await() } finally { writable.close().await() } - updateSnapshot(handle.getFile().await()) + return handle.getFile().await() } @OptIn(ExperimentalWasmJsInterop::class) diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/PlatformFile.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/PlatformFile.web.kt index 31662a18..c91abb7f 100644 --- a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/PlatformFile.web.kt +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/PlatformFile.web.kt @@ -78,6 +78,7 @@ public actual val PlatformFile.name: String is WebFile.DirectoryWrapper -> file.name is WebFile.OriginPrivateFile -> file.name is WebFile.OriginPrivateDirectory -> file.name + is WebFile.SaveDestination -> file.name } public actual val PlatformFile.extension: String @@ -86,6 +87,7 @@ public actual val PlatformFile.extension: String is WebFile.DirectoryWrapper -> "" is WebFile.OriginPrivateFile -> name.substringAfterLast(".", "") is WebFile.OriginPrivateDirectory -> "" + is WebFile.SaveDestination -> name.substringAfterLast(".", "") } public actual val PlatformFile.nameWithoutExtension: String @@ -94,6 +96,7 @@ public actual val PlatformFile.nameWithoutExtension: String is WebFile.DirectoryWrapper -> name is WebFile.OriginPrivateFile -> name.substringBeforeLast(".", name) is WebFile.OriginPrivateDirectory -> name + is WebFile.SaveDestination -> name.substringBeforeLast(".", name) } public actual fun PlatformFile.size(): Long = when (val file = webFile) { @@ -101,6 +104,7 @@ public actual fun PlatformFile.size(): Long = when (val file = webFile) { is WebFile.DirectoryWrapper -> 0 is WebFile.OriginPrivateFile -> file.size is WebFile.OriginPrivateDirectory -> 0 + is WebFile.SaveDestination -> file.size } public actual val PlatformFile.path: String @@ -109,6 +113,7 @@ public actual val PlatformFile.path: String is WebFile.DirectoryWrapper -> file.path is WebFile.OriginPrivateFile -> file.path is WebFile.OriginPrivateDirectory -> file.path + is WebFile.SaveDestination -> file.name } public actual fun PlatformFile.mimeType(): MimeType? = when (val file = webFile) { @@ -131,6 +136,12 @@ public actual fun PlatformFile.mimeType(): MimeType? = when (val file = webFile) is WebFile.OriginPrivateDirectory -> { null } + + is WebFile.SaveDestination -> { + file.type + .takeIf { it.isNotBlank() } + ?.let { MimeType.parse(it) } + } } public actual fun PlatformFile.lastModified(): Instant = when (val file = webFile) { @@ -138,6 +149,7 @@ public actual fun PlatformFile.lastModified(): Instant = when (val file = webFil is WebFile.DirectoryWrapper -> file.lastModified is WebFile.OriginPrivateFile -> file.lastModified is WebFile.OriginPrivateDirectory -> WEB_DIRECTORY_LAST_MODIFIED + is WebFile.SaveDestination -> file.lastModified } public actual fun PlatformFile.parent(): PlatformFile? = when (val file = webFile) { @@ -145,10 +157,11 @@ public actual fun PlatformFile.parent(): PlatformFile? = when (val file = webFil is WebFile.DirectoryWrapper -> file.parent?.toPlatformFile() is WebFile.OriginPrivateFile -> file.parent?.toPlatformFile() is WebFile.OriginPrivateDirectory -> file.parent?.toPlatformFile() + is WebFile.SaveDestination -> null } public actual fun PlatformFile.isRegularFile(): Boolean = - webFile is WebFile.FileWrapper || webFile is WebFile.OriginPrivateFile + webFile is WebFile.FileWrapper || webFile is WebFile.OriginPrivateFile || webFile is WebFile.SaveDestination public actual fun PlatformFile.isDirectory(): Boolean = webFile is WebFile.DirectoryWrapper || webFile is WebFile.OriginPrivateDirectory @@ -170,6 +183,10 @@ public actual fun PlatformFile.list(): List = when (val file = web throw FileKitException("Cannot list a regular file") } + is WebFile.SaveDestination -> { + throw FileKitException("Cannot list a regular file") + } + is WebFile.OriginPrivateDirectory -> { throw FileKitException("Origin private file system directories must be listed with listEntries()") } @@ -196,6 +213,10 @@ public actual suspend fun PlatformFile.readBytes(): ByteArray = when (val file = .readBytes() } + is WebFile.SaveDestination -> { + file.readBytes() + } + is WebFile.OriginPrivateDirectory -> { throw FileKitException("Cannot read bytes from a directory") } @@ -209,7 +230,7 @@ public actual suspend fun PlatformFile.sizeRecursively(): Long = computeSizeRecu internal actual fun PlatformFile.isSymbolicLink(): Boolean = false @OptIn(ExperimentalWasmJsInterop::class) -private suspend fun BrowserFile.readBytes(): ByteArray = withContext(Dispatchers.Main) { +internal suspend fun BrowserFile.readBytes(): ByteArray = withContext(Dispatchers.Main) { suspendCancellableCoroutine { continuation -> val reader = FileReader() reader.onload = { event -> @@ -238,10 +259,10 @@ private suspend fun BrowserFile.readBytes(): ByteArray = withContext(Dispatchers } /** - * Replaces the contents of this origin private file system (OPFS) file with [bytes]. + * Replaces the contents of this OPFS file or web save destination with [bytes]. * - * Only files obtained from [FileKit.originPrivateDir] can be written. Files returned by - * browser pickers are read-only snapshots. + * Files obtained from [FileKit.originPrivateDir] and the web file saver can be written. Files + * returned by browser open-file pickers are read-only snapshots. * * @param bytes The bytes to write. */ @@ -249,7 +270,8 @@ private suspend fun BrowserFile.readBytes(): ByteArray = withContext(Dispatchers public suspend infix fun PlatformFile.write(bytes: ByteArray) { when (val file = webFile) { is WebFile.OriginPrivateFile -> file.write(bytes) - else -> throw FileKitException("Only origin private file system files can be written") + is WebFile.SaveDestination -> file.write(bytes) + else -> throw FileKitException("Only origin private file system files and save destinations can be written") } } diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt new file mode 100644 index 00000000..9b2d28c0 --- /dev/null +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt @@ -0,0 +1,26 @@ +@file:OptIn(ExperimentalFileKitApi::class) + +package io.github.vinceglb.filekit + +import kotlin.js.ExperimentalWasmJsInterop +import kotlin.js.JsAny +import kotlin.js.unsafeCast + +/** + * Creates a web save destination for use by FileKit modules. + * + * This is public only to allow `filekit-dialogs` to pass the browser's opaque file handle to core. + * Applications should obtain save destinations through the dialogs API. + * + * @param handle The `FileSystemFileHandle`, or `null` to use browser download behavior. + * @param name The suggested file name. + */ +@FileKitCoreInternalApi +@OptIn(ExperimentalWasmJsInterop::class) +public fun createSaveDestination(handle: JsAny?, name: String): PlatformFile = + PlatformFile( + WebFile.SaveDestination( + handle = handle?.unsafeCast(), + name = name, + ), + ) \ No newline at end of file diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt index 77e7a0c5..6eafa257 100644 --- a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt @@ -3,6 +3,7 @@ package io.github.vinceglb.filekit import kotlinx.coroutines.await import kotlin.js.ExperimentalWasmJsInterop import kotlin.js.toDouble +import kotlin.js.unsafeCast import kotlin.time.Instant /** @@ -109,6 +110,63 @@ public sealed class WebFile { override fun hashCode(): Int = path.hashCode() } + + /** + * A destination returned by the web file saver. + * + * When the browser supports the File System Access API, writes go to [handle]. Otherwise, + * writes trigger a browser download and remain readable from this instance. + */ + @ExperimentalFileKitApi + @OptIn(ExperimentalWasmJsInterop::class) + public class SaveDestination internal constructor( + internal val handle: FileSystemFileHandle?, + public val name: String, + ) : WebFile() { + private var fileSnapshot: BrowserFile? = null + private var downloadedBytes: ByteArray? = null + + public val isDownload: Boolean + get() = handle == null + + public val type: String + get() = fileSnapshot?.type.orEmpty() + + public val size: Long + get() = fileSnapshot?.size?.toDouble()?.toLong() ?: downloadedBytes?.size?.toLong() ?: 0 + + @Suppress("REDUNDANT_CALL_OF_CONVERSION_METHOD") + public val lastModified: Instant + get() = fileSnapshot?.lastModified + ?.toDouble() + ?.toLong() + ?.let(Instant::fromEpochMilliseconds) + ?: WEB_DIRECTORY_LAST_MODIFIED + + internal fun updateSnapshot(fileSnapshot: BrowserFile) { + this.fileSnapshot = fileSnapshot + downloadedBytes = null + } + + internal fun updateDownloaded(bytes: ByteArray) { + downloadedBytes = bytes.copyOf() + fileSnapshot = BrowserFile( + fileBits = listOf(bytes.toWebBytes()).toJsArray(), + fileName = name, + options = filePropertyBag(type = ""), + ) + } + + internal suspend fun readBytes(): ByteArray { + val fileHandle = handle + if (fileHandle != null) { + val file = fileHandle.getFile().await() + updateSnapshot(file) + return file.readBytes() + } + return downloadedBytes?.copyOf() ?: ByteArray(0) + } + } } internal val WEB_DIRECTORY_LAST_MODIFIED: Instant = Instant.fromEpochMilliseconds(0) diff --git a/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystemTest.kt b/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystemTest.kt index ddf6f840..f410e9a9 100644 --- a/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystemTest.kt +++ b/filekit-core/src/webTest/kotlin/io/github/vinceglb/filekit/OriginPrivateFileSystemTest.kt @@ -1,5 +1,9 @@ @file:Suppress("ktlint:standard:function-naming", "TestFunctionName") -@file:OptIn(ExperimentalFileKitApi::class) +@file:OptIn( + ExperimentalFileKitApi::class, + FileKitCoreInternalApi::class, + kotlin.js.ExperimentalWasmJsInterop::class, +) package io.github.vinceglb.filekit @@ -56,6 +60,40 @@ class OriginPrivateFileSystemTest { } } + @Test + fun PlatformFile_writeSaveDestinationWithoutHandle_downloadsAndKeepsLastContentReadable() = runTest { + val destination = createSaveDestination(handle = null, name = "report.txt") + + assertTrue(destination.isRegularFile()) + assertFalse(destination.isDirectory()) + assertNull(destination.parent()) + assertTrue(destination.readBytes().isEmpty()) + + destination.writeString("Saved content") + + assertEquals("Saved content", destination.readString()) + assertEquals(13L, destination.size()) + assertTrue(destination.lastModified() > Instant.fromEpochMilliseconds(0)) + } + + @Test + fun PlatformFile_writeSaveDestinationWithHandle_updatesContentAndMetadata() = runTest { + val directory = createTestDirectory("save-destination") + try { + val selectedFile = directory.resolveFile("report.txt", create = true) + val handle = (selectedFile.webFile as WebFile.OriginPrivateFile).handle + val destination = createSaveDestination(handle = handle, name = selectedFile.name) + + destination.writeString("Saved content") + + assertEquals("Saved content", destination.readString()) + assertEquals(13L, destination.size()) + assertTrue(destination.lastModified() > Instant.fromEpochMilliseconds(0)) + } finally { + directory.delete(recursively = true) + } + } + @Test fun PlatformFile_resolveFile_nestedPathWithCreate_createsParentDirectories() = runTest { val directory = createTestDirectory("nested") From 10d9dcce20ce4513d800fd324972011907b8fedc Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Wed, 18 Nov 2026 10:26:17 +0800 Subject: [PATCH 3/9] =?UTF-8?q?=E2=9C=A8=20Implement=20file=20saving=20fun?= =?UTF-8?q?ctionality=20in=20the=20browser?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vinceglb/filekit/dialogs/FileSaver.web.kt | 143 ++++++++++++++++++ 1 file changed, 143 insertions(+) create mode 100644 filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt diff --git a/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt new file mode 100644 index 00000000..2876ef2f --- /dev/null +++ b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt @@ -0,0 +1,143 @@ +@file:OptIn(ExperimentalFileKitApi::class) + +package io.github.vinceglb.filekit.dialogs + +import io.github.vinceglb.filekit.ExperimentalFileKitApi +import io.github.vinceglb.filekit.FileKit +import io.github.vinceglb.filekit.FileKitCoreInternalApi +import io.github.vinceglb.filekit.PlatformFile +import io.github.vinceglb.filekit.createSaveDestination +import kotlinx.coroutines.await +import kotlin.js.ExperimentalWasmJsInterop +import kotlin.js.JsAny +import kotlin.js.Promise + +/** + * Opens a browser save picker when the File System Access API is available. + * + * Browsers without the API, and cross-origin frames where the browser denies access to it, use + * download behavior when the returned file is written. [directory] and [dialogSettings] are ignored + * on web. The picker must be called during a user activation, such as directly from a click handler. + * + * @param suggestedName The suggested file name without the default extension. + * @param defaultExtension The default file extension without the dot. + * @param allowedExtensions The file extensions offered by the save picker, without dots. + * @param directory Ignored on web. + * @param dialogSettings Ignored on web. + * @return The selected save destination, or `null` if the user cancelled. + * @throws FileKitDialogException If the picker is rejected for a reason other than cancellation. + */ +@OptIn(ExperimentalWasmJsInterop::class, FileKitCoreInternalApi::class) +@Suppress("UNUSED_PARAMETER") +@ExperimentalFileKitApi +public suspend fun FileKit.openFileSaver( + suggestedName: String, + defaultExtension: String? = null, + allowedExtensions: Set? = null, + directory: PlatformFile? = null, + dialogSettings: FileKitDialogSettings = FileKitDialogSettings.createDefault(), +): PlatformFile? { + val fileName = buildFileSaverSuggestedName(suggestedName, defaultExtension) + val extensions = buildFileSaverAllowedFileTypes(defaultExtension, allowedExtensions) + ?.joinToString(separator = "\u0000") + .orEmpty() + val result = invokeBrowserSavePicker(fileName, extensions).await() + + return when (result.kind) { + "unsupported" -> createSaveDestination(handle = null, name = fileName) + "selected" -> createSaveDestination(handle = result.handle, name = fileName) + "error" -> { + if (result.errorName == "AbortError") { + null + } else { + throw FileKitDialogException( + "Could not open the web file saver (${result.errorName}): ${result.errorMessage}", + ) + } + } + + else -> throw FileKitDialogException("The browser returned an unknown file saver result") + } +} + +@OptIn(ExperimentalWasmJsInterop::class) +private external interface BrowserSavePickerResult : JsAny { + val kind: String + val handle: JsAny? + val errorName: String + val errorMessage: String +} + +/** + * Calls the API before returning its promise so the call remains within the caller's user activation. + * Feature detection and both synchronous and asynchronous error handling stay in this JS boundary. + */ +@OptIn(ExperimentalWasmJsInterop::class) +private fun invokeBrowserSavePicker( + suggestedName: String, + extensions: String, +): Promise = js( + """ + (function(suggestedName, extensionList) { + let crossOriginFrame = false; + let hasUserActivation = true; + const handleError = function(error) { + const errorName = String(error && error.name || "Error"); + const errorMessage = String(error && error.message || error || "Unknown error"); + if (errorName === "SecurityError" && crossOriginFrame && hasUserActivation) { + return { kind: "unsupported" }; + } + return { kind: "error", errorName: errorName, errorMessage: errorMessage }; + }; + + try { + const api = globalThis.showSaveFilePicker; + if (typeof api !== "function") { + return Promise.resolve({ kind: "unsupported" }); + } + + try { + crossOriginFrame = window.self !== window.top && + window.parent.location.origin !== window.location.origin; + } catch (_) { + crossOriginFrame = true; + } + + const userActivation = navigator.userActivation; + hasUserActivation = userActivation == null || userActivation.isActive; + const options = { suggestedName: suggestedName }; + const extensions = extensionList ? extensionList.split("\u0000") : []; + + if (extensions.length > 0) { + const mimeByExtension = Object.assign(Object.create(null), { + txt: "text/plain", text: "text/plain", csv: "text/csv", tsv: "text/tab-separated-values", + html: "text/html", htm: "text/html", css: "text/css", xml: "application/xml", + json: "application/json", pdf: "application/pdf", md: "text/markdown", + png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", + svg: "image/svg+xml", webp: "image/webp", bmp: "image/bmp", ico: "image/x-icon", + mp3: "audio/mpeg", wav: "audio/wav", mp4: "video/mp4", webm: "video/webm", + zip: "application/zip", gz: "application/gzip", tar: "application/x-tar", + doc: "application/msword", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + xls: "application/vnd.ms-excel", xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ppt: "application/vnd.ms-powerpoint", pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation" + }); + const accept = {}; + for (const extension of extensions) { + const key = extension.toLowerCase(); + const mime = mimeByExtension[key] || "application/octet-stream"; + if (!accept[mime]) accept[mime] = []; + accept[mime].push("." + extension); + } + options.types = [{ description: "Files", accept: accept }]; + } + + return Promise.resolve(api.call(globalThis, options)).then( + function(handle) { return { kind: "selected", handle: handle }; }, + handleError + ); + } catch (error) { + return Promise.resolve(handleError(error)); + } + })(suggestedName, extensions) + """, +) From abd6532d3bdeb20be69bd9f51bc6def319ce2d92 Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Wed, 18 Nov 2026 10:44:35 +0800 Subject: [PATCH 4/9] =?UTF-8?q?=E2=9C=A8=20Enhance=20file=20saving=20funct?= =?UTF-8?q?ionality=20with=20browser=20save=20picker=20test=20overrides=20?= =?UTF-8?q?and=20add=20unit=20tests=20for=20various=20scenarios.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vinceglb/filekit/dialogs/FileSaver.web.kt | 17 ++- .../filekit/dialogs/FileSaverWebTest.kt | 141 ++++++++++++++++++ 2 files changed, 153 insertions(+), 5 deletions(-) create mode 100644 filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt diff --git a/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt index 2876ef2f..8d5c0168 100644 --- a/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt +++ b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt @@ -41,7 +41,7 @@ public suspend fun FileKit.openFileSaver( val extensions = buildFileSaverAllowedFileTypes(defaultExtension, allowedExtensions) ?.joinToString(separator = "\u0000") .orEmpty() - val result = invokeBrowserSavePicker(fileName, extensions).await() + val result = invokeBrowserSavePicker(fileName, extensions, browserSavePickerTestOverride).await() return when (result.kind) { "unsupported" -> createSaveDestination(handle = null, name = fileName) @@ -68,6 +68,10 @@ private external interface BrowserSavePickerResult : JsAny { val errorMessage: String } +/** Optional picker replacement used by shared web tests. */ +@OptIn(ExperimentalWasmJsInterop::class) +internal var browserSavePickerTestOverride: JsAny? = null + /** * Calls the API before returning its promise so the call remains within the caller's user activation. * Feature detection and both synchronous and asynchronous error handling stay in this JS boundary. @@ -75,10 +79,11 @@ private external interface BrowserSavePickerResult : JsAny { @OptIn(ExperimentalWasmJsInterop::class) private fun invokeBrowserSavePicker( suggestedName: String, - extensions: String, + extensionList: String, + testOverride: JsAny?, ): Promise = js( """ - (function(suggestedName, extensionList) { + { let crossOriginFrame = false; let hasUserActivation = true; const handleError = function(error) { @@ -91,7 +96,9 @@ private fun invokeBrowserSavePicker( }; try { - const api = globalThis.showSaveFilePicker; + const api = testOverride === null + ? globalThis.showSaveFilePicker + : (testOverride.available ? testOverride.picker : null); if (typeof api !== "function") { return Promise.resolve({ kind: "unsupported" }); } @@ -138,6 +145,6 @@ private fun invokeBrowserSavePicker( } catch (error) { return Promise.resolve(handleError(error)); } - })(suggestedName, extensions) + } """, ) diff --git a/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt new file mode 100644 index 00000000..69624821 --- /dev/null +++ b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt @@ -0,0 +1,141 @@ +@file:OptIn( + ExperimentalFileKitApi::class, + kotlin.js.ExperimentalWasmJsInterop::class, +) + +package io.github.vinceglb.filekit.dialogs + +import io.github.vinceglb.filekit.ExperimentalFileKitApi +import io.github.vinceglb.filekit.FileKit +import io.github.vinceglb.filekit.WebFile +import io.github.vinceglb.filekit.name +import kotlinx.coroutines.test.runTest +import kotlin.js.JsAny +import kotlin.test.Test +import kotlin.test.assertContains +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +private fun unavailablePickerOverride(): JsAny = js("({ available: false })") + +private fun cancelledPickerOverride(): JsAny = js( + "({ available: true, picker: function(options) { globalThis.__filekitSavePickerOptions = options; " + + "return Promise.reject(new DOMException('cancelled', 'AbortError')); } })", +) + +private fun failedPickerOverride(): JsAny = js( + "({ available: true, picker: function(options) { globalThis.__filekitSavePickerOptions = options; " + + "return Promise.reject(new Error('picker failed')); } })", +) + +private fun synchronousFailurePickerOverride(): JsAny = js( + "({ available: true, picker: function(options) { globalThis.__filekitSavePickerOptions = options; " + + "throw new Error('synchronous picker failure'); } })", +) + +private fun selectedPickerOverride(): JsAny = js( + "({ available: true, picker: function(options) { globalThis.__filekitSavePickerOptions = options; " + + "return Promise.resolve({ name: 'selected.txt' }); } })", +) + +private fun lastPickerSuggestedName(): String = + js("globalThis.__filekitSavePickerOptions.suggestedName") + +private fun lastPickerTypesJson(): String = + js("JSON.stringify(globalThis.__filekitSavePickerOptions.types)") + +private fun hasPickerTypes(): Boolean = + js("globalThis.__filekitSavePickerOptions.types !== undefined") + +class FileSaverWebTest { + @Test + fun openFileSaver_whenPickerUnavailable_returnsDownloadDestination() = runTest { + withPickerOverride(unavailablePickerOverride()) { + val file = FileKit.openFileSaver( + suggestedName = "report", + defaultExtension = ".pdf", + ) + + assertEquals("report.pdf", file?.name) + assertTrue((file?.webFile as? WebFile.SaveDestination)?.isDownload == true) + } + } + + @Test + fun openFileSaver_whenCancelled_returnsNull() = runTest { + withPickerOverride(cancelledPickerOverride()) { + assertNull(FileKit.openFileSaver(suggestedName = "report")) + } + } + + @Test + fun openFileSaver_whenPickerFails_throwsDialogException() = runTest { + withPickerOverride(failedPickerOverride()) { + val error = assertFailsWith { + FileKit.openFileSaver(suggestedName = "report") + } + + assertContains(error.message.orEmpty(), "picker failed") + } + } + + @Test + fun openFileSaver_whenPickerThrowsSynchronously_throwsDialogException() = runTest { + withPickerOverride(synchronousFailurePickerOverride()) { + val error = assertFailsWith { + FileKit.openFileSaver(suggestedName = "report") + } + + assertContains(error.message.orEmpty(), "synchronous picker failure") + } + } + + @Test + fun openFileSaver_whenFileIsSelected_returnsHandleDestinationAndExpectedOptions() = runTest { + withPickerOverride(selectedPickerOverride()) { + val file = FileKit.openFileSaver( + suggestedName = "report", + defaultExtension = "pdf", + allowedExtensions = setOf("txt", ".pdf"), + ) + val selectedFile = assertNotNull(file) + val destination = assertIs(selectedFile.webFile) + + assertEquals("report.pdf", selectedFile.name) + assertEquals(false, destination.isDownload) + assertEquals("report.pdf", lastPickerSuggestedName()) + assertEquals( + """[{"description":"Files","accept":{"application/pdf":[".pdf"],"text/plain":[".txt"]}}]""", + lastPickerTypesJson(), + ) + } + } + + @Test + fun openFileSaver_withoutExtensions_omitsPickerTypes() = runTest { + withPickerOverride(selectedPickerOverride()) { + FileKit.openFileSaver(suggestedName = "notes") + + assertEquals("notes", lastPickerSuggestedName()) + assertFalse(hasPickerTypes()) + } + } + + private suspend fun withPickerOverride( + override: JsAny, + block: suspend () -> Unit, + ) { + val previous = browserSavePickerTestOverride + browserSavePickerTestOverride = override + try { + block() + } finally { + browserSavePickerTestOverride = previous + } + } +} From 5048235fcfe9dff6a63c1af9577ca09906046d78 Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Wed, 18 Nov 2026 11:08:10 +0800 Subject: [PATCH 5/9] =?UTF-8?q?=E2=9C=A8=20Refactor=20file=20saver=20imple?= =?UTF-8?q?mentation=20for=20improved=20readability=20and=20structure;=20e?= =?UTF-8?q?nhance=20support=20message=20for=20web=20file=20saving.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../filekit/FileKitCoreInternalApi.kt | 2 +- .../vinceglb/filekit/SaveDestination.web.kt | 2 +- .../io/github/vinceglb/filekit/WebFile.web.kt | 3 +- .../vinceglb/filekit/dialogs/FileSaver.web.kt | 14 ++++- .../filekit/dialogs/FileSaverWebTest.kt | 2 +- .../ui/screens/filesaver/FileSaverLauncher.kt | 4 ++ .../ui/screens/filesaver/FileSaverScreen.kt | 9 ++- .../filesaver/FileSaverLauncher.web.kt | 58 +++++++++++++++---- 8 files changed, 74 insertions(+), 20 deletions(-) diff --git a/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt b/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt index ba9e2558..e4d741ed 100644 --- a/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt +++ b/filekit-core/src/commonMain/kotlin/io/github/vinceglb/filekit/FileKitCoreInternalApi.kt @@ -10,4 +10,4 @@ package io.github.vinceglb.filekit level = RequiresOptIn.Level.WARNING, ) @Retention(AnnotationRetention.BINARY) -public annotation class FileKitCoreInternalApi \ No newline at end of file +public annotation class FileKitCoreInternalApi diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt index 9b2d28c0..5cae7f23 100644 --- a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/SaveDestination.web.kt @@ -23,4 +23,4 @@ public fun createSaveDestination(handle: JsAny?, name: String): PlatformFile = handle = handle?.unsafeCast(), name = name, ), - ) \ No newline at end of file + ) diff --git a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt index 6eafa257..79c77705 100644 --- a/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt +++ b/filekit-core/src/webMain/kotlin/io/github/vinceglb/filekit/WebFile.web.kt @@ -137,7 +137,8 @@ public sealed class WebFile { @Suppress("REDUNDANT_CALL_OF_CONVERSION_METHOD") public val lastModified: Instant - get() = fileSnapshot?.lastModified + get() = fileSnapshot + ?.lastModified ?.toDouble() ?.toLong() ?.let(Instant::fromEpochMilliseconds) diff --git a/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt index 8d5c0168..cef70b78 100644 --- a/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt +++ b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt @@ -44,8 +44,14 @@ public suspend fun FileKit.openFileSaver( val result = invokeBrowserSavePicker(fileName, extensions, browserSavePickerTestOverride).await() return when (result.kind) { - "unsupported" -> createSaveDestination(handle = null, name = fileName) - "selected" -> createSaveDestination(handle = result.handle, name = fileName) + "unsupported" -> { + createSaveDestination(handle = null, name = fileName) + } + + "selected" -> { + createSaveDestination(handle = result.handle, name = fileName) + } + "error" -> { if (result.errorName == "AbortError") { null @@ -56,7 +62,9 @@ public suspend fun FileKit.openFileSaver( } } - else -> throw FileKitDialogException("The browser returned an unknown file saver result") + else -> { + throw FileKitDialogException("The browser returned an unknown file saver result") + } } } diff --git a/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt index 69624821..0f0e44ec 100644 --- a/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt +++ b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt @@ -14,8 +14,8 @@ import kotlin.js.JsAny import kotlin.test.Test import kotlin.test.assertContains import kotlin.test.assertEquals -import kotlin.test.assertFalse import kotlin.test.assertFailsWith +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertNull diff --git a/sample/shared/src/commonMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.kt b/sample/shared/src/commonMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.kt index c7861fbf..4d9ceba6 100644 --- a/sample/shared/src/commonMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.kt +++ b/sample/shared/src/commonMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.kt @@ -7,6 +7,10 @@ import io.github.vinceglb.filekit.dialogs.FileKitDialogSettings internal interface FileSaverLauncher { val isSupported: Boolean + val supportsDirectorySelection: Boolean + get() = true + val supportMessage: String? + get() = null fun launch( suggestedName: String, diff --git a/sample/shared/src/commonMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverScreen.kt b/sample/shared/src/commonMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverScreen.kt index 5d5ca630..5a077ac9 100644 --- a/sample/shared/src/commonMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverScreen.kt +++ b/sample/shared/src/commonMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverScreen.kt @@ -102,6 +102,7 @@ private fun FileSaverScreen( }, ) val isSupported = fileSaverLauncher.isSupported + val supportMessage = fileSaverLauncher.supportMessage val primaryButtonText = if (isSupported) "Save File" else "File Saver Unavailable" fun openFileSaver() { @@ -160,6 +161,7 @@ private fun FileSaverScreen( allowedExtensions = allowedExtensions, saveDirectoryName = saveDirectory?.name, isSupported = isSupported, + supportsDirectorySelection = fileSaverLauncher.supportsDirectorySelection, onSuggestedNameChange = { suggestedName = it }, onDefaultExtensionChange = { newValue -> val trimmed = newValue.trim() @@ -172,10 +174,10 @@ private fun FileSaverScreen( ) } - if (!isSupported) { + if (supportMessage != null) { item { AppPickerSupportCard( - text = "File saver is unavailable on web. Use FileKit.download() for browser downloads.", + text = supportMessage, icon = LucideIcons.Share, modifier = Modifier.sizeIn(maxWidth = AppMaxWidth), ) @@ -202,6 +204,7 @@ private fun FileSaverSettingsCard( allowedExtensions: String, saveDirectoryName: String?, isSupported: Boolean, + supportsDirectorySelection: Boolean, onSuggestedNameChange: (String) -> Unit, onDefaultExtensionChange: (String) -> Unit, onAllowedExtensionsChange: (String) -> Unit, @@ -273,7 +276,7 @@ private fun FileSaverSettingsCard( value = saveDirectoryName, placeholder = "System default", icon = LucideIcons.Folder, - enabled = isSupported, + enabled = isSupported && supportsDirectorySelection, onClick = onPickSaveDirectory, onClear = onClearSaveDirectory, ) diff --git a/sample/shared/src/webMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.web.kt b/sample/shared/src/webMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.web.kt index 3e4f7cec..5e263333 100644 --- a/sample/shared/src/webMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.web.kt +++ b/sample/shared/src/webMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.web.kt @@ -2,26 +2,64 @@ package io.github.vinceglb.filekit.sample.shared.ui.screens.filesaver import androidx.compose.runtime.Composable import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import io.github.vinceglb.filekit.ExperimentalFileKitApi +import io.github.vinceglb.filekit.FileKit import io.github.vinceglb.filekit.PlatformFile import io.github.vinceglb.filekit.dialogs.FileKitDialogException import io.github.vinceglb.filekit.dialogs.FileKitDialogSettings +import io.github.vinceglb.filekit.dialogs.openFileSaver +import io.github.vinceglb.filekit.writeString +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.launch +@OptIn(ExperimentalFileKitApi::class) @Composable internal actual fun rememberFileSaverLauncher( dialogSettings: FileKitDialogSettings, onError: (FileKitDialogException) -> Unit, onResult: (PlatformFile?) -> Unit, -): FileSaverLauncher = remember { - object : FileSaverLauncher { - override val isSupported: Boolean = false +): FileSaverLauncher { + val scope = rememberCoroutineScope() - override fun launch( - suggestedName: String, - defaultExtension: String?, - allowedExtensions: Set?, - directory: PlatformFile?, - ) { - onResult(null) + return remember(scope, dialogSettings, onError, onResult) { + object : FileSaverLauncher { + override val isSupported: Boolean = true + override val supportsDirectorySelection: Boolean = false + override val supportMessage: String = + "Web opens the native save picker when available. Otherwise, writing the file downloads it. " + + "Save In is ignored on web." + + override fun launch( + suggestedName: String, + defaultExtension: String?, + allowedExtensions: Set?, + directory: PlatformFile?, + ) { + // Run up to showSaveFilePicker() synchronously to preserve the click's user activation. + scope.launch(start = CoroutineStart.UNDISPATCHED) { + try { + val file = FileKit.openFileSaver( + suggestedName = suggestedName, + defaultExtension = defaultExtension, + allowedExtensions = allowedExtensions, + directory = directory, + dialogSettings = dialogSettings, + ) + if (file != null) { + file.writeString("FileKit web file saver sample") + } + onResult(file) + } catch (failure: FileKitDialogException) { + onError(failure) + } catch (failure: CancellationException) { + throw failure + } catch (failure: Exception) { + onError(FileKitDialogException("Could not write the selected file", failure)) + } + } + } } } } From 914f73930e87a371de70369760c38fc46f026d9b Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Thu, 19 Nov 2026 10:18:23 +0800 Subject: [PATCH 6/9] =?UTF-8?q?Update=20the=20documentation=20to=20reflect?= =?UTF-8?q?=20the=20experimental=20web=20file=20saving=20feature,=20descri?= =?UTF-8?q?bing=20how=20it=20uses=20the=20browser=E2=80=99s=20file-saving?= =?UTF-8?q?=20picker=20and=20outlining=20alternative=20download=20options.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- docs/ai-assistants.mdx | 2 +- docs/core/web.mdx | 9 ++++++--- docs/dialogs/file-saver.mdx | 27 ++++++++++++++++++++++----- docs/introduction.mdx | 2 +- docs/live-demo.mdx | 2 +- docs/platform-support.mdx | 5 +++-- docs/quickstart.mdx | 2 +- docs/roadmap.mdx | 2 +- 9 files changed, 37 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index c7fc4535..fd93a53a 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ println("${notes.name}: ${notes.size()} bytes") notes.copyTo(FileKit.cacheDir / "notes-backup.txt") ``` -The file saver, app directories, and path operations such as `/` and `copyTo` aren't available on JS and Wasm. Call them from a [non-web source set](https://filekit.mintlify.app/platform-support#use-platform-specific-apis-from-shared-code), and use `FileKit.download` in the browser. +The file saver is experimental on JS and Wasm; it opens the browser save picker when available and otherwise downloads when you write to the destination. App directories and path operations such as `/` and `copyTo` aren't available on the web, so call those from a [non-web source set](https://filekit.mintlify.app/platform-support#use-platform-specific-apis-from-shared-code). Use `FileKit.download` when you want a direct download. The [quickstart](https://filekit.mintlify.app/quickstart) walks through a full pick, read, and save round trip in a few minutes. diff --git a/docs/ai-assistants.mdx b/docs/ai-assistants.mdx index 6459f566..52b369a3 100644 --- a/docs/ai-assistants.mdx +++ b/docs/ai-assistants.mdx @@ -91,6 +91,6 @@ If your project uses an `AGENTS.md`, `CLAUDE.md`, `.cursor/rules`, or Copilot in `FileKitPickerState.Cancelled`. Prefer Compose launcher overloads that take `onError`. - Platform setup: `FileKit.init(appId = ...)` on JVM desktop, Linux native, and Windows native before using app directories. On Android, `FileKit.init(activity)` before calling suspend dialog APIs (Compose launchers do it for you). -- Some APIs are platform-specific (for example, the file saver is not available on JS/Wasm; use `FileKit.download`). +- The experimental `FileKit.openFileSaver()` suspend API is available on JS/Wasm: it uses the browser save picker when available and downloads on write otherwise. Call it during a user action; the Compose `rememberFileSaverLauncher` is not available on web. Use `FileKit.download` for a direct download. Check https://filekit.mintlify.app/platform-support before using an API in `commonMain`. ``` diff --git a/docs/core/web.mdx b/docs/core/web.mdx index 7d542546..6369c21a 100644 --- a/docs/core/web.mdx +++ b/docs/core/web.mdx @@ -8,7 +8,7 @@ import { Platforms } from '/snippets/platforms.jsx' -On JS and Wasm, a `PlatformFile` wraps a browser handle, not a path. Files the user picks are read-only. To give the user a file, download it. To keep files between sessions, store them in the browser's origin private file system. +On JS and Wasm, a `PlatformFile` wraps a browser handle, not a path. Files the user picks are read-only; writable destinations are available through the experimental file saver and OPFS. To trigger a direct download, use `FileKit.download`. ## What a web PlatformFile is @@ -16,6 +16,7 @@ On JS and Wasm, a `PlatformFile` wraps a browser handle, not a path. Files the u | --- | --- | --- | --- | --- | | File picker | A snapshot of a browser `File` | Yes | No | No | | Directory picker | A virtual tree of the selected files | Files only | No | `list()`, `walk()`, `listEntries()` | +| Web file saver | A browser save destination | Yes | Yes | No | | `FileKit.originPrivateDir` (experimental) | A live origin private file system entry | Yes | Yes | `listEntries()` | | `PlatformFile(blob, name)` | A browser `File` made from a `Blob` or `File` | Yes | No | No | @@ -43,7 +44,7 @@ Reads load the whole file into memory: `source()` is not available on the web. ` ## Download files -Browsers don't let a page choose where a file is saved, so there is no file saver on the web. `FileKit.download` hands the file to the browser, which saves it to the user's downloads folder: +`FileKit.download` hands bytes to the browser, which saves them to the user's downloads folder: ```kotlin webMain scope.launch { @@ -54,6 +55,8 @@ scope.launch { Both overloads are suspend functions. The `PlatformFile` overload reads the file first, so it works with picked files and origin private file system files. +To offer a save picker and receive a writable `PlatformFile` destination instead, use the experimental [`FileKit.openFileSaver`](/dialogs/file-saver#web-behavior) API. When the browser has no usable picker, writing to that destination starts a download. + ## Store files in the origin private file system The [origin private file system](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system) (OPFS) is a private storage space for your site, hidden from the user and from other sites. FileKit can read, write, list, and delete files in it. @@ -82,7 +85,7 @@ file.write("Hello again".encodeToByteArray()) val text = file.readString() ``` -`write` and `writeString` replace the file's content. They throw on any file that doesn't come from `FileKit.originPrivateDir`. +`write` and `writeString` replace the file's content. They work with OPFS files and destinations returned by the experimental web file saver; they throw on read-only files returned by the browser's file picker. ### List and delete diff --git a/docs/dialogs/file-saver.mdx b/docs/dialogs/file-saver.mdx index 61646f68..af3102a6 100644 --- a/docs/dialogs/file-saver.mdx +++ b/docs/dialogs/file-saver.mdx @@ -7,9 +7,9 @@ description: 'Let the user choose where to save a file, then write your data to import { Platforms } from '/snippets/platforms.jsx' import DialogResult from '/snippets/dialog-result.mdx' - + -Open the native save dialog. FileKit returns the location the user picked as a `PlatformFile`, and you write your data to it. The file saver is not available on the web, so call it from a non-web source set such as `nonWebMain` (see [shared source sets](/platform-support#use-platform-specific-apis-from-shared-code)). +Open the platform save dialog. FileKit returns the chosen destination as a `PlatformFile`, and you write your data to it. On JS and Wasm, the suspend API is experimental; the browser save picker is used when available, with a download-on-write fallback. The Compose `rememberFileSaverLauncher` is not available on web. ## Usage @@ -75,9 +75,26 @@ val file = FileKit.openFileSaver( Not every platform enforces the filter, so check `file.extension` if your app needs a specific format. -## Download file on the web +## Web behavior -Browsers don't let you choose a save location: use `FileKit.download` to send bytes to the user's downloads folder instead. See [Download files](/core/web#download-files). +On JS and Wasm, `FileKit.openFileSaver()` returns a writable destination. Browsers with the File System Access API open a save picker, and writes go to the selected file. If the API is unavailable or inaccessible (including some cross-origin iframe contexts), the returned destination downloads its bytes when you call `write()` or `writeString()`; the most recently written bytes remain readable from that destination. + +```kotlin webMain +@OptIn(ExperimentalFileKitApi::class) +suspend fun saveReport() { + val file = FileKit.openFileSaver( + suggestedName = "report", + defaultExtension = "txt", + allowedExtensions = setOf("txt", "md"), + ) ?: return // null when the user cancels + + file.writeString("Hello FileKit!") +} +``` + +`allowedExtensions` supplies the picker's file-type filters. `directory` and `dialogSettings` are accepted for API parity but ignored on web. Cancellation returns `null`; other picker failures are wrapped in `FileKitDialogException`. + +Call `openFileSaver()` directly from a user action, such as a click handler. The browser requires transient user activation to show the picker, so don't do other asynchronous work before opening it. For an unconditional download without a save picker, use [`FileKit.download`](/core/web#download-files). ## Platform notes @@ -87,7 +104,7 @@ Browsers don't let you choose a save location: use `FileKit.download` to send by | iOS | Exports a temporary placeholder file through the Files picker, then removes it so you can write to the returned location. `allowedExtensions` is ignored. | | Desktop | The save dialog shows `dialogSettings.title` on Linux native, Windows native, and JVM on macOS. The macOS native saver and the JVM savers on Windows and Linux ignore it. | | Linux native | Needs a running XDG Desktop Portal. See [Dialogs setup](/dialogs/setup#linux-setup). | -| Web | Not available. Use `FileKit.download`. | +| Web | Experimental suspend API; see [Web behavior](#web-behavior). The Compose saver launcher is unavailable. | The `extension` parameter of `openFileSaver` and `launch()` is deprecated. Rename it to `defaultExtension`; the behavior is the same. diff --git a/docs/introduction.mdx b/docs/introduction.mdx index 0382ad7a..914ed281 100644 --- a/docs/introduction.mdx +++ b/docs/introduction.mdx @@ -99,7 +99,7 @@ suspend fun importPhoto() { | :-----: | :-: | :---: | :---------: | :----------: | :------------: | :-: | :--: | :-----: | | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | Core only | -Every target with `filekit-dialogs` uses the platform's native dialogs (watchOS has FileKit Core only). Some features are platform-specific: the camera and share sheet are mobile-only, the file saver is not available in browsers, and Compose and Coil support follows Compose Multiplatform's targets. See the [platform support matrix](/platform-support) for a feature-by-feature breakdown. +Every target with `filekit-dialogs` uses its platform's dialog APIs (watchOS has FileKit Core only). Some features are platform-specific: the camera and share sheet are mobile-only, the experimental web file saver uses browser APIs, and Compose and Coil support follows Compose Multiplatform's targets. See the [platform support matrix](/platform-support) for a feature-by-feature breakdown. ## Modules diff --git a/docs/live-demo.mdx b/docs/live-demo.mdx index 7fbf8f25..dfd8ad11 100644 --- a/docs/live-demo.mdx +++ b/docs/live-demo.mdx @@ -11,7 +11,7 @@ The FileKit sample app is built with Compose Multiplatform and compiled to WebAs -The browser limits what a web page can do with files. File and directory pickers work in modern browsers. The camera picker and share sheet are Android and iOS only, and the file saver dialog is not available on the web, so the sample marks them as unsupported here. On the web, use [`FileKit.download()`](/core/web#download-files) to save files. Each page lists the supported platforms. +The browser limits what a web page can do with files. File and directory pickers work in modern browsers. The camera picker and share sheet are Android and iOS only. The sample's file saver works on web: it opens the browser save picker when available and downloads when the returned destination is written otherwise. The library's Compose `rememberFileSaverLauncher` remains unavailable on web; the experimental suspend API must be called during a user action. Each page lists the supported platforms. ## Run it locally diff --git a/docs/platform-support.mdx b/docs/platform-support.mdx index ec20714e..6727cf8f 100644 --- a/docs/platform-support.mdx +++ b/docs/platform-support.mdx @@ -69,7 +69,7 @@ Columns: **And** Android · **iOS** · **mac** macOS · **JVM** JVM desktop · * | [File picker](/dialogs/file-picker): single, multiple, extension filter | ✅ | ✅ | ✅ | ✅ 9 | ⚠️ 10 | ✅ | ⚠️ 11 | | [Gallery picker](/dialogs/gallery-picker): `Image`, `Video`, `ImageAndVideo` | ✅ Photo Picker | ✅ PHPicker | ⚠️ 12 | ⚠️ 12 | ⚠️ 12 | ⚠️ 12 | ⚠️ 12 | | [Directory picker](/dialogs/directory-picker) | ✅ | ✅ | ✅ | ✅ 9 | ⚠️ 10 | ✅ | ⚠️ 13 | -| [File saver](/dialogs/file-saver) | ⚠️ 14 | ⚠️ 14 | ✅ | ✅ 9 | ⚠️ 10 | ✅ | ❌ use `FileKit.download` | +| [File saver](/dialogs/file-saver) | ⚠️ 14 | ⚠️ 14 | ✅ | ✅ 9 | ⚠️ 10 | ✅ | ⚠️ 17 | | [Camera picker](/dialogs/camera-picker) (photo) | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | [Share file](/dialogs/share-file) | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | | [Open with default app](/dialogs/open-file) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | @@ -115,7 +115,7 @@ Keep only the targets your project declares, and add others (such as `macosMain` ## Notes 1. **Web files are read-only browser handles.** Directories report a size of `0`. `list`, `walk`, and `sizeRecursively` work on folders returned by the directory picker. -2. **Web writing is experimental.** `write`, `writeString`, and `delete` work only on entries in the browser's origin private file system (OPFS) and require `@OptIn(ExperimentalFileKitApi::class)` and a secure context. Writing to a picked file throws. +2. **Web writing is experimental.** `write` and `writeString` work on OPFS files (which require a secure context) and file-saver destinations; `delete` works only on OPFS entries. These APIs require `@OptIn(ExperimentalFileKitApi::class)`. Writing to a picked file throws. 3. **Android `content://` files:** `atomicMove` falls back to copy-then-delete and doesn't support directories. 4. **Linux native:** `createdAt()` always returns `null`. 5. **macOS native:** the output size of `compressImage` depends on the screen's backing scale factor. @@ -130,5 +130,6 @@ Keep only the targets your project declares, and add others (such as `macosMain` 14. **Mobile savers:** on Android, several `allowedExtensions` fall back to the `*/*` MIME type. On iOS, `allowedExtensions` is ignored. 15. **iOS dialog settings:** the presenter view controller and asset representation mode are applied; `title` and `canCreateDirectories` are currently ignored. 16. **Web serialization compiles but fails:** `PlatformFileSerializer` is declared for JS and Wasm, but serializing or deserializing a `PlatformFile` throws at runtime. Store something else, such as the file name or bytes. +17. **Web file saver is experimental.** JS and Wasm use the File System Access API save picker when available; otherwise, writing to the destination downloads the bytes. A browser user action is required to open the picker. `directory` and dialog settings are ignored, and the Compose `rememberFileSaverLauncher` is not available on web. Something wrong or missing? [Open an issue](https://github.com/vinceglb/FileKit/issues) and include the platform and FileKit version. diff --git a/docs/quickstart.mdx b/docs/quickstart.mdx index 7ac2919a..a9e91b53 100644 --- a/docs/quickstart.mdx +++ b/docs/quickstart.mdx @@ -137,7 +137,7 @@ Want to see FileKit before installing it? [Try it in your browser](/live-demo): - The file saver is available on Android, iOS, macOS, JVM, and Linux and Windows native, so call it from a non-web source set. Browsers don't let you choose a save location, so on JS and Wasm use `FileKit.download(bytes, fileName)` instead. See [Files on the web](/core/web#download-files). + The file saver is available on Android, iOS, desktop, Linux and Windows native, and experimentally on JS and Wasm. On web, `FileKit.openFileSaver()` uses the browser save picker when available and downloads when you write to its destination otherwise. Call it directly from a user action so the browser's transient user activation is preserved. Use `FileKit.download(bytes, fileName)` for a direct download. See [File saver](/dialogs/file-saver#web-behavior) and [Files on the web](/core/web#download-files). diff --git a/docs/roadmap.mdx b/docs/roadmap.mdx index 803656d7..ce686735 100644 --- a/docs/roadmap.mdx +++ b/docs/roadmap.mdx @@ -65,7 +65,7 @@ No more removals: existing APIs stay as they were in 0.18, except to fix problem These additions are targeted for the release candidates. They are additive, so if they are not ready by the last RC, they ship in a 1.x release instead: -- **Native save dialog on the web** ([#348](https://github.com/vinceglb/FileKit/issues/348)), using the File System Access API where available, with the current download behavior as a fallback. +- **Web file saver** ([#348](https://github.com/vinceglb/FileKit/issues/348)) is implemented experimentally for JS and Wasm through `FileKit.openFileSaver()`. It uses the File System Access API where available and downloads when the returned destination is written otherwise. - **Blob and W3C `File` interop on the web** ([#173](https://github.com/vinceglb/FileKit/issues/173)), so web code can move between browser types and `PlatformFile` without boilerplate. Shipped early in 0.17.1 with `PlatformFile(blob, name)`. ### 4. FileKit 1.0 From 4e03715de0a650bf9d067b5a0d7e0f5c5b4095da Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Thu, 19 Nov 2026 10:21:44 +0800 Subject: [PATCH 7/9] =?UTF-8?q?=E2=9C=A8=20Added=20test=20cases=20for=20th?= =?UTF-8?q?e=20file=20saver,=20verifying=20basic=20metadata=20and=20string?= =?UTF-8?q?=20read/write=20functionality=20when=20the=20picker=20is=20unav?= =?UTF-8?q?ailable.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../filekit/dialogs/FileSaverWebTest.kt | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt index 0f0e44ec..e22f898f 100644 --- a/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt +++ b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt @@ -8,7 +8,18 @@ package io.github.vinceglb.filekit.dialogs import io.github.vinceglb.filekit.ExperimentalFileKitApi import io.github.vinceglb.filekit.FileKit import io.github.vinceglb.filekit.WebFile +import io.github.vinceglb.filekit.extension +import io.github.vinceglb.filekit.isDirectory +import io.github.vinceglb.filekit.isRegularFile +import io.github.vinceglb.filekit.lastModified +import io.github.vinceglb.filekit.mimeType import io.github.vinceglb.filekit.name +import io.github.vinceglb.filekit.nameWithoutExtension +import io.github.vinceglb.filekit.parent +import io.github.vinceglb.filekit.path +import io.github.vinceglb.filekit.readString +import io.github.vinceglb.filekit.size +import io.github.vinceglb.filekit.writeString import kotlinx.coroutines.test.runTest import kotlin.js.JsAny import kotlin.test.Test @@ -20,6 +31,7 @@ import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlin.time.Instant private fun unavailablePickerOverride(): JsAny = js("({ available: false })") @@ -66,6 +78,40 @@ class FileSaverWebTest { } } + @Test + fun openFileSaver_whenPickerUnavailable_returnsDestinationWithBasicMetadata() = runTest { + withPickerOverride(unavailablePickerOverride()) { + val file = assertNotNull( + FileKit.openFileSaver(suggestedName = "report", defaultExtension = "txt"), + ) + + assertEquals("report.txt", file.name) + assertEquals("report", file.nameWithoutExtension) + assertEquals("txt", file.extension) + assertEquals("report.txt", file.path) + assertEquals(0L, file.size()) + assertNull(file.mimeType()) + assertEquals(Instant.fromEpochMilliseconds(0), file.lastModified()) + assertNull(file.parent()) + assertTrue(file.isRegularFile()) + assertFalse(file.isDirectory()) + } + } + + @Test + fun openFileSaver_whenPickerUnavailable_writesAndReadsString() = runTest { + withPickerOverride(unavailablePickerOverride()) { + val destination = assertNotNull( + FileKit.openFileSaver(suggestedName = "report", defaultExtension = "txt"), + ) + + destination.writeString("Saved from web saver") + + assertEquals("Saved from web saver", destination.readString()) + assertEquals(20L, destination.size()) + } + } + @Test fun openFileSaver_whenCancelled_returnsNull() = runTest { withPickerOverride(cancelledPickerOverride()) { From 277287d050243ef328614974bc6f6d13e45f84c3 Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Thu, 19 Nov 2026 10:53:21 +0800 Subject: [PATCH 8/9] =?UTF-8?q?=E2=9C=A8=20Enhance=20file=20saving=20funct?= =?UTF-8?q?ionality=20to=20support=20PDF=20creation=20and=20conditional=20?= =?UTF-8?q?writing=20based=20on=20file=20extension.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../filesaver/FileSaverLauncher.web.kt | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/sample/shared/src/webMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.web.kt b/sample/shared/src/webMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.web.kt index 5e263333..89d09c2e 100644 --- a/sample/shared/src/webMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.web.kt +++ b/sample/shared/src/webMain/kotlin/io/github/vinceglb/filekit/sample/shared/ui/screens/filesaver/FileSaverLauncher.web.kt @@ -9,6 +9,8 @@ import io.github.vinceglb.filekit.PlatformFile import io.github.vinceglb.filekit.dialogs.FileKitDialogException import io.github.vinceglb.filekit.dialogs.FileKitDialogSettings import io.github.vinceglb.filekit.dialogs.openFileSaver +import io.github.vinceglb.filekit.extension +import io.github.vinceglb.filekit.write import io.github.vinceglb.filekit.writeString import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineStart @@ -48,7 +50,11 @@ internal actual fun rememberFileSaverLauncher( dialogSettings = dialogSettings, ) if (file != null) { - file.writeString("FileKit web file saver sample") + if (file.extension.equals("pdf", ignoreCase = true)) { + file.write(createSamplePdf()) + } else { + file.writeString("FileKit web file saver sample") + } } onResult(file) } catch (failure: FileKitDialogException) { @@ -63,3 +69,35 @@ internal actual fun rememberFileSaverLauncher( } } } + +private fun createSamplePdf(): ByteArray { + val text = "FileKit web file saver sample" + val contentStream = "BT\n/F1 18 Tf\n72 720 Td\n($text) Tj\nET" + val objects = listOf( + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] " + + "/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + "<< /Length ${contentStream.encodeToByteArray().size} >>\nstream\n$contentStream\nendstream", + ) + val pdf = StringBuilder("%PDF-1.4\n") + val objectOffsets = mutableListOf() + + objects.forEachIndexed { index, body -> + objectOffsets += pdf.toString().encodeToByteArray().size + pdf.append("${index + 1} 0 obj\n$body\nendobj\n") + } + + val crossReferenceOffset = pdf.toString().encodeToByteArray().size + pdf.append("xref\n0 ${objects.size + 1}\n") + pdf.append("0000000000 65535 f \n") + objectOffsets.forEach { offset -> + pdf.append("${offset.toString().padStart(10, '0')} 00000 n \n") + } + pdf.append( + "trailer\n<< /Size ${objects.size + 1} /Root 1 0 R >>\n" + + "startxref\n$crossReferenceOffset\n%%EOF\n", + ) + return pdf.toString().encodeToByteArray() +} From 8c740a33327da3af50c49351e941f1b4e64c9307 Mon Sep 17 00:00:00 2001 From: yebintang <553387747@qq.com> Date: Sat, 21 Nov 2026 12:13:12 +0800 Subject: [PATCH 9/9] =?UTF-8?q?=E2=9C=A8=20Update=20the=20documentation=20?= =?UTF-8?q?to=20reflect=20the=20latest=20features=20of=20the=20web=20file?= =?UTF-8?q?=20saver,=20correct=20file=20type=20restrictions,=20and=20add?= =?UTF-8?q?=20new=20test=20cases=20to=20verify=20file=20extension=20handli?= =?UTF-8?q?ng.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/core/web.mdx | 14 +++++++------- .../vinceglb/filekit/dialogs/FileSaver.web.kt | 10 +++++++--- .../filekit/dialogs/FileSaverWebTest.kt | 18 ++++++++++++++++-- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/docs/core/web.mdx b/docs/core/web.mdx index 6369c21a..d07798d0 100644 --- a/docs/core/web.mdx +++ b/docs/core/web.mdx @@ -12,13 +12,13 @@ On JS and Wasm, a `PlatformFile` wraps a browser handle, not a path. Files the u ## What a web PlatformFile is -| Source | Wraps | Read | Write, delete | List | -| --- | --- | --- | --- | --- | -| File picker | A snapshot of a browser `File` | Yes | No | No | -| Directory picker | A virtual tree of the selected files | Files only | No | `list()`, `walk()`, `listEntries()` | -| Web file saver | A browser save destination | Yes | Yes | No | -| `FileKit.originPrivateDir` (experimental) | A live origin private file system entry | Yes | Yes | `listEntries()` | -| `PlatformFile(blob, name)` | A browser `File` made from a `Blob` or `File` | Yes | No | No | +| Source | Wraps | Read | Write | Delete | List | +| --- | --- | --- | --- | --- | --- | +| File picker | A snapshot of a browser `File` | Yes | No | No | No | +| Directory picker | A virtual tree of the selected files | Files only | No | No | `list()`, `walk()`, `listEntries()` | +| Web file saver | A browser save destination | Yes | Yes | No | No | +| `FileKit.originPrivateDir` (experimental) | A live origin private file system entry | Yes | Yes | Yes | `listEntries()` | +| `PlatformFile(blob, name)` | A browser `File` made from a `Blob` or `File` | Yes | No | No | No | The `path` of a picked file is its name, or for a file inside a picked folder, its relative path starting with the folder's name. Path constructors such as `PlatformFile("/path")`, `FileKit.filesDir`, and `exists()` don't exist on the web: keep that code in `nonWebMain`. diff --git a/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt index cef70b78..60f65e3a 100644 --- a/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt +++ b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt @@ -39,6 +39,7 @@ public suspend fun FileKit.openFileSaver( ): PlatformFile? { val fileName = buildFileSaverSuggestedName(suggestedName, defaultExtension) val extensions = buildFileSaverAllowedFileTypes(defaultExtension, allowedExtensions) + ?.filter { it.length + 1 <= MAX_BROWSER_FILE_TYPE_SUFFIX_LENGTH } ?.joinToString(separator = "\u0000") .orEmpty() val result = invokeBrowserSavePicker(fileName, extensions, browserSavePickerTestOverride).await() @@ -49,7 +50,7 @@ public suspend fun FileKit.openFileSaver( } "selected" -> { - createSaveDestination(handle = result.handle, name = fileName) + createSaveDestination(handle = result.handle, name = result.name) } "error" -> { @@ -68,10 +69,13 @@ public suspend fun FileKit.openFileSaver( } } +private const val MAX_BROWSER_FILE_TYPE_SUFFIX_LENGTH = 16 + @OptIn(ExperimentalWasmJsInterop::class) private external interface BrowserSavePickerResult : JsAny { val kind: String val handle: JsAny? + val name: String val errorName: String val errorMessage: String } @@ -113,7 +117,7 @@ private fun invokeBrowserSavePicker( try { crossOriginFrame = window.self !== window.top && - window.parent.location.origin !== window.location.origin; + window.top.location.origin !== window.location.origin; } catch (_) { crossOriginFrame = true; } @@ -147,7 +151,7 @@ private fun invokeBrowserSavePicker( } return Promise.resolve(api.call(globalThis, options)).then( - function(handle) { return { kind: "selected", handle: handle }; }, + function(handle) { return { kind: "selected", handle: handle, name: handle.name }; }, handleError ); } catch (error) { diff --git a/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt index e22f898f..c56b537e 100644 --- a/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt +++ b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt @@ -147,12 +147,13 @@ class FileSaverWebTest { val file = FileKit.openFileSaver( suggestedName = "report", defaultExtension = "pdf", - allowedExtensions = setOf("txt", ".pdf"), + allowedExtensions = setOf("txt", ".pdf", "sublime-workspace"), ) val selectedFile = assertNotNull(file) val destination = assertIs(selectedFile.webFile) - assertEquals("report.pdf", selectedFile.name) + assertEquals("selected.txt", selectedFile.name) + assertEquals("txt", selectedFile.extension) assertEquals(false, destination.isDownload) assertEquals("report.pdf", lastPickerSuggestedName()) assertEquals( @@ -162,6 +163,19 @@ class FileSaverWebTest { } } + @Test + fun openFileSaver_whenAllExtensionsExceedBrowserLimit_omitsPickerTypes() = runTest { + withPickerOverride(selectedPickerOverride()) { + FileKit.openFileSaver( + suggestedName = "report", + defaultExtension = "sublime-workspace", + ) + + assertEquals("report.sublime-workspace", lastPickerSuggestedName()) + assertFalse(hasPickerTypes()) + } + } + @Test fun openFileSaver_withoutExtensions_omitsPickerTypes() = runTest { withPickerOverride(selectedPickerOverride()) {