2019-11-08 03:40:20 +01:00
|
|
|
import parse, { DomElement } from 'html-react-parser';
|
|
|
|
import cleanChildrenTags from './cleanChildrenTags';
|
|
|
|
import cleanWhitespace from './cleanWhitespace';
|
2019-11-12 23:14:12 +01:00
|
|
|
import cleanApiTags from './cleanApiTags';
|
2019-11-08 03:40:20 +01:00
|
|
|
import rewriteLink from './rewriteLink';
|
|
|
|
import parseChildrenOf from './parseChildrenOf';
|
2019-11-12 04:09:29 +01:00
|
|
|
import cleanCalloutTags from './cleanCalloutTags';
|
2019-11-08 03:40:20 +01:00
|
|
|
import { ReactElement } from 'react';
|
|
|
|
import rewriteTable from './rewriteTable';
|
|
|
|
import rewriteHeader from './rewriteHeader';
|
2019-11-14 03:05:03 +01:00
|
|
|
import cleanHeaders from './cleanHeaders';
|
|
|
|
|
2019-11-08 03:40:20 +01:00
|
|
|
/**
|
|
|
|
* Replace all the [CHILDREN] with proper React components.
|
|
|
|
* @param html
|
|
|
|
* @return ReactElement | ReactElement[] | string
|
|
|
|
*/
|
|
|
|
const parseHTML = (html: string): ReactElement | ReactElement[] | string => {
|
2019-11-12 23:14:12 +01:00
|
|
|
let cleanHTML = html;
|
|
|
|
cleanHTML = cleanChildrenTags(cleanHTML);
|
2019-11-12 04:09:29 +01:00
|
|
|
cleanHTML = cleanCalloutTags(cleanHTML);
|
2019-11-08 03:40:20 +01:00
|
|
|
cleanHTML = cleanWhitespace(cleanHTML);
|
2019-11-12 23:14:12 +01:00
|
|
|
cleanHTML = cleanApiTags(cleanHTML);
|
2019-11-14 03:05:03 +01:00
|
|
|
cleanHTML = cleanHeaders(cleanHTML);
|
|
|
|
|
2019-11-08 03:40:20 +01:00
|
|
|
const parseOptions = {
|
|
|
|
replace(domNode: DomElement): ReactElement | object | undefined | false {
|
|
|
|
const { name, attribs, children } = domNode;
|
|
|
|
const domChildren = children || [];
|
|
|
|
if (name && attribs) {
|
|
|
|
if (name === 'a') {
|
|
|
|
return rewriteLink(attribs, domChildren, parseOptions);
|
|
|
|
}
|
|
|
|
if (name === 'table') {
|
|
|
|
return rewriteTable(domChildren, parseOptions);
|
|
|
|
}
|
|
|
|
if (name.match(/^h[0-9]$/)) {
|
|
|
|
return rewriteHeader(domNode);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (domNode.data) {
|
|
|
|
const { data } = domNode;
|
|
|
|
return parseChildrenOf(data);
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
const component = parse(cleanHTML, parseOptions);
|
|
|
|
|
|
|
|
return component;
|
|
|
|
};
|
|
|
|
|
|
|
|
export default parseHTML;
|