forked from CodeYourFuture/CYF-Workshops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
readme.js
56 lines (51 loc) · 1.5 KB
/
readme.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
class ReadmeComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.path = this.getAttribute("path") || "readme";
}
connectedCallback() {
this.path = this.getAttribute("path") || "readme";
this.loadScript(
"https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.1/showdown.min.js"
).then(() => {
this.fetchReadme();
});
}
loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.src = src;
script.onload = () => resolve(script);
script.onerror = (error) =>
reject(new Error(`Script load error: ${error}`));
document.head.append(script);
});
}
async fetchReadme() {
try {
const response = await fetch(
`https://api.github.com/repos/CodeYourFuture/CYF-Workshops/${this.path}`
);
if (!response.ok) {
console.error("Failed to fetch README: " + response.status);
return;
}
const json = await response.json();
const decodedContent = atob(json.content);
this.render(decodedContent);
} catch (error) {
console.error(error);
}
}
render(md) {
try {
let converter = new showdown.Converter();
let html = converter.makeHtml(md);
this.shadowRoot.innerHTML = `${html}`;
} catch (error) {
console.error("Failed to convert markdown to HTML: " + error);
}
}
}
customElements.define("readme-component", ReadmeComponent);