@mieweb/wikigdrive
Version:
Google Drive to MarkDown synchronization
40 lines (39 loc) • 2 kB
JavaScript
import { isMarkdownBeginMacro, isMarkdownEndMacro } from '../macroUtils.js';
import { walkRecursiveSync } from '../markdownNodesUtils.js';
// Related tests:
// test ./example-document.md
export function removePreWrappingAroundMacros(markdownChunks) {
walkRecursiveSync(markdownChunks.body, (preChunk, ctx) => {
if (preChunk.isTag === true && preChunk.tag === 'PRE') {
if (preChunk.children.length > 0) {
let lastChildIdx = -1;
for (let idx = preChunk.children.length - 1; idx >= 0; idx--) {
const child = preChunk.children[idx];
if (child && child.isTag && ['EOL/', 'BR/', 'EMPTY_LINE/'].includes(child.tag)) {
continue;
}
lastChildIdx = idx;
break;
}
const lastChild = preChunk.children[lastChildIdx];
if (lastChild && lastChild.isTag === false && isMarkdownEndMacro(lastChild.text)) {
lastChild.parent = preChunk.parent;
const after = preChunk.children.splice(lastChildIdx, preChunk.children.length - lastChildIdx);
preChunk.parent.children.splice(ctx.nodeIdx + 1, 0, ...after);
}
}
if (preChunk.children.length > 0) {
let firstChildIdx = 0;
const firstChild = preChunk.children[firstChildIdx];
if (firstChild && firstChild.isTag === false && isMarkdownBeginMacro(firstChild.text)) {
const afterFirst = preChunk.children[firstChildIdx + 1];
if (afterFirst && afterFirst.isTag && afterFirst.tag === 'EOL/') {
firstChildIdx++;
}
const before = preChunk.children.splice(0, firstChildIdx + 1);
preChunk.parent.children.splice(ctx.nodeIdx, 0, ...before);
}
}
}
});
}