Compare commits

..

No commits in common. "7012a00c540cc6f431412103b5915a6bb838391f" and "d4ce1c8d0df0c34e8c83bcc007eb146c0247dd9f" have entirely different histories.

6 changed files with 201 additions and 173 deletions

View File

@ -10,48 +10,90 @@
<style>
.markdown-body {
max-width: 980px;
padding: 45px;
}
</style>
<body id="qa">
<body class="markdown-body" id="qa">
<!-- prettier-ignore -->
<div class="markdown-body">
测试 Markdown 格式
***
<div class="md-content">
> Anki-Markdown 模板测试
# 一级标题
## 二级标题
### 三级标题
---
**加粗**
*斜体*
***加粗斜体***
***
> 引用
引用第二行
引用第三行
---
- 无序列表
---
1. 有序列表
---
[链接](https://www.baidu.com)
***
![图片](https://www.baidu.com/img/bd_logo1.png)
- 无序列表
- 无序列表
- 无序列表
---
`行内代码`
***
```javascript
// 代码块
console.log('hello world')
```
1. 有序列表 1
2. 有序列表 2
3. 有序列表 3
```java
/**
* @param src 待拷贝的数组.
* @param srcPos 待拷贝数组开始位置.
* @param dest 目标数组.
* @param destPos 目标数组开始位置.
* @param length 拷贝长度.
*/
@HotSpotIntrinsicCandidate
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
```
</div>
<div class="markdown-body">
### 代码块
`代码块 1`
```c
#include &lt;stdio.h&gt;
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
<!-- prettier-ignore -->
<div class="md-content">
***
超长代码换行显示
```js
const example = "This is a very long string that will wrap automatically when exceeding screen
width.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbccccccccccccccccccccccccccccccccccccccddddddddddddddddddddd";
```
代码块 2
```python
sql = "SELECT * FROM your_table"
cursor.execute(sql)
```
代码块 3
</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>
<li>下面代码的 HTML 格式中 <code>&amp;gt;</code><code>&amp;lt;</code> 不能转义为 &gt;&lt;,否则会有异常的下划线</li>
<li>不转换 <code>&lt;code&gt;&lt;/code&gt;</code>包裹的内容</li>
@ -70,58 +112,6 @@ int factorial(int n) {
</code></pre>
</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 type="text/javascript">
$.get("正面内容模版.html", function (data) {

View File

@ -1,21 +1,20 @@
@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/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');
.markdown-body {
box-sizing: border-box;
min-width: 200px;
margin: 0 auto;
padding: 16px;
font-size: 20px;
text-align: left; /* left-左对齐center-居中对齐 */
}
#qa {
visibility: hidden !important;
}
#qa.qa-visible {
visibility: visible !important;
.md-content {
opacity: 0;
}
/* 代码块自动换行,方便手机端查看代码 */
@ -24,6 +23,10 @@ pre code[class*="language-"] {
font-size: 16px;
}
.katex {
font-size: 1.18em !important; /* 放大公式显示,与 Anki 解析的公式一样大 */
}
/* Anki 似乎不支持 prefers-color-scheme换一种方式设置暗黑模式 */
.nightMode .markdown-body {
/* dark */

View File

@ -1,45 +1,48 @@
<div class="markdown-body">
{{Front}}
<div class="md-content">
{{正面}}
</div>
<script>
// 日志级别: debug、error
// 日志级别: debug、warn、error
var config_logLevel = "error";
var scriptUrls = [
"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/npm/markdown-it-texmath@1.0.0/texmath.min.js",
"https://gcore.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.js"
];
// 执行内容转换
try {
hideCard();
if (typeof AnkiMarkDownIt !== 'undefined') {
// 可以复用 AnkiMarkDownIt直接执行转换
renderMarkDownFn();
} else {
initDivLog();
initCensorUtil();
initScriptResource(scriptUrls).then(() => {
initAnkiMarkDownIt();
// Anki 原来的逻辑执行完成后再转换内容
setTimeout(() => {
renderMarkDownFn();
});
}
} catch (e) {
console.error(e);
DivLog.error("Error: ", e);
showCard();
}
}, 0);
})
/**
* 转换卡片内容为 markdown 网页格式
*/
function renderMarkDownFn() {
document.querySelectorAll('.markdown-body').forEach((div) => {
try {
// 隐藏卡片
hideQAContent()
// 转换内容
initAnkiMarkDownIt();
initCensorUtil();
document.querySelectorAll('.md-content').forEach((div) => {
div.innerHTML = renderMarkDown(div.innerHTML);
div.className = "markdown-body";
});
showCard();
// 显示卡片
showQAContent()
} catch (e) {
DivLog.error("Error: " + e);
}
}
/**
@ -51,27 +54,20 @@
DivLog.debug("======================================");
DivLog.debug("Original content", text);
// 隐藏标签 <code></code>
let code_tag_matches;
[text, code_tag_matches] = CensorUtil.censor(text, CensorUtil.Code_Reg, CensorUtil.Code_Replace);
// <code></code> 包裹的内容不做处理
let code_tag_matches
[text, code_tag_matches] = CensorUtil.censorCodeTag(text);
if (code_tag_matches.length > 0) {
DivLog.debug("After hide html tag <code></code>", text);
}
// 隐藏标签 <mjx-container></mjx-container>
// <mjx-container></mjx-container> 包裹的内容不做处理
let mjx_tag_matches
[text, mjx_tag_matches] = CensorUtil.censor(text, CensorUtil.Mjx_Container_Reg, CensorUtil.Mjx_Container_Replace);
[text, mjx_tag_matches] = CensorUtil.censorMJXTag(text);
if (mjx_tag_matches.length > 0) {
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()
.replace(/&(amp|lt|gt|nbsp);/g, (_, type) => {
const entities = {amp: '&', lt: '<', gt: '>', nbsp: ' '};
@ -85,9 +81,8 @@
DivLog.debug("After markdown-it conversion", text);
// 还原隐藏的内容
text = CensorUtil.decensor(text, CensorUtil.MathJs_Replace, math_tag_matches)
text = CensorUtil.decensor(text, CensorUtil.Mjx_Container_Replace, mjx_tag_matches)
text = CensorUtil.decensor(text, CensorUtil.Code_Replace, code_tag_matches)
text = CensorUtil.decensorMJXTag(text, mjx_tag_matches)
text = CensorUtil.decensorCodeTag(text, code_tag_matches)
return text;
}
@ -95,37 +90,36 @@
// 初始化-日志工具
function initDivLog() {
// 日志工具
if (typeof DivLog === 'undefined') {
window.DivLog = {
currentLevel: 4,
levelMap: {debug: 5, info: 4, warn: 3, error: 2, off: 1},
setLevel(levelStr) {
this.currentLevel = this.levelMap[levelStr];
},
LOG_LEVEL: "info",
levelMap: {'debug': 5, 'info': 4, 'warn': 3, 'error': 2, 'off': 1},
debug(...messages) {
this._log(this.levelMap.debug, "", ...messages);
if (this.levelMap[this.LOG_LEVEL] >= 5) {
this._log("", ...messages);
}
},
info(...messages) {
this._log(this.levelMap.info, "", ...messages);
if (this.levelMap[this.LOG_LEVEL] >= 4) {
this._log("", ...messages);
}
},
warn(...messages) {
this._log(this.levelMap.warn, "orange", ...messages);
if (this.levelMap[this.LOG_LEVEL] >= 3) {
this._log("orange", ...messages);
}
},
error(...messages) {
this._log(this.levelMap.error, "red", ...messages);
},
_log(minLevel, fontColor, ...messages) {
if (minLevel > this.currentLevel || messages.length === 0) {
return;
if (this.levelMap[this.LOG_LEVEL] >= 2) {
this._log("red", ...messages);
}
},
_log(fontColor, ...messages) {
const messageDiv = document.createElement("div");
messageDiv.style.color = fontColor;
messages[0] = new Date().toLocaleTimeString() + " " + messages[0];
messages.forEach(message => {
// 替换数学公式中的界定符号,原样显示,不然会被 anki 替换为公式形状
if (typeof message === 'string') {
message = message.replace(/\\\(/g, '\\_(').replace(/\\\[/g, '\\_[');
}
messageDiv.appendChild(document.createTextNode(message));
messageDiv.appendChild(document.createElement("br"));
});
@ -138,7 +132,6 @@
msgContainer = document.createElement("div");
msgContainer.id = "msgContainer";
msgContainer.style.textAlign = "left";
msgContainer.style.whiteSpace = "pre-wrap";
// 将日志信息放在最后
let qa = document.getElementById("qa");
if (qa) {
@ -155,7 +148,11 @@
}
};
}
DivLog.setLevel(config_logLevel || "info");
// 更新日志级别
if (DivLog.LOG_LEVEL !== config_logLevel) {
DivLog.LOG_LEVEL = config_logLevel;
}
// 清空日志
DivLog.clearLogDiv();
}
@ -187,12 +184,17 @@
// 初始化-markdown-it
function initAnkiMarkDownIt() {
DivLog.info("init AnkiMarkDownIt!")
if (typeof AnkiMarkDownIt !== 'undefined') {
DivLog.debug("AnkiMarkDownIt is init!")
return;
}
DivLog.info("AnkiMarkDownIt did not init!")
window.AnkiMarkDownIt = markdownit({
// 配置参考https://markdown-it.docschina.org/api/MarkdownIt.html#markdownit-new
html: true,
linkify: true,
breaks: true,
typographer: false, // 为 true 时,将 (C)、(R)、(TM) 转化为 ©、®、™
breaks: true, // 为 true 时,将 \n 转化为 <br>
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
@ -202,49 +204,82 @@
}
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() {
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 = {
Code_Reg: /<code[^>]*>([\s\S]*?)<\/code>/g,
Code_Replace: "ANKI_CODE_REPLACE",
// 匹配数学公式转换后: <mjx-container>...</mjx-container>
Mjx_Container_Reg: /<mjx-container[^>]*>([\s\S]*?)<\/mjx-container>/g,
Mjx_Container_Replace: "ANKI_MJX_CONTAINER_REPLACE",
// 匹配数学公式: \[...\] 和 \(...\)
MathJs_Reg: /(\\\[[\s\S]*?\\])|(\\\([\s\S]*?\\\))/g,
MathJs_Replace: "ANKI_MATHJS_REPLACE",
censor: function (note_text, regexp, mask) {
let matches = [];
censorCodeTag: function (note_text) {
return this._censor(note_text, ANKI_CODE_REGEXP, ANKI_CODE_REPLACE)
},
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)
},
decensorMJXTag: function (note_text, replacements) {
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)) {
matches.push(match[0])
}
return [note_text.replace(regexp, mask), matches]
},
decensor: function (note_text, mask, replacements) {
_decensor: function (note_text, mask, replacements) {
for (let replacement of replacements) {
note_text = note_text.replace(mask, replacement)
}
return note_text
}
};
}
}
}
function hideCard() {
const qa = document.getElementById("qa");
if (qa) {
qa.classList.remove("qa-visible");
// 隐藏卡片内容
function hideQAContent() {
// 卡片的内容都是放在 id 为 qa 的 div 中
let qaElement = document.getElementById("qa");
if (qaElement) {
qaElement.style.opacity = "0";
}
}
function showCard() {
const qa = document.getElementById("qa");
if (qa) {
qa.classList.add("qa-visible");
// 显示卡片内容
function showQAContent() {
let answerHr = document.getElementById("answer");
if (answerHr) {
answerHr.style.opacity = "1";
}
let qaElement = document.getElementById("qa");
if (qaElement) {
qaElement.style.opacity = "1";
}
}
</script>

View File

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