class B2C_ColorFilterUtility { static idCount = 0; static RECOLOR_SVG_TEMPLATE = ` `; static recolorFilter({ red, green, blue, alpha = 100 }) { let r = red / 255, g = green / 255, b = blue / 255, a = alpha / 100, filterId = `recolor${this.idCount++}`; const recolorSvg = this.RECOLOR_SVG_TEMPLATE.replace( "R1", String(Math.round((r + Number.EPSILON) * 1000) / 1000), ) .replace( "G1", String(Math.round((g + Number.EPSILON) * 1000) / 1000), ) .replace( "B1", String(Math.round((b + Number.EPSILON) * 1000) / 1000), ) .replace( "A1", String(Math.round((a + Number.EPSILON) * 1000) / 1000), ) .replace("recolorId", filterId); let filterDiv = document.createElement("div"); filterDiv.style.cssText = "height:0; width:0; overflow:hidden"; filterDiv.setAttribute('aria-hidden', 'true'); filterDiv.innerHTML = recolorSvg; document.body.appendChild(filterDiv); return `brightness(0) invert() url('#${filterId}')`; } static hexToRgb(hex) { const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, (m, r, g, b) => { return r + r + g + g + b + b; }); const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? [ parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16), ] : null; } static rgbToFilter(r, g, b, a = 100) { return this.recolorFilter({ red: r, green: g, blue: b, alpha: a }); } static hexToFilter(hex) { let rgb = this.hexToRgb(hex); return (rgb == null) ? null : this.rgbToFilter(...this.hexToRgb(hex)); } }