Compare commits

..

2 Commits

Author SHA1 Message Date
小能饼干 fb10876842
Merge pull request #21 from aisahpA/master 2025-05-04 20:30:57 +08:00
kadimi c857dde4c3 perf:优化代码
1、配置 typographer 为 false,不转换 (C)、(R)、(TM)
2、配置 delimiters 为 ['dollars'],只支持$符号包裹的数学公式, \( 和 \[ 使用 Anki 原本的解析
3、配置 katexOptions 的 throwOnError 为 true,页面上展示解析异常的数学公式
4、将 Anki 已转成 HTML 的数学公式替换掉,不参与 Markdown 转换
5、日志信息不放在 body 最后,避免切换到其他模版时,无法清除里面的内容
2025-05-04 09:12:35 +08:00
2 changed files with 103 additions and 67 deletions

View File

@ -87,6 +87,7 @@ $$\int_{a}^{b} f(x) \, dx$$
配置 config_showMathError 为 false 时忽略数学公式转换异常 配置 config_showMathError 为 false 时忽略数学公式转换异常
$2^{层数-1}$ 有异常unicodeTextInMathMode $2^{层数-1}$ 有异常unicodeTextInMathMode
$E=mc^2%$ 有异常commentAtEnd % $E=mc^2%$ 有异常commentAtEnd %
$\left($ (转换失败)
*** ***
</div> </div>
@ -97,9 +98,14 @@ $E=mc^2%$ 有异常commentAtEnd %
<li>下面代码的 HTML 格式中 <code>&amp;gt;</code><code>&amp;lt;</code> 不能转义为 &gt;&lt;,否则会有异常的下划线</li> <li>下面代码的 HTML 格式中 <code>&amp;gt;</code><code>&amp;lt;</code> 不能转义为 &gt;&lt;,否则会有异常的下划线</li>
<li>不转换 <code>&lt;code&gt;&lt;/code&gt;</code>包裹的内容</li> <li>不转换 <code>&lt;code&gt;&lt;/code&gt;</code>包裹的内容</li>
</ul> </ul>
<pre><code class="hljs java language-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">NumberPair</span>&lt;U <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Number</span>, V <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Number</span>&gt; <span class="hljs-keyword">extends</span> <span class="hljs-title class_">Pair</span>&lt;U,V&gt; { <pre><code class="hljs java language-java"><span class="hljs-keyword">public</span> <span
class="hljs-keyword">class</span> <span class="hljs-title class_">NumberPair</span>&lt;U <span
class="hljs-keyword">extends</span> <span class="hljs-title class_">Number</span>, V <span
class="hljs-keyword">extends</span> <span class="hljs-title class_">Number</span>&gt; <span
class="hljs-keyword">extends</span> <span class="hljs-title class_">Pair</span>&lt;U,V&gt; {
<span class="hljs-comment">//</span> <span class="hljs-comment">//</span>
<span class="hljs-keyword">public</span> <span class="hljs-title function_">NumberPair</span><span class="hljs-params">(U first, V second)</span> { <span class="hljs-keyword">public</span> <span class="hljs-title function_">NumberPair</span><span
class="hljs-params">(U first, V second)</span> {
<span class="hljs-built_in">super</span>(first, second); <span class="hljs-built_in">super</span>(first, second);
} }
} }

View File

@ -5,12 +5,9 @@
<script> <script>
// 日志级别: debug、info、warn、error、off // 日志级别: debug、warn、error
var config_logLevel = "error"; var config_logLevel = "error";
// 是否展示数学公式转换错误信息
var config_showMathError = false;
// javascript 资源加载 // javascript 资源加载
initScriptResource([ initScriptResource([
@ -19,27 +16,38 @@
"https://gcore.jsdelivr.net/npm/markdown-it-texmath@1.0.0/texmath.min.js", "https://gcore.jsdelivr.net/npm/markdown-it-texmath@1.0.0/texmath.min.js",
"https://gcore.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.js" "https://gcore.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.js"
]).then(() => { ]).then(() => {
// Anki 代码都执行完成后再执行,优先使用 Anki 自带的数学公式解析 // Anki 原来的逻辑执行完成后再转换内容
setTimeout(() => { setTimeout(() => {
try { renderMarkDownFn();
parseMarkDownFn();
} catch (e) {
DivLog.error("Error: " + e);
}
}); });
}) })
/** /**
* 转换卡片内容为 markdown 网页格式 * 转换卡片内容为 markdown 网页格式
*/ */
function parseMarkDownFn() { function renderMarkDownFn() {
// markdown-it 实例 try {
let md = markdownit({ document.querySelectorAll('.markdown-body').forEach((div) => {
div.innerHTML = renderMarkDown(div.innerHTML);
div.style.opacity = '1';
});
} catch (e) {
DivLog.error("Error: " + e);
}
}
function getAnkiMarkDownIt() {
if (typeof AnkiMarkDownIt !== 'undefined') {
DivLog.info("AnkiMarkDownIt is loaded!")
return AnkiMarkDownIt;
}
DivLog.info("AnkiMarkDownIt did not load!")
window.AnkiMarkDownIt = markdownit({
// 配置参考https://markdown-it.docschina.org/api/MarkdownIt.html#markdownit-new
html: true, html: true,
linkify: true, linkify: true,
typographer: true, typographer: false, // 为 true 时,将 (C)、(R)、(TM) 转化为 ©、®、™
breaks: true, breaks: true, // 为 true 时,将 \n 转化为 <br>
highlight: function (str, lang) { highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) { if (lang && hljs.getLanguage(lang)) {
try { try {
@ -51,65 +59,62 @@
} }
}).use(window.texmath, { }).use(window.texmath, {
engine: katex, engine: katex,
// 设置数学公式标识符为:$...$ or $$...$$ or \(...\) or \[...\] // 数学公式标识符参考https://www.npmjs.com/package/markdown-it-texmath
// 参考https://www.npmjs.com/package/markdown-it-texmath // 'dollars'$...$ or $$...$$
delimiters: ['dollars', 'brackets'], // 'brackets' \(...\) or \[...\],这个标识符号是 Anki 默认的,不用解析
// 参考https://katex.org/docs/options delimiters: ['dollars'],
// katex 的配置选项参考https://katex.org/docs/options
katexOptions: { katexOptions: {
output: 'html', output: 'html',
throwOnError: false, throwOnError: true, // true-页面展示解析异常false-解析异常的公式展示原字符并标记为红色
// IOS 端没有 console.warn 方法
strict: (errorCode, errorMsg, token) => { strict: (errorCode, errorMsg, token) => {
if (config_showMathError) {
DivLog.error('Warn: ' + errorCode + ' ' + errorMsg + ' ' + token);
return "error";
} else {
DivLog.warn('Warn: ' + errorCode + ' ' + errorMsg + ' ' + token); DivLog.warn('Warn: ' + errorCode + ' ' + errorMsg + ' ' + token);
return "ignore"; return "ignore";
} }
} }
}
});
// 转换内容
document.querySelectorAll('.markdown-body').forEach((div, index) => {
// 预处理文本,替换特殊字符,如:&lt; &gt; &amp; &nbsp;
let text = preProcessText(div, index)
// 转换成 markdown 网页格式
text = md.render(text);
DivLog.debug("After markdown-it conversion", text);
div.innerHTML = md.render(text);
});
// 最后将卡片显示,避免公式闪烁更新
document.querySelectorAll('.markdown-body').forEach((div) => {
div.style.opacity = 1;
}); });
return window.AnkiMarkDownIt;
} }
/** /**
* 预处理文本,替换特殊字符 * 绘制内容为 markdown 网页格式
* @param {Element} div * @param {string} text
* @param {number} index
* @returns {string} * @returns {string}
*/ */
function preProcessText(div, index) { function renderMarkDown(text) {
DivLog.debug("------------.markdown-body: " + (index + 1) + "------------"); DivLog.debug("==========================================");
DivLog.debug("Original content", div.innerHTML); DivLog.debug("Original content", text);
let text = div.innerHTML
// <code></code> 包裹的内容不做处理 // <code></code> 包裹的内容不做处理
let code_tag_matches let code_tag_matches
[text, code_tag_matches] = Censor.censorCodeHtml(text); [text, code_tag_matches] = Censor.censorCodeTag(text);
if (code_tag_matches.length > 0) { if (code_tag_matches.length > 0) {
DivLog.debug("After replacing <code></code>", text); DivLog.debug("After hide html tag <code></code>", text);
}
// <mjx-container></mjx-container> 包裹的内容不做处理
let mjx_tag_matches
[text, mjx_tag_matches] = Censor.censorMJXTag(text);
if (mjx_tag_matches.length > 0) {
DivLog.debug("After hide html tag <mjx-container></mjx-container>", text);
} }
text = text.trim() text = text.trim()
.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&") .replace(/&(amp|lt|gt|nbsp);/g, (_, type) => {
.replace(/&nbsp;/g, ' ') const entities = {amp: '&', lt: '<', gt: '>', nbsp: ' '};
.replace(/<br>/g, '\r\n'); return entities[type] || '';
})
.replace(/<br>/g, '\n');
DivLog.debug("After reverse some HTML tags", text);
// 转换成 markdown 网页格式
text = getAnkiMarkDownIt().render(text);
DivLog.debug("After markdown-it conversion", text);
// 还原隐藏的内容
text = Censor.decensorMJXTag(text, mjx_tag_matches)
text = Censor.decensorCodeTag(text, code_tag_matches)
text = Censor.decensorCodeHtml(text, code_tag_matches)
DivLog.debug("After replacing special characters", text);
return text; return text;
} }
@ -137,13 +142,14 @@
document.head.appendChild(script); document.head.appendChild(script);
}); });
})).catch(error => { })).catch(error => {
DivLog.error('Error: ' + error); DivLog.error(error);
throw error; throw error;
}); });
} }
function initMyClass() { function initMyClass() {
// 日志工具
if (typeof DivLog === 'undefined') { if (typeof DivLog === 'undefined') {
window.DivLog = { window.DivLog = {
LOG_LEVEL: "info", LOG_LEVEL: "info",
@ -171,33 +177,59 @@
}, },
_log(fontColor, ...messages) { _log(fontColor, ...messages) {
const messageDiv = document.createElement("div"); const messageDiv = document.createElement("div");
messageDiv.className = "my-message-div";
messageDiv.style.color = fontColor; messageDiv.style.color = fontColor;
messages.forEach(message => { messages.forEach(message => {
messageDiv.appendChild(document.createTextNode(message)); messageDiv.appendChild(document.createTextNode(message));
messageDiv.appendChild(document.createElement("br")); messageDiv.appendChild(document.createElement("br"));
}); });
messageDiv.appendChild(document.createElement("hr")); messageDiv.appendChild(document.createElement("hr"));
document.body.appendChild(messageDiv) this._getMsgContainer().appendChild(messageDiv)
},
_getMsgContainer() {
let msgContainer = document.getElementById("msgContainer");
if (!msgContainer) {
msgContainer = document.createElement("div");
msgContainer.id = "msgContainer";
msgContainer.style.textAlign = "left";
// 将日志信息放在最后一个 class="markdown-body" 的 div 的后面
const divs = document.querySelectorAll("div.markdown-body");
const lastDiv = divs.length > 0 ? divs[divs.length - 1] : null;
if (lastDiv) {
lastDiv.parentNode.appendChild(msgContainer);
}
}
return msgContainer
}, },
clearLogDiv() { clearLogDiv() {
document.querySelectorAll(".my-message-div").forEach(div => div.remove()); const msgContainer = document.getElementById("msgContainer");
if (msgContainer) {
msgContainer.innerHTML = "";
}
} }
}; };
DivLog.LOG_LEVEL = config_logLevel; DivLog.LOG_LEVEL = config_logLevel;
} }
DivLog.clearLogDiv(); DivLog.clearLogDiv();
// 隐藏特殊片段
if (typeof Censor === 'undefined') { if (typeof Censor === 'undefined') {
const ANKI_CODE_REGEXP = /<code[^>]*>([\s\S]*?)<\/code>/g; const ANKI_CODE_REGEXP = /<code[^>]*>([\s\S]*?)<\/code>/g;
const ANKI_CODE_REPLACE = "##ANKI_CODE_REPLACE##"; const ANKI_CODE_REPLACE = "ANKI_CODE_REPLACE";
const ANKI_MJX_REGEXP = /<mjx-container[^>]*>([\s\S]*?)<\/mjx-container>/g;
const ANKI_MJX_REPLACE = "ANKI_MJX_CONTAINER_REPLACE";
window.Censor = { window.Censor = {
censorCodeHtml: function (note_text) { censorCodeTag: function (note_text) {
return this._censor(note_text, ANKI_CODE_REGEXP, ANKI_CODE_REPLACE) return this._censor(note_text, ANKI_CODE_REGEXP, ANKI_CODE_REPLACE)
}, },
decensorCodeHtml: function (note_text, replacements) { censorMJXTag: function (note_text) {
return this._censor(note_text, ANKI_MJX_REGEXP, ANKI_MJX_REPLACE)
},
decensorCodeTag: function (note_text, replacements) {
return this._decensor(note_text, ANKI_CODE_REPLACE, replacements) return this._decensor(note_text, ANKI_CODE_REPLACE, replacements)
}, },
decensorMJXTag: function (note_text, replacements) {
return this._decensor(note_text, ANKI_MJX_REPLACE, replacements)
},
_censor: function (note_text, regexp, mask) { _censor: function (note_text, regexp, mask) {
/*Take note_text and replace every match of regexp with mask, simultaneously adding it to a string array*/ /*Take note_text and replace every match of regexp with mask, simultaneously adding it to a string array*/
let matches = [] let matches = []
@ -215,6 +247,4 @@
} }
} }
} }
</script> </script>