@growth-labs/store 0.1.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 (117) hide show
  1. package/README.md +41 -0
  2. package/dist/api.d.ts +30 -0
  3. package/dist/api.d.ts.map +1 -0
  4. package/dist/api.js +126 -0
  5. package/dist/api.js.map +1 -0
  6. package/dist/availability.d.ts +30 -0
  7. package/dist/availability.d.ts.map +1 -0
  8. package/dist/availability.js +47 -0
  9. package/dist/availability.js.map +1 -0
  10. package/dist/cache.d.ts +34 -0
  11. package/dist/cache.d.ts.map +1 -0
  12. package/dist/cache.js +80 -0
  13. package/dist/cache.js.map +1 -0
  14. package/dist/cart-client.d.ts +54 -0
  15. package/dist/cart-client.d.ts.map +1 -0
  16. package/dist/cart-client.js +347 -0
  17. package/dist/cart-client.js.map +1 -0
  18. package/dist/checkout-client.d.ts +20 -0
  19. package/dist/checkout-client.d.ts.map +1 -0
  20. package/dist/checkout-client.js +33 -0
  21. package/dist/checkout-client.js.map +1 -0
  22. package/dist/checkout-url.d.ts +25 -0
  23. package/dist/checkout-url.d.ts.map +1 -0
  24. package/dist/checkout-url.js +36 -0
  25. package/dist/checkout-url.js.map +1 -0
  26. package/dist/client.d.ts +459 -0
  27. package/dist/client.d.ts.map +1 -0
  28. package/dist/client.js +139 -0
  29. package/dist/client.js.map +1 -0
  30. package/dist/collections.d.ts +27 -0
  31. package/dist/collections.d.ts.map +1 -0
  32. package/dist/collections.js +24 -0
  33. package/dist/collections.js.map +1 -0
  34. package/dist/health.d.ts +17 -0
  35. package/dist/health.d.ts.map +1 -0
  36. package/dist/health.js +38 -0
  37. package/dist/health.js.map +1 -0
  38. package/dist/image.d.ts +25 -0
  39. package/dist/image.d.ts.map +1 -0
  40. package/dist/image.js +43 -0
  41. package/dist/image.js.map +1 -0
  42. package/dist/index.d.ts +21 -0
  43. package/dist/index.d.ts.map +1 -0
  44. package/dist/index.js +48 -0
  45. package/dist/index.js.map +1 -0
  46. package/dist/options.d.ts +174 -0
  47. package/dist/options.d.ts.map +1 -0
  48. package/dist/options.js +59 -0
  49. package/dist/options.js.map +1 -0
  50. package/dist/product-card-variant.d.ts +13 -0
  51. package/dist/product-card-variant.d.ts.map +1 -0
  52. package/dist/product-card-variant.js +33 -0
  53. package/dist/product-card-variant.js.map +1 -0
  54. package/dist/routes/cart-bootstrap.d.ts +3 -0
  55. package/dist/routes/cart-bootstrap.d.ts.map +1 -0
  56. package/dist/routes/cart-bootstrap.js +5 -0
  57. package/dist/routes/cart-bootstrap.js.map +1 -0
  58. package/dist/routes/checkout.d.ts +4 -0
  59. package/dist/routes/checkout.d.ts.map +1 -0
  60. package/dist/routes/checkout.js +14 -0
  61. package/dist/routes/checkout.js.map +1 -0
  62. package/dist/routes/webhook.d.ts +4 -0
  63. package/dist/routes/webhook.d.ts.map +1 -0
  64. package/dist/routes/webhook.js +12 -0
  65. package/dist/routes/webhook.js.map +1 -0
  66. package/dist/state.d.ts +5 -0
  67. package/dist/state.d.ts.map +1 -0
  68. package/dist/state.js +14 -0
  69. package/dist/state.js.map +1 -0
  70. package/dist/types.d.ts +5111 -0
  71. package/dist/types.d.ts.map +1 -0
  72. package/dist/types.js +167 -0
  73. package/dist/types.js.map +1 -0
  74. package/dist/variant.d.ts +59 -0
  75. package/dist/variant.d.ts.map +1 -0
  76. package/dist/variant.js +81 -0
  77. package/dist/variant.js.map +1 -0
  78. package/dist/vite-plugin.d.ts +4 -0
  79. package/dist/vite-plugin.d.ts.map +1 -0
  80. package/dist/vite-plugin.js +24 -0
  81. package/dist/vite-plugin.js.map +1 -0
  82. package/package.json +59 -0
  83. package/src/analytics-window.d.ts +15 -0
  84. package/src/api.ts +184 -0
  85. package/src/availability.ts +65 -0
  86. package/src/cache.ts +118 -0
  87. package/src/cart-client.ts +423 -0
  88. package/src/checkout-client.ts +49 -0
  89. package/src/checkout-url.ts +52 -0
  90. package/src/client.ts +216 -0
  91. package/src/cloudflare-workers.d.ts +3 -0
  92. package/src/collections.ts +63 -0
  93. package/src/components/AddToCartButton.astro +146 -0
  94. package/src/components/CartDrawer.astro +276 -0
  95. package/src/components/CartIcon.astro +96 -0
  96. package/src/components/CollectionCard.astro +81 -0
  97. package/src/components/CurrencySelector.astro +73 -0
  98. package/src/components/Price.astro +34 -0
  99. package/src/components/ProductCard.astro +225 -0
  100. package/src/components/StoreCartPage.astro +219 -0
  101. package/src/components/StoreCollectionPage.astro +166 -0
  102. package/src/components/StoreIndexPage.astro +193 -0
  103. package/src/components/StoreProductPage.astro +296 -0
  104. package/src/components/VariantPicker.astro +190 -0
  105. package/src/health.ts +54 -0
  106. package/src/image.ts +58 -0
  107. package/src/index.ts +75 -0
  108. package/src/options.ts +74 -0
  109. package/src/product-card-variant.ts +47 -0
  110. package/src/routes/cart-bootstrap.ts +6 -0
  111. package/src/routes/checkout.ts +16 -0
  112. package/src/routes/webhook.ts +14 -0
  113. package/src/state.ts +20 -0
  114. package/src/types.ts +196 -0
  115. package/src/variant.ts +119 -0
  116. package/src/virtual.d.ts +6 -0
  117. package/src/vite-plugin.ts +27 -0
@@ -0,0 +1,193 @@
1
+ ---
2
+ import { env as cloudflareEnv } from 'cloudflare:workers'
3
+ import { cachedJson } from '../cache.js'
4
+ import { createFourthwallClient } from '../client.js'
5
+ import { filterPublishedCollections, getGroupedCollections, type StoreCollection } from '../collections.js'
6
+ import { getConfig } from '../state.js'
7
+ import type { FwProduct } from '../types.js'
8
+ import CollectionCard from './CollectionCard.astro'
9
+ import ProductCard from './ProductCard.astro'
10
+
11
+ interface FwEnv {
12
+ PUBLIC_FW_STOREFRONT_TOKEN?: string
13
+ }
14
+
15
+ interface Props {
16
+ /** Heading copy — sites keep their own hero markup/imagery around this component. */
17
+ heading?: string
18
+ basePath?: string
19
+ }
20
+
21
+ const { heading, basePath = '/store' } = Astro.props
22
+ const config = getConfig()
23
+ const env = cloudflareEnv as FwEnv
24
+ const token = env?.PUBLIC_FW_STOREFRONT_TOKEN ?? ''
25
+ const cookieCurrency = Astro.cookies.get('fw_currency')?.value
26
+ const currency = cookieCurrency && config.supportedCurrencies.includes(cookieCurrency) ? cookieCurrency : config.defaultCurrency
27
+
28
+ const storeUnconfigured = config.checkoutEnabled && !token
29
+ const divisionCollections = getGroupedCollections(config.collections, 'division')
30
+ const typeCollections = getGroupedCollections(config.collections, 'type')
31
+ const client = token ? createFourthwallClient({ token, defaultCurrency: currency }) : null
32
+
33
+ interface CollectionCardData {
34
+ collection: StoreCollection
35
+ coverImageUrl: string | null
36
+ }
37
+
38
+ async function buildCardData(collections: StoreCollection[]): Promise<CollectionCardData[]> {
39
+ if (!client) return []
40
+ const publishedCollections = await filterPublishedCollections(collections, async (handle) => {
41
+ const result = await cachedJson({
42
+ pathSegment: `/collections/${encodeURIComponent(handle)}/products`,
43
+ query: { cur: currency, preview: 'cover' },
44
+ ttlSeconds: 600,
45
+ fetcher: () => client.getCollectionProducts({ handle, currency, size: 1 }),
46
+ })
47
+ return result.results
48
+ })
49
+
50
+ return Promise.all(
51
+ publishedCollections.map(async (collection) => {
52
+ if (collection.coverImagePath) {
53
+ return { collection, coverImageUrl: collection.coverImagePath }
54
+ }
55
+ try {
56
+ const result = await cachedJson({
57
+ pathSegment: `/collections/${encodeURIComponent(collection.handle)}/products`,
58
+ query: { cur: currency, preview: 'cover' },
59
+ ttlSeconds: 600,
60
+ fetcher: () => client.getCollectionProducts({ handle: collection.handle, currency, size: 1 }),
61
+ })
62
+ return { collection, coverImageUrl: result.results[0]?.images[0]?.url ?? null }
63
+ } catch {
64
+ return { collection, coverImageUrl: null }
65
+ }
66
+ }),
67
+ )
68
+ }
69
+
70
+ const [divisionCards, typeCards] = await Promise.all([buildCardData(divisionCollections), buildCardData(typeCollections)])
71
+
72
+ // Full catalogue by default (`landingProductCount: "all"`) — the review found
73
+ // sites hardcoding a 3-product teaser here while the shop held dozens of
74
+ // products, which is the "3/11 products shown" defect.
75
+ let catalogueProducts: FwProduct[] = []
76
+ let catalogueTruncated = false
77
+ if (client) {
78
+ try {
79
+ const PAGE_SIZE = 100
80
+ const firstPage = await cachedJson({
81
+ pathSegment: `/collections/${encodeURIComponent(config.catalogueHandle)}/products`,
82
+ query: { cur: currency, size: String(PAGE_SIZE) },
83
+ ttlSeconds: 300,
84
+ fetcher: () => client.getCollectionProducts({ handle: config.catalogueHandle, currency, size: PAGE_SIZE }),
85
+ })
86
+ catalogueProducts = [...firstPage.results]
87
+ let page = 2
88
+ let hasNextPage = firstPage.paging.hasNextPage
89
+ while (hasNextPage && page <= 10 && (config.landingProductCount === 'all' || catalogueProducts.length < config.landingProductCount)) {
90
+ const next = await cachedJson({
91
+ pathSegment: `/collections/${encodeURIComponent(config.catalogueHandle)}/products`,
92
+ query: { cur: currency, size: String(PAGE_SIZE), page: String(page) },
93
+ ttlSeconds: 300,
94
+ fetcher: () => client.getCollectionProducts({ handle: config.catalogueHandle, currency, size: PAGE_SIZE, page }),
95
+ })
96
+ catalogueProducts.push(...next.results)
97
+ hasNextPage = next.paging.hasNextPage
98
+ page += 1
99
+ }
100
+ catalogueProducts.sort((a, b) => {
101
+ const aT = a.createdAt ? Date.parse(a.createdAt) : 0
102
+ const bT = b.createdAt ? Date.parse(b.createdAt) : 0
103
+ return bT - aT
104
+ })
105
+ if (config.landingProductCount !== 'all' && catalogueProducts.length > config.landingProductCount) {
106
+ catalogueTruncated = true
107
+ catalogueProducts = catalogueProducts.slice(0, config.landingProductCount)
108
+ }
109
+ } catch {
110
+ catalogueProducts = []
111
+ }
112
+ }
113
+ ---
114
+
115
+ <div class="space-y-20 lg:space-y-24">
116
+ {storeUnconfigured && (
117
+ <div role="alert" class="border border-[var(--border)] bg-[var(--card)] p-4 text-sm text-[var(--muted-foreground)]">
118
+ Store isn't configured yet — set PUBLIC_FW_STOREFRONT_TOKEN.
119
+ </div>
120
+ )}
121
+ {!config.checkoutEnabled && (
122
+ <div role="status" class="border border-[var(--border)] bg-[var(--card)] p-4 text-sm text-[var(--muted-foreground)]">
123
+ Browse the catalogue below — checkout for this store is coming soon.
124
+ </div>
125
+ )}
126
+
127
+ {divisionCards.length > 0 && (
128
+ <section id="collections" class="scroll-mt-24 space-y-8">
129
+ <div class="space-y-2">
130
+ <h2 class="text-2xl font-semibold text-[var(--foreground)]">{heading ?? 'Collections'}</h2>
131
+ </div>
132
+ <div class="grid grid-cols-2 gap-x-6 gap-y-10 sm:grid-cols-4 sm:gap-x-8">
133
+ {divisionCards.map(({ collection, coverImageUrl }, idx) => (
134
+ <CollectionCard
135
+ handle={collection.handle}
136
+ name={collection.name}
137
+ description={collection.description}
138
+ coverImageUrl={coverImageUrl}
139
+ priority={idx < 4}
140
+ imageTransformEnabled={config.imageTransform.enabled}
141
+ basePath={`${basePath}/collections`}
142
+ />
143
+ ))}
144
+ </div>
145
+ </section>
146
+ )}
147
+
148
+ {typeCards.length > 0 && (
149
+ <section id="by-type" class="scroll-mt-24 space-y-8">
150
+ <div class="space-y-2">
151
+ <h2 class="text-2xl font-semibold text-[var(--foreground)]">Shop by type</h2>
152
+ </div>
153
+ <div class="grid grid-cols-2 gap-x-6 gap-y-10 sm:grid-cols-4 sm:gap-x-8">
154
+ {typeCards.map(({ collection, coverImageUrl }) => (
155
+ <CollectionCard
156
+ handle={collection.handle}
157
+ name={collection.name}
158
+ description={collection.description}
159
+ coverImageUrl={coverImageUrl}
160
+ imageTransformEnabled={config.imageTransform.enabled}
161
+ basePath={`${basePath}/collections`}
162
+ />
163
+ ))}
164
+ </div>
165
+ </section>
166
+ )}
167
+
168
+ <section id="catalogue" class="scroll-mt-24 space-y-8">
169
+ <div class="flex flex-wrap items-end justify-between gap-4">
170
+ <div class="space-y-2">
171
+ <h2 class="text-2xl font-semibold text-[var(--foreground)]">All merchandise</h2>
172
+ </div>
173
+ {catalogueTruncated && (
174
+ <a href={`${basePath}/collections/${config.catalogueHandle}/`} class="flex items-center gap-1 text-sm font-medium underline-offset-4 hover:underline">
175
+ View all merchandise
176
+ <svg class="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
177
+ <path d="m9 18 6-6-6-6" />
178
+ </svg>
179
+ </a>
180
+ )}
181
+ </div>
182
+
183
+ {catalogueProducts.length > 0 ? (
184
+ <div class="grid grid-cols-1 gap-x-6 gap-y-10 sm:grid-cols-3 sm:gap-x-8">
185
+ {catalogueProducts.map((product, idx) => (
186
+ <ProductCard product={product} priority={idx < 3} imageTransformEnabled={config.imageTransform.enabled} basePath={basePath} />
187
+ ))}
188
+ </div>
189
+ ) : (
190
+ <p class="text-[var(--muted-foreground)]">New arrivals will appear here soon.</p>
191
+ )}
192
+ </section>
193
+ </div>
@@ -0,0 +1,296 @@
1
+ ---
2
+ import { env as cloudflareEnv } from 'cloudflare:workers'
3
+ import { cachedJson, purgeProductCache } from '../cache.js'
4
+ import { createFourthwallClient } from '../client.js'
5
+ import { getConfig } from '../state.js'
6
+ import { hasProductImages, optimizeFwImage } from '../image.js'
7
+ import { FourthwallError, type FwProduct } from '../types.js'
8
+ import {
9
+ buildStoreProductJsonLd,
10
+ buildStoreVariantClientData,
11
+ isStoreVariantAvailable,
12
+ selectStoreVariant,
13
+ } from '../variant.js'
14
+ import AddToCartButton from './AddToCartButton.astro'
15
+ import Price from './Price.astro'
16
+ import VariantPicker from './VariantPicker.astro'
17
+
18
+ interface FwEnv {
19
+ PUBLIC_FW_STOREFRONT_TOKEN?: string
20
+ }
21
+
22
+ interface Props {
23
+ slug: string
24
+ basePath?: string
25
+ notFoundResponseStatus?: number
26
+ fourthwallShopBaseUrl?: string
27
+ /**
28
+ * Extension point for sites that sell more than one kind of thing (e.g.
29
+ * bigbrain's physical objects alongside merch). The site's own routing
30
+ * decides which kind a product page is — pass it explicitly rather than
31
+ * having this package infer it, since Fourthwall's product API doesn't
32
+ * return collection membership. Defaults to `"merch"`.
33
+ */
34
+ kind?: string
35
+ kindModule?: (props: { kind: string; product: unknown }) => unknown
36
+ }
37
+
38
+ const { slug, basePath = '/store', notFoundResponseStatus = 404, fourthwallShopBaseUrl, kind = 'merch', kindModule: KindModule } = Astro.props
39
+ const config = getConfig()
40
+ const env = cloudflareEnv as FwEnv
41
+ const token = env?.PUBLIC_FW_STOREFRONT_TOKEN ?? ''
42
+ const cookieCurrency = Astro.cookies.get('fw_currency')?.value
43
+ const currency = cookieCurrency && config.supportedCurrencies.includes(cookieCurrency) ? cookieCurrency : config.defaultCurrency
44
+
45
+ let product: FwProduct | null = null
46
+ let errorMessage: string | null = null
47
+
48
+ if (!token) {
49
+ if (config.checkoutEnabled) errorMessage = "Store isn't configured yet."
50
+ } else {
51
+ const client = createFourthwallClient({ token, defaultCurrency: currency })
52
+ try {
53
+ product = await cachedJson({
54
+ pathSegment: `/products/${encodeURIComponent(slug)}`,
55
+ query: { cur: currency },
56
+ ttlSeconds: 600,
57
+ fetcher: () => client.getProduct({ slug, currency }),
58
+ })
59
+ if (!hasProductImages(product)) {
60
+ const cachedProduct = product
61
+ try {
62
+ await purgeProductCache(slug, [currency])
63
+ product = await cachedJson({
64
+ pathSegment: `/products/${encodeURIComponent(slug)}`,
65
+ query: { cur: currency },
66
+ ttlSeconds: 600,
67
+ fetcher: () => client.getProduct({ slug, currency }),
68
+ })
69
+ } catch {
70
+ product = cachedProduct
71
+ }
72
+ }
73
+ } catch (err) {
74
+ if (err instanceof FourthwallError && err.status === 404) {
75
+ return new Response('Not Found', { status: notFoundResponseStatus })
76
+ }
77
+ errorMessage = err instanceof Error ? err.message : 'Product unavailable.'
78
+ }
79
+ }
80
+
81
+ const requestedVariantId = Astro.url.searchParams.get('variant')
82
+ const selectedVariant = product ? selectStoreVariant(product, requestedVariantId) : null
83
+ if (product && requestedVariantId !== null && !selectedVariant) {
84
+ return new Response('Not Found', { status: notFoundResponseStatus })
85
+ }
86
+
87
+ interface GalleryImage {
88
+ url: string
89
+ width?: number
90
+ height?: number
91
+ }
92
+ const productLevelImages: GalleryImage[] = (product?.images ?? [])
93
+ .filter((img) => Boolean(img.url))
94
+ .map((img) => ({ url: img.url, width: img.width, height: img.height }))
95
+
96
+ const variantImagesMap: Record<string, GalleryImage[]> = {}
97
+ for (const v of product?.variants ?? []) {
98
+ const seen = new Set<string>()
99
+ const imgs: GalleryImage[] = []
100
+ for (const img of v.images ?? []) {
101
+ if (img.url && !seen.has(img.url)) {
102
+ imgs.push({ url: img.url, width: img.width, height: img.height })
103
+ seen.add(img.url)
104
+ }
105
+ }
106
+ if (imgs.length === 0) {
107
+ for (const img of productLevelImages) {
108
+ if (!seen.has(img.url)) {
109
+ imgs.push(img)
110
+ seen.add(img.url)
111
+ }
112
+ }
113
+ }
114
+ variantImagesMap[v.id] = imgs
115
+ }
116
+ if (Object.keys(variantImagesMap).length === 0) {
117
+ variantImagesMap[''] = productLevelImages
118
+ }
119
+
120
+ const initialVariantId = selectedVariant?.id ?? ''
121
+ const initialGallery = variantImagesMap[initialVariantId] ?? productLevelImages
122
+ const heroImage = initialGallery[0]
123
+ const descriptionHtml = product?.descriptionHtml ?? product?.description ?? ''
124
+
125
+ const jsonLd =
126
+ product && selectedVariant
127
+ ? buildStoreProductJsonLd({
128
+ brandName: config.brandName,
129
+ canonicalProductUrl: Astro.url.origin + Astro.url.pathname,
130
+ product,
131
+ variant: selectedVariant,
132
+ requestedVariant: requestedVariantId !== null,
133
+ images: product.images,
134
+ merchantReturnPolicy: config.merchantReturnPolicy,
135
+ })
136
+ : null
137
+
138
+ const fourthwallProductUrl = fourthwallShopBaseUrl && product ? `${fourthwallShopBaseUrl.replace(/\/+$/, '')}/products/${product.slug}` : undefined
139
+ ---
140
+
141
+ {jsonLd && (
142
+ <script type="application/ld+json" set:html={JSON.stringify(jsonLd)} />
143
+ )}
144
+
145
+ <nav aria-label="Breadcrumb" class="pt-8 text-sm uppercase tracking-[0.08em] text-[var(--muted-foreground)]">
146
+ <a href={`${basePath}/`} class="underline-offset-2 transition-colors hover:text-[var(--foreground)] hover:underline">Store</a>
147
+ <span aria-hidden="true" class="mx-1.5">/</span>
148
+ <span class="text-[var(--foreground)]">{product?.name ?? slug}</span>
149
+ </nav>
150
+
151
+ {errorMessage && (
152
+ <div role="alert" class="border border-[var(--border)] bg-[var(--card)] p-4 text-sm text-[var(--muted-foreground)]">
153
+ {errorMessage}
154
+ </div>
155
+ )}
156
+
157
+ {product && (
158
+ <div
159
+ class="grid grid-cols-1 gap-10 lg:grid-cols-2"
160
+ data-product-root
161
+ data-product-id={product.id}
162
+ data-product-name={product.name}
163
+ data-product-slug={product.slug}
164
+ data-current-variant={initialVariantId}
165
+ data-variants={JSON.stringify(Object.fromEntries((product.variants ?? []).map((v) => [v.id, buildStoreVariantClientData(v)])))}
166
+ >
167
+ <div class="flex flex-col gap-3 lg:flex-row lg:items-start lg:gap-4">
168
+ <div class="order-2 flex gap-2 overflow-x-auto pb-1 lg:order-1 lg:w-20 lg:shrink-0 lg:flex-col lg:overflow-x-visible lg:overflow-y-auto lg:pb-0" data-thumb-row>
169
+ {Object.entries(variantImagesMap).flatMap(([variantId, imgs]) =>
170
+ imgs.slice(0, 8).map((img, i) => (
171
+ <button
172
+ type="button"
173
+ data-thumb
174
+ data-variant-id={variantId}
175
+ data-image-url={img.url}
176
+ class:list={[
177
+ 'fw-thumb aspect-square w-20 shrink-0 overflow-hidden border bg-[var(--muted)] transition focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--ring,var(--foreground))] lg:w-full',
178
+ variantId === initialVariantId
179
+ ? i === 0
180
+ ? 'border-[var(--foreground)]'
181
+ : 'border-transparent hover:border-[var(--foreground)]'
182
+ : 'hidden border-transparent',
183
+ ]}
184
+ aria-label={`Show product image ${i + 1}`}
185
+ >
186
+ <img
187
+ src={optimizeFwImage(img.url, { width: 200, enabled: config.imageTransform.enabled }) ?? img.url}
188
+ alt=""
189
+ loading="lazy"
190
+ decoding="async"
191
+ class="h-full w-full object-cover"
192
+ />
193
+ </button>
194
+ )),
195
+ )}
196
+ </div>
197
+
198
+ <div class="order-1 aspect-[4/5] w-full overflow-hidden bg-[var(--muted)] lg:order-2 lg:flex-1">
199
+ {heroImage?.url ? (
200
+ <img
201
+ data-main-product-image
202
+ src={optimizeFwImage(heroImage.url, { width: 800, enabled: config.imageTransform.enabled }) ?? heroImage.url}
203
+ srcset={[600, 800, 1200, 1600]
204
+ .map((w) => `${optimizeFwImage(heroImage.url, { width: w, enabled: config.imageTransform.enabled })} ${w}w`)
205
+ .join(', ')}
206
+ sizes="(min-width: 1024px) 45vw, 100vw"
207
+ alt={product.name}
208
+ width={heroImage.width ?? 800}
209
+ height={heroImage.height ?? 1000}
210
+ loading="eager"
211
+ decoding="async"
212
+ fetchpriority="high"
213
+ class="h-full w-full object-cover"
214
+ />
215
+ ) : (
216
+ <div class="flex h-full w-full items-center justify-center text-[var(--muted-foreground)]">
217
+ <span class="text-xs font-semibold uppercase tracking-[0.14em]">Store</span>
218
+ </div>
219
+ )}
220
+ </div>
221
+ </div>
222
+
223
+ <div class="space-y-6">
224
+ <div class="space-y-3">
225
+ <h1 class="text-3xl font-semibold leading-tight">{product.name}</h1>
226
+ {selectedVariant && <Price price={selectedVariant.unitPrice} compareAt={selectedVariant.compareAtPrice} class="text-lg" />}
227
+ </div>
228
+
229
+ {KindModule && <KindModule kind={kind} product={product} />}
230
+
231
+ {descriptionHtml && (
232
+ <div
233
+ class="max-w-none text-[var(--foreground)] leading-relaxed [&_p+p]:mt-4 [&_ul]:my-4 [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:my-4 [&_ol]:list-decimal [&_ol]:pl-5 [&_li+li]:mt-2 [&_strong]:font-semibold"
234
+ set:html={descriptionHtml}
235
+ />
236
+ )}
237
+
238
+ {product.variants.length > 1 && selectedVariant && <VariantPicker variants={product.variants} initialVariantId={selectedVariant.id} />}
239
+
240
+ {selectedVariant && config.checkoutEnabled && (
241
+ <div class="space-y-3">
242
+ <AddToCartButton
243
+ firstVariantId={selectedVariant.id}
244
+ initialAvailable={isStoreVariantAvailable(selectedVariant)}
245
+ pickerSelector="[data-variant-picker]"
246
+ checkoutPath={config.routes.checkoutPath}
247
+ fourthwallProductUrl={fourthwallProductUrl}
248
+ />
249
+ <AddToCartButton
250
+ firstVariantId={selectedVariant.id}
251
+ initialAvailable={isStoreVariantAvailable(selectedVariant)}
252
+ pickerSelector="[data-variant-picker]"
253
+ mode="buy-now"
254
+ checkoutPath={config.routes.checkoutPath}
255
+ />
256
+ </div>
257
+ )}
258
+ {selectedVariant && !config.checkoutEnabled && (
259
+ <p role="status" class="text-sm text-[var(--muted-foreground)]">Checkout isn't open for this store yet.</p>
260
+ )}
261
+ </div>
262
+ </div>
263
+ )}
264
+
265
+ <script>
266
+ document.querySelectorAll<HTMLElement>('[data-product-root]').forEach((root) => {
267
+ const mainImage = root.querySelector<HTMLImageElement>('[data-main-product-image]')
268
+ const thumbRow = root.querySelector<HTMLElement>('[data-thumb-row]')
269
+ const thumbs = root.querySelectorAll<HTMLButtonElement>('[data-thumb]')
270
+
271
+ root.addEventListener('fw:variant-changed', (event) => {
272
+ const detail = (event as CustomEvent<{ variantId?: string }>).detail
273
+ const variantId = detail?.variantId
274
+ if (!variantId) return
275
+ root.dataset.currentVariant = variantId
276
+ thumbs.forEach((thumb) => {
277
+ const isCurrent = thumb.dataset.variantId === variantId
278
+ thumb.classList.toggle('hidden', !isCurrent)
279
+ })
280
+ const first = thumbRow?.querySelector<HTMLButtonElement>(`[data-variant-id="${variantId}"]`)
281
+ if (first && mainImage) {
282
+ mainImage.src = first.dataset.imageUrl ?? mainImage.src
283
+ mainImage.removeAttribute('srcset')
284
+ }
285
+ })
286
+
287
+ thumbs.forEach((thumb) => {
288
+ thumb.addEventListener('click', () => {
289
+ if (mainImage && thumb.dataset.imageUrl) {
290
+ mainImage.src = thumb.dataset.imageUrl
291
+ mainImage.removeAttribute('srcset')
292
+ }
293
+ })
294
+ })
295
+ })
296
+ </script>
@@ -0,0 +1,190 @@
1
+ ---
2
+ import { isStoreVariantAvailable } from '../variant.js'
3
+ import type { FwVariant } from '../types.js'
4
+
5
+ interface Props {
6
+ variants: FwVariant[]
7
+ /** Exact server-selected variant for Merchant Center landing URLs. */
8
+ initialVariantId?: string
9
+ }
10
+
11
+ const { variants, initialVariantId } = Astro.props
12
+
13
+ interface ColorOption {
14
+ name: string
15
+ swatch: string | null
16
+ }
17
+ interface SizeOption {
18
+ name: string
19
+ }
20
+
21
+ // Build unique color and size axes across the variant list. Preserves
22
+ // insertion order so the UI matches the order Fourthwall returns.
23
+ const colorMap = new Map<string, ColorOption>()
24
+ const sizeMap = new Map<string, SizeOption>()
25
+ for (const v of variants) {
26
+ const colorName = v.attributes?.color?.name
27
+ const swatch = v.attributes?.color?.swatch ?? null
28
+ if (colorName && !colorMap.has(colorName)) {
29
+ colorMap.set(colorName, { name: colorName, swatch })
30
+ }
31
+ const sizeName = v.attributes?.size?.name
32
+ if (sizeName && !sizeMap.has(sizeName)) {
33
+ sizeMap.set(sizeName, { name: sizeName })
34
+ }
35
+ }
36
+ const colors = [...colorMap.values()]
37
+ const sizes = [...sizeMap.values()]
38
+
39
+ // Lookup table: "color|size" -> { variantId, inStock } so the client script
40
+ // can resolve the active selection back to a variant id.
41
+ const lookup: Record<string, { id: string; inStock: boolean }> = {}
42
+ for (const v of variants) {
43
+ const c = v.attributes?.color?.name ?? ''
44
+ const s = v.attributes?.size?.name ?? ''
45
+ lookup[`${c}|${s}`] = { id: v.id, inStock: isStoreVariantAvailable(v) }
46
+ }
47
+
48
+ const firstInStock = variants.find((variant) => isStoreVariantAvailable(variant)) ?? variants[0]
49
+ const selectedVariant = variants.find((variant) => variant.id === initialVariantId) ?? firstInStock
50
+ const initialColor = selectedVariant?.attributes?.color?.name ?? ''
51
+ const initialSize = selectedVariant?.attributes?.size?.name ?? ''
52
+ ---
53
+
54
+ <div
55
+ class="fw-variant-picker space-y-5"
56
+ data-variant-picker
57
+ data-selected={selectedVariant?.id ?? ''}
58
+ data-initial-color={initialColor}
59
+ data-initial-size={initialSize}
60
+ data-lookup={JSON.stringify(lookup)}
61
+ >
62
+ {colors.length > 1 && (
63
+ <div class="space-y-2">
64
+ <p class="text-sm">
65
+ <span class="text-[var(--muted-foreground)]">Select color:</span>{' '}
66
+ <span class="font-semibold" data-color-name>{initialColor}</span>
67
+ </p>
68
+ <div class="flex flex-wrap gap-3">
69
+ {colors.map((c) => (
70
+ <button
71
+ type="button"
72
+ class="fw-swatch relative h-9 w-9 rounded-full border border-[var(--border)] transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--color-focus)]"
73
+ data-color-button
74
+ data-color-name={c.name}
75
+ data-swatch={c.swatch ?? '#cccccc'}
76
+ aria-label={c.name}
77
+ aria-pressed={c.name === initialColor}
78
+ ></button>
79
+ ))}
80
+ </div>
81
+ </div>
82
+ )}
83
+
84
+ {sizes.length === 1 && (
85
+ <p class="text-sm">
86
+ <span class="text-[var(--muted-foreground)]">Size:</span>{' '}
87
+ <span class="font-semibold">{sizes[0].name}</span>
88
+ </p>
89
+ )}
90
+
91
+ {sizes.length > 1 && (
92
+ <div class="space-y-2">
93
+ <p class="text-sm">
94
+ <span class="text-[var(--muted-foreground)]">Select size:</span>{' '}
95
+ <span class="font-semibold" data-size-name>{initialSize}</span>
96
+ </p>
97
+ <div class="flex flex-wrap gap-2">
98
+ {sizes.map((s) => (
99
+ <button
100
+ type="button"
101
+ class="fw-size-button min-w-[3rem] border border-[var(--border)] px-4 py-2 text-sm transition hover:border-[var(--primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-[var(--color-focus)]"
102
+ data-size-button
103
+ data-size-name={s.name}
104
+ aria-pressed={s.name === initialSize}
105
+ >
106
+ {s.name}
107
+ </button>
108
+ ))}
109
+ </div>
110
+ </div>
111
+ )}
112
+ </div>
113
+
114
+ <script>
115
+ document.querySelectorAll<HTMLElement>('[data-variant-picker]').forEach((picker) => {
116
+ let lookup: Record<string, { id: string; inStock: boolean }> = {}
117
+ try {
118
+ lookup = JSON.parse(picker.getAttribute('data-lookup') || '{}')
119
+ } catch {
120
+ lookup = {}
121
+ }
122
+
123
+ const colorButtons = picker.querySelectorAll<HTMLButtonElement>('[data-color-button]')
124
+ const sizeButtons = picker.querySelectorAll<HTMLButtonElement>('[data-size-button]')
125
+ const colorNameEl = picker.querySelector<HTMLElement>('[data-color-name]')
126
+ const sizeNameEl = picker.querySelector<HTMLElement>('[data-size-name]')
127
+
128
+ let selectedColor =
129
+ [...colorButtons].find((b) => b.getAttribute('aria-pressed') === 'true')?.getAttribute('data-color-name') ??
130
+ picker.getAttribute('data-initial-color') ??
131
+ ''
132
+ let selectedSize =
133
+ [...sizeButtons].find((b) => b.getAttribute('aria-pressed') === 'true')?.getAttribute('data-size-name') ??
134
+ picker.getAttribute('data-initial-size') ??
135
+ ''
136
+
137
+ colorButtons.forEach((btn) => {
138
+ btn.style.backgroundColor = btn.dataset.swatch ?? '#cccccc'
139
+ })
140
+
141
+ function resolveAndEmit() {
142
+ const key = `${selectedColor}|${selectedSize}`
143
+ const hit = lookup[key]
144
+ if (!hit) return
145
+ picker.setAttribute('data-selected', hit.id)
146
+ picker.dispatchEvent(
147
+ new CustomEvent('fw:variant-changed', {
148
+ detail: { variantId: hit.id, available: hit.inStock, color: selectedColor, size: selectedSize },
149
+ bubbles: true,
150
+ }),
151
+ )
152
+ }
153
+
154
+ colorButtons.forEach((btn) => {
155
+ btn.addEventListener('click', () => {
156
+ selectedColor = btn.getAttribute('data-color-name') ?? ''
157
+ colorButtons.forEach((b) => b.setAttribute('aria-pressed', b === btn ? 'true' : 'false'))
158
+ if (colorNameEl) colorNameEl.textContent = selectedColor
159
+ resolveAndEmit()
160
+ })
161
+ })
162
+
163
+ sizeButtons.forEach((btn) => {
164
+ btn.addEventListener('click', () => {
165
+ selectedSize = btn.getAttribute('data-size-name') ?? ''
166
+ sizeButtons.forEach((b) => b.setAttribute('aria-pressed', b === btn ? 'true' : 'false'))
167
+ if (sizeNameEl) sizeNameEl.textContent = selectedSize
168
+ resolveAndEmit()
169
+ })
170
+ })
171
+ })
172
+ </script>
173
+
174
+ <style>
175
+ .fw-swatch {
176
+ cursor: pointer;
177
+ }
178
+ .fw-swatch[aria-pressed='true'] {
179
+ box-shadow:
180
+ 0 0 0 2px var(--background),
181
+ 0 0 0 4px var(--foreground);
182
+ }
183
+ .fw-size-button {
184
+ cursor: pointer;
185
+ }
186
+ .fw-size-button[aria-pressed='true'] {
187
+ border-color: var(--foreground);
188
+ box-shadow: inset 0 0 0 1px var(--foreground);
189
+ }
190
+ </style>