bitsnap-react 1.18.0 → 1.19.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.
- package/AGENTS.md +106 -0
- package/README.md +98 -0
- package/dist/BitsnapCart-E72W5RRZ.mjs +2 -0
- package/dist/BitsnapCart-LHJ6KOTV.css +2 -0
- package/dist/BitsnapCart-LHJ6KOTV.css.map +1 -0
- package/dist/BitsnapCart-Q2HER6GU.js +2 -0
- package/dist/BitsnapCart-Q2HER6GU.js.map +1 -0
- package/dist/CartProvider-677CE2FI.js +2 -0
- package/dist/CartProvider-677CE2FI.js.map +1 -0
- package/dist/CartProvider-YPDOFSYC.mjs +2 -0
- package/dist/{PanelModelFiles-JZFSF7BF.mjs → PanelModelFiles-4B2HYGIE.mjs} +2 -2
- package/dist/{PanelModelFiles-7HPXWONN.js → PanelModelFiles-EKQRLF46.js} +2 -2
- package/dist/PanelModelFiles-EKQRLF46.js.map +1 -0
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/chat.css +2 -0
- package/dist/chat.css.map +1 -0
- package/dist/chat.d.mts +172 -0
- package/dist/chat.d.ts +172 -0
- package/dist/chat.js +2 -0
- package/dist/chat.js.map +1 -0
- package/dist/chat.mjs +2 -0
- package/dist/chat.mjs.map +1 -0
- package/dist/chunk-2FD2QP4Y.js +2 -0
- package/dist/chunk-2FD2QP4Y.js.map +1 -0
- package/dist/chunk-5JRUPLXY.mjs +2 -0
- package/dist/chunk-5JRUPLXY.mjs.map +1 -0
- package/dist/chunk-5M6M7FAR.mjs +2 -0
- package/dist/chunk-5M6M7FAR.mjs.map +1 -0
- package/dist/chunk-6Q3VGPSF.js.map +1 -1
- package/dist/chunk-AAC576BC.mjs +5 -0
- package/dist/chunk-AAC576BC.mjs.map +1 -0
- package/dist/{chunk-4OVOKGGS.mjs → chunk-AB37DWOK.mjs} +2 -2
- package/dist/{chunk-ZATPBYOA.js → chunk-BUYTK7KM.js} +2 -2
- package/dist/chunk-BUYTK7KM.js.map +1 -0
- package/dist/{chunk-DP2NOHCI.js → chunk-D2ASWUXM.js} +2 -2
- package/dist/chunk-D2ASWUXM.js.map +1 -0
- package/dist/chunk-DDIEFKNP.mjs +2 -0
- package/dist/{chunk-ZHTMK5TA.mjs.map → chunk-DDIEFKNP.mjs.map} +1 -1
- package/dist/{chunk-4HGZZJEL.js → chunk-DOJICJCQ.js} +2 -2
- package/dist/chunk-DOJICJCQ.js.map +1 -0
- package/dist/chunk-EMR4YXNY.mjs +2 -0
- package/dist/chunk-EMR4YXNY.mjs.map +1 -0
- package/dist/{chunk-JA62KNAQ.js → chunk-GJOGATP6.js} +2 -2
- package/dist/chunk-GJOGATP6.js.map +1 -0
- package/dist/chunk-GQ5OKU74.js +2 -0
- package/dist/chunk-GQ5OKU74.js.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/chunk-KHQEDQYF.js +5 -0
- package/dist/chunk-KHQEDQYF.js.map +1 -0
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-LGPNJ5XE.js +2 -0
- package/dist/chunk-LGPNJ5XE.js.map +1 -0
- package/dist/chunk-MDAFPGPA.js +2 -0
- package/dist/chunk-MDAFPGPA.js.map +1 -0
- package/dist/{chunk-JHJ3ZZF4.mjs → chunk-MMLBQHBM.mjs} +2 -2
- package/dist/chunk-MWWEPEU2.js +2 -0
- package/dist/chunk-MWWEPEU2.js.map +1 -0
- package/dist/{chunk-GEBRXFT3.mjs → chunk-N523LFAM.mjs} +2 -2
- package/dist/chunk-NWXZ45TV.js +2 -0
- package/dist/chunk-NWXZ45TV.js.map +1 -0
- package/dist/chunk-OFPRIENJ.mjs +2 -0
- package/dist/chunk-OFPRIENJ.mjs.map +1 -0
- package/dist/chunk-OR566YJI.mjs +2 -0
- package/dist/chunk-OR566YJI.mjs.map +1 -0
- package/dist/chunk-Q337IQNA.js +2 -0
- package/dist/chunk-Q337IQNA.js.map +1 -0
- package/dist/chunk-SCEWYZUZ.mjs +2 -0
- package/dist/chunk-SCEWYZUZ.mjs.map +1 -0
- package/dist/{chunk-CF45RDMD.mjs → chunk-SSSF64M7.mjs} +2 -2
- package/dist/{chunk-CF45RDMD.mjs.map → chunk-SSSF64M7.mjs.map} +1 -1
- package/dist/chunk-W3RGQYPD.js.map +1 -1
- package/dist/chunk-WG54EHST.mjs +2 -0
- package/dist/chunk-WG54EHST.mjs.map +1 -0
- package/dist/chunk-XEXPQFKN.mjs +2 -0
- package/dist/chunk-XEXPQFKN.mjs.map +1 -0
- package/dist/chunk-YV2C276H.js +2 -0
- package/dist/chunk-YV2C276H.js.map +1 -0
- package/dist/consent.js.map +1 -1
- package/dist/course.d.mts +2 -14
- package/dist/course.d.ts +2 -14
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/course.mjs.map +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +288 -4
- package/dist/index.d.ts +288 -4
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/methods-64D5DD6K.js +2 -0
- package/dist/methods-64D5DD6K.js.map +1 -0
- package/dist/methods-NQA3DFLE.mjs +2 -0
- package/dist/methods-NQA3DFLE.mjs.map +1 -0
- package/dist/model-files-client-P4PORZJ6.js.map +1 -1
- package/dist/models.js.map +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/texts-9kfgClsA.d.mts +14 -0
- package/dist/texts-9kfgClsA.d.ts +14 -0
- package/dist/{types-D6LsoycW.d.mts → types-B-sjyZQs.d.mts} +7 -1
- package/dist/{types-ClFCVzk_.d.ts → types-iRe6ix2y.d.ts} +7 -1
- package/dist/viewer3d.js.map +1 -1
- package/dist/viewer3d.mjs +1 -1
- package/dist/viewer3d.mjs.map +1 -1
- package/dist/widgets-BT2LN2Nq.d.mts +547 -0
- package/dist/widgets-BVOSj9fU.d.ts +547 -0
- package/package.json +18 -3
- package/dist/CartProvider-OEI526IN.js +0 -2
- package/dist/CartProvider-OEI526IN.js.map +0 -1
- package/dist/CartProvider-RYAA3JDA.mjs +0 -2
- package/dist/PanelModelFiles-7HPXWONN.js.map +0 -1
- package/dist/chunk-4HGZZJEL.js.map +0 -1
- package/dist/chunk-5X7TP3TQ.mjs +0 -2
- package/dist/chunk-5X7TP3TQ.mjs.map +0 -1
- package/dist/chunk-7RXW6XFY.js +0 -2
- package/dist/chunk-7RXW6XFY.js.map +0 -1
- package/dist/chunk-DP2NOHCI.js.map +0 -1
- package/dist/chunk-EVIDNS22.mjs +0 -2
- package/dist/chunk-EVIDNS22.mjs.map +0 -1
- package/dist/chunk-G4V2KWTV.js +0 -2
- package/dist/chunk-G4V2KWTV.js.map +0 -1
- package/dist/chunk-GWF3MRUP.js +0 -2
- package/dist/chunk-GWF3MRUP.js.map +0 -1
- package/dist/chunk-JA62KNAQ.js.map +0 -1
- package/dist/chunk-UPAOIY4R.mjs +0 -2
- package/dist/chunk-UPAOIY4R.mjs.map +0 -1
- package/dist/chunk-V5ECGBFW.js +0 -5
- package/dist/chunk-V5ECGBFW.js.map +0 -1
- package/dist/chunk-VNV5BD4X.js +0 -2
- package/dist/chunk-VNV5BD4X.js.map +0 -1
- package/dist/chunk-VNYHJT6V.mjs +0 -2
- package/dist/chunk-VNYHJT6V.mjs.map +0 -1
- package/dist/chunk-WJO5GSY3.mjs +0 -5
- package/dist/chunk-WJO5GSY3.mjs.map +0 -1
- package/dist/chunk-ZATPBYOA.js.map +0 -1
- package/dist/chunk-ZHTMK5TA.mjs +0 -2
- package/dist/methods-AULQDKVS.mjs +0 -2
- package/dist/methods-PMH5VQ25.js +0 -2
- package/dist/methods-PMH5VQ25.js.map +0 -1
- /package/dist/{CartProvider-RYAA3JDA.mjs.map → BitsnapCart-E72W5RRZ.mjs.map} +0 -0
- /package/dist/{methods-AULQDKVS.mjs.map → CartProvider-YPDOFSYC.mjs.map} +0 -0
- /package/dist/{PanelModelFiles-JZFSF7BF.mjs.map → PanelModelFiles-4B2HYGIE.mjs.map} +0 -0
- /package/dist/{chunk-4OVOKGGS.mjs.map → chunk-AB37DWOK.mjs.map} +0 -0
- /package/dist/{chunk-JHJ3ZZF4.mjs.map → chunk-MMLBQHBM.mjs.map} +0 -0
- /package/dist/{chunk-GEBRXFT3.mjs.map → chunk-N523LFAM.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/products/appearance.ts","../src/components/products/useProducts.ts","../src/components/products/ProductList.tsx","../src/components/products/impressions.ts","../src/components/products/texts.ts"],"sourcesContent":["import type { CSSProperties } from \"react\";\nimport {\n getSlotAppearance,\n resolveAppearanceCore,\n type AppearanceElements,\n type ShadcnVariableMapping,\n type SlotAppearance,\n} from \"@/src/lib/appearance-core\";\n\n/**\n * Product list appearance API.\n *\n * It mirrors `CheckoutAppearance` and `ReturnsAppearance` (theme, tokens,\n * elements) so a shop can reuse one brand object for all of them. The resolver\n * is pure: it turns the caller input into a theme name, the tokens in effect,\n * the slot overrides and the inline style for the theme boundary.\n */\n\nexport type ProductListTheme = \"light\" | \"dark\";\n\nexport type ProductListAppearanceTokens = {\n /** Font family of the list. The library never loads fonts. */\n fontFamily?: string;\n /** Minimum grid track width. Use \"100%\" for one column. */\n gridMinWidth?: string;\n /** Base font size. */\n fontSize?: string;\n /** List background. */\n background?: string;\n /** Raised surfaces: cards, image placeholders, skeletons. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, the struck-through price. */\n mutedForeground?: string;\n /** Borders of cards and buttons. */\n border?: string;\n /** \"Add to cart\" button background. */\n buttonBackground?: string;\n /** \"Add to cart\" button text. */\n buttonForeground?: string;\n /** \"Add to cart\" button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of cards and secondary buttons. */\n hoverSurface?: string;\n /** Focus ring color. */\n focusRing?: string;\n /** Error and unavailable state color. */\n error?: string;\n /** Badge background (subscription, unavailable). */\n badgeBackground?: string;\n /** Badge text. */\n badgeForeground?: string;\n /** Corner radius of cards, images and buttons. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-products-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const PRODUCT_LIST_SLOT_NAMES = [\n \"root\",\n \"grid\",\n \"card\",\n \"cardLink\",\n \"image\",\n \"imagePlaceholder\",\n \"body\",\n \"name\",\n \"description\",\n \"price\",\n \"comparePrice\",\n \"badge\",\n \"model3dBadge\",\n \"actions\",\n \"addToCartButton\",\n \"selectButton\",\n \"message\",\n \"pagination\",\n \"paginationButton\",\n \"pageIndicator\",\n \"emptyState\",\n \"error\",\n \"retryButton\",\n \"skeleton\",\n] as const;\n\nexport type ProductListSlotName = (typeof PRODUCT_LIST_SLOT_NAMES)[number];\n\nexport type ProductListSlotAppearance = SlotAppearance;\n\nexport type ProductListAppearanceElements =\n AppearanceElements<ProductListSlotName>;\n\nexport type ProductListAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ProductListTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ProductListAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ProductListAppearanceElements;\n};\n\nexport type ResolvedProductListAppearance = {\n theme: ProductListTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ProductListAppearanceTokens;\n elements: ProductListAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the list root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const PRODUCT_LIST_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-products-font-family\",\n gridMinWidth: \"--bitsnap-products-grid-min-width\",\n fontSize: \"--bitsnap-products-font-size\",\n background: \"--bitsnap-products-background\",\n surface: \"--bitsnap-products-surface\",\n foreground: \"--bitsnap-products-foreground\",\n mutedForeground: \"--bitsnap-products-muted-foreground\",\n border: \"--bitsnap-products-border\",\n buttonBackground: \"--bitsnap-products-button-background\",\n buttonForeground: \"--bitsnap-products-button-foreground\",\n buttonHoverBackground: \"--bitsnap-products-button-hover-background\",\n hoverSurface: \"--bitsnap-products-hover-surface\",\n focusRing: \"--bitsnap-products-focus-ring\",\n error: \"--bitsnap-products-error\",\n badgeBackground: \"--bitsnap-products-badge-background\",\n badgeForeground: \"--bitsnap-products-badge-foreground\",\n radius: \"--bitsnap-products-radius\",\n} as const;\n\nexport type ProductListTokenName = keyof typeof PRODUCT_LIST_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `products.css` falls back to the light values, which keeps\n * the list usable even when the boundary style is missing.\n */\nexport const PRODUCT_LIST_THEME_PRESETS: Record<\n ProductListTheme,\n ProductListAppearanceTokens\n> = {\n light: {\n background: \"#ffffff\",\n surface: \"#f9fafb\",\n foreground: \"#18181b\",\n mutedForeground: \"#71717a\",\n border: \"#e4e4e7\",\n buttonBackground: \"#18181b\",\n buttonForeground: \"#fafafa\",\n buttonHoverBackground: \"#000000\",\n hoverSurface: \"#f4f4f5\",\n focusRing: \"#71717a\",\n error: \"#dc2626\",\n badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n radius: \"8px\",\n gridMinWidth: \"9rem\",\n },\n dark: {\n background: \"#18181b\",\n surface: \"#27272a\",\n foreground: \"#fafafa\",\n mutedForeground: \"#a1a1aa\",\n border: \"#3f3f46\",\n buttonBackground: \"#fafafa\",\n buttonForeground: \"#18181b\",\n buttonHoverBackground: \"#e4e4e7\",\n hoverSurface: \"#3f3f46\",\n focusRing: \"#a1a1aa\",\n error: \"#f87171\",\n badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n radius: \"8px\",\n gridMinWidth: \"9rem\",\n },\n};\n\n/** The list renders its own elements, so no shared primitive needs remapping. */\nconst PRODUCT_LIST_SHADCN_VARIABLES: ShadcnVariableMapping<ProductListTokenName> =\n [];\n\nexport function resolveProductListAppearance(\n appearance?: ProductListAppearance,\n): ResolvedProductListAppearance {\n const resolved = resolveAppearanceCore<\n ProductListTokenName,\n ProductListTheme,\n ProductListSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: PRODUCT_LIST_THEME_PRESETS,\n variables: PRODUCT_LIST_TOKEN_VARIABLES,\n shadcnVariables: PRODUCT_LIST_SHADCN_VARIABLES,\n });\n\n return {\n theme: resolved.theme,\n tokens: resolved.tokens,\n elements: resolved.elements,\n boundaryClassName: resolved.theme,\n boundaryStyle: resolved.boundaryStyle,\n };\n}\n\n/** Caller overrides for a single slot, if any were provided. */\nexport function getProductListSlotAppearance(\n resolved: ResolvedProductListAppearance,\n slot: ProductListSlotName,\n): ProductListSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { HOST } from \"../checkout/constants\";\nimport {\n clampPageSize,\n fetchProductList,\n pageCountFor,\n type ProductListData,\n type PublicListProduct,\n} from \"./fetch\";\n\nexport type UseProductsOptions = {\n /** Project (shop) ID. */\n projectID: string;\n /**\n * Origin of the Bitsnap backend. Defaults to the library host\n * (`https://bitsnap.pl`, or what `setCustomHost` had set when the component\n * first rendered; later `setCustomHost` calls do not move an existing list).\n * On a custom domain pass the domain itself, or an empty string for\n * same-origin requests.\n */\n host?: string;\n locale?: string;\n /** Products per page, 1 to 48. Defaults to 24. */\n pageSize?: number;\n search?: string;\n /**\n * First page, loaded on the server. It is always used for the first request\n * of the mounted list (the first fetch is skipped and the products are\n * available on the first render), so it has to be the page the props ask\n * for: page 1 with the same `pageSize`, `locale` and `search`. Later changes\n * of the props fetch again.\n */\n initialData?: ProductListData;\n};\n\nexport type UseProductsResult = {\n /** Products of the current page. Keeps the previous page while loading. */\n products: PublicListProduct[];\n totalCount: number;\n /** Current page, starting at 1. */\n page: number;\n pageCount: number;\n setPage: (page: number) => void;\n /** `true` until the current page is available, also during server rendering. */\n isLoading: boolean;\n error: Error | undefined;\n /** Loads the current page again. */\n refetch: () => void;\n};\n\ntype Snapshot = {\n /** Request the data belongs to; empty when it is not tied to one. */\n requestKey: string;\n data: ProductListData | undefined;\n error: Error | undefined;\n};\n\n/**\n * Loads the product catalog page by page. It uses a plain `fetch` without\n * credentials, never reads global state (`setProjectID`, `setCustomHost`) other\n * than the default host, and does nothing during server rendering - pass\n * `initialData` to render products in the server HTML.\n */\nexport function useProducts(options: UseProductsOptions): UseProductsResult {\n const { projectID, locale, search, initialData } = options;\n // The library host is a mutable global; read it once so a later\n // `setCustomHost` does not change the query of a mounted list.\n const [defaultHost] = useState(() => HOST);\n const host = options.host ?? defaultHost;\n const pageSize = clampPageSize(options.pageSize);\n\n // Everything that identifies a list; a change resets the page.\n const queryKey = JSON.stringify([\n projectID,\n host,\n locale ?? null,\n search?.trim() ?? null,\n pageSize,\n ]);\n\n const [pageState, setPageState] = useState({ queryKey, page: 1 });\n if (pageState.queryKey !== queryKey) {\n // Another list: start from page 1 (adjusting state while rendering).\n setPageState({ queryKey, page: 1 });\n }\n const [reloads, setReloads] = useState(0);\n const [snapshot, setSnapshot] = useState<Snapshot>(() => ({\n requestKey: initialData != null ? `${queryKey}|1|0` : \"\",\n data: initialData,\n error: undefined,\n }));\n\n // A page past the end (the catalog shrank) falls back to the last page once\n // the total is known.\n const totalCount = snapshot.data?.totalCount ?? 0;\n const pageCount = pageCountFor(totalCount, pageSize);\n const requestedPage = pageState.queryKey === queryKey ? pageState.page : 1;\n const page = totalCount > 0 ? Math.min(requestedPage, pageCount) : requestedPage;\n\n const requestKey = `${queryKey}|${page}|${reloads}`;\n\n const isCurrent = snapshot.requestKey === requestKey;\n\n useEffect(() => {\n if (isCurrent) {\n return;\n }\n\n const controller = new AbortController();\n fetchProductList(\n {\n projectID,\n host,\n locale,\n search,\n limit: pageSize,\n offset: (page - 1) * pageSize,\n },\n controller.signal,\n ).then(\n (data) => {\n if (controller.signal.aborted) {\n return;\n }\n setSnapshot({ requestKey, data, error: undefined });\n },\n (error: unknown) => {\n if (controller.signal.aborted) {\n return;\n }\n setSnapshot((previous) => ({\n requestKey,\n data: previous.data,\n error: error instanceof Error ? error : new Error(String(error)),\n }));\n },\n );\n\n return () => controller.abort();\n // `requestKey` carries projectID, host, locale, search, pageSize, page and\n // the reload counter.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [requestKey, isCurrent]);\n\n const setPage = useCallback(\n (next: number) => {\n const target = Math.max(1, Math.floor(next));\n setPageState({\n queryKey,\n page: totalCount > 0 ? Math.min(target, pageCount) : target,\n });\n },\n [queryKey, totalCount, pageCount],\n );\n\n const refetch = useCallback(() => setReloads((value) => value + 1), []);\n\n return useMemo(\n () => ({\n products: snapshot.data?.items ?? [],\n totalCount,\n page,\n pageCount,\n setPage,\n isLoading: !isCurrent,\n error: isCurrent ? snapshot.error : undefined,\n refetch,\n }),\n [snapshot, totalCount, page, pageCount, setPage, isCurrent, refetch],\n );\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n withCartAnalyticsMuted,\n type AnalyticsOption,\n type Instrument,\n} from \"@/src/analytics/instrument\";\nimport { DEFAULT_LOCALE } from \"../checkout/locale\";\nimport { addProductToCart, trackProductAdded } from \"./add-to-cart\";\nimport {\n getProductListSlotAppearance,\n resolveProductListAppearance,\n type ProductListAppearance,\n type ProductListSlotName,\n type ResolvedProductListAppearance,\n} from \"./appearance\";\nimport { clampPageSize, type PublicListProduct } from \"./fetch\";\nimport { formatProductPrice } from \"./format\";\nimport { createImpressionTracker } from \"./impressions\";\nimport {\n fillProductListText,\n resolveProductListTexts,\n type ProductListTexts,\n} from \"./texts\";\nimport { useProducts, type UseProductsOptions } from \"./useProducts\";\n\n/** What `renderItem` gets next to the product. */\nexport type ProductListItemContext = {\n /** Product page URL from `productHref`. */\n href: string;\n /** Price formatted for the locale and currency, without the \"from\" prefix. */\n price: string;\n /** Formatted regular price when the product is discounted. */\n compareAtPrice: string | null;\n texts: ProductListTexts;\n locale: string;\n /** Adds the product to the cart the way the built-in button does. */\n addToCart: () => Promise<void>;\n /**\n * Reports a click on the product (`product_clicked`). Call it from the link\n * a custom card renders; the built-in card does it itself.\n */\n trackClick: () => void;\n};\n\nexport type ProductListProps = UseProductsOptions & {\n /**\n * Product page URL. Defaults to the relative `/p/{uniqueSlug}`, which works\n * on a Bitsnap custom domain. Embedded on another site, return the full\n * URL of the product page.\n */\n productHref?: (product: PublicListProduct) => string;\n appearance?: ProductListAppearance;\n /** Text overrides, applied whatever the locale. */\n texts?: Partial<ProductListTexts>;\n /** Replaces the content of a card. The card frame stays. */\n renderItem?: (\n product: PublicListProduct,\n context: ProductListItemContext,\n ) => ReactNode;\n /**\n * Called by the \"Add to cart\" button instead of the default action\n * (`Bitsnap.addProductToCart`). A rejected promise shows the error message.\n */\n onAddToCart?: (product: PublicListProduct) => void | Promise<void>;\n /** Open the cart drawer after the default add to cart. Defaults to `true`. */\n showCartOnAdd?: boolean;\n className?: string;\n /**\n * Usage statistics for your Bitsnap dashboard (list views, impressions,\n * clicks, add to cart). On by default; `false` turns it off. An object\n * lets you forward every event: `{ onEvent }`. Nothing is stored on the\n * visitor's device.\n */\n analytics?: AnalyticsOption;\n};\n\ntype ListContext = {\n appearance: ResolvedProductListAppearance;\n texts: ProductListTexts;\n locale: string;\n};\n\nconst ProductListContext = createContext<ListContext | undefined>(undefined);\n\ntype CardAnalytics = {\n observe: (element: Element, id: string, position: number) => () => void;\n clicked: (product: PublicListProduct, position: number) => void;\n};\n\nconst noCardAnalytics: CardAnalytics = {\n observe: () => () => {},\n clicked: () => {},\n};\n\nconst CardAnalyticsContext = createContext<CardAnalytics>(noCardAnalytics);\n\nfunction useListContext(): ListContext {\n const value = useContext(ProductListContext);\n if (value == null) {\n throw new Error(\"ProductList parts must be rendered inside ProductList\");\n }\n return value;\n}\n\n/** Stable slot attribute, built-in classes and the caller overrides for a slot. */\nfunction useSlot(slot: ProductListSlotName, className?: string) {\n const { appearance } = useListContext();\n const override = getProductListSlotAppearance(appearance, slot);\n\n return {\n \"data-bitsnap-products-slot\": slot,\n className: cn(className, override?.className),\n style: override?.style,\n };\n}\n\nconst BUTTON_CLASS =\n \"inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50\";\nconst BLOCK_BUTTON_CLASS = `${BUTTON_CLASS} w-full`;\nconst LINK_BUTTON_CLASS = `${BLOCK_BUTTON_CLASS} no-underline`;\n\ntype AddStatus = \"idle\" | \"adding\" | \"added\" | \"error\";\n\nfunction AddToCartButton({\n product,\n onAdd,\n}: {\n product: PublicListProduct;\n onAdd: () => Promise<void>;\n}) {\n const { texts } = useListContext();\n const [status, setStatus] = useState<AddStatus>(\"idle\");\n const button = useSlot(\"addToCartButton\", BLOCK_BUTTON_CLASS);\n const message = useSlot(\"message\", \"mt-2 text-xs\");\n\n useEffect(() => {\n if (status !== \"added\") {\n return;\n }\n const timer = setTimeout(() => setStatus(\"idle\"), 2000);\n return () => clearTimeout(timer);\n }, [status]);\n\n const click = useCallback(async () => {\n setStatus(\"adding\");\n try {\n await onAdd();\n setStatus(\"added\");\n } catch (error) {\n console.error(\"bitsnap-react: could not add to the cart\", error);\n setStatus(\"error\");\n }\n }, [onAdd]);\n\n const label =\n status === \"adding\"\n ? texts.addingToCart\n : status === \"added\"\n ? texts.addedToCart\n : texts.addToCart;\n\n return (\n <>\n <button\n type=\"button\"\n {...button}\n disabled={status === \"adding\"}\n aria-label={`${label}: ${product.name}`}\n onClick={click}\n >\n {label}\n </button>\n {status === \"error\" ? (\n <p {...message} role=\"alert\">\n {texts.addToCartError}\n </p>\n ) : null}\n </>\n );\n}\n\nfunction ProductCard({\n product,\n position,\n href,\n onAdd,\n renderItem,\n}: {\n product: PublicListProduct;\n /** Index in the whole catalog (not in the current page). */\n position: number;\n href: string;\n onAdd: () => Promise<void>;\n renderItem?: ProductListProps[\"renderItem\"];\n}) {\n const { texts, locale } = useListContext();\n const analytics = useContext(CardAnalyticsContext);\n const element = useRef<HTMLLIElement>(null);\n useEffect(() => {\n if (element.current == null) {\n return;\n }\n return analytics.observe(element.current, product.id, position);\n }, [analytics, product.id, position]);\n const trackClick = useCallback(\n () => analytics.clicked(product, position),\n [analytics, product, position],\n );\n const card = useSlot(\n \"card\",\n \"relative flex flex-col overflow-hidden border transition-colors\",\n );\n const cardLink = useSlot(\"cardLink\", \"flex flex-1 flex-col no-underline\");\n const imageFrame = useSlot(\"image\", \"aspect-square w-full overflow-hidden\");\n const placeholder = useSlot(\"imagePlaceholder\", \"aspect-square w-full\");\n const body = useSlot(\"body\", \"flex flex-1 flex-col gap-1 p-4\");\n const name = useSlot(\"name\", \"text-base font-medium leading-snug\");\n const description = useSlot(\"description\", \"line-clamp-2 text-sm\");\n const price = useSlot(\"price\", \"mt-auto pt-2 text-base font-semibold\");\n const comparePrice = useSlot(\"comparePrice\", \"ml-2 text-sm font-normal\");\n const badge = useSlot(\n \"badge\",\n \"absolute left-3 top-3 px-2 py-0.5 text-xs font-medium\",\n );\n const model3dBadge = useSlot(\n \"model3dBadge\",\n \"absolute right-3 top-3 inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold\",\n );\n const actions = useSlot(\"actions\", \"p-4 pt-0\");\n const selectButton = useSlot(\"selectButton\", LINK_BUTTON_CLASS);\n\n const formattedPrice = formatProductPrice(\n product.price,\n product.currency,\n locale,\n );\n const formattedCompare =\n product.compareAtPrice != null && product.compareAtPrice > product.price\n ? formatProductPrice(product.compareAtPrice, product.currency, locale)\n : null;\n\n if (renderItem != null) {\n return (\n <li\n ref={element}\n {...card}\n data-unavailable={product.available ? undefined : \"\"}\n >\n {renderItem(product, {\n href,\n price: formattedPrice,\n compareAtPrice: formattedCompare,\n texts,\n locale,\n addToCart: onAdd,\n trackClick,\n })}\n </li>\n );\n }\n\n const imageSource = product.image?.thumbnailUrl ?? product.image?.url;\n const badgeText = !product.available\n ? texts.unavailable\n : product.isRecurring\n ? texts.subscription\n : null;\n\n return (\n <li ref={element} {...card} data-unavailable={product.available ? undefined : \"\"}>\n <a {...cardLink} href={href} onClick={trackClick}>\n {imageSource != null ? (\n <div {...imageFrame}>\n <img\n src={imageSource}\n alt=\"\"\n loading=\"lazy\"\n decoding=\"async\"\n className=\"h-full w-full object-cover\"\n />\n </div>\n ) : (\n <div {...placeholder} aria-hidden=\"true\" />\n )}\n <div {...body}>\n <h3 {...name}>{product.name}</h3>\n {product.shortDescription ? (\n <p {...description}>{product.shortDescription}</p>\n ) : null}\n <p {...price}>\n {product.priceFrom\n ? fillProductListText(texts.priceFrom, { price: formattedPrice })\n : formattedPrice}\n {formattedCompare != null ? (\n <>\n <span className=\"sr-only\">{texts.originalPrice}: </span>\n <del {...comparePrice}>{formattedCompare}</del>\n </>\n ) : null}\n </p>\n </div>\n </a>\n {badgeText != null ? (\n <span\n {...badge}\n data-kind={product.available ? \"subscription\" : \"unavailable\"}\n >\n {badgeText}\n </span>\n ) : null}\n {product.has3d === true ? (\n <span {...model3dBadge} title={texts.model3dLabel}>\n <CubeIcon />\n <span aria-hidden=\"true\">{texts.model3d}</span>\n <span className=\"sr-only\">{texts.model3dLabel}</span>\n </span>\n ) : null}\n <div {...actions}>\n {!product.available ? (\n <button type=\"button\" {...selectButton} disabled>\n {texts.unavailable}\n </button>\n ) : product.addToCart ? (\n <AddToCartButton product={product} onAdd={onAdd} />\n ) : (\n <a {...selectButton} href={href} onClick={trackClick}>\n {product.variantCount > 1 ? texts.chooseOptions : texts.viewProduct}\n </a>\n )}\n </div>\n </li>\n );\n}\n\nfunction CubeIcon() {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"12\"\n height=\"12\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z\" />\n <path d=\"m3.3 7 8.7 5 8.7-5\" />\n <path d=\"M12 22V12\" />\n </svg>\n );\n}\n\nconst GRID_CLASS =\n \"m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,var(--bitsnap-products-grid-min-width,9rem)),1fr))] gap-5 p-0\";\n\nfunction SkeletonGrid({ count, label }: { count: number; label: string }) {\n const grid = useSlot(\"grid\", GRID_CLASS);\n const skeleton = useSlot(\"skeleton\", \"aspect-[3/4] animate-pulse\");\n\n return (\n <div {...grid} role=\"status\" aria-busy=\"true\" aria-label={label}>\n {Array.from({ length: count }, (_, index) => (\n <div key={index} {...skeleton} aria-hidden=\"true\" />\n ))}\n </div>\n );\n}\n\nfunction Pagination({\n page,\n pageCount,\n isLoading,\n onPage,\n}: {\n page: number;\n pageCount: number;\n isLoading: boolean;\n onPage: (page: number) => void;\n}) {\n const { texts } = useListContext();\n const nav = useSlot(\n \"pagination\",\n \"mt-8 flex items-center justify-center gap-4\",\n );\n const button = useSlot(\"paginationButton\", BUTTON_CLASS);\n const indicator = useSlot(\"pageIndicator\", \"text-sm\");\n\n return (\n <nav {...nav} aria-label={texts.pagination}>\n <button\n type=\"button\"\n {...button}\n aria-disabled={isLoading || page <= 1}\n onClick={() => {\n if (!isLoading && page > 1) {\n onPage(page - 1);\n }\n }}\n >\n {texts.previousPage}\n </button>\n <span {...indicator} aria-live=\"polite\">\n {fillProductListText(texts.pageOf, { page, pageCount })}\n </span>\n <button\n type=\"button\"\n {...button}\n aria-disabled={isLoading || page >= pageCount}\n onClick={() => {\n if (!isLoading && page < pageCount) {\n onPage(page + 1);\n }\n }}\n >\n {texts.nextPage}\n </button>\n </nav>\n );\n}\n\nfunction ProductListContent({\n options,\n productHref,\n renderItem,\n onAddToCart,\n showCartOnAdd,\n}: {\n options: UseProductsOptions;\n productHref: (product: PublicListProduct) => string;\n renderItem?: ProductListProps[\"renderItem\"];\n onAddToCart?: ProductListProps[\"onAddToCart\"];\n showCartOnAdd: boolean;\n}) {\n const { texts } = useListContext();\n const { products, page, pageCount, setPage, isLoading, error, refetch } =\n useProducts(options);\n const instrument = useInstrumentContext();\n // The search text is never reported, only that the list was searched.\n const listId = options.search?.trim() ? \"search\" : \"catalog\";\n const pageSize = clampPageSize(options.pageSize);\n\n const viewed = useRef(false);\n useEffect(() => {\n if (viewed.current || isLoading || error != null) {\n return;\n }\n viewed.current = true;\n instrument.track(\"product_list_viewed\", {\n list_id: listId,\n item_count: products.length,\n });\n }, [instrument, isLoading, error, listId, products.length]);\n\n const impressions = useMemo(\n () =>\n createImpressionTracker(({ productIds, positions }) =>\n instrument.track(\"product_impression\", {\n list_id: listId,\n product_ids: productIds,\n positions,\n }),\n ),\n [instrument, listId],\n );\n useEffect(() => () => impressions.destroy(), [impressions]);\n const cardAnalytics = useMemo<CardAnalytics>(\n () => ({\n observe: impressions.observe,\n clicked: (product, position) =>\n instrument.track(\n \"product_clicked\",\n { list_id: listId, position },\n { product_id: product.id },\n ),\n }),\n [impressions, instrument, listId],\n );\n\n // After a page change by the user, move focus to the products (the button\n // that was pressed stays where it is, but the content above it changes) and\n // bring them into view once the page has loaded.\n const content = useRef<HTMLDivElement>(null);\n const movedPage = useRef(false);\n const changePage = useCallback(\n (next: number) => {\n movedPage.current = true;\n setPage(next);\n },\n [setPage],\n );\n useEffect(() => {\n if (isLoading || !movedPage.current) {\n return;\n }\n movedPage.current = false;\n content.current?.focus({ preventScroll: true });\n content.current?.scrollIntoView({ block: \"start\" });\n }, [isLoading]);\n\n const grid = useSlot(\"grid\", GRID_CLASS);\n const empty = useSlot(\"emptyState\", \"py-12 text-center text-sm\");\n const errorSlot = useSlot(\"error\", \"flex flex-col items-center gap-3 py-12 text-center text-sm\");\n const retry = useSlot(\"retryButton\", BUTTON_CLASS);\n\n const { projectID, host } = options;\n const addFor = useCallback(\n (product: PublicListProduct, href: string) => async () => {\n if (onAddToCart != null) {\n // The list reports the add itself; a cart helper called inside must not report it again.\n await withCartAnalyticsMuted(() => onAddToCart(product));\n trackProductAdded(instrument, product);\n return;\n }\n await addProductToCart(product, {\n projectID,\n host,\n showCart: showCartOnAdd,\n analytics: instrument,\n url: href,\n });\n },\n [onAddToCart, projectID, host, showCartOnAdd, instrument],\n );\n\n let body: ReactNode;\n if (isLoading && products.length === 0) {\n body = (\n <SkeletonGrid\n count={Math.min(clampPageSize(options.pageSize), 8)}\n label={texts.loading}\n />\n );\n } else if (error != null) {\n body = (\n <div {...errorSlot} role=\"alert\">\n <p>{texts.error}</p>\n <button type=\"button\" {...retry} onClick={refetch}>\n {texts.retry}\n </button>\n </div>\n );\n } else if (products.length === 0) {\n body = <p {...empty}>{texts.empty}</p>;\n } else {\n body = (\n <ul\n {...grid}\n aria-busy={isLoading || undefined}\n className={cn(grid.className, isLoading && \"opacity-60\")}\n >\n {products.map((product, index) => {\n const href = productHref(product);\n return (\n <ProductCard\n key={product.id}\n product={product}\n position={(page - 1) * pageSize + index}\n href={href}\n onAdd={addFor(product, href)}\n renderItem={renderItem}\n />\n );\n })}\n </ul>\n );\n }\n\n return (\n <CardAnalyticsContext.Provider value={cardAnalytics}>\n <div\n ref={content}\n tabIndex={-1}\n className=\"p-1 outline-none scroll-mt-4\"\n >\n {body}\n {pageCount > 1 && error == null ? (\n <Pagination\n page={page}\n pageCount={pageCount}\n isLoading={isLoading}\n onPage={changePage}\n />\n ) : null}\n </div>\n </CardAnalyticsContext.Provider>\n );\n}\n\nconst defaultProductHref = (product: PublicListProduct) =>\n `/p/${encodeURIComponent(product.uniqueSlug)}`;\n\n/**\n * Responsive grid of the shop's products with pagination, loading, empty and\n * error states. Cards link to the product page and can add to the cart.\n *\n * ```tsx\n * <ProductList projectID=\"…\" locale=\"pl-PL\" initialData={firstPage} />\n * ```\n *\n * It renders on the server: pass `initialData` (the first page, fetched on the\n * server) to have the products in the HTML; without it the server renders the\n * loading skeleton and the browser fetches the first page.\n */\nexport function ProductList({\n productHref = defaultProductHref,\n appearance,\n texts,\n renderItem,\n onAddToCart,\n showCartOnAdd = true,\n className,\n analytics,\n ...options\n}: ProductListProps) {\n const instrument: Instrument = useInstrument(\n options.projectID,\n analytics,\n \"catalog\",\n );\n const locale = options.locale ?? DEFAULT_LOCALE;\n const resolvedAppearance = useMemo(\n () => resolveProductListAppearance(appearance),\n [appearance],\n );\n const resolvedTexts = useMemo(\n () => resolveProductListTexts(locale, texts),\n [locale, texts],\n );\n const context = useMemo(\n () => ({ appearance: resolvedAppearance, texts: resolvedTexts, locale }),\n [resolvedAppearance, resolvedTexts, locale],\n );\n const root = getProductListSlotAppearance(resolvedAppearance, \"root\");\n\n return (\n <InstrumentProvider value={instrument}>\n <ProductListContext.Provider value={context}>\n <div\n data-bitsnap-products=\"root\"\n data-bitsnap-products-slot=\"root\"\n className={cn(\n \"bitsnap-react\",\n resolvedAppearance.boundaryClassName,\n className,\n root?.className,\n )}\n style={\n { ...resolvedAppearance.boundaryStyle, ...root?.style } as CSSProperties\n }\n >\n <ProductListContent\n options={options}\n productHref={productHref}\n renderItem={renderItem}\n onAddToCart={onAddToCart}\n showCartOnAdd={showCartOnAdd}\n />\n </div>\n </ProductListContext.Provider>\n </InstrumentProvider>\n );\n}\n","import { getTracker } from \"@/src/analytics/core\";\n\n/** Matches the contract's `positions` / `product_ids` array limit. */\nconst MAX_PER_EVENT = 50;\nconst FLUSH_DELAY_MS = 1000;\n\nexport type ImpressionBatch = { productIds: string[]; positions: number[] };\n\n/**\n * Collects the products that were at least half visible, each one once, and\n * hands them over in batches. Without `IntersectionObserver` nothing is\n * reported. Never throws.\n */\nexport function createImpressionTracker(\n onBatch: (batch: ImpressionBatch) => void,\n delayMs = FLUSH_DELAY_MS,\n) {\n const seen = new Set<string>();\n const targets = new Map<Element, { id: string; position: number }>();\n let pendingIds: string[] = [];\n let pendingPositions: number[] = [];\n let observer: IntersectionObserver | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let listening = false;\n\n function flush() {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n while (pendingIds.length > 0) {\n const productIds = pendingIds.slice(0, MAX_PER_EVENT);\n const positions = pendingPositions.slice(0, MAX_PER_EVENT);\n pendingIds = pendingIds.slice(MAX_PER_EVENT);\n pendingPositions = pendingPositions.slice(MAX_PER_EVENT);\n try {\n onBatch({ productIds, positions });\n } catch {}\n }\n }\n\n // The tracker flushes its own queue on `pagehide`; ours must be in it by then.\n function flushAll() {\n flush();\n try {\n getTracker()?.flush();\n } catch {}\n }\n const onVisibility = () => {\n if (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") flushAll();\n };\n\n function listen() {\n if (listening || typeof window === \"undefined\") return;\n listening = true;\n window.addEventListener(\"pagehide\", flushAll, true);\n document.addEventListener(\"visibilitychange\", onVisibility, true);\n }\n\n function getObserver(): IntersectionObserver | undefined {\n if (observer) return observer;\n if (typeof IntersectionObserver === \"undefined\") return undefined;\n observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n const target = targets.get(entry.target);\n if (!target || !entry.isIntersecting || entry.intersectionRatio < 0.5) continue;\n targets.delete(entry.target);\n observer?.unobserve(entry.target);\n if (seen.has(target.id)) continue;\n seen.add(target.id);\n pendingIds.push(target.id);\n pendingPositions.push(target.position);\n }\n if (pendingIds.length > 0 && timer === undefined) {\n timer = setTimeout(flush, delayMs);\n (timer as { unref?: () => void }).unref?.();\n }\n },\n { threshold: [0.5] },\n );\n listen();\n return observer;\n }\n\n return {\n /** Starts watching a card. Returns a function that stops. */\n observe(element: Element, id: string, position: number): () => void {\n try {\n if (seen.has(id)) return () => {};\n const watcher = getObserver();\n if (!watcher) return () => {};\n targets.set(element, { id, position });\n watcher.observe(element);\n return () => {\n targets.delete(element);\n watcher.unobserve(element);\n };\n } catch {\n return () => {};\n }\n },\n flush,\n destroy() {\n try {\n flush();\n observer?.disconnect();\n if (listening) {\n window.removeEventListener(\"pagehide\", flushAll, true);\n document.removeEventListener(\"visibilitychange\", onVisibility, true);\n listening = false;\n }\n } catch {}\n observer = undefined;\n targets.clear();\n },\n };\n}\n","import {\n lookupText,\n resolveTexts,\n type LocaleTables,\n} from \"@/src/lib/texts\";\n\n/**\n * Every string `ProductList` renders. Pass a partial object through the\n * `texts` prop to override any of them, whatever the locale. Placeholders\n * (`{price}`, `{page}`, `{pageCount}`) are filled by the component.\n */\nexport type ProductListTexts = {\n /** \"Add to cart\" button of products that can be bought straight from the list. */\n addToCart: string;\n /** Button label while the product is being added. */\n addingToCart: string;\n /** Button label after the product was added. */\n addedToCart: string;\n /** Message shown when adding to the cart failed. */\n addToCartError: string;\n /** Link of products with variants, to pick one on the product page. */\n chooseOptions: string;\n /** Link of products that cannot be added from the list (subscriptions). */\n viewProduct: string;\n /** Label of products that are out of stock. */\n unavailable: string;\n /** Badge of subscription products. */\n subscription: string;\n /** Badge of products with a 3D model. */\n model3d: string;\n /** Screen reader label of the 3D badge. */\n model3dLabel: string;\n /** Price of products whose variants differ in price. `{price}` is the lowest one. */\n priceFrom: string;\n /** Screen reader label of the struck-through regular price. */\n originalPrice: string;\n /** Accessible label of the loading skeleton. */\n loading: string;\n /** Shown when the shop has no products (or none matches the search). */\n empty: string;\n /** Shown when the products could not be loaded. */\n error: string;\n /** Retry button of the error state. */\n retry: string;\n /** Accessible label of the pagination. */\n pagination: string;\n previousPage: string;\n nextPage: string;\n /** Page indicator. `{page}` and `{pageCount}` are filled in. */\n pageOf: string;\n};\n\nexport type ProductListTextKey = keyof ProductListTexts;\n\nexport const PRODUCT_LIST_TEXT_TABLES: LocaleTables<ProductListTextKey> = {\n en: {\n addToCart: \"Add to cart\",\n addingToCart: \"Adding…\",\n addedToCart: \"Added to cart\",\n addToCartError: \"Could not add to the cart. Try again.\",\n chooseOptions: \"Choose\",\n viewProduct: \"View\",\n unavailable: \"Unavailable\",\n subscription: \"Subscription\",\n model3d: \"3D\",\n model3dLabel: \"3D model\",\n priceFrom: \"from {price}\",\n originalPrice: \"Original price\",\n loading: \"Loading products\",\n empty: \"There are no products to show.\",\n error: \"Could not load the products.\",\n retry: \"Try again\",\n pagination: \"Pagination\",\n previousPage: \"Previous\",\n nextPage: \"Next\",\n pageOf: \"Page {page} of {pageCount}\",\n },\n pl: {\n addToCart: \"Dodaj do koszyka\",\n addingToCart: \"Dodawanie…\",\n addedToCart: \"Dodano do koszyka\",\n addToCartError: \"Nie udało się dodać do koszyka. Spróbuj ponownie.\",\n chooseOptions: \"Wybierz\",\n viewProduct: \"Zobacz\",\n unavailable: \"Niedostępny\",\n subscription: \"Subskrypcja\",\n model3d: \"3D\",\n model3dLabel: \"Model 3D\",\n priceFrom: \"od {price}\",\n originalPrice: \"Cena przed obniżką\",\n loading: \"Ładowanie produktów\",\n empty: \"Brak produktów do wyświetlenia.\",\n error: \"Nie udało się załadować produktów.\",\n retry: \"Spróbuj ponownie\",\n pagination: \"Paginacja\",\n previousPage: \"Poprzednia\",\n nextPage: \"Następna\",\n pageOf: \"Strona {page} z {pageCount}\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveProductListTexts(\n locale: string,\n overrides?: Partial<ProductListTexts>,\n): ProductListTexts {\n return resolveTexts(PRODUCT_LIST_TEXT_TABLES, locale, overrides);\n}\n\nexport function getProductListText(\n key: ProductListTextKey,\n locale: string,\n overrides?: Partial<ProductListTexts>,\n): string {\n return lookupText(resolveProductListTexts(locale, overrides), key);\n}\n\n/** Replaces `{name}` placeholders. Unknown placeholders stay untouched. */\nexport function fillProductListText(\n text: string,\n values: Record<string, string | number>,\n): string {\n return text.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in values ? String(values[name]) : match,\n );\n}\n"],"mappings":"4UA6DO,IAAMA,GAA0B,CACrC,OACA,OACA,OACA,WACA,QACA,mBACA,OACA,OACA,cACA,QACA,eACA,QACA,eACA,UACA,kBACA,eACA,UACA,aACA,mBACA,gBACA,aACA,QACA,cACA,UACF,EA8BaC,GAA+B,CAC1C,WAAY,iCACZ,aAAc,oCACd,SAAU,+BACV,WAAY,gCACZ,QAAS,6BACT,WAAY,gCACZ,gBAAiB,sCACjB,OAAQ,4BACR,iBAAkB,uCAClB,iBAAkB,uCAClB,sBAAuB,6CACvB,aAAc,mCACd,UAAW,gCACX,MAAO,2BACP,gBAAiB,sCACjB,gBAAiB,sCACjB,OAAQ,2BACV,EASaC,GAGT,CACF,MAAO,CACL,WAAY,UACZ,QAAS,UACT,WAAY,UACZ,gBAAiB,UACjB,OAAQ,UACR,iBAAkB,UAClB,iBAAkB,UAClB,sBAAuB,UACvB,aAAc,UACd,UAAW,UACX,MAAO,UACP,gBAAiB,UACjB,gBAAiB,UACjB,OAAQ,MACR,aAAc,MAChB,EACA,KAAM,CACJ,WAAY,UACZ,QAAS,UACT,WAAY,UACZ,gBAAiB,UACjB,OAAQ,UACR,iBAAkB,UAClB,iBAAkB,UAClB,sBAAuB,UACvB,aAAc,UACd,UAAW,UACX,MAAO,UACP,gBAAiB,UACjB,gBAAiB,UACjB,OAAQ,MACR,aAAc,MAChB,CACF,EAGMC,GACJ,CAAC,EAEI,SAASC,GACdC,EAC+B,CAC/B,IAAMC,EAAWC,GAIfF,EAAY,CACZ,aAAc,QACd,QAASH,GACT,UAAWD,GACX,gBAAiBE,EACnB,CAAC,EAED,MAAO,CACL,MAAOG,EAAS,MAChB,OAAQA,EAAS,OACjB,SAAUA,EAAS,SACnB,kBAAmBA,EAAS,MAC5B,cAAeA,EAAS,aAC1B,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BAAsB,OACtB,6BAA2B,OAC3B,UAAWe,EACT,gBACAoG,EAAmB,kBACnBxG,EACA6G,GAAM,SACR,EACA,MACE,CAAE,GAAGL,EAAmB,cAAe,GAAGK,GAAM,KAAM,EAGxD,SAAAxH,EAAC6E,GAAA,CACC,QAASC,EACT,YAAaC,EACb,WAAY1C,EACZ,YAAa2C,EACb,cAAeC,EACjB,EACF,EACF,EACA,CAEJ","names":["PRODUCT_LIST_SLOT_NAMES","PRODUCT_LIST_TOKEN_VARIABLES","PRODUCT_LIST_THEME_PRESETS","PRODUCT_LIST_SHADCN_VARIABLES","resolveProductListAppearance","appearance","resolved","resolveAppearanceCore","getProductListSlotAppearance","slot","getSlotAppearance","useCallback","useEffect","useMemo","useState","useProducts","options","projectID","locale","search","initialData","defaultHost","useState","HOST","host","pageSize","clampPageSize","queryKey","pageState","setPageState","reloads","setReloads","snapshot","setSnapshot","totalCount","pageCount","pageCountFor","requestedPage","page","requestKey","isCurrent","useEffect","controller","fetchProductList","data","error","previous","setPage","useCallback","next","target","refetch","value","useMemo","createContext","useCallback","useContext","useEffect","useMemo","useRef","useState","MAX_PER_EVENT","FLUSH_DELAY_MS","createImpressionTracker","onBatch","delayMs","seen","targets","pendingIds","pendingPositions","observer","timer","listening","flush","productIds","positions","flushAll","getTracker","onVisibility","listen","getObserver","entries","entry","target","element","id","position","watcher","PRODUCT_LIST_TEXT_TABLES","resolveProductListTexts","locale","overrides","resolveTexts","fillProductListText","text","values","match","name","Fragment","jsx","jsxs","ProductListContext","createContext","noCardAnalytics","CardAnalyticsContext","useListContext","value","useContext","useSlot","slot","className","appearance","override","getProductListSlotAppearance","cn","BUTTON_CLASS","BLOCK_BUTTON_CLASS","LINK_BUTTON_CLASS","AddToCartButton","product","onAdd","texts","status","setStatus","useState","button","message","useEffect","timer","click","useCallback","error","label","ProductCard","position","href","renderItem","locale","analytics","element","useRef","trackClick","card","cardLink","imageFrame","placeholder","body","name","description","price","comparePrice","badge","model3dBadge","actions","selectButton","formattedPrice","formatProductPrice","formattedCompare","imageSource","badgeText","fillProductListText","CubeIcon","GRID_CLASS","SkeletonGrid","count","grid","skeleton","_","index","Pagination","page","pageCount","isLoading","onPage","nav","indicator","ProductListContent","options","productHref","onAddToCart","showCartOnAdd","products","setPage","refetch","useProducts","instrument","useInstrumentContext","listId","pageSize","clampPageSize","viewed","impressions","useMemo","createImpressionTracker","productIds","positions","cardAnalytics","content","movedPage","changePage","next","empty","errorSlot","retry","projectID","host","addFor","withCartAnalyticsMuted","trackProductAdded","addProductToCart","defaultProductHref","ProductList","useInstrument","DEFAULT_LOCALE","resolvedAppearance","resolveProductListAppearance","resolvedTexts","resolveProductListTexts","context","root","InstrumentProvider"]}
|
|
1
|
+
{"version":3,"sources":["../src/components/products/appearance.ts","../src/components/products/useProducts.ts","../src/components/products/ProductList.tsx","../src/components/products/impressions.ts","../src/components/products/texts.ts"],"sourcesContent":["import type { CSSProperties } from \"react\";\nimport {\n getSlotAppearance,\n resolveAppearanceCore,\n type AppearanceElements,\n type ShadcnVariableMapping,\n type SlotAppearance,\n} from \"@/src/lib/appearance-core\";\n\n/**\n * Product list appearance API.\n *\n * It mirrors `CheckoutAppearance` and `ReturnsAppearance` (theme, tokens,\n * elements) so a shop can reuse one brand object for all of them. The resolver\n * is pure: it turns the caller input into a theme name, the tokens in effect,\n * the slot overrides and the inline style for the theme boundary.\n */\n\nexport type ProductListTheme = \"light\" | \"dark\";\n\nexport type ProductListAppearanceTokens = {\n /** Font family of the list. The library never loads fonts. */\n fontFamily?: string;\n /** Minimum grid track width. Use \"100%\" for one column. */\n gridMinWidth?: string;\n /** Base font size. */\n fontSize?: string;\n /** List background. */\n background?: string;\n /** Raised surfaces: cards, image placeholders, skeletons. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, the struck-through price. */\n mutedForeground?: string;\n /** Borders of cards and buttons. */\n border?: string;\n /** \"Add to cart\" button background. */\n buttonBackground?: string;\n /** \"Add to cart\" button text. */\n buttonForeground?: string;\n /** \"Add to cart\" button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of cards and secondary buttons. */\n hoverSurface?: string;\n /** Focus ring color. */\n focusRing?: string;\n /** Error and unavailable state color. */\n error?: string;\n /** Badge background (subscription, unavailable). */\n badgeBackground?: string;\n /** Badge text. */\n badgeForeground?: string;\n /** Corner radius of cards, images and buttons. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-products-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const PRODUCT_LIST_SLOT_NAMES = [\n \"root\",\n \"grid\",\n \"card\",\n \"cardLink\",\n \"image\",\n \"imagePlaceholder\",\n \"body\",\n \"name\",\n \"description\",\n \"price\",\n \"comparePrice\",\n \"badge\",\n \"model3dBadge\",\n \"actions\",\n \"addToCartButton\",\n \"selectButton\",\n \"message\",\n \"pagination\",\n \"paginationButton\",\n \"pageIndicator\",\n \"emptyState\",\n \"error\",\n \"retryButton\",\n \"skeleton\",\n] as const;\n\nexport type ProductListSlotName = (typeof PRODUCT_LIST_SLOT_NAMES)[number];\n\nexport type ProductListSlotAppearance = SlotAppearance;\n\nexport type ProductListAppearanceElements =\n AppearanceElements<ProductListSlotName>;\n\nexport type ProductListAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ProductListTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ProductListAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ProductListAppearanceElements;\n};\n\nexport type ResolvedProductListAppearance = {\n theme: ProductListTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ProductListAppearanceTokens;\n elements: ProductListAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the list root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const PRODUCT_LIST_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-products-font-family\",\n gridMinWidth: \"--bitsnap-products-grid-min-width\",\n fontSize: \"--bitsnap-products-font-size\",\n background: \"--bitsnap-products-background\",\n surface: \"--bitsnap-products-surface\",\n foreground: \"--bitsnap-products-foreground\",\n mutedForeground: \"--bitsnap-products-muted-foreground\",\n border: \"--bitsnap-products-border\",\n buttonBackground: \"--bitsnap-products-button-background\",\n buttonForeground: \"--bitsnap-products-button-foreground\",\n buttonHoverBackground: \"--bitsnap-products-button-hover-background\",\n hoverSurface: \"--bitsnap-products-hover-surface\",\n focusRing: \"--bitsnap-products-focus-ring\",\n error: \"--bitsnap-products-error\",\n badgeBackground: \"--bitsnap-products-badge-background\",\n badgeForeground: \"--bitsnap-products-badge-foreground\",\n radius: \"--bitsnap-products-radius\",\n} as const;\n\nexport type ProductListTokenName = keyof typeof PRODUCT_LIST_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `products.css` falls back to the light values, which keeps\n * the list usable even when the boundary style is missing.\n */\nexport const PRODUCT_LIST_THEME_PRESETS: Record<\n ProductListTheme,\n ProductListAppearanceTokens\n> = {\n light: {\n background: \"#ffffff\",\n surface: \"#f9fafb\",\n foreground: \"#18181b\",\n mutedForeground: \"#71717a\",\n border: \"#e4e4e7\",\n buttonBackground: \"#18181b\",\n buttonForeground: \"#fafafa\",\n buttonHoverBackground: \"#000000\",\n hoverSurface: \"#f4f4f5\",\n focusRing: \"#71717a\",\n error: \"#dc2626\",\n badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n radius: \"8px\",\n gridMinWidth: \"9rem\",\n },\n dark: {\n background: \"#18181b\",\n surface: \"#27272a\",\n foreground: \"#fafafa\",\n mutedForeground: \"#a1a1aa\",\n border: \"#3f3f46\",\n buttonBackground: \"#fafafa\",\n buttonForeground: \"#18181b\",\n buttonHoverBackground: \"#e4e4e7\",\n hoverSurface: \"#3f3f46\",\n focusRing: \"#a1a1aa\",\n error: \"#f87171\",\n badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n radius: \"8px\",\n gridMinWidth: \"9rem\",\n },\n};\n\n/** The list renders its own elements, so no shared primitive needs remapping. */\nconst PRODUCT_LIST_SHADCN_VARIABLES: ShadcnVariableMapping<ProductListTokenName> =\n [];\n\nexport function resolveProductListAppearance(\n appearance?: ProductListAppearance,\n): ResolvedProductListAppearance {\n const resolved = resolveAppearanceCore<\n ProductListTokenName,\n ProductListTheme,\n ProductListSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: PRODUCT_LIST_THEME_PRESETS,\n variables: PRODUCT_LIST_TOKEN_VARIABLES,\n shadcnVariables: PRODUCT_LIST_SHADCN_VARIABLES,\n });\n\n return {\n theme: resolved.theme,\n tokens: resolved.tokens,\n elements: resolved.elements,\n boundaryClassName: resolved.theme,\n boundaryStyle: resolved.boundaryStyle,\n };\n}\n\n/** Caller overrides for a single slot, if any were provided. */\nexport function getProductListSlotAppearance(\n resolved: ResolvedProductListAppearance,\n slot: ProductListSlotName,\n): ProductListSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { HOST } from \"../checkout/constants\";\nimport {\n clampPageSize,\n fetchProductList,\n pageCountFor,\n type ProductListData,\n type PublicListProduct,\n} from \"./fetch\";\n\nexport type UseProductsOptions = {\n /** Project (shop) ID. */\n projectID: string;\n /**\n * Origin of the Bitsnap backend. Defaults to the library host\n * (`https://bitsnap.pl`, or what `setCustomHost` had set when the component\n * first rendered; later `setCustomHost` calls do not move an existing list).\n * On a custom domain pass the domain itself, or an empty string for\n * same-origin requests.\n */\n host?: string;\n locale?: string;\n /** Products per page, 1 to 48. Defaults to 24. */\n pageSize?: number;\n search?: string;\n /**\n * First page, loaded on the server. It is always used for the first request\n * of the mounted list (the first fetch is skipped and the products are\n * available on the first render), so it has to be the page the props ask\n * for: page 1 with the same `pageSize`, `locale` and `search`. Later changes\n * of the props fetch again.\n */\n initialData?: ProductListData;\n};\n\nexport type UseProductsResult = {\n /** Products of the current page. Keeps the previous page while loading. */\n products: PublicListProduct[];\n totalCount: number;\n /** Current page, starting at 1. */\n page: number;\n pageCount: number;\n setPage: (page: number) => void;\n /** `true` until the current page is available, also during server rendering. */\n isLoading: boolean;\n error: Error | undefined;\n /** Loads the current page again. */\n refetch: () => void;\n};\n\ntype Snapshot = {\n /** Request the data belongs to; empty when it is not tied to one. */\n requestKey: string;\n data: ProductListData | undefined;\n error: Error | undefined;\n};\n\n/**\n * Loads the product catalog page by page. It uses a plain `fetch` without\n * credentials, never reads global state (`setProjectID`, `setCustomHost`) other\n * than the default host, and does nothing during server rendering - pass\n * `initialData` to render products in the server HTML.\n */\nexport function useProducts(options: UseProductsOptions): UseProductsResult {\n const { projectID, locale, search, initialData } = options;\n // The library host is a mutable global; read it once so a later\n // `setCustomHost` does not change the query of a mounted list.\n const [defaultHost] = useState(() => HOST);\n const host = options.host ?? defaultHost;\n const pageSize = clampPageSize(options.pageSize);\n\n // Everything that identifies a list; a change resets the page.\n const queryKey = JSON.stringify([\n projectID,\n host,\n locale ?? null,\n search?.trim() ?? null,\n pageSize,\n ]);\n\n const [pageState, setPageState] = useState({ queryKey, page: 1 });\n if (pageState.queryKey !== queryKey) {\n // Another list: start from page 1 (adjusting state while rendering).\n setPageState({ queryKey, page: 1 });\n }\n const [reloads, setReloads] = useState(0);\n const [snapshot, setSnapshot] = useState<Snapshot>(() => ({\n requestKey: initialData != null ? `${queryKey}|1|0` : \"\",\n data: initialData,\n error: undefined,\n }));\n\n // A page past the end (the catalog shrank) falls back to the last page once\n // the total is known.\n const totalCount = snapshot.data?.totalCount ?? 0;\n const pageCount = pageCountFor(totalCount, pageSize);\n const requestedPage = pageState.queryKey === queryKey ? pageState.page : 1;\n const page = totalCount > 0 ? Math.min(requestedPage, pageCount) : requestedPage;\n\n const requestKey = `${queryKey}|${page}|${reloads}`;\n\n const isCurrent = snapshot.requestKey === requestKey;\n\n useEffect(() => {\n if (isCurrent) {\n return;\n }\n\n const controller = new AbortController();\n fetchProductList(\n {\n projectID,\n host,\n locale,\n search,\n limit: pageSize,\n offset: (page - 1) * pageSize,\n },\n controller.signal,\n ).then(\n (data) => {\n if (controller.signal.aborted) {\n return;\n }\n setSnapshot({ requestKey, data, error: undefined });\n },\n (error: unknown) => {\n if (controller.signal.aborted) {\n return;\n }\n setSnapshot((previous) => ({\n requestKey,\n data: previous.data,\n error: error instanceof Error ? error : new Error(String(error)),\n }));\n },\n );\n\n return () => controller.abort();\n // `requestKey` carries projectID, host, locale, search, pageSize, page and\n // the reload counter.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [requestKey, isCurrent]);\n\n const setPage = useCallback(\n (next: number) => {\n const target = Math.max(1, Math.floor(next));\n setPageState({\n queryKey,\n page: totalCount > 0 ? Math.min(target, pageCount) : target,\n });\n },\n [queryKey, totalCount, pageCount],\n );\n\n const refetch = useCallback(() => setReloads((value) => value + 1), []);\n\n return useMemo(\n () => ({\n products: snapshot.data?.items ?? [],\n totalCount,\n page,\n pageCount,\n setPage,\n isLoading: !isCurrent,\n error: isCurrent ? snapshot.error : undefined,\n refetch,\n }),\n [snapshot, totalCount, page, pageCount, setPage, isCurrent, refetch],\n );\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n withCartAnalyticsMuted,\n type AnalyticsOption,\n type Instrument,\n} from \"@/src/analytics/instrument\";\nimport { DEFAULT_LOCALE } from \"../checkout/locale\";\nimport { addProductToCart, trackProductAdded } from \"./add-to-cart\";\nimport {\n getProductListSlotAppearance,\n resolveProductListAppearance,\n type ProductListAppearance,\n type ProductListSlotName,\n type ResolvedProductListAppearance,\n} from \"./appearance\";\nimport { clampPageSize, type PublicListProduct } from \"./fetch\";\nimport { formatProductPrice } from \"./format\";\nimport { createImpressionTracker } from \"./impressions\";\nimport {\n fillProductListText,\n resolveProductListTexts,\n type ProductListTexts,\n} from \"./texts\";\nimport { useProducts, type UseProductsOptions } from \"./useProducts\";\n\n/** What `renderItem` gets next to the product. */\nexport type ProductListItemContext = {\n /** Product page URL from `productHref`. */\n href: string;\n /** Price formatted for the locale and currency, without the \"from\" prefix. */\n price: string;\n /** Formatted regular price when the product is discounted. */\n compareAtPrice: string | null;\n texts: ProductListTexts;\n locale: string;\n /** Adds the product to the cart the way the built-in button does. */\n addToCart: () => Promise<void>;\n /**\n * Reports a click on the product (`product_clicked`). Call it from the link\n * a custom card renders; the built-in card does it itself.\n */\n trackClick: () => void;\n};\n\nexport type ProductListProps = UseProductsOptions & {\n /**\n * Product page URL. Defaults to the relative `/p/{uniqueSlug}`, which works\n * on a Bitsnap custom domain. Embedded on another site, return the full\n * URL of the product page.\n */\n productHref?: (product: PublicListProduct) => string;\n appearance?: ProductListAppearance;\n /** Text overrides, applied whatever the locale. */\n texts?: Partial<ProductListTexts>;\n /** Replaces the content of a card. The card frame stays. */\n renderItem?: (\n product: PublicListProduct,\n context: ProductListItemContext,\n ) => ReactNode;\n /**\n * Called by the \"Add to cart\" button instead of the default action\n * (`Bitsnap.addProductToCart`). A rejected promise shows the error message.\n */\n onAddToCart?: (product: PublicListProduct) => void | Promise<void>;\n /** Open the cart drawer after the default add to cart. Defaults to `true`. */\n showCartOnAdd?: boolean;\n className?: string;\n /**\n * Usage statistics for your Bitsnap dashboard (list views, impressions,\n * clicks, add to cart). On by default; `false` turns it off. An object\n * lets you forward every event: `{ onEvent }`. Nothing is stored on the\n * visitor's device.\n */\n analytics?: AnalyticsOption;\n};\n\ntype ListContext = {\n appearance: ResolvedProductListAppearance;\n texts: ProductListTexts;\n locale: string;\n};\n\nconst ProductListContext = createContext<ListContext | undefined>(undefined);\n\ntype CardAnalytics = {\n observe: (element: Element, id: string, position: number) => () => void;\n clicked: (product: PublicListProduct, position: number) => void;\n};\n\nconst noCardAnalytics: CardAnalytics = {\n observe: () => () => {},\n clicked: () => {},\n};\n\nconst CardAnalyticsContext = createContext<CardAnalytics>(noCardAnalytics);\n\nfunction useListContext(): ListContext {\n const value = useContext(ProductListContext);\n if (value == null) {\n throw new Error(\"ProductList parts must be rendered inside ProductList\");\n }\n return value;\n}\n\n/** Stable slot attribute, built-in classes and the caller overrides for a slot. */\nfunction useSlot(slot: ProductListSlotName, className?: string) {\n const { appearance } = useListContext();\n const override = getProductListSlotAppearance(appearance, slot);\n\n return {\n \"data-bitsnap-products-slot\": slot,\n className: cn(className, override?.className),\n style: override?.style,\n };\n}\n\nconst BUTTON_CLASS =\n \"inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50\";\nconst BLOCK_BUTTON_CLASS = `${BUTTON_CLASS} w-full`;\nconst LINK_BUTTON_CLASS = `${BLOCK_BUTTON_CLASS} no-underline`;\n\ntype AddStatus = \"idle\" | \"adding\" | \"added\" | \"error\";\n\nfunction AddToCartButton({\n product,\n onAdd,\n}: {\n product: PublicListProduct;\n onAdd: () => Promise<void>;\n}) {\n const { texts } = useListContext();\n const [status, setStatus] = useState<AddStatus>(\"idle\");\n const button = useSlot(\"addToCartButton\", BLOCK_BUTTON_CLASS);\n const message = useSlot(\"message\", \"mt-2 text-xs\");\n\n useEffect(() => {\n if (status !== \"added\") {\n return;\n }\n const timer = setTimeout(() => setStatus(\"idle\"), 2000);\n return () => clearTimeout(timer);\n }, [status]);\n\n const click = useCallback(async () => {\n setStatus(\"adding\");\n try {\n await onAdd();\n setStatus(\"added\");\n } catch (error) {\n console.error(\"bitsnap-react: could not add to the cart\", error);\n setStatus(\"error\");\n }\n }, [onAdd]);\n\n const label =\n status === \"adding\"\n ? texts.addingToCart\n : status === \"added\"\n ? texts.addedToCart\n : texts.addToCart;\n\n return (\n <>\n <button\n type=\"button\"\n {...button}\n disabled={status === \"adding\"}\n aria-label={`${label}: ${product.name}`}\n onClick={click}\n >\n {label}\n </button>\n {status === \"error\" ? (\n <p {...message} role=\"alert\">\n {texts.addToCartError}\n </p>\n ) : null}\n </>\n );\n}\n\nfunction ProductCard({\n product,\n position,\n href,\n onAdd,\n renderItem,\n}: {\n product: PublicListProduct;\n /** Index in the whole catalog (not in the current page). */\n position: number;\n href: string;\n onAdd: () => Promise<void>;\n renderItem?: ProductListProps[\"renderItem\"];\n}) {\n const { texts, locale } = useListContext();\n const analytics = useContext(CardAnalyticsContext);\n const element = useRef<HTMLLIElement>(null);\n useEffect(() => {\n if (element.current == null) {\n return;\n }\n return analytics.observe(element.current, product.id, position);\n }, [analytics, product.id, position]);\n const trackClick = useCallback(\n () => analytics.clicked(product, position),\n [analytics, product, position],\n );\n const card = useSlot(\n \"card\",\n \"relative flex flex-col overflow-hidden border transition-colors\",\n );\n const cardLink = useSlot(\"cardLink\", \"flex flex-1 flex-col no-underline\");\n const imageFrame = useSlot(\"image\", \"aspect-square w-full overflow-hidden\");\n const placeholder = useSlot(\"imagePlaceholder\", \"aspect-square w-full\");\n const body = useSlot(\"body\", \"flex flex-1 flex-col gap-1 p-4\");\n const name = useSlot(\"name\", \"text-base font-medium leading-snug\");\n const description = useSlot(\"description\", \"line-clamp-2 text-sm\");\n const price = useSlot(\"price\", \"mt-auto pt-2 text-base font-semibold\");\n const comparePrice = useSlot(\"comparePrice\", \"ml-2 text-sm font-normal\");\n const badge = useSlot(\n \"badge\",\n \"absolute left-3 top-3 px-2 py-0.5 text-xs font-medium\",\n );\n const model3dBadge = useSlot(\n \"model3dBadge\",\n \"absolute right-3 top-3 inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold\",\n );\n const actions = useSlot(\"actions\", \"p-4 pt-0\");\n const selectButton = useSlot(\"selectButton\", LINK_BUTTON_CLASS);\n\n const formattedPrice = formatProductPrice(\n product.price,\n product.currency,\n locale,\n );\n const formattedCompare =\n product.compareAtPrice != null && product.compareAtPrice > product.price\n ? formatProductPrice(product.compareAtPrice, product.currency, locale)\n : null;\n\n if (renderItem != null) {\n return (\n <li\n ref={element}\n {...card}\n data-unavailable={product.available ? undefined : \"\"}\n >\n {renderItem(product, {\n href,\n price: formattedPrice,\n compareAtPrice: formattedCompare,\n texts,\n locale,\n addToCart: onAdd,\n trackClick,\n })}\n </li>\n );\n }\n\n const imageSource = product.image?.thumbnailUrl ?? product.image?.url;\n const badgeText = !product.available\n ? texts.unavailable\n : product.isRecurring\n ? texts.subscription\n : null;\n\n return (\n <li ref={element} {...card} data-unavailable={product.available ? undefined : \"\"}>\n <a {...cardLink} href={href} onClick={trackClick}>\n {imageSource != null ? (\n <div {...imageFrame}>\n <img\n src={imageSource}\n alt=\"\"\n loading=\"lazy\"\n decoding=\"async\"\n className=\"h-full w-full object-cover\"\n />\n </div>\n ) : (\n <div {...placeholder} aria-hidden=\"true\" />\n )}\n <div {...body}>\n <h3 {...name}>{product.name}</h3>\n {product.shortDescription ? (\n <p {...description}>{product.shortDescription}</p>\n ) : null}\n <p {...price}>\n {product.priceFrom\n ? fillProductListText(texts.priceFrom, { price: formattedPrice })\n : formattedPrice}\n {formattedCompare != null ? (\n <>\n <span className=\"sr-only\">{texts.originalPrice}: </span>\n <del {...comparePrice}>{formattedCompare}</del>\n </>\n ) : null}\n </p>\n </div>\n </a>\n {badgeText != null ? (\n <span\n {...badge}\n data-kind={product.available ? \"subscription\" : \"unavailable\"}\n >\n {badgeText}\n </span>\n ) : null}\n {product.has3d === true ? (\n <span {...model3dBadge} title={texts.model3dLabel}>\n <CubeIcon />\n <span aria-hidden=\"true\">{texts.model3d}</span>\n <span className=\"sr-only\">{texts.model3dLabel}</span>\n </span>\n ) : null}\n <div {...actions}>\n {!product.available ? (\n <button type=\"button\" {...selectButton} disabled>\n {texts.unavailable}\n </button>\n ) : product.addToCart ? (\n <AddToCartButton product={product} onAdd={onAdd} />\n ) : (\n <a {...selectButton} href={href} onClick={trackClick}>\n {product.variantCount > 1 ? texts.chooseOptions : texts.viewProduct}\n </a>\n )}\n </div>\n </li>\n );\n}\n\nfunction CubeIcon() {\n return (\n <svg\n viewBox=\"0 0 24 24\"\n width=\"12\"\n height=\"12\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z\" />\n <path d=\"m3.3 7 8.7 5 8.7-5\" />\n <path d=\"M12 22V12\" />\n </svg>\n );\n}\n\nconst GRID_CLASS =\n \"m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,var(--bitsnap-products-grid-min-width,9rem)),1fr))] gap-5 p-0\";\n\nfunction SkeletonGrid({ count, label }: { count: number; label: string }) {\n const grid = useSlot(\"grid\", GRID_CLASS);\n const skeleton = useSlot(\"skeleton\", \"aspect-[3/4] animate-pulse\");\n\n return (\n <div {...grid} role=\"status\" aria-busy=\"true\" aria-label={label}>\n {Array.from({ length: count }, (_, index) => (\n <div key={index} {...skeleton} aria-hidden=\"true\" />\n ))}\n </div>\n );\n}\n\nfunction Pagination({\n page,\n pageCount,\n isLoading,\n onPage,\n}: {\n page: number;\n pageCount: number;\n isLoading: boolean;\n onPage: (page: number) => void;\n}) {\n const { texts } = useListContext();\n const nav = useSlot(\n \"pagination\",\n \"mt-8 flex items-center justify-center gap-4\",\n );\n const button = useSlot(\"paginationButton\", BUTTON_CLASS);\n const indicator = useSlot(\"pageIndicator\", \"text-sm\");\n\n return (\n <nav {...nav} aria-label={texts.pagination}>\n <button\n type=\"button\"\n {...button}\n aria-disabled={isLoading || page <= 1}\n onClick={() => {\n if (!isLoading && page > 1) {\n onPage(page - 1);\n }\n }}\n >\n {texts.previousPage}\n </button>\n <span {...indicator} aria-live=\"polite\">\n {fillProductListText(texts.pageOf, { page, pageCount })}\n </span>\n <button\n type=\"button\"\n {...button}\n aria-disabled={isLoading || page >= pageCount}\n onClick={() => {\n if (!isLoading && page < pageCount) {\n onPage(page + 1);\n }\n }}\n >\n {texts.nextPage}\n </button>\n </nav>\n );\n}\n\nfunction ProductListContent({\n options,\n productHref,\n renderItem,\n onAddToCart,\n showCartOnAdd,\n}: {\n options: UseProductsOptions;\n productHref: (product: PublicListProduct) => string;\n renderItem?: ProductListProps[\"renderItem\"];\n onAddToCart?: ProductListProps[\"onAddToCart\"];\n showCartOnAdd: boolean;\n}) {\n const { texts } = useListContext();\n const { products, page, pageCount, setPage, isLoading, error, refetch } =\n useProducts(options);\n const instrument = useInstrumentContext();\n // The search text is never reported, only that the list was searched.\n const listId = options.search?.trim() ? \"search\" : \"catalog\";\n const pageSize = clampPageSize(options.pageSize);\n\n const viewed = useRef(false);\n useEffect(() => {\n if (viewed.current || isLoading || error != null) {\n return;\n }\n viewed.current = true;\n instrument.track(\"product_list_viewed\", {\n list_id: listId,\n item_count: products.length,\n });\n }, [instrument, isLoading, error, listId, products.length]);\n\n const impressions = useMemo(\n () =>\n createImpressionTracker(({ productIds, positions }) =>\n instrument.track(\"product_impression\", {\n list_id: listId,\n product_ids: productIds,\n positions,\n }),\n ),\n [instrument, listId],\n );\n useEffect(() => () => impressions.destroy(), [impressions]);\n const cardAnalytics = useMemo<CardAnalytics>(\n () => ({\n observe: impressions.observe,\n clicked: (product, position) =>\n instrument.track(\n \"product_clicked\",\n { list_id: listId, position },\n { product_id: product.id },\n ),\n }),\n [impressions, instrument, listId],\n );\n\n // After a page change by the user, move focus to the products (the button\n // that was pressed stays where it is, but the content above it changes) and\n // bring them into view once the page has loaded.\n const content = useRef<HTMLDivElement>(null);\n const movedPage = useRef(false);\n const changePage = useCallback(\n (next: number) => {\n movedPage.current = true;\n setPage(next);\n },\n [setPage],\n );\n useEffect(() => {\n if (isLoading || !movedPage.current) {\n return;\n }\n movedPage.current = false;\n content.current?.focus({ preventScroll: true });\n content.current?.scrollIntoView({ block: \"start\" });\n }, [isLoading]);\n\n const grid = useSlot(\"grid\", GRID_CLASS);\n const empty = useSlot(\"emptyState\", \"py-12 text-center text-sm\");\n const errorSlot = useSlot(\"error\", \"flex flex-col items-center gap-3 py-12 text-center text-sm\");\n const retry = useSlot(\"retryButton\", BUTTON_CLASS);\n\n const { projectID, host } = options;\n const addFor = useCallback(\n (product: PublicListProduct, href: string) => async () => {\n if (onAddToCart != null) {\n // The list reports the add itself; a cart helper called inside must not report it again.\n await withCartAnalyticsMuted(() => onAddToCart(product));\n trackProductAdded(instrument, product);\n return;\n }\n await addProductToCart(product, {\n projectID,\n host,\n showCart: showCartOnAdd,\n analytics: instrument,\n url: href,\n });\n },\n [onAddToCart, projectID, host, showCartOnAdd, instrument],\n );\n\n let body: ReactNode;\n if (isLoading && products.length === 0) {\n body = (\n <SkeletonGrid\n count={Math.min(clampPageSize(options.pageSize), 8)}\n label={texts.loading}\n />\n );\n } else if (error != null) {\n body = (\n <div {...errorSlot} role=\"alert\">\n <p>{texts.error}</p>\n <button type=\"button\" {...retry} onClick={refetch}>\n {texts.retry}\n </button>\n </div>\n );\n } else if (products.length === 0) {\n body = <p {...empty}>{texts.empty}</p>;\n } else {\n body = (\n <ul\n {...grid}\n aria-busy={isLoading || undefined}\n className={cn(grid.className, isLoading && \"opacity-60\")}\n >\n {products.map((product, index) => {\n const href = productHref(product);\n return (\n <ProductCard\n key={product.id}\n product={product}\n position={(page - 1) * pageSize + index}\n href={href}\n onAdd={addFor(product, href)}\n renderItem={renderItem}\n />\n );\n })}\n </ul>\n );\n }\n\n return (\n <CardAnalyticsContext.Provider value={cardAnalytics}>\n <div\n ref={content}\n tabIndex={-1}\n className=\"p-1 outline-none scroll-mt-4\"\n >\n {body}\n {pageCount > 1 && error == null ? (\n <Pagination\n page={page}\n pageCount={pageCount}\n isLoading={isLoading}\n onPage={changePage}\n />\n ) : null}\n </div>\n </CardAnalyticsContext.Provider>\n );\n}\n\nconst defaultProductHref = (product: PublicListProduct) =>\n `/p/${encodeURIComponent(product.uniqueSlug)}`;\n\n/**\n * Responsive grid of the shop's products with pagination, loading, empty and\n * error states. Cards link to the product page and can add to the cart.\n *\n * ```tsx\n * <ProductList projectID=\"…\" locale=\"pl-PL\" initialData={firstPage} />\n * ```\n *\n * It renders on the server: pass `initialData` (the first page, fetched on the\n * server) to have the products in the HTML; without it the server renders the\n * loading skeleton and the browser fetches the first page.\n */\nexport function ProductList({\n productHref = defaultProductHref,\n appearance,\n texts,\n renderItem,\n onAddToCart,\n showCartOnAdd = true,\n className,\n analytics,\n ...options\n}: ProductListProps) {\n const instrument: Instrument = useInstrument(\n options.projectID,\n analytics,\n \"catalog\",\n );\n const locale = options.locale ?? DEFAULT_LOCALE;\n const resolvedAppearance = useMemo(\n () => resolveProductListAppearance(appearance),\n [appearance],\n );\n const resolvedTexts = useMemo(\n () => resolveProductListTexts(locale, texts),\n [locale, texts],\n );\n const context = useMemo(\n () => ({ appearance: resolvedAppearance, texts: resolvedTexts, locale }),\n [resolvedAppearance, resolvedTexts, locale],\n );\n const root = getProductListSlotAppearance(resolvedAppearance, \"root\");\n\n return (\n <InstrumentProvider value={instrument}>\n <ProductListContext.Provider value={context}>\n <div\n data-bitsnap-products=\"root\"\n data-bitsnap-products-slot=\"root\"\n className={cn(\n \"bitsnap-react\",\n resolvedAppearance.boundaryClassName,\n className,\n root?.className,\n )}\n style={\n { ...resolvedAppearance.boundaryStyle, ...root?.style } as CSSProperties\n }\n >\n <ProductListContent\n options={options}\n productHref={productHref}\n renderItem={renderItem}\n onAddToCart={onAddToCart}\n showCartOnAdd={showCartOnAdd}\n />\n </div>\n </ProductListContext.Provider>\n </InstrumentProvider>\n );\n}\n","import { getTracker } from \"@/src/analytics/core\";\n\n/** Matches the contract's `positions` / `product_ids` array limit. */\nconst MAX_PER_EVENT = 50;\nconst FLUSH_DELAY_MS = 1000;\n\nexport type ImpressionBatch = { productIds: string[]; positions: number[] };\n\n/**\n * Collects the products that were at least half visible, each one once, and\n * hands them over in batches. Without `IntersectionObserver` nothing is\n * reported. Never throws.\n */\nexport function createImpressionTracker(\n onBatch: (batch: ImpressionBatch) => void,\n delayMs = FLUSH_DELAY_MS,\n) {\n const seen = new Set<string>();\n const targets = new Map<Element, { id: string; position: number }>();\n let pendingIds: string[] = [];\n let pendingPositions: number[] = [];\n let observer: IntersectionObserver | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let listening = false;\n\n function flush() {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n while (pendingIds.length > 0) {\n const productIds = pendingIds.slice(0, MAX_PER_EVENT);\n const positions = pendingPositions.slice(0, MAX_PER_EVENT);\n pendingIds = pendingIds.slice(MAX_PER_EVENT);\n pendingPositions = pendingPositions.slice(MAX_PER_EVENT);\n try {\n onBatch({ productIds, positions });\n } catch {}\n }\n }\n\n // The tracker flushes its own queue on `pagehide`; ours must be in it by then.\n function flushAll() {\n flush();\n try {\n getTracker()?.flush();\n } catch {}\n }\n const onVisibility = () => {\n if (typeof document !== \"undefined\" && document.visibilityState === \"hidden\") flushAll();\n };\n\n function listen() {\n if (listening || typeof window === \"undefined\") return;\n listening = true;\n window.addEventListener(\"pagehide\", flushAll, true);\n document.addEventListener(\"visibilitychange\", onVisibility, true);\n }\n\n function getObserver(): IntersectionObserver | undefined {\n if (observer) return observer;\n if (typeof IntersectionObserver === \"undefined\") return undefined;\n observer = new IntersectionObserver(\n (entries) => {\n for (const entry of entries) {\n const target = targets.get(entry.target);\n if (!target || !entry.isIntersecting || entry.intersectionRatio < 0.5) continue;\n targets.delete(entry.target);\n observer?.unobserve(entry.target);\n if (seen.has(target.id)) continue;\n seen.add(target.id);\n pendingIds.push(target.id);\n pendingPositions.push(target.position);\n }\n if (pendingIds.length > 0 && timer === undefined) {\n timer = setTimeout(flush, delayMs);\n (timer as { unref?: () => void }).unref?.();\n }\n },\n { threshold: [0.5] },\n );\n listen();\n return observer;\n }\n\n return {\n /** Starts watching a card. Returns a function that stops. */\n observe(element: Element, id: string, position: number): () => void {\n try {\n if (seen.has(id)) return () => {};\n const watcher = getObserver();\n if (!watcher) return () => {};\n targets.set(element, { id, position });\n watcher.observe(element);\n return () => {\n targets.delete(element);\n watcher.unobserve(element);\n };\n } catch {\n return () => {};\n }\n },\n flush,\n destroy() {\n try {\n flush();\n observer?.disconnect();\n if (listening) {\n window.removeEventListener(\"pagehide\", flushAll, true);\n document.removeEventListener(\"visibilitychange\", onVisibility, true);\n listening = false;\n }\n } catch {}\n observer = undefined;\n targets.clear();\n },\n };\n}\n","import {\n lookupText,\n resolveTexts,\n type LocaleTables,\n} from \"@/src/lib/texts\";\n\n/**\n * Every string `ProductList` renders. Pass a partial object through the\n * `texts` prop to override any of them, whatever the locale. Placeholders\n * (`{price}`, `{page}`, `{pageCount}`) are filled by the component.\n */\nexport type ProductListTexts = {\n /** \"Add to cart\" button of products that can be bought straight from the list. */\n addToCart: string;\n /** Button label while the product is being added. */\n addingToCart: string;\n /** Button label after the product was added. */\n addedToCart: string;\n /** Message shown when adding to the cart failed. */\n addToCartError: string;\n /** Link of products with variants, to pick one on the product page. */\n chooseOptions: string;\n /** Link of products that cannot be added from the list (subscriptions). */\n viewProduct: string;\n /** Label of products that are out of stock. */\n unavailable: string;\n /** Badge of subscription products. */\n subscription: string;\n /** Badge of products with a 3D model. */\n model3d: string;\n /** Screen reader label of the 3D badge. */\n model3dLabel: string;\n /** Price of products whose variants differ in price. `{price}` is the lowest one. */\n priceFrom: string;\n /** Screen reader label of the struck-through regular price. */\n originalPrice: string;\n /** Accessible label of the loading skeleton. */\n loading: string;\n /** Shown when the shop has no products (or none matches the search). */\n empty: string;\n /** Shown when the products could not be loaded. */\n error: string;\n /** Retry button of the error state. */\n retry: string;\n /** Accessible label of the pagination. */\n pagination: string;\n previousPage: string;\n nextPage: string;\n /** Page indicator. `{page}` and `{pageCount}` are filled in. */\n pageOf: string;\n};\n\nexport type ProductListTextKey = keyof ProductListTexts;\n\nexport const PRODUCT_LIST_TEXT_TABLES: LocaleTables<ProductListTextKey> = {\n en: {\n addToCart: \"Add to cart\",\n addingToCart: \"Adding…\",\n addedToCart: \"Added to cart\",\n addToCartError: \"Could not add to the cart. Try again.\",\n chooseOptions: \"Choose\",\n viewProduct: \"View\",\n unavailable: \"Unavailable\",\n subscription: \"Subscription\",\n model3d: \"3D\",\n model3dLabel: \"3D model\",\n priceFrom: \"from {price}\",\n originalPrice: \"Original price\",\n loading: \"Loading products\",\n empty: \"There are no products to show.\",\n error: \"Could not load the products.\",\n retry: \"Try again\",\n pagination: \"Pagination\",\n previousPage: \"Previous\",\n nextPage: \"Next\",\n pageOf: \"Page {page} of {pageCount}\",\n },\n pl: {\n addToCart: \"Dodaj do koszyka\",\n addingToCart: \"Dodawanie…\",\n addedToCart: \"Dodano do koszyka\",\n addToCartError: \"Nie udało się dodać do koszyka. Spróbuj ponownie.\",\n chooseOptions: \"Wybierz\",\n viewProduct: \"Zobacz\",\n unavailable: \"Niedostępny\",\n subscription: \"Subskrypcja\",\n model3d: \"3D\",\n model3dLabel: \"Model 3D\",\n priceFrom: \"od {price}\",\n originalPrice: \"Cena przed obniżką\",\n loading: \"Ładowanie produktów\",\n empty: \"Brak produktów do wyświetlenia.\",\n error: \"Nie udało się załadować produktów.\",\n retry: \"Spróbuj ponownie\",\n pagination: \"Paginacja\",\n previousPage: \"Poprzednia\",\n nextPage: \"Następna\",\n pageOf: \"Strona {page} z {pageCount}\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveProductListTexts(\n locale: string,\n overrides?: Partial<ProductListTexts>,\n): ProductListTexts {\n return resolveTexts(PRODUCT_LIST_TEXT_TABLES, locale, overrides);\n}\n\nexport function getProductListText(\n key: ProductListTextKey,\n locale: string,\n overrides?: Partial<ProductListTexts>,\n): string {\n return lookupText(resolveProductListTexts(locale, overrides), key);\n}\n\n/** Replaces `{name}` placeholders. Unknown placeholders stay untouched. */\nexport function fillProductListText(\n text: string,\n values: Record<string, string | number>,\n): string {\n return text.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n name in values ? String(values[name]) : match,\n );\n}\n"],"mappings":"8WA6DO,IAAMA,GAA0B,CACrC,OACA,OACA,OACA,WACA,QACA,mBACA,OACA,OACA,cACA,QACA,eACA,QACA,eACA,UACA,kBACA,eACA,UACA,aACA,mBACA,gBACA,aACA,QACA,cACA,UACF,EA8BaC,GAA+B,CAC1C,WAAY,iCACZ,aAAc,oCACd,SAAU,+BACV,WAAY,gCACZ,QAAS,6BACT,WAAY,gCACZ,gBAAiB,sCACjB,OAAQ,4BACR,iBAAkB,uCAClB,iBAAkB,uCAClB,sBAAuB,6CACvB,aAAc,mCACd,UAAW,gCACX,MAAO,2BACP,gBAAiB,sCACjB,gBAAiB,sCACjB,OAAQ,2BACV,EASaC,GAGT,CACF,MAAO,CACL,WAAY,UACZ,QAAS,UACT,WAAY,UACZ,gBAAiB,UACjB,OAAQ,UACR,iBAAkB,UAClB,iBAAkB,UAClB,sBAAuB,UACvB,aAAc,UACd,UAAW,UACX,MAAO,UACP,gBAAiB,UACjB,gBAAiB,UACjB,OAAQ,MACR,aAAc,MAChB,EACA,KAAM,CACJ,WAAY,UACZ,QAAS,UACT,WAAY,UACZ,gBAAiB,UACjB,OAAQ,UACR,iBAAkB,UAClB,iBAAkB,UAClB,sBAAuB,UACvB,aAAc,UACd,UAAW,UACX,MAAO,UACP,gBAAiB,UACjB,gBAAiB,UACjB,OAAQ,MACR,aAAc,MAChB,CACF,EAGMC,GACJ,CAAC,EAEI,SAASC,GACdC,EAC+B,CAC/B,IAAMC,EAAWC,GAIfF,EAAY,CACZ,aAAc,QACd,QAASH,GACT,UAAWD,GACX,gBAAiBE,EACnB,CAAC,EAED,MAAO,CACL,MAAOG,EAAS,MAChB,OAAQA,EAAS,OACjB,SAAUA,EAAS,SACnB,kBAAmBA,EAAS,MAC5B,cAAeA,EAAS,aAC1B,CACF,CAGO,SAASE,EACdF,EACAG,EACuC,CACvC,OA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ACAoG,EAAmB,kBACnBxG,EACA6G,GAAM,SACR,EACA,MACE,CAAE,GAAGL,EAAmB,cAAe,GAAGK,GAAM,KAAM,EAGxD,SAAAxH,EAAC6E,GAAA,CACC,QAASC,EACT,YAAaC,EACb,WAAY1C,EACZ,YAAa2C,EACb,cAAeC,EACjB,EACF,EACF,EACA,CAEJ","names":["PRODUCT_LIST_SLOT_NAMES","PRODUCT_LIST_TOKEN_VARIABLES","PRODUCT_LIST_THEME_PRESETS","PRODUCT_LIST_SHADCN_VARIABLES","resolveProductListAppearance","appearance","resolved","resolveAppearanceCore","getProductListSlotAppearance","slot","getSlotAppearance","useCallback","useEffect","useMemo","useState","useProducts","options","projectID","locale","search","initialData","defaultHost","useState","HOST","host","pageSize","clampPageSize","queryKey","pageState","setPageState","reloads","setReloads","snapshot","setSnapshot","totalCount","pageCount","pageCountFor","requestedPage","page","requestKey","isCurrent","useEffect","controller","fetchProductList","data","error","previous","setPage","useCallback","next","target","refetch","value","useMemo","createContext","useCallback","useContext","useEffect","useMemo","useRef","useState","MAX_PER_EVENT","FLUSH_DELAY_MS","createImpressionTracker","onBatch","delayMs","seen","targets","pendingIds","pendingPositions","observer","timer","listening","flush","productIds","positions","flushAll","getTracker","onVisibility","listen","getObserver","entries","entry","target","element","id","position","watcher","PRODUCT_LIST_TEXT_TABLES","resolveProductListTexts","locale","overrides","resolveTexts","fillProductListText","text","values","match","name","Fragment","jsx","jsxs","ProductListContext","createContext","noCardAnalytics","CardAnalyticsContext","useListContext","value","useContext","useSlot","slot","className","appearance","override","getProductListSlotAppearance","cn","BUTTON_CLASS","BLOCK_BUTTON_CLASS","LINK_BUTTON_CLASS","AddToCartButton","product","onAdd","texts","status","setStatus","useState","button","message","useEffect","timer","click","useCallback","error","label","ProductCard","position","href","renderItem","locale","analytics","element","useRef","trackClick","card","cardLink","imageFrame","placeholder","body","name","description","price","comparePrice","badge","model3dBadge","actions","selectButton","formattedPrice","formatProductPrice","formattedCompare","imageSource","badgeText","fillProductListText","CubeIcon","GRID_CLASS","SkeletonGrid","count","grid","skeleton","_","index","Pagination","page","pageCount","isLoading","onPage","nav","indicator","ProductListContent","options","productHref","onAddToCart","showCartOnAdd","products","setPage","refetch","useProducts","instrument","useInstrumentContext","listId","pageSize","clampPageSize","viewed","impressions","useMemo","createImpressionTracker","productIds","positions","cardAnalytics","content","movedPage","changePage","next","empty","errorSlot","retry","projectID","host","addFor","withCartAnalyticsMuted","trackProductAdded","addProductToCart","defaultProductHref","ProductList","useInstrument","DEFAULT_LOCALE","resolvedAppearance","resolveProductListAppearance","resolvedTexts","resolveProductListTexts","context","root","InstrumentProvider"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkD2ASWUXMjs = require('./chunk-D2ASWUXM.js');var s="X-Bitsnap-Client",n=`bitsnap-react@${_chunkD2ASWUXMjs.a}`,i="bs_client",E= exports.a ={[s]:n},T= exports.b =t=>e=>(e.header.set(s,n),t(e));function C(t){let e=t.indexOf("#"),o=e===-1?t:t.slice(0,e),c=e===-1?"":t.slice(e),p=o.includes("?")?/[?&]$/.test(o)?"":"&":"?";return`${o}${p}${i}=${encodeURIComponent(n)}${c}`}var a="https://bitsnap.pl",l= exports.e =a;function _(t){console.log("setCustomHost",t),l= exports.e =t}var _clsx = require('clsx');var _tailwindmerge = require('tailwind-merge');function H(...t){return _tailwindmerge.twMerge.call(void 0, _clsx.clsx.call(void 0, t))}exports.a = E; exports.b = T; exports.c = C; exports.d = a; exports.e = l; exports.f = _; exports.g = H;
|
|
2
|
+
//# sourceMappingURL=chunk-DOJICJCQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-DOJICJCQ.js","../src/lib/client-header.ts"],"names":["CLIENT_HEADER_NAME","CLIENT_HEADER_VALUE","SDK_VERSION"],"mappings":"AAAA,+HAAuC,ICG1BA,CAAAA,CAAqB,kBAAA,CACrBC,CAAAA,CAAsB,CAAA,cAAA,EAAiBC,kBAAW,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-DOJICJCQ.js","sourcesContent":[null,"import type { Interceptor } from \"@connectrpc/connect\";\nimport { SDK_VERSION } from \"../version\";\n\nexport const CLIENT_HEADER_NAME = \"X-Bitsnap-Client\";\nexport const CLIENT_HEADER_VALUE = `bitsnap-react@${SDK_VERSION}`;\n\nexport const CLIENT_QUERY_PARAM = \"bs_client\";\n\n/**\n * Spread into the `headers` of a fetch that already triggers a CORS preflight\n * (JSON POST, Connect RPC). Never use it on a simple cross-origin GET: the\n * custom header would force a preflight that older servers and merchant\n * proxies do not allow. Use `withClientParam` there.\n */\nexport const clientHeaders: Record<string, string> = {\n [CLIENT_HEADER_NAME]: CLIENT_HEADER_VALUE,\n};\n\n/** Connect interceptor adding the client header to every RPC. */\nexport const clientHeaderInterceptor: Interceptor = (next) => (req) => {\n req.header.set(CLIENT_HEADER_NAME, CLIENT_HEADER_VALUE);\n return next(req);\n};\n\n/** Adds `bs_client=<pkg>@<ver>` to a URL, for simple GETs that must stay preflight-free. */\nexport function withClientParam(url: string): string {\n const hash = url.indexOf(\"#\");\n const base = hash === -1 ? url : url.slice(0, hash);\n const fragment = hash === -1 ? \"\" : url.slice(hash);\n const separator = base.includes(\"?\") ? (/[?&]$/.test(base) ? \"\" : \"&\") : \"?\";\n return `${base}${separator}${CLIENT_QUERY_PARAM}=${encodeURIComponent(CLIENT_HEADER_VALUE)}${fragment}`;\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{d as n}from"./chunk-OFPRIENJ.mjs";function i(r,t){try{return new Intl.NumberFormat(r,{style:"currency",currency:t,currencyDisplay:"symbol"})}catch{return}}function a(r,t,u=n){let e=r/100,o=i(u,t)??i(n,t);return o!=null?o.format(e):`${e.toFixed(2)} ${t}`}export{a};
|
|
2
|
+
//# sourceMappingURL=chunk-EMR4YXNY.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/components/products/format.ts"],"sourcesContent":["import { DEFAULT_LOCALE } from \"../checkout/locale\";\n\nfunction createFormatter(\n locale: string,\n currency: string,\n): Intl.NumberFormat | undefined {\n try {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n currencyDisplay: \"symbol\",\n });\n } catch {\n // RangeError: invalid locale or currency code.\n return undefined;\n }\n}\n\n/**\n * Formats a price in minor units (grosze, cents) for the locale, the same way\n * the cart does (`amount / 100`). An unknown locale falls back to Polish and an\n * invalid currency code to a plain number followed by the code.\n */\nexport function formatProductPrice(\n amount: number,\n currency: string,\n locale: string = DEFAULT_LOCALE,\n): string {\n const value = amount / 100;\n const formatter =\n createFormatter(locale, currency) ??\n createFormatter(DEFAULT_LOCALE, currency);\n\n return formatter != null\n ? formatter.format(value)\n : `${value.toFixed(2)} ${currency}`;\n}\n"],"mappings":"yCAEA,SAASA,EACPC,EACAC,EAC+B,CAC/B,GAAI,CACF,OAAO,IAAI,KAAK,aAAaD,EAAQ,CACnC,MAAO,WACP,SAAAC,EACA,gBAAiB,QACnB,CAAC,CACH,MAAQ,CAEN,MACF,CACF,CAOO,SAASC,EACdC,EACAF,EACAD,EAAiBI,EACT,CACR,IAAMC,EAAQF,EAAS,IACjBG,EACJP,EAAgBC,EAAQC,CAAQ,GAChCF,EAAgBK,EAAgBH,CAAQ,EAE1C,OAAOK,GAAa,KAChBA,EAAU,OAAOD,CAAK,EACtB,GAAGA,EAAM,QAAQ,CAAC,CAAC,IAAIJ,CAAQ,EACrC","names":["createFormatter","locale","currency","formatProductPrice","amount","DEFAULT_LOCALE","value","formatter"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkBUYTK7KMjs = require('./chunk-BUYTK7KM.js');var _chunkDOJICJCQjs = require('./chunk-DOJICJCQ.js');var M=["orders","order","confirmation","result","myReturns","myReturn"];function k(e){return M.includes(e)}function L(e){return e?{name:"orders"}:{name:"email"}}function U(e,s){switch(s.type){case"SESSION_EXPIRED":return k(e.name)?{name:"email"}:e;case"CODE_SENT":return e.name==="email"?{name:"code"}:e;case"AUTHENTICATED":return e.name==="email"||e.name==="code"?{name:"orders"}:e;case"SELECT_ORDER":return e.name==="orders"?{name:"order",orderId:s.orderId}:e;case"REVIEW":return e.name==="order"?{name:"confirmation",orderId:e.orderId,items:s.items,note:s.note}:e;case"SUBMITTED":return e.name==="confirmation"?{name:"result",returnId:s.returnId}:e;case"OPEN_MY_RETURNS":return e.name==="orders"||e.name==="result"?{name:"myReturns"}:e;case"SELECT_RETURN":return e.name==="myReturns"?{name:"myReturn",returnId:s.returnId}:e;case"CONTINUE":return e.name==="result"?{name:"orders"}:e;case"BACK":switch(e.name){case"code":return{name:"email"};case"order":case"myReturns":return{name:"orders"};case"confirmation":return{name:"order",orderId:e.orderId,items:e.items,note:e.note};case"myReturn":return{name:"myReturns"};default:return e}}}var K={email:1,code:2,orders:3,order:4,confirmation:5,result:6},B=6;function D(e){return K[e]}var _react = require('react');var _jsxruntime = require('react/jsx-runtime');function V({current:e}){let s=_chunkBUYTK7KMjs.r.call(void 0, ),o=_chunkBUYTK7KMjs.o.call(void 0, "stepIndicator");return _jsxruntime.jsx.call(void 0, "p",{"data-bitsnap-returns-slot":"stepIndicator",className:_chunkDOJICJCQjs.g.call(void 0, "text-xs",o.className),style:o.style,children:s("stepIndicator",{current:e,total:B})})}function W({panelToken:e,logo:s}){let{status:o,challenge:a,projectID:x}=_chunkBUYTK7KMjs.t.call(void 0, "BitsnapReturns"),A=_chunkBUYTK7KMjs.s.call(void 0, ),[r,t]=_react.useReducer.call(void 0, U,L(!1));_react.useEffect.call(void 0, ()=>{o==="authenticated"?t({type:"AUTHENTICATED"}):o==="anonymous"&&t({type:"SESSION_EXPIRED"})},[o]);let i=_react.useRef.call(void 0, !1);if(_react.useEffect.call(void 0, ()=>{i.current||o==="hydrating"||(i.current=!0,o==="anonymous"&&a!=null&&t({type:"CODE_SENT"}))},[o,a]),o==="exchanging"||o==="hydrating"&&e)return _jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.C,{});let m=D(r.name),b=r.name==="email"||r.name==="code";return _jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-4",children:[b&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.c,{projectId:x,locale:A,...s}),m!=null&&_jsxruntime.jsx.call(void 0, V,{current:m}),r.name==="email"&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.D,{showLogo:!1,onSubmitted:()=>t({type:"CODE_SENT"})}),r.name==="code"&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.E,{showLogo:!1,onVerified:()=>t({type:"AUTHENTICATED"}),onBack:()=>t({type:"BACK"})}),r.name==="orders"&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.F,{showLogout:!e,onSelectOrder:u=>t({type:"SELECT_ORDER",orderId:u}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="order"&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.G,{orderId:r.orderId,initialItems:r.items,initialNote:r.note,onBack:()=>t({type:"BACK"}),onContinue:({items:u,note:h})=>t({type:"REVIEW",items:u,note:h})}),r.name==="confirmation"&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.H,{orderId:r.orderId,items:r.items,note:r.note,onBack:()=>t({type:"BACK"}),onSubmitted:u=>t({type:"SUBMITTED",returnId:u})}),r.name==="result"&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.I,{returnId:r.returnId,onContinue:()=>t({type:"CONTINUE"}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="myReturns"&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.J,{onSelectReturn:u=>t({type:"SELECT_RETURN",returnId:u}),onBack:()=>t({type:"BACK"})}),r.name==="myReturn"&&_jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.K,{returnId:r.returnId,onBack:()=>t({type:"BACK"})})]})}function re({showLogo:e,logoUrl:s,logoDarkUrl:o,...a}){return _jsxruntime.jsx.call(void 0, _chunkBUYTK7KMjs.u,{...a,children:_jsxruntime.jsx.call(void 0, W,{panelToken:a.panelAccessToken!=null&&a.panelAccessToken!=="",logo:{showLogo:e,logoUrl:s,logoDarkUrl:o}})})}exports.a = re;
|
|
2
|
+
//# sourceMappingURL=chunk-GJOGATP6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-GJOGATP6.js","../src/components/returns/state-machine.ts","../src/components/returns/BitsnapReturns.tsx"],"names":["STEPS_WITH_SESSION","stepRequiresSession","step","initialReturnsStep","hasSession","reduceReturnsStep","event","STEP_NUMBERS","RETURNS_STEP_COUNT","returnsStepNumber","StepIndicator","current","text","useReturnsText","slot","useReturnsSlot","jsx","cn","ReturnsRouter","panelToken","logo","status","challenge","projectID","useReturnsContext","locale","useReturnsLocale","dispatch","useReducer","useEffect","restored","useRef","SkeletonRows","stepNumber","loginStep","jsxs","LoginBrandLogo","ReturnsEmailStep","ReturnsCodeStep","ReturnsOrderList","orderId","ReturnsOrderDetail","items","note","ReturnsConfirmation","returnId","ReturnsResult","ReturnsMyReturnsList","ReturnsMyReturnDetail","BitsnapReturns","showLogo","logoUrl","logoDarkUrl","props","ReturnsProvider"],"mappings":"AAAA,+HAAyI,sDAAwC,IC8C3KA,CAAAA,CAAiD,CACrD,QAAA,CACA,OAAA,CACA,cAAA,CACA,QAAA,CACA,WAAA,CACA,UACF,CAA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snap-react/emems-chat-v1/dist/chunk-GJOGATP6.js","sourcesContent":[null,"/** One line chosen for return. */\nexport type SelectedReturnLine = {\n lineId: string;\n quantity: number;\n};\n\n/** Where the default flow of `BitsnapReturns` currently is. */\nexport type ReturnsStep =\n | { name: \"email\" }\n | { name: \"code\" }\n | { name: \"orders\" }\n | {\n name: \"order\";\n orderId: string;\n /** Selection to restore when coming back from the confirmation. */\n items?: SelectedReturnLine[];\n note?: string;\n }\n | {\n name: \"confirmation\";\n orderId: string;\n items: SelectedReturnLine[];\n note: string;\n }\n | { name: \"result\"; returnId: string }\n | { name: \"myReturns\" }\n | { name: \"myReturn\"; returnId: string };\n\nexport type ReturnsStepName = ReturnsStep[\"name\"];\n\nexport type ReturnsStepEvent =\n /** A verification code was requested. */\n | { type: \"CODE_SENT\" }\n /** The session became valid: code verified, stored session or panel token. */\n | { type: \"AUTHENTICATED\" }\n /** The session was dropped by the backend, expiry or logout. */\n | { type: \"SESSION_EXPIRED\" }\n | { type: \"SELECT_ORDER\"; orderId: string }\n | { type: \"REVIEW\"; items: SelectedReturnLine[]; note: string }\n | { type: \"SUBMITTED\"; returnId: string }\n | { type: \"OPEN_MY_RETURNS\" }\n | { type: \"SELECT_RETURN\"; returnId: string }\n | { type: \"BACK\" }\n /** Leave the result screen for the order list. */\n | { type: \"CONTINUE\" };\n\nconst STEPS_WITH_SESSION: readonly ReturnsStepName[] = [\n \"orders\",\n \"order\",\n \"confirmation\",\n \"result\",\n \"myReturns\",\n \"myReturn\",\n];\n\n/** Steps that cannot be shown without a returns session. */\nexport function stepRequiresSession(step: ReturnsStepName): boolean {\n return STEPS_WITH_SESSION.includes(step);\n}\n\n/** Starts at the orders when a session exists, otherwise at the email. */\nexport function initialReturnsStep(hasSession: boolean): ReturnsStep {\n return hasSession ? { name: \"orders\" } : { name: \"email\" };\n}\n\n/**\n * Pure transition function of the default flow. Events that do not apply to\n * the current step leave it unchanged.\n */\nexport function reduceReturnsStep(\n step: ReturnsStep,\n event: ReturnsStepEvent,\n): ReturnsStep {\n switch (event.type) {\n case \"SESSION_EXPIRED\":\n // Email and code do not need a session; keep a pending verification.\n return stepRequiresSession(step.name) ? { name: \"email\" } : step;\n case \"CODE_SENT\":\n return step.name === \"email\" ? { name: \"code\" } : step;\n case \"AUTHENTICATED\":\n return step.name === \"email\" || step.name === \"code\"\n ? { name: \"orders\" }\n : step;\n case \"SELECT_ORDER\":\n return step.name === \"orders\"\n ? { name: \"order\", orderId: event.orderId }\n : step;\n case \"REVIEW\":\n return step.name === \"order\"\n ? {\n name: \"confirmation\",\n orderId: step.orderId,\n items: event.items,\n note: event.note,\n }\n : step;\n case \"SUBMITTED\":\n return step.name === \"confirmation\"\n ? { name: \"result\", returnId: event.returnId }\n : step;\n case \"OPEN_MY_RETURNS\":\n return step.name === \"orders\" || step.name === \"result\"\n ? { name: \"myReturns\" }\n : step;\n case \"SELECT_RETURN\":\n return step.name === \"myReturns\"\n ? { name: \"myReturn\", returnId: event.returnId }\n : step;\n case \"CONTINUE\":\n return step.name === \"result\" ? { name: \"orders\" } : step;\n case \"BACK\":\n switch (step.name) {\n case \"code\":\n return { name: \"email\" };\n case \"order\":\n case \"myReturns\":\n return { name: \"orders\" };\n case \"confirmation\":\n return {\n name: \"order\",\n orderId: step.orderId,\n items: step.items,\n note: step.note,\n };\n case \"myReturn\":\n return { name: \"myReturns\" };\n default:\n return step;\n }\n }\n}\n\nconst STEP_NUMBERS: Partial<Record<ReturnsStepName, number>> = {\n email: 1,\n code: 2,\n orders: 3,\n order: 4,\n confirmation: 5,\n result: 6,\n};\n\nexport const RETURNS_STEP_COUNT = 6;\n\n/** Position of a step in the return flow, `undefined` for the \"my returns\" views. */\nexport function returnsStepNumber(step: ReturnsStepName): number | undefined {\n return STEP_NUMBERS[step];\n}\n","import { useEffect, useReducer, useRef } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport {\n LoginBrandLogo,\n type LoginLogoOptions,\n} from \"@/src/ui/email-code-login/LoginBrandLogo\";\nimport { useReturnsSlot } from \"./appearance.context\";\nimport { ReturnsCodeStep, ReturnsEmailStep } from \"./AuthSteps\";\nimport { SkeletonRows } from \"./internal\";\nimport { ReturnsMyReturnDetail, ReturnsMyReturnsList } from \"./MyReturns\";\nimport {\n ReturnsConfirmation,\n ReturnsOrderDetail,\n ReturnsOrderList,\n ReturnsResult,\n} from \"./OrderSteps\";\nimport {\n ReturnsProvider,\n useReturnsContext,\n type ReturnsProviderProps,\n} from \"./ReturnsProvider\";\nimport {\n initialReturnsStep,\n reduceReturnsStep,\n RETURNS_STEP_COUNT,\n returnsStepNumber,\n} from \"./state-machine\";\nimport { useReturnsLocale, useReturnsText } from \"./texts.context\";\n\n/**\n * Props of {@link BitsnapReturns}. `showLogo`, `logoUrl` and `logoDarkUrl` set\n * the shop logo above the e-mail and code steps: by default the logo from the\n * shop settings, or Bitsnap's when the shop has none.\n */\nexport type BitsnapReturnsProps = Omit<ReturnsProviderProps, \"children\"> &\n LoginLogoOptions;\n\nfunction StepIndicator({ current }: { current: number }) {\n const text = useReturnsText();\n const slot = useReturnsSlot(\"stepIndicator\");\n\n return (\n <p\n data-bitsnap-returns-slot=\"stepIndicator\"\n className={cn(\"text-xs\", slot.className)}\n style={slot.style}\n >\n {text(\"stepIndicator\", { current, total: RETURNS_STEP_COUNT })}\n </p>\n );\n}\n\n/** Default step router. All transitions come from the pure state machine. */\nfunction ReturnsRouter({\n panelToken,\n logo,\n}: {\n panelToken: boolean;\n logo: LoginLogoOptions;\n}) {\n const { status, challenge, projectID } = useReturnsContext(\"BitsnapReturns\");\n const locale = useReturnsLocale();\n const [step, dispatch] = useReducer(\n reduceReturnsStep,\n initialReturnsStep(false),\n );\n\n // A valid session (verified code, stored session, exchanged panel token)\n // moves on to the orders; a dropped one returns to the start.\n useEffect(() => {\n if (status === \"authenticated\") {\n dispatch({ type: \"AUTHENTICATED\" });\n } else if (status === \"anonymous\") {\n dispatch({ type: \"SESSION_EXPIRED\" });\n }\n }, [status]);\n\n // A verification that was pending before a reload or an app switch returns\n // to the code step once, when the stored state has been read.\n const restored = useRef(false);\n useEffect(() => {\n if (restored.current || status === \"hydrating\") {\n return;\n }\n restored.current = true;\n if (status === \"anonymous\" && challenge != null) {\n dispatch({ type: \"CODE_SENT\" });\n }\n }, [status, challenge]);\n\n // Without a panel token the server render and the first client render show\n // the email step; a stored session switches to the orders after hydration.\n if (status === \"exchanging\" || (status === \"hydrating\" && panelToken)) {\n return <SkeletonRows />;\n }\n\n const stepNumber = returnsStepNumber(step.name);\n\n // The logo sits above the step indicator, and stays mounted between the\n // e-mail and the code step; the steps themselves then show none.\n const loginStep = step.name === \"email\" || step.name === \"code\";\n\n return (\n <div className=\"flex flex-col gap-4\">\n {loginStep && (\n <LoginBrandLogo projectId={projectID} locale={locale} {...logo} />\n )}\n {stepNumber != null && <StepIndicator current={stepNumber} />}\n {step.name === \"email\" && (\n <ReturnsEmailStep\n showLogo={false}\n onSubmitted={() => dispatch({ type: \"CODE_SENT\" })}\n />\n )}\n {step.name === \"code\" && (\n <ReturnsCodeStep\n showLogo={false}\n onVerified={() => dispatch({ type: \"AUTHENTICATED\" })}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"orders\" && (\n <ReturnsOrderList\n showLogout={!panelToken}\n onSelectOrder={(orderId) =>\n dispatch({ type: \"SELECT_ORDER\", orderId })\n }\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"order\" && (\n <ReturnsOrderDetail\n orderId={step.orderId}\n initialItems={step.items}\n initialNote={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onContinue={({ items, note }) =>\n dispatch({ type: \"REVIEW\", items, note })\n }\n />\n )}\n {step.name === \"confirmation\" && (\n <ReturnsConfirmation\n orderId={step.orderId}\n items={step.items}\n note={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onSubmitted={(returnId) =>\n dispatch({ type: \"SUBMITTED\", returnId })\n }\n />\n )}\n {step.name === \"result\" && (\n <ReturnsResult\n returnId={step.returnId}\n onContinue={() => dispatch({ type: \"CONTINUE\" })}\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"myReturns\" && (\n <ReturnsMyReturnsList\n onSelectReturn={(returnId) =>\n dispatch({ type: \"SELECT_RETURN\", returnId })\n }\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"myReturn\" && (\n <ReturnsMyReturnDetail\n returnId={step.returnId}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n </div>\n );\n}\n\n/**\n * Customer return flow: email, code, orders, line selection, confirmation and\n * result, plus the list of earlier returns. It is `ReturnsProvider` with the\n * default step router; compose your own page from the step components to\n * change the layout.\n *\n * ```tsx\n * <BitsnapReturns projectID=\"…\" appearance={brand} texts={{ emailStepTitle: \"Return a product\" }} />\n * ```\n */\nexport function BitsnapReturns({\n showLogo,\n logoUrl,\n logoDarkUrl,\n ...props\n}: BitsnapReturnsProps) {\n return (\n <ReturnsProvider {...props}>\n <ReturnsRouter\n panelToken={props.panelAccessToken != null && props.panelAccessToken !== \"\"}\n logo={{ showLogo, logoUrl, logoDarkUrl }}\n />\n </ReturnsProvider>\n );\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var _chunkKOYBZORLjs = require('./chunk-KOYBZORL.js');var _chunkMWWEPEU2js = require('./chunk-MWWEPEU2.js');var _chunkDOJICJCQjs = require('./chunk-DOJICJCQ.js');var _chunkD2ASWUXMjs = require('./chunk-D2ASWUXM.js');var _chunkQ337IQNAjs = require('./chunk-Q337IQNA.js');var xt=["root","grid","card","cardLink","image","imagePlaceholder","body","name","description","price","comparePrice","badge","model3dBadge","actions","addToCartButton","selectButton","message","pagination","paginationButton","pageIndicator","emptyState","error","retryButton","skeleton"],Tt={fontFamily:"--bitsnap-products-font-family",gridMinWidth:"--bitsnap-products-grid-min-width",fontSize:"--bitsnap-products-font-size",background:"--bitsnap-products-background",surface:"--bitsnap-products-surface",foreground:"--bitsnap-products-foreground",mutedForeground:"--bitsnap-products-muted-foreground",border:"--bitsnap-products-border",buttonBackground:"--bitsnap-products-button-background",buttonForeground:"--bitsnap-products-button-foreground",buttonHoverBackground:"--bitsnap-products-button-hover-background",hoverSurface:"--bitsnap-products-hover-surface",focusRing:"--bitsnap-products-focus-ring",error:"--bitsnap-products-error",badgeBackground:"--bitsnap-products-badge-background",badgeForeground:"--bitsnap-products-badge-foreground",radius:"--bitsnap-products-radius"},Ct={light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#f4f4f5",focusRing:"#71717a",error:"#dc2626",badgeBackground:"#f4f4f5",badgeForeground:"#3f3f46",radius:"8px",gridMinWidth:"9rem"},dark:{background:"#18181b",surface:"#27272a",foreground:"#fafafa",mutedForeground:"#a1a1aa",border:"#3f3f46",buttonBackground:"#fafafa",buttonForeground:"#18181b",buttonHoverBackground:"#e4e4e7",hoverSurface:"#3f3f46",focusRing:"#a1a1aa",error:"#f87171",badgeBackground:"#3f3f46",badgeForeground:"#e4e4e7",radius:"8px",gridMinWidth:"9rem"}},St=[];function ct(t){let e=_chunkKOYBZORLjs.a.call(void 0, t,{defaultTheme:"light",presets:Ct,variables:Tt,shadcnVariables:St});return{theme:e.theme,tokens:e.tokens,elements:e.elements,boundaryClassName:e.theme,boundaryStyle:e.boundaryStyle}}function q(t,e){return _chunkKOYBZORLjs.b.call(void 0, t.elements,e)}function ut(t,e){try{return new Intl.NumberFormat(t,{style:"currency",currency:e,currencyDisplay:"symbol"})}catch (e2){return}}function U(t,e,n=_chunkQ337IQNAjs.d){let r=t/100,a=_nullishCoalesce(ut(n,e), () => (ut(_chunkQ337IQNAjs.d,e)));return a!=null?a.format(r):`${r.toFixed(2)} ${e}`}var _react = require('react');function V(t){let{projectID:e,locale:n,search:r,initialData:a}=t,[i]=_react.useState.call(void 0, ()=>_chunkDOJICJCQjs.e),d=_nullishCoalesce(t.host, () => (i)),c=_chunkMWWEPEU2js.a.call(void 0, t.pageSize),s=JSON.stringify([e,d,_nullishCoalesce(n, () => (null)),_nullishCoalesce(_optionalChain([r, 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()]), () => (null)),c]),[g,l]=_react.useState.call(void 0, {queryKey:s,page:1});g.queryKey!==s&&l({queryKey:s,page:1});let[P,C]=_react.useState.call(void 0, 0),[m,p]=_react.useState.call(void 0, ()=>({requestKey:a!=null?`${s}|1|0`:"",data:a,error:void 0})),f=_nullishCoalesce(_optionalChain([m, 'access', _4 => _4.data, 'optionalAccess', _5 => _5.totalCount]), () => (0)),b=_chunkMWWEPEU2js.b.call(void 0, f,c),h=g.queryKey===s?g.page:1,k=f>0?Math.min(h,b):h,S=`${s}|${k}|${P}`,T=m.requestKey===S;_react.useEffect.call(void 0, ()=>{if(T)return;let y=new AbortController;return _chunkMWWEPEU2js.c.call(void 0, {projectID:e,host:d,locale:n,search:r,limit:c,offset:(k-1)*c},y.signal).then(L=>{y.signal.aborted||p({requestKey:S,data:L,error:void 0})},L=>{y.signal.aborted||p(E=>({requestKey:S,data:E.data,error:L instanceof Error?L:new Error(String(L))}))}),()=>y.abort()},[S,T]);let I=_react.useCallback.call(void 0, y=>{let L=Math.max(1,Math.floor(y));l({queryKey:s,page:f>0?Math.min(L,b):L})},[s,f,b]),A=_react.useCallback.call(void 0, ()=>C(y=>y+1),[]);return _react.useMemo.call(void 0, ()=>({products:_nullishCoalesce(_optionalChain([m, 'access', _6 => _6.data, 'optionalAccess', _7 => _7.items]), () => ([])),totalCount:f,page:k,pageCount:b,setPage:I,isLoading:!T,error:T?m.error:void 0,refetch:A}),[m,f,k,b,I,T,A])}var H=50,wt=1e3;function pt(t,e=wt){let n=new Set,r=new Map,a=[],i=[],d,c,s=!1;function g(){for(c!==void 0&&clearTimeout(c),c=void 0;a.length>0;){let p=a.slice(0,H),f=i.slice(0,H);a=a.slice(H),i=i.slice(H);try{t({productIds:p,positions:f})}catch (e3){}}}function l(){g();try{_optionalChain([_chunkD2ASWUXMjs.f.call(void 0, ), 'optionalAccess', _8 => _8.flush, 'call', _9 => _9()])}catch (e4){}}let P=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&l()};function C(){s||typeof window>"u"||(s=!0,window.addEventListener("pagehide",l,!0),document.addEventListener("visibilitychange",P,!0))}function m(){if(d)return d;if(!(typeof IntersectionObserver>"u"))return d=new IntersectionObserver(p=>{for(let f of p){let b=r.get(f.target);!b||!f.isIntersecting||f.intersectionRatio<.5||(r.delete(f.target),_optionalChain([d, 'optionalAccess', _10 => _10.unobserve, 'call', _11 => _11(f.target)]),!n.has(b.id)&&(n.add(b.id),a.push(b.id),i.push(b.position)))}a.length>0&&c===void 0&&(c=setTimeout(g,e),_optionalChain([c, 'access', _12 => _12.unref, 'optionalCall', _13 => _13()]))},{threshold:[.5]}),C(),d}return{observe(p,f,b){try{if(n.has(f))return()=>{};let h=m();return h?(r.set(p,{id:f,position:b}),h.observe(p),()=>{r.delete(p),h.unobserve(p)}):()=>{}}catch (e5){return()=>{}}},flush:g,destroy(){try{g(),_optionalChain([d, 'optionalAccess', _14 => _14.disconnect, 'call', _15 => _15()]),s&&(window.removeEventListener("pagehide",l,!0),document.removeEventListener("visibilitychange",P,!0),s=!1)}catch (e6){}d=void 0,r.clear()}}}var It={en:{addToCart:"Add to cart",addingToCart:"Adding\u2026",addedToCart:"Added to cart",addToCartError:"Could not add to the cart. Try again.",chooseOptions:"Choose",viewProduct:"View",unavailable:"Unavailable",subscription:"Subscription",model3d:"3D",model3dLabel:"3D model",priceFrom:"from {price}",originalPrice:"Original price",loading:"Loading products",empty:"There are no products to show.",error:"Could not load the products.",retry:"Try again",pagination:"Pagination",previousPage:"Previous",nextPage:"Next",pageOf:"Page {page} of {pageCount}"},pl:{addToCart:"Dodaj do koszyka",addingToCart:"Dodawanie\u2026",addedToCart:"Dodano do koszyka",addToCartError:"Nie uda\u0142o si\u0119 doda\u0107 do koszyka. Spr\xF3buj ponownie.",chooseOptions:"Wybierz",viewProduct:"Zobacz",unavailable:"Niedost\u0119pny",subscription:"Subskrypcja",model3d:"3D",model3dLabel:"Model 3D",priceFrom:"od {price}",originalPrice:"Cena przed obni\u017Ck\u0105",loading:"\u0141adowanie produkt\xF3w",empty:"Brak produkt\xF3w do wy\u015Bwietlenia.",error:"Nie uda\u0142o si\u0119 za\u0142adowa\u0107 produkt\xF3w.",retry:"Spr\xF3buj ponownie",pagination:"Paginacja",previousPage:"Poprzednia",nextPage:"Nast\u0119pna",pageOf:"Strona {page} z {pageCount}"}};function gt(t,e){return _chunkQ337IQNAjs.b.call(void 0, It,t,e)}function $(t,e){return t.replace(/\{(\w+)\}/g,(n,r)=>r in e?String(e[r]):n)}var _jsxruntime = require('react/jsx-runtime');var bt=_react.createContext.call(void 0, void 0),_t={observe:()=>()=>{},clicked:()=>{}},Pt=_react.createContext.call(void 0, _t);function F(){let t=_react.useContext.call(void 0, bt);if(t==null)throw new Error("ProductList parts must be rendered inside ProductList");return t}function u(t,e){let{appearance:n}=F(),r=q(n,t);return{"data-bitsnap-products-slot":t,className:_chunkDOJICJCQjs.g.call(void 0, e,_optionalChain([r, 'optionalAccess', _16 => _16.className])),style:_optionalChain([r, 'optionalAccess', _17 => _17.style])}}var W="inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50",yt=`${W} w-full`,Nt=`${yt} no-underline`;function Ot({product:t,onAdd:e}){let{texts:n}=F(),[r,a]=_react.useState.call(void 0, "idle"),i=u("addToCartButton",yt),d=u("message","mt-2 text-xs");_react.useEffect.call(void 0, ()=>{if(r!=="added")return;let g=setTimeout(()=>a("idle"),2e3);return()=>clearTimeout(g)},[r]);let c=_react.useCallback.call(void 0, async()=>{a("adding");try{await e(),a("added")}catch(g){console.error("bitsnap-react: could not add to the cart",g),a("error")}},[e]),s=r==="adding"?n.addingToCart:r==="added"?n.addedToCart:n.addToCart;return _jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "button",{type:"button",...i,disabled:r==="adding","aria-label":`${s}: ${t.name}`,onClick:c,children:s}),r==="error"?_jsxruntime.jsx.call(void 0, "p",{...d,role:"alert",children:n.addToCartError}):null]})}function Bt({product:t,position:e,href:n,onAdd:r,renderItem:a}){let{texts:i,locale:d}=F(),c=_react.useContext.call(void 0, Pt),s=_react.useRef.call(void 0, null);_react.useEffect.call(void 0, ()=>{if(s.current!=null)return c.observe(s.current,t.id,e)},[c,t.id,e]);let g=_react.useCallback.call(void 0, ()=>c.clicked(t,e),[c,t,e]),l=u("card","relative flex flex-col overflow-hidden border transition-colors"),P=u("cardLink","flex flex-1 flex-col no-underline"),C=u("image","aspect-square w-full overflow-hidden"),m=u("imagePlaceholder","aspect-square w-full"),p=u("body","flex flex-1 flex-col gap-1 p-4"),f=u("name","text-base font-medium leading-snug"),b=u("description","line-clamp-2 text-sm"),h=u("price","mt-auto pt-2 text-base font-semibold"),k=u("comparePrice","ml-2 text-sm font-normal"),S=u("badge","absolute left-3 top-3 px-2 py-0.5 text-xs font-medium"),T=u("model3dBadge","absolute right-3 top-3 inline-flex items-center gap-1 px-2 py-0.5 text-xs font-semibold"),I=u("actions","p-4 pt-0"),A=u("selectButton",Nt),y=U(t.price,t.currency,d),L=t.compareAtPrice!=null&&t.compareAtPrice>t.price?U(t.compareAtPrice,t.currency,d):null;if(a!=null)return _jsxruntime.jsx.call(void 0, "li",{ref:s,...l,"data-unavailable":t.available?void 0:"",children:a(t,{href:n,price:y,compareAtPrice:L,texts:i,locale:d,addToCart:r,trackClick:g})});let E=_nullishCoalesce(_optionalChain([t, 'access', _18 => _18.image, 'optionalAccess', _19 => _19.thumbnailUrl]), () => (_optionalChain([t, 'access', _20 => _20.image, 'optionalAccess', _21 => _21.url]))),_=t.available?t.isRecurring?i.subscription:null:i.unavailable;return _jsxruntime.jsxs.call(void 0, "li",{ref:s,...l,"data-unavailable":t.available?void 0:"",children:[_jsxruntime.jsxs.call(void 0, "a",{...P,href:n,onClick:g,children:[E!=null?_jsxruntime.jsx.call(void 0, "div",{...C,children:_jsxruntime.jsx.call(void 0, "img",{src:E,alt:"",loading:"lazy",decoding:"async",className:"h-full w-full object-cover"})}):_jsxruntime.jsx.call(void 0, "div",{...m,"aria-hidden":"true"}),_jsxruntime.jsxs.call(void 0, "div",{...p,children:[_jsxruntime.jsx.call(void 0, "h3",{...f,children:t.name}),t.shortDescription?_jsxruntime.jsx.call(void 0, "p",{...b,children:t.shortDescription}):null,_jsxruntime.jsxs.call(void 0, "p",{...h,children:[t.priceFrom?$(i.priceFrom,{price:y}):y,L!=null?_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "span",{className:"sr-only",children:[i.originalPrice,": "]}),_jsxruntime.jsx.call(void 0, "del",{...k,children:L})]}):null]})]})]}),_!=null?_jsxruntime.jsx.call(void 0, "span",{...S,"data-kind":t.available?"subscription":"unavailable",children:_}):null,t.has3d===!0?_jsxruntime.jsxs.call(void 0, "span",{...T,title:i.model3dLabel,children:[_jsxruntime.jsx.call(void 0, Rt,{}),_jsxruntime.jsx.call(void 0, "span",{"aria-hidden":"true",children:i.model3d}),_jsxruntime.jsx.call(void 0, "span",{className:"sr-only",children:i.model3dLabel})]}):null,_jsxruntime.jsx.call(void 0, "div",{...I,children:t.available?t.addToCart?_jsxruntime.jsx.call(void 0, Ot,{product:t,onAdd:r}):_jsxruntime.jsx.call(void 0, "a",{...A,href:n,onClick:g,children:t.variantCount>1?i.chooseOptions:i.viewProduct}):_jsxruntime.jsx.call(void 0, "button",{type:"button",...A,disabled:!0,children:i.unavailable})})]})}function Rt(){return _jsxruntime.jsxs.call(void 0, "svg",{viewBox:"0 0 24 24",width:"12",height:"12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[_jsxruntime.jsx.call(void 0, "path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"}),_jsxruntime.jsx.call(void 0, "path",{d:"m3.3 7 8.7 5 8.7-5"}),_jsxruntime.jsx.call(void 0, "path",{d:"M12 22V12"})]})}var Lt="m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,var(--bitsnap-products-grid-min-width,9rem)),1fr))] gap-5 p-0";function Dt({count:t,label:e}){let n=u("grid",Lt),r=u("skeleton","aspect-[3/4] animate-pulse");return _jsxruntime.jsx.call(void 0, "div",{...n,role:"status","aria-busy":"true","aria-label":e,children:Array.from({length:t},(a,i)=>_jsxruntime.jsx.call(void 0, "div",{...r,"aria-hidden":"true"},i))})}function Ft({page:t,pageCount:e,isLoading:n,onPage:r}){let{texts:a}=F(),i=u("pagination","mt-8 flex items-center justify-center gap-4"),d=u("paginationButton",W),c=u("pageIndicator","text-sm");return _jsxruntime.jsxs.call(void 0, "nav",{...i,"aria-label":a.pagination,children:[_jsxruntime.jsx.call(void 0, "button",{type:"button",...d,"aria-disabled":n||t<=1,onClick:()=>{!n&&t>1&&r(t-1)},children:a.previousPage}),_jsxruntime.jsx.call(void 0, "span",{...c,"aria-live":"polite",children:$(a.pageOf,{page:t,pageCount:e})}),_jsxruntime.jsx.call(void 0, "button",{type:"button",...d,"aria-disabled":n||t>=e,onClick:()=>{!n&&t<e&&r(t+1)},children:a.nextPage})]})}function Mt({options:t,productHref:e,renderItem:n,onAddToCart:r,showCartOnAdd:a}){let{texts:i}=F(),{products:d,page:c,pageCount:s,setPage:g,isLoading:l,error:P,refetch:C}=V(t),m=_chunkD2ASWUXMjs.m.call(void 0, ),p=_optionalChain([t, 'access', _22 => _22.search, 'optionalAccess', _23 => _23.trim, 'call', _24 => _24()])?"search":"catalog",f=_chunkMWWEPEU2js.a.call(void 0, t.pageSize),b=_react.useRef.call(void 0, !1);_react.useEffect.call(void 0, ()=>{b.current||l||P!=null||(b.current=!0,m.track("product_list_viewed",{list_id:p,item_count:d.length}))},[m,l,P,p,d.length]);let h=_react.useMemo.call(void 0, ()=>pt(({productIds:v,positions:w})=>m.track("product_impression",{list_id:p,product_ids:v,positions:w})),[m,p]);_react.useEffect.call(void 0, ()=>()=>h.destroy(),[h]);let k=_react.useMemo.call(void 0, ()=>({observe:h.observe,clicked:(v,w)=>m.track("product_clicked",{list_id:p,position:w},{product_id:v.id})}),[h,m,p]),S=_react.useRef.call(void 0, null),T=_react.useRef.call(void 0, !1),I=_react.useCallback.call(void 0, v=>{T.current=!0,g(v)},[g]);_react.useEffect.call(void 0, ()=>{l||!T.current||(T.current=!1,_optionalChain([S, 'access', _25 => _25.current, 'optionalAccess', _26 => _26.focus, 'call', _27 => _27({preventScroll:!0})]),_optionalChain([S, 'access', _28 => _28.current, 'optionalAccess', _29 => _29.scrollIntoView, 'call', _30 => _30({block:"start"})]))},[l]);let A=u("grid",Lt),y=u("emptyState","py-12 text-center text-sm"),L=u("error","flex flex-col items-center gap-3 py-12 text-center text-sm"),E=u("retryButton",W),{projectID:_,host:G}=t,ht=_react.useCallback.call(void 0, (v,w)=>async()=>{if(r!=null){await _chunkD2ASWUXMjs.p.call(void 0, ()=>r(v)),_chunkMWWEPEU2js.d.call(void 0, m,v);return}await _chunkMWWEPEU2js.e.call(void 0, v,{projectID:_,host:G,showCart:a,analytics:m,url:w})},[r,_,G,a,m]),N;return l&&d.length===0?N=_jsxruntime.jsx.call(void 0, Dt,{count:Math.min(_chunkMWWEPEU2js.a.call(void 0, t.pageSize),8),label:i.loading}):P!=null?N=_jsxruntime.jsxs.call(void 0, "div",{...L,role:"alert",children:[_jsxruntime.jsx.call(void 0, "p",{children:i.error}),_jsxruntime.jsx.call(void 0, "button",{type:"button",...E,onClick:C,children:i.retry})]}):d.length===0?N=_jsxruntime.jsx.call(void 0, "p",{...y,children:i.empty}):N=_jsxruntime.jsx.call(void 0, "ul",{...A,"aria-busy":l||void 0,className:_chunkDOJICJCQjs.g.call(void 0, A.className,l&&"opacity-60"),children:d.map((v,w)=>{let X=e(v);return _jsxruntime.jsx.call(void 0, Bt,{product:v,position:(c-1)*f+w,href:X,onAdd:ht(v,X),renderItem:n},v.id)})}),_jsxruntime.jsx.call(void 0, Pt.Provider,{value:k,children:_jsxruntime.jsxs.call(void 0, "div",{ref:S,tabIndex:-1,className:"p-1 outline-none scroll-mt-4",children:[N,s>1&&P==null?_jsxruntime.jsx.call(void 0, Ft,{page:c,pageCount:s,isLoading:l,onPage:I}):null]})})}var Ut=t=>`/p/${encodeURIComponent(t.uniqueSlug)}`;function zt({productHref:t=Ut,appearance:e,texts:n,renderItem:r,onAddToCart:a,showCartOnAdd:i=!0,className:d,analytics:c,...s}){let g=_chunkD2ASWUXMjs.n.call(void 0, s.projectID,c,"catalog"),l=_nullishCoalesce(s.locale, () => (_chunkQ337IQNAjs.d)),P=_react.useMemo.call(void 0, ()=>ct(e),[e]),C=_react.useMemo.call(void 0, ()=>gt(l,n),[l,n]),m=_react.useMemo.call(void 0, ()=>({appearance:P,texts:C,locale:l}),[P,C,l]),p=q(P,"root");return _jsxruntime.jsx.call(void 0, _chunkD2ASWUXMjs.l,{value:g,children:_jsxruntime.jsx.call(void 0, bt.Provider,{value:m,children:_jsxruntime.jsx.call(void 0, "div",{"data-bitsnap-products":"root","data-bitsnap-products-slot":"root",className:_chunkDOJICJCQjs.g.call(void 0, "bitsnap-react",P.boundaryClassName,d,_optionalChain([p, 'optionalAccess', _31 => _31.className])),style:{...P.boundaryStyle,..._optionalChain([p, 'optionalAccess', _32 => _32.style])},children:_jsxruntime.jsx.call(void 0, Mt,{options:s,productHref:t,renderItem:r,onAddToCart:a,showCartOnAdd:i})})})})}exports.a = xt; exports.b = U; exports.c = V; exports.d = zt;
|
|
2
|
+
//# sourceMappingURL=chunk-GQ5OKU74.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-GQ5OKU74.js","../src/components/products/appearance.ts","../src/components/products/format.ts"],"names":["PRODUCT_LIST_SLOT_NAMES","PRODUCT_LIST_TOKEN_VARIABLES","PRODUCT_LIST_THEME_PRESETS","PRODUCT_LIST_SHADCN_VARIABLES","resolveProductListAppearance","appearance","resolved","resolveAppearanceCore","getProductListSlotAppearance","slot","getSlotAppearance","createFormatter","locale","currency","formatProductPrice","amount","DEFAULT_LOCALE","value","formatter"],"mappings":"AAAA,uuBAAgD,sDAAwE,sDAAgD,sDAAqE,sDAAgD,IC6DhRA,EAAAA,CAA0B,CACrC,MAAA,CACA,MAAA,CACA,MAAA,CACA,UAAA,CACA,OAAA,CACA,kBAAA,CACA,MAAA,CACA,MAAA,CACA,aAAA,CACA,OAAA,CACA,cAAA,CACA,OAAA,CACA,cAAA,CACA,SAAA,CACA,iBAAA,CACA,cAAA,CACA,SAAA,CACA,YAAA,CACA,kBAAA,CACA,eAAA,CACA,YAAA,CACA,OAAA,CACA,aAAA,CACA,UACF,CAAA,CA8BaC,EAAAA,CAA+B,CAC1C,UAAA,CAAY,gCAAA,CACZ,YAAA,CAAc,mCAAA,CACd,QAAA,CAAU,8BAAA,CACV,UAAA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C/B,IAAMC,CAAAA,CAAWC,gCAAAA,CAIfF,CAAY,CACZ,YAAA,CAAc,OAAA,CACd,OAAA,CAASH,EAAAA,CACT,SAAA,CAAWD,EAAAA,CACX,eAAA,CAAiBE,EACnB,CAAC,CAAA,CAED,MAAO,CACL,KAAA,CAAOG,CAAAA,CAAS,KAAA,CAChB,MAAA,CAAQA,CAAAA,CAAS,MAAA,CACjB,QAAA,CAAUA,CAAAA,CAAS,QAAA,CACnB,iBAAA,CAAmBA,CAAAA,CAAS,KAAA,CAC5B,aAAA,CAAeA,CAAAA,CAAS,aAC1B,CACF,CAGO,SAASE,CAAAA,CACdF,CAAAA,CACAG,CAAAA,CACuC,CACvC,OAAOC,gCAAAA,CAAkBJ,CAAS,QAAA,CAAUG,CAAI,CAClD,CCtNA,SAASE,EAAAA,CACPC,CAAAA,CACAC,CAAAA,CAC+B,CAC/B,GAAI,CACF,OAAO,IAAI,IAAA,CAAK,YAAA,CAAaD,CAAAA,CAAQ,CACnC,KAAA,CAAO,UAAA,CACP,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAiB,QACnB,CAAC,CACH,CAAA,UAAQ,CAEN,MACF,CACF,CAOO,SAASC,CAAAA,CACdC,CAAAA,CACAF,CAAAA,CACAD,CAAAA,CAAiBI,kBAAAA,CACT,CACR,IAAMC,CAAAA,CAAQF,CAAAA,CAAS,GAAA,CACjBG,CAAAA,kBACJP,EAAAA,CAAgBC,CAAAA,CAAQC,CAAQ,CAAA,SAChCF,EAAAA,CAAgBK,kBAAAA,CAAgBH,CAAQ,GAAA,CAE1C,OAAOK,CAAAA,EAAa,IAAA,CAChBA,CAAAA,CAAU,MAAA,CAAOD,CAAK,CAAA,CACtB,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-GQ5OKU74.js","sourcesContent":[null,"import type { CSSProperties } from \"react\";\nimport {\n getSlotAppearance,\n resolveAppearanceCore,\n type AppearanceElements,\n type ShadcnVariableMapping,\n type SlotAppearance,\n} from \"@/src/lib/appearance-core\";\n\n/**\n * Product list appearance API.\n *\n * It mirrors `CheckoutAppearance` and `ReturnsAppearance` (theme, tokens,\n * elements) so a shop can reuse one brand object for all of them. The resolver\n * is pure: it turns the caller input into a theme name, the tokens in effect,\n * the slot overrides and the inline style for the theme boundary.\n */\n\nexport type ProductListTheme = \"light\" | \"dark\";\n\nexport type ProductListAppearanceTokens = {\n /** Font family of the list. The library never loads fonts. */\n fontFamily?: string;\n /** Minimum grid track width. Use \"100%\" for one column. */\n gridMinWidth?: string;\n /** Base font size. */\n fontSize?: string;\n /** List background. */\n background?: string;\n /** Raised surfaces: cards, image placeholders, skeletons. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, the struck-through price. */\n mutedForeground?: string;\n /** Borders of cards and buttons. */\n border?: string;\n /** \"Add to cart\" button background. */\n buttonBackground?: string;\n /** \"Add to cart\" button text. */\n buttonForeground?: string;\n /** \"Add to cart\" button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of cards and secondary buttons. */\n hoverSurface?: string;\n /** Focus ring color. */\n focusRing?: string;\n /** Error and unavailable state color. */\n error?: string;\n /** Badge background (subscription, unavailable). */\n badgeBackground?: string;\n /** Badge text. */\n badgeForeground?: string;\n /** Corner radius of cards, images and buttons. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-products-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const PRODUCT_LIST_SLOT_NAMES = [\n \"root\",\n \"grid\",\n \"card\",\n \"cardLink\",\n \"image\",\n \"imagePlaceholder\",\n \"body\",\n \"name\",\n \"description\",\n \"price\",\n \"comparePrice\",\n \"badge\",\n \"model3dBadge\",\n \"actions\",\n \"addToCartButton\",\n \"selectButton\",\n \"message\",\n \"pagination\",\n \"paginationButton\",\n \"pageIndicator\",\n \"emptyState\",\n \"error\",\n \"retryButton\",\n \"skeleton\",\n] as const;\n\nexport type ProductListSlotName = (typeof PRODUCT_LIST_SLOT_NAMES)[number];\n\nexport type ProductListSlotAppearance = SlotAppearance;\n\nexport type ProductListAppearanceElements =\n AppearanceElements<ProductListSlotName>;\n\nexport type ProductListAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ProductListTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ProductListAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ProductListAppearanceElements;\n};\n\nexport type ResolvedProductListAppearance = {\n theme: ProductListTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ProductListAppearanceTokens;\n elements: ProductListAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the list root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const PRODUCT_LIST_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-products-font-family\",\n gridMinWidth: \"--bitsnap-products-grid-min-width\",\n fontSize: \"--bitsnap-products-font-size\",\n background: \"--bitsnap-products-background\",\n surface: \"--bitsnap-products-surface\",\n foreground: \"--bitsnap-products-foreground\",\n mutedForeground: \"--bitsnap-products-muted-foreground\",\n border: \"--bitsnap-products-border\",\n buttonBackground: \"--bitsnap-products-button-background\",\n buttonForeground: \"--bitsnap-products-button-foreground\",\n buttonHoverBackground: \"--bitsnap-products-button-hover-background\",\n hoverSurface: \"--bitsnap-products-hover-surface\",\n focusRing: \"--bitsnap-products-focus-ring\",\n error: \"--bitsnap-products-error\",\n badgeBackground: \"--bitsnap-products-badge-background\",\n badgeForeground: \"--bitsnap-products-badge-foreground\",\n radius: \"--bitsnap-products-radius\",\n} as const;\n\nexport type ProductListTokenName = keyof typeof PRODUCT_LIST_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `products.css` falls back to the light values, which keeps\n * the list usable even when the boundary style is missing.\n */\nexport const PRODUCT_LIST_THEME_PRESETS: Record<\n ProductListTheme,\n ProductListAppearanceTokens\n> = {\n light: {\n background: \"#ffffff\",\n surface: \"#f9fafb\",\n foreground: \"#18181b\",\n mutedForeground: \"#71717a\",\n border: \"#e4e4e7\",\n buttonBackground: \"#18181b\",\n buttonForeground: \"#fafafa\",\n buttonHoverBackground: \"#000000\",\n hoverSurface: \"#f4f4f5\",\n focusRing: \"#71717a\",\n error: \"#dc2626\",\n badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n radius: \"8px\",\n gridMinWidth: \"9rem\",\n },\n dark: {\n background: \"#18181b\",\n surface: \"#27272a\",\n foreground: \"#fafafa\",\n mutedForeground: \"#a1a1aa\",\n border: \"#3f3f46\",\n buttonBackground: \"#fafafa\",\n buttonForeground: \"#18181b\",\n buttonHoverBackground: \"#e4e4e7\",\n hoverSurface: \"#3f3f46\",\n focusRing: \"#a1a1aa\",\n error: \"#f87171\",\n badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n radius: \"8px\",\n gridMinWidth: \"9rem\",\n },\n};\n\n/** The list renders its own elements, so no shared primitive needs remapping. */\nconst PRODUCT_LIST_SHADCN_VARIABLES: ShadcnVariableMapping<ProductListTokenName> =\n [];\n\nexport function resolveProductListAppearance(\n appearance?: ProductListAppearance,\n): ResolvedProductListAppearance {\n const resolved = resolveAppearanceCore<\n ProductListTokenName,\n ProductListTheme,\n ProductListSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: PRODUCT_LIST_THEME_PRESETS,\n variables: PRODUCT_LIST_TOKEN_VARIABLES,\n shadcnVariables: PRODUCT_LIST_SHADCN_VARIABLES,\n });\n\n return {\n theme: resolved.theme,\n tokens: resolved.tokens,\n elements: resolved.elements,\n boundaryClassName: resolved.theme,\n boundaryStyle: resolved.boundaryStyle,\n };\n}\n\n/** Caller overrides for a single slot, if any were provided. */\nexport function getProductListSlotAppearance(\n resolved: ResolvedProductListAppearance,\n slot: ProductListSlotName,\n): ProductListSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { DEFAULT_LOCALE } from \"../checkout/locale\";\n\nfunction createFormatter(\n locale: string,\n currency: string,\n): Intl.NumberFormat | undefined {\n try {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n currencyDisplay: \"symbol\",\n });\n } catch {\n // RangeError: invalid locale or currency code.\n return undefined;\n }\n}\n\n/**\n * Formats a price in minor units (grosze, cents) for the locale, the same way\n * the cart does (`amount / 100`). An unknown locale falls back to Polish and an\n * invalid currency code to a plain number followed by the code.\n */\nexport function formatProductPrice(\n amount: number,\n currency: string,\n locale: string = DEFAULT_LOCALE,\n): string {\n const value = amount / 100;\n const formatter =\n createFormatter(locale, currency) ??\n createFormatter(DEFAULT_LOCALE, currency);\n\n return formatter != null\n ? formatter.format(value)\n : `${value.toFixed(2)} ${currency}`;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-JSDGZ4NY.js"],"names":[],"mappings":"AAAA,6EAAI,CAAC,CAAC,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,aAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,6BAAqB","file":"/home/emems/.t3/worktrees/bitsnap-react/emems-chat-v1/dist/chunk-JSDGZ4NY.js"}
|