@dropins/storefront-checkout 3.3.0-beta.0 → 3.3.0-beta.2
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/CHANGELOG.md +12 -0
- package/api.js +266 -0
- package/api.js.map +1 -0
- package/chunks/PaymentOnAccount.js +1 -1
- package/chunks/PaymentOnAccount.js.map +1 -1
- package/chunks/PurchaseOrder.js +1 -1
- package/chunks/PurchaseOrder.js.map +1 -1
- package/chunks/components.js +2 -2
- package/chunks/components.js.map +1 -1
- package/chunks/events.js +4 -0
- package/chunks/events.js.map +1 -0
- package/chunks/render.js +1 -1
- package/chunks/render.js.map +1 -1
- package/chunks/ui.js +4 -0
- package/chunks/ui.js.map +1 -0
- package/containers/AddressValidation.js +1 -1
- package/containers/AddressValidation.js.map +1 -1
- package/containers/BillToShippingAddress.js +1 -1
- package/containers/BillToShippingAddress.js.map +1 -1
- package/containers/EstimateShipping.js +1 -1
- package/containers/EstimateShipping.js.map +1 -1
- package/containers/LoginForm.js +1 -1
- package/containers/LoginForm.js.map +1 -1
- package/containers/MergedCartBanner.js +1 -1
- package/containers/MergedCartBanner.js.map +1 -1
- package/containers/OutOfStock.js +1 -1
- package/containers/OutOfStock.js.map +1 -1
- package/containers/PaymentMethods.js +1 -1
- package/containers/PaymentMethods.js.map +1 -1
- package/containers/PaymentOnAccount.js +1 -1
- package/containers/PlaceOrder.js +1 -1
- package/containers/PlaceOrder.js.map +1 -1
- package/containers/PurchaseOrder.js +1 -1
- package/containers/ServerError.js +1 -1
- package/containers/ServerError.js.map +1 -1
- package/containers/ShippingMethods.js +1 -1
- package/containers/ShippingMethods.js.map +1 -1
- package/containers/TermsAndConditions.js +1 -1
- package/containers/TermsAndConditions.js.map +1 -1
- package/fragments.js +275 -1
- package/fragments.js.map +1 -1
- package/lib/index.d.ts +0 -1
- package/lib/utils/index.d.ts +1 -1
- package/lib/utils.js +1 -537
- package/lib/utils.js.map +1 -1
- package/package.json +1 -1
- package/render.js +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PaymentMethods.js","sources":["../../node_modules/@adobe-commerce/elsie/src/lib/debounce.ts","/@dropins/storefront-checkout/src/containers/PaymentMethods/handlers.tsx","/@dropins/storefront-checkout/src/containers/PaymentMethods/PaymentMethods.tsx"],"sourcesContent":["/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const debounce = (fn: Function, ms: number) => {\n let timeoutId: ReturnType<typeof setTimeout>;\n const debouncedFn = function (this: any, ...args: any[]) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn.apply(this, args), ms);\n };\n debouncedFn.cancel = () => {\n clearTimeout(timeoutId);\n };\n return debouncedFn;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { setPaymentMethod } from '@/checkout/api';\nimport {\n PaymentMethodConfig,\n PaymentOnAccount,\n PurchaseOrder,\n} from '@/checkout/containers';\nimport { validateNotEmpty } from '@/checkout/lib/validation';\nimport { render as Checkout } from '@/checkout/render/render';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { debounce } from '@adobe-commerce/elsie/lib/debounce';\n\ninterface HandlerConfig {\n Container: Container<any>;\n autoSync: boolean;\n formName?: string;\n validateRefNumber: boolean;\n}\n\nexport enum HandlerCode {\n PaymentOnAccount = 'companycredit',\n PurchaseOrder = 'purchaseorder',\n}\n\nconst HANDLERS_CONFIG: Record<HandlerCode, HandlerConfig> = {\n [HandlerCode.PaymentOnAccount]: {\n Container: PaymentOnAccount,\n autoSync: true,\n formName: 'payment-on-account',\n validateRefNumber: false,\n },\n [HandlerCode.PurchaseOrder]: {\n Container: PurchaseOrder,\n autoSync: false,\n formName: 'purchase-order',\n validateRefNumber: true,\n },\n} as const;\n\n// Cache for debounced handlers to prevent memory leaks\nconst debouncedHandlers = new Map<string, ReturnType<typeof debounce>>();\n\nexport const handleRefNumberChange = (code: string, isRequired: boolean) => {\n const key = `${code}-${isRequired}`;\n\n if (!debouncedHandlers.has(key)) {\n const debouncedFn = debounce(async (refNumber: string) => {\n if (!isRequired || validateNotEmpty(refNumber)) {\n try {\n await setPaymentMethod({\n code,\n purchase_order_number: refNumber,\n });\n } catch (error) {\n console.error(`Failed to set payment method for ${code}:`, error);\n }\n }\n }, 1000);\n\n debouncedHandlers.set(key, debouncedFn);\n }\n\n return debouncedHandlers.get(key)!;\n};\n\nconst handlerCache: Partial<Record<HandlerCode, PaymentMethodConfig>> = {};\n\nexport const resetHandlersCache = () => {\n Object.keys(handlerCache).forEach((key) => {\n delete handlerCache[key as HandlerCode];\n });\n\n debouncedHandlers.clear();\n};\n\nexport const createHandler = (code: HandlerCode): PaymentMethodConfig => {\n if (!(code in HANDLERS_CONFIG)) {\n throw new Error(`Invalid handler code: ${code}`);\n }\n\n if (handlerCache[code]) {\n return handlerCache[code] as PaymentMethodConfig;\n }\n\n const config = HANDLERS_CONFIG[code];\n\n const { autoSync, Container, formName, validateRefNumber } = config;\n\n const handler: PaymentMethodConfig = {\n enabled: true,\n autoSync,\n render: (ctx) => {\n const initialReferenceNumber = String(\n ctx.additionalData?.purchase_order_number ?? ''\n );\n\n const $wrapper = document.createElement('div');\n\n Checkout.render(Container, {\n name: formName,\n initialReferenceNumber,\n onReferenceNumberChange: handleRefNumberChange(code, validateRefNumber),\n })($wrapper);\n\n ctx.replaceHTML($wrapper);\n },\n };\n\n handlerCache[code] = handler;\n\n return handler;\n};\n\nexport const defaultHandlers = {\n [HandlerCode.PaymentOnAccount]: createHandler(HandlerCode.PaymentOnAccount),\n [HandlerCode.PurchaseOrder]: createHandler(HandlerCode.PurchaseOrder),\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { setPaymentMethod } from '@/checkout/api';\nimport { PaymentMethods as PaymentMethodsComponent } from '@/checkout/components/PaymentMethods/PaymentMethods';\nimport { Cart } from '@/checkout/data/models/cart';\nimport {\n AdditionalData,\n PaymentMethod\n} from '@/checkout/data/models/payment-method';\nimport { NegotiableQuote } from '@/checkout/data/models/quote';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingUpdates,\n hasShippingAddress,\n isVirtualCart,\n notifyValues,\n state\n} from '@/checkout/lib';\nimport { TitleProps, UIComponentType } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport {\n Container,\n deepmerge,\n Slot,\n SlotProps\n} from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks';\nimport { defaultHandlers } from './handlers';\n\ninterface RenderContext {\n additionalData?: AdditionalData;\n cartId: string;\n replaceHTML: (domElement: HTMLElement) => void;\n setAdditionalData: (data: AdditionalData) => void;\n}\n\nexport interface PaymentMethodConfig {\n autoSync?: boolean;\n displayLabel?: boolean;\n enabled?: boolean;\n icon?: string;\n render?: SlotProps<RenderContext>;\n}\n\nexport interface PaymentMethodHandlers {\n [code: string]: PaymentMethodConfig;\n}\n\ninterface CartSyncError {\n method: PaymentMethod;\n error: Error;\n}\n\nexport interface PaymentMethodsProps\n extends HTMLAttributes<HTMLDivElement>,\n TitleProps {\n slots?: {\n Methods?: PaymentMethodHandlers;\n } & TitleProps['slots'];\n UIComponentType?: UIComponentType;\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onSelectionChange?: (method: PaymentMethod) => void;\n}\n\nfunction isAvailable(\n selection: PaymentMethod | null,\n options: PaymentMethod[]\n) {\n if (!selection) return false;\n return options.some((option) => option.code === selection.code);\n}\n\nfunction isEqual(a: PaymentMethod | null, b: PaymentMethod | null) {\n if (!a || !b) return false;\n return a.code === b.code;\n}\n\nfunction isValid(method: PaymentMethod | null) {\n if (!method) return false;\n return !!method.code && !!method.title;\n}\n\nexport const PaymentMethods: Container<PaymentMethodsProps> = ({\n UIComponentType = 'ToggleButton',\n active = true,\n autoSync = true,\n displayTitle = true,\n slots,\n onCartSyncError,\n onSelectionChange,\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isInitialized, setIsInitialized] = useState(false);\n const [selection, setSelection] = useState<PaymentMethod | null>(null);\n const [options, setOptions] = useState<PaymentMethod[]>([]);\n const isBusy = hasPendingUpdates.value;\n\n const { cartSyncError, defaultTitle } = useText({\n cartSyncError: 'Checkout.PaymentMethods.cartSyncError',\n defaultTitle: 'Checkout.PaymentMethods.title',\n });\n\n const availableHandlers = useMemo(() => {\n const customHandlers = slots?.Methods ?? {};\n return deepmerge(defaultHandlers, customHandlers);\n }, [slots?.Methods]);\n\n const getSlot = useCallback((method: PaymentMethod) => {\n return availableHandlers[method.code]?.render;\n }, [availableHandlers]);\n\n const hasAutoSyncEnabled = useCallback((method: PaymentMethod) => {\n const config = availableHandlers[method.code];\n if (!config) return autoSync;\n return config.autoSync !== false;\n }, [autoSync, availableHandlers]);\n\n const isEnabled = useCallback((method: PaymentMethod) => {\n const config = availableHandlers[method.code]?.enabled;\n return config !== false;\n }, [availableHandlers]);\n\n const withIcons = useCallback((options: PaymentMethod[]) => {\n return options.map((option) => {\n const handler = availableHandlers[option.code];\n if (!handler) return option;\n return {\n ...option,\n icon: handler.icon\n };\n });\n }, [availableHandlers]);\n\n const setAdditionalData = useCallback((additionalData: AdditionalData) => {\n setSelection((prev) => {\n if (!prev) return prev;\n return { ...prev, additionalData };\n });\n }, []);\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const updateSelection = useCallback((selection: PaymentMethod | null) => {\n setError(null);\n setSelection(selection);\n }, []);\n\n const updateCartSelection = useCallback(\n async (selection: PaymentMethod, fallback?: PaymentMethod | null) => {\n const canSetSelectionOnCart = isVirtualCart() || hasShippingAddress();\n\n if (!canSetSelectionOnCart) return;\n if (!hasAutoSyncEnabled(selection)) return;\n\n setPaymentMethod({\n code: selection.code,\n ...(selection.additionalData ?? {}),\n }).catch((error) => {\n updateSelection(fallback ?? null);\n setError(onCartSyncError ? null : cartSyncError);\n onCartSyncError?.({ method: selection, error });\n });\n },\n [\n cartSyncError,\n hasAutoSyncEnabled,\n onCartSyncError,\n updateSelection,\n ]\n );\n\n const handleSelectionChange = useCallback(\n async (selection: PaymentMethod) => {\n const prevSelection = getValue('selectedPaymentMethod');\n updateSelection(selection);\n onSelectionChange?.(selection);\n await updateCartSelection(selection, prevSelection);\n },\n [onSelectionChange, updateSelection, updateCartSelection]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || data.isEmpty;\n\n if (isEmptyCart) {\n updateSelection(null);\n setOptions([]);\n return;\n }\n\n const availableOptions = data.availablePaymentMethods ?? [];\n const enabledOptions = availableOptions.filter(isEnabled);\n\n setOptions(enabledOptions);\n\n if (enabledOptions.length === 0) {\n updateSelection(null);\n return;\n }\n\n const cartSelection = data.selectedPaymentMethod ?? null;\n const hasCartSelection = isValid(cartSelection);\n const userSelection = getValue('selectedPaymentMethod');\n const isUserSelectionAvailable = isAvailable(userSelection, enabledOptions);\n const haveSameSelection = isEqual(userSelection, cartSelection);\n\n // User has valid selection that differs from cart\n if (userSelection && isUserSelectionAvailable && !haveSameSelection) {\n updateCartSelection(userSelection, cartSelection);\n return;\n }\n\n // User has invalid selection but cart has valid selection\n if (\n (!userSelection || !isUserSelectionAvailable) &&\n hasCartSelection &&\n isAvailable(cartSelection, enabledOptions)\n ) {\n updateSelection(cartSelection);\n return;\n }\n\n // Neither user nor cart has valid selection (or both selections are unavailable)\n if (\n (!userSelection || !isUserSelectionAvailable) &&\n (!hasCartSelection ||\n !isAvailable(cartSelection, enabledOptions))\n ) {\n const newSelection = enabledOptions[0];\n updateSelection(newSelection);\n updateCartSelection(newSelection);\n }\n },\n [isEnabled, updateSelection, updateCartSelection]\n );\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n setIsInitialized(true);\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userSelection = getValue('selectedPaymentMethod');\n if (userSelection) {\n setSelection(userSelection);\n }\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n (data: Cart | NegotiableQuote | null) => {\n setIsInitialized(true);\n handleCheckoutData(data);\n },\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n notifyValues({ selectedPaymentMethod: selection });\n }, [selection]);\n\n const titleContent = useMemo(() => {\n if (!displayTitle) return undefined;\n\n return (\n <Slot name=\"checkout-payment-methods-title\" slot={slots?.Title}>\n <h2>{defaultTitle}</h2>\n </Slot>\n );\n }, [displayTitle, slots?.Title, defaultTitle]);\n\n const paymentMethodContent = useMemo(() => {\n if (!selection) return;\n\n const slot = getSlot(selection);\n if (!slot) return;\n\n return (\n <Slot\n key={selection!.code}\n context={{\n additionalData: selection!.additionalData,\n cartId: state.cartId ?? '',\n replaceHTML(domElement: HTMLElement) {\n this.replaceWith(domElement);\n },\n setAdditionalData,\n }}\n name=\"PaymentMethodContent\"\n slot={slot}\n />\n );\n\n }, [getSlot, selection, setAdditionalData]);\n\n return (\n <PaymentMethodsComponent\n UIComponentType={UIComponentType}\n busy={isBusy}\n error={error}\n initialized={isInitialized}\n options={withIcons(options)}\n paymentMethodContent={paymentMethodContent}\n selection={selection}\n title={titleContent}\n visible={active}\n onDismissError={handleDismissError}\n onSelectionChange={handleSelectionChange}\n />\n );\n};\n"],"names":["debounce","fn","ms","timeoutId","debouncedFn","args","HandlerCode","HANDLERS_CONFIG","PaymentOnAccount","PurchaseOrder","debouncedHandlers","handleRefNumberChange","code","isRequired","key","refNumber","validateNotEmpty","setPaymentMethod","error","handlerCache","resetHandlersCache","createHandler","config","autoSync","Container","formName","validateRefNumber","handler","ctx","initialReferenceNumber","_a","$wrapper","Checkout","defaultHandlers","isAvailable","selection","options","option","isEqual","a","b","isValid","method","PaymentMethods","UIComponentType","active","displayTitle","slots","onCartSyncError","onSelectionChange","setError","useState","isInitialized","setIsInitialized","setSelection","setOptions","isBusy","hasPendingUpdates","cartSyncError","defaultTitle","useText","availableHandlers","useMemo","customHandlers","deepmerge","getSlot","useCallback","hasAutoSyncEnabled","isEnabled","withIcons","setAdditionalData","additionalData","prev","handleDismissError","updateSelection","updateCartSelection","fallback","isVirtualCart","hasShippingAddress","handleSelectionChange","prevSelection","getValue","handleCheckoutData","data","enabledOptions","cartSelection","hasCartSelection","userSelection","isUserSelectionAvailable","haveSameSelection","newSelection","useEffect","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","events","onCheckoutUpdated","notifyValues","titleContent","jsx","Slot","paymentMethodContent","slot","state","domElement","PaymentMethodsComponent"],"mappings":"0zBASa,MAAAA,GAAW,CAACC,EAAcC,IAAe,CAChD,IAAAC,EACE,MAAAC,EAAc,YAAwBC,EA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AS,CACP,eAAgBjE,EAAW,eAC3B,OAAQoE,GAAM,QAAU,GACxB,YAAYC,EAAyB,CACnC,KAAK,YAAYA,CAAU,CAC7B,EACA,kBAAAlC,CACF,EACA,KAAK,uBACL,KAAAgC,CAAA,EAVKnE,EAAW,IAWlB,CAGD,EAAA,CAAC8B,EAAS9B,EAAWmC,CAAiB,CAAC,EAGxC,OAAA6B,EAACM,GAAA,CACC,gBAAiB7D,EACjB,KAAMY,EACN,MAAAtC,EACA,YAAakC,EACb,QAASiB,EAAUjC,CAAO,EAC1B,qBAAAiE,EACA,UAAAlE,EACA,MAAO+D,EACP,QAASrD,EACT,eAAgB4B,EAChB,kBAAmBM,CAAA,CACrB,CAEJ","x_google_ignoreList":[0]}
|
|
1
|
+
{"version":3,"file":"PaymentMethods.js","sources":["../../node_modules/@adobe-commerce/elsie/src/lib/debounce.ts","/@dropins/storefront-checkout/src/containers/PaymentMethods/handlers.tsx","/@dropins/storefront-checkout/src/containers/PaymentMethods/PaymentMethods.tsx"],"sourcesContent":["/********************************************************************\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: Adobe permits you to use, modify, and distribute this \n * file in accordance with the terms of the Adobe license agreement \n * accompanying it. \n *******************************************************************/\n\nexport const debounce = (fn: Function, ms: number) => {\n let timeoutId: ReturnType<typeof setTimeout>;\n const debouncedFn = function (this: any, ...args: any[]) {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => fn.apply(this, args), ms);\n };\n debouncedFn.cancel = () => {\n clearTimeout(timeoutId);\n };\n return debouncedFn;\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2025 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { setPaymentMethod } from '@/checkout/api';\nimport {\n PaymentMethodConfig,\n PaymentOnAccount,\n PurchaseOrder,\n} from '@/checkout/containers';\nimport { validateNotEmpty } from '@/checkout/lib/validation';\nimport { render as Checkout } from '@/checkout/render/render';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { debounce } from '@adobe-commerce/elsie/lib/debounce';\n\ninterface HandlerConfig {\n Container: Container<any>;\n autoSync: boolean;\n formName?: string;\n validateRefNumber: boolean;\n}\n\nexport enum HandlerCode {\n PaymentOnAccount = 'companycredit',\n PurchaseOrder = 'purchaseorder',\n}\n\nconst HANDLERS_CONFIG: Record<HandlerCode, HandlerConfig> = {\n [HandlerCode.PaymentOnAccount]: {\n Container: PaymentOnAccount,\n autoSync: true,\n formName: 'payment-on-account',\n validateRefNumber: false,\n },\n [HandlerCode.PurchaseOrder]: {\n Container: PurchaseOrder,\n autoSync: false,\n formName: 'purchase-order',\n validateRefNumber: true,\n },\n} as const;\n\n// Cache for debounced handlers to prevent memory leaks\nconst debouncedHandlers = new Map<string, ReturnType<typeof debounce>>();\n\nexport const handleRefNumberChange = (code: string, isRequired: boolean) => {\n const key = `${code}-${isRequired}`;\n\n if (!debouncedHandlers.has(key)) {\n const debouncedFn = debounce(async (refNumber: string) => {\n if (!isRequired || validateNotEmpty(refNumber)) {\n try {\n await setPaymentMethod({\n code,\n purchase_order_number: refNumber,\n });\n } catch (error) {\n console.error(`Failed to set payment method for ${code}:`, error);\n }\n }\n }, 1000);\n\n debouncedHandlers.set(key, debouncedFn);\n }\n\n return debouncedHandlers.get(key)!;\n};\n\nconst handlerCache: Partial<Record<HandlerCode, PaymentMethodConfig>> = {};\n\nexport const resetHandlersCache = () => {\n Object.keys(handlerCache).forEach((key) => {\n delete handlerCache[key as HandlerCode];\n });\n\n debouncedHandlers.clear();\n};\n\nexport const createHandler = (code: HandlerCode): PaymentMethodConfig => {\n if (!(code in HANDLERS_CONFIG)) {\n throw new Error(`Invalid handler code: ${code}`);\n }\n\n if (handlerCache[code]) {\n return handlerCache[code] as PaymentMethodConfig;\n }\n\n const config = HANDLERS_CONFIG[code];\n\n const { autoSync, Container, formName, validateRefNumber } = config;\n\n const handler: PaymentMethodConfig = {\n enabled: true,\n autoSync,\n render: (ctx) => {\n const initialReferenceNumber = String(\n ctx.additionalData?.purchase_order_number ?? ''\n );\n\n const $wrapper = document.createElement('div');\n\n Checkout.render(Container, {\n name: formName,\n initialReferenceNumber,\n onReferenceNumberChange: handleRefNumberChange(code, validateRefNumber),\n })($wrapper);\n\n ctx.replaceHTML($wrapper);\n },\n };\n\n handlerCache[code] = handler;\n\n return handler;\n};\n\nexport const defaultHandlers = {\n [HandlerCode.PaymentOnAccount]: createHandler(HandlerCode.PaymentOnAccount),\n [HandlerCode.PurchaseOrder]: createHandler(HandlerCode.PurchaseOrder),\n};\n","/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { setPaymentMethod } from '@/checkout/api';\nimport { PaymentMethods as PaymentMethodsComponent } from '@/checkout/components/PaymentMethods/PaymentMethods';\nimport { Cart } from '@/checkout/data/models/cart';\nimport {\n AdditionalData,\n PaymentMethod\n} from '@/checkout/data/models/payment-method';\nimport { NegotiableQuote } from '@/checkout/data/models/quote';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingUpdates,\n hasShippingAddress,\n notifyValues,\n state\n} from '@/checkout/lib';\nimport { isVirtualCart } from '@/checkout/lib/utils/events';\nimport { TitleProps, UIComponentType } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport {\n Container,\n deepmerge,\n Slot,\n SlotProps\n} from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks';\nimport { defaultHandlers } from './handlers';\n\ninterface RenderContext {\n additionalData?: AdditionalData;\n cartId: string;\n replaceHTML: (domElement: HTMLElement) => void;\n setAdditionalData: (data: AdditionalData) => void;\n}\n\nexport interface PaymentMethodConfig {\n autoSync?: boolean;\n displayLabel?: boolean;\n enabled?: boolean;\n icon?: string;\n render?: SlotProps<RenderContext>;\n}\n\nexport interface PaymentMethodHandlers {\n [code: string]: PaymentMethodConfig;\n}\n\ninterface CartSyncError {\n method: PaymentMethod;\n error: Error;\n}\n\nexport interface PaymentMethodsProps\n extends HTMLAttributes<HTMLDivElement>,\n TitleProps {\n slots?: {\n Methods?: PaymentMethodHandlers;\n } & TitleProps['slots'];\n UIComponentType?: UIComponentType;\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onSelectionChange?: (method: PaymentMethod) => void;\n}\n\nfunction isAvailable(\n selection: PaymentMethod | null,\n options: PaymentMethod[]\n) {\n if (!selection) return false;\n return options.some((option) => option.code === selection.code);\n}\n\nfunction isEqual(a: PaymentMethod | null, b: PaymentMethod | null) {\n if (!a || !b) return false;\n return a.code === b.code;\n}\n\nfunction isValid(method: PaymentMethod | null) {\n if (!method) return false;\n return !!method.code && !!method.title;\n}\n\nexport const PaymentMethods: Container<PaymentMethodsProps> = ({\n UIComponentType = 'ToggleButton',\n active = true,\n autoSync = true,\n displayTitle = true,\n slots,\n onCartSyncError,\n onSelectionChange,\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isInitialized, setIsInitialized] = useState(false);\n const [selection, setSelection] = useState<PaymentMethod | null>(null);\n const [options, setOptions] = useState<PaymentMethod[]>([]);\n const isBusy = hasPendingUpdates.value;\n\n const { cartSyncError, defaultTitle } = useText({\n cartSyncError: 'Checkout.PaymentMethods.cartSyncError',\n defaultTitle: 'Checkout.PaymentMethods.title',\n });\n\n const availableHandlers = useMemo(() => {\n const customHandlers = slots?.Methods ?? {};\n return deepmerge(defaultHandlers, customHandlers);\n }, [slots?.Methods]);\n\n const getSlot = useCallback((method: PaymentMethod) => {\n return availableHandlers[method.code]?.render;\n }, [availableHandlers]);\n\n const hasAutoSyncEnabled = useCallback((method: PaymentMethod) => {\n const config = availableHandlers[method.code];\n if (!config) return autoSync;\n return config.autoSync !== false;\n }, [autoSync, availableHandlers]);\n\n const isEnabled = useCallback((method: PaymentMethod) => {\n const config = availableHandlers[method.code]?.enabled;\n return config !== false;\n }, [availableHandlers]);\n\n const withIcons = useCallback((options: PaymentMethod[]) => {\n return options.map((option) => {\n const handler = availableHandlers[option.code];\n if (!handler) return option;\n return {\n ...option,\n icon: handler.icon\n };\n });\n }, [availableHandlers]);\n\n const setAdditionalData = useCallback((additionalData: AdditionalData) => {\n setSelection((prev) => {\n if (!prev) return prev;\n return { ...prev, additionalData };\n });\n }, []);\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const updateSelection = useCallback((selection: PaymentMethod | null) => {\n setError(null);\n setSelection(selection);\n }, []);\n\n const updateCartSelection = useCallback(\n async (selection: PaymentMethod, fallback?: PaymentMethod | null) => {\n const canSetSelectionOnCart = isVirtualCart() || hasShippingAddress();\n\n if (!canSetSelectionOnCart) return;\n if (!hasAutoSyncEnabled(selection)) return;\n\n setPaymentMethod({\n code: selection.code,\n ...(selection.additionalData ?? {}),\n }).catch((error) => {\n updateSelection(fallback ?? null);\n setError(onCartSyncError ? null : cartSyncError);\n onCartSyncError?.({ method: selection, error });\n });\n },\n [\n cartSyncError,\n hasAutoSyncEnabled,\n onCartSyncError,\n updateSelection,\n ]\n );\n\n const handleSelectionChange = useCallback(\n async (selection: PaymentMethod) => {\n const prevSelection = getValue('selectedPaymentMethod');\n updateSelection(selection);\n onSelectionChange?.(selection);\n await updateCartSelection(selection, prevSelection);\n },\n [onSelectionChange, updateSelection, updateCartSelection]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || data.isEmpty;\n\n if (isEmptyCart) {\n updateSelection(null);\n setOptions([]);\n return;\n }\n\n const availableOptions = data.availablePaymentMethods ?? [];\n const enabledOptions = availableOptions.filter(isEnabled);\n\n setOptions(enabledOptions);\n\n if (enabledOptions.length === 0) {\n updateSelection(null);\n return;\n }\n\n const cartSelection = data.selectedPaymentMethod ?? null;\n const hasCartSelection = isValid(cartSelection);\n const userSelection = getValue('selectedPaymentMethod');\n const isUserSelectionAvailable = isAvailable(userSelection, enabledOptions);\n const haveSameSelection = isEqual(userSelection, cartSelection);\n\n // User has valid selection that differs from cart\n if (userSelection && isUserSelectionAvailable && !haveSameSelection) {\n updateCartSelection(userSelection, cartSelection);\n return;\n }\n\n // User has invalid selection but cart has valid selection\n if (\n (!userSelection || !isUserSelectionAvailable) &&\n hasCartSelection &&\n isAvailable(cartSelection, enabledOptions)\n ) {\n updateSelection(cartSelection);\n return;\n }\n\n // Neither user nor cart has valid selection (or both selections are unavailable)\n if (\n (!userSelection || !isUserSelectionAvailable) &&\n (!hasCartSelection ||\n !isAvailable(cartSelection, enabledOptions))\n ) {\n const newSelection = enabledOptions[0];\n updateSelection(newSelection);\n updateCartSelection(newSelection);\n }\n },\n [isEnabled, updateSelection, updateCartSelection]\n );\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n setIsInitialized(true);\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userSelection = getValue('selectedPaymentMethod');\n if (userSelection) {\n setSelection(userSelection);\n }\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n (data: Cart | NegotiableQuote | null) => {\n setIsInitialized(true);\n handleCheckoutData(data);\n },\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n notifyValues({ selectedPaymentMethod: selection });\n }, [selection]);\n\n const titleContent = useMemo(() => {\n if (!displayTitle) return undefined;\n\n return (\n <Slot name=\"checkout-payment-methods-title\" slot={slots?.Title}>\n <h2>{defaultTitle}</h2>\n </Slot>\n );\n }, [displayTitle, slots?.Title, defaultTitle]);\n\n const paymentMethodContent = useMemo(() => {\n if (!selection) return;\n\n const slot = getSlot(selection);\n if (!slot) return;\n\n return (\n <Slot\n key={selection!.code}\n context={{\n additionalData: selection!.additionalData,\n cartId: state.cartId ?? '',\n replaceHTML(domElement: HTMLElement) {\n this.replaceWith(domElement);\n },\n setAdditionalData,\n }}\n name=\"PaymentMethodContent\"\n slot={slot}\n />\n );\n\n }, [getSlot, selection, setAdditionalData]);\n\n return (\n <PaymentMethodsComponent\n UIComponentType={UIComponentType}\n busy={isBusy}\n error={error}\n initialized={isInitialized}\n options={withIcons(options)}\n paymentMethodContent={paymentMethodContent}\n selection={selection}\n title={titleContent}\n visible={active}\n onDismissError={handleDismissError}\n onSelectionChange={handleSelectionChange}\n />\n );\n};\n"],"names":["debounce","fn","ms","timeoutId","debouncedFn","args","HandlerCode","HANDLERS_CONFIG","PaymentOnAccount","PurchaseOrder","debouncedHandlers","handleRefNumberChange","code","isRequired","key","refNumber","validateNotEmpty","setPaymentMethod","error","handlerCache","resetHandlersCache","createHandler","config","autoSync","Container","formName","validateRefNumber","handler","ctx","initialReferenceNumber","_a","$wrapper","Checkout","defaultHandlers","isAvailable","selection","options","option","isEqual","a","b","isValid","method","PaymentMethods","UIComponentType","active","displayTitle","slots","onCartSyncError","onSelectionChange","setError","useState","isInitialized","setIsInitialized","setSelection","setOptions","isBusy","hasPendingUpdates","cartSyncError","defaultTitle","useText","availableHandlers","useMemo","customHandlers","deepmerge","getSlot","useCallback","hasAutoSyncEnabled","isEnabled","withIcons","setAdditionalData","additionalData","prev","handleDismissError","updateSelection","updateCartSelection","fallback","isVirtualCart","hasShippingAddress","handleSelectionChange","prevSelection","getValue","handleCheckoutData","data","enabledOptions","cartSelection","hasCartSelection","userSelection","isUserSelectionAvailable","haveSameSelection","newSelection","useEffect","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","events","onCheckoutUpdated","notifyValues","titleContent","jsx","Slot","paymentMethodContent","slot","state","domElement","PaymentMethodsComponent"],"mappings":"y3BASa,MAAAA,GAAW,CAACC,EAAcC,IAAe,CAChD,IAAAC,EACE,MAAAC,EAAc,YAAwBC,EAAa,CACvD,aAAaF,CAAS,EACtBA,EAAY,WAAW,IAAMF,EAAG,MAAM,KAAMI,CAAI,EAAGH,CAAE,CACvD,EACA,OAAAE,EAAY,OAAS,IAAM,CACzB,aAAaD,CAAS,CACxB,EACOC,CACT,ECgBY,IAAAE,IAAAA,IACVA,EAAA,iBAAmB,gBACnBA,EAAA,cAAgB,gBAFNA,IAAAA,IAAA,CAAA,CAAA,EAKZ,MAAMC,EAAsD,CACzD,cAA+B,CAC9B,UAAWC,GACX,SAAU,GACV,SAAU,qBACV,kBAAmB,EACrB,EACC,cAA4B,CAC3B,UAAWC,GACX,SAAU,GACV,SAAU,iBACV,kBAAmB,EAAA,CAEvB,EAGMC,MAAwB,IAEjBC,GAAwB,CAACC,EAAcC,IAAwB,CAC1E,MAAMC,EAAM,GAAGF,CAAI,IAAIC,CAAU,GAEjC,GAAI,CAACH,EAAkB,IAAII,CAAG,EAAG,CACzB,MAAAV,EAAcJ,GAAS,MAAOe,GAAsB,CACxD,GAAI,CAACF,GAAcG,GAAiBD,CAAS,EACvC,GAAA,CACF,MAAME,EAAiB,CACrB,KAAAL,EACA,sBAAuBG,CAAA,CACxB,QACMG,EAAO,CACd,QAAQ,MAAM,oCAAoCN,CAAI,IAAKM,CAAK,CAAA,G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DM,GAAA,CAAE,sBAAuB9D,EAAW,CAAA,EAChD,CAACA,CAAS,CAAC,EAER,MAAA+D,EAAepC,EAAQ,IAAM,CAC7B,GAAChB,EAGH,OAAAqD,EAACC,EAAK,CAAA,KAAK,iCAAiC,KAAMrD,GAAA,YAAAA,EAAO,MACvD,SAAAoD,EAAC,KAAI,CAAA,SAAAxC,CAAa,CAAA,EACpB,GAED,CAACb,EAAcC,GAAA,YAAAA,EAAO,MAAOY,CAAY,CAAC,EAEvC0C,EAAuBvC,EAAQ,IAAM,CACzC,GAAI,CAAC3B,EAAW,OAEV,MAAAmE,EAAOrC,EAAQ9B,CAAS,EAC9B,GAAKmE,EAGH,OAAAH,EAACC,EAAA,CAEC,QAAS,CACP,eAAgBjE,EAAW,eAC3B,OAAQoE,GAAM,QAAU,GACxB,YAAYC,EAAyB,CACnC,KAAK,YAAYA,CAAU,CAC7B,EACA,kBAAAlC,CACF,EACA,KAAK,uBACL,KAAAgC,CAAA,EAVKnE,EAAW,IAWlB,CAGD,EAAA,CAAC8B,EAAS9B,EAAWmC,CAAiB,CAAC,EAGxC,OAAA6B,EAACM,GAAA,CACC,gBAAiB7D,EACjB,KAAMY,EACN,MAAAtC,EACA,YAAakC,EACb,QAASiB,EAAUjC,CAAO,EAC1B,qBAAAiE,EACA,UAAAlE,EACA,MAAO+D,EACP,QAASrD,EACT,eAAgB4B,EAChB,kBAAmBM,CAAA,CACrB,CAEJ","x_google_ignoreList":[0]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2026 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{P as
|
|
3
|
+
import{P as d,P as l}from"../chunks/PaymentOnAccount.js";import"@dropins/tools/preact-jsx-runtime.js";import"@dropins/tools/preact-compat.js";import"../chunks/components.js";import"@dropins/tools/lib.js";import"@dropins/tools/i18n.js";import"@dropins/tools/components.js";import"@dropins/tools/preact-hooks.js";import"../api.js";import"@dropins/tools/signals.js";import"@dropins/tools/event-bus.js";import"../fragments.js";import"@dropins/tools/fetch-graphql.js";export{d as PaymentOnAccount,l as default};
|
|
4
4
|
//# sourceMappingURL=PaymentOnAccount.js.map
|
package/containers/PlaceOrder.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2026 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{jsx as
|
|
3
|
+
import{jsx as E}from"@dropins/tools/preact-jsx-runtime.js";import{P as b}from"../chunks/components.js";import{a as z,m as R,E as q,d as C,s as O,g as N}from"../api.js";import{Slot as w}from"@dropins/tools/lib.js";import{events as n}from"@dropins/tools/event-bus.js";import{i as B}from"../chunks/ui.js";import{useState as g,useCallback as u,useEffect as d}from"@dropins/tools/preact-hooks.js";import{useText as M}from"@dropins/tools/i18n.js";import"@dropins/tools/components.js";import"@dropins/tools/preact-compat.js";import"@dropins/tools/signals.js";import"../fragments.js";import"@dropins/tools/fetch-graphql.js";const J=({disabled:y=!1,active:r=!0,handleValidation:i,handlePlaceOrder:m,slots:c,...I})=>{var h;const[P,f]=g(!1),[x,p]=g(!1),S=z.value,a=M({CheckoutUnexpectedError:"Checkout.ServerError.unexpected",placeOrderButton:"Checkout.PlaceOrder.button"}),l=u(e=>{const t=R(e),s=t===q.UNKNOWN_ERROR?a.CheckoutUnexpectedError:e.message;n.emit("checkout/error",{message:s,code:t})},[a]),U=u(async()=>{var e;try{if(i&&!await i())return;await m({cartId:O.cartId,quoteId:O.quoteId,code:((e=C("selectedPaymentMethod"))==null?void 0:e.code)??""})}catch(t){l(t)}},[i,m,l]),o=u(e=>{(!e||"isEmpty"in e&&e.isEmpty)&&p(!1)},[]);return d(()=>{if(r===!1)return;const e=n.on("cart/initialized",t=>{const s=(t==null?void 0:t.items)||[];p(s.some(k=>k.outOfStock||k.insufficientQuantity))},{eager:!0});return()=>{e==null||e.off()}},[r]),d(()=>{if(!r)return;const e=N();if(e){f(!0),o(e);return}const t=n.on("checkout/initialized",s=>{f(!0),o(s)},{eager:!0});return()=>{t==null||t.off()}},[r,o]),d(()=>{if(!r)return;const e=n.on("checkout/updated",t=>{o(t)},{eager:!1});return()=>{e==null||e.off()}},[r,o]),E(b,{...I,disabled:y||x||S||B.value,initialized:P,visible:r,onClick:U,children:E(w,{context:{code:((h=C("selectedPaymentMethod"))==null?void 0:h.code)??""},name:"Content",slot:c==null?void 0:c.Content,children:a.placeOrderButton})})};export{J as PlaceOrder,J as default};
|
|
4
4
|
//# sourceMappingURL=PlaceOrder.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PlaceOrder.js","sources":["/@dropins/storefront-checkout/src/containers/PlaceOrder/PlaceOrder.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { PlaceOrder as PlaceOrderComponent } from '@/checkout/components/PlaceOrder/PlaceOrder';\nimport { Cart, NegotiableQuote } from '@/checkout/data/models';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingUpdates,\n state,\n} from '@/checkout/lib';\nimport { isSetAddressRequestPending } from '@/checkout/store/ui';\nimport { ErrorCodes, mapErrorToCode } from '@/checkout/lib/errors';\nimport { Item as ItemModel } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Container, Slot, SlotProps } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useState } from 'preact/hooks';\n\nexport interface ContentSlotContext {\n code: string;\n}\n\nexport interface HandlePlaceOrderContext {\n code: string;\n cartId?: string | null;\n quoteId?: string | null;\n}\n\nexport interface PlaceOrderProps extends HTMLAttributes<HTMLDivElement> {\n disabled?: boolean;\n active?: boolean;\n handleValidation?: () => boolean | Promise<boolean>;\n handlePlaceOrder: (ctx: HandlePlaceOrderContext) => Promise<void>;\n slots?: {\n Content?: SlotProps<ContentSlotContext>;\n };\n}\n\nexport const PlaceOrder: Container<PlaceOrderProps> = ({\n disabled: disabledViaProp = false,\n active = true,\n handleValidation,\n handlePlaceOrder,\n slots,\n ...props\n}) => {\n const [isInitialized, setIsInitialized] = useState(false);\n const [hasOutOfStockItems, setHasOutOfStockItems] = useState(false);\n\n const hasQueuedUpdates = hasPendingUpdates.value;\n\n const translations = useText({\n CheckoutUnexpectedError: 'Checkout.ServerError.unexpected',\n placeOrderButton: 'Checkout.PlaceOrder.button',\n });\n\n const handlePlaceOrderError = useCallback(\n (error: any) => {\n const code = mapErrorToCode(error);\n\n const message =\n code === ErrorCodes.UNKNOWN_ERROR\n ? translations.CheckoutUnexpectedError\n : error.message;\n\n events.emit('checkout/error', { message, code });\n },\n [translations]\n );\n\n const handleClick = useCallback(async () => {\n try {\n if (handleValidation && !(await handleValidation())) return;\n\n await handlePlaceOrder({\n cartId: state.cartId,\n quoteId: state.quoteId,\n code: getValue('selectedPaymentMethod')?.code ?? '',\n });\n } catch (error: any) {\n handlePlaceOrderError(error);\n }\n }, [handleValidation, handlePlaceOrder, handlePlaceOrderError]);\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || ('isEmpty' in data && data.isEmpty);\n\n if (isEmptyCart) {\n setHasOutOfStockItems(false);\n }\n },\n []\n );\n\n useEffect(() => {\n if (active === false) return;\n\n const onCartData = events.on(\n 'cart/initialized',\n (data) => {\n const items = (data?.items || []) as ItemModel[];\n setHasOutOfStockItems(\n items.some((item) => item.outOfStock || item.insufficientQuantity)\n );\n },\n { eager: true }\n );\n\n return () => {\n onCartData?.off();\n };\n }, [active]);\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n setIsInitialized(true);\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n (data) => {\n setIsInitialized(true);\n handleCheckoutData(data);\n },\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n (data) => {\n handleCheckoutData(data);\n },\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n return (\n <PlaceOrderComponent\n {...props}\n disabled={\n disabledViaProp ||\n hasOutOfStockItems ||\n hasQueuedUpdates ||\n isSetAddressRequestPending.value\n }\n initialized={isInitialized}\n visible={active}\n onClick={handleClick}\n >\n <Slot\n context={{ code: getValue('selectedPaymentMethod')?.code ?? '' }}\n name=\"Content\"\n slot={slots?.Content}\n >\n {translations.placeOrderButton}\n </Slot>\n </PlaceOrderComponent>\n );\n};\n"],"names":["PlaceOrder","disabledViaProp","active","handleValidation","handlePlaceOrder","slots","props","isInitialized","setIsInitialized","useState","hasOutOfStockItems","setHasOutOfStockItems","hasQueuedUpdates","hasPendingUpdates","translations","useText","handlePlaceOrderError","useCallback","error","code","mapErrorToCode","message","ErrorCodes","events","handleClick","state","_a","getValue","handleCheckoutData","data","useEffect","onCartData","items","item","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","onCheckoutUpdated","jsx","PlaceOrderComponent","isSetAddressRequestPending","Slot"],"mappings":"
|
|
1
|
+
{"version":3,"file":"PlaceOrder.js","sources":["/@dropins/storefront-checkout/src/containers/PlaceOrder/PlaceOrder.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { PlaceOrder as PlaceOrderComponent } from '@/checkout/components/PlaceOrder/PlaceOrder';\nimport { Cart, NegotiableQuote } from '@/checkout/data/models';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingUpdates,\n state,\n} from '@/checkout/lib';\nimport { isSetAddressRequestPending } from '@/checkout/store/ui';\nimport { ErrorCodes, mapErrorToCode } from '@/checkout/lib/errors';\nimport { Item as ItemModel } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Container, Slot, SlotProps } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport { useCallback, useEffect, useState } from 'preact/hooks';\n\nexport interface ContentSlotContext {\n code: string;\n}\n\nexport interface HandlePlaceOrderContext {\n code: string;\n cartId?: string | null;\n quoteId?: string | null;\n}\n\nexport interface PlaceOrderProps extends HTMLAttributes<HTMLDivElement> {\n disabled?: boolean;\n active?: boolean;\n handleValidation?: () => boolean | Promise<boolean>;\n handlePlaceOrder: (ctx: HandlePlaceOrderContext) => Promise<void>;\n slots?: {\n Content?: SlotProps<ContentSlotContext>;\n };\n}\n\nexport const PlaceOrder: Container<PlaceOrderProps> = ({\n disabled: disabledViaProp = false,\n active = true,\n handleValidation,\n handlePlaceOrder,\n slots,\n ...props\n}) => {\n const [isInitialized, setIsInitialized] = useState(false);\n const [hasOutOfStockItems, setHasOutOfStockItems] = useState(false);\n\n const hasQueuedUpdates = hasPendingUpdates.value;\n\n const translations = useText({\n CheckoutUnexpectedError: 'Checkout.ServerError.unexpected',\n placeOrderButton: 'Checkout.PlaceOrder.button',\n });\n\n const handlePlaceOrderError = useCallback(\n (error: any) => {\n const code = mapErrorToCode(error);\n\n const message =\n code === ErrorCodes.UNKNOWN_ERROR\n ? translations.CheckoutUnexpectedError\n : error.message;\n\n events.emit('checkout/error', { message, code });\n },\n [translations]\n );\n\n const handleClick = useCallback(async () => {\n try {\n if (handleValidation && !(await handleValidation())) return;\n\n await handlePlaceOrder({\n cartId: state.cartId,\n quoteId: state.quoteId,\n code: getValue('selectedPaymentMethod')?.code ?? '',\n });\n } catch (error: any) {\n handlePlaceOrderError(error);\n }\n }, [handleValidation, handlePlaceOrder, handlePlaceOrderError]);\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || ('isEmpty' in data && data.isEmpty);\n\n if (isEmptyCart) {\n setHasOutOfStockItems(false);\n }\n },\n []\n );\n\n useEffect(() => {\n if (active === false) return;\n\n const onCartData = events.on(\n 'cart/initialized',\n (data) => {\n const items = (data?.items || []) as ItemModel[];\n setHasOutOfStockItems(\n items.some((item) => item.outOfStock || item.insufficientQuantity)\n );\n },\n { eager: true }\n );\n\n return () => {\n onCartData?.off();\n };\n }, [active]);\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n setIsInitialized(true);\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n (data) => {\n setIsInitialized(true);\n handleCheckoutData(data);\n },\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n (data) => {\n handleCheckoutData(data);\n },\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n return (\n <PlaceOrderComponent\n {...props}\n disabled={\n disabledViaProp ||\n hasOutOfStockItems ||\n hasQueuedUpdates ||\n isSetAddressRequestPending.value\n }\n initialized={isInitialized}\n visible={active}\n onClick={handleClick}\n >\n <Slot\n context={{ code: getValue('selectedPaymentMethod')?.code ?? '' }}\n name=\"Content\"\n slot={slots?.Content}\n >\n {translations.placeOrderButton}\n </Slot>\n </PlaceOrderComponent>\n );\n};\n"],"names":["PlaceOrder","disabledViaProp","active","handleValidation","handlePlaceOrder","slots","props","isInitialized","setIsInitialized","useState","hasOutOfStockItems","setHasOutOfStockItems","hasQueuedUpdates","hasPendingUpdates","translations","useText","handlePlaceOrderError","useCallback","error","code","mapErrorToCode","message","ErrorCodes","events","handleClick","state","_a","getValue","handleCheckoutData","data","useEffect","onCartData","items","item","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","onCheckoutUpdated","jsx","PlaceOrderComponent","isSetAddressRequestPending","Slot"],"mappings":"wmBAsDO,MAAMA,EAAyC,CAAC,CACrD,SAAUC,EAAkB,GAC5B,OAAAC,EAAS,GACT,iBAAAC,EACA,iBAAAC,EACA,MAAAC,EACA,GAAGC,CACL,IAAM,OACJ,KAAM,CAACC,EAAeC,CAAgB,EAAIC,EAAS,EAAK,EAClD,CAACC,EAAoBC,CAAqB,EAAIF,EAAS,EAAK,EAE5DG,EAAmBC,EAAkB,MAErCC,EAAeC,EAAQ,CAC3B,wBAAyB,kCACzB,iBAAkB,4BAAA,CACnB,EAEKC,EAAwBC,EAC3BC,GAAe,CACR,MAAAC,EAAOC,EAAeF,CAAK,EAE3BG,EACJF,IAASG,EAAW,cAChBR,EAAa,wBACbI,EAAM,QAEZK,EAAO,KAAK,iBAAkB,CAAE,QAAAF,EAAS,KAAAF,EAAM,CACjD,EACA,CAACL,CAAY,CACf,EAEMU,EAAcP,EAAY,SAAY,OACtC,GAAA,CACF,GAAId,GAAoB,CAAE,MAAMA,IAAqB,OAErD,MAAMC,EAAiB,CACrB,OAAQqB,EAAM,OACd,QAASA,EAAM,QACf,OAAMC,EAAAC,EAAS,uBAAuB,IAAhC,YAAAD,EAAmC,OAAQ,EAAA,CAClD,QACMR,EAAY,CACnBF,EAAsBE,CAAK,CAAA,CAE5B,EAAA,CAACf,EA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AAE,OAAMf,EAAAC,EAAS,uBAAuB,IAAhC,YAAAD,EAAmC,OAAQ,EAAG,EAC/D,KAAK,UACL,KAAMrB,GAAA,YAAAA,EAAO,QAEZ,SAAaS,EAAA,gBAAA,CAAA,CAChB,CACF,CAEJ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2026 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{P as
|
|
3
|
+
import{P as h,P as l}from"../chunks/PurchaseOrder.js";import"@dropins/tools/preact-jsx-runtime.js";import"../chunks/components.js";import"@dropins/tools/lib.js";import"@dropins/tools/i18n.js";import"@dropins/tools/components.js";import"@dropins/tools/preact-compat.js";import"@dropins/tools/preact-hooks.js";import"../api.js";import"@dropins/tools/signals.js";import"@dropins/tools/event-bus.js";import"../fragments.js";import"@dropins/tools/fetch-graphql.js";export{h as PurchaseOrder,l as default};
|
|
4
4
|
//# sourceMappingURL=PurchaseOrder.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2026 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{jsx as a}from"@dropins/tools/preact-jsx-runtime.js";import{a as
|
|
3
|
+
import{jsx as a}from"@dropins/tools/preact-jsx-runtime.js";import{s as c,a as p}from"../chunks/components.js";import"@dropins/tools/lib.js";import"@dropins/tools/components.js";import"@dropins/tools/preact-compat.js";import{useState as g,useRef as k,useEffect as f}from"@dropins/tools/preact-hooks.js";import{events as E}from"@dropins/tools/event-bus.js";import"@dropins/tools/i18n.js";import"../api.js";import"@dropins/tools/signals.js";import"../fragments.js";import"@dropins/tools/fetch-graphql.js";const A=({active:i=!0,onRetry:e,onServerError:t,autoScroll:l=!1})=>{const[r,u]=g(null),s=k(null),n=async()=>{e==null||e(r),u(null)};return f(()=>{const o=E.on("checkout/error",m=>{u(m||null),m&&t&&t(m.message)},{eager:!0});return()=>{o==null||o.off()}},[t]),f(()=>{!l||!r||!s.current||c(s.current)},[r,l]),!i||!r?null:a(p,{errorMessage:r.message,errorMessageRef:s,onClick:n})};export{A as ServerError,A as default};
|
|
4
4
|
//# sourceMappingURL=ServerError.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ServerError.js","sources":["/@dropins/storefront-checkout/src/containers/ServerError/ServerError.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { ServerError as ServerErrorComponent } from '@/checkout/components';\nimport { CheckoutError } from '@/checkout/data/models/checkout';\nimport { scrollToElement } from '@/checkout/lib';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useEffect, useRef, useState } from 'preact/hooks';\n\nexport interface ServerErrorProps {\n autoScroll?: boolean;\n onRetry?: (error: CheckoutError | null) => void;\n onServerError?: (error: string) => void;\n active?: boolean;\n}\n\nexport const ServerError: Container<ServerErrorProps> = ({\n active = true,\n onRetry,\n onServerError,\n autoScroll = false,\n}) => {\n const [error, setError] = useState<CheckoutError | null>(null);\n const errorMessageRef = useRef<HTMLParagraphElement>(null);\n\n const handleClick = async () => {\n onRetry?.(error);\n setError(null);\n };\n\n useEffect(() => {\n const subscription = events.on(\n 'checkout/error',\n (error: CheckoutError | undefined) => {\n setError(error || null);\n if (error && onServerError) {\n onServerError(error.message);\n }\n },\n { eager: true }\n );\n\n return () => {\n subscription?.off();\n };\n }, [onServerError]);\n\n useEffect(() => {\n if (!autoScroll || !error || !errorMessageRef.current) return;\n scrollToElement(errorMessageRef.current);\n }, [error, autoScroll]);\n\n if (!active || !error) return null;\n\n return (\n <ServerErrorComponent\n errorMessage={error.message}\n errorMessageRef={errorMessageRef}\n onClick={handleClick}\n />\n );\n};\n"],"names":["ServerError","active","onRetry","onServerError","autoScroll","error","setError","useState","errorMessageRef","useRef","handleClick","useEffect","subscription","events","scrollToElement","jsx","ServerErrorComponent"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ServerError.js","sources":["/@dropins/storefront-checkout/src/containers/ServerError/ServerError.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { ServerError as ServerErrorComponent } from '@/checkout/components';\nimport { CheckoutError } from '@/checkout/data/models/checkout';\nimport { scrollToElement } from '@/checkout/lib/utils/dom';\nimport { Container } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useEffect, useRef, useState } from 'preact/hooks';\n\nexport interface ServerErrorProps {\n autoScroll?: boolean;\n onRetry?: (error: CheckoutError | null) => void;\n onServerError?: (error: string) => void;\n active?: boolean;\n}\n\nexport const ServerError: Container<ServerErrorProps> = ({\n active = true,\n onRetry,\n onServerError,\n autoScroll = false,\n}) => {\n const [error, setError] = useState<CheckoutError | null>(null);\n const errorMessageRef = useRef<HTMLParagraphElement>(null);\n\n const handleClick = async () => {\n onRetry?.(error);\n setError(null);\n };\n\n useEffect(() => {\n const subscription = events.on(\n 'checkout/error',\n (error: CheckoutError | undefined) => {\n setError(error || null);\n if (error && onServerError) {\n onServerError(error.message);\n }\n },\n { eager: true }\n );\n\n return () => {\n subscription?.off();\n };\n }, [onServerError]);\n\n useEffect(() => {\n if (!autoScroll || !error || !errorMessageRef.current) return;\n scrollToElement(errorMessageRef.current);\n }, [error, autoScroll]);\n\n if (!active || !error) return null;\n\n return (\n <ServerErrorComponent\n errorMessage={error.message}\n errorMessageRef={errorMessageRef}\n onClick={handleClick}\n />\n );\n};\n"],"names":["ServerError","active","onRetry","onServerError","autoScroll","error","setError","useState","errorMessageRef","useRef","handleClick","useEffect","subscription","events","scrollToElement","jsx","ServerErrorComponent"],"mappings":"sfA+BO,MAAMA,EAA2C,CAAC,CACvD,OAAAC,EAAS,GACT,QAAAC,EACA,cAAAC,EACA,WAAAC,EAAa,EACf,IAAM,CACJ,KAAM,CAACC,EAAOC,CAAQ,EAAIC,EAA+B,IAAI,EACvDC,EAAkBC,EAA6B,IAAI,EAEnDC,EAAc,SAAY,CAC9BR,GAAA,MAAAA,EAAUG,GACVC,EAAS,IAAI,CACf,EAwBA,OAtBAK,EAAU,IAAM,CACd,MAAMC,EAAeC,EAAO,GAC1B,iBACCR,GAAqC,CACpCC,EAASD,GAAS,IAAI,EAClBA,GAASF,GACXA,EAAcE,EAAM,OAAO,CAE/B,EACA,CAAE,MAAO,EAAK,CAChB,EAEA,MAAO,IAAM,CACXO,GAAA,MAAAA,EAAc,KAChB,CAAA,EACC,CAACT,CAAa,CAAC,EAElBQ,EAAU,IAAM,CACV,CAACP,GAAc,CAACC,GAAS,CAACG,EAAgB,SAC9CM,EAAgBN,EAAgB,OAAO,CAAA,EACtC,CAACH,EAAOD,CAAU,CAAC,EAElB,CAACH,GAAU,CAACI,EAAc,KAG5BU,EAACC,EAAA,CACC,aAAcX,EAAM,QACpB,gBAAAG,EACA,QAASE,CAAA,CACX,CAEJ"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
/*! Copyright 2026 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{jsx as
|
|
3
|
+
import{jsx as T}from"@dropins/tools/preact-jsx-runtime.js";import{a as ie,b as ne,config as L,n as re,c as V,setShippingMethodsOnCart as oe,d as y,i as $,g as se,t as ue}from"../api.js";import{Slot as ce}from"@dropins/tools/lib.js";import{events as g}from"@dropins/tools/event-bus.js";import{S as le}from"../chunks/components.js";import"@dropins/tools/components.js";import{useState as C,useRef as ae,useCallback as u,useMemo as F,useEffect as I}from"@dropins/tools/preact-hooks.js";import{useText as pe}from"@dropins/tools/i18n.js";import"@dropins/tools/signals.js";import"../fragments.js";import"@dropins/tools/fetch-graphql.js";import"@dropins/tools/preact-compat.js";function D(r,i){return r?i.some(S=>P(S,r)):!1}function P(r,i){return!r||!i||r.amount.value!==i.amount.value?!1:r.code===i.code&&r.carrier.code===i.carrier.code}function fe(r){const i=g.lastPayload("shipping/estimate");i&&g.emit("shipping/estimate",{...i,shippingMethod:ue(r)})}const be=({UIComponentType:r="RadioButton",active:i=!0,autoSync:S=!0,displayTitle:x=!0,initialData:de,slots:s,onCartSyncError:p,onSelectionChange:v,...G})=>{const[H,k]=C(null),[J,K]=C(!1),[A,U]=C(),[N,Q]=C(null),O=ae(null),W=ie.value,X=ne.value,{cartSyncError:w,defaultTitle:z}=pe({cartSyncError:"Checkout.ShippingMethods.cartSyncError",defaultTitle:"Checkout.ShippingMethods.title"}),E=u(e=>{if(!e||e.length===0)return[];const{shipping:t}=L.getConfig();return t!=null&&t.filterOptions?e.filter(t.filterOptions):e},[]),B=u(e=>{if(e.length===0)return null;const{defaults:t}=L.getConfig();return t.selectedShippingMethod(e)},[]),Y=F(()=>E(A),[A,E]),Z=u(()=>{k(null)},[]),o=u(e=>{k(null),Q(t=>P(t,e)?t:(re({selectedShippingMethod:e}),e))},[]),f=u(async(e,t)=>{if(!S||!V())return;const n={carrierCode:e.carrier.code,methodCode:e.code};oe([n]).catch(c=>{o(t??null),p==null||p({method:e,error:c}),p||k(w)})},[S,o,p,w]),_=u(async e=>{const t=y("selectedShippingMethod");o(e),v==null||v(e),V()||fe(e),await f(e,t)},[v,o,f]),d=u(e=>{var q;const t=!e||e.isEmpty,n=!!(e!=null&&e.isVirtual);if(t||n){K(n),o(null),U([]);return}const c=(q=e.shippingAddresses)==null?void 0:q[0];if(!c)return;const h=c.availableShippingMethods??[];$()&&!O.current&&(O.current=h);const j=$()&&O.current?O.current:h;U(j);const m=E(j);if(m.length===0){o(null);return}const l=c.selectedShippingMethod??null,a=y("selectedShippingMethod"),b=D(a,m),te=P(a,l);if(a&&b&&!te){f(a,l);return}if((!a||!b)&&l&&D(l,m)){o(l);return}if((!a||!b)&&(!l||!D(l,m))){const M=B(m);o(M),M&&f(M)}},[E,B,o,f]),R=u(e=>{if(e===void 0)return;const{shippingMethod:t,availableShippingMethods:n}=e,c=(n==null?void 0:n.find(h=>h.code===(t==null?void 0:t.methodCode)&&h.carrier.code===(t==null?void 0:t.carrierCode)))??null;U(n),o(c)},[o]);I(()=>{if(!i)return;const e=se();if(e){const n=y("selectedShippingMethod");n&&Q(n),d(e);return}const t=g.on("checkout/initialized",d,{eager:!0});return()=>{t==null||t.off()}},[i,d]),I(()=>{if(!i)return;const e=g.on("checkout/updated",d,{eager:!1});return()=>{e==null||e.off()}},[i,d]),I(()=>{if(!i||V())return;const e=g.on("shipping/estimate",R,{eager:!0});return()=>{e==null||e.off()}},[i,R]);const ee=F(()=>{if(x)return T(ce,{name:"checkout-shipping-methods-title",slot:s==null?void 0:s.Title,children:T("h3",{children:z})})},[x,s==null?void 0:s.Title,z]);return T(le,{...G,UIComponentType:r,busy:W||X,error:H,initialized:A!==void 0,options:Y,selection:N,shippingMethodItemSlot:s==null?void 0:s.ShippingMethodItem,title:ee,visible:i&&!J,onDismissError:Z,onSelectionChange:_})};export{be as ShippingMethods,be as default,fe as emitShippingEstimateEvent};
|
|
4
4
|
//# sourceMappingURL=ShippingMethods.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShippingMethods.js","sources":["/@dropins/storefront-checkout/src/containers/ShippingMethods/ShippingMethods.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { config, setShippingMethods } from '@/checkout/api';\nimport {\n ShippingMethodItemSlot,\n ShippingMethods as ShippingMethodsComponent,\n} from '@/checkout/components/ShippingMethods';\nimport {\n Cart,\n NegotiableQuote,\n ShippingEstimate,\n ShippingMethod,\n ShippingMethodInput,\n} from '@/checkout/data/models';\nimport { transformShippingEstimateShippingMethod } from '@/checkout/data/transforms';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingShippingEstimate,\n hasPendingUpdates,\n hasShippingAddress,\n isQuoteCheckout,\n notifyValues,\n} from '@/checkout/lib';\nimport { Filter, TitleProps, UIComponentType } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Container, Slot } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'preact/hooks';\n\n/**\n * Context provided to the ShippingMethodItem slot.\n * Used for complete UI replacement via replaceWith.\n */\nexport interface ShippingMethodItemContext {\n method: ShippingMethod;\n isSelected: boolean;\n onSelect: () => void;\n}\n\ninterface CartSyncError {\n method: ShippingMethod;\n error: Error;\n}\n\nexport type ShippingOptionsFilter = Filter<ShippingMethod>;\n\nexport interface ShippingMethodsProps\n extends HTMLAttributes<HTMLDivElement>,\n TitleProps {\n UIComponentType?: UIComponentType;\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onSelectionChange?: (method: ShippingMethod) => void;\n slots?: {\n ShippingMethodItem?: ShippingMethodItemSlot;\n } & TitleProps['slots'];\n}\n\nfunction isMethodAvailable(\n method: ShippingMethod | null,\n options: ShippingMethod[]\n) {\n if (!method) return false;\n return options.some((option) => isEqual(option, method));\n}\n\nfunction isEqual(a: ShippingMethod | null, b: ShippingMethod | null) {\n if (!a || !b) return false;\n if (a.amount.value !== b.amount.value) return false;\n return a.code === b.code && a.carrier.code === b.carrier.code;\n}\n\nexport function emitShippingEstimateEvent(selection: ShippingMethod) {\n const shippingEstimatedEvent = events.lastPayload('shipping/estimate');\n\n if (!shippingEstimatedEvent) return;\n\n events.emit('shipping/estimate', {\n ...shippingEstimatedEvent,\n shippingMethod: transformShippingEstimateShippingMethod(selection),\n });\n}\n\nexport const ShippingMethods: Container<ShippingMethodsProps> = ({\n UIComponentType = 'RadioButton',\n active = true,\n autoSync = true,\n displayTitle = true,\n initialData,\n slots,\n onCartSyncError,\n onSelectionChange,\n ...props\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isVirtual, setIsVirtual] = useState(false);\n const [options, setOptions] = useState<ShippingMethod[] | undefined>();\n const [selection, setSelection] = useState<ShippingMethod | null>(null);\n const initialQuoteOptions = useRef<ShippingMethod[] | null>(null);\n\n const hasQueuedUpdates = hasPendingUpdates.value;\n const hasPendingEstimations = hasPendingShippingEstimate.value;\n\n const { cartSyncError, defaultTitle } = useText({\n cartSyncError: 'Checkout.ShippingMethods.cartSyncError',\n defaultTitle: 'Checkout.ShippingMethods.title',\n });\n\n const filterOptions = useCallback(\n (shippingMethods: ShippingMethod[] | undefined) => {\n if (!shippingMethods || shippingMethods.length === 0) return [];\n const { shipping } = config.getConfig();\n if (!shipping?.filterOptions) return shippingMethods;\n return shippingMethods.filter(shipping.filterOptions);\n },\n []\n );\n\n const preselectOption = useCallback((shippingMethods: ShippingMethod[]) => {\n if (shippingMethods.length === 0) return null;\n const { defaults } = config.getConfig();\n return defaults!.selectedShippingMethod!(shippingMethods);\n }, []);\n\n const filteredOptions = useMemo(() => {\n return filterOptions(options);\n }, [options, filterOptions]);\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const setUserSelection = useCallback(\n (shippingMethod: ShippingMethod | null) => {\n setError(null);\n setSelection((prev) => {\n if (isEqual(prev, shippingMethod)) return prev;\n notifyValues({ selectedShippingMethod: shippingMethod });\n return shippingMethod;\n });\n },\n []\n );\n\n const setUserSelectionOnCart = useCallback(\n async (selection: ShippingMethod, fallback?: ShippingMethod | null) => {\n if (!autoSync || !hasShippingAddress()) return;\n\n const shippingMethodInput: ShippingMethodInput = {\n carrierCode: selection.carrier.code,\n methodCode: selection.code,\n };\n\n setShippingMethods([shippingMethodInput]).catch((error) => {\n setUserSelection(fallback ?? null);\n onCartSyncError?.({ method: selection, error });\n\n if (!onCartSyncError) {\n setError(cartSyncError);\n }\n });\n },\n [autoSync, setUserSelection, onCartSyncError, cartSyncError]\n );\n\n const handleSelectionChange = useCallback(\n async (selection: ShippingMethod) => {\n const prevSelection = getValue('selectedShippingMethod');\n\n setUserSelection(selection);\n onSelectionChange?.(selection);\n\n if (!hasShippingAddress()) {\n emitShippingEstimateEvent(selection);\n }\n\n await setUserSelectionOnCart(selection, prevSelection);\n },\n [onSelectionChange, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || data.isEmpty;\n const isVirtualCart = Boolean(data?.isVirtual);\n\n if (isEmptyCart || isVirtualCart) {\n setIsVirtual(isVirtualCart);\n setUserSelection(null);\n setOptions([]);\n return;\n }\n\n const primaryAddress = data!.shippingAddresses?.[0];\n\n // If there is no primary address, options are handled by the shipping estimation\n if (!primaryAddress) return;\n\n const availableOptions = primaryAddress.availableShippingMethods ?? [];\n\n // For quote checkouts, preserve initial shipping methods. After the first method is selected,\n // the backend only returns that selected method, preventing users from changing to other\n // options. We maintain all initial options to match Luma's behavior.\n if (isQuoteCheckout() && !initialQuoteOptions.current) {\n initialQuoteOptions.current = availableOptions;\n }\n\n const effectiveOptions =\n isQuoteCheckout() && initialQuoteOptions.current\n ? initialQuoteOptions.current\n : availableOptions;\n\n setOptions(effectiveOptions);\n const filteredOptions = filterOptions(effectiveOptions);\n\n // If there are no filtered options, reset the user selection\n if (filteredOptions.length === 0) {\n setUserSelection(null);\n return;\n }\n\n const cartSelection = primaryAddress.selectedShippingMethod ?? null;\n\n const userSelection = getValue('selectedShippingMethod');\n const isAvailable = isMethodAvailable(userSelection, filteredOptions);\n const haveSameSelection = isEqual(userSelection, cartSelection);\n\n // Handle user selection that's available but different from cart\n if (userSelection && isAvailable && !haveSameSelection) {\n setUserSelectionOnCart(userSelection, cartSelection);\n return;\n }\n\n // If no user selection or not available, decide what to do based on cart and filtered options\n if ((!userSelection || !isAvailable) && cartSelection) {\n // Check if cart selection is still available after filtering\n const isCartSelectionAvailable = isMethodAvailable(\n cartSelection,\n filteredOptions\n );\n if (isCartSelectionAvailable) {\n setUserSelection(cartSelection);\n return;\n }\n }\n\n if (\n (!userSelection || !isAvailable) &&\n (!cartSelection || !isMethodAvailable(cartSelection, filteredOptions))\n ) {\n const newSelection = preselectOption(filteredOptions);\n setUserSelection(newSelection);\n if (newSelection) setUserSelectionOnCart(newSelection);\n }\n },\n [filterOptions, preselectOption, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleShippingEstimate = useCallback(\n (estimation: ShippingEstimate | undefined) => {\n if (estimation === undefined) return;\n\n const { shippingMethod, availableShippingMethods } = estimation;\n\n const selectedShippingMethod =\n availableShippingMethods?.find(\n (method) =>\n method.code === shippingMethod?.methodCode &&\n method.carrier.code === shippingMethod?.carrierCode\n ) ?? null;\n\n setOptions(availableShippingMethods);\n setUserSelection(selectedShippingMethod);\n },\n [setUserSelection]\n );\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userSelection = getValue('selectedShippingMethod');\n if (userSelection) {\n setSelection(userSelection);\n }\n\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n handleCheckoutData,\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active || hasShippingAddress()) return;\n\n const onShippingEstimate = events.on(\n 'shipping/estimate',\n handleShippingEstimate,\n { eager: true }\n );\n\n return () => {\n onShippingEstimate?.off();\n };\n }, [active, handleShippingEstimate]);\n\n const titleContent = useMemo(() => {\n if (!displayTitle) return undefined;\n\n return (\n <Slot name=\"checkout-shipping-methods-title\" slot={slots?.Title}>\n <h3>{defaultTitle}</h3>\n </Slot>\n );\n }, [displayTitle, slots?.Title, defaultTitle]);\n\n return (\n <ShippingMethodsComponent\n {...props}\n UIComponentType={UIComponentType}\n busy={hasQueuedUpdates || hasPendingEstimations}\n error={error}\n initialized={options !== undefined}\n options={filteredOptions}\n selection={selection}\n shippingMethodItemSlot={slots?.ShippingMethodItem}\n title={titleContent}\n visible={active && !isVirtual}\n onDismissError={handleDismissError}\n onSelectionChange={handleSelectionChange}\n />\n );\n};\n"],"names":["isMethodAvailable","method","options","option","isEqual","a","b","emitShippingEstimateEvent","selection","shippingEstimatedEvent","events","transformShippingEstimateShippingMethod","ShippingMethods","UIComponentType","active","autoSync","displayTitle","initialData","slots","onCartSyncError","onSelectionChange","props","error","setError","useState","isVirtual","setIsVirtual","setOptions","setSelection","initialQuoteOptions","useRef","hasQueuedUpdates","hasPendingUpdates","hasPendingEstimations","hasPendingShippingEstimate","cartSyncError","defaultTitle","useText","filterOptions","useCallback","shippingMethods","shipping","config","preselectOption","defaults","filteredOptions","useMemo","handleDismissError","setUserSelection","shippingMethod","prev","notifyValues","setUserSelectionOnCart","fallback","hasShippingAddress","shippingMethodInput","setShippingMethods","handleSelectionChange","prevSelection","getValue","handleCheckoutData","data","isEmptyCart","isVirtualCart","primaryAddress","_a","availableOptions","isQuoteCheckout","effectiveOptions","cartSelection","userSelection","isAvailable","haveSameSelection","newSelection","handleShippingEstimate","estimation","availableShippingMethods","selectedShippingMethod","useEffect","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","onCheckoutUpdated","onShippingEstimate","titleContent","jsx","Slot","ShippingMethodsComponent"],"mappings":"6oBAkFA,SAASA,EACPC,EACAC,EACA,CACI,OAACD,EACEC,EAAQ,KAAMC,GAAWC,EAAQD,EAAQF,CAAM,CAAC,EADnC,EAEtB,CAEA,SAASG,EAAQC,EAA0BC,EAA0B,CAEnE,MADI,CAACD,GAAK,CAACC,GACPD,EAAE,OAAO,QAAUC,EAAE,OAAO,MAAc,GACvCD,EAAE,OAASC,EAAE,MAAQD,EAAE,QAAQ,OAASC,EAAE,QAAQ,IAC3D,CAEO,SAASC,GAA0BC,EAA2B,CAC7D,MAAAC,EAAyBC,EAAO,YAAY,mBAAmB,EAEhED,GAELC,EAAO,KAAK,oBAAqB,CAC/B,GAAGD,EACH,eAAgBE,GAAwCH,CAAS,CAAA,CAClE,CACH,CAEO,MAAMI,GAAmD,CAAC,CAC/D,gBAAAC,EAAkB,cAClB,OAAAC,EAAS,GACT,SAAAC,EAAW,GACX,aAAAC,EAAe,GACf,YAAAC,GACA,MAAAC,EACA,gBAAAC,EACA,kBAAAC,EACA,GAAGC,CACL,IAAM,CACJ,KAAM,CAACC,EAAOC,CAAQ,EAAIC,EAAwB,IAAI,EAChD,CAACC,EAAWC,CAAY,EAAIF,EAAS,EAAK,EAC1C,CAACtB,EAASyB,CAAU,EAAIH,EAAuC,EAC/D,CAAChB,EAAWoB,CAAY,EAAIJ,EAAgC,IAAI,EAChEK,EAAsBC,GAAgC,IAAI,EAE1DC,EAAmBC,GAAkB,MACrCC,EAAwBC,GAA2B,MAEnD,CAAE,cAAAC,EAAe,aAAAC,CAAa,EAAIC,GAAQ,CAC9C,cAAe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sB,CAAC,EAE7B,MAAAU,GAAetC,EAAQ,IAAM,CAC7B,GAAC9B,EAGH,OAAAqE,EAACC,GAAK,CAAA,KAAK,kCAAkC,KAAMpE,GAAA,YAAAA,EAAO,MACxD,SAAAmE,EAAC,KAAI,CAAA,SAAAjD,CAAa,CAAA,EACpB,GAED,CAACpB,EAAcE,GAAA,YAAAA,EAAO,MAAOkB,CAAY,CAAC,EAG3C,OAAAiD,EAACE,GAAA,CACE,GAAGlE,EACJ,gBAAiBR,EACjB,KAAMkB,GAAoBE,EAC1B,MAAAX,EACA,YAAapB,IAAY,OACzB,QAAS2C,EACT,UAAArC,EACA,uBAAwBU,GAAA,YAAAA,EAAO,mBAC/B,MAAOkE,GACP,QAAStE,GAAU,CAACW,EACpB,eAAgBsB,EAChB,kBAAmBU,CAAA,CACrB,CAEJ"}
|
|
1
|
+
{"version":3,"file":"ShippingMethods.js","sources":["/@dropins/storefront-checkout/src/containers/ShippingMethods/ShippingMethods.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { config, setShippingMethods } from '@/checkout/api';\nimport {\n ShippingMethodItemSlot,\n ShippingMethods as ShippingMethodsComponent,\n} from '@/checkout/components/ShippingMethods';\nimport {\n Cart,\n NegotiableQuote,\n ShippingEstimate,\n ShippingMethod,\n ShippingMethodInput,\n} from '@/checkout/data/models';\nimport { transformShippingEstimateShippingMethod } from '@/checkout/data/transforms';\nimport {\n getLatestCheckoutUpdate,\n getValue,\n hasPendingShippingEstimate,\n hasPendingUpdates,\n hasShippingAddress,\n isQuoteCheckout,\n notifyValues,\n} from '@/checkout/lib';\nimport { Filter, TitleProps, UIComponentType } from '@/checkout/types';\nimport { useText } from '@adobe-commerce/elsie/i18n';\nimport { Container, Slot } from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { HTMLAttributes } from 'preact/compat';\nimport {\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'preact/hooks';\n\n/**\n * Context provided to the ShippingMethodItem slot.\n * Used for complete UI replacement via replaceWith.\n */\nexport interface ShippingMethodItemContext {\n method: ShippingMethod;\n isSelected: boolean;\n onSelect: () => void;\n}\n\ninterface CartSyncError {\n method: ShippingMethod;\n error: Error;\n}\n\nexport type ShippingOptionsFilter = Filter<ShippingMethod>;\n\nexport interface ShippingMethodsProps\n extends HTMLAttributes<HTMLDivElement>,\n TitleProps {\n UIComponentType?: UIComponentType;\n active?: boolean;\n autoSync?: boolean;\n onCartSyncError?: (error: CartSyncError) => void;\n onSelectionChange?: (method: ShippingMethod) => void;\n slots?: {\n ShippingMethodItem?: ShippingMethodItemSlot;\n } & TitleProps['slots'];\n}\n\nfunction isMethodAvailable(\n method: ShippingMethod | null,\n options: ShippingMethod[]\n) {\n if (!method) return false;\n return options.some((option) => isEqual(option, method));\n}\n\nfunction isEqual(a: ShippingMethod | null, b: ShippingMethod | null) {\n if (!a || !b) return false;\n if (a.amount.value !== b.amount.value) return false;\n return a.code === b.code && a.carrier.code === b.carrier.code;\n}\n\nexport function emitShippingEstimateEvent(selection: ShippingMethod) {\n const shippingEstimatedEvent = events.lastPayload('shipping/estimate');\n\n if (!shippingEstimatedEvent) return;\n\n events.emit('shipping/estimate', {\n ...shippingEstimatedEvent,\n shippingMethod: transformShippingEstimateShippingMethod(selection),\n });\n}\n\nexport const ShippingMethods: Container<ShippingMethodsProps> = ({\n UIComponentType = 'RadioButton',\n active = true,\n autoSync = true,\n displayTitle = true,\n initialData,\n slots,\n onCartSyncError,\n onSelectionChange,\n ...props\n}) => {\n const [error, setError] = useState<string | null>(null);\n const [isVirtual, setIsVirtual] = useState(false);\n const [options, setOptions] = useState<ShippingMethod[] | undefined>();\n const [selection, setSelection] = useState<ShippingMethod | null>(null);\n const initialQuoteOptions = useRef<ShippingMethod[] | null>(null);\n\n const hasQueuedUpdates = hasPendingUpdates.value;\n const hasPendingEstimations = hasPendingShippingEstimate.value;\n\n const { cartSyncError, defaultTitle } = useText({\n cartSyncError: 'Checkout.ShippingMethods.cartSyncError',\n defaultTitle: 'Checkout.ShippingMethods.title',\n });\n\n const filterOptions = useCallback(\n (shippingMethods: ShippingMethod[] | undefined) => {\n if (!shippingMethods || shippingMethods.length === 0) return [];\n const { shipping } = config.getConfig();\n if (!shipping?.filterOptions) return shippingMethods;\n return shippingMethods.filter(shipping.filterOptions);\n },\n []\n );\n\n const preselectOption = useCallback((shippingMethods: ShippingMethod[]) => {\n if (shippingMethods.length === 0) return null;\n const { defaults } = config.getConfig();\n return defaults!.selectedShippingMethod!(shippingMethods);\n }, []);\n\n const filteredOptions = useMemo(() => {\n return filterOptions(options);\n }, [options, filterOptions]);\n\n const handleDismissError = useCallback(() => {\n setError(null);\n }, []);\n\n const setUserSelection = useCallback(\n (shippingMethod: ShippingMethod | null) => {\n setError(null);\n setSelection((prev) => {\n if (isEqual(prev, shippingMethod)) return prev;\n notifyValues({ selectedShippingMethod: shippingMethod });\n return shippingMethod;\n });\n },\n []\n );\n\n const setUserSelectionOnCart = useCallback(\n async (selection: ShippingMethod, fallback?: ShippingMethod | null) => {\n if (!autoSync || !hasShippingAddress()) return;\n\n const shippingMethodInput: ShippingMethodInput = {\n carrierCode: selection.carrier.code,\n methodCode: selection.code,\n };\n\n setShippingMethods([shippingMethodInput]).catch((error) => {\n setUserSelection(fallback ?? null);\n onCartSyncError?.({ method: selection, error });\n\n if (!onCartSyncError) {\n setError(cartSyncError);\n }\n });\n },\n [autoSync, setUserSelection, onCartSyncError, cartSyncError]\n );\n\n const handleSelectionChange = useCallback(\n async (selection: ShippingMethod) => {\n const prevSelection = getValue('selectedShippingMethod');\n\n setUserSelection(selection);\n onSelectionChange?.(selection);\n\n if (!hasShippingAddress()) {\n emitShippingEstimateEvent(selection);\n }\n\n await setUserSelectionOnCart(selection, prevSelection);\n },\n [onSelectionChange, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleCheckoutData = useCallback(\n (data: Cart | NegotiableQuote | null) => {\n const isEmptyCart = !data || data.isEmpty;\n const isVirtualCart = Boolean(data?.isVirtual);\n\n if (isEmptyCart || isVirtualCart) {\n setIsVirtual(isVirtualCart);\n setUserSelection(null);\n setOptions([]);\n return;\n }\n\n const primaryAddress = data!.shippingAddresses?.[0];\n\n // If there is no primary address, options are handled by the shipping estimation\n if (!primaryAddress) return;\n\n const availableOptions = primaryAddress.availableShippingMethods ?? [];\n\n // For quote checkouts, preserve initial shipping methods. After the first method is selected,\n // the backend only returns that selected method, preventing users from changing to other\n // options. We maintain all initial options to match Luma's behavior.\n if (isQuoteCheckout() && !initialQuoteOptions.current) {\n initialQuoteOptions.current = availableOptions;\n }\n\n const effectiveOptions =\n isQuoteCheckout() && initialQuoteOptions.current\n ? initialQuoteOptions.current\n : availableOptions;\n\n setOptions(effectiveOptions);\n const filteredOptions = filterOptions(effectiveOptions);\n\n // If there are no filtered options, reset the user selection\n if (filteredOptions.length === 0) {\n setUserSelection(null);\n return;\n }\n\n const cartSelection = primaryAddress.selectedShippingMethod ?? null;\n\n const userSelection = getValue('selectedShippingMethod');\n const isAvailable = isMethodAvailable(userSelection, filteredOptions);\n const haveSameSelection = isEqual(userSelection, cartSelection);\n\n // Handle user selection that's available but different from cart\n if (userSelection && isAvailable && !haveSameSelection) {\n setUserSelectionOnCart(userSelection, cartSelection);\n return;\n }\n\n // If no user selection or not available, decide what to do based on cart and filtered options\n if ((!userSelection || !isAvailable) && cartSelection) {\n // Check if cart selection is still available after filtering\n const isCartSelectionAvailable = isMethodAvailable(\n cartSelection,\n filteredOptions\n );\n if (isCartSelectionAvailable) {\n setUserSelection(cartSelection);\n return;\n }\n }\n\n if (\n (!userSelection || !isAvailable) &&\n (!cartSelection || !isMethodAvailable(cartSelection, filteredOptions))\n ) {\n const newSelection = preselectOption(filteredOptions);\n setUserSelection(newSelection);\n if (newSelection) setUserSelectionOnCart(newSelection);\n }\n },\n [filterOptions, preselectOption, setUserSelection, setUserSelectionOnCart]\n );\n\n const handleShippingEstimate = useCallback(\n (estimation: ShippingEstimate | undefined) => {\n if (estimation === undefined) return;\n\n const { shippingMethod, availableShippingMethods } = estimation;\n\n const selectedShippingMethod =\n availableShippingMethods?.find(\n (method) =>\n method.code === shippingMethod?.methodCode &&\n method.carrier.code === shippingMethod?.carrierCode\n ) ?? null;\n\n setOptions(availableShippingMethods);\n setUserSelection(selectedShippingMethod);\n },\n [setUserSelection]\n );\n\n useEffect(() => {\n if (!active) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n // When component becomes active, restore key state so handleCheckoutData can work properly\n const userSelection = getValue('selectedShippingMethod');\n if (userSelection) {\n setSelection(userSelection);\n }\n\n handleCheckoutData(pastUpdate);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n handleCheckoutData,\n { eager: true }\n );\n\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active) return;\n\n const onCheckoutUpdated = events.on(\n 'checkout/updated',\n handleCheckoutData,\n { eager: false }\n );\n\n return () => {\n onCheckoutUpdated?.off();\n };\n }, [active, handleCheckoutData]);\n\n useEffect(() => {\n if (!active || hasShippingAddress()) return;\n\n const onShippingEstimate = events.on(\n 'shipping/estimate',\n handleShippingEstimate,\n { eager: true }\n );\n\n return () => {\n onShippingEstimate?.off();\n };\n }, [active, handleShippingEstimate]);\n\n const titleContent = useMemo(() => {\n if (!displayTitle) return undefined;\n\n return (\n <Slot name=\"checkout-shipping-methods-title\" slot={slots?.Title}>\n <h3>{defaultTitle}</h3>\n </Slot>\n );\n }, [displayTitle, slots?.Title, defaultTitle]);\n\n return (\n <ShippingMethodsComponent\n {...props}\n UIComponentType={UIComponentType}\n busy={hasQueuedUpdates || hasPendingEstimations}\n error={error}\n initialized={options !== undefined}\n options={filteredOptions}\n selection={selection}\n shippingMethodItemSlot={slots?.ShippingMethodItem}\n title={titleContent}\n visible={active && !isVirtual}\n onDismissError={handleDismissError}\n onSelectionChange={handleSelectionChange}\n />\n );\n};\n"],"names":["isMethodAvailable","method","options","option","isEqual","a","b","emitShippingEstimateEvent","selection","shippingEstimatedEvent","events","transformShippingEstimateShippingMethod","ShippingMethods","UIComponentType","active","autoSync","displayTitle","initialData","slots","onCartSyncError","onSelectionChange","props","error","setError","useState","isVirtual","setIsVirtual","setOptions","setSelection","initialQuoteOptions","useRef","hasQueuedUpdates","hasPendingUpdates","hasPendingEstimations","hasPendingShippingEstimate","cartSyncError","defaultTitle","useText","filterOptions","useCallback","shippingMethods","shipping","config","preselectOption","defaults","filteredOptions","useMemo","handleDismissError","setUserSelection","shippingMethod","prev","notifyValues","setUserSelectionOnCart","fallback","hasShippingAddress","shippingMethodInput","setShippingMethods","handleSelectionChange","prevSelection","getValue","handleCheckoutData","data","isEmptyCart","isVirtualCart","primaryAddress","_a","availableOptions","isQuoteCheckout","effectiveOptions","cartSelection","userSelection","isAvailable","haveSameSelection","newSelection","handleShippingEstimate","estimation","availableShippingMethods","selectedShippingMethod","useEffect","pastUpdate","getLatestCheckoutUpdate","onCheckoutInit","onCheckoutUpdated","onShippingEstimate","titleContent","jsx","Slot","ShippingMethodsComponent"],"mappings":"+pBAkFA,SAASA,EACPC,EACAC,EACA,CACI,OAACD,EACEC,EAAQ,KAAMC,GAAWC,EAAQD,EAAQF,CAAM,CAAC,EADnC,EAEtB,CAEA,SAASG,EAAQC,EAA0BC,EAA0B,CAEnE,MADI,CAACD,GAAK,CAACC,GACPD,EAAE,OAAO,QAAUC,EAAE,OAAO,MAAc,GACvCD,EAAE,OAASC,EAAE,MAAQD,EAAE,QAAQ,OAASC,EAAE,QAAQ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
1
1
|
/*! Copyright 2026 Adobe
|
|
2
2
|
All Rights Reserved. */
|
|
3
|
-
import{jsx as t}from"@dropins/tools/preact-jsx-runtime.js";import{T as b,M as z}from"../chunks/components.js";import{Slot as U}from"@dropins/tools/lib.js";import{Checkbox as v}from"@dropins/tools/components.js";import
|
|
3
|
+
import{jsx as t}from"@dropins/tools/preact-jsx-runtime.js";import{T as b,M as z}from"../chunks/components.js";import{Slot as U}from"@dropins/tools/lib.js";import{Checkbox as v}from"@dropins/tools/components.js";import"@dropins/tools/preact-compat.js";import{useState as l,useEffect as E}from"@dropins/tools/preact-hooks.js";import{s as _,g as P,A as S}from"../api.js";import{events as $}from"@dropins/tools/event-bus.js";import{useText as j,MarkupText as q}from"@dropins/tools/i18n.js";import"@dropins/tools/signals.js";import"../fragments.js";import"@dropins/tools/fetch-graphql.js";const N=({active:r=!0,slots:n,...u})=>{var m;const[g,s]=l(!1),[h,a]=l(""),{errorMessage:A}=j({errorMessage:"Checkout.TermsAndConditions.error"}),o=((m=_.config)==null?void 0:m.agreementsEnabled)===!1,x=()=>{a("")},C=()=>{a(A)};return E(()=>{if(!r||o)return;if(P()){s(!0);return}const e=$.on("checkout/initialized",()=>{s(!0)},{eager:!0});return()=>{e==null||e.off()}},[r,o]),t(b,{...u,agreements:t(U,{context:{appendAgreement(d){this._registerMethod((...e)=>{const c=d(...e);if(!c)return;const{mode:T,name:p,text:i,translationId:f}=c;if(!i&&!f){console.warn(`The agreement ${p} is misconfigured. Please provide a text or a translationId.`);return}const M=i?t(z,{html:i}):t(q,{id:f}),k=t(v,{checked:T===S.AUTO,label:M,name:p,required:!0,onChange:x,onInvalid:C});this._setProps(I=>({children:[...I.children||[],k]}))})}},name:"Agreements",slot:n==null?void 0:n.Agreements}),error:h,initialized:g,visible:r&&!o})};export{N as TermsAndConditions,N as default};
|
|
4
4
|
//# sourceMappingURL=TermsAndConditions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TermsAndConditions.js","sources":["/@dropins/storefront-checkout/src/containers/TermsAndConditions/TermsAndConditions.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Markup } from '@/checkout/components';\nimport { TermsAndConditions as TermsAndConditionsComponent } from '@/checkout/components/TermsAndConditions';\nimport { AgreementMode } from '@/checkout/data/models';\nimport { getLatestCheckoutUpdate, state } from '@/checkout/lib';\nimport { Checkbox } from '@adobe-commerce/elsie/components';\nimport { MarkupText, useText } from '@adobe-commerce/elsie/i18n';\nimport {\n Container,\n Slot,\n SlotMethod,\n SlotProps,\n} from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useEffect, useState } from 'preact/hooks';\n\nexport interface TermsAndConditionsProps {\n active?: boolean;\n slots?: {\n Agreements?: SlotProps<{\n appendAgreement: SlotMethod<{\n name: string;\n mode: AgreementMode;\n translationId?: string;\n text?: string;\n }>;\n }>;\n };\n}\n\nexport const TermsAndConditions: Container<TermsAndConditionsProps> = ({\n active = true,\n slots,\n ...props\n}) => {\n const [isInitialized, setIsInitialized] = useState(false);\n const [error, setError] = useState<string>('');\n\n const { errorMessage } = useText({\n errorMessage: 'Checkout.TermsAndConditions.error',\n });\n\n const disabledViaConfig = state.config?.agreementsEnabled === false;\n\n const handleChange = () => {\n setError('');\n };\n\n const handleInvalid = () => {\n setError(errorMessage);\n };\n\n useEffect(() => {\n if (!active || disabledViaConfig) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n setIsInitialized(true);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n () => {\n setIsInitialized(true);\n },\n { eager: true }\n );\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, disabledViaConfig]);\n\n return (\n <TermsAndConditionsComponent\n {...props}\n agreements={\n <Slot\n context={{\n appendAgreement(callback) {\n this._registerMethod((...attrs) => {\n const _agreement = callback(...attrs);\n\n if (!_agreement) return;\n\n const { mode, name, text, translationId } = _agreement;\n\n if (!text && !translationId) {\n console.warn(\n `The agreement ${name} is misconfigured. Please provide a text or a translationId.`\n );\n return;\n }\n\n const label = text ? (\n <Markup html={text} />\n ) : (\n <MarkupText id={translationId!} />\n );\n\n const agreement = (\n <Checkbox\n checked={mode === AgreementMode.AUTO}\n label={label}\n name={name}\n required={true}\n onChange={handleChange}\n onInvalid={handleInvalid}\n />\n );\n\n this._setProps((prev: any) => ({\n children: [...(prev.children || []), agreement],\n }));\n });\n },\n }}\n name=\"Agreements\"\n slot={slots?.Agreements}\n />\n }\n error={error}\n initialized={isInitialized}\n visible={active && !disabledViaConfig}\n />\n );\n};\n"],"names":["TermsAndConditions","active","slots","props","isInitialized","setIsInitialized","useState","error","setError","errorMessage","useText","disabledViaConfig","_a","state","handleChange","handleInvalid","useEffect","getLatestCheckoutUpdate","onCheckoutInit","events","jsx","TermsAndConditionsComponent","Slot","callback","attrs","_agreement","mode","name","text","translationId","label","Markup","MarkupText","agreement","Checkbox","AgreementMode","prev"],"mappings":"
|
|
1
|
+
{"version":3,"file":"TermsAndConditions.js","sources":["/@dropins/storefront-checkout/src/containers/TermsAndConditions/TermsAndConditions.tsx"],"sourcesContent":["/********************************************************************\n * ADOBE CONFIDENTIAL\n * __________________\n *\n * Copyright 2024 Adobe\n * All Rights Reserved.\n *\n * NOTICE: All information contained herein is, and remains\n * the property of Adobe and its suppliers, if any. The intellectual\n * and technical concepts contained herein are proprietary to Adobe\n * and its suppliers and are protected by all applicable intellectual\n * property laws, including trade secret and copyright laws.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from Adobe.\n *******************************************************************/\n\nimport { Markup } from '@/checkout/components';\nimport { TermsAndConditions as TermsAndConditionsComponent } from '@/checkout/components/TermsAndConditions';\nimport { AgreementMode } from '@/checkout/data/models';\nimport { getLatestCheckoutUpdate, state } from '@/checkout/lib';\nimport { Checkbox } from '@adobe-commerce/elsie/components';\nimport { MarkupText, useText } from '@adobe-commerce/elsie/i18n';\nimport {\n Container,\n Slot,\n SlotMethod,\n SlotProps,\n} from '@adobe-commerce/elsie/lib';\nimport { events } from '@adobe-commerce/event-bus';\nimport { useEffect, useState } from 'preact/hooks';\n\nexport interface TermsAndConditionsProps {\n active?: boolean;\n slots?: {\n Agreements?: SlotProps<{\n appendAgreement: SlotMethod<{\n name: string;\n mode: AgreementMode;\n translationId?: string;\n text?: string;\n }>;\n }>;\n };\n}\n\nexport const TermsAndConditions: Container<TermsAndConditionsProps> = ({\n active = true,\n slots,\n ...props\n}) => {\n const [isInitialized, setIsInitialized] = useState(false);\n const [error, setError] = useState<string>('');\n\n const { errorMessage } = useText({\n errorMessage: 'Checkout.TermsAndConditions.error',\n });\n\n const disabledViaConfig = state.config?.agreementsEnabled === false;\n\n const handleChange = () => {\n setError('');\n };\n\n const handleInvalid = () => {\n setError(errorMessage);\n };\n\n useEffect(() => {\n if (!active || disabledViaConfig) return;\n\n const pastUpdate = getLatestCheckoutUpdate();\n\n if (pastUpdate) {\n setIsInitialized(true);\n return;\n }\n\n const onCheckoutInit = events.on(\n 'checkout/initialized',\n () => {\n setIsInitialized(true);\n },\n { eager: true }\n );\n return () => {\n onCheckoutInit?.off();\n };\n }, [active, disabledViaConfig]);\n\n return (\n <TermsAndConditionsComponent\n {...props}\n agreements={\n <Slot\n context={{\n appendAgreement(callback) {\n this._registerMethod((...attrs) => {\n const _agreement = callback(...attrs);\n\n if (!_agreement) return;\n\n const { mode, name, text, translationId } = _agreement;\n\n if (!text && !translationId) {\n console.warn(\n `The agreement ${name} is misconfigured. Please provide a text or a translationId.`\n );\n return;\n }\n\n const label = text ? (\n <Markup html={text} />\n ) : (\n <MarkupText id={translationId!} />\n );\n\n const agreement = (\n <Checkbox\n checked={mode === AgreementMode.AUTO}\n label={label}\n name={name}\n required={true}\n onChange={handleChange}\n onInvalid={handleInvalid}\n />\n );\n\n this._setProps((prev: any) => ({\n children: [...(prev.children || []), agreement],\n }));\n });\n },\n }}\n name=\"Agreements\"\n slot={slots?.Agreements}\n />\n }\n error={error}\n initialized={isInitialized}\n visible={active && !disabledViaConfig}\n />\n );\n};\n"],"names":["TermsAndConditions","active","slots","props","isInitialized","setIsInitialized","useState","error","setError","errorMessage","useText","disabledViaConfig","_a","state","handleChange","handleInvalid","useEffect","getLatestCheckoutUpdate","onCheckoutInit","events","jsx","TermsAndConditionsComponent","Slot","callback","attrs","_agreement","mode","name","text","translationId","label","Markup","MarkupText","agreement","Checkbox","AgreementMode","prev"],"mappings":"wkBA8CO,MAAMA,EAAyD,CAAC,CACrE,OAAAC,EAAS,GACT,MAAAC,EACA,GAAGC,CACL,IAAM,OACJ,KAAM,CAACC,EAAeC,CAAgB,EAAIC,EAAS,EAAK,EAClD,CAACC,EAAOC,CAAQ,EAAIF,EAAiB,EAAE,EAEvC,CAAE,aAAAG,CAAa,EAAIC,EAAQ,CAC/B,aAAc,mCAAA,CACf,EAEKC,IAAoBC,EAAAC,EAAM,SAAN,YAAAD,EAAc,qBAAsB,GAExDE,EAAe,IAAM,CACzBN,EAAS,EAAE,CACb,EAEMO,EAAgB,IAAM,CAC1BP,EAASC,CAAY,CACvB,EAEA,OAAAO,EAAU,IAAM,CACV,GAAA,CAACf,GAAUU,EAAmB,OAIlC,GAFmBM,EAAwB,EAE3B,CACdZ,EAAiB,EAAI,EACrB,MAAA,CAGF,MAAMa,EAAiBC,EAAO,GAC5B,uBACA,IAAM,CACJd,EAAiB,EAAI,CACvB,EACA,CAAE,MAAO,EAAK,CAChB,EACA,MAAO,IAAM,CACXa,GAAA,MAAAA,EAAgB,KAClB,CAAA,EACC,CAACjB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