import type { FunctionComponent, HTMLAttributes } from 'react'
import React from 'react'
import { forwardRef } from 'react'
import {
Label,
SROnly,
Link,
type LinkProps,
type LinkElementType,
} from '../..'
import { useDefineVariant, type Variant } from './useDefineVariant'
import { useSkuSlug } from './useSkuSlug'
// TODO: Change by ImageComponent when it be right
const ImageComponentFallback: SkuSelectorProps['ImageComponent'] = ({
src,
alt,
...otherProps
}) =>
export interface SkuOption {
/**
* Alternative text description of the image.
*/
alt?: string
/**
* Image URL.
*/
src?: string
/**
* Label to describe the option when selected. This is mandatory if you want to use the `image` variant.'
*/
label: string
/**
* Current value for this option.
*/
value: string
/**
* Specifies that this option should be disabled.
*/
disabled?: boolean
/**
* Hex color code for this option. This is mandatory if you want to use the `Color` variant.
*/
hexColor?: string
}
export interface SkuSelectorProps extends HTMLAttributes {
/**
* ID to find this component in testing tools (e.g.: cypress,
* testing-library, and jest).
*/
testId?: string
/**
* ID of the current instance of the component.
*/
id?: string
/**
* SKU options that should be rendered.
*/
availableVariations: Record
/**
* Name of the SKU property that this selector is relative to.
*/
skuPropertyName: string
/**
* Currently active variation's value.
*/
activeVariations: Record
/**
* Optional variant type, when is not passed the type is inferred based on options properties
*/
variant?: Variant
/**
* Extends all Link Props.
*/
linkProps?: Partial>
/**
* Optional function to determines the href string.
*/
getItemHref?: (option: SkuOption) => string
/**
* Maps property value combinations to their respective SKU's slug
*/
slugsMap: Record
/**
* Function that returns a React component that will be used to render images.
*/
ImageComponent?: FunctionComponent<{
src: string
alt: string
}>
}
const SkuSelector = forwardRef(
function SkuSelector(
{
availableVariations,
skuPropertyName,
testId,
activeVariations,
linkProps,
slugsMap,
getItemHref: getItemHrefProp,
ImageComponent = ImageComponentFallback,
variant: variantProp,
...otherProps
},
ref
) {
const activeSelectorValue = activeVariations[skuPropertyName]
const options = availableVariations[skuPropertyName]
const variant = useDefineVariant(options, variantProp)
const { getItemHref } = useSkuSlug(
activeVariations,
slugsMap,
skuPropertyName,
getItemHrefProp
)
return (