diff --git a/src/icon.js b/src/icon.js index 32891328..6bbcf19e 100644 --- a/src/icon.js +++ b/src/icon.js @@ -1,6 +1,6 @@ import React from 'react'; import IconMui from '@material-ui/core/Icon'; -import snakeCase from 'lodash/snakeCase'; +import utils from './utils'; // Note: we use font icons instead of SVG icons as this allows us to support any icon dynamically // without adding all icons to the JS bundle. The MaterialUI icons are about 54KB which is @@ -15,10 +15,10 @@ export default class Icon extends React.PureComponent { } }; - // Convert to the font icon name so that we can use the SVG Icon names. This allows us to make - // changes to this logic without changing the calling code. + // Convert to the font icon name so that we can use the SVG Icon names in the MSON. This allows us + // switch between font and SVG icons without changing the MSON definitions. toFontIconName(svgIconName) { - return snakeCase(svgIconName); + return utils.snakeCase(svgIconName); } render() { diff --git a/src/utils.js b/src/utils.js index 0d020f8d..a15fa84a 100644 --- a/src/utils.js +++ b/src/utils.js @@ -9,5 +9,16 @@ class Utils { }); return definedProps; } + + snakeCase(str) { + // 1. Make the first letter lower case so that we don't prepend an underscore in step 2 + const a = str.charAt(0).toLowerCase() + str.slice(1); + + // 2. Convert all caps to lower case and prepend an underscore in all cases, except the first. + const b = a.replace(/([A-Z])/g, (match) => '_' + match.toLowerCase()); + + // 3. Convert any sequence of non-alphanumeric characters to a single underscore + return b.replace(/[^a-z0-9]+/, '_'); + } } export default new Utils(); diff --git a/src/utils.test.js b/src/utils.test.js new file mode 100644 index 00000000..c3b3e43e --- /dev/null +++ b/src/utils.test.js @@ -0,0 +1,8 @@ +import utils from './utils'; + +it('should convert to snake case', () => { + expect(utils.snakeCase('Foo Bar')).toEqual('foo_bar'); + expect(utils.snakeCase('fooBar')).toEqual('foo_bar'); + expect(utils.snakeCase('FooBar')).toEqual('foo_bar'); + expect(utils.snakeCase('Foo Bar')).toEqual('foo_bar'); +});