@usethrottle/storefront-react 0.0.0-stage → 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 (122) hide show
  1. package/CLAUDE.md +67 -0
  2. package/README.md +119 -2
  3. package/dist/StorefrontProvider-Br4wUHui.d.cts +559 -0
  4. package/dist/StorefrontProvider-DLEPEjg6.d.ts +559 -0
  5. package/dist/account/index.cjs +69 -0
  6. package/dist/account/index.cjs.map +1 -0
  7. package/dist/account/index.d.cts +23 -0
  8. package/dist/account/index.d.ts +23 -0
  9. package/dist/account/index.js +68 -0
  10. package/dist/account/index.js.map +1 -0
  11. package/dist/chunk-2LCPIY2P.cjs +16 -0
  12. package/dist/chunk-2LCPIY2P.cjs.map +1 -0
  13. package/dist/chunk-3A72UY6T.js +2126 -0
  14. package/dist/chunk-3A72UY6T.js.map +1 -0
  15. package/dist/chunk-3JMIVAHN.js +185 -0
  16. package/dist/chunk-3JMIVAHN.js.map +1 -0
  17. package/dist/chunk-4J6AGWNC.cjs +24 -0
  18. package/dist/chunk-4J6AGWNC.cjs.map +1 -0
  19. package/dist/chunk-4U6MYDZV.js +17 -0
  20. package/dist/chunk-4U6MYDZV.js.map +1 -0
  21. package/dist/chunk-66HDJVPS.js +22 -0
  22. package/dist/chunk-66HDJVPS.js.map +1 -0
  23. package/dist/chunk-6X2OZSNV.cjs +83 -0
  24. package/dist/chunk-6X2OZSNV.cjs.map +1 -0
  25. package/dist/chunk-6ZMMZ245.cjs +2127 -0
  26. package/dist/chunk-6ZMMZ245.cjs.map +1 -0
  27. package/dist/chunk-7R37CVAB.cjs +23 -0
  28. package/dist/chunk-7R37CVAB.cjs.map +1 -0
  29. package/dist/chunk-A3IFWQUV.js +368 -0
  30. package/dist/chunk-A3IFWQUV.js.map +1 -0
  31. package/dist/chunk-AYC2YK4E.cjs +95 -0
  32. package/dist/chunk-AYC2YK4E.cjs.map +1 -0
  33. package/dist/chunk-AZV5U7YB.cjs +18 -0
  34. package/dist/chunk-AZV5U7YB.cjs.map +1 -0
  35. package/dist/chunk-CE2SKNQP.cjs +71 -0
  36. package/dist/chunk-CE2SKNQP.cjs.map +1 -0
  37. package/dist/chunk-D76CRI4X.js +2175 -0
  38. package/dist/chunk-D76CRI4X.js.map +1 -0
  39. package/dist/chunk-DOAII637.cjs +186 -0
  40. package/dist/chunk-DOAII637.cjs.map +1 -0
  41. package/dist/chunk-DYHHAOMG.cjs +17 -0
  42. package/dist/chunk-DYHHAOMG.cjs.map +1 -0
  43. package/dist/chunk-EYSVU5SJ.js +196 -0
  44. package/dist/chunk-EYSVU5SJ.js.map +1 -0
  45. package/dist/chunk-HSUUDZWS.js +37 -0
  46. package/dist/chunk-HSUUDZWS.js.map +1 -0
  47. package/dist/chunk-HZ6VEN6Q.cjs +101 -0
  48. package/dist/chunk-HZ6VEN6Q.cjs.map +1 -0
  49. package/dist/chunk-IJOTLGPT.js +16 -0
  50. package/dist/chunk-IJOTLGPT.js.map +1 -0
  51. package/dist/chunk-ISDATHVC.js +219 -0
  52. package/dist/chunk-ISDATHVC.js.map +1 -0
  53. package/dist/chunk-LW2A6USV.js +100 -0
  54. package/dist/chunk-LW2A6USV.js.map +1 -0
  55. package/dist/chunk-M4YXSLRG.cjs +369 -0
  56. package/dist/chunk-M4YXSLRG.cjs.map +1 -0
  57. package/dist/chunk-NDUEJJLP.cjs +2176 -0
  58. package/dist/chunk-NDUEJJLP.cjs.map +1 -0
  59. package/dist/chunk-NNE4FYRT.js +820 -0
  60. package/dist/chunk-NNE4FYRT.js.map +1 -0
  61. package/dist/chunk-NW3EFHY2.js +15 -0
  62. package/dist/chunk-NW3EFHY2.js.map +1 -0
  63. package/dist/chunk-NZRUQUN5.js +167 -0
  64. package/dist/chunk-NZRUQUN5.js.map +1 -0
  65. package/dist/chunk-P6HHE57S.cjs +38 -0
  66. package/dist/chunk-P6HHE57S.cjs.map +1 -0
  67. package/dist/chunk-PHY7AY27.cjs +197 -0
  68. package/dist/chunk-PHY7AY27.cjs.map +1 -0
  69. package/dist/chunk-PNJOFFTL.cjs +128 -0
  70. package/dist/chunk-PNJOFFTL.cjs.map +1 -0
  71. package/dist/chunk-PXZQ4ONA.js +127 -0
  72. package/dist/chunk-PXZQ4ONA.js.map +1 -0
  73. package/dist/chunk-Q3VTUBPP.js +82 -0
  74. package/dist/chunk-Q3VTUBPP.js.map +1 -0
  75. package/dist/chunk-Q3XFD5UI.js +45 -0
  76. package/dist/chunk-Q3XFD5UI.js.map +1 -0
  77. package/dist/chunk-QM7KTT7F.js +94 -0
  78. package/dist/chunk-QM7KTT7F.js.map +1 -0
  79. package/dist/chunk-RLWZOLXL.js +70 -0
  80. package/dist/chunk-RLWZOLXL.js.map +1 -0
  81. package/dist/chunk-SV53BRP2.js +23 -0
  82. package/dist/chunk-SV53BRP2.js.map +1 -0
  83. package/dist/chunk-VWXJO427.cjs +821 -0
  84. package/dist/chunk-VWXJO427.cjs.map +1 -0
  85. package/dist/chunk-WIIOJDHR.cjs +220 -0
  86. package/dist/chunk-WIIOJDHR.cjs.map +1 -0
  87. package/dist/chunk-XQHGFWLG.cjs +46 -0
  88. package/dist/chunk-XQHGFWLG.cjs.map +1 -0
  89. package/dist/chunk-ZHCXI2ZZ.cjs +168 -0
  90. package/dist/chunk-ZHCXI2ZZ.cjs.map +1 -0
  91. package/dist/index-RSj2Rg62.d.cts +8 -0
  92. package/dist/index-RSj2Rg62.d.ts +8 -0
  93. package/dist/index.cjs +2829 -0
  94. package/dist/index.cjs.map +1 -0
  95. package/dist/index.d.cts +1718 -0
  96. package/dist/index.d.ts +1718 -0
  97. package/dist/index.js +2828 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/metadata-QhKw-tvz.d.cts +188 -0
  100. package/dist/metadata-QhKw-tvz.d.ts +188 -0
  101. package/dist/next/client.cjs +84 -0
  102. package/dist/next/client.cjs.map +1 -0
  103. package/dist/next/client.d.cts +40 -0
  104. package/dist/next/client.d.ts +40 -0
  105. package/dist/next/client.js +83 -0
  106. package/dist/next/client.js.map +1 -0
  107. package/dist/next/index.cjs +1090 -0
  108. package/dist/next/index.cjs.map +1 -0
  109. package/dist/next/index.d.cts +218 -0
  110. package/dist/next/index.d.ts +218 -0
  111. package/dist/next/index.js +1049 -0
  112. package/dist/next/index.js.map +1 -0
  113. package/dist/server/index.cjs +994 -0
  114. package/dist/server/index.cjs.map +1 -0
  115. package/dist/server/index.d.cts +229 -0
  116. package/dist/server/index.d.ts +229 -0
  117. package/dist/server/index.js +951 -0
  118. package/dist/server/index.js.map +1 -0
  119. package/dist/styles.css +2111 -0
  120. package/dist/use-part-DCfFk7kf.d.ts +24 -0
  121. package/dist/use-part-DgjPBL_O.d.cts +24 -0
  122. package/package.json +121 -3
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/app-throttle/app-throttle/packages/storefront-react/dist/chunk-NDUEJJLP.cjs","../src/site/SlotOutlet.tsx","../src/url/shop-query.ts","../src/seo/JsonLd.tsx","../src/seo/json-ld.ts","../src/seo/metadata.ts","../src/pieces/Badge.tsx","../src/pieces/badges.ts","../src/pieces/reserved.tsx","../src/pieces/Swatch.tsx","../src/product/variant-logic.ts","../src/product/use-product-page.ts","../src/product/AddToCart.tsx","../src/product/Breadcrumbs.tsx","../src/product/QuantityInput.tsx","../src/product/StockStatus.tsx","../src/product/VariantPicker.tsx","../src/product/BuyBox.tsx","../src/product/CategoryList.tsx","../src/product/Gallery.tsx","../src/pieces/RichText.tsx","../src/product/RelatedProducts.tsx","../src/pieces/ProductCard.tsx","../src/product/ReviewForm.tsx","../src/product/Reviews.tsx","../src/server/reviews-page.ts","../src/product/ShippingSection.tsx","../src/product/TagList.tsx","../src/product/ProductSections.tsx","../src/product/use-media-query.ts","../src/product/StickyAddToCart.tsx","../src/product/ProductPage.tsx","../src/shopper/quiet-router.tsx"],"names":["selectOption","useEffect","srcSetOf","DEFAULT_SLOTS","Select","resolved"],"mappings":"AAAA,+8BAAY;AACZ;AACE;AACA;AACA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,IAAA;AACD,EAAA;AACH;AAGS;AAGD,EAAA;AACF,EAAA;AACA,EAAA;AACG,EAAA;AACT;AAEM;AACA;AAEA;AAKG;AACD,EAAA;AACE,EAAA;AACR,EAAA;AACE,IAAA;AACI,IAAA;AACA,IAAA;AACA,IAAA;AACJ,IAAA;AACA,IAAA;AACI,IAAA;AACA,IAAA;AACF,MAAA;AACA,MAAA;AACA,MAAA;AACI,MAAA;AACF,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACE,QAAA;AACF,MAAA;AACF,IAAA;AACI,IAAA;AACN,EAAA;AACF;AAOgB;AACV,EAAA;AACE,EAAA;AACE,EAAA;AACD,EAAA;AACC,IAAA;AACF,IAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACA,IAAA;AACI,IAAA;AACA,IAAA;AACF,MAAA;AACI,MAAA;AACJ,MAAA;AACF,IAAA;AACM,IAAA;AACA,IAAA;AACN,IAAA;AACM,IAAA;AACD,IAAA;AAEC,MAAA;AACF,QAAA;AACA,QAAA;AACF,MAAA;AACE,QAAA;AACA,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACM,IAAA;AACD,IAAA;AACD,IAAA;AAEA,IAAA;AACF,MAAA;AACI,MAAA;AACF,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACI,IAAA;AACE,MAAA;AACF,QAAA;AACA,QAAA;AACA,QAAA;AACA,QAAA;AACF,MAAA;AACA,MAAA;AACF,IAAA;AACK,IAAA;AAED,IAAA;AACE,IAAA;AACA,IAAA;AACN,IAAA;AACM,MAAA;AACA,MAAA;AACJ,MAAA;AACI,MAAA;AACF,QAAA;AACA,QAAA;AACF,MAAA;AACE,QAAA;AACF,MAAA;AACF,IAAA;AACI,IAAA;AACA,IAAA;AACJ,IAAA;AACK,IAAA;AACP,EAAA;AACO,EAAA;AACA,EAAA;AACT;AASgB;AACR,EAAA;AACA,EAAA;AAEA,EAAA;AACC,EAAA;AACT;ApBggCU;AACA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;AACD,EAAA;AACK,EAAA;AAEJ,EAAA;AAMJ;AAOS;AACC,EAAA;AACA,EAAA;AACA,EAAA;AACF,EAAA;AACA,EAAA;AACG,IAAA;AACN,IAAA;AACH,EAAA;AACM,EAAA;AACA,EAAA;AACA,EAAA;AACNA,EAAAA;AAEM,IAAA;AACF,EAAA;AACE,EAAA;AAEF,EAAA;AACF,IAAA;AACF,EAAA;AACI,EAAA;AACF,IAAA;AAKF,EAAA;AAEE,EAAA;AAIJ;AAGS;AACC,EAAA;AACA,EAAA;AACA,EAAA;AACF,EAAA;AAEA,EAAA;AACA,EAAA;AAEJ,EAAA;AACG,IAAA;AACD,oBAAA;AACF,EAAA;AAEJ;AAES;AACC,EAAA;AACD,EAAA;AACT;AAES;AACC,EAAA;AACD,EAAA;AACT;AAES;AACD,EAAA;AAEJ,EAAA;AACE,oBAAA;AACA,oBAAA;AACF,EAAA;AAEJ;AAUS;AACC,EAAA;AACF,EAAA;AAEJ,EAAA;AAGM,oBAAA;AACA,oBAAA;AACA,oBAAA;AACA,oBAAA;AACA,oBAAA;AACA,oBAAA;AACA,oBAAA;AAGN,EAAA;AAEJ;AAMa;AACX,EAAA;AACQ,EAAA;AACR,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AACD;A/B01DS;AACA;AgC5jED;AAkBA;AAbH;AAAc;AAOJ;AACR,EAAA;AACA,EAAA;AACJ,IAAA;AACC,IAAA;AACH,EAAA;AACO,EAAA;AACT;AhCsjEU;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/app-throttle/app-throttle/packages/storefront-react/dist/chunk-NDUEJJLP.cjs","sourcesContent":[null,"import type { StorefrontProduct } from '@usethrottle/catalog';\nimport { useSlotOutlet } from '@usethrottle/ui';\nimport { usePart } from '../parts';\n\n/** The places a host (the Throttle Builder) may add content: above and below a product page and a listing. */\nexport type StorefrontSlotName = 'product.above' | 'product.below' | 'shop.above' | 'shop.below';\n\n/** What a listing slot knows; matches the Builder's `context.listing` data source. */\nexport type ListingContext = {\n source: { kind: 'all' | 'collection' | 'category' | 'tag' | 'search'; handle?: string; q?: string };\n total: number;\n filters: Record<string, string[]>;\n sort: string;\n page: number;\n};\n\n/** What a slot knows; matches the Builder's `context.product` / `context.listing`. */\nexport type SlotContext =\n | { kind: 'product'; product: StorefrontProduct; variantSku: string | null }\n | { kind: 'listing'; listing: ListingContext };\n\n/** The props of `SlotOutlet`: which place this is and what it knows. */\nexport type SlotOutletProps = {\n /** Which place this is. A host registers a renderer for a name. */\n name: StorefrontSlotName;\n /** What the content may read: the product (and variant) or the listing. */\n context: SlotContext;\n};\n\n/**\n * A place where a host (the Builder) may add content. Renders what\n * `useSlotOutlet(name)` returns, with `{ context }`, inside a wrapper; with\n * nothing to render (no host, or no renderer for the name) it renders nothing,\n * not even the wrapper.\n */\nexport function SlotOutlet({ name, context }: SlotOutletProps) {\n const Renderer = useSlotOutlet(name);\n const part = usePart('slot-outlet');\n if (!Renderer) return null;\n return (\n <div {...part} data-slot={name}>\n <Renderer context={context} />\n </div>\n );\n}\n","import {\n formatRange,\n parseRange,\n parseShopQuery as parseCatalogQuery,\n serializeShopQuery,\n type ShopQueryInput,\n} from '@usethrottle/catalog/url';\nimport type { StorefrontProduct } from '@usethrottle/catalog';\nimport { isUnsafeKey } from '../settings/guards';\nimport type { NormalizedSettings } from '../settings/normalize';\n\n/** What `searchParams` is in a Next page: a plain record (a value may repeat). */\nexport type SearchParamsInput = Record<string, string | string[] | undefined>;\n\n/**\n * The shop selection as URL state. Filters and ranges are `filter.<key>` URL\n * parameters (the catalog SDK's wire form: a range is one `min..max` value).\n * `sort` is always the effective sort: the URL's, or the store's default.\n */\nexport type ShopQuery = {\n filters: Record<string, string[]>;\n ranges: Record<string, { min?: number; max?: number }>;\n sort: string;\n page: number;\n q?: string;\n};\n\n/** What a listing shows: the whole shop, one collection, category or tag (by path), or a search. */\nexport type ShopSource =\n | { kind: 'all' }\n | { kind: 'collection' | 'category' | 'tag'; handle: string }\n | { kind: 'search'; q: string };\n\nconst enabledSorts = (settings: NormalizedSettings): Set<string> =>\n new Set(settings.listing.sorts.filter((s) => s.enabled).map((s) => s.key as string));\n\n/** The sort the URL names when the store offers it, else null. */\nexport function explicitSort(params: URLSearchParams | SearchParamsInput, settings: NormalizedSettings): string | null {\n const { sort } = parseCatalogQuery(params as ShopQueryInput);\n return sort !== undefined && enabledSorts(settings).has(sort) ? sort : null;\n}\n\n/**\n * Reads the URL state. A sort the store has disabled (or does not know) falls\n * back to `listing.defaultSort`; a page below 1 or not a number is 1.\n * Parameters follow the catalog SDK's shop URL: `filter.<key>`, `sort`, `page`, `q`.\n *\n * `rangeKeys` names the range-type facets (`display: 'range'`). Only their\n * `a..b` values become `ranges`; on any other key the text stays a filter\n * value. Left out, every `a..b` value is read as a range.\n */\nexport function parseShopQuery(\n params: URLSearchParams | SearchParamsInput,\n settings: NormalizedSettings,\n rangeKeys?: Iterable<string>,\n): ShopQuery {\n const ranged = rangeKeys === undefined ? null : new Set(rangeKeys);\n const raw = parseCatalogQuery(params as ShopQueryInput);\n const filters: ShopQuery['filters'] = {};\n const ranges: ShopQuery['ranges'] = {};\n for (const key of Object.keys(raw.filters ?? {})) {\n if (isUnsafeKey(key)) continue;\n for (const value of raw.filters![key]!) {\n const range = ranged === null || ranged.has(key) ? parseRange(value) : null;\n if (range) {\n if (!Object.hasOwn(ranges, key)) ranges[key] = range;\n } else (filters[key] ??= []).push(value);\n }\n }\n for (const key of Object.keys(filters)) filters[key] = [...new Set(filters[key])].sort();\n const query: ShopQuery = {\n filters,\n ranges,\n sort: explicitSort(params, settings) ?? settings.listing.defaultSort,\n page: raw.page !== undefined && raw.page >= 1 ? raw.page : 1,\n };\n if (raw.q) query.q = raw.q;\n return query;\n}\n\nfunction toCatalogQuery(q: ShopQuery, settings: NormalizedSettings) {\n const filters: Record<string, string[]> = {};\n for (const key of Object.keys(q.filters)) filters[key] = [...q.filters[key]!];\n for (const key of Object.keys(q.ranges)) (filters[key] ??= []).push(formatRange(q.ranges[key]!));\n for (const key of Object.keys(filters)) filters[key] = [...new Set(filters[key])].sort();\n return {\n ...(q.q ? { q: q.q } : {}),\n ...(Object.keys(filters).length > 0 ? { filters } : {}),\n ...(q.sort !== settings.listing.defaultSort ? { sort: q.sort } : {}),\n ...(q.page > 1 ? { page: q.page } : {}),\n };\n}\n\n/** The canonical query string (no leading `?`): keys sorted, values sorted, defaults (the default sort, page 1) omitted. */\nexport function shopQueryToSearch(q: ShopQuery, settings: NormalizedSettings): string {\n return serializeShopQuery(toCatalogQuery(q, settings));\n}\n\n/** The page numbers to show: the first, the last and the current one's neighbours, `null` for a gap. */\nexport function pageWindow(current: number, count: number): Array<number | null> {\n const pages = [...new Set([1, current - 1, current, current + 1, count])]\n .filter((p) => p >= 1 && p <= count)\n .sort((a, b) => a - b);\n const out: Array<number | null> = [];\n for (const [i, p] of pages.entries()) {\n if (i > 0 && p - pages[i - 1]! > 1) out.push(null);\n out.push(p);\n }\n return out;\n}\n\n/** The variant a product URL names (`?variant=<sku>`), or null when it names none the product has. */\nexport function variantFromSearch(\n params: URLSearchParams | SearchParamsInput,\n product: Pick<StorefrontProduct, 'variants'>,\n): string | null {\n const value = params instanceof URLSearchParams ? params.get('variant') : params.variant;\n const sku = Array.isArray(value) ? value[0] : value;\n return sku !== undefined && product.variants.some((v) => v.sku === sku) ? sku : null;\n}\n\n/** Filter values a URL carries: each checked value, each range counts one. */\nconst filterValueCount = (q: ShopQuery): number =>\n Object.values(q.filters).reduce((n, values) => n + values.length, 0) + Object.keys(q.ranges).length;\n\n/**\n * R4: a shop URL is `noindex,follow` when it carries two or more filter\n * values, a sort other than the store's default, or a search term (`q` on a\n * listing; a search page is `noindex` on its own). Links are always followed.\n */\nexport function robotsForShopQuery(q: ShopQuery, settings: NormalizedSettings): { index: boolean; follow: true } {\n return { index: filterValueCount(q) <= 1 && q.sort === settings.listing.defaultSort && !q.q, follow: true };\n}\n\n/**\n * R4: the canonical URL keeps at most one filter value (the first by key, then\n * value) and `page` above 1, and drops the sort. `q` stays only on a search\n * page (`source.kind === 'search'`); on a listing it is dropped. Absolute:\n * `baseUrl` + `pathname`.\n */\nexport function canonicalForShopQuery(\n baseUrl: string,\n pathname: string,\n q: ShopQuery,\n settings: NormalizedSettings,\n source?: ShopSource,\n): string {\n const first = [\n ...Object.entries(q.filters).flatMap(([key, values]) => values.map((value) => ({ key, value }))),\n ...Object.entries(q.ranges).map(([key, range]) => ({ key, value: formatRange(range) })),\n ].sort((a, b) => (a.key === b.key ? a.value.localeCompare(b.value) : a.key.localeCompare(b.key)))[0];\n const kept: ShopQuery = {\n filters: {},\n ranges: {},\n sort: settings.listing.defaultSort,\n page: q.page,\n ...(q.q && source?.kind === 'search' ? { q: q.q } : {}),\n };\n if (first) {\n const range = parseRange(first.value);\n if (range) kept.ranges[first.key] = range;\n else kept.filters[first.key] = [first.value];\n }\n const search = shopQueryToSearch(kept, settings);\n return `${baseUrl.replace(/\\/+$/u, '')}${pathname}${search ? `?${search}` : ''}`;\n}\n","/**\n * A JSON-LD `<script>`. Every `<` in the serialised JSON is written as the\n * JSON escape `<`, so a value can never close the script element.\n */\nexport function JsonLd({ data }: { data: object }) {\n return (\n <script\n type=\"application/ld+json\"\n dangerouslySetInnerHTML={{ __html: JSON.stringify(data).replace(/</gu, '\\\\u003c') }}\n />\n );\n}\n","import type { ListProduct, StorefrontProduct } from '@usethrottle/catalog';\nimport { toDecimalString } from '@usethrottle/money';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport { routeHref } from '../url/routes';\n\nconst SCHEMA = 'https://schema.org';\nconst availabilityOf = (states: Array<string | null | undefined>): string => {\n if (states.includes('in_stock')) return `${SCHEMA}/InStock`;\n if (states.includes('preorder')) return `${SCHEMA}/PreOrder`;\n if (states.includes('backorder')) return `${SCHEMA}/BackOrder`;\n return `${SCHEMA}/OutOfStock`;\n};\n\n/**\n * schema.org `Product` for a product page: its images, brand, SKU and one\n * `Offer` at the lowest price a variant sells for (prices as decimal text).\n * Available when any variant is in stock; with none, pre-order, back-order, else out of stock.\n */\nexport function productJsonLd(\n product: StorefrontProduct,\n o: { url: string; settings: NormalizedSettings; currency: string },\n): object {\n // Only the page's own currency is compared: prices in different currencies are never ordered against each other.\n const priced = product.variants\n .map((v) => ({ minor: v.salePriceMinor ?? v.priceMinor, currency: v.currency ?? o.currency }))\n .filter((p): p is { minor: number; currency: string } => p.minor !== null && p.currency === o.currency);\n const lowest = priced.sort((a, b) => a.minor - b.minor)[0];\n const price = lowest ?? (product.priceRange ? { minor: product.priceRange.minMinor, currency: product.priceRange.currency } : null);\n const store = o.settings.brand.storeName.trim();\n const description = product.shortDescription ?? product.description;\n return {\n '@context': SCHEMA,\n '@type': 'Product',\n name: product.title ?? product.handle,\n ...(description ? { description } : {}),\n ...(product.images.length > 0 ? { image: product.images.map((i) => i.url) } : {}),\n ...(product.brand ? { brand: { '@type': 'Brand', name: product.brand } } : {}),\n ...(product.variants[0] ? { sku: product.variants[0].sku } : {}),\n url: o.url,\n offers: {\n '@type': 'Offer',\n url: o.url,\n ...(price ? { price: toDecimalString(price.minor, price.currency), priceCurrency: price.currency } : {}),\n availability: availabilityOf(\n product.variants.length > 0 ? product.variants.map((v) => v.availability) : [product.availability],\n ),\n ...(store ? { seller: { '@type': 'Organization', name: store } } : {}),\n },\n };\n}\n\n/** schema.org `BreadcrumbList`. `url`s are absolute. */\nexport function breadcrumbJsonLd(crumbs: { name: string; url: string }[]): object {\n return {\n '@context': SCHEMA,\n '@type': 'BreadcrumbList',\n itemListElement: crumbs.map((c, i) => ({ '@type': 'ListItem', position: i + 1, name: c.name, item: c.url })),\n };\n}\n\n/** schema.org `ItemList` of a listing's products, each a link to its page. */\nexport function itemListJsonLd(products: ListProduct[], o: { baseUrl: string; settings: NormalizedSettings }): object {\n const base = o.baseUrl.replace(/\\/+$/u, '');\n return {\n '@context': SCHEMA,\n '@type': 'ItemList',\n itemListElement: products.map((p, i) => ({\n '@type': 'ListItem',\n position: i + 1,\n url: `${base}${routeHref(o.settings, 'product', p.handle)}`,\n ...(p.title ? { name: p.title } : {}),\n })),\n };\n}\n","import type { SiteDesign } from '@usethrottle/ui';\nimport { resolveSiteDesign } from '../site/resolve';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport type { ProductData, ShopAllData } from '../server/types';\nimport { routeHref } from '../url/routes';\nimport { canonicalForShopQuery, robotsForShopQuery, type ShopSource } from '../url/shop-query';\n\n/** Page metadata, assignable to Next's `Metadata`. */\nexport type StorefrontMetadata = {\n title: string;\n description?: string;\n alternates: { canonical: string };\n robots?: { index: boolean; follow: boolean };\n openGraph?: { title: string; description?: string; images?: string[] };\n};\n\ntype MetadataOptions = { baseUrl: string; site?: SiteDesign | null };\n\nconst origin = (baseUrl: string): string => baseUrl.replace(/\\/+$/u, '');\nconst absolute = (baseUrl: string, path: string): string => `${origin(baseUrl)}${path}`;\n\n/** A tab title from `seo.titleTemplate` (`{page}`, `{store}`). With no store name, or no page name, the other side stands alone. */\nfunction pageTitle(template: string, store: string, page: string): string {\n const name = page.trim();\n const shop = store.trim();\n if (name === '') return shop;\n if (shop === '') return name;\n return template.split('{page}').join(name).split('{store}').join(shop);\n}\n\nfunction resolved(data: { settings: NormalizedSettings }, o: MetadataOptions) {\n return resolveSiteDesign({ site: o.site ?? null, settings: data.settings });\n}\n\nconst nonEmpty = (value: string | null | undefined): string | undefined => (value && value.trim() ? value : undefined);\n\nfunction openGraph(title: string, description: string | undefined, images: Array<string | undefined>): StorefrontMetadata['openGraph'] {\n const urls = images.filter((u): u is string => Boolean(u));\n return { title, ...(description ? { description } : {}), ...(urls.length > 0 ? { images: urls } : {}) };\n}\n\n/** The path a listing lives at (without its query string). */\nfunction listingPath(settings: NormalizedSettings, source: ShopSource): string {\n switch (source.kind) {\n case 'all':\n return settings.routes.shop;\n case 'search':\n return settings.routes.search.split('?')[0]!;\n default:\n return routeHref(settings, source.kind, source.handle);\n }\n}\n\n/** A shop, collection, category or tag page: the entity's SEO title, the canonical and robots of R4. */\nexport function shopAllMetadata(data: ShopAllData, o: MetadataOptions): StorefrontMetadata {\n const site = resolved(data, o);\n const title = pageTitle(site.seo.titleTemplate, site.brand.storeName, data.seoTitle ?? data.title);\n const description = nonEmpty(data.description) ?? nonEmpty(site.seo.defaultDescription);\n return {\n title,\n ...(description ? { description } : {}),\n alternates: {\n canonical: canonicalForShopQuery(o.baseUrl, listingPath(data.settings, data.source), data.query, data.settings, data.source),\n },\n robots: robotsForShopQuery(data.query, data.settings),\n openGraph: openGraph(title, description, [site.seo.shareImage]),\n };\n}\n\n/** Search results: indexable search pages only add near-duplicates, so they are `noindex,follow`. */\nexport function searchMetadata(data: ShopAllData, o: MetadataOptions): StorefrontMetadata {\n return { ...shopAllMetadata(data, o), robots: { index: false, follow: true } };\n}\n\n/** A product page: the merchant's SEO title and description, the first image, a canonical without `?variant=`. */\nexport function productMetadata(data: ProductData, o: MetadataOptions): StorefrontMetadata {\n const { product } = data;\n const site = resolved(data, o);\n const name = nonEmpty(product.seoTitle) ?? nonEmpty(product.seo?.title) ?? product.title ?? product.handle;\n const title = pageTitle(site.seo.titleTemplate, site.brand.storeName, name);\n const description =\n nonEmpty(product.seoDescription) ??\n nonEmpty(product.seo?.description) ??\n nonEmpty(product.shortDescription) ??\n nonEmpty(product.description) ??\n nonEmpty(site.seo.defaultDescription);\n return {\n title,\n ...(description ? { description } : {}),\n alternates: { canonical: absolute(o.baseUrl, routeHref(data.settings, 'product', product.handle)) },\n openGraph: openGraph(title, description, [product.images[0]?.url ?? site.seo.shareImage]),\n };\n}\n","import type { CSSProperties, ReactNode } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { isHexColor, parseHex } from '../theme/color';\n\n/** A small label on a card or product (`Sale`, `New`). */\nexport type BadgeProps = UsePartLocal & {\n /** What the badge says it is (`sale`, `new`, `lowStock`, `custom`): `data-badge`, and the colour it starts from. */\n kind?: string;\n /** A hex background the settings chose; the text colour is picked to read on it. Anything but hex is ignored. */\n tone?: string;\n /** The badge's text. */\n children: ReactNode;\n};\n\n/** Token backgrounds by kind, so a badge follows the theme (and dark mode) until the settings pick a colour. */\nconst KIND_BACKGROUND: Record<string, string> = {\n sale: 'var(--throttle-sf-sale)',\n new: 'var(--throttle-sf-accent)',\n lowStock: 'var(--throttle-sf-warning)',\n};\n\nfunction ink(hex: string): string {\n const [r, g, b] = parseHex(hex).map((c) => {\n const v = c / 255;\n return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;\n }) as [number, number, number];\n return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.4 ? '#20150e' : '#ffffff';\n}\n\n/** A small label on a card or a product. */\nexport function Badge({ kind, tone, children, classNames, className, unstyled }: BadgeProps) {\n const part = usePart('product-badge', { classNames, className, unstyled });\n const style: Record<string, string> = {};\n if (isHexColor(tone)) {\n style['--tsf-badge-bg'] = tone;\n style['--tsf-badge-fg'] = ink(tone);\n } else if (kind && KIND_BACKGROUND[kind]) {\n style['--tsf-badge-bg'] = KIND_BACKGROUND[kind]!;\n }\n return (\n <span {...part} data-badge={kind} style={Object.keys(style).length > 0 ? (style as CSSProperties) : undefined}>\n {children}\n </span>\n );\n}\n","import type { ListProduct } from '@usethrottle/catalog';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport { DEFAULT_SETTINGS } from '../settings/defaults';\nimport { isHexColor } from '../theme/color';\n\n/** One badge on a card: its kind, its label and an optional colour. */\nexport type CardBadge = {\n kind: 'sale' | 'new' | 'lowStock' | 'custom';\n label: string;\n /** A hex colour the settings chose. Absent when it is the catalog's own default, so the theme's token shows. */\n tone?: string;\n};\n\nconst DAY_MS = 86_400_000;\n\n/**\n * The product's creation time, when the list answer carries one. `createdAt` is\n * not in `ListProduct` as of catalog 1.4.x, so against that SDK this is always\n * null and the catalog's own `badges.new` flag decides (see `isNew`).\n */\nfunction createdAtOf(product: ListProduct): number | null {\n const at = (product as { createdAt?: unknown }).createdAt;\n const time = typeof at === 'string' ? Date.parse(at) : NaN;\n return Number.isNaN(time) ? null : time;\n}\n\n/** New: by age against `generatedAt` when the product has a creation time, else the catalog's own `badges.new`. */\nfunction isNew(product: ListProduct, days: number, generatedAt: string): boolean {\n const created = createdAtOf(product);\n const now = Date.parse(generatedAt);\n if (created === null || Number.isNaN(now)) return product.badges?.new === true;\n return now - created <= days * DAY_MS;\n}\n\n/** Sale: a compare-at price above the lowest price; with no price range, the catalog's own `badges.sale`. */\nfunction isSale(product: ListProduct): boolean {\n const range = product.priceRange;\n if (!range) return product.badges?.sale === true;\n const compareAt = 'compareAtMinMinor' in range ? range.compareAtMinMinor : null;\n return typeof compareAt === 'number' && compareAt > range.minMinor;\n}\n\nconst toneOf = (colour: string, catalogDefault: string): string | undefined =>\n isHexColor(colour) && colour.toLowerCase() !== catalogDefault.toLowerCase() ? colour : undefined;\n\n/**\n * The badges on a product card, in order: new, sale, low stock, then the custom\n * tag badges. A port of Meridian `lib/badges.ts` (`cardFlags`); time-dependent\n * output reads `generatedAt` (the server's clock, ISO), never `Date.now()`, so a\n * server render and its hydration agree. Server-safe.\n */\nexport function cardBadges(settings: NormalizedSettings, product: ListProduct, generatedAt: string): CardBadge[] {\n if (!settings.card.showBadges) return [];\n const { badges } = settings;\n const out: CardBadge[] = [];\n const add = (kind: CardBadge['kind'], label: string, tone?: string) =>\n out.push(tone === undefined ? { kind, label } : { kind, label, tone });\n\n if (badges.new.enabled && isNew(product, badges.new.days, generatedAt))\n add('new', badges.new.label, toneOf(badges.new.colour, DEFAULT_SETTINGS.badges.new.colour));\n if (badges.sale.enabled && isSale(product))\n add('sale', badges.sale.label, toneOf(badges.sale.colour, DEFAULT_SETTINGS.badges.sale.colour));\n if (badges.lowStock.enabled && product.lowStock && product.availability !== 'out_of_stock')\n add('lowStock', badges.lowStock.label);\n for (const custom of badges.custom)\n if (product.tags?.includes(custom.tag)) add('custom', custom.label, isHexColor(custom.colour) ? custom.colour : undefined);\n return out;\n}\n","/**\n * Places Phase 3 fills (wishlist, back in stock, bundles, review media and\n * votes, questions and answers). Each renders nothing today; a store may\n * already pass them as a slot and a later release gives them a body.\n */\ntype ReservedProps = Record<string, unknown>;\n\n/** Reserved for the wishlist (a later release). Renders nothing today; a store may already pass it as a slot. */\nexport function WishlistButton(_props: ReservedProps): null {\n return null;\n}\n/** Reserved for back-in-stock notices (a later release). Renders nothing today. */\nexport function BackInStock(_props: ReservedProps): null {\n return null;\n}\n/** Reserved for bundles (a later release). Renders nothing today. */\nexport function FrequentlyBoughtTogether(_props: ReservedProps): null {\n return null;\n}\n/** Reserved for review photos (a later release). Renders nothing today. */\nexport function ReviewPhotos(_props: ReservedProps): null {\n return null;\n}\n/** Reserved for review votes (a later release). Renders nothing today. */\nexport function ReviewVotes(_props: ReservedProps): null {\n return null;\n}\n/** Reserved for questions and answers (a later release). Renders nothing today. */\nexport function QuestionsAndAnswers(_props: ReservedProps): null {\n return null;\n}\n","import { usePart, type UsePartLocal } from '../parts';\nimport { isHexColor } from '../theme/color';\n\n/** A colour or texture dot for an option value. */\nexport type SwatchProps = UsePartLocal & {\n /** The option value; it names the swatch to a screen reader. */\n value: string;\n /** A hex colour; anything else is ignored. */\n hex?: string;\n /** An image URL, for a swatch that is a texture. */\n image?: string;\n /** This value is the chosen one. */\n selected?: boolean;\n /** No variant with this value can be bought. */\n disabled?: boolean;\n};\n\n/** A colour or texture dot. It only draws; a picker wraps it in the control that selects. */\nexport function Swatch({ value, hex, image, selected, disabled, classNames, className, unstyled }: SwatchProps) {\n const part = usePart('swatch', { classNames, className, unstyled });\n return (\n <span\n {...part}\n role=\"img\"\n aria-label={value}\n data-selected={selected ? 'true' : undefined}\n data-disabled={disabled ? 'true' : undefined}\n style={image ? { backgroundImage: `url(${JSON.stringify(image)})` } : isHexColor(hex) ? { backgroundColor: hex } : undefined}\n />\n );\n}\n","import type { StorefrontProduct } from '@usethrottle/catalog';\n\n/** A variant as `products.get` answers it. */\nexport type Variant = StorefrontProduct['variants'][number];\n\n/** The values of one option as the picker reads them. */\nexport type PickerOption = { name: string; values: { value: string; swatch?: unknown | null }[] };\n\n/** The picker an option gets by default. */\nexport type PickerKind = 'swatch' | 'buttons' | 'dropdown';\n\n/** More values than this and a row of buttons stops being usable: a dropdown takes over. */\nexport const DROPDOWN_ABOVE = 8;\n\n/**\n * `swatch` when every value has a swatch, `dropdown` when there are more than\n * 8 values, else `buttons`. An option with no values is `buttons`.\n */\nexport function pickerKind(option: PickerOption): PickerKind {\n const { values } = option;\n if (values.length > 0 && values.every((v) => v.swatch !== undefined && v.swatch !== null)) return 'swatch';\n return values.length > DROPDOWN_ABOVE ? 'dropdown' : 'buttons';\n}\n\nconst optionsOf = (variant: Variant): Record<string, string> => variant.options ?? {};\n\n/** True when the variant carries every `name: value` of `selection`. */\nconst matches = (variant: Variant, selection: Record<string, string>): boolean => {\n const own = optionsOf(variant);\n return Object.entries(selection).every(([name, value]) => own[name] === value);\n};\n\n/** A variant that cannot be bought: out of stock, or not purchasable (no price in the currency, for one). */\nexport const isSoldOut = (variant: Variant): boolean => variant.availability === 'out_of_stock' || !variant.purchasable;\n\n/** The variant `selection` names, or undefined for a combination the product does not make. */\nexport function variantForSelection(product: Pick<StorefrontProduct, 'variants'>, selection: Record<string, string>): Variant | undefined {\n return product.variants.find((v) => matches(v, selection));\n}\n\n/**\n * The variant to show: the one `sku` names, else the first that can be bought,\n * else the first one.\n */\nexport function pickVariant(product: Pick<StorefrontProduct, 'variants'>, sku: string | null | undefined): Variant | undefined {\n const { variants } = product;\n return variants.find((v) => v.sku === sku) ?? variants.find((v) => !isSoldOut(v)) ?? variants[0];\n}\n\n/**\n * What choosing `name = value` gives, with the other choices kept. A\n * combination that is sold out is still a choice (`soldOut`, with its `sku`);\n * one the product does not make has no `sku`.\n */\nexport function selectOption(\n product: Pick<StorefrontProduct, 'variants'>,\n current: Record<string, string>,\n name: string,\n value: string,\n): { selection: Record<string, string>; sku: string | null; soldOut: boolean } {\n const selection = { ...current, [name]: value };\n const variant = variantForSelection(product, selection);\n return { selection, sku: variant?.sku ?? null, soldOut: variant ? isSoldOut(variant) : false };\n}\n\n/**\n * The variant to land on when `name = value` does not go with the other\n * choices: among the variants that have the value, the one that keeps the most\n * of the other choices (a buyable one first on a tie).\n */\nexport function nearestVariant(\n product: Pick<StorefrontProduct, 'variants'>,\n current: Record<string, string>,\n name: string,\n value: string,\n): Variant | undefined {\n const others = Object.entries(current).filter(([k]) => k !== name);\n let best: { variant: Variant; kept: number } | undefined;\n for (const variant of product.variants) {\n const own = optionsOf(variant);\n if (own[name] !== value) continue;\n const kept = others.filter(([k, v]) => own[k] === v).length;\n const better = !best || kept > best.kept || (kept === best.kept && isSoldOut(best.variant) && !isSoldOut(variant));\n if (better) best = { variant, kept };\n }\n return best?.variant;\n}\n\n/** How a value stands against the current choices of the other options. */\nexport type ValueState = 'available' | 'sold-out' | 'unavailable';\n\nexport function valueState(\n product: Pick<StorefrontProduct, 'variants'>,\n current: Record<string, string>,\n name: string,\n value: string,\n): ValueState {\n const result = selectOption(product, current, name, value);\n if (result.sku === null) return 'unavailable';\n return result.soldOut ? 'sold-out' : 'available';\n}\n\n/** What the buy box says about a variant. */\nexport type Stock = 'in_stock' | 'low' | 'preorder' | 'backorder' | 'out' | 'no_currency';\n\n/** Not sold in the shopper's currency first, then sold out, then the stock state. */\nexport function stockOf(product: Pick<StorefrontProduct, 'availableInCurrency'>, variant: Variant): Stock {\n if (product.availableInCurrency === false || variant.priceMinor === null) return 'no_currency';\n if (isSoldOut(variant)) return 'out';\n if (variant.availability === 'preorder') return 'preorder';\n if (variant.availability === 'backorder') return 'backorder';\n return variant.lowStock ? 'low' : 'in_stock';\n}\n\n/** The quantity limits of a variant: the minimum is always 1, the maximum is the variant's own limit when it has one. */\nexport function quantityBounds(variant: Variant | undefined): { min: 1; max: number | undefined } {\n const max = variant?.maxOrderQuantity;\n return { min: 1, max: typeof max === 'number' && max >= 1 ? Math.floor(max) : undefined };\n}\n\n/** A quantity held to the bounds; anything that is not a number is the minimum. */\nexport function clampQuantity(value: number, max: number | undefined): number {\n const whole = Number.isFinite(value) ? Math.floor(value) : 1;\n return Math.min(max ?? Number.POSITIVE_INFINITY, Math.max(1, whole));\n}\n","import { isCatalogError, type ListProduct, type StorefrontProduct } from '@usethrottle/catalog';\nimport { useCart } from '@usethrottle/catalog/react';\nimport { toDecimalString } from '@usethrottle/money';\nimport { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react';\nimport type { MutableRefObject } from 'react';\nimport { toGa4Item } from '../analytics/items';\nimport { useTrack } from '../analytics/use-track';\nimport type { PriceContext } from '../pieces/Price';\nimport { useStorefront } from '../provider/context';\nimport { useStrings } from '../strings';\nimport type { ProductData } from '../server/types';\nimport { variantFromSearch } from '../url/shop-query';\nimport {\n clampQuantity, nearestVariant, pickVariant, quantityBounds, selectOption as chooseOption, stockOf,\n type Stock, type Variant,\n} from './variant-logic';\n\n/** The product page's arrangement: `classic` (gallery beside the buy box), `stacked` or `editorial`. */\nexport type ProductLayout = 'classic' | 'stacked' | 'editorial';\n\n/** The reviews section: the summary above the list (`stack`), or beside it from 768 px (`columns`). */\nexport type ReviewsLayout = 'stack' | 'columns';\n/** How the sections are drawn: `tabs`, `accordion`, `stacked`, or `auto` (tabs, accordions under 768 px). */\nexport type SectionsStyle = 'auto' | 'tabs' | 'accordion' | 'stacked';\n\n/** What an add to the cart last said. */\nexport type AddMessage = { tone: 'ok' | 'refused'; text: string };\n\n/**\n * What `useProductPage()` answers inside a product page: the product, the chosen variant and options, stock, the quantity and `add()`.\n */\nexport type ProductPageValue = {\n product: StorefrontProduct;\n /** The product answer's price context (`customer` for a signed-in shopper's own price). */\n priceContext: PriceContext | undefined;\n /** The chosen value of each option. */\n selection: Record<string, string>;\n /** The chosen variant's SKU; null for a product with no variants. */\n sku: string | null;\n variant: Variant | undefined;\n stock: Stock | null;\n /** Chooses `name = value`. A value that does not go with the other choices lands on the nearest variant that has it. */\n selectOption(name: string, value: string): void;\n quantity: number;\n /** Held to 1 and the variant's `maxOrderQuantity`. */\n setQuantity(quantity: number): void;\n maxQuantity: number | undefined;\n add(): Promise<void>;\n adding: boolean;\n message: AddMessage | null;\n layout: ProductLayout;\n sectionsStyle: SectionsStyle;\n reviewsLayout: ReviewsLayout;\n /** The related products the server sent; undefined without server data. */\n related: ListProduct[] | undefined;\n /** When the server built the data (ISO), for the `new` badge. */\n generatedAt: string | undefined;\n /** Absolute origin of the store for JSON-LD links; empty makes them site-relative. */\n baseUrl: string;\n /** The first page of reviews the server loaded (`null`: none to show); undefined when it did not ask. */\n initialReviews: ProductData['reviews'];\n /** The shipping page's body the server loaded (`null`: missing); undefined when it did not ask. */\n shippingPage: ProductData['shippingPage'];\n /** One id for this page's sections, so two product pages in one document (a quick view) never share ids. */\n sectionsId: string;\n /** The main AddToCart sets this so the sticky bar knows when it leaves the viewport. */\n addToCartRef: MutableRefObject<HTMLElement | null>;\n /** `ProductSections` sets this: shows a section (opens its tab or accordion) and says whether it has one. */\n revealSectionRef: MutableRefObject<((key: string) => boolean) | null>;\n};\n\nexport const ProductPageContext = createContext<ProductPageValue | null>(null);\n\n/** The product page state: the product, the chosen variant and quantity, and `add()`. Throws outside `ProductPage.Root`. */\nexport function useProductPage(): ProductPageValue {\n const value = useContext(ProductPageContext);\n if (!value) throw new Error('useProductPage() was called outside <ProductPage.Root>.');\n return value;\n}\n\nconst decimal = (minor: number, currency: string): number => Number(toDecimalString(minor, currency));\n\n/** The SDK's `CartLineError` (here or from another copy of it) carries the refused lines. */\nfunction refusedLine(error: unknown, sku: string): { maxQuantity?: number } | null {\n if (!isCatalogError(error)) return null;\n const lines = (error as unknown as { lines?: { sku: string; maxQuantity?: number }[] }).lines;\n if (!Array.isArray(lines)) return null;\n return lines.find((l) => l.sku === sku) ?? lines[0] ?? null;\n}\n\nexport type ProductPageStateInput = {\n product: StorefrontProduct;\n priceContext: PriceContext | undefined;\n /** The variant the server read from `?variant=`. */\n initialSku: string | null;\n related: ListProduct[] | undefined;\n generatedAt: string | undefined;\n reviews?: ProductData['reviews'];\n shippingPage?: ProductData['shippingPage'];\n layout: ProductLayout;\n sectionsStyle: SectionsStyle;\n reviewsLayout?: ReviewsLayout;\n baseUrl: string;\n};\n\n/**\n * The state behind `ProductPage.Root`. The URL names the variant\n * (`?variant=<sku>`, written with `router.replace`); until the shopper\n * chooses, the URL's variant, else the server's reading, else the first one\n * that can be bought, is the variant.\n */\nexport function useProductPageState(input: ProductPageStateInput): ProductPageValue {\n const { product, priceContext, initialSku } = input;\n const { router, currency: storeCurrency } = useStorefront();\n const { t } = useStrings();\n const track = useTrack();\n const cart = useCart(storeCurrency ? { currency: storeCurrency } : undefined);\n const sectionsId = useId();\n const addToCartRef = useRef<HTMLElement | null>(null);\n const revealSectionRef = useRef<((key: string) => boolean) | null>(null);\n\n const urlSku = variantFromSearch(router.searchParams, product);\n const [chosen, setChosen] = useState<string | null>(null);\n // A change of the URL's own variant (a link, the back button) hands the choice back to the URL.\n useEffect(() => {\n setChosen(null);\n }, [urlSku, product.handle]);\n\n const variant = pickVariant(product, chosen ?? urlSku ?? initialSku);\n const sku = variant?.sku ?? null;\n const selection = useMemo(() => ({ ...(variant?.options ?? {}) }), [variant]);\n const stock = variant ? stockOf(product, variant) : null;\n\n const selectOption = useCallback(\n (name: string, value: string) => {\n const result = chooseOption(product, selection, name, value);\n const next = result.sku ?? nearestVariant(product, selection, name, value)?.sku ?? null;\n if (next === null) return;\n setChosen(next);\n const params = new URLSearchParams(router.searchParams.toString());\n params.set('variant', next);\n router.replace(`${router.pathname}?${params.toString()}`, { scroll: false });\n },\n [product, selection, router],\n );\n\n const maxQuantity = quantityBounds(variant).max;\n const [wanted, setWanted] = useState(1);\n const quantity = clampQuantity(wanted, maxQuantity);\n const setQuantity = useCallback((n: number) => setWanted(clampQuantity(n, maxQuantity)), [maxQuantity]);\n\n const eventCurrency = variant?.currency ?? product.priceRange?.currency ?? storeCurrency;\n const unitMinor = variant ? (variant.salePriceMinor ?? variant.priceMinor) : null;\n\n // view_item: once for each variant the shopper looks at.\n const seen = useRef(new Set<string>());\n useEffect(() => {\n if (!sku || !eventCurrency || seen.current.has(sku)) return;\n seen.current.add(sku);\n track('view_item', {\n currency: eventCurrency,\n ...(unitMinor !== null ? { value: decimal(unitMinor, eventCurrency) } : {}),\n items: [toGa4Item(product, { variantSku: sku })],\n });\n }, [sku, eventCurrency, unitMinor, product, track]);\n\n const [adding, setAdding] = useState(false);\n const [message, setMessage] = useState<AddMessage | null>(null);\n const title = product.title ?? product.handle;\n\n const add = useCallback(async () => {\n if (!sku || adding) return;\n setAdding(true);\n setMessage(null);\n try {\n await cart.add(sku, quantity);\n if (eventCurrency) {\n track('add_to_cart', {\n currency: eventCurrency,\n ...(unitMinor !== null ? { value: decimal(unitMinor * quantity, eventCurrency) } : {}),\n items: [toGa4Item(product, { variantSku: sku, quantity })],\n });\n }\n setMessage({ tone: 'ok', text: t('product.cartAdd.added', { quantity, title }) });\n } catch (error) {\n // A sign-out cancels the change; there is nothing to say.\n if (error instanceof DOMException && error.name === 'AbortError') return;\n const line = refusedLine(error, sku);\n const left = line?.maxQuantity;\n setMessage({\n tone: 'refused',\n text:\n left === 0\n ? t('product.cartAdd.outOfStock')\n : typeof left === 'number'\n ? t('product.cartAdd.onlyLeft', { count: left })\n : t('product.cartAdd.failed'),\n });\n } finally {\n setAdding(false);\n }\n }, [sku, adding, cart, quantity, eventCurrency, unitMinor, product, title, track, t]);\n\n return {\n product, priceContext, selection, sku, variant, stock, selectOption, quantity, setQuantity, maxQuantity,\n add, adding, message, layout: input.layout, sectionsStyle: input.sectionsStyle, reviewsLayout: input.reviewsLayout ?? 'stack', related: input.related,\n generatedAt: input.generatedAt, baseUrl: input.baseUrl, addToCartRef, revealSectionRef,\n initialReviews: input.reviews, shippingPage: input.shippingPage, sectionsId,\n };\n}\n","import { Spinner } from '@usethrottle/ui';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { useStrings } from '../strings';\nimport { useProductPage } from './use-product-page';\n\n/**\n * The add button and what an add said. The add sends the SKU and the quantity\n * only: the price is the catalog's, never the browser's. While an add runs the\n * button is `aria-disabled` (not `disabled`), so it keeps keyboard focus; it is\n * `disabled` only when pressing cannot help (sold out, no price in the currency).\n */\nexport function AddToCart({ classNames, className, unstyled }: UsePartLocal) {\n const local = { classNames, unstyled };\n const { add, adding, stock, sku, message, addToCartRef } = useProductPage();\n const { t } = useStrings();\n const root = usePart('add-to-cart', { ...local, className });\n const button = usePart('add-to-cart-button', local);\n const status = usePart('add-to-cart-message', local);\n const cannot = !sku || stock === 'out' || stock === 'no_currency';\n\n return (\n <div {...root} ref={(el) => { addToCartRef.current = el; }}>\n <button\n {...button}\n type=\"button\"\n disabled={cannot}\n aria-disabled={adding || undefined}\n aria-busy={adding || undefined}\n data-adding={adding ? 'true' : undefined}\n onClick={() => {\n if (!adding) void add();\n }}\n >\n {adding ? <Spinner /> : null}\n {adding ? t('product.cartAdd.adding') : t('product.addToCart')}\n </button>\n <p {...status} role=\"status\" aria-live=\"polite\" data-tone={message?.tone}>\n {message?.text}\n </p>\n </div>\n );\n}\n","import type { StorefrontProduct } from '@usethrottle/catalog';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { useStorefront } from '../provider/context';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport { useStrings } from '../strings';\nimport { routeHref } from '../url/routes';\nimport { useProductPage } from './use-product-page';\n\n/** One step of a product's trail: a name and a site-relative link. */\nexport type ProductCrumb = { name: string; href: string };\n\n/**\n * The trail to a product, site-relative: the store (its name, or `homeLabel`),\n * the category trail the catalog answers, then the product itself.\n */\nexport function productCrumbs(\n product: Pick<StorefrontProduct, 'title' | 'handle' | 'breadcrumbs'>,\n settings: NormalizedSettings,\n homeLabel: string,\n): ProductCrumb[] {\n return [\n { name: settings.brand.storeName.trim() || homeLabel, href: '/' },\n ...(product.breadcrumbs ?? []).map((c) => ({ name: c.name, href: routeHref(settings, 'category', c.handle) })),\n { name: product.title ?? product.handle, href: routeHref(settings, 'product', product.handle) },\n ];\n}\n\n/** The trail as links with the product last (`aria-current=\"page\"`). */\nexport function Breadcrumbs({ classNames, className, unstyled }: UsePartLocal) {\n const local = { classNames, unstyled };\n const { product } = useProductPage();\n const { settings, Link: Anchor } = useStorefront();\n const { t } = useStrings();\n const root = usePart('product-breadcrumbs', { ...local, className });\n const list = usePart('product-breadcrumbs-list', local);\n const item = usePart('product-breadcrumbs-item', local);\n const link = usePart('product-breadcrumbs-link', local);\n const current = usePart('product-breadcrumbs-current', local);\n const crumbs = productCrumbs(product, settings, t('product.crumbs.home'));\n return (\n <nav {...root} aria-label={t('product.crumbs.label')}>\n <ol {...list}>\n {crumbs.map((crumb, i) => (\n <li {...item} key={`${crumb.href}-${i}`}>\n {i === crumbs.length - 1 ? (\n <span {...current} aria-current=\"page\">\n {crumb.name}\n </span>\n ) : (\n <Anchor {...link} href={crumb.href}>\n {crumb.name}\n </Anchor>\n )}\n </li>\n ))}\n </ol>\n </nav>\n );\n}\n","import { VisuallyHidden } from '@usethrottle/ui';\nimport { useEffect, useId, useState } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { useStrings } from '../strings';\nimport { useProductPage } from './use-product-page';\nimport { clampQuantity } from './variant-logic';\n\n/**\n * The quantity: a number field with one-fewer and one-more buttons. The\n * minimum is always 1; the maximum is the variant's `maxOrderQuantity` (none\n * without it). What is typed is held to those bounds at once; an empty field\n * is allowed while typing and returns to the quantity on blur.\n */\nexport function QuantityInput({ classNames, className, unstyled }: UsePartLocal) {\n const local = { classNames, unstyled };\n const { quantity, setQuantity, maxQuantity, stock } = useProductPage();\n const { t } = useStrings();\n const id = useId();\n const root = usePart('quantity-input', { ...local, className });\n const decrease = usePart('quantity-decrease', local);\n const field = usePart('quantity-field', local);\n const increase = usePart('quantity-increase', local);\n const [text, setText] = useState(String(quantity));\n useEffect(() => setText(String(quantity)), [quantity]);\n const disabled = stock === 'out' || stock === 'no_currency';\n\n return (\n <div {...root}>\n <label htmlFor={id}>\n <VisuallyHidden>{t('product.quantity')}</VisuallyHidden>\n </label>\n <button\n {...decrease}\n type=\"button\"\n aria-label={t('product.quantityInput.decrease')}\n disabled={disabled}\n aria-disabled={quantity <= 1 || undefined}\n onClick={() => quantity > 1 && setQuantity(quantity - 1)}\n >\n −\n </button>\n <input\n {...field}\n id={id}\n type=\"number\"\n inputMode=\"numeric\"\n min={1}\n max={maxQuantity}\n value={text}\n disabled={disabled}\n onChange={(e) => {\n const raw = e.target.value;\n if (raw === '') return setText('');\n const n = Number.parseInt(raw, 10);\n if (Number.isNaN(n)) return;\n const held = clampQuantity(n, maxQuantity);\n setText(String(held));\n setQuantity(held);\n }}\n onBlur={() => setText(String(quantity))}\n />\n <button\n {...increase}\n type=\"button\"\n aria-label={t('product.quantityInput.increase')}\n disabled={disabled}\n aria-disabled={(maxQuantity !== undefined && quantity >= maxQuantity) || undefined}\n onClick={() => (maxQuantity === undefined || quantity < maxQuantity) && setQuantity(quantity + 1)}\n >\n +\n </button>\n </div>\n );\n}\n","import type { NormalizedSettings } from '../settings/normalize';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { useStorefront } from '../provider/context';\nimport { useStrings } from '../strings';\nimport { useProductPage } from './use-product-page';\nimport type { Stock } from './variant-logic';\n\nexport type StockWordKey = keyof NormalizedSettings['stock']['words'];\n\n/** The `stock.words` key of each state that has a word. */\nconst WORD_KEY: Record<Exclude<Stock, 'no_currency'>, StockWordKey> = {\n in_stock: 'inStock',\n low: 'lowStock',\n preorder: 'preorder',\n backorder: 'backorder',\n out: 'outOfStock',\n};\n\nconst ENGLISH: Record<StockWordKey, string> = {\n inStock: 'In stock',\n lowStock: 'Only a few left',\n outOfStock: 'Out of stock',\n backorder: 'Available on backorder',\n preorder: 'Pre-order',\n};\n\n/**\n * The store's word for a stock state (`settings.stock.words`). `{count}` fills\n * when the caller knows a count; the catalog's product answer carries none, so\n * a word that needs one falls back to the low-stock badge's label rather than\n * show a bare placeholder. An empty word is the English default.\n */\nexport function stockWord(settings: Pick<NormalizedSettings, 'stock' | 'badges'>, key: StockWordKey, count?: number): string {\n const word = settings.stock.words[key].trim() || ENGLISH[key];\n if (!word.includes('{count}')) return word;\n if (count !== undefined) return word.split('{count}').join(String(count));\n return settings.badges.lowStock.label.trim() || ENGLISH.lowStock;\n}\n\n/** The chosen variant's availability in the merchant's words, with `data-stock-words` naming which word. */\nexport function StockStatus({ classNames, className, unstyled }: UsePartLocal) {\n const { stock, variant } = useProductPage();\n const { settings, currency } = useStorefront();\n const { t } = useStrings();\n const part = usePart('stock-status', { classNames, className, unstyled });\n const state: Stock = stock ?? 'out';\n const shown = variant?.currency ?? currency;\n const text =\n state === 'no_currency'\n ? shown\n ? t('product.stockStatus.noCurrency', { currency: shown })\n : t('product.stockStatus.noCurrencyAny')\n : stockWord(settings, WORD_KEY[state]);\n return (\n <p {...part} data-state={state} data-stock-words={state === 'no_currency' ? undefined : WORD_KEY[state]}>\n {text}\n </p>\n );\n}\n","import type { StorefrontProduct } from '@usethrottle/catalog';\nimport { Select, VisuallyHidden } from '@usethrottle/ui';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { Swatch } from '../pieces/Swatch';\nimport { useStrings } from '../strings';\nimport { useProductPage } from './use-product-page';\nimport { pickerKind, valueState, type PickerKind } from './variant-logic';\n\ntype Option = NonNullable<StorefrontProduct['options']>[number];\ntype Local = Pick<UsePartLocal, 'classNames' | 'unstyled'>;\n\n/** The swatch of a value as a `Swatch` takes it. */\nconst swatchProps = (swatch: Option['values'][number]['swatch']): { hex?: string; image?: string } =>\n !swatch ? {} : 'color' in swatch ? { hex: swatch.color } : { image: swatch.url };\n\nfunction OptionGroup({ option, kind, ...local }: Local & { option: Option; kind: PickerKind }) {\n const { product, selection, selectOption } = useProductPage();\n const { t } = useStrings();\n const group = usePart('variant-option', local);\n const legend = usePart('variant-option-legend', local);\n const nameOf = usePart('variant-option-name', local);\n const chosenOf = usePart('variant-option-chosen', local);\n const values = usePart('variant-option-values', local);\n const value = usePart('variant-value', local);\n const label = usePart('variant-value-label', local);\n const chosen = selection[option.name];\n const others = Object.entries(selection)\n .filter(([name]) => name !== option.name)\n .map(([, v]) => v)\n .join(' / ');\n\n if (kind === 'dropdown') {\n return (\n <div {...group} data-option-name={option.name} data-picker={kind}>\n <Select\n label={option.name}\n value={chosen ?? ''}\n placeholder={chosen === undefined ? t('product.options.chooseOne', { option: option.name }) : undefined}\n options={option.values.map((v) => {\n const state = valueState(product, selection, option.name, v.value);\n return { value: v.value, label: state === 'sold-out' ? `${v.value}${t('product.options.soldOut')}` : v.value };\n })}\n onChange={(next) => next !== '' && selectOption(option.name, next)}\n />\n </div>\n );\n }\n\n return (\n <fieldset {...group} data-option-name={option.name} data-picker={kind}>\n <legend {...legend}>\n <span {...nameOf}>{option.name}</span>\n {chosen ? <span {...chosenOf}>{chosen}</span> : null}\n </legend>\n <div {...values}>\n {option.values.map((v) => {\n const state = valueState(product, selection, option.name, v.value);\n const pressed = chosen === v.value;\n return (\n <button\n {...value}\n key={v.value}\n type=\"button\"\n data-value={v.value}\n data-kind={kind}\n aria-pressed={pressed}\n // Sold out and not made with the other choices are still presses: the first is a variant, the second moves the others.\n aria-disabled={false}\n data-sold-out={state === 'sold-out' ? '' : undefined}\n data-unavailable={state === 'unavailable' ? '' : undefined}\n onClick={() => selectOption(option.name, v.value)}\n >\n {kind === 'swatch' ? <Swatch {...local} {...swatchProps(v.swatch)} value={v.value} selected={pressed} /> : <span {...label}>{v.value}</span>}\n {state === 'sold-out' ? <VisuallyHidden>{t('product.options.soldOut')}</VisuallyHidden> : null}\n {state === 'unavailable' ? <VisuallyHidden>{t('product.options.unavailableWith', { others: others || option.name })}</VisuallyHidden> : null}\n </button>\n );\n })}\n </div>\n </fieldset>\n );\n}\n\n/**\n * One group per option of the product, each a swatch row, a button row or a\n * dropdown by `pickerKind`. Every value can be pressed: one that is sold out\n * with the other choices is marked `data-sold-out` (drawn crossed out) and\n * still selects it; one the product does not make with them (`data-unavailable`)\n * moves the other choices to the nearest variant that has it.\n */\nexport function VariantPicker({ classNames, className, unstyled }: UsePartLocal) {\n const { product } = useProductPage();\n const root = usePart('variant-picker', { classNames, className, unstyled });\n const options = product.options ?? [];\n if (options.length === 0) return null;\n return (\n <div {...root}>\n {options.map((option) => (\n <OptionGroup key={option.name} option={option} kind={pickerKind(option)} classNames={classNames} unstyled={unstyled} />\n ))}\n </div>\n );\n}\n","import type { StorefrontProduct } from '@usethrottle/catalog';\nimport type { ComponentType } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { BackInStock, WishlistButton } from '../pieces/reserved';\nimport { Price, type PriceProps } from '../pieces/Price';\nimport { StarRating } from '../pieces/StarRating';\nimport { useStorefront } from '../provider/context';\nimport { useStrings } from '../strings';\nimport { AddToCart } from './AddToCart';\nimport { QuantityInput } from './QuantityInput';\nimport { StockStatus } from './StockStatus';\nimport { useProductPage } from './use-product-page';\nimport { VariantPicker } from './VariantPicker';\nimport type { Variant } from './variant-logic';\n\ntype Local = Pick<UsePartLocal, 'classNames' | 'unstyled'>;\n\n/** What the reserved places (wishlist, back in stock) are given. */\nexport type ReservedSlotProps = Local & {\n /** The product on the page. */\n product: StorefrontProduct;\n /** The chosen variant, or `undefined` for a product with none. */\n variant: Variant | undefined;\n};\n\n/** The pieces of the buy box a store may replace. Each takes the props its default takes. */\nexport type BuyBoxSlots = {\n Price: ComponentType<PriceProps>;\n VariantPicker: ComponentType<UsePartLocal>;\n StockStatus: ComponentType<UsePartLocal>;\n QuantityInput: ComponentType<UsePartLocal>;\n AddToCart: ComponentType<UsePartLocal>;\n WishlistButton: ComponentType<ReservedSlotProps>;\n BackInStock: ComponentType<ReservedSlotProps>;\n};\n\nconst DEFAULT_SLOTS: BuyBoxSlots = { Price, VariantPicker, StockStatus, QuantityInput, AddToCart, WishlistButton, BackInStock };\n\n/** The buy box: title, price, options, quantity and add to cart. */\nexport type BuyBoxProps = UsePartLocal & {\n /**\n * Replace any piece of the buy box (`Price`, `VariantPicker`, `StockStatus`, `QuantityInput`, `AddToCart`, `WishlistButton`, `BackInStock`).\n */\n slots?: Partial<BuyBoxSlots>;\n /** The product title's heading level (default 1, the page's own heading). A modal that has its own title uses 2. */\n headingLevel?: 1 | 2 | 3 | 4 | 5 | 6;\n};\n\n/**\n * The buy box: title, rating, price, options, availability, quantity and add\n * to cart, of the chosen variant. Each piece can be replaced through `slots`.\n * The price is the variant's own (`priceContext` says whose); it is never computed here.\n */\nexport function BuyBox({ slots, classNames, className, unstyled, headingLevel = 1 }: BuyBoxProps) {\n const Heading = `h${headingLevel}` as const;\n const local = { classNames, unstyled };\n const s = { ...DEFAULT_SLOTS, ...slots };\n const { product, variant, priceContext, revealSectionRef, sectionsId } = useProductPage();\n const { settings, currency } = useStorefront();\n const { t, keyAttr } = useStrings();\n const root = usePart('buy-box', { ...local, className });\n const kicker = usePart('buy-box-kicker', local);\n const title = usePart('buy-box-title', local);\n const ratingLink = usePart('buy-box-rating', local);\n const summary = usePart('buy-box-summary', local);\n const priceRow = usePart('buy-box-price', local);\n const sku = usePart('buy-box-sku', local);\n const actions = usePart('buy-box-actions', local);\n\n const kickerText = [product.productType, product.brand].filter(Boolean).join(' · ');\n const rating = product.rating;\n const showRating =\n rating && rating.count > 0 && rating.average !== null && settings.product.sections.some((x) => x.key === 'reviews' && x.enabled);\n const now = variant ? (variant.salePriceMinor ?? variant.priceMinor) : null;\n const was = variant ? (variant.salePriceMinor !== null && variant.priceMinor !== null ? variant.priceMinor : (variant.compareAtPriceMinor ?? undefined)) : undefined;\n const priced = variant?.currency ?? currency;\n\n return (\n <div {...root}>\n {kickerText ? <p {...kicker}>{kickerText}</p> : null}\n <Heading {...title}>{product.title ?? product.handle}</Heading>\n {showRating ? (\n <a\n {...ratingLink}\n href={`#${sectionsId}-panel-reviews`}\n onClick={(e) => {\n // Opens the reviews tab or accordion first; without sections the link is a plain anchor.\n if (revealSectionRef.current?.('reviews')) {\n e.preventDefault();\n requestAnimationFrame(() => document.getElementById(`${sectionsId}-panel-reviews`)?.scrollIntoView({ block: 'start' }));\n }\n }}\n >\n <StarRating {...local} value={rating.average!} count={rating.count} />\n </a>\n ) : null}\n {product.shortDescription ? <p {...summary}>{product.shortDescription}</p> : null}\n {now !== null && priced ? (\n <p {...priceRow}>\n <s.Price {...local} minor={now} currency={priced} compareAtMinor={was ?? undefined} priceContext={priceContext} />\n </p>\n ) : null}\n <s.VariantPicker {...local} />\n <s.StockStatus {...local} />\n {variant ? (\n <p {...sku}>\n <span {...keyAttr('product.sku')}>{t('product.sku')}</span> {variant.sku}\n </p>\n ) : null}\n <div {...actions}>\n <s.QuantityInput {...local} />\n <s.AddToCart {...local} />\n <s.WishlistButton {...local} product={product} variant={variant} />\n <s.BackInStock {...local} product={product} variant={variant} />\n </div>\n </div>\n );\n}\n\n","import { usePart, type UsePartLocal } from '../parts';\nimport { useStorefront } from '../provider/context';\nimport { routeHref } from '../url/routes';\nimport { useProductPage } from './use-product-page';\n\n/** The product's categories, each a link to its category page. Nothing without categories. */\nexport function CategoryList({ classNames, className, unstyled }: UsePartLocal) {\n const local = { classNames, unstyled };\n const { product } = useProductPage();\n const { settings, Link: Anchor } = useStorefront();\n const root = usePart('category-list', { ...local, className });\n const item = usePart('category-list-item', local);\n const link = usePart('category-list-link', local);\n const categories = product.categories ?? [];\n if (categories.length === 0) return null;\n return (\n <ul {...root}>\n {categories.map((category) => (\n <li {...item} key={category.id} data-category-handle={category.handle}>\n <Anchor {...link} href={routeHref(settings, 'category', category.handle)}>\n {category.name}\n </Anchor>\n </li>\n ))}\n </ul>\n );\n}\n","import { Icon } from '@usethrottle/ui';\nimport { lazy, Suspense, useEffect, useRef, useState } from 'react';\nimport type { KeyboardEvent, PointerEvent } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { Image } from '../pieces/Image';\nimport { useStorefront } from '../provider/context';\nimport { useStrings } from '../strings';\nimport { galleryItems, isVideo, ratioOf, srcSetOf } from './gallery-items';\nimport { useProductPage } from './use-product-page';\n\nconst Lightbox = lazy(() => import('./Lightbox'));\n\n/** The product's photos and videos. Takes the styling props only; the media come from the page's product. */\nexport type GalleryProps = UsePartLocal;\n\nconst SWIPE_PX = 40;\nconst STAGE_SIZES = '(min-width: 1024px) 50vw, 100vw';\n\n/**\n * The product's photos: the one shown, thumbnails, previous and next, a swipe\n * on touch, a zoom under a mouse, and a lightbox (loaded on first use). A\n * media item of `kind: 'video'` plays in place. Choosing a variant shows its\n * photo. The arrow keys move between photos (inverted in a right-to-left page).\n */\nexport function Gallery({ classNames, className, unstyled }: GalleryProps) {\n const local = { classNames, unstyled };\n const { product, variant } = useProductPage();\n const { dir } = useStorefront();\n const { t } = useStrings();\n const items = galleryItems(product);\n const count = items.length;\n const title = product.title ?? product.handle;\n\n const indexOfVariant = () => {\n const url = variant?.image?.url ?? variant?.images[0]?.url;\n const at = url ? items.findIndex((i) => i.url === url) : -1;\n return at >= 0 ? at : 0;\n };\n const [active, setActive] = useState(indexOfVariant);\n const [open, setOpen] = useState(false);\n const [zoom, setZoom] = useState<{ x: number; y: number } | null>(null);\n const start = useRef<{ x: number; moved: boolean } | null>(null);\n // Pointer moves are many a frame: the latest point waits in a ref and one frame turns it into state.\n const zoomAt = useRef<{ x: number; y: number } | null>(null);\n const frame = useRef(0);\n const stopZoom = () => {\n cancelAnimationFrame(frame.current);\n frame.current = 0;\n zoomAt.current = null;\n setZoom(null);\n };\n useEffect(() => () => cancelAnimationFrame(frame.current), []);\n\n // A new variant brings its own photo into view (not on the first render).\n const first = useRef(true);\n const sku = variant?.sku;\n useEffect(() => {\n if (first.current) {\n first.current = false;\n return;\n }\n setActive(indexOfVariant());\n }, [sku]);\n\n const root = usePart('gallery', { ...local, className });\n const stage = usePart('gallery-stage', local);\n const itemPart = usePart('gallery-item', local);\n const video = usePart('gallery-video', local);\n const placeholder = usePart('gallery-placeholder', local);\n const previous = usePart('gallery-previous', local);\n const next = usePart('gallery-next', local);\n const enlarge = usePart('gallery-enlarge', local);\n const counter = usePart('gallery-counter', local);\n const thumbs = usePart('gallery-thumbs', local);\n const thumbItem = usePart('gallery-thumbs-item', local);\n const thumb = usePart('gallery-thumb', local);\n\n const go = (delta: number) => count > 0 && setActive((a) => (a + delta + count) % count);\n const current = items[active];\n\n const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {\n const forward = dir === 'rtl' ? 'ArrowLeft' : 'ArrowRight';\n const backward = dir === 'rtl' ? 'ArrowRight' : 'ArrowLeft';\n if (e.key === forward) go(1);\n else if (e.key === backward) go(-1);\n else if (e.key === 'Home') setActive(0);\n else if (e.key === 'End') setActive(count - 1);\n else return;\n e.preventDefault();\n };\n\n const onPointerDown = (e: PointerEvent<HTMLElement>) => {\n start.current = { x: e.clientX, moved: false };\n };\n const onPointerMove = (e: PointerEvent<HTMLElement>) => {\n if (e.pointerType === 'mouse' && current && !isVideo(current)) {\n const box = e.currentTarget.getBoundingClientRect();\n if (box.width > 0 && box.height > 0) {\n zoomAt.current = { x: ((e.clientX - box.left) / box.width) * 100, y: ((e.clientY - box.top) / box.height) * 100 };\n if (!frame.current) {\n frame.current = requestAnimationFrame(() => {\n frame.current = 0;\n if (zoomAt.current) setZoom(zoomAt.current);\n });\n }\n }\n }\n if (start.current && Math.abs(e.clientX - start.current.x) > 10) start.current.moved = true;\n };\n const onPointerUp = (e: PointerEvent<HTMLElement>) => {\n const from = start.current;\n start.current = null;\n if (!from) return;\n const dx = e.clientX - from.x;\n if (Math.abs(dx) >= SWIPE_PX) go((dir === 'rtl' ? dx > 0 : dx < 0) ? 1 : -1);\n };\n const onClick = () => {\n // A drag is not a click.\n if (start.current?.moved) return;\n if (current && !isVideo(current)) setOpen(true);\n };\n\n return (\n <section {...root} aria-label={t('product.gallery.label', { title })}>\n <div\n {...stage}\n tabIndex={0}\n role=\"group\"\n aria-roledescription=\"carousel\"\n aria-label={t('product.gallery.label', { title })}\n onKeyDown={onKeyDown}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onPointerLeave={() => {\n stopZoom();\n start.current = null;\n }}\n onClick={onClick}\n >\n {current ? (\n <div {...itemPart} data-index={active} data-zoomed={zoom ? 'true' : undefined} style={zoom ? { transformOrigin: `${zoom.x}% ${zoom.y}%` } : undefined}>\n {isVideo(current) ? (\n <video {...video} src={current.url} controls playsInline preload=\"metadata\" aria-label={t('product.gallery.video', { title })} />\n ) : (\n <Image\n {...local}\n src={current.url}\n alt={current.altText ?? t('product.gallery.photoAlt', { title, n: active + 1 })}\n aspectRatio={ratioOf(current)}\n srcSet={srcSetOf(current)}\n sizes={STAGE_SIZES}\n priority={active === 0}\n />\n )}\n </div>\n ) : (\n <div {...placeholder} />\n )}\n {count > 1 ? (\n <>\n <button {...previous} type=\"button\" aria-label={t('product.gallery.previous')} onClick={(e) => { e.stopPropagation(); go(-1); }}>\n <Icon name=\"chevron-left\" size={20} />\n </button>\n <button {...next} type=\"button\" aria-label={t('product.gallery.next')} onClick={(e) => { e.stopPropagation(); go(1); }}>\n <Icon name=\"chevron-right\" size={20} />\n </button>\n {/* `bdi dir=\"ltr\"`: in a right-to-left page \"1 / 5\" would otherwise show as \"5 / 1\". */}\n <p {...counter} aria-live=\"polite\">\n <bdi dir=\"ltr\">{t('product.gallery.counter', { n: active + 1, count })}</bdi>\n </p>\n </>\n ) : null}\n {current && !isVideo(current) ? (\n <button {...enlarge} type=\"button\" aria-label={t('product.gallery.enlarge')} onClick={(e) => { e.stopPropagation(); setOpen(true); }}>\n <Icon name=\"zoom\" size={18} />\n </button>\n ) : null}\n </div>\n {count > 1 ? (\n <ul {...thumbs} aria-label={t('product.gallery.thumbs')}>\n {items.map((item, i) => (\n <li {...thumbItem} key={`${item.url}-${i}`}>\n <button\n {...thumb}\n type=\"button\"\n aria-label={t('product.gallery.showPhoto', { n: i + 1, count })}\n aria-current={i === active ? 'true' : undefined}\n onClick={() => setActive(i)}\n >\n {isVideo(item) && !item.posterUrl ? (\n <Icon name=\"play\" size={20} />\n ) : (\n <Image {...local} src={isVideo(item) ? item.posterUrl! : (item.sizes?.['400'] ?? item.url)} alt=\"\" aspectRatio={ratioOf(item)} />\n )}\n </button>\n </li>\n ))}\n </ul>\n ) : null}\n {open ? (\n <Suspense fallback={null}>\n <Lightbox {...local} open items={items} index={active} title={title} onIndexChange={setActive} onClose={() => setOpen(false)} />\n </Suspense>\n ) : null}\n </section>\n );\n}\n","import { usePart, type UsePartLocal } from '../parts';\nimport { useUnstyled } from '../unstyled';\n\n/** Tags that stay. Anything else is dropped and its text kept, except the elements in `DROP_WITH_CONTENT`. */\nconst ALLOWED_TAGS = new Set([\n 'p', 'br', 'hr', 'div', 'span', 'strong', 'b', 'em', 'i', 'u', 's', 'del', 'ins', 'mark', 'small', 'sub', 'sup',\n 'blockquote', 'pre', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n 'a', 'img', 'figure', 'figcaption',\n 'table', 'caption', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',\n]);\nconst VOID_TAGS = new Set(['br', 'hr', 'img']);\n/** Elements whose content is code or hidden text, never prose: they go whole. */\nconst DROP_WITH_CONTENT = new Set([\n 'script', 'style', 'iframe', 'object', 'embed', 'noscript', 'template', 'textarea', 'title', 'noembed', 'noframes', 'xmp', 'svg', 'math',\n]);\n/** Attributes by tag (`*` is every tag). Nothing else survives: no `on*`, `style`, `class` or `id`. */\nconst ALLOWED_ATTRS: Record<string, readonly string[]> = {\n '*': ['title', 'lang', 'dir'],\n a: ['href', 'target', 'rel'],\n img: ['src', 'alt', 'width', 'height', 'loading'],\n th: ['colspan', 'rowspan', 'scope'],\n td: ['colspan', 'rowspan'],\n};\nconst URL_ATTRS = new Set(['href', 'src']);\nconst SAFE_SCHEME = /^(https?|mailto|tel):/i;\n\nconst NAMED_ENTITIES: Record<string, string> = { colon: ':', tab: '\\t', newline: '\\n', amp: '&', lt: '<', gt: '>', quot: '\"', apos: \"'\", nbsp: ' ' };\n\n/** Decodes the entities that could hide a URL scheme (`java&#x73;cript&colon;`) so the scheme check sees the real text. */\nfunction decodeEntities(value: string): string {\n return value.replace(/&(?:#x([0-9a-f]+)|#(\\d+)|([a-z]+));?/gi, (whole, hex: string, dec: string, name: string) => {\n const code = hex ? Number.parseInt(hex, 16) : dec ? Number.parseInt(dec, 10) : NaN;\n if (!Number.isNaN(code)) return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : '';\n return NAMED_ENTITIES[name.toLowerCase()] ?? whole;\n });\n}\n\n/** A URL a page may follow or load: http(s), mailto, tel, or one with no scheme at all (relative, `#`, `?`). */\nfunction safeUrl(raw: string): string | null {\n // Browsers ignore control characters and spaces inside a scheme; strip them before looking.\n // eslint-disable-next-line no-control-regex -- the control characters are the point: browsers ignore them inside a scheme\n const plain = decodeEntities(raw).replace(/[\\u0000- \\u007f-\\u009f]/g, '');\n if (plain === '') return null;\n if (SAFE_SCHEME.test(plain)) return plain;\n return /^[a-z][a-z0-9+.-]*:/i.test(plain) ? null : decodeEntities(raw).trim();\n}\n\nconst escapeAttr = (value: string) => value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\nconst escapeText = (value: string) => value.replace(/</g, '&lt;').replace(/>/g, '&gt;');\n\nconst TAG_NAME = /[a-z][a-z0-9-]*/iy;\n\ntype Attr = { name: string; value: string };\n\n/** Reads the attributes of one tag from `i` (just after the name) to its `>`. Null when the tag never ends. */\nfunction readTag(html: string, start: number): { attrs: Attr[]; end: number; selfClosing: boolean } | null {\n const attrs: Attr[] = [];\n let i = start;\n for (;;) {\n while (i < html.length && /[\\s/]/.test(html[i]!)) i += 1;\n if (i >= html.length) return null;\n if (html[i] === '>') return { attrs, end: i + 1, selfClosing: /\\/\\s*$/.test(html.slice(start, i)) };\n let name = '';\n while (i < html.length && !/[\\s=/>]/.test(html[i]!)) name += html[i++];\n while (i < html.length && /\\s/.test(html[i]!)) i += 1;\n let value = '';\n if (html[i] === '=') {\n i += 1;\n while (i < html.length && /\\s/.test(html[i]!)) i += 1;\n const quote = html[i];\n if (quote === '\"' || quote === \"'\") {\n const close = html.indexOf(quote, i + 1);\n if (close === -1) return null;\n value = html.slice(i + 1, close);\n i = close + 1;\n } else {\n while (i < html.length && !/[\\s>]/.test(html[i]!)) value += html[i++];\n }\n }\n if (name) attrs.push({ name: name.toLowerCase(), value });\n }\n}\n\n/**\n * Cleans untrusted HTML to an allow-list: known tags with known attributes,\n * `http(s)`/`mailto`/`tel`/relative URLs only, text escaped, every tag closed.\n * Server-safe (no DOM): a tokenizer, not a regex over the whole string.\n */\nexport function sanitizeHtml(html: string, options: { linkClass?: string } = {}): string {\n let out = '';\n const open: string[] = [];\n let i = 0;\n while (i < html.length) {\n const lt = html.indexOf('<', i);\n if (lt === -1) {\n out += escapeText(html.slice(i));\n break;\n }\n out += escapeText(html.slice(i, lt));\n i = lt;\n if (html.startsWith('<!--', i)) {\n const close = html.indexOf('-->', i + 4);\n i = close === -1 ? html.length : close + 3;\n continue;\n }\n const closing = html[i + 1] === '/';\n const nameStart = i + (closing ? 2 : 1);\n TAG_NAME.lastIndex = nameStart;\n const name = TAG_NAME.exec(html)?.[0]?.toLowerCase();\n if (!name) {\n // `<!doctype>`, `<?pi?>`, `<![CDATA[`: a declaration, dropped up to its `>`; a lone `<` is text.\n if (html[i + 1] === '!' || html[i + 1] === '?') {\n const close = html.indexOf('>', i);\n i = close === -1 ? html.length : close + 1;\n } else {\n out += '&lt;';\n i += 1;\n }\n continue;\n }\n const tag = readTag(html, nameStart + name.length);\n if (!tag) break; // an unfinished tag at the end: nothing after it is trusted\n i = tag.end;\n\n if (closing) {\n const at = open.lastIndexOf(name);\n if (at !== -1) {\n while (open.length > at) out += `</${open.pop()}>`;\n }\n continue;\n }\n if (DROP_WITH_CONTENT.has(name)) {\n if (!tag.selfClosing) {\n const close = new RegExp(`</${name}\\\\s*>`, 'ig');\n close.lastIndex = i;\n const found = close.exec(html);\n i = found ? found.index + found[0].length : html.length;\n }\n continue;\n }\n if (!ALLOWED_TAGS.has(name)) continue;\n\n let attrs = '';\n const seen = new Set<string>();\n const blank = name === 'a' && tag.attrs.some((a) => a.name === 'target' && a.value.trim().toLowerCase() === '_blank');\n for (const { name: attr, value } of tag.attrs) {\n if (blank && attr === 'rel') continue;\n if (seen.has(attr) || !(ALLOWED_ATTRS['*']!.includes(attr) || ALLOWED_ATTRS[name]?.includes(attr))) continue;\n seen.add(attr);\n if (URL_ATTRS.has(attr)) {\n const url = safeUrl(value);\n if (url !== null) attrs += ` ${attr}=\"${escapeAttr(url)}\"`;\n } else {\n attrs += ` ${attr}=\"${escapeAttr(decodeEntities(value))}\"`;\n }\n }\n if (blank) attrs += ' rel=\"noopener noreferrer\"';\n if (name === 'a' && options.linkClass) attrs += ` class=\"${escapeAttr(options.linkClass)}\"`;\n out += `<${name}${attrs}>`;\n if (!VOID_TAGS.has(name)) open.push(name);\n }\n while (open.length > 0) out += `</${open.pop()}>`;\n return out;\n}\n\n/** Catalog HTML, drawn through an allow-list. */\nexport type RichTextProps = UsePartLocal & {\n /** Untrusted HTML (a product description, a content page). It is cleaned before it reaches the page. */\n html: string;\n};\n\n/** Renders catalog HTML through an allow-list, so a description can never carry a script or a handler. */\nexport function RichText({ html, classNames, className, unstyled }: RichTextProps) {\n const part = usePart('rich-text', { classNames, className, unstyled });\n const ambient = useUnstyled();\n // A link gets one class of ours (never the author's) so the stylesheet can colour it with a single-class rule.\n const linkClass = (unstyled ?? ambient) ? undefined : 'tsf-rich-text-link';\n return <div {...part} dangerouslySetInnerHTML={{ __html: sanitizeHtml(html, { linkClass }) }} />;\n}\n","import type { ListProduct } from '@usethrottle/catalog';\nimport { useRelated } from '@usethrottle/catalog/react';\nimport { useMemo } from 'react';\nimport { toGa4Item } from '../analytics/items';\nimport { useTrack } from '../analytics/use-track';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { ProductCard, type ProductCardProps } from '../pieces/ProductCard';\nimport type { PriceContext } from '../pieces/Price';\nimport { useStorefront } from '../provider/context';\nimport { useProductPage } from './use-product-page';\n\nconst LIST_NAME = 'related_products';\n\n/**\n * The related products: what the server sent, else a request, at most\n * `settings.product.relatedLimit`. It asks the catalog with the shared cache\n * policy (no override). For a signed-in shopper the answer is read again so\n * the cards carry their prices. With `active` false nothing is requested.\n */\nexport function useRelatedProducts(active = true): { products: ListProduct[]; priceContext: PriceContext | undefined } {\n const { product, related } = useProductPage();\n const { settings } = useStorefront();\n const limit = settings.product.relatedLimit;\n const seeded = useMemo(() => (related ? { products: related } : undefined), [related]);\n const query = useRelated(product.handle, { limit, initialData: seeded, enabled: active || seeded !== undefined });\n const products = (query.data?.products ?? related ?? []).slice(0, limit);\n return { products, priceContext: query.data?.priceContext };\n}\n\n/** The related products of the page's product, as cards. */\nexport type RelatedProductsProps = UsePartLocal & {\n /** False while the section is not shown (a closed tab): no request is made. Default true. */\n active?: boolean;\n /** How the related cards are drawn: their `variant`, `meta` line and `slots`. */\n card?: Pick<ProductCardProps, 'variant' | 'meta' | 'slots'>;\n};\n\n/** The related products as cards. Nothing when there are none. */\nexport function RelatedProducts({ active = true, card, classNames, className, unstyled }: RelatedProductsProps) {\n const local = { classNames, unstyled };\n const { generatedAt } = useProductPage();\n const { products, priceContext } = useRelatedProducts(active);\n const track = useTrack();\n const root = usePart('related-products', { ...local, className });\n const item = usePart('related-products-item', local);\n // Cards age their `new` badge against the server's clock; a client-side answer has only this page's.\n const at = useMemo(() => generatedAt ?? new Date().toISOString(), [generatedAt]);\n if (products.length === 0) return null;\n return (\n <ul {...root}>\n {products.map((p, position) => (\n <li {...item} key={p.handle}>\n <ProductCard\n {...local}\n {...card}\n product={p}\n position={position}\n listName={LIST_NAME}\n generatedAt={at}\n priceContext={priceContext}\n onSelect={() => {\n const currency = p.priceRange?.currency;\n if (currency) track('select_item', { currency, item_list_name: LIST_NAME, items: [toGa4Item(p, { index: position, listName: LIST_NAME })] });\n }}\n />\n </li>\n ))}\n </ul>\n );\n}\n","import type { ListProduct } from '@usethrottle/catalog';\nimport { VisuallyHidden } from '@usethrottle/ui';\nimport { lazy, Suspense } from 'react';\nimport type { ComponentType, ReactNode } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { useStorefront } from '../provider/context';\nimport { useStrings } from '../strings';\nimport { routeHref } from '../url/routes';\nimport { isHexColor } from '../theme/color';\nimport { Badge } from './Badge';\nimport { cardBadges, type CardBadge } from './badges';\nimport { Image, type ImageProps } from './Image';\nimport { Price, type PriceContext, type PriceProps } from './Price';\nimport { WishlistButton } from './reserved';\nimport { StarRating, type StarRatingProps } from './StarRating';\nimport { Swatch } from './Swatch';\n\n/**\n * How a card is drawn: `standard`, `minimal` (no frame), `overlay` (text over the picture) or `row` (picture beside text).\n */\nexport type ProductCardVariant = 'standard' | 'minimal' | 'overlay' | 'row';\n\n/** The small line above a card's title: the product's brand, or its category (the catalog's product type). */\nexport type ProductCardMeta = 'brand' | 'category';\n\ntype Local = Pick<UsePartLocal, 'classNames' | 'unstyled'>;\n\n/** What a `Title` slot of a card receives. */\nexport type CardTitleProps = Local & {\n /** The product the card shows. */\n product: ListProduct;\n /** The text to show as the title. */\n title: string;\n /** The product page's link. */\n href: string;\n /** Called when the shopper follows the link (for analytics). */\n onSelect?: () => void;\n};\n/** What a `Badges` slot of a card receives. */\nexport type CardBadgesProps = Local & {\n /** The badges the settings and the product ask for. */\n badges: CardBadge[];\n /** The product cannot be bought: a sold-out mark is shown. */\n soldOut: boolean;\n};\n/** What a `QuickAdd` or `WishlistButton` slot of a card receives. */\nexport type CardProductProps = Local & {\n /** The product the card shows. */\n product: ListProduct;\n};\n\n/** The pieces of a card a store may replace. Each takes the props its default takes. */\nexport type ProductCardSlots = {\n Image: ComponentType<ImageProps>;\n Title: ComponentType<CardTitleProps>;\n Price: ComponentType<PriceProps>;\n Rating: ComponentType<StarRatingProps>;\n Badges: ComponentType<CardBadgesProps>;\n QuickAdd: ComponentType<CardProductProps>;\n WishlistButton: ComponentType<CardProductProps>;\n};\n\n/**\n * A product in a list: picture, title, price, rating, badges and quick add, drawn by the merchant's card settings.\n */\nexport type ProductCardProps = Local & {\n /** The product, as the catalog's list answer carries it. */\n product: ListProduct;\n /** Default: `settings.card.style`. */\n variant?: ProductCardVariant;\n /**\n * What the line above the title says. Default `'brand'` (when `settings.card.showBrand` is on); `'category'`\n * shows the product type, whatever `showBrand` says, and nothing when the product has none.\n */\n meta?: ProductCardMeta;\n /** The card's place in its list (0-based), for analytics. */\n position?: number;\n /** The list's name, for analytics. */\n listName?: string;\n /** When the data was made (ISO). The `new` badge ages against it, never against the browser's clock. */\n generatedAt: string;\n /** The list answer's `priceContext`. */\n priceContext?: PriceContext;\n /** Whether lists carry ratings. Default: the provider's `reviewsOnLists`. */\n reviewsOnLists?: boolean;\n /** Draw the quick add button on the card. Default: `settings.card.quickAdd`. A `QuickAdd` slot replaces it. */\n quickAdd?: boolean;\n /** Replace any piece of the card (`Image`, `Title`, `Price`, `Rating`, `Badges`, `QuickAdd`, `WishlistButton`). */\n slots?: Partial<ProductCardSlots>;\n /** Called when the shopper follows the card's link, with the product. */\n onSelect?(product: ListProduct): void;\n};\n\nconst SIZES = '(min-width: 1280px) 300px, (min-width: 768px) 33vw, 50vw';\nconst MAX_SWATCHES = 5;\n\ntype CardImage = NonNullable<ListProduct['images']>[number];\n\nfunction srcSetOf(image: CardImage): string | undefined {\n const entries = Object.entries(image.sizes ?? {}).filter(([, url]) => typeof url === 'string' && url !== '');\n return entries.length > 0 ? entries.map(([width, url]) => `${url} ${width}w`).join(', ') : undefined;\n}\n\ntype CardSwatch = { value: string; hex?: string; image?: string };\n\n/** The distinct colour and texture swatches of a product's options, in order. */\nfunction swatchesOf(product: ListProduct): CardSwatch[] {\n const seen = new Set<string>();\n const out: CardSwatch[] = [];\n for (const option of product.optionSwatches ?? []) {\n for (const v of option.values) {\n const swatch = v.swatch;\n if (!swatch) continue;\n const key = 'color' in swatch ? swatch.color.toLowerCase() : swatch.url;\n if (seen.has(key)) continue;\n if ('color' in swatch) {\n if (!isHexColor(swatch.color)) continue;\n out.push({ value: v.label, hex: swatch.color });\n } else {\n out.push({ value: v.label, image: swatch.url });\n }\n seen.add(key);\n }\n }\n return out;\n}\n\nfunction CardTitle({ product, title, href, onSelect, classNames, unstyled }: CardTitleProps) {\n const { Link: Anchor } = useStorefront();\n const heading = usePart('product-card-title', { classNames, unstyled });\n const link = usePart('product-card-title-link', { classNames, unstyled });\n return (\n <h3 {...heading}>\n <Anchor {...link} href={href} onClick={onSelect}>\n {title || product.handle}\n </Anchor>\n </h3>\n );\n}\n\nfunction CardBadges({ badges, soldOut, classNames, unstyled }: CardBadgesProps) {\n const part = usePart('product-card-badges', { classNames, unstyled });\n const { settings } = useStorefront();\n if (badges.length === 0 && !soldOut) return null;\n return (\n <div {...part}>\n {badges.map((b, i) => (\n <Badge key={`${b.kind}-${i}`} kind={b.kind} tone={b.tone} classNames={classNames} unstyled={unstyled}>\n {b.label}\n </Badge>\n ))}\n {soldOut ? (\n <Badge kind=\"soldOut\" classNames={classNames} unstyled={unstyled}>\n {settings.stock.words.outOfStock}\n </Badge>\n ) : null}\n </div>\n );\n}\n\nconst NoQuickAdd: ComponentType<CardProductProps> = () => null;\n\n// The shopper's quick add (a cart hook, the product's options) is fetched the first time a card asks for it.\nconst LoadedQuickAdd = lazy(() => import('../shopper/QuickAdd').then((m) => ({ default: m.QuickAdd })));\nconst ShopperQuickAdd: ComponentType<CardProductProps> = (props) => (\n <Suspense fallback={null}>\n <LoadedQuickAdd {...props} />\n </Suspense>\n);\n\nconst DEFAULT_SLOTS: ProductCardSlots = {\n Image,\n Title: CardTitle,\n Price,\n Rating: StarRating,\n Badges: CardBadges,\n QuickAdd: NoQuickAdd,\n WishlistButton,\n};\n\ntype MediaProps = Local & {\n product: ListProduct;\n slots: ProductCardSlots;\n badges: CardBadge[];\n soldOut: boolean;\n aspectRatio: number;\n href: string;\n onSelect?: () => void;\n};\n\n/** The image (and, on hover or by swipe, the second one) with the badges and the actions laid over it. */\nfunction CardMedia({ product, slots, badges, soldOut, aspectRatio, href, onSelect, classNames, unstyled }: MediaProps) {\n const { settings, Link: Anchor } = useStorefront();\n const local = { classNames, unstyled };\n const media = usePart('product-card-media', local);\n const link = usePart('product-card-media-link', local);\n const first = usePart('product-card-image', local);\n const alt = usePart('product-card-image-alt', local);\n const placeholder = usePart('product-card-placeholder', local);\n const actions = usePart('product-card-actions', local);\n const images = product.images ?? [];\n const primary = images[0];\n const second = settings.card.secondImageOnHover ? images[1] : undefined;\n // The actions box exists only when a store gave a QuickAdd or a WishlistButton of its own.\n const hasActions = slots.QuickAdd !== NoQuickAdd || slots.WishlistButton !== WishlistButton;\n const imageProps = (image: CardImage): ImageProps => ({\n src: image.url,\n // The title link already names the product; a second description would read twice.\n alt: '',\n aspectRatio,\n srcSet: srcSetOf(image),\n sizes: SIZES,\n ...local,\n });\n return (\n <div {...media}>\n <Anchor {...link} href={href} tabIndex={-1} aria-hidden=\"true\" onClick={onSelect}>\n {primary ? (\n <div {...first}>\n <slots.Image {...imageProps(primary)} />\n </div>\n ) : (\n <div {...placeholder} style={{ aspectRatio }} />\n )}\n {second ? (\n <div {...alt}>\n <slots.Image {...imageProps(second)} />\n </div>\n ) : null}\n </Anchor>\n <slots.Badges badges={badges} soldOut={soldOut} {...local} />\n {hasActions ? (\n <div {...actions}>\n <slots.QuickAdd product={product} {...local} />\n <slots.WishlistButton product={product} {...local} />\n </div>\n ) : null}\n </div>\n );\n}\n\nfunction CardBody(props: Local & { product: ListProduct; meta?: ProductCardMeta; slots: ProductCardSlots; href: string; title: string; priceContext?: PriceContext; reviewsOnLists?: boolean; onSelect?: () => void }) {\n const { product, slots, href, title, priceContext, onSelect, classNames, unstyled } = props;\n const { settings, reviewsOnLists: providerReviewsOnLists } = useStorefront();\n const { t } = useStrings();\n const local = { classNames, unstyled };\n const body = usePart('product-card-body', local);\n const brand = usePart('product-card-brand', local);\n const swatchesPart = usePart('product-card-swatches', local);\n const more = usePart('product-card-swatch-more', local);\n const ratingPart = usePart('product-card-rating', local);\n const pricePart = usePart('product-card-price', local);\n const from = usePart('product-card-from', local);\n const unpriced = usePart('product-card-unpriced', local);\n const { card } = settings;\n const metaText = props.meta === 'category' ? product.productType : card.showBrand ? product.brand : null;\n\n const swatches = card.showSwatches ? swatchesOf(product) : [];\n const rating = product.rating;\n // The catalog's `/config` says whether lists carry ratings (the provider holds it; no request here); a prop overrides it.\n const reviewsOnLists = props.reviewsOnLists ?? providerReviewsOnLists;\n const showRating = card.showRating && reviewsOnLists && rating && rating.count > 0 && rating.average !== null;\n const range = product.priceRange ?? null;\n const compareAt = range && 'compareAtMinMinor' in range && typeof range.compareAtMinMinor === 'number' ? range.compareAtMinMinor : undefined;\n\n return (\n <div {...body}>\n {metaText ? (\n <p {...brand} data-meta={props.meta ?? 'brand'}>\n {metaText}\n </p>\n ) : null}\n <slots.Title product={product} title={title} href={href} onSelect={onSelect} {...local} />\n {swatches.length > 0 ? (\n <ul {...swatchesPart} data-card-swatches=\"\">\n {swatches.slice(0, MAX_SWATCHES).map((s) => (\n <li key={s.hex ?? s.image}>\n <Swatch {...local} {...s} />\n </li>\n ))}\n {swatches.length > MAX_SWATCHES ? (\n <li {...more}>\n <span aria-hidden=\"true\">{t('pieces.card.moreSwatches', { count: swatches.length - MAX_SWATCHES })}</span>\n <VisuallyHidden>{t('pieces.card.moreSwatchesLabel', { count: swatches.length - MAX_SWATCHES })}</VisuallyHidden>\n </li>\n ) : null}\n </ul>\n ) : null}\n {showRating ? (\n <div {...ratingPart} data-card-rating=\"\">\n <slots.Rating value={rating.average!} count={rating.count} size=\"sm\" {...local} />\n </div>\n ) : null}\n <p {...pricePart}>\n {range ? (\n <>\n {range.minMinor !== range.maxMinor ? <span {...from}>{t('pieces.price.from')} </span> : null}\n <slots.Price\n minor={range.minMinor}\n currency={range.currency}\n compareAtMinor={card.showCompareAt ? compareAt : undefined}\n priceContext={priceContext}\n {...local}\n />\n </>\n ) : (\n <span {...unpriced}>{t('pieces.price.unavailable')}</span>\n )}\n </p>\n </div>\n );\n}\n\n/** The wrapper the `row` variant lays out in a line; the other variants render their children as they are. */\nfunction RowLayout({ children, classNames, unstyled }: Local & { children: ReactNode }) {\n const row = usePart('product-card-row', { classNames, unstyled });\n return <div {...row}>{children}</div>;\n}\n\n/**\n * A product in a list: image, badges, brand, title, swatches, rating and price,\n * each of them from the catalog settings (`card.*`, `badges.*`, `stock.words`).\n * The variant follows `settings.card.style` unless the prop is set. Pieces can\n * be replaced through `slots`; `QuickAdd` is the shopper's quick add when `settings.card.quickAdd`\n * (or the `quickAdd` prop) is set and nothing otherwise, and `WishlistButton` renders nothing\n * until a store gives one.\n */\nexport function ProductCard(props: ProductCardProps) {\n const { product, position, listName, generatedAt, priceContext, onSelect, classNames, unstyled } = props;\n const { settings } = useStorefront();\n const variant = props.variant ?? settings.card.style;\n const quickAdd = props.quickAdd ?? settings.card.quickAdd;\n const slots = { ...DEFAULT_SLOTS, ...(quickAdd ? { QuickAdd: ShopperQuickAdd } : {}), ...props.slots };\n const local = { classNames, unstyled };\n const root = usePart('product-card', local);\n const href = routeHref(settings, 'product', product.handle);\n const select = onSelect ? () => onSelect(product) : undefined;\n const soldOut = product.availability === 'out_of_stock';\n const inner = (\n <>\n <CardMedia\n product={product}\n slots={slots}\n badges={cardBadges(settings, product, generatedAt)}\n soldOut={settings.card.showBadges && soldOut}\n aspectRatio={variant === 'row' ? 1 : 0.8}\n href={href}\n onSelect={select}\n {...local}\n />\n <CardBody product={product} slots={slots} href={href} title={product.title ?? product.handle} priceContext={priceContext} reviewsOnLists={props.reviewsOnLists} meta={props.meta} onSelect={select} {...local} />\n </>\n );\n return (\n <article\n {...root}\n data-product-card=\"\"\n data-product-handle={product.handle}\n data-variant={variant}\n data-sold-out={soldOut ? '' : undefined}\n data-position={position}\n data-list-name={listName}\n >\n {variant === 'row' ? <RowLayout {...local}>{inner}</RowLayout> : inner}\n </article>\n );\n}\n","import { useSubmitReview } from '@usethrottle/catalog/react';\nimport { Field, VisuallyHidden } from '@usethrottle/ui';\nimport { useEffect, useId, useRef, useState } from 'react';\nimport type { FormEvent } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { useStrings } from '../strings';\nimport { useProductPage } from './use-product-page';\n\ntype FieldName = 'rating' | 'body' | 'displayName';\ntype Problems = Partial<Record<FieldName, string>>;\n\n/**\n * Writing a review, for a shopper who may (`Reviews` shows it only then).\n * Every field has a label; a missing one is marked inline and takes focus.\n * One idempotency key per submission is the SDK's: a retry never makes two reviews.\n */\nexport function ReviewForm({ handle, classNames, className, unstyled }: UsePartLocal & { handle?: string }) {\n const local = { classNames, unstyled };\n const page = useProductPage();\n const submit = useSubmitReview(handle ?? page.product.handle);\n const { t, keyAttr } = useStrings();\n const id = useId();\n const root = usePart('review-form', { ...local, className });\n const heading = usePart('review-form-title', local);\n const stars = usePart('review-form-stars', local);\n const star = usePart('review-form-star', local);\n const starInput = usePart('review-form-star-input', local);\n const textarea = usePart('review-form-textarea', local);\n const fieldPart = usePart('review-form-field', local);\n const errorPart = usePart('review-form-error', local);\n const submitPart = usePart('review-form-submit', local);\n const thanksPart = usePart('review-form-thanks', local);\n const [rating, setRating] = useState(0);\n const [title, setTitle] = useState('');\n const [body, setBody] = useState('');\n const [displayName, setDisplayName] = useState('');\n const [problems, setProblems] = useState<Problems>({});\n const formRef = useRef<HTMLFormElement>(null);\n const thanks = useRef<HTMLParagraphElement>(null);\n\n // The thanks replaces the form and its focused button: move focus to it so it is read and the place is kept.\n useEffect(() => {\n if (submit.status === 'done') thanks.current?.focus();\n }, [submit.status]);\n\n if (submit.status === 'done') {\n return (\n <p {...thanksPart} ref={thanks} role=\"status\" tabIndex={-1}>\n {submit.result?.review.status === 'approved' ? t('product.reviewForm.thanksLive') : t('product.reviewForm.thanksPending')}\n </p>\n );\n }\n\n const busy = submit.status === 'submitting';\n const failure = (code: string | undefined) => {\n switch (code) {\n case 'ALREADY_REVIEWED': return t('product.reviewForm.errorAlready');\n case 'NOT_VERIFIED_BUYER':\n case 'PURCHASE_REFUNDED': return t('product.reviewForm.errorNotBuyer');\n case 'EMAIL_NOT_VERIFIED': return t('product.reviewForm.errorEmail');\n case 'RATE_LIMITED':\n case 'REVIEW_QUEUE_FULL': return t('product.reviewForm.errorBusy');\n default: return t('product.reviewForm.errorGeneric');\n }\n };\n\n const onSubmit = (event: FormEvent) => {\n event.preventDefault();\n if (busy) return;\n const found: Problems = {};\n if (rating < 1) found.rating = t('product.reviewForm.needRating');\n if (body.trim() === '') found.body = t('product.reviewForm.needBody');\n if (displayName.trim() === '') found.displayName = t('product.reviewForm.needName');\n setProblems(found);\n const first = (['rating', 'body', 'displayName'] as const).find((f) => found[f]);\n if (first) {\n const selector = first === 'rating' ? 'input[name=\"rating\"]' : `[name=\"${first}\"]`;\n formRef.current?.querySelector<HTMLElement>(selector)?.focus();\n return;\n }\n submit.submit({ rating, title: title.trim() || null, body: body.trim(), displayName: displayName.trim() }).catch(() => undefined);\n };\n\n return (\n <form {...root} ref={formRef} noValidate aria-busy={busy || undefined} onSubmit={onSubmit}>\n <p {...heading} {...keyAttr('product.writeReview')}>{t('product.writeReview')}</p>\n <fieldset {...stars} aria-describedby={problems.rating ? `${id}-rating-error` : undefined}>\n <legend>{t('product.reviewForm.rating')}</legend>\n {[1, 2, 3, 4, 5].map((n) => (\n <label {...star} key={n} data-on={n <= rating ? 'true' : undefined}>\n <input\n {...starInput}\n type=\"radio\"\n name=\"rating\"\n value={n}\n checked={rating === n}\n aria-invalid={problems.rating ? true : undefined}\n onChange={() => {\n setRating(n);\n setProblems((p) => ({ ...p, rating: undefined }));\n }}\n />\n <span aria-hidden=\"true\">★</span>\n <VisuallyHidden>{n === 1 ? t('product.reviewForm.starOne') : t('product.reviewForm.star', { n })}</VisuallyHidden>\n </label>\n ))}\n {problems.rating ? <span {...errorPart} id={`${id}-rating-error`} role=\"alert\">{problems.rating}</span> : null}\n </fieldset>\n <Field label={t('product.reviewForm.title')} name=\"title\" value={title} onChange={setTitle} />\n <div {...fieldPart}>\n <label htmlFor={`${id}-body`}>{t('product.reviewForm.body')}</label>\n <textarea\n {...textarea}\n id={`${id}-body`}\n name=\"body\"\n rows={4}\n maxLength={4000}\n value={body}\n aria-invalid={problems.body ? true : undefined}\n aria-describedby={problems.body ? `${id}-body-error` : undefined}\n onChange={(e) => {\n setBody(e.target.value);\n setProblems((p) => ({ ...p, body: undefined }));\n }}\n />\n {problems.body ? <span {...errorPart} id={`${id}-body-error`} role=\"alert\">{problems.body}</span> : null}\n </div>\n <Field\n label={t('product.reviewForm.name')}\n name=\"displayName\"\n value={displayName}\n autoComplete=\"given-name\"\n error={problems.displayName}\n onChange={(v) => {\n setDisplayName(v);\n setProblems((p) => ({ ...p, displayName: undefined }));\n }}\n />\n {submit.status === 'error' ? <p {...errorPart} role=\"alert\">{failure(submit.error?.code)}</p> : null}\n {/* aria-disabled, not disabled, so the pressed button keeps focus while the review sends. */}\n <button {...submitPart} type=\"submit\" aria-disabled={busy || undefined}>\n {busy ? t('product.reviewForm.sending') : t('product.reviewForm.submit')}\n </button>\n </form>\n );\n}\n","import type { StorefrontReviewsAnswer } from '@usethrottle/catalog';\nimport { useCatalog, useCustomerKey, useReviews } from '@usethrottle/catalog/react';\nimport { useReviewEligibility } from '@usethrottle/catalog/react/extras';\nimport { Icon, Select, Skeleton } from '@usethrottle/ui';\nimport { useRef, useState } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { Badge } from '../pieces/Badge';\nimport { StarRating } from '../pieces/StarRating';\nimport { useStorefront } from '../provider/context';\nimport { useStrings } from '../strings';\nimport { ReviewForm } from './ReviewForm';\nimport { REVIEWS_PAGE_SIZE } from '../server/reviews-page';\nimport { useProductPage, type ReviewsLayout } from './use-product-page';\n\ntype Answer = Exclude<StorefrontReviewsAnswer, { redirectTo: string }>;\ntype Review = Answer['reviews'][number];\ntype Sort = 'newest' | 'highest' | 'lowest';\ntype Rating = 1 | 2 | 3 | 4 | 5;\ntype Local = Pick<UsePartLocal, 'classNames' | 'unstyled'>;\n\n/** The sorts the catalog's reviews list takes. */\nconst SORTS: Sort[] = ['newest', 'highest', 'lowest'];\nconst STARS: Rating[] = [5, 4, 3, 2, 1];\nexport { REVIEWS_PAGE_SIZE };\n\nconst sortLabelKey = {\n newest: 'product.reviewList.sortNewest',\n highest: 'product.reviewList.sortHighest',\n lowest: 'product.reviewList.sortLowest',\n} as const;\n\nconst gateKey = {\n reviews_disabled: 'product.reviewList.gateReviewsDisabled',\n not_signed_in: 'product.reviewList.gateSignIn',\n email_not_verified: 'product.reviewList.gateEmailNotVerified',\n already_reviewed: 'product.reviewList.gateAlreadyReviewed',\n not_verified_buyer: 'product.reviewList.gateNotVerifiedBuyer',\n} as const;\n\n/** Whether a signed-in shopper may write a review, and the form or the reason. Signed out: no request, a note. */\nfunction ReviewGate({ handle, ...local }: Local & { handle: string }) {\n const signedIn = useCustomerKey() !== null;\n const eligibility = useReviewEligibility(handle);\n const { t } = useStrings();\n const gate = usePart('product-reviews-gate', local);\n if (!signedIn) return <p {...gate}>{t('product.reviewList.gateSignIn')}</p>;\n if (eligibility.error) {\n // NOT_FOUND: reviews are off for this product; there is nothing to offer.\n if (eligibility.error.code === 'NOT_FOUND') return null;\n return <p {...gate}>{t('product.reviewList.gateFailed')}</p>;\n }\n if (!eligibility.data) return <Skeleton />;\n if (eligibility.data.canReview) return <ReviewForm {...local} handle={handle} />;\n const reason = eligibility.data.reason;\n return (\n <p {...gate} data-reason={reason}>\n {t(reason ? gateKey[reason] : 'product.reviewList.gateUnknown')}\n </p>\n );\n}\n\nfunction ReviewItem({ review, ...local }: Local & { review: Review }) {\n const { locale } = useStorefront();\n const { t } = useStrings();\n const root = usePart('product-review', local);\n const head = usePart('product-review-header', local);\n const date = usePart('product-review-date', local);\n const title = usePart('product-review-title', local);\n const body = usePart('product-review-body', local);\n const author = usePart('product-review-author', local);\n const reply = usePart('product-review-reply', local);\n const when = new Date(review.createdAt);\n return (\n <li {...root} data-review-id={review.id}>\n <div {...head}>\n <StarRating {...local} value={review.rating} size=\"sm\" />\n <time {...date} dateTime={review.createdAt}>\n {Number.isNaN(when.getTime()) ? '' : new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }).format(when)}\n </time>\n </div>\n {review.title ? <h3 {...title}>{review.title}</h3> : null}\n <p {...body}>{review.body}</p>\n <p {...author}>\n {review.displayName}\n {review.verified ? <Badge {...local} kind=\"verified\">{t('product.reviewList.verified')}</Badge> : null}\n </p>\n {review.reply ? (\n <div {...reply}>\n <p>{t('product.reviewList.reply')}</p>\n <p>{review.reply.body}</p>\n </div>\n ) : null}\n </li>\n );\n}\n\n/** The reviews section: the average, a histogram, a sort, the list and the form. */\nexport type ReviewsProps = UsePartLocal & {\n /** False while the section is not shown (a closed tab): no request is made. Default true. */\n active?: boolean;\n /** The first page of reviews when the server has it (default: the page's own, from `loadProduct`); no request is made for it. */\n initialData?: StorefrontReviewsAnswer;\n /** Default: the page's (`Root`'s `reviewsLayout`, else `stack`). `columns` puts the summary beside the list from 768 px. */\n layout?: ReviewsLayout;\n};\n\n/**\n * Reviews: the average and a histogram whose rows filter by rating, a sort, the\n * list with \"load more\", and (for a shopper who may) the form. A rating filter\n * and a sort ask the catalog again; the catalog's `summary` stays the product's whole.\n */\nexport function Reviews({ active = true, initialData, layout, classNames, className, unstyled }: ReviewsProps) {\n const local = { classNames, unstyled };\n const { product, initialReviews, reviewsLayout } = useProductPage();\n const arrangement = layout ?? reviewsLayout;\n const handle = product.handle;\n const seed = initialData ?? initialReviews ?? undefined;\n const client = useCatalog();\n const { t, keyAttr } = useStrings();\n const [sort, setSort] = useState<Sort>('newest');\n const [rating, setRating] = useState<Rating | null>(null);\n const [more, setMore] = useState<{ reviews: Review[]; nextCursor: string | null } | null>(null);\n const [loadingMore, setLoadingMore] = useState(false);\n const [moreFailed, setMoreFailed] = useState(false);\n const ask = useRef(0);\n\n const first = useReviews(handle, {\n sort,\n ...(rating ? { rating } : {}),\n limit: REVIEWS_PAGE_SIZE,\n enabled: active,\n keepPreviousData: true,\n ...(seed && sort === 'newest' && rating === null ? { initialData: seed } : {}),\n });\n\n const root = usePart('product-reviews', { ...local, className });\n const summaryPart = usePart('product-reviews-summary', local);\n const mainPart = usePart('product-reviews-main', local);\n const average = usePart('product-reviews-average', local);\n const histogram = usePart('product-reviews-histogram', local);\n const row = usePart('product-reviews-histogram-row', local);\n const bar = usePart('product-reviews-histogram-bar', local);\n const fill = usePart('product-reviews-histogram-fill', local);\n const count = usePart('product-reviews-histogram-count', local);\n const controls = usePart('product-reviews-controls', local);\n const clear = usePart('product-reviews-clear', local);\n const list = usePart('product-reviews-list', local);\n const empty = usePart('product-reviews-empty', local);\n const loadMore = usePart('product-reviews-load-more', local);\n const failed = usePart('product-reviews-error', local);\n\n const change = (next: { sort?: Sort; rating?: Rating | null }) => {\n ask.current += 1;\n setMore(null);\n setMoreFailed(false);\n if (next.sort !== undefined) setSort(next.sort);\n if (next.rating !== undefined) setRating(next.rating);\n };\n\n const data = first.data && !('redirectTo' in first.data) ? first.data : undefined;\n if (first.error && first.error.code === 'NOT_FOUND') return null;\n if (!data) {\n return (\n <div {...root} aria-busy={first.isLoading || undefined}>\n {first.error ? <p {...failed}>{t('product.reviewList.loadFailed')}</p> : active ? <Skeleton count={2} /> : null}\n </div>\n );\n }\n\n const { summary } = data;\n const reviews = [...data.reviews, ...(more?.reviews ?? [])];\n const nextCursor = more ? more.nextCursor : data.nextCursor;\n\n const loadNext = async () => {\n if (!nextCursor || loadingMore) return;\n const mine = ask.current;\n setLoadingMore(true);\n setMoreFailed(false);\n try {\n const page = await client.reviews.list(handle, { sort, ...(rating ? { rating } : {}), limit: REVIEWS_PAGE_SIZE, cursor: nextCursor });\n if (mine !== ask.current || 'redirectTo' in page) return;\n setMore((prev) => ({ reviews: [...(prev?.reviews ?? []), ...page.reviews], nextCursor: page.nextCursor }));\n } catch {\n if (mine === ask.current) setMoreFailed(true);\n } finally {\n if (mine === ask.current) setLoadingMore(false);\n }\n };\n\n const main = (\n <>\n <ReviewGate {...local} handle={handle} />\n\n {summary.count > 0 ? (\n <div {...controls}>\n <Select\n label={t('product.reviewList.sortLabel')}\n value={sort}\n options={SORTS.map((s) => ({ value: s, label: t(sortLabelKey[s]) }))}\n onChange={(value) => change({ sort: value as Sort })}\n />\n {rating !== null ? (\n <button {...clear} type=\"button\" onClick={() => change({ rating: null })}>\n {t('product.reviewList.clearFilter')}\n </button>\n ) : null}\n </div>\n ) : null}\n\n {reviews.length > 0 ? (\n <ul {...list} aria-busy={first.isValidating || undefined}>\n {reviews.map((review) => (\n <ReviewItem {...local} key={review.id} review={review} />\n ))}\n </ul>\n ) : summary.count > 0 ? (\n <p {...empty}>{t('product.reviewList.noneForRating')}</p>\n ) : null}\n\n {moreFailed ? <p {...failed}>{t('product.reviewList.loadFailed')}</p> : null}\n {nextCursor ? (\n <button {...loadMore} type=\"button\" aria-disabled={loadingMore || undefined} onClick={() => void loadNext()}>\n {loadingMore ? t('product.reviewList.loading') : t('product.reviewList.loadMore')}\n </button>\n ) : null}\n </>\n );\n\n return (\n <div {...root} data-layout={arrangement}>\n <div {...summaryPart} data-layout={arrangement}>\n {summary.count > 0 && summary.average !== null ? (\n <>\n <p {...average}>\n <span aria-hidden=\"true\">{summary.average.toFixed(1)}</span>\n <StarRating {...local} value={summary.average} count={summary.count} />\n </p>\n <ol {...histogram} aria-label={t('product.reviewList.ratingsByStars')}>\n {STARS.map((stars) => {\n const n = summary.histogram[String(stars) as '1' | '2' | '3' | '4' | '5'];\n const pressed = rating === stars;\n return (\n <li key={stars}>\n <button\n {...row}\n type=\"button\"\n data-rating={stars}\n aria-pressed={pressed}\n aria-label={t('product.reviewList.filterRating', { rating: stars, count: n })}\n onClick={() => change({ rating: pressed ? null : stars })}\n >\n <span aria-hidden=\"true\">\n {stars} <Icon name=\"star\" size={12} />\n </span>\n <span {...bar} aria-hidden=\"true\">\n {/* money-guard-ignore dec-mul100 not-money: width of a rating bar */}\n <span {...fill} style={{ inlineSize: `${summary.count ? (n / summary.count) * 100 : 0}%` }} />\n </span>\n <span {...count} aria-hidden=\"true\">{n}</span>\n </button>\n </li>\n );\n })}\n </ol>\n </>\n ) : (\n <p {...empty} {...keyAttr('product.noReviews')}>{t('product.noReviews')}</p>\n )}\n </div>\n\n {arrangement === 'columns' ? <div {...mainPart}>{main}</div> : main}\n </div>\n );\n}\n","/** How many reviews a product page asks for at a time; the loader's first page is this long too. */\nexport const REVIEWS_PAGE_SIZE = 10;\n","import type { StorefrontPageAnswer } from '@usethrottle/catalog';\nimport { usePage } from '@usethrottle/catalog/react/extras';\nimport type { SlotRenderer } from '@usethrottle/ui';\nimport { useContext, useMemo } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { RichText } from '../pieces/RichText';\nimport { useStorefront } from '../provider/context';\nimport { ProductPageContext } from './use-product-page';\n\n/** What a shipping section shows: the Builder's page, the catalog's page body, or nothing. */\nexport type ShippingContent =\n | { kind: 'outlet'; Outlet: SlotRenderer }\n | { kind: 'page'; html: string }\n | { kind: 'hidden' };\n\n/**\n * R14. With a Builder (`site.source === 'builder'`) the section is the Builder's\n * published page for `pageHandle` (`site.pageOutlet`); with no outlet, or none\n * for the handle, it is hidden and no catalog request is made. Without a\n * Builder it is the catalog content page's body, hidden while that page loads\n * or when it is missing.\n */\nexport function useShippingContent(pageHandle: string | null): ShippingContent {\n const { site, settings } = useStorefront();\n const builder = site.source === 'builder';\n const pageOutlet = site.pageOutlet;\n const Outlet = useMemo(\n () => (builder && pageHandle && pageOutlet ? pageOutlet(pageHandle) : null),\n [builder, pageHandle, pageOutlet],\n );\n // What `loadProduct` read for the configured shipping page: it seeds the read (no request), so the section is in the server's HTML.\n const loaded = useContext(ProductPageContext)?.shippingPage;\n const configured = settings.product.sections.find((s) => s.key === 'shipping')?.pageHandle ?? null;\n const seeded = pageHandle !== null && pageHandle === configured ? loaded : undefined;\n const seed = useMemo(\n () => (typeof seeded === 'string' ? ({ handle: pageHandle, title: '', bodyHtml: seeded, seo: { title: '', description: '' } } as StorefrontPageAnswer) : undefined),\n [seeded, pageHandle],\n );\n // `null`: the server found the page missing, so there is nothing to ask for.\n const page = usePage(!builder && pageHandle && seeded !== null ? pageHandle : null, seed ? { initialData: seed } : undefined);\n if (builder) return Outlet ? { kind: 'outlet', Outlet } : { kind: 'hidden' };\n const html = page.data?.bodyHtml;\n return html ? { kind: 'page', html } : { kind: 'hidden' };\n}\n\n/** The shipping information of the store (R14), for a product's `shipping` section. */\nexport function ShippingSection({ pageHandle, classNames, className, unstyled }: UsePartLocal & { pageHandle: string | null }) {\n const local = { classNames, unstyled };\n const content = useShippingContent(pageHandle);\n const part = usePart('shipping-section', { ...local, className });\n if (content.kind === 'hidden') return null;\n return (\n <div {...part}>{content.kind === 'outlet' ? <content.Outlet /> : <RichText {...local} html={content.html} />}</div>\n );\n}\n","import { usePart, type UsePartLocal } from '../parts';\nimport { useStorefront } from '../provider/context';\nimport { routeHref } from '../url/routes';\nimport { useProductPage } from './use-product-page';\n\n/** The product's tags, each a link to its tag page. Nothing without tags. */\nexport function TagList({ classNames, className, unstyled }: UsePartLocal) {\n const local = { classNames, unstyled };\n const { product } = useProductPage();\n const { settings, Link: Anchor } = useStorefront();\n const root = usePart('tag-list', { ...local, className });\n const item = usePart('tag-list-item', local);\n const link = usePart('tag-list-link', local);\n const tags = product.tags ?? [];\n if (tags.length === 0) return null;\n return (\n <ul {...root}>\n {tags.map((tag) => (\n <li {...item} key={tag}>\n <Anchor {...link} href={routeHref(settings, 'tag', tag)}>\n {tag}\n </Anchor>\n </li>\n ))}\n </ul>\n );\n}\n","import { Icon, Tabs } from '@usethrottle/ui';\nimport { useEffect, useState } from 'react';\nimport type { ReactNode } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { RichText } from '../pieces/RichText';\nimport { useStorefront } from '../provider/context';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport { useStrings } from '../strings';\nimport { CategoryList } from './CategoryList';\nimport { RelatedProducts } from './RelatedProducts';\nimport { Reviews } from './Reviews';\nimport { ShippingSection, useShippingContent } from './ShippingSection';\nimport { TagList } from './TagList';\nimport { useMediaQuery } from './use-media-query';\nimport { useProductPage, type SectionsStyle } from './use-product-page';\n\ntype SectionKey = NormalizedSettings['product']['sections'][number]['key'];\ntype Local = Pick<UsePartLocal, 'classNames' | 'unstyled'>;\n\n/** Under this width `auto` is an accordion. */\nexport const PHONE_QUERY = '(max-width: 767px)';\n\ntype SpecRow = { key: string; label: string; values: string[] };\n\n/** One row for each attribute key of the variants; a value that differs between variants lists each, in variant order. */\nfunction specRows(variants: ReturnType<typeof useProductPage>['product']['variants'], yes: string, no: string): SpecRow[] {\n const words = (v: string | number | boolean) => (typeof v === 'boolean' ? (v ? yes : no) : String(v));\n const rows = new Map<string, SpecRow>();\n for (const variant of variants) {\n for (const [key, value] of Object.entries(variant.attributes ?? {})) {\n const row = rows.get(key) ?? { key, label: variant.attributeLabels?.[key] ?? key.replace(/_/g, ' '), values: [] };\n if (!row.values.includes(words(value))) row.values.push(words(value));\n rows.set(key, row);\n }\n }\n return [...rows.values()];\n}\n\nfunction Specs({ rows, ...local }: Local & { rows: SpecRow[] }) {\n const root = usePart('product-specs', local);\n const row = usePart('product-specs-row', local);\n const label = usePart('product-specs-label', local);\n const value = usePart('product-specs-value', local);\n return (\n <dl {...root}>\n {rows.map((r) => (\n <div {...row} key={r.key} data-key={r.key}>\n <dt {...label}>{r.label}</dt>\n <dd {...value}>{r.values.join(', ')}</dd>\n </div>\n ))}\n </dl>\n );\n}\n\ntype Entry = { key: SectionKey; title: string; body: ReactNode };\n\n/** The product's description, details, shipping and reviews sections. */\nexport type ProductSectionsProps = UsePartLocal & {\n /** Default: the page's (`Root`'s `sectionsStyle`, else `settings.product.sectionsStyle`). */\n style?: SectionsStyle;\n};\n\n/**\n * The product's sections in the order and with the titles of\n * `settings.product.sections`, those that are enabled and have something to\n * show, as tabs, accordions or a stack (`auto` is tabs, and accordions under\n * 768 px). Each is `data-section=\"<key>\"` with a `data-section-title` heading.\n * A closed tab or accordion makes no request; the reviews link opens the reviews.\n */\nexport function ProductSections({ style, classNames, className, unstyled }: ProductSectionsProps) {\n const local = { classNames, unstyled };\n const page = useProductPage();\n const { product, revealSectionRef } = page;\n const { settings } = useStorefront();\n const { t } = useStrings();\n const phone = useMediaQuery(PHONE_QUERY);\n const base = page.sectionsId;\n const root = usePart('product-sections', { ...local, className });\n const sectionPart = usePart('product-section', local);\n const titlePart = usePart('product-section-title', local);\n const triggerPart = usePart('product-section-trigger', local);\n const bodyPart = usePart('product-section-body', local);\n\n const configured = settings.product.sections;\n const shipping = useShippingContent(configured.find((s) => s.key === 'shipping')?.pageHandle ?? null);\n const requested = style ?? page.sectionsStyle;\n const resolved = requested === 'auto' ? (phone ? 'accordion' : 'tabs') : requested;\n\n const rows = specRows(product.variants, t('boolean.yes'), t('boolean.no'));\n const hasDescription = !!(product.descriptionHtml?.trim() || product.description?.trim());\n const present: Record<SectionKey, boolean> = {\n description: hasDescription,\n specs: rows.length > 0,\n shipping: shipping.kind !== 'hidden',\n tags: (product.tags?.length ?? 0) > 0,\n categories: (product.categories?.length ?? 0) > 0,\n // Server data says; without it the request decides inside the section.\n related: page.related === undefined || page.related.length > 0,\n // `null`: the server found the catalog has no reviews to show for this product.\n reviews: page.initialReviews !== null,\n };\n\n const entries = configured.filter((s) => s.enabled && present[s.key]);\n const [active, setActive] = useState<string | null>(null);\n const [open, setOpen] = useState<string[] | null>(null);\n const firstKey = entries[0]?.key;\n const current = active && entries.some((e) => e.key === active) ? active : (firstKey ?? '');\n const opened = open ?? (firstKey ? [firstKey] : []);\n\n useEffect(() => {\n revealSectionRef.current = (key) => {\n if (!entries.some((e) => e.key === key)) return false;\n setActive(key);\n setOpen((prev) => [...new Set([...(prev ?? (firstKey ? [firstKey] : [])), key])]);\n return true;\n };\n return () => {\n revealSectionRef.current = null;\n };\n });\n\n if (entries.length === 0) return null;\n\n const isShown = (key: SectionKey) => (resolved === 'tabs' ? current === key : resolved === 'accordion' ? opened.includes(key) : true);\n const titleOf = (s: (typeof entries)[number]) =>\n (s.key === 'related' ? settings.product.relatedTitle.trim() : '') || s.title.trim() || t(`product.${s.key}`);\n const bodyOf = (s: (typeof entries)[number]): ReactNode => {\n switch (s.key) {\n case 'description':\n return product.descriptionHtml?.trim() ? <RichText {...local} html={product.descriptionHtml} /> : <p>{product.description}</p>;\n case 'specs':\n return <Specs {...local} rows={rows} />;\n case 'shipping':\n return <ShippingSection {...local} pageHandle={s.pageHandle} />;\n case 'tags':\n return <TagList {...local} />;\n case 'categories':\n return <CategoryList {...local} />;\n case 'related':\n return <RelatedProducts {...local} active={isShown('related')} />;\n case 'reviews':\n return <Reviews {...local} active={isShown('reviews')} initialData={page.initialReviews ?? undefined} />;\n }\n };\n const list: Entry[] = entries.map((s) => ({ key: s.key, title: titleOf(s), body: bodyOf(s) }));\n const toggle = (key: string) => setOpen(opened.includes(key) ? opened.filter((k) => k !== key) : [...opened, key]);\n\n return (\n <div {...root} data-style={resolved}>\n {resolved === 'tabs' ? (\n <Tabs\n tabs={list.map((e) => ({ id: e.key, label: e.title }))}\n active={current}\n onChange={setActive}\n idBase={base}\n />\n ) : null}\n {list.map((e) => {\n const shown = isShown(e.key);\n const region = `${base}-region-${e.key}`;\n if (resolved === 'tabs') {\n return (\n <section\n {...sectionPart}\n key={e.key}\n id={`${base}-panel-${e.key}`}\n role=\"tabpanel\"\n aria-labelledby={`${base}-tab-${e.key}`}\n hidden={!shown}\n data-section={e.key}\n >\n <h2 {...titlePart} data-section-title=\"\" data-in-tabs=\"\">\n {e.title}\n </h2>\n <div {...bodyPart}>{e.body}</div>\n </section>\n );\n }\n if (resolved === 'accordion') {\n return (\n <section {...sectionPart} key={e.key} id={`${base}-panel-${e.key}`} data-section={e.key}>\n <h2 {...titlePart} data-section-title=\"\">\n <button {...triggerPart} type=\"button\" aria-expanded={shown} aria-controls={region} onClick={() => toggle(e.key)}>\n {e.title}\n <Icon name={shown ? 'chevron-up' : 'chevron-down'} size={16} />\n </button>\n </h2>\n <div {...bodyPart} id={region} role=\"region\" hidden={!shown}>\n {e.body}\n </div>\n </section>\n );\n }\n return (\n <section {...sectionPart} key={e.key} id={`${base}-panel-${e.key}`} data-section={e.key}>\n <h2 {...titlePart} data-section-title=\"\">\n {e.title}\n </h2>\n <div {...bodyPart}>{e.body}</div>\n </section>\n );\n })}\n </div>\n );\n}\n","import { useSyncExternalStore } from 'react';\n\n/**\n * Whether a media query matches. False on the server and on the first client\n * render (so hydration agrees), then the browser's answer. False where\n * `matchMedia` does not exist.\n */\nexport function useMediaQuery(query: string): boolean {\n return useSyncExternalStore(\n (onChange) => {\n if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return () => {};\n const list = window.matchMedia(query);\n list.addEventListener('change', onChange);\n return () => list.removeEventListener('change', onChange);\n },\n () => typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia(query).matches,\n () => false,\n );\n}\n","import { useEffect, useState } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { Price } from '../pieces/Price';\nimport { useStorefront } from '../provider/context';\nimport { useStrings } from '../strings';\nimport { useProductPage } from './use-product-page';\n\n/**\n * A bar fixed to the bottom of the screen that shows when the main add button\n * has scrolled out of view (an IntersectionObserver), with the title, the\n * price and an add button. Nothing shows without an observer.\n */\nexport function StickyAddToCart({ classNames, className, unstyled }: UsePartLocal) {\n const local = { classNames, unstyled };\n const { product, variant, priceContext, add, adding, stock, sku, addToCartRef } = useProductPage();\n const { currency } = useStorefront();\n const { t } = useStrings();\n const [shown, setShown] = useState(false);\n const root = usePart('sticky-add-to-cart', { ...local, className });\n const titlePart = usePart('sticky-add-to-cart-title', local);\n const pricePart = usePart('sticky-add-to-cart-price', local);\n const button = usePart('sticky-add-to-cart-button', local);\n\n useEffect(() => {\n const target = addToCartRef.current;\n if (!target || typeof IntersectionObserver === 'undefined') return;\n const observer = new IntersectionObserver(([entry]) => {\n // Gone off the top (scrolled past) or the bottom (not reached yet): only \"scrolled past\" shows the bar.\n setShown(!!entry && !entry.isIntersecting && entry.boundingClientRect.top < 0);\n });\n observer.observe(target);\n return () => observer.disconnect();\n }, [addToCartRef]);\n\n if (!shown) return null;\n const now = variant ? (variant.salePriceMinor ?? variant.priceMinor) : null;\n const priced = variant?.currency ?? currency;\n const cannot = !sku || stock === 'out' || stock === 'no_currency';\n return (\n <div {...root} role=\"region\" aria-label={t('product.sticky.label')}>\n <p {...titlePart}>{product.title ?? product.handle}</p>\n {now !== null && priced ? (\n <p {...pricePart}>\n <Price {...local} minor={now} currency={priced} priceContext={priceContext} />\n </p>\n ) : null}\n <button {...button} type=\"button\" disabled={cannot} aria-disabled={adding || undefined} onClick={() => !adding && void add()}>\n {adding ? t('product.cartAdd.adding') : t('product.addToCart')}\n </button>\n </div>\n );\n}\n","import type { StorefrontProduct, StorefrontProductAnswer } from '@usethrottle/catalog';\nimport { useProduct } from '@usethrottle/catalog/react';\nimport { EmptyState, Skeleton } from '@usethrottle/ui';\nimport { useEffect, useMemo } from 'react';\nimport type { ReactNode } from 'react';\nimport { usePart, type UsePartLocal } from '../parts';\nimport { Price, type PriceContext } from '../pieces/Price';\nimport { useStorefront } from '../provider/context';\nimport { breadcrumbJsonLd, productJsonLd } from '../seo';\nimport { JsonLd } from '../seo/JsonLd';\nimport type { ProductData } from '../server/types';\nimport { SlotOutlet } from '../site/SlotOutlet';\nimport { useStrings } from '../strings';\nimport { routeHref } from '../url/routes';\nimport { AddToCart } from './AddToCart';\nimport { Breadcrumbs, productCrumbs } from './Breadcrumbs';\nimport { BuyBox } from './BuyBox';\nimport { CategoryList } from './CategoryList';\nimport { Gallery } from './Gallery';\nimport { ProductSections } from './ProductSections';\nimport { QuantityInput } from './QuantityInput';\nimport { RelatedProducts } from './RelatedProducts';\nimport { ReviewForm } from './ReviewForm';\nimport { Reviews } from './Reviews';\nimport { ShippingSection } from './ShippingSection';\nimport { StickyAddToCart } from './StickyAddToCart';\nimport { StockStatus } from './StockStatus';\nimport { TagList } from './TagList';\nimport {\n ProductPageContext, useProductPage, useProductPageState,\n type ProductLayout, type ReviewsLayout, type SectionsStyle,\n} from './use-product-page';\nimport { VariantPicker } from './VariantPicker';\n\n/**\n * The props of `ProductPage.Root` (and `ProductPage`): the product to show, from `initialData` or the URL, and the layout options.\n */\nexport type ProductPageRootProps = UsePartLocal & {\n /** The product's handle. Default: `initialData`'s, else read from the URL by `settings.routes.product`. */\n handle?: string;\n /** What `loadProduct` answered: the page renders from it and makes no request on mount. */\n initialData?: ProductData;\n /** Default: `settings.product.layout`. */\n layout?: ProductLayout;\n /** Default: `settings.product.sectionsStyle`. */\n sectionsStyle?: SectionsStyle;\n /** The reviews section's layout. Default `stack`. */\n reviewsLayout?: ReviewsLayout;\n /** The store's origin (`https://shop.example`), so JSON-LD links are absolute. Default: site-relative. */\n baseUrl?: string;\n /**\n * Your own layout, drawn inside the page's state (`ProductPage.Gallery`, `ProductPage.BuyBox`, ...). Without it the default page is drawn.\n */\n children?: ReactNode;\n};\n\n/** The handle a path names under a route pattern such as `/p/{handle}`, or null. */\nfunction handleFromPath(pattern: string, pathname: string): string | null {\n const [head, tail = ''] = pattern.split('{handle}');\n if (!pathname.startsWith(head!) || !pathname.endsWith(tail) || pathname.length <= head!.length + tail.length) return null;\n const raw = pathname.slice(head!.length, pathname.length - tail.length);\n if (raw.includes('/')) return null;\n try {\n return decodeURIComponent(raw);\n } catch {\n return null;\n }\n}\n\nfunction Loaded(props: ProductPageRootProps & { product: StorefrontProduct; priceContext: PriceContext | undefined }) {\n const { product, priceContext, initialData, children, classNames, className, unstyled } = props;\n const { settings } = useStorefront();\n const value = useProductPageState({\n product,\n priceContext,\n initialSku: initialData?.variantSku ?? null,\n related: initialData?.related,\n generatedAt: initialData?.generatedAt,\n reviews: initialData?.reviews,\n shippingPage: initialData?.shippingPage,\n layout: props.layout ?? settings.product.layout,\n sectionsStyle: props.sectionsStyle ?? settings.product.sectionsStyle,\n reviewsLayout: props.reviewsLayout,\n baseUrl: (props.baseUrl ?? '').replace(/\\/+$/u, ''),\n });\n const root = usePart('product-page', { classNames, className, unstyled });\n return (\n <ProductPageContext.Provider value={value}>\n <div {...root} data-layout={value.layout} data-sections-style={value.sectionsStyle} data-product-page={product.handle}>\n {children}\n </div>\n </ProductPageContext.Provider>\n );\n}\n\n/**\n * The product page's state and data, with no markup of its own (a root\n * element aside): put the sections you want inside. It reads the product from\n * `initialData` (no request on mount) or the catalog by `handle`.\n */\nfunction Root(props: ProductPageRootProps) {\n const { settings, router } = useStorefront();\n const { t } = useStrings();\n const { classNames, className, unstyled } = props;\n const handle = props.handle ?? props.initialData?.product.handle ?? handleFromPath(settings.routes.product, router.pathname);\n const seeded = useMemo(\n () => (props.initialData ? ({ product: props.initialData.product } as StorefrontProductAnswer) : undefined),\n [props.initialData],\n );\n const query = useProduct(handle, { initialData: seeded });\n const data = query.data;\n const redirectTo = data && 'redirectTo' in data ? data.redirectTo : null;\n useEffect(() => {\n // A renamed handle: the page lives under the new one.\n if (redirectTo) router.replace(routeHref(settings, 'product', redirectTo));\n }, [redirectTo, router, settings]);\n const root = usePart('product-page', { classNames, className, unstyled });\n\n if (data && 'product' in data) {\n return <Loaded {...props} product={data.product} priceContext={data.priceContext} />;\n }\n if (query.error || redirectTo) {\n return (\n <div {...root} data-status=\"empty\">\n {redirectTo ? null : <EmptyState title={t('error.notFound')} />}\n </div>\n );\n }\n return (\n <div {...root} data-status=\"loading\" aria-busy=\"true\">\n <Skeleton count={4} />\n </div>\n );\n}\n\n/** The product's JSON-LD: the `Product` and its `BreadcrumbList`. Rendered once by the assembled page. */\nfunction ProductJsonLd() {\n const { product, baseUrl } = useProductPage();\n const { settings, currency } = useStorefront();\n const { t } = useStrings();\n const url = `${baseUrl}${routeHref(settings, 'product', product.handle)}`;\n // No currency anywhere (no price at all): a Product with no price is not written.\n const priced = currency ?? product.variants.find((v) => v.currency)?.currency ?? product.priceRange?.currency;\n const crumbs = productCrumbs(product, settings, t('product.crumbs.home')).map((c) => ({ name: c.name, url: `${baseUrl}${c.href}` }));\n return (\n <>\n {priced ? <JsonLd data={productJsonLd(product, { url, settings, currency: priced })} /> : null}\n <JsonLd data={breadcrumbJsonLd(crumbs)} />\n </>\n );\n}\n\nfunction SlotAbove() {\n const { product, sku } = useProductPage();\n return <SlotOutlet name=\"product.above\" context={{ kind: 'product', product, variantSku: sku }} />;\n}\n\nfunction SlotBelow() {\n const { product, sku } = useProductPage();\n return <SlotOutlet name=\"product.below\" context={{ kind: 'product', product, variantSku: sku }} />;\n}\n\nfunction Main({ classNames, unstyled }: Pick<UsePartLocal, 'classNames' | 'unstyled'>) {\n const main = usePart('product-page-main', { classNames, unstyled });\n return (\n <div {...main}>\n <Gallery classNames={classNames} unstyled={unstyled} />\n <BuyBox classNames={classNames} unstyled={unstyled} />\n </div>\n );\n}\n\n/** The props of the whole `ProductPage`: the same as `ProductPage.Root`. */\nexport type ProductPageProps = ProductPageRootProps;\n\n/**\n * The whole product page: breadcrumbs, `product.above`, the gallery and buy\n * box in the layout, `product.below`, the sections and the sticky add bar.\n * Give it `children` to lay the page out yourself (inside the same state).\n */\nfunction ProductPageImpl(props: ProductPageProps) {\n const { children, classNames, unstyled } = props;\n const local = { classNames, unstyled };\n return (\n <Root {...props}>\n {children ?? (\n <>\n <ProductJsonLd />\n <Breadcrumbs {...local} />\n <SlotAbove />\n <Main {...local} />\n <SlotBelow />\n <ProductSections {...local} />\n <StickyAddToCart {...local} />\n </>\n )}\n </Root>\n );\n}\n\n/**\n * `<ProductPage initialData={data} />`, or compose it:\n * `<ProductPage.Root initialData={data}><ProductPage.Gallery /><ProductPage.BuyBox /></ProductPage.Root>`.\n */\nexport const ProductPage = Object.assign(ProductPageImpl, {\n Root,\n JsonLd: ProductJsonLd,\n Breadcrumbs,\n SlotAbove,\n Gallery,\n BuyBox,\n VariantPicker,\n Price,\n StockStatus,\n QuantityInput,\n AddToCart,\n StickyAddToCart,\n ProductSections,\n ShippingSection,\n TagList,\n CategoryList,\n RelatedProducts,\n Reviews,\n ReviewForm,\n SlotBelow,\n});\n","import { useMemo } from 'react';\nimport type { ReactNode } from 'react';\nimport { StorefrontContext } from '../provider/context';\nimport { useStorefront } from '../provider/context';\n\nconst NOOP = () => {};\n\n/**\n * A router that goes nowhere, for a product shown in a modal or a popover. The product page keeps the\n * chosen variant in `?variant=`; there it would rewrite the address of the page behind (a shop's\n * filters share it). Inside, choosing a variant stays in the component's own state.\n */\nexport function QuietRouter({ pathname, children }: { pathname: string; children: ReactNode }) {\n const outer = useStorefront();\n const value = useMemo(\n () => ({ ...outer, router: { pathname, searchParams: new URLSearchParams(), push: NOOP, replace: NOOP } }),\n [outer, pathname],\n );\n return <StorefrontContext.Provider value={value}>{children}</StorefrontContext.Provider>;\n}\n"]}