Skip to content

Instantly share code, notes, and snippets.

@daleobrien
Last active December 7, 2016 23:40
Show Gist options
  • Save daleobrien/eecb24f595f75a27a2d6a103b80f43d4 to your computer and use it in GitHub Desktop.
Save daleobrien/eecb24f595f75a27a2d6a103b80f43d4 to your computer and use it in GitHub Desktop.
'''
svg_font_to_reactjs
Convert a svg fonttello font file into a ReactJS file full of react classes.
They can then be used:
import Wifi from './Font';
<Wifi width={32} height={32}/>
Usage:
svg_font_to_reactjs.py [-i FILE] [-o FILE]
Options:
-h, --help
-o FILE specify output file [default: ./Font.jsx]_
-i FILE specify the svg fontello file [default: ./fontello.svg]_
'''
from docopt import docopt
import re
import os
NAME_AND_PATH_RE = re.compile('^.*glyph-name="([\S]*)".*d="([\d\w\s-]*)".*$')
COMPONENT_TEMPLATE = '''
const {title} = (props) => (
<svg
className="{name}"
xmlns="http://www.w3.org/2000/svg"
width={{props.width}}
height={{props.height}}
viewBox="0 0 1000 1000"
aria-labelledby="title">
<title id="{name}">{title} Icon</title>
<g>
<path
fill={{props.colour}}
d="{path}"
strokeWidth="1"
transform="translate(0, 850) scale(0.9,-0.9)" />
</g>
</svg>
);
{title}.propTypes = {{
width: React.PropTypes.number.isRequired,
height: React.PropTypes.number.isRequired,
colour: React.PropTypes.string.isRequired
}};
{title}.defaultProps = {{
width: 32,
height: 32,
colour: "black"
}};
'''
REACTJS_TEMPLATE = '''import React from 'react';
{components}
'''
EXPORTS = '''
export {{
{titles}
}};
'''
def create_reactjs_from_svg_font(infile, outfile):
components = []
titles = set()
for gylph in open(infile, 'r').readlines():
gylph = gylph.strip()
if not gylph.startswith('<glyph '):
continue
matches = NAME_AND_PATH_RE.match(gylph)
name = matches.group(1)
path = matches.group(2)
title = name.replace('-', ' ').title().replace(' ', '')
titles.add(title)
components.append(
COMPONENT_TEMPLATE.format(name=name, path=path, title=title))
content = REACTJS_TEMPLATE.format(components="\n".join(components))
titles = ",\n ".join(sorted(list(titles)))
content += EXPORTS.format(titles=titles)
with open(outfile, 'w') as f:
f.write(content)
if __name__ == "__main__":
arguments = docopt(__doc__)
infile = arguments['-i']
outfile = arguments['-o']
if os.path.isfile(infile):
create_reactjs_from_svg_font(infile, outfile)
else:
print "Can't find svg font file '%s'" % infile
exit(-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment