mirror of
https://github.com/eternity4719/HowToLiveBetter.git
synced 2026-11-20 08:40:44 +08:00
加 Anki 牌组(issue #97):tools/anki/build.mjs 零依赖生成 .apkg,一条一张问答卡、按节分子牌组,guid 按节号条号固定,重新导入更新内容、保留复习记录;CI 随电子书一起生成并挂到 epub-latest,README 下载行和阅读指引加入口
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
# 正文一改就重新生成三样,挂到固定的 Release「epub-latest」上,下载链接不变:
|
||||
# 正文一改就重新生成四样,挂到固定的 Release「epub-latest」上,下载链接不变:
|
||||
# EPUB https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.epub
|
||||
# PDF https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.pdf
|
||||
# 离线单文件 https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.html
|
||||
# Anki 牌组 https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.apkg
|
||||
# PR 只生成并校验,不发布,产物在 Actions 页面的 artifact 里。
|
||||
name: 电子书
|
||||
|
||||
@@ -111,6 +112,9 @@ jobs:
|
||||
- name: 离线单文件 HTML
|
||||
run: node tools/offline/build.mjs
|
||||
|
||||
- name: Anki 牌组
|
||||
run: node tools/anki/build.mjs
|
||||
|
||||
- name: 装 pandoc、typst 和中文字体
|
||||
run: |
|
||||
sudo apt-get update
|
||||
@@ -143,6 +147,7 @@ jobs:
|
||||
dist/HowToLiveBetter.epub
|
||||
dist/HowToLiveBetter.pdf
|
||||
dist/HowToLiveBetter.html
|
||||
dist/HowToLiveBetter.apkg
|
||||
|
||||
- name: 发布到 Release epub-latest
|
||||
if: github.event_name != 'pull_request'
|
||||
@@ -151,13 +156,14 @@ jobs:
|
||||
run: |
|
||||
git tag -f epub-latest
|
||||
git push -f origin epub-latest
|
||||
notes="正文提交 ${GITHUB_SHA::7},生成于 $(date -u -d '+8 hours' +'%Y-%m-%d %H:%M')(北京时间)。EPUB、PDF、离线单文件 HTML 三样,正文每次更新后自动重新生成,下载链接固定不变。"
|
||||
notes="正文提交 ${GITHUB_SHA::7},生成于 $(date -u -d '+8 hours' +'%Y-%m-%d %H:%M')(北京时间)。EPUB、PDF、离线单文件 HTML、Anki 牌组四样,正文每次更新后自动重新生成,下载链接固定不变。"
|
||||
if gh release view epub-latest >/dev/null 2>&1; then
|
||||
gh release edit epub-latest --title "电子书(EPUB / PDF / 离线 HTML,自动更新)" --notes "$notes"
|
||||
gh release edit epub-latest --title "电子书(EPUB / PDF / 离线 HTML / Anki,自动更新)" --notes "$notes"
|
||||
else
|
||||
gh release create epub-latest --title "电子书(EPUB / PDF / 离线 HTML,自动更新)" --notes "$notes" --latest=false
|
||||
gh release create epub-latest --title "电子书(EPUB / PDF / 离线 HTML / Anki,自动更新)" --notes "$notes" --latest=false
|
||||
fi
|
||||
gh release upload epub-latest \
|
||||
dist/HowToLiveBetter.epub \
|
||||
dist/HowToLiveBetter.pdf \
|
||||
dist/HowToLiveBetter.html --clobber
|
||||
dist/HowToLiveBetter.html \
|
||||
dist/HowToLiveBetter.apkg --clobber
|
||||
|
||||
@@ -93,11 +93,12 @@
|
||||
|
||||
README 开头「这本书想回答的问题」表**一节只占一行**(2026-09-19 用户定):同一个链接贴两遍,读者要在同一个目的地上停两次,两行之间又没有逻辑差别。一节覆盖面宽就在一行里用逗号串几个问题、一个问号收尾(第 19 节「加班费、年休假该怎么算,被裁该拿多少补偿,上班受了伤怎么认定和拿钱?」是范式),不要拆成两行。当天把第 6、8、24 节原有的两行都并掉了,现在是 32 行对 32 节。
|
||||
|
||||
电子版三样,全由 `.github/workflows/book.yml` 在 main 上正文改动后自动生成,挂到固定 Release `epub-latest`(下载链接不变,README 引用的就是它),PR 只生成校验不发布;产物都进 `dist/`(已 gitignore)。**产物本身不入库**,正文几乎天天改,提交二进制只会过时和撑大历史(2026-09-18 issue #12 定的方案)。README 的结构解析和文件清单收在 `tools/lib/book.mjs`,三套构建共用,新增节或长文不用改脚本。**但新增 docs 长文必须手工挂四处链接**(2026-09-21 连漏两次,两次都是用户发现的):① README 顶部导航表格里「长文」那一格(HTML 表格,单元格里必须留空行、用 markdown 写成「[x](docs/x.md)」,写成 `<a href>` 就不被下面那个正则认;2026-09-28 导航区改成表格后不再带「(长文)」后缀);② README 末尾「长文另见」那句;③ README 对应节的目录行(写成「长文见 [docs/x.md](docs/x.md)。」);④ index.html 里 `class="doc-links"` 那一行,URL 要百分号编码。核对办法:`grep -c "docs/<名>.md" README.md` 应为 3,`grep -c "<名>" index.html` 应为 1。第 ① 处是硬性的——`book.mjs` 第 54 行靠正则 `\]\((docs/[^)#/]+\.md)\)` 从 README 里扒长文清单,只在 book/ 条目里链接,EPUB、PDF、离线单文件三套构建都收不到它。sync-stats.ps1 不检查这三处。
|
||||
电子版四样(EPUB、PDF、离线单文件、Anki 牌组),全由 `.github/workflows/book.yml` 在 main 上正文改动后自动生成,挂到固定 Release `epub-latest`(下载链接不变,README 引用的就是它),PR 只生成校验不发布;产物都进 `dist/`(已 gitignore)。**产物本身不入库**,正文几乎天天改,提交二进制只会过时和撑大历史(2026-09-18 issue #12 定的方案)。README 的结构解析和文件清单收在 `tools/lib/book.mjs`,各套构建共用,新增节或长文不用改脚本。**但新增 docs 长文必须手工挂四处链接**(2026-09-21 连漏两次,两次都是用户发现的):① README 顶部导航表格里「长文」那一格(HTML 表格,单元格里必须留空行、用 markdown 写成「[x](docs/x.md)」,写成 `<a href>` 就不被下面那个正则认;2026-09-28 导航区改成表格后不再带「(长文)」后缀);② README 末尾「长文另见」那句;③ README 对应节的目录行(写成「长文见 [docs/x.md](docs/x.md)。」);④ index.html 里 `class="doc-links"` 那一行,URL 要百分号编码。核对办法:`grep -c "docs/<名>.md" README.md` 应为 3,`grep -c "<名>" index.html` 应为 1。第 ① 处是硬性的——`book.mjs` 第 54 行靠正则 `\]\((docs/[^)#/]+\.md)\)` 从 README 里扒长文清单,只在 book/ 条目里链接,EPUB、PDF、离线单文件三套构建都收不到它。sync-stats.ps1 不检查这三处。
|
||||
- **超长的收益、备注和来源在四个出口里都拆成子条目,正文 md 不动**:收益、备注超过 300 字的,在句号处、且下一句开始引用新依据(「X看《…》」「《某条例》」「刑法第…条」「另一项试验」「案例二」等)时断开;来源按括号外的「;」一条一行。规则有两份,`tools/lib/split-items.mjs` 给 EPUB、PDF,index.html 里 `// <split-rules>` 那段给检索网页和离线版,**改一边要同步改另一边**,`node tools/check-split.mjs` 拿全书逐条比对两边结果,也查拆完能不能逐字拼回原文、`**` 有没有被拆开(CI 里是「拆分规则一致性检查」job)。正文仍一个字段一行,index.html 按行解析、sync-stats 按「- 来源:」行数链接都不受影响。
|
||||
- EPUB:`tools/epub/build.mjs`(只依赖 marked,zip 自己打),CI 里跑 epubcheck。本地 `cd tools/epub && npm ci && npm run build`。
|
||||
- EPUB:`tools/epub/build.mjs`(只依赖 marked,zip 用 `tools/lib/zip.mjs` 自己打,Anki 牌组也用它),CI 里跑 epubcheck。本地 `cd tools/epub && npm ci && npm run build`。
|
||||
- 离线单文件 HTML:`tools/offline/build.mjs`(零依赖)把正文**和 docs 长文**内联进 index.html 的 `window.__CORPUS__`(`parts` 放 book/、`docs` 放长文),双击就能看、离线可用;index.html 的 `init()` 认这个变量就不发请求,改 init 的取数逻辑要同时顾到这条路。**检索页的长文是就地弹窗打开的,不跳 GitHub**:点击处统一拦「指向 `docs/*.md` 的 GitHub 链接」(页头那行长文、条目备注里 `hrefOf()` 转出来的相对链接,形状都是这一个),弹窗自带一份可点的章节目录和 scrollspy,markdown 由 index.html 里那个只认标题/段落/列表/表格的小渲染器处理,不引库。长文里如果开始用引用块、代码块这类新语法,要同步加进那个渲染器。
|
||||
- PDF:`tools/pdf/build.mjs` + `tools/pdf/template.typ`,pandoc 转 typst、typst 排版(A4、每节另起一页、页眉带节名、目录带页码、书签到条目级)。本地要 pandoc ≥ 3.1 和 typst ≥ 0.13,用环境变量 `PANDOC`、`TYPST` 指到可执行文件;CI 里按 workflow 顶部 env 里钉的版本下载。版面只改 template.typ。
|
||||
- Anki 牌组:`tools/anki/build.mjs`(零依赖,用 Node 自带的 `node:sqlite`,要 Node ≥ 22.13),issue #97 加的。一条一张问答卡,按节分子牌组,正面节名加标题,背面说人话、成本、性价比、收益量级、口径、证据等级和在线版链接;标签带节号、证据等级、性价比档、口径、争议。性价比规则和 sync-stats 共用 `tools/lib/book.mjs` 的 `COST_W`、`ratioOf`。**笔记 guid 是「hltb-节号-条号」**,牌组和笔记类型的 id 写死,所以重新导入时 Anki 更新内容、保留复习记录;删条目让条号整体减一时,老用户的复习记录会错位一条,这是已知代价。完形填空要逐条人工标,没做。验证办法:scratchpad 里建 venv 装官方 `anki` 包(`pip install --only-binary :all: anki`,不加这个参数会卡在源码构建),用 `import_anki_package` 导入两次,看第二次是否全部算「更新」。
|
||||
|
||||
1. 不要早死(外因:交通、火灾、燃气器具与用气安全、毒蘑菇、溺水、跌落、中毒、疫苗、体检筛查、心理危机(12356 与限制致死手段、自杀念头的时间尺度与未遂之后的长期结局、中毒被救回来之后的不可逆后遗症、高处坠落幸存之后的 ICU 与康复账、摘掉一个肾之后剩余肾的长期代价与卖肾者的随访结局,法律那一侧在第 9 节)、家庭应急装备、安全套与不共用针具、艾滋病的免费自愿咨询检测与窗口期、肉眼血尿等该去查的信号、失控放射源(不捡不拆来路不明的金属件,含源设备与通电产生射线的装置的分界,编在节末因为基础发生率极低);第 37 条是赌博障碍的自杀风险(瑞典登记研究 SMR 自杀 15、总死亡 1.8,2023 年更正男 12.1 女 16.1;B 级,只算了专科病人),落点是 12356 加把钱交给家人管,追加在放射源之后而没插进心理危机那组,免得顺延条号;第 38 条是男男性行为者的暴露前预防药 PrEP(A:iPrEx 44%、PROUD 与 IPERGAY 86%、Fonner 2016 吃药率超七成 RR 0.30;处方药,全国免费政策没查到,按需 2-1-1 只对男男性行为者);第 39、40 条骨质疏松(2026-10-01 按外部建议补):65 岁以上女性和绝经后有危险因素的查 DXA(A 争议:USPSTF 2025 B 级、Kahwati 2025 髋部骨折 RR 0.83、SCOOP 主要终点全部骨质疏松性骨折不显著、过度诊断 11.8% 到 24.1%),查出骨质疏松或脆性骨折过就用药别拿补钙代替(A 争议:Cochrane 2025 阿仑膦酸钠髋部 RR 0.49,Cummings 2019 总死亡率 RR 0.98 不显著;中国指南只拿到 2017 版,2022 版原文没取到);第 41 条(issue #63)上野外冰面前打孔量厚度(C:国内气象局和北京水务局写 15 厘米,美加指南透明冰 10 厘米、白冰翻倍;读者原稿标 A、「规避绝大多数事故」无出处,都没照收);第 42 条(issue #76)用角磨机装好护罩、护目镜加面屏、双手握、别装木工锯片(C:CCOHS、昆士兰 WorkSafe,哈尔滨 2019 与深圳福田 2024 两份事故调查报告都是装带齿锯片没装护罩致死;伤情只有韩国急诊监测和单院病例,收益中凭后果判断;读者原稿的登高作业段删了);第 43 条(issue #94「情绪管理」)直接问身边情绪不对的人有没有想过自杀,问了不会让他更想(B:Gould 2005 JAMA 2342 名中学生随机分组、想过自杀 4.7% 对 3.9% 不显著,Polihronis 2022 荟萃 8 项比较都不显著;收益小,只有替代终点。issue 其余部分「控制自己的情绪」第 3 节第 14、15、17、18、23、24 条已有,「察觉和接住别人的情绪」只有培训课和话术、没有硬终点,没收);装备清单长文放 docs/家庭应急装备清单.md)
|
||||
2. 不要慢慢死(烟酒、运动、睡眠、饮食(含 PR #39 合并后改写的两条食用油:不买小作坊散装自榨花生油,B 级;植物油代替猪油黄油、不必换着买油、亚麻籽油不护心,A 级争议)、久坐——只收效应量大且证据硬的,不追求全;戒烟戒酒不止写收益还写具体办法:戒烟药三类与国内可及性、定戒烟日一次停并提前用尼古丁替代、戒烟门诊与 12320、电子烟(争议,含《电子烟管理办法》的口味与渠道限制)、骨折后接着抽烟骨不愈合 OR 2.32(Scolaro 2014,issue #82 并进第 1 条)、天天大量喝酒的人不能自己硬戒(戒断与震颤谵妄)、简短干预与戒酒药;睡眠那组除夜间时长外还收午睡时长(争议,观察性说长午睡风险高、孟德尔随机化只支持血压腰围,落点是白天困到必须长睡就去查睡眠呼吸暂停等病因)、熬夜之后第二天晚上补觉(补觉指少睡后第一晚多睡,不是攒到周末,与第 3 节第 2 条固定起床不冲突)、上夜班的年数账(剂量反应,只拆账不给结论;出路两条,都写克制:① 夜班时把进食集中在白天(一项 20 人模拟夜班的随机试验 + 一篇只检索到 4 项试验的综述);② 用强光加白天遮光把生物钟搬过去,是唯一被证明真能搬动钟的办法(Czeisler 1990:150 勒克斯六晚不动、7000–12000 勒克斯四天倒过来),但夜里够亮、白天严格遮光、下班戴墨镜三样缺一不可,休息日会打回去,终点只到代谢指标和睡眠;癌症那侧证据远弱于流传说法,IARC 2A 因官网动态加载无法逐字核对故未写;生物钟机制长文放 docs/生物钟和夜班.md);第 42 条做饭开抽油烟机(B 争议,2026-10-01 按外部建议补:Xue 2016 十项病例对照 1.74、不用抽油烟机 2.11,上海女性队列厨房通风差 HR 1.49 但主要落在烧煤人家;甲醛只有儿童哮喘 OR 1.10 和职业暴露、净化器只有替代终点,都没收;成人口腔、听力、视力的空缺候选是老人白内障手术减跌倒,放第 17 节,待查);第 43 条(issue #86)绝经前后潮热盗汗去妇科评估激素治疗,别自己买、别拿来防心脏病(A 争议:Cochrane CD002978 潮热次数少约 75%,WHI 雌孕激素组冠心病 HR 1.29、乳腺癌 1.26、中风 1.41、肺栓塞 2.13,18 年总死亡率 0.99,50 到 59 岁用药期 0.69 但跟到 18 年不显著,USPSTF 2022 D 级;收益按症状终点定大;中国 2023 绝经指南原文取不到没引)
|
||||
|
||||
@@ -25,7 +25,7 @@ AI 助手 skill 支持 Claude Code 和 Codex。装上后直接问「替朋友担
|
||||
<table>
|
||||
<tr><td align="right"><b>下载</b></td><td align="left">
|
||||
|
||||
[PDF](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.pdf) · [EPUB](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.epub) · [离线单文件(HTML)](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.html)
|
||||
[PDF](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.pdf) · [EPUB](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.epub) · [离线单文件(HTML)](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.html) · [Anki 牌组](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.apkg)
|
||||
|
||||
</td></tr>
|
||||
<tr><td align="right"><b>查阅</b></td><td align="left">
|
||||
@@ -118,7 +118,8 @@ AI 助手 skill 支持 Claude Code 和 Codex。装上后直接问「替朋友担
|
||||
- **想离线看、想发给别人**:下载 [离线单文件 HTML](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.html),整本书连同检索和筛选都在这一个文件里,双击就开,不用服务器也不用联网,微信里也能直接传。
|
||||
- **想打印或在手机上翻**:下载 [PDF](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.pdf),A4 排版、两百多页,带目录页码和书签,每节另起一页。
|
||||
- **想在 Kindle 或其他阅读器上读**:下载 [EPUB 电子书](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.epub),Kindle 用 Send to Kindle 发过去即可。
|
||||
- **三样都是正文每次更新后自动重新生成的**,下载链接固定不变;转发出去的那一份不会跟着更新,以在线版为准。
|
||||
- **想记住、隔几天复习一遍**:下载 [Anki 牌组](https://github.com/eternity4719/HowToLiveBetter/releases/download/epub-latest/HowToLiveBetter.apkg),用 Anki 打开就导入。一条一张卡,按节分成子牌组。正面是建议,背面是说人话、成本和证据等级。可以只学其中几节,也可以按「性价比极高」这类标签筛。以后重新下载再导入一次,卡片内容会更新,复习记录不丢。
|
||||
- **这四样都是正文每次更新后自动重新生成的**,下载链接固定不变;转发出去的那一份不会跟着更新,以在线版为准。
|
||||
- **看不懂那串数字**:每条都有一行「说人话」。它把「收益」栏里那些研究里的写法,翻成「同期死亡的概率低约两成」「拘留几日、罚多少钱」这样的日常说法。它只用「收益」栏已经写到的内容,不添新数字。只看这一行就够拿主意。「收益」栏里原样留着全部数字,想自己核对就看那一栏。
|
||||
- **只想看结论最硬的**:在检索页里勾选证据等级 A,只留下有具体数字、来自荟萃分析或大型试验的 438 条。
|
||||
- **只想看最值得做的**:勾选性价比「极高」,得到 114 条既不花钱、不花时间、不需要毅力,收益又落在最大一档的条目。再叠加一个「换回什么」,就是该口径下的优先清单。
|
||||
@@ -150,12 +151,13 @@ python -m http.server 8000
|
||||
|
||||
然后浏览器开 `http://localhost:8000/`。检索页是纯静态的,`README.md` 和 `book/` 就是它的数据,没有后端、没有数据库、不用装依赖;把整个目录丢给任何静态服务器(Nginx、GitHub Pages、对象存储)效果一样。注意 `index.html` 必须经 http 打开,直接双击本地文件会空白——浏览器不许网页读本地文件,那种场景请用上面的离线单文件版。
|
||||
|
||||
想自己生成三样电子版(平时用不着,Release 里的就是自动生成的):
|
||||
想自己生成这四样(平时用不着,Release 里的就是自动生成的):
|
||||
|
||||
```bash
|
||||
cd tools/epub && npm ci && npm run build # EPUB
|
||||
node tools/offline/build.mjs # 离线单文件 HTML
|
||||
node tools/pdf/build.mjs # PDF,另需 pandoc ≥ 3.1 和 typst ≥ 0.13
|
||||
node tools/anki/build.mjs # Anki 牌组,要 Node ≥ 22.13(用自带的 node:sqlite)
|
||||
```
|
||||
|
||||
产物都在 `dist/`。
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
// 把全书条目做成一副 Anki 牌组(.apkg),一条一张问答卡,按节分子牌组(issue #97)。
|
||||
// 用法:node tools/anki/build.mjs [输出路径] 默认输出 dist/HowToLiveBetter.apkg
|
||||
//
|
||||
// 卡片正面是节名和条目标题,背面是说人话、成本、性价比、收益量级、口径和证据等级,再给一个在线版链接。
|
||||
// 标题本身就是建议,所以正面不挖空;复习时回想的是「为什么值得做、代价多大」。
|
||||
// 挖空要逐条人工标,新增条目也得跟着标,维护不起,所以只做自动生成的这一种。
|
||||
//
|
||||
// 零依赖:.apkg 就是一个 zip,里面一个 SQLite 库(Anki 2.1 的旧版库结构,各版本 Anki 都能导入)
|
||||
// 加一个媒体清单。库用 Node 自带的 node:sqlite 写,zip 用 tools/lib/zip.mjs。
|
||||
//
|
||||
// 重新导入时 Anki 按笔记的 guid 认「同一张卡」:内容更新、复习记录保留。guid 取「节号-条号」,
|
||||
// 所以条目只追加在节末(CLAUDE.md 本来就这么要求)就不会串;删条目让后面的条号整体减一时,
|
||||
// 老用户那边的卡会对到新内容上,复习记录跟着错位一条,这个代价能接受。
|
||||
// 牌组、笔记类型的 id 写死,也是为了重新导入时合进原来那副牌,不另起一副。
|
||||
import { writeFileSync, readFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
|
||||
import { resolve, dirname, join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { zip } from '../lib/zip.mjs';
|
||||
import { ROOT, SITE, TITLE, read, readBook, COST_W, ratioOf, gitCommit, buildStamp } from '../lib/book.mjs';
|
||||
|
||||
const OUT = resolve(ROOT, process.argv[2] ?? 'dist/HowToLiveBetter.apkg');
|
||||
const NOW = new Date();
|
||||
const NOW_S = Math.floor(NOW.getTime() / 1000);
|
||||
const NOW_MS = NOW.getTime();
|
||||
|
||||
const MODEL_ID = 1759900000001;
|
||||
const ROOT_DECK_ID = 1759900000100;
|
||||
const deckId = sec => ROOT_DECK_ID + Number(sec);
|
||||
const noteId = (sec, n) => 1759900100000 + Number(sec) * 1000 + Number(n);
|
||||
const cardId = (sec, n) => 1759900200000 + Number(sec) * 1000 + Number(n);
|
||||
|
||||
// ---------- 读条目 ----------
|
||||
const FIELD = { 成本: 'cost', 说人话: 'human', 证据等级: 'grade', 备注: 'note' };
|
||||
|
||||
function parseSection(md) {
|
||||
const head = md.match(/^# (\d+)\. (.+)$/m);
|
||||
if (!head) throw new Error('节文件第三行应该是「# N. 节名」');
|
||||
const entries = [];
|
||||
let e = null;
|
||||
for (const line of md.split('\n')) {
|
||||
const h = line.match(/^### (\d+)\. (.+)$/);
|
||||
if (h) { e = { n: h[1], title: h[2].trim() }; entries.push(e); continue; }
|
||||
if (!e) continue;
|
||||
const tag = line.match(/^<!--\s*成本标签:\s*(.*?)\s*-->/);
|
||||
if (tag) {
|
||||
for (const kv of tag[1].split(/\s+/)) { const [k, v] = kv.split('='); e[k] = v; }
|
||||
continue;
|
||||
}
|
||||
const f = line.match(/^- (成本|说人话|证据等级|备注):(.*)$/);
|
||||
if (f) e[FIELD[f[1]]] = f[2].trim();
|
||||
}
|
||||
return { sec: head[1], name: head[2].trim(), entries };
|
||||
}
|
||||
|
||||
const { bookFiles } = readBook();
|
||||
const sections = bookFiles.map(f => parseSection(read(f)));
|
||||
|
||||
// ---------- 字段 ----------
|
||||
const esc = s => String(s ?? '').replace(/\*\*/g, '').replace(/\\([*_])/g, '$1')
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
const pad = n => String(n).padStart(2, '0');
|
||||
const deckName = s => `${TITLE}::${pad(s.sec)} ${s.name}`;
|
||||
|
||||
const FIELDS = ['节', '标题', '说人话', '成本', '要点', '链接'];
|
||||
const notes = [];
|
||||
let due = 0;
|
||||
for (const s of sections) {
|
||||
for (const e of s.entries) {
|
||||
const cost = (COST_W.money[e.钱] ?? 0) + (COST_W.time[e.时间] ?? 0) + (COST_W.will[e.毅力] ?? 0);
|
||||
const ratio = e.收益 ? ratioOf(cost, e.收益) : '';
|
||||
const grade = (e.grade ?? '').match(/^[ABC]/)?.[0] ?? '';
|
||||
const dispute = /^争议/.test(e.note ?? '');
|
||||
const points = [
|
||||
ratio && `性价比${ratio}`,
|
||||
e.收益 && `收益${e.收益}`,
|
||||
e.口径 && `口径:${e.口径}`,
|
||||
grade && `证据 ${grade} 级${dispute ? '(有争议)' : ''}`,
|
||||
].filter(Boolean).join(' · ');
|
||||
const url = `${SITE}#e-${s.sec}-${e.n}`;
|
||||
const fields = [
|
||||
`第 ${s.sec} 节 · ${esc(s.name)} · 第 ${e.n} 条`,
|
||||
esc(e.title),
|
||||
esc(e.human || ''),
|
||||
esc(e.cost || ''),
|
||||
esc(points),
|
||||
`<a href="${url}">在线版看全文和来源</a>`,
|
||||
];
|
||||
const tags = [`第${pad(s.sec)}节`, grade && `证据${grade}`, ratio && `性价比${ratio}`, e.口径 && `口径${e.口径}`, dispute && '争议']
|
||||
.filter(Boolean);
|
||||
notes.push({ s, e, fields, tags, due: due++ });
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 笔记类型和牌组 ----------
|
||||
const CSS = `.card { font-family: "Segoe UI", -apple-system, "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
|
||||
font-size: 18px; line-height: 1.7; text-align: left; max-width: 40em; margin: 0 auto; padding: 0 12px; color: #213547; background: #fff; }
|
||||
.nightMode.card, .night_mode .card { color: rgba(255,255,245,.86); background: #1b1b1f; }
|
||||
.sec { font-size: 13px; color: #67676c; }
|
||||
.q { font-size: 22px; font-weight: 600; margin: 8px 0 12px; }
|
||||
.hint { font-size: 14px; color: #67676c; }
|
||||
.label { font-size: 13px; color: #67676c; margin-top: 14px; }
|
||||
.points { font-size: 14px; margin-top: 14px; }
|
||||
.link { font-size: 14px; margin-top: 14px; }
|
||||
a { color: #3451b2; }
|
||||
.nightMode a, .night_mode a { color: #a8b1ff; }
|
||||
.nightMode .sec, .nightMode .hint, .nightMode .label { color: #98989f; }`;
|
||||
|
||||
const QFMT = `<div class="sec">{{节}}</div>
|
||||
<div class="q">{{标题}}</div>
|
||||
<div class="hint">想一想:为什么值得做,要花多少代价?</div>`;
|
||||
const AFMT = `<div class="sec">{{节}}</div>
|
||||
<div class="q">{{标题}}</div>
|
||||
<hr id="answer">
|
||||
{{#说人话}}<div class="label">说人话</div><div>{{说人话}}</div>{{/说人话}}
|
||||
{{#成本}}<div class="label">成本</div><div>{{成本}}</div>{{/成本}}
|
||||
<div class="points">{{要点}}</div>
|
||||
<div class="link">{{链接}}</div>`;
|
||||
|
||||
const model = {
|
||||
id: MODEL_ID, name: `${TITLE}(问答卡)`, type: 0, mod: NOW_S, usn: -1, sortf: 1, did: ROOT_DECK_ID,
|
||||
tmpls: [{ name: '问答', ord: 0, qfmt: QFMT, afmt: AFMT, did: null, bqfmt: '', bafmt: '' }],
|
||||
flds: FIELDS.map((name, ord) => ({ name, ord, sticky: false, rtl: false, font: 'Arial', size: 20, media: [] })),
|
||||
css: CSS, latexPre: '', latexPost: '', latexsvg: false, req: [[0, 'any', [1]]], tags: [], vers: [],
|
||||
};
|
||||
|
||||
const deck = (id, name, desc = '') => ({
|
||||
id, name, desc, mod: NOW_S, usn: -1, dyn: 0, conf: 1, collapsed: false, browserCollapsed: false,
|
||||
newToday: [0, 0], revToday: [0, 0], lrnToday: [0, 0], timeToday: [0, 0], extendNew: 0, extendRev: 0,
|
||||
});
|
||||
const commit = gitCommit();
|
||||
const rootDesc = `《${TITLE}》全书条目,一条一张卡,按节分子牌组。生成于 ${buildStamp()}(北京时间)`
|
||||
+ `${commit ? `,正文提交 ${commit.slice(0, 7)}` : ''}。正文会继续更新,以 <a href="${SITE}">在线版</a> 为准;`
|
||||
+ '重新下载导入会更新卡片内容,复习记录保留。';
|
||||
const decks = {
|
||||
1: deck(1, 'Default'),
|
||||
[ROOT_DECK_ID]: deck(ROOT_DECK_ID, TITLE, rootDesc),
|
||||
...Object.fromEntries(sections.map(s => [deckId(s.sec), deck(deckId(s.sec), deckName(s))])),
|
||||
};
|
||||
|
||||
const dconf = {
|
||||
1: {
|
||||
id: 1, name: 'Default', mod: 0, usn: 0, maxTaken: 60, autoplay: true, timer: 0, replayq: true, dyn: false,
|
||||
new: { delays: [1, 10], ints: [1, 4, 7], initialFactor: 2500, order: 1, perDay: 20, bury: true, separate: true },
|
||||
rev: { perDay: 200, ease4: 1.3, fuzz: 0.05, ivlFct: 1, maxIvl: 36500, minSpace: 1, bury: true },
|
||||
lapse: { delays: [10], mult: 0, minInt: 1, leechFails: 8, leechAction: 0 },
|
||||
},
|
||||
};
|
||||
const conf = {
|
||||
activeDecks: [1], curDeck: 1, newSpread: 0, collapseTime: 1200, timeLim: 0, estTimes: true, dueCounts: true,
|
||||
curModel: String(MODEL_ID), nextPos: notes.length + 1, sortType: 'noteFld', sortBackwards: false, addToCur: true,
|
||||
};
|
||||
|
||||
// ---------- 写库 ----------
|
||||
const SCHEMA = `
|
||||
CREATE TABLE col (id integer primary key, crt integer not null, mod integer not null, scm integer not null,
|
||||
ver integer not null, dty integer not null, usn integer not null, ls integer not null, conf text not null,
|
||||
models text not null, decks text not null, dconf text not null, tags text not null);
|
||||
CREATE TABLE notes (id integer primary key, guid text not null, mid integer not null, mod integer not null,
|
||||
usn integer not null, tags text not null, flds text not null, sfld integer not null, csum integer not null,
|
||||
flags integer not null, data text not null);
|
||||
CREATE TABLE cards (id integer primary key, nid integer not null, did integer not null, ord integer not null,
|
||||
mod integer not null, usn integer not null, type integer not null, queue integer not null, due integer not null,
|
||||
ivl integer not null, factor integer not null, reps integer not null, lapses integer not null, left integer not null,
|
||||
odue integer not null, odid integer not null, flags integer not null, data text not null);
|
||||
CREATE TABLE revlog (id integer primary key, cid integer not null, usn integer not null, ease integer not null,
|
||||
ivl integer not null, lastIvl integer not null, factor integer not null, time integer not null, type integer not null);
|
||||
CREATE TABLE graves (usn integer not null, oid integer not null, type integer not null);
|
||||
CREATE INDEX ix_notes_usn on notes (usn);
|
||||
CREATE INDEX ix_cards_usn on cards (usn);
|
||||
CREATE INDEX ix_revlog_usn on revlog (usn);
|
||||
CREATE INDEX ix_cards_nid on cards (nid);
|
||||
CREATE INDEX ix_cards_sched on cards (did, queue, due);
|
||||
CREATE INDEX ix_revlog_cid on revlog (cid);
|
||||
CREATE INDEX ix_notes_csum on notes (csum);`;
|
||||
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'anki-'));
|
||||
const dbPath = join(tmp, 'collection.anki2');
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec(SCHEMA);
|
||||
const dayStart = Math.floor(new Date(NOW.getFullYear(), NOW.getMonth(), NOW.getDate()).getTime() / 1000);
|
||||
db.prepare('INSERT INTO col VALUES (1, ?, ?, ?, 11, 0, 0, 0, ?, ?, ?, ?, ?)').run(
|
||||
dayStart, NOW_MS, NOW_MS, JSON.stringify(conf), JSON.stringify({ [MODEL_ID]: model }),
|
||||
JSON.stringify(decks), JSON.stringify(dconf), '{}');
|
||||
|
||||
const stripHtml = s => s.replace(/<[^>]+>/g, '').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||
const csum = s => parseInt(createHash('sha1').update(stripHtml(s)).digest('hex').slice(0, 8), 16);
|
||||
const insNote = db.prepare('INSERT INTO notes VALUES (?, ?, ?, ?, -1, ?, ?, ?, ?, 0, \'\')');
|
||||
const insCard = db.prepare('INSERT INTO cards VALUES (?, ?, ?, 0, ?, -1, 0, 0, ?, 0, 0, 0, 0, 0, 0, 0, 0, \'\')');
|
||||
db.exec('BEGIN');
|
||||
for (const { s, e, fields, tags, due } of notes) {
|
||||
const sortField = fields[model.sortf];
|
||||
insNote.run(noteId(s.sec, e.n), `hltb-${s.sec}-${e.n}`, MODEL_ID, NOW_S, ` ${tags.join(' ')} `,
|
||||
fields.join('\x1f'), stripHtml(sortField), csum(sortField));
|
||||
insCard.run(cardId(s.sec, e.n), noteId(s.sec, e.n), deckId(s.sec), NOW_S, due);
|
||||
}
|
||||
db.exec('COMMIT');
|
||||
db.close();
|
||||
const collection = readFileSync(dbPath);
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
|
||||
// ---------- 打包 ----------
|
||||
mkdirSync(dirname(OUT), { recursive: true });
|
||||
writeFileSync(OUT, zip([
|
||||
{ name: 'collection.anki2', data: collection },
|
||||
{ name: 'media', data: Buffer.from('{}') },
|
||||
], NOW));
|
||||
const missing = notes.filter(x => !x.fields[2]).length;
|
||||
console.log(`已生成 ${OUT}:${sections.length} 节 ${notes.length} 张卡${missing ? `,其中 ${missing} 张缺说人话` : ''}`);
|
||||
Reference in New Issue
Block a user