Created
July 12, 2019 21:24
-
-
Save believer-ufa/6620d9421f6a91c326bd3d74b233588d to your computer and use it in GitHub Desktop.
Render AST tree on React received from html-parse-stringify library
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
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { compose } from 'recompose'; | |
import { hot } from 'react-hot-loader/root'; | |
import { decode } from 'he'; | |
import isArray from 'lodash/isArray'; | |
import pipe from 'ramda/src/pipe'; | |
import assoc from 'ramda/src/assoc'; | |
import omit from 'ramda/src/omit'; | |
const hoc = compose(hot); | |
const getAttrs = (attrs, type, idx) => { | |
const addKey = assoc('key', `${type}-${idx}`); | |
if (attrs.class) { | |
return pipe( | |
omit(['class']), | |
assoc('className', attrs.class), | |
addKey, | |
)(attrs); | |
} | |
return addKey(attrs); | |
}; | |
const propTypes = { | |
ast: PropTypes.arrayOf(PropTypes.object).isRequired, | |
}; | |
const defaultProps = {}; | |
const AstTreeComponent = ({ ast }) => { | |
if (isArray(ast)) { | |
return ( | |
<React.Fragment> | |
{ast.map((el, idx) => { | |
if (el.type === 'text') { | |
return decode(el.content); | |
} | |
const tagName = el.name && el.name.toLowerCase(); | |
if (el.type === 'tag' && tagName !== 'ib') { | |
if (el.voidElement) { | |
return React.createElement( | |
tagName, | |
getAttrs(el.attrs, el.type, idx), | |
); | |
} | |
return React.createElement( | |
tagName, | |
getAttrs(el.attrs, el.type, idx), | |
<AstTree ast={el.children} />, | |
); | |
} | |
if (el.type === 'component') { | |
return el.component; | |
} | |
return null; | |
})} | |
</React.Fragment> | |
); | |
} | |
return null; | |
}; | |
AstTreeComponent.propTypes = propTypes; | |
AstTreeComponent.defaultProps = defaultProps; | |
const AstTree = hoc(AstTreeComponent); | |
export default AstTree; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment