1"use client";
2
3import { Slot as SlotPrimitive } from "radix-ui";
4import * as React from "react";
5import { useComposedRefs } from "@/lib/compose-refs";
6import { cn } from "@/lib/utils";
7import { useLazyRef } from "@/registry/bases/radix/hooks/use-lazy-ref";
8
9const ROOT_NAME = "QRCode";
10const CANVAS_NAME = "QRCodeCanvas";
11const SVG_NAME = "QRCodeSvg";
12const IMAGE_NAME = "QRCodeImage";
13const SKELETON_NAME = "QRCodeSkeleton";
14
15type QRCodeLevel = "L" | "M" | "Q" | "H";
16
17interface QRCodeCanvasOpts {
18 errorCorrectionLevel: QRCodeLevel;
19 type?: "image/png" | "image/jpeg" | "image/webp";
20 quality?: number;
21 margin?: number;
22 color?: {
23 dark: string;
24 light: string;
25 };
26 width?: number;
27 rendererOpts?: {
28 quality?: number;
29 };
30}
31
32interface StoreState {
33 dataUrl: string | null;
34 svgString: string | null;
35 isGenerating: boolean;
36 error: Error | null;
37 generationKey: string;
38}
39
40interface Store {
41 subscribe: (callback: () => void) => () => void;
42 getState: () => StoreState;
43 setState: <K extends keyof StoreState>(key: K, value: StoreState[K]) => void;
44 setStates: (updates: Partial<StoreState>) => void;
45 notify: () => void;
46}
47
48interface QRCodeContextValue {
49 value: string;
50 size: number;
51 margin: number;
52 level: QRCodeLevel;
53 backgroundColor: string;
54 foregroundColor: string;
55 canvasRef: React.RefObject<HTMLCanvasElement | null>;
56}
57
58const StoreContext = React.createContext<Store | null>(null);
59
60function useStore<T>(selector: (state: StoreState) => T): T {
61 const store = React.useContext(StoreContext);
62 if (!store) {
63 throw new Error(`\`useQRCode\` must be used within \`${ROOT_NAME}\``);
64 }
65
66 const getSnapshot = React.useCallback(
67 () => selector(store.getState()),
68 [store, selector],
69 );
70
71 return React.useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);
72}
73
74const QRCodeContext = React.createContext<QRCodeContextValue | null>(null);
75
76function useQRCodeContext(consumerName: string) {
77 const context = React.useContext(QRCodeContext);
78 if (!context) {
79 throw new Error(`\`${consumerName}\` must be used within \`${ROOT_NAME}\``);
80 }
81 return context;
82}
83
84interface QRCodeProps extends Omit<React.ComponentProps<"div">, "onError"> {
85 value: string;
86 size?: number;
87 level?: QRCodeLevel;
88 margin?: number;
89 quality?: number;
90 backgroundColor?: string;
91 foregroundColor?: string;
92 onError?: (error: Error) => void;
93 onGenerated?: () => void;
94 asChild?: boolean;
95}
96
97function QRCode(props: QRCodeProps) {
98 const {
99 value,
100 size = 200,
101 level = "M",
102 margin = 1,
103 quality = 0.92,
104 backgroundColor = "#ffffff",
105 foregroundColor = "#000000",
106 onError,
107 onGenerated,
108 className,
109 style,
110 asChild,
111 ...rootProps
112 } = props;
113
114 const canvasRef = React.useRef<HTMLCanvasElement>(null);
115
116 const listenersRef = useLazyRef(() => new Set<() => void>());
117 const stateRef = useLazyRef<StoreState>(() => ({
118 dataUrl: null,
119 svgString: null,
120 isGenerating: false,
121 error: null,
122 generationKey: "",
123 }));
124
125 const store = React.useMemo<Store>(() => {
126 return {
127 subscribe: (cb) => {
128 listenersRef.current.add(cb);
129 return () => listenersRef.current.delete(cb);
130 },
131 getState: () => stateRef.current,
132 setState: (key, value) => {
133 if (Object.is(stateRef.current[key], value)) return;
134 stateRef.current[key] = value;
135 store.notify();
136 },
137 setStates: (updates) => {
138 let hasChanged = false;
139
140 for (const key of Object.keys(updates) as Array<keyof StoreState>) {
141 const value = updates[key];
142 if (value !== undefined && !Object.is(stateRef.current[key], value)) {
143 Object.assign(stateRef.current, { [key]: value });
144 hasChanged = true;
145 }
146 }
147
148 if (hasChanged) {
149 store.notify();
150 }
151 },
152 notify: () => {
153 for (const cb of listenersRef.current) {
154 cb();
155 }
156 },
157 };
158 }, [listenersRef, stateRef]);
159
160 const canvasOpts = React.useMemo<QRCodeCanvasOpts>(
161 () => ({
162 errorCorrectionLevel: level,
163 type: "image/png",
164 quality,
165 margin,
166 color: {
167 dark: foregroundColor,
168 light: backgroundColor,
169 },
170 width: size,
171 }),
172 [level, margin, foregroundColor, backgroundColor, size, quality],
173 );
174
175 const generationKey = React.useMemo(() => {
176 if (!value) return "";
177
178 return JSON.stringify({
179 value,
180 size,
181 level,
182 margin,
183 quality,
184 foregroundColor,
185 backgroundColor,
186 });
187 }, [value, level, margin, foregroundColor, backgroundColor, size, quality]);
188
189 const onQRCodeGenerate = React.useCallback(
190 async (targetGenerationKey: string) => {
191 if (!value || !targetGenerationKey) return;
192
193 const currentState = store.getState();
194 if (
195 currentState.isGenerating ||
196 currentState.generationKey === targetGenerationKey
197 )
198 return;
199
200 store.setStates({
201 isGenerating: true,
202 error: null,
203 });
204
205 try {
206 const QRCode = (await import("qrcode")).default;
207
208 let dataUrl: string | null = null;
209
210 try {
211 dataUrl = await QRCode.toDataURL(value, canvasOpts);
212 } catch {
213 dataUrl = null;
214 }
215
216 if (canvasRef.current) {
217 await QRCode.toCanvas(canvasRef.current, value, canvasOpts);
218 }
219
220 const svgString = await QRCode.toString(value, {
221 errorCorrectionLevel: canvasOpts.errorCorrectionLevel,
222 margin: canvasOpts.margin,
223 color: canvasOpts.color,
224 width: canvasOpts.width,
225 type: "svg",
226 });
227
228 store.setStates({
229 dataUrl,
230 svgString,
231 isGenerating: false,
232 generationKey: targetGenerationKey,
233 });
234
235 onGenerated?.();
236 } catch (error) {
237 const parsedError =
238 error instanceof Error
239 ? error
240 : new Error("Failed to generate QR code");
241 store.setStates({
242 error: parsedError,
243 isGenerating: false,
244 });
245 onError?.(parsedError);
246 }
247 },
248 [value, canvasOpts, store, onError, onGenerated],
249 );
250
251 const contextValue = React.useMemo<QRCodeContextValue>(
252 () => ({
253 value,
254 size,
255 level,
256 margin,
257 backgroundColor,
258 foregroundColor,
259 canvasRef,
260 }),
261 [value, size, backgroundColor, foregroundColor, level, margin],
262 );
263
264 React.useLayoutEffect(() => {
265 if (generationKey) {
266 const rafId = requestAnimationFrame(() => {
267 onQRCodeGenerate(generationKey);
268 });
269
270 return () => cancelAnimationFrame(rafId);
271 }
272 }, [generationKey, onQRCodeGenerate]);
273
274 const RootPrimitive = asChild ? SlotPrimitive.Slot : "div";
275
276 return (
277 <StoreContext.Provider value={store}>
278 <QRCodeContext.Provider value={contextValue}>
279 <RootPrimitive
280 data-slot="qr-code"
281 {...rootProps}
282 className={cn(className, "relative flex flex-col items-center gap-2")}
283 style={
284 {
285 "--qr-code-size": `${size}px`,
286 ...style,
287 } as React.CSSProperties
288 }
289 />
290 </QRCodeContext.Provider>
291 </StoreContext.Provider>
292 );
293}
294
295interface QRCodeCanvasProps extends React.ComponentProps<"canvas"> {
296 asChild?: boolean;
297}
298
299function QRCodeCanvas(props: QRCodeCanvasProps) {
300 const { asChild, className, ref, ...canvasProps } = props;
301
302 const context = useQRCodeContext(CANVAS_NAME);
303 const generationKey = useStore((state) => state.generationKey);
304
305 const composedRef = useComposedRefs(ref, context.canvasRef);
306
307 const CanvasPrimitive = asChild ? SlotPrimitive.Slot : "canvas";
308
309 return (
310 <CanvasPrimitive
311 data-slot="qr-code-canvas"
312 {...canvasProps}
313 ref={composedRef}
314 width={context.size}
315 height={context.size}
316 className={cn(
317 "relative max-h-(--qr-code-size) max-w-(--qr-code-size)",
318 !generationKey && "invisible",
319 className,
320 )}
321 />
322 );
323}
324
325interface QRCodeSvgProps extends React.ComponentProps<"div"> {
326 asChild?: boolean;
327}
328
329function QRCodeSvg(props: QRCodeSvgProps) {
330 const { asChild, className, style, ...svgProps } = props;
331
332 const context = useQRCodeContext(SVG_NAME);
333 const svgString = useStore((state) => state.svgString);
334
335 if (!svgString) return null;
336
337 const SvgPrimitive = asChild ? SlotPrimitive.Slot : "div";
338
339 return (
340 <SvgPrimitive
341 data-slot="qr-code-svg"
342 {...svgProps}
343 className={cn(
344 "relative max-h-(--qr-code-size) max-w-(--qr-code-size)",
345 className,
346 )}
347 style={{ width: context.size, height: context.size, ...style }}
348 dangerouslySetInnerHTML={{ __html: svgString }}
349 />
350 );
351}
352
353interface QRCodeImageProps extends React.ComponentProps<"img"> {
354 asChild?: boolean;
355}
356
357function QRCodeImage(props: QRCodeImageProps) {
358 const { alt = "QR Code", asChild, className, ...imageProps } = props;
359
360 const context = useQRCodeContext(IMAGE_NAME);
361 const dataUrl = useStore((state) => state.dataUrl);
362
363 if (!dataUrl) return null;
364
365 const ImagePrimitive = asChild ? SlotPrimitive.Slot : "img";
366
367 return (
368 <ImagePrimitive
369 data-slot="qr-code-image"
370 {...imageProps}
371 src={dataUrl}
372 alt={alt}
373 width={context.size}
374 height={context.size}
375 className={cn(
376 "relative max-h-(--qr-code-size) max-w-(--qr-code-size)",
377 className,
378 )}
379 />
380 );
381}
382
383interface QRCodeDownloadProps extends React.ComponentProps<"button"> {
384 filename?: string;
385 format?: "png" | "svg";
386 asChild?: boolean;
387}
388
389function QRCodeDownload(props: QRCodeDownloadProps) {
390 const {
391 filename = "qrcode",
392 format = "png",
393 asChild,
394 className,
395 children,
396 ...buttonProps
397 } = props;
398
399 const dataUrl = useStore((state) => state.dataUrl);
400 const svgString = useStore((state) => state.svgString);
401
402 const onClick = React.useCallback(
403 (event: React.MouseEvent<HTMLButtonElement>) => {
404 buttonProps.onClick?.(event);
405 if (event.defaultPrevented) return;
406
407 const link = document.createElement("a");
408
409 if (format === "png" && dataUrl) {
410 link.href = dataUrl;
411 link.download = `${filename}.png`;
412 } else if (format === "svg" && svgString) {
413 const blob = new Blob([svgString], { type: "image/svg+xml" });
414 link.href = URL.createObjectURL(blob);
415 link.download = `${filename}.svg`;
416 } else {
417 return;
418 }
419
420 document.body.appendChild(link);
421 link.click();
422 document.body.removeChild(link);
423
424 if (format === "svg" && svgString) {
425 URL.revokeObjectURL(link.href);
426 }
427 },
428 [dataUrl, svgString, filename, format, buttonProps.onClick],
429 );
430
431 const ButtonPrimitive = asChild ? SlotPrimitive.Slot : "button";
432
433 return (
434 <ButtonPrimitive
435 type="button"
436 data-slot="qr-code-download"
437 {...buttonProps}
438 className={cn("max-w-(--qr-code-size)", className)}
439 onClick={onClick}
440 >
441 {children ?? `Download ${format.toUpperCase()}`}
442 </ButtonPrimitive>
443 );
444}
445
446interface QRCodeOverlayProps extends React.ComponentProps<"div"> {
447 asChild?: boolean;
448}
449
450function QRCodeOverlay(props: QRCodeOverlayProps) {
451 const { asChild, className, ...overlayProps } = props;
452
453 const OverlayPrimitive = asChild ? SlotPrimitive.Slot : "div";
454
455 return (
456 <OverlayPrimitive
457 data-slot="qr-code-overlay"
458 {...overlayProps}
459 className={cn(
460 "absolute top-1/2 left-1/2 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-sm bg-background",
461 className,
462 )}
463 />
464 );
465}
466
467interface QRCodeSkeletonProps extends React.ComponentProps<"div"> {
468 asChild?: boolean;
469}
470
471function QRCodeSkeleton(props: QRCodeSkeletonProps) {
472 const { asChild, className, style, ...skeletonProps } = props;
473
474 const context = useQRCodeContext(SKELETON_NAME);
475 const dataUrl = useStore((state) => state.dataUrl);
476 const svgString = useStore((state) => state.svgString);
477 const generationKey = useStore((state) => state.generationKey);
478
479 const isLoaded = dataUrl || svgString || generationKey;
480
481 if (isLoaded) return null;
482
483 const SkeletonPrimitive = asChild ? SlotPrimitive.Slot : "div";
484
485 return (
486 <SkeletonPrimitive
487 data-slot="qr-code-skeleton"
488 {...skeletonProps}
489 className={cn(
490 "absolute max-h-(--qr-code-size) max-w-(--qr-code-size) animate-pulse bg-accent",
491 className,
492 )}
493 style={{
494 width: context.size,
495 height: context.size,
496 ...style,
497 }}
498 />
499 );
500}
501
502export {
503 QRCode,
504 QRCodeCanvas,
505 QRCodeDownload,
506 QRCodeImage,
507 QRCodeOverlay,
508 type QRCodeProps,
509 QRCodeSkeleton,
510 QRCodeSvg,
511 useStore as useQRCode,
512};
513