2018-12-06 03:02:04 +02:00
|
|
|
import parser, { Node, plainParser } from './parser';
|
2018-11-20 22:11:00 +02:00
|
|
|
import * as A from '../prelude/array';
|
|
|
|
import * as S from '../prelude/string';
|
|
|
|
|
2018-12-06 03:02:04 +02:00
|
|
|
export default (source: string, plainText = false): Node[] => {
|
2018-11-20 22:11:00 +02:00
|
|
|
if (source == null || source == '') {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2018-12-06 03:02:04 +02:00
|
|
|
let nodes: Node[] = plainText ? plainParser.root.tryParse(source) : parser.root.tryParse(source);
|
2018-11-20 22:11:00 +02:00
|
|
|
|
|
|
|
const combineText = (es: Node[]): Node =>
|
|
|
|
({ name: 'text', props: { text: S.concat(es.map(e => e.props.text)) } });
|
|
|
|
|
|
|
|
const concatText = (nodes: Node[]): Node[] =>
|
|
|
|
A.concat(A.groupOn(x => x.name, nodes).map(es =>
|
|
|
|
es[0].name === 'text' ? [combineText(es)] : es
|
|
|
|
));
|
|
|
|
|
2018-12-11 13:36:55 +02:00
|
|
|
const concatTextRecursive = (es: Node[]): void => {
|
|
|
|
for (const x of es.filter(x => x.children)) {
|
2018-11-20 22:11:00 +02:00
|
|
|
x.children = concatText(x.children);
|
|
|
|
concatTextRecursive(x.children);
|
2018-12-11 13:36:55 +02:00
|
|
|
}
|
|
|
|
};
|
2018-11-20 22:11:00 +02:00
|
|
|
|
|
|
|
nodes = concatText(nodes);
|
|
|
|
concatTextRecursive(nodes);
|
|
|
|
|
|
|
|
const removeEmptyTextNodes = (nodes: Node[]) => {
|
2018-12-11 13:36:55 +02:00
|
|
|
for (const n of nodes.filter(n => n.children)) {
|
|
|
|
n.children = removeEmptyTextNodes(n.children);
|
|
|
|
}
|
2018-11-20 22:11:00 +02:00
|
|
|
return nodes.filter(n => !(n.name == 'text' && n.props.text == ''));
|
|
|
|
};
|
|
|
|
|
|
|
|
nodes = removeEmptyTextNodes(nodes);
|
|
|
|
|
|
|
|
return nodes;
|
|
|
|
};
|