-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmark-down.js
executable file
·58 lines (44 loc) · 1.39 KB
/
mark-down.js
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
import { useShowdown as useConverter } from './use-showdown.js'
class MarkDown extends HTMLElement {
constructor() {
super();
this.loading = true;
this.setupShadow()
}
setupShadow() {
this.attachShadow({ mode: 'open' });
const template = document.createElement('template');
template.innerHTML = `
<slot> <!-- MD-IN --> </slot>
<div part="html-out"></div>
`;
this.shadowRoot.appendChild(template.content);
}
connectedCallback() {
const slot = this.shadowRoot.querySelector('slot');
slot.addEventListener('slotchange', this.onSlotChange);
if (slot.assignedNodes().length) this.convertContent();
}
onSlotChange = () => {
if (this.loading) {
console.warn('[mark-down] onSlotChange: skipping convertion in loading state.')
return
}
console.info('[mark-down] onSlotChange: converting new content.')
this.convertContent()
}
convertContent() {
const slot = this.shadowRoot.querySelector('slot');
const div = this.shadowRoot.querySelector('div');
const [_, convert] = useConverter();
this.loading = true;
let md = "";
for (const node of slot.assignedNodes()) {
md += node.nodeName === '#text' ? node.textContent : node.innerHTML;
}
slot.style = 'display: none;';
div.innerHTML = convert(md);
this.loading = false;
}
}
customElements.define("mark-down", MarkDown);