Skip to main content

max / makenotwork

964 B · 23 lines History Blame Raw
1 // Cart count badge in the site header. Lived inside `initTabs()` until the
2 // dashboard strips became described regions and `core/tabs.ts` went away; it
3 // was never tab behaviour, it just ran on every page from the one place that
4 // already did.
5
6 /** Fill the header cart link with its item count, and reveal it when non-zero.
7 * Inert on pages without `#nav-cart-link` (`partials/site_header.html`). */
8 export function initCartBadge(): void {
9 const cartLink = document.getElementById('nav-cart-link');
10 if (!cartLink) return;
11
12 fetch('/api/cart/count', { credentials: 'same-origin' })
13 .then((r) => (r.ok ? r.json() : null))
14 .then((data: { count?: number } | null) => {
15 if (data && typeof data.count === 'number' && data.count > 0) {
16 cartLink.classList.remove('hidden');
17 const badge = document.getElementById('cart-badge');
18 if (badge) badge.textContent = ' (' + data.count + ')';
19 }
20 })
21 .catch(() => {});
22 }
23