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/5] =?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/5] =?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/5] =?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/5] =?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/5] =?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)) + } + } + } } } }