forked from rajun/ar-test
34 lines
1.6 KiB
TypeScript
34 lines
1.6 KiB
TypeScript
import { toast } from 'sonner';
|
|
import { qrLogoFill, qrSvgMarkup } from '~/lib/assets/qr';
|
|
import { blobToDataUrl, downloadBlob, loadImage } from '~/lib/browser';
|
|
import type { BrandIdentity } from '~/types/project';
|
|
|
|
const FILE_SIZE = 1024;
|
|
|
|
// The same markup as on screen, with the logo embedded so the file stands alone
|
|
async function buildMarkup(url: string, brand?: BrandIdentity): Promise<string> {
|
|
const logo = brand?.logoUrl ? { href: await blobToDataUrl(await (await fetch(brand.logoUrl)).blob()), fill: qrLogoFill(brand) } : undefined;
|
|
return qrSvgMarkup(url, { logo, fileSize: FILE_SIZE });
|
|
}
|
|
|
|
// Draws the SVG onto a canvas at its own size
|
|
async function toPng(markup: string): Promise<Blob> {
|
|
const image = await loadImage(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`);
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = image.naturalWidth;
|
|
canvas.height = image.naturalHeight;
|
|
canvas.getContext('2d')?.drawImage(image, 0, 0);
|
|
return new Promise((resolve, reject) => canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('PNG export failed'))), 'image/png'));
|
|
}
|
|
|
|
export async function downloadQr(format: 'png' | 'svg', url: string, fileName: string, brand?: BrandIdentity) {
|
|
try {
|
|
const markup = await buildMarkup(url, brand);
|
|
const blob = format === 'png' ? await toPng(markup) : new Blob([markup], { type: 'image/svg+xml' });
|
|
downloadBlob(blob, `${fileName}.${format}`);
|
|
toast.success('QR code downloaded');
|
|
} catch {
|
|
toast.error('Could not download the QR code');
|
|
}
|
|
}
|