-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.mjs
67 lines (63 loc) · 1.83 KB
/
lib.mjs
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
import htm from './htm/index.mjs';
import vhtml from './vhtml/vhtml.mjs';
import marked from './marked/marked.cjs';
const html = htm.bind(vhtml);
const calc_offset = (str) => {
let white_characters = 0;
const len = str.length;
for (let i = 0; i < len; i++) {
const c = str[i];
if (c === '\n') {
white_characters = 0;
}
else if (c === ' ') {
white_characters++;
}
else {
return white_characters;
}
}
// no characters found, only white spaces
return 0;
}
/**
* usage example:
*
* const result = md`# Some Header\nHello there **this** \`is\` a paragraph`
* console.log(Bun.inspect(result));
* // "<h1>Some Header</h1>\n<p>Hello there <strong>this</strong> <code>is</code> a paragraph</p>\n"
*
* `md` will also trim regular whitespaces that indent the whole markdown block, allowing them to be indented same as
* regular code in the scope where they are placed. It allows to write the markdown blocks like this...
*
* md`
* # Title
* some paragraph
* `
*
* rather than this...
*
* md`
* # Title
* some paragraph
* `
*
* and still render properly
*/
const md = (strings, ...args) => {
let result = "";
for (let i = 0; i < strings.length; i++) {
result += strings[i];
if (i < args.length) result += args[i];
}
const offset = calc_offset(result);
if (offset > 0) {
let replacement = "\n";
for (let i = 0; i < offset; i++) replacement += " ";
result = result.replaceAll(replacement, "\n", );
}
let parsed_markdown = marked.parse(result, {headerIds: false});
// https://github.com/developit/htm/issues/226
return html`< dangerouslySetInnerHTML=${{ __html: parsed_markdown }}></>`;
}
export { html, md };