WIP markdown parser

This commit is contained in:
2023-09-16 19:55:03 +02:00
parent 8ccbe01e43
commit c828569a49

View File

@@ -1,39 +1,87 @@
const SymbolsToCheck = [Heading];
export const toHtml = (markdown) => {
const symbols = toSymbols(markdown);
const html = [];
symbols.forEach((s) =>
html.push(renderers.find((r) => r.key === s.key).render(s))
);
return `<div>${html.join("\r\n")}</div>`;
return `<div>${lineFeed.feed}</div>`;
};
const toSymbols = (markdown) => {
const lineFeed = new LineFeed(markdown);
const symbols = [];
if (heading.symbols.some((s) => markdown.includes(s))) {
const symbol = Object.assign({}, heading);
symbol.text = markdown;
symbols.push(symbol);
}
while (!lineFeed.isEmpty()) {}
return symbols;
};
const heading = {
key: "heading",
level: 1,
multiLine: false,
symbols: ["#", "##", "###", "####", "#####", "######"],
text: "",
children: [],
};
class LineFeed {
originalText = undefined;
/**
* @type {string[]}
*/
feed = undefined;
/**
*
* @param {string} markdown
*/
constructor(markdown) {
this.originalText = markdown;
// TODO: Need to identify line endings
this.feed = markdown.split("\n");
}
const renderers = [
{
key: "heading",
render: (symbol) => {
return `<h1>${symbol.text}</h1>`;
},
},
];
/**
* @returns {string}
*/
peek() {
return this.feed[0] ?? undefined;
}
/**
*
* @returns {string|undefined}
*/
claim() {
const line = this.feed.shift();
if (line === undefined) throw new Error("Feed is empty");
return line;
}
/**
*
* @returns {boolean}
*/
isEmpty() {
return this.feed.length === 0;
}
}
class Symbol {
static canParse(line) {
throw new Error("Not implemented");
}
static create(lineFeed) {
throw new Error("Not implemented");
}
render() {
throw new Error("Not implemented");
}
}
class Heading extends Symbol {
/**
*
* @param {string} line
* @returns {boolean}
*/
static canParse(line) {
return line.trim().startsWith("#");
}
static create(lineFeed) {
throw new Error("Not implemented");
}
render() {
return `<h1>${Symbol.text}</h1>`;
}
}