@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class, kotlin.io.encoding.ExperimentalEncodingApi::class) package eu.friedcutlet.yokan.ui.screens.reader import eu.friedcutlet.yokan.services.system.triggerBrowserDownload import kotlin.io.encoding.Base64 import kotlin.js.JsAny import kotlin.js.Promise import kotlinx.coroutines.await actual fun shareImage(bytes: ByteArray, fileName: String, mimeType: String): Boolean { if (bytes.isEmpty()) return false // ponytail: navigator.share is async and needs a user gesture; a plain // download covers the "get the image out" intent. return triggerBrowserDownload(bytes, fileName, mimeType) } /** Browsers choose the download directory; a title folder cannot be created, so [folder] is not applied. */ actual suspend fun saveImageToGallery(bytes: ByteArray, fileName: String, mimeType: String, folder: String?): Boolean { if (bytes.isEmpty()) return false return triggerBrowserDownload(bytes, fileName, mimeType) } /** The async Clipboard API only guarantees `image/png`, so other formats are re-encoded first. */ actual suspend fun copyImageToClipboard(bytes: ByteArray, fileName: String, mimeType: String): Boolean { val png = readerImageAsPng(bytes) ?: return false return runCatching { writeClipboardPng(Base64.encode(png)).await() }.isSuccess } private fun writeClipboardPng(base64: String): Promise = js( """ (async () => { if (!navigator.clipboard || !navigator.clipboard.write || typeof ClipboardItem === 'undefined') { throw new Error('Clipboard images are not supported'); } const binary = atob(base64); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i); await navigator.clipboard.write([new ClipboardItem({ 'image/png': new Blob([bytes], { type: 'image/png' }) })]); return null; })() """, )