Booking
A trip booking form with dates, guests, room options and a live total, the same in every framework.
// Vanilla: the create* factories the elements are built on.
import createButton from "material/components/button";
import createCheckbox from "material/components/checkbox";
import createDatePicker from "material/components/datepicker";
import createDialog from "material/components/dialog";
import createRadios from "material/components/radios";
import createSelect from "material/components/select";
import createSlider from "material/components/slider";
import createSnackbar from "material/components/snackbar";
import createTextField from "material/components/text-field";
import createTimePicker from "material/components/timepicker";
import { ADULT_OPTIONS, CHILD_OPTIONS, CLOCK_ICON, DEFAULTS, EXTRAS, ROOMS, eligibleRooms, normalizeTime, rangeText, roomOf, summary, totalText, validate, withDates, withPrice, type Booking } from "./shared";
let s: Booking = { ...DEFAULTS };
const app = document.getElementById("app")!;
const section = Object.assign(document.createElement("section"), { className: "booking" });
const div = (className: string): HTMLDivElement => Object.assign(document.createElement("div"), { className });
const text = (className: string, value: string, tag = "p"): HTMLElement => Object.assign(document.createElement(tag), { className, textContent: value });
const intro = div("booking__intro");
intro.append(text("booking__title mtrl-headline-small", "Book a stay", "h1"), text("booking__lede mtrl-body-medium", "Choose dates, guests and a room. The total updates as you go."));
const grid = div("booking__grid");
const status = Object.assign(document.createElement("output"), { className: "booking__total mtrl-body-medium" });
status.setAttribute("role", "status");
const range = text("booking__range mtrl-body-medium", "");
const checkIn = createDatePicker({ label: "Check-in", variant: "modal", closeOnSelect: true, dateFormat: "YYYY-MM-DD", value: s.checkIn });
const checkOut = createDatePicker({ label: "Check-out", variant: "modal", closeOnSelect: true, dateFormat: "YYYY-MM-DD", value: s.checkOut, minDate: s.checkIn });
const arrival = createTextField({ label: "Arrival time", value: s.arrivalTime, supportingText: "24-hour time", trailingIcon: CLOCK_ICON, trailingIconLabel: "Choose time" });
const nameField = createTextField({ label: "Name", supportingText: "Required" });
const adults = createSelect({ label: "Adults", value: s.adults, options: ADULT_OPTIONS.map((n) => ({ id: n, text: n })) });
const children = createSelect({ label: "Children", value: s.children, options: CHILD_OPTIONS.map((n) => ({ id: n, text: n })) });
const emailField = createTextField({ label: "Email", type: "email", supportingText: "Required" });
grid.append(checkIn.element, checkOut.element, arrival.element, nameField.element, adults.element, children.element, emailField.element);
const roomGroup = div("booking__group");
const radios = createRadios({ name: "room", value: s.room, options: ROOMS.map((room) => ({ value: room.value, label: `${room.label} — $${room.rate} a night` })) });
radios.element.setAttribute("aria-label", "Room type");
roomGroup.append(text("booking__label mtrl-title-small", "Room type"), radios.element);
const extrasGroup = div("booking__group");
extrasGroup.setAttribute("role", "group");
extrasGroup.setAttribute("aria-labelledby", "extras-label");
const extrasLabel = text("booking__label mtrl-title-small", "Extras");
extrasLabel.id = "extras-label";
extrasGroup.append(extrasLabel);
for (const extra of EXTRAS) {
const control = createCheckbox({ label: `${extra.label} — $${extra.price} ${extra.unit}` });
control.element.querySelector("svg")?.setAttribute("aria-hidden", "true");
control.on("change", ({ checked }) => { s = { ...s, [extra.key]: checked }; render(); });
extrasGroup.append(control.element);
}
const priceGroup = div("booking__group");
const slider = createSlider({ range: true, showValue: true, min: 50, max: 300, step: 10, value: s.priceMin, secondValue: s.priceMax });
slider.element.setAttribute("aria-label", "Price range");
slider.element.querySelectorAll('[role="slider"]').forEach((handle, index) => handle.setAttribute("aria-label", index === 0 ? "Price range minimum" : "Price range maximum"));
priceGroup.append(text("booking__label mtrl-title-small", "Price range"), slider.element, range);
const timePicker = createTimePicker({ value: s.arrivalTime, format: "24h", title: "Arrival time" });
const snackbar = createSnackbar({ message: "Booking confirmed" });
const summaryEl = document.createElement("p");
const dialog = createDialog({
title: "Confirm booking",
container: section,
content: "",
buttons: [
{ text: "Cancel", variant: "text" },
{ text: "Confirm booking", variant: "text", onClick: () => { section.append(snackbar.element); snackbar.show(); } },
],
});
const contentEl = dialog.getContentElement();
if (contentEl) {
contentEl.id = "booking-summary";
contentEl.append(summaryEl);
dialog.element.setAttribute("aria-describedby", "booking-summary");
}
const render = (): void => {
status.textContent = totalText(s);
range.textContent = rangeText(s);
summaryEl.textContent = summary(s);
const eligible = new Set(eligibleRooms(s).map((room) => room.value));
for (const room of ROOMS) eligible.has(room.value) ? radios.enableOption(room.value) : radios.disableOption(room.value);
if (radios.getValue() !== (s.room || null)) radios.setValue(s.room || null);
};
checkIn.on("change", ({ iso }) => {
s = withDates(s, iso, s.checkOut);
checkOut.setValue(s.checkOut);
checkOut.setMinDate(s.checkIn);
render();
});
checkOut.on("change", ({ iso }) => { s = withDates(s, s.checkIn, iso); render(); });
arrival.on("input", ({ value }) => { s = { ...s, arrivalTime: value }; arrival.setError(false); });
arrival.on("change", ({ value }) => {
const time = normalizeTime(value);
if (time) { s = { ...s, arrivalTime: time }; arrival.setValue(time); arrival.setError(false); }
else arrival.setError(true, "Enter a valid time");
});
arrival.on("trailing", () => {
const time = normalizeTime(s.arrivalTime);
timePicker.setValue(time ?? "15:00");
timePicker.open();
});
timePicker.on("change", ({ value }) => { s = { ...s, arrivalTime: value }; arrival.setValue(value); arrival.setError(false); });
adults.on("change", ({ value }) => { s = { ...s, adults: value ?? s.adults }; render(); });
children.on("change", ({ value }) => { s = { ...s, children: value ?? s.children }; render(); });
radios.on("change", ({ value }) => { s = { ...s, room: value ?? "" }; render(); });
slider.on("input", ({ value, secondValue }) => { s = withPrice(s, value, secondValue ?? s.priceMax); render(); });
nameField.on("input", ({ value }) => { s = { ...s, name: value }; nameField.setError(false); });
emailField.on("input", ({ value }) => { s = { ...s, email: value }; emailField.setError(false); });
const actions = Object.assign(document.createElement("footer"), { className: "booking__actions" });
const book = createButton({ text: "Book" });
book.on("click", () => {
const errors = validate(s);
nameField.setError(Boolean(errors.name), errors.name);
emailField.setError(Boolean(errors.email), errors.email);
arrival.setError(Boolean(errors.arrivalTime), errors.arrivalTime);
if (!errors.name && !errors.email && !errors.arrivalTime && roomOf(s)) { render(); dialog.open(); }
});
actions.append(book.element);
section.append(intro, grid, roomGroup, extrasGroup, priceGroup, status, actions, timePicker.element);
app.append(section);
render();
// The state every variant of this example shares, and how it is described.
export interface Booking {
checkIn: string;
checkOut: string;
arrivalTime: string;
adults: string;
children: string;
room: string;
breakfast: boolean;
parking: boolean;
lateCheckout: boolean;
priceMin: number;
priceMax: number;
name: string;
email: string;
}
export const DEFAULTS: Booking = {
checkIn: "2027-04-10",
checkOut: "2027-04-12",
arrivalTime: "15:00",
adults: "2",
children: "0",
room: "double",
breakfast: false,
parking: false,
lateCheckout: false,
priceMin: 80,
priceMax: 240,
name: "",
email: "",
};
export const ROOMS = [
{ value: "standard", label: "Standard room", rate: 95 },
{ value: "double", label: "Double room", rate: 120 },
{ value: "family", label: "Family room", rate: 155 },
{ value: "suite", label: "Suite", rate: 210 },
] as const;
export const EXTRAS = [
{ key: "breakfast", label: "Breakfast", price: 18, unit: "a night" },
{ key: "parking", label: "Parking", price: 12, unit: "a night" },
{ key: "lateCheckout", label: "Late checkout", price: 25, unit: "once" },
] as const;
export type ExtraKey = (typeof EXTRAS)[number]["key"];
export const ADULT_OPTIONS = ["1", "2", "3", "4"];
export const CHILD_OPTIONS = ["0", "1", "2", "3"];
export const CLOCK_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M520-496v-144q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v159q0 8 3 15.5t9 13.5l132 132q11 11 28 11t28-11q11-11 11-28t-11-28L520-496ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0 320q133 0 226.5-93.5T800-480q0-133-93.5-226.5T480-800q-133 0-226.5 93.5T160-480q0 133 93.5 226.5T480-160Z"/></svg>`;
const dayMs = 86_400_000;
const parseDay = (iso: string): number => Date.parse(`${iso}T00:00:00Z`);
/** Whole nights between the dates, at least one: check-out is never before check-in. */
export const nights = (s: Booking): number => {
const diff = Math.round((parseDay(s.checkOut) - parseDay(s.checkIn)) / dayMs);
return Number.isFinite(diff) ? Math.max(1, diff) : 1;
};
/** Check-out cannot be before check-in: an earlier date moves to check-in. */
export const withDates = (s: Booking, checkIn: string, checkOut: string): Booking => ({
...s,
checkIn,
checkOut: parseDay(checkOut) < parseDay(checkIn) ? checkIn : checkOut,
});
/** Rooms whose nightly rate sits inside the chosen price range. */
export const eligibleRooms = (s: Booking) => ROOMS.filter((room) => room.rate >= s.priceMin && room.rate <= s.priceMax);
export const roomOf = (s: Booking) => eligibleRooms(s).find((room) => room.value === s.room) ?? null;
/** A new price range keeps the choice inside it: an excluded room moves to the first eligible one, or to none. */
export const withPrice = (s: Booking, priceMin: number, priceMax: number): Booking => {
const next = { ...s, priceMin, priceMax };
if (!roomOf(next)) next.room = eligibleRooms(next)[0]?.value ?? "";
return next;
};
export const total = (s: Booking): number => {
const room = roomOf(s);
if (!room) return 0;
const count = nights(s);
let sum = count * room.rate;
if (s.breakfast) sum += count * 18;
if (s.parking) sum += count * 12;
if (s.lateCheckout) sum += 25;
return sum;
};
export const money = (value: number): string => `$${value}`;
export const rangeText = (s: Booking): string => `${money(s.priceMin)}–${money(s.priceMax)} a night`;
export const totalText = (s: Booking): string =>
roomOf(s)
? `Estimated total ${money(total(s))} for ${nights(s)} ${nights(s) === 1 ? "night" : "nights"}`
: "No rooms in this price range";
export const summary = (s: Booking): string => {
const room = roomOf(s);
if (!room) return "No rooms in this price range";
const extras = EXTRAS.filter((extra) => s[extra.key]).map((extra) => extra.label);
return (
`${room.label}, ${nights(s)} ${nights(s) === 1 ? "night" : "nights"} · Check-in ${s.checkIn}, check-out ${s.checkOut} · ` +
`Arrival ${s.arrivalTime} · ${s.adults} ${s.adults === "1" ? "adult" : "adults"}, ${s.children} ${s.children === "1" ? "child" : "children"}` +
`${extras.length ? ` · ${extras.join(", ")}` : ""} · ${totalText(s)}`
);
};
/** A typed time, normalized to HH:MM, or null when it is not a 24-hour time. */
export const normalizeTime = (text: string): string | null => {
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text.trim());
if (!match) return null;
const hour = Number(match[1]);
return hour <= 23 ? `${String(hour).padStart(2, "0")}:${match[2]}` : null;
};
export interface BookingErrors { name?: string; email?: string; arrivalTime?: string }
export const validate = (s: Booking): BookingErrors => {
const errors: BookingErrors = {};
if (!s.name.trim()) errors.name = "Enter your name";
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email.trim())) errors.email = "Enter a valid email address";
if (!normalizeTime(s.arrivalTime)) errors.arrivalTime = "Enter a valid time";
return errors;
};
// Web components: the elements themselves, no framework.
import "material/elements/css";
import { defineAll } from "material/elements";
import { ADULT_OPTIONS, CHILD_OPTIONS, CLOCK_ICON, DEFAULTS, EXTRAS, ROOMS, eligibleRooms, normalizeTime, rangeText, roomOf, summary, totalText, validate, withDates, withPrice, type Booking } from "./shared";
defineAll();
let s: Booking = { ...DEFAULTS };
const app = document.getElementById("app")!;
app.innerHTML = `
<section class="booking">
<m-dialog id="dialog" headline="Confirm booking">
<p id="dialog-summary"></p>
<m-button slot="actions" variant="text" id="cancel">Cancel</m-button>
<m-button slot="actions" variant="text" id="confirm">Confirm booking</m-button>
</m-dialog>
<div class="booking__intro">
<h1 class="booking__title mtrl-headline-small">Book a stay</h1>
<p class="booking__lede mtrl-body-medium">Choose dates, guests and a room. The total updates as you go.</p>
</div>
<div class="booking__grid">
<m-datepicker id="check-in" label="Check-in" variant="modal" close-on-select date-format="YYYY-MM-DD" value="${s.checkIn}"></m-datepicker>
<m-datepicker id="check-out" label="Check-out" variant="modal" close-on-select date-format="YYYY-MM-DD" min="${s.checkIn}" value="${s.checkOut}"></m-datepicker>
<m-text-field id="arrival" label="Arrival time" value="${s.arrivalTime}" supporting-text="24-hour time" trailing-icon-label="Choose time"></m-text-field>
<m-text-field id="name" label="Name" supporting-text="Required"></m-text-field>
<m-select id="adults" label="Adults" value="${s.adults}">${ADULT_OPTIONS.map((n) => `<m-select-option value="${n}">${n}</m-select-option>`).join("")}</m-select>
<m-select id="children" label="Children" value="${s.children}">${CHILD_OPTIONS.map((n) => `<m-select-option value="${n}">${n}</m-select-option>`).join("")}</m-select>
<m-text-field id="email" label="Email" type="email" supporting-text="Required"></m-text-field>
</div>
<div class="booking__group">
<p class="booking__label mtrl-title-small">Room type</p>
<m-radios id="room" aria-label="Room type" value="${s.room}">${ROOMS.map((room) => `<m-radio value="${room.value}">${room.label} — $${room.rate} a night</m-radio>`).join("")}</m-radios>
</div>
<div class="booking__group" role="group" aria-labelledby="extras-label">
<p class="booking__label mtrl-title-small" id="extras-label">Extras</p>
${EXTRAS.map((extra) => `<m-checkbox id="${extra.key}">${extra.label} — $${extra.price} ${extra.unit}</m-checkbox>`).join("")}
</div>
<div class="booking__group">
<p class="booking__label mtrl-title-small">Price range</p>
<m-slider id="price" range show-value min="50" max="300" step="10" value="${s.priceMin}" second-value="${s.priceMax}" aria-label="Price range"></m-slider>
<p class="booking__range mtrl-body-medium" id="range"></p>
</div>
<output class="booking__total mtrl-body-medium" role="status"></output>
<footer class="booking__actions"><m-button id="book">Book</m-button></footer>
<m-timepicker id="timepicker" label="Arrival time" value="${s.arrivalTime}" format="24h"></m-timepicker>
<m-snackbar id="snackbar" message="Booking confirmed"></m-snackbar>
</section>`;
type Host = HTMLElement & { value: string; checked: boolean; show(): void; close(): void };
const $ = <T extends HTMLElement = Host>(id: string) => document.getElementById(id) as T;
const total = app.querySelector("output")!;
const arrival = $<HTMLElement & { value: string }>("arrival");
arrival.setAttribute("trailing-icon", CLOCK_ICON);
const detail = <T,>(event: Event): T => (event as CustomEvent<T>).detail;
const render = (): void => {
total.textContent = totalText(s);
$("range").textContent = rangeText(s);
$("dialog-summary").textContent = summary(s);
const eligible = new Set<string>(eligibleRooms(s).map((room) => room.value));
for (const radio of app.querySelectorAll("m-radio")) {
if (eligible.has(radio.getAttribute("value") ?? "")) radio.removeAttribute("disabled");
else radio.setAttribute("disabled", "");
}
const radios = $("room");
if (radios.value !== s.room) radios.value = s.room;
};
const setError = (id: string, message: string | undefined, fallback: string): void => {
const field = $(id);
if (message) { field.setAttribute("error", ""); field.setAttribute("supporting-text", message); }
else { field.removeAttribute("error"); field.setAttribute("supporting-text", fallback); }
};
$("check-in").addEventListener("change", (event) => {
s = withDates(s, detail<{ value: string }>(event).value, s.checkOut);
const out = $("check-out");
out.value = s.checkOut;
out.setAttribute("min", s.checkIn);
render();
});
$("check-out").addEventListener("change", (event) => { s = withDates(s, s.checkIn, detail<{ value: string }>(event).value); render(); });
arrival.addEventListener("input", (event) => { s = { ...s, arrivalTime: detail<{ value: string }>(event).value }; setError("arrival", undefined, "24-hour time"); });
arrival.addEventListener("change", (event) => {
const time = normalizeTime(detail<{ value: string }>(event).value);
if (time) { s = { ...s, arrivalTime: time }; arrival.value = time; setError("arrival", undefined, "24-hour time"); }
else setError("arrival", "Enter a valid time", "24-hour time");
});
arrival.addEventListener("trailing", () => {
const picker = $("timepicker");
picker.value = normalizeTime(s.arrivalTime) ?? "15:00";
picker.show();
});
$("timepicker").addEventListener("change", (event) => {
s = { ...s, arrivalTime: detail<{ value: string }>(event).value };
arrival.value = s.arrivalTime;
setError("arrival", undefined, "24-hour time");
});
$("adults").addEventListener("change", (event) => { s = { ...s, adults: detail<{ value: string }>(event).value }; render(); });
$("children").addEventListener("change", (event) => { s = { ...s, children: detail<{ value: string }>(event).value }; render(); });
$("room").addEventListener("change", (event) => { s = { ...s, room: detail<{ value: string }>(event).value }; render(); });
for (const extra of EXTRAS) {
$(extra.key).addEventListener("change", (event) => { s = { ...s, [extra.key]: detail<{ checked: boolean }>(event).checked }; render(); });
}
$("price").addEventListener("input", (event) => {
const value = detail<{ value: number; secondValue?: number }>(event);
s = withPrice(s, value.value, value.secondValue ?? s.priceMax);
render();
});
$("name").addEventListener("input", (event) => { s = { ...s, name: detail<{ value: string }>(event).value }; setError("name", undefined, "Required"); });
$("email").addEventListener("input", (event) => { s = { ...s, email: detail<{ value: string }>(event).value }; setError("email", undefined, "Required"); });
$("book").addEventListener("click", () => {
const errors = validate(s);
setError("name", errors.name, "Required");
setError("email", errors.email, "Required");
setError("arrival", errors.arrivalTime, "24-hour time");
if (!errors.name && !errors.email && !errors.arrivalTime && roomOf(s)) { render(); $("dialog").show(); }
});
$("cancel").addEventListener("click", () => $("dialog").close());
$("confirm").addEventListener("click", () => { $("dialog").close(); $("snackbar").show(); });
render();
// The state every variant of this example shares, and how it is described.
export interface Booking {
checkIn: string;
checkOut: string;
arrivalTime: string;
adults: string;
children: string;
room: string;
breakfast: boolean;
parking: boolean;
lateCheckout: boolean;
priceMin: number;
priceMax: number;
name: string;
email: string;
}
export const DEFAULTS: Booking = {
checkIn: "2027-04-10",
checkOut: "2027-04-12",
arrivalTime: "15:00",
adults: "2",
children: "0",
room: "double",
breakfast: false,
parking: false,
lateCheckout: false,
priceMin: 80,
priceMax: 240,
name: "",
email: "",
};
export const ROOMS = [
{ value: "standard", label: "Standard room", rate: 95 },
{ value: "double", label: "Double room", rate: 120 },
{ value: "family", label: "Family room", rate: 155 },
{ value: "suite", label: "Suite", rate: 210 },
] as const;
export const EXTRAS = [
{ key: "breakfast", label: "Breakfast", price: 18, unit: "a night" },
{ key: "parking", label: "Parking", price: 12, unit: "a night" },
{ key: "lateCheckout", label: "Late checkout", price: 25, unit: "once" },
] as const;
export type ExtraKey = (typeof EXTRAS)[number]["key"];
export const ADULT_OPTIONS = ["1", "2", "3", "4"];
export const CHILD_OPTIONS = ["0", "1", "2", "3"];
export const CLOCK_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M520-496v-144q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v159q0 8 3 15.5t9 13.5l132 132q11 11 28 11t28-11q11-11 11-28t-11-28L520-496ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0 320q133 0 226.5-93.5T800-480q0-133-93.5-226.5T480-800q-133 0-226.5 93.5T160-480q0 133 93.5 226.5T480-160Z"/></svg>`;
const dayMs = 86_400_000;
const parseDay = (iso: string): number => Date.parse(`${iso}T00:00:00Z`);
/** Whole nights between the dates, at least one: check-out is never before check-in. */
export const nights = (s: Booking): number => {
const diff = Math.round((parseDay(s.checkOut) - parseDay(s.checkIn)) / dayMs);
return Number.isFinite(diff) ? Math.max(1, diff) : 1;
};
/** Check-out cannot be before check-in: an earlier date moves to check-in. */
export const withDates = (s: Booking, checkIn: string, checkOut: string): Booking => ({
...s,
checkIn,
checkOut: parseDay(checkOut) < parseDay(checkIn) ? checkIn : checkOut,
});
/** Rooms whose nightly rate sits inside the chosen price range. */
export const eligibleRooms = (s: Booking) => ROOMS.filter((room) => room.rate >= s.priceMin && room.rate <= s.priceMax);
export const roomOf = (s: Booking) => eligibleRooms(s).find((room) => room.value === s.room) ?? null;
/** A new price range keeps the choice inside it: an excluded room moves to the first eligible one, or to none. */
export const withPrice = (s: Booking, priceMin: number, priceMax: number): Booking => {
const next = { ...s, priceMin, priceMax };
if (!roomOf(next)) next.room = eligibleRooms(next)[0]?.value ?? "";
return next;
};
export const total = (s: Booking): number => {
const room = roomOf(s);
if (!room) return 0;
const count = nights(s);
let sum = count * room.rate;
if (s.breakfast) sum += count * 18;
if (s.parking) sum += count * 12;
if (s.lateCheckout) sum += 25;
return sum;
};
export const money = (value: number): string => `$${value}`;
export const rangeText = (s: Booking): string => `${money(s.priceMin)}–${money(s.priceMax)} a night`;
export const totalText = (s: Booking): string =>
roomOf(s)
? `Estimated total ${money(total(s))} for ${nights(s)} ${nights(s) === 1 ? "night" : "nights"}`
: "No rooms in this price range";
export const summary = (s: Booking): string => {
const room = roomOf(s);
if (!room) return "No rooms in this price range";
const extras = EXTRAS.filter((extra) => s[extra.key]).map((extra) => extra.label);
return (
`${room.label}, ${nights(s)} ${nights(s) === 1 ? "night" : "nights"} · Check-in ${s.checkIn}, check-out ${s.checkOut} · ` +
`Arrival ${s.arrivalTime} · ${s.adults} ${s.adults === "1" ? "adult" : "adults"}, ${s.children} ${s.children === "1" ? "child" : "children"}` +
`${extras.length ? ` · ${extras.join(", ")}` : ""} · ${totalText(s)}`
);
};
/** A typed time, normalized to HH:MM, or null when it is not a 24-hour time. */
export const normalizeTime = (text: string): string | null => {
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text.trim());
if (!match) return null;
const hour = Number(match[1]);
return hour <= 23 ? `${String(hour).padStart(2, "0")}:${match[2]}` : null;
};
export interface BookingErrors { name?: string; email?: string; arrivalTime?: string }
export const validate = (s: Booking): BookingErrors => {
const errors: BookingErrors = {};
if (!s.name.trim()) errors.name = "Enter your name";
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email.trim())) errors.email = "Enter a valid email address";
if (!normalizeTime(s.arrivalTime)) errors.arrivalTime = "Enter a valid time";
return errors;
};
// React: material/react wraps the same elements.
import { useState } from "react";
import { Button, Checkbox, Datepicker, Dialog, Radio, Radios, Select, SelectOption, Slider, Snackbar, TextField, Timepicker } from "material/react";
import { ADULT_OPTIONS, CHILD_OPTIONS, CLOCK_ICON, DEFAULTS, EXTRAS, ROOMS, eligibleRooms, normalizeTime, rangeText, roomOf, summary, totalText, validate, withDates, withPrice, type Booking, type BookingErrors } from "./shared";
export default function Booking() {
const [s, setS] = useState<Booking>(DEFAULTS);
const [errors, setErrors] = useState<BookingErrors>({});
const [dialogOpen, setDialogOpen] = useState(false);
const [confirmed, setConfirmed] = useState(false);
const [timeOpen, setTimeOpen] = useState(false);
const update = (patch: Partial<Booking>) => setS((prev) => ({ ...prev, ...patch }));
const eligible = new Set(eligibleRooms(s).map((room) => room.value));
const book = () => {
const next = validate(s);
setErrors(next);
if (!next.name && !next.email && !next.arrivalTime && roomOf(s)) setDialogOpen(true);
};
const commitTime = (value: string) => {
const time = normalizeTime(value);
if (time) { update({ arrivalTime: time }); setErrors((prev) => ({ ...prev, arrivalTime: undefined })); }
else setErrors((prev) => ({ ...prev, arrivalTime: "Enter a valid time" }));
};
const openPicker = () => {
const time = normalizeTime(s.arrivalTime);
if (time) update({ arrivalTime: time });
setTimeOpen(true);
};
return (
<section className="booking">
<Dialog headline="Confirm booking" open={dialogOpen} onClose={() => setDialogOpen(false)}
actions={<>
<Button variant="text" onClick={() => setDialogOpen(false)}>Cancel</Button>
<Button variant="text" onClick={() => { setDialogOpen(false); setConfirmed(true); }}>Confirm booking</Button>
</>}>
<p>{summary(s)}</p>
</Dialog>
<div className="booking__intro">
<h1 className="booking__title mtrl-headline-small">Book a stay</h1>
<p className="booking__lede mtrl-body-medium">Choose dates, guests and a room. The total updates as you go.</p>
</div>
<div className="booking__grid">
<Datepicker label="Check-in" variant="modal" closeOnSelect dateFormat="YYYY-MM-DD" value={s.checkIn}
onChange={(e) => setS((prev) => withDates(prev, e.detail.value, prev.checkOut))} />
<Datepicker label="Check-out" variant="modal" closeOnSelect dateFormat="YYYY-MM-DD" min={s.checkIn} value={s.checkOut}
onChange={(e) => setS((prev) => withDates(prev, prev.checkIn, e.detail.value))} />
<TextField label="Arrival time" value={s.arrivalTime} trailingIcon={CLOCK_ICON} trailingIconLabel="Choose time"
supportingText={errors.arrivalTime ?? "24-hour time"} error={Boolean(errors.arrivalTime)}
onInput={(e) => { update({ arrivalTime: e.detail.value }); setErrors((prev) => ({ ...prev, arrivalTime: undefined })); }}
onChange={(e) => commitTime(e.detail.value)} onTrailing={openPicker} />
<TextField label="Name" value={s.name} supportingText={errors.name ?? "Required"} error={Boolean(errors.name)}
onInput={(e) => { update({ name: e.detail.value }); setErrors((prev) => ({ ...prev, name: undefined })); }} />
<Select label="Adults" value={s.adults} onChange={(e) => update({ adults: e.detail.value ?? s.adults })}>
{ADULT_OPTIONS.map((n) => <SelectOption key={n} value={n}>{n}</SelectOption>)}
</Select>
<Select label="Children" value={s.children} onChange={(e) => update({ children: e.detail.value ?? s.children })}>
{CHILD_OPTIONS.map((n) => <SelectOption key={n} value={n}>{n}</SelectOption>)}
</Select>
<TextField label="Email" type="email" value={s.email} supportingText={errors.email ?? "Required"} error={Boolean(errors.email)}
onInput={(e) => { update({ email: e.detail.value }); setErrors((prev) => ({ ...prev, email: undefined })); }} />
</div>
<div className="booking__group">
<p className="booking__label mtrl-title-small">Room type</p>
<Radios aria-label="Room type" value={s.room} onChange={(e) => update({ room: e.detail.value ?? s.room })}>
{ROOMS.map((room) => <Radio key={room.value} value={room.value} disabled={!eligible.has(room.value)}>{`${room.label} — $${room.rate} a night`}</Radio>)}
</Radios>
</div>
<div className="booking__group" role="group" aria-labelledby="extras-label">
<p className="booking__label mtrl-title-small" id="extras-label">Extras</p>
{EXTRAS.map((extra) => (
<Checkbox key={extra.key} checked={s[extra.key]} onChange={(e) => update({ [extra.key]: e.detail.checked })}>
{`${extra.label} — $${extra.price} ${extra.unit}`}
</Checkbox>
))}
</div>
<div className="booking__group">
<p className="booking__label mtrl-title-small">Price range</p>
<Slider range showValue min={50} max={300} step={10} value={s.priceMin} secondValue={s.priceMax} aria-label="Price range"
onInput={(e) => setS((prev) => withPrice(prev, e.detail.value, e.detail.secondValue ?? prev.priceMax))} />
<p className="booking__range mtrl-body-medium">{rangeText(s)}</p>
</div>
<output className="booking__total mtrl-body-medium" role="status">{totalText(s)}</output>
<footer className="booking__actions"><Button onClick={book}>Book</Button></footer>
<Timepicker label="Arrival time" format="24h" value={normalizeTime(s.arrivalTime) ?? "15:00"} open={timeOpen}
onChange={(e) => { update({ arrivalTime: e.detail.value }); setErrors((prev) => ({ ...prev, arrivalTime: undefined })); }} onClose={() => setTimeOpen(false)} />
<Snackbar message="Booking confirmed" open={confirmed} onClose={() => setConfirmed(false)} />
</section>
);
}
// The state every variant of this example shares, and how it is described.
export interface Booking {
checkIn: string;
checkOut: string;
arrivalTime: string;
adults: string;
children: string;
room: string;
breakfast: boolean;
parking: boolean;
lateCheckout: boolean;
priceMin: number;
priceMax: number;
name: string;
email: string;
}
export const DEFAULTS: Booking = {
checkIn: "2027-04-10",
checkOut: "2027-04-12",
arrivalTime: "15:00",
adults: "2",
children: "0",
room: "double",
breakfast: false,
parking: false,
lateCheckout: false,
priceMin: 80,
priceMax: 240,
name: "",
email: "",
};
export const ROOMS = [
{ value: "standard", label: "Standard room", rate: 95 },
{ value: "double", label: "Double room", rate: 120 },
{ value: "family", label: "Family room", rate: 155 },
{ value: "suite", label: "Suite", rate: 210 },
] as const;
export const EXTRAS = [
{ key: "breakfast", label: "Breakfast", price: 18, unit: "a night" },
{ key: "parking", label: "Parking", price: 12, unit: "a night" },
{ key: "lateCheckout", label: "Late checkout", price: 25, unit: "once" },
] as const;
export type ExtraKey = (typeof EXTRAS)[number]["key"];
export const ADULT_OPTIONS = ["1", "2", "3", "4"];
export const CHILD_OPTIONS = ["0", "1", "2", "3"];
export const CLOCK_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M520-496v-144q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v159q0 8 3 15.5t9 13.5l132 132q11 11 28 11t28-11q11-11 11-28t-11-28L520-496ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0 320q133 0 226.5-93.5T800-480q0-133-93.5-226.5T480-800q-133 0-226.5 93.5T160-480q0 133 93.5 226.5T480-160Z"/></svg>`;
const dayMs = 86_400_000;
const parseDay = (iso: string): number => Date.parse(`${iso}T00:00:00Z`);
/** Whole nights between the dates, at least one: check-out is never before check-in. */
export const nights = (s: Booking): number => {
const diff = Math.round((parseDay(s.checkOut) - parseDay(s.checkIn)) / dayMs);
return Number.isFinite(diff) ? Math.max(1, diff) : 1;
};
/** Check-out cannot be before check-in: an earlier date moves to check-in. */
export const withDates = (s: Booking, checkIn: string, checkOut: string): Booking => ({
...s,
checkIn,
checkOut: parseDay(checkOut) < parseDay(checkIn) ? checkIn : checkOut,
});
/** Rooms whose nightly rate sits inside the chosen price range. */
export const eligibleRooms = (s: Booking) => ROOMS.filter((room) => room.rate >= s.priceMin && room.rate <= s.priceMax);
export const roomOf = (s: Booking) => eligibleRooms(s).find((room) => room.value === s.room) ?? null;
/** A new price range keeps the choice inside it: an excluded room moves to the first eligible one, or to none. */
export const withPrice = (s: Booking, priceMin: number, priceMax: number): Booking => {
const next = { ...s, priceMin, priceMax };
if (!roomOf(next)) next.room = eligibleRooms(next)[0]?.value ?? "";
return next;
};
export const total = (s: Booking): number => {
const room = roomOf(s);
if (!room) return 0;
const count = nights(s);
let sum = count * room.rate;
if (s.breakfast) sum += count * 18;
if (s.parking) sum += count * 12;
if (s.lateCheckout) sum += 25;
return sum;
};
export const money = (value: number): string => `$${value}`;
export const rangeText = (s: Booking): string => `${money(s.priceMin)}–${money(s.priceMax)} a night`;
export const totalText = (s: Booking): string =>
roomOf(s)
? `Estimated total ${money(total(s))} for ${nights(s)} ${nights(s) === 1 ? "night" : "nights"}`
: "No rooms in this price range";
export const summary = (s: Booking): string => {
const room = roomOf(s);
if (!room) return "No rooms in this price range";
const extras = EXTRAS.filter((extra) => s[extra.key]).map((extra) => extra.label);
return (
`${room.label}, ${nights(s)} ${nights(s) === 1 ? "night" : "nights"} · Check-in ${s.checkIn}, check-out ${s.checkOut} · ` +
`Arrival ${s.arrivalTime} · ${s.adults} ${s.adults === "1" ? "adult" : "adults"}, ${s.children} ${s.children === "1" ? "child" : "children"}` +
`${extras.length ? ` · ${extras.join(", ")}` : ""} · ${totalText(s)}`
);
};
/** A typed time, normalized to HH:MM, or null when it is not a 24-hour time. */
export const normalizeTime = (text: string): string | null => {
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text.trim());
if (!match) return null;
const hour = Number(match[1]);
return hour <= 23 ? `${String(hour).padStart(2, "0")}:${match[2]}` : null;
};
export interface BookingErrors { name?: string; email?: string; arrivalTime?: string }
export const validate = (s: Booking): BookingErrors => {
const errors: BookingErrors = {};
if (!s.name.trim()) errors.name = "Enter your name";
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email.trim())) errors.email = "Enter a valid email address";
if (!normalizeTime(s.arrivalTime)) errors.arrivalTime = "Enter a valid time";
return errors;
};
// Vue: material/vue wraps the same elements; their live state is paired with its event.
import { defineComponent, reactive, ref } from "vue";
import { MButton, MCheckbox, MDatepicker, MDialog, MRadio, MRadios, MSelect, MSelectOption, MSlider, MSnackbar, MTextField, MTimepicker } from "material/vue";
import { ADULT_OPTIONS, CHILD_OPTIONS, CLOCK_ICON, DEFAULTS, EXTRAS, ROOMS, eligibleRooms, normalizeTime, rangeText, roomOf, summary, totalText, validate, withDates, withPrice, type Booking, type BookingErrors } from "./shared";
export default defineComponent({
components: { MButton, MCheckbox, MDatepicker, MDialog, MRadio, MRadios, MSelect, MSelectOption, MSlider, MSnackbar, MTextField, MTimepicker },
setup() {
const s = reactive<Booking>({ ...DEFAULTS });
const errors = reactive<BookingErrors>({});
const dialogOpen = ref(false);
const confirmed = ref(false);
const timeOpen = ref(false);
const setDates = (checkIn: string, checkOut: string) => Object.assign(s, withDates({ ...s }, checkIn, checkOut));
const book = () => {
const next = validate(s);
errors.name = next.name;
errors.email = next.email;
errors.arrivalTime = next.arrivalTime;
if (!next.name && !next.email && !next.arrivalTime && roomOf(s)) dialogOpen.value = true;
};
const confirm = () => { dialogOpen.value = false; confirmed.value = true; };
const commitTime = (value: string) => {
const time = normalizeTime(value);
if (time) { s.arrivalTime = time; errors.arrivalTime = undefined; }
else errors.arrivalTime = "Enter a valid time";
};
const openPicker = () => {
const time = normalizeTime(s.arrivalTime);
if (time) s.arrivalTime = time;
timeOpen.value = true;
};
return { s, errors, dialogOpen, confirmed, timeOpen, setDates, book, confirm, commitTime, openPicker, totalText, summary, rangeText, normalizeTime, eligibleRooms, withPrice, ROOMS, EXTRAS, ADULT_OPTIONS, CHILD_OPTIONS, CLOCK_ICON };
},
template: `
<section class="booking">
<MDialog headline="Confirm booking" :open="dialogOpen" @close="dialogOpen = false">
<p>{{ summary(s) }}</p>
<template #actions>
<MButton variant="text" @click="dialogOpen = false">Cancel</MButton>
<MButton variant="text" @click="confirm">Confirm booking</MButton>
</template>
</MDialog>
<div class="booking__intro">
<h1 class="booking__title mtrl-headline-small">Book a stay</h1>
<p class="booking__lede mtrl-body-medium">Choose dates, guests and a room. The total updates as you go.</p>
</div>
<div class="booking__grid">
<MDatepicker label="Check-in" variant="modal" close-on-select date-format="YYYY-MM-DD" :value="s.checkIn" @change="setDates($event.detail.value, s.checkOut)" />
<MDatepicker label="Check-out" variant="modal" close-on-select date-format="YYYY-MM-DD" :min="s.checkIn" :value="s.checkOut" @change="setDates(s.checkIn, $event.detail.value)" />
<MTextField label="Arrival time" :value="s.arrivalTime" :trailing-icon="CLOCK_ICON" trailing-icon-label="Choose time" :supporting-text="errors.arrivalTime ?? '24-hour time'" :error="Boolean(errors.arrivalTime)" @input="s.arrivalTime = $event.detail.value; errors.arrivalTime = undefined" @change="commitTime($event.detail.value)" @trailing="openPicker" />
<MTextField label="Name" :value="s.name" :supporting-text="errors.name ?? 'Required'" :error="Boolean(errors.name)" @input="s.name = $event.detail.value; errors.name = undefined" />
<MSelect label="Adults" :value="s.adults" @change="s.adults = $event.detail.value ?? s.adults">
<MSelectOption v-for="n in ADULT_OPTIONS" :key="n" :value="n">{{ n }}</MSelectOption>
</MSelect>
<MSelect label="Children" :value="s.children" @change="s.children = $event.detail.value ?? s.children">
<MSelectOption v-for="n in CHILD_OPTIONS" :key="n" :value="n">{{ n }}</MSelectOption>
</MSelect>
<MTextField label="Email" type="email" :value="s.email" :supporting-text="errors.email ?? 'Required'" :error="Boolean(errors.email)" @input="s.email = $event.detail.value; errors.email = undefined" />
</div>
<div class="booking__group">
<p class="booking__label mtrl-title-small">Room type</p>
<MRadios aria-label="Room type" :value="s.room" @change="s.room = $event.detail.value ?? s.room">
<MRadio v-for="room in ROOMS" :key="room.value" :value="room.value" :disabled="!eligibleRooms(s).some((r) => r.value === room.value)">{{ room.label }} — \${{ room.rate }} a night</MRadio>
</MRadios>
</div>
<div class="booking__group" role="group" aria-labelledby="extras-label">
<p class="booking__label mtrl-title-small" id="extras-label">Extras</p>
<MCheckbox v-for="extra in EXTRAS" :key="extra.key" :checked="s[extra.key]" @change="s[extra.key] = $event.detail.checked">{{ extra.label }} — \${{ extra.price }} {{ extra.unit }}</MCheckbox>
</div>
<div class="booking__group">
<p class="booking__label mtrl-title-small">Price range</p>
<MSlider range show-value :min="50" :max="300" :step="10" :value="s.priceMin" :second-value="s.priceMax" aria-label="Price range" @input="Object.assign(s, withPrice(s, $event.detail.value, $event.detail.secondValue ?? s.priceMax))" />
<p class="booking__range mtrl-body-medium">{{ rangeText(s) }}</p>
</div>
<output class="booking__total mtrl-body-medium" role="status">{{ totalText(s) }}</output>
<footer class="booking__actions"><MButton @click="book">Book</MButton></footer>
<MTimepicker label="Arrival time" format="24h" :value="normalizeTime(s.arrivalTime) ?? '15:00'" :open="timeOpen" @change="s.arrivalTime = $event.detail.value; errors.arrivalTime = undefined" @close="timeOpen = false" />
<MSnackbar message="Booking confirmed" :open="confirmed" @close="confirmed = false" />
</section>`,
});
// The state every variant of this example shares, and how it is described.
export interface Booking {
checkIn: string;
checkOut: string;
arrivalTime: string;
adults: string;
children: string;
room: string;
breakfast: boolean;
parking: boolean;
lateCheckout: boolean;
priceMin: number;
priceMax: number;
name: string;
email: string;
}
export const DEFAULTS: Booking = {
checkIn: "2027-04-10",
checkOut: "2027-04-12",
arrivalTime: "15:00",
adults: "2",
children: "0",
room: "double",
breakfast: false,
parking: false,
lateCheckout: false,
priceMin: 80,
priceMax: 240,
name: "",
email: "",
};
export const ROOMS = [
{ value: "standard", label: "Standard room", rate: 95 },
{ value: "double", label: "Double room", rate: 120 },
{ value: "family", label: "Family room", rate: 155 },
{ value: "suite", label: "Suite", rate: 210 },
] as const;
export const EXTRAS = [
{ key: "breakfast", label: "Breakfast", price: 18, unit: "a night" },
{ key: "parking", label: "Parking", price: 12, unit: "a night" },
{ key: "lateCheckout", label: "Late checkout", price: 25, unit: "once" },
] as const;
export type ExtraKey = (typeof EXTRAS)[number]["key"];
export const ADULT_OPTIONS = ["1", "2", "3", "4"];
export const CHILD_OPTIONS = ["0", "1", "2", "3"];
export const CLOCK_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M520-496v-144q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v159q0 8 3 15.5t9 13.5l132 132q11 11 28 11t28-11q11-11 11-28t-11-28L520-496ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0 320q133 0 226.5-93.5T800-480q0-133-93.5-226.5T480-800q-133 0-226.5 93.5T160-480q0 133 93.5 226.5T480-160Z"/></svg>`;
const dayMs = 86_400_000;
const parseDay = (iso: string): number => Date.parse(`${iso}T00:00:00Z`);
/** Whole nights between the dates, at least one: check-out is never before check-in. */
export const nights = (s: Booking): number => {
const diff = Math.round((parseDay(s.checkOut) - parseDay(s.checkIn)) / dayMs);
return Number.isFinite(diff) ? Math.max(1, diff) : 1;
};
/** Check-out cannot be before check-in: an earlier date moves to check-in. */
export const withDates = (s: Booking, checkIn: string, checkOut: string): Booking => ({
...s,
checkIn,
checkOut: parseDay(checkOut) < parseDay(checkIn) ? checkIn : checkOut,
});
/** Rooms whose nightly rate sits inside the chosen price range. */
export const eligibleRooms = (s: Booking) => ROOMS.filter((room) => room.rate >= s.priceMin && room.rate <= s.priceMax);
export const roomOf = (s: Booking) => eligibleRooms(s).find((room) => room.value === s.room) ?? null;
/** A new price range keeps the choice inside it: an excluded room moves to the first eligible one, or to none. */
export const withPrice = (s: Booking, priceMin: number, priceMax: number): Booking => {
const next = { ...s, priceMin, priceMax };
if (!roomOf(next)) next.room = eligibleRooms(next)[0]?.value ?? "";
return next;
};
export const total = (s: Booking): number => {
const room = roomOf(s);
if (!room) return 0;
const count = nights(s);
let sum = count * room.rate;
if (s.breakfast) sum += count * 18;
if (s.parking) sum += count * 12;
if (s.lateCheckout) sum += 25;
return sum;
};
export const money = (value: number): string => `$${value}`;
export const rangeText = (s: Booking): string => `${money(s.priceMin)}–${money(s.priceMax)} a night`;
export const totalText = (s: Booking): string =>
roomOf(s)
? `Estimated total ${money(total(s))} for ${nights(s)} ${nights(s) === 1 ? "night" : "nights"}`
: "No rooms in this price range";
export const summary = (s: Booking): string => {
const room = roomOf(s);
if (!room) return "No rooms in this price range";
const extras = EXTRAS.filter((extra) => s[extra.key]).map((extra) => extra.label);
return (
`${room.label}, ${nights(s)} ${nights(s) === 1 ? "night" : "nights"} · Check-in ${s.checkIn}, check-out ${s.checkOut} · ` +
`Arrival ${s.arrivalTime} · ${s.adults} ${s.adults === "1" ? "adult" : "adults"}, ${s.children} ${s.children === "1" ? "child" : "children"}` +
`${extras.length ? ` · ${extras.join(", ")}` : ""} · ${totalText(s)}`
);
};
/** A typed time, normalized to HH:MM, or null when it is not a 24-hour time. */
export const normalizeTime = (text: string): string | null => {
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text.trim());
if (!match) return null;
const hour = Number(match[1]);
return hour <= 23 ? `${String(hour).padStart(2, "0")}:${match[2]}` : null;
};
export interface BookingErrors { name?: string; email?: string; arrivalTime?: string }
export const validate = (s: Booking): BookingErrors => {
const errors: BookingErrors = {};
if (!s.name.trim()) errors.name = "Enter your name";
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email.trim())) errors.email = "Enter a valid email address";
if (!normalizeTime(s.arrivalTime)) errors.arrivalTime = "Enter a valid time";
return errors;
};
<!-- Svelte: material/svelte wraps the same elements; bind: keeps their live state. -->
<script lang="ts">
import { Button, Checkbox, Datepicker, Dialog, Radio, Radios, Select, SelectOption, Slider, Snackbar, TextField, Timepicker } from "material/svelte";
import { ADULT_OPTIONS, CHILD_OPTIONS, CLOCK_ICON, DEFAULTS, EXTRAS, ROOMS, eligibleRooms, normalizeTime, rangeText, roomOf, summary, totalText, validate, withDates, withPrice, type BookingErrors } from "./shared";
let s = $state({ ...DEFAULTS });
let errors = $state<BookingErrors>({});
let dialogOpen = $state(false);
let confirmed = $state(false);
let timeOpen = $state(false);
const book = () => {
errors = validate(s);
if (!errors.name && !errors.email && !errors.arrivalTime && roomOf(s)) dialogOpen = true;
};
const confirm = () => { dialogOpen = false; confirmed = true; };
const commitTime = (value: string) => {
const time = normalizeTime(value);
if (time) { s.arrivalTime = time; errors = { ...errors, arrivalTime: undefined }; }
else errors = { ...errors, arrivalTime: "Enter a valid time" };
};
</script>
<section class="booking">
<Dialog headline="Confirm booking" open={dialogOpen} onclose={() => (dialogOpen = false)}>
<p>{summary(s)}</p>
{#snippet actions()}
<Button variant="text" onclick={() => (dialogOpen = false)}>Cancel</Button>
<Button variant="text" onclick={confirm}>Confirm booking</Button>
{/snippet}
</Dialog>
<div class="booking__intro">
<h1 class="booking__title mtrl-headline-small">Book a stay</h1>
<p class="booking__lede mtrl-body-medium">Choose dates, guests and a room. The total updates as you go.</p>
</div>
<div class="booking__grid">
<Datepicker label="Check-in" variant="modal" closeOnSelect dateFormat="YYYY-MM-DD" value={s.checkIn}
onchange={(e) => (s = withDates(s, e.detail.value, s.checkOut))} />
<Datepicker label="Check-out" variant="modal" closeOnSelect dateFormat="YYYY-MM-DD" min={s.checkIn} value={s.checkOut}
onchange={(e) => (s = withDates(s, s.checkIn, e.detail.value))} />
<TextField label="Arrival time" value={s.arrivalTime} trailingIcon={CLOCK_ICON} trailingIconLabel="Choose time"
supportingText={errors.arrivalTime ?? "24-hour time"} error={Boolean(errors.arrivalTime)}
oninput={(e) => { s.arrivalTime = e.detail.value; errors = { ...errors, arrivalTime: undefined }; }}
onchange={(e) => commitTime(e.detail.value)}
ontrailing={() => { const time = normalizeTime(s.arrivalTime); if (time) s.arrivalTime = time; timeOpen = true; }} />
<TextField label="Name" value={s.name} supportingText={errors.name ?? "Required"} error={Boolean(errors.name)}
oninput={(e) => { s.name = e.detail.value; errors = { ...errors, name: undefined }; }} />
<Select label="Adults" value={s.adults} onchange={(e) => (s.adults = e.detail.value ?? s.adults)}>
{#each ADULT_OPTIONS as n}<SelectOption value={n}>{n}</SelectOption>{/each}
</Select>
<Select label="Children" value={s.children} onchange={(e) => (s.children = e.detail.value ?? s.children)}>
{#each CHILD_OPTIONS as n}<SelectOption value={n}>{n}</SelectOption>{/each}
</Select>
<TextField label="Email" type="email" value={s.email} supportingText={errors.email ?? "Required"} error={Boolean(errors.email)}
oninput={(e) => { s.email = e.detail.value; errors = { ...errors, email: undefined }; }} />
</div>
<div class="booking__group">
<p class="booking__label mtrl-title-small">Room type</p>
<Radios aria-label="Room type" value={s.room} onchange={(e) => (s.room = e.detail.value ?? s.room)}>
{#each ROOMS as room}<Radio value={room.value} disabled={!eligibleRooms(s).some((r) => r.value === room.value)}>{room.label} — ${room.rate} a night</Radio>{/each}
</Radios>
</div>
<div class="booking__group" role="group" aria-labelledby="extras-label">
<p class="booking__label mtrl-title-small" id="extras-label">Extras</p>
{#each EXTRAS as extra}
<Checkbox checked={s[extra.key]} onchange={(e) => (s[extra.key] = e.detail.checked)}>{extra.label} — ${extra.price} {extra.unit}</Checkbox>
{/each}
</div>
<div class="booking__group">
<p class="booking__label mtrl-title-small">Price range</p>
<Slider range showValue min={50} max={300} step={10} value={s.priceMin} secondValue={s.priceMax} aria-label="Price range"
oninput={(e) => (s = withPrice(s, e.detail.value, e.detail.secondValue ?? s.priceMax))} />
<p class="booking__range mtrl-body-medium">{rangeText(s)}</p>
</div>
<output class="booking__total mtrl-body-medium" role="status">{totalText(s)}</output>
<footer class="booking__actions"><Button onclick={book}>Book</Button></footer>
<Timepicker label="Arrival time" format="24h" value={normalizeTime(s.arrivalTime) ?? "15:00"} open={timeOpen}
onchange={(e) => { s.arrivalTime = e.detail.value; errors = { ...errors, arrivalTime: undefined }; }} onclose={() => (timeOpen = false)} />
<Snackbar message="Booking confirmed" open={confirmed} onclose={() => (confirmed = false)} />
</section>
// The state every variant of this example shares, and how it is described.
export interface Booking {
checkIn: string;
checkOut: string;
arrivalTime: string;
adults: string;
children: string;
room: string;
breakfast: boolean;
parking: boolean;
lateCheckout: boolean;
priceMin: number;
priceMax: number;
name: string;
email: string;
}
export const DEFAULTS: Booking = {
checkIn: "2027-04-10",
checkOut: "2027-04-12",
arrivalTime: "15:00",
adults: "2",
children: "0",
room: "double",
breakfast: false,
parking: false,
lateCheckout: false,
priceMin: 80,
priceMax: 240,
name: "",
email: "",
};
export const ROOMS = [
{ value: "standard", label: "Standard room", rate: 95 },
{ value: "double", label: "Double room", rate: 120 },
{ value: "family", label: "Family room", rate: 155 },
{ value: "suite", label: "Suite", rate: 210 },
] as const;
export const EXTRAS = [
{ key: "breakfast", label: "Breakfast", price: 18, unit: "a night" },
{ key: "parking", label: "Parking", price: 12, unit: "a night" },
{ key: "lateCheckout", label: "Late checkout", price: 25, unit: "once" },
] as const;
export type ExtraKey = (typeof EXTRAS)[number]["key"];
export const ADULT_OPTIONS = ["1", "2", "3", "4"];
export const CHILD_OPTIONS = ["0", "1", "2", "3"];
export const CLOCK_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M520-496v-144q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v159q0 8 3 15.5t9 13.5l132 132q11 11 28 11t28-11q11-11 11-28t-11-28L520-496ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0 320q133 0 226.5-93.5T800-480q0-133-93.5-226.5T480-800q-133 0-226.5 93.5T160-480q0 133 93.5 226.5T480-160Z"/></svg>`;
const dayMs = 86_400_000;
const parseDay = (iso: string): number => Date.parse(`${iso}T00:00:00Z`);
/** Whole nights between the dates, at least one: check-out is never before check-in. */
export const nights = (s: Booking): number => {
const diff = Math.round((parseDay(s.checkOut) - parseDay(s.checkIn)) / dayMs);
return Number.isFinite(diff) ? Math.max(1, diff) : 1;
};
/** Check-out cannot be before check-in: an earlier date moves to check-in. */
export const withDates = (s: Booking, checkIn: string, checkOut: string): Booking => ({
...s,
checkIn,
checkOut: parseDay(checkOut) < parseDay(checkIn) ? checkIn : checkOut,
});
/** Rooms whose nightly rate sits inside the chosen price range. */
export const eligibleRooms = (s: Booking) => ROOMS.filter((room) => room.rate >= s.priceMin && room.rate <= s.priceMax);
export const roomOf = (s: Booking) => eligibleRooms(s).find((room) => room.value === s.room) ?? null;
/** A new price range keeps the choice inside it: an excluded room moves to the first eligible one, or to none. */
export const withPrice = (s: Booking, priceMin: number, priceMax: number): Booking => {
const next = { ...s, priceMin, priceMax };
if (!roomOf(next)) next.room = eligibleRooms(next)[0]?.value ?? "";
return next;
};
export const total = (s: Booking): number => {
const room = roomOf(s);
if (!room) return 0;
const count = nights(s);
let sum = count * room.rate;
if (s.breakfast) sum += count * 18;
if (s.parking) sum += count * 12;
if (s.lateCheckout) sum += 25;
return sum;
};
export const money = (value: number): string => `$${value}`;
export const rangeText = (s: Booking): string => `${money(s.priceMin)}–${money(s.priceMax)} a night`;
export const totalText = (s: Booking): string =>
roomOf(s)
? `Estimated total ${money(total(s))} for ${nights(s)} ${nights(s) === 1 ? "night" : "nights"}`
: "No rooms in this price range";
export const summary = (s: Booking): string => {
const room = roomOf(s);
if (!room) return "No rooms in this price range";
const extras = EXTRAS.filter((extra) => s[extra.key]).map((extra) => extra.label);
return (
`${room.label}, ${nights(s)} ${nights(s) === 1 ? "night" : "nights"} · Check-in ${s.checkIn}, check-out ${s.checkOut} · ` +
`Arrival ${s.arrivalTime} · ${s.adults} ${s.adults === "1" ? "adult" : "adults"}, ${s.children} ${s.children === "1" ? "child" : "children"}` +
`${extras.length ? ` · ${extras.join(", ")}` : ""} · ${totalText(s)}`
);
};
/** A typed time, normalized to HH:MM, or null when it is not a 24-hour time. */
export const normalizeTime = (text: string): string | null => {
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text.trim());
if (!match) return null;
const hour = Number(match[1]);
return hour <= 23 ? `${String(hour).padStart(2, "0")}:${match[2]}` : null;
};
export interface BookingErrors { name?: string; email?: string; arrivalTime?: string }
export const validate = (s: Booking): BookingErrors => {
const errors: BookingErrors = {};
if (!s.name.trim()) errors.name = "Enter your name";
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email.trim())) errors.email = "Enter a valid email address";
if (!normalizeTime(s.arrivalTime)) errors.arrivalTime = "Enter a valid time";
return errors;
};
/** @jsxImportSource solid-js — this file's JSX is Solid's, not React's; tsc reads it. */
// Solid: material/solid wraps the same elements.
import { createSignal } from "solid-js";
import { createStore } from "solid-js/store";
import { Button, Checkbox, Datepicker, Dialog, Radio, Radios, Select, SelectOption, Slider, Snackbar, TextField, Timepicker } from "material/solid";
import { ADULT_OPTIONS, CHILD_OPTIONS, CLOCK_ICON, DEFAULTS, EXTRAS, ROOMS, eligibleRooms, normalizeTime, rangeText, roomOf, summary, totalText, validate, withDates, withPrice, type Booking, type BookingErrors } from "./shared";
export default function Booking() {
const [s, setS] = createStore<Booking>({ ...DEFAULTS });
const [errors, setErrors] = createStore<BookingErrors>({});
const [dialogOpen, setDialogOpen] = createSignal(false);
const [confirmed, setConfirmed] = createSignal(false);
const [timeOpen, setTimeOpen] = createSignal(false);
const book = () => {
const next = validate({ ...s });
setErrors(next);
if (!next.name && !next.email && !next.arrivalTime && roomOf({ ...s })) setDialogOpen(true);
};
const commitTime = (value: string) => {
const time = normalizeTime(value);
if (time) { setS("arrivalTime", time); setErrors("arrivalTime", undefined); }
else setErrors("arrivalTime", "Enter a valid time");
};
return (
<section class="booking">
<Dialog headline="Confirm booking" open={dialogOpen()} onClose={() => setDialogOpen(false)}
actions={<>
<Button variant="text" onClick={() => setDialogOpen(false)}>Cancel</Button>
<Button variant="text" onClick={() => { setDialogOpen(false); setConfirmed(true); }}>Confirm booking</Button>
</>}>
<p>{summary({ ...s })}</p>
</Dialog>
<div class="booking__intro">
<h1 class="booking__title mtrl-headline-small">Book a stay</h1>
<p class="booking__lede mtrl-body-medium">Choose dates, guests and a room. The total updates as you go.</p>
</div>
<div class="booking__grid">
<Datepicker label="Check-in" variant="modal" closeOnSelect dateFormat="YYYY-MM-DD" value={s.checkIn}
onChange={(e) => setS(withDates({ ...s }, e.detail.value, s.checkOut))} />
<Datepicker label="Check-out" variant="modal" closeOnSelect dateFormat="YYYY-MM-DD" min={s.checkIn} value={s.checkOut}
onChange={(e) => setS(withDates({ ...s }, s.checkIn, e.detail.value))} />
<TextField label="Arrival time" value={s.arrivalTime} trailingIcon={CLOCK_ICON} trailingIconLabel="Choose time"
supportingText={errors.arrivalTime ?? "24-hour time"} error={Boolean(errors.arrivalTime)}
onInput={(e) => { setS("arrivalTime", e.detail.value); setErrors("arrivalTime", undefined); }}
onChange={(e) => commitTime(e.detail.value)}
onTrailing={() => { const time = normalizeTime(s.arrivalTime); if (time) setS("arrivalTime", time); setTimeOpen(true); }} />
<TextField label="Name" value={s.name} supportingText={errors.name ?? "Required"} error={Boolean(errors.name)}
onInput={(e) => { setS("name", e.detail.value); setErrors("name", undefined); }} />
<Select label="Adults" value={s.adults} onChange={(e) => setS("adults", e.detail.value ?? s.adults)}>
{ADULT_OPTIONS.map((n) => <SelectOption value={n}>{n}</SelectOption>)}
</Select>
<Select label="Children" value={s.children} onChange={(e) => setS("children", e.detail.value ?? s.children)}>
{CHILD_OPTIONS.map((n) => <SelectOption value={n}>{n}</SelectOption>)}
</Select>
<TextField label="Email" type="email" value={s.email} supportingText={errors.email ?? "Required"} error={Boolean(errors.email)}
onInput={(e) => { setS("email", e.detail.value); setErrors("email", undefined); }} />
</div>
<div class="booking__group">
<p class="booking__label mtrl-title-small">Room type</p>
<Radios aria-label="Room type" value={s.room} onChange={(e) => setS("room", e.detail.value ?? s.room)}>
{ROOMS.map((room) => <Radio value={room.value} disabled={!eligibleRooms({ ...s }).some((r) => r.value === room.value)}>{`${room.label} — $${room.rate} a night`}</Radio>)}
</Radios>
</div>
<div class="booking__group" role="group" aria-labelledby="extras-label">
<p class="booking__label mtrl-title-small" id="extras-label">Extras</p>
{EXTRAS.map((extra) => (
<Checkbox checked={s[extra.key]} onChange={(e) => setS(extra.key, e.detail.checked)}>
{`${extra.label} — $${extra.price} ${extra.unit}`}
</Checkbox>
))}
</div>
<div class="booking__group">
<p class="booking__label mtrl-title-small">Price range</p>
<Slider range showValue min={50} max={300} step={10} value={s.priceMin} secondValue={s.priceMax} aria-label="Price range"
onInput={(e) => setS(withPrice({ ...s }, e.detail.value, e.detail.secondValue ?? s.priceMax))} />
<p class="booking__range mtrl-body-medium">{rangeText({ ...s })}</p>
</div>
<output class="booking__total mtrl-body-medium" role="status">{totalText({ ...s })}</output>
<footer class="booking__actions"><Button onClick={book}>Book</Button></footer>
<Timepicker label="Arrival time" format="24h" value={normalizeTime(s.arrivalTime) ?? "15:00"} open={timeOpen()}
onChange={(e) => { setS("arrivalTime", e.detail.value); setErrors("arrivalTime", undefined); }} onClose={() => setTimeOpen(false)} />
<Snackbar message="Booking confirmed" open={confirmed()} onClose={() => setConfirmed(false)} />
</section>
);
}
// The state every variant of this example shares, and how it is described.
export interface Booking {
checkIn: string;
checkOut: string;
arrivalTime: string;
adults: string;
children: string;
room: string;
breakfast: boolean;
parking: boolean;
lateCheckout: boolean;
priceMin: number;
priceMax: number;
name: string;
email: string;
}
export const DEFAULTS: Booking = {
checkIn: "2027-04-10",
checkOut: "2027-04-12",
arrivalTime: "15:00",
adults: "2",
children: "0",
room: "double",
breakfast: false,
parking: false,
lateCheckout: false,
priceMin: 80,
priceMax: 240,
name: "",
email: "",
};
export const ROOMS = [
{ value: "standard", label: "Standard room", rate: 95 },
{ value: "double", label: "Double room", rate: 120 },
{ value: "family", label: "Family room", rate: 155 },
{ value: "suite", label: "Suite", rate: 210 },
] as const;
export const EXTRAS = [
{ key: "breakfast", label: "Breakfast", price: 18, unit: "a night" },
{ key: "parking", label: "Parking", price: 12, unit: "a night" },
{ key: "lateCheckout", label: "Late checkout", price: 25, unit: "once" },
] as const;
export type ExtraKey = (typeof EXTRAS)[number]["key"];
export const ADULT_OPTIONS = ["1", "2", "3", "4"];
export const CHILD_OPTIONS = ["0", "1", "2", "3"];
export const CLOCK_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M520-496v-144q0-17-11.5-28.5T480-680q-17 0-28.5 11.5T440-640v159q0 8 3 15.5t9 13.5l132 132q11 11 28 11t28-11q11-11 11-28t-11-28L520-496ZM480-80q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0 320q133 0 226.5-93.5T800-480q0-133-93.5-226.5T480-800q-133 0-226.5 93.5T160-480q0 133 93.5 226.5T480-160Z"/></svg>`;
const dayMs = 86_400_000;
const parseDay = (iso: string): number => Date.parse(`${iso}T00:00:00Z`);
/** Whole nights between the dates, at least one: check-out is never before check-in. */
export const nights = (s: Booking): number => {
const diff = Math.round((parseDay(s.checkOut) - parseDay(s.checkIn)) / dayMs);
return Number.isFinite(diff) ? Math.max(1, diff) : 1;
};
/** Check-out cannot be before check-in: an earlier date moves to check-in. */
export const withDates = (s: Booking, checkIn: string, checkOut: string): Booking => ({
...s,
checkIn,
checkOut: parseDay(checkOut) < parseDay(checkIn) ? checkIn : checkOut,
});
/** Rooms whose nightly rate sits inside the chosen price range. */
export const eligibleRooms = (s: Booking) => ROOMS.filter((room) => room.rate >= s.priceMin && room.rate <= s.priceMax);
export const roomOf = (s: Booking) => eligibleRooms(s).find((room) => room.value === s.room) ?? null;
/** A new price range keeps the choice inside it: an excluded room moves to the first eligible one, or to none. */
export const withPrice = (s: Booking, priceMin: number, priceMax: number): Booking => {
const next = { ...s, priceMin, priceMax };
if (!roomOf(next)) next.room = eligibleRooms(next)[0]?.value ?? "";
return next;
};
export const total = (s: Booking): number => {
const room = roomOf(s);
if (!room) return 0;
const count = nights(s);
let sum = count * room.rate;
if (s.breakfast) sum += count * 18;
if (s.parking) sum += count * 12;
if (s.lateCheckout) sum += 25;
return sum;
};
export const money = (value: number): string => `$${value}`;
export const rangeText = (s: Booking): string => `${money(s.priceMin)}–${money(s.priceMax)} a night`;
export const totalText = (s: Booking): string =>
roomOf(s)
? `Estimated total ${money(total(s))} for ${nights(s)} ${nights(s) === 1 ? "night" : "nights"}`
: "No rooms in this price range";
export const summary = (s: Booking): string => {
const room = roomOf(s);
if (!room) return "No rooms in this price range";
const extras = EXTRAS.filter((extra) => s[extra.key]).map((extra) => extra.label);
return (
`${room.label}, ${nights(s)} ${nights(s) === 1 ? "night" : "nights"} · Check-in ${s.checkIn}, check-out ${s.checkOut} · ` +
`Arrival ${s.arrivalTime} · ${s.adults} ${s.adults === "1" ? "adult" : "adults"}, ${s.children} ${s.children === "1" ? "child" : "children"}` +
`${extras.length ? ` · ${extras.join(", ")}` : ""} · ${totalText(s)}`
);
};
/** A typed time, normalized to HH:MM, or null when it is not a 24-hour time. */
export const normalizeTime = (text: string): string | null => {
const match = /^(\d{1,2}):([0-5]\d)$/.exec(text.trim());
if (!match) return null;
const hour = Number(match[1]);
return hour <= 23 ? `${String(hour).padStart(2, "0")}:${match[2]}` : null;
};
export interface BookingErrors { name?: string; email?: string; arrivalTime?: string }
export const validate = (s: Booking): BookingErrors => {
const errors: BookingErrors = {};
if (!s.name.trim()) errors.name = "Enter your name";
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.email.trim())) errors.email = "Enter a valid email address";
if (!normalizeTime(s.arrivalTime)) errors.arrivalTime = "Enter a valid time";
return errors;
};