@thorprovider/storefront 0.15.1 → 0.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +1 -1
  2. package/assets/templates/app/app/[[...slug]]/page.tsx +16 -4
  3. package/assets/templates/app/lib/__STOREFRONT__/header-universal.ts +373 -0
  4. package/assets/templates/app/lib/__STOREFRONT__/registry.tsx +143 -11
  5. package/assets/templates/app/lib/__STOREFRONT__/schema.ts +52 -0
  6. package/assets/templates/app/lib/__STOREFRONT__/shell/content.ts +43 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/shell/props.ts +4 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/spec/index.ts +22 -40
  9. package/assets/templates/app/lib/__STOREFRONT__/views/sections/header-universal.client.tsx +33 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/views/sections/header-universal.tsx +16 -0
  11. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +2 -1
  12. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.header-universal.ts +360 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +1 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +4 -1
  15. package/assets/templates/app/public/demo/accessories.svg +7 -0
  16. package/assets/templates/app/public/demo/dresses.svg +6 -0
  17. package/assets/templates/app/public/demo/furniture.svg +9 -0
  18. package/assets/templates/app/public/demo/home.svg +8 -0
  19. package/assets/templates/app/public/demo/jackets.svg +11 -0
  20. package/assets/templates/app/public/demo/promo-invierno.svg +8 -0
  21. package/assets/templates/features/checkout/state.ts +2 -0
  22. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  23. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/registry.part +2 -0
  24. package/assets/templates/views/category/content.ts +1 -0
  25. package/assets/templates/views/category/index.tsx +1 -0
  26. package/assets/templates/views/category/registry.tsx +2 -0
  27. package/assets/templates/views/category/schema.ts +2 -0
  28. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +19 -0
  29. package/assets/templates/views/checkout/registry.tsx +22 -5
  30. package/assets/templates/views/home/assembly/slots/hero/UniversalBanner/registry.part +6 -1
  31. package/assets/templates/views/home/content.ts +2 -0
  32. package/assets/templates/views/home/props.ts +8 -1
  33. package/assets/templates/views/home/registry.tsx +6 -1
  34. package/assets/templates/views/home/schema.ts +1 -0
  35. package/package.json +1 -1
  36. package/recipes/sections.json +18 -0
  37. package/scripts/candidate.mjs +2 -2
  38. package/scripts/env-file.mjs +5 -0
  39. package/scripts/file-classes.mjs +7 -2
  40. package/scripts/reconcile.mjs +4 -1
  41. package/scripts/render-templates.mjs +106 -1
  42. package/skills/sf-view-gen/assets/recipes/sections.json +18 -0
  43. package/skills/sf-view-gen/assets/templates/views/sections/header-universal.client.tsx +33 -0
  44. package/skills/sf-view-gen/assets/templates/views/sections/header-universal.tsx +16 -0
  45. package/skills/sf-view-gen/assets/templates/views/sections/schema.header-universal.ts +360 -0
package/README.md CHANGED
@@ -144,7 +144,7 @@ yarn dev
144
144
  ```
145
145
 
146
146
  A fresh `create` seeds `home` + `cart` (home hero/benefits/category sections, a
147
- navbar-owned cart sheet, a standalone `/cart` review route). Pass `--starter` to
147
+ header-owned cart sheet, a standalone `/cart` review route). Pass `--starter` to
148
148
  seed the full curated composition instead — every curated view and feature, read
149
149
  from the registry, held units excluded. Everything renders with only
150
150
  `@thorprovider/blocks` (UI) and `@thorprovider/adapters` (data). Then grow it by asking
@@ -3,7 +3,9 @@
3
3
  import { notFound } from 'next/navigation'
4
4
  import { buildBreadcrumbListJsonLd, serializeJsonLd } from '@thorprovider/runtime/contracts'
5
5
  import { getCatalog } from '@thorprovider/runtime/commerce'
6
+ import type { UniversalMainMenuData } from '@thorprovider/blocks'
6
7
  import { __STOREFRONT_CAMEL__App } from '@/lib/__STOREFRONT__/runtime'
8
+ import { buildDemoHeaderMenu, buildHeaderMenu } from '@/lib/__STOREFRONT__/header-universal'
7
9
  import { readCartStateForRender } from '@/lib/__STOREFRONT__/cart-state'
8
10
  import { readAccountSession } from '@/lib/__STOREFRONT__/account-session'
9
11
  import { toAccountInitialState } from '@/lib/__STOREFRONT__/account-session.core'
@@ -25,15 +27,25 @@ export default async function Page({
25
27
  const data = await __STOREFRONT_CAMEL__App.getPageData({ params, searchParams })
26
28
  if (!data) return notFound()
27
29
 
28
- // The shared shell is rendered for every route, so resolve its category links
29
- // here rather than relying on a particular view loader. `getCatalog()` is
30
+ // The shared shell is rendered for every route, so resolve its navigation here
31
+ // rather than relying on a particular view loader. `getCatalog()` is
30
32
  // request-cached by the commerce bridge and is shared with the view loader.
33
+ // The header's menu is the storefront's real catalog taxonomy for a LIVE
34
+ // catalog; without one (mock or no backend) it is the design-B demo taxonomy.
35
+ // The legacy `navCategories` flat list is kept for consumers that still read
36
+ // it.
31
37
  let navCategories: { label: string; href: string }[] = []
38
+ let headerMenu: UniversalMainMenuData = buildDemoHeaderMenu()
32
39
  try {
33
- navCategories = (await getCatalog()).categories.map(({ label, href }) => ({ label, href }))
40
+ const catalog = await getCatalog()
41
+ navCategories = catalog.categories.map(({ label, href }) => ({ label, href }))
42
+ headerMenu =
43
+ catalog.source === 'medusa'
44
+ ? buildHeaderMenu(catalog.categoriesRaw ?? [])
45
+ : buildDemoHeaderMenu()
34
46
  } catch (error) {
35
47
  // A failed catalog read must not invent links or take down otherwise usable
36
- // page content; keep the shell empty and leave a diagnostic for operators.
48
+ // page content; keep the demo taxonomy and leave a diagnostic for operators.
37
49
  console.error('[storefront] Failed to resolve shared navigation categories', error)
38
50
  }
39
51
 
@@ -0,0 +1,373 @@
1
+ // Thor Commerce shell data: the universal header's authored config and the
2
+ // menu builder that turns the storefront's own catalog taxonomy into the
3
+ // header's navigation.
4
+ //
5
+ // Derived (package-owned): regenerate on `storefront sync`. The header's menu
6
+ // IS the universal main menu — there is no horizontal category strip and no
7
+ // separate mega menu.
8
+ //
9
+ // Two navigation sources, one seam:
10
+ // - `buildHeaderMenu` maps the provider's real `ProductCategory[]` taxonomy
11
+ // (id/name/handle/description/productCount/image + parentCategoryId) to a
12
+ // `UniversalMainMenuData`, so hrefs are the storefront's real
13
+ // `/categories/<handle>` routes and images/counts are whatever the backend
14
+ // supplies. This is the live-catalog path and is preferred when a live
15
+ // (Medusa) catalog is present.
16
+ // - `buildDemoHeaderMenu` is a clearly-labelled DEMO taxonomy — the design-B
17
+ // delivery demo — used when no live catalog is present. Its categories reuse
18
+ // the starter's real catalog handles as hrefs (never `#`) and are enriched to
19
+ // the full menu shape (children, badges, counts, descriptions, the season
20
+ // promotion card and the demo labels).
21
+
22
+ import { createDefaultConfig } from '@thorprovider/blocks/blocks/designs/header-universal/contracts'
23
+ import type {
24
+ HeaderConfig,
25
+ HeaderContext,
26
+ HeaderModule,
27
+ } from '@thorprovider/blocks/blocks/designs/header-universal/contracts'
28
+ import type { UniversalMainMenuData, UniversalMainMenuItem } from '@thorprovider/blocks'
29
+ import type { ProductCategory } from '@thorprovider/types'
30
+
31
+ /**
32
+ * The starter header. The storefront feeds the commerce surface it can
33
+ * honestly render: the announcement, search field, account/wishlist/cart
34
+ * accesses and main menu. The cart count and action bind to the live cart in
35
+ * the shell registry. The horizontal category strip (`navigation`) and the
36
+ * region/language/support accesses stay off because the starter feeds no data
37
+ * for them and `/help` is not a served route.
38
+ */
39
+ export function createStorefrontHeaderConfig(): HeaderConfig {
40
+ const base = createDefaultConfig()
41
+
42
+ // Keep the demo surface and drop the host-optional modules the starter does
43
+ // not use (the `navigation` strip, region/language/support, and every other
44
+ // preset module).
45
+ const kept = new Set([
46
+ 'announcement',
47
+ 'logo',
48
+ 'main-menu',
49
+ 'search',
50
+ 'account',
51
+ 'cart',
52
+ ])
53
+ const wishlistModule: HeaderModule = {
54
+ id: 'wishlist',
55
+ type: 'wishlist',
56
+ enabled: true,
57
+ requires: 'saved-items',
58
+ props: { showCount: true },
59
+ // The starter has no dedicated wishlist route; the icon navigates to the
60
+ // account surface where saved items live.
61
+ actions: { click: { name: 'navigate', payload: { href: '/account' } } },
62
+ }
63
+ const modules = [
64
+ ...base.modules
65
+ .filter((module) => kept.has(module.id))
66
+ .map((module) => {
67
+ if (module.id === 'cart') {
68
+ return {
69
+ ...module,
70
+ actions: { ...module.actions, click: { name: 'openCart' } },
71
+ }
72
+ }
73
+ if (module.id !== 'search') return module
74
+ // The demo search is always a bar (never the icon fallback): the block
75
+ // measures its container client-side, so the server render would
76
+ // otherwise fall back to the base-breakpoint icon and the search field
77
+ // copy would never appear in the SSR HTML.
78
+ return { ...module, responsive: undefined }
79
+ }),
80
+ wishlistModule,
81
+ ]
82
+
83
+ const layout = base.layout.map((row) => {
84
+ if (row.id === 'main') {
85
+ return {
86
+ ...row,
87
+ zones: {
88
+ start: ['logo', 'main-menu'],
89
+ center: ['search'],
90
+ end: ['account', 'wishlist', 'cart'],
91
+ },
92
+ }
93
+ }
94
+ if (row.id === 'utility') {
95
+ // Only the announcement; region/language/support are removed above.
96
+ return { ...row, zones: { start: ['announcement'], center: [], end: [] } }
97
+ }
98
+ return row
99
+ })
100
+
101
+ return {
102
+ ...base,
103
+ // The shell `Layout` already wraps the header slot in a sticky `<header>`,
104
+ // so the block itself stays static rather than stacking another sticky.
105
+ behavior: { ...base.behavior, position: 'static' },
106
+ layout,
107
+ modules,
108
+ // The demo feeds every capability the enriched modules require.
109
+ capabilities: {
110
+ catalog: true,
111
+ 'catalog-search': true,
112
+ checkout: true,
113
+ 'customer-account': true,
114
+ 'saved-items': true,
115
+ },
116
+ visibilityRules: [],
117
+ }
118
+ }
119
+
120
+ /** Per-module copy the header block reads through `labels[module.type]`. */
121
+ export const storefrontHeaderLabels: Record<string, Record<string, string>> = {
122
+ logo: { home: 'Inicio' },
123
+ 'main-menu': { triggerLabel: 'Menú' },
124
+ search: {
125
+ label: 'Buscar',
126
+ placeholder: 'Buscar productos, marcas o SKU',
127
+ submit: 'Buscar',
128
+ },
129
+ cart: { label: 'Carrito' },
130
+ account: { account: 'Cuenta' },
131
+ wishlist: { label: 'Favoritos' },
132
+ announcement: { link: 'Ver más' },
133
+ }
134
+
135
+ /** The live-catalog menu labels: the trigger is `Menú`, the rest are required. */
136
+ const HEADER_MENU_LABELS: UniversalMainMenuData['labels'] = {
137
+ menuTrigger: 'Menú',
138
+ menuTitle: 'Categorías',
139
+ close: 'Cerrar menú',
140
+ back: 'Volver',
141
+ openSubmenu: 'Abrir {name}',
142
+ viewAll: 'Ver todo {name}',
143
+ productCount: '{count} productos',
144
+ productCountOne: '1 producto',
145
+ featured: 'Destacado',
146
+ empty: 'No hay categorías disponibles',
147
+ emptyHint: 'El catálogo se está actualizando.',
148
+ panelLabel: 'Menú de {name}',
149
+ railLabel: 'Categorías',
150
+ levelLabel: 'Nivel {level}',
151
+ noImage: 'Sin imagen',
152
+ }
153
+
154
+ /** The demo labels: identical to the live set except the design-B menu title. */
155
+ const DEMO_MENU_LABELS: UniversalMainMenuData['labels'] = {
156
+ ...HEADER_MENU_LABELS,
157
+ menuTitle: 'Todo empieza aquí',
158
+ }
159
+
160
+ /**
161
+ * The shared menu config: hybrid layout, container-anchored panel, light ghost
162
+ * trigger. Both the live taxonomy and the demo taxonomy render identically.
163
+ */
164
+ function buildMenuConfig(): UniversalMainMenuData['config'] {
165
+ return {
166
+ layouts: {
167
+ default: 'hybrid',
168
+ desktop: 'hybrid',
169
+ mobile: 'hybrid',
170
+ bindings: {},
171
+ options: {},
172
+ },
173
+ behavior: {
174
+ platform: 'auto',
175
+ anchor: 'container',
176
+ trigger: 'ghost',
177
+ mobilePattern: 'drill-down',
178
+ openOnHover: true,
179
+ openDelayMs: 200,
180
+ closeDelayMs: 160,
181
+ direction: 'auto',
182
+ },
183
+ transition: {
184
+ panel: 'slide',
185
+ level: 'fade',
186
+ duration: 'base',
187
+ respectReducedMotion: true,
188
+ },
189
+ }
190
+ }
191
+
192
+ function toMenuItem(category: ProductCategory): UniversalMainMenuItem {
193
+ return {
194
+ id: category.id,
195
+ label: category.name,
196
+ href: `/categories/${category.handle}`,
197
+ ...(category.description ? { description: category.description } : {}),
198
+ ...(category.image ? { image: { src: category.image, alt: category.name } } : {}),
199
+ ...(category.productCount !== undefined ? { count: category.productCount } : {}),
200
+ }
201
+ }
202
+
203
+ /** Build the recursive menu tree from the provider's flat taxonomy. */
204
+ function buildTree(categories: ProductCategory[]): UniversalMainMenuItem[] {
205
+ const byParent = new Map<string | undefined, ProductCategory[]>()
206
+ for (const category of categories) {
207
+ const list = byParent.get(category.parentCategoryId)
208
+ if (list) list.push(category)
209
+ else byParent.set(category.parentCategoryId, [category])
210
+ }
211
+ const build = (parentId: string | undefined): UniversalMainMenuItem[] =>
212
+ (byParent.get(parentId) ?? []).map((category) => {
213
+ const children = build(category.id)
214
+ return {
215
+ ...toMenuItem(category),
216
+ ...(children.length > 0 ? { children } : {}),
217
+ }
218
+ })
219
+ return build(undefined)
220
+ }
221
+
222
+ /**
223
+ * The header's LIVE navigation source: a `UniversalMainMenuData` whose
224
+ * categories are the storefront's real catalog taxonomy. The panel is
225
+ * container-anchored and the trigger is the light ghost control.
226
+ */
227
+ export function buildHeaderMenu(categories: ProductCategory[]): UniversalMainMenuData {
228
+ return {
229
+ categories: buildTree(categories),
230
+ config: buildMenuConfig(),
231
+ labels: HEADER_MENU_LABELS,
232
+ }
233
+ }
234
+
235
+ /**
236
+ * The design-B delivery demo taxonomy. Demo-only: the starter's real catalog
237
+ * handles are reused as hrefs so every link resolves to a real route (never
238
+ * `#`), while the menu is enriched to the full shape the designer delivered —
239
+ * children (a featured grid), badges (`Nuevo`, `-30%`), counts, descriptions,
240
+ * the season promotion card and the demo labels. Fed only when no live catalog
241
+ * is present.
242
+ */
243
+ const DEMO_MENU_CATEGORIES: UniversalMainMenuItem[] = [
244
+ {
245
+ id: 'demo-jackets',
246
+ label: 'Jackets',
247
+ href: '/categories/jackets',
248
+ description: 'Outerwear and layering pieces.',
249
+ count: 12,
250
+ image: { src: '/demo/jackets.svg', alt: 'Jackets' },
251
+ badge: { label: 'Nuevo', tone: 'accent' },
252
+ children: [
253
+ { id: 'demo-jackets-quilted', label: 'Quilted', href: '/categories/jackets', count: 6, image: { src: '/demo/jackets.svg', alt: 'Quilted' } },
254
+ { id: 'demo-jackets-coats', label: 'Coats', href: '/categories/dresses', count: 4, image: { src: '/demo/jackets.svg', alt: 'Coats' } },
255
+ { id: 'demo-jackets-layers', label: 'Light layers', href: '/categories/accessories', count: 2, image: { src: '/demo/jackets.svg', alt: 'Light layers' } },
256
+ ],
257
+ },
258
+ {
259
+ id: 'demo-dresses',
260
+ label: 'Dresses',
261
+ href: '/categories/dresses',
262
+ description: 'Editorial silhouettes for seasonal collections.',
263
+ count: 9,
264
+ image: { src: '/demo/dresses.svg', alt: 'Dresses' },
265
+ },
266
+ {
267
+ id: 'demo-home',
268
+ label: 'Home',
269
+ href: '/categories/home',
270
+ description: 'Decor and living objects for lifestyle layouts.',
271
+ count: 14,
272
+ image: { src: '/demo/home.svg', alt: 'Home' },
273
+ },
274
+ {
275
+ id: 'demo-accessories',
276
+ label: 'Accessories',
277
+ href: '/categories/accessories',
278
+ description: 'Complementary products for cart and bundle flows.',
279
+ count: 7,
280
+ image: { src: '/demo/accessories.svg', alt: 'Accessories' },
281
+ },
282
+ {
283
+ id: 'demo-furniture',
284
+ label: 'Furniture',
285
+ href: '/categories/furniture',
286
+ description: 'Statement pieces for the home, including oversized and fragile deliveries.',
287
+ count: 5,
288
+ image: { src: '/demo/furniture.svg', alt: 'Furniture' },
289
+ badge: { label: '-30%', tone: 'promo' },
290
+ },
291
+ ]
292
+
293
+ /** The design-B season promotion card (demo copy). */
294
+ const DEMO_PROMOTION: UniversalMainMenuData['promotion'] = {
295
+ id: 'demo-promo-invierno',
296
+ eyebrow: 'COLECCIÓN DE INVIERNO',
297
+ title: 'Textiles que abrigan la casa',
298
+ description: 'Lana virgen y lino lavado, tejidos en talleres locales.',
299
+ href: '/categories/home',
300
+ ctaLabel: 'Ver la colección',
301
+ image: { src: '/demo/promo-invierno.svg', alt: 'Textiles que abrigan la casa' },
302
+ }
303
+
304
+ /**
305
+ * The header's DEMO navigation source: the full design-B taxonomy. The panel is
306
+ * open in the first paint so the designer sees the rail, the featured grid and
307
+ * the promotion card without a click.
308
+ */
309
+ export function buildDemoHeaderMenu(): UniversalMainMenuData {
310
+ return {
311
+ categories: DEMO_MENU_CATEGORIES,
312
+ config: buildMenuConfig(),
313
+ labels: DEMO_MENU_LABELS,
314
+ promotion: DEMO_PROMOTION,
315
+ preview: { defaultOpen: true },
316
+ }
317
+ }
318
+
319
+ /**
320
+ * Runtime context the shell feeds the header. The cart quantity comes from the
321
+ * live storefront state; announcement and wishlist remain clearly-labelled
322
+ * demonstration content. Region/language stay empty (their modules are removed
323
+ * from the config, so nothing reads them). The live catalog/menu seam is the
324
+ * `menu` argument (built from the real taxonomy or the demo taxonomy above).
325
+ */
326
+ export function buildHeaderContext(
327
+ siteName: string,
328
+ menu?: UniversalMainMenuData,
329
+ accent?: string,
330
+ cartQuantity = 0,
331
+ ): HeaderContext {
332
+ return {
333
+ brand: { name: siteName, href: '/', ...(accent ? { accent } : {}) },
334
+ menu,
335
+ cart: {
336
+ state: 'ready',
337
+ lines: [],
338
+ quantity: cartQuantity,
339
+ lineCount: 0,
340
+ currency: 'EUR',
341
+ shippingGroups: 0,
342
+ subtotalUnavailableLabel: 'Envío calculado al finalizar la compra',
343
+ promotions: [],
344
+ },
345
+ account: { state: 'guest', menu: [] },
346
+ wishlist: { count: 4, lists: 1 },
347
+ regions: { activeId: '', options: [] },
348
+ languages: { activeCode: '', options: [] },
349
+ locations: { enabled: false, options: [] },
350
+ announcements: [
351
+ {
352
+ id: 'demo-free-shipping',
353
+ message: 'Envío gratis desde 250 EUR',
354
+ href: '/categories',
355
+ linkLabel: 'Ver más',
356
+ tone: 'accent',
357
+ dismissible: false,
358
+ },
359
+ ],
360
+ notifications: { available: false, unread: 0, items: [] },
361
+ openComponents: [],
362
+ now: new Date().toISOString(),
363
+ capabilities: {
364
+ catalog: true,
365
+ 'catalog-search': true,
366
+ checkout: true,
367
+ 'customer-account': true,
368
+ 'saved-items': true,
369
+ },
370
+ context: 'guest',
371
+ page: 'home',
372
+ }
373
+ }
@@ -3,21 +3,23 @@
3
3
  // Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/registry.tsx)
4
4
  // Base registry for the app shell plus every registered view's registry fragment.
5
5
  //
6
- // The shell renders the live backend cart: the StorefrontNavbar mini-cart and the cart
7
- // drawer read the authoritative cart state and dispatch cart mutations to the
8
- // Server Actions. A listing card's add-to-cart adds the product's first
9
- // purchasable variant (the card shortcut); opening a product from a listing
10
- // navigates to the detail, where a variant is chosen explicitly.
6
+ // The universal header's cart access and its adjacent sheet share the live cart
7
+ // state and dispatch mutations to the Server Actions. A listing card's
8
+ // add-to-cart adds the product's first purchasable variant (the card shortcut);
9
+ // opening a product from a listing navigates to the detail for explicit choice.
11
10
 
12
11
  import { defineRegistry, useStateStore } from '@json-render/react'
12
+ import { useNextApp } from '@json-render/next'
13
13
  import { useEffect } from 'react'
14
14
  import { usePathname } from 'next/navigation'
15
15
  import { BackToTop as BackToTopBlock } from '@thorprovider/blocks/blocks/e-commerce/navigation/back-to-top'
16
16
  import { MobileBottomNav as MobileBottomNavBlock } from '@thorprovider/blocks/blocks/e-commerce/navigation/mobile-bottom-nav'
17
17
  import { SkipToContent as SkipToContentBlock } from '@thorprovider/blocks/blocks/e-commerce/navigation/skip-to-content'
18
+ import { StorefrontNavbarCartSheet } from '@thorprovider/blocks/blocks/e-commerce/navigation/storefront-navbar-cart-sheet'
18
19
  import Banner1 from '@thorprovider/blocks/blocks/marketing/banners/banner-1'
19
- import { Navbar, StorefrontNavbar, UniversalFooter } from '@thorprovider/blocks'
20
+ import { HeaderUniversal, Navbar, StorefrontNavbar, UniversalFooter } from '@thorprovider/blocks'
20
21
  import { ProductGrid as ProductGridBlock } from '@thorprovider/blocks/blocks/e-commerce/product-list/product-grid'
22
+ import { Sheet, SheetContent, SheetHeader, SheetTitle } from '@thorprovider/blocks/ui/sheet'
21
23
  import type { BackToTopProps } from '@thorprovider/blocks/blocks/e-commerce/navigation/back-to-top'
22
24
  import type { MobileBottomNavProps } from '@thorprovider/blocks/blocks/e-commerce/navigation/mobile-bottom-nav'
23
25
  import type { SkipToContentProps } from '@thorprovider/blocks/blocks/e-commerce/navigation/skip-to-content'
@@ -30,6 +32,8 @@ import { useStorefrontHandlers } from './handlers'
30
32
  import { cartViewAvailable, checkoutAvailable, mountedFeatureNames } from './composition'
31
33
  import { accountStoreUser } from './account-user.core'
32
34
  import { toUniversalFooterProps } from './footer-content'
35
+ import { buildHeaderContext, createStorefrontHeaderConfig, storefrontHeaderLabels } from './header-universal'
36
+ import { navbarLabels } from './shell/content'
33
37
  import type { AccountIdentity, AccountResolution } from './account-session.core'
34
38
  import {
35
39
  bannerPropsSchema,
@@ -37,11 +41,12 @@ import {
37
41
  navbarPropsSchema,
38
42
  productGridPropsSchema,
39
43
  storefrontNavbarPropsSchema,
44
+ universalHeaderShellPropsSchema,
40
45
  } from './schema'
41
46
  import { viewRegistries } from './views/registry'
42
47
 
43
- // StorefrontNavbar accepts its own mini-cart line shape (`qty`), distinct from the block
44
- // `CartItem` contract (`quantity`). Types are local so the asymmetry is explicit.
48
+ // The cart sheet accepts `qty`, distinct from the backend line shape's
49
+ // `quantity`. Types are local so the mapping stays explicit.
45
50
  interface NavCartItem {
46
51
  id: string
47
52
  name: string
@@ -52,7 +57,7 @@ interface NavCartItem {
52
57
  lineTotal?: Money
53
58
  }
54
59
 
55
- /** CartLineState -> StorefrontNavbar cart line. `price` is legacy; the authoritative
60
+ /** CartLineState -> cart-sheet line. `price` is legacy; the authoritative
56
61
  * subtotal and per-line total are passed separately, so neither is computed
57
62
  * from the line. */
58
63
  function toNavCartItems(cart: CartLineState[]): NavCartItem[] {
@@ -67,6 +72,81 @@ function toNavCartItems(cart: CartLineState[]): NavCartItem[] {
67
72
  }))
68
73
  }
69
74
 
75
+ function StorefrontCartSheet({ emit }: { emit: (event: string) => void }) {
76
+ const { state, set } = useStateStore()
77
+ const cart = (state.cart ?? []) as CartLineState[]
78
+ const totals = state.cartTotals as CartTotalsState | null
79
+ const cartQuantity = cart.reduce((quantity, line) => quantity + line.quantity, 0)
80
+ const storeLocale =
81
+ typeof state.storeLocale === 'string' && state.storeLocale.trim() !== ''
82
+ ? state.storeLocale
83
+ : DEFAULT_STORE_LOCALE
84
+ const formatMoney = createStoreMoneyFormatter(storeLocale)
85
+ const cartError = typeof state.cartError === 'string' ? state.cartError : undefined
86
+ const readError = typeof state.cartReadError === 'string' ? state.cartReadError : undefined
87
+ const errorLabel = cartError ?? readError
88
+ const cartState = state.cartPending ? 'pending' : errorLabel ? 'error' : 'idle'
89
+ const amountsValid =
90
+ cart.every((line) => isAvailableMoney(line.lineTotal)) &&
91
+ totals !== null &&
92
+ isAvailableMoney(totals.subtotal) &&
93
+ isAvailableMoney(totals.total)
94
+
95
+ return (
96
+ <Sheet
97
+ open={state.cartOpen === true}
98
+ onOpenChange={(open) => set('/cartOpen', open)}
99
+ >
100
+ <SheetContent
101
+ side='right'
102
+ className='flex w-full max-w-sm flex-col gap-0 p-0'
103
+ closeLabel={navbarLabels.cartClose}
104
+ >
105
+ <SheetHeader className='border-border border-b'>
106
+ <SheetTitle className='text-left text-base'>
107
+ {cartQuantity > 0
108
+ ? `${navbarLabels.cartTitle} (${cartQuantity})`
109
+ : navbarLabels.cartTitle}
110
+ </SheetTitle>
111
+ </SheetHeader>
112
+ <StorefrontNavbarCartSheet
113
+ items={toNavCartItems(cart)}
114
+ onQtyChange={(id, delta) => {
115
+ set('/qtyDelta', { id, delta })
116
+ emit('applyQuantityDelta')
117
+ }}
118
+ onRemove={(id) => {
119
+ set('/lastRemoved', id)
120
+ emit('removeFromCart')
121
+ }}
122
+ subtotal={totals?.subtotal}
123
+ formatMoney={formatMoney}
124
+ onCheckout={() => emit('goToCheckout')}
125
+ onViewCart={() => emit('goToCart')}
126
+ canonical
127
+ state={cartState}
128
+ errorLabel={errorLabel}
129
+ onRetry={() => emit('refreshCart')}
130
+ checkoutUnavailable={!checkoutAvailable}
131
+ checkoutDisabled={cartState !== 'idle' || cart.length === 0 || !amountsValid}
132
+ viewCartUnavailable={!cartViewAvailable}
133
+ decreaseLabel={navbarLabels.decreaseQuantity}
134
+ increaseLabel={navbarLabels.increaseQuantity}
135
+ removeLabel={navbarLabels.remove}
136
+ removeItemLabel={navbarLabels.removeItem}
137
+ emptyTitleLabel={navbarLabels.emptyTitle}
138
+ emptyDescriptionLabel={navbarLabels.emptyDescription}
139
+ continueShoppingLabel={navbarLabels.continueShopping}
140
+ subtotalLabel={navbarLabels.subtotal}
141
+ shippingTaxesLabel={navbarLabels.shippingTaxes}
142
+ checkoutLabel={navbarLabels.checkout}
143
+ viewCartLabel={navbarLabels.viewCart}
144
+ />
145
+ </SheetContent>
146
+ </Sheet>
147
+ )
148
+ }
149
+
70
150
  const baseComponents = {
71
151
  Layout: ({ children, slots }: { children?: React.ReactNode; slots?: Record<string, React.ReactNode> }) => {
72
152
  useStorefrontHandlers()
@@ -195,6 +275,9 @@ const baseComponents = {
195
275
  logoHref={parsed.logoHref}
196
276
  logoAccent={parsed.logoAccent}
197
277
  className={parsed.className}
278
+ // Chrome copy in the store language, authored in the user-owned shell
279
+ // (`shell/content.ts`); omitted fields keep the block's English default.
280
+ labels={parsed.labels}
198
281
  accountHref={parsed.accountHref}
199
282
  // Signed-in identity + account feedback, only while customer-auth is
200
283
  // mounted. `user` is mapped from the shared allowlisted identity; the
@@ -251,6 +334,54 @@ const baseComponents = {
251
334
  />
252
335
  )
253
336
  },
337
+ HeaderUniversal: ({
338
+ props,
339
+ emit,
340
+ }: {
341
+ props: Record<string, unknown>
342
+ emit: (event: string) => void
343
+ }) => {
344
+ const parsed = universalHeaderShellPropsSchema.parse(props)
345
+ const { navigate } = useNextApp()
346
+ const { state } = useStateStore()
347
+ const cart = (state.cart ?? []) as CartLineState[]
348
+ const cartQuantity = cart.reduce((quantity, line) => quantity + line.quantity, 0)
349
+ const config = createStorefrontHeaderConfig()
350
+ const context = buildHeaderContext(
351
+ parsed.siteName,
352
+ parsed.menu,
353
+ parsed.logoAccent?.text.trim() || undefined,
354
+ cartQuantity,
355
+ )
356
+ const cartLabel = (
357
+ cartQuantity === 1 ? navbarLabels.cartCountOne : navbarLabels.cartCount
358
+ ).replace('{count}', String(cartQuantity))
359
+ const labels = { ...storefrontHeaderLabels, cart: { label: cartLabel } }
360
+ // Header navigation stays client-side. The commerce action opens the shared
361
+ // cart state, which is rendered by the sheet mounted beside this header.
362
+ const handleAction = (action: {
363
+ name: string
364
+ payload?: Record<string, string | number | boolean>
365
+ }) => {
366
+ if (action.name === 'navigate' && typeof action.payload?.href === 'string') {
367
+ navigate(action.payload.href)
368
+ } else if (action.name === 'openCart') {
369
+ emit('openCart')
370
+ }
371
+ }
372
+ return (
373
+ <>
374
+ <HeaderUniversal
375
+ config={config}
376
+ context={context}
377
+ labels={labels}
378
+ className={parsed.className}
379
+ onAction={handleAction}
380
+ />
381
+ <StorefrontCartSheet emit={emit} />
382
+ </>
383
+ )
384
+ },
254
385
  Banner: ({ props, emit }: { props: Record<string, unknown>; emit: (event: string) => void }) => {
255
386
  const parsed = bannerPropsSchema.parse(props)
256
387
  const { set } = useStateStore()
@@ -261,6 +392,7 @@ const baseComponents = {
261
392
  href={parsed.href}
262
393
  linkLabel={parsed.linkLabel}
263
394
  avatars={parsed.avatars}
395
+ dismissLabel={parsed.dismissLabel}
264
396
  onDismiss={() => {
265
397
  set('/bannerDismissed', true)
266
398
  emit('dismissBanner')
@@ -280,8 +412,8 @@ const baseComponents = {
280
412
  featured={parsed.featured}
281
413
  signIn={parsed.signIn}
282
414
  cta={parsed.cta}
283
- // Page-level navigation owns no commerce state: the cart affordance and
284
- // its `openCart` intent belong to the StorefrontNavbar shell (D5).
415
+ // Page-level navigation owns no commerce state: the shell header and
416
+ // its cart sheet own the cart affordance and `openCart` intent.
285
417
  />
286
418
  )
287
419
  },