Rocket.Chat.ReactNative/app/containers/markdown/mergeTextNodes.ts

28 lines
810 B
TypeScript
Raw Normal View History

2020-02-28 16:18:03 +00:00
// TODO: should we add this to our commonmark fork instead?
// we loop through nodes and try to merge all texts
export default function mergeTextNodes(ast: any) {
2020-02-28 16:18:03 +00:00
// https://github.com/commonmark/commonmark.js/blob/master/lib/node.js#L268
const walker = ast.walker();
let event;
// eslint-disable-next-line no-cond-assign
while ((event = walker.next())) {
2020-02-28 16:18:03 +00:00
const { entering, node } = event;
const { type } = node;
if (entering && type === 'text') {
while (node._next && node._next.type === 'text') {
const next = node._next;
node.literal += next.literal;
node._next = next._next;
if (node._next) {
node._next._prev = node;
}
if (node._parent._lastChild === next) {
node._parent._lastChild = node;
}
}
walker.resumeAt(node, false);
}
}
return ast;
}