@asteby/storefront-react 0.2.0 → 0.4.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/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as react from 'react';
2
- import { ReactNode, ComponentPropsWithoutRef, ElementType, ComponentType, FormEvent } from 'react';
3
- import { StorefrontClient, Shop, StorefrontClientOptions, Cart, CartLineInput, CartLineMerchandise, CartLineUpdateInput, CartBuyerInput, AddressInput, DeliveryInput, DeliveryOptions, Image as Image$1, FormatMoneyOptions, Money as Money$1, Product, ProductVariant, Collection, Section, Theme, GeoPoint, ShopBranch } from '@asteby/storefront';
2
+ import { ReactNode, ComponentPropsWithoutRef, ComponentType, FormEvent } from 'react';
3
+ import { StorefrontClient, Shop, StorefrontClientOptions, Cart, CartLineInput, CartLineMerchandise, CartLineUpdateInput, CartBuyerInput, AddressInput, DeliveryInput, DeliveryOptions, ProductVariant, Product, Image, Collection, Section, Theme, GeoPoint, ShopBranch, Money } from '@asteby/storefront';
4
+ export { D as DEFAULT_IMAGE_WIDTHS, I as Image, a as ImageLoader, b as ImageProps, M as Money, c as MoneyProps, P as ProductPrice, d as ProductPriceProps, e as defaultImageLoader } from './components-B5XhSH-m.js';
4
5
  import { OpeningHours, GeoPoint as GeoPoint$1, OpenStatus as OpenStatus$1 } from '@asteby/storefront/geo';
5
6
 
6
7
  type StorefrontContextValue = {
@@ -124,55 +125,6 @@ declare function useCart(): CartContextValue;
124
125
  /** Cart context or `null` outside a provider. */
125
126
  declare function useOptionalCart(): CartContextValue | null;
126
127
 
127
- type MoneyProps<As extends ElementType = 'span'> = FormatMoneyOptions & {
128
- data: Money$1;
129
- /** Element to render (default `span`). */
130
- as?: As;
131
- /** Overrides the provider locale. */
132
- locale?: string;
133
- } & Omit<ComponentPropsWithoutRef<As>, 'children' | 'as'>;
134
- /** Formats `Money` with the provider locale (or `locale`). */
135
- declare function Money<As extends ElementType = 'span'>({ data, as, locale, withoutTrailingZeros, withoutCurrency, currencyDisplay, ...rest }: MoneyProps<As>): react.ReactElement<any, string | react.JSXElementConstructor<any>>;
136
- declare const DEFAULT_IMAGE_WIDTHS: readonly [320, 480, 640, 768, 1024, 1280, 1600];
137
- /** Builds the URL for one srcset width. */
138
- type ImageLoader = (src: string, width: number, height?: number) => string;
139
- /**
140
- * Default loader: adds `?width=<w>` (the convention of most image CDNs and of
141
- * the OPS image proxy). URLs that cannot be parsed are returned unchanged.
142
- */
143
- declare const defaultImageLoader: ImageLoader;
144
- type ImageProps = Omit<ComponentPropsWithoutRef<'img'>, 'src' | 'srcSet' | 'width' | 'height'> & {
145
- data: Image$1;
146
- /** `sizes` attribute (default `100vw`). */
147
- sizes?: string;
148
- /** Candidate widths for `srcset` (capped at the intrinsic width when known). */
149
- widths?: readonly number[];
150
- /** URL builder per width (default adds `?width=`). Pass `null` to disable srcset. */
151
- loader?: ImageLoader | null;
152
- /** Above-the-fold image: eager loading and `fetchpriority="high"`. */
153
- priority?: boolean;
154
- /** Forces an aspect ratio, e.g. `1/1` or `4/3`, used for width/height and srcset heights. */
155
- aspectRatio?: string;
156
- };
157
- /** Responsive `<img>` with `srcset`, lazy by default, intrinsic size to avoid layout shift. */
158
- declare function Image({ data, sizes, widths, loader, priority, aspectRatio, alt, loading, decoding, ...rest }: ImageProps): react.JSX.Element;
159
- type ProductPriceProps = Omit<ComponentPropsWithoutRef<'div'>, 'children'> & {
160
- product?: Pick<Product, 'price_range' | 'compare_at_price_range'> | null;
161
- variant?: Pick<ProductVariant, 'price' | 'compare_at_price'> | null;
162
- /** Prefix shown when the product has a price range and no variant is selected (default `Desde`). */
163
- fromLabel?: ReactNode;
164
- /** Accessible label for the compare-at price (default `Precio anterior`). */
165
- compareAtLabel?: string;
166
- locale?: string;
167
- withoutTrailingZeros?: boolean;
168
- };
169
- /**
170
- * Price with optional compare-at (strikethrough). With a `variant` it shows
171
- * that variant; otherwise the product's minimum price (prefixed with
172
- * `fromLabel` when prices vary).
173
- */
174
- declare function ProductPrice({ product, variant, fromLabel, compareAtLabel, locale, withoutTrailingZeros, ...rest }: ProductPriceProps): react.JSX.Element | null;
175
-
176
128
  type ProductOptionValueState = {
177
129
  value: string;
178
130
  /** Part of the current selection. */
@@ -285,7 +237,7 @@ type SeoMetaInput = {
285
237
  description?: string | null;
286
238
  /** Canonical absolute URL. */
287
239
  url?: string | null;
288
- image?: Image$1 | string | null;
240
+ image?: Image | string | null;
289
241
  /** `og:type` (default `website`). */
290
242
  type?: string;
291
243
  siteName?: string | null;
@@ -665,7 +617,7 @@ declare function DirectionsLink({ location, provider, children, ...rest }: Direc
665
617
  type PickupInfo<L extends ShopBranch = ShopBranch> = {
666
618
  location: L;
667
619
  /** `null` = free. Amount as sent by OPS; nothing is calculated here. */
668
- fee: Money$1 | null;
620
+ fee: Money | null;
669
621
  free: boolean;
670
622
  /** Formatted `fee` (`null` when free). */
671
623
  feeText: string | null;
@@ -703,4 +655,4 @@ type NearestLocationFormProps<L extends ShopBranch = ShopBranch> = {
703
655
  */
704
656
  declare function NearestLocationForm<L extends ShopBranch = ShopBranch>({ locations, action, name, defaultValue, onSubmitPostalCode, onLocate, labels, children, ...rest }: NearestLocationFormProps<L>): react.JSX.Element | null;
705
657
 
706
- export { AddToCartButton, type AddToCartButtonProps, type BreadcrumbItem, CART_COOKIE_NAME, type CartContextValue, type CartCookieOptions, type CartLineAddInput, CartProvider, type CartProviderProps, type CartStatus, DEFAULT_IMAGE_WIDTHS, DirectionsLink, type DirectionsLinkProps, type FaqItem, type GeolocationErrorCode, type GeolocationFailure, type GeolocationPermission, Image, type ImageLoader, type ImageProps, type InferSectionProps, JsonLd, type JsonLdObject, type JsonLdProps, type LocalBusinessOptions, type LocationItemState, LocationList, type LocationListProps, LocationPicker, type LocationPickerProps, type MetaDescriptor, Money, type MoneyProps, type NearbyLocation, NearestLocationForm, type NearestLocationFormLabels, type NearestLocationFormProps, OpenStatus, type OpenStatusLabels, type OpenStatusProps, type PickupInfo, PickupOption, type PickupOptionProps, type ProductOptionState, type ProductOptionValueState, type ProductOptionsState, ProductPrice, type ProductPriceProps, SELECTED_LOCATION_PARAM, SELECTED_LOCATION_STORAGE_KEY, type SectionComponentProps, type SectionDefinition, type SectionPropError, type SectionPropKind, type SectionPropSchema, SectionRegistry, type SectionSchema, Sections, type SectionsProps, type SeoMetaInput, type StorefrontContextValue, StorefrontProvider, type StorefrontProviderProps, type ThemeCssOptions, ThemeStyle, type ThemeStyleProps, type UseGeolocationOptions, type UseGeolocationResult, type UseNearestLocationsOptions, type UseNearestLocationsResult, type UseProductOptionsConfig, type UseSelectedLocationOptions, type UseSelectedLocationResult, VariantSelector, type VariantSelectorProps, type VariantSelectorRenderProps, breadcrumbJsonLd, collectionJsonLd, collectionMeta, createSectionRegistry, defaultImageLoader, defineSection, faqJsonLd, getCartIdFromCookie, isSafeCssValue, localBusinessJsonLd, openingHoursJsonLd, optimisticCart, organizationJsonLd, productJsonLd, productMeta, readCartCookie, readSelectedLocationId, resolveSectionProps, sectionJsonSchema, seoMeta, serializeCartCookie, serializeJsonLd, themeFontsHref, themeToCss, themeToCssVariables, toMerchandise, tokenName, useCart, useGeolocation, useNearestLocations, useOptionalCart, useOptionalStorefront, useProductOptions, useSelectedLocation, useStorefront, useStorefrontClient, writeCartCookie };
658
+ export { AddToCartButton, type AddToCartButtonProps, type BreadcrumbItem, CART_COOKIE_NAME, type CartContextValue, type CartCookieOptions, type CartLineAddInput, CartProvider, type CartProviderProps, type CartStatus, DirectionsLink, type DirectionsLinkProps, type FaqItem, type GeolocationErrorCode, type GeolocationFailure, type GeolocationPermission, type InferSectionProps, JsonLd, type JsonLdObject, type JsonLdProps, type LocalBusinessOptions, type LocationItemState, LocationList, type LocationListProps, LocationPicker, type LocationPickerProps, type MetaDescriptor, type NearbyLocation, NearestLocationForm, type NearestLocationFormLabels, type NearestLocationFormProps, OpenStatus, type OpenStatusLabels, type OpenStatusProps, type PickupInfo, PickupOption, type PickupOptionProps, type ProductOptionState, type ProductOptionValueState, type ProductOptionsState, SELECTED_LOCATION_PARAM, SELECTED_LOCATION_STORAGE_KEY, type SectionComponentProps, type SectionDefinition, type SectionPropError, type SectionPropKind, type SectionPropSchema, SectionRegistry, type SectionSchema, Sections, type SectionsProps, type SeoMetaInput, type StorefrontContextValue, StorefrontProvider, type StorefrontProviderProps, type ThemeCssOptions, ThemeStyle, type ThemeStyleProps, type UseGeolocationOptions, type UseGeolocationResult, type UseNearestLocationsOptions, type UseNearestLocationsResult, type UseProductOptionsConfig, type UseSelectedLocationOptions, type UseSelectedLocationResult, VariantSelector, type VariantSelectorProps, type VariantSelectorRenderProps, breadcrumbJsonLd, collectionJsonLd, collectionMeta, createSectionRegistry, defineSection, faqJsonLd, getCartIdFromCookie, isSafeCssValue, localBusinessJsonLd, openingHoursJsonLd, optimisticCart, organizationJsonLd, productJsonLd, productMeta, readCartCookie, readSelectedLocationId, resolveSectionProps, sectionJsonSchema, seoMeta, serializeCartCookie, serializeJsonLd, themeFontsHref, themeToCss, themeToCssVariables, toMerchandise, tokenName, useCart, useGeolocation, useNearestLocations, useOptionalCart, useOptionalStorefront, useProductOptions, useSelectedLocation, useStorefront, useStorefrontClient, writeCartCookie };
package/dist/index.js CHANGED
@@ -1,41 +1,10 @@
1
- import { createContext, useMemo, useContext, useRef, useState, useCallback, useEffect, createElement, Fragment as Fragment$1, useId } from 'react';
2
- import { createStorefrontClient, formatMoney, parseMoney, isStorefrontError } from '@asteby/storefront';
3
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
1
+ import { useOptionalStorefront } from './chunk-C6QZNKRE.js';
2
+ export { DEFAULT_IMAGE_WIDTHS, Image, Money, ProductPrice, StorefrontProvider, defaultImageLoader, useOptionalStorefront, useStorefront, useStorefrontClient } from './chunk-C6QZNKRE.js';
3
+ import { createContext, useRef, useState, useCallback, useEffect, useMemo, useContext, Fragment as Fragment$1, useId } from 'react';
4
+ import { formatMoney, isStorefrontError } from '@asteby/storefront';
5
+ import { jsx, Fragment, jsxs } from 'react/jsx-runtime';
4
6
  import { toSchemaOpeningHours, isValidPoint, rankByDistance, openStatus, directionsUrl } from '@asteby/storefront/geo';
5
7
 
6
- // src/context.tsx
7
- var StorefrontContext = createContext(null);
8
- function StorefrontProvider({ client, config, shop = null, locale, currency, children }) {
9
- const configKey = config ? `${config.baseUrl}|${config.token}|${config.locale ?? ""}|${config.customerToken ?? ""}` : "";
10
- const resolvedClient = useMemo(
11
- () => client ?? (config ? createStorefrontClient(config) : null),
12
- [client, configKey]
13
- );
14
- const value = useMemo(
15
- () => ({
16
- client: resolvedClient,
17
- shop,
18
- locale: locale ?? config?.locale ?? shop?.locale ?? "es-MX",
19
- currency: currency ?? shop?.currency_code ?? "MXN"
20
- }),
21
- [resolvedClient, shop, locale, currency, config?.locale]
22
- );
23
- return /* @__PURE__ */ jsx(StorefrontContext.Provider, { value, children });
24
- }
25
- function useStorefront() {
26
- const ctx = useContext(StorefrontContext);
27
- if (!ctx) throw new Error("useStorefront must be used inside <StorefrontProvider>");
28
- return ctx;
29
- }
30
- function useOptionalStorefront() {
31
- return useContext(StorefrontContext);
32
- }
33
- function useStorefrontClient() {
34
- const { client } = useStorefront();
35
- if (!client) throw new Error("<StorefrontProvider> needs a `client` or `config` for browser-side calls");
36
- return client;
37
- }
38
-
39
8
  // src/cookie.ts
40
9
  var CART_COOKIE_NAME = "sf_cart";
41
10
  function getCartIdFromCookie(cookieHeader, name = CART_COOKIE_NAME) {
@@ -314,128 +283,6 @@ function useCart() {
314
283
  function useOptionalCart() {
315
284
  return useContext(CartContext);
316
285
  }
317
- function Money({
318
- data,
319
- as,
320
- locale,
321
- withoutTrailingZeros,
322
- withoutCurrency,
323
- currencyDisplay,
324
- ...rest
325
- }) {
326
- const sf = useOptionalStorefront();
327
- const text = formatMoney(data, locale ?? sf?.locale, {
328
- ...withoutTrailingZeros !== void 0 ? { withoutTrailingZeros } : {},
329
- ...withoutCurrency !== void 0 ? { withoutCurrency } : {},
330
- ...currencyDisplay !== void 0 ? { currencyDisplay } : {}
331
- });
332
- return createElement(as ?? "span", rest, text);
333
- }
334
- var DEFAULT_IMAGE_WIDTHS = [320, 480, 640, 768, 1024, 1280, 1600];
335
- var defaultImageLoader = (src, width, height) => {
336
- try {
337
- const isAbsolute = /^[a-z][a-z0-9+.-]*:/i.test(src);
338
- const url = new URL(src, "http://relative.invalid");
339
- url.searchParams.set("width", String(width));
340
- if (height) url.searchParams.set("height", String(height));
341
- return isAbsolute ? url.toString() : url.pathname + url.search + url.hash;
342
- } catch {
343
- return src;
344
- }
345
- };
346
- function parseRatio(ratio) {
347
- if (!ratio) return null;
348
- const [w, h] = ratio.split(/[/:]/).map((n) => Number.parseFloat(n));
349
- return w && h ? w / h : null;
350
- }
351
- function Image({
352
- data,
353
- sizes = "100vw",
354
- widths = DEFAULT_IMAGE_WIDTHS,
355
- loader = defaultImageLoader,
356
- priority = false,
357
- aspectRatio,
358
- alt,
359
- loading,
360
- decoding,
361
- ...rest
362
- }) {
363
- const ratio = parseRatio(aspectRatio) ?? (data.width && data.height ? data.width / data.height : null);
364
- let candidates = [...widths].sort((a, b) => a - b);
365
- if (data.width) {
366
- const capped = candidates.filter((w) => w <= data.width);
367
- candidates = capped.length ? capped : [data.width];
368
- }
369
- const srcSet = loader ? candidates.map((w) => `${loader(data.url, w, ratio ? Math.round(w / ratio) : void 0)} ${w}w`).join(", ") : void 0;
370
- const width = data.width ?? candidates[candidates.length - 1];
371
- const height = data.height ?? (ratio && width ? Math.round(width / ratio) : void 0);
372
- return /* @__PURE__ */ jsx(
373
- "img",
374
- {
375
- src: data.url,
376
- alt: alt ?? data.alt ?? "",
377
- ...srcSet ? { srcSet, sizes } : {},
378
- ...width ? { width } : {},
379
- ...height ? { height } : {},
380
- loading: loading ?? (priority ? "eager" : "lazy"),
381
- decoding: decoding ?? (priority ? "auto" : "async"),
382
- ...priority ? { fetchPriority: "high" } : {},
383
- ...rest
384
- }
385
- );
386
- }
387
- var VISUALLY_HIDDEN = {
388
- position: "absolute",
389
- width: 1,
390
- height: 1,
391
- padding: 0,
392
- margin: -1,
393
- overflow: "hidden",
394
- clip: "rect(0, 0, 0, 0)",
395
- whiteSpace: "nowrap",
396
- border: 0
397
- };
398
- function ProductPrice({
399
- product,
400
- variant,
401
- fromLabel = "Desde",
402
- compareAtLabel = "Precio anterior",
403
- locale,
404
- withoutTrailingZeros,
405
- ...rest
406
- }) {
407
- let price = null;
408
- let compareAt = null;
409
- let isRange = false;
410
- if (variant) {
411
- price = variant.price;
412
- compareAt = variant.compare_at_price;
413
- } else if (product) {
414
- price = product.price_range.min;
415
- compareAt = product.compare_at_price_range?.min ?? null;
416
- isRange = product.price_range.min.amount !== product.price_range.max.amount;
417
- }
418
- if (!price) return null;
419
- const onSale = compareAt !== null && parseMoney(compareAt) > parseMoney(price);
420
- const opts = { ...locale ? { locale } : {}, ...withoutTrailingZeros !== void 0 ? { withoutTrailingZeros } : {} };
421
- return /* @__PURE__ */ jsxs("div", { "data-on-sale": onSale || void 0, ...rest, children: [
422
- isRange ? /* @__PURE__ */ jsxs("span", { "data-price-prefix": "", children: [
423
- fromLabel,
424
- " "
425
- ] }) : null,
426
- /* @__PURE__ */ jsx(Money, { data: price, "data-price": "", ...opts }),
427
- onSale && compareAt ? /* @__PURE__ */ jsxs(Fragment, { children: [
428
- " ",
429
- /* @__PURE__ */ jsxs("s", { "data-compare-at-price": "", children: [
430
- /* @__PURE__ */ jsxs("span", { style: VISUALLY_HIDDEN, children: [
431
- compareAtLabel,
432
- ": "
433
- ] }),
434
- /* @__PURE__ */ jsx(Money, { data: compareAt, ...opts })
435
- ] })
436
- ] }) : null
437
- ] });
438
- }
439
286
  function toParams(input) {
440
287
  if (!input) return new URLSearchParams();
441
288
  return input instanceof URLSearchParams ? new URLSearchParams(input) : new URLSearchParams(input);
@@ -1336,6 +1183,6 @@ function NearestLocationForm({
1336
1183
  );
1337
1184
  }
1338
1185
 
1339
- export { AddToCartButton, CART_COOKIE_NAME, CartProvider, DEFAULT_IMAGE_WIDTHS, DirectionsLink, Image, JsonLd, LocationList, LocationPicker, Money, NearestLocationForm, OpenStatus, PickupOption, ProductPrice, SELECTED_LOCATION_PARAM, SELECTED_LOCATION_STORAGE_KEY, SectionRegistry, Sections, StorefrontProvider, ThemeStyle, VariantSelector, breadcrumbJsonLd, collectionJsonLd, collectionMeta, createSectionRegistry, defaultImageLoader, defineSection, faqJsonLd, getCartIdFromCookie, isSafeCssValue, localBusinessJsonLd, openingHoursJsonLd, optimisticCart, organizationJsonLd, productJsonLd, productMeta, readCartCookie, readSelectedLocationId, resolveSectionProps, sectionJsonSchema, seoMeta, serializeCartCookie, serializeJsonLd, themeFontsHref, themeToCss, themeToCssVariables, toMerchandise, tokenName, useCart, useGeolocation, useNearestLocations, useOptionalCart, useOptionalStorefront, useProductOptions, useSelectedLocation, useStorefront, useStorefrontClient, writeCartCookie };
1186
+ export { AddToCartButton, CART_COOKIE_NAME, CartProvider, DirectionsLink, JsonLd, LocationList, LocationPicker, NearestLocationForm, OpenStatus, PickupOption, SELECTED_LOCATION_PARAM, SELECTED_LOCATION_STORAGE_KEY, SectionRegistry, Sections, ThemeStyle, VariantSelector, breadcrumbJsonLd, collectionJsonLd, collectionMeta, createSectionRegistry, defineSection, faqJsonLd, getCartIdFromCookie, isSafeCssValue, localBusinessJsonLd, openingHoursJsonLd, optimisticCart, organizationJsonLd, productJsonLd, productMeta, readCartCookie, readSelectedLocationId, resolveSectionProps, sectionJsonSchema, seoMeta, serializeCartCookie, serializeJsonLd, themeFontsHref, themeToCss, themeToCssVariables, toMerchandise, tokenName, useCart, useGeolocation, useNearestLocations, useOptionalCart, useProductOptions, useSelectedLocation, writeCartCookie };
1340
1187
  //# sourceMappingURL=index.js.map
1341
1188
  //# sourceMappingURL=index.js.map