(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: "异度世界", title: book.title, subtitle: ch ? ch.title : book.subtitle || "", body: chapterExcerpt(ch, 110), foot: "异度星球 · 离线阅读" }); } function makeTextCard(opts) { var canvas = document.createElement("canvas"); canvas.width = 1080; canvas.height = 1440; var ctx = canvas.getContext("2d"); if (!ctx) return null; var g = ctx.createLinearGradient(0, 0, 1080, 1440); g.addColorStop(0, "#1a0b2e"); g.addColorStop(0.45, "#6d28d9"); g.addColorStop(1, "#db2777"); ctx.fillStyle = g; ctx.fillRect(0, 0, 1080, 1440); ctx.fillStyle = "rgba(255,255,255,0.12)"; ctx.beginPath(); ctx.arc(900, 180, 140, 0, Math.PI * 2); ctx.fill(); ctx.fillStyle = "#fce7f3"; ctx.font = "700 56px sans-serif"; ctx.fillText(opts.brand || "异度世界", 96, 220); ctx.font = "600 44px sans-serif"; wrapFillText(ctx, opts.title || "", 96, 320, 880, 58); if (opts.subtitle) { ctx.fillStyle = "rgba(252,231,243,0.88)"; ctx.font = "400 34px sans-serif"; wrapFillText(ctx, opts.subtitle, 96, 480, 880, 48); } if (opts.body) { ctx.fillStyle = "rgba(255,255,255,0.78)"; ctx.font = "400 32px sans-serif"; wrapFillText(ctx, "「" + opts.body + "」", 96, 640, 880, 46); } if (opts.stats) { ctx.fillStyle = "rgba(255,255,255,0.9)"; ctx.font = "600 40px sans-serif"; wrapFillText(ctx, opts.stats, 96, 980, 880, 52); } ctx.fillStyle = "rgba(255,255,255,0.55)"; ctx.font = "400 28px sans-serif"; ctx.fillText(opts.foot || "异度星球 · 离线阅读", 96, 1320); return canvas.toDataURL("image/png"); } function makeCheckinCard() { var book = state.book; var chapters = book.chapters || []; var ch = chapters[state.activeChapter]; var pct = state.scrollPct || 0; var readN = ((state.progress && state.progress.readChapterIds) || []).length; if (!readN) readN = state.activeChapter + 1; var streakDays = (state.streak && state.streak.days) || 0; var stats = "进度 " + pct + "% · 已读 " + readN + "/" + chapters.length + " 章 · 约剩 " + remainingMinutes() + " 分钟"; if (streakDays > 0) { stats += " · 连续 " + streakDays + " 天"; } var mins = todayReadMinutes(); if (mins > 0) { stats += " · 今日 " + mins + " 分钟"; } return makeTextCard({ brand: "阅读打卡", title: book.title, subtitle: ch ? "正在读 · " + ch.title : book.subtitle || "", body: chapterExcerpt(ch, 90), stats: stats, foot: "异度星球 · 小红书小工具" }); } function makeFinishCard() { var book = state.book; var chapters = book.chapters || []; var totalMins = 0; for (var i = 0; i < chapters.length; i++) { totalMins += chapterMinutes(chapters[i].content); } return makeTextCard({ brand: "读完证书", title: book.title, subtitle: "共 " + chapters.length + " 章 · 约 " + totalMins + " 分钟", body: "我在异度星球读完了这本书", stats: "✨ 全书通关 · " + todayKey(), foot: "异度星球 · 小红书小工具" }); } function makeCoverCard() { var book = state.book; return makeTextCard({ brand: "异度世界", title: book.title, subtitle: book.subtitle || "", body: (book.description || "").slice(0, 80) || chapterExcerpt(book.chapters && book.chapters[0], 80), foot: "异度星球 · 离线阅读" }); } function requireMiniTool(actionLabel) { if (!Bridge.getMiniTool()) { alert("请在小红书 App 内使用「" + (actionLabel || "此功能") + "」"); return false; } return true; } function dataUrlToPath(dataUrl, persistRel) { if (persistRel && Bridge.canUseFileSystem(state.buildVersion)) { return Bridge.persistImage(dataUrl, persistRel).then(function (path) { registerWork({ title: persistRel.indexOf("selfie") >= 0 ? "自拍打卡" : "生成图", path: path, kind: "image" }); return path; }); } return Bridge.writeTempFile(dataUrl).catch(function () { return dataUrl; }); } function postImagesNote(title, content, dataUrls) { if (!requireMiniTool("发笔记")) return Promise.resolve(); var urls = dataUrls || []; var chain = Promise.resolve([]); var i; for (i = 0; i < urls.length; i++) { (function (dataUrl, index) { chain = chain.then(function (acc) { return dataUrlToPath(dataUrl, "share/img_" + index + ".png").then( function (path) { acc.push({ url: path }); return acc; } ); }); })(urls[i], i); } return chain .then(function (images) { if (!images.length) throw { errMsg: "无图片可发布" }; return Bridge.postNote({ title: String(title || "").slice(0, 20), content: String(content || "").slice(0, 1000), pageType: "photo_publish", mediaInfo: { image_resources: images.slice(0, 18) } }); }) .catch(function (err) { alert((err && err.errMsg) || "发笔记失败"); }); } function postCheckinNote() { openSettings(false); var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; bumpStreak().then(function (streak) { var card = makeCheckinCard(); if (!card) { alert("无法生成打卡图"); return; } var title = "今日阅读打卡"; var content = "📖 阅读打卡 · 《" + book.title + "》\n" + (ch ? "章节:" + ch.title + "\n" : "") + "进度:" + (state.scrollPct || 0) + "% · 约剩 " + remainingMinutes() + " 分钟\n" + (streak && streak.days ? "连续打卡:" + streak.days + " 天\n" : "") + (todayReadMinutes() > 0 ? "今日已读约:" + todayReadMinutes() + " 分钟\n" : "") + "\n#阅读打卡 #数字游民 #一人公司"; refreshStorageCap(); postImagesNote(title, content, [card]); }); } function postFinishNote() { var book = state.book; var card = makeFinishCard(); if (!card) { alert("无法生成证书"); return; } bumpStreak().then(function (streak) { var content = "🎓 我读完了《" + book.title + "》!\n共 " + (book.chapters || []).length + " 章\n" + (streak && streak.days ? "连续阅读 " + streak.days + " 天\n" : "") + "\n来自小工具「异度星球」\n#读完打卡 #数字游民 #一人公司"; postImagesNote("读完证书", content, [card]); }); } function openPhotoPicker() { if (!requireMiniTool("配图发笔记")) return; openSettings(false); if (!el.inputPhoto) { alert("选图组件未就绪"); return; } try { el.inputPhoto.value = ""; el.inputPhoto.click(); } catch (e) { alert("无法打开相册,请重试"); } } function onPhotoPicked(ev) { var input = ev && ev.target; var file = input && input.files && input.files[0]; if (!file) return; Bridge.blobToDataUrl(file) .then(function (dataUrl) { var quote = makeQuoteCard(); var imgs = [dataUrl]; if (quote) imgs.push(quote); var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; var content = "配图分享 · 《" + book.title + "》" + (ch ? " · " + ch.title : "") + "\n\n来自小工具「异度星球」\n#数字游民 #一人公司"; return postImagesNote((book.title || "异度星球").slice(0, 20), content, imgs); }) .catch(function (err) { alert((err && err.errMsg) || "读取图片失败"); }); } function openVideoPicker() { if (!requireMiniTool("选视频发笔记")) return; openSettings(false); if (!el.inputVideo) { alert("选视频组件未就绪"); return; } try { el.inputVideo.value = ""; el.inputVideo.click(); } catch (e) { alert("无法打开相册,请重试"); } } function onVideoPicked(ev) { var input = ev && ev.target; var file = input && input.files && input.files[0]; if (!file) return; if (!requireMiniTool("选视频发笔记")) return; var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; var cover = makeQuoteCard(); Bridge.blobToDataUrl(file) .then(function (videoDataUrl) { return Bridge.writeTempFile(videoDataUrl).then(function (videoPath) { var coverP = cover ? Bridge.writeTempFile(cover).catch(function () { return cover; }) : Promise.resolve(""); return coverP.then(function (coverPath) { return Bridge.postVideoNote({ title: (book.title || "异度星球").slice(0, 20), content: "视频分享 · 《" + book.title + "》" + (ch ? " · " + ch.title : "") + "\n\n来自小工具「异度星球」\n#数字游民 #一人公司", videoPath: videoPath, coverPath: coverPath || undefined }); }); }); }) .catch(function (err) { alert((err && err.errMsg) || "视频发笔记失败"); }); } function stopCam() { if (state.camStream && state.camStream.getTracks) { var tracks = state.camStream.getTracks(); for (var i = 0; i < tracks.length; i++) { try { tracks[i].stop(); } catch (e) {} } } state.camStream = null; if (el.camVideo) { try { el.camVideo.srcObject = null; } catch (e2) {} } } function openCam() { if (!requireMiniTool("自拍打卡")) return; openSettings(false); state.camShot = null; setHidden(el.camMask, false); setHidden(el.camVideo, false); setHidden(el.camPreview, true); if (el.camTip) el.camTip.textContent = "正在打开摄像头…"; var nav = navigator; var getMedia = (nav.mediaDevices && nav.mediaDevices.getUserMedia ? function (c) { return nav.mediaDevices.getUserMedia(c); } : null) || nav.getUserMedia || nav.webkitGetUserMedia || nav.mozGetUserMedia; if (!getMedia) { if (el.camTip) el.camTip.textContent = "当前环境不支持摄像头"; return; } var constraints = { video: { facingMode: "user" }, audio: false }; var p; if (nav.mediaDevices && nav.mediaDevices.getUserMedia) { p = nav.mediaDevices.getUserMedia(constraints); } else { p = new Promise(function (resolve, reject) { getMedia.call(nav, constraints, resolve, reject); }); } p.then(function (stream) { state.camStream = stream; if (el.camVideo) { el.camVideo.srcObject = stream; var playP = el.camVideo.play && el.camVideo.play(); if (playP && playP.catch) playP.catch(function () {}); } if (el.camTip) el.camTip.textContent = "对准画面后点「拍照」"; }).catch(function () { if (el.camTip) el.camTip.textContent = "摄像头授权失败,请在系统弹窗中允许"; }); } function closeCam() { stopCam(); state.camShot = null; setHidden(el.camMask, true); } function snapCam() { if (!el.camVideo || !el.camCanvas) return; var video = el.camVideo; var w = video.videoWidth || 720; var h = video.videoHeight || 960; if (!w || !h) { if (el.camTip) el.camTip.textContent = "画面未就绪,请稍候再拍"; return; } var canvas = el.camCanvas; canvas.width = 1080; canvas.height = 1440; var ctx = canvas.getContext("2d"); if (!ctx) return; var scale = Math.max(1080 / w, 1440 / h); var dw = w * scale; var dh = h * scale; var dx = (1080 - dw) / 2; var dy = (1440 - dh) / 2; ctx.drawImage(video, dx, dy, dw, dh); var g = ctx.createLinearGradient(0, 1100, 0, 1440); g.addColorStop(0, "rgba(0,0,0,0)"); g.addColorStop(1, "rgba(26,11,46,0.92)"); ctx.fillStyle = g; ctx.fillRect(0, 1000, 1080, 440); ctx.fillStyle = "#fce7f3"; ctx.font = "700 48px sans-serif"; ctx.fillText("自拍打卡", 72, 1180); ctx.font = "600 36px sans-serif"; wrapFillText(ctx, state.book.title || "", 72, 1240, 920, 44); var ch = (state.book.chapters || [])[state.activeChapter]; ctx.fillStyle = "rgba(255,255,255,0.8)"; ctx.font = "400 28px sans-serif"; ctx.fillText( (ch ? ch.title + " · " : "") + "进度 " + (state.scrollPct || 0) + "%" + (state.streak && state.streak.days ? " · 连续" + state.streak.days + "天" : ""), 72, 1360 ); state.camShot = canvas.toDataURL("image/jpeg", 0.92); if (el.camPreview) { el.camPreview.src = state.camShot; setHidden(el.camPreview, false); } setHidden(el.camVideo, true); stopCam(); if (el.camTip) el.camTip.textContent = "已拍照 · 可发笔记或存相册"; } function postCamShot() { if (!state.camShot) { alert("请先拍照"); return; } bumpStreak().then(function (streak) { var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; var content = "📷 自拍打卡 · 《" + book.title + "》\n" + (ch ? "章节:" + ch.title + "\n" : "") + "进度:" + (state.scrollPct || 0) + "%\n" + (streak && streak.days ? "连续打卡:" + streak.days + " 天\n" : "") + "\n#自拍打卡 #数字游民 #一人公司打卡"; postImagesNote("自拍打卡", content, [state.camShot]).then(function () { closeCam(); }); }); } function saveCamAlbum() { if (!state.camShot) { alert("请先拍照"); return; } dataUrlToPath(state.camShot, "share/selfie.jpg") .then(function (path) { return Bridge.saveImageToPhotosAlbum(path); }) .then(function () { alert("已保存到相册"); }) .catch(function (err) { alert((err && err.errMsg) || "保存失败"); }); } function openJournalSheet() { openSettings(false); setHidden(el.journalMask, false); if (el.journalInput) { el.journalInput.value = ""; try { el.journalInput.focus(); } catch (e) {} } } function closeJournalSheet() { setHidden(el.journalMask, true); } function saveJournalEntry(andShare) { var text = el.journalInput ? String(el.journalInput.value || "").trim() : ""; if (!text) { alert("请先写一点内容"); return; } if (text.length > 800) text = text.slice(0, 800); var ch = (state.book.chapters || [])[state.activeChapter]; var entry = { id: "j_" + Date.now(), date: todayKey(), text: text, chapterId: ch && ch.id, chapterTitle: ch && ch.title, bookId: state.book.id, updatedAt: Date.now() }; state.journal = [entry].concat(state.journal || []).slice(0, 60); saveJournal().then(function () { // Best-effort append log line for 9.49+ filesystem if (Bridge.canUseFileSystem(state.buildVersion)) { Bridge.appendUtf8File( "notes/journal.log", todayKey() + "\t" + text.replace(/\n/g, " ") + "\n" ).catch(function () {}); } refreshStorageCap(); if (andShare) { shareJournalEntry(entry); } else { alert("日记已保存 · 可在侧栏「日记」查看"); closeJournalSheet(); openToc(true); setDrawerTab("journal"); } }); } function findJournal(id) { var list = state.journal || []; for (var i = 0; i < list.length; i++) { if (list[i].id === id) return list[i]; } return null; } function shareJournalEntry(entry) { if (!entry) return; var card = makeTextCard({ brand: "阅读日记", title: state.book.title, subtitle: (entry.date || "") + (entry.chapterTitle ? " · " + entry.chapterTitle : ""), body: entry.text || "", foot: "异度星球 · 日记" }); if (!card) return; var content = "📔 阅读日记 · 《" + state.book.title + "》\n" + (entry.date ? entry.date + "\n" : "") + "\n" + (entry.text || "") + "\n\n#数字游民 #一人公司日记"; postImagesNote("阅读日记", content, [card]).then(function () { closeJournalSheet(); }); } function deleteJournalEntry(id) { state.journal = (state.journal || []).filter(function (j) { return j.id !== id; }); saveJournal().then(function () { renderToc(el.tocFilter ? el.tocFilter.value : ""); refreshStorageCap(); }); } function shareAllClipsNote() { openSettings(false); var notes = state.notes || []; if (!notes.length) { alert("还没有摘录,先点「摘录本章」"); return; } var imgs = []; var texts = []; var max = Math.min(notes.length, 9); for (var i = 0; i < max; i++) { var n = notes[i]; var card = makeTextCard({ brand: "摘录 " + (i + 1), title: state.book.title, subtitle: n.title || "", body: n.text || "", foot: "异度星球 · 摘录本" }); if (card) imgs.push(card); texts.push((i + 1) + ". " + (n.text || "").slice(0, 40)); } if (!imgs.length) { alert("无法生成摘录图"); return; } var content = "我的阅读摘录 · 《" + state.book.title + "》\n共 " + notes.length + " 条(发布 " + imgs.length + " 图)\n\n" + texts.join("\n") + "\n\n#数字游民 #一人公司摘录"; postImagesNote("阅读摘录", content, imgs); } function saveAllClipsAlbum() { openSettings(false); var notes = state.notes || []; if (!notes.length) { alert("还没有摘录"); return; } if (!requireMiniTool("存相册")) return; var max = Math.min(notes.length, 9); var chain = Promise.resolve(0); for (var i = 0; i < max; i++) { (function (note, index) { chain = chain.then(function (count) { var card = makeTextCard({ brand: "摘录", title: state.book.title, subtitle: note.title || "", body: note.text || "", foot: "异度星球 · 摘录本" }); if (!card) return count; return dataUrlToPath(card, "notes/batch_" + index + ".png") .then(function (path) { return Bridge.saveImageToPhotosAlbum(path).then(function () { return count + 1; }); }) .catch(function () { return count; }); }); })(notes[i], i); } chain.then(function (count) { alert(count > 0 ? "已保存 " + count + " 张到相册" : "保存失败"); }); } function clipChapter() { var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; if (!ch) return; var text = chapterExcerpt(ch, 160); if (!text) { alert("本章暂无可摘录正文"); return; } var note = { id: "n_" + Date.now(), bookId: book.id, chapterId: ch.id, chapterIndex: state.activeChapter, title: ch.title, text: text, updatedAt: Date.now() }; state.notes = [note].concat(state.notes || []).slice(0, 40); saveNotes().then(function () { alert("已摘录到侧栏「摘录」· 可发笔记 / 存相册 / 发评论"); refreshStorageCap(); openSettings(false); openToc(true); setDrawerTab("notes"); }); } function findNote(id) { var list = state.notes || []; for (var i = 0; i < list.length; i++) { if (list[i].id === id) return list[i]; } return null; } function shareNoteItem(note) { if (!note) return; var card = makeTextCard({ brand: "摘录", title: state.book.title, subtitle: note.title || "", body: note.text || "", foot: "异度星球 · 摘录本" }); if (!card) return; var content = "摘录自《" + state.book.title + "》" + (note.title ? " · " + note.title : "") + "\n\n「" + (note.text || "") + "」\n\n#数字游民 #一人公司摘录"; postImagesNote("阅读摘录", content, [card]); } function saveNoteToAlbum(note) { if (!note || !requireMiniTool("存相册")) return; var card = makeTextCard({ brand: "摘录", title: state.book.title, subtitle: note.title || "", body: note.text || "", foot: "异度星球 · 摘录本" }); if (!card) return; dataUrlToPath(card, "notes/" + note.id + ".png") .then(function (path) { return Bridge.saveImageToPhotosAlbum(path); }) .then(function () { alert("已保存到相册"); }) .catch(function (err) { alert((err && err.errMsg) || "保存失败"); }); } function commentNoteItem(note) { if (!note) return; if (!Bridge.canPostComment(state.buildVersion)) { alert("当前客户端需 9.49+ 才支持发评论"); return; } var card = makeTextCard({ brand: "摘录", title: state.book.title, subtitle: note.title || "", body: note.text || "", foot: "异度星球" }); if (!card) return; Bridge.writeTempFile(card) .then(function (filePath) { return Bridge.postComment( { action: "post_comment", content: "「" + (note.text || "").slice(0, 80) + "」 #数字游民", media_bean: [{ media_type: "image", cover_image_url: filePath }], miniToolSnapshotInfo: JSON.stringify({ bookId: state.book.id, chapterId: note.chapterId, chapterIndex: note.chapterIndex, page: "reader", noteId: note.id }).slice(0, 2000) }, true ); }) .catch(function (err) { alert((err && err.errMsg) || "唤起评论失败"); }); } function deleteNoteItem(id) { state.notes = (state.notes || []).filter(function (n) { return n.id !== id; }); saveNotes().then(function () { renderToc(el.tocFilter ? el.tocFilter.value : ""); refreshStorageCap(); }); } function multiShareNote() { openSettings(false); var cover = makeCoverCard(); var quote = makeQuoteCard(); var checkin = makeCheckinCard(); var imgs = []; if (cover) imgs.push(cover); if (quote) imgs.push(quote); if (checkin) imgs.push(checkin); if (!imgs.length) { alert("无法生成图片"); return; } var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; var content = "正在读《" + book.title + "》" + (ch ? " · " + ch.title : "") + "\n进度 " + (state.scrollPct || 0) + "%\n\n来自小工具「异度星球」· 多图笔记\n#数字游民 #一人公司"; postImagesNote((book.title || "异度星球").slice(0, 20), content, imgs); } function saveQuoteCard() { var dataUrl = makeQuoteCard(); if (!dataUrl) { alert("无法生成图片"); return; } if (!requireMiniTool("保存金句图")) return; dataUrlToPath(dataUrl, "share/quote.png") .then(function (filePath) { return Bridge.saveImageToPhotosAlbum(filePath); }) .then(function () { alert("已保存到相册"); }) .catch(function (err) { Bridge.saveImageToPhotosAlbum(dataUrl) .then(function () { alert("已保存到相册"); }) .catch(function (err2) { alert((err2 && err2.errMsg) || (err && err.errMsg) || "保存失败"); }); }); } function shareNote() { var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; var title = (book.title || "异度星球").slice(0, 20); var excerpt = chapterExcerpt(ch, 80); var content = "我在读《" + book.title + "》" + (ch ? " · " + ch.title : "") + (excerpt ? "\n\n「" + excerpt + "」" : "") + "\n\n来自小工具「异度星球」· 异度世界"; var dataUrl = makeQuoteCard(); if (!dataUrl) { alert("无法生成分享图"); return; } postImagesNote(title, content, [dataUrl]); } function postCommentExcerpt() { var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; var text = "正在读《" + book.title + "》" + (ch ? " · " + ch.title : "") + " #数字游民"; if (!Bridge.canPostComment(state.buildVersion)) { alert("当前客户端版本需 9.49+ 才支持发评论"); return; } var dataUrl = makeQuoteCard(); var snap = { bookId: book.id, chapterId: ch && ch.id, chapterIndex: state.activeChapter, scrollPercent: state.scrollPct || 0, page: "reader" }; var snapStr = JSON.stringify(snap); if (snapStr.length > 2000) { snap = { bookId: book.id, chapterId: ch && ch.id, page: "reader" }; snapStr = JSON.stringify(snap); } Bridge.writeTempFile(dataUrl) .then(function (filePath) { return Bridge.postComment( { action: "post_comment", content: text, media_bean: [ { media_type: "image", cover_image_url: filePath } ], miniToolSnapshotInfo: snapStr }, true ); }) .catch(function (err) { alert((err && err.errMsg) || "唤起评论失败"); }); } function postTextComment() { var book = state.book; var ch = (book.chapters || [])[state.activeChapter]; if (!Bridge.canPostComment(state.buildVersion)) { alert("当前客户端版本需 9.49+ 才支持发评论"); return; } var excerpt = chapterExcerpt(ch, 60); var text = "正在读《" + book.title + "》" + (ch ? " · " + ch.title : "") + (excerpt ? "\n「" + excerpt + "」" : "") + "\n进度 " + (state.scrollPct || 0) + "%" + (todayReadMinutes() > 0 ? " · 今日已读" + todayReadMinutes() + "分钟" : "") + " #异度星球"; var snapStr = JSON.stringify({ bookId: book.id, chapterId: ch && ch.id, chapterIndex: state.activeChapter, scrollPercent: state.scrollPct || 0, page: "reader" }).slice(0, 2000); Bridge.postComment( { action: "post_comment", content: text, miniToolSnapshotInfo: snapStr }, false ).catch(function (err) { alert((err && err.errMsg) || "唤起评论失败"); }); } function findWork(id) { var list = state.works || []; for (var i = 0; i < list.length; i++) { if (list[i].id === id) return list[i]; } return null; } function openWorksPanel() { openSettings(false); openToc(true); setDrawerTab("works"); } function shareWorkItem(work) { if (!work || !work.path) return; if (!requireMiniTool("再发笔记")) return; Bridge.postNote({ title: (work.title || "异度星球").slice(0, 20), content: "来自小工具「异度星球」作品库\n#异度星球", pageType: "photo_publish", mediaInfo: { image_resources: [{ url: work.path }] } }).catch(function (err) { alert((err && err.errMsg) || "发笔记失败"); }); } function saveWorkAlbum(work) { if (!work || !work.path) return; if (!requireMiniTool("存相册")) return; Bridge.saveImageToPhotosAlbum(work.path) .then(function () { alert("已保存到相册"); }) .catch(function (err) { alert((err && err.errMsg) || "保存失败"); }); } function deleteWorkItem(id) { var work = findWork(id); state.works = (state.works || []).filter(function (w) { return w.id !== id; }); saveWorks().then(function () { if (work && work.path && Bridge.canUseFileSystem(state.buildVersion)) { Bridge.unlinkFile(work.path).catch(function () {}); } renderToc(el.tocFilter ? el.tocFilter.value : ""); }); } function cleanupGeneratedFiles() { if (!Bridge.canUseFileSystem(state.buildVersion)) { alert("需客户端 9.49+ 才支持清理文件缓存"); return; } if (!confirm("清理 share/ 下生成的临时图片?作品列表也会同步刷新")) return; Bridge.cleanupShareDir().then(function (n) { state.works = []; return saveWorks().then(function () { alert("已清理 " + (n || 0) + " 个文件"); refreshStorageCap(); }); }); } function clearLocalData() { if (!confirm("清除阅读进度、收藏、摘录和日记?(阅读设置与打卡天数会保留)")) return; Promise.all([ Bridge.removeLocalData(PROGRESS_KEY), Bridge.removeLocalData(BOOKMARKS_KEY), Bridge.removeLocalData(NOTES_KEY), Bridge.removeLocalData(JOURNAL_KEY) ]).then(function () { state.progress = null; state.bookmarks = []; state.notes = []; state.journal = []; syncNotesToFs([]); if (Bridge.canUseFileSystem(state.buildVersion)) { Bridge.writeUtf8File(JOURNAL_FILE, "[]").catch(function () {}); } alert("已清除进度、收藏、摘录与日记"); syncActionLabels(); refreshStorageCap(); goHome(); }); } function closestTocItem(node) { while (node && node.nodeType === 1) { if (node.classList && node.classList.contains("drawer-item")) return node; node = node.parentNode; } return null; } function wrapFillText(ctx, text, x, y, maxWidth, lineHeight) { var chars = String(text || "").split(""); var line = ""; var cy = y; for (var i = 0; i < chars.length; i++) { var test = line + chars[i]; if (ctx.measureText(test).width > maxWidth && line) { ctx.fillText(line, x, cy); line = chars[i]; cy += lineHeight; } else { line = test; } } if (line) ctx.fillText(line, x, cy); } function readCssPx(value) { if (!value) return 0; var n = parseFloat(String(value).replace("px", "").trim()); return isNaN(n) ? 0 : n; } function measureEnvInsetTop() { try { var probe = document.createElement("div"); probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none;padding-top:constant(safe-area-inset-top);padding-top:env(safe-area-inset-top);"; document.body.appendChild(probe); var px = readCssPx(window.getComputedStyle(probe).paddingTop); document.body.removeChild(probe); return px; } catch (e) { return 0; } } function applySafeArea() { try { var root = document.documentElement; var fromVar = 0; try { fromVar = readCssPx( window.getComputedStyle(root).getPropertyValue("--safe-area-inset-top") ); } catch (e1) {} var fromEnv = measureEnvInsetTop(); var status = fromVar || fromEnv || 0; if (status < 20) status = 32; var hostChrome = 48; var padTop = status + hostChrome; root.style.setProperty("--app-pad-top", padTop + "px"); root.style.setProperty("--safe-area-inset-top", status + "px"); } catch (e) { try { document.documentElement.style.setProperty("--app-pad-top", "80px"); } catch (e2) {} } } function collectEls() { el.boot = $("view-boot"); el.bootText = $("boot-text"); el.home = $("view-home"); el.reader = $("view-reader"); el.coverGlow = $("cover-glow"); el.cover = $("btn-cover"); el.coverEmoji = $("cover-emoji"); el.coverTitle = $("cover-title"); el.homeTitle = $("home-title"); el.homeTease = $("home-tease"); el.homeAuthor = $("home-author"); el.homeHint = $("home-hint"); el.homeTime = $("home-time"); el.homeCheckin = $("home-checkin"); el.homeJournal = $("home-journal"); el.homeWorks = $("home-works"); el.btnStart = $("btn-start"); el.btnToc = $("btn-toc"); el.btnTocTitle = $("btn-toc-title"); el.btnSettings = $("btn-settings"); el.btnTop = $("btn-top"); el.btnShare = $("btn-share-note"); el.btnSaveCardFoot = $("btn-save-card-foot"); el.btnBookmark = $("btn-bookmark"); el.btnSaveCard = $("btn-save-card"); el.btnShareSettings = $("btn-share-settings"); el.btnComment = $("btn-comment"); el.btnCommentText = $("btn-comment-text"); el.btnWorks = $("btn-works"); el.btnCleanupFiles = $("btn-cleanup-files"); el.btnCheckin = $("btn-checkin"); el.btnSelfie = $("btn-selfie"); el.btnPhotoNote = $("btn-photo-note"); el.btnVideoNote = $("btn-video-note"); el.btnJournal = $("btn-journal"); el.btnClipNote = $("btn-clip-note"); el.btnClipsShare = $("btn-clips-share"); el.btnClipsAlbum = $("btn-clips-album"); el.btnMultiShare = $("btn-multi-share"); el.btnClearData = $("btn-clear-data"); el.btnBackHome = $("btn-back-home"); el.tabChapters = $("tab-chapters"); el.tabBookmarks = $("tab-bookmarks"); el.tabNotes = $("tab-notes"); el.tabJournal = $("tab-journal"); el.tabWorks = $("tab-works"); el.storageCap = $("storage-cap"); el.inputPhoto = $("input-photo"); el.inputVideo = $("input-video"); el.camMask = $("cam-mask"); el.camVideo = $("cam-video"); el.camCanvas = $("cam-canvas"); el.camPreview = $("cam-preview"); el.camTip = $("cam-tip"); el.btnCamSnap = $("btn-cam-snap"); el.btnCamPost = $("btn-cam-post"); el.btnCamAlbum = $("btn-cam-album"); el.btnCamClose = $("btn-cam-close"); el.journalMask = $("journal-mask"); el.journalSheet = $("journal-sheet"); el.journalInput = $("journal-input"); el.btnJournalSave = $("btn-journal-save"); el.btnJournalPost = $("btn-journal-post"); el.btnJournalClose = $("btn-journal-close"); el.chapterTitle = $("reader-chapter-title"); el.progressLabel = $("reader-progress-label"); el.topbarBar = $("topbar-bar"); el.topbar = $("topbar"); el.paper = $("paper"); el.tocMask = $("toc-mask"); el.tocDrawer = $("toc-drawer"); el.tocFilter = $("toc-filter"); el.tocList = $("toc-list"); el.drawerMeter = $("drawer-meter-fill"); el.drawerStatLeft = $("drawer-stat-left"); el.drawerStatRight = $("drawer-stat-right"); el.settingsMask = $("settings-mask"); el.settingsSheet = $("settings-sheet"); el.prefSize = $("pref-size"); el.prefLh = $("pref-lh"); el.prefFont = $("pref-font"); el.prefTheme = $("pref-theme"); } function bind() { if (state.bound) return; state.bound = true; on(el.btnStart, "click", goRead); on(el.cover, "click", goRead); on(el.btnToc, "click", function () { openToc(true); }); on(el.btnTocTitle, "click", function () { openToc(true); }); on(el.tocMask, "click", function () { openToc(false); }); on(el.tocDrawer, "click", function (ev) { if (ev && ev.stopPropagation) ev.stopPropagation(); }); on(el.btnSettings, "click", function () { refreshPrefSegs(); syncActionLabels(); openSettings(true); }); on(el.settingsMask, "click", function (ev) { if (ev.target === el.settingsMask) openSettings(false); }); on(el.settingsSheet, "click", function (ev) { if (ev && ev.stopPropagation) ev.stopPropagation(); }); on(el.btnTop, "click", function () { jumpToChapter(0); }); on(el.btnShare, "click", shareNote); on(el.btnSaveCardFoot, "click", saveQuoteCard); on(el.btnBookmark, "click", toggleBookmark); on(el.btnSaveCard, "click", saveQuoteCard); on(el.btnShareSettings, "click", shareNote); on(el.btnComment, "click", postCommentExcerpt); on(el.btnCommentText, "click", postTextComment); on(el.btnWorks, "click", openWorksPanel); on(el.btnCleanupFiles, "click", cleanupGeneratedFiles); on(el.btnCheckin, "click", postCheckinNote); on(el.btnSelfie, "click", openCam); on(el.btnPhotoNote, "click", openPhotoPicker); on(el.btnVideoNote, "click", openVideoPicker); on(el.btnJournal, "click", openJournalSheet); on(el.homeCheckin, "click", function () { goRead(); setTimeout(function () { postCheckinNote(); }, 400); }); on(el.homeJournal, "click", function () { goRead(); setTimeout(function () { openJournalSheet(); }, 400); }); on(el.homeWorks, "click", function () { goRead(); setTimeout(function () { openWorksPanel(); }, 400); }); on(el.btnClipNote, "click", clipChapter); on(el.btnClipsShare, "click", shareAllClipsNote); on(el.btnClipsAlbum, "click", saveAllClipsAlbum); on(el.btnMultiShare, "click", multiShareNote); on(el.inputPhoto, "change", onPhotoPicked); on(el.inputVideo, "change", onVideoPicked); on(el.btnCamSnap, "click", snapCam); on(el.btnCamPost, "click", postCamShot); on(el.btnCamAlbum, "click", saveCamAlbum); on(el.btnCamClose, "click", closeCam); on(el.btnJournalSave, "click", function () { saveJournalEntry(false); }); on(el.btnJournalPost, "click", function () { saveJournalEntry(true); }); on(el.btnJournalClose, "click", closeJournalSheet); on(el.journalMask, "click", function (ev) { if (ev.target === el.journalMask) closeJournalSheet(); }); on(el.btnClearData, "click", clearLocalData); on(el.btnBackHome, "click", goHome); on(el.tabChapters, "click", function () { setDrawerTab("chapters"); }); on(el.tabBookmarks, "click", function () { setDrawerTab("bookmarks"); }); on(el.tabNotes, "click", function () { setDrawerTab("notes"); }); on(el.tabJournal, "click", function () { setDrawerTab("journal"); }); on(el.tabWorks, "click", function () { setDrawerTab("works"); }); on(el.tocFilter, "input", function () { renderToc(el.tocFilter.value); }); on(el.tocList, "click", function (ev) { var node = ev.target; while (node && node !== el.tocList) { var wAct = node.getAttribute && node.getAttribute("data-work-act"); if (wAct) { var wid = node.getAttribute("data-work-id"); var work = findWork(wid); if (wAct === "share") shareWorkItem(work); else if (wAct === "album") saveWorkAlbum(work); else if (wAct === "del") deleteWorkItem(wid); return; } var jAct = node.getAttribute && node.getAttribute("data-journal-act"); if (jAct) { var jid = node.getAttribute("data-journal-id"); if (jAct === "share") shareJournalEntry(findJournal(jid)); else if (jAct === "del") deleteJournalEntry(jid); return; } var act = node.getAttribute && node.getAttribute("data-note-act"); if (act) { var nid = node.getAttribute("data-note-id"); var note = findNote(nid); if (act === "share") shareNoteItem(note); else if (act === "album") saveNoteToAlbum(note); else if (act === "comment") commentNoteItem(note); else if (act === "del") deleteNoteItem(nid); return; } if (node.classList && node.classList.contains("drawer-item")) { var idx = Number(node.getAttribute("data-idx") || 0); openToc(false); jumpToChapter(idx); return; } node = node.parentNode; } }); on(el.paper, "click", function (ev) { var node = ev.target; while (node && node !== el.paper) { if (node.getAttribute && node.getAttribute("data-fin") === "share") { postFinishNote(); return; } if (node.getAttribute && node.getAttribute("data-fin") === "restart") { jumpToChapter(0); return; } if (node.getAttribute && node.getAttribute("data-fin") === "home") { goHome(); return; } if (node.classList && node.classList.contains("next-peek")) { var idx = Number(node.getAttribute("data-next-idx") || 0); jumpToChapter(idx); return; } node = node.parentNode; } handleReaderTap(ev); }); var touchStart = null; on(el.paper, "touchstart", function (ev) { var t = ev.touches && ev.touches[0]; if (!t) return; touchStart = { x: t.clientX, y: t.clientY, t: Date.now() }; }); on(el.paper, "touchend", function (ev) { if (!touchStart) return; var t = ev.changedTouches && ev.changedTouches[0]; if (!t) { touchStart = null; return; } var dx = Math.abs(t.clientX - touchStart.x); var dy = Math.abs(t.clientY - touchStart.y); var dt = Date.now() - touchStart.t; touchStart = null; if (dx > 12 || dy > 12 || dt > 450) return; // synthetic path already handled by click on most WebViews }); on(window, "scroll", function () { if (el.reader && (!el.reader.classList || !el.reader.classList.contains("is-hidden"))) { updateProgressUI(); } }); } function setChromeHidden(hidden) { state.chromeHidden = !!hidden; if (!el.reader) return; if (hidden) { if (el.reader.classList) el.reader.classList.add("chrome-hidden"); else el.reader.className += " chrome-hidden"; } else { if (el.reader.classList) el.reader.classList.remove("chrome-hidden"); else el.reader.className = String(el.reader.className || "").replace( /\bchrome-hidden\b/g, "" ); } } function handleReaderTap(ev) { if (!ev) return; var node = ev.target; while (node && node !== el.paper) { if ( node.tagName === "BUTTON" || node.tagName === "A" || (node.classList && (node.classList.contains("next-peek") || node.classList.contains("fin-btn"))) ) { return; } node = node.parentNode; } var x = ev.clientX; if (typeof x !== "number") return; var w = window.innerWidth || 360; var zone = w / 3; if (x < zone) { scrollToY((window.pageYOffset || 0) - Math.round((window.innerHeight || 600) * 0.85)); setTimeout(updateProgressUI, 40); } else if (x > w - zone) { scrollToY((window.pageYOffset || 0) + Math.round((window.innerHeight || 600) * 0.85)); setTimeout(updateProgressUI, 40); } else { setChromeHidden(!state.chromeHidden); } } function findChapterIndex(chapterId) { var chapters = (state.book && state.book.chapters) || []; for (var i = 0; i < chapters.length; i++) { if (chapters[i].id === chapterId) return i; } return -1; } function applySnapshot(snap) { if (!snap || snap.page !== "reader") return false; if (snap.bookId && state.book && snap.bookId !== state.book.id) return false; var idx = typeof snap.chapterIndex === "number" ? snap.chapterIndex : findChapterIndex(snap.chapterId); if (idx < 0) idx = 0; state.activeChapter = idx; var pct = Number(snap.scrollPercent) || 0; getProgress(state.book.id).then(function (progress) { state.progress = progress || { bookId: state.book.id, chapterId: snap.chapterId, chapterIndex: idx, scrollPercent: pct }; if (!progress && snap.chapterId) { state.progress.chapterId = snap.chapterId; state.progress.scrollPercent = pct; } else if (progress && pct > 0) { state.progress.scrollPercent = pct; state.progress.chapterId = snap.chapterId || progress.chapterId; state.progress.chapterIndex = idx; } renderReader(true); refreshPrefSegs(); syncActionLabels(); }); return true; } function boot() { try { if (!Bridge) { if ($("boot-text")) $("boot-text").textContent = "桥接模块未加载"; return; } collectEls(); applySafeArea(); if (!el.boot || !el.home || !el.btnStart) { if (el.bootText) el.bootText.textContent = "页面结构异常"; return; } var book = getBookData(); if (!book) { showBootError("内容未加载"); return; } if (!window.MarkdownLite) { showBootError("渲染模块未加载"); return; } state.book = book; Bridge.getBuildVersion() .then(function (v) { state.buildVersion = v || 0; return Promise.all([ loadPrefs(), loadBookmarks(), loadNotes(), loadJournal(), loadStreak(), loadReadTime(), loadWorks(), Bridge.getLaunchOptions() ]); }) .then(function (tuple) { state.prefs = tuple[0] || copyObj(DEFAULT_PREFS); bind(); refreshStorageCap(); var snap = Bridge.readSnapshotInfo(tuple[7]); if (snap && applySnapshot(snap)) { startReadTimer(); return; } renderHome(); }) .catch(function (err) { showBootError("启动错误: " + (err && err.message ? err.message : String(err))); }); } catch (err) { var msg = err && err.message ? err.message : String(err); showBootError("启动错误: " + msg); } } if (document.readyState === "loading") { on(document, "DOMContentLoaded", boot); } else { boot(); } })();