ImageSharing.wasm.kt
composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/ui/screens/reader/ImageSharing.wasm.kt
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class)23package eu.friedcutlet.yokan.ui.screens.reader45import eu.friedcutlet.yokan.services.system.triggerBrowserDownload6import kotlin.io.encoding.Base647import kotlin.js.JsAny8import kotlin.js.Promise9import kotlinx.coroutines.await1011actual fun shareImage(bytes: ByteArray, fileName: String, mimeType: String): Boolean {12 if (bytes.isEmpty()) return false13 // ponytail: navigator.share is async and needs a user gesture; a plain14 // download covers the "get the image out" intent.15 return triggerBrowserDownload(bytes, fileName, mimeType)16}1718/** Browsers choose the download directory; a title folder cannot be created, so [folder] is not applied. */19actual suspend fun saveImageToGallery(bytes: ByteArray, fileName: String, mimeType: String, folder: String?): Boolean {20 if (bytes.isEmpty()) return false21 return triggerBrowserDownload(bytes, fileName, mimeType)22}2324/** The async Clipboard API only guarantees `image/png`, so other formats are re-encoded first. */25actual suspend fun copyImageToClipboard(bytes: ByteArray, fileName: String, mimeType: String): Boolean {26 val png = readerImageAsPng(bytes) ?: return false27 return runCatching { writeClipboardPng(Base64.encode(png)).await<JsAny?>() }.isSuccess28}2930private fun writeClipboardPng(base64: String): Promise<JsAny?> = js(31 """32 (async () => {33 if (!navigator.clipboard || !navigator.clipboard.write || typeof ClipboardItem === 'undefined') {34 throw new Error('Clipboard images are not supported');35 }36 const binary = atob(base64);37 const bytes = new Uint8Array(binary.length);38 for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);39 await navigator.clipboard.write([new ClipboardItem({ 'image/png': new Blob([bytes], { type: 'image/png' }) })]);40 return null;41 })()42 """,43)44