import { SilkeImageValue } from './utils'; /** * Reads a File and converts it to a SilkeImageValue with base64 data. * Returns a promise that resolves with the image value or null if reading fails. */ export function fileToImageValue(file: File): Promise { return new Promise((resolve) => { if (!file.type.startsWith('image/')) { resolve(null); return; } const reader = new FileReader(); reader.onload = (event) => { const result = event.target?.result; if (typeof result === 'string') { const [, base64Data] = result.split(','); resolve({ type: 'image', data: base64Data, mimeType: file.type, name: file.name || undefined, }); } else { resolve(null); } }; reader.onerror = () => resolve(null); reader.readAsDataURL(file); }); } /** * Extracts the first image file from a ClipboardEvent. * Returns the File or null if no image is found. */ export function getImageFromClipboard(e: React.ClipboardEvent): File | null { const items = e.clipboardData?.items; if (!items) return null; for (const item of items) { if (item.type.startsWith('image/')) { return item.getAsFile(); } } return null; } /** * Extracts the first image file from a DragEvent. * Returns the File or null if no image is found. */ export function getImageFromDragEvent(e: DragEvent): File | null { const files = e.dataTransfer?.files; if (!files || files.length === 0) return null; for (const file of files) { if (file.type.startsWith('image/')) { return file; } } return null; } /** * Generates a data URL from a SilkeImageValue for use in img src. */ export function imageValueToDataUrl(img: SilkeImageValue): string { return `data:${img.mimeType};base64,${img.data}`; }