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
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
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -94,13 +96,15 @@ 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) {
is WebFile.FileWrapper -> file.size
is WebFile.DirectoryWrapper -> 0
is WebFile.OriginPrivateFile -> file.size
is WebFile.OriginPrivateDirectory -> 0
is WebFile.SaveDestination -> file.size
}

public actual val PlatformFile.path: String
Expand All @@ -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) {
Expand All @@ -131,24 +136,32 @@ 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) {
is WebFile.FileWrapper -> file.lastModified
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) {
is WebFile.FileWrapper -> file.parent?.toPlatformFile()
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
Expand All @@ -170,6 +183,10 @@ public actual fun PlatformFile.list(): List<PlatformFile> = 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()")
}
Expand All @@ -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")
}
Expand All @@ -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 ->
Expand Down Expand Up @@ -238,18 +259,19 @@ 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.
*/
@ExperimentalFileKitApi
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")
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<FileSystemFileHandle>(),
name = name,
),
)
Original file line number Diff line number Diff line change
Expand Up @@ -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

/**
Expand Down Expand Up @@ -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<JsAny?>(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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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

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