NGU-Web/src/pages/sections/QrCodeMaker.tsx
Zaldimmar d81f7bd856 Adopt the new palette; square corners, superellipse buttons
The theme defaults (light and dark) come from the 16-color grid,
kept as PALETTE in src/lib/color.ts; every text pair passes the
admin's 4.5:1 check. Nothing is rounded any more except buttons,
which share one btn utility (Poppins Bold, a superellipse corner
where the browser has corner-shape) and true dots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:40:39 -05:00

573 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* ═══════════════════════════════════════════════════════════════
QR CODE MAKER
Pick a page, or type a link, and get a QR code for it.
What main navigation, one kind of record, or a link
typed in
Which the page or record itself
Section for a main page with a subnav, optionally one of
its #sections
Center 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)
Colors 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
draws; records come from GET /directory, which lists only what's
published, and their URLs from hrefs.ts, the same builders the
site links with. So a code can only point at a page that exists.
Codes point at SITE_ORIGIN, never at wherever this page is open,
so one made on localhost still works on a poster.
Downloads are the on-screen <svg> itself: serialized for the SVG,
drawn onto a canvas for the PNG. Neither needs a server.
═══════════════════════════════════════════════════════════════ */
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import QrCode, { QR_DOVE, QR_INK, QR_PAPER, type QrCenter } from '../../components/QrCode.tsx'
import { NAV_ACTIONS, PAGE_LINKS, PAGE_SECTIONS } from '../../navConfig.ts'
import { awardHref, blogHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts'
import { siteUrl } from '../../lib/site.ts'
import { useDirectory, type Directory } from '../../lib/useContent.ts'
import { accentText, BRAND } from '../../lib/color.ts'
const MUTED = 'var(--color-muted)'
/* PNG download size in pixels. Plenty for print at a few inches;
anything bigger should use the SVG. */
const PNG_SIZE = 1024
type Kind = 'pages' | 'events' | 'organizations' | 'teams' | 'awards' | 'people' | 'blog_posts' | 'custom'
const KINDS: Array<[Kind, string]> = [
['pages', 'Main navigation'],
['events', 'Events'],
['organizations', 'Organizations'],
['teams', 'Teams'],
['awards', 'Awards'],
['people', 'People'],
['blog_posts', 'Blog posts'],
['custom', 'A link I type'],
]
/* The centers 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 CENTER_FILES = import.meta.glob<string>('../../assets/qr/*.svg', {
eager: true,
query: '?raw',
import: 'default',
})
type CenterOption = { id: string; label: string; center: (dove: string) => QrCenter }
const toDataUrl = (svg: string) =>
`data:image/svg+xml;base64,${btoa(String.fromCharCode(...new TextEncoder().encode(svg)))}`
const CENTERS: CenterOption[] = [
{ id: 'none', label: 'Nothing', center: () => null },
{ id: 'dove', label: 'NGU dove', center: (color) => ({ kind: 'dove', color }) },
...Object.entries(CENTER_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, center: () => ({ kind: 'image', src }) as QrCenter }
}),
]
/* ── 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. */
const ORG_GROUPS: Array<[string, string]> = [
['national', 'NGU'],
['region', 'Regions'],
['group', 'Groups'],
['partner', 'Partner organizations'],
]
type Choice = { path: string; label: string }
type Group = { label?: string; choices: Choice[] }
/* The header's pages, then any nav action that is a page of its own
rather than an anchor on one of them (Give, not Contact Us). */
function mainPages(): Choice[] {
const pages = PAGE_LINKS.map((p) => ({ path: p.path, label: p.label }))
const known = new Set(pages.map((p) => p.path))
for (const action of NAV_ACTIONS) {
const path = action.to.split('#')[0]
if (!action.to.includes('#') && !known.has(path)) {
pages.push({ path, label: action.label })
known.add(path)
}
}
return pages
}
function groupsFor(kind: Kind, directory: Directory | null): Group[] {
if (kind === 'pages') return [{ choices: mainPages() }]
if (!directory) return []
switch (kind) {
case 'events':
return [
{
choices: directory.events.map((e) => ({
path: eventHref(e.id),
label: e.starts_on ? `${e.name} (${e.starts_on.slice(0, 4)})` : e.name,
})),
},
]
case 'organizations':
return ORG_GROUPS.map(([orgKind, label]) => ({
label,
choices: directory.organizations
.filter((o) => o.kind === orgKind)
.map((o) => ({ path: orgHref(o.id, o.kind), label: o.name })),
})).filter((group) => group.choices.length > 0)
case 'teams':
return [
{
choices: directory.teams.map((t) => ({
path: teamHref(t.id),
label: `${t.name} (${t.org_name})`,
})),
},
]
case 'awards':
return [{ choices: directory.awards.map((a) => ({ path: awardHref(a.id), label: a.name })) }]
case 'people':
return [{ choices: directory.people.map((p) => ({ path: personHref(p.id), label: p.name })) }]
case 'blog_posts':
return [{ choices: directory.blog_posts.map((b) => ({ path: blogHref(b.id), label: b.name })) }]
case 'custom':
return []
}
}
/* "/regions/northwest#events" → "regions-northwest-events"; a typed
link keeps its host too: "example-org-page". */
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 `qr-${stem || 'home'}`
}
function download(href: string, filename: string) {
const a = document.createElement('a')
a.href = href
a.download = filename
document.body.appendChild(a)
a.click()
a.remove()
}
function svgMarkup(svg: SVGSVGElement): string {
return new XMLSerializer().serializeToString(svg)
}
function downloadSvg(svg: SVGSVGElement, stem: string) {
const url = URL.createObjectURL(new Blob([svgMarkup(svg)], { type: 'image/svg+xml' }))
download(url, `${stem}.svg`)
URL.revokeObjectURL(url)
}
function downloadPng(svg: SVGSVGElement, stem: string) {
const image = new Image()
image.onload = () => {
const canvas = document.createElement('canvas')
canvas.width = PNG_SIZE
canvas.height = PNG_SIZE
const context = canvas.getContext('2d')
if (!context) return
context.imageSmoothingEnabled = false
context.drawImage(image, 0, 0, PNG_SIZE, PNG_SIZE)
canvas.toBlob((blob) => {
if (!blob) return
const url = URL.createObjectURL(blob)
download(url, `${stem}.png`)
URL.revokeObjectURL(url)
}, 'image/png')
}
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgMarkup(svg))}`
}
export default function QrCodeMaker() {
const { data: directory, loading, error } = useDirectory()
const [kind, setKind] = useState<Kind>('pages')
const [path, setPath] = useState('/')
const [section, setSection] = useState('')
const [custom, setCustom] = useState('')
const [centerId, setCenterId] = 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 svgRef = useRef<SVGSVGElement>(null)
const groups = useMemo(() => groupsFor(kind, directory), [kind, directory])
const choices = useMemo(() => groups.flatMap((group) => group.choices), [groups])
// A new kind, or the directory arriving, can leave the current
// path outside the list; fall back to its first entry.
useEffect(() => {
if (choices.length > 0 && !choices.some((c) => c.path === path)) {
setPath(choices[0].path)
setSection('')
}
}, [choices, path])
const sections = kind === 'pages' ? (PAGE_SECTIONS[path] ?? []) : []
const selected = choices.find((c) => c.path === path) ?? null
const typed = kind === 'custom' ? typedUrl(custom) : null
const target = kind === 'custom' ? typed : selected ? `${selected.path}${section}` : null
const url = kind === 'custom' ? typed : target ? siteUrl(target) : null
const centerOption = CENTERS.find((c) => c.id === centerId) ?? CENTERS[0]
const center = centerOption.center(doveColor)
const warning = scanWarning(ink, paper)
useEffect(() => setCopied(false), [url])
async function copy() {
if (!url) return
try {
await navigator.clipboard.writeText(url)
setCopied(true)
} catch {
// Clipboard refused (an insecure origin, or a denied
// permission). The link is on screen to copy by hand.
setCopied(false)
}
}
const needsDirectory = kind !== 'pages' && kind !== 'custom'
return (
<div className="grid gap-10 lg:grid-cols-2 lg:items-start">
<div className="space-y-5">
<Select id="qr-kind" label="What to link to" value={kind} onChange={(v) => setKind(v as Kind)}>
{KINDS.map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</Select>
{kind === 'custom' ? (
<div>
<label htmlFor="qr-custom" className="block text-sm font-medium text-body">
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 ? 'var(--color-danger)' : 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>
) : needsDirectory && error ? (
<p className="text-danger">Couldn't load the list of pages. {error}</p>
) : choices.length === 0 ? (
<p style={{ color: MUTED }}>Nothing published here yet.</p>
) : (
<Select
id="qr-target"
label={kind === 'pages' ? 'Page' : 'Which one'}
value={path}
onChange={(v) => {
setPath(v)
setSection('')
}}
>
{groups.map((group, i) =>
group.label ? (
<optgroup key={group.label} label={group.label}>
{group.choices.map((c) => (
<option key={c.path} value={c.path}>
{c.label}
</option>
))}
</optgroup>
) : (
group.choices.map((c) => (
<option key={`${i}-${c.path}`} value={c.path}>
{c.label}
</option>
))
),
)}
</Select>
)}
{sections.length > 0 && (
<Select id="qr-section" label="Section of that page" value={section} onChange={setSection}>
<option value="">The page as a whole</option>
{sections.map((s) => (
<option key={s.hash} value={s.hash}>
{s.label.replace(/^#/, '')}
</option>
))}
</Select>
)}
<Select id="qr-center" label="In the center" value={centerId} onChange={setCenterId}>
{CENTERS.map((c) => (
<option key={c.id} value={c.id}>
{c.label}
</option>
))}
</Select>
<fieldset>
<legend className="text-sm font-medium text-body">Colors</legend>
<div className="mt-2 flex flex-wrap items-end gap-5">
<ColorInput id="qr-ink" label="Code" value={ink} onChange={setInk} />
<ColorInput id="qr-paper" label="Background" value={paper} onChange={setPaper} />
{centerOption.id === 'dove' && (
<ColorInput 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: accentText(BRAND) }}
>
Reset colors
</button>
)}
</div>
{warning && (
<p role="status" className="mt-2 bg-danger-tint px-3 py-2 text-sm text-danger">
{warning}
</p>
)}
</fieldset>
{url && (
<div>
<p className="text-sm font-medium text-body">Links to</p>
<div className="mt-2 flex flex-wrap items-center gap-3">
<code className="break-all bg-surface px-3 py-2 text-sm text-body ring-1 ring-muted/20">
{url}
</code>
<button
type="button"
onClick={copy}
className="btn border px-4 py-2 text-sm transition-colors hover:bg-brand/10"
style={{ borderColor: BRAND, color: accentText(BRAND) }}
>
{copied ? 'Copied' : 'Copy link'}
</button>
</div>
</div>
)}
</div>
<div className="flex flex-col items-center gap-5">
{url ? (
<>
<div className="w-full max-w-sm bg-white p-6 shadow-lg ring-1 ring-muted/10">
<QrCode
ref={svgRef}
value={url}
center={center}
ink={ink}
paper={paper}
label={`QR code for ${url}`}
className="block h-auto w-full"
/>
</div>
<div className="flex flex-wrap justify-center gap-3">
<DownloadButton onClick={() => svgRef.current && downloadPng(svgRef.current, fileStem(target!))}>
Download PNG
</DownloadButton>
<DownloadButton onClick={() => svgRef.current && downloadSvg(svgRef.current, fileStem(target!))}>
Download SVG
</DownloadButton>
</div>
<p className="max-w-sm text-center text-sm" style={{ color: MUTED }}>
PNG for documents and slides, {PNG_SIZE}px square. SVG for print: it stays sharp at
any size.
</p>
</>
) : (
<div className="aspect-square w-full max-w-sm bg-surface/60 ring-1 ring-muted/10" />
)}
</div>
</div>
)
}
function DownloadButton({ onClick, children }: { onClick: () => void; children: ReactNode }) {
return (
<button
type="button"
onClick={onClick}
className="btn bg-action px-6 py-3 text-white transition-colors hover:bg-action-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand/40"
>
{children}
</button>
)
}
const inputClass =
'w-full border border-muted/50 bg-surface px-4 py-3 text-body ' +
'outline-none transition-colors focus:border-brand focus:ring-2 focus:ring-brand/25'
/* A color well with its hex beside it, both editable. */
function ColorInput({
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 border border-muted/25 bg-white"
/>
<input
type="text"
aria-label={`${label} color, 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 border border-muted/50 bg-surface px-2 py-1.5 font-mono text-sm text-body outline-none focus:border-brand"
/>
</div>
</div>
)
}
const selectClass =
'w-full appearance-none border border-muted/50 bg-surface px-4 py-3 pr-10 text-body ' +
'outline-none transition-colors focus:border-brand focus:ring-2 focus:ring-brand/25'
function Select({
id,
label,
value,
onChange,
children,
}: {
id: string
label: string
value: string
onChange: (value: string) => void
children: ReactNode
}) {
return (
<div>
<label htmlFor={id} className="block text-sm font-medium text-body">
{label}
</label>
<div className="relative mt-2">
<select id={id} value={value} onChange={(e) => onChange(e.target.value)} className={selectClass}>
{children}
</select>
<svg
aria-hidden="true"
viewBox="0 0 20 20"
fill="none"
className="pointer-events-none absolute right-4 top-1/2 h-4 w-4 -translate-y-1/2"
style={{ color: MUTED }}
>
<path d="M5 8l5 5 5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
</div>
</div>
)
}