Preview
"use client";
import { useState } from "react";
import {
FlightSeatMap,
type SeatMapLayout,
type SeatPassenger,
type SeatSelection,
} from "@/components/motion/flight-seat-map";
const layout: SeatMapLayout = {
columns: ["A", "B", "C", "", "D", "E", "F"],
sections: [
{ from: 1, to: 2, type: "premium", price: 89 },
{ from: 3, to: 4, type: "extra-legroom", price: 39 },
{ from: 5, to: 12, type: "standard" },
],
exitRows: [4],
};
const passengers: SeatPassenger[] = [
{ id: "p1", name: "Maya Chen" },
{ id: "p2", name: "Leo Park" },
];
const taken = ["1A", "2E", "3C", "4F", "5A", "5B", "6E", "7C", "7D", "8F", "9B", "10A", "10E", "11C", "12D", "12F"];
export function FlightSeatMapPreview() {
const [seats, setSeats] = useState<SeatSelection>({ p1: "3B", p2: null });
return (
<div className="w-full max-w-4xl">
<FlightSeatMap
layout={layout}
passengers={passengers}
taken={taken}
value={seats}
onChange={setSeats}
sound
/>
</div>
);
}
components/motion/flight-seat-map.tsx
1,050 lines"use client";
// beui.dev/components/blocks/flight-seat-map
import { X } from "lucide-react";
import {
AnimatePresence,
motion,
useInView,
useReducedMotion,
useSpring,
} from "motion/react";
import {
type CSSProperties,
type KeyboardEvent,
type ReactNode,
useCallback,
useEffect,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { Tooltip } from "@/components/motion/tooltip";
import { EASE_OUT, SPRING_PANEL, SPRING_SWAP } from "@/lib/ease";
import { useControllable } from "@/lib/hooks/use-controllable";
import { useLocale, useMessages } from "@/lib/i18n";
import { useSound } from "@/lib/sound";
import { buzzSound } from "@/lib/sounds/buzz";
import { dismissSound } from "@/lib/sounds/dismiss";
import { popSound } from "@/lib/sounds/pop";
import { selectSound } from "@/lib/sounds/select";
import { cn } from "@/lib/utils";
export const flightSeatMapMessages = {
map: "Seat map",
row: "Row",
aisleColumn: "Aisle",
seat: "Seat {seat}",
window: "Window",
middle: "Middle",
aisle: "Aisle",
standard: "Standard",
"extra-legroom": "Extra legroom",
premium: "Premium",
available: "Available",
taken: "Taken",
legend: "Seat types",
selectedFor: "selected for {name}",
included: "Included",
passengers: "Passengers",
noSeat: "No seat yet",
total: "Total",
selected: "Selected",
clear: "Remove seat for {name}",
announce: "Seat {seat} selected for {name}",
announceCleared: "Seat removed for {name}",
hint: "Pick a seat for {name}",
};
export type FlightSeatMapMessages = typeof flightSeatMapMessages;
/** How a seat is sold: a plain seat, one with more room in front, or a premium cabin seat. */
export type SeatType = "standard" | "extra-legroom" | "premium";
/** A run of rows that share a seat type and price. */
export interface SeatSection {
/** First row number in the section. */
from: number;
/** Last row number in the section, inclusive. */
to: number;
/** Seat type for every seat in these rows. Default: "standard" */
type?: SeatType;
/** Price of each seat in these rows, in the `currency` unit. Leave out or pass 0 for seats included in the fare. */
price?: number;
}
/** The cabin's shape: which seat letters sit where, and which rows exist. */
export interface SeatMapLayout {
/** Seat letters from left to right; an empty string marks an aisle, e.g. ["A", "B", "C", "", "D", "E", "F"]. */
columns: string[];
/** Row ranges from front to back. Rows not covered by a section are not drawn. */
sections: SeatSection[];
/** Rows with an emergency exit beside them, marked in green at both edges of the cabin floor. */
exitRows?: number[];
/** Row numbers the airline skips, such as 13. */
skipRows?: number[];
}
/** Someone travelling on the booking who needs a seat. */
export interface SeatPassenger {
/** Stable id, used as the key in the selection map. */
id: string;
/** Name shown in the switcher, the summary and seat labels. */
name: string;
}
/** Passenger id to seat id (such as "12A"), or null for a passenger without a seat. */
export type SeatSelection = Record<string, string | null>;
export interface FlightSeatMapProps {
/** The cabin layout: seat columns, aisles, sections, exit rows and skipped rows. */
layout: SeatMapLayout;
/** Everyone who needs a seat. One passenger makes it a single-seat picker. */
passengers: SeatPassenger[];
/** Seat ids that are already taken, such as ["3C", "12A"]. */
taken?: string[];
/** Selected seats, for controlled use. */
value?: SeatSelection;
/** Selected seats at first, when uncontrolled. Default: {} */
defaultValue?: SeatSelection;
/** Called with the whole selection whenever a passenger's seat changes. */
onChange?: (value: SeatSelection) => void;
/** ISO 4217 currency code for seat prices. Default: "USD" */
currency?: string;
/** How far the cabin floor tips away from the viewer, in degrees. 0 draws it flat from above. Default: 42 */
tilt?: number;
/** Play a pop when a head lands in a seat, a flick when a seat is given up, a click when switching passengers and a buzz on a taken seat. Off by default; a `SoundProvider` can mute it app-wide. Default: false */
sound?: boolean;
/** Override any built-in string. */
labels?: Partial<FlightSeatMapMessages>;
className?: string;
}
type Seat = {
id: string;
row: number;
letter: string;
rowIndex: number;
col: number;
type: SeatType;
price: number;
position: "window" | "middle" | "aisle";
};
type Row = {
row: number;
type: SeatType;
exit: boolean;
sectionStart: boolean;
seats: (Seat | null)[];
};
function buildCabin(layout: SeatMapLayout) {
const { columns } = layout;
const skip = new Set(layout.skipRows);
const exits = new Set(layout.exitRows);
const seatCols = columns.flatMap((c, i) => (c ? [i] : []));
const first = seatCols[0];
const last = seatCols[seatCols.length - 1];
const rows: Row[] = [];
const seats = new Map<string, Seat>();
for (const section of layout.sections) {
const type = section.type ?? "standard";
for (let n = section.from; n <= section.to; n++) {
if (skip.has(n)) continue;
const rowIndex = rows.length;
const cells = columns.map((letter, i) => {
if (!letter) return null;
const position =
i === first || i === last
? "window"
: columns[i - 1] === "" || columns[i + 1] === ""
? "aisle"
: "middle";
const seat: Seat = {
id: `${n}${letter}`,
row: n,
letter,
rowIndex,
col: seatCols.indexOf(i),
type,
price: section.price ?? 0,
position,
};
seats.set(seat.id, seat);
return seat;
});
rows.push({
row: n,
type,
exit: exits.has(n),
sectionStart: n === section.from && rowIndex > 0,
seats: cells,
});
}
}
const grid = rows.map((r) => r.seats.filter((s): s is Seat => s !== null));
return { rows, seats, grid };
}
/* -------------------------------------------------------------------------- */
/* Geometry (px). The cabin is laid out flat, then tipped back in 3D. */
/* -------------------------------------------------------------------------- */
/** Seat footprint on the floor: width across the cabin, depth along it. */
const SEAT_W = 58;
const SEAT_D = 52;
/** Seatback height, and how far a head peeks over it. */
const BACK_H = 46;
const PEEK = 19;
const HEAD = 25;
const AISLE_W = 42;
/** Floor margin between the seats and the cabin's edge. */
const PAD = 30;
/** How far the rounding at each end of the cabin reaches along it. */
const END = 110;
/** Camera distance for the stage's perspective. */
const PERSPECTIVE = 2400;
/** Space between rows: more in front of extra legroom rows, which is the point of them. */
const PITCH: Record<SeatType, number> = { standard: 10, "extra-legroom": 26, premium: 16 };
/** The cabin settling into its tilt on entry: a heavy, unhurried, critically
* damped glide, slower than any UI spring because it moves the whole scene. */
const CABIN_SETTLE = { stiffness: 90, damping: 19, mass: 1 };
/** Hair colours for travellers already seated, picked per seat so the cabin looks lived in. */
const HAIR = ["#2f2a26", "#5b4030", "#a7804f", "#8f8f8f", "#1f1f1f", "#6e3b2a"];
function hash(value: string) {
let h = 0;
for (let i = 0; i < value.length; i++) h = (h * 31 + value.charCodeAt(i)) | 0;
return Math.abs(h);
}
function initials(name: string) {
const parts = name.trim().split(/\s+/);
return ((parts[0]?.[0] ?? "") + (parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? "") : "")).toUpperCase();
}
/** Seat fabrics, as CSS colours built from the theme so both modes stay in key. */
const FABRIC: Record<SeatType | "taken" | "picked", string> = {
standard: "color-mix(in oklab, var(--color-foreground) 22%, var(--color-background))",
"extra-legroom": "color-mix(in oklab, var(--color-success) 55%, var(--color-background))",
premium: "color-mix(in oklab, var(--color-warning) 62%, var(--color-background))",
taken: "color-mix(in oklab, var(--color-foreground) 11%, var(--color-background))",
picked: "var(--color-primary)",
};
const NAV_KEYS = new Set(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Home", "End", "PageUp", "PageDown"]);
/** The seat a navigation key lands on from `at`, or undefined at an edge. */
function stepSeat(grid: Seat[][], at: Seat, key: string, ctrlKey: boolean) {
const row = grid[at.rowIndex];
// Up and down keep the seat letter when the next row has it, else the
// nearest column, so cabins with narrower rows still step cleanly.
const sameColumn = (r: Seat[] | undefined) =>
r?.find((s) => s.letter === at.letter) ??
r?.reduce<Seat | undefined>(
(best, s) => (!best || Math.abs(s.col - at.col) < Math.abs(best.col - at.col) ? s : best),
undefined,
);
switch (key) {
case "ArrowLeft":
return row[row.indexOf(at) - 1];
case "ArrowRight":
return row[row.indexOf(at) + 1];
case "ArrowUp":
return sameColumn(grid[at.rowIndex - 1]);
case "ArrowDown":
return sameColumn(grid[at.rowIndex + 1]);
case "Home":
return ctrlKey ? grid[0]?.[0] : row[0];
case "End":
return ctrlKey ? grid[grid.length - 1]?.at(-1) : row.at(-1);
case "PageUp":
return sameColumn(grid[Math.max(at.rowIndex - 5, 0)]);
case "PageDown":
return sameColumn(grid[Math.min(at.rowIndex + 5, grid.length - 1)]);
default:
return undefined;
}
}
/* -------------------------------------------------------------------------- */
/* Scenery */
/* -------------------------------------------------------------------------- */
/** An emergency exit beside a row, marked on the floor at the cabin's edge. */
function ExitMark({ side, offset }: { side: "left" | "right"; offset: number }) {
return (
<span
aria-hidden="true"
className="absolute w-[6px] rounded-full bg-success/80 shadow-[0_0_10px_color-mix(in_oklab,var(--color-success)_60%,transparent)]"
style={{ top: offset + 4, height: SEAT_D - 8, [side]: -PAD + 10 }}
/>
);
}
/* -------------------------------------------------------------------------- */
/* Seat */
/* -------------------------------------------------------------------------- */
type SeatState = "available" | "taken" | "mine" | "other";
interface SeatViewProps {
seat: Seat;
state: SeatState;
holder?: string;
label: string;
tip: ReactNode;
tabIndex: number;
risen: boolean;
introDelay: number | null;
reduce: boolean;
onPick: () => void;
onFocus: () => void;
}
/** Skin tones for the ears of travellers already seated. */
const SKIN = ["#e3b48f", "#c68d64", "#8d5a3b", "#f0c9a8", "#5f3a26"];
/** A traveller already seated, seen from behind: hair and a little of each ear. */
function StrangerHead({ seed }: { seed: number }) {
const hair = HAIR[seed % HAIR.length];
const skin = SKIN[(seed >> 3) % SKIN.length];
return (
<span className="absolute left-1/2 top-0 block -translate-x-1/2" style={{ width: HEAD + 6, height: HEAD }}>
<span className="absolute left-0 top-[44%] block size-[7px] rounded-full" style={{ background: skin }} />
<span className="absolute right-0 top-[44%] block size-[7px] rounded-full" style={{ background: skin }} />
<span
className="absolute inset-x-[3px] inset-y-0 block rounded-[46%_46%_42%_42%]"
style={{
background: `radial-gradient(circle at 50% 28%, color-mix(in oklab, ${hair} 72%, white), ${hair} 62%, color-mix(in oklab, ${hair} 80%, black))`,
}}
/>
</span>
);
}
/**
* The seatback seen from behind. The upholstered backrest, in the seat's
* colour, rises above a moulded shell and ends in a winged headrest with its
* cover. The shell carries the seatback screen, a stowed tray table with its
* latch and the seat pocket.
*/
function SeatBackShell({ fabric, premium, lit, uid }: { fabric: string; premium: boolean; lit: boolean; uid: string }) {
const w = SEAT_W - 2;
const h = BACK_H;
const mid = w / 2;
// Upholstered backrest: slightly wider than the shell, so its colour shows
// round the top and down both sides.
const backrest = `M3.5 ${h} L2 13 C2 4.5 7.5 1 15 1 L${w - 15} 1 C${w - 7.5} 1 ${w - 2} 4.5 ${w - 2} 13 L${w - 3.5} ${h} Z`;
// Plastic shell, starting under the headrest.
const shell = `M6 ${h} L5 18 C5 14.5 7.5 13 11 13 L${w - 11} 13 C${w - 7.5} 13 ${w - 5} 14.5 ${w - 5} 18 L${w - 6} ${h} Z`;
// Headrest with wings that fold forward at each side.
const headrest = `M${mid - 19} 4.5 C${mid - 19} 2.8 ${mid - 17.5} 2 ${mid - 15} 2 L${mid + 15} 2 C${mid + 17.5} 2 ${mid + 19} 2.8 ${mid + 19} 4.5 L${mid + 19} 9.5 C${mid + 19} 11.5 ${mid + 17.5} 12 ${mid + 15.5} 11.5 L${mid + 12} 10.5 L${mid - 12} 10.5 L${mid - 15.5} 11.5 C${mid - 17.5} 12 ${mid - 19} 11.5 ${mid - 19} 9.5 Z`;
const plastic = `color-mix(in oklab, ${fabric} 38%, var(--color-background))`;
return (
<svg aria-hidden="true" width={w} height={h} viewBox={`0 0 ${w} ${h}`} className="block overflow-visible">
<defs>
<linearGradient id={`${uid}-fabric`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor={`color-mix(in oklab, ${fabric} 75%, white)`} />
<stop offset="0.3" stopColor={fabric} />
<stop offset="1" stopColor={`color-mix(in oklab, ${fabric} 62%, black)`} />
</linearGradient>
<linearGradient id={`${uid}-shell`} x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor={`color-mix(in oklab, ${plastic} 86%, white)`} />
<stop offset="1" stopColor={`color-mix(in oklab, ${plastic} 78%, black)`} />
</linearGradient>
<linearGradient id={`${uid}-side`} x1="0" y1="0" x2="1" y2="0">
<stop offset="0" stopColor="black" stopOpacity="0.3" />
<stop offset="0.14" stopColor="black" stopOpacity="0" />
<stop offset="0.86" stopColor="black" stopOpacity="0" />
<stop offset="1" stopColor="black" stopOpacity="0.3" />
</linearGradient>
</defs>
<path d={backrest} fill={`url(#${uid}-fabric)`} />
<path d={backrest} fill={`url(#${uid}-side)`} />
{/* Light catching the top of the backrest. */}
<path
d={`M4.5 12 C4.5 5.5 9 3 15 3 L${w - 15} 3 C${w - 9} 3 ${w - 4.5} 5.5 ${w - 4.5} 12`}
fill="none"
stroke="white"
strokeOpacity="0.4"
/>
{/* Headrest, its stitched edge and its cover. */}
<path d={headrest} fill={`color-mix(in oklab, ${fabric} 88%, white)`} stroke="black" strokeOpacity="0.18" strokeWidth={0.75} />
<rect x={mid - 11} y={3.4} width={22} height={6} rx={2} fill="white" fillOpacity={premium ? 0.92 : 0.55} />
{/* Moulded shell with a lip along its top. */}
<path d={shell} fill={`url(#${uid}-shell)`} />
<path d={shell} fill={`url(#${uid}-side)`} />
<path d={`M5.5 16.5 C5.5 14.5 8 13.5 11 13.5 L${w - 11} 13.5 C${w - 8} 13.5 ${w - 5.5} 14.5 ${w - 5.5} 16.5`} fill="none" stroke="white" strokeOpacity="0.3" />
{/* Screen in its bezel: dark with a glare, or lit up for the seat you picked. */}
<rect x={mid - 10.5} y={16} width={21} height={13} rx={2.4} fill="#16181d" stroke="black" strokeOpacity="0.35" strokeWidth={0.75} />
{lit ? (
<>
<rect x={mid - 9} y={17.4} width={18} height={10.2} rx={1.4} fill="var(--color-primary)" />
<rect x={mid - 9} y={17.4} width={18} height={4} rx={1.4} fill="white" fillOpacity="0.25" />
</>
) : (
<>
<rect x={mid - 9} y={17.4} width={18} height={10.2} rx={1.4} fill="#0a0c10" />
<path d={`M${mid - 6} ${27.2} L${mid + 1.5} ${17.8} L${mid + 4.5} ${17.8} L${mid - 3} ${27.2} Z`} fill="white" fillOpacity="0.09" />
</>
)}
{/* Stowed tray table and its latch. */}
<rect x={mid - 16} y={31} width={32} height={8.5} rx={2} fill="black" fillOpacity="0.07" stroke="black" strokeOpacity="0.24" strokeWidth={0.75} />
<rect x={mid - 3.5} y={30} width={7} height={2.6} rx={1} fill="black" fillOpacity="0.5" />
{/* Seat pocket. */}
<path d={`M${mid - 15} ${h - 4.5} Q${mid} ${h - 2.5} ${mid + 15} ${h - 4.5}`} fill="none" stroke="black" strokeOpacity="0.28" strokeWidth={0.9} />
<path d={`M${mid - 15} ${h - 3.5} Q${mid} ${h - 1.5} ${mid + 15} ${h - 3.5}`} fill="none" stroke="white" strokeOpacity="0.18" strokeWidth={0.75} />
</svg>
);
}
function SeatView({
seat,
state,
holder,
label,
tip,
tabIndex,
risen,
introDelay,
reduce,
onPick,
onFocus,
}: SeatViewProps) {
const uid = useId().replace(/:/g, "");
const fabric =
state === "taken" ? FABRIC.taken : state === "mine" ? FABRIC.picked : FABRIC[seat.type];
// Seats lie flat until the cabin comes into view, then stand row by row.
// Your own seat reclines a little.
const upright = state === "mine" ? -102 : -90;
const backTransition =
introDelay !== null ? { ...SPRING_PANEL, delay: introDelay } : reduce ? { duration: 0 } : SPRING_SWAP;
const head = state === "taken" ? <StrangerHead seed={hash(seat.id)} /> : null;
return (
<Tooltip content={tip} sideOffset={14} arrow className="rounded-xl px-3 py-2 whitespace-nowrap">
<motion.button
type="button"
data-seat={seat.id}
tabIndex={tabIndex}
aria-label={label}
aria-disabled={state === "taken" || undefined}
onClick={onPick}
onFocus={onFocus}
className={cn(
"group relative block shrink-0 outline-none transform-3d",
state === "taken" ? "cursor-not-allowed" : "cursor-pointer",
)}
style={{ width: SEAT_W, height: SEAT_D }}
>
{/* Soft shadow the seat casts on the floor. */}
<span aria-hidden="true" className="absolute inset-x-[2px] top-[6px] -bottom-[3px] rounded-[10px] bg-black/30 blur-[3px]" />
{/* Cushion, on the floor, with its stitched seam. */}
<span
aria-hidden="true"
className="absolute inset-x-[5px] top-[3px] bottom-[2px] overflow-hidden rounded-[10px] transition-[background] duration-200"
style={{
background: `linear-gradient(180deg, color-mix(in oklab, ${fabric} 78%, white), ${fabric} 60%, color-mix(in oklab, ${fabric} 82%, black))`,
}}
>
<span className="absolute inset-x-[4px] top-[38%] block h-px bg-black/15" />
<span className="absolute inset-x-[4px] top-[2px] block h-px bg-white/40" />
</span>
{/* A ring spreads across the floor when a passenger lands in the seat. */}
<AnimatePresence>
{state === "mine" && !reduce ? (
<motion.span
key={holder}
aria-hidden="true"
initial={{ opacity: 0.9, scale: 0.7 }}
animate={{ opacity: 0, scale: 1.9 }}
exit={{ opacity: 0, transition: { duration: 0 } }}
transition={{ duration: 0.7, ease: EASE_OUT }}
className="pointer-events-none absolute inset-0 rounded-[10px] border-2 border-primary"
/>
) : null}
</AnimatePresence>
{/* Armrests, raised off the floor: a padded top and a darker cap at the front. */}
{(["left-0", "right-0"] as const).map((edge) => (
<span
key={edge}
aria-hidden="true"
className={cn("absolute top-[6px] bottom-[1px] block w-[6px] overflow-hidden rounded-full shadow-[0_2px_3px_rgb(0_0_0/0.3)]", edge)}
style={{
transform: "translateZ(10px)",
background:
"linear-gradient(90deg, color-mix(in oklab, var(--color-foreground) 34%, var(--color-background)), color-mix(in oklab, var(--color-foreground) 52%, var(--color-background)) 50%, color-mix(in oklab, var(--color-foreground) 30%, var(--color-background)))",
}}
>
<span className="absolute inset-x-0 top-0 block h-[9px] rounded-full bg-black/35" />
</span>
))}
{/* Seatback, standing at the cushion's rear edge, with the head behind it. */}
<motion.span
aria-hidden="true"
initial={false}
animate={{ rotateX: risen ? upright : 0 }}
transition={backTransition}
className="absolute inset-x-[1px] bottom-0 block origin-bottom"
style={{ height: BACK_H + PEEK }}
>
{head}
<AnimatePresence initial={false}>
{holder ? (
<motion.span
key={holder}
initial={reduce ? { opacity: 0 } : { y: HEAD + 4 }}
animate={reduce ? { opacity: 1 } : { y: 0 }}
exit={reduce ? { opacity: 0 } : { y: HEAD + 4, transition: { duration: 0.16, ease: EASE_OUT } }}
transition={reduce ? { duration: 0.15 } : SPRING_SWAP}
className={cn(
"absolute left-1/2 top-0 -ml-[12.5px] flex items-center justify-center rounded-full text-[9px] font-bold leading-none",
state === "mine"
? "bg-background text-primary ring-2 ring-primary"
: "bg-primary text-primary-foreground",
)}
style={{ width: HEAD, height: HEAD }}
>
{holder}
</motion.span>
) : null}
</AnimatePresence>
<span
className={cn(
"absolute inset-x-0 bottom-0 block rounded-t-[14px] rounded-b-[4px] transition-shadow duration-200",
state === "mine" && "shadow-[0_0_20px_color-mix(in_oklab,var(--color-primary)_50%,transparent)]",
"group-focus-visible:ring-2 group-focus-visible:ring-muted-foreground group-focus-visible:ring-offset-2 group-focus-visible:ring-offset-background",
)}
style={{ height: BACK_H }}
>
<SeatBackShell fabric={fabric} premium={seat.type === "premium"} lit={state === "mine"} uid={uid} />
</span>
</motion.span>
</motion.button>
</Tooltip>
);
}
const EMPTY: SeatSelection = {};
const NO_TAKEN: string[] = [];
/**
* A 3D aircraft cabin for picking seats on a booking. The floor tips away
* from the viewer, every seat stands as a cushion and seatback, and a
* passenger's head pops up over the seat they pick. The grid is one tab stop
* with arrow key movement, and a summary totals the chosen seats.
*/
export function FlightSeatMap({
layout,
passengers,
taken = NO_TAKEN,
value,
defaultValue = EMPTY,
onChange,
currency = "USD",
tilt = 42,
sound = false,
labels,
className,
}: FlightSeatMapProps) {
const t = useMessages("flightSeatMap", flightSeatMapMessages, labels);
const { locale } = useLocale();
const reduce = Boolean(useReducedMotion());
const [selection, setSelection] = useControllable(value, defaultValue, onChange);
const cabin = useMemo(() => buildCabin(layout), [layout]);
const takenSet = useMemo(() => new Set(taken), [taken]);
const playPick = useSound(popSound, { enabled: sound });
const playClear = useSound(dismissSound, { enabled: sound });
const playSwitch = useSound(selectSound, { enabled: sound });
const playTaken = useSound(buzzSound, { enabled: sound, volume: 0.6 });
const formatMoney = useMemo(() => {
const format = new Intl.NumberFormat(locale ?? "en-US", {
style: "currency",
currency,
maximumFractionDigits: 0,
});
return (price: number) => format.format(price);
}, [locale, currency]);
const money = (price: number) => (price > 0 ? formatMoney(price) : t("included"));
// Seat id to the passenger sitting there.
const occupant = useMemo(() => {
const map = new Map<string, SeatPassenger>();
for (const p of passengers) {
const seat = selection[p.id];
if (seat) map.set(seat, p);
}
return map;
}, [passengers, selection]);
// Who is being seated. Falls back to the first passenger without a seat
// when the chosen one leaves the list.
const [activeId, setActiveId] = useState<string | null>(null);
const active =
passengers.find((p) => p.id === activeId) ??
passengers.find((p) => !selection[p.id]) ??
passengers[0];
// The roving tab stop, held as the seat id. Resolved during render: the
// cursor, else the active passenger's seat, else the first free seat.
const [cursor, setCursor] = useState<string | null>(null);
if (cursor !== null && !cabin.seats.has(cursor)) setCursor(null);
const firstFree =
cabin.grid.flat().find((s) => !takenSet.has(s.id) && !occupant.has(s.id)) ?? cabin.grid[0]?.[0];
const activeSeat = active ? selection[active.id] : null;
const tabStop =
cursor && cabin.seats.has(cursor)
? cursor
: activeSeat && cabin.seats.has(activeSeat)
? activeSeat
: (firstFree?.id ?? null);
const [announcement, setAnnouncement] = useState("");
const gridRef = useRef<HTMLDivElement>(null);
const stageRef = useRef<HTMLDivElement>(null);
const planeRef = useRef<HTMLDivElement>(null);
const hullRef = useRef<HTMLDivElement>(null);
// 3D transforms leave layout alone, so the stage takes the height the
// tipped plane really covers on screen, worked out from its flat size:
// with the camera at the stage's bottom edge, a floor of length h tipped by
// θ spans h·cosθ·p / (p + h·sinθ). The plane also shrinks to fit narrow
// stages.
const [frame, setFrame] = useState<{ fit: number; height: number } | null>(null);
useLayoutEffect(() => {
const stage = stageRef.current;
const plane = planeRef.current;
const hull = hullRef.current;
if (!stage || !plane || !hull) return;
const measure = () => {
const fit = hull.offsetWidth > 0 ? Math.min(1, (stage.clientWidth - 16) / hull.offsetWidth) : 1;
const h = plane.offsetHeight;
const theta = (tilt * Math.PI) / 180;
// `scale` shrinks the plane across the screen but not in depth, so the
// fit applies to the rise on screen and the full length to the depth.
const height = Math.ceil((h * fit * Math.cos(theta) * PERSPECTIVE) / (PERSPECTIVE + h * Math.sin(theta))) + 36;
setFrame((f) => (f && f.fit === fit && f.height === height ? f : { fit, height }));
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(stage);
observer.observe(plane);
return () => observer.disconnect();
}, [tilt]);
// The cabin tips into place and the seats stand up once it is on screen.
const inView = useInView(stageRef, { once: true, amount: 0.25 });
const [intro, setIntro] = useState<"waiting" | "running" | "done">(reduce ? "done" : "waiting");
if (reduce && intro !== "done") setIntro("done");
if (!reduce && inView && intro === "waiting") setIntro("running");
const introSpan = cabin.rows.length * 0.045 + 0.7;
useEffect(() => {
if (intro !== "running") return;
const id = window.setTimeout(() => setIntro("done"), introSpan * 1000);
return () => window.clearTimeout(id);
}, [intro, introSpan]);
// The cabin settles from a steeper angle while its seats stand up.
const rotateX = useSpring(reduce ? tilt : tilt + 20, CABIN_SETTLE);
useEffect(() => {
if (intro !== "waiting") rotateX.set(tilt);
}, [intro, tilt, rotateX]);
const focusNext = useRef(false);
const latest = useRef({ cabin, tabStop });
useLayoutEffect(() => {
latest.current = { cabin, tabStop };
});
// A key moved the cursor: move focus to its seat after the commit.
useLayoutEffect(() => {
if (!focusNext.current || !tabStop || !gridRef.current?.contains(document.activeElement)) return;
focusNext.current = false;
gridRef.current?.querySelector<HTMLButtonElement>(`[data-seat="${CSS.escape(tabStop)}"]`)?.focus();
}, [tabStop]);
const assign = (seat: Seat) => {
if (!active) return;
if (takenSet.has(seat.id)) {
playTaken();
return;
}
const holder = occupant.get(seat.id);
if (holder && holder.id !== active.id) {
playSwitch();
setActiveId(holder.id);
return;
}
if (holder?.id === active.id) {
playClear();
setSelection({ ...selection, [active.id]: null });
setAnnouncement(t("announceCleared", { name: active.name }));
return;
}
playPick();
const next = { ...selection, [active.id]: seat.id };
setSelection(next);
setAnnouncement(t("announce", { seat: seat.id, name: active.name }));
// Move on to the next passenger still waiting for a seat.
const start = passengers.findIndex((p) => p.id === active.id);
const waiting = [...passengers.slice(start + 1), ...passengers.slice(0, start)].find((p) => !next[p.id]);
setActiveId(waiting?.id ?? active.id);
};
const clear = (passenger: SeatPassenger) => {
playClear();
setSelection({ ...selection, [passenger.id]: null });
setActiveId(passenger.id);
setAnnouncement(t("announceCleared", { name: passenger.name }));
};
const onKeyDown = useCallback((event: KeyboardEvent<HTMLDivElement>) => {
if (!NAV_KEYS.has(event.key)) return;
event.preventDefault();
const { key, ctrlKey } = event;
// The focused seat is where the keys start from.
const origin = (event.target as HTMLElement).closest<HTMLElement>("[data-seat]")?.dataset.seat;
focusNext.current = true;
// Steps inside the update, so two keys landing in one batch move two
// seats: the first starts from the focused seat, the next from where the
// first left the cursor.
setCursor((current) => {
const { cabin: live, tabStop } = latest.current;
const from = current && current !== tabStop && live.seats.has(current) ? current : (origin ?? tabStop);
const at = from ? live.seats.get(from) : undefined;
if (!at) return current;
return stepSeat(live.grid, at, key, ctrlKey)?.id ?? at.id;
});
}, []);
const seatName = (seat: Seat) => {
const holder = occupant.get(seat.id);
const status = takenSet.has(seat.id)
? t("taken")
: holder
? t("selectedFor", { name: holder.name })
: t("available");
return [t("seat", { seat: seat.id }), t(seat.position), t(seat.type), money(seat.price), status].join(", ");
};
const total = passengers.reduce((sum, p) => {
const seat = selection[p.id];
return sum + (seat ? (cabin.seats.get(seat)?.price ?? 0) : 0);
}, 0);
const types = Array.from(new Set(cabin.rows.map((r) => r.type)));
const firstAisle = layout.columns.indexOf("");
const risen = intro !== "waiting";
return (
<div
className={cn("@container w-full text-sm", className)}
style={
{
"--hull": "color-mix(in oklab, var(--color-foreground) 5%, var(--color-background))",
"--floor": "color-mix(in oklab, var(--color-foreground) 9%, var(--color-background))",
} as CSSProperties
}
>
{/* Narrow: passengers above the cabin. Wide: cabin on the left, passengers beside it. */}
<div className="grid grid-cols-1 items-start gap-4 @3xl:grid-cols-[minmax(0,1fr)_17rem] @3xl:gap-x-6">
<div className="flex min-w-0 flex-col items-center gap-3 @3xl:col-start-1 @3xl:row-start-1">
{/* The stage: the camera sits at its bottom edge, behind the rear. */}
<div
ref={stageRef}
className="relative w-full overflow-x-clip"
style={{
height: frame?.height,
perspective: PERSPECTIVE,
perspectiveOrigin: "50% 100%",
visibility: frame ? undefined : "hidden",
}}
>
<motion.div
ref={planeRef}
className="absolute bottom-4 left-1/2 transform-3d"
style={{
x: "-50%",
scale: frame?.fit ?? 1,
rotateX,
transformOrigin: "50% 100%",
}}
>
{/* Shadow on the ground far below. */}
<span
aria-hidden="true"
className="absolute inset-x-6 inset-y-24 rounded-full bg-foreground/15 blur-[10px]"
style={{ transform: "translateZ(-70px)" }}
/>
{/* Hull: the cabin floor, rounded at both ends. */}
<div
ref={hullRef}
className="relative border border-foreground/20 transform-3d"
style={{
borderRadius: `50% / ${END}px`,
paddingInline: PAD,
// Deep enough that the outer seats clear the curve.
paddingBlock: Math.round(END * 0.62),
background: "var(--hull)",
}}
>
{/* biome-ignore lint/a11y/useSemanticElements: A 3D grid needs plain boxes; table parts flatten transforms. */}
<div
ref={gridRef}
role="grid"
aria-label={t("map")}
onKeyDown={onKeyDown}
className="relative select-none transform-3d"
>
{/* Carpet down the aisle. */}
<span
aria-hidden="true"
className="absolute inset-y-0"
style={{
left: layout.columns.slice(0, firstAisle).filter(Boolean).length * (SEAT_W + 4),
width: AISLE_W,
background: "var(--floor)",
}}
/>
{/* biome-ignore lint/a11y/useSemanticElements: A 3D grid needs plain boxes; table parts flatten transforms. */}
{/* biome-ignore lint/a11y/useFocusableInteractive: The seats inside take focus. */}
<div role="row" className="flex gap-1 pb-1">
{layout.columns.map((letter, i) => (
// biome-ignore lint/a11y/useSemanticElements: See the grid note above.
// biome-ignore lint/a11y/useFocusableInteractive: Headers are not focus stops in this grid.
<span
// biome-ignore lint/suspicious/noArrayIndexKey: Columns are positional; aisles have no letter of their own.
key={i}
role="columnheader"
className="flex shrink-0 items-end justify-center text-[11px] font-semibold text-muted-foreground"
style={{ width: letter ? SEAT_W : AISLE_W }}
>
{letter || <span className="sr-only">{i === firstAisle ? t("row") : t("aisleColumn")}</span>}
</span>
))}
</div>
{cabin.rows.map((row) => {
const top = PITCH[row.type] + (row.sectionStart ? 14 : 0);
return (
// biome-ignore lint/a11y/useSemanticElements: See the grid note above.
// biome-ignore lint/a11y/useFocusableInteractive: The seats inside take focus.
<div
key={row.row}
role="row"
data-row={row.row}
className="relative flex gap-1 transform-3d"
style={{ paddingTop: top }}
>
{row.exit ? (
<>
<ExitMark side="left" offset={top} />
<ExitMark side="right" offset={top} />
</>
) : null}
{row.seats.map((seat, i) => {
if (!seat) {
return i === firstAisle ? (
// biome-ignore lint/a11y/useSemanticElements: See the grid note above.
// biome-ignore lint/a11y/useFocusableInteractive: Headers are not focus stops in this grid.
<span
// biome-ignore lint/suspicious/noArrayIndexKey: Aisles are positional.
key={i}
role="rowheader"
className="flex shrink-0 items-center justify-center text-[11px] font-semibold tabular-nums text-muted-foreground"
style={{ width: AISLE_W, height: SEAT_D }}
>
{row.row}
</span>
) : (
// biome-ignore lint/a11y/useSemanticElements: See the grid note above.
// biome-ignore lint/a11y/useFocusableInteractive: An aisle holds no seat to focus.
// biome-ignore lint/suspicious/noArrayIndexKey: Aisles are positional.
<span key={i} role="gridcell" className="shrink-0" style={{ width: AISLE_W }} />
);
}
const holder = occupant.get(seat.id);
const state: SeatState = takenSet.has(seat.id)
? "taken"
: holder
? holder.id === active?.id
? "mine"
: "other"
: "available";
return (
// biome-ignore lint/a11y/useSemanticElements: See the grid note above.
// biome-ignore lint/a11y/useFocusableInteractive: The seat button inside takes focus.
<div
key={seat.id}
role="gridcell"
aria-selected={Boolean(holder)}
className="transform-3d"
>
<SeatView
seat={seat}
state={state}
holder={holder ? initials(holder.name) : undefined}
label={seatName(seat)}
tip={
<span className="flex flex-col gap-0.5">
<span className="flex items-baseline justify-between gap-4">
<span className="font-semibold">{t("seat", { seat: seat.id })}</span>
<span className="tabular-nums text-muted-foreground">
{state === "taken" ? t("taken") : holder ? holder.name : money(seat.price)}
</span>
</span>
<span className="font-normal text-muted-foreground">
{t(seat.position)} · {t(seat.type)}
</span>
</span>
}
tabIndex={seat.id === tabStop ? 0 : -1}
risen={risen}
introDelay={intro === "running" ? row.seats.indexOf(seat) * 0.015 + seat.rowIndex * 0.045 : null}
reduce={reduce}
onPick={() => {
setCursor(seat.id);
assign(seat);
}}
onFocus={() => setCursor(seat.id)}
/>
</div>
);
})}
</div>
);
})}
</div>
</div>
</motion.div>
</div>
<ul
aria-label={t("legend")}
className="flex flex-wrap justify-center gap-x-3 gap-y-1.5 text-xs text-muted-foreground"
>
{types.map((type) => (
<li key={type} className="flex items-center gap-1.5">
<span aria-hidden="true" className="size-3 rounded-[4px]" style={{ background: FABRIC[type] }} />
{t(type)}
</li>
))}
<li className="flex items-center gap-1.5">
<span aria-hidden="true" className="size-3 rounded-[4px] bg-primary" />
{t("selected")}
</li>
<li className="flex items-center gap-1.5">
<span aria-hidden="true" className="size-3 rounded-[4px]" style={{ background: FABRIC.taken }} />
{t("taken")}
</li>
</ul>
</div>
<div className="min-w-0 @3xl:sticky @3xl:top-4 @3xl:col-start-2 @3xl:row-start-1 @max-3xl:row-start-1">
<div className="overflow-hidden rounded-2xl border border-border">
<ul aria-label={t("passengers")} className="divide-y divide-border">
{passengers.map((p) => {
const seat = selection[p.id] ? cabin.seats.get(selection[p.id] as string) : undefined;
const isActive = p.id === active?.id;
const switcher = passengers.length > 1;
const body = (
<>
<span
aria-hidden="true"
className={cn(
"flex size-7 shrink-0 items-center justify-center rounded-full text-[10px] font-semibold transition-colors duration-200",
isActive && switcher ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground",
)}
>
{initials(p.name)}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium">{p.name}</span>
<span className="block truncate text-xs text-muted-foreground">
{seat
? `${t(seat.position)}, ${t(seat.type)}`
: isActive
? t("hint", { name: p.name.split(" ")[0] ?? p.name })
: t("noSeat")}
</span>
</span>
<AnimatePresence initial={false} mode="popLayout">
{seat ? (
<motion.span
key={seat.id}
initial={{ opacity: 0, y: reduce ? 0 : 6, filter: reduce ? "none" : "blur(4px)" }}
animate={{ opacity: 1, y: 0, filter: "blur(0px)" }}
exit={{ opacity: 0, y: reduce ? 0 : -6, filter: reduce ? "none" : "blur(4px)", transition: { duration: 0.12, ease: EASE_OUT } }}
transition={{ duration: 0.2, ease: EASE_OUT }}
className="text-right"
>
<span className="block font-semibold tabular-nums">{seat.id}</span>
<span className="block text-xs tabular-nums text-muted-foreground">{money(seat.price)}</span>
</motion.span>
) : null}
</AnimatePresence>
</>
);
return (
<li
key={p.id}
className={cn(
"flex h-14 items-center gap-1 pr-2 transition-colors duration-200",
isActive && switcher && "bg-primary/[0.06]",
)}
>
{/* Picking a row makes that passenger the one being seated. */}
{switcher ? (
<button
type="button"
aria-pressed={isActive}
onClick={() => {
if (!isActive) playSwitch();
setActiveId(p.id);
}}
className="flex min-w-0 flex-1 items-center gap-2.5 self-stretch pl-3 pr-1 text-left outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-muted-foreground"
>
{body}
</button>
) : (
<span className="flex min-w-0 flex-1 items-center gap-2.5 pl-3 pr-1">{body}</span>
)}
{seat ? (
<Tooltip content={t("clear", { name: p.name })}>
<button
type="button"
aria-label={t("clear", { name: p.name })}
onClick={() => clear(p)}
className="flex size-7 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-muted-foreground"
>
<X aria-hidden="true" className="size-3.5" />
</button>
</Tooltip>
) : null}
</li>
);
})}
</ul>
<div className="flex items-center justify-between border-t border-border px-3 py-2.5">
<span className="text-muted-foreground">{t("total")}</span>
<span className="font-semibold tabular-nums">{formatMoney(total)}</span>
</div>
</div>
</div>
</div>
<div aria-live="polite" className="sr-only">
{announcement}
</div>
</div>
);
}
Add it with the shadcn CLI, or copy the source manually.
npx shadcn add https://beui.dev/r/theme.json. Theme setupInstall dependencies
npm i @floating-ui/dom clsx lucide-react motion tailwind-mergeAdd 23 files
Put each file at the same path in your project. Read or copy them one at a time in the Code tab above.
- components/motion/flight-seat-map.tsx1050
- components/motion/tooltip.tsx766
- lib/ease.ts68
- lib/hooks/use-controllable.ts31
- lib/i18n.tsx90
- lib/sound.tsx102
- lib/sounds/buzz.ts13
- lib/sounds/dismiss.ts13
- lib/sounds/pop.ts14
- lib/sounds/select.ts14
- lib/utils.ts7
- components/motion/tooltip/grace.ts92
- components/motion/tooltip/positioner.tsx70
- components/motion/tooltip/use-position.ts384
- components/motion/tooltip-surface.tsx71
- lib/hooks/use-dismiss.ts161
- lib/hooks/use-hover-gesture.ts62
- lib/hooks/use-tap-gesture.ts67
- lib/merge-refs.ts15
- lib/audio-context.ts132
- lib/sounds/engine.ts318
- lib/layers.ts77
- lib/touch.ts118
layoutSeatMapLayoutThe cabin layout: seat columns, aisles, sections, exit rows and skipped rows.
passengersSeatPassenger[]Everyone who needs a seat. One passenger makes it a single-seat picker.
taken?string[]Seat ids that are already taken, such as ["3C", "12A"].
[]value?SeatSelectionSelected seats, for controlled use.
defaultValue?SeatSelectionSelected seats at first, when uncontrolled. Default: {}
{}onChange?((value: SeatSelection) => void)Called with the whole selection whenever a passenger's seat changes.
currency?stringISO 4217 currency code for seat prices. Default: "USD"
USDtilt?numberHow far the cabin floor tips away from the viewer, in degrees. 0 draws it flat from above. Default: 42
42sound?booleanPlay a pop when a head lands in a seat, a flick when a seat is given up, a click when switching passengers and a buzz on a taken seat. Off by default; a `SoundProvider` can mute it app-wide. Default: false
falselabels?Partial<{ map: string; row: string; aisleColumn: string; seat: string; window: string; middle: string; aisle: string; standard: string; "extra-legroom": string; premium: string; available: string; taken: string; ... 10 more ...; hint: string; }>Override any built-in string.
className?stringClasses merged onto the root element.
Card Dealer
A card table with a face-down deck, a fanned hand and a discard pile. Cards arc across the table between them and flip in flight, hop over each other when the hand is sorted, and lift on hover. Data-driven by each card's zone, with custom faces and backs, keyboard-playable hand cards and reduced-motion support.
Morphing Tabs
Reorderable tabs whose selected item grows into a white content surface, with the active shape gliding as tabs move and a shared morph between rooms.
Bloom Menu
A button that morphs open into a menu and blooms iris-out from the center, the grid revealing in every direction with radially staggered items.
Some components on this site are inspired by or recreated from existing work across the web. I'm not here to take credit; just to learn, experiment, and sometimes push things a bit further. If something looks familiar and I forgot to mention you, reach out and I'll fix that right away.
Updated