Created
July 17, 2015 09:29
-
-
Save barneycarroll/f43637d3d686a36c71c1 to your computer and use it in GitHub Desktop.
Convert DOM or XML/HTML to Mithril
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
const { map, reduce } = Array.prototype | |
const wrap = document.createElement( 'x' ) | |
export const dom2mithril = dom => | |
dom.nodeType === 3 | |
? dom.nodeValue | |
: dom.nodeType === 1 | |
? { | |
tag : dom.nodeName, | |
attrs : dom.attributes | |
::reduce( ( attrs, attr ) => | |
( { | |
...attrs, | |
[ attr.name ] : attr.value | |
} ), | |
{} | |
), | |
children : dom.childNodes | |
::map( dom2mithril ) | |
} | |
: null | |
export const html2mithril = html => { | |
while ( wrap.hasChildNodes() ) | |
wrap.removeChild( wrap.lastChild ) | |
return wrap | |
.insertAdjacentHTML( 'beforeend', markup ) | |
.childNodes | |
::map( dom2mithril ) | |
} |
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
( this.define || Object )( | |
( this.exports || this ).module = { | |
dom2mithril : function( dom ){ | |
return dom.nodeType === 3 | |
? dom.nodeValue | |
: dom.nodeType === 1 | |
? { | |
tag : dom.nodeName, | |
attrs : Array.prototype.reduce.call( | |
dom.attributes, | |
function( attrs, attr ){ | |
attrs[ attr.name ] = attr.value | |
return attrs | |
}, | |
{} | |
), | |
children : Array.prototype.map.call( dom.childNodes, this.dom2mithril ) | |
} | |
: null | |
}, | |
html2mithril : function( html ){ | |
while ( wrap.hasChildNodes() ) | |
wrap.removeChild( wrap.lastChild ) | |
wrap.insertAdjacentHTML( 'beforeend', markup ) | |
return Array.prototype.map.call( childNodes, this.dom2mithril ) | |
} | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment