Header with a mega menu
A sticky store header with a mega menu, a phone drawer, a search box and a live cart count. One 725-byte island.
Goal: a sticky store header with a mega menu on desktop, a drawer on phones, a search box and a cart link whose count follows the shopper's cart. The cart count is the only JavaScript.
| Data | static: store() and menu() |
| JavaScript | one island, about 725 bytes gzip (the cart count) |
| Uses | useCart(), sir.search, sir.cartDrawer, menu(), store(), toSafeUrl(), the HTML popover attribute |
The block has three files.
The block
Create blocks/site-header/site-header.tsx:
import { block, f, Image, isSafeMediaUrl, menu, sir, store, toSafeUrl, type NavigationItem } from '@bizzpocket/theme';
import { CartCount } from './cart-count';
import './site-header.css';
/** A menu item with a safe link, or null. Menu links come from the store, so check them. */
function link(item: NavigationItem): { id: string; label: string; href: string } | null {
const href = toSafeUrl(item.href);
return href === null ? null : { id: item.id, label: item.label, href };
}
/** The desktop row: an item with children opens a mega panel of columns on hover or focus. */
function MegaItem({ item }: { item: NavigationItem }) {
const top = link(item);
if (top === null) return null;
const columns = item.children.map((c) => ({ head: link(c), links: c.children.map(link) }));
if (columns.length === 0) {
return (
<li className="sh-item">
<a className="sh-top" href={top.href}>{top.label}</a>
</li>
);
}
return (
<li className="sh-item sh-item--mega">
<a className="sh-top" href={top.href} aria-haspopup="true">{top.label}</a>
<div className="sh-mega">
{columns.map((col, i) =>
col.head === null ? null : (
<div key={col.head.id + i} className="sh-col">
<a className="sh-col-head" href={col.head.href}>{col.head.label}</a>
<ul className="sh-col-links">
{col.links.map((l) => (l === null ? null : <li key={l.id}><a href={l.href}>{l.label}</a></li>))}
</ul>
</div>
),
)}
</div>
</li>
);
}
/** The phone drawer: one disclosure per item that has children. */
function DrawerItem({ item }: { item: NavigationItem }) {
const top = link(item);
if (top === null) return null;
const children = item.children.map(link).filter((l) => l !== null);
if (children.length === 0) return <li><a className="sh-drawer-link" href={top.href}>{top.label}</a></li>;
return (
<li>
<details className="sh-drawer-group">
<summary className="sh-drawer-link">{top.label}</summary>
<ul>
<li><a href={top.href}>All {top.label}</a></li>
{children.map((c) => <li key={c.id}><a href={c.href}>{c.label}</a></li>)}
</ul>
</details>
</li>
);
}
export default block({
name: 'Site header',
category: 'header',
role: 'header',
aboveFold: true,
// The cart count must be right as soon as the page loads, not when it scrolls into view.
hydrate: 'load',
fields: {
menuHandle: f.menu({ default: 'main', label: 'Menu' }),
sticky: f.boolean({ default: true, label: 'Stay at the top when scrolling' }),
searchPlaceholder: f.text({ default: 'Search products' }),
cartLabel: f.text({ default: 'Cart' }),
},
data: ({ menuHandle }) => ({ shop: store(), nav: menu({ handle: menuHandle }) }),
render: ({ shop, nav, sticky, searchPlaceholder, cartLabel }, ctx) => {
const items = nav?.items ?? [];
const name = shop?.name ?? ctx.store.name;
const logo = shop?.logoUrl && isSafeMediaUrl(shop.logoUrl) ? shop.logoUrl : null;
const drawerId = `sh-drawer-${ctx.blockId}`;
return (
<header className={sticky ? 'sh sh--sticky' : 'sh'}>
<div className="sh-bar">
{items.length > 0 ? (
<button type="button" className="sh-burger" popoverTarget={drawerId} aria-label="Open menu">
☰
</button>
) : null}
<a className="sh-logo" href="/">
{logo ? <Image src={logo} alt={name} width={160} height={40} priority /> : name}
</a>
{items.length > 0 ? (
<nav className="sh-nav" aria-label="Main">
<ul className="sh-row">
{items.map((item) => <MegaItem key={item.id} item={item} />)}
</ul>
</nav>
) : null}
<form className="sh-search" action="/search" method="get" role="search" {...sir.search({ 'data-action': '/search' })}>
<input
type="search"
name="q"
placeholder={searchPlaceholder}
aria-label={searchPlaceholder}
autoComplete="off"
data-bp-search-input
/>
</form>
<a className="sh-cart" href="/cart" {...sir.cartDrawer()}>
{cartLabel}
<CartCount />
</a>
</div>
{items.length > 0 ? (
<div id={drawerId} className="sh-drawer" popover="auto">
<div className="sh-drawer-head">
<strong>{name}</strong>
<button type="button" className="sh-close" popoverTarget={drawerId} popoverTargetAction="hide" aria-label="Close menu">
✕
</button>
</div>
<nav aria-label="Main">
<ul className="sh-drawer-list">
{items.map((item) => <DrawerItem key={item.id} item={item} />)}
</ul>
</nav>
</div>
) : null}
</header>
);
},
});The cart count island
Create blocks/site-header/cart-count.tsx:
'use client';
import { useCart } from '@bizzpocket/theme/client';
/** The number on the cart link. Nothing until the storefront has answered, or while the cart is empty. */
export function CartCount() {
const { count, ready } = useCart();
if (!ready || count === 0) return null;
return (
<span className="sh-count">
{count}
<span className="sh-sr"> {count === 1 ? 'item' : 'items'}</span>
</span>
);
}The CSS
Create blocks/site-header/site-header.css:
/* The page wraps every block in its own element, so the sticky part is that wrapper. */
[data-block-id]:has(> .sh--sticky) { position: sticky; top: 0; z-index: 50; }
.sh { background: #fff; border-bottom: 1px solid #e5e5e5; }
.sh-bar { display: flex; align-items: center; gap: 1rem; max-width: 80rem; margin: 0 auto; padding: 0.75rem 1rem; }
.sh-logo { font-weight: 700; font-size: 1.25rem; text-decoration: none; color: inherit; white-space: nowrap; }
.sh-logo img { height: 2.5rem; width: auto; display: block; }
.sh-burger, .sh-close { border: 0; background: none; font-size: 1.5rem; line-height: 1; padding: 0.25rem; cursor: pointer; }
/* Desktop row and mega panels. */
.sh-nav { display: none; }
.sh-row { display: flex; gap: 1.5rem; list-style: none; margin: 0; padding: 0; }
.sh-top { display: block; padding: 0.5rem 0; color: inherit; text-decoration: none; font-weight: 500; }
.sh-mega {
display: none; position: absolute; left: 0; right: 0; top: 100%;
padding: 1.5rem 1rem;
background: #fff; border-bottom: 1px solid #e5e5e5; box-shadow: 0 12px 24px rgb(0 0 0 / 0.08);
grid-template-columns: repeat(auto-fill, minmax(12rem, 1fr)); gap: 1.5rem;
}
/* A strip above the panel, so the pointer can travel from the link to the panel without closing it. */
.sh-mega::before { content: ''; position: absolute; left: 0; right: 0; bottom: 100%; height: 1rem; }
/* Open on hover, and on keyboard focus anywhere inside the item. */
.sh-item--mega:hover > .sh-mega, .sh-item--mega:focus-within > .sh-mega { display: grid; }
.sh-col-head { font-weight: 600; color: inherit; text-decoration: none; }
.sh-col-links { list-style: none; margin: 0.5rem 0 0; padding: 0; display: grid; gap: 0.35rem; }
.sh-col-links a { color: #555; text-decoration: none; }
.sh-col-links a:hover, .sh-col-head:hover, .sh-top:hover { text-decoration: underline; }
.sh-search { flex: 1; min-width: 0; }
.sh-search input { width: 100%; max-width: 22rem; padding: 0.5rem 0.75rem; border: 1px solid #ccc; border-radius: 999px; }
.sh-cart { display: inline-flex; align-items: center; gap: 0.4rem; color: inherit; text-decoration: none; font-weight: 500; }
.sh-count { min-width: 1.4rem; padding: 0 0.35rem; border-radius: 999px; background: #111; color: #fff; font-size: 0.75rem; line-height: 1.4rem; text-align: center; }
.sh-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
/* Phone drawer: a native popover (top layer, Esc and outside click close it). */
.sh-drawer { margin: 0; inset: 0 auto 0 0; width: min(20rem, 85vw); height: 100%; max-height: none; padding: 1rem; border: 0; background: #fff; overflow-y: auto; }
.sh-drawer::backdrop { background: rgb(0 0 0 / 0.4); }
.sh-drawer-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem; }
.sh-drawer-list, .sh-drawer-list ul { list-style: none; margin: 0; padding: 0; }
.sh-drawer-list ul { padding: 0 0 0.5rem 1rem; }
.sh-drawer-list a, .sh-drawer-link { display: block; padding: 0.6rem 0; color: inherit; text-decoration: none; cursor: pointer; }
@media (min-width: 960px) {
.sh-bar { position: relative; }
.sh-burger { display: none; }
.sh-nav { display: block; }
.sh-item { position: static; }
.sh-search { flex: 0 1 18rem; margin-left: auto; }
}Put it in the header region of layouts/global.json ("type": "site-header"). The sample menu in
bizzpocket dev --mock is flat, so you see the row of links there. A store menu with nested items shows
the mega panels.
How it works
- The data is static.
store()gives the name and logo,menu({ handle: menuHandle })gives the seller's menu. Both come with the page's one data call. Unset, the menu need is skipped and the header shows only the name, search and cart. - The mega menu is CSS. A top item with children gets a panel with one column per child (its link as
the column heading, its own children below).
:hoverand:focus-withinshow it, so a keyboard shopper opens it by tabbing onto the top link and then tabs into the panel. The top link still goes to its page on click. - The phone drawer is a native popover.
popoverTargeton the burger button andpopover="auto"on the drawer: the browser opens it in the top layer, and closes it with Esc, an outside tap or the close button (popoverTargetAction="hide"). No script. Items with children become<details>disclosures. The id usesctx.blockId, so two headers on one page do not clash. - Search is
sir.search. The form also hasaction="/search"andmethod="get", so it works before the runtime has loaded. The runtime ignores an empty query and only follows a same-sitedata-action. For suggestions while typing, see Search suggestions. - The cart count is the only island.
useCart()asks the storefront for the cart when the island wakes and follows every change. It renders nothing untilready, so the server HTML and the first browser render match.hydrate: 'load'wakes it with the page instead of when it is near the screen. - Sticky. The page puts every block inside its own wrapper element (
data-block-id), and a sticky element only sticks inside its parent. So the CSS makes the wrapper sticky, with[data-block-id]:has(> .sh--sticky). Thestickyfield turns it off. - Store links are checked. Menu
hrefs come from the store, sotoSafeUrl()drops anything that is not a site path,#anchor,https:,mailto:ortel:(URL helpers).
JS cost
block server B client gz css gz data
----------- -------- --------- ------ ------
site-header 5615 725 935 staticThe island is 725 bytes gzip. The mega menu, the drawer and the search box cost nothing. On the Bun host, the first island on a page also loads the shared React runtime, once for every island on the page; the size table counts only your own code.
The cart link carries {...sir.cartDrawer()}: when the store's cart drawer opens, the link stays on the
page; with no drawer, or before JavaScript runs, it goes to /cart. A ctrl/cmd-click still opens /cart
in a new tab.