2022-04-03 16:12:16 +00:00
|
|
|
import {SyntaxNode} from "@lezer/common";
|
|
|
|
import wikiMarkdownLang from "../webapp/parser";
|
|
|
|
|
|
|
|
export type MarkdownTree = {
|
2022-04-04 09:51:41 +00:00
|
|
|
type?: string; // undefined === text node
|
|
|
|
from: number;
|
|
|
|
to: number;
|
|
|
|
text?: string;
|
|
|
|
children?: MarkdownTree[];
|
2022-04-03 16:12:16 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
function treeToAST(text: string, n: SyntaxNode): MarkdownTree {
|
2022-04-04 09:51:41 +00:00
|
|
|
let children: MarkdownTree[] = [];
|
|
|
|
let nodeText: string | undefined;
|
|
|
|
let child = n.firstChild;
|
|
|
|
while (child) {
|
|
|
|
children.push(treeToAST(text, child));
|
|
|
|
child = child.nextSibling;
|
|
|
|
}
|
2022-04-03 16:12:16 +00:00
|
|
|
|
2022-04-04 09:51:41 +00:00
|
|
|
if (children.length === 0) {
|
|
|
|
children = [
|
|
|
|
{
|
2022-04-03 16:12:16 +00:00
|
|
|
from: n.from,
|
|
|
|
to: n.to,
|
2022-04-04 09:51:41 +00:00
|
|
|
text: text.substring(n.from, n.to),
|
|
|
|
},
|
|
|
|
];
|
|
|
|
} else {
|
|
|
|
let newChildren: MarkdownTree[] | string = [];
|
|
|
|
let index = n.from;
|
|
|
|
for (let child of children) {
|
|
|
|
let s = text.substring(index, child.from);
|
|
|
|
if (s) {
|
|
|
|
newChildren.push({
|
|
|
|
from: index,
|
|
|
|
to: child.from,
|
|
|
|
text: s,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
newChildren.push(child);
|
|
|
|
index = child.to;
|
2022-04-03 16:12:16 +00:00
|
|
|
}
|
2022-04-04 09:51:41 +00:00
|
|
|
let s = text.substring(index, n.to);
|
|
|
|
if (s) {
|
|
|
|
newChildren.push({ from: index, to: n.to, text: s });
|
2022-04-03 16:12:16 +00:00
|
|
|
}
|
2022-04-04 09:51:41 +00:00
|
|
|
children = newChildren;
|
|
|
|
}
|
2022-04-03 16:12:16 +00:00
|
|
|
|
2022-04-04 09:51:41 +00:00
|
|
|
let result: MarkdownTree = {
|
|
|
|
type: n.name,
|
|
|
|
from: n.from,
|
|
|
|
to: n.to,
|
|
|
|
};
|
|
|
|
if (children.length > 0) {
|
|
|
|
result.children = children;
|
|
|
|
}
|
|
|
|
if (nodeText) {
|
|
|
|
result.text = nodeText;
|
|
|
|
}
|
|
|
|
return result;
|
2022-04-03 16:12:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function parse(text: string): MarkdownTree {
|
2022-04-04 09:51:41 +00:00
|
|
|
return treeToAST(text, wikiMarkdownLang.parser.parse(text).topNode);
|
2022-04-03 16:12:16 +00:00
|
|
|
}
|