diff --git a/README.md b/README.md index c7fc45353..fd93a53a4 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 6459f5663..52b369a3c 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 7d542546c..d07798d0a 100644 --- a/docs/core/web.mdx +++ b/docs/core/web.mdx @@ -8,16 +8,17 @@ 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 -| 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()` | -| `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`. @@ -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 61646f683..af3102a6c 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 0382ad7ab..914ed2810 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 7fbf8f25d..dfd8ad11d 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 ec20714ea..6727cf8f9 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 7ac2919a0..a9e91b537 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/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 000000000..e4d741ede --- /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 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 a525c5982..ea85ee91b 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 31662a18d..c91abb7f6 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 000000000..5cae7f238 --- /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, + ), + ) 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 77e7a0c50..79c777051 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,64 @@ 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 ddf6f8403..f410e9a9b 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") 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 000000000..60f65e3a6 --- /dev/null +++ b/filekit-dialogs/src/webMain/kotlin/io/github/vinceglb/filekit/dialogs/FileSaver.web.kt @@ -0,0 +1,162 @@ +@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) + ?.filter { it.length + 1 <= MAX_BROWSER_FILE_TYPE_SUFFIX_LENGTH } + ?.joinToString(separator = "\u0000") + .orEmpty() + val result = invokeBrowserSavePicker(fileName, extensions, browserSavePickerTestOverride).await() + + return when (result.kind) { + "unsupported" -> { + createSaveDestination(handle = null, name = fileName) + } + + "selected" -> { + createSaveDestination(handle = result.handle, name = result.name) + } + + "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") + } + } +} + +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 +} + +/** 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. + */ +@OptIn(ExperimentalWasmJsInterop::class) +private fun invokeBrowserSavePicker( + suggestedName: String, + extensionList: String, + testOverride: JsAny?, +): Promise = js( + """ + { + 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 = testOverride === null + ? globalThis.showSaveFilePicker + : (testOverride.available ? testOverride.picker : null); + if (typeof api !== "function") { + return Promise.resolve({ kind: "unsupported" }); + } + + try { + crossOriginFrame = window.self !== window.top && + window.top.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, name: handle.name }; }, + handleError + ); + } catch (error) { + return Promise.resolve(handleError(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 new file mode 100644 index 000000000..c56b537e4 --- /dev/null +++ b/filekit-dialogs/src/webTest/kotlin/io/github/vinceglb/filekit/dialogs/FileSaverWebTest.kt @@ -0,0 +1,201 @@ +@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.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 +import kotlin.test.assertContains +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +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 })") + +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_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()) { + 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", "sublime-workspace"), + ) + val selectedFile = assertNotNull(file) + val destination = assertIs(selectedFile.webFile) + + assertEquals("selected.txt", selectedFile.name) + assertEquals("txt", selectedFile.extension) + assertEquals(false, destination.isDownload) + assertEquals("report.pdf", lastPickerSuggestedName()) + assertEquals( + """[{"description":"Files","accept":{"application/pdf":[".pdf"],"text/plain":[".txt"]}}]""", + lastPickerTypesJson(), + ) + } + } + + @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()) { + 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 + } + } +} 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 c7861fbfe..4d9ceba66 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 5d5ca6302..5a077ac93 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 3e4f7cec3..89d09c2ec 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,102 @@ 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.extension +import io.github.vinceglb.filekit.write +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) { + if (file.extension.equals("pdf", ignoreCase = true)) { + file.write(createSamplePdf()) + } else { + 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)) + } + } + } } } } + +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() +}