'use client'; import React, { useEffect, useState } from 'react'; import QRCode from 'qrcode'; import { Badge } from '@/components/ui/Badge'; import { calculateContrast } from '@/lib/utils'; interface QRPreviewProps { content: string; style: { foregroundColor: string; backgroundColor: string; cornerStyle: 'square' | 'rounded'; size: number; }; } export const QRPreview: React.FC = ({ content, style }) => { const [qrDataUrl, setQrDataUrl] = useState(''); const [error, setError] = useState(''); const contrast = calculateContrast(style.foregroundColor, style.backgroundColor); const hasGoodContrast = contrast >= 4.5; useEffect(() => { const generateQR = async () => { try { if (!content) { setQrDataUrl(''); return; } const options = { width: style.size, margin: 2, color: { dark: style.foregroundColor, light: style.backgroundColor, }, errorCorrectionLevel: 'M' as const, }; const dataUrl = await QRCode.toDataURL(content, options); setQrDataUrl(dataUrl); setError(''); } catch (err) { console.error('Error generating QR code:', err); setError('Failed to generate QR code'); } }; generateQR(); }, [content, style]); const downloadQR = async (format: 'svg' | 'png') => { if (!content) return; try { if (format === 'svg') { const svg = await QRCode.toString(content, { type: 'svg', width: style.size, margin: 2, color: { dark: style.foregroundColor, light: style.backgroundColor, }, }); const blob = new Blob([svg], { type: 'image/svg+xml' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'qrcode.svg'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } else { // For PNG, use the canvas const canvas = document.createElement('canvas'); await QRCode.toCanvas(canvas, content, { width: style.size, margin: 2, color: { dark: style.foregroundColor, light: style.backgroundColor, }, }); canvas.toBlob((blob) => { if (blob) { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'qrcode.png'; document.body.appendChild(a); a.click(); document.body.removeChild(a); URL.revokeObjectURL(url); } }); } } catch (err) { console.error('Error downloading QR code:', err); } }; return (
{error ? (
{error}
) : qrDataUrl ? ( QR Code Preview ) : (
Enter content to generate QR code
)}
{hasGoodContrast ? 'Good contrast' : 'Low contrast'} Contrast: {contrast.toFixed(1)}:1
); };