BizzPocket

Browse URLs: @bizzpocket/theme/browse

On this page

A listing page (shop, category, collection, search) is steered by its URL: ?sort=price-asc&f_color=Red&page=2. The filter rail writes these links. The product grid reads them back. Neither needs to know what a filter means, so the same two blocks work for any catalogue.

@bizzpocket/theme/browse is the one place that defines this vocabulary. It has no dependencies and no Node code, so an island may import it. Use it instead of writing your own ?price_from= and ?page=.

Contents: The URL vocabulary · Reading params · Building links · Pages · Price bands · Query arguments · A listing block with load() · load() or data()


The URL vocabulary

Param Meaning
f_<key> An attribute filter. f_color=Red,Blue means Red or Blue. A list is comma-separated.
price_min, price_max A price range, in the shop's currency.
stock in (only in stock) or out.
sort newest, price-asc or price-desc. Anything else means the server's own order.
page The page number, from 1. Page 1 has no page param.
category Set by the host on a category or collection route. It is not a filter, and it never appears in a built link.

Old bookmarks still work. normalizeSearchParams turns price_from, price_to and availability=in-stock|out-of-stock into price_min, price_max and stock=in|out.

SearchParams is a flat record of name to string: Readonly<Record<string, string>>.


Reading params

Function Returns
normalizeSearchParams(raw) A clean SearchParams from whatever the host gives. The first value of a repeated name wins. Non-strings are dropped. Legacy names are renamed. Start here.
parseListParam(raw) The values of a comma list, trimmed and without duplicates.
parsePriceParam(raw) A number that is not negative and is finite, else undefined.
parseSortParam(params) 'newest', 'price-asc', 'price-desc', or undefined.
parsePageParam(params) A whole number of 1 or more, or undefined.
activeAttributeSelections(params) [{ key, values }] for every f_* param that has a value.
isFilterParam(name) True for f_*, price_min, price_max and stock. False for category, sort and page.
activeFilterCount(params) One per chosen attribute value, plus one for a price range, plus one for stock=in.

attrParamName('color') gives f_color. ATTR_PARAM_PREFIX is f_. SORT_VALUES is the list of sort values.

ts
import { normalizeSearchParams, parseListParam, activeFilterCount } from '@bizzpocket/theme/browse';

const params = normalizeSearchParams({ f_color: 'Red,Blue', price_from: '100' });
parseListParam(params['f_color']);   // ['Red', 'Blue']
activeFilterCount(params);           // 3: two colours and one price range

Every function here returns new params or a link. None changes its input.

Function What it does
applyParamUpdates(params, updates) Applies { name: value | null }. null or '' removes the param. It always drops page first, so any filter or sort change goes back to page 1.
toggleListParam(params, name, value) Adds the value to a comma list, or removes it when it is there. The param goes away when the list is empty.
serializeParams(params) A query-only href such as ?f_color=Red&sort=newest. Keys are sorted, so one selection is one URL. category and empty values are skipped. An empty set gives ?, which is a valid link to the bare path.
clearAllFiltersHref(params) A link with every filter removed. It keeps sort and resets page.
ts
import { applyParamUpdates, toggleListParam, serializeParams, clearAllFiltersHref } from '@bizzpocket/theme/browse';

serializeParams(toggleListParam(params, 'f_color', 'Red'));            // "?f_color=Red"
serializeParams(applyParamUpdates(params, { sort: 'price-asc' }));      // "?sort=price-asc"
clearAllFiltersHref(params);                                            // "?sort=price-asc" when sort was set

Because serializeParams returns a query only, the link works on whatever path the shopper is on. That includes a category path such as /categories/wall-art.

The "active filter count" and "clear all" pair is how you build a filter chip bar or an empty state:

tsx
const count = activeFilterCount(params);
{count > 0 ? <a href={clearAllFiltersHref(params)}>Clear {count} filters</a> : null}

Pages

  • pageHref(params, page) returns the link to a page that keeps the filters. Page 1 drops the page param, so the first page has one URL.
  • pageWindow(active, totalPages, max) returns the page numbers to show: the first page, the last page and a run around the active one ([1, 4, 5, 6, 20]). With totalPages <= max it returns every page.

The kit's Pager calls these for you (kit.md). Call them yourself only when you draw the pager yourself:

tsx
{pageWindow(page, totalPages, 7).map((n) => (
  <a key={n} href={pageHref(params, n)} aria-current={n === page ? 'page' : undefined}>{n}</a>
))}

Price bands

priceBands(min, max, fallbackRange?) cuts a price range into up to four preset bands. The edges are rounded to a clean step (1, 2 or 5 times a power of ten), and the last band has no upper edge.

ts
import { priceBands } from '@bizzpocket/theme/browse';

priceBands(249, 1499);
// [{ max: 500 }, { min: 500, max: 1000 }, { min: 1000, max: 1500 }, { min: 1500 }]

Pass the seller's price range from categoryFilters, else the catalogue's priceRange from productGridProducts.

With no usable range (max missing, not finite, or not above min) it returns []. A min alone is not a range. SDK 2 used a fixed 0 to 10,000 span here, which gave a shop priced 249 to 1,299 bands that were 5,000 wide. If you want the old behaviour, ask for it with span:

ts
priceBands(null, null, { span: 10000 });
// [{ max: 5000 }, { min: 5000, max: 10000 }, { min: 10000, max: 15000 }, { min: 15000 }]

span is opt-in. There is no default. The kit's filterRailModel takes the same thing as priceFallback.fallbackRange (kit.md).


Query arguments

Function What it does
buildBrowseFilters(params) The filters object of productGridProducts: priceMin, priceMax, inStock, color, size and attributes. f_color and f_size fill color and size. Every other f_<key> goes to attributes. It returns undefined when no filter is active.
buildGridQueryArgs(params, { limit, collection?, fallbackSort? }) The whole argument object of productGridProducts: collection, limit, page, sort, filters.

Compose the arguments in one function that every block of the page calls. The host runs identical queries once per page, but only when the arguments match exactly. If the grid, the sort control and the filter rail each build their own, the arguments drift and the page makes the same request three times. buildGridQueryArgs is made to be that one place.

Its rules:

  • A routed category (params.category) becomes collection, unless you pass collection yourself.
  • page is sent only above 1. sort is sent only when the URL has a valid one, or when you pass fallbackSort. It never invents a sort the shopper did not pick.
  • filters is left out when there are none.

A listing block with load()

A listing reads the shopper's URL, so it uses load(ctx). ctx.route holds the URL: q, sort, page and filters (the other search params, with the routed category among them). Build the params once, query once, and pass plain data to render.

This is the pattern of the Shosy theme's product-grid-shosy. The helper file is shared by the grid, the sort control and the filter rail, so all three make the same query.

ts
// blocks/product-grid/listing-query.ts
import type { LoadContext, ProductGridResult, RouteValues } from '@bizzpocket/theme';
import { buildGridQueryArgs, normalizeSearchParams, type SearchParams } from '@bizzpocket/theme/browse';

export const PAGE_SIZE = 24;

/** The URL's words as one flat record. */
export function listingParams(route: RouteValues): SearchParams {
  const raw: Record<string, string> = { ...(route.filters ?? {}) };
  if (route.q !== undefined) raw['q'] = route.q;
  if (route.sort !== undefined) raw['sort'] = route.sort;
  if (route.page !== undefined) raw['page'] = String(route.page);
  return normalizeSearchParams(raw);
}

/** Runs the query. `null` when it fails. */
export function queryListing(ctx: Pick<LoadContext, 'route' | 'query'>): Promise<ProductGridResult | null> {
  const args: Record<string, unknown> = { ...buildGridQueryArgs(listingParams(ctx.route), { limit: PAGE_SIZE }) };
  return ctx.query('productGridProducts', args).catch(() => null);
}

And the block:

tsx
// blocks/product-grid/product-grid.tsx
import { block } from '@bizzpocket/theme';
import { pageHref } from '@bizzpocket/theme/browse';
import { Pager, ProductCard } from '@bizzpocket/theme/kit';
import { listingParams, queryListing } from './listing-query';

export default block({
  name: 'Product grid',
  category: 'products',
  async load(ctx) {
    const result = await queryListing(ctx);
    // A failed query gives an empty object. render must cope with missing keys.
    if (result === null) return {};
    return {
      products: result.products,
      page: Math.max(1, result.page),
      totalPages: result.totalPages,
      params: { ...listingParams(ctx.route) },
    };
  },
  render: ({ products, page, totalPages, params }) => (
    <section>
      <ul className="grid">
        {(products ?? []).map((p) => (
          <li key={p.id}>
            <ProductCard product={p} classNames={{ root: 'card', title: 'card__title' }} />
          </li>
        ))}
      </ul>
      <Pager page={page ?? 1} totalPages={totalPages ?? 0} hrefForPage={(n) => pageHref(params ?? {}, n)} />
    </section>
  ),
});

The filter rail uses the same listingParams and queryListing, and adds categoryFilters to the query. See FilterRail in kit.md.


load() or data()

The rule:

  • A listing that depends on URL filters stays on load(). route.filters is not mapped into products(). A static data() need cannot read the shopper's ?f_color=Red, so it cannot fetch the filtered page. This is the case in this page.
  • Everything else uses data(). A homepage rail, a "new arrivals" strip, a related-products row, the menu and the store profile do not depend on the URL's filters. data() is faster and the page stays cacheable (data.md).

A load() block always counts as runtime in the size table, because it runs on every request. That is the price of a filterable listing. Keep the rest of the page on data().

The routed category still works without load(). A grid with no URL filters can use products({ collection }) in data() and read the collection from a field.