Week 8
Last week, we built a cart.cart Today,on our own computers. This week, we're taking it somewhere new: the real Blueprint website. So far, everything we've built lived in a Vite and React projectworking on your own computer. The Blueprint site is built differently, so the first part of today is about what changed and why. After that, we'll split into teams and write some code together.
By the end of the meeting, you'll have added a Store page to a practice copy of the real Blueprint website, and the cart turns into a merch page.
What we're building
A Store page on the practice copy of the Stevens Blueprint website. It shows last week's made-up products,merch, lets you pick a size, addand adds things to a cart,cart. It starts with made-up products, so it works with no setup. Later tickets connect it to our Fourthwall store, so it shows real products and removeprices them.and Nothing on it is for sale,sends the cart onlyto livescheckout.
Fourthwall is the pageservice (refreshingthat emptiesruns it),the store. It holds the products and nothingtakes youthe changepayment. touchesOur page only shows the products and builds the cart. It never shows a card form.
The shop is called Test. Right now it has four products: the Material Study Tote, the Riverside Studio Hoodie, the Dot Matrix Tee and the Hudson Standard Tee. I'll add more, so don't write code that expects four.
Changes here do not go to the live site.site at sitblueprint.com. The practice copy is a private repo: blueprint-learn/techteam-merch-page.
WhatSet isup
Do aboutthis before the realmeeting site?
The Blueprint website is still HTML, CSS, JavaScript, and React, soif you alreadycan. know most of what's in it. What's different is the tooling around it.
npm installnpm run devdeno task servepackage.jsonvite.config.jsdeno.json_config.tsApp.jsx.mdsrc/.mdApp.cssuseStateonClicknpm run builddeno task buildWe'll go through the big ones.
What is Deno?
Deno is another JavaScript runtime, just like Node.js. It runs JavaScript (and TypeScript) on your computer, outside the browser. The Blueprint website runs on Deno, so that's what starts when you type deno task serve.
You still need Node.js. The site uses npm for one thing, a formatting tool called Prettier.
What is Lume?
Lume is a static site generator. It takes the files in src/ and turns them into a website made of plain HTML and CSS files. Open deno.json and look at tasks:
"build": "deno task lume",
"serve": "deno task lume -s"
deno task serve builds the site and starts a local server. deno task build builds it into the output/ folder, which is the finished site. These are the same idea as the scripts in package.json from Weeks 1 to 7.
The live site is hosted as plain files, so there's no server running our code when someone visits. Whatever Lume builds is all the visitor gets.
How do pages work?
In Weeks 1 to 7, App.jsx was the whole page. Here, the page /about comes from the file src/about.md. At the top of that file, you'll see this:
---
title: About | Blueprint
layout: _layouts/About.jsx
hero:
title: About Us
description: >
We are the Stevens Institute of Technology chapter of Blueprint ...
---
This part is called front matter. It's data: a title, which layout to use, and the words for the page. The layout line points to src/_includes/_layouts/About.jsx, which is a React component. Lume hands it the front matter as props, so hero.title in the JSX is the "About Us" you see above. It's the same idea as a card getting a title prop in Week 4, except these props come from the top of a file.
The site's docs ask us to keep the words in the .md files and use the JSX just for how it looks, so we'll do that too.
Where does React run?
This is the biggest difference.
In Weeks 1 to 7, React ran in your browser. When setCart ran, React redrew the page. On this site, React runs on your computer, once, while Lume builds the site. It turns your JSX into HTML and stops. The browser never gets React.
That's great forbecause things like "make one card for each product". But useState can't remember anything, because the page is already finished before anyone clicks. And onClick does nothing. Lume leaves the handler out of the HTML completely, and it doesn't tell you. We tried a button with onClick={() => alert("hi")}, and it came out as a plain <button>.
So we can't copy last week's cart over. What carries over is the thinking: components, props, .map() with a key, .find(), spread, and .filter(). The part that has to happen when someone clicks, we'll write as a small plain JavaScript file using addEventListener, like Week 2. It's more work, and that's pretty much why React exists.
Here's a way to keep the two halves straight:
.md.jsxsrc/assets/js/<script>.map()What is Tailwind?
Instead of writing CSS in a separate file, this site puts small classes right on the elements. className="text-2xl font-bold text-primary" means big, bold, and the Blueprint blue. primary and secondary are colors set in _config.ts. You don't need to memorize any of them. The Tailwind docs have a search box.
How does a change get onto the real site?
On the real repo, merging to main starts a GitHub Action that builds the site and puts it on the live site. Because of that, the club has an approval process. A change that looks different needs a review from the Website Team and the Design Team before it merges.
That's why we're working in a practice copy today. You can't break sitblueprint.com from here. If the Store page turns out well, getting it onto the real site would go through that process.
Teams
We'll split into teams here. Sit with your team for the rest of the meeting. We'll write the first page together on our own computers, and after that, your team picks tickets from the repo's Issues tab.
Getting started
You should have already installed Deno and cloned the practice copy from the Setup page. Open a terminal in that folder (not inside practice-page) and make a new branch for today:
git switch -c store-page
If Git says that branch already exists, use git switch store-page instead. Then start the site:
deno task serve
Your browser should open the Blueprint homepage at http://localhost:3000. The terminal will show some yellow warnings (about deprecated packages, charset, defaultProps). Those come from the real site's code and don't mean anything is broken. The line that matters ends with Server started at: http://localhost:3000/.
Leave the server running the whole time. Every time you save, it rebuilds and the page refreshes by itself. If deno isn't found, check the Setup page.
Here's what we'll build:download.
| Step | What |
|---|
git clone https://github.com/blueprint-learn/techteam-merch-page.git and cd techteam-merch-page with a heading.
2
brew install deno. On Windows run irm https://deno.land/install.ps1 | iex in PowerShell. Run deno --version. It should say 2.something.
3
node out-v to check. We only use it for Prettier, the code formatter.
4
deno carttask thatserve, npm ci. You only do this once.
Step 1: Add the page
We need two files and one line. Pages are .md files, so let's make one. Create src/store.md:
---
title:The Store | Blueprint
layout: _layouts/Store.jsx
---
That's the whole file for now. Next, the layout it points to. Create src/_includes/_layouts/Store.jsx:
export default ({ comp, title }) => (
<html>
<head>
<comp.GoogleAnalytics />
<comp.OpenGraphCommon />
<link rel="stylesheet" href="/styles.css" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
></meta>
<title>{title}</title>
</head>
<body>
<comp.Navbar alternate={true} />
<main className="mx-auto max-w-5xl px-6 py-10">
<h1 className="text-4xl font-bold text-primary">Store</h1>
<p className="mt-2 text-xl">
Made-up products for practice. Nothing herepage is for sale.
</p>
</main>
<comp.Footer />
</body>
</html>
);
We copied this from Blog.jsx, which sits next to it. A layout is a whole page, so unlike the components from Week 4, it has <html>, <head>, and <body>. title comes from store.md, and comp is how we reach the shared navbar and footer.
Save. Go toat http://localhost:3000/store/ (the slash at the end matters). You should see the navbar, the heading Store, and the footer. If you get a 404, check that the file is src/store.md and that the layout: line matches the layout'it's filename exactly.
Now let's make it easy to find. Open src/_components/Navbar.jsx and add one line to the navigationLinks list at the top:
{ href: "/blog", text: "Blog" },
{ href: "/store", text: "Store" },
Save. Store shows up in the navbar on every page, because the navbar is one shared component.
That's how you add a page here: a .md file, a layout for it, and a link. (Blog posts and project pages have their own steps in the site's docs/DOCS.md.)
Step 2: Product cards
Our products need to come from somewhere. On this site, content goes in the front matter, so open src/store.md and replace it with this. The products part is also in practice/store-fixtures.yml if you'd rather copy it:
---
title: Store | Blueprint
layout: _layouts/Store.jsx
hero:
title: Store
description: Made-up products for practice. Nothing here is for sale.
products:
- id: fixture-tee
name: Practice T-shirt
slug: practice-t-shirt
imageUrl: /assets/practice/practice-tee.svg
variants:
- id: fixture-tee-small
name: Small
price: 24
currency: USD
available: true
- id: fixture-tee-medium
name: Medium
price: 24
currency: USD
available: true
- id: fixture-tee-large
name: Large
price: 24
currency: USD
available: false
- id: fixture-hoodie
name: Practice Hoodie
slug: practice-hoodie
imageUrl: /assets/practice/practice-hoodie.svg
variants:
- id: fixture-hoodie-medium
name: Medium
price: 45
currency: USD
available: true
- id: fixture-hoodie-large
name: Large
price: 45
currency: USD
available: true
- id: fixture-stickers
name: Practice Sticker Pack
slug: practice-sticker-pack
imageUrl: null
variants:
- id: fixture-stickers-one
name: One size
price: 7.5
currency: USD
available: true
---
This is the same product and variant idea from Week 7. A product has variants, and each variant has its own id, a name, a price, and available. A few names changed (name instead of label, price instead of priceMinor) so they match the shape we'll use for the real store. Two other things are different:
price24git 7.5git imageUrl: nullNow the card. Make a folder src/_components/Store, and make a file inside it called ProductCard.jsx:
function formatMoney(amount, currency) {
return new Intl.NumberFormat("en-US", { style: "currency", currency }).format(
amount,
);
}
export default function ProductCard({ product }) {
const first = product.variants[0];
return (
<article className="flex flex-col gap-3 rounded-2xl border border-secondary p-4">
<img
src={product.imageUrl}
alt={product.name}
className="aspect-square w-full rounded-xl object-cover"
/>
<h2 className="text-2xl font-bold text-primary">{product.name}</h2>
<p>{formatMoney(first.price, first.currency)}</p>
</article>
);
}
This is a Week 4 component. It gets a product prop and draws one card. Intl.NumberFormat turns 24 into .$24.00pull
Last,If usesomething breaks, ask the person next to you first. Then ask me.
The token. Only tickets #29 to #33 need the Fourthwall token. I'll give it into theyou layout.when Inthey Store.jsx,open. change the first line so the layout receives the front matter:
export default ({ comp, title, hero, products }) => (
Then replace the heading and paragraph inside <main> with this:
<h1 className="text-4xl font-bold text-primary">{hero.title}</h1>
<p className="mt-2 text-xl">{hero.description}</p>
<div className="mt-8 grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
{products.map((product) => (
<comp.Store.ProductCard key={product.id} product={product} />
))}
</div>
Save. You should see three cards: Practice T-shirt $24.00, Practice Hoodie $45.00, and Practice Sticker Pack $7.50. The sticker pack has a broken picture icon. That's expected, since we told it there's no image. We'll leave that for a ticket.
So what did we just write? products.map(...) is the sameCopy .map() from Week 5, making one card per product, and key is the product's id. comp.Store.ProductCard is the file we just made. The folder name Store and the file name ProductCard become the path. grid, gap-6, and lg:grid-cols-3 are Tailwind classes that mean "put these in a grid, three across on a wide screen".
Try changing to Practice T-shirtenv.examplesomething else in store.md and save. The card changes, and we didn't touch any code.
Step 3: Pick a size
Each card needs a dropdown of sizes. In Week 7, this was a controlled input with useState. Here, the browser already remembers which <option> is selected, so the card only has to draw the options. No state needed.
Open ProductCard.jsx. Delete the const first = ... line and the blank line under it. Then replace the <article ...> line with this:
<article
className="flex flex-col gap-3 rounded-2xl border border-secondary p-4"
data-product-name={product.name}
>
(data-product-name stores the name on the element so our script can read it in the next step.) Now replace the <p> line that shows first.price with the dropdown:
<label htmlFor={`size-${product.id}`}>Size</label>
<select
id={`size-${product.id}`}
className="rounded border border-primary p-2"
>
{product.variants.map((variant) => (
<option
key={variant.id}
value={variant.id}
disabled={!variant.available}
data-variant-name={variant.name}
data-price-label={formatMoney(variant.price, variant.currency)}
>
{variant.name}, {formatMoney(variant.price, variant.currency)}
{!variant.available && " (sold out)"}
</option>
))}
</select>
Save. Each card has a Size dropdown, and the T-shirt's Large is greyed out with "(sold out)".
This is the Week 7 dropdown again. We .map() over the variants to make one <option> each, and each value is the variant ID, so renaming "Small" to "S" wouldn't matter. !variant.available flips a Boolean, and && shows "(sold out)" only when it's true. The data- lines tuck the variant's name and its price text onto each option. We'll read them in a minute.
Notice there's no value={...} and no onChange. We can't have them, because there's no state. The browser keeps track of the selected option on its own.
Step 4: Add to cart
Now we cross over to the browser. The cart has to change when someone clicks, and only plain JavaScript can do that here.
First, give each card a button. In ,ProductCard.jsxenv.local put this right after the closing </select>:
<button
type="button"
data-add-to-cart
className="rounded-lg bg-primary px-4 py-2 font-bold text-white"
>
Add to cart
</button>
data-price={variant.price}
data-currency={variant.currency}
Next, a place on the page for the cart. In Store.jsx, add a script tag to the <head>, right above <title>:
<script src="/assets/js/store.js" defer></script>
Then add the cart section inside <main>, right after the </div> that closes the product grid:
<section aria-labelledby="cart-heading" className="mt-12">
<h2 id="cart-heading" className="text-3xl font-bold text-primary">
Your cart
</h2>
<p id="cart-empty" className="mt-2">
Your cart is empty.
</p>
<ul id="cart-lines" className="mt-4 flex flex-col gap-3"></ul>
</section>
And add this right after </main>. It's a <template>, which the browser keeps hidden until a script copies it:
<template id="cart-line-template">
<li className="flex flex-col gap-1 rounded-xl border border-secondary p-4">
<span data-field="name" className="text-xl font-bold"></span>
<span data-field="price"></span>
<span data-field="quantity"></span>
</li>
</template>
We use a template so the classes stay in the JSX, where we're used to them. The script only has to fill in the words.
Nowvalues, and restart deno task serve. Without a token, the script.page Createstill builds and shows the foldermade-up products. Never commit src/assets/js.env.local and a file in it called store.js:
// Runs in the browser. (Everything in _components and _layouts ran at build time.)
let cart = [];
const emptyMessage = document.querySelector("#cart-empty");
const cartList = document.querySelector("#cart-lines");
const lineTemplate = document.querySelector("#cart-line-template");
function handleAdd(card) {
const option = card.querySelector("select").selectedOptions[0];
setCart([
...cart,
{
variantId: option.value,
productName: card.dataset.productName,
variantName: option.dataset.variantName,
quantity: 1,
unitPrice: Number(option.dataset.price),
currency: option.dataset.currency,
priceLabel: option.dataset.priceLabel,
},
]);
}
function setCart(newCart) {
cart = newCart;
renderCart();
}
function renderCart() {
emptyMessage.hidden = cart.length > 0;
cartList.replaceChildren();
for (const line of cart) {
const item = lineTemplate.content.firstElementChild.cloneNode(true);
item.dataset.variantId = line.variantId;
item.querySelector('[data-field="name"]').textContent =
`${line.productName}, ${line.variantName}`;
item.querySelector('[data-field="price"]').textContent =
`${line.priceLabel} each`;
item.querySelector('[data-field="quantity"]').textContent =
`Quantity: ${line.quantity}`;
cartList.append(item);
}
}
document.addEventListener("click", (event) => {
const addButton = event.target.closest("[data-add-to-cart]");
if (addButton) {
handleAdd(addButton.closest("article"));
}
});
Save and refresh. Pick Small and click Add to cart. You should see "Practice T-shirt, Small", "$24.00 each", and "Quantity:never 1". Addpaste the hoodietoken too,in an issue, a PR or a chat.
How a ticket works
Every change is one ticket (a GitHub issue), one branch and theone cartpull getsrequest a second line.
Let's match this up with Week 7:(PR).
- Open the Issues tab and pick a ticket whose "Depends on" tickets are merged. Skip any with the
let cart = []needs-fourthwall-tokenislabel until I say the token exists. Assign the ticket to yourself. Keep one open ticket at a time.
constmain issue-<issue number>-<short-name>, issue-24-format-money. Run git switch main, then git pull, then git switch -c issue-24-format-money.
Do what the handleAddhandleAddnpm run format:write[...cart,then newLine]setCart(newCart)renderCart()renderCartCloses #<issue number> <li>merges. cart.map(...)PR @Nishit-Sharma) documentclosest(...)check addEventListenerfor datasetOnce data-I dataset"24"Number(...)24Two lines?
Now click Add to cart twice on the same size. You'll see two Small lines, each with Quantity: 1. Open the Console (right-click, Inspect, Console). There's no warning this time. In Week 7, React told us about two children with the same key, but React isn't in the browser here, so nothing is checking our work. That's one more difference.
It's the same bug as Week 7. handleAdd always adds a new line. Refresh to empty the cart, then fixmerge it. Replace handleAdd with this:
function handleAdd(card) {
const option = card.querySelector("select").selectedOptions[0];
const variantId = option.value;
const existingLine = cart.find((line) => line.variantId === variantId);
if (existingLine) {
setCart(
cart.map((line) => {
if (line.variantId === variantId) {
return { ...line, quantity: line.quantity + 1 };
}
return line;
}),
);
return;
}
setCart([
...cart,
{
variantId: variantId,
productName: card.dataset.productName,
variantName: option.dataset.variantName,
quantity: 1,
unitPrice: Number(option.dataset.price),
currency: option.dataset.currency,
priceLabel: option.dataset.priceLabel,
},
]);
}
This is the same fix as Week 7. Look for a line with the same variant ID. If there is one, make a new cart where its quantity is 1 higher, and stop. If there isn't, add a new line.
Save, refresh, and add Small twice. You should see one line with Quantity: 2. Add Medium and you get a second line. If Small and Medium ever share a line, something is comparing product names instead of variant IDs.
Step 5: Remove an item
Each line needs a Remove button that knows which line it's on. In Store.jsx, add the button inside the <li> of the template, under the quantity <span>:
<button
type="button"
data-remove
className="w-fit rounded-lg border border-maroon px-3 py-1 text-maroon"
>
Remove
</button>
In store.js, add handleRemove above the click listener:
function handleRemove(variantId) {
setCart(cart.filter((line) => line.variantId !== variantId));
}
Then changerun the click listener so it reads:
document.addEventListener("click", (event) => {
const addButton = event.target.closest("[data-add-to-cart]");
if (addButton) {
handleAdd(addButton.closest("article"));
}
const removeButton = event.target.closest("[data-remove]");
if (removeButton) {
handleRemove(removeButton.closest("li").dataset.variantId);
}
});
Save. Add a few things and click Remove on one line. The others stay. Remove them all and "Your cart is empty." comes back.
handleRemove is Week 7's .filter() line: keep every line whose variant ID isn't the one we're removing. How does the button know its line? In renderCart, we put item.dataset.variantId = line.variantId on each <li>. The listener walks up from the clicked button to its <li> with closest("li") and reads the ID back.
Tickets
After the walkthrough, we all switch to the same version of the page so your team's work fits together. The facilitator puts the finished page on main. Run this to get it:
git switch main && git pull
Your store-pagebranch stays onbefore your computernext ifticket.
you
want
A tofew compare.rules:
deno.lock, package-lock.json or _config.ts unless the ticket says to.
Don't open stevensblueprint/blueprint_website The tickets
Each ticket is onea smallGitHub jobissue with a checklistscope atof work, acceptance criteria and a "Depends on" list. Read the bottomissue calledfor the acceptancedetails. check.The Startsizes withare Ticketmy 0,guesses, whichand I haven't timed them. "Pair" means two people. There is addingno your name to CONTRIBUTORS.md and opening your first pull request. After that, your team claims tickets. CONTRIBUTING.md in the repo has the steps.#28.
When something goes wrong
deno: command not found#24
deno --versiondeno task serve/store/#26
src/store.mdlayout:Store.jsx)}.jsxcomp.Storesrc/_components/StorelistProducts()
ProductCard.jsxundefined#30
store.mdfourthwall.js
store.jssrc/assets/js<script>Store.jsxonClickuseStatedata-addEventListenervariantId24$24.00M
formatMoneystore.mdThe ones that depend on nothing and don't need the token are #24 and #26. The token tickets wait until I say the token exists.
ResourcesTeams
EverythingI'll neededpost forthe todayteams isand above.tickets These are for later.here.
<template>