Skip to content

Instantly share code, notes, and snippets.

@mwunsch
Created April 23, 2015 14:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwunsch/6b538a0352cae834457a to your computer and use it in GitHub Desktop.
Save mwunsch/6b538a0352cae834457a to your computer and use it in GitHub Desktop.
DOM -> Graphviz
/*
This is an incredibly rudimentary PhantomJS script to walk a DOM and emit a graphviz `dot` document.
It is neither clever nor good.
Proceed with caution.
Usage: phantomjs viz.js http://2015.empirejs.org/ | tee >(dot -Tpng > test.png)
*/
var page = require('webpage').create();
var args = require('system').args;
if (args.length <= 1) {
console.log("err: need arg");
phantom.exit(1);
}
page.open(args[1], function (status) {
if (status !== 'success') {
console.log('err: '+status);
phantom.exit(1);
}
page.onConsoleMessage = function(msg, line, source) {
console.log(msg);
}
page.evaluate(function () {
var
dict = {},
walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
null);
function prevSiblingCount(el, i) {
i = i != null ? i : 0;
var prev = el.previousElementSibling;
if (prev) {
if (prev.nodeName === el.nodeName) {
return prevSiblingCount(prev, i+1);
} else {
return prevSiblingCount(prev, i);
}
} else {
return i;
}
}
function vizLabel(el) {
var buffer = el.nodeName,
count;
if (el.id) {
buffer += ("#"+el.id);
} else {
if (el.className) {
buffer += ("."+el.className.split(/\s/).join("."));
}
if (el.parentElement) {
buffer = vizLabel(el.parentElement)+" > "+buffer;
count = prevSiblingCount(el);
if (count) {
buffer += (":nth-of-type("+prevSiblingCount(el)+")");
}
}
}
return buffer;
}
console.log("digraph El {");
do {
var parentEl = walker.currentNode.parentElement;
if (parentEl) {
console.log("\t\""+vizLabel(parentEl)+"\"->\""+vizLabel(walker.currentNode)+"\";");
} else {
console.log("\t\""+vizLabel(walker.currentNode)+"\";");
}
} while (walker.nextNode());
console.log("}");
});
phantom.exit(0);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment