summaryrefslogtreecommitdiff
path: root/src/text/html.ts
blob: 797f3b3f336371d3b1f490d72d061e73885c1f97 (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { lib as emojilib } from 'emojilib';
import { JSDOM } from 'jsdom';

const handlers = {
	bold({ document }, { bold }) {
		const b = document.createElement('b');
		b.textContent = bold;
		document.body.appendChild(b);
	},

	code({ document }, { code }) {
		const pre = document.createElement('pre');
		const inner = document.createElement('code');
		inner.innerHTML = code;
		pre.appendChild(inner);
		document.body.appendChild(pre);
	},

	emoji({ document }, { content, emoji }) {
		const found = emojilib[emoji];
		const node = document.createTextNode(found ? found.char : content);
		document.body.appendChild(node);
	},

	hashtag({ document }, { hashtag }) {
		const a = document.createElement('a');
		a.href = '/search?q=#' + hashtag;
		a.textContent = hashtag;
	},

	'inline-code'({ document }, { code }) {
		const element = document.createElement('code');
		element.textContent = code;
		document.body.appendChild(element);
	},

	link({ document }, { url, title }) {
		const a = document.createElement('a');
		a.href = url;
		a.textContent = title;
		document.body.appendChild(a);
	},

	mention({ document }, { content }) {
		const a = document.createElement('a');
		a.href = '/' + content;
		a.textContent = content;
		document.body.appendChild(a);
	},

	quote({ document }, { quote }) {
		const blockquote = document.createElement('blockquote');
		blockquote.textContent = quote;
		document.body.appendChild(blockquote);
	},

	text({ document }, { content }) {
		for (const text of content.split('\n')) {
			const node = document.createTextNode(text);
			document.body.appendChild(node);

			const br = document.createElement('br');
			document.body.appendChild(br);
		}
	},

	url({ document }, { url }) {
		const a = document.createElement('a');
		a.href = url;
		a.textContent = url;
		document.body.appendChild(a);
	}
};

export default tokens => {
	const { window } = new JSDOM('');

	for (const token of tokens) {
		handlers[token.type](window, token);
	}

	return `<p>${window.document.body.innerHTML}</p>`;
};