2019-01-30 06:47:58 +02:00
|
|
|
import * as A from '../prelude/array';
|
|
|
|
import * as S from '../prelude/string';
|
2019-03-14 14:23:15 +02:00
|
|
|
import { MfmForest, MfmTree } from './prelude';
|
2019-01-30 06:47:58 +02:00
|
|
|
import { createTree, createLeaf } from '../prelude/tree';
|
|
|
|
|
|
|
|
function isEmptyTextTree(t: MfmTree): boolean {
|
2020-04-04 02:46:54 +03:00
|
|
|
return t.node.type === 'text' && t.node.props.text === '';
|
2019-01-30 06:47:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function concatTextTrees(ts: MfmForest): MfmTree {
|
|
|
|
return createLeaf({ type: 'text', props: { text: S.concat(ts.map(x => x.node.props.text)) } });
|
|
|
|
}
|
|
|
|
|
|
|
|
function concatIfTextTrees(ts: MfmForest): MfmForest {
|
|
|
|
return ts[0].node.type === 'text' ? [concatTextTrees(ts)] : ts;
|
|
|
|
}
|
|
|
|
|
|
|
|
function concatConsecutiveTextTrees(ts: MfmForest): MfmForest {
|
|
|
|
const us = A.concat(A.groupOn(t => t.node.type, ts).map(concatIfTextTrees));
|
|
|
|
return us.map(t => createTree(t.node, concatConsecutiveTextTrees(t.children)));
|
|
|
|
}
|
|
|
|
|
|
|
|
function removeEmptyTextNodes(ts: MfmForest): MfmForest {
|
|
|
|
return ts
|
|
|
|
.filter(t => !isEmptyTextTree(t))
|
|
|
|
.map(t => createTree(t.node, removeEmptyTextNodes(t.children)));
|
|
|
|
}
|
|
|
|
|
|
|
|
export function normalize(ts: MfmForest): MfmForest {
|
|
|
|
return removeEmptyTextNodes(concatConsecutiveTextTrees(ts));
|
|
|
|
}
|