Skip to main content

max / makenotwork

1.6 KB · 35 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 place with its item count, and reveal it when non-zero.
7 * Inert on pages whose header offers no cart place.
8 *
9 * Found by `data-place`, which is `quasi_router::Place::key` as
10 * `quasi-webview` emits it. The header is a described `Chrome::band` since
11 * `c7b0d3c1`, so there is no hand-written `id="nav-cart-link"` to look for;
12 * the key is the app's own identifier and is what a script should be keying
13 * off anyway. The badge is appended here rather than described, because a
14 * count nothing on the server knows at render time is not a fact a
15 * description can carry. */
16 export function initCartBadge(): void {
17 const cartLink = document.querySelector<HTMLElement>('[data-place="cart"]');
18 if (!cartLink) return;
19
20 fetch('/api/cart/count', { credentials: 'same-origin' })
21 .then((r) => (r.ok ? r.json() : null))
22 .then((data: { count?: number } | null) => {
23 if (data && typeof data.count === 'number' && data.count > 0) {
24 // The place is hidden until this attribute is on it; `style.css` says
25 // so, keyed off `data-place="cart"`.
26 cartLink.dataset.count = String(data.count);
27 const badge = document.createElement('span');
28 badge.className = 'cart-badge-count';
29 badge.textContent = ' (' + data.count + ')';
30 cartLink.appendChild(badge);
31 }
32 })
33 .catch(() => {});
34 }
35