BizzPocket

Product page buy box

A product page buy box with option buttons, a price and stock line that follow the shopper's choice, and add to cart. No JavaScript of your own.

On this page

Goal: a product page buy box (picture, price, option buttons, stock, add to cart) that follows the shopper's choice of size or colour and sends no JavaScript of its own.

Data static: one product() need, from the URL
JavaScript 0 bytes of your own. The page's shared SIR runtime does the work.
Uses sir.variantPicker and its helpers, sir.addToCart, sir.wishlistToggle, <Money>, responsiveImage()

The block has two files.

The block

Create blocks/pdp-buy-box/pdp-buy-box.tsx:

blocks/pdp-buy-box/pdp-buy-box.tsx
import { block, f, Money, product, responsiveImage, sir } from '@bizzpocket/theme';
import './pdp-buy-box.css';

const SIZES = '(min-width: 900px) 50vw, 100vw';
const LOCALE = 'en-IN';

export default block({
  name: 'Buy box',
  category: 'commerce',
  // The product page's main block: the editor expects one block with this role there.
  role: 'product-detail',
  // The picture and the price are the first thing a shopper sees on a product page.
  lcp: true,
  fields: {
    addLabel: f.text({ default: 'Add to cart' }),
    soldOutLabel: f.text({ default: 'Sold out' }),
    chooseLabel: f.text({ default: 'Choose an option' }),
    inStockLabel: f.text({ default: 'In stock' }),
    lowStockLabel: f.text({ default: 'Only a few left' }),
    showWishlist: f.boolean({ default: true }),
  },
  // Static: the product comes from the URL (`/products/<handle>`).
  data: (_props, page) => ({ item: product({ handle: page.route.handle }) }),
  render: ({ item, addLabel, soldOutLabel, chooseLabel, inStockLabel, lowStockLabel, showWishlist }) => {
    if (!item) return null;

    // The variant table. Every row names a picture (its own, else the product's),
    // so picking back and forth always swaps the main image.
    const rows = item.variants.map((v) => {
      const img = v.image ?? item.primaryImage ?? null;
      return {
        id: v.id,
        options: Object.fromEntries(v.options.map((o) => [o.name, o.value])),
        price: v.price,
        compareAtPrice: v.compareAtPrice ?? null,
        sku: v.sku,
        inStock: v.inStock,
        image: img && { ...img, srcset: responsiveImage({ src: img.src, sizes: SIZES }).srcSet ?? '' },
      };
    });
    const hasVariants = rows.length > 0;

    // The opening state, computed exactly as the SIR runtime computes it.
    const { groups, selection, variant } = sir.variantState(rows);
    const chosen = Object.keys(selection).length > 0;
    const price = variant?.price ?? item.price;
    const compare = hasVariants ? variant?.compareAtPrice ?? null : item.compareAtPrice ?? null;
    const picture = variant?.image ?? item.primaryImage ?? item.images[0] ?? null;
    const inStock = hasVariants ? variant?.inStock === true : item.inStock;
    const low = item.stock?.lowStockRemaining ?? null;
    const label = hasVariants && !chosen ? chooseLabel : inStock ? addLabel : soldOutLabel;

    return (
      <section className="pbb">
        <div className="pbb-media">
          {picture ? (
            <img
              {...responsiveImage({ src: picture.src, sizes: SIZES })}
              {...(hasVariants ? sir.variantImage(item.id) : {})}
              alt={picture.alt}
              width={900}
              height={900}
              fetchPriority="high"
              className="pbb-img"
            />
          ) : null}
        </div>

        <div
          className="pbb-info"
          {...(hasVariants ? sir.variantPicker({ 'data-product-id': item.id, 'data-locale': LOCALE }) : {})}
        >
          <h1 className="pbb-title">{item.title}</h1>

          <p className="pbb-price">
            <span {...sir.variantTarget('price')}>
              <Money amount={price.amount} currency={price.currency} locale={LOCALE} />
            </span>{' '}
            <s className="pbb-compare" {...sir.variantTarget('compare')} hidden={!compare}>
              {compare ? <Money amount={compare.amount} currency={compare.currency} locale={LOCALE} /> : null}
            </s>
          </p>

          {groups.map((g) => (
            <fieldset key={g.name} className="pbb-group">
              <legend className="pbb-legend">{g.name}</legend>
              <div className="pbb-options" {...sir.variantGroup(g.name)}>
                {g.values.map((v) => (
                  <button key={v.value} type="button" className="pbb-option" {...sir.variantOption({ name: g.name, ...v })}>
                    {v.value}
                  </button>
                ))}
              </div>
            </fieldset>
          ))}

          <p className="pbb-stock">
            <span
              {...sir.variantTarget('stock')}
              data-label-in-stock={inStockLabel}
              data-label-out-of-stock={soldOutLabel}
            >
              {hasVariants && !chosen ? '' : inStock ? inStockLabel : soldOutLabel}
            </span>
            {inStock && low !== null ? <span className="pbb-low"> · {lowStockLabel}</span> : null}
          </p>

          <div className="pbb-actions">
            <div className="pbb-qty" {...sir.qtyStepper({ 'data-max': '10', 'data-bp-qty-for': item.id })}>
              <button type="button" data-bp-qty-decrement="" aria-label="Decrease quantity">−</button>
              <input data-bp-qty-input="" type="number" inputMode="numeric" min={1} max={10} defaultValue={1} aria-label="Quantity" />
              <button type="button" data-bp-qty-increment="" aria-label="Increase quantity">+</button>
            </div>
            <button
              type="button"
              className="pbb-add"
              disabled={!inStock}
              {...sir.addToCart({
                'data-product-id': item.id,
                'data-handle': item.handle,
                ...(variant ? { 'data-variant-id': variant.id } : {}),
                'data-label-add': addLabel,
                'data-label-oos': soldOutLabel,
                'data-label-select': chooseLabel,
              })}
            >
              {label}
            </button>
            {showWishlist ? (
              <button
                type="button"
                className="pbb-heart"
                aria-label="Save to wishlist"
                {...sir.wishlistToggle({ 'data-product-id': item.id })}
              >
                ♡
              </button>
            ) : null}
          </div>

          <p className="pbb-sku" {...sir.variantTarget('row')} hidden={!(variant?.sku ?? item.sku)}>
            SKU <span {...sir.variantTarget('sku')}>{variant?.sku ?? item.sku}</span>
          </p>

          {hasVariants ? <script {...sir.variantData(rows)} /> : null}
        </div>
      </section>
    );
  },
});

The CSS

Create blocks/pdp-buy-box/pdp-buy-box.css:

blocks/pdp-buy-box/pdp-buy-box.css
.pbb { display: grid; gap: 2rem; padding: 2rem 1rem; max-width: 72rem; margin: 0 auto; }
@media (min-width: 900px) { .pbb { grid-template-columns: 1fr 1fr; align-items: start; } }
.pbb-img { width: 100%; height: auto; display: block; border-radius: 0.5rem; }
.pbb-title { margin: 0 0 0.5rem; font-size: 1.75rem; }
.pbb-price { font-size: 1.25rem; font-weight: 600; margin: 0 0 1.5rem; }
.pbb-compare { font-weight: 400; opacity: 0.6; }
.pbb-group { border: 0; padding: 0; margin: 0 0 1rem; }
.pbb-legend { font-weight: 600; margin-bottom: 0.5rem; }
.pbb-options { display: flex; flex-wrap: wrap; gap: 0.5rem; }
.pbb-option { min-width: 3rem; padding: 0.5rem 0.9rem; border: 1px solid #ccc; border-radius: 999px; background: #fff; cursor: pointer; }
.pbb-option[aria-checked='true'] { border-color: currentColor; box-shadow: inset 0 0 0 1px currentColor; }
/* A value no in-stock variant reaches: still focusable and pickable, so style aria-disabled, not :disabled. */
.pbb-option[aria-disabled='true'] { opacity: 0.45; text-decoration: line-through; }
.pbb-stock { margin: 0 0 1rem; font-size: 0.9rem; }
.pbb-low { color: #b45309; }
.pbb-actions { display: flex; gap: 0.5rem; }
.pbb-qty { display: flex; border: 1px solid #ccc; border-radius: 0.5rem; }
.pbb-qty button { width: 2.75rem; border: 0; background: none; font-size: 1.1rem; cursor: pointer; }
.pbb-qty input { width: 3rem; border: 0; text-align: center; font: inherit; }
.pbb-add { flex: 1; padding: 0.9rem 1.5rem; border: 0; border-radius: 0.5rem; background: #111; color: #fff; font-weight: 600; cursor: pointer; }
.pbb-add:disabled { background: #999; cursor: not-allowed; }
.pbb-heart { width: 3.25rem; border: 1px solid #ccc; border-radius: 0.5rem; background: #fff; font-size: 1.25rem; cursor: pointer; }
.pbb-heart[aria-pressed='true'] { color: #dc2626; }
.pbb-sku { font-size: 0.8rem; opacity: 0.7; margin: 1rem 0 0; }

Add it to the product page with bunx bizzpocket add-to-layout pdp-buy-box --page product, then open a product in bunx bizzpocket dev --mock (/products/classic-train-set has a Colour option, /products/wooden-rainbow-stacker has none).

How it works

  • The data is one static need. product({ handle: page.route.handle }) reads the handle from the URL, so the build turns data() into a template and the product arrives in the page's single data call.
  • The server paints the opening choice. sir.variantState(rows) picks the first in-stock variant and marks the values no in-stock variant can reach, with the same functions the SIR runtime uses. The HTML you send is already right, and nothing moves when the runtime wakes.
  • The runtime keeps it right. Everything the pick changes sits inside the sir.variantPicker root: the price and compare-at price (variantTarget('price' | 'compare')), the stock text (variantTarget('stock') with its two data-label-* texts), the SKU and its row, and the sir.addToCart button, which gets the chosen data-variant-id, its disabled state and one of the three data-label-* texts. The main picture is outside the root: sir.variantImage(item.id) links it by product id.
  • Prices do not jump. <Money locale="en-IN"> and data-locale="en-IN" format the same way, so the runtime's text matches the server's.
  • A product without options has no variant table and no picker root. The button adds the product itself, and the stock text is the product's inStock.
  • The low-stock line shows only when the store sends stock.lowStockRemaining, which it does only inside the seller's own low-stock window. It is product-wide, not per variant, so it does not follow the pick.
  • Quantity. sir.qtyStepper with data-bp-qty-for={item.id} writes its value to the button's data-qty, which the add sends. Without data-bp-qty-for, a stepper inside the same sir.variantPicker root (or a data-bp-product-root element) feeds that root's button.
  • A pick writes ?variant=<id> to the URL, and announces the price and stock in a polite live region. An island elsewhere on the page can follow the choice with useShared('variant:' + productId, null) (see State).

JS cost

block        server B  client gz  css gz  data
-----------  --------  ---------  ------  ------
pdp-buy-box      5483          0     560  static

client gz is 0: the option buttons, the price, the stock text, the quantity, the button and the heart are all handled by the SIR runtime that every storefront page already loads.

Thumbnails

To add thumbnails, wrap the picture and the thumbs in sir.imageGallery(), give the main <img> data-bp-gallery-main, and give each thumb sir.imageGalleryThumb({ 'data-src', 'data-srcset', 'data-sizes' }) built from responsiveImage(): the gallery swaps the srcset with the src, so the picked picture shows.