Last active
July 11, 2017 15:42
-
-
Save developit/63ffcd531381bee5a3d9959e3a90035b to your computer and use it in GitHub Desktop.
preact vdom viewer
This file contains 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
/** Use the built-in document viewer in devtools to inspect your VDOM. | |
* Usage in console: | |
* viewComponentTree(document.body) | |
*/ | |
function viewComponentTree(node) { | |
let doc = new DOMParser().parseFromString('', 'application/xml'); | |
function visitor(dom) { | |
let el, c; | |
if (dom instanceof Node) { | |
el = dom.cloneNode(); | |
for (let i=0; i<dom.childNodes.length; i++) { | |
let c = dom.childNodes[i]; | |
el.appendChild(visitor(c._component || c)); | |
} | |
} | |
else { | |
el = doc.createElement(getName(dom.constructor)); | |
for (let i in dom.props) if (i!=='children' && dom.props[i]!==undefined) { | |
el.setAttribute(i, stringify(dom.props[i])); | |
} | |
el.appendChild(visitor(dom._component || dom.base)); | |
} | |
return el; | |
} | |
function getName(component) { | |
return component.displayName || component.name || 'UnnamedComponent'; | |
} | |
function stringify(value) { | |
if (value && typeof value==='object') { | |
if (value.join) return '[ '+value.map(stringify).join(', ')+' ]'; | |
if ('nodeName' in value && 'attributes' in value && 'children' in value) { | |
let props = value.__preactattr_ || value.attributes || {}; | |
return '<'+(typeof value.nodeName==='function'?getName(value.nodeName):value.nodeName)+' '+Object.keys(props).map(k=>k+'="'+stringify(props[k])+'"')+' />'; | |
} | |
let r = '{'; | |
for (let i in value) { | |
r += (r[1]?', ':' ') + (typeof value[i]==='function'?'':(i+': ')) + stringify(value[i]); | |
} | |
value = (r.length>60?(r.substring(0,58)+'…'):r) + ' }'; | |
} | |
if (typeof value==='function') value = (value.name || 'fn')+'()'; | |
return String(value); | |
} | |
doc.removeChild(doc.firstChild); | |
doc.appendChild(visitor(node)); | |
return doc.firstChild; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment