generated from ArnavK-09/gitpod-deno-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.ts
79 lines (74 loc) · 2.43 KB
/
plugin.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
/**
* Imports required */
import { glow } from "npm:nue-glow";
import type { Page, Plugin, Site } from "https://deno.land/x/lume/core.ts";
/**
* Plugin Options
*/
export interface Options {
/**
* tells glow the language of the code. This is optional. When not provided, glow attempts to guess the language.
*/
language?: string;
/**
* is a boolean flag indicating whether line numbers should be rendered
*/
numbered?: boolean;
/**
* configure package size for glow styles
*/
size?: "nano" | "default";
}
/**
* Hosted Links for Glow css
*/
const LINKS = {
default:
"https://raw.githubusercontent.com/nuejs/nue/master/packages/glow/minified/glow.css",
nano: "https://raw.githubusercontent.com/nuejs/nue/master/packages/glow/minified/glow.nano.css",
};
/**
* A plugin to glow your code
*/
export default function (userOptions?: Options): Plugin {
return (site: Site) => {
site.process([".html"], processCodeHighlight);
async function processCodeHighlight(pages: Page[]) {
for (const page of pages) {
const allCodeBlocks: HTMLElement[] = Array.from(
page.document.getElementsByTagName("code"),
);
// markup all codeblocks
allCodeBlocks.forEach((element: HTMLElement) => {
try {
let language;
if (Array.from(element.classList)[0]?.includes("language-")) {
language = element.classList[0].replace("language-", "");
}
if (element.parentElement?.tagName == "PRE") {
element.parentElement!.setAttribute("glow", "");
element.parentElement!.innerHTML = glow(element.innerText, {
language: userOptions?.language ?? language,
numbered: userOptions?.numbered,
});
}
} catch (error) {
console.log(
`Error glowing code block in ${page.sourcePath}: ${error}`,
);
}
});
// add glow styles to page
if (Array.from(allCodeBlocks).length !== 0) {
const stylesheet =
userOptions?.size == "nano" ? LINKS.nano : LINKS.default;
const src = await fetch(stylesheet);
const css = await src.text();
const tag = page.document.createElement("style");
tag.innerHTML = css + `pre { overflow-x: auto }`;
page.document.getElementsByTagName("head")[0].appendChild(tag);
}
}
}
};
}