/* bundled xhs ebook — data = weapp nomadCodeBook */ // Auto-generated from src/data/nomadCodeBook.ts (weapp SoT) — do not edit by hand. var BOOK_DATA = { "id": "default", "title": "数字游民", "subtitle": "远程生活 · 自由工作入门", "author": "林远", "cover_emoji": "📖", "description": "离开工位、带着电脑去看世界——一边工作,一边把日子过成自己想要的样子。", "tags": [ "数字游民", "远程办公", "旅居生活", "自由职业", "边走边工作" ], "chapter_count": 7, "word_count": 5001, "is_free": true, "chapters": [ { "id": "00-preface", "title": "序:我想换一种活法", "order": 1, "content": "# 序:我想换一种活法\r\n\r\n二〇二三年秋天,我在公司工位上坐满了三年。\r\n\r\n显示器左边是 Jira,右边是 Slack,中间是我已经改过十七遍的需求文档。某个加班的深夜,我刷到一张清迈咖啡馆的照片——阳光从百叶窗缝里漏进来,一台 MacBook 和一杯冰美式,背景里有人在用泰语点单。\r\n\r\n那一刻我突然意识到:**我想要的不是更好的工位,而是可以选择坐在哪里。**\r\n\r\n---\r\n\r\n## 这不是逃离\r\n\r\n很多人把数字游民理解成「辞职、环游世界、发 Instagram」。不是的。\r\n\r\n数字游民是一种**工作方式**:你的产出不绑定在某个地理坐标上。你可以在上海写代码,也可以在里斯本写代码——只要网络稳定、时区能协调、交付不掉链子。\r\n\r\nHomelab 则是另一种自由:无论你在哪个时区醒来,你的文件、你的服务、你的数据,都在一个你完全掌控的地方等着你。\r\n\r\n这本书写的,就是这两件事如何交织在一起。\r\n\r\n---\r\n\r\n## 你会读到什么\r\n\r\n这不是技术文档,也不是旅行攻略。这是一个普通程序员,从第一次远程办公,到在东南亚租下月付公寓,再到把家里那台旧服务器变成「随时能连回去的数字基地」的真实过程。\r\n\r\n有踩过的坑,也有意外的好运。\r\n\r\n如果你也在想:**能不能不辞职,但换一种活法?**\r\n\r\n那就从下一章开始吧。\r\n" }, { "id": "01-first-remote", "title": "第一次远程办公的那个周五", "order": 2, "content": "# 第一次远程办公的那个周五\r\n\r\n周五下午三点,Team Leader 在群里发了一条消息:\r\n\r\n> 「下周开始,技术组全员 remote,有问题的私聊 HR。」\r\n\r\n我盯着这条消息看了很久。不是担心,是一种奇怪的安静——像考试结束铃响之前,你已经写完了最后一道题。\r\n\r\n---\r\n\r\n## 第一天\r\n\r\n周一早上九点,我穿着睡衣坐在餐桌前,打开 Zoom。\r\n\r\n同事们的脸出现在格子里,有人还在刷牙,有人背景是乱糟糟的卧室。会议结束后,我泡了杯咖啡,走到阳台。\r\n\r\n楼下有人在遛狗,阳光很好。\r\n\r\n**原来工作日也可以是这样。**\r\n\r\n---\r\n\r\n## 效率的幻觉\r\n\r\n远程的第一周,我效率奇高。没有通勤,没有工位旁的闲聊,没有「开完这个会再写代码」的拖延。\r\n\r\n第二周,我开始分不清「工作结束」和「生活开始」的边界。晚上十一点,Slack 还亮着绿点。周末,邮箱里躺着三条「不急,周一前看就行」的消息。\r\n\r\n我学到一个词:**异步沟通**。不是「随时在线」,而是「明确预期」——什么时候回复、什么算紧急、什么可以等到下一个工作日。\r\n\r\n---\r\n\r\n## 那个周五的后续\r\n\r\n三个月后,HR 发邮件说办公室租约到期,技术组永久 remote。\r\n\r\n我没有回「太好了」,也没有回「怎么办」。我只是打开地图,搜索了「清迈 月租 公寓 WiFi」。\r\n\r\n有些改变,不是突然发生的。是你某天回头看,发现路已经走了一半。\r\n" }, { "id": "02-chiangmai", "title": "清迈的周二早晨", "order": 3, "content": "# 清迈的周二早晨\r\n\r\n七点半,我被摩托车声叫醒。\r\n\r\n不是闹钟——是楼下送菜的小贩,喇叭里循环播放泰语,我一个字也听不懂,但已经习惯了。这是我在清迈的第三周。\r\n\r\n---\r\n\r\n## 咖啡馆即办公室\r\n\r\n我住的公寓步行十分钟有一家叫 **Graph Table** 的咖啡馆。二层靠窗的位置,能看到一条安静的小巷。WiFi 密码写在收银台的小黑板上,下载速度稳定在 80 Mbps 左右。\r\n\r\n我点一杯 flat white,打开 VS Code。\r\n\r\n旁边的荷兰设计师在画 Figma,日本背包客在写旅行博客。没有人问「你是来旅游的还是来工作的」——在这里,这两件事本来就不矛盾。\r\n\r\n---\r\n\r\n## 时区的艺术\r\n\r\n我在东七区,团队大部分人在东八区。这意味着:\r\n\r\n- 我的「早上十点 standup」,是清迈的九点\r\n- 他们的「下班前 review」,是我的下午五点——刚好收工去夜市\r\n\r\n我学会把深度工作放在本地上午,把会议和沟通压缩到下午。不是妥协,是**设计**。\r\n\r\n---\r\n\r\n## 孤独与社群\r\n\r\n数字游民最容易被忽视的问题,不是签证,不是网络,是**孤独**。\r\n\r\n我在 Nomad List 的 Discord 里认识了几个常驻清迈的开发者。我们每周三晚上在 Nimman 区聚餐,聊技术、聊签证、聊哪个 co-working 空间的空调更冷。\r\n\r\n**游牧不是一个人流浪,是在流动中找到同类。**\r\n\r\n---\r\n\r\n## 周二的结尾\r\n\r\n晚上八点,我骑摩托车回公寓。路过塔佩门,游客正在拍夜景。我停了一分钟,然后继续往前。\r\n\r\n明天还有 standup。但此刻,清迈的风是温的。\r\n" }, { "id": "03-gear", "title": "行囊里真正重要的东西", "order": 4, "content": "# 行囊里真正重要的东西\r\n\r\n出发前,我在 Reddit 的 r/digitalnomad 翻了三天装备帖。最后发现:**带多了是负担,带少了会后悔。**\r\n\r\n这是我在路上一年后,精简再精简的清单。\r\n\r\n---\r\n\r\n## 电脑:唯一不能妥协的\r\n\r\n一台 14 寸 MacBook Pro,M 系列芯片,16GB 内存。不是最新款,但足够跑 Docker、开十几个 Chrome 标签、同时 Zoom 和写代码。\r\n\r\n外接显示器?我试过,最后卖了。游牧的核心是**移动**,不是把工位复制到每一个城市。\r\n\r\n---\r\n\r\n## 网络:比护照更重要\r\n\r\n我随身带三样东西:\r\n\r\n1. **本地 SIM 卡** — 落地当天买,流量包月\r\n2. **便携路由器** — GL.iNet 那类,支持 4G 备用\r\n3. **Tailscale** — 后面会细讲,这是连回 Homelab 的钥匙\r\n\r\n在清迈、巴厘岛、里斯本,我学会的第一件事永远是:先测 WiFi,再 unpack。\r\n\r\n---\r\n\r\n## 其他:能省则省\r\n\r\n- 降噪耳机:飞机、咖啡馆、合租房必备\r\n- 万能转换插头:一个就够\r\n- 折叠键盘:可选,我最后只用笔记本自带\r\n\r\n衣服?一个 40L 背包,七天的量,到哪里都能洗。\r\n\r\n---\r\n\r\n## 真正重要的\r\n\r\n装备可以列清单,但有三样东西清单上写不下:\r\n\r\n**稳定的收入、可预期的工作节奏、以及一个随时可以回去的地方。**\r\n\r\n第三个,Homelab 会帮你解决。\r\n" }, { "id": "04-homelab", "title": "把熟悉的数字生活带在身边", "order": 5, "content": "# 把熟悉的数字生活带在身边\r\n\r\n二〇二二年,我还住在租来的单间里,床底下藏着一台 Dell OptiPlex 小主机。\r\n\r\n当时只是想跑个 Plex,把电影串流到手机。没想到,这台几百块的机器,后来成了我整个数字生活的中枢。\r\n\r\n---\r\n\r\n## 什么是 Homelab\r\n\r\nHomelab,字面意思是「家庭实验室」。简单说,就是**你自己搭的、自己管的服务器环境**。\r\n\r\n不是云服务那种「按月订阅、数据在别人机房」。是你的 NAS、你的 Git 仓库、你的笔记同步、你的自动化脚本——物理上可能就在你国内那个出租屋里,逻辑上却跟着你走遍世界。\r\n\r\n---\r\n\r\n## 我的第一套配置\r\n\r\n| 组件 | 选择 | 用途 |\r\n|------|------|------|\r\n| 主机 | Dell OptiPlex 7040 | 7×24 低功耗运行 |\r\n| 系统 | Proxmox | 虚拟机管理 |\r\n| 存储 | 4TB 机械 + 256GB SSD | 文件 + 系统 |\r\n| 服务 | Jellyfin, Nextcloud, Gitea | 媒体、同步、代码 |\r\n\r\n总花费不到三千块。比一台新 iPhone 便宜,但价值在于:**它是你的。**\r\n\r\n---\r\n\r\n## 为什么游牧者需要 Homelab\r\n\r\n人在清迈,文件在上海的硬盘里——听起来很蠢,对吧?\r\n\r\n但云盘有容量限制,有审查风险,有「服务条款变更」的隐患。Homelab 给你的,是**数据主权**和**不受地点限制的访问权**。\r\n\r\n配合 Tailscale 或 WireGuard,你在任何 WiFi 下,都能像坐在家里一样访问自己的服务。\r\n\r\n---\r\n\r\n## 从一台旧电脑开始\r\n\r\n你不需要一上来就买机柜、交换机、UPS。\r\n\r\n找一台闲置笔记本,装 Linux,跑一个 Nextcloud 或 FileBrowser。能远程访问,就算 Homelab 入门了。\r\n\r\n**完美是优秀的敌人。先跑起来,再迭代。**\r\n\r\n下一章,我们聊怎么「连回家」。\r\n" }, { "id": "05-network", "title": "无论在哪,都能连回家", "order": 6, "content": "# 无论在哪,都能连回家\r\n\r\n清迈咖啡馆的 WiFi 突然断了。\r\n\r\n我切换到手机热点,打开终端,输入:\r\n\r\n```bash\r\nssh nas\r\n```\r\n\r\n三秒后,我出现在家里那台 Proxmox 主机的 shell 里。文件在,服务在,就像从未离开过。\r\n\r\n靠的是 **Tailscale**。\r\n\r\n---\r\n\r\n## 虚拟局域网\r\n\r\nTailscale 基于 WireGuard,把你在不同网络的设备,组成一个加密的虚拟局域网(Tailnet)。\r\n\r\n家里跑 Tailscale 的 NAS,笔记本跑 Tailscale 客户端——无论 IP 怎么变,它们永远在「同一个局域网」里。\r\n\r\n配置过程:\r\n\r\n1. 在 Homelab 主机安装 Tailscale\r\n2. 笔记本、手机同样安装并登录同一账号\r\n3. 用 MagicDNS 给设备起名字,比如 `nas.tail-xxxxx.ts.net`\r\n\r\n不需要公网 IP,不需要端口转发,不需要折腾路由器。\r\n\r\n---\r\n\r\n## 我常用的远程场景\r\n\r\n**同步文件** — Nextcloud 客户端走 Tailscale 内网,速度比公网快,也不暴露服务到互联网。\r\n\r\n**看代码** — Gitea 跑在内网,浏览器打开 `http://gitea:3000`,只有 Tailnet 里的设备能访问。\r\n\r\n**紧急修复** — 生产环境告警,SSH 进去,改配置,重启服务。人在巴厘岛,手在家里。\r\n\r\n---\r\n\r\n## 安全习惯\r\n\r\n- Homelab 服务**默认不暴露公网**\r\n- 敏感操作走 SSH 密钥,禁用密码登录\r\n- 定期备份到另一块硬盘,异地再备一份\r\n\r\n网络自由的前提,是**安全意识**不能掉线。\r\n\r\n---\r\n\r\n## 连回家,意味着什么\r\n\r\n游牧者容易有一种漂流感:今天这条街,明天那座城,没有锚。\r\n\r\nHomelab 给我的锚,不是地理上的,是**数字上的**——我知道有一个地方,存着我的东西,跑着我的服务,随时等我回来。\r\n\r\n这种确定感,和清迈的咖啡一样,是/nomad 生活的基础设施。\r\n" }, { "id": "06-epilogue", "title": "终章:自由是一种日常", "order": 7, "content": "# 终章:自由是一种日常\r\n\r\n写这本书时,我人在里斯本。\r\n\r\n公寓窗外是电车轨道,偶尔有铃声。桌上有半杯 bica,电脑屏幕里是未提交的 commit。\r\n\r\n---\r\n\r\n## 自由不是假期\r\n\r\n很多人把数字游民想象成「永远在度假」。实际上,周二依然是周二,需求依然会改,bug 依然会在上线前出现。\r\n\r\n**自由不是不用工作,而是可以选择在哪里、以什么节奏工作。**\r\n\r\n---\r\n\r\n## 流动的生活,与随身的「数字家」\r\n\r\n这两件事看起来方向相反:\r\n\r\n- 旅居是**流动**\r\n- 数字家是**固定**\r\n\r\n但组合在一起,逻辑就通了:你在物理世界移动,数字世界的「家」保持不动。像蜗牛的壳,不是负担,是随身携带的秩序。\r\n\r\n---\r\n\r\n## 给正在考虑的你\r\n\r\n如果你还在工位上读这本书,不必立刻辞职,不必立刻买票。\r\n\r\n你可以:\r\n\r\n1. 先和团队谈一次远程办公的可能性\r\n2. 整理一套自己常用的文件与备份习惯\r\n3. 选一个周末,带着电脑去邻城住两晚,测试「在别处工作」的感觉\r\n\r\n**小步验证,比宏大计划更可靠。**\r\n\r\n---\r\n\r\n## 最后\r\n\r\n《数字游民》写的不是「如何逃离」,而是「如何建造」——建造一种你真正想要的生活,并用节奏和纪律去支撑它。\r\n\r\n书到这里结束。你的下一章,在自己手里。\r\n\r\n—— 林远 \r\n写于里斯本,一个普通的周二\r\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, "&") .replace(//g, ">"); } function inline(s, c) { return escapeHtml(s) .replace(/\*\*(.+?)\*\*/g, '$1') .replace(/\*(.+?)\*/g, '$1') .replace(/`([^`]+)`/g, '$1'); } 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(//g, ""); text = text.replace(//gi, "> 🎬 视频请在 nomadro 查看"); text = text.replace(//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(""); inUl = false; } if (inOl) { out.push(""); inOl = false; olIndex = 0; } } function flushQuote() { if (!inQuote) return; var body = quoteBuf.map(function (q) { return inline(q, c); }).join("
"); out.push('
' + body + "
"); 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 = ['
']; rows[0].forEach(function (cell) { html.push(""); }); html.push(""); for (var r = 1; r < rows.length; r++) { html.push(""); rows[r].forEach(function (cell) { html.push(""); }); html.push(""); } html.push("
" + inline(cell, c) + "
" + inline(cell, c) + "
"); 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('
' + escapeHtml(codeBuf.join("\n")) + "
"); 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('
'); continue; } var h1 = /^#\s+(.+)$/.exec(line); if (h1) { closeLists(); if (!skippedChapterTitle) { skippedChapterTitle = true; continue; } out.push("

" + inline(h1[1], c) + "

"); 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("

" + inline(h2[1], c) + "

"); continue; } var h3 = /^###\s+(.+)$/.exec(line); if (h3) { closeLists(); out.push("

" + inline(h3[1], c) + "

"); continue; } var task = /^\s*[-*+]\s+\[([ xX])\]\s+(.+)$/.exec(line); if (task) { if (inOl) { out.push(""); inOl = false; olIndex = 0; } if (!inUl) { out.push('
'); inUl = true; } var mark = /x/i.test(task[1]) ? "☑" : "☐"; out.push("
" + mark + " " + inline(task[2], c) + "
"); continue; } var ul = /^\s*[-*+]\s+(.+)$/.exec(line); if (ul) { if (inOl) { out.push("
"); inOl = false; olIndex = 0; } if (!inUl) { out.push('
'); inUl = true; } out.push("
• " + inline(ul[1], c) + "
"); continue; } var ol = /^\s*(\d+)\.\s+(.+)$/.exec(line); if (ol) { if (inUl) { out.push("
"); inUl = false; } if (!inOl) { out.push('
'); inOl = true; olIndex = 0; } olIndex += 1; out.push("
" + olIndex + ". " + inline(ol[2], c) + "
"); continue; } if (!line.trim()) { closeLists(); continue; } closeLists(); paraCount += 1; var cls = dropCap && paraCount === 1 ? ' class="dropcap"' : ""; out.push("" + inline(line.trim(), c) + "

"); } flushQuote(); closeLists(); if (inCode) { out.push('
' + escapeHtml(codeBuf.join("\n")) + "
"); } 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 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); /* book-app runtime */ (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 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, "&") .replace(//g, ">"); } 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( '
' + escapeText(work.title || "作品") + '' + escapeText(work.kind || "image") + " · " + formatAgo(work.updatedAt || Date.now()) + '
' + '' + '' + '
' ); } el.tocList.innerHTML = html.join("") || '

还没有作品。保存金句图 / 打卡后会出现在这里(需 9.49+ 文件能力)。

'; 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( '
' + escapeText(je.date || "日记") + (je.chapterTitle ? " · " + escapeText(je.chapterTitle) : "") + '' + escapeText((je.text || "").slice(0, 80)) + (je.text && je.text.length > 80 ? "…" : "") + '
' + '' + '
' ); } el.tocList.innerHTML = html.join("") || '

还没有日记。在设置里点「写阅读日记」。

'; 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( '
' + escapeText(note.title || "摘录") + '' + escapeText((note.text || "").slice(0, 72)) + (note.text && note.text.length > 72 ? "…" : "") + '
' + '' + '' + (Bridge.canPostComment(state.buildVersion) ? '' : "") + '
' ); } el.tocList.innerHTML = html.join("") || '

还没有摘录。在设置里点「摘录本章」,可发小红书笔记。

'; 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( '" ); } el.tocList.innerHTML = html.join("") || '

还没有收藏,在设置里点「收藏本章」

'; 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( '" ); } el.tocList.innerHTML = html.join("") || '

没有匹配的章节

'; 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( '
' + '' + escapeText(book.cover_emoji || "🌏") + "" + '' + escapeText(book.title || "") + "" + '' + escapeText(book.subtitle || "") + "" + '
' + '
' + chapters.length + '章节
' + '
' + Math.max(1, Math.round((book.word_count || 5000) / 1000)) + 'k字数
' + '
' + totalMins + '分钟
' + '
' + remainingMinutes() + '余下
' + "
" + '点左右翻页 · 点中间显隐顶栏' + "
" ); 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('
'); if (i > 0) { html.push( '
· · ·
' ); } html.push( '
' + '
' + '' + emoji + "" + '' + pad2(i + 1) + '/' + chapters.length + "" + "
" + '' + escapeText(ch.title) + "" + '约 ' + mins + " 分钟 · 第 " + (i + 1) + " 章" + "
" + '
' + window.MarkdownLite.markdownToHtml(ch.content, { theme: state.prefs.theme, dropCap: true }) + "
" ); if (next) { html.push( '" ); } html.push("
"); } html.push( '
' + '✨' + '全书读完' + '数字游民 · 一人公司 · 慢慢翻完也很棒' + '
' + '' + '' + '' + "
" ); 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: "nomadro", 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 || "nomadro", 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: "nomadro", 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来自小工具「数字游民」· nomadro"; 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(); } })();