BizzPocket

Collection filters

Price bands taken from the catalogue's own price range, an in-stock toggle and a phone filter sheet, all as plain links. A grid block that honours them.

On this page

Goal: a filter panel for a collection or category page, with price bands worked out from the catalogue's own prices, an "only in stock" toggle and a bottom sheet on phones, and a product grid that follows the filters in the URL. Neither block sends JavaScript.

Data filters: static (products().priceRange); grid: runtime (load(), see why)
JavaScript 0 bytes. Every filter is a link; the sheet is a native popover.
Uses products(), page.route / ctx.route.filters, load() with ctx.query, the HTML popover attribute

The recipe has two blocks and five files. The filters write the URL (?price_min=500&price_max=1000&stock=in); the grid reads it.

The URL helpers

Both blocks share one small file, so they always agree on what a URL means. Create blocks/collection-filters/browse-params.ts:

blocks/collection-filters/browse-params.ts
import type { RouteValues } from '@bizzpocket/theme';

/**
 * The URL words the filters write and the grid reads: `?price_min=500&price_max=1000&stock=in`.
 * They are the names BizzPocket's own themes use, so a theme that mixes blocks still agrees on them.
 */
export type FilterUpdate = Partial<Record<'price_min' | 'price_max' | 'stock', string | null>>;

/** One price band. `min` / `max` are the URL values (strings), so they compare with the route as is. */
export interface PriceBand {
  min?: string;
  max?: string;
}

const round = (n: number) => String(Math.round(n * 100) / 100);

/**
 * About `count` bands with round edges over the catalogue's own price range:
 * 499 to 2149 gives "Under 500", "500 – 1000", "1000 – 1500", "1500 – 2000", "2000 and up".
 */
export function priceBands(range: { min: number; max: number } | null, count = 4): PriceBand[] {
  if (range === null || !(range.max > range.min)) return [];
  const raw = (range.max - range.min) / count;
  const mag = 10 ** Math.floor(Math.log10(raw));
  const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag;
  const first = Math.ceil(range.min / step) * step;
  const edges: number[] = [];
  for (let i = 0; first + i * step < range.max && i < 8; i++) edges.push(first + i * step);
  if (edges.length === 0) return [];
  const bands: PriceBand[] = [{ max: round(edges[0]!) }];
  for (let i = 1; i < edges.length; i++) bands.push({ min: round(edges[i - 1]!), max: round(edges[i]!) });
  bands.push({ min: round(edges[edges.length - 1]!) });
  return bands;
}

/**
 * A query-only link (`?…`) to the same page with `updates` applied (`null` removes a key). It keeps the
 * shopper's other filters and the sort, and drops the page number, so a new filter starts on page 1.
 * `category` is left out: on a category or collection page the host adds it from the path.
 */
export function filterHref(route: RouteValues, updates: FilterUpdate): string {
  const params = new URLSearchParams();
  for (const [k, v] of Object.entries(route.filters ?? {})) if (k !== 'category') params.set(k, v);
  if (route.sort !== undefined) params.set('sort', route.sort);
  for (const [k, v] of Object.entries(updates)) {
    if (v === null || v === undefined) params.delete(k);
    else params.set(k, v);
  }
  const qs = params.toString();
  return qs === '' ? '?' : `?${qs}`;
}

/** How many filters are on (a price band counts once). */
export function activeCount(filters: Record<string, string>): number {
  return (filters.price_min !== undefined || filters.price_max !== undefined ? 1 : 0) + (filters.stock === 'in' ? 1 : 0);
}

const price = (v: string | undefined): number | undefined => {
  const n = v === undefined || v.trim() === '' ? NaN : Number(v);
  return Number.isFinite(n) && n >= 0 ? n : undefined;
};

/** The route's filters as `productGridProducts`' typed `filters` input. */
export function gridFilters(filters: Record<string, string>): { priceMin?: number; priceMax?: number; inStock?: true } {
  const out: { priceMin?: number; priceMax?: number; inStock?: true } = {};
  const min = price(filters.price_min);
  const max = price(filters.price_max);
  if (min !== undefined) out.priceMin = min;
  if (max !== undefined) out.priceMax = max;
  if (filters.stock === 'in') out.inStock = true;
  return out;
}

The filters block

Create blocks/collection-filters/collection-filters.tsx:

blocks/collection-filters/collection-filters.tsx
import { block, f, products } from '@bizzpocket/theme';
import { activeCount, filterHref, priceBands } from './browse-params';
import './collection-filters.css';

export default block({
  name: 'Collection filters',
  category: 'utility',
  fields: {
    heading: f.text({ default: 'Filters' }),
    priceLabel: f.text({ default: 'Price' }),
    stockLabel: f.text({ default: 'Only in stock' }),
    clearLabel: f.text({ default: 'Clear all' }),
    currencySymbol: f.text({ default: '₹' }),
  },
  // Static. One product is enough: only `priceRange` is used, the range of the whole
  // collection (the route's handle), unfiltered, so the bands stay put while the shopper filters.
  data: (_props, page) => ({ all: products({ collection: page.route.handle, first: 1 }) }),
  render: ({ all, heading, priceLabel, stockLabel, clearLabel, currencySymbol }, ctx) => {
    const route = ctx.route;
    const current = route.filters ?? {};
    const bands = priceBands(all?.priceRange ?? null);
    const inStockOnly = current.stock === 'in';
    const active = activeCount(current);
    const sheetId = `cf-sheet-${ctx.blockId}`;
    const fmt = (n: number) => `${currencySymbol}${n.toLocaleString('en-IN')}`;

    return (
      <aside className="cf" aria-label={heading}>
        {/* Phones: one button opens the sheet. Wider screens hide it and show the panel inline. */}
        <button type="button" className="cf-open" popoverTarget={sheetId}>
          {active > 0 ? `${heading} (${active})` : heading}
        </button>

        <div id={sheetId} className="cf-sheet" popover="auto">
          <div className="cf-head">
            <h2 className="cf-title">{heading}</h2>
            <button type="button" className="cf-close" popoverTarget={sheetId} popoverTargetAction="hide" aria-label="Close">
              ✕
            </button>
          </div>

          {bands.length > 0 ? (
            <fieldset className="cf-group">
              <legend>{priceLabel}</legend>
              <ul className="cf-chips">
                {bands.map((b) => {
                  const on = current.price_min === b.min && current.price_max === b.max;
                  const text =
                    b.min !== undefined && b.max !== undefined
                      ? `${fmt(Number(b.min))} to ${fmt(Number(b.max))}`
                      : b.max !== undefined
                        ? `Under ${fmt(Number(b.max))}`
                        : `${fmt(Number(b.min))} and up`;
                  return (
                    <li key={`${b.min}-${b.max}`}>
                      <a
                        className={on ? 'cf-chip cf-chip--on' : 'cf-chip'}
                        href={filterHref(route, { price_min: on ? null : b.min ?? null, price_max: on ? null : b.max ?? null })}
                        {...(on ? { 'aria-current': 'true' as const } : {})}
                      >
                        {text}
                      </a>
                    </li>
                  );
                })}
              </ul>
            </fieldset>
          ) : null}

          <fieldset className="cf-group">
            <legend>Availability</legend>
            <a
              className={inStockOnly ? 'cf-chip cf-chip--on' : 'cf-chip'}
              href={filterHref(route, { stock: inStockOnly ? null : 'in' })}
              {...(inStockOnly ? { 'aria-current': 'true' as const } : {})}
            >
              {stockLabel}
            </a>
          </fieldset>

          {active > 0 ? (
            <a className="cf-clear" href={filterHref(route, { price_min: null, price_max: null, stock: null })}>
              {clearLabel}
            </a>
          ) : null}
        </div>
      </aside>
    );
  },
});

Create blocks/collection-filters/collection-filters.css:

blocks/collection-filters/collection-filters.css
.cf { padding: 1rem; }
.cf-open { width: 100%; padding: 0.75rem 1rem; border: 1px solid #ccc; border-radius: 0.5rem; background: #fff; font-weight: 600; cursor: pointer; }

/* Phones: the panel is a bottom sheet (a native popover: Esc and an outside tap close it). */
.cf-sheet {
  inset: auto 0 0 0; margin: 0; width: 100%; max-width: none; max-height: 80vh; overflow-y: auto;
  padding: 1rem 1rem 2rem; border: 0; border-radius: 1rem 1rem 0 0; background: #fff;
}
.cf-sheet::backdrop { background: rgb(0 0 0 / 0.4); }
.cf-head { display: flex; justify-content: space-between; align-items: center; }
.cf-title { margin: 0; font-size: 1.125rem; }
.cf-close { border: 0; background: none; font-size: 1.25rem; cursor: pointer; }

.cf-group { border: 0; padding: 0; margin: 1.25rem 0 0; }
.cf-group legend { font-weight: 600; margin-bottom: 0.5rem; }
.cf-chips { display: flex; flex-wrap: wrap; gap: 0.5rem; list-style: none; margin: 0; padding: 0; }
.cf-chip { display: inline-block; padding: 0.4rem 0.9rem; border: 1px solid #ccc; border-radius: 999px; color: inherit; text-decoration: none; }
.cf-chip--on { background: #111; border-color: #111; color: #fff; }
.cf-clear { display: inline-block; margin-top: 1.25rem; color: inherit; }

/* Wider screens: no button, and the same panel sits in the page. Author CSS beats the
   browser's `[popover]:not(:popover-open) { display: none }`, so it shows without being opened. */
@media (min-width: 900px) {
  .cf-open, .cf-close { display: none; }
  .cf-sheet { display: block; position: static; inset: auto; max-height: none; overflow: visible; padding: 0; border-radius: 0; background: none; }
  .cf-chips { flex-direction: column; align-items: flex-start; }
}

The grid block

Create blocks/filtered-grid/filtered-grid.tsx:

blocks/filtered-grid/filtered-grid.tsx
import { block, f, Image, Money, type ProductGridResult } from '@bizzpocket/theme';
import { filterHref, gridFilters } from '../collection-filters/browse-params';
import './filtered-grid.css';

export default block({
  name: 'Filtered grid',
  category: 'products',
  fields: {
    count: f.number({ default: 12, min: 1, max: 48, integer: true }),
    emptyText: f.text({ default: 'No products match these filters.' }),
  },
  // Runtime by design: the URL's filters are strings, and `productGridProducts` wants numbers
  // (`priceMin: 500`) and a boolean (`inStock: true`). Turning one into the other is logic,
  // and a static `data()` cannot hold logic. `load()` runs per request, as the shopper.
  async load(ctx) {
    const grid = (await ctx.query('productGridProducts', {
      collection: ctx.route.handle,
      limit: ctx.props.count,
      page: ctx.route.page,
      sort: ctx.route.sort,
      filters: gridFilters(ctx.route.filters ?? {}),
    })) as ProductGridResult | null;
    return { grid };
  },
  render: ({ grid, emptyText }, ctx) => {
    const list = grid?.products ?? [];
    if (list.length === 0) return <p className="fg-empty">{emptyText}</p>;
    const page = grid?.page ?? 1;
    const pages = grid?.totalPages ?? 1;
    // Keep the shopper's filters and sort on the page links.
    const pageHref = (n: number) => {
      const base = filterHref(ctx.route, {});
      return n === 1 ? base : `${base}${base === '?' ? '' : '&'}page=${n}`;
    };
    return (
      <section className="fg">
        <p className="fg-total">{`${grid?.total ?? list.length} products`}</p>
        <ul className="fg-grid">
          {list.map((p) => (
            <li key={p.id}>
              <a className="fg-card" href={`/products/${encodeURIComponent(p.handle)}`}>
                {p.image ? <Image src={p.image.src} alt={p.image.alt} width={400} height={400} sizes="(min-width: 900px) 25vw, 50vw" /> : null}
                <span className="fg-name">{p.title}</span>
                <Money amount={p.price.amount} currency={p.price.currency} locale="en-IN" />
              </a>
            </li>
          ))}
        </ul>
        {pages > 1 ? (
          <nav className="fg-pages" aria-label="Pages">
            {page > 1 ? <a href={pageHref(page - 1)}>Previous</a> : null}
            <span>{`Page ${page} of ${pages}`}</span>
            {page < pages ? <a href={pageHref(page + 1)}>Next</a> : null}
          </nav>
        ) : null}
      </section>
    );
  },
});

Create blocks/filtered-grid/filtered-grid.css:

blocks/filtered-grid/filtered-grid.css
.fg { padding: 1rem; }
.fg-total { margin: 0 0 1rem; opacity: 0.7; }
.fg-grid { display: grid; gap: 1rem; grid-template-columns: repeat(2, 1fr); list-style: none; margin: 0; padding: 0; }
@media (min-width: 900px) { .fg-grid { grid-template-columns: repeat(4, 1fr); } }
.fg-card { display: grid; gap: 0.25rem; color: inherit; text-decoration: none; }
.fg-card img { width: 100%; height: auto; aspect-ratio: 1; object-fit: cover; border-radius: 0.5rem; }
.fg-name { font-weight: 500; }
.fg-pages { display: flex; gap: 1rem; justify-content: center; margin-top: 2rem; }
.fg-empty { padding: 3rem 1rem; text-align: center; }

Put both blocks on the collection and category pages (bunx bizzpocket add-to-layout collection-filters --page collection, then filtered-grid), and try /collections/puzzles?price_min=500&price_max=1000 in bunx bizzpocket dev --mock. The sample data's prices run from ₹499 to ₹2,149, so the bands are "Under ₹500" up to "₹2,000 and up". (The mock does not filter, so the grid shows every product there.)

How it works

  • The bands come from the catalogue. products({ collection: page.route.handle, first: 1 }) asks for a single product, because only priceRange ({ min, max } of the whole collection) is wanted. It has no filters, so the bands do not shrink as the shopper filters. priceBands() cuts the range at round edges (steps of 1, 2 or 5 times a power of ten). On /shop the handle is unset and the range is the whole store's. The need stays static: it only passes page.route.handle through.
  • Every filter is a link. filterHref() builds a query-only URL (?price_min=500&price_max=1000) from ctx.route: the shopper's other filters and the sort stay, the page number goes, and a chip that is on links to the URL without it. Query-only links stay on the site, work with JavaScript off, and can be shared and bookmarked. render reads the active state from ctx.route.filters, so the panel always matches the page the shopper sees.
  • route.filters is already cleaned. The host drops tracking and reserved parameters (utm_*, fbclid, q, page, sort...), keeps at most 16 keys and 200 characters a value, and on a category or collection page adds category from the path. That is why filterHref() leaves category out.
  • The phone sheet is a native popover. The "Filters (1)" button opens it with popoverTarget, and Esc or a tap outside closes it. At 900 px and wider, the CSS hides both buttons and shows the same panel in the page: author CSS overrides the browser's display: none for a closed popover. One panel, no duplicated markup.
  • The grid reads the same URL. gridFilters() turns price_min, price_max and stock=in into the typed input of productGridProducts ({ priceMin, priceMax, inStock }). The page links keep the filters.

Why the grid uses load()

products() takes filters as a typed ProductBrowseFilters object and hands it to the store unchanged. The store's filters input is typed (priceMin: Float, inStock: Boolean, attribute filters as [{ key, values }]), and the URL only has strings, so products({ filters: page.route.filters }) cannot filter by price. Converting needs code, which a static data() does not allow, so the grid is a load() block: always runtime, never cached, one extra round of fetches. The filters block itself stays static.

JS cost

block               server B  client gz  css gz  data
------------------  --------  ---------  ------  -------
collection-filters      5736          0     524  static
filtered-grid           2427          0     310  runtime

why runtime (see docs/theme-sdk/data.md, "Why is my block runtime?"):
  blocks/filtered-grid/filtered-grid.tsx:15  load() runs on every request (runtime by design) [load]

client gz is 0 for both. Filtering is a page load with a new URL, which the server renders.

Taking it further

  • Sort. Add links that set sort (newest, price-asc, price-desc) the same way. filterHref() already keeps it.
  • Seller filters. productGridProducts also returns facets ({ name, values: [{ label, value, count }] }) and accepts filters.attributes: [{ key, values }]. Render a facet's values as chips that write, for example, f_<key>=<value>, and add the matching attributes entry in gridFilters().