BizzPocket

The kit: @bizzpocket/theme/kit

On this page

Every store theme needs a product card, a price, a pager, a filter rail and a gallery. Without the kit, each theme writes them again. The kit holds the parts that should be the same everywhere. It does not hold your look.

The kit is headless:

  • The SDK owns the logic, the accessibility and the data wiring: which price is a real saving, which pages the pager shows, which option link turns a filter on, which attributes make a link safe.
  • Your theme owns the markup classes and every string. You pass className or classNames, and labels for text (or translate every kit string once: i18n.md). Nothing in the kit has a style.
  • Server-rendered by default. The components are plain React with no hooks, so they work in a normal block and also inside an island. Filters and the pager are links, so they work without JavaScript.

Each component has a model function next to it (productCardModel, filterRailModel, galleryModel, cartModel). Use the component, or use only the model and write your own markup.

Contents: Which tool for what · Money · Paths · JSON-LD · Breadcrumbs · Pager · ProductCard · FilterRail · Gallery · Cart model · Variant options · Colour helpers · Listing title · safeNextPath · All exports


Which tool for what

You need Use Import from
A product tile ProductCard, or productCardModel for your own markup @bizzpocket/theme/kit
A price with a sale price Price, formatMoney, discountPercent @bizzpocket/theme/kit
Page links under a listing Pager, pageRun @bizzpocket/theme/kit
Filters beside a listing FilterRail, facetGroups, filterRailModel @bizzpocket/theme/kit
A product photo gallery Gallery, galleryModel @bizzpocket/theme/kit
A CDN image as <picture> (AVIF + WebP, phone art, LCP preload) CdnImg @bizzpocket/theme or /kit (Images)
Cart totals, free shipping, line links cartModel, freeShippingNote @bizzpocket/theme/kit
A cart that updates in the browser useCartView @bizzpocket/theme/client (state.md)
Size and colour pickers buildOptionGroups, chooseOption, optionState, swatchFor @bizzpocket/theme/kit
SEO data (JSON-LD) JsonLd, breadcrumbList, productItemList, faqPage, productJsonLd, organizationJsonLd @bizzpocket/theme/kit
A trail of links Breadcrumbs @bizzpocket/theme/kit
Product, category and collection URLs productPath, categoryPath, collectionPath @bizzpocket/theme/kit
Filter, sort and page URLs parseListParam, applyParamUpdates, pageHref, buildGridQueryArgs... @bizzpocket/theme/browse (browse.md)
A safe ?next= redirect safeNextPath @bizzpocket/theme/kit

The pure functions import no SDK code, so an island may import them. Server components such as Pager render in a block or in an island.


Money

tsx
import { Price, formatMoney, formatMoneyValue, discountPercent } from '@bizzpocket/theme/kit';

formatMoney(100000, 'INR');                 // "₹1,00,000"
formatMoneyValue(product.price);            // the same, from a { amount, currency } object
discountPercent(product.price, product.compareAtPrice); // 20, or null when there is no real saving

<Price price={product.price} compareAtPrice={product.compareAtPrice} showDiscount wasLabel="Was " />
  • formatMoney(amount, currency, { locale?, fractionDigits? }) groups digits by the currency's home locale (INR: ₹1,00,000). fractionDigits: 'auto' (default) drops .00 on whole amounts; 'currency' always shows the minor units. A bad currency code gives "<amount> <code>". A number that is not finite gives an empty string. It never throws.
  • currencyHomeLocale('INR') returns the locale used (en-IN), or en-US for a currency it does not know.
  • discountPercent(price, compareAtPrice) returns a whole number only when the compare-at price is higher than the price and in the same currency. Otherwise null. This stops a fake discount when a seller copies the price into "compare at".

Price props:

Prop Default Meaning
price required { amount, currency }
compareAtPrice none The was-price. Shown struck through only when it is a real saving.
className, classNames none Wrapper class; parts are current, compare, off, was.
as 'span' Wrapper element: 'span', 'p' or 'div'.
showDiscount false Show an "N% off" tag when the saving is 1% or more.
discountLabel (n) => `${n}% off` Text of the tag.
wasLabel none Text before the struck price. Visible; hide it with your own class on classNames.was if you want screen readers only.
live false Adds aria-live="polite". Use it for a price that changes when the shopper picks a variant.

Paths

tsx
import { productPath, categoryPath, collectionPath } from '@bizzpocket/theme/kit';

productPath('linen-shirt');      // "/products/linen-shirt"
categoryPath('wall-art');        // "/categories/wall-art"
collectionPath('summer');        // "/collections/summer"

The handle is URL-encoded. Use these instead of writing /products/${handle} by hand, so a change of URL scheme reaches every theme.


JSON-LD

JsonLd writes one <script type="application/ld+json">. It escapes <, >, & and the two line separator characters, so a product named </script> cannot close the tag. Never use JSON.stringify in dangerouslySetInnerHTML for this.

tsx
import { JsonLd, breadcrumbList, productItemList } from '@bizzpocket/theme/kit';

<JsonLd data={productItemList(items)} marker={false} escape="script-close" />
<JsonLd data={breadcrumbList(trail, origin)} />

JsonLd props:

Prop Default Meaning
data required One node, an array of nodes, or null. null and an empty array render nothing.
origin none Site origin such as https://shop.example.com. Root-relative URLs in data become absolute.
marker true Adds the data-bp-json-ld attribute. false gives a bare script tag.
dedupe true Writes nothing when the page's <head> already carries every entry of data (the host writes the canonical product and breadcrumb data there), so the same JSON-LD is not written twice. false always writes it. With no host, nothing is skipped.
escape 'unicode' 'unicode' writes < > & as \uXXXX. 'script-close' escapes only </, <!-- and the line separators, which matches the old buildStructuredData output. Use it when a theme moves over and must keep its HTML.

The builders return a node, or null when there is nothing worth writing:

Builder Writes
breadcrumbList(trail, origin?) BreadcrumbList from { label, href? } crumbs. A crumb with no safe href has no item.
productItemList(products, origin?) ItemList of product URLs for a listing page. Products without a handle are skipped.
faqPage(items) FAQPage from { question, answer }. Only use it for questions the page really shows.
productJsonLd(input) Product with one Offer. See the warning below.
organizationJsonLd(input) Organization, OnlineStore or Store, for the home page.

serializeJsonLd(data) returns the escaped string. absolutizeJsonLd(node, origin) returns a copy with root-relative values of url, item, image, logo, @id, merchantReturnLink, contentUrl and thumbnailUrl made absolute. JsonLd already calls it when you pass origin.

Do not write a second Product on a product page. The storefront host already writes the canonical Product JSON-LD on a product page. A second one competes with it and can carry a stale price. Use productJsonLd only on pages where the host writes none.


tsx
import { Breadcrumbs } from '@bizzpocket/theme/kit';

<Breadcrumbs
  items={[{ label: 'Home', href: '/' }, { label: 'Wall art', href: '/categories/wall-art' }, { label: 'Poster' }]}
  classNames={{ list: 'crumbs', link: 'crumbs__link', current: 'crumbs__here' }}
  separator="›"
/>

It renders <nav aria-label="Breadcrumb"><ol>. The last crumb is the current page: aria-current="page" and never a link. Earlier crumbs are links only when their href is safe.

Prop Default Meaning
items required { label, href? }[]. An empty list renders nothing.
className, classNames none nav class; parts are list, item, link, current, separator.
separator / Between crumbs, aria-hidden.
ariaLabel Breadcrumb Name of the nav.
jsonLd true Also write the BreadcrumbList JSON-LD. Set false if you write it yourself.
origin none Makes root-relative hrefs absolute in the JSON-LD.

Pager

A pager made of plain links. Page 1 has no page parameter, so the first page keeps one URL. It renders nothing for one page or fewer.

tsx
import { Pager } from '@bizzpocket/theme/kit';
import { pageHref } from '@bizzpocket/theme/browse';

<Pager
  page={data.page}
  totalPages={data.totalPages}
  hrefForPage={(n) => pageHref(data.params, n)}
  windowSize={7}
  prevLabel="Previous"
  nextLabel="Next"
  className="pages"
  classNames={{ page: 'pages__link', current: 'pages__link--current' }}
/>

Hrefs come from one of two places. Pass query (a URLSearchParams, a query string or a plain record) and optionally pathname, and the pager keeps the query and changes only page. Or pass hrefForPage for full control. An unsafe result from hrefForPage renders as plain text.

Prop Default Meaning
page required Current page, 1-based. Clamped into range.
totalPages required Number of pages.
query none Query to keep.
pathname none Path in front of the query.
hrefForPage none (page) => href. Overrides query and pathname.
windowSize 5 How many numbered links to show.
windowStyle 'elided' 'elided' shows the first and last page and a run between (1 4 5 6 20). 'run' shows only a run (3 4 5 6 7).
structure 'list' 'list' is <nav><ul><li>. 'flat' has bare prev/next links in the nav and a <span> around each number.
disabledEdges 'render' 'render' draws a disabled prev or next at the ends. 'omit' draws nothing.
labelMode 'links' Which elements get aria-label: 'links', 'all' or 'none' (visible text only).
labels English { prev?, next?, page?(n) }: the accessible names.
prevLabel, nextLabel ‹, › Visible content of prev and next.
ellipsis off { className?, label? }. Draws a mark (default …) before a number that does not follow the last one.
ariaLabel Pagination Name of the nav.
markers true Write the data-bp-pager* attributes. false leaves only your markup.
pageAttrOrder 'class-first' 'href-first' swaps the attribute order. It changes no meaning. It only keeps a theme's old HTML byte-for-byte when it adopts the kit.
className, classNames none nav class; parts are list, item, page, current, prev, next, disabled.

pageRun(active, totalPages, size = 5) returns the plain run that windowStyle="run" draws, as an array of page numbers. Use it when you build your own hrefs for those pages. It returns [] when totalPages or size is below 1.


ProductCard

A product tile: a photo link, a title link, a price, and optional quick-add and wishlist buttons.

tsx
import { ProductCard } from '@bizzpocket/theme/kit';

<ProductCard
  product={p}
  classNames={{ root: 'card', media: 'card__media', title: 'card__title', price: 'card__price' }}
  quickAdd="below"
  wishlist
  labels={{ addToCart: 'Add to bag', soldOut: 'Sold out' }}
  slots={{ body: (m) => <p className="card__note">{m.title}</p> }}
/>

product is any object with id, handle, title and price. A Product from products(), related() or search() fits. Optional fields: compareAtPrice, image: { src, alt } and inStock. Product has no stock field today. If your gql() selects one, pass it as inStock. false means sold out. Anything else means available.

Props:

Prop Default Meaning
product required See above.
classNames none root, media, img, placeholder, body, title, link, price, compareAt, badge, soldOut, actions, add, wishlist.
heading 'h3' The title element: 'h2', 'h3' or 'span'.
priority false Above the fold: loading="eager" and fetchpriority="high".
sizes, widths grid sizes sizes and widths of the responsive image. The default sizes is PRODUCT_CARD_SIZES, for 2 to 4 columns.
imageWidth, imageHeight 600, 800 The image box, so the layout does not shift.
imageComponent none (a plain <img>) Render the photo through this component, for example imageComponent={kitPicture} for a <picture> with an AVIF source. It receives exactly the props the plain <img> gets (src, srcSet, sizes, class, alt, size, loading, and fetchPriority on a priority card). You pass the component, so a card that does not use it ships no picture code.
quickAdd false 'overlay' puts the button in the photo frame. 'below' puts it after the body.
wishlist false Adds the wishlist heart.
wishlistIcon a heart Your own SVG for the heart.
badges -N% when there is a saving (model) => node. Badges over the photo.
labels English was, off(pct), sale(pct), soldOut, addToCart, wishlist (use {title}).
slots none media, body, footer, actions. Each is a node, or a function of the card model.
children none Rendered after the body, in the same place as slots.body, after it.
linkMode 'title-and-image' See below.
currencyLocale currency home Locale used for the price in the accessible name.

Link mode. In 'title-and-image' the photo link has tabIndex={-1} and aria-hidden, and the title link names the card. In 'whole-card' one link wraps the photo, the title and the price, and the buttons are siblings of it that you place with CSS.

Sold out. When inStock is false, the badge shows labels.soldOut (class classNames.soldOut, else badge), and the quick-add button is disabled.

The card's accessible name is "Title, ₹499, 20% off", set on the <article>.

No interactive element inside the link. A link inside a link, or a button inside one, is invalid HTML and breaks keyboard and screen-reader use. These parts render inside a link: the badge in both modes, and slots.media and slots.body in whole-card mode. Do not put a button, link, input or select in them. Put such things in slots.actions, which is always outside the link. In development the card warns once per slot when it finds one.

Quick-add and the heart use the host's add-to-cart and wishlist-toggle islands. You write no client code for them.

Your own markup: productCardModel

tsx
import { productCardModel } from '@bizzpocket/theme/kit';

const m = productCardModel(p, { sizes: '(max-width: 640px) 50vw, 20vw' });
// m.href, m.title, m.available, m.price, m.compareAt, m.discountPct, m.image, m.ariaLabel

m.compareAt and m.discountPct are set only for a real saving. m.image carries src, srcSet, sizes and alt. The second argument takes sizes, widths, currencyLocale and labels: { off }.


FilterRail

Filters made of links. Each option is an <a> whose href is the listing URL with that option turned on or off. The URLs come from the browse helpers, so every theme writes the same ones. It needs no JavaScript.

There are two steps. First turn the seller's filters into groups with facetGroups. Then turn the groups into links with filterRailModel. Then draw the model with FilterRail, or with your own markup.

tsx
import { FilterRail, facetGroups, filterRailModel } from '@bizzpocket/theme/kit';

const groups = facetGroups(defs, listing);   // defs: categoryFilters, listing: productGridProducts
const model = filterRailModel(groups, params, {
  currency: 'INR',
  availability: { param: 'stock', value: 'in', label: 'In stock only', position: 'first' },
  anyPrice: { label: 'Any price' },
});

<FilterRail model={model} classNames={{ root: 'filters', link: 'filters__link' }} collapsible />

The block that holds this must read the URL, so it uses load(). See browse.md.

facetGroups

facetGroups(defs, listing?, { priceLabel?, booleanCounts? })

  • defs is the seller's filter list (categoryFilters: { name, key, type, options?, min?, max? }), or the listing's own facets (listing.facets).
  • listing is a productGridProducts result. When you pass it, each option gets a product count (0 when the facet was counted and the value is absent). Without it, count is not set.
  • A def of type range with the key price becomes a price group. A boolean def becomes one option meaning "yes". A def of type multi allows several values. A group whose name looks like colour (color, colour) gets swatches. Bad defs are dropped. Nothing throws.
  • If no price group exists and listing.priceRange has a real span, a price group is added. priceLabel names it (default Price).
  • booleanCounts: true also counts a boolean def under its true value. It is off by default because a counted 0 hides the option.

filterRailModel

filterRailModel(groups, params, options?) returns { groups, clearHref, activeCount }. clearHref is null when no filter is active. An option with a count of 0 that is not chosen is dropped, because it would give an empty page. A group with no option left is dropped.

Option Default Meaning
currency none ISO currency of the shop. Required for price groups. Without it price groups are left out; the kit never guesses a currency.
maxVisible 6 Options shown before "+ N more".
maxColours 10 The same, for colour groups. A single option is never folded.
availability none { param, value, label, position? }. Adds an "in stock only" style toggle (?param=value). position is 'first' or 'last' (default). Opt-in.
priceFallback none Price bands when groups has no price group. Pass { products } (bands from the page's products) or { min, max }. Add fallbackRange: { span } to cut bands from lo to lo + span when there is no usable range.
labels English rail, clear, more(hidden), count(n), price, availability, under(max), over(min), range(min, max).
formatBand none (band, currency) => string. Writes the band text yourself, instead of labels plus formatMoney.
anyPrice none { label }. While a price range is chosen, adds an option after the bands that clears it. It has kind: 'any-price'.

Price fallback. With no range at all, priceBands returns no bands (SDK 2 invented a 0 to 10,000 range). A theme that wants the old bands sets priceFallback: { min: null, max: null, fallbackRange: { span: 10000 } }. The fallback applies to every price group in the model.

Each group is { key, label, type, options, more, hidden, selected, chosen }. more holds the folded options. selected counts chosen options in this group. chosen counts the values chosen in the URL for this attribute, including values that are not among the options. Each option is { value, label, count?, href, active, swatch?, kind? }.

FilterRail props

Prop Default Meaning
model required From filterRailModel.
classNames none root, group, label, selectedCount, list, item, link, linkActive, any, swatch, count, more, moreToggle, clear.
collapsible false true, or (group) => boolean. Wraps a group in <details>. Others are a role="group" div.
open first group and any with a chosen option (group, index) => boolean. Whether a collapsible group starts open.
renderOption built-in link (option, group) => node. Keep the <a> and aria-current in your markup.
renderLabel label and selected count (group) => node. The group heading.
renderMore labels.more (hidden, group) => node. The "+ N more" text.
groupAriaLabel group label (group) => string. For a group that is not collapsible.
groupProps none (group) => attributes, for example { 'data-kind': 'colour' }.
as 'div' Root tag.
rootProps none Attributes spread on the root after the defaults. Set one to undefined to remove it.
listRole true Put role="list" on the option lists.
showClear true Draw the "Clear all" link. Set false and place model.clearHref yourself.
swatches true Draw the colour swatch in a colour option.
markers true Write the data-bp-* attributes.
labels English Same shape as in filterRailModel.

The active option has aria-current="true". A swatch is aria-hidden; the option's text names it.

Custom render

To keep your own markup for an option, pass renderOption. The kit draws the <li> around it.

tsx
<FilterRail
  model={model}
  renderOption={(o) => (
    <a className={o.active ? 'chip chip--on' : 'chip'} href={o.href} {...(o.active ? { 'aria-current': 'true' } : {})}>
      {o.swatch ? <span className="chip__dot" style={{ background: o.swatch }} aria-hidden="true" /> : null}
      {o.label}
    </a>
  )}
/>

To control all of the markup, skip FilterRail and loop over model.groups yourself.


The product photo gallery: a model and a server component. The component writes the markup with data-bp-gallery="v2". The storefront's image-gallery behaviour then adds thumbnails, variant photos, video and a zoom lightbox. The server renders the opening state, so the page is correct before any script runs.

tsx
import { Gallery, galleryModel } from '@bizzpocket/theme/kit';

const model = galleryModel(product, { variantId, video: videoUrl ? { src: videoUrl, poster: posterUrl } : undefined });

<Gallery
  model={model}
  zoom
  imageInZoom
  classNames={{ root: 'gallery', main: 'gallery__main', thumbs: 'gallery__thumbs', thumb: 'gallery__thumb' }}
  icons={{ zoom: <ZoomIcon />, close: <CloseIcon />, prev: <PrevIcon />, next: <NextIcon /> }}
/>

galleryModel(product, options?) takes a ProductDetail. It returns { productId, slides, byVariant, variantId, order, start }.

  • slides are the product images, then variant photos that are not product images, then the video. Only https or root-relative sources are kept.
  • byVariant maps a variant id to the slide indexes it shows: its own photos, then the shared ones. A variant with no photos of its own is absent, and shows every slide.
  • variantId is the variant the page opens on, only when it has its own photos. order lists the slides shown first, and start is order[0].

Model options: variantId (the buy box's choice or ?variant=), sizes (main image, default (min-width: 1024px) 50vw, 100vw), thumbSizes (default 96px) and video: { src, poster?, alt? } (added as the last slide).

Gallery props:

Prop Default Meaning
model required From galleryModel.
classNames none root, stage, main, video, zoom, thumbs, thumb, thumbImage, lightbox, lightboxImage, close, prev, next, counter, thumbPlaceholder.
thumbs true Thumbnail strip. It is hidden for one slide anyway.
zoom false Zoom button and lightbox. Opt-in.
imageComponent none (plain <img>) Render the main image and the thumbnails through this component, for example kitPicture. It receives exactly the props the plain <img> gets (src, srcSet, sizes, class, alt, size, loading, the data-bp-gallery-main hook on the main image). The gallery runtime drops the main image's <source> elements when it swaps photos, so a variant change shows the right photo.
imageInZoom false Put the main image inside the zoom button, so a click on the photo zooms. Needs zoom. With false the button is a sibling.
icons none prev, next, zoom, close: content of the icon buttons. The buttons keep their accessible names.
labels the theme's kit.gallery.* text, else English show(n, total, alt), zoom, close, prev, next. Every field is optional: a label you leave out falls back field by field to the theme's translation, then to English.
aspectRatio 1 Width over height of the main image when the image data has no size. Sets width and height so the page does not shift.

Video. A video slide uses a <video> element with controls and preload="none". Its thumbnail is the poster. With no poster, a placeholder (classNames.thumbPlaceholder) stands in.

The data-bp-gallery="v2" behaviour. The root has data-bp-island="image-gallery" and data-bp-gallery="v2". The runtime reads the data-bp-gallery-* hooks and a <script type="application/json" data-bp-gallery-data> inside the root. It changes the photo on a thumb click, switches the photo set when the shopper picks a variant (the bizzpocket:variant:change event, and ?variant=), and opens the lightbox (a role="dialog" with Escape, arrow keys, a focus loop, swipe and a live counter). If you bring your own markup with galleryModel only, you do not get this behaviour. Write your own island, as the themes did before.

New in 3.3. Gallery is the first version of this component. Themes that already ship their own gallery island keep working. Switch when you want the shared behaviour, and check zoom and video on a real product first.


Content and reviews

tsx
import { ContentBody, safeReviews } from '@bizzpocket/theme/kit';

ContentBody shows a store content page's body (page().body, see data.md). The body is plain text: a blank line starts a <p>, a single line break becomes <br>, and nothing is read as HTML (markup in the text shows as text). text is the body (null, undefined or blank renders nothing); className is the wrapper's class and paragraphClassName the class of each <p>.

tsx
<ContentBody text={about.body} className="prose" paragraphClassName="prose__p" />

safeReviews(data, anonymous?) takes the result of reviews() and returns { rating, reviews } that is safe to render: ratings are clamped to 0 to 5, names (80 characters) and comments (2,000) are trimmed and cut without splitting an emoji or a letter with its accents, and entries with no comment are dropped. rating is null when the product has no rating; anonymous is the name shown for a review with no name. It never throws, and null gives an empty result.

tsx
const { rating, reviews: list } = safeReviews(reviews, 'A customer');
return list.map((r) => <blockquote key={r.comment}>{r.comment} <cite>{r.name}</cite></blockquote>);

Cart model

Cart logic with no markup: line links, item count, subtotal, free-shipping progress and a sentence for a screen reader. It is pure and works on the server.

tsx
import { cartModel } from '@bizzpocket/theme/kit';

const cart = cartModel(initialCart, { freeShippingOver: 2000 });
// cart.lines (with .href), cart.itemCount, cart.subtotal, cart.freeShipping, cart.liveMessage

For a cart that changes in the browser, give the same input to useCartView from @bizzpocket/theme/client (state.md). It runs cartModel for you and keeps it in step with the host.

The input is { lines, totals? }. A line has lineId, productId, variantId, title, quantity, price, handle and optional variantTitle, options, compareAtPrice, image and swatchColor. CartLine<{ gift: boolean }> adds your own fields, and the model keeps them.

Options:

Option Default Meaning
freeShippingOver none The store's threshold, in the cart's currency. null or 0 or less: no progress.
fromLines false Work out the subtotal from the lines, not from totals.subtotal. Use it while a change is waiting for the host.
messages English The live-region sentences: empty, updated, freeShippingRemaining, freeShippingReached. Each is a template with {name} values, or a function.
pctRounding 'floor-until-reached' How freeShipping.pct rounds. 'floor-until-reached' rounds to the nearest percent but never shows more than 99 until the threshold is met. 'round' rounds to the nearest percent, so 99.5 shows 100 before it is met.

The template values: updated gets count and subtotal (formatted), freeShippingRemaining gets remaining (formatted). A message can also be a function of the same values.

Money maths. Amounts stay in major units, like 499.5. Inside, the model adds in whole minor units (paise, cents) and rounds half up on the decimal digits, so 1.005 is not 1.00. The number of minor-unit digits comes from the currency (JPY 0, USD 2, KWD 3).

Mixed currency. The cart's currency is the one in totals.subtotal, else the first line's. A line in another currency sets mixedCurrency: true. Such a line is left out of a computed subtotal, and freeShipping is null. Show your own message in that case.

freeShippingProgress(subtotal, threshold, currency, pctRounding?) is the free-shipping maths on its own. It returns { remaining, pct, reached, currency }, or null without a usable threshold.

freeShippingNote

The sentence for an announcement bar or a product page. The SDK formats the money. Your theme gives the words, because there is no default text.

tsx
import { freeShippingNote } from '@bizzpocket/theme/kit';

const note = freeShippingNote({
  threshold: 1499,
  subtotal: cart.subtotal.amount,        // leave out on a page with no cart
  currency: 'INR',
  labels: {
    over: (t) => `Free shipping on orders over ${t}`,
    remaining: (left) => `Add ${left} more for free shipping`,
    reached: () => 'Your order ships free',
  },
});
note?.text;   // the sentence. note.kind is 'over', 'remaining' or 'reached'. note.parts has the amounts.

It returns null without a usable threshold. Without subtotal it says over. remaining and reached fall back to over when you do not give them.


Variant options

Pure helpers for the size and colour pickers of a buy box. They work on BuyVariant objects: { id, title, price, compareAt, inStock, options: [{ name, value }], image }.

tsx
import { buildOptionGroups, initialSelection, chooseOption, matchVariant, optionState } from '@bizzpocket/theme/kit';

const groups = buildOptionGroups(variants);              // [{ name: 'Size', values: ['S', 'M'] }, ...]
const [sel, setSel] = useState(() => initialSelection(variants, groups, preferredId));
const variant = matchVariant(variants, groups, sel);     // the chosen variant, or null
optionState(variants, groups, sel, 'Size', 'M');         // 'available' | 'soldout' | 'unavailable'
setSel(chooseOption(variants, groups, sel, 'Size', 'M'));
Function What it does
buildOptionGroups(variants) One group per option name that offers a real choice. An option with a single value is not a picker.
initialSelection(variants, groups, preferredId?) The start: the ?variant= one if it exists, else the first in stock, else the first.
startVariantId(variants, preferredId?) The same rule, returning the id. null without variants.
matchVariant(variants, groups, selection) The variant the picks select, or null.
chooseOption(variants, groups, selection, name, value) Picks the value. If that mix does not exist, it keeps the pick and moves the other options to the closest mix that does, preferring one in stock.
optionState(variants, groups, selection, name, value) How a value would look if picked now.
galleryForVariant(images, variantImages, variantId) The photos for one variant: its own, then the shared ones. A variant with none shows all.

Selection is a record of option name to chosen value. OptionGroup is { name, values }.

Colour helpers

  • isColourOption(name) is true for color, colour, colors and colours (any case).
  • swatchFor(value) returns a CSS background for a known colour name, or null. Use the text chip when it is null: a wrong guess at a colour is worse than its name.
  • parseColor(css) reads #rgb, #rgba, #rrggbb, #rrggbbaa, rgb() and rgba() into [r, g, b], or null. The alpha is ignored.
  • contrastRatio(a, b) is the WCAG 2 ratio of two Rgb colours, from 1 to 21. AA_CONTRAST is 4.5.
  • readableOnColors(colors, inherited?) returns the on-background, on-card, on-primary ... tokens a palette needs, picking a colour that passes AA. A key the palette already sets is kept.
tsx
import { swatchFor, isColourOption } from '@bizzpocket/theme/kit';

isColourOption('Colour');       // true
swatchFor('Navy Blue');         // '#1d2a57'
swatchFor('Midnight');          // null

Listing title

  • humanizeSlug('wall-art') returns "Wall art".
  • resolveListingH1(shopTitle, ctx) returns the one <h1> text of a shop, category, collection or search page, or null on any other page. A category uses its real name from the category tree, else the humanised slug. ListingTitleContext is the slice of a block load() context it reads.

safeNextPath

safeNextPath(next) checks a ?next= value before you redirect to it. It returns a same-site path, or null. Use it on the server and in the browser; it needs no origin.

tsx
import { safeNextPath } from '@bizzpocket/theme/kit';

const to = safeNextPath(url.searchParams.get('next')) ?? '/account';

It refuses anything that is not a string, anything over 2048 characters, anything that does not start with a single / (//host, https://..., javascript:...), and any backslash or control character. safeNextPath is not exported from @bizzpocket/theme/client, because servers need it too. In an island, useCustomerAuth already applies it to ?next= for you.


Images: Image, responsiveImage or CdnImg

Three tools, from least to most control. All are server-safe (no hooks) and work in islands.

Use When
<Image src alt width height sizes priority /> The default for a block: one image, and the SDK picks the markup. A BizzPocket CDN image gets a <picture> with an AVIF source and a WebP srcset; any other host a plain <img>.
responsiveImage({ src, sizes }) You write the <img> yourself (extra attributes, a wrapper that must stay a bare <img>): spread the result for the srcset, sizes and a mid-size src. responsivePicture() also gives the AVIF <source>.
<CdnImg image={{ src, sizes }} ... /> Markup ported from @bizzpocket/theme-sdk's CdnImg (same props, same HTML, same CDN URLs), phone art with mobile={{ src, media }}, or an LCP image with priority (adds the preload links). Use it to drop the SDK 2 import with a one-line change.
tsx
import { CdnImg } from '@bizzpocket/theme';

<CdnImg image={{ src: hero.src, sizes: '100vw' }} mobile={{ src: hero.mobileSrc, media: '(max-width: 767px)' }}
        alt={hero.alt} width={1600} height={900} priority />

CdnImg renders a <picture style="display: contents">, so CSS written as parent > img must also list parent > picture > img. Do not nest it inside another <picture>. Also pass imageComponent={kitPicture} (exported next to CdnImg) to ProductCard and Gallery to get the same markup there.


All exports

Functions and values: CdnImg, kitPicture, formatMoney, formatMoneyValue, currencyHomeLocale, Price, discountPercent, JsonLd, absolutizeJsonLd, serializeJsonLd, breadcrumbList, faqPage, productItemList, productJsonLd, organizationJsonLd, Breadcrumbs, Pager, pageRun, productPath, categoryPath, collectionPath, safeNextPath, isColourOption, swatchFor, humanizeSlug, resolveListingH1, buildOptionGroups, matchVariant, initialSelection, chooseOption, optionState, startVariantId, galleryForVariant, AA_CONTRAST, parseColor, contrastRatio, readableOnColors, cartModel, freeShippingProgress, freeShippingNote, Gallery, galleryModel, ProductCard, productCardModel, PRODUCT_CARD_SIZES, FilterRail, facetGroups, filterRailModel, ContentBody, contentParagraphs, safeReviews, clampRating, KIT_EN, I18nProvider, useKitI18n, kitText, kitNumber, registerRenderOriginSource, currentRenderOrigin, normaliseOrigin, registerRenderHeadSource, registerRenderI18nSource, currentRenderI18n.

Types: CdnImgProps, CdnImgMobileArt, FormatMoneyOptions, PriceProps, PriceClassNames, JsonLdProps, StructuredDataPayload, ProductJsonLdInput, OrganizationJsonLdInput, BreadcrumbsProps, BreadcrumbsClassNames, Crumb, PagerProps, PagerClassNames, PagerQuery, ListingTitleContext, BuyVariant, OptionGroup, Selection, Rgb, CartLine, CartLineBase, CartPctRounding, FreeShippingNote, FreeShippingNoteLabels, CartTotals, CartInput, CartModel, CartModelOptions, FreeShippingProgress, CartMessages, CartMessage, GalleryProps, GalleryModel, GallerySlide, GalleryModelOptions, GalleryClassNames, GalleryLabels, GalleryIcons, ProductCardProps, ProductCardModel, ProductCardClassNames, ProductCardSource, ProductCardLabels, ProductCardSlots, ProductCardSlot, FacetGroup, FilterDefLike, FilterRailModel, FilterRailGroup, FilterRailOption, FilterRailProps, FilterRailClassNames, FilterRailLabels, FilterRailAvailability, FilterRailPriceFallback, FilterRailBand, ContentBodyProps, SafeReview, SafeReviews, KitI18n.

The URL helpers (pageHref, pageWindow, priceBands and the rest) live in @bizzpocket/theme/browse. See browse.md.