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) => { export const toHtml = (markdown) => {
const symbols = toSymbols(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 toSymbols = (markdown) => {
const lineFeed = new LineFeed(markdown);
const symbols = []; const symbols = [];
if (heading.symbols.some((s) => markdown.includes(s))) { while (!lineFeed.isEmpty()) {}
const symbol = Object.assign({}, heading);
symbol.text = markdown;
symbols.push(symbol);
}
return symbols; return symbols;
}; };
const heading = { class LineFeed {
key: "heading", originalText = undefined;
level: 1, /**
multiLine: false, * @type {string[]}
symbols: ["#", "##", "###", "####", "#####", "######"], */
text: "", feed = undefined;
children: [], /**
}; *
* @param {string} markdown
*/
constructor(markdown) {
this.originalText = markdown;
// TODO: Need to identify line endings
this.feed = markdown.split("\n");
}
const renderers = [ /**
{ * @returns {string}
key: "heading", */
render: (symbol) => { peek() {
return `<h1>${symbol.text}</h1>`; 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>`;
}
}