-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkdown.ts
91 lines (79 loc) · 2.4 KB
/
markdown.ts
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
84
85
86
87
88
89
90
91
import { marked, Renderer } from "https://esm.sh/[email protected]";
export { embedMarkdownFromGithub };
async function fetchMarkdownFromGithub(
repoOwner: string,
repoName: string,
filePath: string
): Promise<string> {
const fileUrl = `https://raw.githubusercontent.com/${repoOwner}/${repoName}/${filePath}`;
const response = await fetch(fileUrl);
if (!response.ok) {
throw new Error(`Error fetching Markdown file: ${response.statusText}`);
}
return await response.text();
}
function createMarkdownToHtmlConverter(
repoOwner: string,
repoName: string
): (markdown: string) => string {
const renderer = new Renderer({});
const buildAbsoluteGithubUrl = (
repoOwner: string,
repoName: string,
href: string
) => {
const isAbsolutePath = href.startsWith("/");
const isRelativePath = !href.startsWith("http") && !isAbsolutePath;
const baseUrl = `https://raw.githubusercontent.com/${repoOwner}/${repoName}/main`;
if (isAbsolutePath) {
return `${baseUrl}${href}`;
} else if (isRelativePath) {
return `${baseUrl}/${href}`;
}
return href;
};
renderer.link = (href, title, text) => {
href = buildAbsoluteGithubUrl(repoOwner, repoName, href);
title = title ? ` title="${title}"` : "";
return `<a href="${href}"${title}>${text}</a>`;
};
renderer.image = (src, title, alt) => {
src = buildAbsoluteGithubUrl(repoOwner, repoName, src);
title = title ? ` title="${title}"` : "";
alt = alt ? ` alt="${alt}"` : "";
return `<img src="${src}"${alt}${title}>`;
};
return (markdown: string) => {
return marked(markdown, { renderer });
};
}
function embedHtmlContent(html: string, containerId: string): void {
const container = document.getElementById(containerId);
if (container) {
container.innerHTML = html;
} else {
console.error(`Container with ID "${containerId}" not found.`);
}
}
async function embedMarkdownFromGithub(
repoOwner: string,
repoName: string,
filePath: string,
containerId: string
): Promise<void> {
try {
const markdown = await fetchMarkdownFromGithub(
repoOwner,
repoName,
filePath
);
const convertMarkdownToHtml = createMarkdownToHtmlConverter(
repoOwner,
repoName
);
const html = convertMarkdownToHtml(markdown);
embedHtmlContent(html, containerId);
} catch (error) {
console.error(`Error embedding Markdown: ${error.message}`);
}
}