/* ═══════════════════════════════════════════════════════════════ QR CODE MAKER Pick a page, get a QR code for it on the live site. What main navigation, or one kind of record Which the page or record itself Section for a main page with a subnav, optionally one of its #sections 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 itself: serialised 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 from '../../components/QrCode.tsx' import { NAV_ACTIONS, PAGE_LINKS, PAGE_SECTIONS } from '../../navConfig.ts' import { awardHref, eventHref, orgHref, personHref, teamHref } from '../../lib/hrefs.ts' import { siteUrl } from '../../lib/site.ts' import { useDirectory, type Directory } from '../../lib/useContent.ts' const TEAL = '#138ba0' const MUTED = '#4a6b72' /* 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' const KINDS: Array<[Kind, string]> = [ ['pages', 'Main navigation'], ['events', 'Events'], ['organizations', 'Organizations'], ['teams', 'Teams'], ['awards', 'Awards'], ['people', 'People'], ] /* Organizations are grouped by kind in the dropdown, in this order. */ const ORG_GROUPS: Array<[string, string]> = [ ['national', 'NGU'], ['region', 'Regions'], ['chapter', 'Chapters'], ['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 })) }] } } /* "/regions/northwest#events" → "regions-northwest-events". */ function fileStem(path: string): string { const stem = path.replace(/^\//, '').replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '') return `ngu-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('pages') const [path, setPath] = useState('/') const [section, setSection] = useState('') const [dove, setDove] = useState(true) const [copied, setCopied] = useState(false) const svgRef = useRef(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 target = selected ? `${selected.path}${section}` : null const url = target ? siteUrl(target) : null 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' return (
{needsDirectory && loading && !directory ? (

Loading the list…

) : needsDirectory && error ? (

Couldn't load the list of pages. {error}

) : choices.length === 0 ? (

Nothing published here yet.

) : ( )} {sections.length > 0 && ( )} {url && (

Links to

{url}
)}
{url ? ( <>
svgRef.current && downloadPng(svgRef.current, fileStem(target!))}> Download PNG svgRef.current && downloadSvg(svgRef.current, fileStem(target!))}> Download SVG

PNG for documents and slides, {PNG_SIZE}px square. SVG for print: it stays sharp at any size.

) : (
)}
) } function DownloadButton({ onClick, children }: { onClick: () => void; children: ReactNode }) { return ( ) } const selectClass = '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' function Select({ id, label, value, onChange, children, }: { id: string label: string value: string onChange: (value: string) => void children: ReactNode }) { return (
) }