nomadro/apps/miniprogram/xhs/release/book/app.js
eric 9f8fec1723 Ship portal PC/H5 acceptance, VIP ScrollReader, admin analytics and ops anchors.
Adds /api/health, ntfy notify on config save, /admin/analytics charts, and deploy smoke for miniprogram config/API.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 23:52:00 -05:00

3798 lines
126 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* bundled classic script for xhs minitool */
// Auto-generated by scripts/build_book_data.py — do not edit by hand.
var BOOK_DATA = {
"id": "nomad-solopreneur",
"title": "数字游民 · 一人公司小册",
"subtitle": "写给想把生活与工作重新排布的人",
"author": "Eric的云游日记",
"cover_emoji": "🌏",
"description": "数字游民与一人公司行动地图:地理套利、技能变现、内容资产与30天清单。",
"tags": [
"数字游民",
"一人公司",
"远程工作",
"副业"
],
"chapter_count": 16,
"word_count": 3390,
"is_free": true,
"chapters": [
{
"id": "c1",
"title": "写在前面",
"order": 1,
"content": "> 写给想把生活与工作重新排布的人 \n> 整理自 Eric的云游日记 · 仅供参考 · 持续更新\n\n---\n\n## 写在前面\n\n\n你手里这份小册,不是「一夜暴富教程」,而是一份**把技能做成可带走的收入**的行动地图。\n\n数字游民(Digital Nomad)的本质很简单:\n\n- 收入主要来自互联网与远程协作\n- 人不被一座城市、一份坐班绑死\n- 用**地理套利**把收入换成更舒服的生活与节奏\n\n一人公司(Solopreneur)则是另一半拼图:\n\n| 维度 | 为什么适合普通人 |\n|------|------------------|\n| 启动成本 | 一部电脑 + 稳定网络就能开工 |\n| 交付形态 | 内容、咨询、小产品、远程服务 |\n| 商业模式 | 少而精的客户,或可复用的数字资产 |\n| 时间自由 | 交付可异步,不必坐班打卡 |\n| 地理套利 | 在生活成本友好的城市,也能稳住现金流 |\n\n**声明:**\n\n- 文中不涉及收费课程强推,也不做账号买卖中介\n- 平台与税务规则会变,请以官方最新政策为准\n- 灰色手段风险极高,后文只作踩坑警示,不鼓励模仿\n\n一个人走得快,一群人走得远。欢迎把这份小册当成随身笔记本,边读边改成你自己的版本。\n\n---\n"
},
{
"id": "c2",
"title": "目录",
"order": 2,
"content": "## 目录\n\n> 请用右上角「目」打开章节列表跳转。\n\n"
},
{
"id": "c3",
"title": "一、为什么普通人适合做「一人公司」",
"order": 3,
"content": "## 一、为什么普通人适合做「一人公司」\n\n\n### 1.1 杠杆变了\n\n过去普通人创业,往往先要资金、团队、仓库。今天更常见的路径是:\n\n- 先卖**时间与专业**(咨询、远程岗位、项目制)\n- 再沉淀成**可复用资产**(模板、手册、小工具、课程笔记)\n- 最后用资产降低「必须人肉交付」的比例\n\n一人公司不是「单打独斗很酷」,而是:**用最小组织,把价值交付跑通**。\n\n### 1.2 你真正卖的是什么\n\n多数成功的一人公司,卖的不是「神秘方法」,而是:\n\n1. **确定性**:帮客户少踩坑、少决策成本 \n2. **结果感**:交付物清晰(文档、方案、成品) \n3. **信任**:真实经历与稳定输出 \n\n如果你还在找「风口」,不如先问:我过去三年反复帮别人解决的问题是什么?\n\n### 1.3 三种起步形态\n\n1. **远程岗位 / 项目制**:最稳,先换现金流 \n2. **内容 + 产品**:把方法论写成可售卖资产 \n3. **小工具 / 自动化**:用产品服务一小群人 \n\n三种可以叠加,但新手建议:**先有一个能稳定收款的主引擎**。\n\n---\n"
},
{
"id": "c4",
"title": "二、数字游民视角:地理套利与生活设计",
"order": 4,
"content": "## 二、数字游民视角:地理套利与生活设计\n\n\n### 2.1 什么是地理套利\n\n数字游民最本质的优势,不是「环球旅行发朋友圈」,而是:\n\n**高购买力收入 × 友好生活成本地区 = 更大的自由现金流**\n\n常见组合:\n\n- 远程收入 → 在国内三四线 / 生活成本友好城市生活 \n- 错峰旅居:淡季交通与房租更松 \n- 把「城市」当成可切换的操作系统,而不是身份标签 \n\n国内常见第一站:气候友好、物价相对友好、网络与快递顺畅的城市。出国旅居请自行评估安全、签证与医疗,不要用幸存者偏差安慰自己。\n\n### 2.2 生活设计先于「逃逸」\n\n真正可持续的游民生活,通常先回答:\n\n1. 每月**最低生存成本**是多少? \n2. 收入波动时,能撑几个月? \n3. 健康、社交、专注环境如何保障? \n\n「先辞职再想办法」很少是好策略。更稳的是:副业跑通 → 缓冲金到位 → 再调整工作形态。\n\n### 2.3 节奏比地点更重要\n\n换城市解决不了拖延与分心。游民需要的是:\n\n- 固定的深度工作时段 \n- 可随身带走的工具与资料 \n- 每周一次复盘:收入、精力、关系 \n\n地点是风景,节奏才是系统。\n\n---\n"
},
{
"id": "c5",
"title": "三、选一条可带走的能力:技能盘点",
"order": 5,
"content": "## 三、选一条可带走的能力:技能盘点\n\n\n### 3.1 能力四象限\n\n把你的技能放进四个格子:\n\n| | 你喜欢 | 你不喜欢 |\n|--|--------|----------|\n| **别人愿意付费** | ★ 优先发展 | 可短期现金牛 |\n| **别人不愿付费** | 爱好,控制投入 | 尽快减少 |\n\n一人公司的主航道,尽量落在「喜欢 × 可付费」。\n\n### 3.2 可带走能力的特征\n\n- 不依赖本地实体店面 \n- 交付可线上完成或可邮寄数字化 \n- 结果可验证(作品集、案例、前后对比) \n\n例如:写作与编辑、设计与演示、研究与报告、自动化与小工具、教学与陪跑、运营与内容策划。\n\n### 3.3 写出你的「一句话供给」\n\n模板:\n\n> 我帮助【谁】,在【场景】下,完成【结果】,方式是【方法】。\n\n写不清楚,就很难定价,也很难被转介绍。\n\n---\n"
},
{
"id": "c6",
"title": "四、收入结构:现金牛、被动底座与试验田",
"order": 6,
"content": "## 四、收入结构:现金牛、被动底座与试验田\n\n\n### 4.1 三种发动机\n\n成熟一点的一人公司,收入通常分层:\n\n```\n远程工作 / 接单(现金牛)\n +\n可复用数字产品(被动底座)\n +\n试验中的新产品(试验田)\n────────────────\n更稳的自由现金流\n```\n\n- **现金牛**:保证这个月能活 \n- **被动底座**:睡后仍可能产生的复利 \n- **试验田**:允许失败的小预算探索 \n\n### 4.2 别过早「只做被动」\n\n被动收入大多是主动交付的副产品。先有人愿意为你的时间付钱,再谈产品化。\n\n### 4.3 每周收入复盘三个数\n\n1. 本周进账 \n2. 本周有效深度工作小时 \n3. 下周唯一最重要目标 \n\n简单到能坚持,比复杂表格有用。\n\n---\n"
},
{
"id": "c7",
"title": "五、内容资产:把经历写成可复用产品",
"order": 7,
"content": "## 五、内容资产:把经历写成可复用产品\n\n\n### 5.1 内容不是表演,是资产生产线\n\n你写过的踩坑、清单、模板、复盘,都可以变成:\n\n- 公开笔记(建立信任) \n- 付费手册 / 模板包 \n- 陪跑与咨询的「说明书」 \n\n### 5.2 最小内容系统\n\n每周固定产出即可,例如:\n\n1. 1 篇深度复盘(问题 → 过程 → 结论) \n2. 3 条短更新(工具、书摘、工作流) \n3. 1 次整理:把旧笔记升级成模板 \n\n持续比爆款重要。\n\n### 5.3 产品化三步\n\n1. **文档化**:把口头经验写成步骤 \n2. **模板化**:别人填空就能用 \n3. **服务化**:仍搞不定的人,可加咨询档 \n\n从文档走到服务,客单价自然抬升。\n\n---\n"
},
{
"id": "c8",
"title": "六、远程工作与接单:先稳住现金流",
"order": 8,
"content": "## 六、远程工作与接单:先稳住现金流\n\n\n### 6.1 远程岗位的好处\n\n- 收入相对可预期 \n- 强迫你建立异步协作习惯 \n- 为一人公司提供「安全垫」 \n\n### 6.2 接单的注意事项\n\n- 范围写清楚(Scope) \n- 修改次数与交付节点写进约定 \n- 预付款 / 阶段款,避免尾款黑洞 \n\n### 6.3 作品集怎么做才有用\n\n不要堆数量,展示:\n\n1. 背景与约束 \n2. 你做了什么关键决策 \n3. 可感知的结果 \n\n三到五个扎实案例,胜过二十个截图。\n\n---\n"
},
{
"id": "c9",
"title": "七、工具栈:够用就好,别被软件绑架",
"order": 9,
"content": "## 七、工具栈:够用就好,别被软件绑架\n\n\n### 7.1 最小工具箱\n\n- 笔记与知识库(能全文搜索) \n- 任务清单(今天只看三件事) \n- 文档与云盘(可跨设备) \n- 日历(保护深度工作块) \n\n能跑通闭环之前,少追新工具。\n\n### 7.2 自动化的正确时机\n\n当你第三次重复同一操作,再自动化。过早自动化,等于给错误流程加速。\n\n### 7.3 AI 的用法\n\n适合:\n\n- 起草、摘要、对照检查 \n- 生成提纲与检查清单 \n\n不适合:\n\n- 代替你对客户结果负责 \n- 输出你自己都看不懂的方案 \n\nAI 是副驾驶,方向盘还在你手里。\n\n---\n"
},
{
"id": "c10",
"title": "八、时间与精力:副业实验的正确姿势",
"order": 10,
"content": "## 八、时间与精力:副业实验的正确姿势\n\n\n### 8.1 副业实验协议\n\n对大多数上班族:\n\n1. 每周固定 6~10 小时实验窗 \n2. 连续 8~12 周再评估去留 \n3. 用「可验证里程碑」代替感觉 \n\n例如:完成作品集、收到第一笔小额付款、沉淀出第一份可售模板。\n\n### 8.2 精力管理三原则\n\n- 难事先做 \n- 社交型任务集中处理 \n- 睡眠与运动是生产力,不是奖励 \n\n### 8.3 防止自我压榨\n\n一人公司最常见的失败不是没单,而是燃尽。给自己定:\n\n- 每周休息日不可谈判 \n- 深度工作有上限(健康优先) \n\n---\n"
},
{
"id": "c11",
"title": "九、定价、边界与客户管理",
"order": 11,
"content": "## 九、定价、边界与客户管理\n\n\n### 9.1 定价从成本倒推不够\n\n还要看:\n\n- 你替代了客户多少决策成本 \n- 市场同类交付的价格带 \n- 你是否提供售后与迭代 \n\n早期可以略低换案例,但要有「涨价日程」。\n\n### 9.2 边界清单(建议抄进笔记)\n\n- 不接什么类型的需求 \n- 沟通时段 \n- 修改次数 \n- 延期如何处理 \n\n边界清晰,关系更久。\n\n### 9.3 客户分级\n\n- A:愿付费、沟通顺、可复购 \n- B:可做,但不优先 \n- C:消耗大、价值低 → 礼貌拒绝 \n\n一人公司的自由,很大程度来自「会拒绝」。\n\n---\n"
},
{
"id": "c12",
"title": "十、合规与财务:别等到卡款才慌",
"order": 12,
"content": "## 十、合规与财务:别等到卡款才慌\n\n\n### 10.1 基础习惯\n\n- 收支分账记录 \n- 合同 / 聊天记录留存 \n- 发票与税务按你所在地规则处理 \n\n### 10.2 缓冲金\n\n建议至少准备:**3~6 个月最低生活成本**。游民生活波动更大,缓冲金是自由的地基。\n\n### 10.3 别碰的灰区\n\n账号买卖、虚假流量、欺诈性承诺、违规跨境操作等,短期看似捷径,长期是地雷。知道即可,不要当主策略。\n\n---\n"
},
{
"id": "c13",
"title": "十一、赛道灵感:普通人能落地的方向",
"order": 13,
"content": "## 十一、赛道灵感:普通人能落地的方向\n\n\n### 11.1 兜底方向(示例)\n\n1. **写作与内容策划**:帮小团队做选题、文案、手册 \n2. **效率与自动化**:帮人整理工作流、表格、小脚本 \n3. **垂直咨询**:你有真实从业经验的领域陪跑 \n\n### 11.2 「元能力」:教别人复盘\n\n如果你暂时没有强垂直:\n\n> 把「如何建立可持续的一人工作系统」本身做成内容与产品。\n\n但请建立在真实实践上,而不是空转概念。\n\n### 11.3 本地优势也能在线卖\n\n你熟悉的城市、行业、语言、审美,都可以变成线上可交付的信息差产品——关键是**可验证、可复用、可持续更新**。\n\n---\n"
},
{
"id": "c14",
"title": "十二、从副业到一人公司:扩展路径",
"order": 14,
"content": "## 十二、从副业到一人公司:扩展路径\n\n\n### 12.1 升级阶梯\n\n```\n副业实验\n → 稳定月入覆盖部分生活成本\n → 产品化(模板 / 手册)\n → 提高客单价或减少人肉交付\n → 可选:减班 / 远程 / 旅居\n```\n\n每一步都要有数字,而不是口号。\n\n### 12.2 一人公司的组织原则\n\n- 默认外包非核心 \n- 文档先于口头约定 \n- 系统优先于英雄主义加班 \n\n### 12.3 收入拼图(理想态)\n\n```\n远程工作 / 接单(现金牛)\n +\n数字产品 / 模板(被动底座)\n +\n小社群或陪跑(高信任)\n────────────────\n地理套利下的自由现金流\n```\n\n---\n"
},
{
"id": "c15",
"title": "十三、30 天行动清单",
"order": 15,
"content": "## 十三、30 天行动清单\n\n\n### 第 1 周:盘点与定位\n\n- [ ] 写出技能四象限 \n- [ ] 完成「一句话供给」 \n- [ ] 算出每月最低生活成本与缓冲金缺口 \n\n### 第 2 周:作品与可信度\n\n- [ ] 整理 3 个案例(或练习项目) \n- [ ] 搭一个简单主页 / 简介页(不必复杂) \n- [ ] 公开更新 2 次真实复盘 \n\n### 第 3 周:第一次交易\n\n- [ ] 给出明确报价与边界 \n- [ ] 完成 1 次小额交付或预售模板 \n- [ ] 记录耗时,为定价校准 \n\n### 第 4 周:系统化\n\n- [ ] 固化每周工作节奏 \n- [ ] 把重复内容做成模板 \n- [ ] 复盘:保留 / 调整 / 放弃什么 \n\n完成不了全部也没关系——**完成「第一次诚实交付」比完美计划重要。**\n\n---\n"
},
{
"id": "c16",
"title": "十四、结语:自由是设计出来的",
"order": 16,
"content": "## 十四、结语:自由是设计出来的\n\n\n书店里很少有一本「刚好适合你」的人生说明书。这本小册只做一件事:把分散的经验,收成一份可执行的底稿。\n\n数字游民与一人公司改变生活的方式,通常不是戏剧性的一夜翻盘,而是:\n\n> 某天你发现:收入不再完全绑在工位上; \n> 你的笔记、模板与信誉,开始替你工作; \n> 你可以选择城市,而不是被城市选择。\n\n它也会伴随试错:报价踩坑、客户消耗、自我管理失败……这些都是真实成本,不是营销话术。\n\n**给你的最终建议:**\n\n1. 把一人公司当**长期资产**,不是彩票 \n2. 先稳住**现金牛**,再谈被动与旅居 \n3. 用文档与边界保护精力 \n4. 小步产品化,持续复盘 \n5. 灰产捷径可以「知道」,但不要当成主策略 \n\n后续可能更新:选题与定价实验、远程协作清单、一人公司财务表等。\n\n---\n\n### 附录 A:关键概念速查\n\n| 项目 | 说明 |\n|------|------|\n| 地理套利 | 收入与生活成本不在同一「坐标系」 |\n| 现金牛 | 短期稳定进账的引擎 |\n| 被动底座 | 可复用、可重复销售的数字资产 |\n| 试验田 | 小预算试错区 |\n| 一人公司 | 以个人为核心的最小商业系统 |\n| 缓冲金 | 3~6 个月最低生活成本建议 |\n\n### 附录 B:读法建议\n\n1. 先通读「写在前面」与「结语」定方向 \n2. 按 30 天清单执行,而不是只收藏 \n3. 每章只带走一个可立刻做的动作 \n\n---\n\n*完 · 愿你把自由设计成可执行的系统。*\n"
}
]
};
/**
* Lightweight markdown → HTML for offline 小红书小工具.
* No eval / network / Worker.
*/
(function (global) {
function themeColors(theme) {
if (theme === "light") {
return {
text: "#1e1630",
muted: "#6d6286",
accent: "#db2777",
accentSoft: "rgba(219,39,119,.1)",
code: "#7c3aed",
strong: "#120f1d",
};
}
if (theme === "sepia") {
return {
text: "#3d2f1f",
muted: "#8a7358",
accent: "#c2410c",
accentSoft: "rgba(194,65,12,.12)",
code: "#c2410c",
strong: "#2a1f14",
};
}
return {
text: "#f3eefc",
muted: "#b4a9c8",
accent: "#ff7ab6",
accentSoft: "rgba(255,122,182,.14)",
code: "#c4b5fd",
strong: "#ffffff",
};
}
function escapeHtml(s) {
return String(s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
function inline(s, c) {
return escapeHtml(s)
.replace(/\*\*(.+?)\*\*/g, '<strong style="color:' + c.strong + ';font-weight:700;">$1</strong>')
.replace(/\*(.+?)\*/g, '<em style="color:' + c.muted + ';">$1</em>')
.replace(/`([^`]+)`/g, '<span class="md-code">$1</span>');
}
function markdownToHtml(src, opts) {
opts = opts || {};
var dropCap = opts.dropCap !== false;
var c = themeColors(opts.theme || "dark");
var text = String(src || "").replace(/\r\n/g, "\n");
text = text.replace(/<!--[\s\S]*?-->/g, "");
text = text.replace(/<video[\s\S]*?<\/video>/gi, "> 🎬 视频请在异度世界公众号查看");
text = text.replace(/<img\b[\s\S]*?>/gi, "> 🖼 配图已省略(离线版)");
text = text.replace(/!\[[^\]]*\]\([^)]+\)/g, "> 🖼 配图已省略(离线版)");
var lines = text.split("\n");
var out = [];
var inCode = false;
var codeBuf = [];
var inUl = false;
var inOl = false;
var olIndex = 0;
var inQuote = false;
var quoteBuf = [];
var paraCount = 0;
var skippedChapterTitle = false;
function closeLists() {
if (inUl) {
out.push("</div>");
inUl = false;
}
if (inOl) {
out.push("</div>");
inOl = false;
olIndex = 0;
}
}
function flushQuote() {
if (!inQuote) return;
var body = quoteBuf.map(function (q) {
return inline(q, c);
}).join("<br/>");
out.push('<div class="md-quote">' + body + "</div>");
inQuote = false;
quoteBuf = [];
}
function isTableSep(line) {
return /^\s*\|?[\s:-]+\|[\s|:-]*\|?\s*$/.test(line);
}
function splitRow(line) {
var s = line.trim();
if (s.charAt(0) === "|") s = s.slice(1);
if (s.charAt(s.length - 1) === "|") s = s.slice(0, -1);
return s.split("|").map(function (cell) {
return cell.trim();
});
}
function renderTable(rows) {
if (!rows.length) return;
var html = ['<div class="md-table-wrap"><table class="md-table"><thead><tr>'];
rows[0].forEach(function (cell) {
html.push("<th>" + inline(cell, c) + "</th>");
});
html.push("</tr></thead><tbody>");
for (var r = 1; r < rows.length; r++) {
html.push("<tr>");
rows[r].forEach(function (cell) {
html.push("<td>" + inline(cell, c) + "</td>");
});
html.push("</tr>");
}
html.push("</tbody></table></div>");
out.push(html.join(""));
}
for (var i = 0; i < lines.length; i++) {
var raw = lines[i];
var line = raw;
if (/^```/.test(line)) {
flushQuote();
closeLists();
if (inCode) {
out.push('<pre class="md-pre"><code>' + escapeHtml(codeBuf.join("\n")) + "</code></pre>");
codeBuf = [];
inCode = false;
} else {
inCode = true;
}
continue;
}
if (inCode) {
codeBuf.push(line);
continue;
}
// GFM table
if (
line.indexOf("|") !== -1 &&
i + 1 < lines.length &&
isTableSep(lines[i + 1])
) {
flushQuote();
closeLists();
var rows = [splitRow(line)];
i += 1; // skip separator
while (i + 1 < lines.length && lines[i + 1].indexOf("|") !== -1 && lines[i + 1].trim()) {
i += 1;
if (isTableSep(lines[i])) continue;
rows.push(splitRow(lines[i]));
}
renderTable(rows);
continue;
}
if (/^\s*>\s?/.test(line)) {
closeLists();
inQuote = true;
quoteBuf.push(line.replace(/^\s*>\s?/, ""));
continue;
}
if (inQuote) flushQuote();
if (/^\s*---+\s*$/.test(line) || /^\s*\*\*\*+\s*$/.test(line)) {
closeLists();
out.push('<hr class="md-hr"/>');
continue;
}
var h1 = /^#\s+(.+)$/.exec(line);
if (h1) {
closeLists();
if (!skippedChapterTitle) {
skippedChapterTitle = true;
continue;
}
out.push("<h2>" + inline(h1[1], c) + "</h2>");
continue;
}
var h2 = /^##\s+(.+)$/.exec(line);
if (h2) {
closeLists();
// Chapter title already shown in reader chrome — skip first ##
if (!skippedChapterTitle) {
skippedChapterTitle = true;
continue;
}
out.push("<h2>" + inline(h2[1], c) + "</h2>");
continue;
}
var h3 = /^###\s+(.+)$/.exec(line);
if (h3) {
closeLists();
out.push("<h3>" + inline(h3[1], c) + "</h3>");
continue;
}
var task = /^\s*[-*+]\s+\[([ xX])\]\s+(.+)$/.exec(line);
if (task) {
if (inOl) {
out.push("</div>");
inOl = false;
olIndex = 0;
}
if (!inUl) {
out.push('<div class="md-list">');
inUl = true;
}
var mark = /x/i.test(task[1]) ? "☑" : "☐";
out.push("<div>" + mark + " " + inline(task[2], c) + "</div>");
continue;
}
var ul = /^\s*[-*+]\s+(.+)$/.exec(line);
if (ul) {
if (inOl) {
out.push("</div>");
inOl = false;
olIndex = 0;
}
if (!inUl) {
out.push('<div class="md-list">');
inUl = true;
}
out.push("<div>• " + inline(ul[1], c) + "</div>");
continue;
}
var ol = /^\s*(\d+)\.\s+(.+)$/.exec(line);
if (ol) {
if (inUl) {
out.push("</div>");
inUl = false;
}
if (!inOl) {
out.push('<div class="md-list">');
inOl = true;
olIndex = 0;
}
olIndex += 1;
out.push("<div>" + olIndex + ". " + inline(ol[2], c) + "</div>");
continue;
}
if (!line.trim()) {
closeLists();
continue;
}
closeLists();
paraCount += 1;
var cls = dropCap && paraCount === 1 ? ' class="dropcap"' : "";
out.push("<p" + cls + ">" + inline(line.trim(), c) + "</p>");
}
flushQuote();
closeLists();
if (inCode) {
out.push('<pre class="md-pre"><code>' + escapeHtml(codeBuf.join("\n")) + "</code></pre>");
}
return out.join("");
}
global.MarkdownLite = { markdownToHtml: markdownToHtml, themeColors: themeColors };
})(window);
/**
* Official XHS miniTool bridge helpers (Chrome 61 / ES2017).
* Prefer window.xhs.miniTool Storage (9.46+); fall back to localStorage.
*/
(function (global) {
"use strict";
var STORAGE_MIN = 9460;
var COMMENT_MIN = 9490;
var FILE_MIN = 9490;
function readBuildVersion(launchOptions) {
var env = launchOptions && launchOptions.miniToolEnv;
return Number(env && env.buildVersion) || 0;
}
function getClientVersion(buildVersion) {
return Math.floor((Number(buildVersion) || 0) / 1000);
}
function isClientVersionAtLeast(buildVersion, minimum) {
return getClientVersion(buildVersion) >= minimum;
}
function getMiniTool() {
return global.xhs && global.xhs.miniTool ? global.xhs.miniTool : null;
}
function getBuildVersion() {
var xhs = global.xhs;
var sync = readBuildVersion(xhs && xhs.launchOptions);
if (sync) {
return Promise.resolve(sync);
}
var mt = getMiniTool();
if (!mt || typeof mt.getLaunchOptions !== "function") {
return Promise.resolve(0);
}
return Promise.resolve(mt.getLaunchOptions())
.then(function (opts) {
return readBuildVersion(opts);
})
.catch(function () {
return 0;
});
}
function setLocalData(key, data, encrypt) {
var serialized;
try {
serialized = JSON.stringify(data);
} catch (e) {
return Promise.resolve(false);
}
if (typeof serialized !== "string") return Promise.resolve(false);
var useEncrypt = !!encrypt;
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.setStorage === "function"
) {
var payload = { key: key, data: serialized };
if (useEncrypt) payload.encrypt = true;
return Promise.resolve(mt.setStorage(payload))
.then(function () {
return true;
})
.catch(function () {
return writeBrowser(key, serialized);
});
}
return writeBrowser(key, serialized);
});
}
function writeBrowser(key, serialized) {
try {
global.localStorage.setItem(key, serialized);
return true;
} catch (e) {
return false;
}
}
function getLocalData(key, fallback, encrypt) {
var useEncrypt = !!encrypt;
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.getStorage === "function"
) {
var payload = { key: key };
if (useEncrypt) payload.encrypt = true;
return Promise.resolve(mt.getStorage(payload))
.then(function (res) {
var raw = res && res.data;
if (raw != null && raw !== "") {
try {
return JSON.parse(raw);
} catch (e) {
return fallback;
}
}
// Retry without encrypt (migration), then browser
if (useEncrypt) {
return Promise.resolve(mt.getStorage({ key: key }))
.then(function (res2) {
var raw2 = res2 && res2.data;
if (raw2 != null && raw2 !== "") {
try {
var parsed = JSON.parse(raw2);
return setLocalData(key, parsed, true).then(function () {
return parsed;
});
} catch (e2) {
return readBrowser(key, fallback);
}
}
return readBrowser(key, fallback);
})
.catch(function () {
return readBrowser(key, fallback);
});
}
var fromBrowser = readBrowser(key, null);
if (fromBrowser == null) return fallback;
return writeNative(mt, key, JSON.stringify(fromBrowser), false).then(
function () {
return fromBrowser;
},
function () {
return fromBrowser;
}
);
})
.catch(function () {
return readBrowser(key, fallback);
});
}
return readBrowser(key, fallback);
});
}
function writeNative(mt, key, serialized, encrypt) {
if (!mt || typeof mt.setStorage !== "function") {
return Promise.resolve(false);
}
var payload = { key: key, data: serialized };
if (encrypt) payload.encrypt = true;
return Promise.resolve(mt.setStorage(payload)).then(
function () {
return true;
},
function () {
return false;
}
);
}
function readBrowser(key, fallback) {
try {
var raw = global.localStorage.getItem(key);
if (raw == null || raw === "") return fallback;
return JSON.parse(raw);
} catch (e) {
return fallback;
}
}
function removeLocalData(key) {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.removeStorage === "function"
) {
return Promise.resolve(mt.removeStorage({ key: key }))
.then(function () {
removeBrowser(key);
return true;
})
.catch(function () {
return removeBrowser(key);
});
}
return removeBrowser(key);
});
}
function clearLocalData() {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
isClientVersionAtLeast(buildVersion, STORAGE_MIN) &&
mt &&
typeof mt.clearStorage === "function"
) {
return Promise.resolve(mt.clearStorage())
.then(function () {
clearBrowser();
return true;
})
.catch(function () {
return clearBrowser();
});
}
return clearBrowser();
});
}
function removeBrowser(key) {
try {
global.localStorage.removeItem(key);
return true;
} catch (e) {
return false;
}
}
function clearBrowser() {
try {
global.localStorage.clear();
return true;
} catch (e) {
return false;
}
}
function getLaunchOptions() {
var xhs = global.xhs;
if (xhs && xhs.launchOptions) {
return Promise.resolve(xhs.launchOptions);
}
var mt = getMiniTool();
if (!mt || typeof mt.getLaunchOptions !== "function") {
return Promise.resolve(null);
}
return Promise.resolve(mt.getLaunchOptions()).catch(function () {
return null;
});
}
/** Read miniToolSnapshotInfo from launch options (comment re-entry, §3.9). */
function readSnapshotInfo(launchOptions) {
if (!launchOptions) return null;
var raw =
launchOptions.miniToolSnapshotInfo ||
(launchOptions.query && launchOptions.query.miniToolSnapshotInfo) ||
(launchOptions.referrerInfo &&
launchOptions.referrerInfo.miniToolSnapshotInfo) ||
(launchOptions.extraData && launchOptions.extraData.miniToolSnapshotInfo);
if (!raw) return null;
if (typeof raw === "object") return raw;
try {
return JSON.parse(raw);
} catch (e) {
return null;
}
}
function callApi(name, options) {
var mt = getMiniTool();
if (!mt || typeof mt[name] !== "function") {
return Promise.reject({ errMsg: name + ":fail not available" });
}
return Promise.resolve(mt[name](options || {}));
}
function writeTempFile(dataUrl) {
return callApi("writeTempFile", { data: dataUrl }).then(function (res) {
return (res && res.filePath) || dataUrl;
});
}
function saveImageToPhotosAlbum(filePath) {
return callApi("saveImageToPhotosAlbum", { filePath: filePath });
}
function postNote(opts) {
return callApi("postNote", opts);
}
function canPostComment(buildVersion) {
var mt = getMiniTool();
return (
isClientVersionAtLeast(buildVersion, COMMENT_MIN) &&
mt &&
typeof mt.interactionOpenApi === "function"
);
}
function postComment(payload, saveToAlbum) {
return callApi("interactionOpenApi", {
payload: payload,
saveToAlbum: saveToAlbum !== false
});
}
function getStorageInfo() {
return getBuildVersion().then(function (buildVersion) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(buildVersion, STORAGE_MIN) ||
!mt ||
typeof mt.getStorageInfo !== "function"
) {
return null;
}
return Promise.resolve(mt.getStorageInfo()).catch(function () {
return null;
});
});
}
function canUseFileSystem(buildVersion) {
var mt = getMiniTool();
return (
isClientVersionAtLeast(buildVersion, FILE_MIN) &&
mt &&
typeof mt.writeFile === "function" &&
typeof mt.readFile === "function"
);
}
function getUserDataPath() {
return getLaunchOptions().then(function (opts) {
var env = opts && opts.miniToolEnv;
return (env && env.userDataPath) || "";
});
}
function ensureDir(dirPath) {
var mt = getMiniTool();
if (!mt || typeof mt.mkdir !== "function") {
return Promise.resolve(false);
}
return Promise.resolve(mt.mkdir({ dirPath: dirPath, recursive: true }))
.then(function () {
return true;
})
.catch(function () {
return false;
});
}
function writeUtf8File(relativePath, data) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.reject({ errMsg: "writeFile:fail version" });
}
return getUserDataPath().then(function (root) {
if (!root) return Promise.reject({ errMsg: "writeFile:fail no path" });
var rel = String(relativePath || "").replace(/^\/+/, "");
var parts = rel.split("/");
var dir =
parts.length > 1 ? root + "/" + parts.slice(0, -1).join("/") : root;
var filePath = root + "/" + rel;
return ensureDir(dir).then(function () {
return callApi("writeFile", {
filePath: filePath,
data: typeof data === "string" ? data : JSON.stringify(data),
encoding: "utf8"
}).then(function () {
return filePath;
});
});
});
});
}
function appendUtf8File(relativePath, data) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.reject({ errMsg: "appendFile:fail version" });
}
var mt = getMiniTool();
if (!mt || typeof mt.appendFile !== "function") {
// Fallback: read + write
return readUtf8File(relativePath).then(function (prev) {
return writeUtf8File(
relativePath,
(prev || "") + (typeof data === "string" ? data : String(data))
);
});
}
return getUserDataPath().then(function (root) {
if (!root) return Promise.reject({ errMsg: "appendFile:fail no path" });
var rel = String(relativePath || "").replace(/^\/+/, "");
var parts = rel.split("/");
var dir =
parts.length > 1 ? root + "/" + parts.slice(0, -1).join("/") : root;
var filePath = root + "/" + rel;
return ensureDir(dir).then(function () {
return callApi("appendFile", {
filePath: filePath,
data: typeof data === "string" ? data : String(data),
encoding: "utf8"
}).then(function () {
return filePath;
});
});
});
});
}
function postVideoNote(opts) {
var videoRes = { video_url: opts.videoPath };
if (opts.coverPath) videoRes.cover_url = opts.coverPath;
return callApi("postNote", {
title: opts.title,
content: opts.content,
pageType: "video_publish",
mediaInfo: {
video_resources: videoRes
}
});
}
function readUtf8File(relativePath) {
return getBuildVersion().then(function (bv) {
if (!canUseFileSystem(bv)) {
return Promise.resolve(null);
}
return getUserDataPath().then(function (root) {
if (!root) return null;
var filePath = root + "/" + String(relativePath || "").replace(/^\/+/, "");
return callApi("readFile", { filePath: filePath, encoding: "utf8" })
.then(function (res) {
return res && res.data != null ? res.data : null;
})
.catch(function () {
return null;
});
});
});
}
/** Write dataURL to temp, then optionally persist via saveFile (9.49+). */
function persistImage(dataUrl, relativePath) {
return writeTempFile(dataUrl).then(function (tempPath) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!relativePath ||
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.saveFile !== "function"
) {
return tempPath;
}
return getUserDataPath().then(function (root) {
if (!root) return tempPath;
var dest = root + "/" + String(relativePath).replace(/^\/+/, "");
var dir = dest.replace(/\/[^/]+$/, "");
return ensureDir(dir).then(function () {
return callApi("saveFile", {
tempFilePath: tempPath,
filePath: dest
})
.then(function (res) {
return (res && res.savedFilePath) || dest || tempPath;
})
.catch(function () {
return tempPath;
});
});
});
});
});
}
function getFileStorageInfo() {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.getFileStorageInfo !== "function"
) {
return null;
}
return Promise.resolve(mt.getFileStorageInfo()).catch(function () {
return null;
});
});
}
function unlinkFile(relativeOrAbsPath) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.unlink !== "function"
) {
return false;
}
var path = String(relativeOrAbsPath || "");
if (!path) return false;
var p = Promise.resolve(path);
if (path.indexOf("/") !== 0 && path.indexOf("usr") !== 0) {
p = getUserDataPath().then(function (root) {
return root ? root + "/" + path.replace(/^\/+/, "") : path;
});
}
return p.then(function (filePath) {
return callApi("unlink", { filePath: filePath })
.then(function () {
return true;
})
.catch(function () {
return false;
});
});
});
}
function readDirList(relativeDir) {
return getBuildVersion().then(function (bv) {
var mt = getMiniTool();
if (
!isClientVersionAtLeast(bv, FILE_MIN) ||
!mt ||
typeof mt.readDir !== "function"
) {
return [];
}
return getUserDataPath().then(function (root) {
if (!root) return [];
var dirPath =
root +
(relativeDir
? "/" + String(relativeDir).replace(/^\/+|\/+$/g, "")
: "");
return callApi("readDir", { dirPath: dirPath })
.then(function (res) {
var files = (res && res.files) || [];
return files.map(function (f) {
if (typeof f === "string") {
return { name: f, path: dirPath + "/" + f };
}
var name = f.name || f.fileName || String(f);
return {
name: name,
path: f.path || f.filePath || dirPath + "/" + name,
isDir: !!(f.isDir || f.isDirectory)
};
});
})
.catch(function () {
return [];
});
});
});
}
function cleanupShareDir() {
return readDirList("share").then(function (files) {
var chain = Promise.resolve(0);
for (var i = 0; i < files.length; i++) {
(function (file) {
if (file.isDir) return;
chain = chain.then(function (n) {
return callApi("unlink", { filePath: file.path })
.then(function () {
return n + 1;
})
.catch(function () {
return n;
});
});
})(files[i]);
}
return chain;
});
}
/** Convert <input type=file> File / Blob to data URL (offline, no network). */
function blobToDataUrl(blob) {
return new Promise(function (resolve, reject) {
if (!blob) {
reject({ errMsg: "blobToDataUrl:fail empty" });
return;
}
try {
var reader = new FileReader();
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = function () {
reject({ errMsg: "blobToDataUrl:fail read" });
};
reader.readAsDataURL(blob);
} catch (e) {
reject({ errMsg: "blobToDataUrl:fail " + (e && e.message) });
}
});
}
global.XhsBridge = {
getBuildVersion: getBuildVersion,
getClientVersion: getClientVersion,
isClientVersionAtLeast: isClientVersionAtLeast,
setLocalData: setLocalData,
getLocalData: getLocalData,
removeLocalData: removeLocalData,
clearLocalData: clearLocalData,
getStorageInfo: getStorageInfo,
getFileStorageInfo: getFileStorageInfo,
getLaunchOptions: getLaunchOptions,
readSnapshotInfo: readSnapshotInfo,
writeTempFile: writeTempFile,
saveImageToPhotosAlbum: saveImageToPhotosAlbum,
postNote: postNote,
canPostComment: canPostComment,
postComment: postComment,
canUseFileSystem: canUseFileSystem,
getUserDataPath: getUserDataPath,
writeUtf8File: writeUtf8File,
appendUtf8File: appendUtf8File,
readUtf8File: readUtf8File,
persistImage: persistImage,
unlinkFile: unlinkFile,
readDirList: readDirList,
cleanupShareDir: cleanupShareDir,
blobToDataUrl: blobToDataUrl,
postVideoNote: postVideoNote,
getMiniTool: getMiniTool,
STORAGE_MIN: STORAGE_MIN,
COMMENT_MIN: COMMENT_MIN,
FILE_MIN: FILE_MIN
};
})(window);
(function () {
"use strict";
var PROGRESS_KEY = "yidu_reading_progress";
var PREFS_KEY = "yidu_reader_prefs";
var BOOKMARKS_KEY = "yidu_bookmarks";
var NOTES_KEY = "yidu_clip_notes";
var STREAK_KEY = "yidu_checkin_streak";
var JOURNAL_KEY = "yidu_journal";
var TIME_KEY = "yidu_read_time";
var WORKS_KEY = "yidu_works";
var NOTES_FILE = "notes/clips.json";
var JOURNAL_FILE = "notes/journal.json";
var Bridge = window.XhsBridge;
var FONT_SIZES = [
{ label: "小", value: 15 },
{ label: "中", value: 16 },
{ label: "大", value: 17 },
{ label: "特", value: 18 }
];
var LINE_HEIGHTS = [
{ label: "紧", value: "1.55" },
{ label: "适", value: "1.7" },
{ label: "疏", value: "1.9" }
];
var FONTS = [
{ label: "黑", value: "sans", css: "'PingFang SC','Hiragino Sans GB','Microsoft YaHei',sans-serif" },
{ label: "宋", value: "serif", css: "'Songti SC','STSong','SimSun',serif" }
];
var THEMES = [
{ label: "夜", value: "dark" },
{ label: "暖", value: "sepia" },
{ label: "昼", value: "light" }
];
var DEFAULT_PREFS = {
fontSize: 16,
lineHeight: "1.7",
fontFamily: "sans",
theme: "dark"
};
var CHAPTER_EMOJIS = ["📖", "✨", "🔥", "💡", "🎯", "🚀", "💎", "🧭", "🌙", "⚡", "🎬", "☁️"];
var state = {
book: null,
prefs: null,
progress: null,
bookmarks: [],
notes: [],
journal: [],
works: [],
readTime: { date: "", seconds: 0, total: 0 },
readTick: null,
streak: { days: 0, lastDate: "" },
drawerTab: "chapters",
activeChapter: 0,
saveTimer: null,
bound: false,
scrollPct: 0,
buildVersion: 0,
jumpLockUntil: 0,
chromeHidden: false,
camStream: null,
camShot: null
};
var el = {};
function $(id) {
return document.getElementById(id);
}
function on(node, eventName, handler) {
if (!node || typeof node.addEventListener !== "function") return false;
node.addEventListener(eventName, handler);
return true;
}
function copyObj(src) {
var out = {};
for (var k in src) {
if (Object.prototype.hasOwnProperty.call(src, k)) out[k] = src[k];
}
return out;
}
function setHidden(node, hidden) {
if (!node) return;
if (hidden) {
if (node.classList) node.classList.add("is-hidden");
else node.className += " is-hidden";
node.style.display = "none";
} else {
if (node.classList) node.classList.remove("is-hidden");
else node.className = String(node.className || "").replace(/\bis-hidden\b/g, "");
node.style.display = "";
}
}
function loadPrefs() {
return Bridge.getLocalData(PREFS_KEY, null).then(function (raw) {
if (!raw || typeof raw !== "object") return copyObj(DEFAULT_PREFS);
return {
fontSize: Number(raw.fontSize) || DEFAULT_PREFS.fontSize,
lineHeight: String(raw.lineHeight || DEFAULT_PREFS.lineHeight),
fontFamily: raw.fontFamily || DEFAULT_PREFS.fontFamily,
theme: raw.theme || DEFAULT_PREFS.theme
};
});
}
function savePrefs(prefs) {
state.prefs = prefs;
return Bridge.setLocalData(PREFS_KEY, prefs);
}
function getProgress(bookId) {
return Bridge.getLocalData(PROGRESS_KEY, null).then(function (raw) {
if (!raw || raw.bookId !== bookId) return null;
return raw;
});
}
function saveProgress(partial) {
return getProgress(partial.bookId).then(function (prev) {
prev = prev || {};
var readSet = {};
var i;
var ids = prev.readChapterIds || [];
for (i = 0; i < ids.length; i++) readSet[ids[i]] = true;
ids = partial.readChapterIds || [];
for (i = 0; i < ids.length; i++) readSet[ids[i]] = true;
if (partial.chapterId) readSet[partial.chapterId] = true;
var keys = [];
for (var k in readSet) {
if (Object.prototype.hasOwnProperty.call(readSet, k)) keys.push(k);
}
var next = {
bookId: partial.bookId,
chapterId: partial.chapterId,
chapterIndex: partial.chapterIndex,
scrollPercent: partial.scrollPercent,
readChapterIds: keys,
updatedAt: Date.now()
};
state.progress = next;
return Bridge.setLocalData(PROGRESS_KEY, next).then(function () {
return next;
});
});
}
function loadBookmarks() {
return Bridge.getLocalData(BOOKMARKS_KEY, []).then(function (list) {
state.bookmarks = Array.isArray(list) ? list : [];
return state.bookmarks;
});
}
function saveBookmarks() {
return Bridge.setLocalData(BOOKMARKS_KEY, state.bookmarks || []);
}
function loadNotes() {
return Bridge.getLocalData(NOTES_KEY, null).then(function (list) {
if (Array.isArray(list) && list.length) {
state.notes = list;
return state.notes;
}
// Fallback: filesystem backup (9.49+)
return Bridge.readUtf8File(NOTES_FILE).then(function (raw) {
if (!raw) {
state.notes = [];
return state.notes;
}
try {
var parsed = JSON.parse(raw);
state.notes = Array.isArray(parsed) ? parsed : [];
} catch (e) {
state.notes = [];
}
if (state.notes.length) {
return Bridge.setLocalData(NOTES_KEY, state.notes).then(function () {
return state.notes;
});
}
return state.notes;
});
});
}
function syncNotesToFs(list) {
if (!Bridge.canUseFileSystem(state.buildVersion)) {
return Promise.resolve(false);
}
return Bridge.writeUtf8File(NOTES_FILE, JSON.stringify(list || [])).then(
function () {
return true;
},
function () {
return false;
}
);
}
function saveNotes() {
var list = state.notes || [];
return Bridge.setLocalData(NOTES_KEY, list).then(function (ok) {
return syncNotesToFs(list).then(function () {
return ok;
});
});
}
function loadJournal() {
return Bridge.getLocalData(JOURNAL_KEY, null, true).then(function (list) {
if (Array.isArray(list) && list.length) {
state.journal = list;
return state.journal;
}
return Bridge.readUtf8File(JOURNAL_FILE).then(function (raw) {
if (!raw) {
state.journal = [];
return state.journal;
}
try {
var parsed = JSON.parse(raw);
state.journal = Array.isArray(parsed) ? parsed : [];
} catch (e) {
state.journal = [];
}
if (state.journal.length) {
return Bridge.setLocalData(JOURNAL_KEY, state.journal, true).then(
function () {
return state.journal;
}
);
}
return state.journal;
});
});
}
function saveJournal() {
var list = state.journal || [];
return Bridge.setLocalData(JOURNAL_KEY, list, true).then(function (ok) {
if (Bridge.canUseFileSystem(state.buildVersion)) {
return Bridge.writeUtf8File(JOURNAL_FILE, JSON.stringify(list)).then(
function () {
return ok;
},
function () {
return ok;
}
);
}
return ok;
});
}
function loadReadTime() {
return Bridge.getLocalData(TIME_KEY, null).then(function (raw) {
var today = todayKey();
if (raw && typeof raw === "object") {
state.readTime = {
date: String(raw.date || ""),
seconds: Number(raw.seconds) || 0,
total: Number(raw.total) || 0
};
if (state.readTime.date !== today) {
state.readTime.date = today;
state.readTime.seconds = 0;
}
} else {
state.readTime = { date: today, seconds: 0, total: 0 };
}
return state.readTime;
});
}
function saveReadTime() {
return Bridge.setLocalData(TIME_KEY, state.readTime || {});
}
function todayReadMinutes() {
return Math.max(
0,
Math.floor(((state.readTime && state.readTime.seconds) || 0) / 60)
);
}
function totalReadMinutes() {
return Math.max(
0,
Math.floor(((state.readTime && state.readTime.total) || 0) / 60)
);
}
function startReadTimer() {
stopReadTimer();
state.readTick = setInterval(function () {
if (
!el.reader ||
(el.reader.classList && el.reader.classList.contains("is-hidden"))
) {
return;
}
var today = todayKey();
if (!state.readTime) state.readTime = { date: today, seconds: 0, total: 0 };
if (state.readTime.date !== today) {
state.readTime.date = today;
state.readTime.seconds = 0;
}
state.readTime.seconds += 15;
state.readTime.total += 15;
saveReadTime();
if (el.homeTime && !el.home.classList.contains("is-hidden")) {
updateHomeTimeLabel();
}
}, 15000);
}
function stopReadTimer() {
if (state.readTick) {
clearInterval(state.readTick);
state.readTick = null;
}
}
function updateHomeTimeLabel() {
if (!el.homeTime) return;
var m = todayReadMinutes();
var t = totalReadMinutes();
if (m <= 0 && t <= 0) {
el.homeTime.textContent = "";
return;
}
el.homeTime.textContent =
"今日已读约 " + Math.max(1, Math.round(m) || 1) + " 分钟 · 累计 " + Math.max(1, Math.round(t) || 1) + " 分钟";
}
function loadWorks() {
return Bridge.getLocalData(WORKS_KEY, []).then(function (list) {
state.works = Array.isArray(list) ? list : [];
return state.works;
});
}
function saveWorks() {
return Bridge.setLocalData(WORKS_KEY, (state.works || []).slice(0, 40));
}
function registerWork(item) {
if (!item || !item.path) return Promise.resolve();
var list = state.works || [];
list = list.filter(function (w) {
return w.path !== item.path;
});
list.unshift({
id: item.id || "w_" + Date.now(),
title: item.title || "作品",
path: item.path,
kind: item.kind || "image",
updatedAt: Date.now()
});
state.works = list.slice(0, 40);
return saveWorks();
}
function refreshWorksFromFs() {
if (!Bridge.canUseFileSystem(state.buildVersion)) {
return Promise.resolve(state.works || []);
}
return Bridge.readDirList("share").then(function (files) {
var known = {};
var i;
for (i = 0; i < (state.works || []).length; i++) {
known[state.works[i].path] = state.works[i];
}
for (i = 0; i < files.length; i++) {
var f = files[i];
if (f.isDir) continue;
if (!known[f.path]) {
known[f.path] = {
id: "w_fs_" + i,
title: f.name || "生成图",
path: f.path,
kind: "image",
updatedAt: Date.now()
};
}
}
var merged = [];
for (var k in known) {
if (Object.prototype.hasOwnProperty.call(known, k)) merged.push(known[k]);
}
merged.sort(function (a, b) {
return (b.updatedAt || 0) - (a.updatedAt || 0);
});
state.works = merged.slice(0, 40);
return saveWorks().then(function () {
return state.works;
});
});
}
function refreshStorageCap() {
if (!el.storageCap) return;
Promise.all([Bridge.getStorageInfo(), Bridge.getFileStorageInfo()]).then(
function (pair) {
var info = pair[0];
var fileInfo = pair[1];
var parts = [];
if (info) {
parts.push(
"缓存 " +
(Number(info.currentSize) || 0) +
"/" +
(Number(info.limitSize) || 10240) +
" KB"
);
} else {
parts.push("缓存 · 需客户端 9.46+");
}
parts.push("摘录 " + (state.notes || []).length + " 条");
if (state.streak && state.streak.days) {
parts.push("连续打卡 " + state.streak.days + " 天");
}
if (fileInfo) {
var usedMb = ((Number(fileInfo.usedBytes) || 0) / 1024 / 1024).toFixed(1);
var limitMb = ((Number(fileInfo.limitBytes) || 0) / 1024 / 1024).toFixed(0);
parts.push("文件 " + usedMb + "/" + limitMb + " MB");
}
el.storageCap.textContent = parts.join(" · ");
}
);
}
function todayKey() {
var d = new Date();
var m = d.getMonth() + 1;
var day = d.getDate();
return (
d.getFullYear() +
"-" +
(m < 10 ? "0" + m : m) +
"-" +
(day < 10 ? "0" + day : day)
);
}
function yesterdayKey() {
var d = new Date(Date.now() - 86400000);
var m = d.getMonth() + 1;
var day = d.getDate();
return (
d.getFullYear() +
"-" +
(m < 10 ? "0" + m : m) +
"-" +
(day < 10 ? "0" + day : day)
);
}
function loadStreak() {
return Bridge.getLocalData(STREAK_KEY, null).then(function (raw) {
if (raw && typeof raw === "object") {
state.streak = {
days: Number(raw.days) || 0,
lastDate: String(raw.lastDate || "")
};
} else {
state.streak = { days: 0, lastDate: "" };
}
return state.streak;
});
}
function bumpStreak() {
var today = todayKey();
var s = state.streak || { days: 0, lastDate: "" };
if (s.lastDate === today) {
return Promise.resolve(s);
}
if (s.lastDate === yesterdayKey()) {
s.days = (Number(s.days) || 0) + 1;
} else {
s.days = 1;
}
s.lastDate = today;
state.streak = s;
return Bridge.setLocalData(STREAK_KEY, s).then(function () {
return s;
});
}
function formatAgo(ts) {
var diff = Math.max(0, Date.now() - ts);
var m = Math.floor(diff / 60000);
if (m < 1) return "刚刚";
if (m < 60) return m + " 分钟前";
var h = Math.floor(m / 60);
if (h < 24) return h + " 小时前";
return Math.floor(h / 24) + " 天前";
}
function coverPaletteFromSeed(seed) {
var palettes = [
{ from: "#1a0b2e", via: "#6d28d9", to: "#db2777", glow: "rgba(219,39,119,.45)", ink: "#fce7f3" },
{ from: "#0b1226", via: "#1d4ed8", to: "#06b6d4", glow: "rgba(6,182,212,.4)", ink: "#e0f2fe" },
{ from: "#1c0a12", via: "#be185d", to: "#f59e0b", glow: "rgba(245,158,11,.4)", ink: "#fff7ed" },
{ from: "#0c1424", via: "#4338ca", to: "#818cf8", glow: "rgba(129,140,248,.42)", ink: "#eef2ff" }
];
var h = 2166136261;
var s = seed || "book";
for (var i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = (h * 16777619) | 0;
}
return palettes[Math.abs(h) % palettes.length];
}
function showBootError(msg) {
setHidden(el.boot, false);
setHidden(el.home, true);
setHidden(el.reader, true);
if (el.bootText) el.bootText.textContent = msg || "打开失败";
}
function showView(name) {
setHidden(el.boot, true);
setHidden(el.home, name !== "home");
setHidden(el.reader, name !== "reader");
if (name === "home") {
try {
window.scrollTo(0, 0);
} catch (e) {}
}
}
function getBookData() {
if (typeof BOOK_DATA !== "undefined" && BOOK_DATA && BOOK_DATA.chapters) return BOOK_DATA;
if (window.BOOK_DATA && window.BOOK_DATA.chapters) return window.BOOK_DATA;
return null;
}
function escapeText(s) {
return String(s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
function chapterMinutes(content) {
var n = (String(content || "").match(/[\u4e00-\u9fff]/g) || []).length;
return Math.max(1, Math.round(n / 400));
}
function renderHome() {
var book = state.book;
getProgress(book.id).then(function (progress) {
state.progress = progress;
var palette = coverPaletteFromSeed(book.id + "|" + book.title);
if (el.coverGlow) el.coverGlow.style.background = palette.glow;
if (el.cover) {
el.cover.style.background =
"linear-gradient(155deg, " + palette.from + " 0%, " + palette.via + " 42%, " + palette.to + " 100%)";
}
if (el.coverEmoji) el.coverEmoji.textContent = book.cover_emoji || "🌏";
if (el.coverTitle) {
el.coverTitle.textContent = book.title;
el.coverTitle.style.color = palette.ink;
}
if (el.homeTitle) el.homeTitle.textContent = book.title;
var tease = (book.subtitle || book.description || "").trim();
if (tease.length > 48) tease = tease.slice(0, 48) + "…";
if (el.homeTease) el.homeTease.textContent = tease || "翻开第一页,故事才刚刚开始。";
if (el.homeAuthor) el.homeAuthor.textContent = book.author || "";
if (progress && progress.chapterId) {
if (el.btnStart) el.btnStart.textContent = "继续阅读";
if (el.homeHint) {
var chTitle = "";
var chapters = book.chapters || [];
var ci =
typeof progress.chapterIndex === "number"
? progress.chapterIndex
: -1;
if (ci < 0) {
for (var hi = 0; hi < chapters.length; hi++) {
if (chapters[hi].id === progress.chapterId) {
ci = hi;
break;
}
}
}
if (ci >= 0 && chapters[ci]) chTitle = chapters[ci].title || "";
if (chTitle.length > 16) chTitle = chTitle.slice(0, 16) + "…";
var pct = Math.max(0, Math.min(100, Math.round(Number(progress.scrollPercent) || 0)));
var ago = progress.updatedAt ? formatAgo(progress.updatedAt) : "";
var parts = [];
if (chTitle) parts.push("第" + (ci + 1) + "章「" + chTitle + "」");
if (pct > 0) parts.push(pct + "%");
if (ago) parts.push(ago);
el.homeHint.textContent =
parts.length > 0 ? "上次 · " + parts.join(" · ") : "接着上次的地方";
}
} else {
if (el.btnStart) el.btnStart.textContent = "开始阅读";
if (el.homeHint) el.homeHint.textContent = "点一下,直接进入正文";
}
updateHomeTimeLabel();
showView("home");
});
}
function applyReaderChrome() {
var prefs = state.prefs;
var font = FONTS[0];
var i;
for (i = 0; i < FONTS.length; i++) {
if (FONTS[i].value === prefs.fontFamily) font = FONTS[i];
}
if (el.reader) el.reader.className = "view reader theme-" + prefs.theme;
if (el.tocDrawer) {
el.tocDrawer.className = "drawer theme-" + prefs.theme;
}
if (el.settingsSheet) {
el.settingsSheet.className = "rs-sheet theme-" + prefs.theme;
}
if (el.paper) {
el.paper.style.fontSize = prefs.fontSize + "px";
el.paper.style.lineHeight = prefs.lineHeight;
el.paper.style.fontFamily = font.css;
}
}
function pad2(n) {
return n < 10 ? "0" + n : String(n);
}
function renderToc(filter) {
if (!el.tocList) return;
var q = String(filter || "").trim().toLowerCase();
var html = [];
if (state.drawerTab === "works") {
var works = state.works || [];
for (var w = 0; w < works.length; w++) {
var work = works[w];
if (q && String(work.title || "").toLowerCase().indexOf(q) === -1) continue;
html.push(
'<div class="note-item" data-work-id="' +
escapeText(work.id) +
'"><span class="note-item-title">' +
escapeText(work.title || "作品") +
'</span><span class="note-item-body">' +
escapeText(work.kind || "image") +
" · " +
formatAgo(work.updatedAt || Date.now()) +
'</span><div class="note-item-actions">' +
'<button type="button" class="note-chip" data-work-act="share" data-work-id="' +
escapeText(work.id) +
'">再发笔记</button>' +
'<button type="button" class="note-chip" data-work-act="album" data-work-id="' +
escapeText(work.id) +
'">存相册</button>' +
'<button type="button" class="note-chip ghost" data-work-act="del" data-work-id="' +
escapeText(work.id) +
'">删除</button></div></div>'
);
}
el.tocList.innerHTML =
html.join("") ||
'<p class="foot-tip" style="padding:12px">还没有作品。保存金句图 / 打卡后会出现在这里(需 9.49+ 文件能力)。</p>';
updateDrawerMeta();
return;
}
if (state.drawerTab === "journal") {
var journals = state.journal || [];
for (var j = 0; j < journals.length; j++) {
var je = journals[j];
if (q && String(je.text || "").toLowerCase().indexOf(q) === -1) continue;
html.push(
'<div class="note-item" data-journal-id="' +
escapeText(je.id) +
'"><span class="note-item-title">' +
escapeText(je.date || "日记") +
(je.chapterTitle ? " · " + escapeText(je.chapterTitle) : "") +
'</span><span class="note-item-body">' +
escapeText((je.text || "").slice(0, 80)) +
(je.text && je.text.length > 80 ? "…" : "") +
'</span><div class="note-item-actions">' +
'<button type="button" class="note-chip" data-journal-act="share" data-journal-id="' +
escapeText(je.id) +
'">发笔记</button>' +
'<button type="button" class="note-chip ghost" data-journal-act="del" data-journal-id="' +
escapeText(je.id) +
'">删除</button></div></div>'
);
}
el.tocList.innerHTML =
html.join("") ||
'<p class="foot-tip" style="padding:12px">还没有日记。在设置里点「写阅读日记」。</p>';
updateDrawerMeta();
return;
}
if (state.drawerTab === "notes") {
var notes = state.notes || [];
for (var n = 0; n < notes.length; n++) {
var note = notes[n];
if (
q &&
String(note.title || "").toLowerCase().indexOf(q) === -1 &&
String(note.text || "").toLowerCase().indexOf(q) === -1
) {
continue;
}
html.push(
'<div class="note-item" data-note-id="' +
escapeText(note.id) +
'"><span class="note-item-title">' +
escapeText(note.title || "摘录") +
'</span><span class="note-item-body">' +
escapeText((note.text || "").slice(0, 72)) +
(note.text && note.text.length > 72 ? "…" : "") +
'</span><div class="note-item-actions">' +
'<button type="button" class="note-chip" data-note-act="share" data-note-id="' +
escapeText(note.id) +
'">发笔记</button>' +
'<button type="button" class="note-chip" data-note-act="album" data-note-id="' +
escapeText(note.id) +
'">存相册</button>' +
(Bridge.canPostComment(state.buildVersion)
? '<button type="button" class="note-chip" data-note-act="comment" data-note-id="' +
escapeText(note.id) +
'">发评论</button>'
: "") +
'<button type="button" class="note-chip ghost" data-note-act="del" data-note-id="' +
escapeText(note.id) +
'">删除</button></div></div>'
);
}
el.tocList.innerHTML =
html.join("") ||
'<p class="foot-tip" style="padding:12px">还没有摘录。在设置里点「摘录本章」,可发小红书笔记。</p>';
updateDrawerMeta();
return;
}
if (state.drawerTab === "bookmarks") {
var marks = state.bookmarks || [];
for (var b = 0; b < marks.length; b++) {
var m = marks[b];
if (q && String(m.title || "").toLowerCase().indexOf(q) === -1) continue;
html.push(
'<button type="button" class="drawer-item" data-ch="' +
m.chapterId +
'" data-idx="' +
(m.chapterIndex || 0) +
'"><span class="drawer-idx">★</span><span class="drawer-body"><span class="drawer-name">' +
escapeText(m.title || "") +
"</span></span></button>"
);
}
el.tocList.innerHTML =
html.join("") || '<p class="foot-tip" style="padding:12px">还没有收藏,在设置里点「收藏本章」</p>';
updateDrawerMeta();
return;
}
var chapters = state.book.chapters || [];
for (var i = 0; i < chapters.length; i++) {
var ch = chapters[i];
if (q && ch.title.toLowerCase().indexOf(q) === -1) continue;
var active = i === state.activeChapter ? " active" : "";
var emoji = CHAPTER_EMOJIS[i % CHAPTER_EMOJIS.length];
var starred = isBookmarked(ch.id) ? " ★" : "";
html.push(
'<button type="button" class="drawer-item' +
active +
'" data-ch="' +
ch.id +
'" data-idx="' +
i +
'"><span class="drawer-idx">' +
pad2(i + 1) +
'</span><span class="drawer-body"><span class="drawer-name">' +
emoji +
" " +
escapeText(ch.title) +
starred +
"</span></span></button>"
);
}
el.tocList.innerHTML = html.join("") || '<p class="foot-tip" style="padding:12px">没有匹配的章节</p>';
updateDrawerMeta();
}
function isBookmarked(chapterId) {
var list = state.bookmarks || [];
for (var i = 0; i < list.length; i++) {
if (list[i].chapterId === chapterId) return true;
}
return false;
}
function toggleBookmark() {
var ch = (state.book.chapters || [])[state.activeChapter];
if (!ch) return;
var list = state.bookmarks || [];
var next = [];
var found = false;
for (var i = 0; i < list.length; i++) {
if (list[i].chapterId === ch.id) {
found = true;
} else {
next.push(list[i]);
}
}
if (!found) {
next.unshift({
chapterId: ch.id,
chapterIndex: state.activeChapter,
title: ch.title,
updatedAt: Date.now()
});
}
state.bookmarks = next;
saveBookmarks().then(function () {
if (el.btnBookmark) {
el.btnBookmark.textContent = found ? "收藏本章" : "取消收藏";
}
alert(found ? "已取消收藏" : "已收藏本章");
});
}
function setDrawerTab(tab) {
if (tab === "bookmarks") state.drawerTab = "bookmarks";
else if (tab === "notes") state.drawerTab = "notes";
else if (tab === "journal") state.drawerTab = "journal";
else if (tab === "works") state.drawerTab = "works";
else state.drawerTab = "chapters";
if (el.tabChapters) {
el.tabChapters.className = "drawer-tab" + (state.drawerTab === "chapters" ? " on" : "");
}
if (el.tabBookmarks) {
el.tabBookmarks.className = "drawer-tab" + (state.drawerTab === "bookmarks" ? " on" : "");
}
if (el.tabNotes) {
el.tabNotes.className = "drawer-tab" + (state.drawerTab === "notes" ? " on" : "");
}
if (el.tabJournal) {
el.tabJournal.className = "drawer-tab" + (state.drawerTab === "journal" ? " on" : "");
}
if (el.tabWorks) {
el.tabWorks.className = "drawer-tab" + (state.drawerTab === "works" ? " on" : "");
}
if (el.tocFilter) {
el.tocFilter.placeholder =
state.drawerTab === "notes"
? "搜索摘录"
: state.drawerTab === "bookmarks"
? "搜索收藏"
: state.drawerTab === "journal"
? "搜索日记"
: state.drawerTab === "works"
? "搜索作品"
: "搜索章节";
}
if (state.drawerTab === "works") {
refreshWorksFromFs().then(function () {
renderToc(el.tocFilter ? el.tocFilter.value : "");
});
return;
}
renderToc(el.tocFilter ? el.tocFilter.value : "");
}
function updateDrawerMeta() {
var chapters = (state.book && state.book.chapters) || [];
var total = chapters.length || 1;
var pct = Math.max(
state.scrollPct || 0,
Math.round(((state.activeChapter + 1) / total) * 100)
);
if (el.drawerMeter) el.drawerMeter.style.width = pct + "%";
if (el.drawerStatLeft) el.drawerStatLeft.textContent = "进度 " + pct + "%";
if (el.drawerStatRight) {
el.drawerStatRight.textContent =
state.activeChapter + 1 + " / " + chapters.length + " 章";
}
}
function remainingMinutes() {
var chapters = (state.book && state.book.chapters) || [];
var sum = 0;
for (var i = state.activeChapter; i < chapters.length; i++) {
sum += chapterMinutes(chapters[i].content);
}
return Math.max(1, sum);
}
function updateProgressUI() {
if (!state.book || !el.paper) return;
var locked = Date.now() < (state.jumpLockUntil || 0);
var chapters = state.book.chapters || [];
var doc = document.documentElement;
var scrollY = window.pageYOffset || doc.scrollTop || 0;
var max = Math.max(1, (doc.scrollHeight || 1) - (window.innerHeight || 1));
var pct = Math.min(100, Math.round((scrollY / max) * 100));
state.scrollPct = pct;
if (el.topbarBar) el.topbarBar.style.width = pct + "%";
var blocks = el.paper.querySelectorAll(".chapter-block");
var active = state.activeChapter || 0;
var topbarH = topbarOffset();
if (!locked) {
active = 0;
for (var i = 0; i < blocks.length; i++) {
var rect = blocks[i].getBoundingClientRect();
if (rect.top <= topbarH + 24) active = i;
}
state.activeChapter = active;
}
var ch = chapters[active];
if (ch) {
var emoji = CHAPTER_EMOJIS[active % CHAPTER_EMOJIS.length];
if (el.chapterTitle) el.chapterTitle.textContent = emoji + " " + ch.title;
if (el.progressLabel) {
el.progressLabel.textContent =
active + 1 + "/" + chapters.length + " · 约剩 " + remainingMinutes() + " 分钟";
}
updateDrawerMeta();
if (!locked) {
if (state.saveTimer) clearTimeout(state.saveTimer);
state.saveTimer = setTimeout(function () {
saveProgress({
bookId: state.book.id,
chapterId: ch.id,
chapterIndex: active,
scrollPercent: pct,
readChapterIds: [ch.id]
});
}, 280);
}
}
setHidden(el.btnTop, scrollY < 420);
}
function topbarOffset() {
var h = (el.topbar && el.topbar.offsetHeight) || 0;
if (h > 0) return h;
try {
var pad = parseFloat(
window.getComputedStyle(document.documentElement).getPropertyValue("--app-pad-top")
);
if (!isNaN(pad) && pad > 0) return pad + 44;
} catch (e) {}
return 96;
}
function scrollToY(y) {
try {
if (typeof window.scrollTo === "function") {
window.scrollTo(0, Math.max(0, y));
} else {
document.documentElement.scrollTop = Math.max(0, y);
document.body.scrollTop = Math.max(0, y);
}
} catch (e) {}
}
function jumpToChapter(idx, opts) {
opts = opts || {};
var chapters = (state.book && state.book.chapters) || [];
if (idx < 0 || idx >= chapters.length) return;
var ch = chapters[idx];
var target = $("ch-" + ch.id);
if (!target) return;
state.jumpLockUntil = Date.now() + (opts.lockMs || 520);
state.activeChapter = idx;
var rect = target.getBoundingClientRect();
var current = window.pageYOffset || document.documentElement.scrollTop || 0;
var y = Math.max(0, current + rect.top - topbarOffset());
scrollToY(y);
if (opts.update !== false) {
setTimeout(function () {
updateProgressUI();
}, 60);
}
}
function restoreScrollPercent(pct) {
pct = Math.max(0, Math.min(100, Number(pct) || 0));
if (pct <= 0) return;
state.jumpLockUntil = Date.now() + 700;
setTimeout(function () {
try {
var doc = document.documentElement;
var max = Math.max(0, (doc.scrollHeight || 0) - (window.innerHeight || 0));
if (max > 0) scrollToY(Math.round(max * (pct / 100)));
} catch (e) {}
setTimeout(function () {
updateProgressUI();
}, 80);
}, 40);
}
function openToc(open) {
setHidden(el.tocMask, !open);
if (open) {
applyReaderChrome();
renderToc(el.tocFilter ? el.tocFilter.value : "");
}
}
function openSettings(open) {
setHidden(el.settingsMask, !open);
if (open) {
applyReaderChrome();
refreshStorageCap();
}
}
function buildSeg(container, items, current, onPick) {
if (!container) return;
container.innerHTML = "";
for (var i = 0; i < items.length; i++) {
(function (item) {
var btn = document.createElement("button");
btn.type = "button";
btn.textContent = item.label;
if (item.value === current) btn.className = "on";
on(btn, "click", function () {
onPick(item.value);
});
container.appendChild(btn);
})(items[i]);
}
}
function refreshPrefSegs() {
buildSeg(el.prefSize, FONT_SIZES, state.prefs.fontSize, function (v) {
var next = copyObj(state.prefs);
next.fontSize = v;
savePrefs(next);
applyReaderChrome();
refreshPrefSegs();
});
buildSeg(el.prefLh, LINE_HEIGHTS, state.prefs.lineHeight, function (v) {
var next = copyObj(state.prefs);
next.lineHeight = v;
savePrefs(next);
applyReaderChrome();
refreshPrefSegs();
});
buildSeg(el.prefFont, FONTS, state.prefs.fontFamily, function (v) {
var next = copyObj(state.prefs);
next.fontFamily = v;
savePrefs(next);
applyReaderChrome();
refreshPrefSegs();
});
buildSeg(el.prefTheme, THEMES, state.prefs.theme, function (v) {
var next = copyObj(state.prefs);
next.theme = v;
savePrefs(next);
applyReaderChrome();
refreshPrefSegs();
});
}
function renderReader(jumpToProgress) {
var book = state.book;
var chapters = book.chapters || [];
applyReaderChrome();
if (!window.MarkdownLite || typeof window.MarkdownLite.markdownToHtml !== "function") {
showBootError("渲染模块未加载");
return;
}
var totalMins = Math.max(1, Math.round((book.word_count || 0) / 400));
if (!book.word_count) {
totalMins = 0;
for (var t = 0; t < chapters.length; t++) totalMins += chapterMinutes(chapters[t].content);
totalMins = Math.max(1, totalMins);
}
var html = [];
html.push(
'<div class="hero-card">' +
'<span class="hero-emoji">' +
escapeText(book.cover_emoji || "🌏") +
"</span>" +
'<span class="hero-title">' +
escapeText(book.title || "") +
"</span>" +
'<span class="hero-sub">' +
escapeText(book.subtitle || "") +
"</span>" +
'<div class="hero-stats">' +
'<div class="stat"><span class="stat-n">' +
chapters.length +
'</span><span class="stat-l">章节</span></div>' +
'<div class="stat"><span class="stat-n">' +
Math.max(1, Math.round((book.word_count || 5000) / 1000)) +
'k</span><span class="stat-l">字数</span></div>' +
'<div class="stat"><span class="stat-n">' +
totalMins +
'</span><span class="stat-l">分钟</span></div>' +
'<div class="stat"><span class="stat-n">' +
remainingMinutes() +
'</span><span class="stat-l">余下</span></div>' +
"</div>" +
'<span class="hero-tip">点左右翻页 · 点中间显隐顶栏</span>' +
"</div>"
);
for (var i = 0; i < chapters.length; i++) {
var ch = chapters[i];
var mins = chapterMinutes(ch.content);
var emoji = CHAPTER_EMOJIS[i % CHAPTER_EMOJIS.length];
var next = chapters[i + 1];
var nextEmoji = CHAPTER_EMOJIS[(i + 1) % CHAPTER_EMOJIS.length];
html.push('<section class="chapter-block" id="ch-' + ch.id + '" data-idx="' + i + '">');
if (i > 0) {
html.push(
'<div class="chapter-divider"><span class="chapter-divider-text">· · ·</span></div>'
);
}
html.push(
'<div class="chapter-hero">' +
'<div class="chapter-hero-top">' +
'<span class="chapter-hero-emoji">' +
emoji +
"</span>" +
'<span class="chapter-ring"><span class="chapter-ring-n">' +
pad2(i + 1) +
'</span><span class="chapter-ring-t">/' +
chapters.length +
"</span></span>" +
"</div>" +
'<span class="chapter-title">' +
escapeText(ch.title) +
"</span>" +
'<span class="chapter-meta">约 ' +
mins +
" 分钟 · 第 " +
(i + 1) +
" 章</span>" +
"</div>" +
'<div class="md-wrap md-body">' +
window.MarkdownLite.markdownToHtml(ch.content, {
theme: state.prefs.theme,
dropCap: true
}) +
"</div>"
);
if (next) {
html.push(
'<button type="button" class="next-peek" data-next-idx="' +
(i + 1) +
'">' +
'<span class="next-peek-label">下一章</span>' +
'<span class="next-peek-title">' +
nextEmoji +
" " +
escapeText(next.title) +
"</span></button>"
);
}
html.push("</section>");
}
html.push(
'<div class="fin" id="book-fin">' +
'<span class="fin-emoji">✨</span>' +
'<span class="fin-title">全书读完</span>' +
'<span class="fin-desc">数字游民 · 一人公司 · 慢慢翻完也很棒</span>' +
'<div class="fin-actions">' +
'<button type="button" class="fin-btn" data-fin="share">发读完证书</button>' +
'<button type="button" class="fin-btn ghost" data-fin="restart">从头再读</button>' +
'<button type="button" class="fin-btn ghost" data-fin="home">返回封面</button>' +
"</div></div>"
);
if (el.paper) el.paper.innerHTML = html.join("");
renderToc("");
showView("reader");
setTimeout(function () {
if (jumpToProgress && state.progress && state.progress.chapterId) {
var idx = findChapterIndex(state.progress.chapterId);
if (idx < 0 && typeof state.progress.chapterIndex === "number") {
idx = state.progress.chapterIndex;
}
if (idx < 0) idx = 0;
state.activeChapter = idx;
var pct = Number(state.progress.scrollPercent) || 0;
if (pct > 2) {
restoreScrollPercent(pct);
} else {
jumpToChapter(idx, { lockMs: 600 });
}
} else {
scrollToY(0);
state.activeChapter = 0;
updateProgressUI();
}
}, 30);
}
function goRead() {
getProgress(state.book.id).then(function (progress) {
state.progress = progress;
if (progress) {
var idx =
typeof progress.chapterIndex === "number"
? progress.chapterIndex
: findChapterIndex(progress.chapterId);
if (idx >= 0) state.activeChapter = idx;
}
renderReader(true);
refreshPrefSegs();
syncActionLabels();
startReadTimer();
});
}
function goHome() {
stopReadTimer();
saveReadTime();
openToc(false);
openSettings(false);
closeCam();
closeJournalSheet();
renderHome();
}
function syncActionLabels() {
var ch = (state.book.chapters || [])[state.activeChapter];
if (el.btnBookmark) {
el.btnBookmark.textContent =
ch && isBookmarked(ch.id) ? "取消收藏" : "收藏本章";
}
var showComment = Bridge.canPostComment(state.buildVersion);
if (el.btnComment) setHidden(el.btnComment, !showComment);
if (el.btnCommentText) setHidden(el.btnCommentText, !showComment);
}
function chapterExcerpt(ch, maxLen) {
maxLen = maxLen || 100;
var raw = String((ch && ch.content) || "")
.replace(/```[\s\S]*?```/g, " ")
.replace(/`[^`]+`/g, " ")
.replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
.replace(/\[[^\]]*\]\([^)]*\)/g, " ")
.replace(/[#>*_\-~|]/g, " ")
.replace(/\s+/g, " ")
.trim();
if (raw.length <= maxLen) return raw;
return raw.slice(0, maxLen) + "…";
}
function makeQuoteCard() {
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
return makeTextCard({
brand: "异度世界",
title: book.title,
subtitle: ch ? ch.title : book.subtitle || "",
body: chapterExcerpt(ch, 110),
foot: "异度星球 · 离线阅读"
});
}
function makeTextCard(opts) {
var canvas = document.createElement("canvas");
canvas.width = 1080;
canvas.height = 1440;
var ctx = canvas.getContext("2d");
if (!ctx) return null;
var g = ctx.createLinearGradient(0, 0, 1080, 1440);
g.addColorStop(0, "#1a0b2e");
g.addColorStop(0.45, "#6d28d9");
g.addColorStop(1, "#db2777");
ctx.fillStyle = g;
ctx.fillRect(0, 0, 1080, 1440);
ctx.fillStyle = "rgba(255,255,255,0.12)";
ctx.beginPath();
ctx.arc(900, 180, 140, 0, Math.PI * 2);
ctx.fill();
ctx.fillStyle = "#fce7f3";
ctx.font = "700 56px sans-serif";
ctx.fillText(opts.brand || "异度世界", 96, 220);
ctx.font = "600 44px sans-serif";
wrapFillText(ctx, opts.title || "", 96, 320, 880, 58);
if (opts.subtitle) {
ctx.fillStyle = "rgba(252,231,243,0.88)";
ctx.font = "400 34px sans-serif";
wrapFillText(ctx, opts.subtitle, 96, 480, 880, 48);
}
if (opts.body) {
ctx.fillStyle = "rgba(255,255,255,0.78)";
ctx.font = "400 32px sans-serif";
wrapFillText(ctx, "「" + opts.body + "」", 96, 640, 880, 46);
}
if (opts.stats) {
ctx.fillStyle = "rgba(255,255,255,0.9)";
ctx.font = "600 40px sans-serif";
wrapFillText(ctx, opts.stats, 96, 980, 880, 52);
}
ctx.fillStyle = "rgba(255,255,255,0.55)";
ctx.font = "400 28px sans-serif";
ctx.fillText(opts.foot || "异度星球 · 离线阅读", 96, 1320);
return canvas.toDataURL("image/png");
}
function makeCheckinCard() {
var book = state.book;
var chapters = book.chapters || [];
var ch = chapters[state.activeChapter];
var pct = state.scrollPct || 0;
var readN = ((state.progress && state.progress.readChapterIds) || []).length;
if (!readN) readN = state.activeChapter + 1;
var streakDays = (state.streak && state.streak.days) || 0;
var stats =
"进度 " +
pct +
"% · 已读 " +
readN +
"/" +
chapters.length +
" 章 · 约剩 " +
remainingMinutes() +
" 分钟";
if (streakDays > 0) {
stats += " · 连续 " + streakDays + " 天";
}
var mins = todayReadMinutes();
if (mins > 0) {
stats += " · 今日 " + mins + " 分钟";
}
return makeTextCard({
brand: "阅读打卡",
title: book.title,
subtitle: ch ? "正在读 · " + ch.title : book.subtitle || "",
body: chapterExcerpt(ch, 90),
stats: stats,
foot: "异度星球 · 小红书小工具"
});
}
function makeFinishCard() {
var book = state.book;
var chapters = book.chapters || [];
var totalMins = 0;
for (var i = 0; i < chapters.length; i++) {
totalMins += chapterMinutes(chapters[i].content);
}
return makeTextCard({
brand: "读完证书",
title: book.title,
subtitle: "共 " + chapters.length + " 章 · 约 " + totalMins + " 分钟",
body: "我在异度星球读完了这本书",
stats: "✨ 全书通关 · " + todayKey(),
foot: "异度星球 · 小红书小工具"
});
}
function makeCoverCard() {
var book = state.book;
return makeTextCard({
brand: "异度世界",
title: book.title,
subtitle: book.subtitle || "",
body: (book.description || "").slice(0, 80) || chapterExcerpt(book.chapters && book.chapters[0], 80),
foot: "异度星球 · 离线阅读"
});
}
function requireMiniTool(actionLabel) {
if (!Bridge.getMiniTool()) {
alert("请在小红书 App 内使用「" + (actionLabel || "此功能") + "」");
return false;
}
return true;
}
function dataUrlToPath(dataUrl, persistRel) {
if (persistRel && Bridge.canUseFileSystem(state.buildVersion)) {
return Bridge.persistImage(dataUrl, persistRel).then(function (path) {
registerWork({
title: persistRel.indexOf("selfie") >= 0 ? "自拍打卡" : "生成图",
path: path,
kind: "image"
});
return path;
});
}
return Bridge.writeTempFile(dataUrl).catch(function () {
return dataUrl;
});
}
function postImagesNote(title, content, dataUrls) {
if (!requireMiniTool("发笔记")) return Promise.resolve();
var urls = dataUrls || [];
var chain = Promise.resolve([]);
var i;
for (i = 0; i < urls.length; i++) {
(function (dataUrl, index) {
chain = chain.then(function (acc) {
return dataUrlToPath(dataUrl, "share/img_" + index + ".png").then(
function (path) {
acc.push({ url: path });
return acc;
}
);
});
})(urls[i], i);
}
return chain
.then(function (images) {
if (!images.length) throw { errMsg: "无图片可发布" };
return Bridge.postNote({
title: String(title || "").slice(0, 20),
content: String(content || "").slice(0, 1000),
pageType: "photo_publish",
mediaInfo: { image_resources: images.slice(0, 18) }
});
})
.catch(function (err) {
alert((err && err.errMsg) || "发笔记失败");
});
}
function postCheckinNote() {
openSettings(false);
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
bumpStreak().then(function (streak) {
var card = makeCheckinCard();
if (!card) {
alert("无法生成打卡图");
return;
}
var title = "今日阅读打卡";
var content =
"📖 阅读打卡 · 《" +
book.title +
"》\n" +
(ch ? "章节:" + ch.title + "\n" : "") +
"进度:" +
(state.scrollPct || 0) +
"% · 约剩 " +
remainingMinutes() +
" 分钟\n" +
(streak && streak.days ? "连续打卡:" + streak.days + " 天\n" : "") +
(todayReadMinutes() > 0
? "今日已读约:" + todayReadMinutes() + " 分钟\n"
: "") +
"\n#阅读打卡 #数字游民 #一人公司";
refreshStorageCap();
postImagesNote(title, content, [card]);
});
}
function postFinishNote() {
var book = state.book;
var card = makeFinishCard();
if (!card) {
alert("无法生成证书");
return;
}
bumpStreak().then(function (streak) {
var content =
"🎓 我读完了《" +
book.title +
"》!\n共 " +
(book.chapters || []).length +
" 章\n" +
(streak && streak.days ? "连续阅读 " + streak.days + " 天\n" : "") +
"\n来自小工具「异度星球」\n#读完打卡 #数字游民 #一人公司";
postImagesNote("读完证书", content, [card]);
});
}
function openPhotoPicker() {
if (!requireMiniTool("配图发笔记")) return;
openSettings(false);
if (!el.inputPhoto) {
alert("选图组件未就绪");
return;
}
try {
el.inputPhoto.value = "";
el.inputPhoto.click();
} catch (e) {
alert("无法打开相册,请重试");
}
}
function onPhotoPicked(ev) {
var input = ev && ev.target;
var file = input && input.files && input.files[0];
if (!file) return;
Bridge.blobToDataUrl(file)
.then(function (dataUrl) {
var quote = makeQuoteCard();
var imgs = [dataUrl];
if (quote) imgs.push(quote);
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
var content =
"配图分享 · 《" +
book.title +
"》" +
(ch ? " · " + ch.title : "") +
"\n\n来自小工具「异度星球」\n#数字游民 #一人公司";
return postImagesNote((book.title || "异度星球").slice(0, 20), content, imgs);
})
.catch(function (err) {
alert((err && err.errMsg) || "读取图片失败");
});
}
function openVideoPicker() {
if (!requireMiniTool("选视频发笔记")) return;
openSettings(false);
if (!el.inputVideo) {
alert("选视频组件未就绪");
return;
}
try {
el.inputVideo.value = "";
el.inputVideo.click();
} catch (e) {
alert("无法打开相册,请重试");
}
}
function onVideoPicked(ev) {
var input = ev && ev.target;
var file = input && input.files && input.files[0];
if (!file) return;
if (!requireMiniTool("选视频发笔记")) return;
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
var cover = makeQuoteCard();
Bridge.blobToDataUrl(file)
.then(function (videoDataUrl) {
return Bridge.writeTempFile(videoDataUrl).then(function (videoPath) {
var coverP = cover
? Bridge.writeTempFile(cover).catch(function () {
return cover;
})
: Promise.resolve("");
return coverP.then(function (coverPath) {
return Bridge.postVideoNote({
title: (book.title || "异度星球").slice(0, 20),
content:
"视频分享 · 《" +
book.title +
"》" +
(ch ? " · " + ch.title : "") +
"\n\n来自小工具「异度星球」\n#数字游民 #一人公司",
videoPath: videoPath,
coverPath: coverPath || undefined
});
});
});
})
.catch(function (err) {
alert((err && err.errMsg) || "视频发笔记失败");
});
}
function stopCam() {
if (state.camStream && state.camStream.getTracks) {
var tracks = state.camStream.getTracks();
for (var i = 0; i < tracks.length; i++) {
try {
tracks[i].stop();
} catch (e) {}
}
}
state.camStream = null;
if (el.camVideo) {
try {
el.camVideo.srcObject = null;
} catch (e2) {}
}
}
function openCam() {
if (!requireMiniTool("自拍打卡")) return;
openSettings(false);
state.camShot = null;
setHidden(el.camMask, false);
setHidden(el.camVideo, false);
setHidden(el.camPreview, true);
if (el.camTip) el.camTip.textContent = "正在打开摄像头…";
var nav = navigator;
var getMedia =
(nav.mediaDevices && nav.mediaDevices.getUserMedia
? function (c) {
return nav.mediaDevices.getUserMedia(c);
}
: null) ||
nav.getUserMedia ||
nav.webkitGetUserMedia ||
nav.mozGetUserMedia;
if (!getMedia) {
if (el.camTip) el.camTip.textContent = "当前环境不支持摄像头";
return;
}
var constraints = { video: { facingMode: "user" }, audio: false };
var p;
if (nav.mediaDevices && nav.mediaDevices.getUserMedia) {
p = nav.mediaDevices.getUserMedia(constraints);
} else {
p = new Promise(function (resolve, reject) {
getMedia.call(nav, constraints, resolve, reject);
});
}
p.then(function (stream) {
state.camStream = stream;
if (el.camVideo) {
el.camVideo.srcObject = stream;
var playP = el.camVideo.play && el.camVideo.play();
if (playP && playP.catch) playP.catch(function () {});
}
if (el.camTip) el.camTip.textContent = "对准画面后点「拍照」";
}).catch(function () {
if (el.camTip) el.camTip.textContent = "摄像头授权失败,请在系统弹窗中允许";
});
}
function closeCam() {
stopCam();
state.camShot = null;
setHidden(el.camMask, true);
}
function snapCam() {
if (!el.camVideo || !el.camCanvas) return;
var video = el.camVideo;
var w = video.videoWidth || 720;
var h = video.videoHeight || 960;
if (!w || !h) {
if (el.camTip) el.camTip.textContent = "画面未就绪,请稍候再拍";
return;
}
var canvas = el.camCanvas;
canvas.width = 1080;
canvas.height = 1440;
var ctx = canvas.getContext("2d");
if (!ctx) return;
var scale = Math.max(1080 / w, 1440 / h);
var dw = w * scale;
var dh = h * scale;
var dx = (1080 - dw) / 2;
var dy = (1440 - dh) / 2;
ctx.drawImage(video, dx, dy, dw, dh);
var g = ctx.createLinearGradient(0, 1100, 0, 1440);
g.addColorStop(0, "rgba(0,0,0,0)");
g.addColorStop(1, "rgba(26,11,46,0.92)");
ctx.fillStyle = g;
ctx.fillRect(0, 1000, 1080, 440);
ctx.fillStyle = "#fce7f3";
ctx.font = "700 48px sans-serif";
ctx.fillText("自拍打卡", 72, 1180);
ctx.font = "600 36px sans-serif";
wrapFillText(ctx, state.book.title || "", 72, 1240, 920, 44);
var ch = (state.book.chapters || [])[state.activeChapter];
ctx.fillStyle = "rgba(255,255,255,0.8)";
ctx.font = "400 28px sans-serif";
ctx.fillText(
(ch ? ch.title + " · " : "") +
"进度 " +
(state.scrollPct || 0) +
"%" +
(state.streak && state.streak.days ? " · 连续" + state.streak.days + "天" : ""),
72,
1360
);
state.camShot = canvas.toDataURL("image/jpeg", 0.92);
if (el.camPreview) {
el.camPreview.src = state.camShot;
setHidden(el.camPreview, false);
}
setHidden(el.camVideo, true);
stopCam();
if (el.camTip) el.camTip.textContent = "已拍照 · 可发笔记或存相册";
}
function postCamShot() {
if (!state.camShot) {
alert("请先拍照");
return;
}
bumpStreak().then(function (streak) {
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
var content =
"📷 自拍打卡 · 《" +
book.title +
"》\n" +
(ch ? "章节:" + ch.title + "\n" : "") +
"进度:" +
(state.scrollPct || 0) +
"%\n" +
(streak && streak.days ? "连续打卡:" + streak.days + " 天\n" : "") +
"\n#自拍打卡 #数字游民 #一人公司打卡";
postImagesNote("自拍打卡", content, [state.camShot]).then(function () {
closeCam();
});
});
}
function saveCamAlbum() {
if (!state.camShot) {
alert("请先拍照");
return;
}
dataUrlToPath(state.camShot, "share/selfie.jpg")
.then(function (path) {
return Bridge.saveImageToPhotosAlbum(path);
})
.then(function () {
alert("已保存到相册");
})
.catch(function (err) {
alert((err && err.errMsg) || "保存失败");
});
}
function openJournalSheet() {
openSettings(false);
setHidden(el.journalMask, false);
if (el.journalInput) {
el.journalInput.value = "";
try {
el.journalInput.focus();
} catch (e) {}
}
}
function closeJournalSheet() {
setHidden(el.journalMask, true);
}
function saveJournalEntry(andShare) {
var text = el.journalInput ? String(el.journalInput.value || "").trim() : "";
if (!text) {
alert("请先写一点内容");
return;
}
if (text.length > 800) text = text.slice(0, 800);
var ch = (state.book.chapters || [])[state.activeChapter];
var entry = {
id: "j_" + Date.now(),
date: todayKey(),
text: text,
chapterId: ch && ch.id,
chapterTitle: ch && ch.title,
bookId: state.book.id,
updatedAt: Date.now()
};
state.journal = [entry].concat(state.journal || []).slice(0, 60);
saveJournal().then(function () {
// Best-effort append log line for 9.49+ filesystem
if (Bridge.canUseFileSystem(state.buildVersion)) {
Bridge.appendUtf8File(
"notes/journal.log",
todayKey() + "\t" + text.replace(/\n/g, " ") + "\n"
).catch(function () {});
}
refreshStorageCap();
if (andShare) {
shareJournalEntry(entry);
} else {
alert("日记已保存 · 可在侧栏「日记」查看");
closeJournalSheet();
openToc(true);
setDrawerTab("journal");
}
});
}
function findJournal(id) {
var list = state.journal || [];
for (var i = 0; i < list.length; i++) {
if (list[i].id === id) return list[i];
}
return null;
}
function shareJournalEntry(entry) {
if (!entry) return;
var card = makeTextCard({
brand: "阅读日记",
title: state.book.title,
subtitle: (entry.date || "") + (entry.chapterTitle ? " · " + entry.chapterTitle : ""),
body: entry.text || "",
foot: "异度星球 · 日记"
});
if (!card) return;
var content =
"📔 阅读日记 · 《" +
state.book.title +
"》\n" +
(entry.date ? entry.date + "\n" : "") +
"\n" +
(entry.text || "") +
"\n\n#数字游民 #一人公司日记";
postImagesNote("阅读日记", content, [card]).then(function () {
closeJournalSheet();
});
}
function deleteJournalEntry(id) {
state.journal = (state.journal || []).filter(function (j) {
return j.id !== id;
});
saveJournal().then(function () {
renderToc(el.tocFilter ? el.tocFilter.value : "");
refreshStorageCap();
});
}
function shareAllClipsNote() {
openSettings(false);
var notes = state.notes || [];
if (!notes.length) {
alert("还没有摘录,先点「摘录本章」");
return;
}
var imgs = [];
var texts = [];
var max = Math.min(notes.length, 9);
for (var i = 0; i < max; i++) {
var n = notes[i];
var card = makeTextCard({
brand: "摘录 " + (i + 1),
title: state.book.title,
subtitle: n.title || "",
body: n.text || "",
foot: "异度星球 · 摘录本"
});
if (card) imgs.push(card);
texts.push((i + 1) + ". " + (n.text || "").slice(0, 40));
}
if (!imgs.length) {
alert("无法生成摘录图");
return;
}
var content =
"我的阅读摘录 · 《" +
state.book.title +
"》\n共 " +
notes.length +
" 条(发布 " +
imgs.length +
" 图)\n\n" +
texts.join("\n") +
"\n\n#数字游民 #一人公司摘录";
postImagesNote("阅读摘录", content, imgs);
}
function saveAllClipsAlbum() {
openSettings(false);
var notes = state.notes || [];
if (!notes.length) {
alert("还没有摘录");
return;
}
if (!requireMiniTool("存相册")) return;
var max = Math.min(notes.length, 9);
var chain = Promise.resolve(0);
for (var i = 0; i < max; i++) {
(function (note, index) {
chain = chain.then(function (count) {
var card = makeTextCard({
brand: "摘录",
title: state.book.title,
subtitle: note.title || "",
body: note.text || "",
foot: "异度星球 · 摘录本"
});
if (!card) return count;
return dataUrlToPath(card, "notes/batch_" + index + ".png")
.then(function (path) {
return Bridge.saveImageToPhotosAlbum(path).then(function () {
return count + 1;
});
})
.catch(function () {
return count;
});
});
})(notes[i], i);
}
chain.then(function (count) {
alert(count > 0 ? "已保存 " + count + " 张到相册" : "保存失败");
});
}
function clipChapter() {
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
if (!ch) return;
var text = chapterExcerpt(ch, 160);
if (!text) {
alert("本章暂无可摘录正文");
return;
}
var note = {
id: "n_" + Date.now(),
bookId: book.id,
chapterId: ch.id,
chapterIndex: state.activeChapter,
title: ch.title,
text: text,
updatedAt: Date.now()
};
state.notes = [note].concat(state.notes || []).slice(0, 40);
saveNotes().then(function () {
alert("已摘录到侧栏「摘录」· 可发笔记 / 存相册 / 发评论");
refreshStorageCap();
openSettings(false);
openToc(true);
setDrawerTab("notes");
});
}
function findNote(id) {
var list = state.notes || [];
for (var i = 0; i < list.length; i++) {
if (list[i].id === id) return list[i];
}
return null;
}
function shareNoteItem(note) {
if (!note) return;
var card = makeTextCard({
brand: "摘录",
title: state.book.title,
subtitle: note.title || "",
body: note.text || "",
foot: "异度星球 · 摘录本"
});
if (!card) return;
var content =
"摘录自《" +
state.book.title +
"》" +
(note.title ? " · " + note.title : "") +
"\n\n「" +
(note.text || "") +
"」\n\n#数字游民 #一人公司摘录";
postImagesNote("阅读摘录", content, [card]);
}
function saveNoteToAlbum(note) {
if (!note || !requireMiniTool("存相册")) return;
var card = makeTextCard({
brand: "摘录",
title: state.book.title,
subtitle: note.title || "",
body: note.text || "",
foot: "异度星球 · 摘录本"
});
if (!card) return;
dataUrlToPath(card, "notes/" + note.id + ".png")
.then(function (path) {
return Bridge.saveImageToPhotosAlbum(path);
})
.then(function () {
alert("已保存到相册");
})
.catch(function (err) {
alert((err && err.errMsg) || "保存失败");
});
}
function commentNoteItem(note) {
if (!note) return;
if (!Bridge.canPostComment(state.buildVersion)) {
alert("当前客户端需 9.49+ 才支持发评论");
return;
}
var card = makeTextCard({
brand: "摘录",
title: state.book.title,
subtitle: note.title || "",
body: note.text || "",
foot: "异度星球"
});
if (!card) return;
Bridge.writeTempFile(card)
.then(function (filePath) {
return Bridge.postComment(
{
action: "post_comment",
content: "「" + (note.text || "").slice(0, 80) + "」 #数字游民",
media_bean: [{ media_type: "image", cover_image_url: filePath }],
miniToolSnapshotInfo: JSON.stringify({
bookId: state.book.id,
chapterId: note.chapterId,
chapterIndex: note.chapterIndex,
page: "reader",
noteId: note.id
}).slice(0, 2000)
},
true
);
})
.catch(function (err) {
alert((err && err.errMsg) || "唤起评论失败");
});
}
function deleteNoteItem(id) {
state.notes = (state.notes || []).filter(function (n) {
return n.id !== id;
});
saveNotes().then(function () {
renderToc(el.tocFilter ? el.tocFilter.value : "");
refreshStorageCap();
});
}
function multiShareNote() {
openSettings(false);
var cover = makeCoverCard();
var quote = makeQuoteCard();
var checkin = makeCheckinCard();
var imgs = [];
if (cover) imgs.push(cover);
if (quote) imgs.push(quote);
if (checkin) imgs.push(checkin);
if (!imgs.length) {
alert("无法生成图片");
return;
}
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
var content =
"正在读《" +
book.title +
"》" +
(ch ? " · " + ch.title : "") +
"\n进度 " +
(state.scrollPct || 0) +
"%\n\n来自小工具「异度星球」· 多图笔记\n#数字游民 #一人公司";
postImagesNote((book.title || "异度星球").slice(0, 20), content, imgs);
}
function saveQuoteCard() {
var dataUrl = makeQuoteCard();
if (!dataUrl) {
alert("无法生成图片");
return;
}
if (!requireMiniTool("保存金句图")) return;
dataUrlToPath(dataUrl, "share/quote.png")
.then(function (filePath) {
return Bridge.saveImageToPhotosAlbum(filePath);
})
.then(function () {
alert("已保存到相册");
})
.catch(function (err) {
Bridge.saveImageToPhotosAlbum(dataUrl)
.then(function () {
alert("已保存到相册");
})
.catch(function (err2) {
alert((err2 && err2.errMsg) || (err && err.errMsg) || "保存失败");
});
});
}
function shareNote() {
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
var title = (book.title || "异度星球").slice(0, 20);
var excerpt = chapterExcerpt(ch, 80);
var content =
"我在读《" +
book.title +
"》" +
(ch ? " · " + ch.title : "") +
(excerpt ? "\n\n「" + excerpt + "」" : "") +
"\n\n来自小工具「异度星球」· 异度世界";
var dataUrl = makeQuoteCard();
if (!dataUrl) {
alert("无法生成分享图");
return;
}
postImagesNote(title, content, [dataUrl]);
}
function postCommentExcerpt() {
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
var text =
"正在读《" + book.title + "》" + (ch ? " · " + ch.title : "") + " #数字游民";
if (!Bridge.canPostComment(state.buildVersion)) {
alert("当前客户端版本需 9.49+ 才支持发评论");
return;
}
var dataUrl = makeQuoteCard();
var snap = {
bookId: book.id,
chapterId: ch && ch.id,
chapterIndex: state.activeChapter,
scrollPercent: state.scrollPct || 0,
page: "reader"
};
var snapStr = JSON.stringify(snap);
if (snapStr.length > 2000) {
snap = { bookId: book.id, chapterId: ch && ch.id, page: "reader" };
snapStr = JSON.stringify(snap);
}
Bridge.writeTempFile(dataUrl)
.then(function (filePath) {
return Bridge.postComment(
{
action: "post_comment",
content: text,
media_bean: [
{ media_type: "image", cover_image_url: filePath }
],
miniToolSnapshotInfo: snapStr
},
true
);
})
.catch(function (err) {
alert((err && err.errMsg) || "唤起评论失败");
});
}
function postTextComment() {
var book = state.book;
var ch = (book.chapters || [])[state.activeChapter];
if (!Bridge.canPostComment(state.buildVersion)) {
alert("当前客户端版本需 9.49+ 才支持发评论");
return;
}
var excerpt = chapterExcerpt(ch, 60);
var text =
"正在读《" +
book.title +
"》" +
(ch ? " · " + ch.title : "") +
(excerpt ? "\n「" + excerpt + "」" : "") +
"\n进度 " +
(state.scrollPct || 0) +
"%" +
(todayReadMinutes() > 0 ? " · 今日已读" + todayReadMinutes() + "分钟" : "") +
" #异度星球";
var snapStr = JSON.stringify({
bookId: book.id,
chapterId: ch && ch.id,
chapterIndex: state.activeChapter,
scrollPercent: state.scrollPct || 0,
page: "reader"
}).slice(0, 2000);
Bridge.postComment(
{
action: "post_comment",
content: text,
miniToolSnapshotInfo: snapStr
},
false
).catch(function (err) {
alert((err && err.errMsg) || "唤起评论失败");
});
}
function findWork(id) {
var list = state.works || [];
for (var i = 0; i < list.length; i++) {
if (list[i].id === id) return list[i];
}
return null;
}
function openWorksPanel() {
openSettings(false);
openToc(true);
setDrawerTab("works");
}
function shareWorkItem(work) {
if (!work || !work.path) return;
if (!requireMiniTool("再发笔记")) return;
Bridge.postNote({
title: (work.title || "异度星球").slice(0, 20),
content: "来自小工具「异度星球」作品库\n#异度星球",
pageType: "photo_publish",
mediaInfo: { image_resources: [{ url: work.path }] }
}).catch(function (err) {
alert((err && err.errMsg) || "发笔记失败");
});
}
function saveWorkAlbum(work) {
if (!work || !work.path) return;
if (!requireMiniTool("存相册")) return;
Bridge.saveImageToPhotosAlbum(work.path)
.then(function () {
alert("已保存到相册");
})
.catch(function (err) {
alert((err && err.errMsg) || "保存失败");
});
}
function deleteWorkItem(id) {
var work = findWork(id);
state.works = (state.works || []).filter(function (w) {
return w.id !== id;
});
saveWorks().then(function () {
if (work && work.path && Bridge.canUseFileSystem(state.buildVersion)) {
Bridge.unlinkFile(work.path).catch(function () {});
}
renderToc(el.tocFilter ? el.tocFilter.value : "");
});
}
function cleanupGeneratedFiles() {
if (!Bridge.canUseFileSystem(state.buildVersion)) {
alert("需客户端 9.49+ 才支持清理文件缓存");
return;
}
if (!confirm("清理 share/ 下生成的临时图片?作品列表也会同步刷新")) return;
Bridge.cleanupShareDir().then(function (n) {
state.works = [];
return saveWorks().then(function () {
alert("已清理 " + (n || 0) + " 个文件");
refreshStorageCap();
});
});
}
function clearLocalData() {
if (!confirm("清除阅读进度、收藏、摘录和日记?(阅读设置与打卡天数会保留)")) return;
Promise.all([
Bridge.removeLocalData(PROGRESS_KEY),
Bridge.removeLocalData(BOOKMARKS_KEY),
Bridge.removeLocalData(NOTES_KEY),
Bridge.removeLocalData(JOURNAL_KEY)
]).then(function () {
state.progress = null;
state.bookmarks = [];
state.notes = [];
state.journal = [];
syncNotesToFs([]);
if (Bridge.canUseFileSystem(state.buildVersion)) {
Bridge.writeUtf8File(JOURNAL_FILE, "[]").catch(function () {});
}
alert("已清除进度、收藏、摘录与日记");
syncActionLabels();
refreshStorageCap();
goHome();
});
}
function closestTocItem(node) {
while (node && node.nodeType === 1) {
if (node.classList && node.classList.contains("drawer-item")) return node;
node = node.parentNode;
}
return null;
}
function wrapFillText(ctx, text, x, y, maxWidth, lineHeight) {
var chars = String(text || "").split("");
var line = "";
var cy = y;
for (var i = 0; i < chars.length; i++) {
var test = line + chars[i];
if (ctx.measureText(test).width > maxWidth && line) {
ctx.fillText(line, x, cy);
line = chars[i];
cy += lineHeight;
} else {
line = test;
}
}
if (line) ctx.fillText(line, x, cy);
}
function readCssPx(value) {
if (!value) return 0;
var n = parseFloat(String(value).replace("px", "").trim());
return isNaN(n) ? 0 : n;
}
function measureEnvInsetTop() {
try {
var probe = document.createElement("div");
probe.style.cssText =
"position:absolute;visibility:hidden;pointer-events:none;padding-top:constant(safe-area-inset-top);padding-top:env(safe-area-inset-top);";
document.body.appendChild(probe);
var px = readCssPx(window.getComputedStyle(probe).paddingTop);
document.body.removeChild(probe);
return px;
} catch (e) {
return 0;
}
}
function applySafeArea() {
try {
var root = document.documentElement;
var fromVar = 0;
try {
fromVar = readCssPx(
window.getComputedStyle(root).getPropertyValue("--safe-area-inset-top")
);
} catch (e1) {}
var fromEnv = measureEnvInsetTop();
var status = fromVar || fromEnv || 0;
if (status < 20) status = 32;
var hostChrome = 48;
var padTop = status + hostChrome;
root.style.setProperty("--app-pad-top", padTop + "px");
root.style.setProperty("--safe-area-inset-top", status + "px");
} catch (e) {
try {
document.documentElement.style.setProperty("--app-pad-top", "80px");
} catch (e2) {}
}
}
function collectEls() {
el.boot = $("view-boot");
el.bootText = $("boot-text");
el.home = $("view-home");
el.reader = $("view-reader");
el.coverGlow = $("cover-glow");
el.cover = $("btn-cover");
el.coverEmoji = $("cover-emoji");
el.coverTitle = $("cover-title");
el.homeTitle = $("home-title");
el.homeTease = $("home-tease");
el.homeAuthor = $("home-author");
el.homeHint = $("home-hint");
el.homeTime = $("home-time");
el.homeCheckin = $("home-checkin");
el.homeJournal = $("home-journal");
el.homeWorks = $("home-works");
el.btnStart = $("btn-start");
el.btnToc = $("btn-toc");
el.btnTocTitle = $("btn-toc-title");
el.btnSettings = $("btn-settings");
el.btnTop = $("btn-top");
el.btnShare = $("btn-share-note");
el.btnSaveCardFoot = $("btn-save-card-foot");
el.btnBookmark = $("btn-bookmark");
el.btnSaveCard = $("btn-save-card");
el.btnShareSettings = $("btn-share-settings");
el.btnComment = $("btn-comment");
el.btnCommentText = $("btn-comment-text");
el.btnWorks = $("btn-works");
el.btnCleanupFiles = $("btn-cleanup-files");
el.btnCheckin = $("btn-checkin");
el.btnSelfie = $("btn-selfie");
el.btnPhotoNote = $("btn-photo-note");
el.btnVideoNote = $("btn-video-note");
el.btnJournal = $("btn-journal");
el.btnClipNote = $("btn-clip-note");
el.btnClipsShare = $("btn-clips-share");
el.btnClipsAlbum = $("btn-clips-album");
el.btnMultiShare = $("btn-multi-share");
el.btnClearData = $("btn-clear-data");
el.btnBackHome = $("btn-back-home");
el.tabChapters = $("tab-chapters");
el.tabBookmarks = $("tab-bookmarks");
el.tabNotes = $("tab-notes");
el.tabJournal = $("tab-journal");
el.tabWorks = $("tab-works");
el.storageCap = $("storage-cap");
el.inputPhoto = $("input-photo");
el.inputVideo = $("input-video");
el.camMask = $("cam-mask");
el.camVideo = $("cam-video");
el.camCanvas = $("cam-canvas");
el.camPreview = $("cam-preview");
el.camTip = $("cam-tip");
el.btnCamSnap = $("btn-cam-snap");
el.btnCamPost = $("btn-cam-post");
el.btnCamAlbum = $("btn-cam-album");
el.btnCamClose = $("btn-cam-close");
el.journalMask = $("journal-mask");
el.journalSheet = $("journal-sheet");
el.journalInput = $("journal-input");
el.btnJournalSave = $("btn-journal-save");
el.btnJournalPost = $("btn-journal-post");
el.btnJournalClose = $("btn-journal-close");
el.chapterTitle = $("reader-chapter-title");
el.progressLabel = $("reader-progress-label");
el.topbarBar = $("topbar-bar");
el.topbar = $("topbar");
el.paper = $("paper");
el.tocMask = $("toc-mask");
el.tocDrawer = $("toc-drawer");
el.tocFilter = $("toc-filter");
el.tocList = $("toc-list");
el.drawerMeter = $("drawer-meter-fill");
el.drawerStatLeft = $("drawer-stat-left");
el.drawerStatRight = $("drawer-stat-right");
el.settingsMask = $("settings-mask");
el.settingsSheet = $("settings-sheet");
el.prefSize = $("pref-size");
el.prefLh = $("pref-lh");
el.prefFont = $("pref-font");
el.prefTheme = $("pref-theme");
}
function bind() {
if (state.bound) return;
state.bound = true;
on(el.btnStart, "click", goRead);
on(el.cover, "click", goRead);
on(el.btnToc, "click", function () {
openToc(true);
});
on(el.btnTocTitle, "click", function () {
openToc(true);
});
on(el.tocMask, "click", function () {
openToc(false);
});
on(el.tocDrawer, "click", function (ev) {
if (ev && ev.stopPropagation) ev.stopPropagation();
});
on(el.btnSettings, "click", function () {
refreshPrefSegs();
syncActionLabels();
openSettings(true);
});
on(el.settingsMask, "click", function (ev) {
if (ev.target === el.settingsMask) openSettings(false);
});
on(el.settingsSheet, "click", function (ev) {
if (ev && ev.stopPropagation) ev.stopPropagation();
});
on(el.btnTop, "click", function () {
jumpToChapter(0);
});
on(el.btnShare, "click", shareNote);
on(el.btnSaveCardFoot, "click", saveQuoteCard);
on(el.btnBookmark, "click", toggleBookmark);
on(el.btnSaveCard, "click", saveQuoteCard);
on(el.btnShareSettings, "click", shareNote);
on(el.btnComment, "click", postCommentExcerpt);
on(el.btnCommentText, "click", postTextComment);
on(el.btnWorks, "click", openWorksPanel);
on(el.btnCleanupFiles, "click", cleanupGeneratedFiles);
on(el.btnCheckin, "click", postCheckinNote);
on(el.btnSelfie, "click", openCam);
on(el.btnPhotoNote, "click", openPhotoPicker);
on(el.btnVideoNote, "click", openVideoPicker);
on(el.btnJournal, "click", openJournalSheet);
on(el.homeCheckin, "click", function () {
goRead();
setTimeout(function () {
postCheckinNote();
}, 400);
});
on(el.homeJournal, "click", function () {
goRead();
setTimeout(function () {
openJournalSheet();
}, 400);
});
on(el.homeWorks, "click", function () {
goRead();
setTimeout(function () {
openWorksPanel();
}, 400);
});
on(el.btnClipNote, "click", clipChapter);
on(el.btnClipsShare, "click", shareAllClipsNote);
on(el.btnClipsAlbum, "click", saveAllClipsAlbum);
on(el.btnMultiShare, "click", multiShareNote);
on(el.inputPhoto, "change", onPhotoPicked);
on(el.inputVideo, "change", onVideoPicked);
on(el.btnCamSnap, "click", snapCam);
on(el.btnCamPost, "click", postCamShot);
on(el.btnCamAlbum, "click", saveCamAlbum);
on(el.btnCamClose, "click", closeCam);
on(el.btnJournalSave, "click", function () {
saveJournalEntry(false);
});
on(el.btnJournalPost, "click", function () {
saveJournalEntry(true);
});
on(el.btnJournalClose, "click", closeJournalSheet);
on(el.journalMask, "click", function (ev) {
if (ev.target === el.journalMask) closeJournalSheet();
});
on(el.btnClearData, "click", clearLocalData);
on(el.btnBackHome, "click", goHome);
on(el.tabChapters, "click", function () {
setDrawerTab("chapters");
});
on(el.tabBookmarks, "click", function () {
setDrawerTab("bookmarks");
});
on(el.tabNotes, "click", function () {
setDrawerTab("notes");
});
on(el.tabJournal, "click", function () {
setDrawerTab("journal");
});
on(el.tabWorks, "click", function () {
setDrawerTab("works");
});
on(el.tocFilter, "input", function () {
renderToc(el.tocFilter.value);
});
on(el.tocList, "click", function (ev) {
var node = ev.target;
while (node && node !== el.tocList) {
var wAct = node.getAttribute && node.getAttribute("data-work-act");
if (wAct) {
var wid = node.getAttribute("data-work-id");
var work = findWork(wid);
if (wAct === "share") shareWorkItem(work);
else if (wAct === "album") saveWorkAlbum(work);
else if (wAct === "del") deleteWorkItem(wid);
return;
}
var jAct = node.getAttribute && node.getAttribute("data-journal-act");
if (jAct) {
var jid = node.getAttribute("data-journal-id");
if (jAct === "share") shareJournalEntry(findJournal(jid));
else if (jAct === "del") deleteJournalEntry(jid);
return;
}
var act = node.getAttribute && node.getAttribute("data-note-act");
if (act) {
var nid = node.getAttribute("data-note-id");
var note = findNote(nid);
if (act === "share") shareNoteItem(note);
else if (act === "album") saveNoteToAlbum(note);
else if (act === "comment") commentNoteItem(note);
else if (act === "del") deleteNoteItem(nid);
return;
}
if (node.classList && node.classList.contains("drawer-item")) {
var idx = Number(node.getAttribute("data-idx") || 0);
openToc(false);
jumpToChapter(idx);
return;
}
node = node.parentNode;
}
});
on(el.paper, "click", function (ev) {
var node = ev.target;
while (node && node !== el.paper) {
if (node.getAttribute && node.getAttribute("data-fin") === "share") {
postFinishNote();
return;
}
if (node.getAttribute && node.getAttribute("data-fin") === "restart") {
jumpToChapter(0);
return;
}
if (node.getAttribute && node.getAttribute("data-fin") === "home") {
goHome();
return;
}
if (node.classList && node.classList.contains("next-peek")) {
var idx = Number(node.getAttribute("data-next-idx") || 0);
jumpToChapter(idx);
return;
}
node = node.parentNode;
}
handleReaderTap(ev);
});
var touchStart = null;
on(el.paper, "touchstart", function (ev) {
var t = ev.touches && ev.touches[0];
if (!t) return;
touchStart = { x: t.clientX, y: t.clientY, t: Date.now() };
});
on(el.paper, "touchend", function (ev) {
if (!touchStart) return;
var t = ev.changedTouches && ev.changedTouches[0];
if (!t) {
touchStart = null;
return;
}
var dx = Math.abs(t.clientX - touchStart.x);
var dy = Math.abs(t.clientY - touchStart.y);
var dt = Date.now() - touchStart.t;
touchStart = null;
if (dx > 12 || dy > 12 || dt > 450) return;
// synthetic path already handled by click on most WebViews
});
on(window, "scroll", function () {
if (el.reader && (!el.reader.classList || !el.reader.classList.contains("is-hidden"))) {
updateProgressUI();
}
});
}
function setChromeHidden(hidden) {
state.chromeHidden = !!hidden;
if (!el.reader) return;
if (hidden) {
if (el.reader.classList) el.reader.classList.add("chrome-hidden");
else el.reader.className += " chrome-hidden";
} else {
if (el.reader.classList) el.reader.classList.remove("chrome-hidden");
else
el.reader.className = String(el.reader.className || "").replace(
/\bchrome-hidden\b/g,
""
);
}
}
function handleReaderTap(ev) {
if (!ev) return;
var node = ev.target;
while (node && node !== el.paper) {
if (
node.tagName === "BUTTON" ||
node.tagName === "A" ||
(node.classList &&
(node.classList.contains("next-peek") || node.classList.contains("fin-btn")))
) {
return;
}
node = node.parentNode;
}
var x = ev.clientX;
if (typeof x !== "number") return;
var w = window.innerWidth || 360;
var zone = w / 3;
if (x < zone) {
scrollToY((window.pageYOffset || 0) - Math.round((window.innerHeight || 600) * 0.85));
setTimeout(updateProgressUI, 40);
} else if (x > w - zone) {
scrollToY((window.pageYOffset || 0) + Math.round((window.innerHeight || 600) * 0.85));
setTimeout(updateProgressUI, 40);
} else {
setChromeHidden(!state.chromeHidden);
}
}
function findChapterIndex(chapterId) {
var chapters = (state.book && state.book.chapters) || [];
for (var i = 0; i < chapters.length; i++) {
if (chapters[i].id === chapterId) return i;
}
return -1;
}
function applySnapshot(snap) {
if (!snap || snap.page !== "reader") return false;
if (snap.bookId && state.book && snap.bookId !== state.book.id) return false;
var idx =
typeof snap.chapterIndex === "number"
? snap.chapterIndex
: findChapterIndex(snap.chapterId);
if (idx < 0) idx = 0;
state.activeChapter = idx;
var pct = Number(snap.scrollPercent) || 0;
getProgress(state.book.id).then(function (progress) {
state.progress = progress || {
bookId: state.book.id,
chapterId: snap.chapterId,
chapterIndex: idx,
scrollPercent: pct
};
if (!progress && snap.chapterId) {
state.progress.chapterId = snap.chapterId;
state.progress.scrollPercent = pct;
} else if (progress && pct > 0) {
state.progress.scrollPercent = pct;
state.progress.chapterId = snap.chapterId || progress.chapterId;
state.progress.chapterIndex = idx;
}
renderReader(true);
refreshPrefSegs();
syncActionLabels();
});
return true;
}
function boot() {
try {
if (!Bridge) {
if ($("boot-text")) $("boot-text").textContent = "桥接模块未加载";
return;
}
collectEls();
applySafeArea();
if (!el.boot || !el.home || !el.btnStart) {
if (el.bootText) el.bootText.textContent = "页面结构异常";
return;
}
var book = getBookData();
if (!book) {
showBootError("内容未加载");
return;
}
if (!window.MarkdownLite) {
showBootError("渲染模块未加载");
return;
}
state.book = book;
Bridge.getBuildVersion()
.then(function (v) {
state.buildVersion = v || 0;
return Promise.all([
loadPrefs(),
loadBookmarks(),
loadNotes(),
loadJournal(),
loadStreak(),
loadReadTime(),
loadWorks(),
Bridge.getLaunchOptions()
]);
})
.then(function (tuple) {
state.prefs = tuple[0] || copyObj(DEFAULT_PREFS);
bind();
refreshStorageCap();
var snap = Bridge.readSnapshotInfo(tuple[7]);
if (snap && applySnapshot(snap)) {
startReadTimer();
return;
}
renderHome();
})
.catch(function (err) {
showBootError("启动错误: " + (err && err.message ? err.message : String(err)));
});
} catch (err) {
var msg = err && err.message ? err.message : String(err);
showBootError("启动错误: " + msg);
}
}
if (document.readyState === "loading") {
on(document, "DOMContentLoaded", boot);
} else {
boot();
}
})();