"use client";
import { memo } from "react";
import { IconX } from "@tabler/icons-react";
import { cn, generateUUID } from "@/lib/utils";
export type ImageAttachment = {
id: string;
data: string; // Base64-encoded image data (without data: prefix)
mimeType: string; // "image/png", "image/jpeg", "image/gif", "image/webp"
preview: string; // Data URL for preview display
size: number; // File size in bytes
width: number; // Image width in pixels
height: number; // Image height in pixels
};
// Supported image types
export const SUPPORTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp"];
// Size limits
export const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB per image
export const MAX_TOTAL_SIZE = 20 * 1024 * 1024; // 20MB total
export const MAX_IMAGES = 10;
export function formatBytes(bytes: number): string {
if (bytes === 0) return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
}
type ImageAttachmentPreviewProps = {
attachments: ImageAttachment[];
onRemove: (id: string) => void;
disabled?: boolean;
};
export const ImageAttachmentPreview = memo(function ImageAttachmentPreview({
attachments,
onRemove,
disabled = false,
}: ImageAttachmentPreviewProps) {
if (attachments.length === 0) return null;
return (
{attachments.map((attachment) => (
{/* eslint-disable-next-line @next/next/no-img-element -- base64/blob preview URLs are not compatible with next/image */}

{/* Remove button - inside the image bounds */}
{!disabled && (
)}
))}
);
});
/**
* Process a pasted or dropped file into an ImageAttachment
* Returns null if the file is invalid (wrong type, too large, etc.)
*/
export function processImageFile(file: File): Promise {
return new Promise((resolve) => {
// Validate type
if (!SUPPORTED_IMAGE_TYPES.includes(file.type)) {
console.warn(`Unsupported image type: ${file.type}`);
resolve(null);
return;
}
// Validate size
if (file.size > MAX_IMAGE_SIZE) {
console.warn(
`Image too large: ${formatBytes(file.size)} (max: ${formatBytes(MAX_IMAGE_SIZE)})`,
);
resolve(null);
return;
}
const reader = new FileReader();
reader.onload = (event) => {
const dataUrl = event.target?.result as string;
if (!dataUrl) {
resolve(null);
return;
}
// Extract base64 data (remove "data:image/png;base64," prefix)
const base64 = dataUrl.split(",")[1];
const mimeType = dataUrl.split(";")[0].split(":")[1];
// Read image dimensions
const img = new Image();
img.onload = () => {
resolve({
id: generateUUID(),
data: base64,
mimeType,
preview: dataUrl,
size: file.size,
width: img.naturalWidth,
height: img.naturalHeight,
});
};
img.onerror = () => resolve(null);
img.src = dataUrl;
};
reader.onerror = () => {
console.error("Failed to read image file");
resolve(null);
};
reader.readAsDataURL(file);
});
}