feat: add thoughts detail page, tab navigation, vertical ranking, back-to-top

1. Thoughts detail page: standalone full-page view replacing modal,
   classifies content into 3 categories (highlights/book reviews/thoughts)
   with filter tabs, visual badges, and chapter grouping
2. Tab navigation: sections converted from vertical scroll to horizontal
   tab switching with lazy-loaded charts
3. Reading ranking: changed from card grid to vertical list with smaller
   covers matching shelf size, gold/silver/bronze rank badges
4. Back-to-top button: floating button appears after scrolling 400px
5. Book detail modal: added 'View Thoughts' button to navigate to
   thoughts page
This commit is contained in:
admin committed 2026-07-17 11:30:24 +08:00
1 parent 4d8cc2a2d7
commit 7c918140b3
3 files changed
+840 -471

No files matched your search

+309 -300
View File
@@ -4,18 +4,10 @@ const API_BASE = "";
// ===== 主题管理 =====
/**
* 获取当前主题。
* @returns {"light"|"dark"}
*/
function getCurrentTheme() {
return document.documentElement.getAttribute("data-theme") === "dark" ? "dark" : "light";
}
/**
* 切换明亮/黑暗主题。
* 持久化到 localStorage,并触发图表重绘。
*/
function toggleTheme() {
const newTheme = getCurrentTheme() === "dark" ? "light" : "dark";
document.documentElement.setAttribute("data-theme", newTheme);
@@ -23,9 +15,6 @@ function toggleTheme() {
refreshChartsForTheme();
}
/**
* 从 CSS 变量读取当前主题的颜色值,供 ECharts 使用。
*/
function getChartColors() {
const cs = getComputedStyle(document.documentElement);
return {
@@ -45,13 +34,6 @@ function getChartColors() {
// ===== 工具函数 =====
/**
* 升级微信读书封面图 URL 到高清晰度版本。
* 微信读书 CDN 的封面图通过文件名前缀区分分辨率:
* t6_ = 低清缩略图(~150px,Retina 屏模糊)
* t8_ = 高清版(~500px,适合 2x/3x 屏幕)
* 如果 URL 不含 t6_ 前缀或已是高清则原样返回。
*/
function hdCover(url) {
if (!url) return "";
return url.replace("/t6_", "/t8_");
@@ -68,55 +50,47 @@ function formatHours(seconds) {
return (seconds / 3600).toFixed(1);
}
function escapeHtml(text) {
if (!text) return "";
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
// ===== 数据库健康检查 =====
// 存储所有 ECharts 实例,用于主题切换时重绘
const chartInstances = {};
let chartsLoaded = false;
let currentThoughtsData = null;
/**
* 主题切换后重绘所有 ECharts 图表。
*/
function refreshChartsForTheme() {
if (!chartsLoaded) return;
Object.values(chartInstances).forEach((chart) => {
if (chart && !chart.isDisposed()) {
chart.dispose();
}
if (chart && !chart.isDisposed()) chart.dispose();
});
// 重新加载所有图表
loadYearlyTrend();
loadTimeDistribution();
loadCategories();
loadAuthors();
}
/**
* 页面加载时检查 MySQL 数据库连接状态。
* 如果连接失败,显示告警横幅并阻止后续数据加载。
*/
async function checkDBHealth() {
try {
const resp = await fetch(API_BASE + "/api/health");
const data = await resp.json();
if (resp.ok && data.database === "connected") {
// 数据库连接正常,隐藏告警横幅
document.getElementById("dbAlertBanner").style.display = "none";
return true;
} else {
// 数据库连接异常,显示告警横幅
showDBAlert(data.message || "数据库连接失败");
return false;
}
} catch (error) {
// 健康检查接口本身无法访问
showDBAlert("无法连接到服务器,请检查后端服务是否运行。");
return false;
}
}
/**
* 显示数据库连接告警横幅。
* @param {string} message - 告警详情信息
*/
function showDBAlert(message) {
const banner = document.getElementById("dbAlertBanner");
const detail = document.getElementById("dbAlertDetail");
@@ -124,61 +98,78 @@ function showDBAlert(message) {
if (detail) detail.textContent = message;
}
// ===== 初始化 =====
document.addEventListener("DOMContentLoaded", async () => {
// 首先检查数据库连接状态
const isHealthy = await checkDBHealth();
if (!isHealthy) {
// 数据库连接失败,不加载后续数据
return;
// ===== 标签页切换 =====
function switchTab(tabName) {
document.querySelectorAll(".tab-panel").forEach((panel) => {
panel.classList.remove("active");
});
document.querySelectorAll(".nav-link").forEach((link) => {
link.classList.toggle("active", link.dataset.tab === tabName);
});
const target = document.getElementById(`tab-${tabName}`);
if (target) {
target.classList.add("active");
}
// 数据库连接正常,加载所有数据模块
window.scrollTo({ top: 0, behavior: "smooth" });
// 懒加载图表
if (tabName === "charts" && !chartsLoaded) {
chartsLoaded = true;
loadYearlyTrend();
loadTimeDistribution();
loadCategories();
loadAuthors();
}
// 切换到图表时重绘尺寸
if (tabName === "charts" && chartsLoaded) {
setTimeout(() => {
Object.values(chartInstances).forEach((chart) => {
if (chart && !chart.isDisposed()) chart.resize();
});
}, 100);
}
}
// ===== 回到顶部按钮 =====
function initBackToTop() {
const btn = document.getElementById("backToTop");
window.addEventListener("scroll", () => {
btn.classList.toggle("visible", window.scrollY > 400);
});
}
function scrollToTop() {
window.scrollTo({ top: 0, behavior: "smooth" });
}
// ===== 初始化 =====
document.addEventListener("DOMContentLoaded", async () => {
const isHealthy = await checkDBHealth();
if (!isHealthy) return;
loadOverview();
loadYearlyTrend();
loadTimeDistribution();
loadCategories();
loadAuthors();
loadTopBooks();
loadShelf(1);
loadNotebooks();
loadRecommend(0);
initNavScroll();
initBackToTop();
// 搜索和筛选事件
document.getElementById("shelfSearch").addEventListener("input", debounce(() => loadShelf(1), 300));
document.getElementById("finishedOnly").addEventListener("change", () => loadShelf(1));
});
// ===== 导航栏滚动高亮 =====
function initNavScroll() {
const links = document.querySelectorAll(".nav-link");
const sections = document.querySelectorAll("section[id]");
window.addEventListener("scroll", () => {
let current = "";
sections.forEach((sec) => {
const top = sec.offsetTop - 100;
if (window.scrollY >= top) current = sec.id;
});
links.forEach((link) => {
link.classList.toggle("active", link.getAttribute("href") === `#${current}`);
});
});
links.forEach((link) => {
link.addEventListener("click", (e) => {
e.preventDefault();
const target = document.querySelector(link.getAttribute("href"));
if (target) {
window.scrollTo({ top: target.offsetTop - 60, behavior: "smooth" });
}
});
});
}
// ===== 总览数据 =====
async function loadOverview() {
try {
const data = await fetchAPI("/api/overview");
// Hero 统计
const heroStats = document.getElementById("heroStats");
heroStats.innerHTML = `
<div class="hero-stat">
@@ -202,7 +193,6 @@ async function loadOverview() {
document.getElementById("heroSubtitle").textContent =
`自 ${data.regist_time} 加入微信读书,已陪伴你 ${data.read_days} 个阅读的日子`;
// 统计卡片
const statsGrid = document.getElementById("statsGrid");
statsGrid.innerHTML = `
<div class="stat-card">
@@ -231,7 +221,6 @@ async function loadOverview() {
</div>
`;
// 更新时间
const timeStr = `数据更新: ${data.fetch_time}`;
document.getElementById("fetchTime").textContent = timeStr;
document.getElementById("footerTime").textContent = data.fetch_time;
@@ -278,31 +267,20 @@ async function loadYearlyTrend() {
axisLabel: { color: c.axis },
splitLine: { lineStyle: { color: c.splitLine } },
},
series: [
{
data: hours,
type: "bar",
barWidth: "50%",
itemStyle: {
borderRadius: [8, 8, 0, 0],
color: {
type: "linear",
x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: c.accentLight },
{ offset: 1, color: c.accent },
],
},
},
label: {
show: true,
position: "top",
color: c.label,
fontSize: 12,
formatter: "{c}h",
},
series: [{
data: hours,
type: "bar",
barWidth: "50%",
itemStyle: {
borderRadius: [8, 8, 0, 0],
color: { type: "linear", x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: c.accentLight },
{ offset: 1, color: c.accent },
] },
},
],
label: { show: true, position: "top", color: c.label, fontSize: 12, formatter: "{c}h" },
}],
});
window.addEventListener("resize", () => chart.resize());
} catch (e) {
@@ -338,11 +316,7 @@ async function loadTimeDistribution() {
xAxis: {
type: "category",
data: hours,
axisLabel: {
color: c.axis,
fontSize: 10,
interval: 2,
},
axisLabel: { color: c.axis, fontSize: 10, interval: 2 },
axisLine: { lineStyle: { color: c.axisLine } },
},
yAxis: {
@@ -352,27 +326,22 @@ async function loadTimeDistribution() {
axisLabel: { color: c.axis },
splitLine: { lineStyle: { color: c.splitLine } },
},
series: [
{
data: minutes,
type: "line",
smooth: true,
symbol: "circle",
symbolSize: 4,
lineStyle: { width: 2, color: c.accent },
itemStyle: { color: c.accent },
areaStyle: {
color: {
type: "linear",
x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: c.accent + "4D" },
{ offset: 1, color: c.accent + "05" },
],
},
},
series: [{
data: minutes,
type: "line",
smooth: true,
symbol: "circle",
symbolSize: 4,
lineStyle: { width: 2, color: c.accent },
itemStyle: { color: c.accent },
areaStyle: {
color: { type: "linear", x: 0, y: 0, x2: 0, y2: 1,
colorStops: [
{ offset: 0, color: c.accent + "4D" },
{ offset: 1, color: c.accent + "05" },
] },
},
],
}],
});
window.addEventListener("resize", () => chart.resize());
} catch (e) {
@@ -414,33 +383,19 @@ async function loadCategories() {
bottom: 20,
textStyle: { color: c.label, fontSize: 11 },
},
series: [
{
type: "pie",
radius: ["40%", "70%"],
center: ["35%", "50%"],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 6,
borderColor: c.borderColor,
borderWidth: 2,
},
label: { show: false },
emphasis: {
label: {
show: true,
fontSize: 14,
fontWeight: "bold",
color: c.tooltipText,
},
},
data: items,
color: [
"#c17b4a", "#e8a87c", "#d4a574", "#b8860b",
"#cd853f", "#daa520", "#bc8f8f", "#bdb76b",
],
series: [{
type: "pie",
radius: ["40%", "70%"],
center: ["35%", "50%"],
avoidLabelOverlap: false,
itemStyle: { borderRadius: 6, borderColor: c.borderColor, borderWidth: 2 },
label: { show: false },
emphasis: {
label: { show: true, fontSize: 14, fontWeight: "bold", color: c.tooltipText },
},
],
data: items,
color: ["#c17b4a", "#e8a87c", "#d4a574", "#b8860b", "#cd853f", "#daa520", "#bc8f8f", "#bdb76b"],
}],
});
window.addEventListener("resize", () => chart.resize());
} catch (e) {
@@ -486,31 +441,20 @@ async function loadAuthors() {
axisLabel: { color: c.axis, fontSize: 12 },
axisLine: { lineStyle: { color: c.axisLine } },
},
series: [
{
type: "bar",
data: counts.reverse(),
barWidth: "50%",
itemStyle: {
borderRadius: [0, 6, 6, 0],
color: {
type: "linear",
x: 0, y: 0, x2: 1, y2: 0,
colorStops: [
{ offset: 0, color: c.accentLight },
{ offset: 1, color: c.accent },
],
},
},
label: {
show: true,
position: "right",
color: c.label,
fontSize: 12,
formatter: "{c}本",
},
series: [{
type: "bar",
data: counts.reverse(),
barWidth: "50%",
itemStyle: {
borderRadius: [0, 6, 6, 0],
color: { type: "linear", x: 0, y: 0, x2: 1, y2: 0,
colorStops: [
{ offset: 0, color: c.accentLight },
{ offset: 1, color: c.accent },
] },
},
],
label: { show: true, position: "right", color: c.label, fontSize: 12, formatter: "{c}本" },
}],
});
window.addEventListener("resize", () => chart.resize());
} catch (e) {
@@ -518,31 +462,31 @@ async function loadAuthors() {
}
}
// ===== 读书排行 =====
// ===== 读书排行(竖向列表) =====
async function loadTopBooks() {
try {
const data = await fetchAPI("/api/top-books");
const grid = document.getElementById("topBooksGrid");
const list = document.getElementById("topBooksGrid");
grid.innerHTML = data
list.innerHTML = data
.map((book, i) => {
const tagsHtml = book.tags
.map((t) => `<span class="top-book-tag">${t}</span>`)
.join("");
return `
<div class="top-book-card" onclick="openBook('${book.book_id}')">
<div class="top-book-cover-wrapper">
<span class="top-book-rank">${i + 1}</span>
<img class="top-book-cover" src="${hdCover(book.cover)}" alt="${book.title}"
loading="lazy"
onerror="this.onerror=null;this.src='${book.cover}';this.onerror=function(){this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22120%22 height=%22160%22%3E%3Crect fill=%22%23e8e0d4%22 width=%22120%22 height=%22160%22/%3E%3Ctext x=%2260%22 y=%2280%22 text-anchor=%22middle%22 fill=%22%239b8e80%22 font-size=%2214%22%3E无封面%3C/text%3E%3C/svg%3E'}">
</div>
<div class="top-book-info">
<div class="top-book-title">${book.title}</div>
<div class="top-book-author">${book.author}</div>
<div class="top-book-time">⏱ ${book.read_time_str}</div>
${tagsHtml ? `<div class="top-book-tags">${tagsHtml}</div>` : ""}
<div class="top-book-row" onclick="openBook('${book.book_id}')">
<span class="top-book-rank-num">${i + 1}</span>
<img class="top-book-mini-cover" src="${hdCover(book.cover)}" alt="${book.title}"
loading="lazy"
onerror="this.onerror=null;this.src='${book.cover}';this.onerror=function(){this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2248%22 height=%2264%22%3E%3Crect fill=%22%23e8e0d4%22 width=%2248%22 height=%2264%22/%3E%3C/svg%3E'}">
<div class="top-book-row-info">
<div class="top-book-row-title">${book.title}</div>
<div class="top-book-row-meta">
<span>${book.author}</span>
${tagsHtml ? `<div class="top-book-row-tags">${tagsHtml}</div>` : ""}
</div>
</div>
<div class="top-book-row-time">⏱ ${book.read_time_str}</div>
</div>`;
})
.join("");
@@ -558,12 +502,7 @@ async function loadShelf(page) {
shelfCurrentPage = page;
const search = document.getElementById("shelfSearch").value;
const finished = document.getElementById("finishedOnly").checked ? "1" : "0";
const params = new URLSearchParams({
page: page,
per_page: 60,
category: search,
finished: finished,
});
const params = new URLSearchParams({ page: page, per_page: 60, category: search, finished: finished });
try {
const data = await fetchAPI(`/api/shelf?${params}`);
@@ -591,7 +530,6 @@ async function loadShelf(page) {
})
.join("");
// 分页
renderPagination(page, data.total_pages);
} catch (e) {
console.error("加载书架失败:", e);
@@ -600,13 +538,9 @@ async function loadShelf(page) {
function renderPagination(current, total) {
const pag = document.getElementById("pagination");
if (total <= 1) {
pag.innerHTML = "";
return;
}
if (total <= 1) { pag.innerHTML = ""; return; }
let html = `<button class="page-btn" ${current <= 1 ? "disabled" : ""} onclick="loadShelf(${current - 1})">上一页</button>`;
const maxButtons = 7;
let start = Math.max(1, current - 3);
let end = Math.min(total, start + maxButtons - 1);
@@ -616,31 +550,20 @@ function renderPagination(current, total) {
html += `<button class="page-btn" onclick="loadShelf(1)">1</button>`;
if (start > 2) html += `<span class="page-info">...</span>`;
}
for (let i = start; i <= end; i++) {
html += `<button class="page-btn ${i === current ? "active" : ""}" onclick="loadShelf(${i})">${i}</button>`;
}
if (end < total) {
if (end < total - 1) html += `<span class="page-info">...</span>`;
html += `<button class="page-btn" onclick="loadShelf(${total})">${total}</button>`;
}
html += `<button class="page-btn" ${current >= total ? "disabled" : ""} onclick="loadShelf(${current + 1})">下一页</button>`;
pag.innerHTML = html;
}
// 搜索和筛选事件
document.getElementById("shelfSearch").addEventListener("input", debounce(() => loadShelf(1), 300));
document.getElementById("finishedOnly").addEventListener("change", () => loadShelf(1));
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); };
}
// ===== 笔记概览 =====
@@ -677,7 +600,7 @@ async function loadNotebooks() {
.map((nb) => {
const progress = nb.reading_progress || 0;
return `
<div class="notebook-card" onclick="openNotes('${nb.book_id}', '${nb.title.replace(/'/g, "\\'")}', '${(nb.author || '').replace(/'/g, "\\'")}', '${nb.cover}')" style="cursor:pointer">
<div class="notebook-card" onclick="openThoughtsPage('${nb.book_id}', '${nb.title.replace(/'/g, "\\'")}', '${(nb.author || '').replace(/'/g, "\\'")}', '${nb.cover}')" style="cursor:pointer">
<img class="notebook-cover" src="${hdCover(nb.cover)}" alt="${nb.title}"
loading="lazy"
onerror="this.onerror=null;this.src='${nb.cover}';this.onerror=function(){this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2260%22 height=%2280%22%3E%3Crect fill=%22%23e8e0d4%22 width=%2260%22 height=%2280%22/%3E%3C/svg%3E'}">
@@ -701,7 +624,7 @@ async function loadNotebooks() {
}
}
// ===== 打开书籍详情弹窗 =====
// ===== 书籍详情弹窗 =====
function openBook(bookId) {
if (!bookId) return;
showModal("bookDetailModal");
@@ -726,12 +649,12 @@ function openBook(bookId) {
<div class="detail-title">${data.title}</div>
<div class="detail-author">${data.author || ''}${data.translator ? ' / 译: ' + data.translator : ''}</div>
<div class="detail-tags">${tags.map(t => `<span class="detail-tag">${t}</span>`).join('')}</div>
${progress.is_start_reading ? `
${p.is_start_reading ? `
<div class="detail-progress-info">
<div style="font-size:13px;color:var(--text-secondary)">
阅读进度: <strong>${progress.progress}%</strong>
${progress.record_reading_time_str ? ' · 累计 ' + progress.record_reading_time_str : ''}
${progress.finish_time ? ' · 读完于 ' + progress.finish_time : ''}
阅读进度: <strong>${p.progress}%</strong>
${p.record_reading_time_str ? ' · 累计 ' + p.record_reading_time_str : ''}
${p.finish_time ? ' · 读完于 ' + p.finish_time : ''}
</div>
<div class="detail-progress-bar">
<div class="detail-progress-fill" style="width:${progress}%"></div>
@@ -748,6 +671,7 @@ function openBook(bookId) {
</div>
<div class="detail-actions">
<button class="btn-primary" onclick="window.open('weread://reading?bId=${bookId}','_blank')">在微信读书中打开</button>
<button class="btn-primary detail-action-thoughts" onclick="closeModal('bookDetailModal');openThoughtsPage('${bookId}', '${(data.title || '').replace(/'/g, "\\'")}', '${(data.author || '').replace(/'/g, "\\'")}', '${data.cover || ''}')">📖 查看想法</button>
</div>
`;
})
@@ -756,88 +680,180 @@ function openBook(bookId) {
});
}
// ===== 打开笔记详情弹窗 =====
function openNotes(bookId, title, author, cover) {
// ===== 想法详情独立页面 =====
function openThoughtsPage(bookId, title, author, cover) {
if (!bookId) return;
showModal("notesDetailModal");
const body = document.getElementById("notesDetailBody");
body.innerHTML = `
<div class="notes-header">
<img class="notes-cover" src="${hdCover(cover || '')}" alt="${title}"
onerror="this.onerror=null;this.src='${cover || ''}';this.onerror=function(){this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2260%22 height=%2280%22%3E%3Crect fill=%22%23e8e0d4%22 width=%2260%22 height=%2280%22/%3E%3C/svg%3E'}">
<div>
<div class="notes-title">${title}</div>
<div class="notes-author">${author || ''}</div>
</div>
// 隐藏主视图,显示想法页面
document.getElementById("mainView").style.display = "none";
document.getElementById("thoughtsPage").style.display = "block";
window.scrollTo({ top: 0, behavior: "auto" });
// 渲染头部
const header = document.getElementById("thoughtsBookHeader");
header.innerHTML = `
<img class="thoughts-book-cover" src="${hdCover(cover || '')}" alt="${title}"
onerror="this.onerror=null;this.src='${cover || ''}';this.onerror=function(){this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2264%22 height=%2285%22%3E%3Crect fill=%22%23e8e0d4%22 width=%2264%22 height=%2285%22/%3E%3C/svg%3E'}">
<div>
<div class="thoughts-book-title">${title}</div>
<div class="thoughts-book-author">${author || ''}</div>
<div class="thoughts-book-stats" id="thoughtsBookStats">加载中...</div>
</div>
<div class="loading"><div class="loading-spinner"></div></div>
`;
const content = document.getElementById("thoughtsContent");
content.innerHTML = `<div class="loading"><div class="loading-spinner"></div></div>`;
fetchAPI(`/api/book/notes?book_id=${bookId}`)
.then((data) => {
let html = `
<div class="notes-header">
<img class="notes-cover" src="${hdCover(cover || '')}" alt="${title}"
onerror="this.onerror=null;this.src='${cover || ''}';this.onerror=function(){this.src='data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2260%22 height=%2280%22%3E%3Crect fill=%22%23e8e0d4%22 width=%2260%22 height=%2280%22/%3E%3C/svg%3E'}">
<div>
<div class="notes-title">${title}</div>
<div class="notes-author">${author || ''}</div>
<div class="notes-counts">
<span>划线 <strong>${data.highlight_count}</strong></span>
<span>想法/点评 <strong>${data.review_count}</strong></span>
</div>
</div>
</div>
`;
currentThoughtsData = data;
renderThoughtsPage(data);
})
.catch((e) => {
content.innerHTML = `<div class="thoughts-empty">加载失败: ${e.message}</div>`;
});
}
// 划线区
if (data.highlight_count > 0) {
html += `<div class="notes-section-title">📌 划线 (${data.highlight_count})</div>`;
const grouped = data.grouped_highlights;
for (const [chTitle, items] of Object.entries(grouped)) {
html += `<div class="chapter-group">`;
html += `<div class="chapter-title">${chTitle}</div>`;
items.forEach((h) => {
html += `
<div class="highlight-item">
${escapeHtml(h.mark_text)}
<div class="highlight-date">${h.create_time || ''}</div>
</div>
`;
});
html += `</div>`;
function closeThoughtsPage() {
document.getElementById("thoughtsPage").style.display = "none";
document.getElementById("mainView").style.display = "";
currentThoughtsData = null;
}
function renderThoughtsPage(data) {
// 更新统计
const stats = document.getElementById("thoughtsBookStats");
// 分类:划线 / 书评 / 想法
const highlights = data.highlights || [];
const bookReviews = (data.reviews || []).filter((r) => r.is_finish);
const thoughts = (data.reviews || []).filter((r) => !r.is_finish);
stats.innerHTML = `
<span>划线 <strong>${highlights.length}</strong></span>
<span>书评 <strong>${bookReviews.length}</strong></span>
<span>想法 <strong>${thoughts.length}</strong></span>
`;
const content = document.getElementById("thoughtsContent");
if (highlights.length === 0 && bookReviews.length === 0 && thoughts.length === 0) {
content.innerHTML = `<div class="thoughts-empty">暂无笔记数据</div>`;
return;
}
let html = `
<div class="thoughts-filters">
<button class="thought-filter-btn active" onclick="filterThoughts('all')">全部</button>
<button class="thought-filter-btn" onclick="filterThoughts('highlight')">
📌 划线 <span class="filter-count">${highlights.length}</span>
</button>
<button class="thought-filter-btn" onclick="filterThoughts('review')">
⭐ 书评 <span class="filter-count">${bookReviews.length}</span>
</button>
<button class="thought-filter-btn" onclick="filterThoughts('thought')">
💭 想法 <span class="filter-count">${thoughts.length}</span>
</button>
</div>
<div id="thoughtsList"></div>
`;
content.innerHTML = html;
renderThoughtsList("all");
}
function filterThoughts(category) {
document.querySelectorAll(".thought-filter-btn").forEach((btn) => {
btn.classList.remove("active");
});
event.target.closest(".thought-filter-btn").classList.add("active");
renderThoughtsList(category);
}
function renderThoughtsList(category) {
const data = currentThoughtsData;
if (!data) return;
const highlights = data.highlights || [];
const bookReviews = (data.reviews || []).filter((r) => r.is_finish);
const thoughts = (data.reviews || []).filter((r) => !r.is_finish);
const list = document.getElementById("thoughtsList");
let html = "";
// 划线区
if (category === "all" || category === "highlight") {
if (highlights.length > 0) {
html += `<div class="thoughts-section-title">📌 划线 <span class="section-badge badge-highlight">${highlights.length}</span></div>`;
const grouped = data.grouped_highlights || {};
for (const [chTitle, items] of Object.entries(grouped)) {
if (category === "highlight") {
html += `<div class="thoughts-chapter-group">`;
html += `<div class="thoughts-chapter-title">${chTitle}</div>`;
}
}
// 想法/点评区
if (data.review_count > 0) {
html += `<div class="notes-section-title">💭 想法/点评 (${data.review_count})</div>`;
data.reviews.forEach((r) => {
const starVal = Math.max(0, Math.min(5, parseInt(r.star) || 0));
const stars = starVal > 0 ? `<span class="review-star">${"★".repeat(starVal)}${"☆".repeat(5 - starVal)}</span>` : "";
items.forEach((h) => {
html += `
<div class="review-item">
${escapeHtml(r.content)}
<div class="review-meta">
${stars}
${r.chapter_name ? ' · ' + r.chapter_name : ''}
${r.is_finish ? ' · 书评' : ''}
· ${r.create_time || ''}
<div class="thought-highlight-item">
${escapeHtml(h.mark_text)}
<div class="thought-highlight-meta">
${h.chapter_title ? `<span>${h.chapter_title}</span>` : ""}
${h.create_time ? `<span>${h.create_time}</span>` : ""}
</div>
</div>
`;
});
if (category === "highlight") html += `</div>`;
}
}
}
if (data.highlight_count === 0 && data.review_count === 0) {
html += `<div class="empty-state">暂无笔记数据</div>`;
}
// 书评区
if (category === "all" || category === "review") {
if (bookReviews.length > 0) {
html += `<div class="thoughts-section-title">⭐ 书评 <span class="section-badge badge-review">${bookReviews.length}</span></div>`;
bookReviews.forEach((r) => {
const starVal = Math.max(0, Math.min(5, parseInt(r.star) || 0));
const stars = starVal > 0 ? `<div class="thought-review-stars">${"★".repeat(starVal)}${"☆".repeat(5 - starVal)}</div>` : "";
html += `
<div class="thought-review-item">
${stars}
${escapeHtml(r.content)}
<div class="thought-review-meta">
${r.chapter_name ? `<span>${r.chapter_name}</span>` : ""}
<span>${r.create_time || ""}</span>
</div>
</div>
`;
});
}
}
body.innerHTML = html;
})
.catch((e) => {
body.innerHTML = `<div class="empty-state">加载失败: ${e.message}</div>`;
});
// 想法区
if (category === "all" || category === "thought") {
if (thoughts.length > 0) {
html += `<div class="thoughts-section-title">💭 想法 <span class="section-badge badge-thought">${thoughts.length}</span></div>`;
thoughts.forEach((r) => {
const abstract = r.abstract ? `<div class="thought-thought-abstract">${escapeHtml(r.abstract)}</div>` : "";
html += `
<div class="thought-thought-item">
${abstract}
<div class="thought-thought-content">${escapeHtml(r.content)}</div>
<div class="thought-thought-meta">
${r.chapter_name ? `<span>${r.chapter_name}</span>` : ""}
<span>${r.create_time || ""}</span>
</div>
</div>
`;
});
}
}
if (!html) {
html = `<div class="thoughts-empty">该分类暂无内容</div>`;
}
list.innerHTML = html;
}
// ===== 弹窗控制 =====
@@ -851,22 +867,15 @@ function closeModal(id) {
document.body.style.overflow = "";
}
// ESC 关闭弹窗
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
closeModal("bookDetailModal");
closeModal("notesDetailModal");
if (document.getElementById("thoughtsPage").style.display !== "none") {
closeThoughtsPage();
}
}
});
// ===== HTML 转义 =====
function escapeHtml(text) {
if (!text) return "";
const div = document.createElement("div");
div.textContent = text;
return div.innerHTML;
}
// ===== 推荐发现 =====
let recommendMaxIdx = 0;