import { Feature } from "#Source/environment/base.index.ts" import { ensurePermissionGranted } from "./permission.ts" /** * @description Writes the given text to the clipboard. This function ensures * that the Clipboard API is available and that the necessary * permissions are granted before attempting to write to the clipboard. */ export const writeTextToClipboard = async (text: T): Promise => { Feature.ensureClipboard() await ensurePermissionGranted({ name: "clipboard-write" }) // write text to clipboard await navigator.clipboard.writeText(text) return text } /** * @description Reads text from the clipboard. This function ensures that * the Clipboard API is available and that the necessary * permissions are granted before attempting to read from the clipboard. * * It returns the text read from the clipboard as a string. */ export const readTextFromClipboard = async (): Promise => { Feature.ensureClipboard() await ensurePermissionGranted({ name: "clipboard-read" }) // read text from clipboard const text = await navigator.clipboard.readText() return text } /** * @description Writes the given image blob to the clipboard. This function ensures * that the Clipboard API is available and that the necessary * permissions are granted before attempting to write to the clipboard. * * It returns the blob that was written to the clipboard. */ export const writeBlobImageToClipboard = async (blob: T): Promise => { Feature.ensureClipboard() await ensurePermissionGranted({ name: "clipboard-write" }) // write image to clipboard await navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })]) return blob } const base64ToBlob = (base64: string): Blob | null => { try { const byteString = atob(base64.split(",")[1] ?? "") const mimeString = base64.split(",")[0]?.split(":")[1]?.split(";")[0] if (mimeString === undefined) { throw new Error("Invalid MIME type") } const arrayBuffer = new ArrayBuffer(byteString.length) const uintArray = new Uint8Array(arrayBuffer) for (let i = 0; i < byteString.length; i = i + 1) { const codePoint = byteString.codePointAt(i) if (codePoint === undefined) { throw new Error("Invalid character in base64 string") } uintArray[i] = codePoint } return new Blob([arrayBuffer], { type: mimeString }) } catch (exception) { console.error("Failed to convert base64 to Blob:", exception) return null } } /** * @description Writes a base64-encoded image to the clipboard. This function first converts * the base64 string to a Blob object and then uses the `writeBlobImageToClipboard` * function to write the image to the clipboard. * * It returns the original base64 string if the operation is successful. */ export const writeBase64ImageToClipboard = async (base64: T): Promise => { const blob = base64ToBlob(base64) if (blob === null) { throw new Error("Failed to convert base64 to Blob") } await writeBlobImageToClipboard(blob) return base64 }