@yyds-dudu/dsh-novel-reader 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -8
- package/client.js +1023 -111
- package/docs/SOURCES.md +90 -0
- package/docs/screenshot-online-reading.png +0 -0
- package/docs/screenshot-online-search.png +0 -0
- package/docs/screenshot-online-shelf.png +0 -0
- package/docs/screenshot-sources.png +0 -0
- package/index.js +197 -2
- package/lib/community-sources.js +2090 -0
- package/lib/html.js +52 -0
- package/lib/http.js +62 -0
- package/lib/legado.js +345 -0
- package/lib/sources/custom.js +76 -0
- package/lib/sources/daizhige.js +68 -0
- package/lib/sources/index.js +34 -0
- package/lib/sources/wikisource.js +244 -0
- package/locale/en.json +118 -33
- package/locale/zh.json +114 -29
- package/package.json +11 -2
package/client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
window.__ModuleLoader__.load({
|
|
2
|
-
id
|
|
2
|
+
// 与包名一致:加载器按 manifest 包名组织浏览器模块图,id 不一致会导致模块无法挂载。
|
|
3
|
+
id: '@yyds-dudu/dsh-novel-reader',
|
|
3
4
|
factory(require) {
|
|
4
5
|
const React = require('react');
|
|
5
6
|
const h = React.createElement;
|
|
@@ -9,6 +10,23 @@ window.__ModuleLoader__.load({
|
|
|
9
10
|
const STORE_KEY = NS + ':state';
|
|
10
11
|
const TEXT_KEY = NS + ':text'; // 全文单独存:大文件下翻页只写轻量元数据,避免每页重复序列化整本小说
|
|
11
12
|
const PROFILES_KEY = NS + ':profiles'; // 多套样式配置:{ 名称: style对象 }
|
|
13
|
+
const DB_NAME = 'dsh-novel-reader'; // IndexedDB:本地书架(元数据 + 正文)
|
|
14
|
+
const SOURCES_KEY = NS + ':sources'; // 用户自填书源,存 JSON 数组
|
|
15
|
+
const HIDDEN_KEY = NS + ':hidden-sources'; // 用户删除的社区书源 id,重启后仍生效
|
|
16
|
+
const MAX_BOOK_TEXT = 2000000; // 单本正文上限,防止异常页面撑爆本地存储
|
|
17
|
+
const BUILTIN_SOURCES = [
|
|
18
|
+
{ id: 'daizhige', name: '殆知阁(公版古典)' },
|
|
19
|
+
{ id: 'wikisource', name: '维基文库(自由授权)' },
|
|
20
|
+
];
|
|
21
|
+
// 自定义书源的示例模板:新手可以直接照着改
|
|
22
|
+
const SAMPLE_SOURCE = {
|
|
23
|
+
name: '示例站点',
|
|
24
|
+
search: {
|
|
25
|
+
url: 'https://example.com/search?q={q}&page={page}',
|
|
26
|
+
item: '<a href="(?<url>[^"]+)"[^>]*>(?<title>[^<]+)</a>',
|
|
27
|
+
},
|
|
28
|
+
book: { content: '<div class="content">(?<body>[\s\S]+?)</div>' },
|
|
29
|
+
};
|
|
12
30
|
|
|
13
31
|
// 给任意颜色套上透明度:alpha>=1 原样返回;支持 #rgb/#rrggbb 与 rgb()/rgba()
|
|
14
32
|
function withOpacity(color, alpha) {
|
|
@@ -73,6 +91,41 @@ window.__ModuleLoader__.load({
|
|
|
73
91
|
resizeHint: 'Drag the window edge to resize; changes are saved automatically',
|
|
74
92
|
reopenHint: 'Book data was cleared by the browser; please re-import the same file to resume.',
|
|
75
93
|
imported: 'Imported: {name} · {chapters} chapters',
|
|
94
|
+
searchTitle: 'Find books', searchPlaceholder: 'Title or keyword', searchButton: 'Search',
|
|
95
|
+
searching: 'Searching…', searchEmpty: 'Type a keyword and search. Built-in source is public-domain classics.',
|
|
96
|
+
searchNoResult: 'No results', manageSources: 'Sources', sourceLabel: 'Source', sourceDaizhige: 'Daizhige (public domain)', sourceWikisource: 'Wikisource (free license)',
|
|
97
|
+
shelfTitle: 'Bookshelf', shelfEmpty: 'No books yet. Search online or import a .txt.',
|
|
98
|
+
openBook: 'Open', download: 'Download txt', deleteBook: 'Delete', back: 'Back',
|
|
99
|
+
sourcesTitle: 'Custom sources', sourcesHint: 'JSON array. Each item: name, search.url ({q}, optional {page}), search.item regex with named groups url/title, book.content regex (optional named group body). Example below; save then pick it in Find books.',
|
|
100
|
+
sourcesSave: 'Save sources', sourcesSaved: 'Saved {count} custom source(s)', sourcesInvalid: 'Invalid JSON',
|
|
101
|
+
importBook: 'Import', importingBook: 'Downloading…', serverUnreachable: 'Cannot reach local service. Is the plugin host running?',
|
|
102
|
+
bookImported: 'Imported: {title}', bookTruncated: ' (text truncated)',
|
|
103
|
+
confirmDeleteBook: 'Delete "{title}"? The local text will be removed too.', currentReading: 'Reading',
|
|
104
|
+
healthRun: '🩺 Check', healthBusy: 'Checking…', healthProgress: 'Checking {done}/{total}',
|
|
105
|
+
healthDone: 'Checked: {ok}/{total} available',
|
|
106
|
+
stopLabel: '⏹ Stop', searchFrom: 'From: {name}', unknownSource: 'unknown source',
|
|
107
|
+
searchContinue: 'Search other sources →', searchContinueShort: 'Search again', searchStopped: 'Stopped',
|
|
108
|
+
searchProgress: 'Searching: {name} ({i}/{n})',
|
|
109
|
+
searchAllFailed: 'Tried {n} sources, none matched "{q}"', noSources: 'No available sources',
|
|
110
|
+
fetchingAll: 'Fetching all chapters and downloading txt… (delete the book in the shelf to abort)',
|
|
111
|
+
importedAndDownloaded: 'Imported and downloaded: {name}.txt',
|
|
112
|
+
importDownloadFailed: 'Added to shelf, but the automatic download failed: {msg}',
|
|
113
|
+
downloadedOk: 'Downloaded: {name}.txt', downloadFailed: 'Download failed: {msg}',
|
|
114
|
+
deletedDownloadStopped: 'Deleted; download stopped', deletedOne: 'Deleted', deleteFailed: 'Delete failed: {msg}',
|
|
115
|
+
downloadStopped: 'Download stopped', downloadingShelf: '⏳ Downloading',
|
|
116
|
+
sourcesManageTitle: 'Source management', sourceAdd: '+ New', sourceAddTitle: 'New source', sourceEditTitle: 'Edit source',
|
|
117
|
+
saveLabel: 'Save',
|
|
118
|
+
sourceEditorHint: 'Paste a Legado (reading3) source JSON (object or array). Rules only; @js:, <js>, java.* and XPath are rejected.',
|
|
119
|
+
sourcesSummary: 'Built-in {b} · Community {c} (✔{ok} OK) · Custom {n}',
|
|
120
|
+
sourcesBuiltinGroup: 'Built-in sources (read-only)', sourcesBuiltinTag: 'Licensed content',
|
|
121
|
+
sourcesCustomGroup: 'Custom sources (editable)',
|
|
122
|
+
sourcesCustomEmpty: 'No custom sources yet. Click “+ New” to add one.',
|
|
123
|
+
sourcesCommunityGroup: 'Community sources ({n}, disable or delete)',
|
|
124
|
+
sourceDisabledTag: ' · disabled', sourceDisable: 'Disable', sourceEnable: 'Enable',
|
|
125
|
+
editLabel: 'Edit', deleteLabel: 'Delete', sourceNameFallback: 'Source {n}',
|
|
126
|
+
sourceSaved: 'Saved {n} custom source(s)', sourceSaveFailed: 'Save failed: {msg}', sourceDeleted: 'Deleted: {name}',
|
|
127
|
+
confirmDeleteSource: 'Delete source "{name}"?', confirmDeleteCommunity: 'Delete community source "{name}"?',
|
|
128
|
+
loadingChapter: 'Loading this chapter…', reloadChapter: 'Reload chapter', onlineTag: ' · online', wordsWan: '0k words',
|
|
76
129
|
},
|
|
77
130
|
zh: {
|
|
78
131
|
name: '小说', import: '导入 txt', importing: '导入中…', settings: '设置', close: '收起',
|
|
@@ -106,6 +159,41 @@ window.__ModuleLoader__.load({
|
|
|
106
159
|
resizeHint: '拖动窗口边缘可调整大小,改动会自动保存',
|
|
107
160
|
reopenHint: '书籍正文已被浏览器清理,请重新导入同一文件继续阅读。',
|
|
108
161
|
imported: '已导入:{name} · 共 {chapters} 章',
|
|
162
|
+
searchTitle: '找书', searchPlaceholder: '书名或关键词', searchButton: '搜索',
|
|
163
|
+
searching: '搜索中…', searchEmpty: '输入关键词后搜索;内置源为公版古典文献。',
|
|
164
|
+
searchNoResult: '没有找到结果', manageSources: '书源', sourceLabel: '书源', sourceDaizhige: '殆知阁(公版古典)', sourceWikisource: '维基文库(自由授权)',
|
|
165
|
+
shelfTitle: '书架', shelfEmpty: '书架还是空的,去「找书」或导入一份 txt。',
|
|
166
|
+
openBook: '打开', download: '下载 txt', deleteBook: '删除', back: '返回',
|
|
167
|
+
sourcesTitle: '自定义书源', sourcesHint: 'JSON 数组,每项:name、search.url(含 {q},可选 {page})、search.item 正则需命名组 url/title、book.content 正则(可选命名组 body)。下面是示例,保存后在「找书」里选择。',
|
|
168
|
+
sourcesSave: '保存书源', sourcesSaved: '已保存 {count} 个自定义书源', sourcesInvalid: 'JSON 格式有误',
|
|
169
|
+
importBook: '导入', importingBook: '下载中…', serverUnreachable: '连不上本地服务,请确认插件宿主已运行。',
|
|
170
|
+
bookImported: '已导入:{title}', bookTruncated: '(正文过长已截断)',
|
|
171
|
+
confirmDeleteBook: '确定删除「{title}」?本地正文也会一起删除。', currentReading: '在读',
|
|
172
|
+
healthRun: '🩺 体检', healthBusy: '体检中…', healthProgress: '体检中 {done}/{total}',
|
|
173
|
+
healthDone: '体检完成:{ok}/{total} 可用',
|
|
174
|
+
stopLabel: '⏹ 停止', searchFrom: '来自:{name}', unknownSource: '未知书源',
|
|
175
|
+
searchContinue: '继续搜索其他书源 →', searchContinueShort: '继续搜索', searchStopped: '已停止',
|
|
176
|
+
searchProgress: '正在搜索:{name}({i}/{n})',
|
|
177
|
+
searchAllFailed: '已试过 {n} 个书源,都没有找到「{q}」', noSources: '没有可用的书源',
|
|
178
|
+
fetchingAll: '正在抓取全部章节并下载 txt…(可在书架点 ✕ 删除来中止)',
|
|
179
|
+
importedAndDownloaded: '已导入并下载:{name}.txt',
|
|
180
|
+
importDownloadFailed: '已加入书架,但自动下载失败:{msg}',
|
|
181
|
+
downloadedOk: '已下载:{name}.txt', downloadFailed: '下载失败:{msg}',
|
|
182
|
+
deletedDownloadStopped: '已删除,下载任务已停止', deletedOne: '已删除', deleteFailed: '删除失败:{msg}',
|
|
183
|
+
downloadStopped: '已停止下载', downloadingShelf: '⏳ 下载中',
|
|
184
|
+
sourcesManageTitle: '书源管理', sourceAdd: '+ 新增', sourceAddTitle: '新增书源', sourceEditTitle: '编辑书源',
|
|
185
|
+
saveLabel: '保存',
|
|
186
|
+
sourceEditorHint: '粘贴阅读3 / Legado 书源 JSON(单个对象或数组)。仅支持纯规则;含 @js: / <js> / java.* / XPath 的会报错。',
|
|
187
|
+
sourcesSummary: '内置 {b} · 社区 {c}(✔{ok} 可用)· 自定义 {n}',
|
|
188
|
+
sourcesBuiltinGroup: '内置书源(不可删除)', sourcesBuiltinTag: '合规内容源',
|
|
189
|
+
sourcesCustomGroup: '自定义书源(可编辑/删除)',
|
|
190
|
+
sourcesCustomEmpty: '还没有自定义书源,点右上角「+ 新增」导入',
|
|
191
|
+
sourcesCommunityGroup: '社区书源({n},可停用/删除)',
|
|
192
|
+
sourceDisabledTag: ' · 已停用', sourceDisable: '停用', sourceEnable: '启用',
|
|
193
|
+
editLabel: '编辑', deleteLabel: '删除', sourceNameFallback: '书源 {n}',
|
|
194
|
+
sourceSaved: '已保存,共 {n} 个自定义书源', sourceSaveFailed: '保存失败:{msg}', sourceDeleted: '已删除:{name}',
|
|
195
|
+
confirmDeleteSource: '确定删除书源「{name}」?', confirmDeleteCommunity: '确定删除社区书源「{name}」?',
|
|
196
|
+
loadingChapter: '正在加载本章…', reloadChapter: '重新加载本章', onlineTag: ' · 在线', wordsWan: ' 万字',
|
|
109
197
|
},
|
|
110
198
|
};
|
|
111
199
|
|
|
@@ -238,6 +326,16 @@ window.__ModuleLoader__.load({
|
|
|
238
326
|
return d && typeof d === 'object' && !Array.isArray(d) ? d : {};
|
|
239
327
|
} catch (e) { return {}; }
|
|
240
328
|
}
|
|
329
|
+
// 自定义书源:JSON 数组,损坏时当作空
|
|
330
|
+
function loadCustomRaw() {
|
|
331
|
+
try { return localStorage.getItem(SOURCES_KEY) || ''; } catch (e) { return ''; }
|
|
332
|
+
}
|
|
333
|
+
function loadCustomSources() {
|
|
334
|
+
try {
|
|
335
|
+
const arr = JSON.parse(loadCustomRaw() || '[]');
|
|
336
|
+
return Array.isArray(arr) ? arr.filter(x => x && typeof x === 'object' && (x.name || x.bookSourceName)) : [];
|
|
337
|
+
} catch (e) { return []; }
|
|
338
|
+
}
|
|
241
339
|
function saveProfiles(p) {
|
|
242
340
|
try { localStorage.setItem(PROFILES_KEY, JSON.stringify(p)); } catch (e) { /* 存储不可用 */ }
|
|
243
341
|
store.set({ profiles: p });
|
|
@@ -247,12 +345,21 @@ window.__ModuleLoader__.load({
|
|
|
247
345
|
open: false, pinned: false, book: null, chapterIndex: 0, pageIndex: 0,
|
|
248
346
|
style: { ...DEFAULT_STYLE }, pos: null, settingsOpen: false, notice: '',
|
|
249
347
|
profiles: loadProfiles(), profileName: '', // 多套样式配置
|
|
348
|
+
// 在线找书 / 书架
|
|
349
|
+
panelView: 'read', books: [], textVersion: 0,
|
|
350
|
+
searchQuery: '', searching: false, searchResults: [], searchError: '', importing: '', importProgress: '',
|
|
351
|
+
searchProgress: '', searchStopped: false, searchSourceName: '', searchCursor: 0,
|
|
352
|
+
editingSource: null, // { index, json }:书源编辑框状态;index>=0 编辑,-1 新增
|
|
353
|
+
activeSourceId: 'daizhige', customSources: loadCustomSources(),
|
|
354
|
+
communitySources: [], healthBusy: false, healthMsg: '',
|
|
355
|
+
sourcesRaw: loadCustomRaw() || JSON.stringify([SAMPLE_SOURCE], null, 2),
|
|
250
356
|
});
|
|
251
357
|
// 点击图标打开;未钉住时鼠标移出阅读区即收起,需重新点击图标才能再次打开。
|
|
252
358
|
// 钉住后只能点工具栏「收起」关闭,移出不会收起。
|
|
253
359
|
// 用短延迟避免鼠标在图标与阅读区之间移动时闪烁;进入阅读区即取消收起。
|
|
254
360
|
let hideTimer = null;
|
|
255
361
|
let dragActive = false; // 正在拖动面板时暂停自动收起
|
|
362
|
+
let keepOpenOnLeave = false; // 从大弹窗返回阅读区时,忽略紧随其后的一次移出
|
|
256
363
|
function cancelHide() { if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; } }
|
|
257
364
|
function scheduleHide() {
|
|
258
365
|
cancelHide();
|
|
@@ -263,11 +370,565 @@ window.__ModuleLoader__.load({
|
|
|
263
370
|
if (st.open && !st.pinned && !st.settingsOpen && !dragActive) store.set({ open: false, notice: '' });
|
|
264
371
|
}, 200);
|
|
265
372
|
}
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
373
|
+
// 弹窗「返回」:回到阅读视图并忽略紧随其后的移出(鼠标仍在原弹窗区域)
|
|
374
|
+
function backToRead() { keepOpenOnLeave = true; store.set({ panelView: 'read' }); }
|
|
375
|
+
// 弹窗「✕」:真正关闭整个面板,下次点图标重新打开
|
|
376
|
+
function closePanel() { store.set({ panelView: 'read', open: false }); }
|
|
377
|
+
let fullText = ''; // 当前在读的正文;持久化在 IndexedDB,localStorage 只存轻量状态
|
|
378
|
+
let chapterText = ''; // 在线书的当前章正文;按章缓存到 IndexedDB,不整本存
|
|
269
379
|
let anchorEl = null; // 触发图标的 DOM 节点,用于向上定位真实输入框
|
|
270
380
|
|
|
381
|
+
// ---- 本地书库:IndexedDB 两个表,meta 放轻量元数据,texts 单独放整本正文 ----
|
|
382
|
+
let dbPromise = null;
|
|
383
|
+
function openDb() {
|
|
384
|
+
if (dbPromise) return dbPromise;
|
|
385
|
+
dbPromise = new Promise((resolve, reject) => {
|
|
386
|
+
if (typeof indexedDB === 'undefined') { reject(new Error('当前环境不支持 IndexedDB,无法保存书架')); return; }
|
|
387
|
+
const req = indexedDB.open(DB_NAME, 1);
|
|
388
|
+
req.onupgradeneeded = () => {
|
|
389
|
+
const db = req.result;
|
|
390
|
+
if (!db.objectStoreNames.contains('meta')) db.createObjectStore('meta', { keyPath: 'id' });
|
|
391
|
+
if (!db.objectStoreNames.contains('texts')) db.createObjectStore('texts', { keyPath: 'id' });
|
|
392
|
+
};
|
|
393
|
+
req.onsuccess = () => resolve(req.result);
|
|
394
|
+
req.onerror = () => reject(req.error || new Error('IndexedDB 打开失败'));
|
|
395
|
+
});
|
|
396
|
+
return dbPromise;
|
|
397
|
+
}
|
|
398
|
+
function dbRun(storeName, mode, fn) {
|
|
399
|
+
return openDb().then(db => new Promise((resolve, reject) => {
|
|
400
|
+
let tx;
|
|
401
|
+
try { tx = db.transaction(storeName, mode); } catch (e) { reject(e); return; }
|
|
402
|
+
const os = tx.objectStore(storeName);
|
|
403
|
+
let req;
|
|
404
|
+
try { req = fn(os); } catch (e) { reject(e); return; }
|
|
405
|
+
tx.oncomplete = () => resolve(req ? req.result : undefined);
|
|
406
|
+
tx.onerror = () => reject(tx.error || new Error('本地书库写入失败'));
|
|
407
|
+
tx.onabort = () => reject(tx.error || new Error('本地书库操作被中止'));
|
|
408
|
+
}));
|
|
409
|
+
}
|
|
410
|
+
const dbGet = (name, key) => dbRun(name, 'readonly', os => os.get(key));
|
|
411
|
+
const dbAll = name => dbRun(name, 'readonly', os => os.getAll());
|
|
412
|
+
const dbPut = (name, value) => dbRun(name, 'readwrite', os => os.put(value));
|
|
413
|
+
const dbDel = (name, key) => dbRun(name, 'readwrite', os => os.delete(key));
|
|
414
|
+
|
|
415
|
+
// 同一本书(同源同地址)重复导入时覆盖,避免书架堆重复条目
|
|
416
|
+
function bookKey(source, url, title) {
|
|
417
|
+
const sid = source && source.spec ? 'custom:' + (source.spec.name || source.spec.bookSourceName || 'source') : ((source && source.id) || 'local');
|
|
418
|
+
const base = url ? sid + '|' + url : 'local|' + title;
|
|
419
|
+
let hash = 0;
|
|
420
|
+
for (let i = 0; i < base.length; i++) hash = (hash * 31 + base.charCodeAt(i)) | 0;
|
|
421
|
+
return 'b' + (hash >>> 0).toString(36);
|
|
422
|
+
}
|
|
423
|
+
async function saveBook(entry) {
|
|
424
|
+
const text = String(entry.text || '');
|
|
425
|
+
if (text.length > MAX_BOOK_TEXT) throw new Error('正文超过 ' + Math.round(MAX_BOOK_TEXT / 10000) + ' 万字上限,已放弃导入');
|
|
426
|
+
const id = bookKey(entry.source, entry.url, entry.title);
|
|
427
|
+
const chapters = detectChapters(text, store.get().style.customRegex);
|
|
428
|
+
const meta = {
|
|
429
|
+
id, title: String(entry.title || '未命名').slice(0, 80), author: String(entry.author || ''),
|
|
430
|
+
source: entry.source || { id: 'local' }, url: entry.url || '',
|
|
431
|
+
chapters, chars: text.length, updatedAt: Date.now(),
|
|
432
|
+
};
|
|
433
|
+
await dbPut('meta', meta);
|
|
434
|
+
await dbPut('texts', { id, text });
|
|
435
|
+
await refreshBooks();
|
|
436
|
+
return meta;
|
|
437
|
+
}
|
|
438
|
+
async function refreshBooks() {
|
|
439
|
+
try {
|
|
440
|
+
const list = await dbAll('meta');
|
|
441
|
+
list.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
|
|
442
|
+
store.set({ books: list });
|
|
443
|
+
} catch (e) { store.set({ notice: '读取书架失败:' + ((e && e.message) || e) }); }
|
|
444
|
+
}
|
|
445
|
+
async function openBook(id) {
|
|
446
|
+
try {
|
|
447
|
+
const meta = await dbGet('meta', id);
|
|
448
|
+
if (!meta) throw new Error('找不到这本书');
|
|
449
|
+
const st = store.get();
|
|
450
|
+
const same = st.book && st.book.id === id;
|
|
451
|
+
if (meta.online) {
|
|
452
|
+
const chapters = meta.chapters || [];
|
|
453
|
+
const idx = same ? Math.min(st.chapterIndex, Math.max(0, chapters.length - 1)) : 0;
|
|
454
|
+
const cache = await dbGet('texts', id + ':' + idx);
|
|
455
|
+
fullText = '';
|
|
456
|
+
chapterText = (cache && cache.text) || '';
|
|
457
|
+
store.set({
|
|
458
|
+
book: { id: meta.id, name: meta.title, author: meta.author || '', url: meta.url || '', source: meta.source || null, chapters, length: meta.chars || 0, online: true },
|
|
459
|
+
chapterIndex: idx, pageIndex: same ? st.pageIndex : 0, panelView: 'read',
|
|
460
|
+
textVersion: (st.textVersion || 0) + 1,
|
|
461
|
+
});
|
|
462
|
+
persist();
|
|
463
|
+
if (!chapterText) await loadChapter(idx);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const rec = await dbGet('texts', id);
|
|
467
|
+
if (!rec) throw new Error('这本书的正文已不在本地,请重新导入');
|
|
468
|
+
chapterText = '';
|
|
469
|
+
fullText = rec.text || '';
|
|
470
|
+
const chapters = meta.chapters && meta.chapters.length ? meta.chapters : detectChapters(fullText, st.style.customRegex);
|
|
471
|
+
store.set({
|
|
472
|
+
book: { id: meta.id, name: meta.title, author: meta.author || '', url: meta.url || '', source: meta.source || null, chapters, length: meta.chars || fullText.length },
|
|
473
|
+
chapterIndex: same ? Math.min(st.chapterIndex, chapters.length - 1) : 0,
|
|
474
|
+
pageIndex: same ? st.pageIndex : 0,
|
|
475
|
+
panelView: 'read',
|
|
476
|
+
textVersion: (st.textVersion || 0) + 1,
|
|
477
|
+
});
|
|
478
|
+
persist();
|
|
479
|
+
} catch (e) { store.set({ notice: (e && e.message) || '打开失败' }); }
|
|
480
|
+
}
|
|
481
|
+
// ---- 下载任务取消 ----
|
|
482
|
+
// 一本书一个任务;删除书籍时置 cancelled,抓取循环在下一个检查点立刻退出,
|
|
483
|
+
// 并且把「取消之后才写进去」的缓存一并清掉,避免留下孤儿数据。
|
|
484
|
+
const downloadJobs = new Map(); // bookId -> { cancelled }
|
|
485
|
+
|
|
486
|
+
function startDownload(bookId) {
|
|
487
|
+
const job = { bookId, cancelled: false };
|
|
488
|
+
downloadJobs.set(bookId, job);
|
|
489
|
+
return job;
|
|
490
|
+
}
|
|
491
|
+
function endDownload(bookId) {
|
|
492
|
+
downloadJobs.delete(bookId);
|
|
493
|
+
}
|
|
494
|
+
// 返回是否确实取消了一个进行中的任务
|
|
495
|
+
function cancelDownload(bookId) {
|
|
496
|
+
const job = downloadJobs.get(bookId);
|
|
497
|
+
if (!job) return false;
|
|
498
|
+
job.cancelled = true;
|
|
499
|
+
downloadJobs.delete(bookId);
|
|
500
|
+
return true;
|
|
501
|
+
}
|
|
502
|
+
const isCancelled = (job) => !!(job && job.cancelled);
|
|
503
|
+
|
|
504
|
+
// 在线书:逐章抓取(优先读缓存)合并为全文;onProgress(done,total) 回报进度。
|
|
505
|
+
// job 取消后立即抛 CancelledError,并清理本次已写入的缓存。
|
|
506
|
+
async function fetchOnlineText(meta, onProgress, job) {
|
|
507
|
+
const chapters = meta.chapters || [];
|
|
508
|
+
const pieces = new Array(chapters.length).fill('');
|
|
509
|
+
const written = []; // 本次新写入的缓存 key,取消时回滚
|
|
510
|
+
let done = 0;
|
|
511
|
+
const report = () => { if (onProgress) onProgress(done, chapters.length); };
|
|
512
|
+
// 取消检查点:抛出带 cancelled 标记的错误,调用方据此静默收场
|
|
513
|
+
const throwIfCancelled = () => {
|
|
514
|
+
if (isCancelled(job)) {
|
|
515
|
+
const err = new Error('下载已取消');
|
|
516
|
+
err.cancelled = true;
|
|
517
|
+
throw err;
|
|
518
|
+
}
|
|
519
|
+
};
|
|
520
|
+
// 1) 先读缓存
|
|
521
|
+
const missing = [];
|
|
522
|
+
for (let i = 0; i < chapters.length; i++) {
|
|
523
|
+
if (i % 20 === 0) throwIfCancelled();
|
|
524
|
+
const cache = await dbGet('texts', meta.id + ':' + i);
|
|
525
|
+
if (cache && cache.text) { pieces[i] = cache.text; done++; } else missing.push(i);
|
|
526
|
+
}
|
|
527
|
+
report();
|
|
528
|
+
// 2) 批量抓缺失章节
|
|
529
|
+
const BATCH = 20;
|
|
530
|
+
for (let s = 0; s < missing.length; s += BATCH) {
|
|
531
|
+
throwIfCancelled(); // 每批开头:取消后不再发新请求
|
|
532
|
+
const idxs = missing.slice(s, s + BATCH);
|
|
533
|
+
const urls = idxs.map(i => chapters[i].url);
|
|
534
|
+
let got = null;
|
|
535
|
+
try { got = (await hostCall('contents', { source: meta.source, urls })).texts || null; } catch { got = null; }
|
|
536
|
+
for (const i of idxs) {
|
|
537
|
+
throwIfCancelled(); // 逐章:取消后立即停
|
|
538
|
+
let one = got && got[chapters[i].url];
|
|
539
|
+
if (!one) {
|
|
540
|
+
// 批量没拿到,退回单章
|
|
541
|
+
try {
|
|
542
|
+
const data = await hostCall('content', { source: meta.source, url: chapters[i].url });
|
|
543
|
+
one = data.text || '';
|
|
544
|
+
} catch { one = ''; }
|
|
545
|
+
}
|
|
546
|
+
one = normalizeText(one || '');
|
|
547
|
+
if (one) {
|
|
548
|
+
pieces[i] = one;
|
|
549
|
+
await dbPut('texts', { id: meta.id + ':' + i, text: one });
|
|
550
|
+
written.push(meta.id + ':' + i);
|
|
551
|
+
}
|
|
552
|
+
done++;
|
|
553
|
+
report();
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
// 3) 缺失章节保留章节标题占位,方便用户看出哪里没抓到
|
|
557
|
+
for (let i = 0; i < chapters.length; i++) {
|
|
558
|
+
if (!pieces[i]) pieces[i] = '【' + (chapters[i].title || ('第' + (i + 1) + '章')) + ' 抓取失败,可在书架点 💾 重试】';
|
|
559
|
+
}
|
|
560
|
+
return pieces.join('\n\n');
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// 取消下载并清理:删掉 bookId 的所有章节缓存,不留孤儿数据
|
|
564
|
+
async function purgeBookCache(bookId, chapterCount) {
|
|
565
|
+
try { await dbDel('texts', bookId); } catch (e) { /* 忽略 */ }
|
|
566
|
+
const n = Number(chapterCount) || 0;
|
|
567
|
+
for (let i = 0; i < n; i++) {
|
|
568
|
+
try { await dbDel('texts', bookId + ':' + i); } catch (e) { /* 忽略 */ }
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
// 浏览器 Blob 下载 txt
|
|
572
|
+
function triggerTxtDownload(text, title) {
|
|
573
|
+
const safe = String(title || 'book').replace(/[\\/:*?"<>|]/g, '_').slice(0, 60);
|
|
574
|
+
const blob = new Blob([text], { type: 'text/plain;charset=utf-8' });
|
|
575
|
+
const url = URL.createObjectURL(blob);
|
|
576
|
+
const a = document.createElement('a');
|
|
577
|
+
a.href = url; a.download = safe + '.txt';
|
|
578
|
+
document.body.appendChild(a); a.click(); document.body.removeChild(a);
|
|
579
|
+
setTimeout(() => { try { URL.revokeObjectURL(url); } catch (e) { /* 忽略 */ } }, 5000);
|
|
580
|
+
return safe;
|
|
581
|
+
}
|
|
582
|
+
async function exportBook(id, title) {
|
|
583
|
+
const meta = await dbGet('meta', id).catch(() => null);
|
|
584
|
+
const job = startDownload(id);
|
|
585
|
+
try {
|
|
586
|
+
let text = '';
|
|
587
|
+
if (meta && meta.online) {
|
|
588
|
+
text = await fetchOnlineText(meta, (done, total) => store.set({ importProgress: done + '/' + total }), job);
|
|
589
|
+
if (!text) throw new Error('没有可下载的章节正文');
|
|
590
|
+
} else {
|
|
591
|
+
const rec = await dbGet('texts', id);
|
|
592
|
+
if (!rec || !rec.text) throw new Error('本地没有这本书的正文');
|
|
593
|
+
text = rec.text;
|
|
594
|
+
}
|
|
595
|
+
// 抓取期间被取消:不再生成 txt
|
|
596
|
+
if (isCancelled(job)) return;
|
|
597
|
+
const safe = triggerTxtDownload(text, title);
|
|
598
|
+
store.set({ importing: '', importProgress: '', notice: t('downloadedOk', { name: safe }) });
|
|
599
|
+
} catch (e) {
|
|
600
|
+
if (e && e.cancelled) return; // 用户主动取消,静默
|
|
601
|
+
store.set({ notice: t('downloadFailed', { msg: (e && e.message) || e }) });
|
|
602
|
+
} finally {
|
|
603
|
+
endDownload(id);
|
|
604
|
+
store.set({ importProgress: '' });
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
async function removeBook(id) {
|
|
608
|
+
const st = store.get();
|
|
609
|
+
const meta = st.books.find(b => b.id === id);
|
|
610
|
+
if (typeof window !== 'undefined' && window.confirm && !window.confirm(t('confirmDeleteBook', { title: (meta && meta.title) || '这本书' }))) return;
|
|
611
|
+
// 先叫停下载任务:正在进行的抓取会在下一个检查点退出,不再往库里写
|
|
612
|
+
const wasDownloading = cancelDownload(id);
|
|
613
|
+
try {
|
|
614
|
+
await dbDel('meta', id);
|
|
615
|
+
await dbDel('texts', id);
|
|
616
|
+
// 章节缓存可能数量很多,逐条删;若删书时仍在下载,最后再清一次兜底
|
|
617
|
+
const count = meta && meta.online && meta.chapters ? meta.chapters.length : 0;
|
|
618
|
+
for (let i = 0; i < count; i++) await dbDel('texts', id + ':' + i);
|
|
619
|
+
if (st.book && st.book.id === id) {
|
|
620
|
+
fullText = '';
|
|
621
|
+
store.set({ book: null, chapterIndex: 0, pageIndex: 0, panelView: 'shelf', textVersion: (st.textVersion || 0) + 1 });
|
|
622
|
+
persist();
|
|
623
|
+
}
|
|
624
|
+
await refreshBooks();
|
|
625
|
+
// 清掉可能残留的进度显示
|
|
626
|
+
store.set({ notice: wasDownloading ? t('deletedDownloadStopped') : t('deletedOne'), importProgress: '', importing: '' });
|
|
627
|
+
// 被取消的任务可能在删除之后才处理完手上那一章,稍后再清一次残留缓存
|
|
628
|
+
if (wasDownloading) {
|
|
629
|
+
setTimeout(() => { purgeBookCache(id, count).catch(() => {}); }, 1500);
|
|
630
|
+
}
|
|
631
|
+
} catch (e) { store.set({ notice: t('deleteFailed', { msg: (e && e.message) || e }) }); }
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// ---- 在线找书:全部走宿主同源路由,浏览器不直接跨域抓站点 ----
|
|
635
|
+
async function hostCall(path, payload) {
|
|
636
|
+
let res;
|
|
637
|
+
try {
|
|
638
|
+
res = await fetch('/api/dsh-novel-reader/' + path, {
|
|
639
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload),
|
|
640
|
+
});
|
|
641
|
+
} catch (e) { throw new Error(tr('serverUnreachable')); }
|
|
642
|
+
let data = null;
|
|
643
|
+
try { data = await res.json(); } catch (e) { data = null; }
|
|
644
|
+
if (!res.ok || !data || !data.ok) throw new Error((data && data.error) || ('请求失败:HTTP ' + res.status));
|
|
645
|
+
return data;
|
|
646
|
+
}
|
|
647
|
+
// 被用户删除的社区书源 id(持久化,重启后仍过滤)
|
|
648
|
+
function loadHiddenSources() {
|
|
649
|
+
try {
|
|
650
|
+
const arr = JSON.parse(localStorage.getItem(HIDDEN_KEY) || '[]');
|
|
651
|
+
return Array.isArray(arr) ? arr.map(String) : [];
|
|
652
|
+
} catch (e) { return []; }
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// 拉取社区书源清单(只含元数据,规则在宿主侧)
|
|
656
|
+
async function loadCommunitySources() {
|
|
657
|
+
try {
|
|
658
|
+
const data = await hostCall('sources', {});
|
|
659
|
+
const hidden = new Set(loadHiddenSources());
|
|
660
|
+
const list = (data.community || []).filter((x) => !hidden.has(x.id));
|
|
661
|
+
store.set({ communitySources: list });
|
|
662
|
+
} catch (e) { /* 宿主未就绪时忽略,内置源仍可用 */ }
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// 书源体检:对社区源跑一次「搜索→目录→正文」,回写健康状态
|
|
666
|
+
async function runHealth(ids) {
|
|
667
|
+
const st = store.get();
|
|
668
|
+
if (st.healthBusy) return;
|
|
669
|
+
const targets = ids && ids.length ? ids : (st.communitySources || []).map((x) => x.id);
|
|
670
|
+
if (!targets.length) return;
|
|
671
|
+
store.set({ healthBusy: true, healthMsg: t('healthProgress', { done: 0, total: targets.length }) });
|
|
672
|
+
const map = new Map();
|
|
673
|
+
// 分批,每批 8 个,避免一次请求太久
|
|
674
|
+
for (let i = 0; i < targets.length; i += 8) {
|
|
675
|
+
const batch = targets.slice(i, i + 8);
|
|
676
|
+
try {
|
|
677
|
+
const data = await hostCall('health', { ids: batch, query: '剑来' });
|
|
678
|
+
for (const r of data.items || []) map.set(r.id, r);
|
|
679
|
+
} catch (e) { /* 单批失败不影响其它 */ }
|
|
680
|
+
store.set({ healthMsg: t('healthProgress', { done: Math.min(i + 8, targets.length), total: targets.length }) });
|
|
681
|
+
}
|
|
682
|
+
const merged = (store.get().communitySources || []).map((x) => {
|
|
683
|
+
const r = map.get(x.id);
|
|
684
|
+
if (!r) return x;
|
|
685
|
+
return { ...x, status: r.status, enabled: r.status === 'ok', stats: { search: r.search, chapters: r.chapters, contentLen: r.contentLen } };
|
|
686
|
+
});
|
|
687
|
+
store.set({ communitySources: merged, healthBusy: false, healthMsg: '', notice: t('healthDone', { ok: merged.filter((x) => x.status === 'ok').length, total: merged.length }) });
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function currentSource() {
|
|
691
|
+
const st = store.get();
|
|
692
|
+
const active = st.activeSourceId || 'daizhige';
|
|
693
|
+
// 先按名称找自定义 / 阅读3 书源
|
|
694
|
+
const spec = (st.customSources || []).find(x => (x.name || x.bookSourceName) === active);
|
|
695
|
+
if (spec) return { spec };
|
|
696
|
+
// 再按 id 找内置源或社区源(两者都是 { id } 形态,宿主侧负责解析)
|
|
697
|
+
if (BUILTIN_SOURCES.some(x => x.id === active)) return { id: active };
|
|
698
|
+
if ((st.communitySources || []).some(x => x.id === active)) return { id: active };
|
|
699
|
+
return { id: 'daizhige' };
|
|
700
|
+
}
|
|
701
|
+
// ---- 自动多源搜索 ----
|
|
702
|
+
// 不要求用户选源:按「内置 → 社区验证 → 社区候选 → 自定义」的顺序逐个试,
|
|
703
|
+
// 找到结果就停下来让用户看;用户可以点「继续搜索」换下一个源再找,或点「停止」。
|
|
704
|
+
let searchCursor = 0; // 下次从第几个源开始
|
|
705
|
+
let searchAbort = null; // 当前搜索的取消令牌
|
|
706
|
+
|
|
707
|
+
/** 按可用性排出搜索顺序:状态 ok 的优先,其次内置,最后未验证。 */
|
|
708
|
+
function searchOrder() {
|
|
709
|
+
const st = store.get();
|
|
710
|
+
const list = [];
|
|
711
|
+
// 内置源排最前(合规且稳定)
|
|
712
|
+
for (const b of BUILTIN_SOURCES) list.push({ id: b.id, name: b.name, rank: 0 });
|
|
713
|
+
// 社区源:ok(1) → partial(2) → unknown(3)
|
|
714
|
+
const rankOf = (s2) => s2 === 'ok' ? 1 : (s2 === 'partial' ? 2 : 3);
|
|
715
|
+
const community = (st.communitySources || [])
|
|
716
|
+
.filter((x) => x.enabled !== false)
|
|
717
|
+
.slice()
|
|
718
|
+
.sort((a, b) => rankOf(a.status) - rankOf(b.status));
|
|
719
|
+
for (const c of community) list.push({ id: c.id, name: c.name, rank: rankOf(c.status) });
|
|
720
|
+
// 自定义书源(按名称引用)
|
|
721
|
+
for (const cs of st.customSources || []) list.push({ id: cs.name || cs.bookSourceName, name: cs.name || cs.bookSourceName, rank: 2 });
|
|
722
|
+
return list;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** 从 cursor 开始逐个源搜索,直到出结果或全部试完。 */
|
|
726
|
+
async function runSearch(continueMode) {
|
|
727
|
+
const st = store.get();
|
|
728
|
+
const query = String(st.searchQuery || '').trim();
|
|
729
|
+
if (!query) return;
|
|
730
|
+
if (st.searching) return;
|
|
731
|
+
if (!continueMode) { searchCursor = 0; store.set({ searchResults: [], searchError: '' }); }
|
|
732
|
+
const order = searchOrder();
|
|
733
|
+
if (!order.length) { store.set({ searchError: t('noSources') }); return; }
|
|
734
|
+
if (searchCursor >= order.length) { searchCursor = 0; }
|
|
735
|
+
|
|
736
|
+
const token = { cancelled: false };
|
|
737
|
+
searchAbort = token;
|
|
738
|
+
store.set({ searching: true, searchError: '', searchProgress: '', searchStopped: false });
|
|
739
|
+
const tried = [];
|
|
740
|
+
try {
|
|
741
|
+
while (searchCursor < order.length) {
|
|
742
|
+
if (token.cancelled) { store.set({ searching: false, searchStopped: true, searchProgress: '' }); return; }
|
|
743
|
+
const src = order[searchCursor];
|
|
744
|
+
store.set({ searchProgress: t('searchProgress', { name: src.name, i: searchCursor + 1, n: order.length }) });
|
|
745
|
+
try {
|
|
746
|
+
const data = await hostCall('search', { source: { id: src.id }, query, page: 0 });
|
|
747
|
+
const items = data.items || [];
|
|
748
|
+
if (items.length) {
|
|
749
|
+
// 给每条结果打上来源标记,导入时才知道该用哪个书源
|
|
750
|
+
const tagged = items.map((it) => ({ ...it, _srcId: src.id, _srcName: src.name }));
|
|
751
|
+
store.set({ searchResults: tagged, searching: false, searchProgress: '', searchSourceName: src.name });
|
|
752
|
+
searchCursor += 1; // 下次「继续搜索」从这个源之后开始
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
tried.push(src.name);
|
|
756
|
+
} catch (e) {
|
|
757
|
+
tried.push(src.name); // 抛错也算试过,继续下一个
|
|
758
|
+
}
|
|
759
|
+
searchCursor += 1;
|
|
760
|
+
}
|
|
761
|
+
// 全部试完都没有
|
|
762
|
+
store.set({
|
|
763
|
+
searching: false, searchProgress: '', searchCursor,
|
|
764
|
+
searchError: t('searchAllFailed', { n: order.length, q: query }),
|
|
765
|
+
});
|
|
766
|
+
} finally {
|
|
767
|
+
if (searchAbort === token) searchAbort = null;
|
|
768
|
+
store.set({ searching: false, searchProgress: '' });
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/** 停止当前搜索。 */
|
|
773
|
+
function stopSearch() {
|
|
774
|
+
if (searchAbort) searchAbort.cancelled = true;
|
|
775
|
+
store.set({ searching: false, searchProgress: '', searchStopped: true });
|
|
776
|
+
}
|
|
777
|
+
async function importSearchItem(item) {
|
|
778
|
+
if (store.get().importing) return;
|
|
779
|
+
store.set({ importing: item.url, searchError: '' });
|
|
780
|
+
try {
|
|
781
|
+
// 优先用这条结果实际的来源(自动搜索时可能来自任意一个源)
|
|
782
|
+
const source = item && item._srcId ? { id: item._srcId } : currentSource();
|
|
783
|
+
const spec = source.spec;
|
|
784
|
+
// 阅读3 书源,以及维基文库这类按章组织结构的内置源,都走在线阅读
|
|
785
|
+
const isOnline = (!!(spec && (spec.bookSourceName || spec.bookSourceUrl) && spec.ruleToc))
|
|
786
|
+
|| source.id === 'wikisource'
|
|
787
|
+
|| String(source.id || '').startsWith('src:');
|
|
788
|
+
if (isOnline) {
|
|
789
|
+
const toc = await hostCall('chapters', { source, url: item.url, hint: { title: item.title, author: item.author } });
|
|
790
|
+
const chapters = (toc.chapters || []).map(c => ({ title: c.title, url: c.url, start: 0, end: 0 }));
|
|
791
|
+
if (!chapters.length) throw new Error('这本书没有可在线阅读的章节');
|
|
792
|
+
const id = bookKey(source, item.url, item.title);
|
|
793
|
+
const meta = {
|
|
794
|
+
id, title: toc.title || item.title, author: toc.author || item.author || '',
|
|
795
|
+
source, url: item.url, chapters, chars: 0, online: true, updatedAt: Date.now(),
|
|
796
|
+
};
|
|
797
|
+
await dbPut('meta', meta);
|
|
798
|
+
await refreshBooks();
|
|
799
|
+
await openBook(id);
|
|
800
|
+
// 在线书:点导入即抓取所有章节并下载 txt 到本地(逐章缓存,可断点续抓)
|
|
801
|
+
store.set({ panelView: 'read', notice: t('fetchingAll') });
|
|
802
|
+
const job = startDownload(id);
|
|
803
|
+
try {
|
|
804
|
+
const full = await fetchOnlineText(meta, (done, total) => store.set({ importProgress: done + '/' + total }), job);
|
|
805
|
+
// 抓取过程中用户删了这本书:什么都别做
|
|
806
|
+
if (isCancelled(job)) return;
|
|
807
|
+
if (full) {
|
|
808
|
+
const safe = triggerTxtDownload(full, meta.title);
|
|
809
|
+
store.set({ notice: t('importedAndDownloaded', { name: safe }) });
|
|
810
|
+
}
|
|
811
|
+
} catch (dlErr) {
|
|
812
|
+
if (dlErr && dlErr.cancelled) return; // 用户主动取消,静默收场
|
|
813
|
+
store.set({ notice: t('importDownloadFailed', { msg: (dlErr && dlErr.message) || dlErr }) });
|
|
814
|
+
} finally {
|
|
815
|
+
endDownload(id);
|
|
816
|
+
store.set({ importing: '', importProgress: '' });
|
|
817
|
+
}
|
|
818
|
+
return;
|
|
819
|
+
}
|
|
820
|
+
const data = await hostCall('book', { source, url: item.url });
|
|
821
|
+
const text = normalizeText(data.text || '');
|
|
822
|
+
if (text.length < 50) throw new Error('正文过短,放弃导入');
|
|
823
|
+
const meta = await saveBook({
|
|
824
|
+
title: data.title || item.title, author: data.author || '',
|
|
825
|
+
source, url: item.url, text,
|
|
826
|
+
});
|
|
827
|
+
await openBook(meta.id);
|
|
828
|
+
store.set({ importing: '', panelView: 'read', notice: t('bookImported', { title: meta.title }) + (data.truncated ? tr('bookTruncated') : '') });
|
|
829
|
+
} catch (e) { store.set({ importing: '', searchError: (e && e.message) || '导入失败' }); }
|
|
830
|
+
}
|
|
831
|
+
// 在线书:按需抓取单章正文并缓存;失败只提示不阻塞阅读
|
|
832
|
+
async function loadChapter(index) {
|
|
833
|
+
const st = store.get();
|
|
834
|
+
const book = st.book;
|
|
835
|
+
if (!book || !book.online || !book.chapters[index]) return;
|
|
836
|
+
if (index !== st.chapterIndex) return;
|
|
837
|
+
const key = book.id + ':' + index;
|
|
838
|
+
try {
|
|
839
|
+
const cache = await dbGet('texts', key);
|
|
840
|
+
if (cache && cache.text) {
|
|
841
|
+
if (index === store.get().chapterIndex) { chapterText = cache.text; store.set({ textVersion: (store.get().textVersion || 0) + 1 }); }
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
const data = await hostCall('content', { source: book.source, url: book.chapters[index].url });
|
|
845
|
+
const text = normalizeText(data.text || '');
|
|
846
|
+
await dbPut('texts', { id: key, text });
|
|
847
|
+
if (index === store.get().chapterIndex) {
|
|
848
|
+
chapterText = text;
|
|
849
|
+
store.set({ textVersion: (store.get().textVersion || 0) + 1, notice: '' });
|
|
850
|
+
}
|
|
851
|
+
} catch (e) {
|
|
852
|
+
if (index === store.get().chapterIndex) store.set({ notice: '章节加载失败:' + ((e && e.message) || e) });
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
// ---- 自定义书源的增 / 改 / 删 ----
|
|
857
|
+
/** 校验一条书源,返回规范化对象;不合法抛中文错误。 */
|
|
858
|
+
function normalizeSource(spec) {
|
|
859
|
+
if (!spec || typeof spec !== 'object' || Array.isArray(spec)) throw new Error('书源必须是一个 JSON 对象');
|
|
860
|
+
const isLegado = !!(spec.bookSourceName || spec.bookSourceUrl) && !!(spec.ruleSearch || spec.ruleToc || spec.ruleContent);
|
|
861
|
+
const isSpec = !!(spec.name && spec.search && spec.search.url && spec.search.item && spec.book && spec.book.content);
|
|
862
|
+
if (!isLegado && !isSpec) throw new Error('需为自定义书源 JSON 或阅读3(Legado)书源 JSON');
|
|
863
|
+
if (isLegado) {
|
|
864
|
+
// 提前挡掉本插件跑不了的规则,避免保存后才在搜索时失败
|
|
865
|
+
const rules = [spec.searchUrl, spec.ruleSearch, spec.ruleToc, spec.ruleContent]
|
|
866
|
+
.map((x) => (typeof x === 'string' ? x : JSON.stringify(x || {}))).join(' ');
|
|
867
|
+
if (/@js:|<js|java\.|webJs/.test(rules)) throw new Error('这个书源用了 JS 规则(@js:/<js>/java.*),当前版本不支持');
|
|
868
|
+
if (/@xpath:|^\s*\/\//m.test(String(spec.ruleToc && spec.ruleToc.chapterList || ''))) throw new Error('这个书源用了 XPath 规则,当前版本不支持');
|
|
869
|
+
}
|
|
870
|
+
return spec;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
function persistCustomSources(list) {
|
|
874
|
+
localStorage.setItem(SOURCES_KEY, JSON.stringify(list));
|
|
875
|
+
store.set({ customSources: list });
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
/** 保存编辑框里的书源(新增或覆盖)。支持粘贴单个对象或数组。 */
|
|
879
|
+
function saveSourceInEditor() {
|
|
880
|
+
const editing = store.get().editingSource;
|
|
881
|
+
if (!editing) return;
|
|
882
|
+
try {
|
|
883
|
+
const raw = String(editing.json || '').trim();
|
|
884
|
+
if (!raw) throw new Error('内容为空');
|
|
885
|
+
let parsed = JSON.parse(raw);
|
|
886
|
+
if (!Array.isArray(parsed)) parsed = [parsed];
|
|
887
|
+
const list = (store.get().customSources || []).slice();
|
|
888
|
+
if (editing.index >= 0) {
|
|
889
|
+
// 编辑模式:只替换这一条(数组只取第一条)
|
|
890
|
+
list[editing.index] = normalizeSource(parsed[0]);
|
|
891
|
+
} else {
|
|
892
|
+
// 新增模式:追加(支持一次粘数组)
|
|
893
|
+
for (const one of parsed) list.push(normalizeSource(one));
|
|
894
|
+
}
|
|
895
|
+
persistCustomSources(list);
|
|
896
|
+
store.set({ editingSource: null, notice: t('sourceSaved', { n: list.length }) });
|
|
897
|
+
} catch (e) {
|
|
898
|
+
store.set({ notice: t('sourceSaveFailed', { msg: (e && e.message) || e }) });
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/** 删除第 index 个自定义书源。 */
|
|
903
|
+
function removeSource(index) {
|
|
904
|
+
const list = (store.get().customSources || []).slice();
|
|
905
|
+
if (index < 0 || index >= list.length) return;
|
|
906
|
+
const name = list[index].bookSourceName || list[index].name || ('书源 ' + (index + 1));
|
|
907
|
+
if (typeof window !== 'undefined' && window.confirm && !window.confirm(t('confirmDeleteSource', { name }))) return;
|
|
908
|
+
list.splice(index, 1);
|
|
909
|
+
persistCustomSources(list);
|
|
910
|
+
store.set({ notice: t('sourceDeleted', { name }) });
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/** 启用 / 停用社区书源(停用后自动搜索会跳过)。 */
|
|
914
|
+
function toggleCommunitySource(id) {
|
|
915
|
+
const list = (store.get().communitySources || []).map((x) => x.id === id ? { ...x, enabled: x.enabled === false } : x);
|
|
916
|
+
store.set({ communitySources: list });
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/** 从本地隐藏一个社区书源(不删内置数据,只是标记 hidden 并重启后仍生效需持久化)。 */
|
|
920
|
+
function removeCommunitySource(id) {
|
|
921
|
+
const st2 = store.get();
|
|
922
|
+
const target = (st2.communitySources || []).find((x) => x.id === id);
|
|
923
|
+
if (!target) return;
|
|
924
|
+
if (typeof window !== 'undefined' && window.confirm && !window.confirm(t('confirmDeleteCommunity', { name: target.name }))) return;
|
|
925
|
+
const hidden = new Set(loadHiddenSources());
|
|
926
|
+
hidden.add(id);
|
|
927
|
+
try { localStorage.setItem(HIDDEN_KEY, JSON.stringify([...hidden])); } catch (e) { /* 忽略 */ }
|
|
928
|
+
const list = (st2.communitySources || []).filter((x) => x.id !== id);
|
|
929
|
+
store.set({ communitySources: list, notice: t('sourceDeleted', { name: target.name }) });
|
|
930
|
+
}
|
|
931
|
+
|
|
271
932
|
// 从图标向上找到真实编辑器,再读取它的矩形与计算样式(配色/字体/圆角)
|
|
272
933
|
function findEditorInfo() {
|
|
273
934
|
if (!anchorEl || typeof document === 'undefined') return null;
|
|
@@ -337,37 +998,47 @@ window.__ModuleLoader__.load({
|
|
|
337
998
|
};
|
|
338
999
|
}
|
|
339
1000
|
|
|
340
|
-
//
|
|
1001
|
+
// 翻页只写轻量状态;正文放 IndexedDB,localStorage 只留书号和进度
|
|
341
1002
|
function persist() {
|
|
342
1003
|
const s = store.get();
|
|
343
1004
|
const base = {
|
|
344
1005
|
style: s.style, pos: s.pos, pinned: s.pinned,
|
|
345
|
-
|
|
1006
|
+
bookId: s.book ? s.book.id : null,
|
|
346
1007
|
chapterIndex: s.chapterIndex, pageIndex: s.pageIndex,
|
|
347
1008
|
};
|
|
348
1009
|
try { localStorage.setItem(STORE_KEY, JSON.stringify(base)); } catch (e) { /* 存储不可用 */ }
|
|
349
1010
|
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
fullText = stored ? normalizeText(stored) : ''; // 旧数据也套用统一排版
|
|
361
|
-
savedProgress = d.book ? { name: d.book.name, chapterIndex: d.chapterIndex || 0, pageIndex: d.pageIndex || 0 } : null;
|
|
362
|
-
store.set({
|
|
363
|
-
book: d.book || null,
|
|
364
|
-
style: { ...DEFAULT_STYLE, ...(d.style || {}) },
|
|
365
|
-
pos: null, // 不使用旧位置,每次打开都重新贴合输入框,避免框跑偏超出范围
|
|
366
|
-
pinned: !!d.pinned,
|
|
367
|
-
chapterIndex: d.chapterIndex || 0, pageIndex: d.pageIndex || 0,
|
|
368
|
-
});
|
|
1011
|
+
// 启动:恢复样式与上次在读的书;旧版把整本正文塞 localStorage 的数据顺带迁移进书库
|
|
1012
|
+
async function hydrate() {
|
|
1013
|
+
let saved = null;
|
|
1014
|
+
try { const raw = localStorage.getItem(STORE_KEY); if (raw) saved = JSON.parse(raw); } catch (e) { saved = null; }
|
|
1015
|
+
if (saved && saved.style) store.set({ style: { ...DEFAULT_STYLE, ...saved.style }, pos: null, pinned: !!saved.pinned });
|
|
1016
|
+
try { await refreshBooks(); } catch (e) { /* 书库不可用时仍可继续导入 */ }
|
|
1017
|
+
try { await loadCommunitySources(); } catch (e) { /* 社区源不可用时忽略 */ }
|
|
1018
|
+
let activeId = (saved && saved.bookId) || null;
|
|
1019
|
+
if (!activeId) {
|
|
1020
|
+
try { activeId = await migrateLegacy(saved); } catch (e) { activeId = null; }
|
|
369
1021
|
}
|
|
370
|
-
|
|
1022
|
+
const books = store.get().books || [];
|
|
1023
|
+
if (!activeId && books.length) activeId = books[0].id;
|
|
1024
|
+
if (!activeId) return;
|
|
1025
|
+
await openBook(activeId);
|
|
1026
|
+
if (saved && saved.bookId === activeId) {
|
|
1027
|
+
const chapters = (store.get().book && store.get().book.chapters) || [];
|
|
1028
|
+
store.set({ chapterIndex: Math.min(saved.chapterIndex || 0, Math.max(0, chapters.length - 1)), pageIndex: saved.pageIndex || 0 });
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
async function migrateLegacy(saved) {
|
|
1032
|
+
let text = '';
|
|
1033
|
+
try { text = localStorage.getItem(TEXT_KEY) || ''; } catch (e) { return null; }
|
|
1034
|
+
if (!text) return null;
|
|
1035
|
+
const meta = await saveBook({
|
|
1036
|
+
title: (saved && saved.book && saved.book.name) || '本地导入', author: '',
|
|
1037
|
+
source: { id: 'local' }, url: '', text: normalizeText(text),
|
|
1038
|
+
});
|
|
1039
|
+
try { localStorage.removeItem(TEXT_KEY); } catch (e) { /* 忽略 */ }
|
|
1040
|
+
return meta.id;
|
|
1041
|
+
}
|
|
371
1042
|
|
|
372
1043
|
// 读取文件:显式按钮 / 拖放共用
|
|
373
1044
|
async function readFile(file) {
|
|
@@ -386,19 +1057,12 @@ window.__ModuleLoader__.load({
|
|
|
386
1057
|
catch (err2) { throw new Error(tr('decodeError')); }
|
|
387
1058
|
}
|
|
388
1059
|
}
|
|
389
|
-
|
|
390
|
-
const
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
}
|
|
395
|
-
store.set({
|
|
396
|
-
book: { name: file.name, chapters, length: text.length },
|
|
397
|
-
chapterIndex: ci, pageIndex: pi,
|
|
398
|
-
notice: t('imported', { name: file.name, chapters: chapters.length }),
|
|
399
|
-
});
|
|
400
|
-
persistText();
|
|
401
|
-
persist();
|
|
1060
|
+
const normalized = normalizeText(text); // 统一排版:不沿用原 txt 的缩进与硬换行
|
|
1061
|
+
const title = file.name.replace(/\.txt$/i, '');
|
|
1062
|
+
const meta = await saveBook({ title, author: '', source: { id: 'local' }, url: '', text: normalized });
|
|
1063
|
+
store.set({ notice: t('imported', { name: title, chapters: meta.chapters.length }) });
|
|
1064
|
+
await openBook(meta.id);
|
|
1065
|
+
store.set({ panelView: 'read' });
|
|
402
1066
|
} catch (err) {
|
|
403
1067
|
store.set({ notice: (err && err.message) || tr('importFailed') });
|
|
404
1068
|
}
|
|
@@ -440,6 +1104,23 @@ window.__ModuleLoader__.load({
|
|
|
440
1104
|
const resizeRef = useRef(null); // 边缘缩放:起始鼠标位置 / 起始宽高 / 方向
|
|
441
1105
|
const [resizing, setResizing] = useState(false);
|
|
442
1106
|
const [chapterMenuOpen, setChapterMenuOpen] = useState(false); // 章节下拉菜单开合
|
|
1107
|
+
// 章节弹层:脱离面板容器渲染(fixed),避免被面板的 overflow:hidden 裁剪
|
|
1108
|
+
const chapterBtnRef = useRef(null); // 章节按钮,用于测量弹层位置
|
|
1109
|
+
const chapterMenuRef = useRef(null); // 章节列表,用于打开时滚动到当前章
|
|
1110
|
+
const [chapterMenuRect, setChapterMenuRect] = useState(null); // 弹层定位(fixed 坐标系)
|
|
1111
|
+
|
|
1112
|
+
// 在线书:进入某章时按需抓取正文(已缓存则直接读)
|
|
1113
|
+
useEffect(() => {
|
|
1114
|
+
if (s.open && s.book && s.book.online && s.panelView === 'read') loadChapter(s.chapterIndex);
|
|
1115
|
+
}, [s.open, s.book && s.book.id, s.chapterIndex, s.panelView]);
|
|
1116
|
+
|
|
1117
|
+
// 打开章节菜单时滚动到当前章,让用户先看到正在读的位置
|
|
1118
|
+
useEffect(() => {
|
|
1119
|
+
const el = chapterMenuRef.current;
|
|
1120
|
+
if (!chapterMenuOpen || !el) return;
|
|
1121
|
+
const row = el.children && el.children[s.chapterIndex];
|
|
1122
|
+
if (row) el.scrollTop = Math.max(0, row.offsetTop - el.clientHeight / 2 + row.offsetHeight / 2);
|
|
1123
|
+
}, [chapterMenuOpen]);
|
|
443
1124
|
|
|
444
1125
|
// 读取真实输入框的矩形与配色,作为覆盖层的默认样式
|
|
445
1126
|
useEffect(() => {
|
|
@@ -515,8 +1196,9 @@ window.__ModuleLoader__.load({
|
|
|
515
1196
|
|
|
516
1197
|
const chapter = s.book && s.book.chapters[s.chapterIndex] || null;
|
|
517
1198
|
const pages = useMemo(
|
|
518
|
-
() => chapter ? layoutPages(fullText.slice(chapter.start, chapter.end), eff) : [],
|
|
519
|
-
|
|
1199
|
+
() => chapter ? layoutPages(s.book.online ? chapterText : fullText.slice(chapter.start, chapter.end), eff) : [],
|
|
1200
|
+
// fullText/chapterText 是模块内变量,靠 textVersion 触发重算(换书/异步载入正文时递增)
|
|
1201
|
+
[chapter && chapter.start, chapter && chapter.end, eff.width, eff.height, eff.fontSize, eff.lineHeight, s.textVersion]
|
|
520
1202
|
);
|
|
521
1203
|
const pageCount = pages.length;
|
|
522
1204
|
const pageIndex = Math.min(s.pageIndex, Math.max(0, pageCount - 1));
|
|
@@ -532,7 +1214,26 @@ window.__ModuleLoader__.load({
|
|
|
532
1214
|
if (!s.book) return;
|
|
533
1215
|
const next = s.chapterIndex + delta;
|
|
534
1216
|
if (next < 0 || next >= s.book.chapters.length) return;
|
|
535
|
-
store.set({ chapterIndex: next, pageIndex: 0 });
|
|
1217
|
+
if (s.book.online) { chapterText = ''; store.set({ chapterIndex: next, pageIndex: 0, textVersion: (s.textVersion || 0) + 1 }); }
|
|
1218
|
+
else store.set({ chapterIndex: next, pageIndex: 0 });
|
|
1219
|
+
persist();
|
|
1220
|
+
}
|
|
1221
|
+
// 打开/关闭章节弹层:打开时量出按钮位置,弹层固定在按钮上方(不受面板裁剪)
|
|
1222
|
+
function toggleChapterMenu() {
|
|
1223
|
+
if (!s.book) return;
|
|
1224
|
+
if (chapterMenuOpen) { setChapterMenuOpen(false); return; }
|
|
1225
|
+
const btn = chapterBtnRef.current;
|
|
1226
|
+
if (btn) {
|
|
1227
|
+
const r = btn.getBoundingClientRect();
|
|
1228
|
+
const width = Math.max(r.width, 200);
|
|
1229
|
+
setChapterMenuRect({
|
|
1230
|
+
left: Math.max(8, Math.min(r.left, window.innerWidth - width - 8)),
|
|
1231
|
+
bottom: window.innerHeight - r.top + 4, // 贴按钮上沿向上展开
|
|
1232
|
+
width,
|
|
1233
|
+
maxHeight: Math.min(280, Math.max(120, r.top - 12)), // 约十章高度,且不超出屏幕顶部
|
|
1234
|
+
});
|
|
1235
|
+
}
|
|
1236
|
+
setChapterMenuOpen(true);
|
|
536
1237
|
}
|
|
537
1238
|
// 开始边缘缩放:记录初始宽高与鼠标位置、当前面板左上角
|
|
538
1239
|
function startResize(e, dir) {
|
|
@@ -552,15 +1253,18 @@ window.__ModuleLoader__.load({
|
|
|
552
1253
|
|
|
553
1254
|
if (!s.open) return null;
|
|
554
1255
|
const isSettings = !!s.settingsOpen;
|
|
1256
|
+
// 书架/找书/书源:不再挤在输入框大小里,改用与设置面板一样的大面板弹窗
|
|
1257
|
+
const isPopup = s.panelView !== 'read';
|
|
1258
|
+
const isLarge = isSettings || isPopup; // 两种「大面板」共用 peff 尺寸与配色
|
|
555
1259
|
// 设置面板配色直接取自 peff(与阅读区 eff 完全独立),改一边不影响另一边。
|
|
556
1260
|
const panelBg = peff.bg;
|
|
557
1261
|
const panelColor = peff.color;
|
|
558
1262
|
// 阅读区渲染背景:在基础背景色上叠加透明度(跟随开关/取色器仍用 eff.bg 原值,不受影响)
|
|
559
1263
|
const readerBg = withOpacity(eff.bg, st.bgOpacity);
|
|
560
1264
|
// 设置模式用 peff 尺寸(可自定义),超出滚动;阅读模式用 eff 精确贴合输入框尺寸
|
|
561
|
-
const panelW =
|
|
562
|
-
const panelH =
|
|
563
|
-
const panelTop =
|
|
1265
|
+
const panelW = isLarge ? peff.width : eff.width;
|
|
1266
|
+
const panelH = isLarge ? peff.height : eff.height;
|
|
1267
|
+
const panelTop = isLarge && typeof window !== 'undefined'
|
|
564
1268
|
? Math.max(8, Math.min(eff.y, window.innerHeight - panelH - 20)) : eff.y;
|
|
565
1269
|
// 边框样式:设置面板与阅读区各自独立(圆角/显示开关分开存),默认都跟随输入框。
|
|
566
1270
|
// 边框颜色源随模式取对应背景所属元素,避免串色。必须在 wrapStyle 之前定义,避免 TDZ。
|
|
@@ -571,19 +1275,19 @@ window.__ModuleLoader__.load({
|
|
|
571
1275
|
}
|
|
572
1276
|
const readerBorder = borderOf(st.radiusValue, st.borderVisible, { radius: eff.radius, border: eff.border });
|
|
573
1277
|
const panelBorder = borderOf(st.panelRadiusValue, st.panelBorderVisible, { radius: eff.radius, border: eff.border });
|
|
574
|
-
const borderOn =
|
|
575
|
-
const finalRadius =
|
|
576
|
-
const finalBorder =
|
|
577
|
-
//
|
|
578
|
-
const curFont =
|
|
579
|
-
const curFontSize =
|
|
1278
|
+
const borderOn = isLarge ? (st.panelBorderVisible !== false) : (st.borderVisible !== false);
|
|
1279
|
+
const finalRadius = isLarge ? panelBorder.radius : readerBorder.radius;
|
|
1280
|
+
const finalBorder = isLarge ? panelBorder.border : readerBorder.border;
|
|
1281
|
+
// 当前模式的字体/字号/行距:大面板用 peff,阅读区用 eff
|
|
1282
|
+
const curFont = isLarge ? peff.fontFamily : eff.fontFamily;
|
|
1283
|
+
const curFontSize = isLarge ? peff.fontSize : eff.fontSize;
|
|
580
1284
|
const wrapStyle = {
|
|
581
1285
|
position: 'fixed', left: eff.x, top: panelTop, width: panelW, height: panelH,
|
|
582
1286
|
// border-box:让宽高包含边框与内边距,精确覆盖输入框而不多出像素
|
|
583
1287
|
boxSizing: 'border-box',
|
|
584
1288
|
zIndex: 100000, display: 'flex', flexDirection: 'column', overflow: 'hidden',
|
|
585
|
-
background:
|
|
586
|
-
color:
|
|
1289
|
+
background: isLarge ? panelBg : readerBg,
|
|
1290
|
+
color: isLarge ? panelColor : eff.color,
|
|
587
1291
|
fontFamily: curFont, fontSize: curFontSize,
|
|
588
1292
|
border: finalBorder, borderRadius: finalRadius,
|
|
589
1293
|
boxShadow: eff.shadow || undefined,
|
|
@@ -630,6 +1334,214 @@ window.__ModuleLoader__.load({
|
|
|
630
1334
|
background: 'transparent', color: 'inherit', fontSize: 12, padding: '2px 4px',
|
|
631
1335
|
};
|
|
632
1336
|
|
|
1337
|
+
// ---- 三个视图:找书 / 书架 / 书源,都复用同一块面板,用 panelView 切换 ----
|
|
1338
|
+
const smallBtn = {
|
|
1339
|
+
border: '1px solid rgba(120,140,170,0.4)', borderRadius: 5, background: 'transparent',
|
|
1340
|
+
color: 'inherit', fontSize: 12, padding: '2px 8px', cursor: 'pointer', whiteSpace: 'nowrap',
|
|
1341
|
+
};
|
|
1342
|
+
const fieldStyle = {
|
|
1343
|
+
border: '1px solid rgba(120,140,170,0.45)', borderRadius: 6, background: 'transparent',
|
|
1344
|
+
color: 'inherit', fontSize: 12, padding: '3px 8px', minWidth: 0,
|
|
1345
|
+
};
|
|
1346
|
+
const viewStyle = { flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', gap: 6, padding: '8px 12px', fontSize: 12, color: 'inherit' };
|
|
1347
|
+
const viewHeader = { display: 'flex', alignItems: 'center', gap: 6 };
|
|
1348
|
+
const rowStyle = { display: 'flex', alignItems: 'center', gap: 8, padding: '5px 0', borderBottom: '1px solid rgba(120,140,170,0.18)' };
|
|
1349
|
+
const lineStyle = { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' };
|
|
1350
|
+
const noticeStyle = { fontSize: 11, opacity: 0.85, padding: '2px 0', cursor: 'pointer', flexShrink: 0 };
|
|
1351
|
+
|
|
1352
|
+
function readView() {
|
|
1353
|
+
const hint = !s.book ? tr('importHint') : (s.book.online ? (!chapterText ? t('loadingChapter') : null) : (!fullText ? tr('reopenHint') : null));
|
|
1354
|
+
const hintBtn = s.book && s.book.online && !chapterText
|
|
1355
|
+
? h('button', { type: 'button', onClick: () => loadChapter(s.chapterIndex), style: smallBtn }, t('reloadChapter'))
|
|
1356
|
+
: (s.book && !s.book.online && !fullText
|
|
1357
|
+
? h('button', { type: 'button', onClick: () => fileRef.current && fileRef.current.click(), style: smallBtn }, tr('import'))
|
|
1358
|
+
: null);
|
|
1359
|
+
return h('div', {
|
|
1360
|
+
onClick: onReadClick, onDragOver: e => e.preventDefault(), onDrop: onDrop,
|
|
1361
|
+
style: { position: 'relative', flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', padding: '2px 14px' },
|
|
1362
|
+
},
|
|
1363
|
+
s.notice || s.importProgress ? h('div', { style: noticeStyle, onClick: () => store.set({ notice: '', importProgress: '' }) }, (s.importProgress ? '[' + s.importProgress + '] ' : '') + (s.notice || '')) : null,
|
|
1364
|
+
h('div', { style: { flex: 1, minHeight: 0, overflow: 'hidden', fontSize: eff.fontSize, lineHeight: eff.lineHeight, cursor: 'pointer' } },
|
|
1365
|
+
hint
|
|
1366
|
+
? h('div', null,
|
|
1367
|
+
h('div', { style: { opacity: 0.7, fontSize: 13, lineHeight: 1.8 } }, hint),
|
|
1368
|
+
hintBtn)
|
|
1369
|
+
: h('div', { style: { whiteSpace: 'pre-wrap', wordBreak: 'break-word', userSelect: 'text' } }, pageText)),
|
|
1370
|
+
h('div', { style: { position: 'absolute', left: 0, top: 0, bottom: 0, width: '28%', display: 'flex', alignItems: 'center', pointerEvents: 'none' } },
|
|
1371
|
+
h('span', { style: { opacity: 0.15, fontSize: 22, paddingLeft: 4 } }, tr('prevPage'))),
|
|
1372
|
+
h('div', { style: { position: 'absolute', right: 0, top: 0, bottom: 0, width: '28%', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', pointerEvents: 'none' } },
|
|
1373
|
+
h('span', { style: { opacity: 0.15, fontSize: 22, paddingRight: 4 } }, tr('nextPage'))),
|
|
1374
|
+
// 边缘缩放手柄:右边缘调宽、下边缘调高、右下角同时调
|
|
1375
|
+
h('div', { title: tr('resizeHint'), onMouseDown: e => startResize(e, 'e'), onClick: e => e.stopPropagation(), style: { position: 'absolute', right: 0, top: 10, bottom: 10, width: 6, cursor: 'ew-resize', zIndex: 4 } }),
|
|
1376
|
+
h('div', { title: tr('resizeHint'), onMouseDown: e => startResize(e, 's'), onClick: e => e.stopPropagation(), style: { position: 'absolute', bottom: 0, left: 10, right: 10, height: 6, cursor: 'ns-resize', zIndex: 4 } }),
|
|
1377
|
+
h('div', { title: tr('resizeHint'), onMouseDown: e => startResize(e, 'se'), onClick: e => e.stopPropagation(), style: { position: 'absolute', right: 0, bottom: 0, width: 16, height: 16, cursor: 'nwse-resize', zIndex: 5 } })
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
function searchView() {
|
|
1382
|
+
const rows = s.searchResults || [];
|
|
1383
|
+
return h('div', { style: viewStyle },
|
|
1384
|
+
h('div', { style: viewHeader },
|
|
1385
|
+
toolBtn('← ' + tr('back'), backToRead),
|
|
1386
|
+
h('span', { style: { flex: 1, fontWeight: 600 } }, tr('searchTitle')),
|
|
1387
|
+
toolBtn(tr('manageSources'), () => store.set({ panelView: 'sources' })),
|
|
1388
|
+
toolBtn(s.healthBusy ? (s.healthMsg || t('healthBusy')) : t('healthRun'), () => runHealth(), s.healthBusy),
|
|
1389
|
+
toolBtn('✕', closePanel)
|
|
1390
|
+
),
|
|
1391
|
+
// 不选源:自动按可用书源顺序找
|
|
1392
|
+
h('div', { style: { display: 'flex', alignItems: 'center', gap: 6 } },
|
|
1393
|
+
h('input', {
|
|
1394
|
+
type: 'text', value: s.searchQuery, placeholder: tr('searchPlaceholder'),
|
|
1395
|
+
onChange: e => store.set({ searchQuery: e.target.value }),
|
|
1396
|
+
onKeyDown: e => { if (e.key === 'Enter') runSearch(false); },
|
|
1397
|
+
style: { ...fieldStyle, flex: 1 },
|
|
1398
|
+
}),
|
|
1399
|
+
s.searching
|
|
1400
|
+
? h('button', { type: 'button', onClick: stopSearch, style: { ...smallBtn, color: '#c0392b', fontWeight: 600 } }, t('stopLabel'))
|
|
1401
|
+
: h('button', { type: 'button', onClick: () => runSearch(false), style: { ...smallBtn, fontWeight: 600 } }, tr('searchButton'))
|
|
1402
|
+
),
|
|
1403
|
+
// 结果来自哪个源 + 继续换下一个源再搜
|
|
1404
|
+
(!s.searching && rows.length > 0)
|
|
1405
|
+
? h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, opacity: 0.85, flexWrap: 'wrap' } },
|
|
1406
|
+
h('span', null, t('searchFrom', { name: s.searchSourceName || t('unknownSource') })),
|
|
1407
|
+
h('button', { type: 'button', onClick: () => runSearch(true), style: { ...smallBtn, fontSize: 11 } }, t('searchContinue')))
|
|
1408
|
+
: null,
|
|
1409
|
+
s.searchProgress ? h('div', { style: { fontSize: 11, opacity: 0.75 } }, s.searchProgress) : null,
|
|
1410
|
+
s.searchError ? h('div', { style: { color: '#c0392b', fontSize: 12 } }, s.searchError) : null,
|
|
1411
|
+
s.searchStopped && !s.searching
|
|
1412
|
+
? h('div', { style: { display: 'flex', gap: 6, alignItems: 'center', fontSize: 11 } },
|
|
1413
|
+
h('span', { style: { opacity: 0.75 } }, t('searchStopped')),
|
|
1414
|
+
h('button', { type: 'button', onClick: () => runSearch(true), style: { ...smallBtn, fontSize: 11 } }, t('searchContinueShort')))
|
|
1415
|
+
: null,
|
|
1416
|
+
h('div', { style: { flex: 1, minHeight: 0, overflowY: 'auto' } },
|
|
1417
|
+
rows.length === 0
|
|
1418
|
+
? h('div', { style: { opacity: 0.65, marginTop: 8, fontSize: 12, lineHeight: 1.7 } }, s.searching ? tr('searching') : tr('searchEmpty'))
|
|
1419
|
+
: rows.map((item, i) => h('div', { key: i, style: rowStyle },
|
|
1420
|
+
h('div', { style: { flex: 1, minWidth: 0 } },
|
|
1421
|
+
h('div', { style: lineStyle }, item.title),
|
|
1422
|
+
item.note ? h('div', { style: { opacity: 0.6, fontSize: 11 } }, item.note) : null),
|
|
1423
|
+
h('button', {
|
|
1424
|
+
type: 'button', disabled: !!s.importing, onClick: () => importSearchItem(item),
|
|
1425
|
+
style: { ...smallBtn, opacity: s.importing ? 0.4 : 1 },
|
|
1426
|
+
}, s.importing === item.url ? ((s.importProgress ? s.importProgress + ' ' : '') + tr('importingBook')) : tr('importBook'))
|
|
1427
|
+
))
|
|
1428
|
+
),
|
|
1429
|
+
s.notice ? h('div', { style: noticeStyle, onClick: () => store.set({ notice: '' }) }, s.notice) : null
|
|
1430
|
+
);
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
function shelfView() {
|
|
1434
|
+
const books = s.books || [];
|
|
1435
|
+
return h('div', { style: viewStyle },
|
|
1436
|
+
h('div', { style: viewHeader },
|
|
1437
|
+
toolBtn('← ' + tr('back'), backToRead),
|
|
1438
|
+
h('span', { style: { flex: 1, fontWeight: 600 } }, tr('shelfTitle')),
|
|
1439
|
+
toolBtn('🔍 ' + tr('searchTitle'), () => store.set({ panelView: 'search' })),
|
|
1440
|
+
toolBtn('✕', closePanel)
|
|
1441
|
+
),
|
|
1442
|
+
h('div', { style: { flex: 1, minHeight: 0, overflowY: 'auto' } },
|
|
1443
|
+
books.length === 0
|
|
1444
|
+
? h('div', { style: { opacity: 0.65, marginTop: 8, lineHeight: 1.7 } }, tr('shelfEmpty'))
|
|
1445
|
+
: books.map(meta => {
|
|
1446
|
+
const current = s.book && s.book.id === meta.id;
|
|
1447
|
+
// 这本书是否正在抓取全章(下载任务存在且未结束)
|
|
1448
|
+
const downloading = downloadJobs.has(meta.id);
|
|
1449
|
+
return h('div', { key: meta.id, style: rowStyle },
|
|
1450
|
+
h('div', { style: { flex: 1, minWidth: 0 } },
|
|
1451
|
+
h('div', { style: lineStyle }, meta.title),
|
|
1452
|
+
h('div', { style: { opacity: 0.6, fontSize: 11 } },
|
|
1453
|
+
(meta.author ? meta.author + ' · ' : '') + (meta.chapters ? meta.chapters.length : 0) + tr('chapterCount')
|
|
1454
|
+
+ (meta.online ? t('onlineTag') : ' · ' + Math.max(1, Math.round((meta.chars || 0) / 10000)) + t('wordsWan'))
|
|
1455
|
+
+ (downloading ? ' · ' + t('downloadingShelf') + (s.importProgress ? ' ' + s.importProgress : '') : '')
|
|
1456
|
+
+ (current ? ' · ' + tr('currentReading') : ''))),
|
|
1457
|
+
h('button', { type: 'button', onClick: () => openBook(meta.id), style: { ...smallBtn, fontWeight: current ? 600 : 400 } }, tr('openBook')),
|
|
1458
|
+
// 下载中把下载按钮换成「停止」:只停下载,不删书
|
|
1459
|
+
downloading
|
|
1460
|
+
? h('button', {
|
|
1461
|
+
type: 'button',
|
|
1462
|
+
onClick: () => { cancelDownload(meta.id); store.set({ importProgress: '', notice: t('downloadStopped') }); },
|
|
1463
|
+
style: { ...smallBtn, color: '#c0392b' },
|
|
1464
|
+
}, t('stopLabel'))
|
|
1465
|
+
: h('button', { type: 'button', onClick: () => exportBook(meta.id, meta.title), style: smallBtn }, '💾'),
|
|
1466
|
+
h('button', { type: 'button', onClick: () => removeBook(meta.id), style: smallBtn }, '✕')
|
|
1467
|
+
);
|
|
1468
|
+
})
|
|
1469
|
+
),
|
|
1470
|
+
s.notice ? h('div', { style: noticeStyle, onClick: () => store.set({ notice: '' }) }, s.notice) : null
|
|
1471
|
+
);
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
// ---- 书源管理:列表 + 新增 / 编辑 / 删除 ----
|
|
1475
|
+
function sourcesView() {
|
|
1476
|
+
const editing = s.editingSource;
|
|
1477
|
+
if (editing) {
|
|
1478
|
+
return h('div', { style: viewStyle },
|
|
1479
|
+
h('div', { style: viewHeader },
|
|
1480
|
+
toolBtn('← ' + tr('back'), () => store.set({ editingSource: null, notice: '' })),
|
|
1481
|
+
h('span', { style: { flex: 1, fontWeight: 600 } }, (editing.index >= 0 ? t('sourceEditTitle') : t('sourceAddTitle'))),
|
|
1482
|
+
toolBtn(t('saveLabel'), saveSourceInEditor),
|
|
1483
|
+
toolBtn('✕', closePanel)
|
|
1484
|
+
),
|
|
1485
|
+
h('div', { style: { fontSize: 11, opacity: 0.7, lineHeight: 1.6 } },
|
|
1486
|
+
t('sourceEditorHint')),
|
|
1487
|
+
h('textarea', {
|
|
1488
|
+
value: editing.json, spellCheck: false,
|
|
1489
|
+
onChange: e => store.set({ editingSource: { ...store.get().editingSource, json: e.target.value } }),
|
|
1490
|
+
style: { flex: 1, minHeight: 160, width: '100%', boxSizing: 'border-box', fontFamily: 'monospace', fontSize: 11, border: '1px solid rgba(120,140,170,0.45)', borderRadius: 6, background: 'transparent', color: 'inherit', padding: '6px 8px', resize: 'vertical' },
|
|
1491
|
+
}),
|
|
1492
|
+
s.notice ? h('div', { style: noticeStyle, onClick: () => store.set({ notice: '' }) }, s.notice) : null
|
|
1493
|
+
);
|
|
1494
|
+
}
|
|
1495
|
+
const customs = s.customSources || [];
|
|
1496
|
+
const builtins = BUILTIN_SOURCES || [];
|
|
1497
|
+
const community = s.communitySources || [];
|
|
1498
|
+
const okCount = community.filter(x => x.status === 'ok').length;
|
|
1499
|
+
return h('div', { style: viewStyle },
|
|
1500
|
+
h('div', { style: viewHeader },
|
|
1501
|
+
toolBtn('← ' + tr('back'), () => store.set({ panelView: 'search' })),
|
|
1502
|
+
h('span', { style: { flex: 1, fontWeight: 600 } }, t('sourcesManageTitle')),
|
|
1503
|
+
toolBtn(t('sourceAdd'), () => store.set({ editingSource: { index: -1, json: '' }, notice: '' })),
|
|
1504
|
+
toolBtn('✕', closePanel)
|
|
1505
|
+
),
|
|
1506
|
+
h('div', { style: { fontSize: 11, opacity: 0.7 } },
|
|
1507
|
+
t('sourcesSummary', { b: builtins.length, c: community.length, ok: okCount, n: customs.length })),
|
|
1508
|
+
h('div', { style: { flex: 1, minHeight: 0, overflowY: 'auto' } },
|
|
1509
|
+
h('div', { style: { opacity: 0.6, fontSize: 11, margin: '6px 0 2px' } }, t('sourcesBuiltinGroup')),
|
|
1510
|
+
builtins.map((x) => h('div', { key: 'b:' + x.id, style: rowStyle },
|
|
1511
|
+
h('div', { style: { flex: 1, minWidth: 0 } },
|
|
1512
|
+
h('div', { style: lineStyle }, x.name),
|
|
1513
|
+
h('div', { style: { opacity: 0.55, fontSize: 11 } }, t('sourcesBuiltinTag'))))),
|
|
1514
|
+
h('div', { style: { opacity: 0.6, fontSize: 11, margin: '10px 0 2px' } }, t('sourcesCustomGroup')),
|
|
1515
|
+
customs.length === 0
|
|
1516
|
+
? h('div', { style: { opacity: 0.55, fontSize: 11, padding: '4px 0' } }, t('sourcesCustomEmpty'))
|
|
1517
|
+
: customs.map((x, i) => h('div', { key: 'c:' + i, style: rowStyle },
|
|
1518
|
+
h('div', { style: { flex: 1, minWidth: 0 } },
|
|
1519
|
+
h('div', { style: lineStyle }, x.bookSourceName || x.name || t('sourceNameFallback', { n: i + 1 })),
|
|
1520
|
+
h('div', { style: { opacity: 0.55, fontSize: 11 } }, x.bookSourceUrl || '')),
|
|
1521
|
+
h('button', { type: 'button', onClick: () => store.set({ editingSource: { index: i, json: JSON.stringify(x, null, 2) }, notice: '' }), style: smallBtn }, t('editLabel')),
|
|
1522
|
+
h('button', { type: 'button', onClick: () => removeSource(i), style: smallBtn }, t('deleteLabel'))
|
|
1523
|
+
)),
|
|
1524
|
+
h('div', { style: { opacity: 0.6, fontSize: 11, margin: '10px 0 2px' } }, t('sourcesCommunityGroup', { n: community.length })),
|
|
1525
|
+
community.map((x) => {
|
|
1526
|
+
const on = x.enabled !== false;
|
|
1527
|
+
return h('div', { key: 'm:' + x.id, style: rowStyle },
|
|
1528
|
+
h('div', { style: { flex: 1, minWidth: 0 } },
|
|
1529
|
+
h('div', { style: lineStyle }, (x.status === 'ok' ? '✔ ' : (x.status === 'partial' ? '△ ' : '? ')) + x.name),
|
|
1530
|
+
h('div', { style: { opacity: 0.55, fontSize: 11 } }, x.host + (on ? '' : t('sourceDisabledTag')))),
|
|
1531
|
+
h('button', { type: 'button', onClick: () => toggleCommunitySource(x.id), style: smallBtn }, on ? t('sourceDisable') : t('sourceEnable')),
|
|
1532
|
+
h('button', { type: 'button', onClick: () => removeCommunitySource(x.id), style: smallBtn }, t('deleteLabel'))
|
|
1533
|
+
);
|
|
1534
|
+
})
|
|
1535
|
+
),
|
|
1536
|
+
s.notice ? h('div', { style: noticeStyle, onClick: () => store.set({ notice: '' }) }, s.notice) : null
|
|
1537
|
+
);
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
const mainView = s.panelView === 'search' ? searchView()
|
|
1541
|
+
: s.panelView === 'sources' ? sourcesView()
|
|
1542
|
+
: s.panelView === 'shelf' ? shelfView()
|
|
1543
|
+
: readView();
|
|
1544
|
+
|
|
633
1545
|
// 工具栏:置于窗口底部(用户要求),拖动它仍可移动整个面板
|
|
634
1546
|
const toolbar = h('div', {
|
|
635
1547
|
onMouseDown: (e) => {
|
|
@@ -652,38 +1564,21 @@ window.__ModuleLoader__.load({
|
|
|
652
1564
|
store.set({ pinned: !s.pinned }); persist();
|
|
653
1565
|
}),
|
|
654
1566
|
toolBtn(tr('prevChapter'), () => goChapter(-1), !s.book || s.chapterIndex <= 0),
|
|
655
|
-
//
|
|
1567
|
+
// 章节下拉:按钮只负责开合,弹层在根节点外层用 fixed 渲染(见 chapterMenu)
|
|
656
1568
|
h('div', { style: { position: 'relative' } },
|
|
657
1569
|
h('button', {
|
|
658
|
-
type: 'button', disabled: !s.book,
|
|
659
|
-
onClick:
|
|
1570
|
+
ref: chapterBtnRef, type: 'button', disabled: !s.book,
|
|
1571
|
+
onClick: toggleChapterMenu,
|
|
660
1572
|
style: {
|
|
661
1573
|
maxWidth: 150, border: '1px solid rgba(120,140,170,0.4)', borderRadius: 6,
|
|
662
1574
|
background: 'transparent', color: 'inherit', fontSize: 12, padding: '2px 6px',
|
|
663
1575
|
cursor: s.book ? 'pointer' : 'default', opacity: s.book ? 1 : 0.4,
|
|
664
1576
|
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
|
665
1577
|
},
|
|
666
|
-
}, s.book && s.book.chapters[s.chapterIndex] ? s.book.chapters[s.chapterIndex].title : tr('chapterPlaceholder'), ' ▾')
|
|
667
|
-
chapterMenuOpen && s.book ? h('div', {
|
|
668
|
-
style: {
|
|
669
|
-
position: 'absolute', left: 0, bottom: '100%', zIndex: 5,
|
|
670
|
-
maxHeight: 220, overflowY: 'auto', minWidth: 160,
|
|
671
|
-
border: '1px solid rgba(120,140,170,0.45)', borderRadius: 6,
|
|
672
|
-
background: isSettings ? panelBg : readerBg, color: isSettings ? panelColor : eff.color,
|
|
673
|
-
boxShadow: '0 2px 10px rgba(0,0,0,0.25)',
|
|
674
|
-
},
|
|
675
|
-
}, s.book.chapters.map((c, i) => h('button', {
|
|
676
|
-
key: i, type: 'button',
|
|
677
|
-
onClick: () => { store.set({ chapterIndex: i, pageIndex: 0 }); persist(); setChapterMenuOpen(false); },
|
|
678
|
-
style: {
|
|
679
|
-
display: 'block', width: '100%', textAlign: 'left', border: 'none',
|
|
680
|
-
background: i === s.chapterIndex ? 'rgba(120,140,170,0.22)' : 'transparent',
|
|
681
|
-
color: 'inherit', fontSize: 12, padding: '4px 8px', cursor: 'pointer',
|
|
682
|
-
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
|
683
|
-
},
|
|
684
|
-
}, c.title))) : null
|
|
1578
|
+
}, s.book && s.book.chapters[s.chapterIndex] ? s.book.chapters[s.chapterIndex].title : tr('chapterPlaceholder'), ' ▾')
|
|
685
1579
|
),
|
|
686
1580
|
toolBtn(tr('nextChapter'), () => goChapter(1), !s.book || s.chapterIndex >= s.book.chapters.length - 1),
|
|
1581
|
+
toolBtn('📚 ' + tr('shelfTitle'), () => store.set({ panelView: 'shelf', settingsOpen: false, open: true })),
|
|
687
1582
|
h('span', { style: { flex: 1, minWidth: 4 } }),
|
|
688
1583
|
h('span', { style: { opacity: 0.75, whiteSpace: 'nowrap' } },
|
|
689
1584
|
s.book ? `${s.chapterIndex + 1}/${s.book.chapters.length}${tr('chapterCount')} · ${pageIndex + 1}/${pageCount}${tr('page')}` : ''),
|
|
@@ -694,43 +1589,57 @@ window.__ModuleLoader__.load({
|
|
|
694
1589
|
})
|
|
695
1590
|
);
|
|
696
1591
|
|
|
697
|
-
|
|
1592
|
+
// 章节弹层:fixed 定位在根节点外层,不会被面板的 overflow:hidden 裁掉
|
|
1593
|
+
const chapterMenu = chapterMenuOpen && s.book && chapterMenuRect && !isLarge ? h('div', {
|
|
1594
|
+
ref: chapterMenuRef,
|
|
1595
|
+
style: {
|
|
1596
|
+
position: 'fixed', left: chapterMenuRect.left, bottom: chapterMenuRect.bottom,
|
|
1597
|
+
width: chapterMenuRect.width, maxHeight: chapterMenuRect.maxHeight,
|
|
1598
|
+
overflowY: 'auto', zIndex: 100001,
|
|
1599
|
+
border: '1px solid rgba(120,140,170,0.45)', borderRadius: 6,
|
|
1600
|
+
background: readerBg, color: eff.color,
|
|
1601
|
+
boxShadow: '0 2px 10px rgba(0,0,0,0.25)',
|
|
1602
|
+
},
|
|
1603
|
+
}, s.book.chapters.map((c, i) => h('button', {
|
|
1604
|
+
key: i, type: 'button',
|
|
1605
|
+
onClick: () => {
|
|
1606
|
+
if (s.book && s.book.online) { chapterText = ''; store.set({ chapterIndex: i, pageIndex: 0, textVersion: (s.textVersion || 0) + 1 }); }
|
|
1607
|
+
else store.set({ chapterIndex: i, pageIndex: 0 });
|
|
1608
|
+
persist(); setChapterMenuOpen(false);
|
|
1609
|
+
},
|
|
1610
|
+
style: {
|
|
1611
|
+
display: 'block', width: '100%', textAlign: 'left', border: 'none',
|
|
1612
|
+
background: i === s.chapterIndex ? 'rgba(120,140,170,0.22)' : 'transparent',
|
|
1613
|
+
color: 'inherit', fontSize: 12, padding: '4px 8px', cursor: 'pointer',
|
|
1614
|
+
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
|
1615
|
+
},
|
|
1616
|
+
}, c.title))) : null;
|
|
1617
|
+
|
|
1618
|
+
return h(React.Fragment, null, h('div', {
|
|
698
1619
|
style: wrapStyle,
|
|
699
1620
|
onMouseEnter: () => cancelHide(), // 鼠标进入阅读区,取消收起
|
|
700
|
-
|
|
1621
|
+
// 弹窗里的书架/找书需要持续操作、章节弹层在面板之外,这两种情况鼠标离开都不收起
|
|
1622
|
+
onMouseLeave: () => {
|
|
1623
|
+
if (isPopup || chapterMenuOpen) return;
|
|
1624
|
+
// 刚点了弹窗里的「返回」:鼠标还在原弹窗位置,不算离开阅读区
|
|
1625
|
+
if (keepOpenOnLeave) { keepOpenOnLeave = false; return; }
|
|
1626
|
+
scheduleHide();
|
|
1627
|
+
},
|
|
701
1628
|
onDragOver: (e) => e.preventDefault(),
|
|
702
1629
|
onDrop: onDrop,
|
|
703
1630
|
},
|
|
704
|
-
//
|
|
705
|
-
|
|
706
|
-
onClick: onReadClick,
|
|
707
|
-
style: {
|
|
708
|
-
position: 'relative', flex: 1, overflow: 'hidden', padding: '2px 14px',
|
|
709
|
-
fontSize: eff.fontSize, lineHeight: eff.lineHeight, cursor: 'pointer',
|
|
710
|
-
},
|
|
711
|
-
},
|
|
712
|
-
!s.book
|
|
713
|
-
? h('div', { style: { opacity: 0.7, fontSize: 13, lineHeight: 1.6 } }, tr('importHint'))
|
|
714
|
-
: (!fullText
|
|
715
|
-
? h('div', null,
|
|
716
|
-
h('div', { style: { opacity: 0.7, fontSize: 12, marginBottom: 4 } }, tr('reopenHint')),
|
|
717
|
-
h('button', {
|
|
718
|
-
type: 'button', onClick: () => fileRef.current && fileRef.current.click(),
|
|
719
|
-
style: { border: '1px solid rgba(120,140,170,0.4)', background: 'transparent', color: 'inherit', borderRadius: 6, fontSize: 12, padding: '2px 8px', cursor: 'pointer' },
|
|
720
|
-
}, tr('import'))
|
|
721
|
-
)
|
|
722
|
-
: h('div', { style: { whiteSpace: 'pre-wrap', wordBreak: 'break-word', userSelect: 'text' } }, pageText)),
|
|
723
|
-
h('div', { style: { position: 'absolute', left: 0, top: 0, bottom: 0, width: '28%', display: 'flex', alignItems: 'center', pointerEvents: 'none' } },
|
|
724
|
-
h('span', { style: { opacity: 0.15, fontSize: 22, paddingLeft: 4 } }, tr('prevPage'))),
|
|
725
|
-
h('div', { style: { position: 'absolute', right: 0, top: 0, bottom: 0, width: '28%', display: 'flex', alignItems: 'center', justifyContent: 'flex-end', pointerEvents: 'none' } },
|
|
726
|
-
h('span', { style: { opacity: 0.15, fontSize: 22, paddingRight: 4 } }, tr('nextPage'))),
|
|
727
|
-
// 边缘缩放手柄:右边缘调宽、下边缘调高、右下角同时调
|
|
728
|
-
h('div', { title: tr('resizeHint'), onMouseDown: e => startResize(e, 'e'), onClick: e => e.stopPropagation(), style: { position: 'absolute', right: 0, top: 10, bottom: 10, width: 6, cursor: 'ew-resize', zIndex: 4 } }),
|
|
729
|
-
h('div', { title: tr('resizeHint'), onMouseDown: e => startResize(e, 's'), onClick: e => e.stopPropagation(), style: { position: 'absolute', bottom: 0, left: 10, right: 10, height: 6, cursor: 'ns-resize', zIndex: 4 } }),
|
|
730
|
-
h('div', { title: tr('resizeHint'), onMouseDown: e => startResize(e, 'se'), onClick: e => e.stopPropagation(), style: { position: 'absolute', right: 0, bottom: 0, width: 16, height: 16, cursor: 'nwse-resize', zIndex: 5 } })
|
|
731
|
-
) : null,
|
|
1631
|
+
// 阅读区只在阅读视图渲染;书架/找书/书源改走下面的独立大弹窗
|
|
1632
|
+
s.settingsOpen || isPopup ? null : mainView,
|
|
732
1633
|
// 隐藏的文件选择 input
|
|
733
1634
|
h('input', { ref: fileRef, type: 'file', accept: '.txt,text/plain', style: { display: 'none' }, onChange: onFile }),
|
|
1635
|
+
// 书架/找书/书源:与设置面板同尺寸的独立弹窗,不再受输入框大小限制
|
|
1636
|
+
isPopup && !s.settingsOpen ? h('div', {
|
|
1637
|
+
style: {
|
|
1638
|
+
flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column',
|
|
1639
|
+
background: panelBg, color: panelColor,
|
|
1640
|
+
fontFamily: peff.fontFamily, fontSize: peff.fontSize, lineHeight: peff.lineHeight,
|
|
1641
|
+
},
|
|
1642
|
+
}, mainView) : null,
|
|
734
1643
|
// 设置面板:独立大面板完整展示
|
|
735
1644
|
s.settingsOpen ? h('div', {
|
|
736
1645
|
style: {
|
|
@@ -770,7 +1679,7 @@ window.__ModuleLoader__.load({
|
|
|
770
1679
|
toolBtn(tr('profileSelect'), () => {
|
|
771
1680
|
updateStyle({ ...DEFAULT_STYLE, ...(s.profiles[name] || {}) });
|
|
772
1681
|
store.set({ pos: null });
|
|
773
|
-
if (s.book) store.set({ book: { ...s.book, chapters: detectChapters(fullText, store.get().style.customRegex) }, chapterIndex: 0, pageIndex: 0 });
|
|
1682
|
+
if (s.book && fullText) store.set({ book: { ...s.book, chapters: detectChapters(fullText, store.get().style.customRegex) }, chapterIndex: 0, pageIndex: 0 });
|
|
774
1683
|
store.set({ notice: t('profileApplied', { name }) });
|
|
775
1684
|
persist();
|
|
776
1685
|
}),
|
|
@@ -908,19 +1817,19 @@ window.__ModuleLoader__.load({
|
|
|
908
1817
|
toolBtn(tr('reset'), () => {
|
|
909
1818
|
updateStyle({ ...DEFAULT_STYLE });
|
|
910
1819
|
store.set({ pos: null });
|
|
911
|
-
if (s.book) store.set({ book: { ...s.book, chapters: detectChapters(fullText, '') }, chapterIndex: 0, pageIndex: 0 });
|
|
1820
|
+
if (s.book && fullText) store.set({ book: { ...s.book, chapters: detectChapters(fullText, '') }, chapterIndex: 0, pageIndex: 0 });
|
|
912
1821
|
}),
|
|
913
1822
|
toolBtn(tr('resetPos'), () => { store.set({ pos: null }); persist(); }),
|
|
914
1823
|
toolBtn(tr('done'), () => {
|
|
915
|
-
if (s.book) store.set({ book: { ...s.book, chapters: detectChapters(fullText, store.get().style.customRegex) } });
|
|
1824
|
+
if (s.book && fullText) store.set({ book: { ...s.book, chapters: detectChapters(fullText, store.get().style.customRegex) } });
|
|
916
1825
|
store.set({ settingsOpen: false }); persist();
|
|
917
1826
|
})
|
|
918
1827
|
),
|
|
919
1828
|
)
|
|
920
1829
|
) : null,
|
|
921
|
-
//
|
|
922
|
-
toolbar
|
|
923
|
-
);
|
|
1830
|
+
// 工具栏固定在窗口最下方(弹窗模式不显示阅读工具栏)
|
|
1831
|
+
isPopup ? null : toolbar
|
|
1832
|
+
), chapterMenu);
|
|
924
1833
|
|
|
925
1834
|
function settingRow(label, control, value) {
|
|
926
1835
|
return h('div', {
|
|
@@ -968,6 +1877,9 @@ window.__ModuleLoader__.load({
|
|
|
968
1877
|
}
|
|
969
1878
|
}
|
|
970
1879
|
|
|
1880
|
+
// 异步恢复书架与上次在读的书;不阻塞首帧,失败也不影响导入
|
|
1881
|
+
hydrate().catch(() => { /* 首次启动时书库不可用,忽略 */ });
|
|
1882
|
+
|
|
971
1883
|
ctx.slots.inject('conversation.input.left', () => ctx.slots.register({
|
|
972
1884
|
name: 'conversation.input.left', id: 'novel-reader-trigger', order: 6, label: () => tr('name'), locale: NS,
|
|
973
1885
|
}, Trigger));
|