Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

fix: update QR downloading and rendering

Snazzah1efa80314aa0
diff --git a/components/app/modals/link-qr-modal.tsx b/components/app/modals/link-qr-modal.tsx
index 9b0d2a3e71..9ed725cc40 100644
--- a/components/app/modals/link-qr-modal.tsx
+++ b/components/app/modals/link-qr-modal.tsx
@@ -50,10 +50,12 @@ function LinkQRModalHelper({
const [qrData, setQrData] = useState({
bgColor: "#ffffff",
fgColor: "#000000",
+ size: 1024,
+ level: "Q",
imageSettings: {
- src: logo || "/static/logo.svg",
- height: 36,
- width: 36,
+ src: logo || "https://dub.sh/static/logo.svg",
+ height: 256,
+ width: 256,
excavate: true,
},
});
@@ -83,9 +85,14 @@ function LinkQRModalHelper({
size={128}
bgColor={qrData.bgColor}
fgColor={qrData.fgColor}
- level="L"
+ level="Q"
includeMargin={false}
- imageSettings={qrData.imageSettings}
+ imageSettings={{
+ src: qrData.imageSettings.src,
+ height: 36,
+ width: 36,
+ excavate: true
+ }}
/>
</div>
@@ -95,7 +102,6 @@ function LinkQRModalHelper({
download(
getQRAsSVGDataUri({
value: qrDestUrl,
- size: 1024,
...qrData,
}),
"svg"
@@ -106,10 +112,10 @@ function LinkQRModalHelper({
<Download /> SVG
</button>
<button
- onClick={() =>
+ onClick={async () =>
download(
- getQRAsCanvas(
- { value: qrDestUrl, size: 1024, ...qrData },
+ await getQRAsCanvas(
+ { value: qrDestUrl, ...qrData },
"image/png"
),
"png"
@@ -120,10 +126,11 @@ function LinkQRModalHelper({
<Download /> PNG
</button>
<button
- onClick={() =>
+ onClick={
+ async () =>
download(
- getQRAsCanvas(
- { value: qrDestUrl, size: 1024, ...qrData },
+ await getQRAsCanvas(
+ { value: qrDestUrl, ...qrData },
"image/jpeg"
),
"jpg"
@@ -136,7 +143,7 @@ function LinkQRModalHelper({
</div>
{/* This will be used to prompt downloads. */}
- <a className="hidden" download={`${props.key}.svg`} ref={anchorRef} />
+ <a className="hidden" download={`${props.key}-qrcode.svg`} ref={anchorRef} />
</div>
</div>
</Modal>
diff --git a/lib/qr/index.tsx b/lib/qr/index.tsx
index fa3ed77612..4d00b3c32c 100644
--- a/lib/qr/index.tsx
+++ b/lib/qr/index.tsx
@@ -4,20 +4,20 @@
* SPDX-License-Identifier: ISC
*/
-import { escape } from "html-escaper";
-import type { CSSProperties } from "react";
-import React, { useEffect, useRef, useState } from "react";
+import { escape } from 'html-escaper';
+import type { CSSProperties } from 'react';
+import React, { useEffect, useRef, useState } from 'react';
-import qrcodegen from "./codegen";
+import qrcodegen from './codegen';
-type Modules = ReturnType<qrcodegen.QrCode["getModules"]>;
+type Modules = ReturnType<qrcodegen.QrCode['getModules']>;
type Excavation = { x: number; y: number; w: number; h: number };
const ERROR_LEVEL_MAP: { [index: string]: qrcodegen.QrCode.Ecc } = {
L: qrcodegen.QrCode.Ecc.LOW,
M: qrcodegen.QrCode.Ecc.MEDIUM,
Q: qrcodegen.QrCode.Ecc.QUARTILE,
- H: qrcodegen.QrCode.Ecc.HIGH,
+ H: qrcodegen.QrCode.Ecc.HIGH
};
type ImageSettings = {
@@ -44,9 +44,9 @@ type QRPropsCanvas = QRProps & React.CanvasHTMLAttributes<HTMLCanvasElement>;
type QRPropsSVG = QRProps & React.SVGProps<SVGSVGElement>;
const DEFAULT_SIZE = 128;
-const DEFAULT_LEVEL = "L";
-const DEFAULT_BGCOLOR = "#FFFFFF";
-const DEFAULT_FGCOLOR = "#000000";
+const DEFAULT_LEVEL = 'L';
+const DEFAULT_BGCOLOR = '#FFFFFF';
+const DEFAULT_FGCOLOR = '#000000';
const DEFAULT_INCLUDEMARGIN = false;
const MARGIN_SIZE = 4;
@@ -65,9 +65,7 @@ function generatePath(modules: Modules, margin = 0): string {
if (!cell && start !== null) {
// M0 0h7v1H0z injects the space with the move and drops the comma,
// saving a char per operation
- ops.push(
- `M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z`
- );
+ ops.push(`M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z`);
start = null;
return;
}
@@ -84,11 +82,7 @@ function generatePath(modules: Modules, margin = 0): string {
ops.push(`M${x + margin},${y + margin} h1v1H${x + margin}z`);
} else {
// Otherwise finish the current line.
- ops.push(
- `M${start + margin},${y + margin} h${x + 1 - start}v1H${
- start + margin
- }z`
- );
+ ops.push(`M${start + margin},${y + margin} h${x + 1 - start}v1H${start + margin}z`);
}
return;
}
@@ -98,7 +92,7 @@ function generatePath(modules: Modules, margin = 0): string {
}
});
});
- return ops.join("");
+ return ops.join('');
}
// We could just do this in generatePath, except that we want to support
@@ -138,14 +132,8 @@ function getImageSettings(
const scale = numCells / size;
const w = (imageSettings.width || defaultSize) * scale;
const h = (imageSettings.height || defaultSize) * scale;
- const x =
- imageSettings.x == null
- ? cells.length / 2 - w / 2
- : imageSettings.x * scale;
- const y =
- imageSettings.y == null
- ? cells.length / 2 - h / 2
- : imageSettings.y * scale;
+ const x = imageSettings.x == null ? cells.length / 2 - w / 2 : imageSettings.x * scale;
+ const y = imageSettings.y == null ? cells.length / 2 - h / 2 : imageSettings.y * scale;
let excavation = null;
if (imageSettings.excavate) {
@@ -201,32 +189,20 @@ export function QRCodeCanvas(props: QRPropsCanvas) {
if (_canvas.current != null) {
const canvas = _canvas.current;
- const ctx = canvas.getContext("2d");
+ const ctx = canvas.getContext('2d');
if (!ctx) {
return;
}
- let cells = qrcodegen.QrCode.encodeText(
- value,
- ERROR_LEVEL_MAP[level]
- ).getModules();
+ let cells = qrcodegen.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules();
const margin = includeMargin ? MARGIN_SIZE : 0;
const numCells = cells.length + margin * 2;
- const calculatedImageSettings = getImageSettings(
- cells,
- size,
- includeMargin,
- imageSettings
- );
+ const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings);
const image = _image.current;
const haveImageToRender =
- calculatedImageSettings != null &&
- image !== null &&
- image.complete &&
- image.naturalHeight !== 0 &&
- image.naturalWidth !== 0;
+ calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0;
if (haveImageToRender) {
if (calculatedImageSettings.excavation != null) {
@@ -286,7 +262,7 @@ export function QRCodeCanvas(props: QRPropsCanvas) {
<img
src={imgSrc}
key={imgSrc}
- style={{ display: "none" }}
+ style={{ display: 'none' }}
onLoad={() => {
setIsImageLoaded(true);
}}
@@ -296,13 +272,7 @@ export function QRCodeCanvas(props: QRPropsCanvas) {
}
return (
<>
- <canvas
- style={canvasStyle}
- height={size}
- width={size}
- ref={_canvas}
- {...otherProps}
- />
+ <canvas style={canvasStyle} height={size} width={size} ref={_canvas} {...otherProps} />
{img}
</>
);
@@ -320,19 +290,11 @@ export function QRCodeSVG(props: QRPropsSVG) {
...otherProps
} = props;
- let cells = qrcodegen.QrCode.encodeText(
- value,
- ERROR_LEVEL_MAP[level]
- ).getModules();
+ let cells = qrcodegen.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules();
const margin = includeMargin ? MARGIN_SIZE : 0;
const numCells = cells.length + margin * 2;
- const calculatedImageSettings = getImageSettings(
- cells,
- size,
- includeMargin,
- imageSettings
- );
+ const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings);
let image = null;
if (imageSettings != null && calculatedImageSettings != null) {
@@ -361,17 +323,8 @@ export function QRCodeSVG(props: QRPropsSVG) {
const fgPath = generatePath(cells, margin);
return (
- <svg
- height={size}
- width={size}
- viewBox={`0 0 ${numCells} ${numCells}`}
- {...otherProps}
- >
- <path
- fill={bgColor}
- d={`M0,0 h${numCells}v${numCells}H0z`}
- shapeRendering="crispEdges"
- />
+ <svg height={size} width={size} viewBox={`0 0 ${numCells} ${numCells}`} {...otherProps}>
+ <path fill={bgColor} d={`M0,0 h${numCells}v${numCells}H0z`} shapeRendering="crispEdges" />
<path fill={fgColor} d={fgPath} shapeRendering="crispEdges" />
{image}
</svg>
@@ -386,35 +339,26 @@ export function getQRAsSVGDataUri(props: QRProps) {
bgColor = DEFAULT_BGCOLOR,
fgColor = DEFAULT_FGCOLOR,
includeMargin = DEFAULT_INCLUDEMARGIN,
- imageSettings,
+ imageSettings
} = props;
- let cells = qrcodegen.QrCode.encodeText(
- value,
- ERROR_LEVEL_MAP[level]
- ).getModules();
+ let cells = qrcodegen.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules();
const margin = includeMargin ? MARGIN_SIZE : 0;
const numCells = cells.length + margin * 2;
- const calculatedImageSettings = getImageSettings(
- cells,
- size,
- includeMargin,
- imageSettings
- );
+ const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings);
- let image = "";
+ let image = '';
if (imageSettings != null && calculatedImageSettings != null) {
- if (calculatedImageSettings.excavation != null)
- cells = excavateModules(cells, calculatedImageSettings.excavation);
+ if (calculatedImageSettings.excavation != null) cells = excavateModules(cells, calculatedImageSettings.excavation);
image = [
`<image xlinkHref="${escape(imageSettings.src)}"`,
`height="${calculatedImageSettings.h}"`,
`width="${calculatedImageSettings.w}"`,
`x="${calculatedImageSettings.x + margin}"`,
`y="${calculatedImageSettings.y + margin}"`,
- 'preserveAspectRatio="none"></image>',
- ].join(" ");
+ 'preserveAspectRatio="none"></image>'
+ ].join(' ');
}
const fgPath = generatePath(cells, margin);
@@ -423,13 +367,27 @@ export function getQRAsSVGDataUri(props: QRProps) {
`<path fill="${bgColor}" d="M0,0 h${numCells}v${numCells}H0z" shapeRendering="crispEdges"></path>`,
`<path fill="${fgColor}" d="${fgPath}" shapeRendering="crispEdges"></path>`,
image,
- "</svg>",
- ].join("");
+ '</svg>'
+ ].join('');
return `data:image/svg+xml,${encodeURIComponent(svgData)}`;
}
-export function getQRAsCanvas(props: QRProps, type: string) {
+function waitUntilImageLoaded(img: HTMLImageElement, src: string) {
+ return new Promise((resolve) => {
+ function onFinish() {
+ img.onload = null;
+ img.onerror = null;
+ resolve(true);
+ }
+ img.onload = onFinish;
+ img.onerror = onFinish;
+ img.src = src;
+ img.loading = 'eager';
+ });
+}
+
+export async function getQRAsCanvas(props: QRProps, type: string) {
const {
value,
size = DEFAULT_SIZE,
@@ -437,17 +395,24 @@ export function getQRAsCanvas(props: QRProps, type: string) {
bgColor = DEFAULT_BGCOLOR,
fgColor = DEFAULT_FGCOLOR,
includeMargin = DEFAULT_INCLUDEMARGIN,
+ imageSettings
} = props;
- const canvas = document.createElement("canvas");
- const ctx = canvas.getContext("2d");
+ const canvas = document.createElement('canvas');
+ const ctx = canvas.getContext('2d');
- const cells = qrcodegen.QrCode.encodeText(
- value,
- ERROR_LEVEL_MAP[level]
- ).getModules();
+ let cells = qrcodegen.QrCode.encodeText(value, ERROR_LEVEL_MAP[level]).getModules();
const margin = includeMargin ? MARGIN_SIZE : 0;
const numCells = cells.length + margin * 2;
+ const calculatedImageSettings = getImageSettings(cells, size, includeMargin, imageSettings);
+
+ const image = new Image();
+ if (calculatedImageSettings) {
+ await waitUntilImageLoaded(image, imageSettings.src);
+ if (calculatedImageSettings.excavation != null) {
+ cells = excavateModules(cells, calculatedImageSettings.excavation);
+ }
+ }
const pixelRatio = window.devicePixelRatio || 1;
canvas.height = canvas.width = size * pixelRatio;
@@ -472,7 +437,20 @@ export function getQRAsCanvas(props: QRProps, type: string) {
});
}
+ const haveImageToRender =
+ calculatedImageSettings != null && image !== null && image.complete && image.naturalHeight !== 0 && image.naturalWidth !== 0;
+ if (haveImageToRender) {
+ ctx.drawImage(
+ image,
+ calculatedImageSettings.x + margin,
+ calculatedImageSettings.y + margin,
+ calculatedImageSettings.w,
+ calculatedImageSettings.h
+ );
+ }
+
const url = canvas.toDataURL(type, 1.0);
canvas.remove();
+ image.remove();
return url;
}