Merge pull request #23 from aisahpA/dev

perf: 优化代码
This commit is contained in:
小能饼干 2025-05-13 15:53:39 +08:00 committed by GitHub
commit 7012a00c54
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 172 additions and 200 deletions

View File

@ -10,90 +10,48 @@
<style> <style>
.markdown-body { .markdown-body {
max-width: 980px; max-width: 980px;
padding: 45px;
} }
</style> </style>
<body class="markdown-body" id="qa"> <body id="qa">
<!-- prettier-ignore --> <!-- prettier-ignore -->
<div class="md-content"> <div class="markdown-body">
> Anki-Markdown 模板测试 测试 Markdown 格式
***
# 一级标题 # 一级标题
## 二级标题 ## 二级标题
### 三级标题 ### 三级标题
---
**加粗** **加粗**
*斜体* *斜体*
***加粗斜体*** ***加粗斜体***
***
> 引用 > 引用
--- 引用第二行
引用第三行
- 无序列表
- 无序列表
- 无序列表 - 无序列表
---
1. 有序列表
---
[链接](https://www.baidu.com)
***
![图片](https://www.baidu.com/img/bd_logo1.png)
--- 1. 有序列表 1
`行内代码` 2. 有序列表 2
*** 3. 有序列表 3
```javascript </div>
// 代码块 <div class="markdown-body">
console.log('hello world') ### 代码块
`代码块 1`
```c
#include &lt;stdio.h&gt;
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
``` ```
代码块 2
```java ```python
/** sql = "SELECT * FROM your_table"
* @param src 待拷贝的数组. cursor.execute(sql)
* @param srcPos 待拷贝数组开始位置. ```
* @param dest 目标数组. 代码块 3
* @param destPos 目标数组开始位置.
* @param length 拷贝长度.
*/
@HotSpotIntrinsicCandidate
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
```
</div>
<!-- prettier-ignore -->
<div class="md-content">
***
超长代码换行显示
```js
const example = "This is a very long string that will wrap automatically when exceeding screen
width.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccddddddddddddddddddddd";
```
</div>
<div class="md-content">
行内公式:$E=mc^2$
***
块级公式:
$$\frac{d}{dx}(x^n) = nx^{n-1}$$
***
矩阵:
$$\begin{pmatrix} a & b \\ c & d \end{pmatrix}$$
***
积分:
$$\int_{a}^{b} f(x) \, dx$$
</div>
<div class="md-content">
***
配置 config_showMathError 为 false 时忽略数学公式转换异常
$2^{层数-1}$ 有异常unicodeTextInMathMode
$E=mc^2%$ 有异常commentAtEnd %
$\left($ (转换失败)
***
</div>
<div class="md-content">
<ul> <ul>
<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>
@ -112,6 +70,58 @@ $\left($ (转换失败)
</code></pre> </code></pre>
</div> </div>
<div class="markdown-body">
### 数学公式 - 由 Anki 解析
**行内公式:**
- \(E=mc^2\)、 \(\lfloor i/2 \rfloor\)、\(f(x)\)、\(A\)
- Does \(\sum_{k = 1}^{\infty}\frac{1}{k}\) converge?
- 勾股定理:\(a^2 + b^2 = c^2\),其中 \(c\) 是斜边
- \({\Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,.}\)
- \(\begin{pmatrix} a &amp; b \\ c &amp; d \end{pmatrix}\)、 \(\int_{a}^{b} f(x) \, dx\)
**块级公式:**
\[\frac{d}{dx}(x^n) = nx^{n-1}\]
\[\sum_{k=1}^n k = \frac{n(n+1)}{2}\]
**多行公式:**
行内:
\(f(x) =
\left\{
\begin{aligned}
&amp; \lambda e^{-\lambda x} &amp; x &gt; 0 \\
&amp; 0 &amp; x \leq 0 \\
\end{aligned}
\right.\)
块级:
\[f(x) =
\left\{
\begin{aligned}
&amp; \lambda e^{-\lambda x} &amp; x &gt; 0 \\
&amp; 0 &amp; x \leq 0 \\
\end{aligned}
\right.\]
忽略解析警告:
\(2^{层数-1}\)
非法数学公式:
\(\left\{()\right\)
不解析为特殊字符:
(C) 不解析为 ©
(R) 不解析为 ®
不支持 \$ 数学公式,请转换为 `\ (...\ )` 或 `\ [...\ ]`
$E=mc^2$
$$a^2 + b^2 = c^2$$
</div>
<div class="markdown-body">
### 链接与图片
[百度](https://www.baidu.com)
![图片链接](https://www.baidu.com/img/bd_logo1.png)
</div>
<script src="https://gcore.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script> <script src="https://gcore.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script type="text/javascript"> <script type="text/javascript">
$.get("正面内容模版.html", function (data) { $.get("正面内容模版.html", function (data) {

View File

@ -1,20 +1,21 @@
@import url('https://gcore.jsdelivr.net/npm/github-markdown-css@5.8.1/github-markdown.min.css'); @import url('https://gcore.jsdelivr.net/npm/github-markdown-css@5.8.1/github-markdown.min.css');
@import url('https://gcore.jsdelivr.net/npm/highlight.js@11.11.1/styles/night-owl.min.css'); @import url('https://gcore.jsdelivr.net/npm/highlight.js@11.11.1/styles/night-owl.min.css');
@import url('https://gcore.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css');
@import url('https://gcore.jsdelivr.net/npm/markdown-it-texmath@1.0.0/css/texmath.min.css');
@import url('https://gcore.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css'); @import url('https://gcore.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css');
.markdown-body { .markdown-body {
box-sizing: border-box; box-sizing: border-box;
min-width: 200px;
margin: 0 auto; margin: 0 auto;
padding: 16px; padding: 16px;
font-size: 20px; font-size: 20px;
text-align: left; /* left-左对齐center-居中对齐 */ text-align: left; /* left-左对齐center-居中对齐 */
} }
.md-content { #qa {
opacity: 0; visibility: hidden !important;
}
#qa.qa-visible {
visibility: visible !important;
} }
/* 代码块自动换行,方便手机端查看代码 */ /* 代码块自动换行,方便手机端查看代码 */
@ -23,10 +24,6 @@ pre code[class*="language-"] {
font-size: 16px; font-size: 16px;
} }
.katex {
font-size: 1.18em !important; /* 放大公式显示,与 Anki 解析的公式一样大 */
}
/* Anki 似乎不支持 prefers-color-scheme换一种方式设置暗黑模式 */ /* Anki 似乎不支持 prefers-color-scheme换一种方式设置暗黑模式 */
.nightMode .markdown-body { .nightMode .markdown-body {
/* dark */ /* dark */

View File

@ -1,48 +1,45 @@
<div class="md-content"> <div class="markdown-body">
{{正面}} {{Front}}
</div> </div>
<script> <script>
// 日志级别: debug、warn、error // 日志级别: debug、error
var config_logLevel = "error"; var config_logLevel = "error";
var scriptUrls = [ var scriptUrls = [
"https://gcore.jsdelivr.net/npm/markdown-it@14.1.0/dist/markdown-it.min.js", "https://gcore.jsdelivr.net/npm/markdown-it@14.1.0/dist/markdown-it.min.js",
"https://gcore.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js", "https://gcore.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.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"
]; ];
initDivLog(); // 执行内容转换
initScriptResource(scriptUrls).then(() => { try {
// Anki 原来的逻辑执行完成后再转换内容 hideCard();
setTimeout(() => { if (typeof AnkiMarkDownIt !== 'undefined') {
// 可以复用 AnkiMarkDownIt直接执行转换
renderMarkDownFn(); renderMarkDownFn();
}, 0); } else {
}) initDivLog();
initCensorUtil();
initScriptResource(scriptUrls).then(() => {
initAnkiMarkDownIt();
renderMarkDownFn();
});
}
} catch (e) {
console.error(e);
DivLog.error("Error: ", e);
showCard();
}
/** /**
* 转换卡片内容为 markdown 网页格式 * 转换卡片内容为 markdown 网页格式
*/ */
function renderMarkDownFn() { function renderMarkDownFn() {
try { document.querySelectorAll('.markdown-body').forEach((div) => {
// 隐藏卡片 div.innerHTML = renderMarkDown(div.innerHTML);
hideQAContent() });
showCard();
// 转换内容
initAnkiMarkDownIt();
initCensorUtil();
document.querySelectorAll('.md-content').forEach((div) => {
div.innerHTML = renderMarkDown(div.innerHTML);
div.className = "markdown-body";
});
// 显示卡片
showQAContent()
} catch (e) {
DivLog.error("Error: " + e);
}
} }
/** /**
@ -54,20 +51,27 @@
DivLog.debug("======================================"); DivLog.debug("======================================");
DivLog.debug("Original content", text); DivLog.debug("Original content", text);
// <code></code> 包裹的内容不做处理 // 隐藏标签 <code></code>
let code_tag_matches let code_tag_matches;
[text, code_tag_matches] = CensorUtil.censorCodeTag(text); [text, code_tag_matches] = CensorUtil.censor(text, CensorUtil.Code_Reg, CensorUtil.Code_Replace);
if (code_tag_matches.length > 0) { if (code_tag_matches.length > 0) {
DivLog.debug("After hide html tag <code></code>", text); DivLog.debug("After hide html tag <code></code>", text);
} }
// <mjx-container></mjx-container> 包裹的内容不做处理 // 隐藏标签 <mjx-container></mjx-container>
let mjx_tag_matches let mjx_tag_matches
[text, mjx_tag_matches] = CensorUtil.censorMJXTag(text); [text, mjx_tag_matches] = CensorUtil.censor(text, CensorUtil.Mjx_Container_Reg, CensorUtil.Mjx_Container_Replace);
if (mjx_tag_matches.length > 0) { if (mjx_tag_matches.length > 0) {
DivLog.debug("After hide html tag <mjx-container></mjx-container>", text); DivLog.debug("After hide html tag <mjx-container></mjx-container>", text);
} }
// 隐藏数学公式:\(...\) 和 \[...\]
let math_tag_matches;
[text, math_tag_matches] = CensorUtil.censor(text, CensorUtil.MathJs_Reg, CensorUtil.MathJs_Replace);
if (math_tag_matches.length > 0) {
DivLog.debug("After hide \\ (...\\) 和 \\ [...\\]", text);
}
text = text.trim() text = text.trim()
.replace(/&(amp|lt|gt|nbsp);/g, (_, type) => { .replace(/&(amp|lt|gt|nbsp);/g, (_, type) => {
const entities = {amp: '&', lt: '<', gt: '>', nbsp: ' '}; const entities = {amp: '&', lt: '<', gt: '>', nbsp: ' '};
@ -81,8 +85,9 @@
DivLog.debug("After markdown-it conversion", text); DivLog.debug("After markdown-it conversion", text);
// 还原隐藏的内容 // 还原隐藏的内容
text = CensorUtil.decensorMJXTag(text, mjx_tag_matches) text = CensorUtil.decensor(text, CensorUtil.MathJs_Replace, math_tag_matches)
text = CensorUtil.decensorCodeTag(text, code_tag_matches) text = CensorUtil.decensor(text, CensorUtil.Mjx_Container_Replace, mjx_tag_matches)
text = CensorUtil.decensor(text, CensorUtil.Code_Replace, code_tag_matches)
return text; return text;
} }
@ -90,36 +95,37 @@
// 初始化-日志工具 // 初始化-日志工具
function initDivLog() { function initDivLog() {
// 日志工具
if (typeof DivLog === 'undefined') { if (typeof DivLog === 'undefined') {
window.DivLog = { window.DivLog = {
LOG_LEVEL: "info", currentLevel: 4,
levelMap: {'debug': 5, 'info': 4, 'warn': 3, 'error': 2, 'off': 1}, levelMap: {debug: 5, info: 4, warn: 3, error: 2, off: 1},
setLevel(levelStr) {
this.currentLevel = this.levelMap[levelStr];
},
debug(...messages) { debug(...messages) {
if (this.levelMap[this.LOG_LEVEL] >= 5) { this._log(this.levelMap.debug, "", ...messages);
this._log("", ...messages);
}
}, },
info(...messages) { info(...messages) {
if (this.levelMap[this.LOG_LEVEL] >= 4) { this._log(this.levelMap.info, "", ...messages);
this._log("", ...messages);
}
}, },
warn(...messages) { warn(...messages) {
if (this.levelMap[this.LOG_LEVEL] >= 3) { this._log(this.levelMap.warn, "orange", ...messages);
this._log("orange", ...messages);
}
}, },
error(...messages) { error(...messages) {
if (this.levelMap[this.LOG_LEVEL] >= 2) { this._log(this.levelMap.error, "red", ...messages);
this._log("red", ...messages);
}
}, },
_log(fontColor, ...messages) { _log(minLevel, fontColor, ...messages) {
if (minLevel > this.currentLevel || messages.length === 0) {
return;
}
const messageDiv = document.createElement("div"); const messageDiv = document.createElement("div");
messageDiv.style.color = fontColor; messageDiv.style.color = fontColor;
messages[0] = new Date().toLocaleTimeString() + " " + messages[0];
messages.forEach(message => { messages.forEach(message => {
// 替换数学公式中的界定符号,原样显示,不然会被 anki 替换为公式形状
if (typeof message === 'string') {
message = message.replace(/\\\(/g, '\\_(').replace(/\\\[/g, '\\_[');
}
messageDiv.appendChild(document.createTextNode(message)); messageDiv.appendChild(document.createTextNode(message));
messageDiv.appendChild(document.createElement("br")); messageDiv.appendChild(document.createElement("br"));
}); });
@ -132,6 +138,7 @@
msgContainer = document.createElement("div"); msgContainer = document.createElement("div");
msgContainer.id = "msgContainer"; msgContainer.id = "msgContainer";
msgContainer.style.textAlign = "left"; msgContainer.style.textAlign = "left";
msgContainer.style.whiteSpace = "pre-wrap";
// 将日志信息放在最后 // 将日志信息放在最后
let qa = document.getElementById("qa"); let qa = document.getElementById("qa");
if (qa) { if (qa) {
@ -148,11 +155,7 @@
} }
}; };
} }
// 更新日志级别 DivLog.setLevel(config_logLevel || "info");
if (DivLog.LOG_LEVEL !== config_logLevel) {
DivLog.LOG_LEVEL = config_logLevel;
}
// 清空日志
DivLog.clearLogDiv(); DivLog.clearLogDiv();
} }
@ -184,17 +187,12 @@
// 初始化-markdown-it // 初始化-markdown-it
function initAnkiMarkDownIt() { function initAnkiMarkDownIt() {
if (typeof AnkiMarkDownIt !== 'undefined') { DivLog.info("init AnkiMarkDownIt!")
DivLog.debug("AnkiMarkDownIt is init!")
return;
}
DivLog.info("AnkiMarkDownIt did not init!")
window.AnkiMarkDownIt = markdownit({ window.AnkiMarkDownIt = markdownit({
// 配置参考https://markdown-it.docschina.org/api/MarkdownIt.html#markdownit-new // 配置参考https://markdown-it.docschina.org/api/MarkdownIt.html#markdownit-new
html: true, html: true,
linkify: true, linkify: 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 {
@ -204,82 +202,49 @@
} }
return ''; return '';
} }
}).use(window.texmath, {
engine: katex,
// 数学公式标识符参考https://www.npmjs.com/package/markdown-it-texmath
// 'dollars'$...$ or $$...$$
// 'brackets' \(...\) or \[...\],这个标识符号是 Anki 默认的,
// 但安卓端数学公式的解析是在页面加载完成后执行,这里的 Markdown 转换会破坏公式,还是需要将 'brackets' 配置上
delimiters: ['dollars', 'brackets'],
// katex 的配置选项参考https://katex.org/docs/options
katexOptions: {
output: 'html',
throwOnError: false, // true-页面展示解析异常false-解析异常的公式展示原字符并标记为红色
strict: (errorCode, errorMsg, token) => {
DivLog.warn('Warn: ' + errorCode + ' ' + errorMsg + ' ' + token);
return "ignore";
}
}
}); });
} }
// 初始化-特殊片段隐藏工具 // 初始化-特殊片段隐藏工具
function initCensorUtil() { function initCensorUtil() {
if (typeof CensorUtil === 'undefined') { if (typeof CensorUtil === 'undefined') {
const ANKI_CODE_REGEXP = /<code[^>]*>([\s\S]*?)<\/code>/g;
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.CensorUtil = { window.CensorUtil = {
censorCodeTag: function (note_text) { Code_Reg: /<code[^>]*>([\s\S]*?)<\/code>/g,
return this._censor(note_text, ANKI_CODE_REGEXP, ANKI_CODE_REPLACE) Code_Replace: "ANKI_CODE_REPLACE",
}, // 匹配数学公式转换后: <mjx-container>...</mjx-container>
censorMJXTag: function (note_text) { Mjx_Container_Reg: /<mjx-container[^>]*>([\s\S]*?)<\/mjx-container>/g,
return this._censor(note_text, ANKI_MJX_REGEXP, ANKI_MJX_REPLACE) Mjx_Container_Replace: "ANKI_MJX_CONTAINER_REPLACE",
}, // 匹配数学公式: \[...\] 和 \(...\)
decensorCodeTag: function (note_text, replacements) { MathJs_Reg: /(\\\[[\s\S]*?\\])|(\\\([\s\S]*?\\\))/g,
return this._decensor(note_text, ANKI_CODE_REPLACE, replacements) MathJs_Replace: "ANKI_MATHJS_REPLACE",
}, censor: function (note_text, regexp, mask) {
decensorMJXTag: function (note_text, replacements) { let matches = [];
return this._decensor(note_text, ANKI_MJX_REPLACE, replacements)
},
_censor: function (note_text, regexp, mask) {
/*Take note_text and replace every match of regexp with mask, simultaneously adding it to a string array*/
let matches = []
for (let match of note_text.matchAll(regexp)) { for (let match of note_text.matchAll(regexp)) {
matches.push(match[0]) matches.push(match[0])
} }
return [note_text.replace(regexp, mask), matches] return [note_text.replace(regexp, mask), matches]
}, },
_decensor: function (note_text, mask, replacements) { decensor: function (note_text, mask, replacements) {
for (let replacement of replacements) { for (let replacement of replacements) {
note_text = note_text.replace(mask, replacement) note_text = note_text.replace(mask, replacement)
} }
return note_text return note_text
} }
} };
} }
} }
function hideCard() {
// 隐藏卡片内容 const qa = document.getElementById("qa");
function hideQAContent() { if (qa) {
// 卡片的内容都是放在 id 为 qa 的 div 中 qa.classList.remove("qa-visible");
let qaElement = document.getElementById("qa");
if (qaElement) {
qaElement.style.opacity = "0";
} }
} }
// 显示卡片内容 function showCard() {
function showQAContent() { const qa = document.getElementById("qa");
let answerHr = document.getElementById("answer"); if (qa) {
if (answerHr) { qa.classList.add("qa-visible");
answerHr.style.opacity = "1";
}
let qaElement = document.getElementById("qa");
if (qaElement) {
qaElement.style.opacity = "1";
} }
} }
</script> </script>

View File

@ -1,5 +1,5 @@
{{FrontSide}} {{FrontSide}}
<hr id="answer" style="opacity: 0;"> <hr id=answer>
<div class="md-content">{{背面}}</div> <div class="markdown-body">{{Back}}</div>