Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/ai-assistants.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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).
- 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.
- The experimental `FileKit.openFileSaver()` suspend API and Compose `rememberFileSaverLauncher()` are available on JS/Wasm: they use the browser save picker when available and download on write otherwise. Invoke them directly during a user action; both web APIs require `@OptIn(ExperimentalFileKitApi::class)`. Use `FileKit.download` for a direct download.
Check https://filekit.mintlify.app/platform-support before using an API in `commonMain`.
```
10 changes: 5 additions & 5 deletions docs/dialogs/file-saver.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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'

<Platforms scope="dialogs" supported="macos jvm windows" partial={{ android: 'Several allowedExtensions fall back to */*', ios: 'allowedExtensions is ignored', linux: 'Needs the XDG Desktop Portal', web: 'Experimental; uses the browser save picker when available, otherwise downloads on write' }} anchor="filekit-dialogs" />
<Platforms scope="dialogs" supported="macos jvm windows" partial={{ android: 'Several allowedExtensions fall back to */*', ios: 'allowedExtensions is ignored', linux: 'Needs the XDG Desktop Portal', web: 'Experimental; Compose launcher uses the browser save picker when available, otherwise downloads on write' }} anchor="filekit-dialogs" />

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.
Open the platform save dialog. FileKit returns the chosen destination as a `PlatformFile`, and you write your data to it. On JS and Wasm, both `FileKit.openFileSaver()` and the Compose `rememberFileSaverLauncher` are experimental; the browser save picker is used when available, with a download-on-write fallback. Add `@OptIn(ExperimentalFileKitApi::class)` when calling the Compose launcher from web code.

## Usage

Expand Down Expand Up @@ -77,7 +77,7 @@ Not every platform enforces the filter, so check `file.extension` if your app ne

## Web behavior

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.
On JS and Wasm, `FileKit.openFileSaver()` returns a writable destination, while the Compose `rememberFileSaverLauncher()` returns a launcher that reports that destination through `onResult`. 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 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)
Expand All @@ -94,7 +94,7 @@ suspend fun saveReport() {

`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).
Call `openFileSaver()` or the Compose launcher's `launch()` method 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

Expand All @@ -104,7 +104,7 @@ Call `openFileSaver()` directly from a user action, such as a click handler. The
| 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 | Experimental suspend API; see [Web behavior](#web-behavior). The Compose saver launcher is unavailable. |
| Web | Experimental suspend and Compose APIs; see [Web behavior](#web-behavior). `directory` and dialog settings are ignored. |

<Accordion title="Upgrading from older versions">
The `extension` parameter of `openFileSaver` and `launch()` is deprecated. Rename it to `defaultExtension`; the behavior is the same.
Expand Down
2 changes: 1 addition & 1 deletion docs/live-demo.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ The FileKit sample app is built with Compose Multiplatform and compiled to WebAs
<FileKitDemo title="FileKit sample" height={680} />

<Note>
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.
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 uses the library's experimental Compose `rememberFileSaverLauncher`: it opens the browser save picker when available and downloads when the returned destination is written otherwise. Launch it directly from a user action. Each page lists the supported platforms.
</Note>

## Run it locally
Expand Down
4 changes: 2 additions & 2 deletions docs/platform-support.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ Columns: **And** Android · **iOS** · **mac** macOS · **JVM** JVM desktop · *
| Feature | Android | iOS | macOS | JVM | Web |
| --- | :-: | :-: | :-: | :-: | :-: |
| `rememberFilePickerLauncher`, `rememberDirectoryPickerLauncher` | ✅ | ✅ | ✅ | ✅ | ✅ <sup>13</sup> |
| `rememberFileSaverLauncher` | ✅ | ✅ | ✅ | ✅ | ❌ |
| `rememberFileSaverLauncher` | ✅ | ✅ | ✅ | ✅ | ⚠️ <sup>17</sup> |
| `rememberCameraPickerLauncher`, `rememberShareFileLauncher` | ✅ | ✅ | ❌ | ❌ | ❌ |
| `PlatformFile.toImageBitmap()`, `ImageBitmap.encodeToByteArray()` | ✅ | ✅ | ✅ | ✅ | ✅ |
| [Coil](/integrations/coil) `AsyncImage(model = platformFile)` | ✅ | ✅ | ✅ | ✅ | ✅ |
Expand Down Expand Up @@ -130,6 +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.
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. Both `FileKit.openFileSaver()` and the Compose `rememberFileSaverLauncher` are available on web and require `@OptIn(ExperimentalFileKitApi::class)`.

Something wrong or missing? [Open an issue](https://github.com/vinceglb/FileKit/issues) and include the platform and FileKit version.
2 changes: 1 addition & 1 deletion docs/roadmap.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ No more removals: existing APIs stay as they were in 0.18, except to fix problem

These additions are targeted for the release candidates. They are additive, so if they are not ready by the last RC, they ship in a 1.x release instead:

- **File saver on the web** ([#348](https://github.com/vinceglb/FileKit/issues/348)). `FileKit.openFileSaver()` and `rememberFileSaverLauncher()` come to JS and Wasm with the same signatures as on other platforms, first as `@ExperimentalFileKitApi`. Chromium browsers show the native save dialog. Firefox and Safari have no such dialog, so the returned file downloads its content when you write to it. Once the behavior has settled, the file saver, `write()` and `writeString()` move to common code. This is additive: code that compiles today keeps compiling.
- **File saver on the web** ([#348](https://github.com/vinceglb/FileKit/issues/348)). `FileKit.openFileSaver()` and `rememberFileSaverLauncher()` are available on JS and Wasm with the same signatures as on other platforms, marked `@ExperimentalFileKitApi`. Chromium browsers show the native save dialog. Browsers without the File System Access API download the returned file's content when you write to it. Once the behavior has settled, the file saver, `write()` and `writeString()` can move to common code. This is additive: code that compiles today keeps compiling.
- **Blob and W3C `File` interop on the web** ([#173](https://github.com/vinceglb/FileKit/issues/173)), so web code can move between browser types and `PlatformFile` without boilerplate. Shipped early in 0.17.1 with `PlatformFile(blob, name)`.

### 4. FileKit 1.0
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
@file:OptIn(io.github.vinceglb.filekit.ExperimentalFileKitApi::class)

package io.github.vinceglb.filekit.dialogs.compose

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
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 kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

/**
* Creates and remembers a [SaverResultLauncher] for saving a file on the web.
* The browser save picker requires this launcher to be called from a user action.
*
* @param dialogSettings Ignored on web.
* @param onResult Callback invoked with the save destination, or null if cancelled.
* @return A [SaverResultLauncher] that can be used to launch the saver.
*/
@ExperimentalFileKitApi
@Composable
public fun rememberFileSaverLauncher(
dialogSettings: FileKitDialogSettings,
onResult: (PlatformFile?) -> Unit,
): SaverResultLauncher = rememberFileSaverLauncher(
dialogSettings = dialogSettings,
onError = {},
onResult = onResult,
)

/**
* Creates and remembers a [SaverResultLauncher] for saving a file on the web.
* The browser save picker requires this launcher to be called from a user action.
*
* @param dialogSettings Ignored on web.
* @param onError Callback invoked when the browser save operation cannot complete. It is not invoked for cancellation.
* @param onResult Callback invoked with the save destination, or null if cancelled.
* @return A [SaverResultLauncher] that can be used to launch the saver.
*/
@ExperimentalFileKitApi
@Composable
public fun rememberFileSaverLauncher(
dialogSettings: FileKitDialogSettings,
onError: (FileKitDialogException) -> Unit,
onResult: (PlatformFile?) -> Unit,
): SaverResultLauncher {
val coroutineScope = rememberCoroutineScope()
val stableDialogSettings = rememberStableDialogSettings(dialogSettings)
val currentDialogSettings by rememberUpdatedState(stableDialogSettings)
val currentOnError by rememberUpdatedState(onError)
val currentOnResult by rememberUpdatedState(onResult)

return remember {
SaverResultLauncher { suggestedName, defaultExtension, allowedExtensions, directory ->
// The browser requires showSaveFilePicker() to be invoked within the user activation.
coroutineScope.launchWebFileSaverOperation {
runDialogOperation(
operation = {
FileKit.openFileSaver(
suggestedName = suggestedName,
defaultExtension = defaultExtension,
allowedExtensions = allowedExtensions,
directory = directory,
dialogSettings = currentDialogSettings,
)
},
onError = currentOnError,
onResult = currentOnResult,
)
}
}
}
}

internal fun CoroutineScope.launchWebFileSaverOperation(
operation: suspend () -> Unit,
): Job = launch(start = CoroutineStart.UNDISPATCHED) {
operation()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@file:Suppress("UNUSED_VARIABLE")
@file:OptIn(io.github.vinceglb.filekit.ExperimentalFileKitApi::class)

package io.github.vinceglb.filekit.dialogs.compose

import androidx.compose.runtime.Composable
import io.github.vinceglb.filekit.PlatformFile
import io.github.vinceglb.filekit.dialogs.FileKitDialogException
import io.github.vinceglb.filekit.dialogs.FileKitDialogSettings

@Composable
private fun CompileWebFileSaverCallShapes() {
val settings = FileKitDialogSettings.createDefault()
val legacy = rememberFileSaverLauncher(settings) { _: PlatformFile? -> }
val explicit = rememberFileSaverLauncher(
dialogSettings = settings,
onError = { _: FileKitDialogException -> },
onResult = { _: PlatformFile? -> },
)

legacy.launch(suggestedName = "report", defaultExtension = "pdf")
explicit.launch(
suggestedName = "report",
defaultExtension = "pdf",
allowedExtensions = setOf("pdf", "txt"),
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package io.github.vinceglb.filekit.dialogs.compose

import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertTrue

class FileSaverLauncherWebTest {
@Test
fun launchWebFileSaverOperation_startsBeforeReturningToPreserveUserActivation() = runTest {
var operationStarted = false

val job = launchWebFileSaverOperation {
operationStarted = true
awaitCancellation()
}

assertTrue(operationStarted)
job.cancel()
}
}
Loading
Loading