@openseat/react
v0.1.0
Published
React bindings for OpenSeat: SeatMap, BookingMap and hooks.
Maintainers
Readme
@openseat/react
React bindings for OpenSeat.
import { useMemo, useState } from "react";
import type { LayoutDocument } from "@openseat/core";
import type { SeatStatus, SeatVisualState } from "@openseat/booking";
import { SeatMap, useSeatMap } from "@openseat/react";
interface Props {
layout: LayoutDocument;
statuses: ReadonlyMap<string, SeatStatus>; // from your inventory API, keyed by seat ID
}
export function Venue({ layout, statuses }: Props) {
const [selected, setSelected] = useState<string[]>([]);
const map = useSeatMap();
const seatStates = useMemo(() => {
const states = new Map<string, SeatVisualState>(statuses);
for (const id of selected) states.set(id, "selected");
return states;
}, [statuses, selected]);
return (
<>
<button onClick={map.fitToScreen}>Fit</button>
<SeatMap
ref={map.ref}
layout={layout}
seatStates={seatStates}
onObjectClick={({ seatId }) => {
if (!seatId || statuses.has(seatId)) return; // you decide what is selectable
setSelected((s) => (s.includes(seatId) ? s.filter((x) => x !== seatId) : [...s, seatId]));
}}
/>
</>
);
}SeatMap is controlled: what it draws comes only from props. Clicking a seat calls your callback and changes nothing until you update seatStates.
Props
| Prop | Purpose |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| layout | The layout. Update it immutably. |
| seatStates | Map or plain object of seat ID → available / selected / held / booked / blocked. Standing areas, booths and whole tables use their inventory key. |
| selectedObjectIds | Objects drawn with a selection outline (edit mode). |
| focusedObjectId | Object drawn with a focus ring and scrolled into view. |
| mode | "view" (default) or "edit". |
| theme | From @openseat/theme-default's createTheme. |
| panOnDrag, snapMove | Edit-mode drag behaviour. |
| seatVisibility, seatHideScale | Hide individual seats when zoomed out below a scale. |
| areaFillMode | "tint" (default) or "solid" fills for coloured sections and standing areas. |
| All SeatMapRenderer events | onObjectClick, onMoveEnd, onTransformEnd, onMarqueeSelect, … |
| zoomLimits, seatLabelMinScale, rowLabelMinScale, hitTolerance, isHittable, initialViewport | Read once, at mount. |
Callbacks can change identity on every render without rebuilding the canvas.
useSeatMap() returns { ref, fitToScreen, zoomIn, zoomOut, getRenderer } for toolbars outside the map.
The SeatMap ref (SeatMapHandle) offers fitToScreen(), zoomIn(), zoomOut(), zoomBy(factor), isGestureActive() (an edit gesture is in progress), cancelGesture() (abort it without committing) and the underlying renderer.
Booking
BookingMap is the batteries-included booking view: legend, seat card, selected-ticket summary, selection rules, keyboard navigation, live announcements, an accessible-seat filter and an accessible seat list.
import { useState } from "react";
import { buildCart, type AreaQuantity } from "@openseat/booking";
import { BookingMap, useHold, useInventory } from "@openseat/react";
export function Tickets({ eventId }: { eventId: string }) {
const { statuses } = useInventory(adapter, eventId); // loads and subscribes to real-time updates
const hold = useHold(adapter, eventId, { maxTickets: 10, layout });
const [selection, setSelection] = useState<readonly string[]>([]);
const [areas] = useState<AreaQuantity[]>([]); // zone places, booths, whole tables, from your picker
const cart = buildCart({ layout, seatIds: selection, areas, priceOf: (id) => prices[id] });
const s = hold.state;
return (
<BookingMap
layout={layout}
statuses={statuses}
selectedSeatIds={selection}
onSelectionChange={(next) => setSelection(next)}
onAreaSelect={(area) => openQuantityPicker(area)} // zones, booths, whole tables
extraItems={cart.lines.filter((l) => l.kind !== "seats")}
categoryPrices={{ vip: "₹1,499", general: "₹299" }}
reservedSeatIds={
s.status === "holding"
? s.seatIds
: s.status === "held" || s.status === "confirming"
? s.hold.seatIds
: undefined
}
rules={{ maxTickets: 10, preventOrphans: true }}
renderActions={({ valid }) => (
<button disabled={!valid || !hold.canHold} onClick={() => hold.hold(selection, areas)}>
Continue with {cart.ticketCount} tickets
</button>
)}
/>
);
}- Controlled or uncontrolled: pass
selectedSeatIds+onSelectionChange, ordefaultSelectedSeatIds. - Rules: refused clicks call
onSelectionRejected(violation)and are announced.maxTicketsis one per-buyer limit across seats, standing places, booths and whole tables, with no default: store it per event (the playground offers 1 to 100 and starts at 20, two tables of 10) and enforce it on your server too; pass the non-seat lines asextraItems({ label, quantity }) so the summary and seat clicks count them. - Real time: seats that become unavailable are removed from the selection and announced (
change.type === "unavailable"). - Your own hold: pass its seats as
reservedSeatIdsfrom the moment the hold request starts, so the backend reporting them as "held" does not remove them. Any check you run yourself (validateSelectionon the basket) must also read those seats as available, or it reports "Seat 5 in row E is no longer available." right after a successful hold; see Holds. - Keyboard: Tab into the map, arrow keys move between seats (works on curved and staggered rows), Enter or Space selects, Home, +/−. Enter and Space follow the same rule as a click: a seat of a
bookAsWholetable goes toonAreaSelectas the whole table (when it is set) and is never selected on its own. - Large venues (
sectionZoom): below the overview scale (default 1.6 × the renderer's fit-to-screen scale, orsectionZoom={{ overviewScale }}), clicking a section or anything in it zooms to that section instead of selecting. An "Overview" button and Escape zoom back out; in the overview the arrow keys move between sections and Enter zooms in. The default,"auto", turns this on for layouts with more than 2,500 seats. hideSeatsInOverview: in the overview, individual seats are hidden and each section is filled solidly in its category colour (sold-out sections grey), with contrasting labels; zooming into a section shows its seats over the usual tint. Implies the click-to-zoom ofsectionZoom.- Phones (
initialView):"auto"(default) opens narrow maps on the most valuable section, or zoomed in enough to tap a seat;"fit"always shows the whole venue (the playground's buyer page uses it).mapOverlaydraws your own controls over the map; 44 px zoom buttons outside the map never cover seats. - Not for sale wording (
notForSaleLabel): the key, seat card and area list say "Not for sale" by default. A buyer's page can pass"Reserved"(LEGEND_LABELS.reservedfrom@openseat/theme-default) so held-back places never read as sold out; not-for-sale places never show a price, and a ticket type whosecategoryPricesentry equals the label is left out of the key. - Whole-unit areas (
onAreaSelect): a standing area, a booth with aninventoryId, or abookAsWholetable (or any of its seats) callsonAreaSelect(area)with its inventory key, kind, label and capacity. Show your own quantity picker, then hold withhold.hold(seatIds, [{ inventoryId, quantity }]); without the callback, table seats stay individually selectable. Status records keyed by an area's inventory key draw it as held, "Sold out" (booked) or Not for sale (blocked, hatched). - Zones (
areaStatuses,legendStyle,AreaQuantityPicker): zones (GA areas and sections shown as zones) are sold by quantity. PassareaStatuses(places left, fromgetAreaStatuses) so sold-out zones grey out;legendStyle="auto"shows a zone map's Available / Sold out legend when no seat is sold on its own.AreaQuantityPickeris the buyer's − / + picker: a bottom sheet on phones (≤ 640 px), a popover otherwise, with 44 px touch targets. - Prices (
categoryPrices): display-only price text per category ID. The legend lists ticket types as "VIP · ₹1,499" and the summary and seat card use it for seats whose status has nopriceLabel(a per-seatpriceLabelwins). When seats are drawn in their ticket-type colours, the legend leaves out the white "Available" dot; selected seats are ink (#0f172a) with a white check. - Accessible seats: wheelchair spaces carry a pictogram and companion seats a mark; the legend adds "Accessible seat" (and "Companion seat") entries when the layout has them, and the "Show accessible seats" switch (
accessibleFilter, on by default when there are any) highlights them and dims the rest.accessibleFilter="always"also tells buyers when a layout has none ("No wheelchair seats listed for this event"). - Not for sale: blocked seats and areas get a "Not for sale" legend entry (a crossed seat, a hatched square) and refuse clicks with a sentence ("Booth B7 is not for sale.").
- Seat card (
seatCard, default true): hovering over a seat, or tapping it, shows "Row C, Seat 5 · Stalls · ₹200 · Wheelchair space". - Bundle size:
BookingMapdraws withSeatMapViewRendererfrom@openseat/renderer-konva, the view-only renderer without Konva'sTransformer(the resize and rotate handles), so a booking page never downloads them.<SeatMap>usesSeatMapRenderer, which adds the handles for edit mode. - Screen readers: each focused seat is announced in full ("Seat 5, row A, Stalls, VIP, ₹200, available"); an accessible list of every seat as a labelled checkbox, grouped by section and row, is visually hidden by default (
accessibleList="visible"shows it).
useHold(adapter, eventId, { maxTickets?, layout? }) returns { state, canHold, remainingMs, hold(seatIds, areas?), confirm, release, reset, controller }. canHold is true whenever a new booking can start, including straight after a confirmed one; reset() returns to idle for UIs that show a start state between bookings.
useBookingFlow: the whole buyer flow in one hook
For a backend where your server books the seats after payment (the OpenSeat Cloud API, or your own), useBookingFlow keeps the live statuses, the basket, the hold and its countdown together, and works out reservedSeatIds and own-hold-aware validation for you:
import { BookingMap, useBookingFlow } from "@openseat/react";
export function SeatPage({ eventId, savedHoldId }: { eventId: string; savedHoldId?: string }) {
const flow = useBookingFlow(adapter, eventId, {
layout,
maxTickets: 10,
onHeld: (hold) => createOrder(hold), // once per hold or replacement; the hold is re-read afterwards
onError: (error) => showToast(error.message),
...(savedHoldId ? { resumeHoldId: savedHoldId } : {}), // after a payment page reloaded the tab
holdRefreshMs: 15_000, // see your server's lock and extensions
ownSeatsBookedCompletes: true, // the live feed shows the seats booked → "completed"
});
const minutes = Math.ceil(flow.remainingMs / 60_000);
return (
<BookingMap
layout={layout}
statuses={flow.statuses}
areaStatuses={flow.areaStatuses}
selectedSeatIds={flow.selection}
onSelectionChange={(next) => flow.setSelection(next)}
reservedSeatIds={[...flow.reservedSeatIds]}
rules={{ maxTickets: 10 }}
renderActions={() =>
flow.holdState.status === "completed" ? (
<p>Booked</p>
) : (
<button disabled={!flow.canHold} onClick={() => void flow.holdSelection()}>
{flow.hold ? `Change seats · ${minutes} min left` : `Continue with ${flow.selection.length} tickets`}
</button>
)
}
/>
);
}holdSelection()holds the basket (selectionplusareas, set withsetAreas), or replaces the active hold with it. Adapters such as@openseat/cloudswap holds atomically; with others, callrelease()first.autoExtendOnReplaceSextends after a replacement (a refusal at the server's cap is silent).- On
SEATS_UNAVAILABLEthe taken seats leave the basket, the rest stay selected and statuses are re-read;onErroris told. - A locked hold (
locked, set when your server attached an order) cannot be changed or released here:canHoldis false and both calls are refused withCONFLICT/HOLD_LOCKED. - With
getHold, the countdown is checked with the server when it ends (verifyExpiry), so an extension made by your server is never missed.onHoldExpiredfires only when the hold is really gone; the basket is kept. ownSeatsBookedCompletes: when the live feed shows every seat of the hold booked, the state becomescompleted(onCompleted, basket cleared). A hold of zones only is re-read when its areas change.complete()does it by hand.areaStatusescounts the places of the customer's own hold as available to them, so a replacement can keep them.- Nothing is ever released on its own. Holds survive unmounting (navigation to your checkout page);
releaseOnDispose: truereleases an unlocked hold on unmount.
Returns { statuses, areaStatuses, loading, error, selection, setSelection, areas, setAreas, basketValidation, reservedSeatIds, hold, holdState, remainingMs, locked, canHold, holdSelection, release, extend, refresh, complete }.
Also exported: AreaQuantityPicker, formatQuantityTotal(amount, currency, priceEach) ("₹3,996" for INR), SeatLegend (categories, categoryPrices, accessible, companion, notForSale, notForSaleLabel), SelectionSummary, seatCardText, areaCardText, parsePriceLabel ("₹1,200" → 1200), and hooks useSeatSelection, useInventory (applies an adapter's onSnapshot re-reads as replacements), useHold, useBookingFlow, useLayout (validates a layout from an object, JSON or a loader).
Documentation
Embedding the booking map (every prop, zones, holds, accessible seating, phones, prices in ₹) and Integrating end to end (a complete ticket page and its public link).
