-
-
Notifications
You must be signed in to change notification settings - Fork 374
/
highlight.js
87 lines (80 loc) · 2.32 KB
/
highlight.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
/**
* Module core/highlight
*
* Performs syntax highlighting to all pre and code elements.
*/
import { pub, sub } from "core/pubsubhub";
import utils from "core/utils";
import { worker } from "core/worker";
import ghCss from "deps/text!core/css/github.css";
export const name = "core/highlight";
// Opportunistically insert the style into the head to reduce FOUC.
var codeStyle = document.createElement("style");
codeStyle.textContent = ghCss;
var swapStyleOwner = utils.makeOwnerSwapper(codeStyle);
swapStyleOwner(document.head);
function getLanguageHint(classList) {
return Array
.from(classList)
.filter(item => item !== "highlight")
.map(item => item.toLowerCase());
}
let doneResolver;
let doneRejector;
export const done = new Promise((resolve, reject) => {
doneResolver = resolve;
doneRejector = reject;
});
export async function run(conf, doc, cb) {
// Nothing to do
if (conf.noHighlightCSS) {
doneResolver();
return cb();
}
if (codeStyle.ownerDocument !== doc) {
swapStyleOwner(doc.head);
}
if (doc.querySelector(".highlight")) {
pub("warn", "pre elements don't need a 'highlight' class anymore.");
}
const promisesToHighlight = Array
.from(
doc.querySelectorAll("pre:not(.idl):not(.highlightdone)")
)
.map(element => {
return new Promise((resolve, reject) => {
if (element.textContent.trim() === "") {
return resolve(); // no work to do
}
const msg = {
action: "highlight",
code: element.textContent,
id: Math.random().toString(),
languages: getLanguageHint(element.classList),
};
worker.postMessage(msg);
worker.addEventListener("message", function listener(ev) {
if (ev.data.id !== msg.id) {
return; // not for us!
}
worker.removeEventListener("message", listener);
element.innerHTML = ev.data.value;
element.classList.add("hljs");
resolve();
});
setTimeout(() => {
const errMsg = "Timeout error trying to process: " + msg.code;
const err = new Error(errMsg);
reject(err);
}, 5000);
});
});
try {
await Promise.all(promisesToHighlight);
doneResolver();
} catch (err) {
console.error(err);
doneRejector(err);
}
cb();
}