From 58380da0aec43d535e2a77507d585e19e4eb9198 Mon Sep 17 00:00:00 2001 From: neo Date: Fri, 15 Nov 2019 01:35:56 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0highlight=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- wp-heightlight.js | 107 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 wp-heightlight.js diff --git a/wp-heightlight.js b/wp-heightlight.js new file mode 100644 index 0000000..01e1972 --- /dev/null +++ b/wp-heightlight.js @@ -0,0 +1,107 @@ +/*! + * WordPress highlight + * https://github.com/ineo6/wordpress-highlight + */ + +(function ($) { + function initHighlight() { + function createBar(i) { + var attributes = { + 'autocomplete': 'off', + 'autocorrect': 'off', + 'autocapitalize': 'off', + 'spellcheck': 'false', + 'contenteditable': 'false', + }; + var codeCls = $('pre:eq(' + i + ')')[0].children[0].className; + + var result = codeCls.match(/language-(\w+)/); + + var lang = "text"; + + if (result && result.length) { + lang = result[1]; + } + + $('pre:eq(' + i + ')').addClass('highlight-wrap'); + for (var t in attributes) { + $('pre:eq(' + i + ')').attr(t, attributes[t]); + } + $('pre:eq(' + i + ') code').attr('data-rel', lang.toUpperCase()).attr({id: "highlight-code-" + i}) + .after('复制'); + } + + function highlight_code_worker_function() { + importScripts('https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.16.2/build/highlight.min.js'); + + onmessage = function (event) { + var data = JSON.parse(event.data); + + var result = self.hljs.highlightAuto(data.code); + + postMessage(JSON.stringify({result: result.value, index: data.index})); + }; + } + + // 使用 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); + + codeBlocks[highlightData.index].innerHTML = highlightData.result; + createBar(highlightData.index); + + new ClipboardJS('.copy-code'); + + 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, + 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(); + } + } + + $(document).ready(function () { + initHighlight(); + }); +})(jQuery);