Compare commits

...

34 Commits

Author SHA1 Message Date
laishunchao d91a14290f fix: 更新README,移除字节cdn信息并添加开发调试说明 2025-09-19 10:16:04 +08:00
laishunchao 24f1f6fe99 移除 字节cdn(已倒闭) 2025-09-18 19:37:32 +08:00
小能饼干 7012a00c54
Merge pull request #23 from aisahpA/dev
perf: 优化代码
2025-05-13 15:53:39 +08:00
kadimi 709b487a15 perf: 优化代码
1、去掉数学工具 katex 的引用,不再支持$格式的数学公式,请将$格式转换为\(...\)或\[...\]格式
2、将数学公式相关的内容隐藏起来,避免 markdown 转换导致公式失效
3、优化执行逻辑,只在第一次使用异步,后面卡片都使用同步模式(安卓端逻辑不一样,每次都是新的页面)
4、优化日志工具中内容的展示
5、添加模板导入牌组
2025-05-13 15:37:57 +08:00
小能饼干 d4ce1c8d0d
Merge pull request #22 from aisahpA/feature_数学公式 2025-05-06 22:17:21 +08:00
kadimi 4882f7b1d9 fix: 安卓端无法渲染 Anki 编辑的数学公式
1、markdownit 的 delimiters 添加配置 'brackets',让安卓端正常解析 Anki 编辑的数学公式
2、更改卡片隐藏显示方式,让外层 div 来控制
3、更改日志信息存放的位置,以便切换到其它模版时可删除日志
2025-05-06 20:29:23 +08:00
小能饼干 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
小能饼干 afd9ca5427
Merge pull request #20 from aisahpA/master 2025-04-30 22:00:55 +08:00
kadimi 5fa9e09b7d fix:隐藏数学公式转换异常,优化日志、优化<code></code>包裹代码处理
1、配置 config_showMathError 显示/隐藏数学公式转换异常
2、优化日志显示,配置 config_logLevel 可指定日志级别
3、<code></code>包裹的代码原样输出
2025-04-30 21:56:31 +08:00
小能饼干 97c03a0fcd
Merge pull request #19 from aisahpA/master
feat:支持数学公式
2025-04-29 15:57:55 +08:00
kadimi c37941fad8 feat:支持数学公式 2025-04-29 15:49:09 +08:00
DESKTOP-T47KVGU\15404 43d37b2a68 chore: 回滚数学公式的解析代码 2025-04-29 00:22:22 +08:00
laishunchao 7607fb89a9 feat: 添加数学公式的解析 2025-04-15 11:49:19 +08:00
laishunchao 580f442c57 chore: 文件结构调整 2025-04-15 11:13:40 +08:00
laishunchao 3185864cef chore: 回滚卡片模板内容 + 上传最新修复的卡组导出 2025-04-14 21:14:35 +08:00
laishunchao 55f1eb6835 temp: mathJax 数学公式测试 2025-04-14 21:07:14 +08:00
小能饼干 e478eb5a83
Merge pull request #17 from xuanqb/patch-1
fix:安卓端渲染失败
2025-04-12 13:39:37 +08:00
港島小叔子 f28502348d
fix:安卓端渲染失败 2025-04-11 20:23:32 +08:00
港島小叔子 d1db63d7d3
fix:安卓端渲染失败 2025-04-11 18:41:34 +08:00
小能饼干 a8fafb73fc
Update README.md 2025-02-12 16:59:38 +08:00
laishunchao f5825eedde idea 配置文件 2025-02-12 14:37:57 +08:00
laishunchao 4dbee55934 readme 计划修改 2025-02-12 14:37:30 +08:00
小能饼干 46a35668d4
Update README.md 2025-02-08 16:29:18 +08:00
laishunchao f7eb78de31 feat: 重构为2.0 2025-02-08 16:17:20 +08:00
小能饼干 6a9286dc9a
Update README.md 2024-10-31 19:44:30 +08:00
小能饼干 df579900f6
Update README.md 2024-10-31 19:41:35 +08:00
小能饼干 6683c74674
Update README.md 2024-10-28 23:19:37 +08:00
aote777 58ab3e149c fix 2024-03-12 21:44:18 +08:00
aote777 3447f33768 fix 2024-03-12 21:31:20 +08:00
aote777 1d243084a5 更新最新卡片模板 2024-03-11 11:47:40 +08:00
小能饼干 cad6601b31
Merge pull request #8 from LemonPrefect/patch-1
fix(template): make anki equation render normal, first line no <pre>
2024-03-09 21:11:31 +08:00
Saphir Gu 9bceaad978
fix(template): make anki equation render normal, first line no <pre>
When there's space leading the first line, it'll be parsed to be a codeblock. use `.trim` to prevent this.
Make html render to `true` in case of anki equation needed.
2024-03-09 21:07:40 +08:00
aote777 6ef27ee8ff fix 2024-03-06 18:51:16 +08:00
13 changed files with 819 additions and 583 deletions

6
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"recommendations": [
"esbenp.prettier-vscode",
"shd101wyy.markdown-preview-enhanced"
]
}

View File

@ -1,18 +1,17 @@
> **2.0 版本来了使用更简洁的js脚本流程**
# 可以解析`markdown`语法的`anki`卡片模板。
# 特点:纯文本代码模板 无需任何插件。复制就能用
> 核心markdown解析器 👉[markdown-it](https://github.com/markdown-it/markdown-it)
> `https://github.com/markdown-it/markdown-it`
> **核心代码在`demo.html`中** > **不想手动创建模板,可以直接导入我上传好的牌组(./markdown.apkg),就会自动导入卡片模板了**
# 可以解析`markdown`语法的`anki`卡片模板。
👇 目前的功能(有什么改进可以在 issue 里提 有能力可以自行修改提 pr,喜欢的兄弟姐妹们可以点个star支持一下
> cdn 引入所需资源(使用的字节的公共库,根据自己的网络情况替换),无需任何本地媒体文件。
> 跟着复制代码就完事了 , 或者直接导入现成的牌组获取
👇 这个是具体操作步骤。只看这里的操作步骤就好 卡片模板代码已 GitHub 上为准(是最新的)。
`https://www.jianshu.com/p/57b84a7a3c75` [点我跳转](https://www.jianshu.com/p/57b84a7a3c75)
👇 目前的功能(有什么改进可以在 issue 里提 有能力可以自行修改提 pr
- [x] 代码自动高亮
- [x] 全部样式风格采用`github-markdown-css` css 样式文件修改成自动识别系统主题(是否是暗黑模式) 以前的版本可以修改一下 cdn 地址
@ -25,21 +24,36 @@
- [x] 图片直接截图或者保存 cv 就行
- [x] pr 提了个 html 字符反转义合上去了 不需要可以自行去掉
- [x] html 字符反转义
---
**缺陷**
1.~~代码段中输入的空格会被 markdown 转义 直接输出 nbsp;~~ (修复)
1. ~~代码段中输入的空格会被 markdown 转义 直接输出 nbsp;~~ (修复)
2. windows中的anki github-markdown-css 样式库 暗黑模式失效ios中可以自动切换到暗黑模式 有空看看什么原因
---
**cdn 仓库(~~慢的可以自己换成国内的 cdn 仓库~~换成字节的 cdn 库了国内速度挺快)**
**cdn 仓库(请勿继续使用字节cdn 已倒闭)**
****
#### 如果样式或者解析失效
可能是网络的问题,因为是采用 cdn 加载资源 不是本地
大部分是是网络的问题,因为是采用 cdn 加载资源 不是本地
可以反复刷新 或者 切换网络尝试修复一下
或者把梯子关了(或者自己设置规则) 因为默认用的是字节的cdn库
### 卡片模板创建新手指引(或直接导入仓库现成的 `.apkg` 牌组)
1. 正面模板内容 完整复制仓库 `./卡片正面内容模板.txt` 的内容
2. 背面内容模板 完整复制仓库 `./卡片北面面内容模板.txt` 的内容
3. 样式 完整复制仓库`./卡片样式.css` 文件的内容
#### 开发调试
使用 `./card-demo-dev-test.html` 开启live server 浏览器中调试
在anki 卡片模板预览中 实时调试

200
card-demo-dev-test.html Normal file
View File

@ -0,0 +1,200 @@
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.8.1/github-markdown.min.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/styles/base16/onedark.min.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/markdown-it-texmath@1.0.0/css/texmath.min.css"
/>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css"
/>
<title>anki-md模板测试chrome等浏览器开发测试即可</title>
</head>
<style>
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
/* 初始状态下设置透明度为0 */
.md-content {
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
</style>
<body>
<!-- prettier-ignore -->
<div class="md-content">
### 我看showdown真是老糊涂了
</div>
<!-- prettier-ignore -->
<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$$
***
> 呵呵呵
# 一级标题
## 二级标题
### 三级标题
---
**加粗**
*斜体*
***加粗斜体***
---
> 引用
---
- 无序列表
---
1. 有序列表
---
[链接](https://www.baidu.com)
---
![图片](https://www.baidu.com/img/bd_logo1.png)
---
`行内代码`
---
```javascript
// 代码块
console.log('hello world')
```
</div>
<script>
var getResources = [
getScript(
"https://gcore.jsdelivr.net/npm/markdown-it@14.1.0/dist/markdown-it.min.js"
),
getScript(
"https://gcore.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js"
),
// getScript(
// "https://cdn.jsdelivr.net/npm/markdown-it-texmath@1.0.0/texmath.min.js"
// ),
// getScript(
// "https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.js"
// ),
];
// 加载资源并初始化
Promise.all(getResources)
.then(() => {
parseMarkDownFn();
})
.catch((error) => {
consoleLog("Failed to load required resources: " + error);
});
function getScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.onload = resolve;
script.onerror = () =>
reject(new Error(`Failed to load script from ${url}`));
script.src = url;
document.head.appendChild(script);
});
}
// 在anki中通过窗口查看调试信息 没控制台啊
function consoleLog(str) {
var div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
}
// 清除br标签
// anki自动生成的<br>全部干掉 严格按照原生换行来写
var clearBR = (str) => {
str = str.replace(/<br>/g, "\r\n");
return str;
};
// 清除空格实体字符
var clearBlankNbsp = (str) => {
str = str.replace(/&nbsp;/g, " ");
return str;
};
// 反转义 HTML 实体,确保卡片中所有的符号正常
// Eg. #include <stdio.h>
var unescapeHTMLEntities = (innerHTML) =>
Object.assign(document.createElement("textarea"), { innerHTML }).value;
// 解析入口main方法
var parseMarkDownFn = () => {
const md = markdownit({
html: true, // 若为 false 将导致 anki 自带的公式渲染失效。
linkify: true,
typographer: true,
breaks: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, { language: lang }).value;
} catch (__) {}
}
return ""; // use external default escaping
},
});
// md.use(texmath, {
// engine: katex,
// delimiters: "dollars",
// katexOptions: { macros: { "\\RR": "\\mathbb{R}" } },
// });
document.querySelectorAll(".md-content").forEach((div, index) => {
console.log("查找到的容器元素", div);
// 需要去除首尾空格 不然markdown-it会解析错误
var text = unescapeHTMLEntities(div.innerHTML).trim();
console.log("text", text);
// 清除br标签
text = clearBR(text);
// 👇关键核心md转换
var html = md.render(text);
var newDiv = document.createElement("div");
var hr = document.createElement("hr");
newDiv.innerHTML = html;
// 激活github-markdown-css
newDiv.className = "markdown-body";
div.parentNode.insertBefore(newDiv, div.nextSibling);
index === 1 ? div.parentNode.insertBefore(hr, div.nextSibling) : null;
div.className = `x-${index}`;
div.style.display = "none";
// 不能从body直接插入元素 anki 不刷新的
});
};
</script>
</body>
</html>

201
demo.html
View File

@ -1,201 +0,0 @@
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>anki-md模板测试</title>
</head>
<style>
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 45px;
}
@media (max-width: 767px) {
.markdown-body {
padding: 15px;
}
}
/* 初始状态下设置透明度为0 */
.md-content {
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
</style>
<body>
<!-- prettier-ignore -->
<div class="md-content">
### 我看showdown真是老糊涂了
</div>
<!-- prettier-ignore -->
<div class="md-content">
> 呵呵呵
> 呵呵呵哈哈哈哈
> 喜喜
# 一级标题
## 二级标题
### 三级标题
#### 四级标题
##### 五级标题
###### 六级标题
---
**加粗**
*斜体*
***加粗斜体***
---
> 引用
---
- 无序列表
- 无序列表
- 无序列表
---
1. 有序列表
2. 有序列表
3. 有序列表
---
[链接](https://www.baidu.com)
---
![图片](https://www.baidu.com/img/bd_logo1.png)
---
`行内代码`
---
```javascript
// 代码块
console.log('hello world')
```
</div>
<script>
'use strict'
// 在anki中查看调试信息 没控制台啊
function consoleLog(str) {
var div = document.createElement('div')
div.innerHTML = str
document.body.appendChild(div)
}
// https://github.com/markdown-it/markdown-it
var MARKDOWN_IT_CDN =
'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/markdown-it/12.3.2/markdown-it.min.js'
// 代码高亮库
var HIGHLIGHT_JS_CDN =
'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/highlight.js/11.4.0/highlight.min.js'
// 代码高亮样式
var HIGHLIGHT_CSS_CDN =
'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/highlight.js/11.4.0/styles/base16/onedark.min.css'
// github-markdown-css
var GITHUB_MARKDOWN_CSS_CDN =
'https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/github-markdown-css/5.1.0/github-markdown.min.css'
// 加载库文件
var createScript = (src) => {
var scriptElement = document.createElement('script')
scriptElement.src = src
scriptElement.async = true
scriptElement.type = 'text/javascript'
document.head.appendChild(scriptElement)
return new Promise((resolve) => {
scriptElement.onload = function () {
resolve(src)
}
})
}
// 加载css文件
var createLink = (url) => {
var linkElement = document.createElement('link')
linkElement.rel = 'stylesheet'
linkElement.href = url
linkElement.onload = () => {}
document.head.appendChild(linkElement)
}
createLink(GITHUB_MARKDOWN_CSS_CDN)
createLink(HIGHLIGHT_CSS_CDN)
// 清除br标签
// anki自动生成的<br>全部干掉 严格按照原生换行来写
var clearBR = (str) => {
str = str.replace(/<br>/g, '\r\n')
return str
}
// 清除空格实体字符
var clearBlankNbsp = (str) => {
str = str.replace(/&nbsp;/g, ' ')
return str
}
// 反转义 HTML 实体,确保卡片中所有的符号正常
// Eg. #include <stdio.h>
var unescapeHTMLEntities = (innerHTML) =>
Object.assign(document.createElement('textarea'), { innerHTML }).value
// 解析入口main方法
var parseMarkDownFn = () => {
const md = markdownit({
html: false,
linkify: true,
typographer: true,
breaks: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, { language: lang }).value
} catch (__) {}
}
return '' // use external default escaping
},
})
document.querySelectorAll('.md-content').forEach((div, index) => {
console.log('查找到的容器元素', div)
// 需要去除首尾空格 不然markdown-it会解析错误
var text = unescapeHTMLEntities(div.innerHTML)
console.log('text', text)
// 清除br标签
text = clearBR(text)
// 👇关键核心md转换
var html = md.render(text)
var newDiv = document.createElement('div')
var hr = document.createElement('hr')
newDiv.innerHTML = html
// 激活github-markdown-css
newDiv.className = 'markdown-body'
div.parentNode.insertBefore(newDiv, div.nextSibling)
index === 1 ? div.parentNode.insertBefore(hr, div.nextSibling) : null
div.className = `x-${index}`
div.style.display = 'none'
// 不能从body直接插入元素 anki 不刷新的
})
}
createScript(HIGHLIGHT_JS_CDN)
.then(() => {
return createScript(MARKDOWN_IT_CDN)
})
.then(() => {
// anki模板无法使用window.onload我怀疑是被占用了
parseMarkDownFn()
})
.then(() => {
// 清除重复项 试试
var repeatEl = document.querySelectorAll('.x-0')
repeatEl.forEach((el, i) => {
if (i === repeatEl.length - 1) {
return
}
document.body.removeChild(el)
})
})
</script>
</body>
</html>

Binary file not shown.

View File

@ -1,371 +0,0 @@
/*
把这里的样式代码 复制到卡片模板 的样式区域
*/
/* github样式 */
.markdown-body {
box-sizing: border-box;
min-width: 200px;
max-width: 980px;
margin: 0 auto;
padding: 32px;
}
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
/* Document
========================================================================== */
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in iOS.
*/
html {
line-height: 1.15; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
width: 100%;
height: 100%;
}
/* Sections
========================================================================== */
/**
* Remove the margin in all browsers.
*/
body {
margin: 0;
background: #fff;
width: 100%;
height: 100%;
text-align: left;
}
/**
* Render the `main` element consistently in IE.
*/
main {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/* Grouping content
========================================================================== */
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/* Text-level semantics
========================================================================== */
/**
* Remove the gray background on active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* 1. Remove the bottom border in Chrome 57-
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
========================================================================== */
/**
* Remove the border on images inside links in IE 10.
*/
img {
border-style: none;
}
/* Forms
========================================================================== */
/**
* 1. Change the font styles in all browsers.
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: 1.15; /* 1 */
margin: 0; /* 2 */
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input {
/* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select {
/* 1 */
text-transform: none;
}
/**
* Correct the inability to style clickable types in iOS and Safari.
*/
button,
[type='button'],
[type='reset'],
[type='submit'] {
-webkit-appearance: button;
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type='button']::-moz-focus-inner,
[type='reset']::-moz-focus-inner,
[type='submit']::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type='button']:-moz-focusring,
[type='reset']:-moz-focusring,
[type='submit']:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Correct the padding in Firefox.
*/
fieldset {
padding: 0.35em 0.75em 0.625em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
vertical-align: baseline;
}
/**
* Remove the default vertical scrollbar in IE 10+.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10.
* 2. Remove the padding in IE 10.
*/
[type='checkbox'],
[type='radio'] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type='number']::-webkit-inner-spin-button,
[type='number']::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type='search'] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding in Chrome and Safari on macOS.
*/
[type='search']::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive
========================================================================== */
/*
* Add the correct display in Edge, IE 10+, and Firefox.
*/
details {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Misc
========================================================================== */
/**
* Add the correct display in IE 10+.
*/
template {
display: none;
}
/**
* Add the correct display in IE 10.
*/
[hidden] {
display: none;
}

View File

@ -0,0 +1,21 @@
@import url('https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.8.1/github-markdown.min.css');
@import url('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.11.1/styles/base16/onedark.min.css');
@import url('https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css');
/* @import url('https://cdn.jsdelivr.net/npm/markdown-it-texmath@1.0.0/css/texmath.min.css'); */
/* @import url('https://cdn.jsdelivr.net/npm/katex@0.16.22/dist/katex.min.css'); */
/*
把这里的样式代码 ctrl a 复制到卡片模板 的样式区域
*/
/* 初始状态下设置透明度为0 */
.md-content {
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
/* 卡片内容展示样式 */
.markdown-body {
box-sizing: border-box;
min-width: 200px;
margin: 0 auto;
padding: 16px;
}

View File

@ -0,0 +1,94 @@
<div class="md-content">
{{Front}}
</div>
<script>
var getResources = [
getScript("https://gcore.jsdelivr.net/npm/markdown-it@14.1.0/dist/markdown-it.min.js"),
getScript("https://gcore.jsdelivr.net/gh/highlightjs/cdn-release@11.11.1/build/highlight.min.js"),
];
// 加载资源并初始化
Promise.all(getResources)
.then(() => {
parseMarkDownFn();
})
.catch(error => {
consoleLog('Failed to load required resources: ' + error);
});
function getScript(url) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.onload = resolve;
script.onerror = () => reject(new Error(`Failed to load script from ${url}`));
script.src = url;
document.head.appendChild(script);
});
}
// 在anki中通过窗口查看调试信息 没控制台啊
function consoleLog(str) {
var div = document.createElement('div')
div.innerHTML = str
document.body.appendChild(div)
}
// 清除br标签
// anki自动生成的<br>全部干掉 严格按照原生换行来写
var clearBR = (str) => {
str = str.replace(/<br>/g, '\r\n')
return str
}
// 清除空格实体字符
var clearBlankNbsp = (str) => {
str = str.replace(/&nbsp;/g, ' ')
return str
}
// 反转义 HTML 实体,确保卡片中所有的符号正常
// Eg. #include <stdio.h>
var unescapeHTMLEntities = (innerHTML) =>
Object.assign(document.createElement('textarea'), { innerHTML }).value
// 解析入口main方法
var parseMarkDownFn = () => {
const md = markdownit({
html: true, // 若为 false 将导致 anki 自带的公式渲染失效。
linkify: true,
typographer: true,
breaks: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, { language: lang }).value
} catch (__) { }
}
return '' // use external default escaping
},
})
document.querySelectorAll('.md-content').forEach((div, index) => {
console.log('查找到的容器元素', div)
// 需要去除首尾空格 不然markdown-it会解析错误
var text = unescapeHTMLEntities(div.innerHTML).trim()
console.log('text', text)
// 清除br标签
text = clearBR(text)
// 👇关键核心md转换
var html = md.render(text)
var newDiv = document.createElement('div')
var hr = document.createElement('hr')
newDiv.innerHTML = html
// 激活github-markdown-css
newDiv.className = 'markdown-body'
div.parentNode.insertBefore(newDiv, div.nextSibling)
index === 1 ? div.parentNode.insertBefore(hr, div.nextSibling) : null
div.className = `x-${index}`
div.style.display = 'none'
// 不能从body直接插入元素 anki 不刷新的
})
}
</script>

View File

@ -0,0 +1,3 @@
{{FrontSide}}
<div class="md-content">{{Back}}</div>

View File

@ -0,0 +1,134 @@
<!DOCTYPE html>
<html lang="cn" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="样式.css">
<title>Anki-Markdown 模板测试</title>
</head>
<style>
.markdown-body {
max-width: 980px;
}
</style>
<body id="qa">
<!-- prettier-ignore -->
<div class="markdown-body">
测试 Markdown 格式
***
# 一级标题
## 二级标题
### 三级标题
**加粗**
*斜体*
***加粗斜体***
> 引用
引用第二行
引用第三行
- 无序列表
- 无序列表
- 无序列表
1. 有序列表 1
2. 有序列表 2
3. 有序列表 3
</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);
}
```
代码块 2
```python
sql = "SELECT * FROM your_table"
cursor.execute(sql)
```
代码块 3
<ul>
<li>下面代码的 HTML 格式中 <code>&amp;gt;</code><code>&amp;lt;</code> 不能转义为 &gt;&lt;,否则会有异常的下划线</li>
<li>不转换 <code>&lt;code&gt;&lt;/code&gt;</code>包裹的内容</li>
</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; {
<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-built_in">super</span>(first, second);
}
}
</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) {
$('#templateScriptDiv').html(data)
});
</script>
<div id="templateScriptDiv"></div>
</body>
</html>

View File

@ -0,0 +1,81 @@
@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/normalize.css@8.0.1/normalize.min.css');
.markdown-body {
box-sizing: border-box;
margin: 0 auto;
padding: 16px;
font-size: 20px;
text-align: left; /* left-左对齐center-居中对齐 */
}
#qa {
visibility: hidden !important;
}
#qa.qa-visible {
visibility: visible !important;
}
/* 代码块自动换行,方便手机端查看代码 */
pre code[class*="language-"] {
white-space: pre-wrap;
font-size: 16px;
}
/* Anki 似乎不支持 prefers-color-scheme换一种方式设置暗黑模式 */
.nightMode .markdown-body {
/* dark */
color-scheme: dark;
--focus-outlineColor: #1f6feb;
--fgColor-default: #f0f6fc;
--fgColor-muted: #9198a1;
--fgColor-accent: #4493f8;
--fgColor-success: #3fb950;
--fgColor-attention: #d29922;
--fgColor-danger: #f85149;
--fgColor-done: #ab7df8;
--bgColor-default: #0d1117;
--bgColor-muted: #151b23;
--bgColor-neutral-muted: #656c7633;
--bgColor-attention-muted: #bb800926;
--borderColor-default: #3d444d;
--borderColor-muted: #3d444db3;
--borderColor-neutral-muted: #3d444db3;
--borderColor-accent-emphasis: #1f6feb;
--borderColor-success-emphasis: #238636;
--borderColor-attention-emphasis: #9e6a03;
--borderColor-danger-emphasis: #da3633;
--borderColor-done-emphasis: #8957e5;
--color-prettylights-syntax-comment: #9198a1;
--color-prettylights-syntax-constant: #79c0ff;
--color-prettylights-syntax-constant-other-reference-link: #a5d6ff;
--color-prettylights-syntax-entity: #d2a8ff;
--color-prettylights-syntax-storage-modifier-import: #f0f6fc;
--color-prettylights-syntax-entity-tag: #7ee787;
--color-prettylights-syntax-keyword: #ff7b72;
--color-prettylights-syntax-string: #a5d6ff;
--color-prettylights-syntax-variable: #ffa657;
--color-prettylights-syntax-brackethighlighter-unmatched: #f85149;
--color-prettylights-syntax-brackethighlighter-angle: #9198a1;
--color-prettylights-syntax-invalid-illegal-text: #f0f6fc;
--color-prettylights-syntax-invalid-illegal-bg: #8e1519;
--color-prettylights-syntax-carriage-return-text: #f0f6fc;
--color-prettylights-syntax-carriage-return-bg: #b62324;
--color-prettylights-syntax-string-regexp: #7ee787;
--color-prettylights-syntax-markup-list: #f2cc60;
--color-prettylights-syntax-markup-heading: #1f6feb;
--color-prettylights-syntax-markup-italic: #f0f6fc;
--color-prettylights-syntax-markup-bold: #f0f6fc;
--color-prettylights-syntax-markup-deleted-text: #ffdcd7;
--color-prettylights-syntax-markup-deleted-bg: #67060c;
--color-prettylights-syntax-markup-inserted-text: #aff5b4;
--color-prettylights-syntax-markup-inserted-bg: #033a16;
--color-prettylights-syntax-markup-changed-text: #ffdfb6;
--color-prettylights-syntax-markup-changed-bg: #5a1e02;
--color-prettylights-syntax-markup-ignored-text: #f0f6fc;
--color-prettylights-syntax-markup-ignored-bg: #1158c7;
--color-prettylights-syntax-meta-diff-range: #d2a8ff;
--color-prettylights-syntax-sublimelinter-gutter-mark: #3d444d;
}

View File

@ -0,0 +1,250 @@
<div class="markdown-body">
{{Front}}
</div>
<script>
// 日志级别: debug、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",
];
// 执行内容转换
try {
hideCard();
if (typeof AnkiMarkDownIt !== 'undefined') {
// 可以复用 AnkiMarkDownIt直接执行转换
renderMarkDownFn();
} else {
initDivLog();
initCensorUtil();
initScriptResource(scriptUrls).then(() => {
initAnkiMarkDownIt();
renderMarkDownFn();
});
}
} catch (e) {
console.error(e);
DivLog.error("Error: ", e);
showCard();
}
/**
* 转换卡片内容为 markdown 网页格式
*/
function renderMarkDownFn() {
document.querySelectorAll('.markdown-body').forEach((div) => {
div.innerHTML = renderMarkDown(div.innerHTML);
});
showCard();
}
/**
* 绘制内容为 markdown 网页格式
* @param {string} text
* @returns {string}
*/
function renderMarkDown(text) {
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);
if (code_tag_matches.length > 0) {
DivLog.debug("After hide html tag <code></code>", text);
}
// 隐藏标签 <mjx-container></mjx-container>
let mjx_tag_matches
[text, mjx_tag_matches] = CensorUtil.censor(text, CensorUtil.Mjx_Container_Reg, CensorUtil.Mjx_Container_Replace);
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: ' '};
return entities[type] || '';
})
.replace(/<br>/g, '\n');
DivLog.debug("After reverse some HTML tags", text);
// 转换成 markdown 网页格式
text = AnkiMarkDownIt.render(text);
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)
return text;
}
// 初始化-日志工具
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];
},
debug(...messages) {
this._log(this.levelMap.debug, "", ...messages);
},
info(...messages) {
this._log(this.levelMap.info, "", ...messages);
},
warn(...messages) {
this._log(this.levelMap.warn, "orange", ...messages);
},
error(...messages) {
this._log(this.levelMap.error, "red", ...messages);
},
_log(minLevel, fontColor, ...messages) {
if (minLevel > this.currentLevel || messages.length === 0) {
return;
}
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"));
});
messageDiv.appendChild(document.createElement("hr"));
this._getMsgContainer().appendChild(messageDiv)
},
_getMsgContainer() {
let msgContainer = document.getElementById("msgContainer");
if (!msgContainer) {
msgContainer = document.createElement("div");
msgContainer.id = "msgContainer";
msgContainer.style.textAlign = "left";
msgContainer.style.whiteSpace = "pre-wrap";
// 将日志信息放在最后
let qa = document.getElementById("qa");
if (qa) {
qa.appendChild(msgContainer);
}
}
return msgContainer
},
clearLogDiv() {
const msgContainer = document.getElementById("msgContainer");
if (msgContainer) {
msgContainer.remove();
}
}
};
}
DivLog.setLevel(config_logLevel || "info");
DivLog.clearLogDiv();
}
/**
* 初始化-javascript 资源
* @param scriptUrls 多个资源地址数组
* @returns {Promise<Awaited<unknown>[]>|Promise<void>}
*/
function initScriptResource(scriptUrls) {
if (typeof markdownit !== 'undefined') {
DivLog.info("markdown-it is loaded!")
return Promise.resolve();
}
DivLog.info("markdown-it did not load, re-adding triggers loading!")
return Promise.all(scriptUrls.map(url => {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.onload = resolve;
script.onerror = () => reject(new Error(`Failed to load script from ${url}`));
script.src = url;
document.head.appendChild(script);
});
})).catch(error => {
DivLog.error(error);
throw error;
});
}
// 初始化-markdown-it
function initAnkiMarkDownIt() {
DivLog.info("init AnkiMarkDownIt!")
window.AnkiMarkDownIt = markdownit({
// 配置参考https://markdown-it.docschina.org/api/MarkdownIt.html#markdownit-new
html: true,
linkify: true,
breaks: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, {language: lang}).value
} catch (__) {
}
}
return '';
}
});
}
// 初始化-特殊片段隐藏工具
function initCensorUtil() {
if (typeof CensorUtil === 'undefined') {
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 = [];
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) {
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 showCard() {
const qa = document.getElementById("qa");
if (qa) {
qa.classList.add("qa-visible");
}
}
</script>

View File

@ -0,0 +1,5 @@
{{FrontSide}}
<hr id=answer>
<div class="markdown-body">{{Back}}</div>