适配pjax加载markdown编辑器下的katex

This commit is contained in:
mjsoftware 2025-02-28 14:27:44 +08:00
parent b224a65fc6
commit e913d842fd
6 changed files with 40 additions and 18 deletions

View File

@ -4954,6 +4954,12 @@ button.swiper-pagination-bullet {
} }
} }
/* 文本绘图 */
text-diagram[data-type="mermaid"] {
display: flex ;
justify-content: center;
}
/* 友链界面 */ /* 友链界面 */
.links:not(.widget) { .links:not(.widget) {
margin-bottom: 20px; margin-bottom: 20px;

View File

@ -129,10 +129,11 @@ $(document).on('pjax:success', async function (event, data, status, xhr, options
$head.find('link[rel="canonical"]').remove() $head.find('link[rel="canonical"]').remove()
$head.append($currentTarget.filter('meta')) $head.append($currentTarget.filter('meta'))
$head.append($currentTarget.filter('link[rel="canonical"]')) $head.append($currentTarget.filter('link[rel="canonical"]'))
$currentTarget.filter('link').filter(function() { $currentTarget.filter('link').filter(function () {
const isDataPjax = $(this).is('[data-pjax]') const isDataPjax = $(this).is('[data-pjax]')
const href = $(this).attr('href') const href = $(this).attr('href')
const isStaticPath = href && (href.startsWith('/plugins/PluginHighlightJS/') || href.startsWith('/plugins/plugin-katex/')) const isStaticPath = href && (href.startsWith('/plugins/PluginHighlightJS/') ||
href.startsWith('/plugins/plugin-katex/'))
return isDataPjax || isStaticPath return isDataPjax || isStaticPath
}).each(function () { }).each(function () {
let href = $(this).attr('href') let href = $(this).attr('href')
@ -146,10 +147,11 @@ $(document).on('pjax:success', async function (event, data, status, xhr, options
} }
} }
}) })
let $scripts = $currentTarget.filter('script').filter(function() { let $scripts = $currentTarget.filter('script').filter(function () {
const isDataPjax = $(this).is('[data-pjax]') const isDataPjax = $(this).is('[data-pjax]')
const src = $(this).attr('src') const src = $(this).attr('src')
const isStaticPath = src && (src.startsWith('/plugins/PluginHighlightJS/')) const isStaticPath = src && (src.startsWith('/plugins/PluginHighlightJS/') ||
src.startsWith('/plugins/text-diagram/'))
return isDataPjax || isStaticPath return isDataPjax || isStaticPath
}) })
if ($scripts.length > 0) { if ($scripts.length > 0) {
@ -185,6 +187,8 @@ $(document).on('pjax:success', async function (event, data, status, xhr, options
window.postPjax && window.postPjax(serialNumber) window.postPjax && window.postPjax(serialNumber)
/* 初始化Katex */ /* 初始化Katex */
window.initKatex && window.initKatex() window.initKatex && window.initKatex()
/* 初始化Mermaid */
window.initMermaid && window.initMermaid()
/* 刷新人生倒计时 */ /* 刷新人生倒计时 */
commonContext.initTimeCount() commonContext.initTimeCount()
/* 初始化任务列表,禁止点击 */ /* 初始化任务列表,禁止点击 */

View File

@ -42,18 +42,18 @@ const postContext = {
} }
// 生成行号 // 生成行号
let codes = $(this).text().split('\n') || [] let codes = $(this).text().split('\n') || []
let nums = codes.length-1 let nums = codes.length - 1
let lineDigit = String(nums).length let lineDigit = String(nums).length
if (lineDigit === 1) lineDigit = 2 if (lineDigit === 1) lineDigit = 2
let lis = '' let lis = ''
for (var i = 0; i < nums; i++) { for (var i = 0; i < nums; i++) {
lis += `<li ${(lines && /^\s*\|\+\s+/.test(codes[i]))? 'class="code-select"' : ''}>${String(i + 1).padStart(lineDigit, 0)}</li>` lis += `<li ${(lines && /^\s*\|\+\s+/.test(codes[i])) ? 'class="code-select"' : ''}>${String(i + 1).padStart(lineDigit, 0)}</li>`
} }
if (codes[nums].trim() !== '') { if (codes[nums].trim() !== '') {
lis += `<li ${(lines && /^\s*\|\+\s+/.test(codes[i]))? 'class="code-select"' : ''}>${String(nums + 1).padStart(lineDigit, 0)}</li>` lis += `<li ${(lines && /^\s*\|\+\s+/.test(codes[i])) ? 'class="code-select"' : ''}>${String(nums + 1).padStart(lineDigit, 0)}</li>`
} }
if (lines) { if (lines) {
$(this).text($(this).text().replace(/(^\s*)\|\+\s/gm,'$1')) $(this).text($(this).text().replace(/(^\s*)\|\+\s/gm, '$1'))
} }
// 代码块的id用于代码块复制和折叠 // 代码块的id用于代码块复制和折叠
let id = `codeBlock${index}-${new Date().getTime()}` let id = `codeBlock${index}-${new Date().getTime()}`
@ -92,7 +92,7 @@ const postContext = {
/* 代码块高亮 */ /* 代码块高亮 */
initHighlighting() { initHighlighting() {
// 初始化代码块高亮工具 // 初始化代码块高亮工具
if(typeof hljs !== 'undefined' && hljs !== null) { if (typeof hljs !== 'undefined' && hljs !== null) {
document.querySelectorAll('code[data-highlighted="yes"]').forEach(element => { document.querySelectorAll('code[data-highlighted="yes"]').forEach(element => {
element.removeAttribute('data-highlighted') element.removeAttribute('data-highlighted')
}) })
@ -101,8 +101,8 @@ const postContext = {
} }
}, },
/** /**
* 初始化分享 * 初始化分享
*/ */
initShare() { initShare() {
if (!window.DShare) return if (!window.DShare) return
let imageUrl = $('.cover-image').css('background-image') let imageUrl = $('.cover-image').css('background-image')
@ -206,11 +206,23 @@ window.initKatex = function () {
console.log('katex is not defined') console.log('katex is not defined')
return return
} }
$mainContent.find('[math-inline]').each(function (index, domEle) { $mainContent.find('[math-inline], .math-inline, .katex--inline').each(function (index, domEle) {
katex.render(domEle.innerText, domEle, { displayMode: false }) katex.render(domEle.innerText, domEle, {displayMode: false})
}) })
$mainContent.find('[math-display]').each(function (index, domEle) { $mainContent.find('[math-display], .math-display, .katex--display').each(function (index, domEle) {
katex.render(domEle.innerText, domEle, { displayMode: true }) katex.render(domEle.innerText, domEle, {displayMode: true})
})
}
// 初始化Mermaid
window.initMermaid = function () {
if (typeof mermaid === 'undefined' || mermaid === null) {
return
}
const postBody = document.body
mermaid.initialize({startOnLoad: true})
mermaid.run({
querySelector: 'text-diagram[data-type=mermaid]',
}) })
} }

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
(()=>{let i=!1;const a={initCodeBlock(){var e=$("*:not(figure) > pre > code");0!==e.length&&e.each(function(e){var i=$(this).parent();let t=$(this).attr("class"),n="",a=!1,o=!1;if(null!=t){var l=t.match(/[|<](.*)$/),r=t.match(/:select/);if(l||r){let e=0;r&&(e=r.index,l?l[1].endsWith(r[0])&&(l[1]=l[1].substring(0,l[1].length-r[0].length)):n=t.substring(9,r.index),a=!0),l&&(e=l.index<e?l.index:e,"<"===l[0][0]&&(o=!0),n=l[1]),$(this).attr("class",t.substring(0,e)),n=n||t.substring(9,e)}else n=t.substring(9)}let s=$(this).text().split("\n")||[],d=s.length-1,c=String(d).length,h=(1===c&&(c=2),"");for(var g=0;g<d;g++)h+=`<li ${a&&/^\s*\|\+\s+/.test(s[g])?'class="code-select"':""}>${String(g+1).padStart(c,0)}</li>`;""!==s[d].trim()&&(h+=`<li ${a&&/^\s*\|\+\s+/.test(s[g])?'class="code-select"':""}>${String(1+d).padStart(c,0)}</li>`),a&&$(this).text($(this).text().replace(/(^\s*)\|\+\s/gm,"$1"));let p=`codeBlock${e}-`+(new Date).getTime(),u="";o&&(u=" close",$(this).parent().hide());r=`<div><i class="ri-arrow-down-s-line${u}" data-code='#${p}'></i><i class="ri-file-copy-2-line btn-clipboard" title="复制代码" data-clipboard-target='#${p}'></i></div>`;$(this).attr("id",p),i.prepend(`<ul>${h}</ul>`),d>DreamConfig.code_fold_line?i.wrap('<figure class="fold hljs"></figure>').append('<div class="expand-done"><i class="ri-arrow-up-double-line"></i></div>'):i.wrap('<figure class="hljs"></figure>'),i.parent().prepend(`<figcaption>${n}${r}</figcaption>`)})},initLiterature(){$(".literature-content>p:not([class]),.literature-content>mew-hide>p:not([class])").each(function(){0===$(this).children(":not(code,a,strong,em,ins,b,s,br,span.pwd)").length&&$(this).addClass("note")})},initLike(){Utils.initLikeButton(".admire .agree.like","posts")},initHighlighting(){"undefined"!=typeof hljs&&null!==hljs&&(document.querySelectorAll('code[data-highlighted="yes"]').forEach(e=>{e.removeAttribute("data-highlighted")}),hljs.highlightAll())},initShare(){if(window.DShare){let e=$(".cover-image").css("background-image");e=e&&e.substring(5,e.length-2),DShare.create(".dshare",{image:e,imageSelector:".main-content"})}},initClipboard(){window.clipboard||(window.clipboard=new ClipboardJS(".btn-clipboard"),clipboard.on("error",function(e){e.clearSelection(),Qmsg.error("您的浏览器不支持复制")}),clipboard.on("success",function(){Qmsg.success("复制成功")}))},foldImage(){var e;DreamConfig.img_fold_height&&((e=$(".article .gallery-item>[data-fancybox]>img")).parent().addClass("fold"),e.each(function(){const e=$(this).parent();this.complete?this.scrollHeight>=DreamConfig.img_fold_height?e.append('<div class="expand-done"><i class="ri-arrow-up-double-line"></i></div>'):e.removeClass("fold"):this.onload=function(){this.scrollHeight>=DreamConfig.img_fold_height?e.append('<div class="expand-done"><i class="ri-arrow-up-double-line"></i></div>'):e.removeClass("fold")}}))},initEvent(){var e;i||((e=$("body")).on("click","figure>figcaption .ri-arrow-down-s-line",function(){var e=$(this);e.is(".close")?($(e.attr("data-code")).parent().slideDown(200),e.removeClass("close")):($(e.attr("data-code")).parent().slideUp(200),e.addClass("close"))}),e.on("click","figure > pre > .expand-done",function(){Utils.foldBlock($(this).parent().parent())}),e.on("click",".gallery-item .expand-done",function(e){e.stopPropagation(),Utils.foldBlock($(this).parent())}),Utils.initLikeEvent(".admire .agree.like","posts",e=>e.find("span").find("span")),window.onCommentSuccessEvent=(e,i)=>{var t=encrypt("mew-hide-"+i),n=(n=localStorage.getItem(t))?JSON.parse(decrypt(n)):[],e=String(e.postId);n.includes(e)||(n.push(e),$(`.main-content[data-target='${i}'][data-id='${e}'] mew-hide[hide]`).each(function(){$(this).before(decrypt(this.getAttribute("hide"))),$(this).remove(),commonContext.initGallery(),a.initCodeBlock(),a.initLiterature(),a.initHighlighting(),"true"===this.getAttribute("toc")&&commonContext.initTocAndNotice()}),localStorage.setItem(t,encrypt(JSON.stringify(n))))},i=!0)}};window.initKatex=function(){var e=$(".main-content");"undefined"!=typeof katex&&null!==katex&&0!==e.length?(e.find("[math-inline]").each(function(e,i){katex.render(i.innerText,i,{displayMode:!1})}),e.find("[math-display]").each(function(e,i){katex.render(i.innerText,i,{displayMode:!0})})):console.log("katex is not defined")},window.postPjax=function(i){0!==$(".main-content").length&&Object.keys(a).forEach(e=>window.pjaxSerialNumber===i&&a[e]())};{const t=["initEvent","initCodeBlock","initLiterature","initLike","foldImage"];Object.keys(a).forEach(e=>!window.pjaxSerialNumber&&t.includes(e)&&a[e]()),document.addEventListener("DOMContentLoaded",function(){Object.keys(a).forEach(e=>!window.pjaxSerialNumber&&!t.includes(e)&&a[e]())})}})(); (()=>{let i=!1;const a={initCodeBlock(){var e=$("*:not(figure) > pre > code");0!==e.length&&e.each(function(e){var i=$(this).parent();let t=$(this).attr("class"),n="",a=!1,o=!1;if(null!=t){var r=t.match(/[|<](.*)$/),l=t.match(/:select/);if(r||l){let e=0;l&&(e=l.index,r?r[1].endsWith(l[0])&&(r[1]=r[1].substring(0,r[1].length-l[0].length)):n=t.substring(9,l.index),a=!0),r&&(e=r.index<e?r.index:e,"<"===r[0][0]&&(o=!0),n=r[1]),$(this).attr("class",t.substring(0,e)),n=n||t.substring(9,e)}else n=t.substring(9)}let s=$(this).text().split("\n")||[],d=s.length-1,c=String(d).length,h=(1===c&&(c=2),"");for(var g=0;g<d;g++)h+=`<li ${a&&/^\s*\|\+\s+/.test(s[g])?'class="code-select"':""}>${String(g+1).padStart(c,0)}</li>`;""!==s[d].trim()&&(h+=`<li ${a&&/^\s*\|\+\s+/.test(s[g])?'class="code-select"':""}>${String(1+d).padStart(c,0)}</li>`),a&&$(this).text($(this).text().replace(/(^\s*)\|\+\s/gm,"$1"));let p=`codeBlock${e}-`+(new Date).getTime(),u="";o&&(u=" close",$(this).parent().hide());l=`<div><i class="ri-arrow-down-s-line${u}" data-code='#${p}'></i><i class="ri-file-copy-2-line btn-clipboard" title="复制代码" data-clipboard-target='#${p}'></i></div>`;$(this).attr("id",p),i.prepend(`<ul>${h}</ul>`),d>DreamConfig.code_fold_line?i.wrap('<figure class="fold hljs"></figure>').append('<div class="expand-done"><i class="ri-arrow-up-double-line"></i></div>'):i.wrap('<figure class="hljs"></figure>'),i.parent().prepend(`<figcaption>${n}${l}</figcaption>`)})},initLiterature(){$(".literature-content>p:not([class]),.literature-content>mew-hide>p:not([class])").each(function(){0===$(this).children(":not(code,a,strong,em,ins,b,s,br,span.pwd)").length&&$(this).addClass("note")})},initLike(){Utils.initLikeButton(".admire .agree.like","posts")},initHighlighting(){"undefined"!=typeof hljs&&null!==hljs&&(document.querySelectorAll('code[data-highlighted="yes"]').forEach(e=>{e.removeAttribute("data-highlighted")}),hljs.highlightAll())},initShare(){if(window.DShare){let e=$(".cover-image").css("background-image");e=e&&e.substring(5,e.length-2),DShare.create(".dshare",{image:e,imageSelector:".main-content"})}},initClipboard(){window.clipboard||(window.clipboard=new ClipboardJS(".btn-clipboard"),clipboard.on("error",function(e){e.clearSelection(),Qmsg.error("您的浏览器不支持复制")}),clipboard.on("success",function(){Qmsg.success("复制成功")}))},foldImage(){var e;DreamConfig.img_fold_height&&((e=$(".article .gallery-item>[data-fancybox]>img")).parent().addClass("fold"),e.each(function(){const e=$(this).parent();this.complete?this.scrollHeight>=DreamConfig.img_fold_height?e.append('<div class="expand-done"><i class="ri-arrow-up-double-line"></i></div>'):e.removeClass("fold"):this.onload=function(){this.scrollHeight>=DreamConfig.img_fold_height?e.append('<div class="expand-done"><i class="ri-arrow-up-double-line"></i></div>'):e.removeClass("fold")}}))},initEvent(){var e;i||((e=$("body")).on("click","figure>figcaption .ri-arrow-down-s-line",function(){var e=$(this);e.is(".close")?($(e.attr("data-code")).parent().slideDown(200),e.removeClass("close")):($(e.attr("data-code")).parent().slideUp(200),e.addClass("close"))}),e.on("click","figure > pre > .expand-done",function(){Utils.foldBlock($(this).parent().parent())}),e.on("click",".gallery-item .expand-done",function(e){e.stopPropagation(),Utils.foldBlock($(this).parent())}),Utils.initLikeEvent(".admire .agree.like","posts",e=>e.find("span").find("span")),window.onCommentSuccessEvent=(e,i)=>{var t=encrypt("mew-hide-"+i),n=(n=localStorage.getItem(t))?JSON.parse(decrypt(n)):[],e=String(e.postId);n.includes(e)||(n.push(e),$(`.main-content[data-target='${i}'][data-id='${e}'] mew-hide[hide]`).each(function(){$(this).before(decrypt(this.getAttribute("hide"))),$(this).remove(),commonContext.initGallery(),a.initCodeBlock(),a.initLiterature(),a.initHighlighting(),"true"===this.getAttribute("toc")&&commonContext.initTocAndNotice()}),localStorage.setItem(t,encrypt(JSON.stringify(n))))},i=!0)}};window.initKatex=function(){var e=$(".main-content");"undefined"!=typeof katex&&null!==katex&&0!==e.length?(e.find("[math-inline], .math-inline, .katex--inline").each(function(e,i){katex.render(i.innerText,i,{displayMode:!1})}),e.find("[math-display], .math-display, .katex--display").each(function(e,i){katex.render(i.innerText,i,{displayMode:!0})})):console.log("katex is not defined")},window.initMermaid=function(){"undefined"!=typeof mermaid&&null!==mermaid&&(document.body,mermaid.initialize({startOnLoad:!0}),mermaid.run({querySelector:"text-diagram[data-type=mermaid]"}))},window.postPjax=function(i){0!==$(".main-content").length&&Object.keys(a).forEach(e=>window.pjaxSerialNumber===i&&a[e]())};{const t=["initEvent","initCodeBlock","initLiterature","initLike","foldImage"];Object.keys(a).forEach(e=>!window.pjaxSerialNumber&&t.includes(e)&&a[e]()),document.addEventListener("DOMContentLoaded",function(){Object.keys(a).forEach(e=>!window.pjaxSerialNumber&&!t.includes(e)&&a[e]())})}})();