Ticket card

A printed-style ticket for events, travel or memberships. A main panel and a stub are joined by a dashed perforation with round notches cut from both edges, so the page shows through. Three layouts: event (date block, title, venue, seat or tier), boarding pass (route codes joined by a dashed flight arc, gate, seat, boarding time) and membership pass (tier, holder, expiry). The stub can be torn off by dragging it or with a Tear button: it drops away, leaves a torn edge and an Admitted stamp, and calls onTear. Passes can flip in 3D to a back face with a decorative code drawn from a seed and fine print. Fields use description lists, the flip is a pressed-state button, and reduced motion swaps the flip and tear for fades. The layout stacks on narrow screens.

CardsComponentTailwind v4

Source

import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent, type ReactNode } from "react";
import { Plane, RotateCw, Scissors } from "lucide-react";
import { cn } from "@/lib/utils";

export type EventFields = {
  month: string;
  day: string;
  weekday?: string;
  title: string;
  subtitle?: string;
  venue: string;
  time: string;
  section?: string;
  row?: string;
  seat?: string;
  /** Shown instead of section/row/seat for general admission. */
  tier?: string;
  reference: string;
};

export type BoardingFields = {
  passenger: string;
  carrier: string;
  flight: string;
  from: { code: string; city: string };
  to: { code: string; city: string };
  date: string;
  boarding: string;
  gate: string;
  seat: string;
  zone?: string;
  reference: string;
};

export type PassFields = {
  org: string;
  tier: string;
  holder: string;
  memberId: string;
  expires: string;
  since?: string;
  reference: string;
};

type LayoutProps =
  | { layout: "event"; fields: EventFields }
  | { layout: "boarding"; fields: BoardingFields }
  | { layout: "pass"; fields: PassFields };

export type TicketCardProps = LayoutProps & {
  /** Any colour, e.g. "var(--chart-2)" or "var(--primary)". */
  accent?: string;
  tearable?: boolean;
  flippable?: boolean;
  onTear?: () => void;
  /** Seeds the decorative code on the back; defaults to the reference. */
  seed?: string;
  finePrint?: string;
  defaultFlipped?: boolean;
  /** Render as already used: stub gone, torn edge and stamp shown. */
  defaultTorn?: boolean;
  className?: string;
};

const CSS = `
.tkt{container-type:inline-size;--r:11px;--edge:color-mix(in oklab,var(--foreground) 22%,transparent)}
.tkt-row{display:flex;flex-direction:column}
.tkt-face{filter:drop-shadow(0 0 0.75px var(--edge)) drop-shadow(0 8px 10px rgb(0 0 0/.07))}
.tkt-main{border-radius:18px 18px 6px 6px;-webkit-mask:radial-gradient(circle at 0 100%,#0000 var(--r),#000 calc(var(--r) + .5px)) left/51% 100% no-repeat,radial-gradient(circle at 100% 100%,#0000 var(--r),#000 calc(var(--r) + .5px)) right/51% 100% no-repeat}
.tkt-main[data-torn]{-webkit-mask:linear-gradient(#000 0 0) top/100% calc(100% - 7px) no-repeat,conic-gradient(from 323deg at 50% 100%,#000 74deg,#0000 0) bottom/10px 7px repeat-x}
.tkt-stub{position:relative;border-radius:6px 6px 18px 18px;transform-origin:0 0;-webkit-mask:radial-gradient(circle at 0 0,#0000 var(--r),#000 calc(var(--r) + .5px)) left/51% 100% no-repeat,radial-gradient(circle at 100% 0,#0000 var(--r),#000 calc(var(--r) + .5px)) right/51% 100% no-repeat}
.tkt-stub::before{content:"";position:absolute;top:0;left:calc(var(--r) + 6px);right:calc(var(--r) + 6px);border-top:2px dashed var(--edge)}
.tkt-stub[data-state=tearing]{animation:tkt-fall-y .75s cubic-bezier(.5,0,.75,0) forwards;pointer-events:none}
.tkt-stub[data-state=torn]{background:none!important;-webkit-mask:none;mask:none;align-items:center;justify-content:center}
.tkt-stub[data-state=torn]::before{display:none}
@container (min-width:520px){
  .tkt-row{flex-direction:row}
  .tkt-main{border-radius:18px 6px 6px 18px;-webkit-mask:radial-gradient(circle at 100% 0,#0000 var(--r),#000 calc(var(--r) + .5px)) top/100% 51% no-repeat,radial-gradient(circle at 100% 100%,#0000 var(--r),#000 calc(var(--r) + .5px)) bottom/100% 51% no-repeat}
  .tkt-main[data-torn]{-webkit-mask:linear-gradient(#000 0 0) left/calc(100% - 7px) 100% no-repeat,conic-gradient(from 233deg at 100% 50%,#000 74deg,#0000 0) right/7px 10px repeat-y}
  .tkt-stub{width:156px;flex:none;border-radius:6px 18px 18px 6px;-webkit-mask:radial-gradient(circle at 0 0,#0000 var(--r),#000 calc(var(--r) + .5px)) top/100% 51% no-repeat,radial-gradient(circle at 0 100%,#0000 var(--r),#000 calc(var(--r) + .5px)) bottom/100% 51% no-repeat}
  .tkt-stub::before{top:calc(var(--r) + 6px);bottom:calc(var(--r) + 6px);left:0;right:auto;border-top:0;border-left:2px dashed var(--edge)}
  .tkt-stub[data-state=tearing]{animation-name:tkt-fall-x}
}
.tkt-flip{perspective:1400px}
.tkt-card{position:relative;transform-style:preserve-3d;transition:transform .8s cubic-bezier(.3,.7,.2,1)}
.tkt-card[data-flipped]{transform:rotateY(180deg)}
.tkt-front,.tkt-back{backface-visibility:hidden;-webkit-backface-visibility:hidden;transition:opacity .35s}
.tkt-back{position:absolute;inset:0;transform:rotateY(180deg)}
.tkt-stamp{animation:tkt-stamp .45s cubic-bezier(.2,1.4,.4,1) both}
@keyframes tkt-fall-x{to{transform:translate(36px,150%) rotate(26deg);opacity:0}}
@keyframes tkt-fall-y{to{transform:translate(12px,130%) rotate(7deg);opacity:0}}
@keyframes tkt-fade{to{opacity:0}}
@keyframes tkt-stamp{from{transform:scale(1.7) rotate(-14deg);opacity:0}to{transform:scale(1) rotate(-8deg);opacity:1}}
@media (prefers-reduced-motion:reduce){
  .tkt-stub[data-state=tearing]{animation:tkt-fade .3s linear forwards!important}
  .tkt-card,.tkt-card[data-flipped]{transform:none;transition:none}
  .tkt-back{transform:none}
  .tkt-card[data-flipped] .tkt-front,.tkt-card:not([data-flipped]) .tkt-back{opacity:0}
  .tkt-stamp{animation:none;transform:rotate(-8deg)}
}`;

/* Small deterministic generator so the same seed always draws the same code. */
function generator(seed: string) {
  let h = 1779033703 ^ seed.length;
  for (let i = 0; i < seed.length; i++) {
    h = Math.imul(h ^ seed.charCodeAt(i), 3432918353);
    h = (h << 13) | (h >>> 19);
  }
  let a = h >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function CodeGrid({ seed, size = 25 }: { seed: string; size?: number }) {
  const path = useMemo(() => {
    const next = generator(seed);
    const finder = (x: number, y: number) => {
      for (const [fx, fy] of [[0, 0], [size - 7, 0], [0, size - 7]]) {
        const dx = x - fx;
        const dy = y - fy;
        if (dx >= -1 && dx <= 7 && dy >= -1 && dy <= 7) {
          if (dx < 0 || dy < 0 || dx > 6 || dy > 6) return false;
          const ring = Math.min(dx, dy, 6 - dx, 6 - dy);
          return ring !== 1;
        }
      }
      return null;
    };
    let d = "";
    for (let y = 0; y < size; y++)
      for (let x = 0; x < size; x++) {
        const fixed = finder(x, y);
        if (fixed ?? next() < 0.48) d += `M${x} ${y}h1v1h-1z`;
      }
    return d;
  }, [seed, size]);
  return (
    <svg viewBox={`-1 -1 ${size + 2} ${size + 2}`} aria-hidden="true" className="size-full" shapeRendering="crispEdges">
      <rect x="-1" y="-1" width={size + 2} height={size + 2} rx="1.5" fill="var(--card)" />
      <path d={path} fill="currentColor" />
    </svg>
  );
}

function Field({ label, children, large }: { label: string; children: ReactNode; large?: boolean }) {
  return (
    <div className="min-w-0">
      <dt className="text-[10px] font-medium uppercase tracking-[0.14em] text-muted-foreground">{label}</dt>
      <dd className={cn("mt-0.5 truncate font-medium tabular-nums text-foreground", large ? "text-2xl font-semibold tracking-tight" : "text-sm")}>{children}</dd>
    </div>
  );
}

function EventMain({ fields: f, accent }: { fields: EventFields; accent: string }) {
  return (
    <div className="flex gap-5">
      <div
        className="flex w-16 shrink-0 flex-col self-start items-center justify-center rounded-xl py-3 text-center"
        style={{ background: `color-mix(in oklab, ${accent} 14%, var(--card))`, color: `color-mix(in oklab, ${accent} 72%, var(--foreground))` }}
      >
        <span className="text-[11px] font-semibold uppercase tracking-[0.16em]">{f.month}</span>
        <span className="text-3xl font-semibold leading-none tracking-tight tabular-nums">{f.day}</span>
        {f.weekday && <span className="mt-1 text-[11px] font-medium opacity-80">{f.weekday}</span>}
      </div>
      <div className="min-w-0 flex-1">
        {f.subtitle && <p className="text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">{f.subtitle}</p>}
        <h3 className="mt-1 text-xl font-semibold leading-tight tracking-tight text-foreground @min-[520px]:text-2xl">{f.title}</h3>
        <dl className="mt-4 grid grid-cols-2 gap-x-4 gap-y-3 @min-[520px]:grid-cols-3">
          <Field label="Venue">{f.venue}</Field>
          <Field label="Doors">{f.time}</Field>
          {f.tier ? <Field label="Tier">{f.tier}</Field> : f.section && <Field label="Section">{f.section}</Field>}
        </dl>
      </div>
    </div>
  );
}

function BoardingMain({ fields: f, accent }: { fields: BoardingFields; accent: string }) {
  return (
    <div>
      <div className="flex items-center justify-between text-xs">
        <span className="font-semibold tracking-tight text-foreground">{f.carrier}</span>
        <span className="font-mono text-muted-foreground">{f.flight}</span>
      </div>
      <div className="mt-4 grid grid-cols-[auto_1fr_auto] items-end gap-3">
        <div>
          <p className="text-4xl font-semibold leading-none tracking-tight text-foreground @min-[520px]:text-5xl">{f.from.code}</p>
          <p className="mt-1 text-xs text-muted-foreground">{f.from.city}</p>
        </div>
        <div className="relative mb-6 h-10" style={{ color: accent }} aria-hidden="true">
          <svg viewBox="0 0 100 40" preserveAspectRatio="none" className="absolute inset-0 size-full overflow-visible">
            <path d="M2 38 Q50 -6 98 38" fill="none" stroke="currentColor" strokeWidth="1.5" strokeDasharray="3 4" vectorEffect="non-scaling-stroke" />
          </svg>
          <Plane className="absolute left-1/2 top-0 size-4 -translate-x-1/2 -translate-y-1/2 rotate-45" />
        </div>
        <div className="text-right">
          <p className="text-4xl font-semibold leading-none tracking-tight text-foreground @min-[520px]:text-5xl">{f.to.code}</p>
          <p className="mt-1 text-xs text-muted-foreground">{f.to.city}</p>
        </div>
      </div>
      <dl className="mt-5 grid grid-cols-2 gap-x-4 gap-y-3 @min-[520px]:grid-cols-4">
        <Field label="Passenger">{f.passenger}</Field>
        <Field label="Date">{f.date}</Field>
        <Field label="Boards">{f.boarding}</Field>
        {f.zone && <Field label="Zone">{f.zone}</Field>}
      </dl>
    </div>
  );
}

function PassMain({ fields: f, accent }: { fields: PassFields; accent: string }) {
  return (
    <div>
      <div className="flex items-center justify-between gap-3">
        <span className="text-sm font-semibold tracking-tight text-foreground">{f.org}</span>
        <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold uppercase tracking-[0.12em]" style={{ background: `color-mix(in oklab, ${accent} 16%, transparent)`, color: `color-mix(in oklab, ${accent} 72%, var(--foreground))` }}>
          {f.tier}
        </span>
      </div>
      <p className="mt-6 text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground">Member</p>
      <p className="text-2xl font-semibold tracking-tight text-foreground">{f.holder}</p>
      <dl className="mt-4 grid grid-cols-2 gap-x-4 gap-y-3 @min-[520px]:grid-cols-3">
        <Field label="Member ID">{f.memberId}</Field>
        {f.since && <Field label="Since">{f.since}</Field>}
        <Field label="Expires">{f.expires}</Field>
      </dl>
    </div>
  );
}

function StubBody(props: LayoutProps) {
  if (props.layout === "event") {
    const f = props.fields;
    return f.tier ? (
      <dl className="space-y-2"><Field label="Admit one" large>{f.tier}</Field></dl>
    ) : (
      <dl className="grid grid-cols-3 gap-3 @min-[520px]:grid-cols-2">
        <Field label="Row" large>{f.row}</Field>
        <Field label="Seat" large>{f.seat}</Field>
        <Field label="Sec">{f.section}</Field>
      </dl>
    );
  }
  if (props.layout === "boarding") {
    const f = props.fields;
    return (
      <dl className="grid grid-cols-3 gap-3 @min-[520px]:grid-cols-2">
        <Field label="Gate" large>{f.gate}</Field>
        <Field label="Seat" large>{f.seat}</Field>
        <Field label="Boards">{f.boarding}</Field>
      </dl>
    );
  }
  const f = props.fields;
  return (
    <dl className="grid grid-cols-2 gap-3 @min-[520px]:grid-cols-1">
      <Field label="Tier" large>{f.tier}</Field>
      <Field label="Valid to">{f.expires}</Field>
    </dl>
  );
}

const button =
  "inline-flex h-8 items-center gap-1.5 rounded-md border border-border bg-background/70 px-2.5 text-xs font-medium text-foreground outline-none hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background";

export function TicketCard(props: TicketCardProps) {
  const { accent = "var(--primary)", tearable = false, flippable = false, onTear, seed, finePrint, defaultFlipped = false, defaultTorn = false, className } = props;
  const [state, setState] = useState<"attached" | "tearing" | "torn">(defaultTorn ? "torn" : "attached");
  const [flipped, setFlipped] = useState(flippable && defaultFlipped);
  const [announce, setAnnounce] = useState("");
  const stubRef = useRef<HTMLDivElement>(null);
  const drag = useRef<{ x: number; y: number; id: number } | null>(null);
  const reference = props.fields.reference;

  useEffect(() => {
    if (state !== "tearing") return;
    // Fallback in case animationend never fires (hidden tab, no animations).
    const timer = window.setTimeout(() => setState("torn"), 900);
    return () => window.clearTimeout(timer);
  }, [state]);

  const tear = () => {
    if (state !== "attached") return;
    if (stubRef.current) stubRef.current.style.transition = "";
    setState("tearing");
    setAnnounce("Stub torn off. Admitted.");
    onTear?.();
  };

  const wide = () => (stubRef.current?.parentElement?.clientWidth ?? 0) > 0 && getComputedStyle(stubRef.current!.parentElement!).flexDirection === "row";

  const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {
    if (!tearable || state !== "attached" || (event.target as HTMLElement).closest("button")) return;
    drag.current = { x: event.clientX, y: event.clientY, id: event.pointerId };
    event.currentTarget.setPointerCapture(event.pointerId);
    event.currentTarget.style.transition = "none";
  };
  const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {
    if (!drag.current || drag.current.id !== event.pointerId) return;
    const pull = Math.max(0, event.clientY - drag.current.y) + Math.max(0, event.clientX - drag.current.x) * 0.4;
    event.currentTarget.style.transform = wide()
      ? `rotate(${Math.min(22, pull / 4)}deg)`
      : `translateY(${Math.min(36, pull * 0.45)}px) rotate(${Math.min(5, pull / 14)}deg)`;
  };
  const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {
    if (!drag.current || drag.current.id !== event.pointerId) return;
    const pull = Math.max(0, event.clientY - drag.current.y) + Math.max(0, event.clientX - drag.current.x) * 0.4;
    drag.current = null;
    if (pull > 64) return tear();
    event.currentTarget.style.transition = "transform .45s cubic-bezier(.2,1.3,.4,1)";
    event.currentTarget.style.transform = "";
  };

  const main =
    props.layout === "event" ? <EventMain fields={props.fields} accent={accent} />
    : props.layout === "boarding" ? <BoardingMain fields={props.fields} accent={accent} />
    : <PassMain fields={props.fields} accent={accent} />;

  const stubTint = { background: `color-mix(in oklab, ${accent} 9%, var(--card))` } as CSSProperties;
  const showActions = flippable || (tearable && state === "attached");
  const fine = finePrint ?? "Non-transferable. Present this code at entry. Valid only for the holder named on the front and only on the date shown.";

  return (
    <div className={cn("tkt w-full", className)}>
      <style href="chm-ticket-card" precedence="default">{CSS}</style>
      <div className="tkt-flip">
        <div className="tkt-card" data-flipped={flipped || undefined}>
          <div className="tkt-front tkt-face" aria-hidden={flipped || undefined} inert={flipped}>
            <div className="tkt-row">
              <div className="tkt-main relative min-w-0 flex-1 bg-card p-5 @min-[520px]:p-6" data-torn={state !== "attached" || undefined}>
                {main}
              </div>
              <div
                ref={stubRef}
                className={cn("tkt-stub flex flex-col justify-between gap-4 p-5", tearable && state === "attached" && "cursor-grab touch-none active:cursor-grabbing")}
                style={stubTint}
                data-state={state}
                onPointerDown={onPointerDown}
                onPointerMove={onPointerMove}
                onPointerUp={onPointerUp}
                onPointerCancel={onPointerUp}
                onAnimationEnd={() => state === "tearing" && setState("torn")}
              >
                {state === "torn" ? (
                  <span className="tkt-stamp rounded-md border-2 px-2.5 py-1 text-xs font-bold uppercase tracking-[0.2em]" style={{ borderColor: accent, color: accent }}>
                    Admitted
                  </span>
                ) : (
                  <>
                    <StubBody {...(props as LayoutProps)} />
                    <div className="flex flex-wrap items-center justify-between gap-2">
                      <span className="whitespace-nowrap font-mono text-[11px] text-muted-foreground">{reference}</span>
                      {tearable && state === "attached" && (
                        <button type="button" onClick={tear} className={cn(button, "h-7 px-2")} aria-label="Tear off stub">
                          <Scissors aria-hidden="true" className="size-3.5" /> Tear
                        </button>
                      )}
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>

          {flippable && (
            <div className="tkt-back tkt-face" aria-hidden={!flipped || undefined} inert={!flipped}>
              <div className="flex size-full items-center gap-5 rounded-[18px] bg-card p-5 @min-[520px]:p-6">
                <div className="aspect-square h-full max-h-36 shrink-0 text-foreground">
                  <CodeGrid seed={seed || reference} />
                </div>
                <div className="min-w-0">
                  <p className="text-[10px] font-medium uppercase tracking-[0.14em] text-muted-foreground">Reference</p>
                  <p className="font-mono text-sm font-medium text-foreground">{reference}</p>
                  <span className="sr-only">Code for reference {reference}</span>
                  <p className="mt-3 line-clamp-4 text-[11px] leading-relaxed text-muted-foreground">{fine}</p>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {showActions && (
        <div className="mt-3 flex flex-wrap items-center gap-2">
          {flippable && (
            <button type="button" className={button} aria-pressed={flipped} onClick={() => setFlipped((value) => !value)}>
              <RotateCw aria-hidden="true" className="size-3.5" /> {flipped ? "Show front" : "Show back"}
            </button>
          )}
          {tearable && state === "attached" && <span className="text-xs text-muted-foreground">Drag the stub down to tear it off</span>}
        </div>
      )}
      <span className="sr-only" aria-live="polite">{announce}</span>
    </div>
  );
}