109 lines
3.0 KiB
JavaScript
109 lines
3.0 KiB
JavaScript
// 确保 MathJax 配置正确
|
||
window.MathJax = window.MathJax || {
|
||
loader: {
|
||
load: ['[tex]/ams', '[tex]/newcommand']
|
||
},
|
||
tex: {
|
||
inlineMath: [['$', '$'], ['\\(', '\\)']],
|
||
displayMath: [['$$', '$$'], ['\\[', '\\]']]
|
||
},
|
||
a11y: {
|
||
// 启用 MathJax 可访问性功能,确保使用 aria-label
|
||
texHints: true,
|
||
screenReader: true,
|
||
mathml: {
|
||
enable: true,
|
||
},
|
||
label: {
|
||
// 公式的 aria-label 配置
|
||
enable: true,
|
||
texClass: 'MathJax-Label',
|
||
form: 'LaTeX'
|
||
}
|
||
},
|
||
svg: { fontCache: 'global' }
|
||
};
|
||
|
||
// **定义全局渲染方法**
|
||
window.renderMathJax = function (tinymceId) {
|
||
if (window.MathJax && typeof window.MathJax.typesetPromise === "function") {
|
||
// console.log("正在渲染 MathJax 公式...");
|
||
|
||
// 如果提供了 TinyMCE 编辑器 ID
|
||
if (tinymceId) {
|
||
const editorInstance = window.tinymce.get(tinymceId); // 根据 ID 获取 TinyMCE 实例
|
||
if (!editorInstance) return;
|
||
|
||
const editorBody = editorInstance.getBody();
|
||
|
||
// 获取所有 <wmath> 元素
|
||
const wmathElements = editorBody.querySelectorAll('wmath');
|
||
|
||
if (wmathElements.length > 0) {
|
||
wmathElements.forEach((element) => {
|
||
const latexContent = element.getAttribute('data-latex');
|
||
if (latexContent) {
|
||
// 将公式内容填入标签内部
|
||
element.innerHTML = latexContent;
|
||
|
||
// 使用 MathJax 渲染该元素
|
||
window.MathJax.typesetPromise([element]).catch((err) => {
|
||
console.warn("TinyMCE MathJax 渲染失败:", err);
|
||
});
|
||
}
|
||
});
|
||
}
|
||
|
||
// 渲染 <math>(MathML)标签,如果有的话
|
||
const mathElements = editorBody.querySelectorAll('math');
|
||
if (mathElements.length > 0) {
|
||
window.MathJax.typesetPromise(Array.from(mathElements)).catch((err) => {
|
||
console.warn("MathML 渲染失败:", err);
|
||
});
|
||
}
|
||
}
|
||
else {
|
||
// 处理全局文档中的 <wmath> 标签
|
||
const wmathElements = document.querySelectorAll('wmath');
|
||
wmathElements.forEach((element) => {
|
||
// 检查 <wmath> 标签是否包含有效的 data-latex 属性值
|
||
const latexContent = element.getAttribute('data-latex');
|
||
if (latexContent) {
|
||
// 将元素的内部内容替换为 data-latex 的值
|
||
element.innerHTML = latexContent;
|
||
|
||
// 渲染 MathJax 公式
|
||
window.MathJax.typesetPromise([element]).catch((err) => {
|
||
console.warn("MathJax 渲染失败:", err);
|
||
});
|
||
}
|
||
});
|
||
|
||
// 处理全局文档中的 <math> 标签(MathML 内容)
|
||
const mathElements = document.querySelectorAll('math');
|
||
mathElements.forEach((element) => {
|
||
// 渲染 MathJax 公式
|
||
window.MathJax.typesetPromise([element]).catch((err) => {
|
||
console.warn("MathJax 渲染失败:", err);
|
||
});
|
||
});
|
||
}
|
||
|
||
} else {
|
||
console.warn("MathJax 未正确加载!");
|
||
}
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|