Low-stock badge on the product tile
React · React · beginner · modification
Shoppers asked to know when an item is about to run out, so the product tile now warns them before it sells out. `src/catalog/ProductTile.jsx` shows an `Only N left` badge when a product is low on stock, keeping the existing `Out of stock` badge and disabled button for sold-out products. `src/catalog/ProductTile.css` adds the badge's attention colours from the theme. `src/catalog/ProductTile.test.jsx` (new) covers the badges and the Add to cart button.
Shop SPA on React 18.3 (Vite, function components). Tests run with `npm test`: Vitest 2 with @testing-library/react 16 in jsdom. Existing and unchanged: `CatalogPage.jsx` loads the catalog once, shows its own loading and error states, and renders one `<ProductTile product={product} onAddToCart={addToCart} />` per product. `product` is `{ id, name, imageUrl, priceLabel, stock }`: `id` a non-empty string, `name` a non-empty string, `imageUrl` a URL, `priceLabel` the price already formatted by the API (for example `$24.00`), `stock` the units on hand, an integer from 0 to 100000 (the API validates it). Stock does not change while the page is open: the catalog has no live updates, so the badges are static text. The theme tokens `--attention-fg`, `--attention-subtle`, `--danger-fg` and `--danger-subtle` exist in both the light and dark themes.
Requirements
- A product tile shows a low-stock badge reading `Only N left` (N is the product's `stock`) when 5 or fewer units are left, that is when `stock` is 1, 2, 3, 4 or 5. Above 5 it shows no stock badge.
- At 0 units the tile keeps showing the existing `Out of stock` badge and no low-stock badge, and its Add to cart button stays disabled.
- The low-stock badge uses the attention colours of the theme (`--attention-fg` on `--attention-subtle`), next to the existing danger colours of `Out of stock`.
- Unchanged: the tile's image, name, price label and Add to cart button, which calls `onAddToCart(product.id)` when clicked.
- The tile has tests that run with the existing `npm test` (Vitest).
Files touched
- src/catalog/ProductTile.jsx
- src/catalog/ProductTile.css
- src/catalog/ProductTile.test.jsx