Created
September 11, 2015 10:30
-
-
Save dmitriid/e3aa38043f054d6e0ae3 to your computer and use it in GitHub Desktop.
Convert svg files to virtual-dom's VTree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Convert svg files to virtual-dom's VTree | |
To use the resulting tree | |
import svg from 'virtual-dom/virtual-hyperscript/svg' | |
if you use Cycle.js: | |
import {svg} from '@cycle/dom'; | |
*/ | |
import fs from 'fs'; | |
import libxmljs from 'libxmljs'; | |
import {js_beautify} from 'js-beautify'; | |
function attr2h(attrs){ | |
let attributes = {}; | |
let dataSet = {}; | |
for(const v of attrs){ | |
const key = v.name(); | |
const value = v.value(); | |
const maybeData = key.split('-'); | |
if(maybeData[0] === 'data'){ | |
dataSet[maybeData[1]] = value; | |
} else { | |
attributes[key] = value; | |
} | |
} | |
attributes['dataset'] = dataSet; | |
return JSON.stringify(attributes); | |
} | |
function node2h(node) { | |
if (node.name() === 'text') { | |
const str = node.toString().trim(); | |
return str === '' ? str : `'${str}'`; | |
} | |
const children = node.childNodes().reduce((acc, child) => { | |
const ch = node2h(child); | |
if(ch !== ''){ | |
acc.push(ch); | |
} | |
return acc; | |
}, []).join(',\n'); | |
const attrs = attr2h(node.attrs()); | |
return js_beautify(`svg('${node.name()}', ${attrs}, [${children}])`); | |
} | |
export default function(what, saveTo){ | |
var str = fs.readFileSync(what); | |
var doc = libxmljs.parseXml(str); | |
fs.writeFileSync(saveTo, node2h(doc.root())); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example, using an icon from http://useiconic.com
Original file
Convert
Result: