Files
Convivo/apps/admin/src/views/BadgeEditor.tsx
T
8e38052f4c feat(admin): per-row badge preview with unconfigured tooltip, Excel-style column filters and search in Contacts/Registrations
- New shared BadgeRender module (resolveText/resolveQr/BadgeElementBody/BadgePagePreview/fitScale) reused by the badge editor and the new read-only preview modal
- Registrations: Badge button on every row opens a live preview of that attendee's badge; grayed out with a Uiverse-style APPE-red tooltip when the event has no badge configured
- Contacts + Registrations: per-column multi-select filters (LinkedIn/Visibility/Admin; Type/Ticket/Checked in) with Excel-style live counts, plus general search (contacts: first/last/email; registrations: +type)
- New Tooltip and ColumnFilter primitives in ui.tsx (portal-based, escape/outside-click close)
- e2e: registration-badge-preview.spec.ts (13) + table-filters.spec.ts (13), all green; docs synced

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-16 08:53:46 +02:00

1045 lines
48 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.
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<string>();
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<Event[]>([]);
const [eventId, setEventId] = useState('');
const [layouts, setLayouts] = useState<BadgeLayout[]>([]);
const [doc, setDoc] = useState<Doc>(DEFAULT_DOC);
const [selectedIds, setSelectedIds] = useState<string[]>([]);
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<Guide[]>([]);
const [sample, setSample] = useState<BadgeSample>({
full_name: 'John Doe', email: '[email protected]', ticket_type: 'attendee',
qr_token: 'CV-DEMO-0001', event_name: 'Sample Event', company: 'Sample Company',
});
const past = useRef<Doc[]>([]);
const future = useRef<Doc[]>([]);
const pageRef = useRef<HTMLDivElement>(null);
const drag = useRef<null | (
| { kind: 'move'; ids: string[]; start: Vec; origs: { id: string; x: number; y: number; w: number; h: number }[] }
| { kind: 'resize'; id: string; start: Vec; orig: BadgeElement; dir: Vec }
| { kind: 'rotate'; id: string; start: Vec; orig: BadgeElement; startAngle: number }
)>(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<BadgeElement>) => {
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<BadgeElement>) => {
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<string, number>();
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 <div className="loading-screen"><Spinner /></div>;
}
const evSelect = (
<select className="input" value={eventId} onChange={(e) => setEventId(e.target.value)} aria-label="Event">
{events.length === 0 && <option value="">No events</option>}
{events.map((ev) => <option key={ev.id} value={ev.id}>{ev.name}{ev.is_active ? ' (active)' : ''}</option>)}
</select>
);
if (!eventId) {
return <div className="badge-editor"><div className="page-head"><h1>Badge Editor</h1></div><Empty icon="🎫" text="Create an event first to design its badges." /></div>;
}
return (
<div className="badge-editor">
<div className="page-head">
<div>
<h1>Badge Editor</h1>
<p className="muted small">Design a printable attendee badge for each event. Positions are in millimetres.</p>
</div>
<div className="badge-event-pick">{evSelect}</div>
</div>
{loadingEvent ? (
<div className="loading-screen"><Spinner /></div>
) : (
<>
<div className="badge-toolbar" role="toolbar" aria-label="Badge editor toolbar">
<div className="badge-layout-pick">
<span className="muted small">Badge layout:</span>
<select className="input" value={doc.name} onChange={(e) => chooseLayout(e.target.value)} aria-label="Badge layout">
{layouts.length === 0 && <option value={doc.name}>{doc.name}</option>}
{layouts.map((l) => <option key={l.id} value={l.name}>{l.name}{l.is_default ? ' ★' : ''}</option>)}
</select>
<button className="btn small" onClick={newLayout} title="New layout">New</button>
<button className="btn small" onClick={makeDefault} disabled={doc.is_default} title="Set as default">
<Star size={14} aria-hidden="true" /> {doc.is_default ? 'Default' : 'Make default'}
</button>
<button className="btn small danger" onClick={removeLayout} title="Delete layout"><Trash2 size={14} aria-hidden="true" /></button>
</div>
<div className="badge-tools">
<button className="btn small" onClick={() => addElement('text')} title="Add text box"><TypeIcon size={14} aria-hidden="true" /> Text</button>
<button className="btn small" onClick={() => addElement('qr')} title="Add QR code"><QrIcon size={14} aria-hidden="true" /> QR Code</button>
<button className="btn small" onClick={() => addElement('image')} title="Add image"><ImageIcon size={14} aria-hidden="true" /> Image</button>
<span className="badge-tool-sep" />
<button className="btn small" onClick={duplicateSelected} disabled={selected.length === 0} title="Duplicate"><Copy size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={deleteSelected} disabled={selected.length === 0} title="Delete (Del)"><Trash2 size={14} aria-hidden="true" /></button>
<span className="badge-tool-sep" />
<button className="btn small" onClick={undo} disabled={past.current.length === 0} title="Undo (Ctrl+Z)"><Undo2 size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={redo} disabled={future.current.length === 0} title="Redo (Ctrl+Y)"><Redo2 size={14} aria-hidden="true" /></button>
</div>
<div className="badge-tools" role="group" aria-label="Align">
<select
className="input badge-align-ref"
value={alignRef}
onChange={(e) => setAlignRef(e.target.value as 'page' | 'selection')}
aria-label="Align relative to"
title="Align relative to the page, or to the selection"
>
<option value="page">To page</option>
<option value="selection" disabled={selected.length < 2}>To selection</option>
</select>
<button className="btn small" onClick={() => applyAlign('left')} disabled={selected.length === 0} title="Align left"><AlignStartVertical size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => applyAlign('hcenter')} disabled={selected.length === 0} title="Align centers horizontally"><AlignCenterVertical size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => applyAlign('right')} disabled={selected.length === 0} title="Align right"><AlignEndVertical size={14} aria-hidden="true" /></button>
<span className="badge-tool-sep" />
<button className="btn small" onClick={() => applyAlign('top')} disabled={selected.length === 0} title="Align top"><AlignStartHorizontal size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => applyAlign('vcenter')} disabled={selected.length === 0} title="Align centers vertically"><AlignCenterHorizontal size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => applyAlign('bottom')} disabled={selected.length === 0} title="Align bottom"><AlignEndHorizontal size={14} aria-hidden="true" /></button>
<span className="badge-tool-sep" />
<button className="btn small" onClick={() => applyDistribute('h')} disabled={selected.length < 3} title="Distribute horizontally"><AlignHorizontalDistributeCenter size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => applyDistribute('v')} disabled={selected.length < 3} title="Distribute vertically"><AlignVerticalDistributeCenter size={14} aria-hidden="true" /></button>
</div>
<div className="badge-tools right">
<button className={`btn small ${mode === 'html' ? 'active' : ''}`} onClick={() => setMode(mode === 'html' ? 'edit' : 'html')} title="Layout JSON"><Braces size={14} aria-hidden="true" /></button>
<button className={`btn small ${mode === 'preview' ? 'active' : ''}`} onClick={() => setMode(mode === 'preview' ? 'edit' : 'preview')} title="Preview"><Eye size={14} aria-hidden="true" /></button>
<button className="btn small primary" onClick={save} disabled={saving || !dirty}>{saving ? 'Saving…' : 'Save'}</button>
</div>
</div>
<div className="badge-workspace">
<div className="badge-canvas-wrap">
<div className="badge-zoom">
<button className="btn small" onClick={() => setZoom((z) => Math.max(0.6, round(z - 0.2)))}>−</button>
<span className="muted small">{Math.round(zoom * 100)}%</span>
<button className="btn small" onClick={() => setZoom((z) => Math.min(4, round(z + 0.2)))}>+</button>
{dirty && <span className="pill amber" style={{ marginLeft: 8 }}>unsaved</span>}
</div>
<div className="badge-canvas-scroll">
<div
ref={pageRef}
className="badge-page"
style={{ width: doc.page_width_mm * pxPerMm, height: doc.page_height_mm * pxPerMm }}
onPointerMove={onPointerMove}
onPointerUp={endPointer}
onPointerDown={() => setSelectedIds([])}
>
{doc.elements.length === 0 && mode === 'edit' && (
<div className="badge-page-empty">Add a text box, QR code or image to start designing.</div>
)}
{doc.elements.map((el) => (
<BadgeElementView
key={el.id}
el={el}
pxPerMm={pxPerMm}
sample={sample}
selected={mode === 'edit' && selectedIds.includes(el.id)}
interactive={mode === 'edit'}
onMove={startMove}
onResize={startResize}
onRotate={startRotate}
/>
))}
{mode === 'edit' && guides.map((g, i) => (
<span
key={`g${i}`}
className={`badge-guide badge-guide-${g.orientation} badge-guide-${g.kind}`}
style={g.orientation === 'v'
? { left: g.pos * pxPerMm, top: g.from * pxPerMm, height: (g.to - g.from) * pxPerMm }
: { top: g.pos * pxPerMm, left: g.from * pxPerMm, width: (g.to - g.from) * pxPerMm }}
/>
))}
</div>
</div>
</div>
{mode === 'html' ? (
<div className="badge-props">
<div className="badge-props-head"><strong>Layout JSON</strong></div>
<pre className="badge-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)}</pre>
</div>
) : (
<BadgePropsPanel
doc={doc}
selected={primary}
count={selected.length}
alignRef={alignRef}
setAlignRef={setAlignRef}
onAlign={applyAlign}
onDistribute={applyDistribute}
setDocPage={(patch) => commit({ ...doc, ...patch })}
setDocMeta={(patch) => commit({ ...doc, ...patch })}
patchElement={patchElement}
/>
)}
</div>
</>
)}
</div>
);
}
// ---- 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 (
<div
className={`badge-el badge-el-${el.type} ${selected ? 'selected' : ''}`}
style={style}
onPointerDown={interactive ? (e) => onMove(e, el) : undefined}
>
<BadgeElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
{selected && interactive && (
<>
{HANDLES.map((h) => (
<span
key={h.id}
className={`badge-handle badge-handle-${h.css}`}
onPointerDown={(e) => onResize(e, el, h.dir)}
/>
))}
<span className="badge-rotate-stem" />
<span className="badge-handle badge-handle-rotate" onPointerDown={(e) => onRotate(e, el)} />
</>
)}
</div>
);
}
// ---- properties panel -------------------------------------------------------
function Num({ label, value, onChange, step = 0.1, min }: { label: string; value: number; onChange: (n: number) => void; step?: number; min?: number }) {
return (
<label className="badge-field">
<span>{label}</span>
<input className="input" type="number" value={value} step={step} min={min} onChange={(e) => onChange(Number(e.target.value))} />
</label>
);
}
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<Doc>) => void;
setDocMeta: (patch: Partial<Doc>) => void;
patchElement: (id: string, patch: Partial<BadgeElement>) => void;
}) {
if (!selected) {
return (
<div className="badge-props">
<div className="badge-props-head"><strong>Page</strong></div>
<div className="badge-props-body">
<label className="badge-field">
<span>Layout name</span>
<input className="input" value={doc.name} onChange={(e) => setDocMeta({ name: e.target.value })} />
</label>
<div className="badge-field-row">
<Num label="Width (mm)" value={doc.page_width_mm} min={1} step={1} onChange={(n) => setDocPage({ page_width_mm: Math.max(1, n) })} />
<Num label="Height (mm)" value={doc.page_height_mm} min={1} step={1} onChange={(n) => setDocPage({ page_height_mm: Math.max(1, n) })} />
</div>
<p className="muted small">Select an element on the canvas to edit its properties. Shift-click to select several, then use the align tools. Press <kbd>Del</kbd> to remove, <kbd>Ctrl</kbd>+<kbd>Z</kbd> to undo and <kbd>Ctrl</kbd>+<kbd>Y</kbd> to redo.</p>
</div>
</div>
);
}
const alignBlock = (
<div className="badge-field">
<span>Align {count > 1 ? `${count} items` : 'item'}</span>
<div className="badge-btn-row">
<select className="input badge-align-ref" value={alignRef} onChange={(e) => setAlignRef(e.target.value as 'page' | 'selection')} aria-label="Align relative to">
<option value="page">To page</option>
<option value="selection" disabled={count < 2}>To selection</option>
</select>
</div>
<div className="badge-btn-row">
<button className="btn small" onClick={() => onAlign('left')} title="Align left"><AlignStartVertical size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => onAlign('hcenter')} title="Align centers horizontally"><AlignCenterVertical size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => onAlign('right')} title="Align right"><AlignEndVertical size={14} aria-hidden="true" /></button>
<span className="badge-tool-sep" />
<button className="btn small" onClick={() => onAlign('top')} title="Align top"><AlignStartHorizontal size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => onAlign('vcenter')} title="Align centers vertically"><AlignCenterHorizontal size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => onAlign('bottom')} title="Align bottom"><AlignEndHorizontal size={14} aria-hidden="true" /></button>
<span className="badge-tool-sep" />
<button className="btn small" onClick={() => onDistribute('h')} disabled={count < 3} title="Distribute horizontally"><AlignHorizontalDistributeCenter size={14} aria-hidden="true" /></button>
<button className="btn small" onClick={() => onDistribute('v')} disabled={count < 3} title="Distribute vertically"><AlignVerticalDistributeCenter size={14} aria-hidden="true" /></button>
</div>
</div>
);
const common = (
<>
<div className="badge-field-row">
<Num label="x (mm)" value={selected.x} onChange={(n) => patchElement(selected.id, { x: n })} />
<Num label="y (mm)" value={selected.y} onChange={(n) => patchElement(selected.id, { y: n })} />
</div>
<div className="badge-field-row">
<Num label="Width (mm)" value={selected.width} min={MIN_MM} onChange={(n) => patchElement(selected.id, { width: Math.max(MIN_MM, n) })} />
<Num label="Height (mm)" value={selected.height} min={MIN_MM} onChange={(n) => patchElement(selected.id, { height: Math.max(MIN_MM, n) })} />
</div>
<Num label="Rotation (°)" value={selected.rotation} step={1} onChange={(n) => patchElement(selected.id, { rotation: n })} />
</>
);
let typeBlock: React.ReactNode = null;
if (selected.type === 'text') {
const t = selected;
typeBlock = (
<>
<label className="badge-field">
<span>Content</span>
<select className="input" value={t.content} onChange={(e) => patchElement(t.id, { content: e.target.value as BadgeTextElement['content'] })}>
{(Object.keys(CONTENT_LABEL) as BadgeTextElement['content'][]).map((k) => <option key={k} value={k}>{CONTENT_LABEL[k]}</option>)}
</select>
</label>
{t.content === 'static' && (
<label className="badge-field">
<span>Text</span>
<textarea className="input" value={t.text} onChange={(e) => patchElement(t.id, { text: e.target.value })} />
</label>
)}
<label className="badge-field">
<span>Font</span>
<select className="input" value={t.font} onChange={(e) => patchElement(t.id, { font: e.target.value })}>
{FONTS.map((f) => <option key={f} value={f}>{f}</option>)}
</select>
</label>
<div className="badge-field-row">
<Num label="Font size (pt)" value={t.font_size} min={1} step={0.5} onChange={(n) => patchElement(t.id, { font_size: Math.max(1, n) })} />
<Num label="Line height" value={t.line_height} min={0.5} step={0.1} onChange={(n) => patchElement(t.id, { line_height: Math.max(0.5, n) })} />
</div>
<label className="badge-field">
<span>Text color</span>
<input className="badge-color" type="color" value={t.color} onChange={(e) => patchElement(t.id, { color: e.target.value })} />
</label>
<div className="badge-field">
<span>Style</span>
<div className="badge-btn-row">
<button className={`btn small ${t.bold ? 'active' : ''}`} onClick={() => patchElement(t.id, { bold: !t.bold })} title="Bold"><strong>B</strong></button>
<button className={`btn small ${t.italic ? 'active' : ''}`} onClick={() => patchElement(t.id, { italic: !t.italic })} title="Italic"><em>I</em></button>
</div>
</div>
<div className="badge-field">
<span>Align text in box</span>
<div className="badge-align-group">
<span className="badge-align-group-label">Horizontal</span>
<div className="badge-btn-row">
{ALIGN_H.map(({ v, label, Icon }) => (
<button key={v} className={`btn small ${t.align_h === v ? 'active' : ''}`} onClick={() => patchElement(t.id, { align_h: v })} title={label} aria-label={label} aria-pressed={t.align_h === v}><Icon size={16} aria-hidden="true" /></button>
))}
</div>
</div>
<div className="badge-align-group">
<span className="badge-align-group-label">Vertical</span>
<div className="badge-btn-row">
{ALIGN_V.map(({ v, label, Icon }) => (
<button key={v} className={`btn small ${t.align_v === v ? 'active' : ''}`} onClick={() => patchElement(t.id, { align_v: v })} title={label} aria-label={label} aria-pressed={t.align_v === v}><Icon size={16} aria-hidden="true" /></button>
))}
</div>
</div>
</div>
<label className="badge-field">
<span>Transform</span>
<select className="input" value={t.transform} onChange={(e) => patchElement(t.id, { transform: e.target.value as BadgeTextElement['transform'] })}>
<option value="none">None</option>
<option value="uppercase">UPPERCASE</option>
<option value="lowercase">lowercase</option>
<option value="capitalize">Capitalize</option>
</select>
</label>
</>
);
} else if (selected.type === 'qr') {
const q = selected;
typeBlock = (
<>
<label className="badge-field">
<span>QR value</span>
<select className="input" value={q.value} onChange={(e) => patchElement(q.id, { value: e.target.value as BadgeQrElement['value'] })}>
{(Object.keys(QR_LABEL) as BadgeQrElement['value'][]).map((k) => <option key={k} value={k}>{QR_LABEL[k]}</option>)}
</select>
</label>
{q.value === 'static' && (
<label className="badge-field">
<span>Static value</span>
<input className="input" value={q.static_value} onChange={(e) => patchElement(q.id, { static_value: e.target.value })} />
</label>
)}
</>
);
} else {
const im = selected;
typeBlock = (
<>
<label className="badge-field">
<span>Image URL / data URI</span>
<input className="input" value={im.src} placeholder="https://… or paste a data: URI" onChange={(e) => patchElement(im.id, { src: e.target.value })} />
</label>
<label className="badge-field">
<span>Fit</span>
<select className="input" value={im.fit} onChange={(e) => patchElement(im.id, { fit: e.target.value as BadgeImageElement['fit'] })}>
<option value="contain">Contain</option>
<option value="cover">Cover</option>
<option value="fill">Fill</option>
</select>
</label>
</>
);
}
return (
<div className="badge-props">
<div className="badge-props-head">
<strong>{selected.type === 'text' ? 'Text box' : selected.type === 'qr' ? 'QR Code' : 'Image'}</strong>
{count > 1 && <span className="pill violet" style={{ marginLeft: 8 }}>{count} selected</span>}
</div>
<div className="badge-props-body">
{typeBlock}
<div className="badge-props-divider" />
{alignBlock}
<div className="badge-props-divider" />
{common}
{count > 1 && <p className="muted small">Editing the fields above changes only the last-selected item; the align tools act on all {count}.</p>}
</div>
</div>
);
}