@shopify/hydrogen-react
Version:
React components, hooks, and utilities for creating custom Shopify storefronts
1 lines • 14.5 kB
Source Map (JSON)
{"version":3,"file":"useMoney.mjs","sources":["../../src/useMoney.tsx"],"sourcesContent":["import {useMemo} from 'react';\nimport {useShop} from './ShopifyProvider.js';\nimport {\n CurrencyCode as StorefrontApiCurrencyCode,\n MoneyV2 as StorefrontApiMoneyV2,\n} from './storefront-api-types.js';\nimport type {\n MoneyV2 as CustomerAccountApiMoneyV2,\n CurrencyCode as CustomerAccountApiCurrencyCode,\n} from './customer-account-api-types.js';\n\n// Support MoneyV2 from both Storefront API and Customer Account API\n// The APIs may have different CurrencyCode enums\n/**\n * Supports MoneyV2 from both Storefront API and Customer Account API.\n * The APIs may have different CurrencyCode enums (e.g., Customer Account API added USDC in 2025-10, but Storefront API doesn't support USDC in 2025-10).\n * This union type ensures useMoney works with data from either API.\n */\ntype MoneyV2 = StorefrontApiMoneyV2 | CustomerAccountApiMoneyV2;\n\n/**\n * Supports CurrencyCode from both Storefront API and Customer Account API. The APIs may have different CurrencyCode enums (e.g., Customer Account API added USDC in 2025-10, but Storefront API doesn't support USDC in 2025-10).\n * This union type ensures useMoney works with data from either API.\n */\ntype CurrencyCode = StorefrontApiCurrencyCode | CustomerAccountApiCurrencyCode;\n\nexport type UseMoneyValue = {\n /**\n * The currency code from the `MoneyV2` object.\n */\n currencyCode: CurrencyCode;\n /**\n * The name for the currency code, returned by `Intl.NumberFormat`.\n */\n currencyName?: string;\n /**\n * The currency symbol returned by `Intl.NumberFormat`.\n */\n currencySymbol?: string;\n /**\n * The currency narrow symbol returned by `Intl.NumberFormat`.\n */\n currencyNarrowSymbol?: string;\n /**\n * The localized amount, without any currency symbols or non-number types from the `Intl.NumberFormat.formatToParts` parts.\n */\n amount: string;\n /**\n * All parts returned by `Intl.NumberFormat.formatToParts`.\n */\n parts: Intl.NumberFormatPart[];\n /**\n * A string returned by `new Intl.NumberFormat` for the amount and currency code,\n * using the `locale` value in the [`LocalizationProvider` component](https://shopify.dev/api/hydrogen/components/localization/localizationprovider).\n */\n localizedString: string;\n /**\n * The `MoneyV2` object provided as an argument to the hook.\n */\n original: MoneyV2;\n /**\n * A string with trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `$640`.\n * `$640.42` remains `$640.42`.\n */\n withoutTrailingZeros: string;\n /**\n * A string without currency and without trailing zeros removed from the fractional part, if any exist. If there are no trailing zeros, then the fractional part remains.\n * For example, `$640.00` turns into `640`.\n * `$640.42` turns into `640.42`.\n */\n withoutTrailingZerosAndCurrency: string;\n};\n\n/**\n * The `useMoney` hook takes a [MoneyV2 object from the Storefront API](https://shopify.dev/docs/api/storefront/2026-01/objects/MoneyV2)\n * or a [MoneyV2 object from the Customer Account API](https://shopify.dev/docs/api/customer/2026-01/objects/moneyv2) and returns a\n * default-formatted string of the amount with the correct currency indicator, along with some of the parts provided by\n * [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat).\n * Uses `locale` from `ShopifyProvider`\n * \n * @see {@link https://shopify.dev/api/hydrogen/hooks/usemoney}\n * @example initialize the money object\n * ```ts\n * const money = useMoney({\n * amount: '100.00',\n * currencyCode: 'USD'\n * })\n * ```\n * \n *\n * @example basic usage, outputs: $100.00\n * ```ts\n * money.localizedString\n * ```\n * \n *\n * @example without currency, outputs: 100.00\n * ```ts\n * money.amount\n * ```\n * \n *\n * @example without trailing zeros, outputs: $100\n * ```ts\n * money.withoutTrailingZeros\n * ```\n * \n *\n * @example currency name, outputs: US dollars\n * ```ts\n * money.currencyCode\n * ```\n * \n *\n * @example currency symbol, outputs: $\n * ```ts\n * money.currencySymbol\n * ```\n * \n *\n * @example without currency and without trailing zeros, outputs: 100\n * ```ts\n * money.withoutTrailingZerosAndCurrency\n * ```\n */\nexport function useMoney(money: MoneyV2): UseMoneyValue {\n const {countryIsoCode, languageIsoCode} = useShop();\n const locale = languageIsoCode.includes('_')\n ? languageIsoCode.replace('_', '-')\n : `${languageIsoCode}-${countryIsoCode}`;\n\n if (!locale) {\n throw new Error(\n `useMoney(): Unable to get 'locale' from 'useShop()', which means that 'locale' was not passed to '<ShopifyProvider/>'. 'locale' is required for 'useMoney()' to work`,\n );\n }\n\n const amount = parseFloat(money.amount);\n\n // Check if the currency code is supported by Intl.NumberFormat\n let isCurrencySupported = true;\n try {\n new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: money.currencyCode,\n });\n } catch (e) {\n if (e instanceof RangeError && e.message.includes('currency')) {\n isCurrencySupported = false;\n }\n }\n\n const {\n defaultFormatter,\n nameFormatter,\n narrowSymbolFormatter,\n withoutTrailingZerosFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n } = useMemo(() => {\n // For unsupported currencies (like USDC cryptocurrency), use decimal formatting with 2 decimal places\n // We default to 2 decimal places based on research showing USDC displays like USD to reinforce its 1:1 peg\n const options = isCurrencySupported\n ? {\n style: 'currency' as const,\n currency: money.currencyCode,\n }\n : {\n style: 'decimal' as const,\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n };\n\n return {\n defaultFormatter: getLazyFormatter(locale, options),\n nameFormatter: getLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'name',\n }),\n narrowSymbolFormatter: getLazyFormatter(locale, {\n ...options,\n currencyDisplay: 'narrowSymbol',\n }),\n withoutTrailingZerosFormatter: getLazyFormatter(locale, {\n ...options,\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }),\n withoutCurrencyFormatter: getLazyFormatter(locale, {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }),\n withoutTrailingZerosOrCurrencyFormatter: getLazyFormatter(locale, {\n minimumFractionDigits: 0,\n maximumFractionDigits: 0,\n }),\n };\n }, [money.currencyCode, locale, isCurrencySupported]);\n\n const isPartCurrency = (part: Intl.NumberFormatPart): boolean =>\n part.type === 'currency';\n\n // By wrapping these properties in functions, we only\n // create formatters if they are going to be used.\n const lazyFormatters = useMemo(\n () => ({\n original: (): MoneyV2 => money,\n currencyCode: (): CurrencyCode => money.currencyCode,\n\n localizedString: (): string => {\n const formatted = defaultFormatter().format(amount);\n // For unsupported currencies, append the currency code\n return isCurrencySupported\n ? formatted\n : `${formatted} ${money.currencyCode}`;\n },\n\n parts: (): Intl.NumberFormatPart[] => {\n const parts = defaultFormatter().formatToParts(amount);\n // For unsupported currencies, add currency code as a currency part\n if (!isCurrencySupported) {\n parts.push(\n {type: 'literal', value: ' '},\n {type: 'currency', value: money.currencyCode},\n );\n }\n return parts;\n },\n\n withoutTrailingZeros: (): string => {\n const formatted =\n amount % 1 === 0\n ? withoutTrailingZerosFormatter().format(amount)\n : defaultFormatter().format(amount);\n // For unsupported currencies, append the currency code\n return isCurrencySupported\n ? formatted\n : `${formatted} ${money.currencyCode}`;\n },\n\n withoutTrailingZerosAndCurrency: (): string =>\n amount % 1 === 0\n ? withoutTrailingZerosOrCurrencyFormatter().format(amount)\n : withoutCurrencyFormatter().format(amount),\n\n currencyName: (): string =>\n nameFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"US dollars\"\n\n currencySymbol: (): string =>\n defaultFormatter().formatToParts(amount).find(isPartCurrency)?.value ??\n money.currencyCode, // e.g. \"USD\"\n\n currencyNarrowSymbol: (): string =>\n narrowSymbolFormatter().formatToParts(amount).find(isPartCurrency)\n ?.value ?? '', // e.g. \"$\"\n\n amount: (): string =>\n defaultFormatter()\n .formatToParts(amount)\n .filter((part) =>\n ['decimal', 'fraction', 'group', 'integer', 'literal'].includes(\n part.type,\n ),\n )\n .map((part) => part.value)\n .join(''),\n }),\n [\n money,\n amount,\n isCurrencySupported,\n nameFormatter,\n defaultFormatter,\n narrowSymbolFormatter,\n withoutCurrencyFormatter,\n withoutTrailingZerosFormatter,\n withoutTrailingZerosOrCurrencyFormatter,\n ],\n );\n\n // Call functions automatically when the properties are accessed\n // to keep these functions as an implementation detail.\n return useMemo(\n () =>\n new Proxy(lazyFormatters as unknown as UseMoneyValue, {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n get: (target, key) => Reflect.get(target, key)?.call(null),\n }),\n [lazyFormatters],\n );\n}\n\nconst formatterCache = new Map<string, Intl.NumberFormat>();\n\nfunction getLazyFormatter(\n locale: string,\n options?: Intl.NumberFormatOptions,\n): () => Intl.NumberFormat {\n const key = JSON.stringify([locale, options]);\n\n return function (): Intl.NumberFormat {\n let formatter = formatterCache.get(key);\n if (!formatter) {\n try {\n formatter = new Intl.NumberFormat(locale, options);\n } catch (error) {\n // Handle unsupported currency codes (e.g., USDC from Customer Account API)\n // Fall back to formatting without currency\n if (error instanceof RangeError && error.message.includes('currency')) {\n const fallbackOptions = {...options};\n delete fallbackOptions.currency;\n delete fallbackOptions.currencyDisplay;\n delete fallbackOptions.currencySign;\n formatter = new Intl.NumberFormat(locale, fallbackOptions);\n } else {\n throw error;\n }\n }\n formatterCache.set(key, formatter);\n }\n return formatter;\n };\n}\n"],"names":[],"mappings":";;AA8HO,SAAS,SAAS,OAA+B;AACtD,QAAM,EAAC,gBAAgB,gBAAA,IAAmB,QAAA;AAC1C,QAAM,SAAS,gBAAgB,SAAS,GAAG,IACvC,gBAAgB,QAAQ,KAAK,GAAG,IAChC,GAAG,eAAe,IAAI,cAAc;AAExC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAEA,QAAM,SAAS,WAAW,MAAM,MAAM;AAGtC,MAAI,sBAAsB;AAC1B,MAAI;AACF,QAAI,KAAK,aAAa,QAAQ;AAAA,MAC5B,OAAO;AAAA,MACP,UAAU,MAAM;AAAA,IAAA,CACjB;AAAA,EACH,SAAS,GAAG;AACV,QAAI,aAAa,cAAc,EAAE,QAAQ,SAAS,UAAU,GAAG;AAC7D,4BAAsB;AAAA,IACxB;AAAA,EACF;AAEA,QAAM;AAAA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