commercetools-8.x-1.2-alpha1/modules/commercetools_demo/js/product_attribute_subscriber.js
modules/commercetools_demo/js/product_attribute_subscriber.js
/**
* It is a demo of overriding the output of the attribute values.
*/
/**
* Converts attribute labelValue like "White:#FFFFFF" into
* icon + label HTML snippet for certain attribute types.
*
* @param {{ key: string, labelValue: string }} attr
* Attribute object. This function mutates `attr.labelValue` in-place.
* @return {void}
*/
function colorAttrIcon(attr) {
const applicableTypes = ['color', 'finish'];
if (
!attr ||
!applicableTypes.includes(attr.key) ||
typeof attr.labelValue !== 'string'
) {
return;
}
const [label, color] = attr.labelValue.split(':', 2);
const hexRe = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
if (label && color && (hexRe.test(color) || color === 'transparent')) {
attr.labelValue = `
<span
style="width: 1.5rem; height: 1.5rem; background-color: ${color};"
class="d-inline-block align-middle border border-dark"
></span> ${label.trim()}`;
}
}
document.addEventListener('commercetools:productAttributeLabel', (event) => {
colorAttrIcon(event.detail);
});
