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
This commit is contained in:
Lago committed 2026-10-16 08:53:46 +02:00
1 parent 6b277a2a67
commit 3d4dc207ff
10 files changed
+988 -121

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
import { QRCodeSVG } from 'qrcode.react';
import type { BadgeElement, BadgeQrElement, BadgeSample, BadgeTextElement } from '../lib/types';
// CSS 96 dpi: 1mm = 3.7795px. Shared by the editor canvas and read-only previews.
export const MM = 3.7795275591;
export const CONTENT_LABEL: Record<BadgeTextElement['content'], string> = {
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',
};
export const QR_LABEL: Record<BadgeQrElement['value'], string> = {
qr_token: 'QR / badge token',
checkin_url: 'Check-in URL',
email: 'Email address',
attendee_name: 'Attendee name',
static: 'Static value',
};
/** Resolve the bound content of a text element against a sample attendee. */
export 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;
}
/** Resolve the encoded value of a QR element against a sample attendee. */
export 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 || '[email protected]';
case 'attendee_name': return sample.full_name || 'Attendee';
default: return el.static_value || 'https://example.com';
}
}
/** The visual body of one badge element (text / QR / image), no editing chrome. */
export function BadgeElementBody({ el, sample, pxPerMm }: { el: BadgeElement; sample: BadgeSample; pxPerMm: number }) {
if (el.type === 'text') {
const text = resolveText(el, sample);
return (
<div
className="badge-text-body"
style={{
fontFamily: `"${el.font}", sans-serif`,
fontSize: el.font_size * (pxPerMm / MM), // pt→mm→px so print scale matches
lineHeight: el.line_height,
color: el.color,
fontWeight: el.bold ? 700 : 400,
fontStyle: el.italic ? 'italic' : 'normal',
justifyContent: el.align_h === 'left' ? 'flex-start' : el.align_h === 'right' ? 'flex-end' : 'center',
alignItems: el.align_v === 'top' ? 'flex-start' : el.align_v === 'bottom' ? 'flex-end' : 'center',
textAlign: el.align_h,
}}
>
<span>{text || <span className="badge-el-placeholder">{CONTENT_LABEL[el.content]}</span>}</span>
</div>
);
}
if (el.type === 'qr') {
const size = Math.round(Math.min(el.width, el.height) * pxPerMm);
return (
<div className="badge-qr-body">
<QRCodeSVG value={resolveQr(el, sample)} size={Math.max(16, size)} level="M" marginSize={0} />
</div>
);
}
// image
if (!el.src) {
return <div className="badge-image-body badge-image-empty">Image</div>;
}
return <img className="badge-image-body" src={el.src} alt="" style={{ objectFit: el.fit }} />;
}
export interface BadgePageData {
page_width_mm: number;
page_height_mm: number;
elements: BadgeElement[];
}
/**
* Read-only rendering of a badge layout for a specific attendee — the exact
* same markup the editor canvas produces, minus the editing chrome.
*/
export function BadgePagePreview({ layout, sample, pxPerMm, className = '' }: {
layout: BadgePageData; sample: BadgeSample; pxPerMm: number; className?: string;
}) {
return (
<div
className={`badge-page badge-page-static ${className}`}
style={{ width: layout.page_width_mm * pxPerMm, height: layout.page_height_mm * pxPerMm }}
>
{layout.elements.map((el) => (
<div
key={el.id}
className={`badge-el badge-el-${el.type}`}
style={{
left: el.x * pxPerMm, top: el.y * pxPerMm,
width: el.width * pxPerMm, height: el.height * pxPerMm,
transform: `rotate(${el.rotation}deg)`,
cursor: 'default',
}}
>
<BadgeElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
</div>
))}
</div>
);
}
/** Fit a layout inside a box of `maxW` × `maxH` px, returning the px-per-mm scale. */
export function fitScale(layout: BadgePageData, maxW: number, maxH: number): number {
return Math.min(maxW / layout.page_width_mm, maxH / layout.page_height_mm);
}
+139 -1
View File
@@ -1,4 +1,6 @@
import { type ReactNode } from 'react';
import { cloneElement, isValidElement, useEffect, useRef, useState, useId, type ReactElement, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { Filter } from 'lucide-react';
import { QRCodeSVG } from 'qrcode.react';
const AV_COLORS = ['#d50000', '#20b2aa', '#e11d48', '#0d9488', '#f59e0b', '#0ea5e9', '#dc2626', '#7c3aed', '#16a34a', '#ea580c', '#0891b2', '#db2777'];
@@ -108,3 +110,139 @@ export function Toggle({
</label>
);
}
/**
* Hover/focus tooltip rendered through a portal, so it is never clipped by
* scrollable or `overflow: hidden` ancestors (e.g. data tables). The card
* visual follows the Uiverse dark-glass tooltip already used in Interfaces,
* re-themed to the APPE red accent. Wrap any element — including a disabled
* button, whose own mouse events browsers suppress.
*/
export function Tooltip({ content, title, children }: {
content: ReactNode;
title?: string;
children: ReactNode;
}) {
const anchor = useRef<HTMLSpanElement>(null);
const id = useId();
const [pos, setPos] = useState<{ x: number; y: number } | null>(null);
const show = () => {
const r = anchor.current?.getBoundingClientRect();
if (r) setPos({ x: r.left + r.width / 2, y: r.top });
};
const hide = () => setPos(null);
// Point the control at the card so screen readers announce the explanation
// when it is focused (focus also reveals it visually).
const child = isValidElement(children)
? cloneElement(children as ReactElement<{ 'aria-describedby'?: string }>, { 'aria-describedby': id })
: children;
return (
<span className="tip-anchor" ref={anchor} onMouseEnter={show} onMouseLeave={hide} onFocus={show} onBlur={hide}>
{child}
{pos && createPortal(
<div className="tip-card" role="tooltip" id={id} style={{ left: pos.x, top: pos.y - 10 }}>
{title && (
<div className="tip-head">
<span className="tip-ico" aria-hidden="true">
<svg viewBox="0 0 20 20" fill="currentColor" width="15" height="15">
<path clipRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" fillRule="evenodd" />
</svg>
</span>
<strong>{title}</strong>
</div>
)}
<p>{content}</p>
<span className="tip-arrow" aria-hidden="true" />
</div>,
document.body,
)}
</span>
);
}
/** One selectable value inside a `ColumnFilter`, with a live result count. */
export interface ColumnFilterOption {
value: string;
label: string;
count: number;
}
/**
* Excel-style multi-select filter for a table column. Rendered through a portal
* so the dropdown is never clipped by the table's `overflow: hidden`. An empty
* selection means "no filter" (everything matches).
*/
export function ColumnFilter({ label, options, selected, onChange }: {
label: string;
options: ColumnFilterOption[];
selected: string[];
onChange: (next: string[]) => void;
}) {
const btnRef = useRef<HTMLButtonElement>(null);
const popRef = useRef<HTMLDivElement>(null);
const [open, setOpen] = useState(false);
const [pos, setPos] = useState<{ left: number; top: number } | null>(null);
const active = selected.length > 0;
const toggleOpen = () => {
if (!open) {
const r = btnRef.current?.getBoundingClientRect();
if (r) setPos({ left: Math.min(Math.max(8, r.left), window.innerWidth - 240), top: r.bottom + 6 });
}
setOpen((o) => !o);
};
const toggleValue = (value: string) =>
onChange(selected.includes(value) ? selected.filter((v) => v !== value) : [...selected, value]);
useEffect(() => {
if (!open) return;
const onDown = (e: MouseEvent) => {
const t = e.target as Node;
if (popRef.current?.contains(t) || btnRef.current?.contains(t)) return;
setOpen(false);
};
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); };
const onScroll = () => setOpen(false);
window.addEventListener('mousedown', onDown);
window.addEventListener('keydown', onKey);
window.addEventListener('scroll', onScroll, true);
return () => {
window.removeEventListener('mousedown', onDown);
window.removeEventListener('keydown', onKey);
window.removeEventListener('scroll', onScroll, true);
};
}, [open]);
return (
<span className="colfilter">
<button
ref={btnRef}
type="button"
className={`colfilter-btn ${active ? 'on' : ''}`}
onClick={toggleOpen}
aria-label={`Filter ${label}`}
aria-expanded={open}
title={`Filter ${label}`}
>
<Filter size={13} aria-hidden="true" />
{active && <span className="colfilter-count">{selected.length}</span>}
</button>
{open && pos && createPortal(
<div className="colfilter-pop" ref={popRef} role="group" aria-label={`Filter ${label}`} style={{ left: pos.left, top: pos.top }}>
<div className="colfilter-head">
<strong>{label}</strong>
{active && <button type="button" className="colfilter-clear" onClick={() => onChange([])}>Clear</button>}
</div>
{options.map((o) => (
<label key={o.value} className="colfilter-opt">
<input type="checkbox" checked={selected.includes(o.value)} onChange={() => toggleValue(o.value)} />
<span className="lbl">{o.label}</span>
<span className="cnt">{o.count}</span>
</label>
))}
</div>,
document.body,
)}
</span>
);
}
+58
View File
@@ -171,6 +171,34 @@ body {
.uiverse-tooltip .uiverse-card h3 { margin: 0; font-size: 13px; font-weight: 600; color: #fff; }
.uiverse-tooltip .uiverse-card p { margin: 0; font-size: 13px; line-height: 1.5; color: #d1d5db; }
.uiverse-tooltip .uiverse-card .uiverse-foot { display: flex; align-items: center; gap: 8px; margin-top: 10px; font-size: 11px; color: #9ca3af; }
/* Portal tooltip (same Uiverse dark-glass card, APPE-red themed). Rendered on
document.body so it is never clipped by table overflow. */
.tip-anchor { position: relative; display: inline-flex; }
/* Disabled buttons swallow mouse events, so make them hit-test-transparent and
let the wrapper carry the hover (and the not-allowed cursor). */
.tip-anchor > button:disabled { pointer-events: none; }
.tip-anchor:has(> button:disabled) { cursor: not-allowed; }
.tip-card {
position: fixed; transform: translate(-50%, -100%); width: 250px; padding: 13px 15px;
background: linear-gradient(135deg, rgba(17,24,39,.97), rgba(31,41,55,.97));
backdrop-filter: blur(8px); border: 1px solid rgba(213,0,0,.35); border-radius: 14px;
box-shadow: 0 0 26px rgba(213,0,0,.18), 0 14px 34px rgba(0,0,0,.35);
z-index: 120; pointer-events: none; animation: tip-in .18s ease;
}
@keyframes tip-in { from { opacity: 0; transform: translate(-50%, calc(-100% + 6px)); } to { opacity: 1; transform: translate(-50%, -100%); } }
.tip-card .tip-head { display: flex; align-items: center; gap: 9px; margin-bottom: 6px; }
.tip-card .tip-head strong { font-size: 13px; font-weight: 700; color: #fff; }
.tip-card .tip-ico {
display: flex; align-items: center; justify-content: center; width: 26px; height: 26px;
border-radius: 50%; background: rgba(213,0,0,.22); color: #ff6b6b; flex-shrink: 0;
}
.tip-card p { margin: 0; font-size: 12.5px; line-height: 1.5; color: #d1d5db; }
.tip-card .tip-arrow {
position: absolute; bottom: -6px; left: 50%; transform: translateX(-50%) rotate(45deg);
width: 12px; height: 12px; background: rgba(31,41,55,.97);
border-right: 1px solid rgba(213,0,0,.35); border-bottom: 1px solid rgba(213,0,0,.35);
}
/* sponsor tiers */
.pill.headline { background: rgba(213,0,0,.1); border-color: rgba(213,0,0,.35); color: var(--red); }
.pill.platinum { background: rgba(148,163,184,.16); border-color: rgba(148,163,184,.45); color: #475569; }
@@ -227,6 +255,31 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
.row-actions { display: flex; gap: 6px; justify-content: flex-end; flex-wrap: wrap; }
/* ---------- Column filter (Excel-style, portalled so it isn't clipped) ---------- */
.colfilter { position: relative; display: inline-flex; margin-left: 6px; vertical-align: middle; }
.colfilter-btn {
display: inline-flex; align-items: center; gap: 3px; padding: 3px 6px; border-radius: 7px;
border: 1px solid var(--line); background: var(--surface); color: var(--muted);
cursor: pointer; font: inherit; transition: all .15s ease;
}
.colfilter-btn:hover { border-color: rgba(213,0,0,.4); color: var(--accent); }
.colfilter-btn.on { background: var(--accent-soft); border-color: rgba(213,0,0,.45); color: var(--accent); }
.colfilter-count { font-size: 10px; font-weight: 800; min-width: 14px; text-align: center; }
.colfilter-pop {
position: fixed; z-index: 130; width: 220px; max-height: 300px; overflow-y: auto; padding: 8px;
background: var(--surface); border: 1px solid var(--line); border-radius: 12px;
box-shadow: 0 16px 40px rgba(66,60,60,.22); animation: colfilter-in .14s ease;
}
@keyframes colfilter-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
.colfilter-head { display: flex; align-items: center; justify-content: space-between; padding: 4px 8px 8px; border-bottom: 1px solid var(--line); margin-bottom: 6px; }
.colfilter-head strong { font-size: 12px; text-transform: uppercase; letter-spacing: .4px; color: var(--muted); }
.colfilter-clear { border: none; background: none; color: var(--accent); font-size: 12px; font-weight: 700; cursor: pointer; padding: 2px 4px; }
.colfilter-opt { display: flex; align-items: center; gap: 9px; padding: 7px 8px; border-radius: 8px; cursor: pointer; font-size: 13px; }
.colfilter-opt:hover { background: var(--surface-2); }
.colfilter-opt input { accent-color: var(--accent); width: 15px; height: 15px; cursor: pointer; }
.colfilter-opt .lbl { flex: 1; text-transform: capitalize; }
.colfilter-opt .cnt { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
/* ---------- Modal ---------- */
.backdrop { position: fixed; inset: 0; background: rgba(5,5,10,.6); backdrop-filter: blur(3px); z-index: 70; display: flex; align-items: center; justify-content: center; padding: 20px; }
.modal {
@@ -424,6 +477,11 @@ table.data tr:hover td { background: rgba(244,245,249,.6); }
.badge-el-placeholder { color: #cbd5e1; font-style: italic; }
.badge-align-group { margin-top: 8px; }
.badge-align-group-label { display: block; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 4px; }
.badge-preview-stage {
display: flex; justify-content: center; align-items: center; padding: 16px;
background: var(--surface-2); border: 1px solid var(--line); border-radius: 14px; min-height: 180px;
}
.badge-page-static { flex: none; }
.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; }
+2 -88
View File
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import {
Copy,
Eye,
@@ -46,30 +45,11 @@ import type {
} from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Empty, Spinner } from '../components/ui';
import { CONTENT_LABEL, MM, QR_LABEL, BadgeElementBody } from '../components/BadgeRender';
// 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<BadgeTextElement['content'], string> = {
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<BadgeQrElement['value'], string> = {
qr_token: 'QR / badge token',
checkin_url: 'Check-in URL',
email: 'Email address',
attendee_name: 'Attendee name',
static: 'Static value',
};
// 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 },
@@ -220,35 +200,6 @@ 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 || '[email protected]';
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' },
@@ -872,7 +823,7 @@ function BadgeElementView({
style={style}
onPointerDown={interactive ? (e) => onMove(e, el) : undefined}
>
<ElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
<BadgeElementBody el={el} sample={sample} pxPerMm={pxPerMm} />
{selected && interactive && (
<>
{HANDLES.map((h) => (
@@ -890,43 +841,6 @@ function BadgeElementView({
);
}
function ElementBody({ el, sample, pxPerMm }: { el: BadgeElement; sample: BadgeSample; pxPerMm: number }) {
if (el.type === 'text') {
const text = resolveText(el, sample);
return (
<div
className="badge-text-body"
style={{
fontFamily: `"${el.font}", sans-serif`,
fontSize: el.font_size * (pxPerMm / MM), // pt→mm→px so print scale matches
lineHeight: el.line_height,
color: el.color,
fontWeight: el.bold ? 700 : 400,
fontStyle: el.italic ? 'italic' : 'normal',
justifyContent: el.align_h === 'left' ? 'flex-start' : el.align_h === 'right' ? 'flex-end' : 'center',
alignItems: el.align_v === 'top' ? 'flex-start' : el.align_v === 'bottom' ? 'flex-end' : 'center',
textAlign: el.align_h,
}}
>
<span>{text || <span className="badge-el-placeholder">{CONTENT_LABEL[el.content]}</span>}</span>
</div>
);
}
if (el.type === 'qr') {
const size = Math.round(Math.min(el.width, el.height) * pxPerMm);
return (
<div className="badge-qr-body">
<QRCodeSVG value={resolveQr(el, sample)} size={Math.max(16, size)} level="M" marginSize={0} />
</div>
);
}
// image
if (!el.src) {
return <div className="badge-image-body badge-image-empty">Image</div>;
}
return <img className="badge-image-body" src={el.src} alt="" style={{ objectFit: el.fit }} />;
}
// ---- properties panel -------------------------------------------------------
function Num({ label, value, onChange, step = 0.1, min }: { label: string; value: number; onChange: (n: number) => void; step?: number; min?: number }) {
return (
+42 -12
View File
@@ -2,13 +2,24 @@ import { useEffect, useMemo, useState } from 'react';
import { adjustPoints, deleteContact, getAllContacts, updateContact, upsertContact } from '../lib/api';
import type { Contact } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { Avatar, Empty, Modal, Spinner, Toggle } from '../components/ui';
import { Avatar, ColumnFilter, Empty, Modal, Spinner, Toggle, type ColumnFilterOption } from '../components/ui';
// Multi-select column filters are Excel-style: an empty selection means "all".
const VIS_LABELS: Record<string, string> = { both: 'Both shown', email: 'Email only', linkedin: 'LinkedIn only', none: 'None shown' };
const visKey = (c: Contact) => (c.show_email && c.show_linkedin ? 'both' : c.show_email ? 'email' : c.show_linkedin ? 'linkedin' : 'none');
const ynOptions = (rows: Contact[], fn: (c: Contact) => boolean): ColumnFilterOption[] => [
{ value: 'yes', label: 'Yes', count: rows.filter(fn).length },
{ value: 'no', label: 'No', count: rows.filter((c) => !fn(c)).length },
];
export function Contacts() {
const { push } = useToast();
const [contacts, setContacts] = useState<Contact[] | null>(null);
const [error, setError] = useState<string | null>(null);
const [query, setQuery] = useState('');
const [fLinkedin, setFLinkedin] = useState<string[]>([]);
const [fVis, setFVis] = useState<string[]>([]);
const [fAdmin, setFAdmin] = useState<string[]>([]);
const [editing, setEditing] = useState<Contact | null>(null);
const [creating, setCreating] = useState(false);
@@ -41,18 +52,37 @@ export function Contacts() {
load();
}, []);
const filtered = useMemo(() => {
// General search: first name, last name or email address.
const searched = useMemo(() => {
if (!contacts) return [];
const q = query.trim().toLowerCase();
if (!q) return contacts;
return contacts.filter(
(c) =>
c.full_name.toLowerCase().includes(q) ||
c.email.toLowerCase().includes(q) ||
(c.linkedin_url ?? '').toLowerCase().includes(q),
);
return contacts.filter((c) => {
const name = c.full_name.toLowerCase();
return name.split(/\s+/).some((part) => part.includes(q)) || name.includes(q) || c.email.toLowerCase().includes(q);
});
}, [contacts, query]);
const passLinkedin = (c: Contact) => fLinkedin.length === 0 || fLinkedin.includes(c.linkedin_url ? 'yes' : 'no');
const passVis = (c: Contact) => fVis.length === 0 || fVis.includes(visKey(c));
const passAdmin = (c: Contact) => fAdmin.length === 0 || fAdmin.includes(c.is_admin ? 'yes' : 'no');
const filtered = useMemo(
() => searched.filter((c) => passLinkedin(c) && passVis(c) && passAdmin(c)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[searched, fLinkedin, fVis, fAdmin],
);
// Option counts follow Excel: each column counts what the OTHER filters leave.
const linkedinOptions = ynOptions(searched.filter((c) => passVis(c) && passAdmin(c)), (c) => !!c.linkedin_url);
const adminOptions = ynOptions(searched.filter((c) => passLinkedin(c) && passVis(c)), (c) => c.is_admin);
const visCounts = new Map<string, number>();
for (const c of searched.filter((c) => passLinkedin(c) && passAdmin(c))) {
const k = visKey(c);
visCounts.set(k, (visCounts.get(k) ?? 0) + 1);
}
const visOptions = ['both', 'email', 'linkedin', 'none']
.filter((k) => visCounts.has(k))
.map((k) => ({ value: k, label: VIS_LABELS[k], count: visCounts.get(k)! }));
if (error) return <Empty icon="⚠️" text={error} />;
if (!contacts)
return (
@@ -72,7 +102,7 @@ export function Contacts() {
<input
className="input"
style={{ maxWidth: 260 }}
placeholder="Search name, email…"
placeholder="Search first name, last name, email…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
@@ -87,9 +117,9 @@ export function Contacts() {
<thead>
<tr>
<th>Name</th>
<th>LinkedIn</th>
<th>Visibility</th>
<th>Admin</th>
<th>LinkedIn <ColumnFilter label="LinkedIn" options={linkedinOptions} selected={fLinkedin} onChange={setFLinkedin} /></th>
<th>Visibility <ColumnFilter label="Visibility" options={visOptions} selected={fVis} onChange={setFVis} /></th>
<th>Admin <ColumnFilter label="Admin" options={adminOptions} selected={fAdmin} onChange={setFAdmin} /></th>
<th style={{ textAlign: 'right' }}>Actions</th>
</tr>
</thead>
+154 -13
View File
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import {
createRegistration,
deleteContacts,
getBadgeLayouts,
getAllContacts,
getAllEvents,
getActiveEvent,
@@ -12,12 +13,18 @@ import {
setRegistrationType,
upsertSponsor,
} from '../lib/api';
import type { Contact, Event, Registration, RegistrationType, Sponsor, SponsorType } from '../lib/types';
import type { BadgeLayout, BadgeSample, Contact, Event, Registration, RegistrationType, Sponsor, SponsorType } from '../lib/types';
import { useToast } from '../context/ToastContext';
import { useAuth } from '../context/AuthContext';
import { Avatar, Empty, Modal, QrImage, Spinner, Toggle, TypeBadge } from '../components/ui';
import { Avatar, ColumnFilter, Empty, Modal, QrImage, Spinner, Toggle, Tooltip, TypeBadge, type ColumnFilterOption } from '../components/ui';
import { BadgePagePreview, fitScale } from '../components/BadgeRender';
const TYPES: RegistrationType[] = ['attendee', 'speaker', 'staff', 'sponsor'];
// Multi-select column filters are Excel-style: an empty selection means "all".
const ynOptions = (rows: Registration[], fn: (r: Registration) => boolean): ColumnFilterOption[] => [
{ value: 'yes', label: 'Yes', count: rows.filter(fn).length },
{ value: 'no', label: 'No', count: rows.filter((r) => !fn(r)).length },
];
export function Registrations() {
const { push } = useToast();
@@ -35,12 +42,20 @@ export function Registrations() {
const [busy, setBusy] = useState(false);
const [deletingAll, setDeletingAll] = useState(false);
const [mergeFor, setMergeFor] = useState<Registration | null>(null);
const [badgeFor, setBadgeFor] = useState<Registration | null>(null);
const [badgeLayouts, setBadgeLayouts] = useState<BadgeLayout[]>([]);
const [fType, setFType] = useState<string[]>([]);
const [fTicket, setFTicket] = useState<string[]>([]);
const [fCheckedIn, setFCheckedIn] = useState<string[]>([]);
const selectedEventId = useRef(selectedId);
selectedEventId.current = selectedId;
const event = events.find((e) => e.id === selectedId) ?? null;
const eventRegistrations = registrations.filter((registration) => registration.event_id === selectedId);
const ticketed = eventRegistrations.filter((registration) => registration.qr_token?.trim());
// A badge is "configured" once a layout for this event actually has elements;
// an empty layout would render a blank white badge, so treat it as unconfigured.
const badgeConfigured = badgeLayouts.some((l) => Array.isArray(l.elements) && l.elements.length > 0);
async function reloadRegistrations(eventId: string) {
const rows = await getRegistrations(eventId);
@@ -79,6 +94,11 @@ export function Registrations() {
if (!cancelled) setError(e instanceof Error ? e.message : 'Failed to load');
}
})();
// Badge layouts are best-effort: a failure just leaves the Badge buttons
// disabled (treated as "not configured") rather than breaking the list.
getBadgeLayouts(selectedId)
.then((ls) => { if (!cancelled) setBadgeLayouts(ls); })
.catch(() => { if (!cancelled) setBadgeLayouts([]); });
return () => {
cancelled = true;
};
@@ -114,21 +134,40 @@ export function Registrations() {
const byEmail = useMemo(() => new Map(contacts.map((c) => [c.email, c])), [contacts]);
const filtered = useMemo(() => {
if (!registrations) return [];
// General search: first name, last name, email address or type.
const searched = useMemo(() => {
const q = query.trim().toLowerCase();
if (!q) return registrations.filter((r) => r.event_id === selectedId);
return registrations.filter((r) => {
if (r.event_id !== selectedId) return false;
const c = byEmail.get(r.contact_email);
const rows = registrations.filter((r) => r.event_id === selectedId);
if (!q) return rows;
return rows.filter((r) => {
const name = (byEmail.get(r.contact_email)?.full_name ?? '').toLowerCase();
return (
(c?.full_name ?? '').toLowerCase().includes(q) ||
name.split(/\s+/).some((part) => part.includes(q)) ||
name.includes(q) ||
r.contact_email.toLowerCase().includes(q) ||
r.type.toLowerCase().includes(q)
);
});
}, [registrations, query, byEmail, selectedId]);
const hasTicket = (r: Registration) => !!r.qr_token?.trim();
const passType = (r: Registration) => fType.length === 0 || fType.includes(r.type);
const passTicket = (r: Registration) => fTicket.length === 0 || fTicket.includes(hasTicket(r) ? 'yes' : 'no');
const passCheckedIn = (r: Registration) => fCheckedIn.length === 0 || fCheckedIn.includes(r.checked_in ? 'yes' : 'no');
const filtered = useMemo(
() => searched.filter((r) => passType(r) && passTicket(r) && passCheckedIn(r)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[searched, fType, fTicket, fCheckedIn],
);
// Option counts follow Excel: each column counts what the OTHER filters leave.
const typeCounts = new Map<string, number>();
for (const r of searched.filter((r) => passTicket(r) && passCheckedIn(r))) typeCounts.set(r.type, (typeCounts.get(r.type) ?? 0) + 1);
const typeOptions = [...typeCounts.entries()]
.sort((a, b) => TYPES.indexOf(a[0] as RegistrationType) - TYPES.indexOf(b[0] as RegistrationType))
.map(([value, count]) => ({ value, label: value, count }));
const ticketOptions = ynOptions(searched.filter((r) => passType(r) && passCheckedIn(r)), hasTicket);
const checkedInOptions = ynOptions(searched.filter((r) => passType(r) && passTicket(r)), (r) => r.checked_in);
async function changeType(r: Registration, type: RegistrationType) {
setBusy(true);
try {
@@ -215,7 +254,7 @@ export function Registrations() {
<input
className="input"
style={{ maxWidth: 220 }}
placeholder="Search name, email, type…"
placeholder="Search first name, last name, email, type…"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
@@ -233,9 +272,9 @@ export function Registrations() {
<thead>
<tr>
<th>Contact</th>
<th>Type</th>
<th>QR token</th>
<th>Checked in</th>
<th>Type <ColumnFilter label="Type" options={typeOptions} selected={fType} onChange={setFType} /></th>
<th>QR token <ColumnFilter label="Ticket" options={ticketOptions} selected={fTicket} onChange={setFTicket} /></th>
<th>Checked in <ColumnFilter label="Checked in" options={checkedInOptions} selected={fCheckedIn} onChange={setFCheckedIn} /></th>
<th style={{ textAlign: 'right' }}>Points</th>
</tr>
</thead>
@@ -277,6 +316,17 @@ export function Registrations() {
{r.qr_token?.trim() && <button className="btn small" onClick={() => setQrFor(r)}>
QR
</button>}
{badgeConfigured ? (
<button className="btn small" onClick={() => setBadgeFor(r)} title="Preview this attendee's badge">
Badge
</button>
) : (
<Tooltip title="No badge yet" content="A badge needs to be configured for this event first. Design one in the Badges view.">
<button className="btn small" disabled>
Badge
</button>
</Tooltip>
)}
{!r.qr_token?.trim() && r.import_source === 'sessionize' && (
<button className="btn small" disabled={busy} onClick={() => setMergeFor(r)}>
Merge tickets
@@ -348,6 +398,16 @@ export function Registrations() {
</Modal>
)}
{badgeFor && (
<BadgePreviewModal
registration={badgeFor}
contact={byEmail.get(badgeFor.contact_email)}
event={event}
layouts={badgeLayouts}
onClose={() => setBadgeFor(null)}
/>
)}
{sponsorFor && (
<SponsorLookupModal
registration={sponsorFor}
@@ -365,6 +425,87 @@ export function Registrations() {
);
}
/** Renders the event's badge layout for one attendee, chosen from its layouts. */
function BadgePreviewModal({ registration, contact, event, layouts, onClose }: {
registration: Registration;
contact?: Contact;
event: Event;
layouts: BadgeLayout[];
onClose: () => void;
}) {
const hasContent = (l: BadgeLayout) => Array.isArray(l.elements) && l.elements.length > 0;
const [layoutName, setLayoutName] = useState(() => {
const def = (layouts.find((l) => l.is_default && hasContent(l)) ?? layouts.find(hasContent) ?? layouts[0]);
return def?.name ?? '';
});
const sample: BadgeSample = {
full_name: contact?.full_name ?? registration.contact_email,
email: registration.contact_email,
ticket_type: registration.type,
qr_token: registration.qr_token ?? '',
event_name: event.name,
company: event.company ?? '',
};
const layout = layouts.find((l) => l.name === layoutName) ?? null;
const name = contact?.full_name ?? registration.contact_email;
// Fit the badge to the stage's real width (responsive) and the viewport height.
const stageRef = useRef<HTMLDivElement>(null);
const [stageW, setStageW] = useState(0);
useEffect(() => {
const el = stageRef.current;
if (!el) return;
const measure = () => setStageW(el.clientWidth);
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
return () => ro.disconnect();
}, [layout]);
const maxH = Math.max(180, Math.min(420, Math.round(window.innerHeight * 0.45)));
const pxPerMm = layout && stageW > 0 ? fitScale(layout, stageW, maxH) : 0;
return (
<Modal
open
title={`Badge — ${name}`}
onClose={onClose}
footer={
<button className="btn primary" onClick={onClose}>
Done
</button>
}
>
{layouts.length === 0 && (
<Empty icon="🎫" text="No badge layout for this event yet. Design one in the Badges view." />
)}
{layouts.length > 0 && !layout && (
<Empty icon="🎫" text="This event's badge layout is empty. Add elements to it in the Badges view." />
)}
{layout && (
<>
{layouts.length > 1 && (
<label className="badge-field">
<span>Layout</span>
<select className="input" value={layoutName} onChange={(e) => setLayoutName(e.target.value)}>
{layouts.map((l) => (
<option key={l.id} value={l.name}>{l.name}{l.is_default ? ' ★' : ''}</option>
))}
</select>
</label>
)}
<div className="badge-preview-stage" ref={stageRef}>
{pxPerMm > 0 && <BadgePagePreview layout={layout} sample={sample} pxPerMm={pxPerMm} />}
</div>
<p className="muted small" style={{ textAlign: 'center' }}>
{layout.name} · {layout.page_width_mm} × {layout.page_height_mm} mm
</p>
</>
)}
</Modal>
);
}
function MergeTicketsModal({ source, contacts, tickets, onClose, onMerged }: {
source: Registration;
contacts: Map<string, Contact>;