96 lines
2.7 KiB
JavaScript
96 lines
2.7 KiB
JavaScript
// 确保 MathJax 配置正确
|
|
window.MathJax = window.MathJax || {
|
|
loader: {
|
|
load: ['[tex]/ams', '[tex]/newcommand']
|
|
},
|
|
tex: {
|
|
inlineMath: [['$', '$'], ['\\(', '\\)']],
|
|
displayMath: [['$$', '$$'], ['\\[', '\\]']]
|
|
},
|
|
a11y: {
|
|
texHints: true,
|
|
screenReader: true,
|
|
mathml: {
|
|
enable: true,
|
|
},
|
|
label: {
|
|
enable: true,
|
|
texClass: 'MathJax-Label',
|
|
form: 'LaTeX'
|
|
}
|
|
},
|
|
svg: { fontCache: 'global' }
|
|
};
|
|
|
|
function stripLatexDelimiters(latex) {
|
|
return String(latex || '')
|
|
.trim()
|
|
.replace(/^\$\$/, '')
|
|
.replace(/\$\$$/, '')
|
|
.replace(/^\$/, '')
|
|
.replace(/\$$/, '')
|
|
.trim();
|
|
}
|
|
|
|
/** 按 data-wrap 选择行内 $ 或块级 $$ 分隔符 */
|
|
function buildLatexContentForRender(latex, wrapMode) {
|
|
const raw = stripLatexDelimiters(latex);
|
|
if (!raw) return '';
|
|
if (wrapMode === 'inline') {
|
|
return '$' + raw + '$';
|
|
}
|
|
return '$$' + raw + '$$';
|
|
}
|
|
|
|
function prepareWmathElement(element) {
|
|
const latexContent = element.getAttribute('data-latex');
|
|
if (!latexContent) return;
|
|
const wrap = element.getAttribute('data-wrap') || 'block';
|
|
element.innerHTML = buildLatexContentForRender(latexContent, wrap);
|
|
}
|
|
|
|
// **定义全局渲染方法**
|
|
window.renderMathJax = function (tinymceId) {
|
|
if (window.MathJax && typeof window.MathJax.typesetPromise === 'function') {
|
|
if (tinymceId) {
|
|
const editorInstance = window.tinymce.get(tinymceId);
|
|
if (!editorInstance) return;
|
|
|
|
const editorBody = editorInstance.getBody();
|
|
const wmathElements = editorBody.querySelectorAll('wmath');
|
|
|
|
if (wmathElements.length > 0) {
|
|
wmathElements.forEach((element) => {
|
|
prepareWmathElement(element);
|
|
window.MathJax.typesetPromise([element]).catch((err) => {
|
|
console.warn('TinyMCE MathJax 渲染失败:', err);
|
|
});
|
|
});
|
|
}
|
|
|
|
const mathElements = editorBody.querySelectorAll('math');
|
|
if (mathElements.length > 0) {
|
|
window.MathJax.typesetPromise(Array.from(mathElements)).catch((err) => {
|
|
console.warn('MathML 渲染失败:', err);
|
|
});
|
|
}
|
|
} else {
|
|
const wmathElements = document.querySelectorAll('wmath');
|
|
wmathElements.forEach((element) => {
|
|
prepareWmathElement(element);
|
|
window.MathJax.typesetPromise([element]).catch((err) => {
|
|
console.warn('MathJax 渲染失败:', err);
|
|
});
|
|
});
|
|
|
|
const mathElements = document.querySelectorAll('math');
|
|
mathElements.forEach((element) => {
|
|
window.MathJax.typesetPromise([element]).catch((err) => {
|
|
console.warn('MathJax 渲染失败:', err);
|
|
});
|
|
});
|
|
}
|
|
} else {
|
|
console.warn('MathJax 未正确加载!');
|
|
}
|
|
}; |