A storefront: home, sale, product, cart, checkout and confirmation
A whole shop as one app document: a home page with a sale banner, a sale list with filters, category and product pages, a cart with quantities and a promo code, checkout, and the order's confirmation. It is drawn with this library's components and one of the shop's own (the banner), reads through a DataSource and changes the cart and places the order only through the shop's operations. Every product, price and person in it is made up, and it is in test mode: it takes only test card numbers, charges nothing and keeps only a card's last four digits.
The catalog is this library's analytics catalog plus the banner, added with extendCatalog:
catalog.ts:
import { childList, dynamicString } from "@surfaces-ui/document";
import { analyticsCatalog, extendCatalog } from "@surfaces-ui/spec";
import { z } from "zod";
/**
* The shop's catalog: everything this library's analytics catalog draws (cards, lists of rows, filters, inputs,
* buttons, images), plus the one component the shop needs that it does not have: a sale banner.
*/
export const shopCatalog = extendCatalog(analyticsCatalog, {
id: "urn:example:storefront:v1",
title: "Storefront",
description: "A shop's pages: this library's components and a sale banner.",
components: {
SaleHero: {
description:
"A banner across the top of a page that announces a sale or a collection: a short line above (`eyebrow`), a title, a sentence, and its actions (`children`, usually one or two Buttons). `level` 1 when the title is the page's own heading, once per page.",
props: {
eyebrow: dynamicString.optional(),
title: dynamicString,
text: dynamicString.optional(),
level: z.union([z.literal(1), z.literal(2)]).optional(),
children: childList.optional(),
},
example: { id: "hero", component: "SaleHero", eyebrow: "Winter sale", title: "Up to 40% off outerwear", text: "Jackets, boots and knitwear, while they last.", level: 1, children: ["shop-sale"] },
},
},
});The banner's renderer uses the theme's variables only, so it follows light, dark and every preset; product pictures are names (product-103) that the page turns into addresses, since an Image never loads what a document wrote. Here they are drawn as SVG; a real shop returns its CDN's address:
renderers.tsx:
import type { ComponentRenderer } from "@surfaces-ui/runtime";
import { analyticsRenderers } from "@surfaces-ui/spec/react";
import "./shop.css";
const words = (value: unknown) => (value == null ? "" : String(value));
/**
* The sale banner, drawn with the theme's own variables (`--sf-*`), so it follows light, dark and every preset. Its
* levels are the ones this library's `Text` uses: a page's heading is an `h2`, since the page around an app owns `h1`.
*/
const SaleHero: ComponentRenderer = ({ props, component, children }) => {
const Title = props.level === 1 ? "h2" : "h3";
return (
<section className="shop-hero" aria-label={words(props.title)}>
{props.eyebrow ? <p className="shop-hero-eyebrow">{words(props.eyebrow)}</p> : null}
<Title className="shop-hero-title">{words(props.title)}</Title>
{props.text ? <p className="shop-hero-text">{words(props.text)}</p> : null}
{component.children ? <div className="shop-hero-actions">{children(component.children)}</div> : null}
</section>
);
};
/** This library's renderers with the shop's own spread in, as `extendCatalog` expects. */
export const shopRenderers: Record<string, ComponentRenderer> = { ...analyticsRenderers, SaleHero };
const SHAPES: Record<string, string> = {
Jackets: "M38 22 L50 16 L62 22 L76 30 L70 46 L64 43 L64 84 L36 84 L36 43 L30 46 L24 30 Z",
Shoes: "M18 60 L40 58 L52 44 L62 46 L66 58 L84 62 C88 63 88 72 84 72 L18 72 Z",
Bags: "M26 38 L74 38 L80 84 L20 84 Z M38 38 C38 22 62 22 62 38",
Hats: "M22 66 C22 40 78 40 78 66 Z M14 66 L86 66 L86 72 L14 72 Z",
Knitwear: "M36 20 L64 20 L82 34 L74 48 L68 44 L68 84 L32 84 L32 44 L26 48 L18 34 Z",
};
// The pictures' own colours: what a photo of the product would show, not the interface's, so they are not theme tokens.
const TINTS: Record<string, [string, string]> = {
Navy: ["#1f3a5f", "#dfe7f1"], Black: ["#222222", "#e8e8e8"], Olive: ["#5b6b2f", "#ecefdf"], Camel: ["#b07c45", "#f5ebdf"],
Orange: ["#d9622b", "#fbe6da"], White: ["#9aa3ad", "#f4f6f8"], Brown: ["#6b4226", "#efe4db"], Grey: ["#6f7780", "#eceff2"],
Green: ["#2f6b4a", "#dff0e6"], Natural: ["#b9a88a", "#f6f1e7"], Red: ["#b3262e", "#f8dfe0"], Sand: ["#c2a878", "#f7f0e2"],
Cream: ["#cdbb95", "#faf6ec"], Blue: ["#2b5bb5", "#e0e8f8"], Rust: ["#a4471f", "#f6e2d8"],
};
/**
* The shop's product pictures. An `Image` never loads what the document wrote: the page resolves each name
* (`product-103`, `category-Shoes`) to an address of its own. These are drawn here as SVG; a real shop returns its
* CDN's address.
*/
export function productImages(products: readonly { product_id: string; category: string; color: string }[]) {
const made = new Map<string, string>();
const draw = (category: string, color: string) => {
const [ink, ground] = TINTS[color] ?? ["#555555", "#eeeeee"];
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" fill="${ground}"/><path d="${SHAPES[category] ?? ""}" fill="${ink}" stroke="${ink}" stroke-width="2" stroke-linejoin="round"/></svg>`;
return URL.createObjectURL(new Blob([svg], { type: "image/svg+xml" }));
};
return (name: string): string | undefined => {
if (made.has(name)) return made.get(name);
const product = name.startsWith("product-") ? products.find((p) => p.product_id === name.slice(8)) : undefined;
const category = name.startsWith("category-") ? products.find((p) => p.category === name.slice(9)) : undefined;
const picked = product ?? category;
if (!picked || typeof URL.createObjectURL !== "function") return undefined;
const url = draw(picked.category, picked.color);
made.set(name, url);
return url;
};
}The backend. The pages read seven tables (products, sale, categories, cart_lines, cart, orders, order_lines) and change them through five operations. The rules are the shop's, on its side: stock, promo codes, totals, and which cards are taken. It is in memory here; on your own backend the tables are your queries and each operation is your handler:
shop.ts:
import { type DataSource, OperationError, type OperationSpec, memoryDataSource, memoryOperations } from "@surfaces-ui/data";
/** One product of the made-up shop. Every name, price and stock level here is invented. */
export type Product = {
product_id: string;
name: string;
category: string;
color: string;
price: number;
/** The price today: the sale price when it is on sale. */
price_now: number;
on_sale: boolean;
percent_off: number;
stock: number;
featured: boolean;
description: string;
};
const MADE_UP: [string, string, string, number, number, number, boolean, string][] = [
["Harbor rain jacket", "Jackets", "Navy", 189, 0.3, 14, true, "A light, fully taped shell that packs into its own pocket."],
["Summit down parka", "Jackets", "Black", 329, 0.4, 6, false, "Warm to minus twenty, with a hood that fits over a helmet."],
["Field quilted vest", "Jackets", "Olive", 119, 0.25, 22, false, "A quilted layer for cold mornings and long walks."],
["Coastline wool coat", "Jackets", "Camel", 279, 0, 9, true, "Double-faced wool, cut long, lined in recycled satin."],
["Trail running shoe", "Shoes", "Orange", 139, 0.2, 31, true, "A grippy outsole and a rock plate for rough trails."],
["City leather sneaker", "Shoes", "White", 129, 0, 40, false, "Full-grain leather on a cushioned cup sole."],
["Alpine hiking boot", "Shoes", "Brown", 219, 0.35, 3, false, "Waterproof leather with a stiff sole for steep ground."],
["Studio slip-on", "Shoes", "Grey", 79, 0.15, 18, false, "Knitted upper, no laces, made to be kicked off."],
["Commuter backpack", "Bags", "Black", 149, 0.2, 25, true, "A padded sleeve for a laptop and a pocket for everything else."],
["Weekend duffel", "Bags", "Green", 169, 0.3, 11, false, "Forty litres, a shoe pocket and handles that tuck away."],
["Market tote", "Bags", "Natural", 49, 0, 60, false, "Heavy canvas with a lined inner pocket."],
["Merino beanie", "Hats", "Red", 39, 0.25, 50, false, "Soft merino wool that does not itch."],
["Wide-brim sun hat", "Hats", "Sand", 59, 0, 17, true, "Packable, with a cord for windy days."],
["Fisherman sweater", "Knitwear", "Cream", 159, 0.3, 12, true, "A heavy cable knit in undyed wool."],
["Cashmere crew", "Knitwear", "Blue", 199, 0.2, 8, false, "Two-ply cashmere in a relaxed fit."],
["Ribbed cardigan", "Knitwear", "Rust", 129, 0, 15, false, "A long rib with horn buttons."],
];
/** The made-up catalogue: sixteen products in five categories, half of them on sale. */
export const sampleProducts = (): Product[] =>
MADE_UP.map(([name, category, color, price, off, stock, featured, description], i) => ({
product_id: String(101 + i),
name,
category,
color,
price,
price_now: Math.round(price * (1 - off) * 100) / 100,
on_sale: off > 0,
percent_off: Math.round(off * 100),
stock,
featured,
description,
}));
/** Card numbers this shop takes. It is in test mode: no other number is accepted, and none is ever charged. */
export const TEST_CARDS = { works: "4242424242424242", declined: "4000000000000002" } as const;
const PROMO_CODES: Record<string, number> = { WELCOME10: 0.1 };
const money = (value: number) => Math.round(value * 100) / 100;
interface CartLine {
product_id: string;
quantity: number;
}
interface Order {
order_id: string;
name: string;
email: string;
ship_to: string;
items: number;
total: number;
card: string;
placed_at: string;
lines: { product_id: string; name: string; quantity: number; line_total: number }[];
}
/**
* The shop's backend, in memory: a `DataSource` that reads the products, the cart and the orders as they are now,
* and the operations that change the cart and place an order. A page reads through one and writes through the
* other, as it would against your own backend. One shopper, one cart.
*/
export function shopBackend(options: { now?: () => Date } = {}) {
const products = sampleProducts();
const byId = new Map(products.map((p) => [p.product_id, p]));
let cart: CartLine[] = [];
let promo = "";
const orders: Order[] = [];
const now = options.now ?? (() => new Date());
const totals = () => {
const lines = cart.map((line) => ({ ...line, product: byId.get(line.product_id)! }));
const items = lines.reduce((sum, line) => sum + line.quantity, 0);
const subtotal = money(lines.reduce((sum, line) => sum + line.quantity * line.product.price_now, 0));
// The discount is negative, so it reads as money off wherever it is shown.
const discount = -money(subtotal * (PROMO_CODES[promo] ?? 0));
const shipping = items === 0 || subtotal + discount >= 100 ? 0 : 7.95;
const tax = money((subtotal + discount) * 0.08);
return { lines, items, subtotal, discount, shipping, tax, total: money(subtotal + discount + shipping + tax) };
};
// The tables the pages read. The memory source copies its rows when it is made, so it is made again after a change.
const tables = () => {
const t = totals();
return {
products,
sale: products.filter((p) => p.on_sale),
categories: [...new Set(products.map((p) => p.category))].map((category) => ({ category, products: products.filter((p) => p.category === category).length, first_product: products.find((p) => p.category === category)!.product_id })),
cart_lines: t.lines.map(({ product, quantity }) => ({ product_id: product.product_id, name: product.name, color: product.color, quantity, price_now: product.price_now, line_total: money(quantity * product.price_now) })),
cart: [{ cart: "current", items: t.items, subtotal: t.subtotal, discount: t.discount, promo: promo || "None", shipping: t.shipping, tax: t.tax, total: t.total }],
orders: orders.map(({ lines: _lines, ...order }) => order),
order_lines: orders.flatMap((order) => order.lines.map((line) => ({ order_id: order.order_id, ...line }))),
};
};
let source = memoryDataSource({ tables: tables() });
const changed = () => {
source = memoryDataSource({ tables: tables() });
};
const dataSource = new Proxy({} as DataSource, { get: (_target, key) => (...args: unknown[]) => (source as unknown as Record<PropertyKey, (...a: unknown[]) => unknown>)[key]!(...args) });
const product = (id: unknown) => {
const found = byId.get(String(id));
if (!found) throw new OperationError(`There is no product ${String(id)}.`);
return found;
};
const inCart = (id: string) => cart.find((line) => line.product_id === id)?.quantity ?? 0;
const put = (id: string, quantity: number) => {
cart = quantity <= 0 ? cart.filter((line) => line.product_id !== id) : inCart(id) ? cart.map((line) => (line.product_id === id ? { ...line, quantity } : line)) : [...cart, { product_id: id, quantity }];
changed();
};
const specs: OperationSpec[] = [
{
id: "add-to-cart",
title: "Add to cart",
description: "Puts a number of one product in the cart, as long as the shop has that many.",
effect: "update",
target: "shop.cart",
args: [
{ name: "product_id", label: "Product", type: "text", required: true },
{ name: "quantity", label: "Quantity", type: "number", required: true, min: 1, max: 10 },
],
refreshes: ["memory"],
run: (args) => {
const p = product(args.product_id);
const want = inCart(p.product_id) + Number(args.quantity);
if (want > p.stock) throw new OperationError(`Only ${p.stock} left of the ${p.name}${inCart(p.product_id) ? `, and ${inCart(p.product_id)} are in your cart` : ""}.`);
put(p.product_id, want);
return { affected: 1, message: `Added ${args.quantity} × ${p.name} to your cart.` };
},
},
{
id: "change-quantity",
title: "Change quantity",
description: "One more or one less of a product already in the cart; one less of the last one takes it out.",
effect: "update",
target: "shop.cart",
args: [
{ name: "product_id", label: "Product", type: "text", required: true },
{ name: "by", label: "By", type: "number", required: true, min: -1, max: 1 },
],
refreshes: ["memory"],
run: (args) => {
const p = product(args.product_id);
const want = inCart(p.product_id) + Number(args.by);
if (want > p.stock) throw new OperationError(`Only ${p.stock} left of the ${p.name}.`);
put(p.product_id, want);
return { affected: 1, message: want === 0 ? `Took the ${p.name} out of your cart.` : `${want} × ${p.name} in your cart.` };
},
},
{
id: "remove-from-cart",
title: "Remove from cart",
description: "Takes a product out of the cart.",
effect: "update",
target: "shop.cart",
risk: "low",
args: [{ name: "product_id", label: "Product", type: "text", required: true }],
refreshes: ["memory"],
run: (args) => {
const p = product(args.product_id);
put(p.product_id, 0);
return { affected: 1, message: `Took the ${p.name} out of your cart.` };
},
},
{
id: "apply-promo",
title: "Apply promo code",
description: "Applies a promo code to the cart.",
effect: "update",
target: "shop.cart",
args: [{ name: "code", label: "Promo code", type: "text", required: true, maxLength: 20 }],
refreshes: ["memory"],
run: (args) => {
const code = String(args.code).trim().toUpperCase();
if (!(code in PROMO_CODES)) throw new OperationError(`${code} is not a code this shop knows.`);
promo = code;
changed();
return { affected: 1, message: `${code} applied: ${PROMO_CODES[code]! * 100}% off.` };
},
},
{
id: "place-order",
title: "Place order",
description: "Places an order for what is in the cart, paid by card. Test mode: only the shop's test cards are taken and nothing is charged.",
effect: "create",
target: "shop.orders",
args: [
{ name: "name", label: "Full name", type: "text", required: true, maxLength: 80 },
{ name: "email", label: "Email", type: "text", required: true, pattern: "[^@\\s]+@[^@\\s]+\\.[^@\\s]+" },
{ name: "address", label: "Address", type: "text", required: true, maxLength: 120 },
{ name: "city", label: "City", type: "text", required: true, maxLength: 60 },
{ name: "postcode", label: "Postcode", type: "text", required: true, pattern: "[A-Za-z0-9 -]{3,10}" },
{ name: "card_number", label: "Card number", type: "text", required: true, pattern: "[0-9 ]{12,23}" },
{ name: "expiry", label: "Expiry", type: "text", required: true, pattern: "(0[1-9]|1[0-2])/[0-9]{2}" },
{ name: "cvc", label: "Security code", type: "text", required: true, pattern: "[0-9]{3,4}" },
],
refreshes: ["memory"],
run: (args) => {
const t = totals();
if (t.items === 0) throw new OperationError("Your cart is empty, so there is nothing to order.");
for (const line of t.lines) if (line.quantity > line.product.stock) throw new OperationError(`Only ${line.product.stock} of the ${line.product.name} are left. Change your cart, then try again.`);
const [month, year] = String(args.expiry).split("/").map(Number);
const today = now();
if (2000 + year! < today.getUTCFullYear() || (2000 + year! === today.getUTCFullYear() && month! < today.getUTCMonth() + 1)) throw new OperationError("That card has expired. Nothing was charged.");
const card = String(args.card_number).replace(/\s/g, "");
if (card === TEST_CARDS.declined) throw new OperationError("The card was declined. Nothing was charged. Try test card 4242 4242 4242 4242.");
if (card !== TEST_CARDS.works) throw new OperationError("This shop is in test mode and takes only its test cards: use 4242 4242 4242 4242. No real card is charged.");
const order_id = `SO-${1001 + orders.length}`;
// The card number is never kept: only its last four digits.
orders.push({
order_id,
name: String(args.name),
email: String(args.email),
ship_to: `${String(args.address)}, ${String(args.city)} ${String(args.postcode)}`,
items: t.items,
total: t.total,
card: `Test card ending ${card.slice(-4)}`,
placed_at: today.toISOString().slice(0, 16).replace("T", " "),
lines: t.lines.map((line) => ({ product_id: line.product_id, name: line.product.name, quantity: line.quantity, line_total: money(line.quantity * line.product.price_now) })),
});
for (const line of t.lines) line.product.stock -= line.quantity;
cart = [];
promo = "";
changed();
return { affected: 1, result: { order_id }, message: `Order ${order_id} placed.` };
},
},
];
const operations = memoryOperations({ operations: specs, actor: () => ({ id: "shopper", name: "Shopper" }) });
return { dataSource, operations, cart: () => totals(), orders: () => orders };
}The app. Product cards are a RowList whose child reads each row's columns (name, price_now, and product_id for the picture and the page it opens). The sale list is filtered by a FilterBar whose filters are app state kept for the session. The product, cart, checkout and confirmation pages each read one record (record): the product, the cart's totals, the order. Buttons inside a row run an operation with that row's key. Checkout's button waits for every field it requires, and on success moves on to the order it made (then reads /@run/place/result/order_id); a declined card leaves the person where they were, with what they typed:
app.ts:
import { A2UI_VERSION, type AppDocument, type SurfaceComponent } from "@surfaces-ui/document";
const CATALOG = "urn:example:storefront:v1";
const text = (id: string, value: unknown, variant?: string): SurfaceComponent => ({ id, component: "Text", text: value, ...(variant ? { variant } : {}) });
const button = (id: string, label: unknown, action: unknown, extra: Record<string, unknown> = {}): SurfaceComponent[] => [{ id, component: "Button", child: `${id}-label`, action, ...extra }, text(`${id}-label`, label)];
const go = (to: string, values?: Record<string, unknown>) => ({ functionCall: { "@call": "navigate", args: { to, ...(values ? { values } : {}) } } });
const run = (operation: string, args: Record<string, unknown>, then?: unknown) => ({ functionCall: { "@call": "run", args: { operation, args, ...(then ? { then } : {}) } } });
const money = (path: string) => ({ "@call": "formatCurrency", args: { value: { "@path": path }, currency: "USD" } });
const page = (id: string, title: string, components: SurfaceComponent[], extra: Record<string, unknown> = {}) => ({ id, title, catalogId: CATALOG, a2ui: A2UI_VERSION, components, ...extra });
/**
* One product card, drawn once per row of a `RowList`. Inside it a relative path reads the row's column: `name`,
* `price_now`, and `product_id` for the picture's name and the product page it opens.
*/
const productCard = (prefix: string, sale: boolean): SurfaceComponent[] => [
{ id: `${prefix}-card`, component: "Card", child: `${prefix}-body` },
{ id: `${prefix}-body`, component: "Column", gap: 2, children: [`${prefix}-image`, `${prefix}-name`, `${prefix}-price`, ...(sale ? [`${prefix}-was`] : []), `${prefix}-view`] },
{ id: `${prefix}-image`, component: "Image", src: { "@call": "formatString", args: { value: "product-${product_id}" } }, alt: { "@call": "formatString", args: { value: "${name}, ${color}" } }, height: 180, fit: "cover" },
text(`${prefix}-name`, { "@path": "name" }, "h3"),
text(`${prefix}-price`, money("price_now")),
...(sale ? [text(`${prefix}-was`, { "@call": "formatString", args: { value: "Was ${price} · ${percent_off}% off" } }, "caption")] : []),
...button(`${prefix}-view`, { "@call": "formatString", args: { value: "View ${name}" } }, go("/products/[id]", { id: { "@path": "product_id" } })),
];
/**
* The shop as one app document, with no code: a home page, a sale with filters, a category, a product, the cart,
* checkout and the confirmation. It reads through the shop's `DataSource` (source `memory`) and changes the cart and
* places the order only through the shop's operations.
*/
export const shopApp: AppDocument = {
id: "storefront",
title: "Northwind Outfitters",
catalogId: CATALOG,
a2ui: A2UI_VERSION,
state: { saleFilters: { type: "array", default: [], keep: "session" } },
nav: [
{ label: "Home", to: "/" },
{ label: "Sale", to: "/sale" },
{ label: "Cart", to: "/cart" },
],
operations: ["add-to-cart", "change-quantity", "remove-from-cart", "apply-promo", "place-order"],
pages: [
{
route: "/",
page: page("home", "Home", [
{ id: "root", component: "Column", gap: 6, children: ["hero", "new-title", "new", "cat-title", "categories"] },
{ id: "hero", component: "SaleHero", eyebrow: "Winter sale", title: "Up to 40% off outerwear", text: "Jackets, boots and knitwear, while they last. Free shipping over $100.", level: 1, children: ["shop-sale"] },
...button("shop-sale", "Shop the sale", go("/sale"), { variant: "primary" }),
text("new-title", "New this season", "h2"),
{ id: "new", component: "RowList", sourceId: "memory", sql: "SELECT * FROM products", filters: [{ column: "featured", op: "eq", values: [true] }], child: "new-card", label: "New this season", rowKey: "product_id", layout: "grid", pageSize: 8 },
...productCard("new", false),
text("cat-title", "Shop by category", "h2"),
{ id: "categories", component: "RowList", sourceId: "memory", sql: "SELECT * FROM categories", child: "cat-card", label: "Categories", rowKey: "category", layout: "grid" },
{ id: "cat-card", component: "Card", child: "cat-body" },
{ id: "cat-body", component: "Column", gap: 2, children: ["cat-image", "cat-name", "cat-count", "cat-open"] },
{ id: "cat-image", component: "Image", src: { "@call": "formatString", args: { value: "category-${category}" } }, alt: "", height: 120, fit: "cover" },
text("cat-name", { "@path": "category" }, "h3"),
text("cat-count", { "@call": "formatString", args: { value: "${products} products" } }, "caption"),
...button("cat-open", { "@call": "formatString", args: { value: "Shop ${category}" } }, go("/category/[name]", { name: { "@path": "category" } })),
]),
},
{
route: "/sale",
page: page("sale", "Sale", [
{ id: "root", component: "Column", gap: 4, children: ["hero", "filters", "list"] },
{ id: "hero", component: "SaleHero", eyebrow: "Ends Sunday", title: "The winter sale", text: "Every price here is already reduced. Filter by category or colour.", level: 1 },
{ id: "filters", component: "FilterBar", sourceId: "memory", sql: "SELECT * FROM sale", filters: { "@path": "/app/saleFilters" }, columns: ["category", "color"] },
{ id: "list", component: "RowList", sourceId: "memory", sql: "SELECT * FROM sale", filters: { "@path": "/app/saleFilters" }, sorts: [{ column: "percent_off", desc: true }], child: "sale-card", label: "Products on sale", rowKey: "product_id", layout: "grid", emptyMessage: "Nothing on sale matches these filters." },
...productCard("sale", true),
]),
},
{
route: "/category/[name]",
page: page("category", "Category", [
{ id: "root", component: "Column", gap: 4, children: ["back", "heading", "list"] },
{ id: "back", component: "Link", text: "Home", url: "/" },
text("heading", { "@path": "/@route/name" }, "h1"),
{ id: "list", component: "RowList", sourceId: "memory", sql: "SELECT * FROM products", filters: [{ column: "category", op: "eq", values: [{ "@path": "/@route/name" }] }], child: "cat-card", label: "Products", rowKey: "product_id", layout: "grid" },
...productCard("cat", false),
]),
},
{
route: "/products/[id]",
page: page(
"product",
"Product",
[
{ id: "root", component: "Column", gap: 4, children: ["back", "top"] },
{ id: "back", component: "Link", text: "Back to the sale", url: "/sale" },
{ id: "top", component: "Grid", columns: 2, align: "start", children: ["image", "info"] },
{ id: "image", component: "Image", src: { "@call": "formatString", args: { value: "product-${/@route/id}" } }, alt: { "@call": "formatString", args: { value: "${/@record/page/name}, ${/@record/page/color}" } }, height: 420, fit: "cover" },
{ id: "info", component: "Column", gap: 3, children: ["badge", "name", "price", "was", "description", "facts", "qty", "add", "to-cart"] },
{ id: "badge", component: "Badge", text: { "@call": "formatString", args: { value: "Sale: ${/@record/page/percent_off}% off" } }, tone: "warning", visibleWhen: { path: "/@record/page/on_sale", equals: true } },
text("name", { "@path": "/@record/page/name" }, "h1"),
text("price", money("/@record/page/price_now"), "h2"),
text("was", { "@call": "formatString", args: { value: "Was ${/@record/page/price}" } }, "caption"),
text("description", { "@path": "/@record/page/description" }),
{
id: "facts",
component: "KeyValue",
items: [
{ label: "Category", value: { "@path": "/@record/page/category" } },
{ label: "Colour", value: { "@path": "/@record/page/color" } },
{ label: "In stock", value: { "@path": "/@record/page/stock" } },
],
},
{ id: "qty", component: "NumberField", label: "Quantity", value: { "@path": "/qty" }, min: 1, max: 10, step: 1, required: true },
...button("add", "Add to cart", run("add-to-cart", { product_id: { "@path": "/@route/id" }, quantity: { "@path": "/qty" } }), { variant: "primary", requires: ["qty"] }),
{ id: "to-cart", component: "Link", text: "Go to your cart", url: "/cart" },
],
{ data: { qty: 1 }, record: { sourceId: "memory", sql: "SELECT * FROM products", key: { column: "product_id", value: { "@path": "/@route/id" } } } },
),
},
{
route: "/cart",
page: page(
"cart",
"Cart",
[
{ id: "root", component: "Column", gap: 4, children: ["heading", "layout"] },
text("heading", "Your cart", "h1"),
{ id: "layout", component: "Grid", columns: 2, widths: [2, 1], align: "start", children: ["lines", "summary"] },
{ id: "lines", component: "RowList", sourceId: "memory", sql: "SELECT * FROM cart_lines", child: "line", label: "Items in your cart", rowKey: "product_id", emptyMessage: "Your cart is empty." },
{ id: "line", component: "Card", child: "line-row" },
{ id: "line-row", component: "Row", align: "center", sizes: [{ fixed: 96 }, "fill", "hug"], children: ["line-image", "line-text", "line-actions"] },
{ id: "line-image", component: "Image", src: { "@call": "formatString", args: { value: "product-${product_id}" } }, alt: "", height: 96, fit: "cover" },
{ id: "line-text", component: "Column", gap: 1, children: ["line-name", "line-detail", "line-total"] },
text("line-name", { "@path": "name" }, "h3"),
text("line-detail", { "@call": "formatString", args: { value: "${color} · quantity ${quantity}" } }, "caption"),
text("line-total", money("line_total")),
{ id: "line-actions", component: "Row", gap: 2, children: ["less", "more", "remove"] },
...button("less", "One less", run("change-quantity", { product_id: { "@path": "product_id" }, by: -1 })),
...button("more", "One more", run("change-quantity", { product_id: { "@path": "product_id" }, by: 1 })),
...button("remove", "Remove", run("remove-from-cart", { product_id: { "@path": "product_id" } })),
{ id: "summary", component: "Card", child: "summary-col" },
{ id: "summary-col", component: "Column", gap: 3, children: ["summary-title", "totals", "promo", "apply", "checkout"] },
text("summary-title", "Summary", "h2"),
{
id: "totals",
component: "KeyValue",
items: [
{ label: "Items", value: { "@path": "/@record/page/items" } },
{ label: "Subtotal", value: money("/@record/page/subtotal") },
{ label: { "@call": "formatString", args: { value: "Promo (${/@record/page/promo})" } }, value: money("/@record/page/discount") },
{ label: "Shipping", value: money("/@record/page/shipping") },
{ label: "Tax", value: money("/@record/page/tax") },
{ label: "Total", value: money("/@record/page/total") },
],
},
{ id: "promo", component: "TextField", label: "Promo code", value: { "@path": "/promo" }, help: "Try WELCOME10.", maxLength: 20, required: true },
...button("apply", "Apply code", run("apply-promo", { code: { "@path": "/promo" } }, { "@call": "setValue", args: { path: "/promo", value: "" } }), { requires: ["promo"] }),
...button("checkout", "Check out", go("/checkout"), { variant: "primary" }),
],
{ data: { promo: "" }, record: { sourceId: "memory", sql: "SELECT * FROM cart", key: { column: "cart", value: "current" } } },
),
},
{
route: "/checkout",
page: page(
"checkout",
"Checkout",
[
{ id: "root", component: "Column", gap: 4, children: ["back", "heading", "layout"] },
{ id: "back", component: "Link", text: "Back to your cart", url: "/cart" },
text("heading", "Checkout", "h1"),
{ id: "layout", component: "Grid", columns: 2, widths: [3, 2], align: "start", children: ["forms", "summary"] },
{ id: "forms", component: "Column", gap: 4, children: ["ship", "pay", "place"] },
{ id: "ship", component: "Card", child: "ship-col" },
{ id: "ship-col", component: "Column", gap: 3, children: ["ship-title", "name", "email", "address", "city-row"] },
text("ship-title", "Shipping", "h2"),
{ id: "name", component: "TextField", label: "Full name", value: { "@path": "/checkout/name" }, required: true, maxLength: 80 },
{ id: "email", component: "TextField", label: "Email", value: { "@path": "/checkout/email" }, required: true, pattern: "[^@\\s]+@[^@\\s]+\\.[^@\\s]+", help: "Where the confirmation goes." },
{ id: "address", component: "TextField", label: "Address", value: { "@path": "/checkout/address" }, required: true, maxLength: 120 },
{ id: "city-row", component: "Row", children: ["city", "postcode"] },
{ id: "city", component: "TextField", label: "City", value: { "@path": "/checkout/city" }, required: true },
{ id: "postcode", component: "TextField", label: "Postcode", value: { "@path": "/checkout/postcode" }, required: true },
{ id: "pay", component: "Card", child: "pay-col" },
{ id: "pay-col", component: "Column", gap: 3, children: ["pay-title", "test-mode", "card", "card-row"] },
text("pay-title", "Payment", "h2"),
text("test-mode", "Test mode: no card is charged and only test cards are taken. Use 4242 4242 4242 4242 with any future date and any three digits; 4000 0000 0000 0002 is declined.", "caption"),
{ id: "card", component: "TextField", label: "Card number", value: { "@path": "/checkout/card" }, required: true, placeholder: "4242 4242 4242 4242", pattern: "[0-9 ]{12,23}" },
{ id: "card-row", component: "Row", children: ["expiry", "cvc"] },
{ id: "expiry", component: "TextField", label: "Expiry (MM/YY)", value: { "@path": "/checkout/expiry" }, required: true, placeholder: "12/30", pattern: "(0[1-9]|1[0-2])/[0-9]{2}" },
{ id: "cvc", component: "TextField", label: "Security code", value: { "@path": "/checkout/cvc" }, required: true, placeholder: "123", pattern: "[0-9]{3,4}" },
...button(
"place",
"Place order",
run(
"place-order",
{
name: { "@path": "/checkout/name" },
email: { "@path": "/checkout/email" },
address: { "@path": "/checkout/address" },
city: { "@path": "/checkout/city" },
postcode: { "@path": "/checkout/postcode" },
card_number: { "@path": "/checkout/card" },
expiry: { "@path": "/checkout/expiry" },
cvc: { "@path": "/checkout/cvc" },
},
{ "@call": "navigate", args: { to: "/orders/[id]", values: { id: { "@path": "/@run/place/result/order_id" } } } },
),
{ variant: "primary", requires: ["name", "email", "address", "city", "postcode", "card", "expiry", "cvc"] },
),
{ id: "summary", component: "Card", child: "summary-col" },
{ id: "summary-col", component: "Column", gap: 3, children: ["summary-title", "summary-lines", "totals"] },
text("summary-title", "Order summary", "h2"),
{ id: "summary-lines", component: "RowList", sourceId: "memory", sql: "SELECT * FROM cart_lines", child: "summary-line", label: "Items", rowKey: "product_id", emptyMessage: "Your cart is empty." },
{ id: "summary-line", component: "Row", sizes: ["fill", "hug"], children: ["summary-line-name", "summary-line-total"] },
text("summary-line-name", { "@call": "formatString", args: { value: "${quantity} × ${name}" } }),
text("summary-line-total", money("line_total")),
{
id: "totals",
component: "KeyValue",
items: [
{ label: "Subtotal", value: money("/@record/page/subtotal") },
{ label: "Promo", value: money("/@record/page/discount") },
{ label: "Shipping", value: money("/@record/page/shipping") },
{ label: "Tax", value: money("/@record/page/tax") },
{ label: "Total", value: money("/@record/page/total") },
],
},
],
{ record: { sourceId: "memory", sql: "SELECT * FROM cart", key: { column: "cart", value: "current" } } },
),
},
{
route: "/orders/[id]",
page: page(
"confirmation",
"Order placed",
[
{ id: "root", component: "Column", gap: 4, children: ["badge", "heading", "intro", "cards", "continue"] },
{ id: "cards", component: "Grid", columns: 2, align: "start", children: ["facts-card", "lines-card"] },
{ id: "facts-card", component: "Card", child: "facts" },
{ id: "lines-card", component: "Card", child: "lines-col" },
{ id: "lines-col", component: "Column", gap: 3, children: ["lines-title", "lines"] },
{ id: "badge", component: "Badge", text: "Order placed", tone: "positive" },
text("heading", { "@call": "formatString", args: { value: "Thank you, ${/@record/page/name}" } }, "h1"),
text("intro", { "@call": "formatString", args: { value: "Order ${/@route/id} is on its way. A confirmation goes to ${/@record/page/email}." } }),
{
id: "facts",
component: "KeyValue",
items: [
{ label: "Order", value: { "@path": "/@route/id" } },
{ label: "Placed", value: { "@path": "/@record/page/placed_at" } },
{ label: "Ships to", value: { "@path": "/@record/page/ship_to" } },
{ label: "Paid with", value: { "@path": "/@record/page/card" } },
{ label: "Total", value: money("/@record/page/total") },
],
},
text("lines-title", "What you ordered", "h2"),
{ id: "lines", component: "RowList", sourceId: "memory", sql: "SELECT * FROM order_lines", filters: [{ column: "order_id", op: "eq", values: [{ "@path": "/@route/id" }] }], child: "line", label: "What you ordered", rowKey: "product_id" },
{ id: "line", component: "Row", sizes: ["fill", "hug"], children: ["line-name", "line-total"] },
text("line-name", { "@call": "formatString", args: { value: "${quantity} × ${name}" } }),
text("line-total", money("line_total")),
...button("continue", "Continue shopping", go("/"), { variant: "primary" }),
],
{ record: { sourceId: "memory", sql: "SELECT * FROM orders", key: { column: "order_id", value: { "@path": "/@route/id" } } } },
),
},
],
};The shell:
App.tsx:
import { DataSourceProvider, ThemeProvider } from "@surfaces-ui/components";
import "@surfaces-ui/components/styles.css";
import type { DataSource, Operations } from "@surfaces-ui/data";
import { validateApp } from "@surfaces-ui/document";
import type { OperationDefinition } from "@surfaces-ui/proto";
import { appOperationChecks } from "@surfaces-ui/spec";
import { AppView, useHashLocation } from "@surfaces-ui/spec/react";
import { shopApp } from "./app.js";
import { shopCatalog } from "./catalog.js";
import { shopRenderers } from "./renderers.js";
export interface ShopProps {
/** Where the pages read: the shop's products, cart and orders. */
dataSource: DataSource;
/** Where the cart changes and an order is placed, and the operations as the backend lists them. */
operations: Operations;
operationDefinitions: readonly OperationDefinition[];
/** Turns a picture's name (`product-103`) into an address. */
resolveImage?(name: string): string | undefined;
mode?: "light" | "dark";
}
/** The shop: one document, this library's components and the shop's sale banner, the address kept in the hash. */
export function Shop({ dataSource, operations, operationDefinitions, resolveImage, mode = "light" }: ShopProps) {
const location = useHashLocation();
const problems = validateApp(shopApp, shopCatalog, appOperationChecks(operationDefinitions));
if (problems.length > 0) return <pre role="alert">{problems.map((p) => `${p.path}: ${p.message}`).join("\n")}</pre>;
return (
<ThemeProvider initialMode={mode} storage={null} scope="scoped">
<DataSourceProvider dataSource={dataSource}>
<AppView app={shopApp} catalog={shopCatalog} renderers={shopRenderers} operations={operations} operationDefinitions={operationDefinitions} resolveImage={resolveImage} storage={null} {...location} />
</DataSourceProvider>
</ThemeProvider>
);
}The test checks the document against the catalog and the shop's operations, and every query against the data (with an order placed, so no table is empty); holds the shop to its rules (stock, a code it does not know, a declined card, a real card refused, a card number at its field, only the last four digits kept); and in the page adds two jackets from the product page and places the order from checkout:
storefront.test.tsx:
// @vitest-environment jsdom
import { validateApp, validateAppData } from "@surfaces-ui/document";
import { appOperationChecks } from "@surfaces-ui/spec";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { Shop } from "./App.js";
import { shopApp } from "./app.js";
import { shopCatalog } from "./catalog.js";
import { TEST_CARDS, shopBackend } from "./shop.js";
afterEach(() => {
cleanup();
window.location.hash = "";
});
const checkout = { name: "Rosa Moreau", email: "rosa@example.com", address: "12 Harbour Road", city: "Portland", postcode: "97201", expiry: "12/30", cvc: "123" };
const placed = async (shop: ReturnType<typeof shopBackend>, card: string) => {
const answer = await shop.operations.run({ operationId: "place-order", args: { ...checkout, card_number: card } });
return { status: answer.status, message: answer.message };
};
describe("a storefront as one app document", () => {
it("passes validateApp with the shop's operations, and every query names columns the data has", async () => {
const shop = shopBackend();
const { operations } = await shop.operations.listOperations({});
expect(validateApp(shopApp, shopCatalog, appOperationChecks(operations))).toEqual([]);
// With something in the cart and an order placed, every table has rows, so every column is checked.
await shop.operations.run({ operationId: "add-to-cart", args: { product_id: "101", quantity: 1 } });
await placed(shop, "4242 4242 4242 4242");
await shop.operations.run({ operationId: "add-to-cart", args: { product_id: "102", quantity: 1 } });
const report = await validateAppData(shopApp, shopCatalog, shop.dataSource);
expect(report.problems).toEqual([]);
expect(report.skipped).toEqual([]);
});
it("keeps the shop's rules on its own side: stock, codes, and test cards only", async () => {
const shop = shopBackend();
const add = (product_id: string, quantity: number) => shop.operations.run({ operationId: "add-to-cart", args: { product_id, quantity } });
expect((await placed(shop, TEST_CARDS.works)).message).toBe("Your cart is empty, so there is nothing to order.");
expect((await add("107", 5)).message).toBe("Only 3 left of the Alpine hiking boot.");
await add("101", 3);
expect((await shop.operations.run({ operationId: "apply-promo", args: { code: "FREESTUFF" } })).message).toBe("FREESTUFF is not a code this shop knows.");
await shop.operations.run({ operationId: "apply-promo", args: { code: "welcome10" } });
// 3 × $132.30, 10% off, free shipping over $100, 8% tax.
expect(shop.cart()).toMatchObject({ items: 3, subtotal: 396.9, discount: -39.69, shipping: 0, tax: 28.58, total: 385.79 });
expect((await placed(shop, "4000 0000 0000 0002")).message).toBe("The card was declined. Nothing was charged. Try test card 4242 4242 4242 4242.");
expect((await placed(shop, "4111 1111 1111 1111")).message).toMatch(/test mode and takes only its test cards/);
// A card number that is not a number is refused at its field before the shop's code runs.
const wrong = await shop.operations.run({ operationId: "place-order", args: { ...checkout, card_number: "abcd" } });
expect(wrong.errors.map((e) => e.field)).toEqual(["card_number"]);
expect(shop.orders()).toHaveLength(0);
expect(await placed(shop, "4242 4242 4242 4242")).toMatchObject({ message: "Order SO-1001 placed." });
// Only the last four digits are kept.
expect(JSON.stringify(shop.orders())).not.toContain("4242424242424242");
expect(shop.orders()[0]).toMatchObject({ card: "Test card ending 4242", total: 385.79, items: 3 });
expect(shop.cart().items).toBe(0);
});
it("adds to the cart from the product page and places the order from checkout", async () => {
const shop = shopBackend();
const { operations } = await shop.operations.listOperations({});
window.location.hash = "#/products/101";
render(<Shop dataSource={shop.dataSource} operations={shop.operations} operationDefinitions={operations} />);
const live = () => document.querySelector(".sf-app-live")!.textContent!.trim();
await screen.findByRole("heading", { name: "Harbor rain jacket" });
fireEvent.change(screen.getByRole("spinbutton", { name: /Quantity/ }), { target: { value: "2" } });
fireEvent.click(screen.getByRole("button", { name: "Add to cart" }));
await waitFor(() => expect(live()).toBe("Added 2 × Harbor rain jacket to your cart."));
expect(shop.cart().items).toBe(2);
window.location.hash = "#/checkout";
await screen.findByRole("heading", { name: "Checkout" });
const fill = (label: RegExp, value: string) => fireEvent.change(screen.getByRole("textbox", { name: label }), { target: { value } });
fill(/^Full name/, checkout.name);
fill(/^Email/, checkout.email);
fill(/^Address/, checkout.address);
fill(/^City/, checkout.city);
fill(/^Postcode/, checkout.postcode);
fill(/^Card number/, "4242 4242 4242 4242");
fill(/^Expiry/, checkout.expiry);
fill(/^Security code/, checkout.cvc);
fireEvent.click(screen.getByRole("button", { name: "Place order" }));
// `then` moves on to the order the operation made.
await screen.findByRole("heading", { name: "Thank you, Rosa Moreau" }, { timeout: 5000 });
expect(window.location.hash).toBe("#/orders/SO-1001");
expect(screen.getByText("Test card ending 4242")).toBeTruthy();
});
});In a browser
See it with pnpm --filter @surfaces-ui/recipes exec vite src/storefront (?mode=dark for dark). apps/e2e/tests/storefront.spec.ts walks it in Chromium on every change, at desktop width in light and dark and at phone width: home, the sale filtered to jackets, a product, two added, more than the shop has (refused), one more in the cart, an unknown code and then WELCOME10, a declined test card, then 4242 4242 4242 4242 and the confirmation, with axe's WCAG 2.2 AA checks and no console errors at each step. The pictures are taken by that test (SURFACES_EVIDENCE_DIR=… pnpm e2e storefront).
The home page, with the shop's banner and new products:
The storefront's home page: a sale banner and six product cards
The sale, filtered to jackets, in light and dark:
The sale list filtered to jackets: three products with their reduced prices
The same sale list in dark mode
A product, with two added:
The Harbor rain jacket's page with its price, sale badge, quantity and Add to cart
The cart with WELCOME10 applied, at desktop and phone width:
The cart: three jackets, a 10% promo, free shipping, tax and the total, $385.79
The same cart at phone width
A declined test card: the shopper stays on checkout with what they typed:
Checkout with the message that the card was declined and nothing was charged
The confirmation, with only the card's last four digits:
The order confirmation: thank you, the order number, what was ordered and the total
Source and test: apps/recipes/src/storefront