UNPKG

1.88 kBJavaScriptView Raw
1(function () {
2
3 if (typeof Prism === 'undefined' || typeof document === 'undefined') {
4 return;
5 }
6
7 // https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
8 if (!Element.prototype.matches) {
9 Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
10 }
11
12
13 Prism.plugins.UnescapedMarkup = true;
14
15 Prism.hooks.add('before-highlightall', function (env) {
16 env.selector += ', [class*="lang-"] script[type="text/plain"]'
17 + ', [class*="language-"] script[type="text/plain"]'
18 + ', script[type="text/plain"][class*="lang-"]'
19 + ', script[type="text/plain"][class*="language-"]';
20 });
21
22 Prism.hooks.add('before-sanity-check', function (env) {
23 /** @type {HTMLElement} */
24 var element = env.element;
25
26 if (element.matches('script[type="text/plain"]')) {
27 // found a <script type="text/plain" ...> element
28 // we convert this element to a regular <pre><code> code block
29
30 var code = document.createElement('code');
31 var pre = document.createElement('pre');
32
33 // copy class name
34 pre.className = code.className = element.className;
35
36 // copy all "data-" attributes
37 var dataset = element.dataset;
38 Object.keys(dataset || {}).forEach(function (key) {
39 if (Object.prototype.hasOwnProperty.call(dataset, key)) {
40 pre.dataset[key] = dataset[key];
41 }
42 });
43
44 code.textContent = env.code = env.code.replace(/&lt;\/script(?:>|&gt;)/gi, '</scri' + 'pt>');
45
46 // change DOM
47 pre.appendChild(code);
48 element.parentNode.replaceChild(pre, element);
49 env.element = code;
50 return;
51 }
52
53 if (!env.code) {
54 // no code
55 var childNodes = element.childNodes;
56 if (childNodes.length === 1 && childNodes[0].nodeName == '#comment') {
57 // the only child is a comment -> use the comment's text
58 element.textContent = env.code = childNodes[0].textContent;
59 }
60 }
61 });
62}());