QR tool: choose the centre, type any link, pick the colours

The centre can be nothing, the NGU dove, or any SVG dropped into
src/assets/qr, embedded in the code so downloads carry it. "A link I
type" takes a site path (sent to the live site), a full http(s)
address, or a bare domain. The code, background and dove colours can
be changed, with a warning under 4:1 contrast or for an inverted
code, which many scanners can't read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-27 23:20:55 -05:00
parent 9075cfb908
commit 9eeb13c5ec
5 changed files with 279 additions and 51 deletions

View file

@ -39,7 +39,7 @@
}, },
"/qr": { "/qr": {
"title": "QR Codes", "title": "QR Codes",
"description": "Codes for flyers, slides and signs, pointing at any page on the site." "description": "Codes for flyers, slides and signs, pointing at any page on the site or any link, in your choice of colours."
}, },
"/give": { "/give": {
"title": "Giving", "title": "Giving",

View file

@ -1,16 +1,25 @@
/* ═══════════════════════════════════════════════════════════════ /* ═══════════════════════════════════════════════════════════════
QR CODE QR CODE
A QR code as an <svg>, sized by its container. With `dove`, the A QR code as an <svg>, sized by its container.
NGU dove sits on a white badge over the centre; the code switches
to high error correction so the modules under the badge are
recovered when it's scanned (see lib/qr.ts). The badge covers
under 6% of the code, well inside what 'H' repairs, and never
reaches the three corner finder patterns.
Everything is drawn in the SVG itself (no CSS, no external `centre` puts something on a badge over the middle: the NGU dove,
references), so the element serialises to a file that looks the or an image (an SVG from src/assets/qr, passed as a data: URL).
same outside the page. `ref` reaches the <svg> for exactly that. With anything there, the code switches to high error correction
so the modules under the badge are recovered when it's scanned
(see lib/qr.ts). The badge covers under 6% of the code, well
inside what 'H' repairs, and never reaches the three corner
finder patterns.
`ink` is the modules and the badge's outline, `paper` the
background and the badge. A code should stay dark on light with
strong contrast to scan reliably; QrCodeMaker warns when it
doesn't, this just draws what it's given.
Everything is drawn in the SVG itself (no CSS, and an image is
embedded rather than linked), so the element serialises to a
file that looks the same outside the page. `ref` reaches the
<svg> for exactly that.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { useMemo, type Ref } from 'react' import { useMemo, type Ref } from 'react'
@ -23,8 +32,9 @@ import { qrMatrix, qrPath } from '../lib/qr.ts'
const MARGIN = 4 const MARGIN = 4
/* Dark enough to scan as black; the site's deep teal. */ /* Dark enough to scan as black; the site's deep teal. */
const INK = '#04262e' export const QR_INK = '#04262e'
const TEAL = '#138ba0' export const QR_PAPER = '#ffffff'
export const QR_DOVE = '#138ba0'
/* Badge side as a share of the code's width. */ /* Badge side as a share of the code's width. */
const BADGE = 0.24 const BADGE = 0.24
@ -32,21 +42,28 @@ const BADGE = 0.24
/* DoveMark's own viewBox is 72.87 × 48.57. */ /* DoveMark's own viewBox is 72.87 × 48.57. */
const DOVE_ASPECT = 72.867699 / 48.568241 const DOVE_ASPECT = 72.867699 / 48.568241
export type QrCentre = { kind: 'dove'; color?: string } | { kind: 'image'; src: string } | null
export default function QrCode({ export default function QrCode({
value, value,
dove = false, centre = null,
ink = QR_INK,
paper = QR_PAPER,
label, label,
ref, ref,
className, className,
}: { }: {
value: string value: string
dove?: boolean centre?: QrCentre
ink?: string
paper?: string
/** Accessible name for the image, e.g. "QR code for /retreats". */ /** Accessible name for the image, e.g. "QR code for /retreats". */
label: string label: string
ref?: Ref<SVGSVGElement> ref?: Ref<SVGSVGElement>
className?: string className?: string
}) { }) {
const matrix = useMemo(() => qrMatrix(value, dove ? 'H' : 'M'), [value, dove]) const level = centre ? 'H' : 'M'
const matrix = useMemo(() => qrMatrix(value, level), [value, level])
const path = useMemo(() => qrPath(matrix, MARGIN), [matrix]) const path = useMemo(() => qrPath(matrix, MARGIN), [matrix])
const total = matrix.size + MARGIN * 2 const total = matrix.size + MARGIN * 2
@ -54,6 +71,7 @@ export default function QrCode({
const badgeAt = (total - badge) / 2 const badgeAt = (total - badge) / 2
const doveWidth = badge * 0.78 const doveWidth = badge * 0.78
const doveHeight = doveWidth / DOVE_ASPECT const doveHeight = doveWidth / DOVE_ASPECT
const imageSize = badge * 0.8
return ( return (
<svg <svg
@ -65,10 +83,10 @@ export default function QrCode({
className={className} className={className}
shapeRendering="crispEdges" shapeRendering="crispEdges"
> >
<rect width={total} height={total} fill="#ffffff" /> <rect width={total} height={total} fill={paper} />
<path d={path} fill={INK} /> <path d={path} fill={ink} />
{dove && ( {centre && (
<g shapeRendering="auto"> <g shapeRendering="auto">
<rect <rect
x={badgeAt} x={badgeAt}
@ -76,17 +94,28 @@ export default function QrCode({
width={badge} width={badge}
height={badge} height={badge}
rx={badge * 0.22} rx={badge * 0.22}
fill="#ffffff" fill={paper}
stroke={INK} stroke={ink}
strokeWidth={0.35} strokeWidth={0.35}
/> />
<DoveMark {centre.kind === 'dove' ? (
x={(total - doveWidth) / 2} <DoveMark
y={(total - doveHeight) / 2} x={(total - doveWidth) / 2}
width={doveWidth} y={(total - doveHeight) / 2}
height={doveHeight} width={doveWidth}
style={{ color: TEAL }} height={doveHeight}
/> style={{ color: centre.color ?? QR_DOVE }}
/>
) : (
<image
href={centre.src}
x={(total - imageSize) / 2}
y={(total - imageSize) / 2}
width={imageSize}
height={imageSize}
preserveAspectRatio="xMidYMid meet"
/>
)}
</g> </g>
)} )}
</svg> </svg>

View file

@ -19,7 +19,7 @@ const SECTIONS = [
id: 'make', id: 'make',
title: 'Make a QR code', title: 'Make a QR code',
blurb: blurb:
'Pick a page from the main navigation, or any event, organization, team, award, person or blog post on the site. The code always points at the live site.', 'Pick a page from the main navigation, any event, organization, team, award, person or blog post, or type any link. Site pages always point at the live site. Choose what sits in the centre and the colours; a warning shows if the code might not scan.',
accent: '#138ba0', accent: '#138ba0',
background: '#eef9fb', background: '#eef9fb',
content: ( content: (

View file

@ -135,7 +135,7 @@ export const TOOLS_NAV = {
{ {
to: "/qr", to: "/qr",
label: "QR code generator", label: "QR code generator",
blurb: "Codes for flyers, slides and signs, pointing at any page on the site.", blurb: "Codes for flyers, slides and signs: any page or link, in your choice of colours.",
}, },
], ],
}; };

View file

@ -1,12 +1,23 @@
/* ═══════════════════════════════════════════════════════════════ /* ═══════════════════════════════════════════════════════════════
QR CODE MAKER QR CODE MAKER
Pick a page, get a QR code for it on the live site. Pick a page, or type a link, and get a QR code for it.
What main navigation, or one kind of record What main navigation, one kind of record, or a link
typed in
Which the page or record itself Which the page or record itself
Section for a main page with a subnav, optionally one of Section for a main page with a subnav, optionally one of
its #sections its #sections
Centre nothing, the NGU dove, or any SVG in
src/assets/qr (drop a file there and it's offered;
it's embedded in the code, so downloads carry it)
Colours the code, its background, and the dove. A warning
appears when the pair is unlikely to scan: too
little contrast, or a light code on a dark ground
A typed link can be a site path (/retreats, which goes to the live
site like every other choice), a full http(s) address, or a bare
domain, which gets https:// in front.
The main pages come from navConfig.ts, the same list the header The main pages come from navConfig.ts, the same list the header
draws; records come from GET /directory, which lists only what's draws; records come from GET /directory, which lists only what's
@ -22,7 +33,7 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react' import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import QrCode from '../../components/QrCode.tsx' import QrCode, { QR_DOVE, QR_INK, QR_PAPER, type QrCentre } from '../../components/QrCode.tsx'
import { NAV_ACTIONS, PAGE_LINKS, PAGE_SECTIONS } from '../../navConfig.ts' import { NAV_ACTIONS, PAGE_LINKS, PAGE_SECTIONS } from '../../navConfig.ts'
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts' import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts'
import { siteUrl } from '../../lib/site.ts' import { siteUrl } from '../../lib/site.ts'
@ -35,7 +46,7 @@ const MUTED = '#4a6b72'
anything bigger should use the SVG. */ anything bigger should use the SVG. */
const PNG_SIZE = 1024 const PNG_SIZE = 1024
type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' | 'blog_posts' type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' | 'blog_posts' | 'custom'
const KINDS: Array<[Kind, string]> = [ const KINDS: Array<[Kind, string]> = [
['pages', 'Main navigation'], ['pages', 'Main navigation'],
@ -45,8 +56,81 @@ const KINDS: Array<[Kind, string]> = [
['awards', 'Awards'], ['awards', 'Awards'],
['people', 'People'], ['people', 'People'],
['blog_posts', 'Blog posts'], ['blog_posts', 'Blog posts'],
['custom', 'A link I type'],
] ]
/* The centres on offer: the dove, then every SVG in src/assets/qr,
named after its file ("ngu-circle.svg" → "Ngu circle"). Read as
text and turned into data: URLs so they sit inside the code's own
SVG. */
const CENTRE_FILES = import.meta.glob<string>('../../assets/qr/*.svg', {
eager: true,
query: '?raw',
import: 'default',
})
type CentreOption = { id: string; label: string; centre: (dove: string) => QrCentre }
const toDataUrl = (svg: string) =>
`data:image/svg+xml;base64,${btoa(String.fromCharCode(...new TextEncoder().encode(svg)))}`
const CENTRES: CentreOption[] = [
{ id: 'none', label: 'Nothing', centre: () => null },
{ id: 'dove', label: 'NGU dove', centre: (color) => ({ kind: 'dove', color }) },
...Object.entries(CENTRE_FILES)
.sort(([a], [b]) => a.localeCompare(b))
.map(([path, svg]) => {
const name = path.split('/').pop()!.replace(/\.svg$/i, '')
const label = name.replace(/[-_]+/g, ' ').replace(/^./, (c) => c.toUpperCase())
const src = toDataUrl(svg)
return { id: `file:${name}`, label, centre: () => ({ kind: 'image', src }) as QrCentre }
}),
]
/* ── Contrast ──────────────────────────────────────────────────
WCAG relative luminance and contrast ratio. Below MIN_CONTRAST
some phone cameras struggle; a code lighter than its background
is "inverted", which many scanners don't read at all. */
const MIN_CONTRAST = 4
function luminance(hex: string): number {
const m = hex.replace('#', '').match(/^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i)
if (!m) return 0
const [r, g, b] = m.slice(1).map((h) => {
const c = parseInt(h, 16) / 255
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
})
return 0.2126 * r + 0.7152 * g + 0.0722 * b
}
function scanWarning(ink: string, paper: string): string | null {
const a = luminance(ink)
const b = luminance(paper)
if (a > b) return 'The code is lighter than its background. Many scanners can’t read an inverted code.'
const ratio = (b + 0.05) / (a + 0.05)
if (ratio < MIN_CONTRAST) {
return `Low contrast (${ratio.toFixed(1)}:1). Use a darker code or a lighter background so it scans reliably.`
}
return null
}
/* What a typed link means: a site path goes to the live site, a
full address is used as it is, a bare domain gets https://.
Anything else isn't a link. */
function typedUrl(raw: string): string | null {
const value = raw.trim()
if (!value) return null
if (value.startsWith('/') && !value.startsWith('//')) return siteUrl(value)
const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(value) ? value : /^[^\s/]+\.[^\s/]+/.test(value) ? `https://${value}` : null
if (!withScheme) return null
try {
const url = new URL(withScheme)
return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null
} catch {
return null
}
}
/* Organizations are grouped by kind in the dropdown, in this order. */ /* Organizations are grouped by kind in the dropdown, in this order. */
const ORG_GROUPS: Array<[string, string]> = [ const ORG_GROUPS: Array<[string, string]> = [
['national', 'NGU'], ['national', 'NGU'],
@ -109,12 +193,22 @@ function groupsFor(kind: Kind, directory: Directory | null): Group[] {
return [{ choices: directory.people.map((p) => ({ path: personHref(p.id), label: p.name })) }] return [{ choices: directory.people.map((p) => ({ path: personHref(p.id), label: p.name })) }]
case 'blog_posts': case 'blog_posts':
return [{ choices: directory.blog_posts.map((b) => ({ path: blogHref(b.id), label: b.name })) }] return [{ choices: directory.blog_posts.map((b) => ({ path: blogHref(b.id), label: b.name })) }]
case 'custom':
return []
} }
} }
/* "/regions/northwest#events" → "regions-northwest-events". */ /* "/regions/northwest#events" → "regions-northwest-events"; a typed
function fileStem(path: string): string { link keeps its host too: "example-org-page". */
const stem = path.replace(/^\//, '').replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '') function fileStem(target: string): string {
let name = target
try {
const url = new URL(target)
name = `${url.hostname.replace(/^www\./, '')}${url.pathname}${url.hash}`
} catch {
/* a site path */
}
const stem = name.replace(/^\//, '').replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '')
return `ngu-qr-${stem || 'home'}` return `ngu-qr-${stem || 'home'}`
} }
@ -163,7 +257,11 @@ export default function QrCodeMaker() {
const [kind, setKind] = useState<Kind>('pages') const [kind, setKind] = useState<Kind>('pages')
const [path, setPath] = useState('/') const [path, setPath] = useState('/')
const [section, setSection] = useState('') const [section, setSection] = useState('')
const [dove, setDove] = useState(true) const [custom, setCustom] = useState('')
const [centreId, setCentreId] = useState('dove')
const [ink, setInk] = useState(QR_INK)
const [paper, setPaper] = useState(QR_PAPER)
const [doveColor, setDoveColor] = useState(QR_DOVE)
const [copied, setCopied] = useState(false) const [copied, setCopied] = useState(false)
const svgRef = useRef<SVGSVGElement>(null) const svgRef = useRef<SVGSVGElement>(null)
@ -181,8 +279,13 @@ export default function QrCodeMaker() {
const sections = kind === 'pages' ? (PAGE_SECTIONS[path] ?? []) : [] const sections = kind === 'pages' ? (PAGE_SECTIONS[path] ?? []) : []
const selected = choices.find((c) => c.path === path) ?? null const selected = choices.find((c) => c.path === path) ?? null
const target = selected ? `${selected.path}${section}` : null const typed = kind === 'custom' ? typedUrl(custom) : null
const url = target ? siteUrl(target) : null const target = kind === 'custom' ? typed : selected ? `${selected.path}${section}` : null
const url = kind === 'custom' ? typed : target ? siteUrl(target) : null
const centreOption = CENTRES.find((c) => c.id === centreId) ?? CENTRES[0]
const centre = centreOption.centre(doveColor)
const warning = scanWarning(ink, paper)
useEffect(() => setCopied(false), [url]) useEffect(() => setCopied(false), [url])
@ -198,7 +301,7 @@ export default function QrCodeMaker() {
} }
} }
const needsDirectory = kind !== 'pages' const needsDirectory = kind !== 'pages' && kind !== 'custom'
return ( return (
<div className="grid gap-10 lg:grid-cols-2 lg:items-start"> <div className="grid gap-10 lg:grid-cols-2 lg:items-start">
@ -211,7 +314,27 @@ export default function QrCodeMaker() {
))} ))}
</Select> </Select>
{needsDirectory && loading && !directory ? ( {kind === 'custom' ? (
<div>
<label htmlFor="qr-custom" className="block text-sm font-medium text-[#26454c]">
Link
</label>
<input
id="qr-custom"
type="text"
inputMode="url"
value={custom}
onChange={(e) => setCustom(e.target.value)}
placeholder="https://… or /retreats"
className={`mt-2 ${inputClass}`}
/>
<p className="mt-1 text-sm" style={{ color: custom.trim() && !typed ? '#b3261e' : MUTED }}>
{custom.trim() && !typed
? 'That isn’t a web address. Use https://…, a domain, or a site path like /retreats.'
: 'A full address, a domain (example.org), or a path on this site (/retreats).'}
</p>
</div>
) : needsDirectory && loading && !directory ? (
<p style={{ color: MUTED }}>Loading the list…</p> <p style={{ color: MUTED }}>Loading the list…</p>
) : needsDirectory && error ? ( ) : needsDirectory && error ? (
<p className="text-[#b3261e]">Couldn't load the list of pages. {error}</p> <p className="text-[#b3261e]">Couldn't load the list of pages. {error}</p>
@ -258,15 +381,43 @@ export default function QrCodeMaker() {
</Select> </Select>
)} )}
<label className="flex items-center gap-3 text-[#26454c]"> <Select id="qr-centre" label="In the centre" value={centreId} onChange={setCentreId}>
<input {CENTRES.map((c) => (
type="checkbox" <option key={c.id} value={c.id}>
checked={dove} {c.label}
onChange={(e) => setDove(e.target.checked)} </option>
className="h-4 w-4 accent-[#138ba0]" ))}
/> </Select>
NGU dove in the centre
</label> <fieldset>
<legend className="text-sm font-medium text-[#26454c]">Colours</legend>
<div className="mt-2 flex flex-wrap items-end gap-5">
<ColourInput id="qr-ink" label="Code" value={ink} onChange={setInk} />
<ColourInput id="qr-paper" label="Background" value={paper} onChange={setPaper} />
{centreOption.id === 'dove' && (
<ColourInput id="qr-dove" label="Dove" value={doveColor} onChange={setDoveColor} />
)}
{(ink !== QR_INK || paper !== QR_PAPER || doveColor !== QR_DOVE) && (
<button
type="button"
onClick={() => {
setInk(QR_INK)
setPaper(QR_PAPER)
setDoveColor(QR_DOVE)
}}
className="pb-2 text-sm underline"
style={{ color: TEAL }}
>
Reset colours
</button>
)}
</div>
{warning && (
<p role="status" className="mt-2 rounded-lg bg-[#fdf3f2] px-3 py-2 text-sm text-[#b3261e]">
{warning}
</p>
)}
</fieldset>
{url && ( {url && (
<div> <div>
@ -295,7 +446,9 @@ export default function QrCodeMaker() {
<QrCode <QrCode
ref={svgRef} ref={svgRef}
value={url} value={url}
dove={dove} centre={centre}
ink={ink}
paper={paper}
label={`QR code for ${url}`} label={`QR code for ${url}`}
className="block h-auto w-full" className="block h-auto w-full"
/> />
@ -333,6 +486,52 @@ function DownloadButton({ onClick, children }: { onClick: () => void; children:
) )
} }
const inputClass =
'w-full rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 text-[#26454c] ' +
'outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25'
/* A colour well with its hex beside it, both editable. */
function ColourInput({
id,
label,
value,
onChange,
}: {
id: string
label: string
value: string
onChange: (value: string) => void
}) {
const [text, setText] = useState(value)
useEffect(() => setText(value), [value])
return (
<div>
<label htmlFor={id} className="block text-xs font-medium" style={{ color: MUTED }}>
{label}
</label>
<div className="mt-1 flex items-center gap-2">
<input
id={id}
type="color"
value={value}
onChange={(e) => onChange(e.target.value)}
className="h-9 w-11 cursor-pointer rounded border border-[#4a6b72]/25 bg-white"
/>
<input
type="text"
aria-label={`${label} colour, as hex`}
value={text}
onChange={(e) => {
setText(e.target.value)
if (/^#[0-9a-f]{6}$/i.test(e.target.value)) onChange(e.target.value.toLowerCase())
}}
className="w-24 rounded-lg border border-[#4a6b72]/25 bg-white px-2 py-1.5 font-mono text-sm text-[#26454c] outline-none focus:border-[#138ba0]"
/>
</div>
</div>
)
}
const selectClass = const selectClass =
'w-full appearance-none rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 pr-10 text-[#26454c] ' + 'w-full appearance-none rounded-xl border border-[#4a6b72]/25 bg-white px-4 py-3 pr-10 text-[#26454c] ' +
'outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25' 'outline-none transition-colors focus:border-[#138ba0] focus:ring-2 focus:ring-[#138ba0]/25'