Compare commits

..

No commits in common. "fb10876842abb62bf8edfc32a3930b9f6241a4fb" and "afd9ca542782144554b19be96efd796f872136e9" have entirely different histories.

2 changed files with 67 additions and 103 deletions

View File

@ -87,7 +87,6 @@ $$\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>
@ -98,14 +97,9 @@ $\left($ (转换失败)
<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 <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; {
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 <span class="hljs-keyword">public</span> <span class="hljs-title function_">NumberPair</span><span class="hljs-params">(U first, V second)</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,9 +5,12 @@
<script> <script>
// 日志级别: debug、warn、error // 日志级别: debug、info、warn、error、off
var config_logLevel = "error"; var config_logLevel = "error";
// 是否展示数学公式转换错误信息
var config_showMathError = false;
// javascript 资源加载 // javascript 资源加载
initScriptResource([ initScriptResource([
@ -16,38 +19,27 @@
"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(() => {
renderMarkDownFn(); try {
parseMarkDownFn();
} catch (e) {
DivLog.error("Error: " + e);
}
}); });
}) })
/** /**
* 转换卡片内容为 markdown 网页格式 * 转换卡片内容为 markdown 网页格式
*/ */
function renderMarkDownFn() { function parseMarkDownFn() {
try { // markdown-it 实例
document.querySelectorAll('.markdown-body').forEach((div) => { let md = markdownit({
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: false, // 为 true 时,将 (C)、(R)、(TM) 转化为 ©、®、™ typographer: true,
breaks: true, // 为 true 时,将 \n 转化为 <br> breaks: true,
highlight: function (str, lang) { highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) { if (lang && hljs.getLanguage(lang)) {
try { try {
@ -59,62 +51,65 @@
} }
}).use(window.texmath, { }).use(window.texmath, {
engine: katex, engine: katex,
// 数学公式标识符参考https://www.npmjs.com/package/markdown-it-texmath // 设置数学公式标识符为:$...$ or $$...$$ or \(...\) or \[...\]
// 'dollars'$...$ or $$...$$ // 参考https://www.npmjs.com/package/markdown-it-texmath
// 'brackets' \(...\) or \[...\],这个标识符号是 Anki 默认的,不用解析 delimiters: ['dollars', 'brackets'],
delimiters: ['dollars'], // 参考https://katex.org/docs/options
// katex 的配置选项参考https://katex.org/docs/options
katexOptions: { katexOptions: {
output: 'html', output: 'html',
throwOnError: true, // true-页面展示解析异常false-解析异常的公式展示原字符并标记为红色 throwOnError: false,
// IOS 端没有 console.warn 方法
strict: (errorCode, errorMsg, token) => { strict: (errorCode, errorMsg, token) => {
DivLog.warn('Warn: ' + errorCode + ' ' + errorMsg + ' ' + token); if (config_showMathError) {
return "ignore"; DivLog.error('Warn: ' + errorCode + ' ' + errorMsg + ' ' + token);
return "error";
} else {
DivLog.warn('Warn: ' + errorCode + ' ' + errorMsg + ' ' + token);
return "ignore";
}
} }
} }
}); });
return window.AnkiMarkDownIt; // 转换内容
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;
});
} }
/** /**
* 绘制内容为 markdown 网页格式 * 预处理文本,替换特殊字符
* @param {string} text * @param {Element} div
* @param {number} index
* @returns {string} * @returns {string}
*/ */
function renderMarkDown(text) { function preProcessText(div, index) {
DivLog.debug("=========================================="); DivLog.debug("------------.markdown-body: " + (index + 1) + "------------");
DivLog.debug("Original content", text); DivLog.debug("Original content", div.innerHTML);
let text = div.innerHTML
// <code></code> 包裹的内容不做处理 // <code></code> 包裹的内容不做处理
let code_tag_matches let code_tag_matches
[text, code_tag_matches] = Censor.censorCodeTag(text); [text, code_tag_matches] = Censor.censorCodeHtml(text);
if (code_tag_matches.length > 0) { if (code_tag_matches.length > 0) {
DivLog.debug("After hide html tag <code></code>", text); DivLog.debug("After replacing <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(/&(amp|lt|gt|nbsp);/g, (_, type) => { .replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&")
const entities = {amp: '&', lt: '<', gt: '>', nbsp: ' '}; .replace(/&nbsp;/g, ' ')
return entities[type] || ''; .replace(/<br>/g, '\r\n');
})
.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;
} }
@ -142,14 +137,13 @@
document.head.appendChild(script); document.head.appendChild(script);
}); });
})).catch(error => { })).catch(error => {
DivLog.error(error); DivLog.error('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",
@ -177,59 +171,33 @@
}, },
_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"));
this._getMsgContainer().appendChild(messageDiv) document.body.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() {
const msgContainer = document.getElementById("msgContainer"); document.querySelectorAll(".my-message-div").forEach(div => div.remove());
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 = {
censorCodeTag: function (note_text) { censorCodeHtml: 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)
}, },
censorMJXTag: function (note_text) { decensorCodeHtml: function (note_text, replacements) {
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 = []
@ -247,4 +215,6 @@
} }
} }
} }
</script> </script>