diff --git a/apps/admin/src/App.tsx b/apps/admin/src/App.tsx index 0d6ade7..0b852e9 100644 --- a/apps/admin/src/App.tsx +++ b/apps/admin/src/App.tsx @@ -9,6 +9,7 @@ import { Sponsors } from './views/Sponsors'; import { Schedule } from './views/Schedule'; import { Activity } from './views/Activity'; import { Raffle } from './views/Raffle'; +import { BadgeEditor } from './views/BadgeEditor'; import { Events } from './views/Events'; import { Interfaces } from './views/Interfaces'; import { Reports } from './views/Reports'; @@ -24,6 +25,7 @@ export type View = | 'schedule' | 'activity' | 'raffle' + | 'badges' | 'events' | 'interfaces' | 'reports' @@ -37,6 +39,7 @@ const NAV: { id: View; label: string; ico: string }[] = [ { id: 'schedule', label: 'Schedule', ico: 'πŸ—“οΈ' }, { id: 'activity', label: 'Activity', ico: '⚑' }, { id: 'raffle', label: 'Raffle', ico: '🎯' }, + { id: 'badges', label: 'Badges', ico: '🎫' }, { id: 'events', label: 'Events', ico: 'πŸ“…' }, { id: 'interfaces', label: 'Interfaces', ico: 'πŸ”Œ' }, { id: 'reports', label: 'Reports', ico: 'πŸ“€' }, @@ -108,6 +111,7 @@ function Shell() { {view === 'schedule' && } {view === 'activity' && } {view === 'raffle' && } + {view === 'badges' && } {view === 'events' && } {view === 'interfaces' && } {view === 'reports' && } diff --git a/apps/admin/src/lib/api.ts b/apps/admin/src/lib/api.ts index f5f7eca..36c95f0 100644 --- a/apps/admin/src/lib/api.ts +++ b/apps/admin/src/lib/api.ts @@ -1,5 +1,7 @@ import { supabase } from './supabase'; import type { + BadgeElement, + BadgeLayout, Checkin, Connection, Contact, @@ -215,6 +217,7 @@ export async function upsertEvent( start_date: string; end_date: string; location?: string | null; + company?: string | null; sessionize_endpoint?: string | null; pretix_organizer?: string | null; pretix_event_slug?: string | null; @@ -376,6 +379,45 @@ export async function resetRaffle(): Promise { await rpc('reset_raffle', {}); } +// ---- Badge editor (per-event WYSIWYG badge layout) -------------------------- + +/** All badge layouts for an event (default first, then by name). */ +export async function getBadgeLayouts(eventId: string): Promise { + const rows = await all('badge_layouts'); + return rows + .filter((r) => r.event_id === eventId) + .sort((a, b) => Number(b.is_default) - Number(a.is_default) || a.name.localeCompare(b.name)); +} + +/** Insert or update a layout (matched on event_id + name). */ +export async function saveBadgeLayout(input: { + event_id: string; + name: string; + page_width_mm: number; + page_height_mm: number; + elements: BadgeElement[]; + is_default: boolean; +}): Promise { + return rpc('save_badge_layout', { + p_event_id: input.event_id, + p_name: input.name, + p_page_width_mm: input.page_width_mm, + p_page_height_mm: input.page_height_mm, + p_elements: input.elements, + p_is_default: input.is_default, + }); +} + +/** Promote a layout to the event's default (demoting the previous one). */ +export async function setDefaultBadgeLayout(id: string): Promise { + await rpc('set_default_badge_layout', { p_id: id }); +} + +/** Delete a layout (the sole default may not be removed). */ +export async function deleteBadgeLayout(id: string): Promise { + await rpc('delete_badge_layout', { p_id: id }); +} + // ---- Sessions: speakers, material, AI feedback ------------------------------- export async function setSessionSpeakers(sessionId: string, emails: string[]): Promise { diff --git a/apps/admin/src/lib/types.ts b/apps/admin/src/lib/types.ts index a676ad3..486dee7 100644 --- a/apps/admin/src/lib/types.ts +++ b/apps/admin/src/lib/types.ts @@ -59,6 +59,8 @@ export interface Event { pretix_event_slug?: string | null; /** Pretix API token for this event (stored in plain text, visible in settings). */ pretix_api_key?: string | null; + /** The owning organisation / company (e.g. the Pretix organizer name). */ + company?: string | null; /** When the Sessionize sync last ran for this event. */ last_synced_at: string | null; /** Bonus points each party earns for a connection when they shared a checked-in talk (0 = off). */ @@ -152,6 +154,7 @@ export interface PretixRun { reason?: string; orders?: number; attendees?: number; + company?: string | null; skipped?: number; summary?: PretixSyncSummary; error?: string; @@ -343,3 +346,89 @@ export interface RaffleWinner extends RafflePoolEntry { draw_number: number; drawn_at: string; } + +// ---- Badge editor (per-event WYSIWYG badge layout) -------------------------- + +/** A bindable attendee/event field for a text element. */ +export type BadgeContentField = + | 'attendee_name' + | 'full_name' + | 'email' + | 'ticket_type' + | 'event_name' + | 'company' + | 'qr_token' + | 'static'; + +/** A bindable payload source for a QR element. */ +export type BadgeQrValue = + | 'qr_token' + | 'checkin_url' + | 'email' + | 'attendee_name' + | 'static'; + +export type BadgeElementType = 'text' | 'qr' | 'image'; + +/** Common geometry for every badge element, in millimetres / degrees. */ +export interface BadgeElementBase { + id: string; + type: BadgeElementType; + x: number; + y: number; + width: number; + height: number; + rotation: number; +} + +export interface BadgeTextElement extends BadgeElementBase { + type: 'text'; + content: BadgeContentField; + text: string; + font: string; + font_size: number; + line_height: number; + color: string; + bold: boolean; + italic: boolean; + align_h: 'left' | 'center' | 'right'; + align_v: 'top' | 'middle' | 'bottom'; + transform: 'none' | 'uppercase' | 'lowercase' | 'capitalize'; +} + +export interface BadgeQrElement extends BadgeElementBase { + type: 'qr'; + value: BadgeQrValue; + static_value: string; +} + +export interface BadgeImageElement extends BadgeElementBase { + type: 'image'; + src: string; + fit: 'contain' | 'cover' | 'fill'; +} + +export type BadgeElement = BadgeTextElement | BadgeQrElement | BadgeImageElement; + +/** A saved badge layout row from `badge_layouts`. */ +export interface BadgeLayout { + id: string; + event_id: string; + name: string; + is_default: boolean; + page_width_mm: number; + page_height_mm: number; + elements: BadgeElement[]; + created_at: string; + updated_at: string; +} + +/** A sample attendee used to preview a layout's bound fields. */ +export interface BadgeSample { + full_name: string; + email: string; + ticket_type: string; + qr_token: string; + event_name: string; + company: string; +} diff --git a/apps/admin/src/styles.css b/apps/admin/src/styles.css index fc68536..2e62e17 100644 --- a/apps/admin/src/styles.css +++ b/apps/admin/src/styles.css @@ -106,6 +106,7 @@ body { .btn.ghost { background: transparent; } .btn.danger { background: rgba(213,0,0,.08); border-color: rgba(213,0,0,.35); color: var(--red); } .btn.small { padding: 8px 12px; font-size: 12.5px; border-radius: 10px; } +.btn.active { background: var(--accent-soft); border-color: rgba(213,0,0,.4); color: var(--accent); } .btn:disabled { opacity: .45; cursor: not-allowed; } .icon-btn { width: 34px; height: 34px; border-radius: 10px; border: 1px solid var(--line); background: var(--surface); @@ -389,3 +390,87 @@ table.data tr:hover td { background: rgba(244,245,249,.6); } .sidebar-foot { display: none; } .content { padding: 20px 16px 50px; } } + +/* ---------- Badge editor (per-event WYSIWYG layout) ---------- */ +.badge-editor { display: grid; gap: 16px; } +.badge-event-pick select { min-width: 220px; } +.badge-toolbar { + display: flex; align-items: center; gap: 14px; flex-wrap: wrap; + padding: 10px 12px; background: var(--surface); border: 1px solid var(--line); border-radius: 14px; +} +.badge-layout-pick, .badge-tools { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.badge-tools.right { margin-left: auto; } +.badge-layout-pick select { min-width: 160px; } +.badge-tool-sep { width: 1px; height: 22px; background: var(--line); margin: 0 2px; } +.badge-workspace { display: grid; grid-template-columns: 1fr 300px; gap: 16px; align-items: start; } +.badge-canvas-wrap { display: grid; gap: 10px; min-width: 0; } +.badge-zoom { display: flex; align-items: center; gap: 8px; } +.badge-canvas-scroll { + overflow: auto; background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px; + padding: 28px; display: flex; justify-content: center; align-items: flex-start; min-height: 360px; +} +.badge-page { + position: relative; background: #fff; box-shadow: 0 10px 30px rgba(0,0,0,.12); flex: none; + touch-action: none; +} +.badge-page-empty { + position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; + color: #94a3b8; font-size: 13px; text-align: center; padding: 20px; pointer-events: none; +} +.badge-el { position: absolute; overflow: visible; cursor: move; } +.badge-el.selected { outline: 1.5px solid var(--accent); } +.badge-text-body { width: 100%; height: 100%; display: flex; overflow: hidden; } +.badge-text-body > span { max-width: 100%; overflow-wrap: anywhere; } +.badge-el-placeholder { color: #cbd5e1; font-style: italic; } +.badge-qr-body { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; } +.badge-qr-body svg { width: 100%; height: 100%; } +.badge-image-body { width: 100%; height: 100%; display: block; } +.badge-image-empty { + display: flex; align-items: center; justify-content: center; color: #94a3b8; font-size: 12px; + border: 1px dashed #cbd5e1; background: #f8fafc; +} +.badge-handle { + position: absolute; width: 9px; height: 9px; background: #fff; border: 1.5px solid var(--accent); + border-radius: 2px; transform: translate(-50%, -50%); z-index: 2; +} +.badge-handle-nw { left: 0; top: 0; cursor: nwse-resize; } +.badge-handle-n { left: 50%; top: 0; cursor: ns-resize; } +.badge-handle-ne { left: 100%; top: 0; cursor: nesw-resize; } +.badge-handle-e { left: 100%; top: 50%; cursor: ew-resize; } +.badge-handle-se { left: 100%; top: 100%; cursor: nwse-resize; } +.badge-handle-s { left: 50%; top: 100%; cursor: ns-resize; } +.badge-handle-sw { left: 0; top: 100%; cursor: nesw-resize; } +.badge-handle-w { left: 0; top: 50%; cursor: ew-resize; } +.badge-rotate-stem { position: absolute; left: 50%; top: -18px; width: 1.5px; height: 18px; background: var(--accent); transform: translateX(-50%); } +.badge-handle-rotate { left: 50%; top: -18px; border-radius: 50%; cursor: grab; } +.badge-props { background: var(--surface); border: 1px solid var(--line); border-radius: 14px; overflow: hidden; position: sticky; top: 16px; } +.badge-props-head { padding: 12px 14px; border-bottom: 1px solid var(--line); background: var(--surface-2); } +.badge-props-body { padding: 14px; display: grid; gap: 12px; } +.badge-field { display: grid; gap: 5px; } +.badge-field > span { font-size: 12px; font-weight: 600; color: var(--muted); } +.badge-field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; } +.badge-color { width: 100%; height: 34px; padding: 2px; border: 1px solid var(--line); border-radius: 10px; background: var(--surface-2); } +.badge-btn-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } +.badge-props-divider { height: 1px; background: var(--line); margin: 2px 0; } +.badge-json { + margin: 14px; font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; + max-height: 560px; overflow: auto; color: var(--text); +} +@media (max-width: 900px) { + .badge-workspace { grid-template-columns: 1fr; } + .badge-props { position: static; } +} + +/* Badge editor: alignment tools + multi-select */ +.badge-props-head { display: flex; align-items: center; } +.badge-align-ref { width: auto; flex: 1; min-width: 110px; padding: 7px 10px; font-size: 12.5px; } +.badge-editor kbd { + font-family: inherit; font-size: 11px; font-weight: 700; padding: 1px 5px; + border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 5px; background: var(--surface-2); +} + +/* Badge editor: PowerPoint-style smart guides (shown while dragging) */ +.badge-guide { position: absolute; pointer-events: none; z-index: 5; } +.badge-guide-v { width: 0; border-left: 1px dashed #ff2d95; } +.badge-guide-h { height: 0; border-top: 1px dashed #ff2d95; } +.badge-guide-space { border-color: #0ea5e9; } diff --git a/apps/admin/src/views/BadgeEditor.tsx b/apps/admin/src/views/BadgeEditor.tsx new file mode 100644 index 0000000..72a7788 --- /dev/null +++ b/apps/admin/src/views/BadgeEditor.tsx @@ -0,0 +1,1089 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { QRCodeSVG } from 'qrcode.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, +} 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'; + +// CSS 96 dpi: 1mm = 3.7795px. Multiplied by the editor zoom. +const MM = 3.7795275591; +const MIN_MM = 2; +const FONTS = ['Open Sans', 'Helvetica', 'Arial', 'Georgia', 'Times New Roman', 'Courier New', 'system-ui']; + +const CONTENT_LABEL: Record = { + attendee_name: 'Attendee name', + full_name: 'Full name', + email: 'Email address', + ticket_type: 'Ticket type', + event_name: 'Event name', + company: 'Company / organizer', + qr_token: 'QR / badge token', + static: 'Static text', +}; +const QR_LABEL: Record = { + qr_token: 'QR / badge token', + checkin_url: 'Check-in URL', + email: 'Email address', + attendee_name: 'Attendee name', + static: 'Static value', +}; + +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 }); + +// Resolve the bound content of a text element against a sample attendee. +function resolveText(el: BadgeTextElement, sample: BadgeSample): string { + let v: string; + switch (el.content) { + case 'attendee_name': + case 'full_name': v = sample.full_name; break; + case 'email': v = sample.email; break; + case 'ticket_type': v = sample.ticket_type; break; + case 'event_name': v = sample.event_name; break; + case 'company': v = sample.company; break; + case 'qr_token': v = sample.qr_token; break; + default: v = el.text; + } + if (el.transform === 'uppercase') return v.toUpperCase(); + if (el.transform === 'lowercase') return v.toLowerCase(); + if (el.transform === 'capitalize') return v.replace(/\b\w/g, (m) => m.toUpperCase()); + return v; +} + +function resolveQr(el: BadgeQrElement, sample: BadgeSample): string { + switch (el.value) { + case 'qr_token': return sample.qr_token || 'CONVIVO-QR'; + case 'checkin_url': return `${window.location.origin}/checkin/${sample.qr_token || 'TOKEN'}`; + case 'email': return sample.email || 'attendee@example.com'; + case 'attendee_name': return sample.full_name || 'Attendee'; + default: return el.static_value || 'https://example.com'; + } +} + +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 β€” but + // only when focus is not in a text field (so typing in the panel 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; + 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)} /> + + )} +
+ ); +} + +function ElementBody({ el, sample, pxPerMm }: { el: BadgeElement; sample: BadgeSample; pxPerMm: number }) { + if (el.type === 'text') { + const text = resolveText(el, sample); + return ( +
+ {text || {CONTENT_LABEL[el.content]}} +
+ ); + } + if (el.type === 'qr') { + const size = Math.round(Math.min(el.width, el.height) * pxPerMm); + return ( +
+ +
+ ); + } + // image + if (!el.src) { + return
Image
; + } + return ; +} + +// ---- 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.

+
+
+ ); + } + + 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' && ( +