Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
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).
- 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`.
```
21 changes: 12 additions & 9 deletions docs/core/web.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@ import { Platforms } from '/snippets/platforms.jsx'

<Platforms scope="core" supported="web" anchor="filekit-core" />

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`.

Expand All @@ -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 {
Expand All @@ -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.
Expand Down Expand Up @@ -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

Expand Down
27 changes: 22 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' }} 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; uses the browser save picker when available, otherwise downloads on write' }} anchor="filekit-dialogs" />

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

Expand Down Expand Up @@ -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

Expand All @@ -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. |

<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/introduction.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

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, 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.
</Note>

## Run it locally
Expand Down
5 changes: 3 additions & 2 deletions docs/platform-support.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ Columns: **And** Android · **iOS** · **mac** macOS · **JVM** JVM desktop · *
| [File picker](/dialogs/file-picker): single, multiple, extension filter | ✅ | ✅ | ✅ | ✅ <sup>9</sup> | ⚠️ <sup>10</sup> | ✅ | ⚠️ <sup>11</sup> |
| [Gallery picker](/dialogs/gallery-picker): `Image`, `Video`, `ImageAndVideo` | ✅ Photo Picker | ✅ PHPicker | ⚠️ <sup>12</sup> | ⚠️ <sup>12</sup> | ⚠️ <sup>12</sup> | ⚠️ <sup>12</sup> | ⚠️ <sup>12</sup> |
| [Directory picker](/dialogs/directory-picker) | ✅ | ✅ | ✅ | ✅ <sup>9</sup> | ⚠️ <sup>10</sup> | ✅ | ⚠️ <sup>13</sup> |
| [File saver](/dialogs/file-saver) | ⚠️ <sup>14</sup> | ⚠️ <sup>14</sup> | ✅ | ✅ <sup>9</sup> | ⚠️ <sup>10</sup> | ✅ | ❌ use `FileKit.download` |
| [File saver](/dialogs/file-saver) | ⚠️ <sup>14</sup> | ⚠️ <sup>14</sup> | ✅ | ✅ <sup>9</sup> | ⚠️ <sup>10</sup> | ✅ | ⚠️ <sup>17</sup> |
| [Camera picker](/dialogs/camera-picker) (photo) | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
| [Share file](/dialogs/share-file) | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
| [Open with default app](/dialogs/open-file) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
Expand Down Expand Up @@ -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.
Expand All @@ -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.
2 changes: 1 addition & 1 deletion docs/quickstart.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ Want to see FileKit before installing it? [Try it in your browser](/live-demo):
</CodeGroup>

<Note>
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).
</Note>
</Step>
</Steps>
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading