@thorprovider/storefront 0.3.1 → 0.4.0-mvp.0

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 (179) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +248 -99
  3. package/assets/templates/app/app/[[...slug]]/page.tsx +13 -2
  4. package/assets/templates/app/app/layout.tsx +18 -4
  5. package/assets/templates/app/app/robots.ts +13 -0
  6. package/assets/templates/app/app/sitemap.ts +12 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +542 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/cart-state.ts +66 -0
  9. package/assets/templates/app/lib/__STOREFRONT__/catalog.ts +40 -57
  10. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +608 -0
  11. package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +165 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/handlers.ts +5 -36
  13. package/assets/templates/app/lib/__STOREFRONT__/icon-map.ts +27 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +13 -11
  15. package/assets/templates/app/lib/__STOREFRONT__/registry.tsx +232 -51
  16. package/assets/templates/app/lib/__STOREFRONT__/runtime.ts +3 -3
  17. package/assets/templates/app/lib/__STOREFRONT__/schema.ts +121 -0
  18. package/assets/templates/app/lib/__STOREFRONT__/session.core.ts +470 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/session.ts +169 -0
  20. package/assets/templates/app/lib/__STOREFRONT__/shell/content.ts +96 -0
  21. package/assets/templates/app/lib/__STOREFRONT__/shell/props.ts +34 -0
  22. package/assets/templates/app/lib/__STOREFRONT__/spec/index.ts +100 -11
  23. package/assets/templates/app/lib/__STOREFRONT__/spec/page-root.ts +5 -1
  24. package/assets/templates/app/lib/__STOREFRONT__/spec/seo.ts +26 -0
  25. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +257 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/state.ts +7 -31
  27. package/assets/templates/app/lib/__STOREFRONT__/store-context.ts +142 -0
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/cta.client.tsx +25 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/cta.tsx +16 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/faq.client.tsx +24 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/faq.tsx +5 -18
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +17 -0
  33. package/assets/templates/app/lib/__STOREFRONT__/views/sections/logoCloud.tsx +26 -14
  34. package/assets/templates/app/lib/__STOREFRONT__/views/sections/pricing.tsx +36 -18
  35. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.cta.ts +19 -0
  36. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.faq.ts +18 -0
  37. package/assets/templates/app/lib/__STOREFRONT__/views/sections/statistics.tsx +35 -14
  38. package/assets/templates/app/lib/__STOREFRONT__/views/sections/testimonials.tsx +31 -13
  39. package/assets/templates/app/lib/__STOREFRONT__/views/types.ts +5 -3
  40. package/assets/templates/features/checkout/handlers.ts +153 -0
  41. package/assets/templates/features/checkout/state.ts +61 -0
  42. package/assets/templates/features/customer-auth/handlers.ts +59 -0
  43. package/assets/templates/features/customer-auth/state.ts +36 -0
  44. package/assets/templates/features/recommendations/state.ts +11 -0
  45. package/assets/templates/views/account/content.ts +35 -0
  46. package/assets/templates/views/account/index.tsx +114 -0
  47. package/assets/templates/views/account/registry.tsx +378 -0
  48. package/assets/templates/views/account/schema.ts +52 -0
  49. package/assets/templates/views/category/assembly/assembly.json +28 -0
  50. package/assets/templates/views/category/assembly/index.skeleton.tsx +193 -0
  51. package/assets/templates/views/category/assembly/registry.skeleton.tsx +33 -0
  52. package/assets/templates/views/category/assembly/slots/filter/CategoryFilter2/catalog.part +5 -0
  53. package/assets/templates/views/category/assembly/slots/filter/CategoryFilter2/element.part +34 -0
  54. package/assets/templates/views/category/assembly/slots/filter/CategoryFilter2/registry.part +71 -0
  55. package/assets/templates/views/category/content.ts +30 -0
  56. package/assets/templates/views/category/data.ts +12 -0
  57. package/assets/templates/views/category/index.tsx +230 -0
  58. package/assets/templates/views/category/props.ts +16 -0
  59. package/assets/templates/views/category/registry.tsx +103 -0
  60. package/assets/templates/views/category/schema.ts +78 -0
  61. package/assets/templates/views/checkout/content.ts +105 -0
  62. package/assets/templates/views/checkout/data.ts +23 -0
  63. package/assets/templates/views/checkout/index.tsx +111 -0
  64. package/assets/templates/views/checkout/props.ts +49 -0
  65. package/assets/templates/views/checkout/registry.tsx +217 -0
  66. package/assets/templates/views/checkout/schema.ts +229 -0
  67. package/assets/templates/views/home/assembly/assembly.json +24 -0
  68. package/assets/templates/views/home/assembly/index.skeleton.tsx +72 -0
  69. package/assets/templates/views/home/assembly/registry.skeleton.tsx +25 -0
  70. package/assets/templates/views/home/assembly/slots/benefits/Feature1/binding.json +5 -0
  71. package/assets/templates/views/home/assembly/slots/benefits/Feature1/catalog.part +4 -0
  72. package/assets/templates/views/home/assembly/slots/benefits/Feature1/element.part +4 -0
  73. package/assets/templates/views/home/assembly/slots/benefits/Feature1/registry.part +11 -0
  74. package/assets/templates/views/home/assembly/slots/benefits/Feature2/binding.json +5 -0
  75. package/assets/templates/views/home/assembly/slots/benefits/Feature2/catalog.part +4 -0
  76. package/assets/templates/views/home/assembly/slots/benefits/Feature2/element.part +4 -0
  77. package/assets/templates/views/home/assembly/slots/benefits/Feature2/registry.part +10 -0
  78. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/binding.json +5 -0
  79. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/catalog.part +4 -0
  80. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/element.part +5 -0
  81. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/registry.part +16 -0
  82. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/binding.json +5 -0
  83. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/catalog.part +4 -0
  84. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/element.part +5 -0
  85. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/registry.part +26 -0
  86. package/assets/templates/views/home/content.ts +70 -0
  87. package/assets/templates/views/home/data.ts +15 -0
  88. package/assets/templates/views/home/index.tsx +38 -84
  89. package/assets/templates/views/home/props.ts +22 -0
  90. package/assets/templates/views/home/registry.tsx +38 -22
  91. package/assets/templates/views/home/schema.ts +93 -0
  92. package/assets/templates/views/product/content.ts +25 -0
  93. package/assets/templates/views/product/data.ts +48 -0
  94. package/assets/templates/views/product/index.tsx +104 -0
  95. package/assets/templates/views/product/props.ts +20 -0
  96. package/assets/templates/views/product/registry.tsx +78 -0
  97. package/assets/templates/views/product/schema.ts +108 -0
  98. package/assets/templates/views/static/content.ts +99 -0
  99. package/assets/templates/views/static/index.tsx +60 -0
  100. package/assets/templates/views/static/registry.tsx +66 -0
  101. package/assets/templates/views/static/schema.ts +45 -0
  102. package/{skills/sf-view-gen/assets → assets}/templates/views/user-panel/index.tsx +8 -70
  103. package/{skills/sf-view-gen/assets → assets}/templates/views/user-panel/registry.tsx +23 -18
  104. package/assets/templates/views/user-panel/schema.ts +79 -0
  105. package/bin/storefront.js +1278 -79
  106. package/commands/sf-add-view.md +44 -13
  107. package/commands/sf-feature.md +28 -0
  108. package/commands/sf-theme.md +14 -8
  109. package/commands/sf-view.md +54 -12
  110. package/package.json +6 -4
  111. package/recipes/archetypes.json +28 -1
  112. package/recipes/catalog.json +361 -0
  113. package/recipes/catalog.mjs +128 -0
  114. package/recipes/catalog.schema.json +64 -0
  115. package/recipes/feature.schema.json +89 -0
  116. package/recipes/features.json +139 -0
  117. package/recipes/manifest.schema.json +69 -0
  118. package/recipes/operations.schema.json +43 -0
  119. package/recipes/recipe.schema.json +11 -2
  120. package/recipes/recipes.json +60 -5
  121. package/recipes/sections.json +24 -5
  122. package/recipes/validate.mjs +784 -32
  123. package/scripts/candidate.mjs +236 -0
  124. package/scripts/composers.mjs +140 -0
  125. package/scripts/file-classes.mjs +116 -0
  126. package/scripts/logical-controls.mjs +61 -0
  127. package/scripts/manifest.mjs +298 -0
  128. package/scripts/operation-registry.mjs +256 -0
  129. package/scripts/operations.mjs +720 -0
  130. package/scripts/ownership-conflict.mjs +356 -0
  131. package/scripts/pinning.mjs +504 -0
  132. package/scripts/plan-apply.mjs +843 -0
  133. package/scripts/preflight.mjs +51 -0
  134. package/scripts/reconcile.mjs +511 -0
  135. package/scripts/render-templates.mjs +245 -28
  136. package/scripts/schema-validate.mjs +132 -0
  137. package/scripts/section-compat.mjs +300 -0
  138. package/scripts/section-operations.mjs +508 -0
  139. package/scripts/sync-assets.mjs +22 -15
  140. package/scripts/view-assembly.mjs +291 -0
  141. package/scripts/view-selection.mjs +211 -0
  142. package/skills/sf-feature/SKILL.md +67 -0
  143. package/skills/sf-theme-gen/SKILL.md +12 -5
  144. package/skills/sf-view-gen/SKILL.md +123 -93
  145. package/skills/sf-view-gen/assets/recipes/archetypes.json +28 -1
  146. package/skills/sf-view-gen/assets/recipes/catalog.json +361 -0
  147. package/skills/sf-view-gen/assets/recipes/catalog.schema.json +64 -0
  148. package/skills/sf-view-gen/assets/recipes/features.json +139 -0
  149. package/skills/sf-view-gen/assets/recipes/recipes.json +60 -5
  150. package/skills/sf-view-gen/assets/recipes/sections.json +24 -5
  151. package/skills/sf-view-gen/assets/templates/views/sections/cta.client.tsx +25 -0
  152. package/skills/sf-view-gen/assets/templates/views/sections/cta.tsx +16 -0
  153. package/skills/sf-view-gen/assets/templates/views/sections/faq.client.tsx +13 -9
  154. package/skills/sf-view-gen/assets/templates/views/sections/faq.tsx +2 -7
  155. package/skills/sf-view-gen/assets/templates/views/sections/logoCloud.client.tsx +12 -8
  156. package/skills/sf-view-gen/assets/templates/views/sections/logoCloud.tsx +2 -7
  157. package/skills/sf-view-gen/assets/templates/views/sections/pricing.client.tsx +14 -10
  158. package/skills/sf-view-gen/assets/templates/views/sections/pricing.tsx +2 -9
  159. package/skills/sf-view-gen/assets/templates/views/sections/schema.cta.ts +19 -0
  160. package/skills/sf-view-gen/assets/templates/views/sections/schema.faq.ts +18 -0
  161. package/skills/sf-view-gen/assets/templates/views/sections/schema.logoCloud.ts +19 -0
  162. package/skills/sf-view-gen/assets/templates/views/sections/schema.pricing.ts +26 -0
  163. package/skills/sf-view-gen/assets/templates/views/sections/schema.statistics.ts +25 -0
  164. package/skills/sf-view-gen/assets/templates/views/sections/schema.testimonials.ts +23 -0
  165. package/skills/sf-view-gen/assets/templates/views/sections/statistics.client.tsx +16 -8
  166. package/skills/sf-view-gen/assets/templates/views/sections/statistics.tsx +2 -7
  167. package/skills/sf-view-gen/assets/templates/views/sections/testimonials.client.tsx +13 -9
  168. package/skills/sf-view-gen/assets/templates/views/sections/testimonials.tsx +2 -5
  169. package/skills/sf-view-gen/references/views.md +44 -10
  170. package/skills/sf-view-gen/scripts/catalog.mjs +128 -0
  171. package/skills/sf-view-gen/scripts/schema-validate.mjs +132 -0
  172. package/skills/sf-view-gen/scripts/validate.mjs +784 -32
  173. package/skills/storefront-workflow/SKILL.md +116 -0
  174. package/skills/sf-view-gen/assets/templates/views/category/index.tsx +0 -86
  175. package/skills/sf-view-gen/assets/templates/views/category/registry.tsx +0 -48
  176. package/skills/sf-view-gen/assets/templates/views/checkout/index.tsx +0 -192
  177. package/skills/sf-view-gen/assets/templates/views/checkout/registry.tsx +0 -45
  178. package/skills/sf-view-gen/assets/templates/views/product/index.tsx +0 -122
  179. package/skills/sf-view-gen/assets/templates/views/product/registry.tsx +0 -49
@@ -0,0 +1,5 @@
1
+ CategoryFilter2: {
2
+ props: categoryFilterPropsSchema,
3
+ description:
4
+ 'Listado de categoría: una sola presentación controlada CategoryFilter2 con productos, paginación, búsqueda y filtros opcionales.',
5
+ },
@@ -0,0 +1,34 @@
1
+ 'category.filter': {
2
+ type: 'CategoryFilter2',
3
+ props: {
4
+ // User-owned copy first, so a customization can be overridden by the
5
+ // feature config (search placeholder) and the derived state bindings.
6
+ ...categoryFilterProps,
7
+ showSearch: hasSearch,
8
+ showFilters: hasFilters,
9
+ showSort: true,
10
+ showPrice: filtersConfig.showPrice === true,
11
+ ...(hasSearch && searchConfig.placeholder
12
+ ? { searchPlaceholder: searchConfig.placeholder }
13
+ : {}),
14
+ // Composition context for generated navigation (task 4.11): the client
15
+ // registry drops a removed feature's owned orphan parameters on a UI
16
+ // action. Read separately from the block props; never a `CategoryFilter2`
17
+ // prop and never bound to state.
18
+ mountedFeatures,
19
+ products: { $state: '/categoryFilterProducts' },
20
+ pagination: { $state: '/categoryFilterPagination' },
21
+ status: { $state: '/categoryFilterStatus' },
22
+ activeFilters: { $state: '/categoryFilterActiveFilters' },
23
+ searchValue: { $state: '/categoryFilterSearchValue' },
24
+ selectedCategories: { $state: '/categoryFilterSelectedCategories' },
25
+ selectedCollections: { $state: '/categoryFilterSelectedCollections' },
26
+ selectedSort: { $state: '/categoryFilterSelectedSort' },
27
+ selectedPage: { $state: '/categoryFilterSelectedPage' },
28
+ selectedPageSize: { $state: '/categoryFilterSelectedPageSize' },
29
+ sortOptions: { $state: '/categoryFilterSortOptions' },
30
+ categories: { $state: '/categoryFilterCategories' },
31
+ collections: { $state: '/categoryFilterCollections' },
32
+ priceRange: { $state: '/categoryFilterPriceRange' },
33
+ },
34
+ },
@@ -0,0 +1,71 @@
1
+ CategoryFilter2: ({ props, emit }) => {
2
+ const router = useRouter()
3
+ const pathname = usePathname()
4
+ const { set } = useStateStore()
5
+ const p = props as unknown as CategoryFilter2RegistryProps
6
+
7
+ // Minimal `updateURL` seam (task 6.1; task 5.2 verified the criterion and is
8
+ // complete): apply one change to the current browser URL and let the server
9
+ // loader rebuild the listing. The page reset rules live in the pure helper,
10
+ // not here. The installed-feature context is passed so generated navigation
11
+ // drops a removed feature's owned orphan parameters (task 4.11) while never
12
+ // dropping the base listing's route scope, `sort`, `page`, or `pageSize`.
13
+ //
14
+ // History policy (task 5.3): an intentional filter/sort/page/pageSize commit
15
+ // pushes a history entry so reload and back/forward restore the previous
16
+ // query and products; repair and the immediate per-keystroke search replace
17
+ // the current entry (no per-keystroke history explosion). The choice is the
18
+ // pure `catalogHistoryMode` seam, not ad-hoc logic here.
19
+ const apply = (change: CategoryQueryChange) => {
20
+ const search = typeof window === 'undefined' ? '' : window.location.search
21
+ const href = buildCategoryQueryHref(pathname, search, change, p.mountedFeatures)
22
+ if (catalogHistoryMode(change) === 'push') router.push(href)
23
+ else router.replace(href)
24
+ }
25
+
26
+ return (
27
+ <CategoryFilter2Block
28
+ products={p.products}
29
+ categories={p.categories}
30
+ collections={p.collections}
31
+ sortOptions={p.sortOptions}
32
+ pagination={p.pagination}
33
+ priceRange={p.priceRange}
34
+ showSearch={p.showSearch}
35
+ showFilters={p.showFilters}
36
+ showSort={p.showSort}
37
+ showPrice={p.showPrice}
38
+ searchValue={p.searchValue}
39
+ selectedCategories={p.selectedCategories}
40
+ selectedCollections={p.selectedCollections}
41
+ selectedSort={p.selectedSort}
42
+ selectedPage={p.selectedPage}
43
+ selectedPageSize={p.selectedPageSize}
44
+ selectedPriceRange={p.selectedPriceRange}
45
+ status={p.status}
46
+ activeFilters={p.activeFilters}
47
+ filtersTitle={p.filtersTitle}
48
+ searchLabel={p.searchLabel}
49
+ searchPlaceholder={p.searchPlaceholder}
50
+ sortPlaceholder={p.sortPlaceholder}
51
+ productsTitle={p.productsTitle}
52
+ onSearchChange={(text) => apply({ kind: 'search', text })}
53
+ onSortChange={(sort) => apply({ kind: 'sort', sort })}
54
+ onPageChange={(page) => apply({ kind: 'page', page })}
55
+ onPageSizeChange={(size) => apply({ kind: 'pageSize', pageSize: size })}
56
+ onFilterChange={(filters: CategoryFilter2Filters) =>
57
+ apply({ kind: 'filters', categories: filters.categories, collections: filters.collections ?? [] })
58
+ }
59
+ onClearFilters={() => apply({ kind: 'clearFilters' })}
60
+ onRepair={(remove) => apply({ kind: 'repair', remove })}
61
+ onRetry={() => router.refresh()}
62
+ onRemoveFilter={(filter: CategoryFilter2ActiveFilter) =>
63
+ apply({ kind: 'removeFilter', filter })
64
+ }
65
+ onProductClick={(product) => {
66
+ set('/lastClicked', { id: product.id })
67
+ emit('openProduct')
68
+ }}
69
+ />
70
+ )
71
+ },
@@ -0,0 +1,30 @@
1
+ // Thor Commerce view content: category
2
+ // User-owned view content — listing copy for the single controlled
3
+ // `CategoryFilter2`. Reconcile seeds this file once and never rewrites it; the
4
+ // derived view module (./index.tsx) imports it and wires it into the element
5
+ // tree, so your edits here survive `storefront sync` and unit removal. Plain
6
+ // data only: no React and no server imports.
7
+ //
8
+ // The sort OPTIONS are not listed here: they come from the adapter-advertised
9
+ // set (`getCatalogSortKeys`), never from assumed global price sorts.
10
+
11
+ export const filterContent = {
12
+ filtersTitle: 'Filtros',
13
+ searchLabel: 'Buscar',
14
+ searchPlaceholder: 'Buscar productos',
15
+ sortPlaceholder: 'Ordenar por',
16
+ productsTitle: 'Productos',
17
+ emptyTitle: 'Sin resultados',
18
+ emptyDescription: 'Ningún producto coincide con los filtros activos.',
19
+ clearFiltersLabel: 'Limpiar filtros',
20
+ }
21
+
22
+ /**
23
+ * Editorial section instance content, keyed by the section instance id the
24
+ * manifest persists (`views[].sections[].id`, e.g. `category-faq-1`). The derived
25
+ * view module reads `sectionContent[id]`, so adding, reordering, or removing a
26
+ * section never rewrites this file and your copy survives `storefront sync`.
27
+ * Plain data only, matching the section fragment's props; an unset id renders
28
+ * the section's neutral default.
29
+ */
30
+ export const sectionContent: Record<string, Record<string, unknown>> = {}
@@ -0,0 +1,12 @@
1
+ // Thor Commerce view data: category
2
+ // User-owned loader shaping for the category view. Reconcile seeds this file once
3
+ // and never rewrites it; the derived view module (./index.tsx) imports these
4
+ // helpers and calls them from its loader, so edits here survive `storefront sync`
5
+ // and unit removal. Pure functions only: no React and no server imports.
6
+
7
+ export function selectCategoryProducts<T>(
8
+ all: readonly T[],
9
+ scoped: readonly T[] | null,
10
+ ): T[] {
11
+ return scoped ? [...scoped] : [...all]
12
+ }
@@ -0,0 +1,230 @@
1
+ // Thor Commerce view module: category
2
+ // Server Component module: elements + catalog entries + route + loader only.
3
+ // The client-side component mappings live in ./registry.tsx ('use client'); this
4
+ // module imports them as data so the RSC graph never evaluates @json-render/react
5
+ // on the server. Registered by importing it in ../index.ts. Recipe: recipes.json -> "category".
6
+ //
7
+ // E2 task 6.1: the category listing is ONE controlled `CategoryFilter2` — the
8
+ // base listing slot `category.filter`, always present. The optional
9
+ // `catalog-search` / `category-filters` features are control contributions to
10
+ // that single block (logical mounts `category.search` / `category.filters`),
11
+ // never a second listing/controller. Their visibility and config are read from
12
+ // the installed manifest (`mountedFeatures` / `mountedFeatureConfigs`) that
13
+ // `sync` derives from `storefront.config.json`; no loader is hand-edited to add
14
+ // or remove them.
15
+
16
+ import { z } from 'zod'
17
+ import {
18
+ buildActiveFilterChips,
19
+ getCatalog,
20
+ getCatalogSortKeys,
21
+ getCollectionOptions,
22
+ loadCategoryListing,
23
+ mapCatalogOutcomeToStatus,
24
+ mapCatalogResultsToFilterProps,
25
+ } from '@thorprovider/runtime/commerce'
26
+ import { getDataSource, getStoreContext, isRealMode } from '../../store-context'
27
+ import { mountedFeatures, mountedFeatureConfigs } from '../../composition'
28
+ import { pageRoot } from '../../spec/page-root'
29
+ import type { StorefrontElement } from '../../spec/types'
30
+ import type { ViewModule } from '../types'
31
+ import { registry } from './registry'
32
+ import { categoryFilterProps } from './props'
33
+ import { categoryFilterPropsSchema } from './schema'
34
+
35
+ // The single controlled `CategoryFilter2` base listing. The search/filter
36
+ // controls are shown only when the matching feature is installed; the base
37
+ // listing always owns the route scope, `sort`, `page`, `pageSize`, the products,
38
+ // and pagination.
39
+ const hasSearch = mountedFeatures.includes('catalog-search')
40
+ const hasFilters = mountedFeatures.includes('category-filters')
41
+ const searchConfig = (mountedFeatureConfigs['catalog-search'] ?? {}) as { placeholder?: string }
42
+ const filtersConfig = (mountedFeatureConfigs['category-filters'] ?? {}) as {
43
+ filterSet?: string[]
44
+ showPrice?: boolean
45
+ }
46
+
47
+ // UI labels for the adapter-advertised sort keys. The keys themselves come from
48
+ // the provider (`getCatalogSortKeys`); no global price sort is ever assumed.
49
+ const SORT_LABELS: Record<string, string> = {
50
+ featured: 'Destacados',
51
+ name: 'Nombre',
52
+ newest: 'Más recientes',
53
+ }
54
+
55
+ const elements: Record<string, StorefrontElement> = {
56
+ 'category.filter': {
57
+ type: 'CategoryFilter2',
58
+ props: {
59
+ // User-owned copy first, so a customization can be overridden by the
60
+ // feature config (search placeholder) and the derived state bindings.
61
+ ...categoryFilterProps,
62
+ showSearch: hasSearch,
63
+ showFilters: hasFilters,
64
+ showSort: true,
65
+ showPrice: filtersConfig.showPrice === true,
66
+ ...(hasSearch && searchConfig.placeholder
67
+ ? { searchPlaceholder: searchConfig.placeholder }
68
+ : {}),
69
+ // Composition context for generated navigation (task 4.11): the client
70
+ // registry drops a removed feature's owned orphan parameters on a UI
71
+ // action. Read separately from the block props; never a `CategoryFilter2`
72
+ // prop and never bound to state.
73
+ mountedFeatures,
74
+ products: { $state: '/categoryFilterProducts' },
75
+ pagination: { $state: '/categoryFilterPagination' },
76
+ status: { $state: '/categoryFilterStatus' },
77
+ activeFilters: { $state: '/categoryFilterActiveFilters' },
78
+ searchValue: { $state: '/categoryFilterSearchValue' },
79
+ selectedCategories: { $state: '/categoryFilterSelectedCategories' },
80
+ selectedCollections: { $state: '/categoryFilterSelectedCollections' },
81
+ selectedSort: { $state: '/categoryFilterSelectedSort' },
82
+ selectedPage: { $state: '/categoryFilterSelectedPage' },
83
+ selectedPageSize: { $state: '/categoryFilterSelectedPageSize' },
84
+ sortOptions: { $state: '/categoryFilterSortOptions' },
85
+ categories: { $state: '/categoryFilterCategories' },
86
+ collections: { $state: '/categoryFilterCollections' },
87
+ priceRange: { $state: '/categoryFilterPriceRange' },
88
+ },
89
+ },
90
+ }
91
+
92
+ const catalog = {
93
+ CategoryFilter2: {
94
+ props: categoryFilterPropsSchema,
95
+ description:
96
+ 'Listado de categoría: una sola presentación controlada CategoryFilter2 con productos, paginación, búsqueda y filtros opcionales.',
97
+ },
98
+ }
99
+
100
+ /** Empty state for the single listing, used on every failure path. */
101
+ const emptyFilterState = () => ({
102
+ categoryFilterProducts: [],
103
+ categoryFilterPagination: [] as (number | string)[],
104
+ categoryFilterActiveFilters: [],
105
+ categoryFilterSearchValue: '',
106
+ categoryFilterSelectedCategories: [] as string[],
107
+ categoryFilterSelectedCollections: [] as string[],
108
+ categoryFilterSelectedSort: 'featured',
109
+ categoryFilterSelectedPage: 1,
110
+ categoryFilterSelectedPageSize: 50,
111
+ categoryFilterSortOptions: [],
112
+ categoryFilterCategories: [],
113
+ categoryFilterCollections: [],
114
+ categoryFilterPriceRange: undefined,
115
+ })
116
+
117
+ export const category: ViewModule = {
118
+ name: 'category',
119
+ elements,
120
+ catalog,
121
+ registry,
122
+ route: {
123
+ path: '/categorias/[[...slug]]',
124
+ loaderName: 'category',
125
+ layout: 'default',
126
+ metadata: {
127
+ title: 'Categoría',
128
+ description: 'Explora los productos de esta categoría en __SITE_NAME__.',
129
+ },
130
+ entry: pageRoot('category', ['category.filter'], elements),
131
+ },
132
+ loader: {
133
+ category: async (params, searchParams) => {
134
+ const slug = Array.isArray(params.slug) ? params.slug[0] : params.slug
135
+ try {
136
+ // Validate the raw URL through the pure boundary before any commerce
137
+ // call. An invalid, repeated, or unknown parameter — or one owned by a
138
+ // feature that is not installed — returns a typed error with zero
139
+ // provider resolution, not even the sidebar catalog (E2 task 5.1/6.1).
140
+ const listing = await loadCategoryListing({
141
+ searchParams: searchParams ?? {},
142
+ ...(slug ? { categoryScope: slug } : {}),
143
+ mountedFeatures,
144
+ ...(isRealMode() ? { context: getStoreContext() } : {}),
145
+ })
146
+
147
+ if (!listing.ok) {
148
+ return {
149
+ storeCategories: [],
150
+ dataSource: getDataSource(),
151
+ dataError: null,
152
+ ...emptyFilterState(),
153
+ categoryFilterStatus: mapCatalogOutcomeToStatus({ ok: false, error: listing.error }),
154
+ }
155
+ }
156
+
157
+ const catalog = await getCatalog()
158
+ const advertisedSortKeys = await getCatalogSortKeys()
159
+ const sortOptions = advertisedSortKeys.map((key) => ({
160
+ value: key,
161
+ label: SORT_LABELS[key] ?? key,
162
+ }))
163
+ // Real adapter category options (handle + name). No fake counts/ranges.
164
+ const allCategories = catalog.categoriesRaw.map((entry) => ({
165
+ id: entry.handle,
166
+ label: entry.name,
167
+ }))
168
+ const filterSet = filtersConfig.filterSet ?? ['categories', 'collections']
169
+ const categories = filterSet.includes('categories') ? allCategories : undefined
170
+ // Real, backend-scoped collection options (handle + title), fetched only
171
+ // when `category-filters` is installed and owns the collections control.
172
+ // An empty backend list omits the control; no option is ever fabricated.
173
+ const showCollections = hasFilters && filterSet.includes('collections')
174
+ const allCollections = showCollections
175
+ ? (await getCollectionOptions()).map((entry) => ({
176
+ id: entry.id,
177
+ label: entry.label,
178
+ }))
179
+ : []
180
+ const collections = allCollections.length > 0 ? allCollections : undefined
181
+ const presentation = mapCatalogResultsToFilterProps({
182
+ query: listing.query,
183
+ results: listing.results,
184
+ // A scoped listing (`/categorias/<handle>`) must not offer the
185
+ // category facet: the scope already fixes the category. The root
186
+ // catalog passes no scope and keeps it.
187
+ ...(slug ? { categoryScope: slug } : {}),
188
+ // Product links point at the product-detail route. The runtime stays
189
+ // route-agnostic, so this view supplies the href builder.
190
+ productHref: (handle: string) => `/productos/${handle}`,
191
+ ...(categories ? { categories } : {}),
192
+ ...(collections ? { collections } : {}),
193
+ sortOptions,
194
+ })
195
+ const activeFilters = buildActiveFilterChips(listing.query, {
196
+ categories: Object.fromEntries(allCategories.map((entry) => [entry.id, entry.label])),
197
+ collections: Object.fromEntries(allCollections.map((entry) => [entry.id, entry.label])),
198
+ })
199
+
200
+ return {
201
+ storeCategories: catalog.categories,
202
+ dataSource: catalog.source,
203
+ dataError: null,
204
+ categoryFilterProducts: presentation.products,
205
+ categoryFilterPagination: presentation.pagination,
206
+ categoryFilterStatus: mapCatalogOutcomeToStatus({ ok: true, results: listing.results }),
207
+ categoryFilterActiveFilters: activeFilters,
208
+ categoryFilterSearchValue: presentation.searchValue,
209
+ categoryFilterSelectedCategories: presentation.selectedCategories,
210
+ categoryFilterSelectedCollections: presentation.selectedCollections,
211
+ categoryFilterSelectedSort: presentation.selectedSort,
212
+ categoryFilterSelectedPage: presentation.selectedPage,
213
+ categoryFilterSelectedPageSize: presentation.selectedPageSize,
214
+ categoryFilterSortOptions: presentation.sortOptions ?? [],
215
+ categoryFilterCategories: presentation.categories ?? [],
216
+ categoryFilterCollections: presentation.collections ?? [],
217
+ categoryFilterPriceRange: presentation.priceRange,
218
+ }
219
+ } catch (error) {
220
+ return {
221
+ storeCategories: [],
222
+ dataSource: getDataSource(),
223
+ dataError: error instanceof Error ? error.message : 'No se pudo cargar la categoría.',
224
+ ...emptyFilterState(),
225
+ categoryFilterStatus: { state: 'error' as const },
226
+ }
227
+ }
228
+ },
229
+ },
230
+ }
@@ -0,0 +1,16 @@
1
+ // Thor Commerce view props: category
2
+ // User-owned element props for the category view. Reconcile seeds this file once
3
+ // and never rewrites it; the derived view module (./index.tsx) imports these
4
+ // objects and binds them into the element tree, so edits here survive
5
+ // `storefront sync` and unit removal. Plain data only: no React and no server
6
+ // imports.
7
+ //
8
+ // The listing state (products, pagination, selected query values, status) is
9
+ // derived wiring, not copy: it is bound to `$state` in ./index.tsx from the
10
+ // URL-backed loader. Only presentation copy lives here.
11
+
12
+ import { filterContent } from './content'
13
+
14
+ export const categoryFilterProps = {
15
+ ...filterContent,
16
+ }
@@ -0,0 +1,103 @@
1
+ 'use client'
2
+
3
+ // Thor Commerce view registry fragment: category
4
+ // The category view's single client boundary: one controlled `CategoryFilter2`
5
+ // (the base listing slot `category.filter`). Search/filters/sort/pagination are
6
+ // URL-backed: the block emits a change, this registry rewrites the URL through
7
+ // the pure `buildCategoryQueryHref` seam, and the server loader re-seeds the
8
+ // controlled props from the new URL. No fetch and no provider call happens on
9
+ // the client. The search and filter controls are only present because the
10
+ // installed manifest enabled them; the block never adds a second listing.
11
+
12
+ import {
13
+ CategoryFilter2 as CategoryFilter2Block,
14
+ type CategoryFilter2ActiveFilter,
15
+ type CategoryFilter2Filters,
16
+ type CategoryFilter2Props,
17
+ } from '@thorprovider/blocks'
18
+ import { buildCategoryQueryHref, catalogHistoryMode, type CategoryQueryChange } from '@thorprovider/runtime/commerce'
19
+ import type { CatalogFeatureName } from '@thorprovider/runtime/contracts'
20
+ import { useStateStore } from '@json-render/react'
21
+ import { usePathname, useRouter } from 'next/navigation'
22
+ import type { ViewRegistry } from '../types'
23
+
24
+ // The generated view module injects the installed-feature context as an element
25
+ // prop (task 4.11); it is composition context, not a `CategoryFilter2` prop, so
26
+ // it is read separately from the block props.
27
+ type CategoryFilter2RegistryProps = CategoryFilter2Props & {
28
+ mountedFeatures?: readonly CatalogFeatureName[]
29
+ }
30
+
31
+ export const registry: ViewRegistry = {
32
+ CategoryFilter2: ({ props, emit }) => {
33
+ const router = useRouter()
34
+ const pathname = usePathname()
35
+ const { set } = useStateStore()
36
+ const p = props as unknown as CategoryFilter2RegistryProps
37
+
38
+ // Minimal `updateURL` seam (task 6.1; task 5.2 verified the criterion and is
39
+ // complete): apply one change to the current browser URL and let the server
40
+ // loader rebuild the listing. The page reset rules live in the pure helper,
41
+ // not here. The installed-feature context is passed so generated navigation
42
+ // drops a removed feature's owned orphan parameters (task 4.11) while never
43
+ // dropping the base listing's route scope, `sort`, `page`, or `pageSize`.
44
+ //
45
+ // History policy (task 5.3): an intentional filter/sort/page/pageSize commit
46
+ // pushes a history entry so reload and back/forward restore the previous
47
+ // query and products; repair and the immediate per-keystroke search replace
48
+ // the current entry (no per-keystroke history explosion). The choice is the
49
+ // pure `catalogHistoryMode` seam, not ad-hoc logic here.
50
+ const apply = (change: CategoryQueryChange) => {
51
+ const search = typeof window === 'undefined' ? '' : window.location.search
52
+ const href = buildCategoryQueryHref(pathname, search, change, p.mountedFeatures)
53
+ if (catalogHistoryMode(change) === 'push') router.push(href)
54
+ else router.replace(href)
55
+ }
56
+
57
+ return (
58
+ <CategoryFilter2Block
59
+ products={p.products}
60
+ categories={p.categories}
61
+ collections={p.collections}
62
+ sortOptions={p.sortOptions}
63
+ pagination={p.pagination}
64
+ priceRange={p.priceRange}
65
+ showSearch={p.showSearch}
66
+ showFilters={p.showFilters}
67
+ showSort={p.showSort}
68
+ showPrice={p.showPrice}
69
+ searchValue={p.searchValue}
70
+ selectedCategories={p.selectedCategories}
71
+ selectedCollections={p.selectedCollections}
72
+ selectedSort={p.selectedSort}
73
+ selectedPage={p.selectedPage}
74
+ selectedPageSize={p.selectedPageSize}
75
+ selectedPriceRange={p.selectedPriceRange}
76
+ status={p.status}
77
+ activeFilters={p.activeFilters}
78
+ filtersTitle={p.filtersTitle}
79
+ searchLabel={p.searchLabel}
80
+ searchPlaceholder={p.searchPlaceholder}
81
+ sortPlaceholder={p.sortPlaceholder}
82
+ productsTitle={p.productsTitle}
83
+ onSearchChange={(text) => apply({ kind: 'search', text })}
84
+ onSortChange={(sort) => apply({ kind: 'sort', sort })}
85
+ onPageChange={(page) => apply({ kind: 'page', page })}
86
+ onPageSizeChange={(size) => apply({ kind: 'pageSize', pageSize: size })}
87
+ onFilterChange={(filters: CategoryFilter2Filters) =>
88
+ apply({ kind: 'filters', categories: filters.categories, collections: filters.collections ?? [] })
89
+ }
90
+ onClearFilters={() => apply({ kind: 'clearFilters' })}
91
+ onRepair={(remove) => apply({ kind: 'repair', remove })}
92
+ onRetry={() => router.refresh()}
93
+ onRemoveFilter={(filter: CategoryFilter2ActiveFilter) =>
94
+ apply({ kind: 'removeFilter', filter })
95
+ }
96
+ onProductClick={(product) => {
97
+ set('/lastClicked', { id: product.id })
98
+ emit('openProduct')
99
+ }}
100
+ />
101
+ )
102
+ },
103
+ }
@@ -0,0 +1,78 @@
1
+ // Thor Commerce view schema fragment: category
2
+ // Zod mirror of the single controlled `CategoryFilter2` prop contract for this
3
+ // view — the source for the catalog entry and the client-side registry parsing
4
+ // (json-render does not validate props against the catalog itself, so the
5
+ // registry parses here). Kept free of React and server imports so the Server
6
+ // Component module and the 'use client' registry can share one contract. Block
7
+ // zod contracts are mirrored, not imported: @thorprovider/blocks ships zod v3
8
+ // while the scaffold runs zod v4 and cross-major schema assignment breaks the
9
+ // catalog contract.
10
+
11
+ import { z } from 'zod'
12
+
13
+ export const filterProductSchema = z.object({
14
+ id: z.string(),
15
+ name: z.string(),
16
+ price: z.string(),
17
+ image: z.string().optional(),
18
+ // Product-detail link supplied by the presentation layer; when absent the
19
+ // block falls back to its onClick path.
20
+ href: z.string().optional(),
21
+ })
22
+
23
+ export const categoryFilterSortOptionSchema = z.object({
24
+ value: z.string(),
25
+ label: z.string(),
26
+ })
27
+
28
+ export const categoryFilterOptionSchema = z.object({
29
+ id: z.string(),
30
+ label: z.string(),
31
+ })
32
+
33
+ export const categoryFilterActiveFilterSchema = z.object({
34
+ id: z.string(),
35
+ kind: z.string(),
36
+ label: z.string(),
37
+ params: z.array(z.string()),
38
+ value: z.string().optional(),
39
+ })
40
+
41
+ export const categoryFilterPriceRangeSchema = z.object({
42
+ min: z.number(),
43
+ max: z.number(),
44
+ step: z.number(),
45
+ })
46
+
47
+ export const categoryFilterStatusSchema = z.object({ state: z.string() }).catchall(z.unknown())
48
+
49
+ export const categoryFilterPropsSchema = z
50
+ .object({
51
+ products: z.array(filterProductSchema),
52
+ pagination: z.array(z.union([z.number(), z.string()])),
53
+ status: categoryFilterStatusSchema,
54
+ activeFilters: z.array(categoryFilterActiveFilterSchema),
55
+ searchValue: z.string(),
56
+ selectedCategories: z.array(z.string()),
57
+ selectedCollections: z.array(z.string()),
58
+ selectedSort: z.string(),
59
+ selectedPage: z.union([z.number(), z.string()]),
60
+ selectedPageSize: z.union([z.number(), z.string()]),
61
+ selectedPriceRange: z.array(z.number()).optional(),
62
+ sortOptions: z.array(categoryFilterSortOptionSchema),
63
+ categories: z.array(categoryFilterOptionSchema),
64
+ collections: z.array(categoryFilterOptionSchema),
65
+ priceRange: categoryFilterPriceRangeSchema.optional(),
66
+ showSearch: z.boolean(),
67
+ showFilters: z.boolean(),
68
+ showSort: z.boolean(),
69
+ showPrice: z.boolean().optional(),
70
+ filtersTitle: z.string().optional(),
71
+ searchLabel: z.string().optional(),
72
+ searchPlaceholder: z.string().optional(),
73
+ sortPlaceholder: z.string().optional(),
74
+ productsTitle: z.string().optional(),
75
+ })
76
+ .catchall(z.unknown())
77
+
78
+ export type CategoryFilterProps = z.infer<typeof categoryFilterPropsSchema>