|
| 1 | +import type {i18n} from '@coveo/atomic'; |
| 2 | +import React, {useEffect, useRef} from 'react'; |
| 3 | +import {AtomicCommerceRecommendationInterface} from './components.js'; |
| 4 | + |
| 5 | +export type AtomicCommerceRecommendationInterface = React.ComponentProps< |
| 6 | + typeof AtomicCommerceRecommendationInterface |
| 7 | +>; |
| 8 | + |
| 9 | +/** |
| 10 | + * The properties of the AtomicCommerceRecommendationInterface component |
| 11 | + */ |
| 12 | +interface WrapperProps |
| 13 | + extends Omit< |
| 14 | + AtomicCommerceRecommendationInterface, |
| 15 | + 'i18n' | 'pipeline' | 'searchHub' |
| 16 | + > { |
| 17 | + /** |
| 18 | + * An optional callback that lets you control the interface localization. |
| 19 | + * |
| 20 | + * The function receives the search interface 18n instance, which you can then modify (see [Localization](https://docs.coveo.com/en/atomic/latest/usage/atomic-localization/)). |
| 21 | + * |
| 22 | + */ |
| 23 | + localization?: (i18n: i18n) => void; |
| 24 | +} |
| 25 | + |
| 26 | +const DefaultProps: Required<Pick<WrapperProps, 'localization'>> = { |
| 27 | + localization: () => {}, |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * This component serves as a wrapper for the core AtomicCommerceRecommendationInterface. |
| 32 | + * @param props |
| 33 | + * @returns |
| 34 | + */ |
| 35 | +export const InterfaceWrapper = ( |
| 36 | + props: React.PropsWithChildren<WrapperProps> |
| 37 | +) => { |
| 38 | + const mergedProps = {...DefaultProps, ...props}; |
| 39 | + if (!mergedProps.engine) { |
| 40 | + throw new Error('The "engine" prop is required.'); |
| 41 | + } |
| 42 | + const {engine, localization, ...allOtherProps} = mergedProps; |
| 43 | + const interfaceRef = |
| 44 | + useRef<React.ElementRef<typeof AtomicCommerceRecommendationInterface>>( |
| 45 | + null |
| 46 | + ); |
| 47 | + let initialization: Promise<void> | null = null; |
| 48 | + |
| 49 | + useEffect(() => { |
| 50 | + const CommerceRecommendationInterfaceAtomic = interfaceRef.current!; |
| 51 | + if (!initialization) { |
| 52 | + initialization = |
| 53 | + CommerceRecommendationInterfaceAtomic.initializeWithEngine(engine); |
| 54 | + initialization.then(() => { |
| 55 | + localization(CommerceRecommendationInterfaceAtomic.i18n); |
| 56 | + }); |
| 57 | + } |
| 58 | + }, [interfaceRef]); |
| 59 | + |
| 60 | + return ( |
| 61 | + <AtomicCommerceRecommendationInterface |
| 62 | + engine={engine} |
| 63 | + ref={interfaceRef} |
| 64 | + {...allOtherProps} |
| 65 | + > |
| 66 | + {props.children} |
| 67 | + </AtomicCommerceRecommendationInterface> |
| 68 | + ); |
| 69 | +}; |
0 commit comments