Skip to content

Instantly share code, notes, and snippets.

@ivan-hilckov
Created September 29, 2016 14:37
Show Gist options
  • Select an option

  • Save ivan-hilckov/eb377b9df6d438436881b2b4e62ea0c2 to your computer and use it in GitHub Desktop.

Select an option

Save ivan-hilckov/eb377b9df6d438436881b2b4e62ea0c2 to your computer and use it in GitHub Desktop.
import React from 'react';
import { PropTypes, assertPropTypesDecorator } from 'iv-react-prop-types';
const VIEWBOX_REGEXP = /viewBox="([0-9]+) ([0-9]+) ([0-9]+) ([0-9]+)"/i;
function getViewBoxFromSvgHtml (html) {
const viewBoxMatch = VIEWBOX_REGEXP.exec(html);
if (viewBoxMatch) {
return [ parseFloat(viewBoxMatch[3]) || 0, parseFloat(viewBoxMatch[4]) || 0 ];
}
else {
return [ 0, 0 ];
}
}
function applyColorMappingToSvgHtml (html, colorMapping) {
if (!colorMapping) {
return html;
}
const fromColors = Object.keys(colorMapping);
if (fromColors.length <= 0) {
return html;
}
// Build color regexp in the form of '(#ffffff)|(rgba\(0,0,0,0.0\))' to find all the colors we are about to replace.
const colorsRegexpString = '(' + fromColors.map((fromColor) => {
return fromColor.replace(/[().]/g, '\\$1');
}).join(')|(') + ')';
// Make the regexp with the global search.
const colorsRegexp = new RegExp(colorsRegexpString, 'g');
// Apply the mapping.
return html.replace(colorsRegexp, (foundColor) => {
return colorMapping[foundColor];
});
}
function IvUiSvgIcon ({
html,
width,
height,
verticalAlign,
colorMapping,
}) {
const [ viewBoxWidth, viewBoxHeight ] = getViewBoxFromSvgHtml(html);
return (
<span
style={{
position: 'relative',
display: 'inline-block',
verticalAlign,
width: (width || viewBoxWidth || 'auto'),
height: (height || viewBoxHeight || 'auto'),
backgroundImage: `url('data:image/svg+xml;utf8,${encodeURIComponent(applyColorMappingToSvgHtml(html, colorMapping))}')`,
backgroundSize: 'contain',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center center',
}}
/>
);
}
IvUiSvgIcon.propTypes = {
html: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
verticalAlign: PropTypes.string,
colorMapping: PropTypes.object,
};
IvUiSvgIcon.defaultProps = {
html: '',
width: 0,
height: 0,
verticalAlign: 'top',
};
const IvUiSvgIconDecorated = assertPropTypesDecorator(IvUiSvgIcon);
export default IvUiSvgIconDecorated;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment