-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
94 lines (90 loc) · 2.19 KB
/
index.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
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
92
93
94
import Showdown from "showdown";
import * as shiki from "shiki";
/**
*
* @param {string} encodedString
* @returns {string}
*/
function decodeHtml(encodedString) {
var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
var translate = {
nbsp: " ",
amp: "&",
quot: '"',
lt: "<",
gt: ">",
};
return encodedString
.replace(translate_re, function (match, entity) {
return translate[entity];
})
.replace(/&#(\d+);/gi, function (match, numStr) {
var num = parseInt(numStr, 10);
return String.fromCharCode(num);
});
}
//------------------------------------------
const hlter = await shiki.createHighlighter({
langs: Object.keys(shiki.bundledLanguages),
themes: Object.keys(shiki.bundledThemes),
});
/**
*
* @param {string} code
* @param {import("shiki").BuiltinLanguage} lang
* @param {import("./index").Themes} themes
* @returns {string}
*/
function shikiHL(code, lang, themes) {
if (themes && themes.darkMode) {
const dk = themes.theme?.dark ?? "github-dark";
const lg = themes.theme?.light ?? "github-light";
return hlter.codeToHtml(code, {
lang: lang,
themes: { light: lg, dark: dk },
});
}
const df = themes?.theme ?? "github-light";
return hlter.codeToHtml(code, {
lang: lang,
theme: df,
});
}
/**
*
* @param {import("./index").Options} [opts]
* @returns {Showdown.ShowdownExtension | Showdown.ShowdownExtension[]}
*/
function showdownShiki(opts) {
function filter(text, converter, options) {
const params = {
left: "<pre><code\\b[^>]*>",
right: "</code></pre>",
flags: "g",
};
function replacement(wholeMatch, match, left, right) {
const _match = decodeHtml(match);
const regex = /class=\"([^ \"]+)/;
const lan = left.match(regex)?.[1] || "";
if (!lan || lan === "") {
return wholeMatch;
}
return shikiHL(_match, lan, opts?.themes);
}
return Showdown.helper.replaceRecursiveRegExp(
text,
replacement,
params.left,
params.right,
params.flags
);
}
return [
{
type: "output",
filter: filter,
},
];
}
Showdown.extension("showdown-shiki", showdownShiki);
export default showdownShiki;