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.

QR Code Style Customization (#3788)

Pedro Ladeirac327b2df679d
diff --git a/apps/web/lib/qr/index.tsx b/apps/web/lib/qr/index.tsx
index f88ca00f05..9b753ed749 100644
--- a/apps/web/lib/qr/index.tsx
+++ b/apps/web/lib/qr/index.tsx
@@ -14,12 +14,22 @@ import {
DEFAULT_SIZE,
ERROR_LEVEL_MAP,
} from "./constants";
-import { QRProps, QRPropsCanvas } from "./types";
+import {
+ DotStyle,
+ MarkerBorderStyle,
+ MarkerCenterStyle,
+ QRProps,
+ QRPropsCanvas,
+} from "./types";
import {
SUPPORTS_PATH2D,
excavateModules,
+ generateExtraRoundedDotPath,
generatePath,
+ generateRoundedDotPath,
+ generateSquareDotPath,
getImageSettings,
+ isFinderPatternCell,
} from "./utils";
export * from "./types";
export * from "./utils";
@@ -40,15 +50,10 @@ export function QRCodeCanvas(props: QRPropsCanvas) {
const _canvas = useRef<HTMLCanvasElement>(null);
const _image = useRef<HTMLImageElement>(null);
- // We're just using this state to trigger rerenders when images load. We
- // Don't actually read the value anywhere. A smarter use of useEffect would
- // depend on this value.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [isImgLoaded, setIsImageLoaded] = useState(false);
useEffect(() => {
- // Always update the canvas. It's cheap enough and we want to be correct
- // with the current state.
if (_canvas.current != null) {
const canvas = _canvas.current;
@@ -84,22 +89,16 @@ export function QRCodeCanvas(props: QRPropsCanvas) {
}
}
- // We're going to scale this so that the number of drawable units
- // matches the number of cells. This avoids rounding issues, but does
- // result in some potentially unwanted single pixel issues between
- // blocks, only in environments that don't support Path2D.
const pixelRatio = window.devicePixelRatio || 1;
canvas.height = canvas.width = size * pixelRatio;
const scale = (size / numCells) * pixelRatio;
ctx.scale(scale, scale);
- // Draw solid background, only paint dark modules.
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, numCells, numCells);
ctx.fillStyle = fgColor;
if (SUPPORTS_PATH2D) {
- // $FlowFixMe: Path2D c'tor doesn't support args yet.
ctx.fill(new Path2D(generatePath(cells, margin)));
} else {
cells.forEach(function (row, rdx) {
@@ -123,8 +122,6 @@ export function QRCodeCanvas(props: QRPropsCanvas) {
}
});
- // Ensure we mark image loaded as false here so we trigger updating the
- // canvas in our other effect.
useEffect(() => {
setIsImageLoaded(false);
}, [imgSrc]);
@@ -159,6 +156,162 @@ export function QRCodeCanvas(props: QRPropsCanvas) {
);
}
+// ─── SVG string helpers for download ─────────────────────────────────────────
+
+function roundedRectPath(
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ r: number,
+): string {
+ return (
+ `M${x + r},${y}` +
+ `H${x + w - r}` +
+ `A${r},${r} 0 0 1 ${x + w},${y + r}` +
+ `V${y + h - r}` +
+ `A${r},${r} 0 0 1 ${x + w - r},${y + h}` +
+ `H${x + r}` +
+ `A${r},${r} 0 0 1 ${x},${y + h - r}` +
+ `V${y + r}` +
+ `A${r},${r} 0 0 1 ${x + r},${y}` +
+ `Z`
+ );
+}
+
+function circlePath(cx: number, cy: number, r: number): string {
+ return (
+ `M${cx - r},${cy}` +
+ `A${r},${r} 0 1 0 ${cx + r},${cy}` +
+ `A${r},${r} 0 1 0 ${cx - r},${cy}` +
+ `Z`
+ );
+}
+
+function finderBorderPathString(
+ x: number,
+ y: number,
+ borderStyle: MarkerBorderStyle,
+): string {
+ const cx = x + 3.5;
+ const cy = y + 3.5;
+ if (borderStyle === "square") {
+ return (
+ `M${x},${y}H${x + 7}V${y + 7}H${x}Z ` +
+ `M${x + 1},${y + 1}H${x + 6}V${y + 6}H${x + 1}Z`
+ );
+ }
+ if (borderStyle === "rounded-square") {
+ return (
+ roundedRectPath(x, y, 7, 7, 1.5) +
+ " " +
+ roundedRectPath(x + 1, y + 1, 5, 5, 0.75)
+ );
+ }
+ return circlePath(cx, cy, 3.5) + " " + circlePath(cx, cy, 2.5);
+}
+
+function getFinderPatternSVGString({
+ x,
+ y,
+ markerColor,
+ borderStyle = "square",
+ centerStyle = "square",
+}: {
+ x: number;
+ y: number;
+ markerColor: string;
+ bgColor: string;
+ borderStyle?: MarkerBorderStyle;
+ centerStyle?: MarkerCenterStyle;
+}): string {
+ const cx = x + 3.5;
+ const cy = y + 3.5;
+
+ const borderPath = finderBorderPathString(x, y, borderStyle);
+ const border = `<path d="${borderPath}" fill="${markerColor}" fill-rule="evenodd"></path>`;
+
+ const center =
+ centerStyle === "square"
+ ? `<rect x="${x + 2}" y="${y + 2}" width="3" height="3" fill="${markerColor}" shape-rendering="crispEdges"></rect>`
+ : `<circle cx="${cx}" cy="${cy}" r="1.5" fill="${markerColor}"></circle>`;
+
+ return `<g>${border}${center}</g>`;
+}
+
+// ─── Canvas helpers for finder patterns ──────────────────────────────────────
+
+function drawRoundedRect(
+ ctx: CanvasRenderingContext2D,
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ r: number,
+) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.lineTo(x + w - r, y);
+ ctx.arcTo(x + w, y, x + w, y + r, r);
+ ctx.lineTo(x + w, y + h - r);
+ ctx.arcTo(x + w, y + h, x + w - r, y + h, r);
+ ctx.lineTo(x + r, y + h);
+ ctx.arcTo(x, y + h, x, y + h - r, r);
+ ctx.lineTo(x, y + r);
+ ctx.arcTo(x, y, x + r, y, r);
+ ctx.closePath();
+ ctx.fill();
+}
+
+function drawCanvasFinderPattern(
+ ctx: CanvasRenderingContext2D,
+ fx: number,
+ fy: number,
+ markerColor: string,
+ bgColor: string,
+ borderStyle: MarkerBorderStyle = "square",
+ centerStyle: MarkerCenterStyle = "square",
+) {
+ const cx = fx + 3.5;
+ const cy = fy + 3.5;
+
+ // Draw outer border shape
+ ctx.fillStyle = markerColor;
+ if (borderStyle === "square") {
+ ctx.fillRect(fx, fy, 7, 7);
+ } else if (borderStyle === "rounded-square") {
+ drawRoundedRect(ctx, fx, fy, 7, 7, 1.5);
+ } else {
+ ctx.beginPath();
+ ctx.arc(cx, cy, 3.5, 0, Math.PI * 2);
+ ctx.fill();
+ }
+
+ // Punch the gap in a shape that matches the border style
+ ctx.fillStyle = bgColor;
+ if (borderStyle === "square") {
+ ctx.fillRect(fx + 1, fy + 1, 5, 5);
+ } else if (borderStyle === "rounded-square") {
+ drawRoundedRect(ctx, fx + 1, fy + 1, 5, 5, 0.75);
+ } else {
+ ctx.beginPath();
+ ctx.arc(cx, cy, 2.5, 0, Math.PI * 2);
+ ctx.fill();
+ }
+
+ // Draw inner center
+ ctx.fillStyle = markerColor;
+ if (centerStyle === "square") {
+ ctx.fillRect(fx + 2, fy + 2, 3, 3);
+ } else {
+ ctx.beginPath();
+ ctx.arc(cx, cy, 1.5, 0, Math.PI * 2);
+ ctx.fill();
+ }
+}
+
+// ─── Public download helpers ──────────────────────────────────────────────────
+
export async function getQRAsSVGDataUri(props: QRProps) {
const {
value,
@@ -168,8 +321,14 @@ export async function getQRAsSVGDataUri(props: QRProps) {
fgColor = DEFAULT_FGCOLOR,
margin = DEFAULT_MARGIN,
imageSettings,
+ dotStyle = "square",
+ markerCenterStyle = "square",
+ markerBorderStyle = "square",
+ markerColor,
} = props;
+ const effectiveMarkerColor = markerColor ?? fgColor;
+
let cells = qrcodegen.QrCode.encodeText(
value,
ERROR_LEVEL_MAP[level],
@@ -200,12 +359,38 @@ export async function getQRAsSVGDataUri(props: QRProps) {
].join(" ");
}
- const fgPath = generatePath(cells, margin);
+ const fgPath =
+ dotStyle === "rounded"
+ ? generateRoundedDotPath(cells, margin)
+ : dotStyle === "extra-rounded"
+ ? generateExtraRoundedDotPath(cells, margin)
+ : generateSquareDotPath(cells, margin);
+
+ const numModules = cells.length;
+ const finderPositions = [
+ { x: margin, y: margin },
+ { x: numModules - 7 + margin, y: margin },
+ { x: margin, y: numModules - 7 + margin },
+ ];
+
+ const finderSVG = finderPositions
+ .map((pos) =>
+ getFinderPatternSVGString({
+ x: pos.x,
+ y: pos.y,
+ markerColor: effectiveMarkerColor,
+ bgColor,
+ borderStyle: markerBorderStyle,
+ centerStyle: markerCenterStyle,
+ }),
+ )
+ .join("");
const svgData = [
`<svg xmlns="http://www.w3.org/2000/svg" height="${size}" width="${size}" viewBox="0 0 ${numCells} ${numCells}">`,
- `<path fill="${bgColor}" d="M0,0 h${numCells}v${numCells}H0z" shapeRendering="crispEdges"></path>`,
- `<path fill="${fgColor}" d="${fgPath}" shapeRendering="crispEdges"></path>`,
+ `<path fill="${bgColor}" d="M0,0 h${numCells}v${numCells}H0z" shape-rendering="crispEdges"></path>`,
+ `<path fill="${fgColor}" d="${fgPath}" shape-rendering="crispEdges"></path>`,
+ finderSVG,
image,
"</svg>",
].join("");
@@ -265,8 +450,14 @@ export async function getQRAsCanvas(
fgColor = DEFAULT_FGCOLOR,
margin = DEFAULT_MARGIN,
imageSettings,
+ dotStyle = "square",
+ markerCenterStyle = "square",
+ markerBorderStyle = "square",
+ markerColor,
} = props;
+ const effectiveMarkerColor = markerColor ?? fgColor;
+
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d") as CanvasRenderingContext2D;
@@ -297,24 +488,97 @@ export async function getQRAsCanvas(
const scale = (size / numCells) * pixelRatio;
ctx.scale(scale, scale);
- // Draw solid background, only paint dark modules.
+ // Background
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, numCells, numCells);
+ // Data dots (excluding finder pattern cells)
ctx.fillStyle = fgColor;
- if (SUPPORTS_PATH2D) {
- // $FlowFixMe: Path2D c'tor doesn't support args yet.
- ctx.fill(new Path2D(generatePath(cells, margin)));
- } else {
- cells.forEach(function (row, rdx) {
- row.forEach(function (cell, cdx) {
- if (cell) {
- ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
- }
+ if (dotStyle === "rounded") {
+ const r = 0.4;
+ cells.forEach((row, y) => {
+ row.forEach((cell, x) => {
+ if (!cell || isFinderPatternCell(x, y, cells.length)) return;
+ const px = x + margin;
+ const py = y + margin;
+ drawRoundedRect(ctx, px, py, 1, 1, r);
+ });
+ });
+ } else if (dotStyle === "extra-rounded") {
+ const r = 0.5;
+ const n = cells.length;
+ const isDark = (xi: number, yi: number) =>
+ xi >= 0 &&
+ yi >= 0 &&
+ xi < n &&
+ yi < n &&
+ !!(cells[yi][xi] && !isFinderPatternCell(xi, yi, n));
+
+ cells.forEach((row, y) => {
+ row.forEach((cell, x) => {
+ if (!cell || isFinderPatternCell(x, y, n)) return;
+
+ const px = x + margin;
+ const py = y + margin;
+ const top = isDark(x, y - 1);
+ const right = isDark(x + 1, y);
+ const bottom = isDark(x, y + 1);
+ const left = isDark(x - 1, y);
+
+ // Draw as a rounded rect where connected sides have no arc
+ const rTL = top || left ? 0 : r;
+ const rTR = top || right ? 0 : r;
+ const rBR = bottom || right ? 0 : r;
+ const rBL = bottom || left ? 0 : r;
+
+ ctx.beginPath();
+ ctx.moveTo(px + rTL, py);
+ ctx.lineTo(px + 1 - rTR, py);
+ if (rTR > 0) ctx.arcTo(px + 1, py, px + 1, py + rTR, rTR);
+ ctx.lineTo(px + 1, py + 1 - rBR);
+ if (rBR > 0) ctx.arcTo(px + 1, py + 1, px + 1 - rBR, py + 1, rBR);
+ ctx.lineTo(px + rBL, py + 1);
+ if (rBL > 0) ctx.arcTo(px, py + 1, px, py + 1 - rBL, rBL);
+ ctx.lineTo(px, py + rTL);
+ if (rTL > 0) ctx.arcTo(px, py, px + rTL, py, rTL);
+ ctx.closePath();
+ ctx.fill();
});
});
+ } else {
+ if (SUPPORTS_PATH2D) {
+ ctx.fill(new Path2D(generateSquareDotPath(cells, margin)));
+ } else {
+ cells.forEach((row, rdx) => {
+ row.forEach((cell, cdx) => {
+ if (cell && !isFinderPatternCell(cdx, rdx, cells.length)) {
+ ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
+ }
+ });
+ });
+ }
}
+ // Finder patterns
+ const numModules = cells.length;
+ const finderPositions = [
+ { x: margin, y: margin },
+ { x: numModules - 7 + margin, y: margin },
+ { x: margin, y: numModules - 7 + margin },
+ ];
+
+ finderPositions.forEach(({ x, y }) => {
+ drawCanvasFinderPattern(
+ ctx,
+ x,
+ y,
+ effectiveMarkerColor,
+ bgColor,
+ markerBorderStyle,
+ markerCenterStyle,
+ );
+ });
+
const haveImageToRender =
calculatedImageSettings != null &&
image !== null &&
@@ -345,21 +609,33 @@ export function getQRData({
hideLogo,
logo,
margin,
+ dotStyle,
+ markerCenterStyle,
+ markerBorderStyle,
+ markerColor,
}: {
url: string;
fgColor?: string;
hideLogo?: boolean;
logo?: string;
margin?: number;
+ dotStyle?: DotStyle;
+ markerCenterStyle?: MarkerCenterStyle;
+ markerBorderStyle?: MarkerBorderStyle;
+ markerColor?: string;
}) {
return {
value: `${url}?qr=1`,
bgColor: "#ffffff",
fgColor,
size: 1024,
- level: "Q", // QR Code error correction level: https://blog.qrstuff.com/general/qr-code-error-correction
+ level: "Q",
hideLogo,
margin,
+ dotStyle,
+ markerCenterStyle,
+ markerBorderStyle,
+ markerColor,
...(!hideLogo && {
imageSettings: {
src: logo || DUB_QR_LOGO,
diff --git a/apps/web/lib/qr/types.ts b/apps/web/lib/qr/types.ts
index 0470554813..2d73ae9be5 100644
--- a/apps/web/lib/qr/types.ts
+++ b/apps/web/lib/qr/types.ts
@@ -4,6 +4,19 @@ import qrcodegen from "./codegen";
export type Modules = ReturnType<qrcodegen.QrCode["getModules"]>;
export type Excavation = { x: number; y: number; w: number; h: number };
+export type DotStyle = "square" | "rounded" | "extra-rounded";
+export type MarkerCenterStyle = "square" | "circle";
+export type MarkerBorderStyle = "square" | "rounded-square" | "circle";
+
+export type QRCodeDesign = {
+ fgColor: string;
+ hideLogo: boolean;
+ dotStyle?: DotStyle;
+ markerCenterStyle?: MarkerCenterStyle;
+ markerBorderStyle?: MarkerBorderStyle;
+ markerColor?: string;
+};
+
export type ImageSettings = {
src: string;
height: number;
@@ -23,6 +36,10 @@ export type QRProps = {
style?: CSSProperties;
imageSettings?: ImageSettings;
isOGContext?: boolean;
+ dotStyle?: DotStyle;
+ markerCenterStyle?: MarkerCenterStyle;
+ markerBorderStyle?: MarkerBorderStyle;
+ markerColor?: string;
};
export type QRPropsCanvas = QRProps &
React.CanvasHTMLAttributes<HTMLCanvasElement>;
diff --git a/apps/web/lib/qr/utils.tsx b/apps/web/lib/qr/utils.tsx
index 3b70284505..db5242dda1 100644
--- a/apps/web/lib/qr/utils.tsx
+++ b/apps/web/lib/qr/utils.tsx
@@ -8,7 +8,14 @@ import {
DEFAULT_SIZE,
ERROR_LEVEL_MAP,
} from "./constants";
-import { Excavation, ImageSettings, Modules, QRPropsSVG } from "./types";
+import {
+ Excavation,
+ ImageSettings,
+ MarkerBorderStyle,
+ MarkerCenterStyle,
+ Modules,
+ QRPropsSVG,
+} from "./types";
import type { JSX } from "react";
@@ -31,14 +38,214 @@ export function excavateModules(
});
}
+/**
+ * Returns true if the cell at (x, y) belongs to one of the three 7×7 finder
+ * pattern zones in the QR code corners. numModules is the raw module count
+ * (without margin).
+ */
+export function isFinderPatternCell(
+ x: number,
+ y: number,
+ numModules: number,
+): boolean {
+ return (
+ (x < 7 && y < 7) || // top-left
+ (x >= numModules - 7 && y < 7) || // top-right
+ (x < 7 && y >= numModules - 7) // bottom-left
+ );
+}
+
+/**
+ * Generates an SVG path string for all dark data modules, skipping the three
+ * finder pattern regions. Uses the same batched run-length approach as before
+ * for maximum efficiency.
+ */
+export function generateSquareDotPath(modules: Modules, margin = 0): string {
+ const numModules = modules.length;
+ const ops: Array<string> = [];
+ modules.forEach(function (row, y) {
+ // Skip finder pattern rows entirely where possible — still check per cell
+ // so the separator white modules are handled correctly.
+ let start: number | null = null;
+ row.forEach(function (cell, x) {
+ const isFinder = isFinderPatternCell(x, y, numModules);
+
+ // If we hit a non-dark cell or a finder cell, close any open run.
+ if ((!cell || isFinder) && start !== null) {
+ ops.push(
+ `M${start + margin} ${y + margin}h${x - start}v1H${start + margin}z`,
+ );
+ start = null;
+ return;
+ }
+
+ if (x === row.length - 1) {
+ if (!cell || isFinder) {
+ return;
+ }
+ if (start === null) {
+ ops.push(`M${x + margin},${y + margin} h1v1H${x + margin}z`);
+ } else {
+ ops.push(
+ `M${start + margin},${y + margin} h${x + 1 - start}v1H${
+ start + margin
+ }z`,
+ );
+ }
+ return;
+ }
+
+ if (cell && !isFinder && start === null) {
+ start = x;
+ }
+ });
+ });
+ return ops.join("");
+}
+
+/**
+ * Generates an SVG path string for all dark data modules as rounded squares
+ * (close to circles), skipping finder pattern cells.
+ */
+export function generateRoundedDotPath(modules: Modules, margin = 0): string {
+ const numModules = modules.length;
+ const r = 0.4; // corner radius — fraction of module size
+ const ops: Array<string> = [];
+
+ modules.forEach(function (row, y) {
+ row.forEach(function (cell, x) {
+ if (!cell || isFinderPatternCell(x, y, numModules)) return;
+
+ const cx = x + margin;
+ const cy = y + margin;
+ // Rounded-rectangle arc path for a 1×1 module
+ ops.push(
+ `M${cx + r},${cy}` +
+ `h${1 - 2 * r}` +
+ `a${r},${r} 0 0 1 ${r},${r}` +
+ `v${1 - 2 * r}` +
+ `a${r},${r} 0 0 1 ${-r},${r}` +
+ `h${-(1 - 2 * r)}` +
+ `a${r},${r} 0 0 1 ${-r},${-r}` +
+ `v${-(1 - 2 * r)}` +
+ `a${r},${r} 0 0 1 ${r},${-r}` +
+ `z`,
+ );
+ });
+ });
+
+ return ops.join("");
+}
+
+/**
+ * Draws a rectangle where each of the four corners can have an independent
+ * radius (0 = sharp right angle, r = quarter-circle arc).
+ */
+function cornerRoundedRect(
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ rTL: number,
+ rTR: number,
+ rBR: number,
+ rBL: number,
+): string {
+ const parts: string[] = [];
+ parts.push(`M${x + rTL},${y}`);
+
+ if (rTR > 0) {
+ parts.push(`H${x + w - rTR}`);
+ parts.push(`A${rTR},${rTR} 0 0 1 ${x + w},${y + rTR}`);
+ } else {
+ parts.push(`H${x + w}`);
+ }
+
+ if (rBR > 0) {
+ parts.push(`V${y + h - rBR}`);
+ parts.push(`A${rBR},${rBR} 0 0 1 ${x + w - rBR},${y + h}`);
+ } else {
+ parts.push(`V${y + h}`);
+ }
+
+ if (rBL > 0) {
+ parts.push(`H${x + rBL}`);
+ parts.push(`A${rBL},${rBL} 0 0 1 ${x},${y + h - rBL}`);
+ } else {
+ parts.push(`H${x}`);
+ }
+
+ if (rTL > 0) {
+ parts.push(`V${y + rTL}`);
+ parts.push(`A${rTL},${rTL} 0 0 1 ${x + rTL},${y}`);
+ } else {
+ parts.push(`V${y}`);
+ }
+
+ parts.push("Z");
+ return parts.join("");
+}
+
+/**
+ * "Extra-rounded" / connected style: each module checks its 4 neighbours.
+ * Corners that touch a dark neighbour are kept sharp; free corners get a
+ * full r=0.5 arc — so isolated cells become perfect circles, horizontal
+ * pairs become pills, and L/T-shapes flow into smooth organic forms.
+ */
+export function generateExtraRoundedDotPath(
+ modules: Modules,
+ margin = 0,
+): string {
+ const numModules = modules.length;
+ const r = 0.5;
+ const ops: string[] = [];
+
+ const isDark = (x: number, y: number): boolean => {
+ if (x < 0 || y < 0 || x >= numModules || y >= numModules) return false;
+ return !!(modules[y][x] && !isFinderPatternCell(x, y, numModules));
+ };
+
+ modules.forEach((row, y) => {
+ row.forEach((cell, x) => {
+ if (!cell || isFinderPatternCell(x, y, numModules)) return;
+
+ const px = x + margin;
+ const py = y + margin;
+
+ const top = isDark(x, y - 1);
+ const right = isDark(x + 1, y);
+ const bottom = isDark(x, y + 1);
+ const left = isDark(x - 1, y);
+
+ ops.push(
+ cornerRoundedRect(
+ px,
+ py,
+ 1,
+ 1,
+ top || left ? 0 : r, // TL
+ top || right ? 0 : r, // TR
+ bottom || right ? 0 : r, // BR
+ bottom || left ? 0 : r, // BL
+ ),
+ );
+ });
+ });
+
+ return ops.join("");
+}
+
+/**
+ * Legacy path generator kept for use by canvas and SVG download helpers that
+ * haven't been updated yet. Renders ALL dark modules as squares (no finder
+ * exclusion). Use the named generators above for new code.
+ */
export function generatePath(modules: Modules, margin = 0): string {
const ops: Array<string> = [];
modules.forEach(function (row, y) {
let start: number | null = null;
row.forEach(function (cell, x) {
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`,
);
@@ -46,18 +253,13 @@ export function generatePath(modules: Modules, margin = 0): string {
return;
}
- // end of row, clean up or skip
if (x === row.length - 1) {
if (!cell) {
- // We would have closed the op above already so this can only mean
- // 2+ light modules in a row.
return;
}
if (start === null) {
- // Just a single dark module.
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
@@ -97,7 +299,6 @@ export function getImageSettings(
const w = (imageSettings.width || defaultSize) * scale;
const h = (imageSettings.height || defaultSize) * scale;
- // Center the image in the QR code area (without margins)
const x =
imageSettings.x == null ? qrCodeSize / 2 - w / 2 : imageSettings.x * scale;
const y =
@@ -136,6 +337,120 @@ export function convertImageSettingsToPixels(
return { imgWidth, imgHeight, imgLeft, imgTop };
}
+// ─── SVG path helpers for compound finder-pattern shapes ─────────────────────
+
+/** Closed SVG path for a rounded rectangle. */
+function roundedRectPath(
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ r: number,
+): string {
+ return (
+ `M${x + r},${y}` +
+ `H${x + w - r}` +
+ `A${r},${r} 0 0 1 ${x + w},${y + r}` +
+ `V${y + h - r}` +
+ `A${r},${r} 0 0 1 ${x + w - r},${y + h}` +
+ `H${x + r}` +
+ `A${r},${r} 0 0 1 ${x},${y + h - r}` +
+ `V${y + r}` +
+ `A${r},${r} 0 0 1 ${x + r},${y}` +
+ `Z`
+ );
+}
+
+/** Closed SVG path for a circle (two half-arc moves). */
+function circlePath(cx: number, cy: number, r: number): string {
+ return (
+ `M${cx - r},${cy}` +
+ `A${r},${r} 0 1 0 ${cx + r},${cy}` +
+ `A${r},${r} 0 1 0 ${cx - r},${cy}` +
+ `Z`
+ );
+}
+
+/**
+ * Returns a compound SVG path for the finder-pattern border ring using the
+ * evenodd fill rule, so the gap is transparent (no white rectangle needed).
+ */
+function finderBorderPath(
+ x: number,
+ y: number,
+ borderStyle: MarkerBorderStyle,
+): string {
+ const cx = x + 3.5;
+ const cy = y + 3.5;
+
+ if (borderStyle === "square") {
+ const outer = `M${x},${y}H${x + 7}V${y + 7}H${x}Z`;
+ const inner = `M${x + 1},${y + 1}H${x + 6}V${y + 6}H${x + 1}Z`;
+ return `${outer} ${inner}`;
+ }
+
+ if (borderStyle === "rounded-square") {
+ const outer = roundedRectPath(x, y, 7, 7, 1.5);
+ // Inner cutout uses a smaller radius so corners look intentional
+ const inner = roundedRectPath(x + 1, y + 1, 5, 5, 0.75);
+ return `${outer} ${inner}`;
+ }
+
+ // circle
+ const outer = circlePath(cx, cy, 3.5);
+ const inner = circlePath(cx, cy, 2.5);
+ return `${outer} ${inner}`;
+}
+
+/**
+ * Renders a single finder pattern (7×7 zone) at the given top-left corner
+ * position (in module coordinates, already including margin).
+ *
+ * Uses fill-rule="evenodd" so the border ring gap is transparent — no
+ * background-coloured rectangle is painted, which avoids the hard-cornered
+ * white square that looks bad on rounded / circle border styles.
+ */
+function FinderPattern({
+ x,
+ y,
+ markerColor,
+ borderStyle = "square",
+ centerStyle = "square",
+}: {
+ x: number;
+ y: number;
+ markerColor: string;
+ bgColor: string; // kept in signature for API stability; not needed with evenodd
+ borderStyle?: MarkerBorderStyle;
+ centerStyle?: MarkerCenterStyle;
+}): JSX.Element {
+ const cx = x + 3.5;
+ const cy = y + 3.5;
+ const borderPath = finderBorderPath(x, y, borderStyle);
+
+ return (
+ <g>
+ {/* Border ring — compound path punches a transparent hole via evenodd */}
+ <path d={borderPath} fill={markerColor} fillRule="evenodd" />
+
+ {/* Inner center */}
+ {centerStyle === "square" && (
+ <rect
+ x={x + 2}
+ y={y + 2}
+ width={3}
+ height={3}
+ fill={markerColor}
+ shapeRendering="crispEdges"
+ />
+ )}
+ {centerStyle === "circle" && (
+ <circle cx={cx} cy={cy} r={1.5} fill={markerColor} />
+ )}
+ </g>
+ );
+}
+
export function QRCodeSVG(props: QRPropsSVG) {
const {
value,
@@ -146,14 +461,18 @@ export function QRCodeSVG(props: QRPropsSVG) {
margin = DEFAULT_MARGIN,
isOGContext = false,
imageSettings,
+ dotStyle = "square",
+ markerCenterStyle = "square",
+ markerBorderStyle = "square",
+ markerColor,
...otherProps
} = props;
+ const effectiveMarkerColor = markerColor ?? fgColor;
+
const shouldUseHigherErrorLevel =
isOGContext && imageSettings?.excavate && (level === "L" || level === "M");
- // Use a higher error correction level 'Q' when excavation is enabled
- // to ensure the QR code remains scannable despite the removed modules.
const effectiveLevel = shouldUseHigherErrorLevel ? "Q" : level;
let cells = qrcodegen.QrCode.encodeText(
@@ -211,13 +530,20 @@ export function QRCodeSVG(props: QRPropsSVG) {
}
}
- // Drawing strategy: instead of a rect per module, we're going to create a
- // single path for the dark modules and layer that on top of a light rect,
- // for a total of 2 DOM nodes. We pay a bit more in string concat but that's
- // way faster than DOM ops.
- // For level 1, 441 nodes -> 2
- // For level 40, 31329 -> 2
- const fgPath = generatePath(cells, margin);
+ const fgPath =
+ dotStyle === "rounded"
+ ? generateRoundedDotPath(cells, margin)
+ : dotStyle === "extra-rounded"
+ ? generateExtraRoundedDotPath(cells, margin)
+ : generateSquareDotPath(cells, margin);
+
+ // The three finder pattern top-left corners in module coordinates (+ margin)
+ const numModules = cells.length;
+ const finderPositions = [
+ { x: margin, y: margin }, // top-left
+ { x: numModules - 7 + margin, y: margin }, // top-right
+ { x: margin, y: numModules - 7 + margin }, // bottom-left
+ ];
return (
<svg
@@ -232,6 +558,17 @@ export function QRCodeSVG(props: QRPropsSVG) {
shapeRendering="crispEdges"
/>
<path fill={fgColor} d={fgPath} shapeRendering="crispEdges" />
+ {finderPositions.map((pos, i) => (
+ <FinderPattern
+ key={i}
+ x={pos.x}
+ y={pos.y}
+ markerColor={effectiveMarkerColor}
+ bgColor={bgColor}
+ borderStyle={markerBorderStyle}
+ centerStyle={markerCenterStyle}
+ />
+ ))}
{image}
</svg>
);
diff --git a/apps/web/ui/links/link-builder/qr-code-preview.tsx b/apps/web/ui/links/link-builder/qr-code-preview.tsx
index e21a584629..1fef5d0a8c 100644
--- a/apps/web/ui/links/link-builder/qr-code-preview.tsx
+++ b/apps/web/ui/links/link-builder/qr-code-preview.tsx
@@ -1,3 +1,4 @@
+import { QRCodeDesign } from "@/lib/qr/types";
import useDomain from "@/lib/swr/use-domain";
import useWorkspace from "@/lib/swr/use-workspace";
import { LinkFormData } from "@/ui/links/link-builder/link-builder-provider";
@@ -16,7 +17,7 @@ import { AnimatePresence, motion } from "motion/react";
import { useMemo, useRef } from "react";
import { useFormContext, useWatch } from "react-hook-form";
import { useDebounce } from "use-debounce";
-import { QRCodeDesign, useLinkQRModal } from "../../modals/link-qr-modal";
+import { useLinkQRModal } from "../../modals/link-qr-modal";
import { useLinkBuilderKeyboardShortcut } from "./use-link-builder-keyboard-shortcut";
export function QRCodePreview() {
@@ -45,6 +46,9 @@ export function QRCodePreview() {
{
fgColor: "#000000",
hideLogo: true,
+ dotStyle: "square",
+ markerCenterStyle: "square",
+ markerBorderStyle: "square",
},
);
@@ -110,6 +114,10 @@ export function QRCodePreview() {
hideLogo={hideLogo}
logo={logo}
scale={0.5}
+ dotStyle={data.dotStyle}
+ markerCenterStyle={data.markerCenterStyle}
+ markerBorderStyle={data.markerBorderStyle}
+ markerColor={data.markerColor}
/>
</motion.div>
</AnimatePresence>
diff --git a/apps/web/ui/modals/link-qr-modal.tsx b/apps/web/ui/modals/link-qr-modal.tsx
index b898c636ba..e22a0280ef 100644
--- a/apps/web/ui/modals/link-qr-modal.tsx
+++ b/apps/web/ui/modals/link-qr-modal.tsx
@@ -1,64 +1,33 @@
-import { getQRAsCanvas, getQRAsSVGDataUri, getQRData } from "@/lib/qr";
+import { getQRData } from "@/lib/qr";
+import { QRCodeDesign } from "@/lib/qr/types";
import useDomain from "@/lib/swr/use-domain";
import useWorkspace from "@/lib/swr/use-workspace";
import { QRLinkProps } from "@/lib/types";
-import { QRCode } from "@/ui/shared/qr-code";
import {
- Button,
- ButtonTooltip,
- IconMenu,
InfoTooltip,
Modal,
- Popover,
- ShimmerDots,
- Switch,
Tooltip,
TooltipContent,
- useCopyToClipboard,
useLocalStorage,
- useMediaQuery,
} from "@dub/ui";
-import {
- Check,
- Check2,
- Copy,
- CrownSmall,
- Download,
- Hyperlink,
- Photo,
-} from "@dub/ui/icons";
-import { API_DOMAIN, cn, DUB_QR_LOGO, linkConstructor } from "@dub/utils";
-import { AnimatePresence, motion } from "motion/react";
+import { Crown } from "@dub/ui/icons";
+import { DUB_QR_LOGO, linkConstructor } from "@dub/utils";
import {
Dispatch,
- PropsWithChildren,
SetStateAction,
useCallback,
- useId,
useMemo,
- useRef,
useState,
} from "react";
-import { HexColorInput, HexColorPicker } from "react-colorful";
-import { toast } from "sonner";
-import { useDebouncedCallback } from "use-debounce";
import { ProBadgeTooltip } from "../shared/pro-badge-tooltip";
+import {
+ DEFAULT_QR_DESIGN,
+ QRCodeDesignFields,
+ SegmentTab,
+ SegmentedControl,
+} from "./qr-code-design-fields";
-const DEFAULT_COLORS = [
- "#000000",
- "#C73E33",
- "#DF6547",
- "#F4B3D7",
- "#F6CF54",
- "#49A065",
- "#2146B7",
- "#AE49BF",
-];
-
-export type QRCodeDesign = {
- fgColor: string;
- hideLogo: boolean;
-};
+export type { QRCodeDesign };
type LinkQRModalProps = {
props: QRLinkProps;
@@ -92,32 +61,32 @@ function LinkQRModalInner({
setShowLinkQRModal: Dispatch<SetStateAction<boolean>>;
} & LinkQRModalProps) {
const { id: workspaceId, slug, plan, logo: workspaceLogo } = useWorkspace();
- const id = useId();
- const { isMobile } = useMediaQuery();
const { logo: domainLogo } = useDomain({
slug: props.domain,
enabled: showLinkQRModal,
});
- const url = useMemo(() => {
- return props.key && props.domain
- ? linkConstructor({ key: props.key, domain: props.domain })
- : undefined;
- }, [props.key, props.domain]);
+ const isPro = plan && plan !== "free";
+
+ const url = useMemo(
+ () =>
+ props.key && props.domain
+ ? linkConstructor({ key: props.key, domain: props.domain })
+ : undefined,
+ [props.key, props.domain],
+ );
const [dataPersisted, setDataPersisted] = useLocalStorage<QRCodeDesign>(
`qr-code-design-${workspaceId}`,
- {
- fgColor: "#000000",
- hideLogo: false,
- },
+ DEFAULT_QR_DESIGN,
);
- const [data, setData] = useState(dataPersisted);
+ const [data, setData] = useState<QRCodeDesign>(dataPersisted);
- const hideLogo = data.hideLogo && plan !== "free";
- const logo =
- plan === "free" ? DUB_QR_LOGO : domainLogo || workspaceLogo || DUB_QR_LOGO;
+ const hideLogo = data.hideLogo && !!isPro;
+ const logo = !isPro
+ ? DUB_QR_LOGO
+ : domainLogo || workspaceLogo || DUB_QR_LOGO;
const qrData = useMemo(
() =>
@@ -127,16 +96,15 @@ function LinkQRModalInner({
fgColor: data.fgColor,
hideLogo,
logo,
+ dotStyle: data.dotStyle,
+ markerCenterStyle: data.markerCenterStyle,
+ markerBorderStyle: data.markerBorderStyle,
+ markerColor: data.markerColor,
})
: null,
[url, data, hideLogo, logo],
);
- const onColorChange = useDebouncedCallback(
- (color: string) => setData((d) => ({ ...d, fgColor: color })),
- 500,
- );
-
return (
<form
className="flex flex-col gap-6 p-4"
@@ -144,11 +112,11 @@ function LinkQRModalInner({
e.preventDefault();
e.stopPropagation();
setShowLinkQRModal(false);
-
setDataPersisted(data);
onSave?.(data);
}}
>
+ {/* Header */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<h3 className="text-lg font-medium">QR Code</h3>
@@ -172,376 +140,81 @@ function LinkQRModalInner({
</div>
</div>
- <div>
- <div className="flex items-center justify-between gap-2">
- <div className="flex items-center gap-2">
- <span className="text-sm font-medium text-neutral-700">
- QR Code Preview
- </span>
- <InfoTooltip content="Customize your QR code to fit your brand. [Learn more.](https://dub.co/help/article/custom-qr-codes)" />
- </div>
- {url && qrData && (
- <div className="flex items-center gap-2">
- <DownloadPopover qrData={qrData} props={props}>
- <div>
- <ButtonTooltip
- tooltipProps={{
- content: "Download QR code",
- }}
- >
- <Download className="h-4 w-4 text-neutral-500" />
- </ButtonTooltip>
- </div>
- </DownloadPopover>
- <CopyPopover qrData={qrData} props={props}>
- <div>
- <ButtonTooltip
- tooltipProps={{
- content: "Copy QR code",
- }}
- >
- <Copy className="h-4 w-4 text-neutral-500" />
- </ButtonTooltip>
- </div>
- </CopyPopover>
+ <QRCodeDesignFields
+ data={data}
+ setData={setData}
+ url={url}
+ logo={logo}
+ linkProps={props}
+ qrData={qrData}
+ onClose={() => setShowLinkQRModal(false)}
+ logoSection={
+ <div>
+ <div className="flex items-center gap-1.5">
+ <label className="text-sm font-medium text-neutral-700">
+ Logo
+ </label>
+ <InfoTooltip content="Display your logo in the center of the QR code. [Learn more.](https://dub.co/help/article/custom-qr-codes)" />
</div>
- )}
- </div>
- <div className="relative mt-2 flex h-44 items-center justify-center overflow-hidden rounded-md border border-neutral-300">
- {!isMobile && (
- <ShimmerDots className="opacity-30 [mask-image:radial-gradient(40%_80%,transparent_50%,black)]" />
- )}
- {url && (
- <AnimatePresence mode="wait">
- <motion.div
- key={data.fgColor + data.hideLogo}
- initial={{ filter: "blur(2px)", opacity: 0.4 }}
- animate={{ filter: "blur(0px)", opacity: 1 }}
- exit={{ filter: "blur(2px)", opacity: 0.4 }}
- transition={{ duration: 0.1 }}
- className="relative flex size-full items-center justify-center"
- >
- <QRCode
- url={url}
- fgColor={data.fgColor}
- hideLogo={data.hideLogo}
- logo={logo}
- scale={1}
- />
- </motion.div>
- </AnimatePresence>
- )}
- </div>
- </div>
-
- {/* Logo toggle */}
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2">
- <label
- className="text-sm font-medium text-neutral-700"
- htmlFor={`${id}-show-logo`}
- >
- Logo
- </label>
- <InfoTooltip content="Display your logo in the center of the QR code. [Learn more.](https://dub.co/help/article/custom-qr-codes)" />
- </div>
- <Switch
- id={`${id}-hide-logo`}
- checked={!data.hideLogo}
- fn={() => {
- setData((d) => ({ ...d, hideLogo: !d.hideLogo }));
- }}
- disabledTooltip={
- !plan || plan === "free" ? (
- <TooltipContent
- title="You need to be on the Pro plan and above to customize your QR Code logo."
- cta="Upgrade to Pro"
- href={slug ? `/${slug}/upgrade` : "https://dub.co/pricing"}
- target="_blank"
- />
- ) : undefined
- }
- thumbIcon={
- !plan || plan === "free" ? (
- <CrownSmall className="size-full text-neutral-500" />
- ) : undefined
- }
- />
- </div>
-
- {/* Color selector */}
- <div>
- <span className="block text-sm font-medium text-neutral-700">
- QR Code Color
- </span>
- <div className="mt-2 flex gap-6">
- <div className="relative flex h-9 w-32 shrink-0 rounded-md shadow-sm">
- <Tooltip
- content={
- <div className="flex max-w-xs flex-col items-center space-y-3 p-5 text-center">
- <HexColorPicker
- color={data.fgColor}
- onChange={onColorChange}
- />
- </div>
- }
- >
- <div
- className="h-full w-12 rounded-l-md border"
- style={{
- backgroundColor: data.fgColor,
- borderColor: data.fgColor,
- }}
- />
- </Tooltip>
- <HexColorInput
- id="color"
- name="color"
- color={data.fgColor}
- onChange={onColorChange}
- prefixed
- style={{ borderColor: data.fgColor }}
- className="block w-full rounded-r-md border-2 border-l-0 pl-3 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-black sm:text-sm"
- />
- </div>
- <div className="mt-1 flex flex-wrap items-center gap-3">
- {DEFAULT_COLORS.map((color) => {
- const isSelected = data.fgColor === color;
- return (
- <button
- key={color}
- type="button"
- aria-pressed={isSelected}
- onClick={() => setData((d) => ({ ...d, fgColor: color }))}
- className={cn(
- "flex size-7 items-center justify-center rounded-full transition-all",
- isSelected
- ? "ring-1 ring-black ring-offset-[3px]"
- : "ring-black/10 hover:ring-4",
- )}
- style={{ backgroundColor: color }}
- >
- {isSelected && <Check2 className="size-4 text-white" />}
- </button>
- );
- })}
- </div>
- </div>
- </div>
-
- <div className="flex items-center justify-end gap-2">
- <Button
- type="button"
- variant="secondary"
- text="Cancel"
- className="h-9 w-fit"
- onClick={() => {
- setShowLinkQRModal(false);
- }}
- />
- <Button
- type="submit"
- variant="primary"
- text="Save changes"
- className="h-9 w-fit"
- />
- </div>
- </form>
- );
-}
-
-function DownloadPopover({
- qrData,
- props,
- children,
-}: PropsWithChildren<{
- qrData: ReturnType<typeof getQRData>;
- props: QRLinkProps;
-}>) {
- const anchorRef = useRef<HTMLAnchorElement>(null);
-
- function download(url: string, extension: string) {
- if (!anchorRef.current) return;
- anchorRef.current.href = url;
- anchorRef.current.download = `${props.key}-qrcode.${extension}`;
- anchorRef.current.click();
- setOpenPopover(false);
- }
-
- const [openPopover, setOpenPopover] = useState(false);
-
- return (
- <div>
- <Popover
- content={
- <div className="grid p-1 sm:min-w-48">
- <button
- type="button"
- onClick={async () => {
- download(await getQRAsSVGDataUri(qrData), "svg");
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Download SVG"
- icon={<Photo className="h-4 w-4" />}
- />
- </button>
- <button
- type="button"
- onClick={async () => {
- download(
- (await getQRAsCanvas(qrData, "image/png")) as string,
- "png",
- );
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
+ <SegmentedControl
+ activeIndex={data.hideLogo && isPro ? 1 : 0}
+ count={2}
+ disabled={!isPro}
>
- <IconMenu
- text="Download PNG"
- icon={<Photo className="h-4 w-4" />}
- />
- </button>
- <button
- type="button"
- onClick={async () => {
- download(
- (await getQRAsCanvas(qrData, "image/jpeg")) as string,
- "jpg",
- );
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Download JPEG"
- icon={<Photo className="h-4 w-4" />}
- />
- </button>
+ <SegmentTab
+ active={!data.hideLogo || !isPro}
+ onClick={() => setData((d) => ({ ...d, hideLogo: false }))}
+ disabled={!isPro}
+ >
+ <span className="text-sm">Show</span>
+ </SegmentTab>
+ <SegmentTab
+ active={!!(data.hideLogo && isPro)}
+ onClick={() => setData((d) => ({ ...d, hideLogo: true }))}
+ disabled={!isPro}
+ >
+ {!isPro && (
+ <Tooltip
+ content={
+ <TooltipContent
+ title="Upgrade to Pro to show or hide your QR code logo."
+ cta="Upgrade to Pro"
+ href={
+ slug ? `/${slug}/upgrade` : "https://dub.co/pricing"
+ }
+ target="_blank"
+ />
+ }
+ >
+ <Crown className="text-content-default mr-1 size-4" />
+ </Tooltip>
+ )}
+ <span className="text-sm">Hide</span>
+ </SegmentTab>
+ </SegmentedControl>
</div>
}
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- {children}
- </Popover>
- {/* This will be used to prompt downloads. */}
- <a
- className="hidden"
- download={`${props.key}-qrcode.svg`}
- ref={anchorRef}
/>
- </div>
- );
-}
-
-function CopyPopover({
- qrData,
- props,
- children,
-}: PropsWithChildren<{
- qrData: ReturnType<typeof getQRData>;
- props: QRLinkProps;
-}>) {
- const [openPopover, setOpenPopover] = useState(false);
- const [copiedURL, copyUrlToClipboard] = useCopyToClipboard(2000);
- const [copiedImage, copyImageToClipboard] = useCopyToClipboard(2000);
-
- const copyToClipboard = async () => {
- try {
- const canvas = await getQRAsCanvas(qrData, "image/png", true);
- (canvas as HTMLCanvasElement).toBlob(async function (blob) {
- // @ts-ignore
- const item = new ClipboardItem({ "image/png": blob });
- await copyImageToClipboard(item);
- setOpenPopover(false);
- });
- } catch (e) {
- throw e;
- }
- };
-
- return (
- <Popover
- content={
- <div className="grid p-1 sm:min-w-48">
- <button
- type="button"
- onClick={async () => {
- toast.promise(copyToClipboard, {
- loading: "Copying QR code to clipboard...",
- success: "Copied QR code to clipboard!",
- error: "Failed to copy",
- });
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Copy Image"
- icon={
- copiedImage ? (
- <Check className="h-4 w-4" />
- ) : (
- <Photo className="h-4 w-4" />
- )
- }
- />
- </button>
- <button
- type="button"
- onClick={() => {
- const url = `${API_DOMAIN}/qr?url=${linkConstructor({
- key: props.key,
- domain: props.domain,
- searchParams: {
- qr: "1",
- },
- })}${qrData.hideLogo ? "&hideLogo=true" : ""}`;
- toast.promise(copyUrlToClipboard(url), {
- success: "Copied QR code URL to clipboard!",
- });
- setOpenPopover(false);
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Copy URL"
- icon={
- copiedURL ? (
- <Check className="h-4 w-4" />
- ) : (
- <Hyperlink className="h-4 w-4" />
- )
- }
- />
- </button>
- </div>
- }
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- {children}
- </Popover>
+ </form>
);
}
export function useLinkQRModal(props: LinkQRModalProps) {
const [showLinkQRModal, setShowLinkQRModal] = useState(false);
- const LinkQRModalCallback = useCallback(() => {
- return (
+ const LinkQRModalCallback = useCallback(
+ () => (
<LinkQRModal
showLinkQRModal={showLinkQRModal}
setShowLinkQRModal={setShowLinkQRModal}
{...props}
/>
- );
- }, [showLinkQRModal, setShowLinkQRModal]);
+ ),
+ [showLinkQRModal, setShowLinkQRModal, props],
+ );
return useMemo(
- () => ({
- setShowLinkQRModal,
- LinkQRModal: LinkQRModalCallback,
- }),
+ () => ({ setShowLinkQRModal, LinkQRModal: LinkQRModalCallback }),
[setShowLinkQRModal, LinkQRModalCallback],
);
}
diff --git a/apps/web/ui/modals/partner-link-modal.tsx b/apps/web/ui/modals/partner-link-modal.tsx
index 46f9da53cc..ce228bc3ef 100644
--- a/apps/web/ui/modals/partner-link-modal.tsx
+++ b/apps/web/ui/modals/partner-link-modal.tsx
@@ -98,7 +98,7 @@ function QRCodePreview({
`qr-code-design-program-${programEnrollment?.program?.id}`,
{
fgColor: "#000000",
- logo: logo ?? undefined,
+ hideLogo: false,
},
);
diff --git a/apps/web/ui/modals/partner-link-qr-modal.tsx b/apps/web/ui/modals/partner-link-qr-modal.tsx
index d016afb2de..de16fca740 100644
--- a/apps/web/ui/modals/partner-link-qr-modal.tsx
+++ b/apps/web/ui/modals/partner-link-qr-modal.tsx
@@ -1,51 +1,19 @@
-import { getQRAsCanvas, getQRAsSVGDataUri, getQRData } from "@/lib/qr";
+import { getQRData } from "@/lib/qr";
+import { QRCodeDesign } from "@/lib/qr/types";
import useProgramEnrollment from "@/lib/swr/use-program-enrollment";
import { QRLinkProps } from "@/lib/types";
-import { QRCode } from "@/ui/shared/qr-code";
-import {
- Button,
- ButtonTooltip,
- IconMenu,
- InfoTooltip,
- Modal,
- Popover,
- ShimmerDots,
- Tooltip,
- useCopyToClipboard,
- useLocalStorage,
- useMediaQuery,
-} from "@dub/ui";
-import { Check, Copy, Download, Hyperlink, Photo } from "@dub/ui/icons";
-import { API_DOMAIN, linkConstructor } from "@dub/utils";
-import { AnimatePresence, motion } from "motion/react";
+import { InfoTooltip, Modal, useLocalStorage } from "@dub/ui";
+import { linkConstructor } from "@dub/utils";
import {
Dispatch,
- PropsWithChildren,
SetStateAction,
useCallback,
useMemo,
- useRef,
useState,
} from "react";
-import { HexColorInput, HexColorPicker } from "react-colorful";
-import { toast } from "sonner";
-import { useDebouncedCallback } from "use-debounce";
-
-const DEFAULT_COLORS = [
- "#000000",
- "#C73E33",
- "#DF6547",
- "#F4B3D7",
- "#F6CF54",
- "#49A065",
- "#2146B7",
- "#AE49BF",
-];
+import { DEFAULT_QR_DESIGN, QRCodeDesignFields } from "./qr-code-design-fields";
-export type QRCodeDesign = {
- fgColor: string;
- logo?: string;
-};
+export type { QRCodeDesign };
type PartnerLinkQRModalProps = {
props: QRLinkProps;
@@ -77,25 +45,23 @@ function PartnerLinkQRModalInner({
showLinkQRModal: boolean;
setShowLinkQRModal: Dispatch<SetStateAction<boolean>>;
} & PartnerLinkQRModalProps) {
- const { isMobile } = useMediaQuery();
const { programEnrollment } = useProgramEnrollment();
const { logo } = programEnrollment?.program ?? {};
- const url = useMemo(() => {
- return props.key && props.domain
- ? linkConstructor({ key: props.key, domain: props.domain })
- : undefined;
- }, [props.key, props.domain]);
+ const url = useMemo(
+ () =>
+ props.key && props.domain
+ ? linkConstructor({ key: props.key, domain: props.domain })
+ : undefined,
+ [props.key, props.domain],
+ );
const [dataPersisted, setDataPersisted] = useLocalStorage<QRCodeDesign>(
`qr-code-design-program-${programEnrollment?.program?.id}`,
- {
- fgColor: "#000000",
- logo: logo ?? undefined,
- },
+ DEFAULT_QR_DESIGN,
);
- const [data, setData] = useState(dataPersisted);
+ const [data, setData] = useState<QRCodeDesign>(dataPersisted);
const qrData = useMemo(
() =>
@@ -104,16 +70,15 @@ function PartnerLinkQRModalInner({
url,
fgColor: data.fgColor,
logo: logo ?? undefined,
+ dotStyle: data.dotStyle,
+ markerCenterStyle: data.markerCenterStyle,
+ markerBorderStyle: data.markerBorderStyle,
+ markerColor: data.markerColor,
})
: null,
[url, data, logo],
);
- const onColorChange = useDebouncedCallback(
- (color: string) => setData((d) => ({ ...d, fgColor: color })),
- 500,
- );
-
return (
<form
className="flex flex-col gap-6 p-4"
@@ -125,339 +90,41 @@ function PartnerLinkQRModalInner({
onSave?.(data);
}}
>
+ {/* Header */}
<div className="flex items-center gap-2">
<h3 className="text-lg font-medium">QR Code</h3>
<InfoTooltip content="Set a custom QR code design to improve click-through rates. [Learn more.](https://dub.co/help/article/custom-qr-codes)" />
</div>
- <div>
- <div className="flex items-center justify-between gap-2">
- <div className="flex items-center gap-2">
- <span className="text-sm font-medium text-neutral-700">
- QR Code Preview
- </span>
- <InfoTooltip content="Customize your QR code to fit your brand. [Learn more.](https://dub.co/help/article/custom-qr-codes)" />
- </div>
- {url && qrData && (
- <div className="flex items-center gap-2">
- <DownloadPopover qrData={qrData} props={props}>
- <div>
- <ButtonTooltip
- tooltipProps={{
- content: "Download QR code",
- }}
- >
- <Download className="h-4 w-4 text-neutral-500" />
- </ButtonTooltip>
- </div>
- </DownloadPopover>
- <CopyPopover qrData={qrData} props={props}>
- <div>
- <ButtonTooltip
- tooltipProps={{
- content: "Copy QR code",
- }}
- >
- <Copy className="h-4 w-4 text-neutral-500" />
- </ButtonTooltip>
- </div>
- </CopyPopover>
- </div>
- )}
- </div>
- <div className="relative mt-2 flex h-44 items-center justify-center overflow-hidden rounded-md border border-neutral-300">
- {!isMobile && (
- <ShimmerDots className="opacity-30 [mask-image:radial-gradient(40%_80%,transparent_50%,black)]" />
- )}
- {url && (
- <AnimatePresence mode="wait">
- <motion.div
- key={data.fgColor}
- initial={{ filter: "blur(2px)", opacity: 0.4 }}
- animate={{ filter: "blur(0px)", opacity: 1 }}
- exit={{ filter: "blur(2px)", opacity: 0.4 }}
- transition={{ duration: 0.1 }}
- className="relative flex size-full items-center justify-center"
- >
- <QRCode url={url} scale={1} {...data} />
- </motion.div>
- </AnimatePresence>
- )}
- </div>
- </div>
-
- {/* Color selector */}
- <div>
- <span className="block text-sm font-medium text-neutral-700">
- QR Code Color
- </span>
- <div className="mt-2 flex gap-6">
- <div className="relative flex h-9 w-32 shrink-0 rounded-md shadow-sm">
- <Tooltip
- content={
- <div className="flex max-w-xs flex-col items-center space-y-3 p-5 text-center">
- <HexColorPicker
- color={data.fgColor}
- onChange={onColorChange}
- />
- </div>
- }
- >
- <div
- className="h-full w-12 rounded-l-md border"
- style={{
- backgroundColor: data.fgColor,
- borderColor: data.fgColor,
- }}
- />
- </Tooltip>
- <HexColorInput
- id="color"
- name="color"
- color={data.fgColor}
- onChange={onColorChange}
- prefixed
- style={{ borderColor: data.fgColor }}
- className="block w-full rounded-r-md border-2 border-l-0 pl-3 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-black sm:text-sm"
- />
- </div>
- <div className="mt-1 flex flex-wrap items-center gap-3">
- {DEFAULT_COLORS.map((color) => {
- const isSelected = data.fgColor === color;
- return (
- <button
- key={color}
- type="button"
- aria-pressed={isSelected}
- onClick={() => setData((d) => ({ ...d, fgColor: color }))}
- className={`flex size-7 items-center justify-center rounded-full transition-all ${
- isSelected
- ? "ring-1 ring-black ring-offset-[3px]"
- : "ring-black/10 hover:ring-4"
- }`}
- style={{ backgroundColor: color }}
- >
- {isSelected && <Check className="size-4 text-white" />}
- </button>
- );
- })}
- </div>
- </div>
- </div>
-
- <div className="flex items-center justify-end gap-2">
- <Button
- type="button"
- variant="secondary"
- text="Cancel"
- className="h-9 w-fit"
- onClick={() => {
- setShowLinkQRModal(false);
- }}
- />
- <Button
- type="submit"
- variant="primary"
- text="Save changes"
- className="h-9 w-fit"
- />
- </div>
- </form>
- );
-}
-
-function DownloadPopover({
- qrData,
- props,
- children,
-}: PropsWithChildren<{
- qrData: ReturnType<typeof getQRData>;
- props: QRLinkProps;
-}>) {
- const anchorRef = useRef<HTMLAnchorElement>(null);
-
- function download(url: string, extension: string) {
- if (!anchorRef.current) return;
- anchorRef.current.href = url;
- anchorRef.current.download = `${props.key}-qrcode.${extension}`;
- anchorRef.current.click();
- setOpenPopover(false);
- }
-
- const [openPopover, setOpenPopover] = useState(false);
-
- return (
- <div>
- <Popover
- content={
- <div className="grid p-1 sm:min-w-48">
- <button
- type="button"
- onClick={async () => {
- download(await getQRAsSVGDataUri(qrData), "svg");
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Download SVG"
- icon={<Photo className="h-4 w-4" />}
- />
- </button>
- <button
- type="button"
- onClick={async () => {
- download(
- (await getQRAsCanvas(qrData, "image/png")) as string,
- "png",
- );
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Download PNG"
- icon={<Photo className="h-4 w-4" />}
- />
- </button>
- <button
- type="button"
- onClick={async () => {
- download(
- (await getQRAsCanvas(qrData, "image/jpeg")) as string,
- "jpg",
- );
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Download JPEG"
- icon={<Photo className="h-4 w-4" />}
- />
- </button>
- </div>
- }
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- {children}
- </Popover>
- {/* This will be used to prompt downloads. */}
- <a
- className="hidden"
- download={`${props.key}-qrcode.svg`}
- ref={anchorRef}
+ <QRCodeDesignFields
+ data={data}
+ setData={setData}
+ url={url}
+ logo={logo ?? undefined}
+ linkProps={props}
+ qrData={qrData}
+ onClose={() => setShowLinkQRModal(false)}
/>
- </div>
- );
-}
-
-function CopyPopover({
- qrData,
- props,
- children,
-}: PropsWithChildren<{
- qrData: ReturnType<typeof getQRData>;
- props: QRLinkProps;
-}>) {
- const [openPopover, setOpenPopover] = useState(false);
- const [copiedURL, copyUrlToClipboard] = useCopyToClipboard(2000);
- const [copiedImage, copyImageToClipboard] = useCopyToClipboard(2000);
-
- const copyToClipboard = async () => {
- try {
- const canvas = await getQRAsCanvas(qrData, "image/png", true);
- (canvas as HTMLCanvasElement).toBlob(async function (blob) {
- // @ts-ignore
- const item = new ClipboardItem({ "image/png": blob });
- await copyImageToClipboard(item);
- setOpenPopover(false);
- });
- } catch (e) {
- throw e;
- }
- };
-
- return (
- <Popover
- content={
- <div className="grid p-1 sm:min-w-48">
- <button
- type="button"
- onClick={async () => {
- toast.promise(copyToClipboard, {
- loading: "Copying QR code to clipboard...",
- success: "Copied QR code to clipboard!",
- error: "Failed to copy",
- });
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Copy Image"
- icon={
- copiedImage ? (
- <Check className="h-4 w-4" />
- ) : (
- <Photo className="h-4 w-4" />
- )
- }
- />
- </button>
- <button
- type="button"
- onClick={() => {
- const url = `${API_DOMAIN}/qr?url=${linkConstructor({
- key: props.key,
- domain: props.domain,
- searchParams: {
- qr: "1",
- },
- })}`;
- toast.promise(copyUrlToClipboard(url), {
- success: "Copied QR code URL to clipboard!",
- });
- setOpenPopover(false);
- }}
- className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
- >
- <IconMenu
- text="Copy URL"
- icon={
- copiedURL ? (
- <Check className="h-4 w-4" />
- ) : (
- <Hyperlink className="h-4 w-4" />
- )
- }
- />
- </button>
- </div>
- }
- openPopover={openPopover}
- setOpenPopover={setOpenPopover}
- >
- {children}
- </Popover>
+ </form>
);
}
export function usePartnerLinkQRModal(props: PartnerLinkQRModalProps) {
const [showLinkQRModal, setShowLinkQRModal] = useState(false);
- const LinkQRModalCallback = useCallback(() => {
- return (
+ const LinkQRModalCallback = useCallback(
+ () => (
<PartnerLinkQRModal
showLinkQRModal={showLinkQRModal}
setShowLinkQRModal={setShowLinkQRModal}
{...props}
/>
- );
- }, [showLinkQRModal, setShowLinkQRModal]);
+ ),
+ [showLinkQRModal, setShowLinkQRModal, props],
+ );
return useMemo(
- () => ({
- setShowLinkQRModal,
- LinkQRModal: LinkQRModalCallback,
- }),
+ () => ({ setShowLinkQRModal, LinkQRModal: LinkQRModalCallback }),
[setShowLinkQRModal, LinkQRModalCallback],
);
}
diff --git a/apps/web/ui/modals/qr-code-design-fields.tsx b/apps/web/ui/modals/qr-code-design-fields.tsx
new file mode 100644
index 0000000000..5eba4cdf23
--- /dev/null
+++ b/apps/web/ui/modals/qr-code-design-fields.tsx
@@ -0,0 +1,826 @@
+import { getQRAsCanvas, getQRAsSVGDataUri, getQRData } from "@/lib/qr";
+import { QRCodeDesign } from "@/lib/qr/types";
+import { QRLinkProps } from "@/lib/types";
+import { QRCode } from "@/ui/shared/qr-code";
+import {
+ Button,
+ ButtonTooltip,
+ IconMenu,
+ InfoTooltip,
+ Popover,
+ ShimmerDots,
+ Tooltip,
+ useCopyToClipboard,
+ useMediaQuery,
+} from "@dub/ui";
+import { Check, Check2, Copy, Download, Hyperlink, Photo } from "@dub/ui/icons";
+import { API_DOMAIN, cn, linkConstructor } from "@dub/utils";
+import { AnimatePresence, motion } from "motion/react";
+import {
+ Dispatch,
+ PropsWithChildren,
+ SetStateAction,
+ useId,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { HexColorInput, HexColorPicker } from "react-colorful";
+import { toast } from "sonner";
+import { useDebouncedCallback } from "use-debounce";
+
+// ─── Constants ────────────────────────────────────────────────────────────────
+
+export const DEFAULT_COLORS = [
+ "#000000",
+ "#C73E33",
+ "#DF6547",
+ "#F4B3D7",
+ "#F6CF54",
+ "#49A065",
+ "#2146B7",
+ "#AE49BF",
+];
+
+export const DEFAULT_QR_DESIGN: QRCodeDesign = {
+ fgColor: "#000000",
+ hideLogo: false,
+ dotStyle: "square",
+ markerCenterStyle: "square",
+ markerBorderStyle: "square",
+};
+
+// ─── Shared form body ─────────────────────────────────────────────────────────
+
+/**
+ * The inner content of the QR code design form — preview, style toggles, color
+ * pickers, and action buttons. Both link and partner modals render this,
+ * differing only in their header and the optional `logoSection` slot.
+ */
+export function QRCodeDesignFields({
+ data,
+ setData,
+ url,
+ logo,
+ linkProps,
+ qrData,
+ onClose,
+ logoSection,
+}: {
+ data: QRCodeDesign;
+ setData: Dispatch<SetStateAction<QRCodeDesign>>;
+ url?: string;
+ logo?: string;
+ linkProps: QRLinkProps;
+ qrData: ReturnType<typeof getQRData> | null;
+ onClose: () => void;
+ /** Optional slot rendered left of Dot style (link modal uses this for Logo toggle). */
+ logoSection?: React.ReactNode;
+}) {
+ const id = useId();
+ const { isMobile } = useMediaQuery();
+
+ const onColorChange = useDebouncedCallback(
+ (color: string) => setData((d) => ({ ...d, fgColor: color })),
+ 500,
+ );
+
+ const onMarkerColorChange = useDebouncedCallback(
+ (color: string) => setData((d) => ({ ...d, markerColor: color })),
+ 500,
+ );
+
+ const previewKey = `${data.fgColor}-${data.hideLogo}-${data.dotStyle}-${data.markerCenterStyle}-${data.markerBorderStyle}-${data.markerColor ?? ""}`;
+
+ return (
+ <>
+ {/* Preview */}
+ <div>
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-neutral-700">
+ QR Code Preview
+ </span>
+ <InfoTooltip content="Customize your QR code to fit your brand. [Learn more.](https://dub.co/help/article/custom-qr-codes)" />
+ </div>
+ {url && qrData && (
+ <div className="flex items-center gap-2">
+ <DownloadPopover qrData={qrData} linkProps={linkProps}>
+ <div>
+ <ButtonTooltip tooltipProps={{ content: "Download QR code" }}>
+ <Download className="h-4 w-4 text-neutral-500" />
+ </ButtonTooltip>
+ </div>
+ </DownloadPopover>
+ <CopyPopover qrData={qrData} linkProps={linkProps}>
+ <div>
+ <ButtonTooltip tooltipProps={{ content: "Copy QR code" }}>
+ <Copy className="h-4 w-4 text-neutral-500" />
+ </ButtonTooltip>
+ </div>
+ </CopyPopover>
+ </div>
+ )}
+ </div>
+ <div className="relative mt-2 flex h-44 items-center justify-center overflow-hidden rounded-md border border-neutral-300">
+ {!isMobile && (
+ <ShimmerDots className="opacity-30 [mask-image:radial-gradient(40%_80%,transparent_50%,black)]" />
+ )}
+ {url && (
+ <AnimatePresence mode="wait">
+ <motion.div
+ key={previewKey}
+ initial={{ filter: "blur(2px)", opacity: 0.4 }}
+ animate={{ filter: "blur(0px)", opacity: 1 }}
+ exit={{ filter: "blur(2px)", opacity: 0.4 }}
+ transition={{ duration: 0.1 }}
+ className="relative flex size-full items-center justify-center"
+ >
+ <QRCode
+ url={url}
+ fgColor={data.fgColor}
+ hideLogo={data.hideLogo}
+ logo={logo}
+ scale={1}
+ dotStyle={data.dotStyle}
+ markerCenterStyle={data.markerCenterStyle}
+ markerBorderStyle={data.markerBorderStyle}
+ markerColor={data.markerColor}
+ />
+ </motion.div>
+ </AnimatePresence>
+ )}
+ </div>
+ </div>
+
+ {/* Logo slot + Dot style */}
+ <div className={cn(logoSection && "grid grid-cols-2 gap-4")}>
+ {logoSection}
+ <div>
+ <div className="flex items-center gap-1.5">
+ <label className="text-sm font-medium text-neutral-700">
+ Dot style
+ </label>
+ </div>
+ <SegmentedControl
+ activeIndex={
+ data.dotStyle === "rounded"
+ ? 1
+ : data.dotStyle === "extra-rounded"
+ ? 2
+ : 0
+ }
+ count={3}
+ >
+ <SegmentTab
+ active={!data.dotStyle || data.dotStyle === "square"}
+ onClick={() => setData((d) => ({ ...d, dotStyle: "square" }))}
+ ariaLabel="Square dots"
+ >
+ <SquareDotIcon />
+ </SegmentTab>
+ <SegmentTab
+ active={data.dotStyle === "rounded"}
+ onClick={() => setData((d) => ({ ...d, dotStyle: "rounded" }))}
+ ariaLabel="Rounded dots"
+ >
+ <RoundedDotIcon />
+ </SegmentTab>
+ <SegmentTab
+ active={data.dotStyle === "extra-rounded"}
+ onClick={() =>
+ setData((d) => ({ ...d, dotStyle: "extra-rounded" }))
+ }
+ ariaLabel="Extra-rounded dots"
+ >
+ <ExtraRoundedDotIcon />
+ </SegmentTab>
+ </SegmentedControl>
+ </div>
+ </div>
+
+ {/* Marker center + Marker border */}
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <div className="flex items-center gap-1.5">
+ <label className="text-sm font-medium text-neutral-700">
+ Marker center
+ </label>
+ </div>
+ <SegmentedControl
+ activeIndex={data.markerCenterStyle === "circle" ? 1 : 0}
+ count={2}
+ >
+ <SegmentTab
+ active={
+ !data.markerCenterStyle || data.markerCenterStyle === "square"
+ }
+ onClick={() =>
+ setData((d) => ({ ...d, markerCenterStyle: "square" }))
+ }
+ ariaLabel="Square marker center"
+ >
+ <MarkerCenterSquareIcon />
+ </SegmentTab>
+ <SegmentTab
+ active={data.markerCenterStyle === "circle"}
+ onClick={() =>
+ setData((d) => ({ ...d, markerCenterStyle: "circle" }))
+ }
+ ariaLabel="Circle marker center"
+ >
+ <MarkerCenterCircleIcon />
+ </SegmentTab>
+ </SegmentedControl>
+ </div>
+
+ <div>
+ <div className="flex items-center gap-1.5">
+ <label className="text-sm font-medium text-neutral-700">
+ Marker border
+ </label>
+ </div>
+ <SegmentedControl
+ activeIndex={
+ data.markerBorderStyle === "rounded-square"
+ ? 1
+ : data.markerBorderStyle === "circle"
+ ? 2
+ : 0
+ }
+ count={3}
+ >
+ <SegmentTab
+ active={
+ !data.markerBorderStyle || data.markerBorderStyle === "square"
+ }
+ onClick={() =>
+ setData((d) => ({ ...d, markerBorderStyle: "square" }))
+ }
+ ariaLabel="Square marker border"
+ >
+ <MarkerBorderSquareIcon />
+ </SegmentTab>
+ <SegmentTab
+ active={data.markerBorderStyle === "rounded-square"}
+ onClick={() =>
+ setData((d) => ({
+ ...d,
+ markerBorderStyle: "rounded-square",
+ }))
+ }
+ ariaLabel="Rounded marker border"
+ >
+ <MarkerBorderRoundedIcon />
+ </SegmentTab>
+ <SegmentTab
+ active={data.markerBorderStyle === "circle"}
+ onClick={() =>
+ setData((d) => ({ ...d, markerBorderStyle: "circle" }))
+ }
+ ariaLabel="Circle marker border"
+ >
+ <MarkerBorderCircleIcon />
+ </SegmentTab>
+ </SegmentedControl>
+ </div>
+ </div>
+
+ <ColorSection
+ id={`${id}-fg`}
+ label="Dot Color"
+ color={data.fgColor}
+ onChange={onColorChange}
+ onSwatchClick={(color) => setData((d) => ({ ...d, fgColor: color }))}
+ />
+
+ <ColorSection
+ id={`${id}-marker`}
+ label="Marker Color"
+ tooltip="Set a different color for the finder pattern markers. Defaults to the QR code color."
+ color={data.markerColor ?? data.fgColor}
+ onChange={onMarkerColorChange}
+ onSwatchClick={(color) =>
+ setData((d) => ({ ...d, markerColor: color }))
+ }
+ extraAction={
+ data.markerColor && data.markerColor !== data.fgColor ? (
+ <button
+ type="button"
+ onClick={() => setData((d) => ({ ...d, markerColor: undefined }))}
+ className="text-xs text-neutral-400 underline-offset-2 hover:text-neutral-600 hover:underline"
+ >
+ Match dot color
+ </button>
+ ) : undefined
+ }
+ />
+
+ <div className="flex items-center justify-end gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Cancel"
+ className="h-9 w-fit"
+ onClick={onClose}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ text="Save changes"
+ className="h-9 w-fit"
+ />
+ </div>
+ </>
+ );
+}
+
+// ─── Segmented control ────────────────────────────────────────────────────────
+
+export function SegmentedControl({
+ activeIndex,
+ count,
+ disabled,
+ children,
+}: {
+ activeIndex: number;
+ count: number;
+ disabled?: boolean;
+ children: React.ReactNode;
+}) {
+ return (
+ <div
+ className={cn(
+ "relative mt-1 flex h-11 rounded-xl border border-neutral-200 bg-neutral-50 p-1",
+ disabled && "opacity-50",
+ )}
+ >
+ <div
+ className="pointer-events-none absolute inset-y-1 left-1 rounded-lg bg-white"
+ style={{
+ width: `calc((100% - 8px) / ${count})`,
+ transform: `translateX(calc(${activeIndex} * 100%))`,
+ transition: "transform 200ms cubic-bezier(0.23, 1, 0.32, 1)",
+ boxShadow:
+ "0px 2px 6px 0px rgba(0,0,0,0.10), 0px 0px 2px 0px rgba(0,0,0,0.05)",
+ }}
+ />
+ {children}
+ </div>
+ );
+}
+
+export function SegmentTab({
+ active,
+ onClick,
+ disabled,
+ ariaLabel,
+ children,
+}: {
+ active: boolean;
+ onClick: () => void;
+ disabled?: boolean;
+ ariaLabel?: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ disabled={disabled}
+ aria-label={ariaLabel}
+ aria-pressed={active}
+ className={cn(
+ "relative flex flex-1 items-center justify-center rounded-lg text-neutral-700",
+ disabled && "cursor-not-allowed",
+ )}
+ >
+ {children}
+ </button>
+ );
+}
+
+// ─── Color section ────────────────────────────────────────────────────────────
+
+export function ColorSection({
+ id,
+ label,
+ tooltip,
+ color,
+ onChange,
+ onSwatchClick,
+ extraAction,
+}: {
+ id: string;
+ label: string;
+ tooltip?: string;
+ color: string;
+ onChange: (color: string) => void;
+ onSwatchClick: (color: string) => void;
+ extraAction?: React.ReactNode;
+}) {
+ return (
+ <div>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className="block text-sm font-medium text-neutral-700">
+ {label}
+ </span>
+ {tooltip && <InfoTooltip content={tooltip} />}
+ </div>
+ {extraAction}
+ </div>
+ <div className="mt-2 flex gap-6">
+ <div className="relative flex h-9 w-32 shrink-0 rounded-md shadow-sm">
+ <Tooltip
+ content={
+ <div className="flex max-w-xs flex-col items-center space-y-3 p-5 text-center">
+ <HexColorPicker color={color} onChange={onChange} />
+ </div>
+ }
+ >
+ <div
+ className="h-full w-12 rounded-l-md border"
+ style={{ backgroundColor: color, borderColor: color }}
+ />
+ </Tooltip>
+ <HexColorInput
+ id={id}
+ name={id}
+ color={color}
+ onChange={onChange}
+ prefixed
+ style={{ borderColor: color }}
+ className="block w-full rounded-r-md border-2 border-l-0 pl-3 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-black sm:text-sm"
+ />
+ </div>
+ <div className="mt-1 flex flex-wrap items-center gap-3">
+ {DEFAULT_COLORS.map((swatch) => {
+ const isSelected = color === swatch;
+ return (
+ <button
+ key={swatch}
+ type="button"
+ aria-pressed={isSelected}
+ onClick={() => onSwatchClick(swatch)}
+ className={cn(
+ "flex size-7 items-center justify-center rounded-full transition-all",
+ isSelected
+ ? "ring-1 ring-black ring-offset-[3px]"
+ : "ring-black/10 hover:ring-4",
+ )}
+ style={{ backgroundColor: swatch }}
+ >
+ {isSelected && <Check2 className="size-4 text-white" />}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// ─── Style icons ──────────────────────────────────────────────────────────────
+
+export function SquareDotIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <rect width="5" height="5" />
+ <rect x="10" width="5" height="5" />
+ <rect x="5" y="10" width="5" height="5" />
+ <rect x="15" width="5" height="5" />
+ <rect x="15" y="10" width="5" height="5" />
+ <rect y="5" width="5" height="5" />
+ <rect y="15" width="5" height="5" />
+ <rect x="10" y="5" width="5" height="5" />
+ <rect x="15" y="15" width="5" height="5" />
+ <rect x="10" y="15" width="5" height="5" />
+ </svg>
+ );
+}
+
+export function RoundedDotIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path d="M0 2.5C0 1.11929 1.11929 0 2.5 0C3.88071 0 5 1.11929 5 2.5C5 3.88071 3.88071 5 2.5 5C1.11929 5 0 3.88071 0 2.5Z" />
+ <path d="M10 2.5C10 1.11929 11.1193 0 12.5 0C13.8807 0 15 1.11929 15 2.5C15 3.88071 13.8807 5 12.5 5C11.1193 5 10 3.88071 10 2.5Z" />
+ <path d="M5 12.5C5 11.1193 6.11929 10 7.5 10C8.88071 10 10 11.1193 10 12.5C10 13.8807 8.88071 15 7.5 15C6.11929 15 5 13.8807 5 12.5Z" />
+ <path d="M15 2.5C15 1.11929 16.1193 0 17.5 0C18.8807 0 20 1.11929 20 2.5C20 3.88071 18.8807 5 17.5 5C16.1193 5 15 3.88071 15 2.5Z" />
+ <path d="M15 12.5C15 11.1193 16.1193 10 17.5 10C18.8807 10 20 11.1193 20 12.5C20 13.8807 18.8807 15 17.5 15C16.1193 15 15 13.8807 15 12.5Z" />
+ <path d="M0 7.5C0 6.11929 1.11929 5 2.5 5C3.88071 5 5 6.11929 5 7.5C5 8.88071 3.88071 10 2.5 10C1.11929 10 0 8.88071 0 7.5Z" />
+ <path d="M0 17.5C0 16.1193 1.11929 15 2.5 15C3.88071 15 5 16.1193 5 17.5C5 18.8807 3.88071 20 2.5 20C1.11929 20 0 18.8807 0 17.5Z" />
+ <path d="M10 7.5C10 6.11929 11.1193 5 12.5 5C13.8807 5 15 6.11929 15 7.5C15 8.88071 13.8807 10 12.5 10C11.1193 10 10 8.88071 10 7.5Z" />
+ <path d="M15 17.5C15 16.1193 16.1193 15 17.5 15C18.8807 15 20 16.1193 20 17.5C20 18.8807 18.8807 20 17.5 20C16.1193 20 15 18.8807 15 17.5Z" />
+ <path d="M10 17.5C10 16.1193 11.1193 15 12.5 15C13.8807 15 15 16.1193 15 17.5C15 18.8807 13.8807 20 12.5 20C11.1193 20 10 18.8807 10 17.5Z" />
+ </svg>
+ );
+}
+
+export function ExtraRoundedDotIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="currentColor"
+ aria-hidden="true"
+ >
+ <path d="M5 12.5C5 11.1193 6.11929 10 7.5 10C8.88071 10 10 11.1193 10 12.5C10 13.8807 8.88071 15 7.5 15C6.11929 15 5 13.8807 5 12.5Z" />
+ <path d="M5 7.5C5 8.88071 3.88071 10 2.5 10C1.11929 10 0 8.88071 0 7.5V2.5C0 1.11929 1.11929 0 2.5 0C3.88071 0 5 1.11929 5 2.5V7.5Z" />
+ <path d="M0 17.5C0 16.1193 1.11929 15 2.5 15C3.88071 15 5 16.1193 5 17.5C5 18.8807 3.88071 20 2.5 20C1.11929 20 0 18.8807 0 17.5Z" />
+ <path d="M15 7.5C15 8.88071 13.8807 10 12.5 10C11.1193 10 10 8.88071 10 7.5V5C10 2.23858 12.2386 0 15 0H17.5C18.8807 0 20 1.11929 20 2.5C20 3.88071 18.8807 5 17.5 5H15V7.5Z" />
+ <path d="M20 15C20 17.7614 17.7614 20 15 20H12.5C11.1193 20 10 18.8807 10 17.5C10 16.1193 11.1193 15 12.5 15H15V12.5C15 11.1193 16.1193 10 17.5 10C18.8807 10 20 11.1193 20 12.5V15Z" />
+ </svg>
+ );
+}
+
+export function MarkerCenterSquareIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="none"
+ aria-hidden="true"
+ >
+ <rect
+ x="1.25"
+ y="1.25"
+ width="17.5"
+ height="17.5"
+ stroke="currentColor"
+ strokeOpacity="0.35"
+ strokeWidth="2.5"
+ />
+ <rect x="5" y="5" width="10" height="10" fill="currentColor" />
+ </svg>
+ );
+}
+
+export function MarkerCenterCircleIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="none"
+ aria-hidden="true"
+ >
+ <rect
+ x="1.25"
+ y="1.25"
+ width="17.5"
+ height="17.5"
+ stroke="currentColor"
+ strokeOpacity="0.35"
+ strokeWidth="2.5"
+ />
+ <path
+ d="M5 10C5 7.23858 7.23858 5 10 5C12.7614 5 15 7.23858 15 10C15 12.7614 12.7614 15 10 15C7.23858 15 5 12.7614 5 10Z"
+ fill="currentColor"
+ />
+ </svg>
+ );
+}
+
+export function MarkerBorderSquareIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="none"
+ aria-hidden="true"
+ >
+ <rect
+ x="1.25"
+ y="1.25"
+ width="17.5"
+ height="17.5"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ />
+ </svg>
+ );
+}
+
+export function MarkerBorderRoundedIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="none"
+ aria-hidden="true"
+ >
+ <path
+ d="M5 1.25H15C17.0711 1.25 18.75 2.92893 18.75 5V15C18.75 17.0711 17.0711 18.75 15 18.75H5C2.92893 18.75 1.25 17.0711 1.25 15V5C1.25 2.92893 2.92893 1.25 5 1.25Z"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ />
+ </svg>
+ );
+}
+
+export function MarkerBorderCircleIcon() {
+ return (
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 20 20"
+ fill="none"
+ aria-hidden="true"
+ >
+ <path
+ d="M10 1.25C14.8325 1.25 18.75 5.16751 18.75 10C18.75 14.8325 14.8325 18.75 10 18.75C5.16751 18.75 1.25 14.8325 1.25 10C1.25 5.16751 5.16751 1.25 10 1.25Z"
+ stroke="currentColor"
+ strokeWidth="2.5"
+ />
+ </svg>
+ );
+}
+
+// ─── Download / Copy popovers ─────────────────────────────────────────────────
+
+export function DownloadPopover({
+ qrData,
+ linkProps,
+ children,
+}: PropsWithChildren<{
+ qrData: ReturnType<typeof getQRData>;
+ linkProps: QRLinkProps;
+}>) {
+ const anchorRef = useRef<HTMLAnchorElement>(null);
+ const [openPopover, setOpenPopover] = useState(false);
+
+ function download(url: string, extension: string) {
+ if (!anchorRef.current) return;
+ anchorRef.current.href = url;
+ anchorRef.current.download = `${linkProps.key}-qrcode.${extension}`;
+ anchorRef.current.click();
+ setOpenPopover(false);
+ }
+
+ return (
+ <div>
+ <Popover
+ content={
+ <div className="grid p-1 sm:min-w-48">
+ <button
+ type="button"
+ onClick={async () =>
+ download(await getQRAsSVGDataUri(qrData), "svg")
+ }
+ className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
+ >
+ <IconMenu
+ text="Download SVG"
+ icon={<Photo className="h-4 w-4" />}
+ />
+ </button>
+ <button
+ type="button"
+ onClick={async () =>
+ download(
+ (await getQRAsCanvas(qrData, "image/png")) as string,
+ "png",
+ )
+ }
+ className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
+ >
+ <IconMenu
+ text="Download PNG"
+ icon={<Photo className="h-4 w-4" />}
+ />
+ </button>
+ <button
+ type="button"
+ onClick={async () =>
+ download(
+ (await getQRAsCanvas(qrData, "image/jpeg")) as string,
+ "jpg",
+ )
+ }
+ className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
+ >
+ <IconMenu
+ text="Download JPEG"
+ icon={<Photo className="h-4 w-4" />}
+ />
+ </button>
+ </div>
+ }
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ {children}
+ </Popover>
+ <a
+ className="hidden"
+ download={`${linkProps.key}-qrcode.svg`}
+ ref={anchorRef}
+ />
+ </div>
+ );
+}
+
+export function CopyPopover({
+ qrData,
+ linkProps,
+ children,
+}: PropsWithChildren<{
+ qrData: ReturnType<typeof getQRData>;
+ linkProps: QRLinkProps;
+}>) {
+ const [openPopover, setOpenPopover] = useState(false);
+ const [copiedURL, copyUrlToClipboard] = useCopyToClipboard(2000);
+ const [copiedImage, copyImageToClipboard] = useCopyToClipboard(2000);
+
+ const copyToClipboard = async () => {
+ const canvas = await getQRAsCanvas(qrData, "image/png", true);
+ (canvas as HTMLCanvasElement).toBlob(async (blob) => {
+ // @ts-ignore
+ const item = new ClipboardItem({ "image/png": blob });
+ await copyImageToClipboard(item);
+ setOpenPopover(false);
+ });
+ };
+
+ return (
+ <Popover
+ content={
+ <div className="grid p-1 sm:min-w-48">
+ <button
+ type="button"
+ onClick={() =>
+ toast.promise(copyToClipboard, {
+ loading: "Copying QR code to clipboard...",
+ success: "Copied QR code to clipboard!",
+ error: "Failed to copy",
+ })
+ }
+ className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
+ >
+ <IconMenu
+ text="Copy Image"
+ icon={
+ copiedImage ? (
+ <Check className="h-4 w-4" />
+ ) : (
+ <Photo className="h-4 w-4" />
+ )
+ }
+ />
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ const url = `${API_DOMAIN}/qr?url=${linkConstructor({
+ key: linkProps.key,
+ domain: linkProps.domain,
+ searchParams: { qr: "1" },
+ })}${qrData.hideLogo ? "&hideLogo=true" : ""}`;
+ toast.promise(copyUrlToClipboard(url), {
+ success: "Copied QR code URL to clipboard!",
+ });
+ setOpenPopover(false);
+ }}
+ className="rounded-md p-2 text-left text-sm font-medium text-neutral-500 transition-all duration-75 hover:bg-neutral-100"
+ >
+ <IconMenu
+ text="Copy URL"
+ icon={
+ copiedURL ? (
+ <Check className="h-4 w-4" />
+ ) : (
+ <Hyperlink className="h-4 w-4" />
+ )
+ }
+ />
+ </button>
+ </div>
+ }
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ >
+ {children}
+ </Popover>
+ );
+}
+
+// Re-export for convenience
+export { useMemo };
+export type { QRCodeDesign };
diff --git a/apps/web/ui/shared/qr-code.tsx b/apps/web/ui/shared/qr-code.tsx
index 2aa59ec7f9..669497ebae 100644
--- a/apps/web/ui/shared/qr-code.tsx
+++ b/apps/web/ui/shared/qr-code.tsx
@@ -1,5 +1,6 @@
import { getQRData, QRCodeSVG } from "@/lib/qr";
import { DEFAULT_MARGIN } from "@/lib/qr/constants";
+import { DotStyle, MarkerBorderStyle, MarkerCenterStyle } from "@/lib/qr/types";
import { memo, useMemo } from "react";
export const QRCode = memo(
@@ -10,6 +11,10 @@ export const QRCode = memo(
logo,
scale = 1,
margin = DEFAULT_MARGIN,
+ dotStyle,
+ markerCenterStyle,
+ markerBorderStyle,
+ markerColor,
}: {
url: string;
fgColor?: string;
@@ -17,10 +22,35 @@ export const QRCode = memo(
logo?: string;
scale?: number;
margin?: number;
+ dotStyle?: DotStyle;
+ markerCenterStyle?: MarkerCenterStyle;
+ markerBorderStyle?: MarkerBorderStyle;
+ markerColor?: string;
}) => {
const qrData = useMemo(
- () => getQRData({ url, fgColor, hideLogo, logo, margin }),
- [url, fgColor, hideLogo, logo, margin],
+ () =>
+ getQRData({
+ url,
+ fgColor,
+ hideLogo,
+ logo,
+ margin,
+ dotStyle,
+ markerCenterStyle,
+ markerBorderStyle,
+ markerColor,
+ }),
+ [
+ url,
+ fgColor,
+ hideLogo,
+ logo,
+ margin,
+ dotStyle,
+ markerCenterStyle,
+ markerBorderStyle,
+ markerColor,
+ ],
);
return (
@@ -31,6 +61,10 @@ export const QRCode = memo(
fgColor={qrData.fgColor}
level={qrData.level}
margin={qrData.margin}
+ dotStyle={qrData.dotStyle}
+ markerCenterStyle={qrData.markerCenterStyle}
+ markerBorderStyle={qrData.markerBorderStyle}
+ markerColor={qrData.markerColor}
{...(qrData.imageSettings && {
imageSettings: {
...qrData.imageSettings,