Last active
March 25, 2018 15:45
-
-
Save Logiraptor/5210b356beeb410875be63062bbb3910 to your computer and use it in GitHub Desktop.
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
javascript:(function(){ | |
let script = document.createElement('script'); | |
script.src = 'https://unpkg.com/[email protected]/viz.js'; | |
script.onload = function() { | |
let findReactComponent = function (el) { | |
for (const key in el) { | |
if (key.startsWith('__reactInternalInstance$')) { | |
const fiberNode = el[key]; | |
return fiberNode && fiberNode.return && fiberNode.return.stateNode; | |
} | |
} | |
return null; | |
}; | |
let walkDOM = function (node, func) { | |
if (func(node)) { | |
node = node.firstChild; | |
while (node) { | |
walkDOM(node, func); | |
node = node.nextSibling; | |
} | |
} | |
}; | |
let findAllReactComponents = function (el) { | |
const component = findReactComponent(el); | |
if (component) { | |
let tree = {node: component, children: []}; | |
let node = el.firstChild; | |
while (node) { | |
let childComponent = findAllReactComponents(node); | |
if (childComponent) { | |
tree.children.push(childComponent); | |
} | |
node = node.nextSibling; | |
} | |
return tree; | |
} | |
return null; | |
}; | |
let names = {}; | |
let getName = function(name) { | |
if (name in names) { | |
return names[name]; | |
} else { | |
return names[name] = Object.keys(names).length; | |
} | |
}; | |
let generateForTree = function (tree) { | |
let output = []; | |
let name = getName(tree.node.constructor.name); | |
output.push(name + " [label=\"" + tree.node.constructor.name + "\"]"); | |
for (let child of tree.children) { | |
output.push(name + " -> " + getName(child.node.constructor.name)); | |
output = output.concat(generateForTree(child)); | |
} | |
return output; | |
}; | |
let generateGraph = function() { | |
walkDOM(document.body, node => { | |
let components = findAllReactComponents(node); | |
if (components) { | |
let lines = new Set(generateForTree(components)); | |
let output = []; | |
output.push('digraph {'); | |
for (let line of lines) { | |
output.push(line + ";"); | |
} | |
output.push('}'); | |
console.log(output.join("\n")); | |
let svgbiz = Viz(output.join("")); | |
let string = 'data:image/svg+xml;base64,' + btoa(svgbiz); | |
var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"; | |
var x = window.open(); | |
x.document.open(); | |
x.document.write(iframe); | |
x.document.close(); | |
return false; | |
} | |
return true; | |
}) | |
}; | |
generateGraph(); | |
}; | |
document.documentElement.appendChild(script); | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment