QR code
158 lines · 1 file · MIT
A QR code on its own paper so it scans in either theme, with PNG and SVG downloads at print size.
import { useEffect, useRef } from "react";
import QRCodeStyling, {
type CornerDotType,
type CornerSquareType,
type DotType,
} from "qr-code-styling";
import { Button } from "./button";
import { Download } from "./icons";
import { cn } from "./cn";
export type QrDotStyle = DotType;
export type QrCornerStyle = CornerSquareType & CornerDotType;
export interface QrLook {
/** Module shape. Default "rounded". */
dotStyle?: QrDotStyle;
/** Ink, a hex colour. Default a near-black. */
color?: string;
/** Finder "eye" shape. Default "extra-rounded". */
corner?: QrCornerStyle;
/** Finder eye colour; follows `color` when empty. */
eyeColor?: string;
/** Background hex, or "transparent". Default white. */
bg?: string;
/** A logo's URL or data URI, drawn in the middle. */
logo?: string;
}
const INK = "#17151f";
const PAPER = "#ffffff";
/** Pixel size of a downloaded code, whatever the preview's size. A PNG is a
* bitmap: exported at preview size it would be about 17mm wide printed. */
const DOWNLOAD_SIZE = 1024;
/** qr-code-styling takes its margin in pixels, so it is held as a ratio of
* the size: the quiet zone stays the same share of a 1024px file. */
const MARGIN_RATIO = 8 / 208;
function options(value: string, size: number, look: QrLook) {
const ink = look.color || INK;
const eye = look.eyeColor || ink;
const corner = look.corner ?? "extra-rounded";
return {
width: size,
height: size,
type: "svg" as const,
data: value,
image: look.logo,
margin: Math.round(size * MARGIN_RATIO),
// A logo covers the middle, so it needs the highest error correction.
qrOptions: { errorCorrectionLevel: look.logo ? ("H" as const) : ("Q" as const) },
imageOptions: { margin: 4, imageSize: 0.35, saveAsBlob: false as const },
dotsOptions: { color: ink, type: look.dotStyle ?? "rounded" },
cornersSquareOptions: { color: eye, type: corner },
cornersDotOptions: { color: eye, type: corner },
backgroundOptions: { color: look.bg || PAPER },
};
}
/**
* A QR code that scans the same in either theme: it is drawn on its own
* paper, never on the page's colours. Previews are drawn at 1024px and
* scaled by CSS. qr-code-styling gives every module a whole number of
* pixels, and the remainder becomes white space around the code; at a
* small size that remainder was a third of the box.
*/
export function QrCode({
value,
size = 208,
label,
className,
...look
}: QrLook & {
/** What the code encodes, usually a short link. */
value: string;
/** Pixels, square. */
size?: number;
/** The image's accessible name; "QR code for" the value by default. */
label?: string;
className?: string;
}) {
const holder = useRef<HTMLDivElement>(null);
const qr = useRef<QRCodeStyling | null>(null);
const { dotStyle, color, corner, eyeColor, bg, logo } = look;
useEffect(() => {
const next = options(value, DOWNLOAD_SIZE, { dotStyle, color, corner, eyeColor, bg, logo });
if (!qr.current && holder.current) {
qr.current = new QRCodeStyling(next);
qr.current.append(holder.current);
} else qr.current?.update(next);
}, [value, dotStyle, color, corner, eyeColor, bg, logo]);
return (
<div
ref={holder}
role="img"
aria-label={label ?? `QR code for ${value}`}
style={{ width: size, height: size }}
className={cn(
"shrink-0 overflow-hidden rounded-lg bg-white shadow-[0_0_0_1px_var(--border)] [&_svg]:block [&_svg]:h-full [&_svg]:w-full",
className,
)}
/>
);
}
/**
* PNG and SVG download buttons. They draw a fresh code at 1024px: exporting
* the preview would give a file as small as the preview.
*/
export function QrDownloadButtons({
value,
name,
onError,
disabled,
className,
...look
}: QrLook & {
value: string;
/** The file name, without its extension. */
name: string;
/** Drawing at 1024px can fail on a browser short of memory. Say so here. */
onError?: () => void;
disabled?: boolean;
className?: string;
}) {
const download = async (extension: "png" | "svg") => {
try {
await new QRCodeStyling(options(value, DOWNLOAD_SIZE, look)).download({ name, extension });
} catch {
onError?.();
}
};
return (
<div className={cn("flex gap-2", className)}>
{/* Named in full: beside a link, "PNG" alone says nothing about what is downloaded. */}
<Button
size="sm"
disabled={disabled}
aria-label="Download QR code as PNG"
onClick={() => void download("png")}
>
<Download size={13} /> PNG
</Button>
<Button
size="sm"
disabled={disabled}
aria-label="Download QR code as SVG"
onClick={() => void download("svg")}
>
<Download size={13} /> SVG
</Button>
</div>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/qr-code- Category
- Display
- Files
- qr-code.tsx
- Brings in
- qr-code-styling