Add artistic QR (templates + customization) with qr-code-styling

Editor QR tab now generates a styled, scannable QR with live preview and clean
PNG/SVG export (no frame or text — the owner lays it out).

- Restaurant.qrConfig JSON persists the styling (migration 0003)
- qr-code-styling (MIT) runs client-side in QrTab: preview + WYSIWYG PNG (2048px)
  and vector SVG export, avoiding native canvas deps in the alpine image
- Controls: dots color/gradient, background (incl. transparent), corners color,
  dot & corner shapes, optional center logo (uploaded via /upload, capped at 20%)
- Scannability: error correction forced to 'H' whenever there's a logo or color;
  WCAG contrast check warns on low contrast; persistent 'verify before printing' notice
- Templates inherit the menu palette but every value is independently editable
- QR always targets {APP_BASE_URL}/{slug}
- PATCH /api/[slug]/qr saves config; GET stays as a config-aware server fallback
- i18n (es/en) for the qr namespace; glassmorphism, mobile-first

Verified: build passes; migration 0003 applies; PATCH persists qrConfig; GET
honors saved colors/ECC (png + colored svg); auth guard returns 401.
This commit is contained in:
Jorem Juárez committed 2026-06-14 02:00:45 -06:00
1 parent d6ffbbd60b
commit 9a40a988e0
12 files changed
+594 -45

No files matched your search

+30
View File
@@ -87,6 +87,36 @@
"copied": "Copied",
"paletteHint": "This does not affect the macro color code"
},
"qr": {
"templates": "Templates",
"customize": "Customize",
"dotsColor": "Dots color",
"cornersColor": "Corners color",
"background": "Background",
"transparent": "Transparent",
"dotShape": "Dot shape",
"cornerShape": "Corner shape",
"gradient": "Gradient",
"logo": "Center logo",
"uploadLogo": "Upload logo",
"logoHint": "The logo takes up at most 20% of the code so it doesn't hurt scanning.",
"errorLevel": "Error correction",
"lowContrast": "Contrast between dots and background is low; the QR may not scan well. Use higher-contrast colors.",
"verifyScan": "Check that your QR scans well before printing.",
"shapes": {
"square": "Square",
"rounded": "Rounded",
"dots": "Dots",
"classy": "Classy",
"classy-rounded": "Classy rounded",
"extra-rounded": "Extra rounded"
},
"corners": {
"square": "Square",
"dot": "Dot",
"extra-rounded": "Rounded"
}
},
"import": {
"title": "Load menu",
"loadMenu": "Load menu",
+30
View File
@@ -87,6 +87,36 @@
"copied": "Copiado",
"paletteHint": "Esto no afecta el código de color de macros"
},
"qr": {
"templates": "Plantillas",
"customize": "Personalizar",
"dotsColor": "Color de puntos",
"cornersColor": "Color de esquinas",
"background": "Fondo",
"transparent": "Transparente",
"dotShape": "Forma de puntos",
"cornerShape": "Forma de esquinas",
"gradient": "Degradado",
"logo": "Logo al centro",
"uploadLogo": "Subir logo",
"logoHint": "El logo ocupa máximo 20% del código para no afectar el escaneo.",
"errorLevel": "Corrección de errores",
"lowContrast": "El contraste entre puntos y fondo es bajo; el QR podría no escanear bien. Usa colores con más contraste.",
"verifyScan": "Verifica que tu QR escanea bien antes de imprimir.",
"shapes": {
"square": "Cuadrado",
"rounded": "Redondeado",
"dots": "Puntos",
"classy": "Elegante",
"classy-rounded": "Elegante redondeado",
"extra-rounded": "Muy redondeado"
},
"corners": {
"square": "Cuadrada",
"dot": "Punto",
"extra-rounded": "Redondeada"
}
},
"import": {
"title": "Cargar menú",
"loadMenu": "Cargar menú",
+19
View File
@@ -15,6 +15,7 @@
"jose": "^5.9.6",
"next": "14.2.21",
"next-intl": "^3.26.3",
"qr-code-styling": "^1.9.2",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-dom": "^18.3.1",
@@ -2233,6 +2234,18 @@
"fsevents": "2.3.3"
}
},
"node_modules/qr-code-styling": {
"version": "1.9.2",
"resolved": "https://registry.npmjs.org/qr-code-styling/-/qr-code-styling-1.9.2.tgz",
"integrity": "sha512-RgJaZJ1/RrXJ6N0j7a+pdw3zMBmzZU4VN2dtAZf8ZggCfRB5stEQ3IoDNGaNhYY3nnZKYlYSLl5YkfWN5dPutg==",
"license": "MIT",
"dependencies": {
"qrcode-generator": "^1.4.4"
},
"engines": {
"node": ">=18.18.0"
}
},
"node_modules/qrcode": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
@@ -2250,6 +2263,12 @@
"node": ">=10.13.0"
}
},
"node_modules/qrcode-generator": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/qrcode-generator/-/qrcode-generator-1.5.2.tgz",
"integrity": "sha512-pItrW0Z9HnDBnFmgiNrY1uxRdri32Uh9EjNYLPVC2zZ3ZRIIEqBoDgm4DkvDwNNDHTK7FNkmr8zAa77BYc9xNw==",
"license": "MIT"
},
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz",
+3 -2
View File
@@ -23,10 +23,11 @@
"jose": "^5.9.6",
"next": "14.2.21",
"next-intl": "^3.26.3",
"qr-code-styling": "^1.9.2",
"qrcode": "^1.5.4",
"xlsx": "^0.18.5",
"react": "^18.3.1",
"react-dom": "^18.3.1"
"react-dom": "^18.3.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.6",
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Restaurant" ADD COLUMN "qrConfig" JSONB NOT NULL DEFAULT '{}';
+1
View File
@@ -18,6 +18,7 @@ model Restaurant {
username String
hashedPassword String
palette Json @default("{}")
qrConfig Json @default("{}") // artistic QR styling (qr-code-styling config)
ordersEnabled Boolean @default(false)
defaultLocale String @default("es")
active Boolean @default(true)
+2 -1
View File
@@ -2,7 +2,7 @@ import { redirect, notFound } from 'next/navigation';
import { prisma } from '@/lib/prisma';
import { getEditorSession } from '@/lib/auth';
import { paletteToCssVars } from '@/lib/palette';
import type { EditorData } from '@/components/editor/types';
import type { EditorData, QrConfig } from '@/components/editor/types';
import type { Palette } from '@/lib/types';
import Editor from '@/components/editor/Editor';
@@ -39,6 +39,7 @@ export default async function EditorPage({
ordersEnabled: restaurant.ordersEnabled,
defaultLocale: restaurant.defaultLocale as 'es' | 'en',
palette: (restaurant.palette as Palette) ?? {},
qrConfig: (restaurant.qrConfig as QrConfig) ?? {},
publishedVersionName: restaurant.publishedVersion?.versionName ?? null,
sections: restaurant.sections.map((s) => ({
id: s.id,
+37 -14
View File
@@ -1,28 +1,39 @@
import { NextResponse } from 'next/server';
import QRCode from 'qrcode';
import { prisma } from '@/lib/prisma';
import { requireEditor } from '@/lib/guard';
export const dynamic = 'force-dynamic';
// Generates the public-menu QR as PNG or SVG.
type QrConfig = {
dotsColor?: string;
background?: string; // hex or 'transparent'
errorCorrectionLevel?: 'L' | 'M' | 'Q' | 'H';
};
// GET: server-side fallback QR (honors saved colors + ECC). The editor's
// artistic export (shapes/gradients/logo) is generated client-side with
// qr-code-styling; this endpoint stays available for direct/basic use.
export async function GET(req: Request, { params }: { params: { slug: string } }) {
const restaurant = await prisma.restaurant.findUnique({
where: { slug: params.slug },
select: { id: true },
select: { id: true, qrConfig: true },
});
if (!restaurant) return NextResponse.json({ error: 'not_found' }, { status: 404 });
const cfg = (restaurant.qrConfig as QrConfig) ?? {};
const dark = cfg.dotsColor || '#2a2520';
// QR libs can't render a transparent module color; fall back to white bg here.
const light = cfg.background && cfg.background !== 'transparent' ? cfg.background : '#ffffff';
const ecc = cfg.errorCorrectionLevel || 'H';
const format = new URL(req.url).searchParams.get('format') === 'svg' ? 'svg' : 'png';
const base = process.env.APP_BASE_URL || new URL(req.url).origin;
const url = `${base}/${params.slug}`;
const opts = { margin: 2, width: 1024, errorCorrectionLevel: ecc, color: { dark, light } } as const;
if (format === 'svg') {
const svg = await QRCode.toString(url, {
type: 'svg',
margin: 2,
width: 1024,
color: { dark: '#2a2520', light: '#ffffff' },
});
const svg = await QRCode.toString(url, { type: 'svg', ...opts });
return new NextResponse(svg, {
headers: {
'Content-Type': 'image/svg+xml',
@@ -31,12 +42,7 @@ export async function GET(req: Request, { params }: { params: { slug: string } }
});
}
const buffer = await QRCode.toBuffer(url, {
type: 'png',
margin: 2,
width: 1024,
color: { dark: '#2a2520', light: '#ffffff' },
});
const buffer = await QRCode.toBuffer(url, { type: 'png', ...opts });
return new NextResponse(new Uint8Array(buffer), {
headers: {
'Content-Type': 'image/png',
@@ -44,3 +50,20 @@ export async function GET(req: Request, { params }: { params: { slug: string } }
},
});
}
// PATCH: persist the artistic QR config (qrConfig JSON) on the restaurant.
export async function PATCH(req: Request, { params }: { params: { slug: string } }) {
const guard = await requireEditor(params.slug);
if ('error' in guard) return guard.error;
const body = await req.json().catch(() => null);
const config = body?.qrConfig;
if (!config || typeof config !== 'object') {
return NextResponse.json({ error: 'invalid' }, { status: 400 });
}
await prisma.restaurant.update({
where: { id: guard.restaurant.id },
data: { qrConfig: config as object },
});
return NextResponse.json({ ok: true });
}
+8 -1
View File
@@ -57,7 +57,14 @@ export default function Editor({ data, baseUrl }: { data: EditorData; baseUrl: s
setOrdersEnabled={setOrdersEnabled}
/>
)}
{tab === 'qr' && <QrTab slug={data.slug} baseUrl={baseUrl} />}
{tab === 'qr' && (
<QrTab
slug={data.slug}
baseUrl={baseUrl}
palette={data.palette}
initialConfig={data.qrConfig}
/>
)}
{/* Bottom tab bar */}
<nav className="glass fixed bottom-0 left-1/2 z-30 flex w-full max-w-2xl -translate-x-1/2 items-stretch justify-around rounded-t-3xl px-2 py-2">
+409 -27
View File
@@ -1,12 +1,218 @@
'use client';
import { useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import type { Palette } from '@/lib/types';
import type { QrConfig } from './types';
import { contrastRatio, QR_MIN_CONTRAST } from '@/lib/contrast';
import { api } from './api';
// qr-code-styling is a browser library; it's imported dynamically on the client
// and both the preview and the PNG/SVG export run here so the export matches the
// preview pixel-for-pixel. The QR always points to {baseUrl}/{slug}.
type DotsType = NonNullable<QrConfig['dotsType']>;
type CornersType = NonNullable<QrConfig['cornersType']>;
const DOT_SHAPES: DotsType[] = [
'square',
'rounded',
'dots',
'classy',
'classy-rounded',
'extra-rounded',
];
const CORNER_SHAPES: CornersType[] = ['square', 'dot', 'extra-rounded'];
const TRANSPARENT = 'transparent';
function buildTemplates(palette: Palette): { id: string; label: string; config: QrConfig }[] {
const ink = palette.text || '#2a2520';
const accent = palette.accent || '#b45309';
return [
{
id: 'classic',
label: 'Clásico',
config: { dotsColor: '#2a2520', dotsType: 'square', cornersColor: '#2a2520', cornersType: 'square', background: '#ffffff' },
},
{
id: 'brand',
label: 'Marca',
config: { dotsColor: ink, dotsType: 'rounded', cornersColor: accent, cornersType: 'extra-rounded', background: '#ffffff' },
},
{
id: 'dots',
label: 'Puntos',
config: { dotsColor: accent, dotsType: 'dots', cornersColor: accent, cornersType: 'dot', background: '#ffffff' },
},
{
id: 'gradient',
label: 'Degradado',
config: {
dotsColor: accent,
dotsType: 'classy-rounded',
cornersColor: ink,
cornersType: 'extra-rounded',
background: '#ffffff',
gradient: { enabled: true, color2: ink, type: 'linear' },
},
},
{
id: 'transparent',
label: 'Transparente',
config: { dotsColor: ink, dotsType: 'rounded', cornersColor: accent, cornersType: 'extra-rounded', background: TRANSPARENT },
},
];
}
// Default config inherits the menu palette but is independently editable.
function defaultConfig(palette: Palette): QrConfig {
return {
dotsColor: palette.text || '#2a2520',
dotsType: 'rounded',
cornersColor: palette.accent || palette.text || '#2a2520',
cornersType: 'extra-rounded',
background: '#ffffff',
gradient: { enabled: false, color2: palette.accent || '#b45309', type: 'linear' },
logo: null,
};
}
export default function QrTab({
slug,
baseUrl,
palette,
initialConfig,
}: {
slug: string;
baseUrl: string;
palette: Palette;
initialConfig: QrConfig;
}) {
const t = useTranslations('qr');
const tc = useTranslations('common');
const te = useTranslations('editor');
export default function QrTab({ slug, baseUrl }: { slug: string; baseUrl: string }) {
const t = useTranslations('editor');
const [copied, setCopied] = useState(false);
const link = `${baseUrl || (typeof window !== 'undefined' ? window.location.origin : '')}/${slug}`;
const templates = useMemo(() => buildTemplates(palette), [palette]);
const [config, setConfig] = useState<QrConfig>({
...defaultConfig(palette),
...initialConfig,
});
const [saved, setSaved] = useState(false);
const [copied, setCopied] = useState(false);
const [uploading, setUploading] = useState(false);
const previewRef = useRef<HTMLDivElement>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const qrRef = useRef<any>(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const QRClassRef = useRef<any>(null);
const hasColorOrLogo =
!!config.logo ||
config.gradient?.enabled ||
(config.dotsColor || '').toLowerCase() !== '#2a2520' ||
(config.background || '#ffffff').toLowerCase() !== '#ffffff';
// Force H whenever there's a logo or color, per scannability rules.
const ecc: NonNullable<QrConfig['errorCorrectionLevel']> = hasColorOrLogo ? 'H' : 'M';
const ratio = contrastRatio(config.dotsColor || '#000', config.background || '#fff');
const lowContrast = ratio < QR_MIN_CONTRAST;
// Build the qr-code-styling options from the current config.
// Returned as `any` so the literal (gradient/dots unions) satisfies the
// library's strict Options type without per-field casts.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function buildOptions(size: number): any {
const dots = config.gradient?.enabled
? {
type: config.dotsType,
gradient: {
type: config.gradient.type,
rotation: 0,
colorStops: [
{ offset: 0, color: config.dotsColor },
{ offset: 1, color: config.gradient.color2 },
],
},
}
: { type: config.dotsType, color: config.dotsColor };
return {
width: size,
height: size,
type: 'canvas' as const,
data: link,
margin: Math.round(size * 0.04),
qrOptions: { errorCorrectionLevel: ecc },
image: config.logo || undefined,
dotsOptions: dots,
backgroundOptions: {
color: config.background === TRANSPARENT ? 'rgba(0,0,0,0)' : config.background,
},
cornersSquareOptions: { type: config.cornersType, color: config.cornersColor },
cornersDotOptions: { color: config.cornersColor },
imageOptions: { crossOrigin: 'anonymous', imageSize: 0.2, margin: 4, hideBackgroundDots: true },
};
}
// Initialize the preview instance once the library is loaded client-side.
useEffect(() => {
let cancelled = false;
(async () => {
const mod = await import('qr-code-styling');
if (cancelled) return;
QRClassRef.current = mod.default;
qrRef.current = new mod.default(buildOptions(280));
if (previewRef.current) {
previewRef.current.innerHTML = '';
qrRef.current.append(previewRef.current);
}
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Re-render the preview whenever the config changes.
useEffect(() => {
if (qrRef.current) qrRef.current.update(buildOptions(280));
setSaved(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [config, ecc]);
function patch(p: Partial<QrConfig>) {
setConfig((c) => ({ ...c, ...p }));
}
async function uploadLogo(file: File | null) {
if (!file) return;
setUploading(true);
try {
const form = new FormData();
form.append('file', file);
const res = await api<{ path: string }>(slug, '/upload', { method: 'POST', body: form });
patch({ logo: res.path });
} finally {
setUploading(false);
}
}
async function save() {
await api(slug, '/qr', { method: 'PATCH', json: { qrConfig: { ...config, errorCorrectionLevel: ecc } } });
setSaved(true);
}
async function download(ext: 'png' | 'svg') {
if (!QRClassRef.current) return;
// High-resolution export; SVG is vector so size is nominal.
const size = ext === 'png' ? 2048 : 1024;
const instance = new QRClassRef.current({ ...buildOptions(size), type: ext === 'svg' ? 'svg' : 'canvas' });
await instance.download({ name: `menu-${slug}`, extension: ext });
}
async function copy() {
await navigator.clipboard.writeText(link);
@@ -15,40 +221,216 @@ export default function QrTab({ slug, baseUrl }: { slug: string; baseUrl: string
}
return (
<div className="flex flex-col items-center gap-5">
<div className="glass rounded-3xl p-6">
{/* Live PNG from the QR endpoint */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={`/api/${slug}/qr?format=png`}
alt="QR"
className="h-60 w-60 rounded-2xl bg-white"
/>
<div className="flex flex-col gap-4">
{/* Live preview */}
<div className="glass flex flex-col items-center gap-2 rounded-3xl p-5">
<div
className="rounded-2xl p-3"
style={{
background:
config.background === TRANSPARENT
? 'repeating-conic-gradient(#e5e5e5 0% 25%, #ffffff 0% 50%) 50% / 16px 16px'
: config.background,
}}
>
<div ref={previewRef} className="h-[280px] w-[280px]" />
</div>
<span className="text-[11px] text-[var(--text)]/55">
{t('errorLevel')}: {ecc}
</span>
</div>
<div className="glass flex w-full max-w-sm items-center gap-2 rounded-2xl px-4 py-3">
{/* Scannability warning */}
{lowContrast && (
<p className="rounded-2xl bg-red-50 px-4 py-2 text-sm text-red-700">
⚠️ {t('lowContrast')}
</p>
)}
<p className="rounded-2xl bg-amber-50/70 px-4 py-2 text-xs text-amber-800">
⚠️ {t('verifyScan')}
</p>
{/* Templates */}
<section className="glass rounded-3xl p-4">
<h3 className="display mb-2 text-sm font-semibold">{t('templates')}</h3>
<div className="flex flex-wrap gap-2">
{templates.map((tpl) => (
<button
key={tpl.id}
onClick={() => setConfig((c) => ({ ...c, ...tpl.config }))}
className="glass-soft rounded-full px-3 py-2 text-sm"
>
{tpl.label}
</button>
))}
</div>
</section>
{/* Customization */}
<section className="glass flex flex-col gap-4 rounded-3xl p-4">
<h3 className="display text-sm font-semibold">{t('customize')}</h3>
<ColorRow label={t('dotsColor')} value={config.dotsColor || '#000000'} onChange={(v) => patch({ dotsColor: v })} />
<ColorRow label={t('cornersColor')} value={config.cornersColor || '#000000'} onChange={(v) => patch({ cornersColor: v })} />
{/* Background incl. transparent */}
<div className="flex items-center justify-between gap-2 text-sm">
<span>{t('background')}</span>
<div className="flex items-center gap-2">
<button
onClick={() => patch({ background: config.background === TRANSPARENT ? '#ffffff' : TRANSPARENT })}
className={`rounded-full px-3 py-1 text-xs ${
config.background === TRANSPARENT ? 'bg-[var(--accent)] text-white' : 'glass-soft'
}`}
>
{t('transparent')}
</button>
<input
type="color"
value={config.background === TRANSPARENT ? '#ffffff' : config.background || '#ffffff'}
onChange={(e) => patch({ background: e.target.value })}
className="h-9 w-14 rounded-lg border-0 bg-transparent"
/>
</div>
</div>
{/* Dot shape */}
<div className="flex flex-col gap-1.5 text-sm">
<span>{t('dotShape')}</span>
<div className="flex flex-wrap gap-2">
{DOT_SHAPES.map((s) => (
<button
key={s}
onClick={() => patch({ dotsType: s })}
className={`rounded-full px-3 py-1 text-xs ${
config.dotsType === s ? 'bg-[var(--accent)] text-white' : 'glass-soft'
}`}
>
{t(`shapes.${s}`)}
</button>
))}
</div>
</div>
{/* Corner shape */}
<div className="flex flex-col gap-1.5 text-sm">
<span>{t('cornerShape')}</span>
<div className="flex flex-wrap gap-2">
{CORNER_SHAPES.map((s) => (
<button
key={s}
onClick={() => patch({ cornersType: s })}
className={`rounded-full px-3 py-1 text-xs ${
config.cornersType === s ? 'bg-[var(--accent)] text-white' : 'glass-soft'
}`}
>
{t(`corners.${s}`)}
</button>
))}
</div>
</div>
{/* Gradient */}
<div className="flex items-center justify-between gap-2 text-sm">
<span>{t('gradient')}</span>
<div className="flex items-center gap-2">
<button
onClick={() =>
patch({
gradient: {
enabled: !config.gradient?.enabled,
color2: config.gradient?.color2 || palette.accent || '#b45309',
type: config.gradient?.type || 'linear',
},
})
}
className={`relative h-6 w-11 rounded-full transition ${
config.gradient?.enabled ? 'bg-green-500' : 'bg-gray-300'
}`}
>
<span className={`absolute top-1 h-4 w-4 rounded-full bg-white transition-all ${config.gradient?.enabled ? 'left-6' : 'left-1'}`} />
</button>
{config.gradient?.enabled && (
<input
type="color"
value={config.gradient.color2}
onChange={(e) =>
patch({ gradient: { ...config.gradient!, color2: e.target.value } })
}
className="h-9 w-14 rounded-lg border-0 bg-transparent"
/>
)}
</div>
</div>
{/* Logo */}
<div className="flex items-center justify-between gap-2 text-sm">
<span>{t('logo')}</span>
<div className="flex items-center gap-2">
{config.logo && (
<button onClick={() => patch({ logo: null })} className="glass-soft rounded-full px-3 py-1 text-xs">
{tc('delete')}
</button>
)}
<label className="glass-pill cursor-pointer rounded-full px-3 py-1 text-xs">
{uploading ? '…' : t('uploadLogo')}
<input type="file" accept="image/*" hidden onChange={(e) => uploadLogo(e.target.files?.[0] ?? null)} />
</label>
</div>
</div>
{config.logo && <p className="text-[11px] text-[var(--text)]/55">{t('logoHint')}</p>}
</section>
{/* Save */}
<button
onClick={save}
className="rounded-2xl bg-[var(--accent)] py-3 font-medium text-white"
>
{saved ? '✓ ' : ''}
{tc('save')}
</button>
{/* Link + export */}
<div className="glass flex w-full items-center gap-2 rounded-2xl px-4 py-3">
<span className="min-w-0 flex-1 truncate text-sm">{link}</span>
<button onClick={copy} className="glass-pill rounded-full px-3 py-1 text-xs font-medium">
{copied ? t('copied') : t('copyLink')}
{copied ? te('copied') : te('copyLink')}
</button>
</div>
<div className="flex gap-2">
<a
href={`/api/${slug}/qr?format=png`}
download
className="rounded-2xl bg-[var(--accent)] px-5 py-3 text-sm font-medium text-white"
>
{t('downloadQr')} PNG
</a>
<a
href={`/api/${slug}/qr?format=svg`}
download
className="glass-pill rounded-2xl px-5 py-3 text-sm font-medium"
<button
onClick={() => download('png')}
className="flex-1 rounded-2xl bg-[var(--accent)] py-3 text-sm font-medium text-white"
>
{te('downloadQr')} PNG
</button>
<button onClick={() => download('svg')} className="glass-pill flex-1 rounded-2xl py-3 text-sm font-medium">
SVG
</a>
</button>
</div>
</div>
);
}
function ColorRow({
label,
value,
onChange,
}: {
label: string;
value: string;
onChange: (v: string) => void;
}) {
return (
<label className="flex items-center justify-between text-sm">
{label}
<input
type="color"
value={value}
onChange={(e) => onChange(e.target.value)}
className="h-9 w-14 rounded-lg border-0 bg-transparent"
/>
</label>
);
}
+13
View File
@@ -24,12 +24,25 @@ export type EditorSection = {
products: EditorProduct[];
};
export type QrConfig = {
template?: string;
dotsColor?: string;
dotsType?: 'square' | 'dots' | 'rounded' | 'classy' | 'classy-rounded' | 'extra-rounded';
cornersColor?: string;
cornersType?: 'square' | 'dot' | 'extra-rounded';
background?: string; // hex or 'transparent'
gradient?: { enabled: boolean; color2: string; type: 'linear' | 'radial' };
logo?: string | null;
errorCorrectionLevel?: 'L' | 'M' | 'Q' | 'H';
};
export type EditorData = {
slug: string;
name: string;
ordersEnabled: boolean;
defaultLocale: Locale;
palette: Palette;
qrConfig: QrConfig;
publishedVersionName: string | null;
sections: EditorSection[];
};
+40
View File
@@ -0,0 +1,40 @@
// WCAG relative-luminance contrast ratio, used to warn when a QR's dots vs
// background won't scan reliably. QR scanners need strong contrast; we treat
// anything below ~3:1 as risky and recommend much higher for print.
function hexToRgb(hex: string): [number, number, number] | null {
const m = hex.replace('#', '');
if (m.length === 3) {
const r = parseInt(m[0] + m[0], 16);
const g = parseInt(m[1] + m[1], 16);
const b = parseInt(m[2] + m[2], 16);
return [r, g, b];
}
if (m.length === 6) {
return [parseInt(m.slice(0, 2), 16), parseInt(m.slice(2, 4), 16), parseInt(m.slice(4, 6), 16)];
}
return null;
}
function luminance([r, g, b]: [number, number, number]): number {
const a = [r, g, b].map((v) => {
const s = v / 255;
return s <= 0.03928 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
});
return 0.2126 * a[0] + 0.7152 * a[1] + 0.7252 * a[2];
}
// Returns contrast ratio (1..21). `background='transparent'` is measured against
// white, since that's the most common print surface.
export function contrastRatio(dots: string, background: string): number {
const fg = hexToRgb(dots);
const bg = hexToRgb(background === 'transparent' ? '#ffffff' : background);
if (!fg || !bg) return 21;
const l1 = luminance(fg);
const l2 = luminance(bg);
const lighter = Math.max(l1, l2);
const darker = Math.min(l1, l2);
return (lighter + 0.05) / (darker + 0.05);
}
// Below this, scanning becomes unreliable — surface the warning.
export const QR_MIN_CONTRAST = 4;