import * as React from 'react';
import { useObservableState } from 'observable-hooks';
import Box from '@wcpos/components/src/box';
import Link from '@wcpos/components/src/link';
import Text from '@wcpos/components/src/text';
import { useQueryManager } from '@wcpos/query';
import { useVariationTable } from './variation-table-rows/context';
import { useT } from '../../../../contexts/translations';
type Props = {
product: import('@wcpos/database').ProductDocument;
};
export const PlainAttributes = ({ product }: Props) => {
const attributes = useObservableState(product.attributes$, product.attributes);
/**
*
*/
return (
{attributes
.filter((attr: any) => !attr.variation)
.map((attr: any) => (
{`${attr.name}: `}
{attr.options.map((option: string, index: number) => (
{option}
{index < attr.options.length - 1 && ', '}
))}
))}
);
};
const ProductAttributes = ({ product }: Props) => {
const attributes = useObservableState(product.attributes$, product.attributes);
const {
expanded,
setExpanded,
setInitialSelectedAttributes,
childrenSearchCount,
parentSearchTerm,
} = useVariationTable();
const manager = useQueryManager();
const t = useT();
/**
*
*/
const handleSelect = React.useCallback(
(attribute, option) => {
if (!expanded) {
setInitialSelectedAttributes({
id: attribute.id,
name: attribute.name,
option,
});
setExpanded(true);
} else {
const query = manager.getQuery(['variations', { parentID: product.id }]);
if (query) {
query.updateVariationAttributeSelector({
id: attribute.id,
name: attribute.name,
option,
});
}
}
},
[expanded, manager, product.id, setExpanded, setInitialSelectedAttributes]
);
/**
* Expand text string
*/
const expandText = React.useMemo(() => {
let text = '';
if (expanded) {
text += t('Collapse', { _tags: 'core' });
} else {
text += t('Expand', { _tags: 'core' });
}
if (childrenSearchCount === 1) {
text += ' - ';
text += t('1 variation found for {term}', {
term: parentSearchTerm,
_tags: 'core',
});
} else if (childrenSearchCount > 0) {
text += ' - ';
text += t('{count} variations found for {term}', {
count: childrenSearchCount,
term: parentSearchTerm,
_tags: 'core',
});
}
return text;
}, [childrenSearchCount, expanded, parentSearchTerm, t]);
/**
*
*/
return (
{attributes
.filter((attr: any) => attr.variation)
.map((attr: any) => (
{`${attr.name}: `}
{attr.options.map((option: string, index: number) => (
handleSelect(attr, option)}>
{option}
{index < attr.options.length - 1 && ', '}
))}
))}
setExpanded(!expanded)}>
{expandText}
);
};
export default ProductAttributes;