To truly understand useReducer, let's build a Shopping Cart. This is the perfect example because adding an item isn't just a simple update; it requires checking if the item exists, updating quantities, and calculating totals.
🖇️ The Shopping Cart Architecture
1. Define the Actions
In a professional setting, we use an object to store action names to prevent typos.
ADD_ITEM: Adds a product or increases quantity.
REMOVE_ITEM: Deletes an item from the cart.
CLEAR_CART: Resets everything.
File- 1 : ActionTypes.js
export const CART_ACTIONS = {
ADD_ITEM: 'ADD_ITEM',
REMOVE_ITEM: 'REMOVE_ITEM',
CLEAR_CART: 'CLEAR_CART',
};2. The Reducer Function
The reducer is the "brain." It looks at the current state and the action, then calculates the new state.
import { CART_ACTIONS } from './ActionTypes'; // Import constants
// 1. Define the Initial State
export const initialState = {
items: [],
total: 0,
};
// 2. Define the Reducer Function
export function cartReducer(state, action) {
switch (action.type) {
case CART_ACTIONS.ADD_ITEM: {
const existingItemIndex = state.items.findIndex(item => item.id === action.payload.id);
let updatedItems;
if (existingItemIndex > -1) {
// Create a new array and update the specific item's quantity
updatedItems = [...state.items];
updatedItems[existingItemIndex] = {
...updatedItems[existingItemIndex],
quantity: updatedItems[existingItemIndex].quantity + 1
};
} else {
// Add new item with quantity of 1
updatedItems = [...state.items, { ...action.payload, quantity: 1 }];
}
return {
...state,
items: updatedItems,
total: state.total + action.payload.price,
};
}
case CART_ACTIONS.REMOVE_ITEM: {
const itemToRemove = state.items.find(item => item.id === action.payload.id);
const filteredItems = state.items.filter(item => item.id !== action.payload.id);
return {
...state,
items: filteredItems,
total: state.total - (itemToRemove.price * itemToRemove.quantity),
};
}
case CART_ACTIONS.CLEAR_CART:
return initialState;
default:
return state;
}
}3. The Component Implementation
Here is how we bring it all together in a React component using the dispatch function.
import React, { useReducer } from 'react';
import { cartReducer, initialState } from './CartReducer'; // Importing the logic
import { CART_ACTIONS } from './ActionTypes'; // Import constants
const PRODUCTS = [
{ id: 1, name: 'Mechanical Keyboard', price: 100 },
{ id: 2, name: 'Gaming Mouse', price: 50 },
];
export default function ShoppingCart() {
// 3. Initialize useReducer
const [state, dispatch] = useReducer(cartReducer, initialState);
return (
<div style={{ padding: '20px', fontFamily: 'Arial' }}>
<h2>Store Products</h2>
<div style={{ display: 'flex', gap: '10px' }}>
{PRODUCTS.map(product => (
<button
key={product.id}
onClick={() => dispatch({ type: CART_ACTIONS.ADD_ITEM, payload: product })}
>
Add {product.name} (${product.price})
</button>
))}
</div>
<hr />
<h2>Your Cart</h2>
<p><strong>Total Price: ${state.total}</strong></p>
{state.items.length === 0 ? (
<p>Your cart is empty.</p>
) : (
<>
<ul>
{state.items.map(item => (
<li key={item.id} style={{ marginBottom: '10px' }}>
{item.name} — ${item.price} (x{item.quantity})
<button
style={{ marginLeft: '10px' }}
onClick={() => dispatch({ type: CART_ACTIONS.REMOVE_ITEM, payload: item })}
>
Remove
</button>
</li>
))}
</ul>
<button onClick={() => dispatch({ type: CART_ACTIONS.CLEAR_CART })}>
Clear Entire Cart
</button>
</>
)}
</div>
);
}<div class="infographic-vscodeterm" id="vt">
<style>
.infographic-vscodeterm {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-deep: #1942a8;
--accent-soft: #e3ebfd;
--line: #ddd6c9;
--radius: 8px;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', system-ui, sans-serif;
--mono-font: 'IBM Plex Mono', monospace;
max-width: 900px;
margin: 0 auto;
box-sizing: border-box;
background: transparent;
color: var(--ink);
font-family: var(--body-font);
}
.infographic-vscodeterm[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #13171f;
--paper-alt: #1c212b;
--accent: #5b8def;
--accent-deep: #8fb4ff;
--accent-soft: #20293f;
--line: #2c313d;
}
.infographic-vscodeterm * { box-sizing: border-box; min-width: 0; }
.vt-eyebrow {
font-family: var(--mono-font); font-size: 0.72rem; letter-spacing: 0.1em;
text-transform: uppercase; color: var(--accent); margin: 0 0 0.45rem;
display: flex; align-items: center; justify-content: center; gap: 0.4rem;
}
.vt-eyebrow::before { content: ""; width: 14px; height: 2px; background: var(--accent); display: inline-block; }
.vt-title {
font-family: var(--display-font); font-size: clamp(1.5rem, 4vw, 2.3rem); text-align: center;
margin: 0 0 0.5rem; line-height: 1.14; letter-spacing: -0.01em;
}
.vt-sub { color: var(--ink-soft); font-size: 0.95rem; text-align: center; margin: 0 0 1.7rem; }
/* ===== VS Code window — fixed dark theme regardless of page mode ===== */
.vt-window { border-radius: 8px; overflow: hidden; box-shadow: 0 16px 40px -14px rgba(0,0,0,0.45); border: 1px solid #1e1e1e; font-family: var(--mono-font); }
.vt-titlebar { background: #323233; display: flex; align-items: center; padding: 0.5rem 0.8rem; position: relative; }
.vt-dots { display: flex; gap: 0.4rem; }
.vt-dots span { width: 10px; height: 10px; border-radius: 50%; display: block; }
.vt-dots span:nth-child(1) { background: #ff5f56; }
.vt-dots span:nth-child(2) { background: #ffbd2e; }
.vt-dots span:nth-child(3) { background: #27c93f; }
.vt-titlebar-text { position: absolute; left: 50%; transform: translateX(-50%); font-size: 0.72rem; color: #cccccc; }
.vt-body { display: flex; height: 340px; }
.vt-resize-h { width: 5px; cursor: col-resize; background: transparent; flex-shrink: 0; transition: background 0.15s; touch-action: none; }
.vt-resize-h:hover, .vt-resize-h.is-dragging { background: #0078d4; }
.vt-resize-v { height: 5px; cursor: row-resize; background: transparent; flex-shrink: 0; transition: background 0.15s; touch-action: none; }
.vt-resize-v:hover, .vt-resize-v.is-dragging { background: #0078d4; }
.vt-window-resize {
height: 9px; background: #252526; cursor: row-resize; display: flex; align-items: center;
justify-content: center; border-top: 1px solid #1e1e1e; touch-action: none;
}
.vt-window-resize span { width: 30px; height: 3px; border-radius: 2px; background: #4a4a52; }
.vt-window-resize:hover span, .vt-window-resize.is-dragging span { background: #0078d4; }
.vt-toggle-btn {
background: none; border: none; color: #9a9a9a; cursor: pointer; display: flex; align-items: center;
padding: 0.3rem; border-radius: 3px; flex-shrink: 0;
}
.vt-toggle-btn:hover { background: #2a2d2e; color: #fff; }
.vt-toggle-btn svg { width: 13px; height: 13px; }
.vt-sidebar.is-hidden { width: 0 !important; overflow: hidden; border-right: none; }
.vt-terminal.is-collapsed { height: auto !important; }
.vt-terminal.is-collapsed .vt-term-body { display: none; }
.vt-terminal.is-collapsed .vt-term-toggle svg { transform: rotate(-90deg); }
.vt-activitybar { width: 40px; background: #333333; display: flex; flex-direction: column; align-items: center; padding-top: 0.7rem; gap: 1.1rem; flex-shrink: 0; }
.vt-activitybar svg { width: 18px; height: 18px; opacity: 0.55; }
.vt-activitybar svg.is-on { opacity: 1; }
.vt-sidebar { width: 180px; background: #252526; flex-shrink: 0; overflow-y: auto; border-right: 1px solid #1e1e1e; }
.vt-sidebar-head { font-size: 0.65rem; font-weight: 700; letter-spacing: 0.06em; color: #bbbbbb; padding: 0.6rem 0.8rem 0.3rem; }
.vt-sidebar-root { font-size: 0.74rem; color: #cccccc; padding: 0.2rem 0.7rem; display: flex; align-items: center; gap: 0.3rem; }
.vt-sidebar-folder { font-size: 0.74rem; color: #cccccc; padding: 0.2rem 0.7rem 0.2rem 1.4rem; display: flex; align-items: center; gap: 0.3rem; }
.vt-row {
display: flex; align-items: center; gap: 0.35rem; width: 100%; background: none; border: none;
color: #cccccc; font: inherit; font-size: 0.74rem; padding: 0.24rem 0.7rem 0.24rem 2.1rem;
cursor: pointer; text-align: left; border-left: 2px solid transparent;
}
.vt-row:hover { background: #2a2d2e; }
.vt-row.is-selected { background: #37373d; border-left-color: #0078d4; }
.vt-badge { width: 15px; height: 15px; border-radius: 3px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 0.46rem; font-weight: 700; color: #1a1a1a; background: #29b6f6; }
.vt-main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.vt-tabbar { display: flex; background: #252526; border-bottom: 1px solid #1e1e1e; overflow-x: auto; }
.vt-tab {
display: flex; align-items: center; gap: 0.35rem; background: #1e1e1e; color: #808080; font: inherit;
font-size: 0.72rem; padding: 0.45rem 0.8rem; border: none; border-right: 1px solid #1e1e1e;
border-top: 2px solid transparent; cursor: pointer; white-space: nowrap;
}
.vt-tab.is-active { color: #d4d4d4; border-top-color: #0078d4; background: #1e1e1e; }
.vt-tab .vt-badge { width: 13px; height: 13px; font-size: 0.42rem; }
.vt-code-wrap { flex: 1; background: #1e1e1e; overflow: auto; padding: 0.85rem 1rem; }
.vt-code-wrap pre { margin: 0; }
.vt-code-wrap code { font-family: var(--mono-font); font-size: 0.68rem; line-height: 1.65; color: #d4d4d8; white-space: pre; }
.tok-kw { color: #c678dd; }
.tok-tag { color: #e06c75; }
.tok-type { color: #61afef; }
.tok-attr { color: #d19a66; }
.tok-str { color: #98c379; }
.tok-expr { color: #56b6c2; }
.tok-punc { color: #6b7280; }
.tok-comment { color: #7f848e; font-style: italic; }
/* ===== terminal ===== */
.vt-terminal { background: #181818; border-top: 1px solid #2c2c2c; display: flex; flex-direction: column; height: 150px; flex-shrink: 0; }
.vt-term-head { display: flex; align-items: center; gap: 0.4rem; font-size: 0.62rem; letter-spacing: 0.05em; color: #9a9a9a; padding: 0.35rem 0.8rem; border-bottom: 1px solid #262626; text-transform: uppercase; }
.vt-term-body { flex: 1; overflow-y: auto; padding: 0.5rem 0.9rem; font-size: 0.72rem; line-height: 1.65; }
.vt-term-line { color: #d4d4d4; white-space: pre; opacity: 0; transform: translateY(2px); animation: vt-line-in 0.25s ease forwards; }
@keyframes vt-line-in { to { opacity: 1; transform: none; } }
.vt-term-line.is-cmd { color: #7ee787; }
.vt-term-line.is-ok { color: #7ee787; font-weight: 600; }
.vt-term-prompt { color: #7ee787; }
.vt-run-row { display: flex; align-items: center; gap: 0.5rem; margin-top: 0.2rem; }
.vt-run-btn {
font: inherit; font-size: 0.68rem; font-weight: 600; color: #1a1a1a; background: #7ee787;
border: none; border-radius: 4px; padding: 0.3rem 0.7rem; cursor: pointer; display: flex; align-items: center; gap: 0.3rem;
}
.vt-run-btn:disabled { opacity: 0.5; cursor: default; }
.vt-run-btn svg { width: 9px; height: 9px; }
.vt-run-hint { color: #6b7280; font-size: 0.68rem; }
@media (max-width: 620px) {
.vt-sidebar { width: 140px; }
.vt-body { height: 360px; }
}
@media (max-width: 480px) { .vt-activitybar { display: none; } }
/* ===== browser output ===== */
.vt-output-label {
font-family: var(--mono-font); font-size: 0.68rem; letter-spacing: 0.1em; text-transform: uppercase;
color: var(--ink-soft); text-align: center; margin: 1.5rem 0 0.7rem;
}
.vt-browser {
border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; max-width: 440px; margin: 0 auto;
box-shadow: 0 10px 24px -12px rgba(26,26,26,0.18);
opacity: 0; transform: translateY(8px); transition: opacity 0.4s ease, transform 0.4s ease; pointer-events: none;
}
.vt-browser.is-shown { opacity: 1; transform: none; pointer-events: auto; }
.vt-browser-bar { background: #e9e9e9; padding: 0.5rem 0.7rem; display: flex; align-items: center; gap: 0.5rem; }
.vt-browser-bar .vt-dots span { width: 8px; height: 8px; }
.vt-browser-url { font-family: var(--mono-font); font-size: 0.65rem; color: #555; background: #fff; border-radius: 4px; padding: 0.2rem 0.5rem; flex: 1; }
.vt-output-placeholder { text-align: center; font-size: 0.82rem; color: var(--ink-soft); }
/* --- ShoppingCart --- */
.vt-cart { background: #fff; padding: 1.3rem 1.4rem; font-family: Arial, var(--body-font); text-align: left; }
.vt-cart h2 { font-size: 1rem; margin: 0.6rem 0 0.6rem; color: #000; }
.vt-cart h2:first-child { margin-top: 0; }
.vt-cart hr { border: none; border-top: 1px solid #ddd; margin: 0.9rem 0; }
.vt-products { display: flex; gap: 0.6rem; flex-wrap: wrap; }
.vt-product-btn {
font-family: inherit; font-size: 0.78rem; color: #1a1a1a; background: #f1f1f1; border: 1px solid #ccc;
border-radius: 6px; padding: 0.5rem 0.8rem; cursor: pointer; transition: background 0.15s;
}
.vt-product-btn:hover { background: #e6e6e6; }
.vt-cart-total { font-size: 0.9rem; color: #000; margin: 0 0 0.7rem; }
.vt-cart-empty { color: #666; font-size: 0.85rem; }
.vt-cart-list { list-style: none; margin: 0 0 0.8rem; padding: 0; }
.vt-cart-list li {
font-size: 0.85rem; color: #222; margin-bottom: 0.6rem; display: flex; align-items: center; justify-content: space-between;
background: #fafaf8; border: 1px solid #eee; border-radius: 6px; padding: 0.5rem 0.7rem;
}
.vt-remove-btn {
font-family: inherit; font-size: 0.72rem; color: #fff; background: #dc2626; border: none; border-radius: 5px;
padding: 0.3rem 0.6rem; cursor: pointer; margin-left: 0.6rem; flex-shrink: 0;
}
.vt-clear-btn {
font-family: inherit; font-size: 0.8rem; font-weight: 600; color: #fff; background: var(--accent); border: none;
border-radius: 6px; padding: 0.5rem 0.9rem; cursor: pointer;
}
.vt-takeaway {
margin-top: 1.7rem; padding: 0.95rem 1.2rem; background: var(--accent-soft); border-left: 3px solid var(--accent);
border-radius: 4px; font-size: 0.9rem; color: var(--ink); line-height: 1.5; max-width: 660px; margin-left: auto; margin-right: auto;
}
.vt-takeaway b { color: var(--accent-deep); }
.vt-takeaway code { font-family: var(--mono-font); }
@media (prefers-reduced-motion: reduce) {
.infographic-vscodeterm *, .infographic-vscodeterm *::before, .infographic-vscodeterm *::after {
transition-duration: 0.001ms !important; animation-duration: 0.001ms !important;
}
}
</style>
<div class="vt-eyebrow">useReducer</div>
<p class="vt-sub">Run the dev server, then add and remove items — the total is computed by the reducer.</p>
<div class="vt-window">
<div class="vt-titlebar">
<div class="vt-dots"><span></span><span></span><span></span></div>
<div class="vt-titlebar-text">cart-demo — Visual Studio Code</div>
</div>
<div class="vt-body">
<div class="vt-activitybar">
<svg class="is-on" viewBox="0 0 24 24" fill="none" aria-hidden="true"><rect x="3" y="4" width="7" height="7" rx="1" stroke="#fff" stroke-width="1.6"/><rect x="14" y="4" width="7" height="7" rx="1" stroke="#fff" stroke-width="1.6"/><rect x="3" y="15" width="7" height="7" rx="1" stroke="#fff" stroke-width="1.6"/><rect x="14" y="15" width="7" height="7" rx="1" stroke="#fff" stroke-width="1.6"/></svg>
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="10" cy="10" r="6.5" stroke="#fff" stroke-width="1.6"/><line x1="15" y1="15" x2="20" y2="20" stroke="#fff" stroke-width="1.6" stroke-linecap="round"/></svg>
</div>
<div class="vt-sidebar">
<div class="vt-sidebar-head">EXPLORER</div>
<div class="vt-sidebar-root">▾ CART-DEMO</div>
<div class="vt-sidebar-folder">▾ src</div>
<button class="vt-row" data-file="actiontypes" type="button"><span class="vt-badge">JS</span><span>ActionTypes.js</span></button>
<button class="vt-row" data-file="cartreducer" type="button"><span class="vt-badge">JS</span><span>CartReducer.js</span></button>
<button class="vt-row is-selected" data-file="shoppingcart" type="button"><span class="vt-badge">JS</span><span>ShoppingCart.jsx</span></button>
</div>
<div class="vt-resize-h" id="vtSidebarHandle" title="Drag to resize sidebar"></div>
<div class="vt-main">
<div class="vt-tabbar">
<button class="vt-toggle-btn" id="vtToggleSidebar" type="button" aria-label="Toggle sidebar" title="Toggle sidebar">
<svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><rect x="1.5" y="2" width="13" height="12" rx="1.5" stroke="currentColor" stroke-width="1.3"/><line x1="6" y1="2" x2="6" y2="14" stroke="currentColor" stroke-width="1.3"/></svg>
</button>
<button class="vt-tab" data-file="actiontypes" type="button"><span class="vt-badge">JS</span><span>ActionTypes.js</span></button>
<button class="vt-tab" data-file="cartreducer" type="button"><span class="vt-badge">JS</span><span>CartReducer.js</span></button>
<button class="vt-tab is-active" data-file="shoppingcart" type="button"><span class="vt-badge">JS</span><span>ShoppingCart.jsx</span></button>
</div>
<div class="vt-code-wrap">
<pre><code id="vtCode"></code></pre>
</div>
<div class="vt-resize-v" id="vtTerminalHandle" title="Drag to resize terminal"></div>
<div class="vt-terminal">
<div class="vt-term-head">
<button class="vt-toggle-btn vt-term-toggle" id="vtToggleTerminal" type="button" aria-label="Toggle terminal" title="Toggle terminal">
<svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M4 6l4 4 4-4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<span>Terminal</span>
</div>
<div class="vt-term-body">
<div id="vtTermLines"><div class="vt-term-line" style="animation-delay:0s;"><span class="vt-term-prompt">$</span> </div></div>
<div class="vt-run-row">
<button class="vt-run-btn" id="vtRunBtn" type="button">
<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 1.5v9l7-4.5z" fill="currentColor"/></svg>
<span id="vtRunLabel">npm start</span>
</button>
<span class="vt-run-hint" id="vtRunHint">runs the dev server</span>
</div>
</div>
</div>
</div>
</div>
<div class="vt-window-resize" id="vtWindowHandle" title="Drag to resize window"><span></span></div>
</div>
<div class="vt-output-label">Output</div>
<div id="vtOutputArea">
<p class="vt-output-placeholder">Run <code style="font-family:var(--mono-font)">npm start</code> above to see it here.</p>
<div class="vt-browser" id="vtBrowser">
<div class="vt-browser-bar">
<div class="vt-dots"><span></span><span></span><span></span></div>
<div class="vt-browser-url">localhost:3000</div>
</div>
<div class="vt-cart">
<h2>Store Products</h2>
<div class="vt-products" id="vtProducts"></div>
<hr />
<h2>Your Cart</h2>
<p class="vt-cart-total"><strong>Total Price: $<span id="vtTotal">0</span></strong></p>
<div id="vtCartBody"><p class="vt-cart-empty">Your cart is empty.</p></div>
</div>
</div>
</div>
</div>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@500;600&family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<script>
(function () {
var root = document.getElementById('vt');
if (!root) return;
/* --- dark mode detection: body attribute > cookie > postMessage > light --- */
function applyDark(dark) {
if (dark) root.setAttribute('data-theme', 'dark');
else root.removeAttribute('data-theme');
}
var bodyAttr = document.body.getAttribute('data-darkmode');
var dark;
if (bodyAttr === 'true') dark = true;
else if (bodyAttr === 'false') dark = false;
else {
var match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
applyDark(dark);
window.addEventListener('message', function (e) {
if (e.data && e.data.type === 'darkMode') applyDark(!!e.data.value);
});
/* --- file switching --- */
var files = {
actiontypes:
'<span class="tok-kw">export</span> <span class="tok-kw">const</span> <span class="tok-type">CART_ACTIONS</span> <span class="tok-punc">=</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-attr">ADD_ITEM</span><span class="tok-punc">:</span> <span class="tok-str">\'ADD_ITEM\'</span><span class="tok-punc">,</span>\n' +
' <span class="tok-attr">REMOVE_ITEM</span><span class="tok-punc">:</span> <span class="tok-str">\'REMOVE_ITEM\'</span><span class="tok-punc">,</span>\n' +
' <span class="tok-attr">CLEAR_CART</span><span class="tok-punc">:</span> <span class="tok-str">\'CLEAR_CART\'</span><span class="tok-punc">,</span>\n' +
'<span class="tok-punc">};</span>',
cartreducer:
'<span class="tok-kw">import</span> <span class="tok-punc">{</span> <span class="tok-type">CART_ACTIONS</span> <span class="tok-punc">}</span> <span class="tok-kw">from</span> <span class="tok-str">\'./ActionTypes\'</span><span class="tok-punc">;</span>\n\n' +
'<span class="tok-comment">// 1. Define the Initial State</span>\n' +
'<span class="tok-kw">export</span> <span class="tok-kw">const</span> initialState <span class="tok-punc">=</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-attr">items</span><span class="tok-punc">:</span> <span class="tok-punc">[],</span>\n' +
' <span class="tok-attr">total</span><span class="tok-punc">:</span> <span class="tok-expr">0</span><span class="tok-punc">,</span>\n' +
'<span class="tok-punc">};</span>\n\n' +
'<span class="tok-comment">// 2. Define the Reducer Function</span>\n' +
'<span class="tok-kw">export</span> <span class="tok-kw">function</span> cartReducer<span class="tok-punc">(</span>state<span class="tok-punc">,</span> action<span class="tok-punc">) {</span>\n' +
' <span class="tok-kw">switch</span> <span class="tok-punc">(</span>action.type<span class="tok-punc">) {</span>\n' +
' <span class="tok-kw">case</span> <span class="tok-type">CART_ACTIONS</span><span class="tok-punc">.</span>ADD_ITEM<span class="tok-punc">: {</span>\n' +
' <span class="tok-kw">const</span> existingItemIndex <span class="tok-punc">=</span> state.items.findIndex<span class="tok-punc">(</span>item <span class="tok-punc">=></span> item.id <span class="tok-punc">===</span> action.payload.id<span class="tok-punc">);</span>\n' +
' <span class="tok-kw">let</span> updatedItems<span class="tok-punc">;</span>\n\n' +
' <span class="tok-kw">if</span> <span class="tok-punc">(</span>existingItemIndex <span class="tok-punc">></span> <span class="tok-punc">-</span><span class="tok-expr">1</span><span class="tok-punc">) {</span>\n' +
' <span class="tok-comment">// Create a new array and update the specific item\'s quantity</span>\n' +
' updatedItems <span class="tok-punc">=</span> <span class="tok-punc">[...</span>state.items<span class="tok-punc">];</span>\n' +
' updatedItems<span class="tok-punc">[</span>existingItemIndex<span class="tok-punc">]</span> <span class="tok-punc">=</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-punc">...</span>updatedItems<span class="tok-punc">[</span>existingItemIndex<span class="tok-punc">],</span>\n' +
' <span class="tok-attr">quantity</span><span class="tok-punc">:</span> updatedItems<span class="tok-punc">[</span>existingItemIndex<span class="tok-punc">].</span>quantity <span class="tok-punc">+</span> <span class="tok-expr">1</span>\n' +
' <span class="tok-punc">};</span>\n' +
' <span class="tok-punc">} else {</span>\n' +
' <span class="tok-comment">// Add new item with quantity of 1</span>\n' +
' updatedItems <span class="tok-punc">=</span> <span class="tok-punc">[...</span>state.items<span class="tok-punc">,</span> <span class="tok-punc">{</span> <span class="tok-punc">...</span>action.payload<span class="tok-punc">,</span> <span class="tok-attr">quantity</span><span class="tok-punc">:</span> <span class="tok-expr">1</span> <span class="tok-punc">}];</span>\n' +
' <span class="tok-punc">}</span>\n\n' +
' <span class="tok-kw">return</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-punc">...</span>state<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">items</span><span class="tok-punc">:</span> updatedItems<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">total</span><span class="tok-punc">:</span> state.total <span class="tok-punc">+</span> action.payload.price<span class="tok-punc">,</span>\n' +
' <span class="tok-punc">};</span>\n' +
' <span class="tok-punc">}</span>\n\n' +
' <span class="tok-kw">case</span> <span class="tok-type">CART_ACTIONS</span><span class="tok-punc">.</span>REMOVE_ITEM<span class="tok-punc">: {</span>\n' +
' <span class="tok-kw">const</span> itemToRemove <span class="tok-punc">=</span> state.items.find<span class="tok-punc">(</span>item <span class="tok-punc">=></span> item.id <span class="tok-punc">===</span> action.payload.id<span class="tok-punc">);</span>\n' +
' <span class="tok-kw">const</span> filteredItems <span class="tok-punc">=</span> state.items.filter<span class="tok-punc">(</span>item <span class="tok-punc">=></span> item.id <span class="tok-punc">!==</span> action.payload.id<span class="tok-punc">);</span>\n\n' +
' <span class="tok-kw">return</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-punc">...</span>state<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">items</span><span class="tok-punc">:</span> filteredItems<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">total</span><span class="tok-punc">:</span> state.total <span class="tok-punc">-</span> <span class="tok-punc">(</span>itemToRemove.price <span class="tok-punc">*</span> itemToRemove.quantity<span class="tok-punc">),</span>\n' +
' <span class="tok-punc">};</span>\n' +
' <span class="tok-punc">}</span>\n\n' +
' <span class="tok-kw">case</span> <span class="tok-type">CART_ACTIONS</span><span class="tok-punc">.</span>CLEAR_CART<span class="tok-punc">:</span>\n' +
' <span class="tok-kw">return</span> initialState<span class="tok-punc">;</span>\n\n' +
' <span class="tok-kw">default</span><span class="tok-punc">:</span>\n' +
' <span class="tok-kw">return</span> state<span class="tok-punc">;</span>\n' +
' <span class="tok-punc">}</span>\n' +
'<span class="tok-punc">}</span>',
shoppingcart:
'<span class="tok-kw">import</span> <span class="tok-type">React</span><span class="tok-punc">,</span> <span class="tok-punc">{</span> useReducer <span class="tok-punc">}</span> <span class="tok-kw">from</span> <span class="tok-str">\'react\'</span><span class="tok-punc">;</span>\n' +
'<span class="tok-kw">import</span> <span class="tok-punc">{</span> cartReducer<span class="tok-punc">,</span> initialState <span class="tok-punc">}</span> <span class="tok-kw">from</span> <span class="tok-str">\'./CartReducer\'</span><span class="tok-punc">;</span>\n' +
'<span class="tok-kw">import</span> <span class="tok-punc">{</span> <span class="tok-type">CART_ACTIONS</span> <span class="tok-punc">}</span> <span class="tok-kw">from</span> <span class="tok-str">\'./ActionTypes\'</span><span class="tok-punc">;</span>\n\n' +
'<span class="tok-kw">const</span> <span class="tok-type">PRODUCTS</span> <span class="tok-punc">=</span> <span class="tok-punc">[</span>\n' +
' <span class="tok-punc">{</span> <span class="tok-attr">id</span><span class="tok-punc">:</span> <span class="tok-expr">1</span><span class="tok-punc">,</span> <span class="tok-attr">name</span><span class="tok-punc">:</span> <span class="tok-str">\'Mechanical Keyboard\'</span><span class="tok-punc">,</span> <span class="tok-attr">price</span><span class="tok-punc">:</span> <span class="tok-expr">100</span> <span class="tok-punc">},</span>\n' +
' <span class="tok-punc">{</span> <span class="tok-attr">id</span><span class="tok-punc">:</span> <span class="tok-expr">2</span><span class="tok-punc">,</span> <span class="tok-attr">name</span><span class="tok-punc">:</span> <span class="tok-str">\'Gaming Mouse\'</span><span class="tok-punc">,</span> <span class="tok-attr">price</span><span class="tok-punc">:</span> <span class="tok-expr">50</span> <span class="tok-punc">},</span>\n' +
'<span class="tok-punc">];</span>\n\n' +
'<span class="tok-kw">export</span> <span class="tok-kw">default</span> <span class="tok-kw">function</span> <span class="tok-type">ShoppingCart</span><span class="tok-punc">() {</span>\n' +
' <span class="tok-kw">const</span> <span class="tok-punc">[</span>state<span class="tok-punc">,</span> dispatch<span class="tok-punc">]</span> <span class="tok-punc">=</span> useReducer<span class="tok-punc">(</span>cartReducer<span class="tok-punc">,</span> initialState<span class="tok-punc">);</span>\n\n' +
' <span class="tok-kw">return</span> <span class="tok-punc">(</span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">div</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">h2</span><span class="tok-punc">></span>Store Products<span class="tok-punc"></</span><span class="tok-tag">h2</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc">{</span><span class="tok-type">PRODUCTS</span>.map<span class="tok-punc">(</span>product <span class="tok-punc">=> (</span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">button</span> <span class="tok-attr">key</span><span class="tok-punc">={</span>product.id<span class="tok-punc">}</span>\n' +
' <span class="tok-attr">onClick</span><span class="tok-punc">={</span><span class="tok-punc">()</span> <span class="tok-punc">=></span> dispatch<span class="tok-punc">({</span> <span class="tok-attr">type</span><span class="tok-punc">:</span> <span class="tok-type">CART_ACTIONS</span>.ADD_ITEM<span class="tok-punc">,</span> <span class="tok-attr">payload</span><span class="tok-punc">:</span> product <span class="tok-punc">})}></span>\n' +
' Add <span class="tok-punc">{</span>product.name<span class="tok-punc">}</span> <span class="tok-punc">(</span>$<span class="tok-punc">{</span>product.price<span class="tok-punc">})</span>\n' +
' <span class="tok-punc"></</span><span class="tok-tag">button</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc">))}</span>\n\n' +
' <span class="tok-punc"><</span><span class="tok-tag">h2</span><span class="tok-punc">></span>Your Cart<span class="tok-punc"></</span><span class="tok-tag">h2</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">p</span><span class="tok-punc">></span>Total<span class="tok-punc">:</span> $<span class="tok-punc">{</span>state.total<span class="tok-punc">}</</span><span class="tok-tag">p</span><span class="tok-punc">></span>\n\n' +
' <span class="tok-punc">{</span>state.items.map<span class="tok-punc">(</span>item <span class="tok-punc">=> (</span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">li</span> <span class="tok-attr">key</span><span class="tok-punc">={</span>item.id<span class="tok-punc">}></span>\n' +
' <span class="tok-punc">{</span>item.name<span class="tok-punc">}</span> <span class="tok-punc">(</span>x<span class="tok-punc">{</span>item.quantity<span class="tok-punc">})</span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">button</span> <span class="tok-attr">onClick</span><span class="tok-punc">={</span><span class="tok-punc">()</span> <span class="tok-punc">=></span> dispatch<span class="tok-punc">({</span> <span class="tok-attr">type</span><span class="tok-punc">:</span> <span class="tok-type">CART_ACTIONS</span>.REMOVE_ITEM<span class="tok-punc">,</span> <span class="tok-attr">payload</span><span class="tok-punc">:</span> item <span class="tok-punc">})}></span>Remove<span class="tok-punc"></</span><span class="tok-tag">button</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc"></</span><span class="tok-tag">li</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc">))}</span>\n\n' +
' <span class="tok-punc"><</span><span class="tok-tag">button</span> <span class="tok-attr">onClick</span><span class="tok-punc">={</span><span class="tok-punc">()</span> <span class="tok-punc">=></span> dispatch<span class="tok-punc">({</span> <span class="tok-attr">type</span><span class="tok-punc">:</span> <span class="tok-type">CART_ACTIONS</span>.CLEAR_CART <span class="tok-punc">})}></span>\n' +
' Clear Entire Cart\n' +
' <span class="tok-punc"></</span><span class="tok-tag">button</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc"></</span><span class="tok-tag">div</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc">);</span>\n' +
'<span class="tok-punc">}</span>'
};
var codeEl = root.querySelector('#vtCode');
var rows = root.querySelectorAll('.vt-row');
var tabs = root.querySelectorAll('.vt-tab');
function selectFile(id) {
codeEl.innerHTML = files[id];
rows.forEach(function (r) { r.classList.toggle('is-selected', r.getAttribute('data-file') === id); });
tabs.forEach(function (t) { t.classList.toggle('is-active', t.getAttribute('data-file') === id); });
}
rows.forEach(function (r) { r.addEventListener('click', function () { selectFile(r.getAttribute('data-file')); }); });
tabs.forEach(function (t) { t.addEventListener('click', function () { selectFile(t.getAttribute('data-file')); }); });
selectFile('shoppingcart');
/* --- terminal run simulation --- */
var termLines = root.querySelector('#vtTermLines');
var runBtn = root.querySelector('#vtRunBtn');
var runLabel = root.querySelector('#vtRunLabel');
var runHint = root.querySelector('#vtRunHint');
var browser = root.querySelector('#vtBrowser');
var placeholder = root.querySelector('.vt-output-placeholder');
var running = false;
var lines = [
{ text: '$ npm start', cls: 'is-cmd', delay: 0 },
{ text: 'Starting the development server\u2026', cls: '', delay: 500 },
{ text: 'Compiled successfully!', cls: 'is-ok', delay: 1350 },
{ text: 'You can now view cart-demo in the browser.', cls: '', delay: 1600 },
{ text: ' Local: http://localhost:3000', cls: '', delay: 1850 }
];
runBtn.addEventListener('click', function () {
if (running) return;
running = true;
runBtn.disabled = true;
runLabel.textContent = 'running\u2026';
browser.classList.remove('is-shown');
placeholder.style.display = 'block';
termLines.innerHTML = '';
lines.forEach(function (line) {
setTimeout(function () {
var div = document.createElement('div');
div.className = 'vt-term-line ' + line.cls;
div.textContent = line.text;
termLines.appendChild(div);
}, line.delay);
});
setTimeout(function () {
placeholder.style.display = 'none';
browser.classList.add('is-shown');
runBtn.disabled = false;
runLabel.textContent = 'npm start';
runHint.textContent = 'server running \u2014 rerun anytime';
running = false;
}, 2300);
});
/* --- resize handles (pointer-capture drag) --- */
function makeResizable(handle, opts) {
var dragging = false, startPos = 0, startSize = 0;
handle.addEventListener('pointerdown', function (e) {
dragging = true;
handle.classList.add('is-dragging');
startPos = opts.axis === 'x' ? e.clientX : e.clientY;
startSize = opts.target.getBoundingClientRect()[opts.axis === 'x' ? 'width' : 'height'];
handle.setPointerCapture(e.pointerId);
e.preventDefault();
});
handle.addEventListener('pointermove', function (e) {
if (!dragging) return;
var pos = opts.axis === 'x' ? e.clientX : e.clientY;
var delta = pos - startPos;
if (opts.invert) delta = -delta;
var size = Math.min(opts.max, Math.max(opts.min, startSize + delta));
opts.target.style[opts.prop] = size + 'px';
if (opts.onResize) opts.onResize(size);
});
function stop() { dragging = false; handle.classList.remove('is-dragging'); }
handle.addEventListener('pointerup', stop);
handle.addEventListener('pointercancel', stop);
}
var sidebar = root.querySelector('.vt-sidebar');
var sidebarHandle = root.querySelector('#vtSidebarHandle');
var lastSidebarWidth = sidebar.getBoundingClientRect().width || 180;
makeResizable(sidebarHandle, {
axis: 'x', target: sidebar, prop: 'width', min: 110, max: 300, invert: false,
onResize: function (s) { lastSidebarWidth = s; }
});
var terminal = root.querySelector('.vt-terminal');
var terminalHandle = root.querySelector('#vtTerminalHandle');
var lastTerminalHeight = terminal.getBoundingClientRect().height || 150;
makeResizable(terminalHandle, {
axis: 'y', target: terminal, prop: 'height', min: 60, max: 280, invert: true,
onResize: function (s) { lastTerminalHeight = s; }
});
var vtBody = root.querySelector('.vt-body');
var windowHandle = root.querySelector('#vtWindowHandle');
makeResizable(windowHandle, {
axis: 'y', target: vtBody, prop: 'height', min: 320, max: 620, invert: false
});
/* --- show/hide toggles --- */
var toggleSidebarBtn = root.querySelector('#vtToggleSidebar');
var sidebarHidden = false;
toggleSidebarBtn.addEventListener('click', function () {
sidebarHidden = !sidebarHidden;
if (sidebarHidden) {
var w = sidebar.getBoundingClientRect().width;
if (w > 0) lastSidebarWidth = w;
sidebar.classList.add('is-hidden');
sidebarHandle.style.display = 'none';
} else {
sidebar.classList.remove('is-hidden');
sidebar.style.width = lastSidebarWidth + 'px';
sidebarHandle.style.display = '';
}
});
var toggleTerminalBtn = root.querySelector('#vtToggleTerminal');
var terminalCollapsed = false;
toggleTerminalBtn.addEventListener('click', function () {
terminalCollapsed = !terminalCollapsed;
if (terminalCollapsed) {
var h = terminal.getBoundingClientRect().height;
if (h > 30) lastTerminalHeight = h;
terminal.classList.add('is-collapsed');
terminalHandle.style.display = 'none';
} else {
terminal.classList.remove('is-collapsed');
terminal.style.height = lastTerminalHeight + 'px';
terminalHandle.style.display = '';
}
});
/* --- real behavior: an actual cartReducer driving the output --- */
var CART_ACTIONS = { ADD_ITEM: 'ADD_ITEM', REMOVE_ITEM: 'REMOVE_ITEM', CLEAR_CART: 'CLEAR_CART' };
var initialState = { items: [], total: 0 };
function cartReducer(state, action) {
switch (action.type) {
case CART_ACTIONS.ADD_ITEM: {
var existingItemIndex = state.items.findIndex(function (item) { return item.id === action.payload.id; });
var updatedItems;
if (existingItemIndex > -1) {
updatedItems = state.items.slice();
updatedItems[existingItemIndex] = Object.assign({}, updatedItems[existingItemIndex], {
quantity: updatedItems[existingItemIndex].quantity + 1
});
} else {
updatedItems = state.items.concat([Object.assign({}, action.payload, { quantity: 1 })]);
}
return Object.assign({}, state, { items: updatedItems, total: state.total + action.payload.price });
}
case CART_ACTIONS.REMOVE_ITEM: {
var itemToRemove = state.items.find(function (item) { return item.id === action.payload.id; });
var filteredItems = state.items.filter(function (item) { return item.id !== action.payload.id; });
return Object.assign({}, state, {
items: filteredItems,
total: state.total - (itemToRemove.price * itemToRemove.quantity)
});
}
case CART_ACTIONS.CLEAR_CART:
return initialState;
default:
return state;
}
}
var PRODUCTS = [
{ id: 1, name: 'Mechanical Keyboard', price: 100 },
{ id: 2, name: 'Gaming Mouse', price: 50 }
];
var state = initialState;
var productsEl = root.querySelector('#vtProducts');
var totalEl = root.querySelector('#vtTotal');
var cartBodyEl = root.querySelector('#vtCartBody');
function dispatch(action) {
state = cartReducer(state, action);
render();
}
function render() {
totalEl.textContent = state.total;
if (state.items.length === 0) {
cartBodyEl.innerHTML = '<p class="vt-cart-empty">Your cart is empty.</p>';
return;
}
var ul = document.createElement('ul');
ul.className = 'vt-cart-list';
state.items.forEach(function (item) {
var li = document.createElement('li');
var label = document.createElement('span');
label.textContent = item.name + ' — $' + item.price + ' (x' + item.quantity + ')';
var removeBtn = document.createElement('button');
removeBtn.className = 'vt-remove-btn';
removeBtn.type = 'button';
removeBtn.textContent = 'Remove';
removeBtn.addEventListener('click', function () {
dispatch({ type: CART_ACTIONS.REMOVE_ITEM, payload: item });
});
li.appendChild(label);
li.appendChild(removeBtn);
ul.appendChild(li);
});
var clearBtn = document.createElement('button');
clearBtn.className = 'vt-clear-btn';
clearBtn.type = 'button';
clearBtn.textContent = 'Clear Entire Cart';
clearBtn.addEventListener('click', function () {
dispatch({ type: CART_ACTIONS.CLEAR_CART });
});
cartBodyEl.innerHTML = '';
cartBodyEl.appendChild(ul);
cartBodyEl.appendChild(clearBtn);
}
PRODUCTS.forEach(function (product) {
var btn = document.createElement('button');
btn.className = 'vt-product-btn';
btn.type = 'button';
btn.textContent = 'Add ' + product.name + ' ($' + product.price + ')';
btn.addEventListener('click', function () {
dispatch({ type: CART_ACTIONS.ADD_ITEM, payload: product });
});
productsEl.appendChild(btn);
});
render();
})();
</script>Problem: If we remove the item from this, all the quantities will be removed. Solving it:
<div class="infographic-vscodeterm" id="vt">
<style>
.infographic-vscodeterm {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb;
--accent-deep: #1942a8;
--accent-soft: #e3ebfd;
--line: #ddd6c9;
--radius: 8px;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', system-ui, sans-serif;
--mono-font: 'IBM Plex Mono', monospace;
max-width: 900px;
margin: 0 auto;
box-sizing: border-box;
background: transparent;
color: var(--ink);
font-family: var(--body-font);
}
.infographic-vscodeterm[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #13171f;
--paper-alt: #1c212b;
--accent: #5b8def;
--accent-deep: #8fb4ff;
--accent-soft: #20293f;
--line: #2c313d;
}
.infographic-vscodeterm * { box-sizing: border-box; min-width: 0; }
.vt-eyebrow {
font-family: var(--mono-font); font-size: 0.72rem; letter-spacing: 0.1em;
text-transform: uppercase; color: var(--accent); margin: 0 0 0.45rem;
display: flex; align-items: center; justify-content: center; gap: 0.4rem;
}
.vt-eyebrow::before { content: ""; width: 14px; height: 2px; background: var(--accent); display: inline-block; }
.vt-title {
font-family: var(--display-font); font-size: clamp(1.5rem, 4vw, 2.3rem); text-align: center;
margin: 0 0 0.5rem; line-height: 1.14; letter-spacing: -0.01em;
}
.vt-sub { color: var(--ink-soft); font-size: 0.95rem; text-align: center; margin: 0 0 1.7rem; }
/* ===== VS Code window — fixed dark theme regardless of page mode ===== */
.vt-window { border-radius: 8px; overflow: hidden; box-shadow: 0 16px 40px -14px rgba(0,0,0,0.45); border: 1px solid #1e1e1e; font-family: var(--mono-font); }
.vt-titlebar { background: #323233; display: flex; align-items: center; padding: 0.5rem 0.8rem; position: relative; }
.vt-dots { display: flex; gap: 0.4rem; }
.vt-dots span { width: 10px; height: 10px; border-radius: 50%; display: block; }
.vt-dots span:nth-child(1) { background: #ff5f56; }
.vt-dots span:nth-child(2) { background: #ffbd2e; }
.vt-dots span:nth-child(3) { background: #27c93f; }
.vt-titlebar-text { position: absolute; left: 50%; transform: translateX(-50%); font-size: 0.72rem; color: #cccccc; }
.vt-body { display: flex; height: 340px; }
.vt-resize-h { width: 5px; cursor: col-resize; background: transparent; flex-shrink: 0; transition: background 0.15s; touch-action: none; }
.vt-resize-h:hover, .vt-resize-h.is-dragging { background: #0078d4; }
.vt-resize-v { height: 5px; cursor: row-resize; background: transparent; flex-shrink: 0; transition: background 0.15s; touch-action: none; }
.vt-resize-v:hover, .vt-resize-v.is-dragging { background: #0078d4; }
.vt-window-resize {
height: 9px; background: #252526; cursor: row-resize; display: flex; align-items: center;
justify-content: center; border-top: 1px solid #1e1e1e; touch-action: none;
}
.vt-window-resize span { width: 30px; height: 3px; border-radius: 2px; background: #4a4a52; }
.vt-window-resize:hover span, .vt-window-resize.is-dragging span { background: #0078d4; }
.vt-toggle-btn {
background: none; border: none; color: #9a9a9a; cursor: pointer; display: flex; align-items: center;
padding: 0.3rem; border-radius: 3px; flex-shrink: 0;
}
.vt-toggle-btn:hover { background: #2a2d2e; color: #fff; }
.vt-toggle-btn svg { width: 13px; height: 13px; }
.vt-sidebar.is-hidden { width: 0 !important; overflow: hidden; border-right: none; }
.vt-terminal.is-collapsed { height: auto !important; }
.vt-terminal.is-collapsed .vt-term-body { display: none; }
.vt-terminal.is-collapsed .vt-term-toggle svg { transform: rotate(-90deg); }
.vt-activitybar { width: 40px; background: #333333; display: flex; flex-direction: column; align-items: center; padding-top: 0.7rem; gap: 1.1rem; flex-shrink: 0; }
.vt-activitybar svg { width: 18px; height: 18px; opacity: 0.55; }
.vt-activitybar svg.is-on { opacity: 1; }
.vt-sidebar { width: 180px; background: #252526; flex-shrink: 0; overflow-y: auto; border-right: 1px solid #1e1e1e; }
.vt-sidebar-head { font-size: 0.65rem; font-weight: 700; letter-spacing: 0.06em; color: #bbbbbb; padding: 0.6rem 0.8rem 0.3rem; }
.vt-sidebar-root { font-size: 0.74rem; color: #cccccc; padding: 0.2rem 0.7rem; display: flex; align-items: center; gap: 0.3rem; }
.vt-sidebar-folder { font-size: 0.74rem; color: #cccccc; padding: 0.2rem 0.7rem 0.2rem 1.4rem; display: flex; align-items: center; gap: 0.3rem; }
.vt-row {
display: flex; align-items: center; gap: 0.35rem; width: 100%; background: none; border: none;
color: #cccccc; font: inherit; font-size: 0.74rem; padding: 0.24rem 0.7rem 0.24rem 2.1rem;
cursor: pointer; text-align: left; border-left: 2px solid transparent;
}
.vt-row:hover { background: #2a2d2e; }
.vt-row.is-selected { background: #37373d; border-left-color: #0078d4; }
.vt-badge { width: 15px; height: 15px; border-radius: 3px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 0.46rem; font-weight: 700; color: #1a1a1a; background: #29b6f6; }
.vt-main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.vt-tabbar { display: flex; background: #252526; border-bottom: 1px solid #1e1e1e; overflow-x: auto; }
.vt-tab {
display: flex; align-items: center; gap: 0.35rem; background: #1e1e1e; color: #808080; font: inherit;
font-size: 0.72rem; padding: 0.45rem 0.8rem; border: none; border-right: 1px solid #1e1e1e;
border-top: 2px solid transparent; cursor: pointer; white-space: nowrap;
}
.vt-tab.is-active { color: #d4d4d4; border-top-color: #0078d4; background: #1e1e1e; }
.vt-tab .vt-badge { width: 13px; height: 13px; font-size: 0.42rem; }
.vt-code-wrap { flex: 1; background: #1e1e1e; overflow: auto; padding: 0.85rem 1rem; }
.vt-code-wrap pre { margin: 0; }
.vt-code-wrap code { font-family: var(--mono-font); font-size: 0.68rem; line-height: 1.65; color: #d4d4d8; white-space: pre; }
.tok-kw { color: #c678dd; }
.tok-tag { color: #e06c75; }
.tok-type { color: #61afef; }
.tok-attr { color: #d19a66; }
.tok-str { color: #98c379; }
.tok-expr { color: #56b6c2; }
.tok-punc { color: #6b7280; }
.tok-comment { color: #7f848e; font-style: italic; }
/* ===== terminal ===== */
.vt-terminal { background: #181818; border-top: 1px solid #2c2c2c; display: flex; flex-direction: column; height: 150px; flex-shrink: 0; }
.vt-term-head { display: flex; align-items: center; gap: 0.4rem; font-size: 0.62rem; letter-spacing: 0.05em; color: #9a9a9a; padding: 0.35rem 0.8rem; border-bottom: 1px solid #262626; text-transform: uppercase; }
.vt-term-body { flex: 1; overflow-y: auto; padding: 0.5rem 0.9rem; font-size: 0.72rem; line-height: 1.65; }
.vt-term-line { color: #d4d4d4; white-space: pre; opacity: 0; transform: translateY(2px); animation: vt-line-in 0.25s ease forwards; }
@keyframes vt-line-in { to { opacity: 1; transform: none; } }
.vt-term-line.is-cmd { color: #7ee787; }
.vt-term-line.is-ok { color: #7ee787; font-weight: 600; }
.vt-term-prompt { color: #7ee787; }
.vt-run-row { display: flex; align-items: center; gap: 0.5rem; margin-top: 0.2rem; }
.vt-run-btn {
font: inherit; font-size: 0.68rem; font-weight: 600; color: #1a1a1a; background: #7ee787;
border: none; border-radius: 4px; padding: 0.3rem 0.7rem; cursor: pointer; display: flex; align-items: center; gap: 0.3rem;
}
.vt-run-btn:disabled { opacity: 0.5; cursor: default; }
.vt-run-btn svg { width: 9px; height: 9px; }
.vt-run-hint { color: #6b7280; font-size: 0.68rem; }
@media (max-width: 620px) {
.vt-sidebar { width: 140px; }
.vt-body { height: 360px; }
}
@media (max-width: 480px) { .vt-activitybar { display: none; } }
/* ===== browser output ===== */
.vt-output-label {
font-family: var(--mono-font); font-size: 0.68rem; letter-spacing: 0.1em; text-transform: uppercase;
color: var(--ink-soft); text-align: center; margin: 1.5rem 0 0.7rem;
}
.vt-browser {
border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; max-width: 440px; margin: 0 auto;
box-shadow: 0 10px 24px -12px rgba(26,26,26,0.18);
opacity: 0; transform: translateY(8px); transition: opacity 0.4s ease, transform 0.4s ease; pointer-events: none;
}
.vt-browser.is-shown { opacity: 1; transform: none; pointer-events: auto; }
.vt-browser-bar { background: #e9e9e9; padding: 0.5rem 0.7rem; display: flex; align-items: center; gap: 0.5rem; }
.vt-browser-bar .vt-dots span { width: 8px; height: 8px; }
.vt-browser-url { font-family: var(--mono-font); font-size: 0.65rem; color: #555; background: #fff; border-radius: 4px; padding: 0.2rem 0.5rem; flex: 1; }
.vt-output-placeholder { text-align: center; font-size: 0.82rem; color: var(--ink-soft); }
/* --- ShoppingCart --- */
.vt-cart { background: #fff; padding: 1.3rem 1.4rem; font-family: Arial, var(--body-font); text-align: left; }
.vt-cart h2 { font-size: 1rem; margin: 0.6rem 0 0.6rem; color: #000; }
.vt-cart h2:first-child { margin-top: 0; }
.vt-cart hr { border: none; border-top: 1px solid #ddd; margin: 0.9rem 0; }
.vt-products { display: flex; gap: 0.6rem; flex-wrap: wrap; }
.vt-product-btn {
font-family: inherit; font-size: 0.78rem; color: #1a1a1a; background: #f1f1f1; border: 1px solid #ccc;
border-radius: 6px; padding: 0.5rem 0.8rem; cursor: pointer; transition: background 0.15s;
}
.vt-product-btn:hover { background: #e6e6e6; }
.vt-cart-total { font-size: 0.9rem; color: #000; margin: 0 0 0.7rem; }
.vt-cart-empty { color: #666; font-size: 0.85rem; }
.vt-cart-list { list-style: none; margin: 0 0 0.8rem; padding: 0; }
.vt-cart-list li {
font-size: 0.85rem; color: #222; margin-bottom: 0.6rem; display: flex; align-items: center; justify-content: space-between;
background: #fafaf8; border: 1px solid #eee; border-radius: 6px; padding: 0.5rem 0.7rem;
}
.vt-qty-controls { display: flex; align-items: center; gap: 0.4rem; margin-left: 0.6rem; flex-shrink: 0; }
.vt-qty-btn {
font-family: inherit; font-size: 0.8rem; font-weight: 700; color: #1a1a1a; background: #eee; border: 1px solid #ccc;
border-radius: 5px; width: 22px; height: 22px; line-height: 1; cursor: pointer; display: flex; align-items: center; justify-content: center;
}
.vt-qty-btn:hover { background: #e0e0e0; }
.vt-remove-btn {
font-family: inherit; font-size: 0.72rem; color: #fff; background: #dc2626; border: none; border-radius: 5px;
padding: 0.3rem 0.6rem; cursor: pointer;
}
.vt-clear-btn {
font-family: inherit; font-size: 0.8rem; font-weight: 600; color: #fff; background: var(--accent); border: none;
border-radius: 6px; padding: 0.5rem 0.9rem; cursor: pointer;
}
.vt-takeaway {
margin-top: 1.7rem; padding: 0.95rem 1.2rem; background: var(--accent-soft); border-left: 3px solid var(--accent);
border-radius: 4px; font-size: 0.9rem; color: var(--ink); line-height: 1.5; max-width: 660px; margin-left: auto; margin-right: auto;
}
.vt-takeaway b { color: var(--accent-deep); }
.vt-takeaway code { font-family: var(--mono-font); }
@media (prefers-reduced-motion: reduce) {
.infographic-vscodeterm *, .infographic-vscodeterm *::before, .infographic-vscodeterm *::after {
transition-duration: 0.001ms !important; animation-duration: 0.001ms !important;
}
}
</style>
<div class="vt-eyebrow">useReducer</div>
<p class="vt-sub">Run the dev server, then use +/− to change quantity — removing goes one at a time, not straight to zero.</p>
<div class="vt-window">
<div class="vt-titlebar">
<div class="vt-dots"><span></span><span></span><span></span></div>
<div class="vt-titlebar-text">cart-demo — Visual Studio Code</div>
</div>
<div class="vt-body">
<div class="vt-activitybar">
<svg class="is-on" viewBox="0 0 24 24" fill="none" aria-hidden="true"><rect x="3" y="4" width="7" height="7" rx="1" stroke="#fff" stroke-width="1.6"/><rect x="14" y="4" width="7" height="7" rx="1" stroke="#fff" stroke-width="1.6"/><rect x="3" y="15" width="7" height="7" rx="1" stroke="#fff" stroke-width="1.6"/><rect x="14" y="15" width="7" height="7" rx="1" stroke="#fff" stroke-width="1.6"/></svg>
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="10" cy="10" r="6.5" stroke="#fff" stroke-width="1.6"/><line x1="15" y1="15" x2="20" y2="20" stroke="#fff" stroke-width="1.6" stroke-linecap="round"/></svg>
</div>
<div class="vt-sidebar">
<div class="vt-sidebar-head">EXPLORER</div>
<div class="vt-sidebar-root">▾ CART-DEMO</div>
<div class="vt-sidebar-folder">▾ src</div>
<button class="vt-row" data-file="actiontypes" type="button"><span class="vt-badge">JS</span><span>ActionTypes.js</span></button>
<button class="vt-row is-selected" data-file="cartreducer" type="button"><span class="vt-badge">JS</span><span>CartReducer.js</span></button>
<button class="vt-row" data-file="shoppingcart" type="button"><span class="vt-badge">JS</span><span>ShoppingCart.jsx</span></button>
</div>
<div class="vt-resize-h" id="vtSidebarHandle" title="Drag to resize sidebar"></div>
<div class="vt-main">
<div class="vt-tabbar">
<button class="vt-toggle-btn" id="vtToggleSidebar" type="button" aria-label="Toggle sidebar" title="Toggle sidebar">
<svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><rect x="1.5" y="2" width="13" height="12" rx="1.5" stroke="currentColor" stroke-width="1.3"/><line x1="6" y1="2" x2="6" y2="14" stroke="currentColor" stroke-width="1.3"/></svg>
</button>
<button class="vt-tab" data-file="actiontypes" type="button"><span class="vt-badge">JS</span><span>ActionTypes.js</span></button>
<button class="vt-tab is-active" data-file="cartreducer" type="button"><span class="vt-badge">JS</span><span>CartReducer.js</span></button>
<button class="vt-tab" data-file="shoppingcart" type="button"><span class="vt-badge">JS</span><span>ShoppingCart.jsx</span></button>
</div>
<div class="vt-code-wrap">
<pre><code id="vtCode"></code></pre>
</div>
<div class="vt-resize-v" id="vtTerminalHandle" title="Drag to resize terminal"></div>
<div class="vt-terminal">
<div class="vt-term-head">
<button class="vt-toggle-btn vt-term-toggle" id="vtToggleTerminal" type="button" aria-label="Toggle terminal" title="Toggle terminal">
<svg viewBox="0 0 16 16" fill="none" aria-hidden="true"><path d="M4 6l4 4 4-4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
</button>
<span>Terminal</span>
</div>
<div class="vt-term-body">
<div id="vtTermLines"><div class="vt-term-line" style="animation-delay:0s;"><span class="vt-term-prompt">$</span> </div></div>
<div class="vt-run-row">
<button class="vt-run-btn" id="vtRunBtn" type="button">
<svg viewBox="0 0 12 12" aria-hidden="true"><path d="M2.5 1.5v9l7-4.5z" fill="currentColor"/></svg>
<span id="vtRunLabel">npm start</span>
</button>
<span class="vt-run-hint" id="vtRunHint">runs the dev server</span>
</div>
</div>
</div>
</div>
</div>
<div class="vt-window-resize" id="vtWindowHandle" title="Drag to resize window"><span></span></div>
</div>
<div class="vt-output-label">Output</div>
<div id="vtOutputArea">
<p class="vt-output-placeholder">Run <code style="font-family:var(--mono-font)">npm start</code> above to see it here.</p>
<div class="vt-browser" id="vtBrowser">
<div class="vt-browser-bar">
<div class="vt-dots"><span></span><span></span><span></span></div>
<div class="vt-browser-url">localhost:3000</div>
</div>
<div class="vt-cart">
<h2>Store Products</h2>
<div class="vt-products" id="vtProducts"></div>
<hr />
<h2>Your Cart</h2>
<p class="vt-cart-total"><strong>Total Price: $<span id="vtTotal">0</span></strong></p>
<div id="vtCartBody"><p class="vt-cart-empty">Your cart is empty.</p></div>
</div>
</div>
</div>
</div>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@500;600&family=Inter:wght@400;500;600;700&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<script>
(function () {
var root = document.getElementById('vt');
if (!root) return;
/* --- dark mode detection: body attribute > cookie > postMessage > light --- */
function applyDark(dark) {
if (dark) root.setAttribute('data-theme', 'dark');
else root.removeAttribute('data-theme');
}
var bodyAttr = document.body.getAttribute('data-darkmode');
var dark;
if (bodyAttr === 'true') dark = true;
else if (bodyAttr === 'false') dark = false;
else {
var match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
applyDark(dark);
window.addEventListener('message', function (e) {
if (e.data && e.data.type === 'darkMode') applyDark(!!e.data.value);
});
/* --- file switching --- */
var files = {
actiontypes:
'<span class="tok-kw">export</span> <span class="tok-kw">const</span> <span class="tok-type">CART_ACTIONS</span> <span class="tok-punc">=</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-attr">ADD_ITEM</span><span class="tok-punc">:</span> <span class="tok-str">\'ADD_ITEM\'</span><span class="tok-punc">,</span>\n' +
' <span class="tok-attr">REMOVE_ITEM</span><span class="tok-punc">:</span> <span class="tok-str">\'REMOVE_ITEM\'</span><span class="tok-punc">,</span>\n' +
' <span class="tok-attr">CLEAR_CART</span><span class="tok-punc">:</span> <span class="tok-str">\'CLEAR_CART\'</span><span class="tok-punc">,</span>\n' +
'<span class="tok-punc">};</span>',
cartreducer:
'<span class="tok-kw">import</span> <span class="tok-punc">{</span> <span class="tok-type">CART_ACTIONS</span> <span class="tok-punc">}</span> <span class="tok-kw">from</span> <span class="tok-str">\'./ActionTypes\'</span><span class="tok-punc">;</span>\n\n' +
'<span class="tok-comment">// 1. Define the Initial State</span>\n' +
'<span class="tok-kw">export</span> <span class="tok-kw">const</span> initialState <span class="tok-punc">=</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-attr">items</span><span class="tok-punc">:</span> <span class="tok-punc">[],</span>\n' +
' <span class="tok-attr">total</span><span class="tok-punc">:</span> <span class="tok-expr">0</span><span class="tok-punc">,</span>\n' +
'<span class="tok-punc">};</span>\n\n' +
'<span class="tok-comment">// 2. Define the Reducer Function</span>\n' +
'<span class="tok-kw">export</span> <span class="tok-kw">function</span> cartReducer<span class="tok-punc">(</span>state<span class="tok-punc">,</span> action<span class="tok-punc">) {</span>\n' +
' <span class="tok-kw">switch</span> <span class="tok-punc">(</span>action.type<span class="tok-punc">) {</span>\n' +
' <span class="tok-kw">case</span> <span class="tok-type">CART_ACTIONS</span><span class="tok-punc">.</span>ADD_ITEM<span class="tok-punc">: {</span>\n' +
' <span class="tok-kw">const</span> existingItemIndex <span class="tok-punc">=</span> state.items.findIndex<span class="tok-punc">(</span>item <span class="tok-punc">=></span> item.id <span class="tok-punc">===</span> action.payload.id<span class="tok-punc">);</span>\n' +
' <span class="tok-kw">let</span> updatedItems<span class="tok-punc">;</span>\n\n' +
' <span class="tok-kw">if</span> <span class="tok-punc">(</span>existingItemIndex <span class="tok-punc">></span> <span class="tok-punc">-</span><span class="tok-expr">1</span><span class="tok-punc">) {</span>\n' +
' <span class="tok-comment">// Create a new array and update the specific item\'s quantity</span>\n' +
' updatedItems <span class="tok-punc">=</span> <span class="tok-punc">[...</span>state.items<span class="tok-punc">];</span>\n' +
' updatedItems<span class="tok-punc">[</span>existingItemIndex<span class="tok-punc">]</span> <span class="tok-punc">=</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-punc">...</span>updatedItems<span class="tok-punc">[</span>existingItemIndex<span class="tok-punc">],</span>\n' +
' <span class="tok-attr">quantity</span><span class="tok-punc">:</span> updatedItems<span class="tok-punc">[</span>existingItemIndex<span class="tok-punc">].</span>quantity <span class="tok-punc">+</span> <span class="tok-expr">1</span>\n' +
' <span class="tok-punc">};</span>\n' +
' <span class="tok-punc">} else {</span>\n' +
' <span class="tok-comment">// Add new item with quantity of 1</span>\n' +
' updatedItems <span class="tok-punc">=</span> <span class="tok-punc">[...</span>state.items<span class="tok-punc">,</span> <span class="tok-punc">{</span> <span class="tok-punc">...</span>action.payload<span class="tok-punc">,</span> <span class="tok-attr">quantity</span><span class="tok-punc">:</span> <span class="tok-expr">1</span> <span class="tok-punc">}];</span>\n' +
' <span class="tok-punc">}</span>\n\n' +
' <span class="tok-kw">return</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-punc">...</span>state<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">items</span><span class="tok-punc">:</span> updatedItems<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">total</span><span class="tok-punc">:</span> state.total <span class="tok-punc">+</span> action.payload.price<span class="tok-punc">,</span>\n' +
' <span class="tok-punc">};</span>\n' +
' <span class="tok-punc">}</span>\n\n' +
' <span class="tok-comment">// REMOVE_ITEM now takes off ONE unit at a time instead of deleting</span>\n' +
' <span class="tok-comment">// the whole line — the item only disappears once quantity hits 0.</span>\n' +
' <span class="tok-kw">case</span> <span class="tok-type">CART_ACTIONS</span><span class="tok-punc">.</span>REMOVE_ITEM<span class="tok-punc">: {</span>\n' +
' <span class="tok-kw">const</span> existingItemIndex <span class="tok-punc">=</span> state.items.findIndex<span class="tok-punc">(</span>item <span class="tok-punc">=></span> item.id <span class="tok-punc">===</span> action.payload.id<span class="tok-punc">);</span>\n' +
' <span class="tok-kw">if</span> <span class="tok-punc">(</span>existingItemIndex <span class="tok-punc">===</span> <span class="tok-punc">-</span><span class="tok-expr">1</span><span class="tok-punc">)</span> <span class="tok-kw">return</span> state<span class="tok-punc">;</span>\n\n' +
' <span class="tok-kw">const</span> existingItem <span class="tok-punc">=</span> state.items<span class="tok-punc">[</span>existingItemIndex<span class="tok-punc">];</span>\n' +
' <span class="tok-kw">let</span> updatedItems<span class="tok-punc">;</span>\n\n' +
' <span class="tok-kw">if</span> <span class="tok-punc">(</span>existingItem.quantity <span class="tok-punc">></span> <span class="tok-expr">1</span><span class="tok-punc">) {</span>\n' +
' <span class="tok-comment">// More than 1 left — just decrement the quantity</span>\n' +
' updatedItems <span class="tok-punc">=</span> <span class="tok-punc">[...</span>state.items<span class="tok-punc">];</span>\n' +
' updatedItems<span class="tok-punc">[</span>existingItemIndex<span class="tok-punc">]</span> <span class="tok-punc">=</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-punc">...</span>existingItem<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">quantity</span><span class="tok-punc">:</span> existingItem.quantity <span class="tok-punc">-</span> <span class="tok-expr">1</span>\n' +
' <span class="tok-punc">};</span>\n' +
' <span class="tok-punc">} else {</span>\n' +
' <span class="tok-comment">// Quantity is 1 — this click removes the item entirely</span>\n' +
' updatedItems <span class="tok-punc">=</span> state.items.filter<span class="tok-punc">(</span>item <span class="tok-punc">=></span> item.id <span class="tok-punc">!==</span> action.payload.id<span class="tok-punc">);</span>\n' +
' <span class="tok-punc">}</span>\n\n' +
' <span class="tok-kw">return</span> <span class="tok-punc">{</span>\n' +
' <span class="tok-punc">...</span>state<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">items</span><span class="tok-punc">:</span> updatedItems<span class="tok-punc">,</span>\n' +
' <span class="tok-attr">total</span><span class="tok-punc">:</span> state.total <span class="tok-punc">-</span> existingItem.price<span class="tok-punc">,</span>\n' +
' <span class="tok-punc">};</span>\n' +
' <span class="tok-punc">}</span>\n\n' +
' <span class="tok-kw">case</span> <span class="tok-type">CART_ACTIONS</span><span class="tok-punc">.</span>CLEAR_CART<span class="tok-punc">:</span>\n' +
' <span class="tok-kw">return</span> initialState<span class="tok-punc">;</span>\n\n' +
' <span class="tok-kw">default</span><span class="tok-punc">:</span>\n' +
' <span class="tok-kw">return</span> state<span class="tok-punc">;</span>\n' +
' <span class="tok-punc">}</span>\n' +
'<span class="tok-punc">}</span>',
shoppingcart:
'<span class="tok-kw">import</span> <span class="tok-type">React</span><span class="tok-punc">,</span> <span class="tok-punc">{</span> useReducer <span class="tok-punc">}</span> <span class="tok-kw">from</span> <span class="tok-str">\'react\'</span><span class="tok-punc">;</span>\n' +
'<span class="tok-kw">import</span> <span class="tok-punc">{</span> cartReducer<span class="tok-punc">,</span> initialState <span class="tok-punc">}</span> <span class="tok-kw">from</span> <span class="tok-str">\'./CartReducer\'</span><span class="tok-punc">;</span>\n' +
'<span class="tok-kw">import</span> <span class="tok-punc">{</span> <span class="tok-type">CART_ACTIONS</span> <span class="tok-punc">}</span> <span class="tok-kw">from</span> <span class="tok-str">\'./ActionTypes\'</span><span class="tok-punc">;</span>\n\n' +
'<span class="tok-kw">const</span> <span class="tok-type">PRODUCTS</span> <span class="tok-punc">=</span> <span class="tok-punc">[</span>\n' +
' <span class="tok-punc">{</span> <span class="tok-attr">id</span><span class="tok-punc">:</span> <span class="tok-expr">1</span><span class="tok-punc">,</span> <span class="tok-attr">name</span><span class="tok-punc">:</span> <span class="tok-str">\'Mechanical Keyboard\'</span><span class="tok-punc">,</span> <span class="tok-attr">price</span><span class="tok-punc">:</span> <span class="tok-expr">100</span> <span class="tok-punc">},</span>\n' +
' <span class="tok-punc">{</span> <span class="tok-attr">id</span><span class="tok-punc">:</span> <span class="tok-expr">2</span><span class="tok-punc">,</span> <span class="tok-attr">name</span><span class="tok-punc">:</span> <span class="tok-str">\'Gaming Mouse\'</span><span class="tok-punc">,</span> <span class="tok-attr">price</span><span class="tok-punc">:</span> <span class="tok-expr">50</span> <span class="tok-punc">},</span>\n' +
'<span class="tok-punc">];</span>\n\n' +
'<span class="tok-kw">export</span> <span class="tok-kw">default</span> <span class="tok-kw">function</span> <span class="tok-type">ShoppingCart</span><span class="tok-punc">() {</span>\n' +
' <span class="tok-kw">const</span> <span class="tok-punc">[</span>state<span class="tok-punc">,</span> dispatch<span class="tok-punc">]</span> <span class="tok-punc">=</span> useReducer<span class="tok-punc">(</span>cartReducer<span class="tok-punc">,</span> initialState<span class="tok-punc">);</span>\n\n' +
' <span class="tok-kw">return</span> <span class="tok-punc">(</span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">div</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">h2</span><span class="tok-punc">></span>Store Products<span class="tok-punc"></</span><span class="tok-tag">h2</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc">{</span><span class="tok-type">PRODUCTS</span>.map<span class="tok-punc">(</span>product <span class="tok-punc">=> (</span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">button</span> <span class="tok-attr">key</span><span class="tok-punc">={</span>product.id<span class="tok-punc">}</span>\n' +
' <span class="tok-attr">onClick</span><span class="tok-punc">={</span><span class="tok-punc">()</span> <span class="tok-punc">=></span> dispatch<span class="tok-punc">({</span> <span class="tok-attr">type</span><span class="tok-punc">:</span> <span class="tok-type">CART_ACTIONS</span>.ADD_ITEM<span class="tok-punc">,</span> <span class="tok-attr">payload</span><span class="tok-punc">:</span> product <span class="tok-punc">})}></span>\n' +
' Add <span class="tok-punc">{</span>product.name<span class="tok-punc">}</span> <span class="tok-punc">(</span>$<span class="tok-punc">{</span>product.price<span class="tok-punc">})</span>\n' +
' <span class="tok-punc"></</span><span class="tok-tag">button</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc">))}</span>\n\n' +
' <span class="tok-punc"><</span><span class="tok-tag">h2</span><span class="tok-punc">></span>Your Cart<span class="tok-punc"></</span><span class="tok-tag">h2</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">p</span><span class="tok-punc">></span>Total<span class="tok-punc">:</span> $<span class="tok-punc">{</span>state.total<span class="tok-punc">}</</span><span class="tok-tag">p</span><span class="tok-punc">></span>\n\n' +
' <span class="tok-comment">{/* Remove now takes off ONE unit — not the whole item */}</span>\n' +
' <span class="tok-punc">{</span>state.items.map<span class="tok-punc">(</span>item <span class="tok-punc">=> (</span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">li</span> <span class="tok-attr">key</span><span class="tok-punc">={</span>item.id<span class="tok-punc">}></span>\n' +
' <span class="tok-punc">{</span>item.name<span class="tok-punc">}</span> <span class="tok-punc">(</span>x<span class="tok-punc">{</span>item.quantity<span class="tok-punc">})</span>\n' +
' <span class="tok-punc"><</span><span class="tok-tag">button</span> <span class="tok-attr">onClick</span><span class="tok-punc">={</span><span class="tok-punc">()</span> <span class="tok-punc">=></span> dispatch<span class="tok-punc">({</span> <span class="tok-attr">type</span><span class="tok-punc">:</span> <span class="tok-type">CART_ACTIONS</span>.REMOVE_ITEM<span class="tok-punc">,</span> <span class="tok-attr">payload</span><span class="tok-punc">:</span> item <span class="tok-punc">})}></span>−<span class="tok-punc"></</span><span class="tok-tag">button</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc"></</span><span class="tok-tag">li</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc">))}</span>\n\n' +
' <span class="tok-punc"><</span><span class="tok-tag">button</span> <span class="tok-attr">onClick</span><span class="tok-punc">={</span><span class="tok-punc">()</span> <span class="tok-punc">=></span> dispatch<span class="tok-punc">({</span> <span class="tok-attr">type</span><span class="tok-punc">:</span> <span class="tok-type">CART_ACTIONS</span>.CLEAR_CART <span class="tok-punc">})}></span>\n' +
' Clear Entire Cart\n' +
' <span class="tok-punc"></</span><span class="tok-tag">button</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc"></</span><span class="tok-tag">div</span><span class="tok-punc">></span>\n' +
' <span class="tok-punc">);</span>\n' +
'<span class="tok-punc">}</span>'
};
var codeEl = root.querySelector('#vtCode');
var rows = root.querySelectorAll('.vt-row');
var tabs = root.querySelectorAll('.vt-tab');
function selectFile(id) {
codeEl.innerHTML = files[id];
rows.forEach(function (r) { r.classList.toggle('is-selected', r.getAttribute('data-file') === id); });
tabs.forEach(function (t) { t.classList.toggle('is-active', t.getAttribute('data-file') === id); });
}
rows.forEach(function (r) { r.addEventListener('click', function () { selectFile(r.getAttribute('data-file')); }); });
tabs.forEach(function (t) { t.addEventListener('click', function () { selectFile(t.getAttribute('data-file')); }); });
selectFile('cartreducer');
/* --- terminal run simulation --- */
var termLines = root.querySelector('#vtTermLines');
var runBtn = root.querySelector('#vtRunBtn');
var runLabel = root.querySelector('#vtRunLabel');
var runHint = root.querySelector('#vtRunHint');
var browser = root.querySelector('#vtBrowser');
var placeholder = root.querySelector('.vt-output-placeholder');
var running = false;
var lines = [
{ text: '$ npm start', cls: 'is-cmd', delay: 0 },
{ text: 'Starting the development server\u2026', cls: '', delay: 500 },
{ text: 'Compiled successfully!', cls: 'is-ok', delay: 1350 },
{ text: 'You can now view cart-demo in the browser.', cls: '', delay: 1600 },
{ text: ' Local: http://localhost:3000', cls: '', delay: 1850 }
];
runBtn.addEventListener('click', function () {
if (running) return;
running = true;
runBtn.disabled = true;
runLabel.textContent = 'running\u2026';
browser.classList.remove('is-shown');
placeholder.style.display = 'block';
termLines.innerHTML = '';
lines.forEach(function (line) {
setTimeout(function () {
var div = document.createElement('div');
div.className = 'vt-term-line ' + line.cls;
div.textContent = line.text;
termLines.appendChild(div);
}, line.delay);
});
setTimeout(function () {
placeholder.style.display = 'none';
browser.classList.add('is-shown');
runBtn.disabled = false;
runLabel.textContent = 'npm start';
runHint.textContent = 'server running \u2014 rerun anytime';
running = false;
}, 2300);
});
/* --- resize handles (pointer-capture drag) --- */
function makeResizable(handle, opts) {
var dragging = false, startPos = 0, startSize = 0;
handle.addEventListener('pointerdown', function (e) {
dragging = true;
handle.classList.add('is-dragging');
startPos = opts.axis === 'x' ? e.clientX : e.clientY;
startSize = opts.target.getBoundingClientRect()[opts.axis === 'x' ? 'width' : 'height'];
handle.setPointerCapture(e.pointerId);
e.preventDefault();
});
handle.addEventListener('pointermove', function (e) {
if (!dragging) return;
var pos = opts.axis === 'x' ? e.clientX : e.clientY;
var delta = pos - startPos;
if (opts.invert) delta = -delta;
var size = Math.min(opts.max, Math.max(opts.min, startSize + delta));
opts.target.style[opts.prop] = size + 'px';
if (opts.onResize) opts.onResize(size);
});
function stop() { dragging = false; handle.classList.remove('is-dragging'); }
handle.addEventListener('pointerup', stop);
handle.addEventListener('pointercancel', stop);
}
var sidebar = root.querySelector('.vt-sidebar');
var sidebarHandle = root.querySelector('#vtSidebarHandle');
var lastSidebarWidth = sidebar.getBoundingClientRect().width || 180;
makeResizable(sidebarHandle, {
axis: 'x', target: sidebar, prop: 'width', min: 110, max: 300, invert: false,
onResize: function (s) { lastSidebarWidth = s; }
});
var terminal = root.querySelector('.vt-terminal');
var terminalHandle = root.querySelector('#vtTerminalHandle');
var lastTerminalHeight = terminal.getBoundingClientRect().height || 150;
makeResizable(terminalHandle, {
axis: 'y', target: terminal, prop: 'height', min: 60, max: 280, invert: true,
onResize: function (s) { lastTerminalHeight = s; }
});
var vtBody = root.querySelector('.vt-body');
var windowHandle = root.querySelector('#vtWindowHandle');
makeResizable(windowHandle, {
axis: 'y', target: vtBody, prop: 'height', min: 320, max: 620, invert: false
});
/* --- show/hide toggles --- */
var toggleSidebarBtn = root.querySelector('#vtToggleSidebar');
var sidebarHidden = false;
toggleSidebarBtn.addEventListener('click', function () {
sidebarHidden = !sidebarHidden;
if (sidebarHidden) {
var w = sidebar.getBoundingClientRect().width;
if (w > 0) lastSidebarWidth = w;
sidebar.classList.add('is-hidden');
sidebarHandle.style.display = 'none';
} else {
sidebar.classList.remove('is-hidden');
sidebar.style.width = lastSidebarWidth + 'px';
sidebarHandle.style.display = '';
}
});
var toggleTerminalBtn = root.querySelector('#vtToggleTerminal');
var terminalCollapsed = false;
toggleTerminalBtn.addEventListener('click', function () {
terminalCollapsed = !terminalCollapsed;
if (terminalCollapsed) {
var h = terminal.getBoundingClientRect().height;
if (h > 30) lastTerminalHeight = h;
terminal.classList.add('is-collapsed');
terminalHandle.style.display = 'none';
} else {
terminal.classList.remove('is-collapsed');
terminal.style.height = lastTerminalHeight + 'px';
terminalHandle.style.display = '';
}
});
/* --- real behavior: an actual cartReducer driving the output ---
REMOVE_ITEM decrements quantity by 1; the item is only dropped
from state.items once its quantity would reach 0. */
var CART_ACTIONS = { ADD_ITEM: 'ADD_ITEM', REMOVE_ITEM: 'REMOVE_ITEM', CLEAR_CART: 'CLEAR_CART' };
var initialState = { items: [], total: 0 };
function cartReducer(state, action) {
switch (action.type) {
case CART_ACTIONS.ADD_ITEM: {
var existingItemIndex = state.items.findIndex(function (item) { return item.id === action.payload.id; });
var updatedItems;
if (existingItemIndex > -1) {
updatedItems = state.items.slice();
updatedItems[existingItemIndex] = Object.assign({}, updatedItems[existingItemIndex], {
quantity: updatedItems[existingItemIndex].quantity + 1
});
} else {
updatedItems = state.items.concat([Object.assign({}, action.payload, { quantity: 1 })]);
}
return Object.assign({}, state, { items: updatedItems, total: state.total + action.payload.price });
}
case CART_ACTIONS.REMOVE_ITEM: {
var existingItemIndex = state.items.findIndex(function (item) { return item.id === action.payload.id; });
if (existingItemIndex === -1) return state;
var existingItem = state.items[existingItemIndex];
var updatedItems;
if (existingItem.quantity > 1) {
updatedItems = state.items.slice();
updatedItems[existingItemIndex] = Object.assign({}, existingItem, { quantity: existingItem.quantity - 1 });
} else {
updatedItems = state.items.filter(function (item) { return item.id !== action.payload.id; });
}
return Object.assign({}, state, { items: updatedItems, total: state.total - existingItem.price });
}
case CART_ACTIONS.CLEAR_CART:
return initialState;
default:
return state;
}
}
var PRODUCTS = [
{ id: 1, name: 'Mechanical Keyboard', price: 100 },
{ id: 2, name: 'Gaming Mouse', price: 50 }
];
var state = initialState;
var productsEl = root.querySelector('#vtProducts');
var totalEl = root.querySelector('#vtTotal');
var cartBodyEl = root.querySelector('#vtCartBody');
function dispatch(action) {
state = cartReducer(state, action);
render();
}
function render() {
totalEl.textContent = state.total;
if (state.items.length === 0) {
cartBodyEl.innerHTML = '<p class="vt-cart-empty">Your cart is empty.</p>';
return;
}
var ul = document.createElement('ul');
ul.className = 'vt-cart-list';
state.items.forEach(function (item) {
var li = document.createElement('li');
var label = document.createElement('span');
label.textContent = item.name + ' — $' + item.price + ' (x' + item.quantity + ')';
var controls = document.createElement('div');
controls.className = 'vt-qty-controls';
var minusBtn = document.createElement('button');
minusBtn.className = 'vt-qty-btn';
minusBtn.type = 'button';
minusBtn.textContent = '−';
minusBtn.title = item.quantity > 1 ? 'Remove one' : 'Remove item';
minusBtn.addEventListener('click', function () {
dispatch({ type: CART_ACTIONS.REMOVE_ITEM, payload: item });
});
var plusBtn = document.createElement('button');
plusBtn.className = 'vt-qty-btn';
plusBtn.type = 'button';
plusBtn.textContent = '+';
plusBtn.title = 'Add one more';
plusBtn.addEventListener('click', function () {
dispatch({ type: CART_ACTIONS.ADD_ITEM, payload: { id: item.id, name: item.name, price: item.price } });
});
controls.appendChild(minusBtn);
controls.appendChild(plusBtn);
li.appendChild(label);
li.appendChild(controls);
ul.appendChild(li);
});
var clearBtn = document.createElement('button');
clearBtn.className = 'vt-clear-btn';
clearBtn.type = 'button';
clearBtn.textContent = 'Clear Entire Cart';
clearBtn.addEventListener('click', function () {
dispatch({ type: CART_ACTIONS.CLEAR_CART });
});
cartBodyEl.innerHTML = '';
cartBodyEl.appendChild(ul);
cartBodyEl.appendChild(clearBtn);
}
PRODUCTS.forEach(function (product) {
var btn = document.createElement('button');
btn.className = 'vt-product-btn';
btn.type = 'button';
btn.textContent = 'Add ' + product.name + ' ($' + product.price + ')';
btn.addEventListener('click', function () {
dispatch({ type: CART_ACTIONS.ADD_ITEM, payload: product });
});
productsEl.appendChild(btn);
});
render();
})();
</script>🧠 Deep Dive: How the logic flows
The Trigger (Dispatch): When you click "Add Keyboard," you call
dispatch({ type: 'ADD_ITEM', payload: product }).The Message (Action): The
dispatchsends that object (the "Action") to thecartReducer.The Calculation (Reducer): The reducer sees the type is
'ADD_ITEM', takes thepayload(the keyboard data), and uses the current state to calculate a new state object.The Re-render: React receives the new state object, notices the changes, and updates the UI automatically.
🚀 Why this is better than useState here:
If you used useState, your addItem function would be huge and living inside your UI component. With useReducer, all that "math" and "finding indexes" lives in a clean, separate function that you could even move to a different file and write tests for independently.