highlight/wp-heightlight.js

105 lines
3.1 KiB
JavaScript
Raw Normal View History

2019-11-15 01:35:56 +08:00
/*!
* WordPress highlight
* https://github.com/ineo6/wordpress-highlight
*/
(function ($) {
function initHighlight() {
2019-11-18 18:12:37 +08:00
function getLang(codeCls) {
var result = codeCls.match(/language-(\w+)/);
var lang = "plaintext";
if (result && result.length) {
lang = result[1];
}
if (lang === "text") {
lang = "plaintext";
}
return lang;
}
2019-11-15 01:35:56 +08:00
function createBar(i) {
var attributes = {
'autocomplete': 'off',
'autocorrect': 'off',
'autocapitalize': 'off',
'spellcheck': 'false',
'contenteditable': 'false',
};
var codeCls = $('pre:eq(' + i + ')')[0].children[0].className;
$('pre:eq(' + i + ')').addClass('highlight-wrap');
for (var t in attributes) {
$('pre:eq(' + i + ')').attr(t, attributes[t]);
}
2019-11-18 18:12:37 +08:00
$('pre:eq(' + i + ') code').addClass('hljs').attr('data-rel', getLang(codeCls).toUpperCase()).attr({id: "highlight-code-" + i})
2019-11-15 01:35:56 +08:00
.after('<a class="copy-code" data-clipboard-target="#highlight-code-' + i + '" title="拷贝代码">复制</a>');
}
// 使用 web worker
function highlightWorker() {
var codeBlocks = document.querySelectorAll('pre code');
if (window.theme_url) {
var worker = new Worker(window.theme_url + '/js/highlight-worker.js');
} else {
return false;
}
worker.onmessage = (event) => {
var highlightData = JSON.parse(event.data);
2019-11-18 18:12:37 +08:00
codeBlocks[highlightData.index].innerHTML = highlightData.result.value;
2019-11-15 01:35:56 +08:00
createBar(highlightData.index);
if (highlightData.index === codeBlocks.length - 1) {
// 结束关闭worker
worker.terminate();
hljs.initLineNumbersOnLoad({
singleLine: true
});
}
};
codeBlocks.forEach(function (block, index) {
worker.postMessage(JSON.stringify({
code: block.textContent,
2019-11-18 18:12:37 +08:00
lang: getLang(block.className),
2019-11-15 01:35:56 +08:00
index,
total: codeBlocks.length,
}));
})
}
function highlightNormal() {
$('pre code').each(function (i, block) {
hljs.highlightBlock(block);
});
for (var i = 0, len = $('pre').length; i < len; i++) {
createBar(i);
}
// 代码行数
hljs.initLineNumbersOnLoad({
singleLine: true
});
}
if (typeof (Worker) === undefined) {
highlightNormal();
} else {
highlightWorker();
}
2019-11-18 18:12:37 +08:00
new ClipboardJS('.copy-code');
2019-11-15 01:35:56 +08:00
}
$(document).ready(function () {
initHighlight();
});
})(jQuery);