import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Copy, Eye, Redo2, Trash2, Undo2, Braces, Type as TypeIcon, QrCode as QrIcon, Image as ImageIcon, Star, AlignStartVertical, AlignCenterVertical, AlignEndVertical, AlignStartHorizontal, AlignCenterHorizontal, AlignEndHorizontal, AlignHorizontalDistributeCenter, AlignVerticalDistributeCenter, AlignLeft, AlignCenter, AlignRight, ArrowUpToLine, ArrowDownToLine, ChevronsUpDown, } from 'lucide-react'; import { deleteBadgeLayout, getAllEvents, getBadgeLayouts, getRegistrations, getAllContacts, saveBadgeLayout, setDefaultBadgeLayout, } from '../lib/api'; import type { BadgeElement, BadgeImageElement, BadgeLayout, BadgeQrElement, BadgeSample, BadgeTextElement, Event, } from '../lib/types'; import { useToast } from '../context/ToastContext'; import { Empty, Spinner } from '../components/ui'; import { CONTENT_LABEL, MM, QR_LABEL, BadgeElementBody } from '../components/BadgeRender'; const MIN_MM = 2; const FONTS = ['Open Sans', 'Helvetica', 'Arial', 'Georgia', 'Times New Roman', 'Courier New', 'system-ui']; // Text alignment *within* an element's own box (not the box on the page). const ALIGN_H: { v: BadgeTextElement['align_h']; label: string; Icon: typeof AlignLeft }[] = [ { v: 'left', label: 'Align text left', Icon: AlignLeft }, { v: 'center', label: 'Center text', Icon: AlignCenter }, { v: 'right', label: 'Align text right', Icon: AlignRight }, ]; const ALIGN_V: { v: BadgeTextElement['align_v']; label: string; Icon: typeof ArrowUpToLine }[] = [ { v: 'top', label: 'Align text to top', Icon: ArrowUpToLine }, { v: 'middle', label: 'Center text vertically', Icon: ChevronsUpDown }, { v: 'bottom', label: 'Align text to bottom', Icon: ArrowDownToLine }, ]; function newId(): string { return Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4); } function makeText(): BadgeTextElement { return { id: newId(), type: 'text', x: 10, y: 10, width: 60, height: 10, rotation: 0, content: 'attendee_name', text: 'John Doe', font: 'Open Sans', font_size: 13, line_height: 1, color: '#000000', bold: false, italic: false, align_h: 'left', align_v: 'middle', transform: 'none', }; } function makeQr(): BadgeQrElement { return { id: newId(), type: 'qr', x: 10, y: 10, width: 25, height: 25, rotation: 0, value: 'qr_token', static_value: 'https://example.com' }; } function makeImage(): BadgeImageElement { return { id: newId(), type: 'image', x: 10, y: 10, width: 30, height: 20, rotation: 0, src: '', fit: 'contain' }; } // ---- geometry helpers (vectors in mm) --------------------------------------- type Vec = { x: number; y: number }; // A PowerPoint-style smart guide drawn while dragging. `orientation` is the // line's direction on screen: 'v' = a vertical line at constant x=`pos`, // 'h' = a horizontal line at constant y=`pos`. `from`/`to` are its extent along // that line. `kind` distinguishes edge/centre alignment from equal-spacing. type Guide = { orientation: 'v' | 'h'; pos: number; from: number; to: number; kind: 'align' | 'space' }; interface Box { x: number; y: number; w: number; h: number } // Snap distance, in screen pixels, converted to mm by the caller. const SNAP_PX = 6; // The bounding box of a set of dragged elements after applying `delta`. function draggedBox(origs: { x: number; y: number; w: number; h: number }[], delta: Vec): Box { const minX = Math.min(...origs.map((o) => o.x)) + delta.x; const minY = Math.min(...origs.map((o) => o.y)) + delta.y; const maxX = Math.max(...origs.map((o) => o.x + o.w)) + delta.x; const maxY = Math.max(...origs.map((o) => o.y + o.h)) + delta.y; return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }; } // Compute PowerPoint-style smart guides for a moving box against the page and // the other (static) elements. Returns the snap offset to apply plus the guide // lines to draw. Alignment wins over equal-spacing on each axis. function computeSmartGuides( box: Box, statics: Box[], page: { w: number; h: number }, thr: number, ): { dx: number; dy: number; guides: Guide[] } { const guides: Guide[] = []; const mL = box.x, mCx = box.x + box.w / 2, mR = box.x + box.w; const mT = box.y, mCy = box.y + box.h / 2, mB = box.y + box.h; // ---- X axis: vertical guides (constant x) ---- const xTargets: { val: number; from: number; to: number }[] = [ { val: 0, from: 0, to: page.h }, { val: page.w / 2, from: 0, to: page.h }, { val: page.w, from: 0, to: page.h }, ]; for (const s of statics) { xTargets.push({ val: s.x, from: s.y, to: s.y + s.h }); xTargets.push({ val: s.x + s.w / 2, from: s.y, to: s.y + s.h }); xTargets.push({ val: s.x + s.w, from: s.y, to: s.y + s.h }); } let dx = 0; let best = thr + 1; for (const mv of [mL, mCx, mR]) for (const t of xTargets) { const d = t.val - mv; if (Math.abs(d) < Math.abs(best)) best = d; } if (Math.abs(best) <= thr) { dx = best; for (const mv of [mL, mCx, mR]) for (const t of xTargets) { if (Math.abs(t.val - mv - best) < 1e-6) { guides.push({ orientation: 'v', pos: t.val, from: Math.min(t.from, mT), to: Math.max(t.to, mB), kind: 'align' }); } } } else { // Equal horizontal spacing between the nearest static edges on each side. const edges = [0, page.w]; for (const s of statics) edges.push(s.x, s.x + s.w); edges.sort((a, b) => a - b); let leftEdge = -Infinity; let rightEdge = Infinity; for (const e of edges) { if (e <= mL + 1e-9) leftEdge = Math.max(leftEdge, e); if (e >= mR - 1e-9) rightEdge = Math.min(rightEdge, e); } if (Number.isFinite(leftEdge) && Number.isFinite(rightEdge)) { const gapL = mL - leftEdge; const gapR = rightEdge - mR; if (gapL > 0 && gapR > 0 && Math.abs(gapL - gapR) <= thr) { dx = (gapR - gapL) / 2; guides.push({ orientation: 'h', pos: mCy, from: leftEdge, to: mL + dx, kind: 'space' }); guides.push({ orientation: 'h', pos: mCy, from: mR + dx, to: rightEdge, kind: 'space' }); } } } // ---- Y axis: horizontal guides (constant y) ---- const yTargets: { val: number; from: number; to: number }[] = [ { val: 0, from: 0, to: page.w }, { val: page.h / 2, from: 0, to: page.w }, { val: page.h, from: 0, to: page.w }, ]; for (const s of statics) { yTargets.push({ val: s.y, from: s.x, to: s.x + s.w }); yTargets.push({ val: s.y + s.h / 2, from: s.x, to: s.x + s.w }); yTargets.push({ val: s.y + s.h, from: s.x, to: s.x + s.w }); } let dy = 0; let bestY = thr + 1; for (const mv of [mT, mCy, mB]) for (const t of yTargets) { const d = t.val - mv; if (Math.abs(d) < Math.abs(bestY)) bestY = d; } if (Math.abs(bestY) <= thr) { dy = bestY; for (const mv of [mT, mCy, mB]) for (const t of yTargets) { if (Math.abs(t.val - mv - bestY) < 1e-6) { guides.push({ orientation: 'h', pos: t.val, from: Math.min(t.from, mL), to: Math.max(t.to, mR), kind: 'align' }); } } } else { const edges = [0, page.h]; for (const s of statics) edges.push(s.y, s.y + s.h); edges.sort((a, b) => a - b); let topEdge = -Infinity; let botEdge = Infinity; for (const e of edges) { if (e <= mT + 1e-9) topEdge = Math.max(topEdge, e); if (e >= mB - 1e-9) botEdge = Math.min(botEdge, e); } if (Number.isFinite(topEdge) && Number.isFinite(botEdge)) { const gapT = mT - topEdge; const gapB = botEdge - mB; if (gapT > 0 && gapB > 0 && Math.abs(gapT - gapB) <= thr) { dy = (gapB - gapT) / 2; guides.push({ orientation: 'v', pos: mCx, from: topEdge, to: mT + dy, kind: 'space' }); guides.push({ orientation: 'v', pos: mCx, from: mB + dy, to: botEdge, kind: 'space' }); } } } // De-duplicate identical guide lines. const seen = new Set(); const uniq = guides.filter((g) => { const k = `${g.orientation}:${Math.round(g.pos * 100)}:${g.kind}`; if (seen.has(k)) return false; seen.add(k); return true; }); return { dx, dy, guides: uniq }; } const rad = (d: number) => (d * Math.PI) / 180; function rotate(v: Vec, deg: number): Vec { const c = Math.cos(rad(deg)); const s = Math.sin(rad(deg)); return { x: v.x * c - v.y * s, y: v.x * s + v.y * c }; } const add = (a: Vec, b: Vec): Vec => ({ x: a.x + b.x, y: a.y + b.y }); const sub = (a: Vec, b: Vec): Vec => ({ x: a.x - b.x, y: a.y - b.y }); const centerOf = (e: BadgeElement): Vec => ({ x: e.x + e.width / 2, y: e.y + e.height / 2 }); type Handle = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w'; const HANDLES: { id: Handle; dir: Vec; css: string }[] = [ { id: 'nw', dir: { x: -1, y: -1 }, css: 'nw' }, { id: 'n', dir: { x: 0, y: -1 }, css: 'n' }, { id: 'ne', dir: { x: 1, y: -1 }, css: 'ne' }, { id: 'e', dir: { x: 1, y: 0 }, css: 'e' }, { id: 'se', dir: { x: 1, y: 1 }, css: 'se' }, { id: 's', dir: { x: 0, y: 1 }, css: 's' }, { id: 'sw', dir: { x: -1, y: 1 }, css: 'sw' }, { id: 'w', dir: { x: -1, y: 0 }, css: 'w' }, ]; type Doc = { name: string; is_default: boolean; page_width_mm: number; page_height_mm: number; elements: BadgeElement[] }; const DEFAULT_DOC: Doc = { name: 'Default', is_default: true, page_width_mm: 100, page_height_mm: 70, elements: [] }; function docFromLayout(l: BadgeLayout): Doc { return { name: l.name, is_default: l.is_default, page_width_mm: Number(l.page_width_mm), page_height_mm: Number(l.page_height_mm), elements: Array.isArray(l.elements) ? l.elements : [], }; } export function BadgeEditor() { const { push } = useToast(); const [events, setEvents] = useState([]); const [eventId, setEventId] = useState(''); const [layouts, setLayouts] = useState([]); const [doc, setDoc] = useState(DEFAULT_DOC); const [selectedIds, setSelectedIds] = useState([]); const [alignRef, setAlignRef] = useState<'page' | 'selection'>('page'); const [loaded, setLoaded] = useState(false); const [loadingEvent, setLoadingEvent] = useState(false); const [saving, setSaving] = useState(false); const [mode, setMode] = useState<'edit' | 'preview' | 'html'>('edit'); const [zoom, setZoom] = useState(1.6); const [dirty, setDirty] = useState(false); const [guides, setGuides] = useState([]); const [sample, setSample] = useState({ full_name: 'John Doe', email: 'john@example.com', ticket_type: 'attendee', qr_token: 'CV-DEMO-0001', event_name: 'Sample Event', company: 'Sample Company', }); const past = useRef([]); const future = useRef([]); const pageRef = useRef(null); const drag = useRef(null); const pxPerMm = MM * zoom; // Load events once; default to the active event. useEffect(() => { (async () => { try { const evs = await getAllEvents(); setEvents(evs); const active = evs.find((e) => e.is_active) ?? evs[0]; if (active) setEventId(active.id); else setLoaded(true); } catch (e) { push('error', e instanceof Error ? e.message : 'Failed to load events'); setLoaded(true); } })(); }, [push]); // Load layouts + a real sample attendee whenever the event changes. useEffect(() => { if (!eventId) return; let active = true; setLoadingEvent(true); (async () => { try { const [ls, regs, contacts] = await Promise.all([getBadgeLayouts(eventId), getRegistrations(eventId), getAllContacts()]); if (!active) return; setLayouts(ls); const ev = events.find((e) => e.id === eventId); if (ev) { const byEmail = new Map(contacts.map((c) => [c.email, c])); const real = regs.find((r) => r.type !== 'staff' && byEmail.get(r.contact_email)); const c = real ? byEmail.get(real.contact_email) : undefined; if (c) { setSample({ full_name: c.full_name, email: c.email, ticket_type: real?.type ?? 'attendee', qr_token: real?.qr_token || 'CV-DEMO-0001', event_name: ev.name, company: ev.company || '', }); } else { setSample((s) => ({ ...s, event_name: ev.name, company: ev.company || '' })); } } const def = ls.find((l) => l.is_default) ?? ls[0]; setDoc(def ? docFromLayout(def) : { ...DEFAULT_DOC }); setSelectedIds([]); past.current = []; future.current = []; setDirty(false); setLoaded(true); } catch (e) { if (active) push('error', e instanceof Error ? e.message : 'Failed to load badge layouts'); setLoaded(true); } finally { if (active) setLoadingEvent(false); } })(); return () => { active = false; }; }, [eventId, events, push]); const selected = useMemo( () => doc.elements.filter((el) => selectedIds.includes(el.id)), [doc.elements, selectedIds], ); // The properties panel edits the most-recently selected element. const primary = selected.length > 0 ? selected[selected.length - 1] : null; function selectOnly(id: string | null) { setSelectedIds(id ? [id] : []); } const commit = useCallback((next: Doc) => { past.current.push(doc); if (past.current.length > 60) past.current.shift(); future.current = []; setDoc(next); setDirty(true); }, [doc]); const patchElement = useCallback((id: string, patch: Partial) => { commit({ ...doc, elements: doc.elements.map((el) => (el.id === id ? ({ ...el, ...patch } as BadgeElement) : el)) }); }, [commit, doc]); // Live (non-history) update used during a drag; history is pushed on pointerup. const livePatch = useCallback((id: string, patch: Partial) => { setDoc((d) => ({ ...d, elements: d.elements.map((el) => (el.id === id ? ({ ...el, ...patch } as BadgeElement) : el)) })); setDirty(true); }, []); function undo() { const prev = past.current.pop(); if (!prev) return; future.current.push(doc); setDoc(prev); setSelectedIds([]); setDirty(true); } function redo() { const nxt = future.current.pop(); if (!nxt) return; past.current.push(doc); setDoc(nxt); setSelectedIds([]); setDirty(true); } function addElement(kind: BadgeElement['type']) { const el = kind === 'text' ? makeText() : kind === 'qr' ? makeQr() : makeImage(); commit({ ...doc, elements: [...doc.elements, el] }); selectOnly(el.id); setMode('edit'); } function duplicateSelected() { if (selected.length === 0) return; const copies = selected.map((el) => ({ ...el, id: newId(), x: el.x + 4, y: el.y + 4 }) as BadgeElement); commit({ ...doc, elements: [...doc.elements, ...copies] }); setSelectedIds(copies.map((c) => c.id)); } function deleteSelected() { if (selected.length === 0) return; const drop = new Set(selectedIds); commit({ ...doc, elements: doc.elements.filter((el) => !drop.has(el.id)) }); setSelectedIds([]); } // ---- alignment (Word-style page edges + PowerPoint-style object align) ---- // The reference box: the page, or the bounding box of the selection. function alignBounds(): { x: number; y: number; w: number; h: number } { if (alignRef === 'selection' && selected.length >= 2) { const minX = Math.min(...selected.map((e) => e.x)); const minY = Math.min(...selected.map((e) => e.y)); const maxX = Math.max(...selected.map((e) => e.x + e.width)); const maxY = Math.max(...selected.map((e) => e.y + e.height)); return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }; } return { x: 0, y: 0, w: doc.page_width_mm, h: doc.page_height_mm }; } function applyAlign(mode: 'left' | 'hcenter' | 'right' | 'top' | 'vcenter' | 'bottom') { if (selected.length === 0) return; const b = alignBounds(); const ids = new Set(selectedIds); const elements = doc.elements.map((el) => { if (!ids.has(el.id)) return el; switch (mode) { case 'left': return { ...el, x: round(b.x) }; case 'hcenter': return { ...el, x: round(b.x + b.w / 2 - el.width / 2) }; case 'right': return { ...el, x: round(b.x + b.w - el.width) }; case 'top': return { ...el, y: round(b.y) }; case 'vcenter': return { ...el, y: round(b.y + b.h / 2 - el.height / 2) }; case 'bottom': return { ...el, y: round(b.y + b.h - el.height) }; default: return el; } }); commit({ ...doc, elements }); } // PowerPoint-style even distribution across the reference box (needs 3+). function applyDistribute(axis: 'h' | 'v') { if (selected.length < 3) return; const b = alignBounds(); const sorted = [...selected].sort((a, c) => (axis === 'h' ? a.x - c.x : a.y - c.y)); const total = axis === 'h' ? sorted.reduce((s, e) => s + e.width, 0) : sorted.reduce((s, e) => s + e.height, 0); const span = axis === 'h' ? b.w : b.h; const gap = (span - total) / (sorted.length - 1); const pos = new Map(); let cursor = axis === 'h' ? b.x : b.y; for (const el of sorted) { pos.set(el.id, round(cursor)); cursor += (axis === 'h' ? el.width : el.height) + gap; } const ids = new Set(selectedIds); const elements = doc.elements.map((el) => { if (!ids.has(el.id)) return el; const p = pos.get(el.id); return p == null ? el : (axis === 'h' ? { ...el, x: p } : { ...el, y: p }); }); commit({ ...doc, elements }); } // Keyboard: Delete/Backspace removes the selection, Escape clears it, and // Ctrl/Cmd+Z undoes / Ctrl+Y (or Ctrl/Cmd+Shift+Z) redoes — but only when // focus is not in a text field (so typing or native field undo is safe). useEffect(() => { function onKey(e: KeyboardEvent) { const t = e.target as HTMLElement | null; const typing = !!t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable); if (typing) return; const mod = e.ctrlKey || e.metaKey; const key = e.key.toLowerCase(); if (mod && key === 'z' && !e.shiftKey) { e.preventDefault(); undo(); } else if ((mod && key === 'y') || (mod && key === 'z' && e.shiftKey)) { e.preventDefault(); redo(); } else if ((e.key === 'Delete' || e.key === 'Backspace') && selectedIds.length > 0) { e.preventDefault(); deleteSelected(); } else if (e.key === 'Escape') { setSelectedIds([]); } } window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); // eslint-disable-next-line react-hooks/exhaustive-deps }, [selectedIds, doc]); // ---- pointer interactions ------------------------------------------------- function toMm(clientX: number, clientY: number): Vec { const rect = pageRef.current?.getBoundingClientRect(); if (!rect) return { x: 0, y: 0 }; return { x: (clientX - rect.left) / pxPerMm, y: (clientY - rect.top) / pxPerMm }; } function startMove(e: React.PointerEvent, el: BadgeElement) { e.stopPropagation(); // Shift/Ctrl toggles membership (multi-select); otherwise select just this one. let ids: string[]; if (e.shiftKey || e.ctrlKey || e.metaKey) { ids = selectedIds.includes(el.id) ? selectedIds.filter((x) => x !== el.id) : [...selectedIds, el.id]; // Dragging acts on the whole resulting selection. if (!ids.includes(el.id)) ids = [...ids, el.id]; setSelectedIds(ids); } else { ids = selectedIds.includes(el.id) && selectedIds.length > 1 ? selectedIds : [el.id]; setSelectedIds(ids); } const drop = new Set(ids); (e.target as Element).setPointerCapture?.(e.pointerId); setGuides([]); drag.current = { kind: 'move', ids, start: toMm(e.clientX, e.clientY), origs: doc.elements.filter((x) => drop.has(x.id)).map((x) => ({ id: x.id, x: x.x, y: x.y, w: x.width, h: x.height })), }; } function startResize(e: React.PointerEvent, el: BadgeElement, dir: Vec) { e.stopPropagation(); (e.target as Element).setPointerCapture?.(e.pointerId); drag.current = { kind: 'resize', id: el.id, start: toMm(e.clientX, e.clientY), orig: el, dir }; } function startRotate(e: React.PointerEvent, el: BadgeElement) { e.stopPropagation(); (e.target as Element).setPointerCapture?.(e.pointerId); const c = centerOf(el); const p = toMm(e.clientX, e.clientY); drag.current = { kind: 'rotate', id: el.id, start: p, orig: el, startAngle: Math.atan2(p.y - c.y, p.x - c.x) }; } function onPointerMove(e: React.PointerEvent) { const d = drag.current; if (!d) return; const p = toMm(e.clientX, e.clientY); if (d.kind === 'move') { let delta = sub(p, d.start); // Smart guides: snap the dragged group's bounding box to nearby edges / // centres and equalise spacing, and record the guide lines to draw. const drop = new Set(d.ids); const statics: Box[] = doc.elements.filter((el) => !drop.has(el.id)).map((el) => ({ x: el.x, y: el.y, w: el.width, h: el.height })); const thr = SNAP_PX / pxPerMm; const { dx, dy, guides: gs } = computeSmartGuides(draggedBox(d.origs, delta), statics, { w: doc.page_width_mm, h: doc.page_height_mm }, thr); delta = { x: delta.x + dx, y: delta.y + dy }; setGuides(gs); for (const o of d.origs) livePatch(o.id, { x: round(o.x + delta.x), y: round(o.y + delta.y) }); } else if (d.kind === 'resize') { const dir = d.dir; const local = rotate(sub(p, d.start), -d.orig.rotation); const oldC = centerOf(d.orig); let w = d.orig.width + dir.x * local.x; let h = d.orig.height + dir.y * local.y; w = Math.max(MIN_MM, w); h = Math.max(MIN_MM, h); // Keep the opposite anchor fixed on screen. const anchorLocalOld = { x: (-dir.x * d.orig.width) / 2, y: (-dir.y * d.orig.height) / 2 }; const anchorPage = add(oldC, rotate(anchorLocalOld, d.orig.rotation)); const anchorLocalNew = { x: (-dir.x * w) / 2, y: (-dir.y * h) / 2 }; const newC = sub(anchorPage, rotate(anchorLocalNew, d.orig.rotation)); livePatch(d.id, { width: round(w), height: round(h), x: round(newC.x - w / 2), y: round(newC.y - h / 2), }); } else if (d.kind === 'rotate') { const c = centerOf(d.orig); let angle = (Math.atan2(p.y - c.y, p.x - c.x) - d.startAngle) * 180 / Math.PI + d.orig.rotation; if (e.shiftKey) angle = Math.round(angle / 15) * 15; livePatch(d.id, { rotation: round(angle) }); } } function endPointer(e: React.PointerEvent) { const d = drag.current; if (!d) return; (e.target as Element).releasePointerCapture?.(e.pointerId); setGuides([]); // Push a single history entry for the whole gesture. if (d.kind === 'move') { const origs = new Map(d.origs.map((o) => [o.id, o])); const changed = doc.elements.some((el) => { const o = origs.get(el.id); return o != null && (o.x !== el.x || o.y !== el.y); }); if (changed) { past.current.push({ ...doc, elements: doc.elements.map((el) => { const o = origs.get(el.id); return o ? ({ ...el, x: o.x, y: o.y } as BadgeElement) : el; }), }); future.current = []; } } else { const current = doc.elements.find((el) => el.id === d.id); if (current && JSON.stringify(current) !== JSON.stringify(d.orig)) { past.current.push({ ...doc, elements: doc.elements.map((el) => (el.id === d.id ? d.orig : el)) }); future.current = []; } } drag.current = null; } const round = (n: number) => Math.round(n * 100) / 100; // ---- save / layout management -------------------------------------------- async function reloadLayouts(keepName?: string) { const ls = await getBadgeLayouts(eventId); setLayouts(ls); if (keepName) { const match = ls.find((l) => l.name === keepName); if (match) setDoc(docFromLayout(match)); } } async function save() { if (!eventId) return; if (!doc.name.trim()) { push('error', 'Layout name is required'); return; } setSaving(true); try { await saveBadgeLayout({ event_id: eventId, name: doc.name.trim(), page_width_mm: doc.page_width_mm, page_height_mm: doc.page_height_mm, elements: doc.elements, is_default: doc.is_default, }); await reloadLayouts(doc.name.trim()); setDirty(false); push('success', `Saved "${doc.name.trim()}"`); } catch (e) { push('error', e instanceof Error ? e.message : 'Failed to save layout'); } finally { setSaving(false); } } async function chooseLayout(name: string) { if (name === doc.name && !dirty) return; const l = layouts.find((x) => x.name === name); if (l) { setDoc(docFromLayout(l)); setSelectedIds([]); past.current = []; future.current = []; setDirty(false); } } async function newLayout() { const base = prompt('New layout name', 'New layout'); if (!base || !base.trim()) return; const name = base.trim(); if (layouts.some((l) => l.name === name)) { push('error', 'A layout with that name already exists'); return; } setDoc({ ...DEFAULT_DOC, name, is_default: false }); setSelectedIds([]); past.current = []; future.current = []; setDirty(true); setMode('edit'); } async function makeDefault() { const existing = layouts.find((l) => l.name === doc.name); if (existing) { try { await setDefaultBadgeLayout(existing.id); await reloadLayouts(doc.name); push('success', `"${doc.name}" is now the default`); } catch (e) { push('error', e instanceof Error ? e.message : 'Failed to set default'); } } else { setDoc((d) => ({ ...d, is_default: true })); setDirty(true); } } async function removeLayout() { const existing = layouts.find((l) => l.name === doc.name); if (!existing) { push('error', 'Save this layout before deleting it'); return; } if (!confirm(`Delete badge layout "${doc.name}"?`)) return; try { await deleteBadgeLayout(existing.id); const ls = await getBadgeLayouts(eventId); setLayouts(ls); const def = ls.find((l) => l.is_default) ?? ls[0]; setDoc(def ? docFromLayout(def) : { ...DEFAULT_DOC }); setSelectedIds([]); past.current = []; future.current = []; setDirty(false); push('success', 'Layout deleted'); } catch (e) { push('error', e instanceof Error ? e.message : 'Failed to delete layout'); } } if (!loaded) { return
; } const evSelect = ( ); if (!eventId) { return

Badge Editor

; } return (

Badge Editor

Design a printable attendee badge for each event. Positions are in millimetres.

{evSelect}
{loadingEvent ? (
) : ( <>
Badge layout:
{Math.round(zoom * 100)}% {dirty && unsaved}
setSelectedIds([])} > {doc.elements.length === 0 && mode === 'edit' && (
Add a text box, QR code or image to start designing.
)} {doc.elements.map((el) => ( ))} {mode === 'edit' && guides.map((g, i) => ( ))}
{mode === 'html' ? (
Layout JSON
{JSON.stringify({ name: doc.name, is_default: doc.is_default, page_width_mm: doc.page_width_mm, page_height_mm: doc.page_height_mm, elements: doc.elements }, null, 2)}
) : ( commit({ ...doc, ...patch })} setDocMeta={(patch) => commit({ ...doc, ...patch })} patchElement={patchElement} /> )}
)}
); } // ---- one element rendered on the canvas ------------------------------------- function BadgeElementView({ el, pxPerMm, sample, selected, interactive, onMove, onResize, onRotate, }: { el: BadgeElement; pxPerMm: number; sample: BadgeSample; selected: boolean; interactive: boolean; onMove: (e: React.PointerEvent, el: BadgeElement) => void; onResize: (e: React.PointerEvent, el: BadgeElement, dir: Vec) => void; onRotate: (e: React.PointerEvent, el: BadgeElement) => void; }) { const style: React.CSSProperties = { left: el.x * pxPerMm, top: el.y * pxPerMm, width: el.width * pxPerMm, height: el.height * pxPerMm, transform: `rotate(${el.rotation}deg)`, }; return (
onMove(e, el) : undefined} > {selected && interactive && ( <> {HANDLES.map((h) => ( onResize(e, el, h.dir)} /> ))} onRotate(e, el)} /> )}
); } // ---- properties panel ------------------------------------------------------- function Num({ label, value, onChange, step = 0.1, min }: { label: string; value: number; onChange: (n: number) => void; step?: number; min?: number }) { return ( ); } function BadgePropsPanel({ doc, selected, count, alignRef, setAlignRef, onAlign, onDistribute, setDocPage, setDocMeta, patchElement, }: { doc: Doc; selected: BadgeElement | null; count: number; alignRef: 'page' | 'selection'; setAlignRef: (v: 'page' | 'selection') => void; onAlign: (m: 'left' | 'hcenter' | 'right' | 'top' | 'vcenter' | 'bottom') => void; onDistribute: (axis: 'h' | 'v') => void; setDocPage: (patch: Partial) => void; setDocMeta: (patch: Partial) => void; patchElement: (id: string, patch: Partial) => void; }) { if (!selected) { return (
Page
setDocPage({ page_width_mm: Math.max(1, n) })} /> setDocPage({ page_height_mm: Math.max(1, n) })} />

Select an element on the canvas to edit its properties. Shift-click to select several, then use the align tools. Press Del to remove, Ctrl+Z to undo and Ctrl+Y to redo.

); } const alignBlock = (
Align {count > 1 ? `${count} items` : 'item'}
); const common = ( <>
patchElement(selected.id, { x: n })} /> patchElement(selected.id, { y: n })} />
patchElement(selected.id, { width: Math.max(MIN_MM, n) })} /> patchElement(selected.id, { height: Math.max(MIN_MM, n) })} />
patchElement(selected.id, { rotation: n })} /> ); let typeBlock: React.ReactNode = null; if (selected.type === 'text') { const t = selected; typeBlock = ( <> {t.content === 'static' && (