-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.ts
More file actions
63 lines (54 loc) · 1.55 KB
/
Copy pathparser.ts
File metadata and controls
63 lines (54 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { BlockToken } from './blockToken.ts'
import { HeaderToken } from './headerToken.ts'
import { ParagraphToken } from './paragraphToken.ts'
import { QuoteToken } from './quoteToken.ts'
import { SeparatorToken } from './separatorToken.ts'
import { ListToken } from './listToken.ts'
export class MarkdownParser {
private types: any;
private markdown: string;
constructor(markdown: string) {
this.types = [HeaderToken, QuoteToken, SeparatorToken, ListToken, ParagraphToken];
this.markdown = this.escape(markdown);
}
parse(): string {
const lines: string[] = this.markdown.split('\n');
let tokens: BlockToken[] = [];
for(let line of lines) {
const tokenType = this.types.find(t => t.match(line));
if(!tokenType) continue;
tokens.push(tokenType.fromLine(line));
}
// Merging
for(let i = 1; i < tokens.length; i++) {
let t1 = tokens[i - 1];
let t2 = tokens[i];
if(!this.compareTypes(t1,t2)) continue;
if(t1.merge(t2)) {
tokens.splice(i, 1);
i--;
}
}
let html: string = "";
// Rendering
for(let token of tokens) {
html += token.renderHTML();
}
return html;
}
private escape(text: string): string {
return text
//.replaceAll("\\\\", "\")
.replaceAll("\\=", "=")
.replaceAll("\\*", "*")
.replaceAll("\\_", "_")
.replaceAll("\\>", ">")
.replaceAll("\\`", "`")
.replaceAll("\\.", ".")
.replaceAll("\\-", "–")
.replaceAll("\\#", "#");
}
private compareTypes(t1: BlockToken, t2: BlockToken): boolean {
return t1.constructor === t2.constructor;
}
}