-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathbook.html
More file actions
347 lines (313 loc) · 14.6 KB
/
book.html
File metadata and controls
347 lines (313 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>作品详情</title>
<meta name="description" content="">
<!-- P3修复:DNS预解析和预连接 -->
<link rel="preconnect" href="https://github.com" crossorigin>
<link rel="dns-prefetch" href="https://github.com">
<link rel="stylesheet" href="/style.css">
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#d4a574">
</head>
<body>
<div class="navbar">
<h1><a href="/">📚 我的书架</a></h1>
<nav>
<a href="https://github.com/xingzihai/novel-site" target="_blank" rel="noopener" title="GitHub">GitHub</a>
<a href="/admin.html">管理</a>
<button class="theme-toggle" onclick="toggleTheme()" title="切换主题">🌙</button>
</nav>
</div>
<div class="container">
<div class="breadcrumb"><a href="/">书架</a><span>›</span><span id="bc-title">加载中...</span></div>
<div id="content" class="loading">加载中...</div>
</div>
<script>
const THEMES = ['light','dark','green','sepia','blue'];
const THEME_ICONS = {'light':'🌙','dark':'☀️','green':'🍃','sepia':'📜','blue':'💧'};
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
updateThemeBtn();
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
const idx = THEMES.indexOf(current);
const next = THEMES[(idx + 1) % THEMES.length];
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
updateThemeBtn();
}
function updateThemeBtn() {
const btn = document.querySelector('.theme-toggle');
const t = document.documentElement.getAttribute('data-theme');
btn.textContent = THEME_ICONS[t] || '🌙';
}
const bookId = new URLSearchParams(location.search).get('id');
let allChapters = [];
if (!bookId || !/^\d+$/.test(bookId)) {
document.getElementById('content').innerHTML = '<div class="msg msg-error">无效的书籍ID</div>';
} else {
loadBook();
}
// 加载站点设置
fetch('/api/settings').then(r => r.json()).then(d => {
const s = d.settings || {};
if (s.site_name) document.querySelector('.navbar h1 a').textContent = '📚 ' + s.site_name;
}).catch(() => {});
// PWA Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').catch(() => {});
}
async function loadBook() {
const el = document.getElementById('content');
try {
const res = await fetch(`/api/books/${bookId}`);
if (!res.ok) throw new Error(res.status === 404 ? '书籍不存在' : '加载失败');
const data = await res.json();
const b = data.book;
const chapters = data.chapters || [];
allChapters = chapters;
document.title = esc(b.title) + ' - 我的书架';
document.querySelector('meta[name="description"]').content = b.description || b.title;
document.getElementById('bc-title').textContent = b.title;
const tagsHtml = (b.tags || []).map(t => `<span class="tag-pill" style="background:${esc(t.color)}22;color:${esc(t.color)}">${esc(t.name)}</span>`).join('');
const tagsBlock = tagsHtml ? `<div class="book-tags">${tagsHtml}</div>` : '';
const uploaderHtml = b.uploader ? `<div class="uploader" style="font-size:13px;color:var(--text-light);margin-top:4px">${b.uploader_avatar ? '<img src="'+esc(b.uploader_avatar)+'" style="width:16px;height:16px;border-radius:50%;vertical-align:middle;margin-right:3px">' : ''}上传:${esc(b.uploader)}</div>` : '';
let html;
if (b.cover_key) {
html = `
<div class="book-header">
<div class="book-header-with-cover">
<img class="book-cover-img" src="/api/covers/${b.id}" alt="${esc(b.title)}">
<div class="book-info">
<h2>${esc(b.title)}</h2>
${b.author ? `<div class="author">作者:${esc(b.author)}</div>` : ''}
${uploaderHtml}
${b.description ? `<div class="desc">${cleanDesc(b.description)}</div>` : ''}
${tagsBlock}
</div>
</div>
</div>
`;
} else {
html = `
<div class="book-header">
<h2>${esc(b.title)}</h2>
${b.author ? `<div class="author">作者:${esc(b.author)}</div>` : ''}
${uploaderHtml}
${b.description ? `<div class="desc">${cleanDesc(b.description)}</div>` : ''}
${tagsBlock}
</div>
`;
}
if (chapters.length > 0) {
html += `<div class="search-bar" style="margin-top:16px;margin-bottom:0"><input type="text" id="chapter-search" placeholder="搜索章节标题..." autocomplete="off"><button onclick="filterChapters()">搜索</button></div>`;
}
if (chapters.length === 0) {
html += '<div class="empty"><p>暂无章节</p></div>';
} else {
// P2修复:大量章节时分页加载,每页50章
const CHAPTERS_PER_PAGE = 50;
const needsPagination = chapters.length > CHAPTERS_PER_PAGE;
html += '<ul class="chapter-list" id="chapter-list">';
// 首次只渲染第一页
const initialChapters = needsPagination ? chapters.slice(0, CHAPTERS_PER_PAGE) : chapters;
html += initialChapters.map(c => `
<li>
<a href="/read.html?id=${c.id}">
<span class="chapter-title">${esc(c.title)}</span>
<span class="chapter-meta">${c.word_count} 字</span>
</a>
</li>
`).join('');
html += '</ul>';
// 分页控制
if (needsPagination) {
const totalPages = Math.ceil(chapters.length / CHAPTERS_PER_PAGE);
html += `<div class="chapter-pagination" id="chapter-pagination" data-page="1" data-per-page="${CHAPTERS_PER_PAGE}" data-total="${chapters.length}">
<button id="ch-prev" disabled>上一页</button>
<span class="page-info">第 <span id="ch-current">1</span> / ${totalPages} 页(共 ${chapters.length} 章)</span>
<button id="ch-next">下一页</button>
</div>`;
}
html += `<div style="margin-top:20px;text-align:center"><a href="#" id="export-link" style="font-size:13px;color:var(--text-light);text-decoration:none;border-bottom:1px dashed var(--text-light);padding-bottom:1px">导出全书 TXT</a></div>`;
}
// 书签列表
const bookmarks = getBookmarks(bookId);
if (bookmarks.length > 0) {
html += `<div style="margin-top:24px"><h3 style="font-size:16px;margin-bottom:12px;color:var(--text)">🔖 我的书签(${bookmarks.length})</h3>`;
html += '<ul class="chapter-list">' + bookmarks.sort((a,b) => b.time - a.time).map(bm => `
<li>
<a href="/read.html?id=${bm.chapterId}">
<span class="chapter-title">${esc(bm.chapterTitle)}</span>
<span class="chapter-meta">${formatTimeAgo(bm.time)}</span>
</a>
</li>
`).join('') + '</ul></div>';
}
el.innerHTML = html;
// 安全绑定导出事件(避免onclick中拼接字符串)
const exportLink = document.getElementById('export-link');
if (exportLink) {
exportLink.addEventListener('click', (e) => { e.preventDefault(); exportBook(b.id, b.title, b.author); });
}
// P2修复:绑定章节分页事件
bindChapterPagination();
} catch (e) {
el.innerHTML = `<div class="msg msg-error">${esc(e.message)}</div>`;
}
}
function esc(s) { const d = document.createElement('div'); d.textContent = s || ''; return d.innerHTML; }
function cleanDesc(s) {
if (!s) return '';
if (!/<[a-z][\s\S]*>/i.test(s)) return esc(s);
const doc = new DOMParser().parseFromString('<body>' + s + '</body>', 'text/html').body;
const parts = [];
doc.querySelectorAll('p, div, li').forEach(b => { const t = b.textContent.trim(); if (t) parts.push(esc(t)); });
return parts.length > 0 ? parts.join('<br>') : esc(doc.textContent.trim());
}
function getBookmarks(bookId) {
try { return JSON.parse(localStorage.getItem(`bookmarks_${bookId}`)) || []; }
catch { return []; }
}
function formatTimeAgo(ts) {
const diff = Date.now() - ts;
const min = Math.floor(diff / 60000);
if (min < 1) return '刚刚';
if (min < 60) return min + '分钟前';
const hr = Math.floor(min / 60);
if (hr < 24) return hr + '小时前';
return Math.floor(hr / 24) + '天前';
}
function filterChapters() {
const input = document.getElementById('chapter-search');
if (!input) return;
const q = input.value.trim().toLowerCase();
const listEl = document.querySelector('.chapter-list');
if (!listEl) return;
const filtered = q ? allChapters.filter(c => c.title.toLowerCase().includes(q)) : allChapters;
if (filtered.length === 0) {
listEl.innerHTML = '<li style="padding:16px;text-align:center;color:var(--text-light)">没有匹配的章节</li>';
} else {
listEl.innerHTML = filtered.map(c => `
<li><a href="/read.html?id=${c.id}">
<span class="chapter-title">${highlightMatch(esc(c.title), q)}</span>
<span class="chapter-meta">${c.word_count} 字</span>
</a></li>
`).join('');
}
}
function highlightMatch(text, q) {
if (!q) return text;
const re = new RegExp(`(${q.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')})`, 'gi');
return text.replace(re, '<mark>$1</mark>');
}
// 绑定搜索事件(DOM加载后立即执行,避免竞态条件)
function bindSearchEvents() {
const searchInput = document.getElementById('chapter-search');
if (searchInput) {
searchInput.addEventListener('keydown', (e) => { if (e.key === 'Enter') filterChapters(); });
searchInput.addEventListener('input', (e) => { if (!e.target.value.trim()) filterChapters(); });
}
}
// 如果DOM已加载完成,立即绑定;否则等待DOMContentLoaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', bindSearchEvents);
} else {
bindSearchEvents();
}
// P2修复:章节分页控制
function bindChapterPagination() {
const pagination = document.getElementById('chapter-pagination');
if (!pagination) return;
const prevBtn = document.getElementById('ch-prev');
const nextBtn = document.getElementById('ch-next');
const currentSpan = document.getElementById('ch-current');
const perPage = parseInt(pagination.dataset.perPage);
const total = parseInt(pagination.dataset.total);
const totalPages = Math.ceil(total / perPage);
prevBtn.addEventListener('click', () => {
let page = parseInt(pagination.dataset.page);
if (page > 1) {
page--;
renderChapterPage(page, perPage, total, totalPages);
pagination.dataset.page = page;
currentSpan.textContent = page;
prevBtn.disabled = page === 1;
nextBtn.disabled = false;
}
});
nextBtn.addEventListener('click', () => {
let page = parseInt(pagination.dataset.page);
if (page < totalPages) {
page++;
renderChapterPage(page, perPage, total, totalPages);
pagination.dataset.page = page;
currentSpan.textContent = page;
nextBtn.disabled = page === totalPages;
prevBtn.disabled = false;
}
});
}
function renderChapterPage(page, perPage, total, totalPages) {
const listEl = document.getElementById('chapter-list');
if (!listEl) return;
const start = (page - 1) * perPage;
const end = Math.min(start + perPage, total);
const pageChapters = allChapters.slice(start, end);
listEl.innerHTML = pageChapters.map(c => `
<li><a href="/read.html?id=${c.id}">
<span class="chapter-title">${esc(c.title)}</span>
<span class="chapter-meta">${c.word_count} 字</span>
</a></li>
`).join('');
// 滚动到章节列表顶部
listEl.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
async function exportBook(bookId, title, author) {
try {
const res = await fetch(`/api/books/${bookId}`);
const data = await res.json();
const chapters = data.chapters || [];
if (chapters.length === 0) return alert('没有章节可导出');
// 使用流式处理避免大文件内存溢出
const CHUNK_SIZE = 100; // 每次处理的章节数
const sep = '\n\n' + '='.repeat(40) + '\n\n';
const header = `《${title}》\n${author ? '作者:'+author+'\n' : ''}\n`;
const BOM = '\uFEFF';
// 创建可写流
const chunks = [BOM + header];
let processedCount = 0;
// 分块处理章节,避免一次性加载所有内容到内存
for (let i = 0; i < chapters.length; i += CHUNK_SIZE) {
const batch = chapters.slice(i, i + CHUNK_SIZE);
const batchPromises = batch.map(async (ch) => {
const r = await fetch(`/api/chapters/${ch.id}`);
const d = await r.json();
return ch.title + '\n\n' + d.content;
});
const batchResults = await Promise.all(batchPromises);
// 添加分隔符
if (processedCount > 0) {
chunks.push(sep);
}
chunks.push(...batchResults);
processedCount += batchResults.length;
// 让出主线程,保持UI响应
await new Promise(resolve => setTimeout(resolve, 0));
}
// 使用 Blob 构造函数的分块模式,减少内存峰值
const blob = new Blob(chunks, {type:'text/plain;charset=utf-8'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = (title + (author ? '_'+author : '') + '.txt').replace(/[<>:"/\\|?*]/g,'_');
a.click();
URL.revokeObjectURL(url);
} catch (e) { alert('导出失败:'+e.message); }
}
</script>
</body>
</html>