@yyds-dudu/dsh-novel-reader 0.0.0-stage → 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 +153 -2
- package/client.js +1893 -0
- package/cordis.patch.yml +8 -0
- package/docs/DETAIL.md +1 -0
- package/docs/SOURCES.md +90 -0
- package/docs/preview.svg +15 -0
- package/docs/screenshot-1.png +0 -0
- package/docs/screenshot-2.png +0 -0
- package/docs/screenshot-3.png +0 -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/icon.svg +7 -0
- package/index.js +197 -0
- 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 +156 -0
- package/locale/zh.json +156 -0
- package/package.json +68 -4
package/client.js
ADDED
|
@@ -0,0 +1,1893 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
// 与包名一致:加载器按 manifest 包名组织浏览器模块图,id 不一致会导致模块无法挂载。
|
|
3
|
+
id: '@yyds-dudu/dsh-novel-reader',
|
|
4
|
+
factory(require) {
|
|
5
|
+
const React = require('react');
|
|
6
|
+
const h = React.createElement;
|
|
7
|
+
const { useState, useEffect, useMemo, useRef } = React;
|
|
8
|
+
|
|
9
|
+
const NS = '@local/dsh-novel-reader';
|
|
10
|
+
const STORE_KEY = NS + ':state';
|
|
11
|
+
const TEXT_KEY = NS + ':text'; // 全文单独存:大文件下翻页只写轻量元数据,避免每页重复序列化整本小说
|
|
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
|
+
};
|
|
30
|
+
|
|
31
|
+
// 给任意颜色套上透明度:alpha>=1 原样返回;支持 #rgb/#rrggbb 与 rgb()/rgba()
|
|
32
|
+
function withOpacity(color, alpha) {
|
|
33
|
+
if (alpha == null || alpha >= 1) return color;
|
|
34
|
+
const a = Math.max(0, Math.min(1, alpha));
|
|
35
|
+
if (typeof color !== 'string') return color;
|
|
36
|
+
const hex = color.match(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/);
|
|
37
|
+
if (hex) {
|
|
38
|
+
let h = hex[1];
|
|
39
|
+
if (h.length === 3) h = h.split('').map(c => c + c).join('');
|
|
40
|
+
const r = parseInt(h.slice(0, 2), 16), g = parseInt(h.slice(2, 4), 16), b = parseInt(h.slice(4, 6), 16);
|
|
41
|
+
return `rgba(${r}, ${g}, ${b}, ${a})`;
|
|
42
|
+
}
|
|
43
|
+
const m = color.match(/rgba?\(\s*(\d+)[,\s]+(\d+)[,\s]+(\d+)/i);
|
|
44
|
+
if (m) return `rgba(${m[1]}, ${m[2]}, ${m[3]}, ${a})`;
|
|
45
|
+
return color;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 空值 = 跟随输入框真实样式。字体/尺寸/配色全部从输入框计算样式读取,做到完美隐蔽。
|
|
49
|
+
const DEFAULT_STYLE = {
|
|
50
|
+
fontSize: 0, lineHeight: 0, fontFamily: '',
|
|
51
|
+
textColor: '', bgColor: '', bgOpacity: 1, width: 0, height: 0, customRegex: '',
|
|
52
|
+
// 设置面板独立样式(与阅读区一一对应,互不干扰)。空值 = 跟随输入框真实样式。
|
|
53
|
+
panelFontSize: 0, panelLineHeight: 0, panelFontFamily: '',
|
|
54
|
+
panelTextColor: '', panelBgColor: '', panelWidth: 0, panelHeight: 0,
|
|
55
|
+
panelRadiusValue: '', // 设置面板圆角;空字符串 = 跟随输入框
|
|
56
|
+
panelBorderVisible: true, // 设置面板边框开关
|
|
57
|
+
radiusValue: '', // 阅读区圆角像素值;空字符串 = 跟随输入框真实圆角
|
|
58
|
+
borderVisible: true, // 阅读区是否显示窗口边框
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const DICT = {
|
|
62
|
+
en: {
|
|
63
|
+
name: 'Novel', import: 'Import txt', importing: 'Importing...', settings: 'Settings', close: 'Close',
|
|
64
|
+
prevChapter: 'Prev ch.', nextChapter: 'Next ch.', prevPage: '‹', nextPage: '›',
|
|
65
|
+
chapterPlaceholder: 'Select a chapter',
|
|
66
|
+
noBook: 'No book imported', importHint: 'Click Import txt or drop a .txt file here (UTF-8 / GBK)',
|
|
67
|
+
settingsTitle: 'Reading settings', followInput: 'Follow input style',
|
|
68
|
+
followInputHint: 'Match the input box size, colors and font',
|
|
69
|
+
panelStyleGroup: 'Appearance', readerStyleGroup: 'Reading area',
|
|
70
|
+
panelGroup: 'Settings panel style', readerGroup: 'Reading area style',
|
|
71
|
+
readerTextGroup: 'Text & layout', readerSizeGroup: 'Window size', chapterGroup: 'Chapter detection', actionGroup: 'Actions',
|
|
72
|
+
panelTextGroup: 'Panel text & font', panelSizeGroup: 'Panel size',
|
|
73
|
+
readerFollowLabel: 'Reading area follows input', panelFollowLabel: 'Panel follows input',
|
|
74
|
+
panelFontSize: 'Font size', panelLineHeight: 'Line height', panelFontFamily: 'Font',
|
|
75
|
+
panelTextColor: 'Panel text', panelBgColor: 'Panel background',
|
|
76
|
+
fontSize: 'Font size', lineHeight: 'Line height', fontFamily: 'Font',
|
|
77
|
+
textColor: 'Text color', backgroundColor: 'Background', bgOpacity: 'Background opacity', windowWidth: 'Panel width',
|
|
78
|
+
windowHeight: 'Panel height', customChapterRegex: 'Chapter regex',
|
|
79
|
+
borderStyleGroup: 'Border', borderRadius: 'Corner radius', borderVisible: 'Show border',
|
|
80
|
+
readerBorderGroup: 'Reading area border', panelBorderGroup: 'Settings panel border',
|
|
81
|
+
pin: 'Pin open', unpin: 'Unpin',
|
|
82
|
+
profileGroup: 'Saved profiles', profileName: 'Profile name', profileSave: 'Save current',
|
|
83
|
+
profileSelect: 'Apply', profileDelete: 'Delete', profileNone: 'No saved profiles yet',
|
|
84
|
+
profileSaved: 'Saved: {name}', profileDeleted: 'Deleted: {name}', profileApplied: 'Applied: {name}',
|
|
85
|
+
profileEmptyName: 'Enter a profile name first', profileConfirmDelete: 'Delete profile "{name}"?',
|
|
86
|
+
regexHint: 'One regex per line; empty uses built-in rules', reset: 'Reset', resetPos: 'Reset position', done: 'Done',
|
|
87
|
+
chapterCount: 'ch', page: 'p', noChapters: 'No chapter detected; reading the whole file as one',
|
|
88
|
+
decodeError: 'Cannot decode this file (tried UTF-8 and GBK)', importFailed: 'Import failed',
|
|
89
|
+
byteUnavailable: 'Browser cannot read raw bytes and UTF-8 decoding failed. Re-save the file as UTF-8.',
|
|
90
|
+
styleTip: 'Click 📖 to open · Mouse out closes · Click again to reopen · Drag the bar to move · Drop a .txt to import',
|
|
91
|
+
resizeHint: 'Drag the window edge to resize; changes are saved automatically',
|
|
92
|
+
reopenHint: 'Book data was cleared by the browser; please re-import the same file to resume.',
|
|
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',
|
|
129
|
+
},
|
|
130
|
+
zh: {
|
|
131
|
+
name: '小说', import: '导入 txt', importing: '导入中…', settings: '设置', close: '收起',
|
|
132
|
+
prevChapter: '上一章', nextChapter: '下一章', prevPage: '‹', nextPage: '›',
|
|
133
|
+
chapterPlaceholder: '选择章节',
|
|
134
|
+
noBook: '尚未导入小说', importHint: '点击「导入 txt」或把 .txt 文件拖到这里(支持 UTF-8 / GBK)',
|
|
135
|
+
settingsTitle: '阅读设置', followInput: '跟随输入框样式',
|
|
136
|
+
followInputHint: '自动匹配输入框的尺寸、配色和字体',
|
|
137
|
+
panelStyleGroup: '外观', readerStyleGroup: '阅读区域',
|
|
138
|
+
panelGroup: '设置面板样式', readerGroup: '阅读区样式',
|
|
139
|
+
readerTextGroup: '阅读区文字与排版', readerSizeGroup: '阅读区尺寸', chapterGroup: '章节识别', actionGroup: '操作',
|
|
140
|
+
panelTextGroup: '面板文字与字体', panelSizeGroup: '面板尺寸',
|
|
141
|
+
readerFollowLabel: '阅读区跟随输入框', panelFollowLabel: '面板跟随输入框',
|
|
142
|
+
panelFontSize: '字号', panelLineHeight: '行距', panelFontFamily: '字体',
|
|
143
|
+
panelTextColor: '面板文字颜色', panelBgColor: '面板背景颜色',
|
|
144
|
+
fontSize: '字号', lineHeight: '行距', fontFamily: '字体',
|
|
145
|
+
textColor: '文字颜色', backgroundColor: '背景颜色', bgOpacity: '背景透明度', windowWidth: '面板宽度',
|
|
146
|
+
windowHeight: '面板高度', customChapterRegex: '章节识别正则',
|
|
147
|
+
borderStyleGroup: '窗口边框', borderRadius: '圆角大小', borderVisible: '显示边框',
|
|
148
|
+
readerBorderGroup: '阅读区边框', panelBorderGroup: '设置面板边框',
|
|
149
|
+
pin: '钉住常开', unpin: '取消钉住',
|
|
150
|
+
profileGroup: '已保存配置', profileName: '配置名称', profileSave: '保存当前配置',
|
|
151
|
+
profileSelect: '应用', profileDelete: '删除', profileNone: '暂无保存的配置',
|
|
152
|
+
profileSaved: '已保存:{name}', profileDeleted: '已删除:{name}', profileApplied: '已应用:{name}',
|
|
153
|
+
profileEmptyName: '请先输入配置名称', profileConfirmDelete: '确定删除配置「{name}」?',
|
|
154
|
+
regexHint: '每行一条正则;留空用内置规则', reset: '恢复默认', resetPos: '重置位置', done: '完成',
|
|
155
|
+
chapterCount: '章', page: '页', noChapters: '未识别到章节,整本作为一章阅读',
|
|
156
|
+
decodeError: '无法解码该文件(已尝试 UTF-8 与 GBK)', importFailed: '导入失败',
|
|
157
|
+
byteUnavailable: '浏览器无法读取原始字节且 UTF-8 解码失败,请将文件另存为 UTF-8。',
|
|
158
|
+
styleTip: '点击 📖 打开 · 鼠标移出收起 · 再点图标重开 · 拖动底部条移动 · 拖入 .txt 导入',
|
|
159
|
+
resizeHint: '拖动窗口边缘可调整大小,改动会自动保存',
|
|
160
|
+
reopenHint: '书籍正文已被浏览器清理,请重新导入同一文件继续阅读。',
|
|
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: ' 万字',
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
// ---- 章节识别 ----
|
|
201
|
+
const BUILTIN_PATTERNS = [
|
|
202
|
+
/^\s*第[零一二三四五六七八九十百千两0-9]+[章节回卷部篇集][^\n]{0,40}$/gm,
|
|
203
|
+
/^\s*(Chapter|CHAPTER|chapter)\s+[0-9零一二三四五六七八九十]+[^\n]{0,40}$/gm,
|
|
204
|
+
];
|
|
205
|
+
function detectChapters(text, custom) {
|
|
206
|
+
const patterns = BUILTIN_PATTERNS.slice();
|
|
207
|
+
if (custom) for (const line of custom.split('\n')) {
|
|
208
|
+
const s = line.trim(); if (!s) continue;
|
|
209
|
+
try { patterns.push(new RegExp(s, 'gm')); } catch (e) { /* 非法正则忽略 */ }
|
|
210
|
+
}
|
|
211
|
+
const points = [];
|
|
212
|
+
for (const re of patterns) {
|
|
213
|
+
re.lastIndex = 0; let m;
|
|
214
|
+
while ((m = re.exec(text)) !== null) {
|
|
215
|
+
points.push({ start: m.index, title: m[0].trim().slice(0, 40) || '开篇' });
|
|
216
|
+
if (m[0].length === 0) re.lastIndex++;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
points.sort((a, b) => a.start - b.start);
|
|
220
|
+
const uniq = [];
|
|
221
|
+
for (const p of points) if (!uniq.length || p.start - uniq[uniq.length - 1].start > 8) uniq.push(p);
|
|
222
|
+
if (!uniq.length) return [{ title: '开篇', start: 0, end: text.length }];
|
|
223
|
+
const chapters = [];
|
|
224
|
+
if (uniq[0].start > Math.min(2000, text.length * 0.05)) {
|
|
225
|
+
chapters.push({ title: '开篇', start: 0, end: uniq[0].start });
|
|
226
|
+
}
|
|
227
|
+
for (let i = 0; i < uniq.length; i++) {
|
|
228
|
+
chapters.push({ title: uniq[i].title, start: uniq[i].start, end: i + 1 < uniq.length ? uniq[i + 1].start : text.length });
|
|
229
|
+
}
|
|
230
|
+
return chapters.length ? chapters : [{ title: '开篇', start: 0, end: text.length }];
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ---- 排版优化:不沿用 txt 原排版,自动识别段落、合并硬换行、便于阅读 ----
|
|
234
|
+
function normalizeText(raw) {
|
|
235
|
+
const lines = raw.replace(/\r\n?/g, '\n').split('\n');
|
|
236
|
+
// 探测原文件排版风格:是否用「首行缩进两格」标记段落
|
|
237
|
+
const hasIndent = lines.some(l => /^[\u3000 ]{2,}/.test(l));
|
|
238
|
+
const out = [];
|
|
239
|
+
const isHeading = (s) => /^(第[零一二三四五六七八九十百千两0-9]+[章节回卷部篇集]|Chapter\s+\d|序章|楔子|番外|尾声|后记|PROLOGUE|EPILOGUE)/i.test(s);
|
|
240
|
+
for (let line of lines) {
|
|
241
|
+
const indented = /^[\u3000 ]{2,}/.test(line);
|
|
242
|
+
const content = line.replace(/^[\s\u3000]+|[\s\u3000]+$/g, '');
|
|
243
|
+
if (!content) {
|
|
244
|
+
if (out.length && out[out.length - 1] !== '') out.push(''); // 连续空行压成一个
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
// 有缩进标记时:带缩进/标题/空行后首行 = 新段,无缩进行 = 硬换行并入当前段
|
|
248
|
+
// 无缩进标记时:每行本就是作者分段,逐行独立,绝不合并成一整块
|
|
249
|
+
const newPara = isHeading(content) || (hasIndent ? indented : true) || !out.length || out[out.length - 1] === '';
|
|
250
|
+
if (newPara) out.push(content);
|
|
251
|
+
else out[out.length - 1] += content;
|
|
252
|
+
}
|
|
253
|
+
// 统一用空行分隔段落,阅读时段间距清晰
|
|
254
|
+
return out.filter((l, i) => l !== '' || (i > 0 && out[i - 1] !== '')).join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// ---- 分页:按窗口高度自适应,以「物理行」为单位切分 ----
|
|
258
|
+
// 不再按字符数估算(中英文混排会估偏,导致一页文字超出高度被裁掉看不到)。
|
|
259
|
+
// 每页最多放 lpp 个物理行,正好适配阅读区高度,放不下的整行移到下一页。
|
|
260
|
+
function layoutPages(text, eff) {
|
|
261
|
+
const fs = eff.fontSize || 14;
|
|
262
|
+
// 每行可容纳的字符数:中文按 1 个全角宽,英文/数字/半角标点按 0.55 宽估算
|
|
263
|
+
const cpl = Math.max(8, Math.floor((eff.width - 28) / fs));
|
|
264
|
+
// 每页行数:由阅读区高度决定(减去工具栏与内边距占用的高度)
|
|
265
|
+
const lpp = Math.max(2, Math.floor((eff.height - 40) / (fs * (eff.lineHeight || 1.6))));
|
|
266
|
+
const physical = [];
|
|
267
|
+
for (const line of String(text).split('\n')) {
|
|
268
|
+
if (line === '') { physical.push(''); continue; } // 空行(段落间距)单独占一行
|
|
269
|
+
let cur = '', w = 0;
|
|
270
|
+
for (const ch of line) {
|
|
271
|
+
const cw = /[\x00-\xff]/.test(ch) ? 0.55 : 1;
|
|
272
|
+
if (w + cw > cpl && cur) { physical.push(cur); cur = ''; w = 0; }
|
|
273
|
+
cur += ch; w += cw;
|
|
274
|
+
}
|
|
275
|
+
physical.push(cur);
|
|
276
|
+
}
|
|
277
|
+
const pages = [];
|
|
278
|
+
for (let i = 0; i < physical.length; i += lpp) {
|
|
279
|
+
pages.push(physical.slice(i, i + lpp).join('\n'));
|
|
280
|
+
}
|
|
281
|
+
return pages.length ? pages : [''];
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// ---- 共享 store ----
|
|
285
|
+
function createStore(initial) {
|
|
286
|
+
let state = initial; const ls = new Set();
|
|
287
|
+
return {
|
|
288
|
+
get: () => state,
|
|
289
|
+
set(patch) {
|
|
290
|
+
state = { ...state, ...(typeof patch === 'function' ? patch(state) : patch) };
|
|
291
|
+
for (const l of Array.from(ls)) l();
|
|
292
|
+
},
|
|
293
|
+
subscribe(l) { ls.add(l); return () => ls.delete(l); },
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
function useStore(store) {
|
|
297
|
+
const [s, setS] = useState(store.get());
|
|
298
|
+
useEffect(() => store.subscribe(() => setS(store.get())), [store]);
|
|
299
|
+
return s;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
return {
|
|
303
|
+
inject: ['slots', 'locale'],
|
|
304
|
+
apply(ctx) {
|
|
305
|
+
let tr = (k) => (DICT.zh[k] || DICT.en[k] || k);
|
|
306
|
+
// 按 DSH 现有插件写法:register(ns, { zh, en }),再 bind(ns) 取翻译函数
|
|
307
|
+
try {
|
|
308
|
+
ctx.locale.register(NS, { zh: DICT.zh, en: DICT.en });
|
|
309
|
+
const bound = ctx.locale.bind(NS);
|
|
310
|
+
tr = (k) => {
|
|
311
|
+
try { const v = bound(k); if (typeof v === 'string' && v) return v; } catch (e) { /* 回退本地字典 */ }
|
|
312
|
+
return DICT.zh[k] || DICT.en[k] || k;
|
|
313
|
+
};
|
|
314
|
+
} catch (e) { /* 本地字典回退 */ }
|
|
315
|
+
const t = (k, vars) => {
|
|
316
|
+
let v = tr(k);
|
|
317
|
+
if (vars) for (const key of Object.keys(vars)) v = String(v).replace('{' + key + '}', vars[key]);
|
|
318
|
+
return v;
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
// 多套样式配置:从独立 key 读取,损坏时回退空集
|
|
322
|
+
function loadProfiles() {
|
|
323
|
+
try {
|
|
324
|
+
const raw = localStorage.getItem(PROFILES_KEY);
|
|
325
|
+
const d = raw ? JSON.parse(raw) : null;
|
|
326
|
+
return d && typeof d === 'object' && !Array.isArray(d) ? d : {};
|
|
327
|
+
} catch (e) { return {}; }
|
|
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
|
+
}
|
|
339
|
+
function saveProfiles(p) {
|
|
340
|
+
try { localStorage.setItem(PROFILES_KEY, JSON.stringify(p)); } catch (e) { /* 存储不可用 */ }
|
|
341
|
+
store.set({ profiles: p });
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const store = createStore({
|
|
345
|
+
open: false, pinned: false, book: null, chapterIndex: 0, pageIndex: 0,
|
|
346
|
+
style: { ...DEFAULT_STYLE }, pos: null, settingsOpen: false, notice: '',
|
|
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),
|
|
356
|
+
});
|
|
357
|
+
// 点击图标打开;未钉住时鼠标移出阅读区即收起,需重新点击图标才能再次打开。
|
|
358
|
+
// 钉住后只能点工具栏「收起」关闭,移出不会收起。
|
|
359
|
+
// 用短延迟避免鼠标在图标与阅读区之间移动时闪烁;进入阅读区即取消收起。
|
|
360
|
+
let hideTimer = null;
|
|
361
|
+
let dragActive = false; // 正在拖动面板时暂停自动收起
|
|
362
|
+
let keepOpenOnLeave = false; // 从大弹窗返回阅读区时,忽略紧随其后的一次移出
|
|
363
|
+
function cancelHide() { if (hideTimer) { clearTimeout(hideTimer); hideTimer = null; } }
|
|
364
|
+
function scheduleHide() {
|
|
365
|
+
cancelHide();
|
|
366
|
+
hideTimer = setTimeout(() => {
|
|
367
|
+
hideTimer = null;
|
|
368
|
+
const st = store.get();
|
|
369
|
+
// 钉住、设置面板打开、或正在拖动时不自动收起
|
|
370
|
+
if (st.open && !st.pinned && !st.settingsOpen && !dragActive) store.set({ open: false, notice: '' });
|
|
371
|
+
}, 200);
|
|
372
|
+
}
|
|
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,不整本存
|
|
379
|
+
let anchorEl = null; // 触发图标的 DOM 节点,用于向上定位真实输入框
|
|
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
|
+
|
|
932
|
+
// 从图标向上找到真实编辑器,再读取它的矩形与计算样式(配色/字体/圆角)
|
|
933
|
+
function findEditorInfo() {
|
|
934
|
+
if (!anchorEl || typeof document === 'undefined') return null;
|
|
935
|
+
// 常见编辑器形态:原生 textarea / contenteditable / ProseMirror / CodeMirror / role=textbox
|
|
936
|
+
const EDIT_SEL = 'textarea, [contenteditable="true"], [contenteditable]:not([contenteditable="false"]), [role="textbox"], .ProseMirror, .cm-content';
|
|
937
|
+
const isEditor = (n) => n && (
|
|
938
|
+
n.tagName === 'TEXTAREA' ||
|
|
939
|
+
(n.getAttribute && n.getAttribute('contenteditable') === 'true') ||
|
|
940
|
+
(n.getAttribute && n.getAttribute('role') === 'textbox') ||
|
|
941
|
+
(n.matches && n.matches(EDIT_SEL))
|
|
942
|
+
);
|
|
943
|
+
let editor = null;
|
|
944
|
+
let node = anchorEl;
|
|
945
|
+
while (node && node !== document.body) {
|
|
946
|
+
if (isEditor(node)) { editor = node; break; }
|
|
947
|
+
if (node.querySelector) { const inner = node.querySelector(EDIT_SEL); if (inner) { editor = inner; break; } }
|
|
948
|
+
node = node.parentElement;
|
|
949
|
+
}
|
|
950
|
+
// 兜底:从图标向上没找到时,全局查找第一个可见编辑器
|
|
951
|
+
if ((!editor || !editor.getBoundingClientRect) && document.querySelectorAll) {
|
|
952
|
+
const cands = document.querySelectorAll(EDIT_SEL);
|
|
953
|
+
for (const c of cands) {
|
|
954
|
+
if (c.getBoundingClientRect && c.getBoundingClientRect().width) { editor = c; break; }
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
if (!editor || !editor.getBoundingClientRect) return null;
|
|
958
|
+
const cs = window.getComputedStyle ? window.getComputedStyle(editor) : null;
|
|
959
|
+
// 背景向上找第一个非透明色,保证取到输入框卡片的底色
|
|
960
|
+
let bg = ''; let bgNode = editor;
|
|
961
|
+
while (bgNode && bgNode !== document.body) {
|
|
962
|
+
const c = window.getComputedStyle ? window.getComputedStyle(bgNode) : null;
|
|
963
|
+
const v = c && c.backgroundColor;
|
|
964
|
+
if (v && v !== 'rgba(0, 0, 0, 0)' && v !== 'transparent' && v !== 'rgba(0,0,0,0)') { bg = v; break; }
|
|
965
|
+
bgNode = bgNode.parentElement;
|
|
966
|
+
}
|
|
967
|
+
// 圆角/边框/阴影:输入框卡片往往把这些画在外层容器上,向上找第一个「有效值」
|
|
968
|
+
// (textarea 自身常是 0px 圆角、无边框,直接取它会导致圆角/边框丢失)
|
|
969
|
+
let radius = '', border = '', shadow = '';
|
|
970
|
+
let bnode = editor;
|
|
971
|
+
while (bnode && bnode !== document.body) {
|
|
972
|
+
const c = window.getComputedStyle ? window.getComputedStyle(bnode) : null;
|
|
973
|
+
if (c) {
|
|
974
|
+
const br = c.borderRadius || '';
|
|
975
|
+
if (!radius && br && parseFloat(br) > 0) radius = br;
|
|
976
|
+
const bw = parseFloat(c.borderTopWidth) || 0;
|
|
977
|
+
const bs = c.borderTopStyle;
|
|
978
|
+
if (!border && bw > 0 && bs && bs !== 'none') {
|
|
979
|
+
border = c.borderTopWidth + ' ' + bs + ' ' + c.borderTopColor;
|
|
980
|
+
}
|
|
981
|
+
if (!shadow && c.boxShadow && c.boxShadow !== 'none') shadow = c.boxShadow;
|
|
982
|
+
}
|
|
983
|
+
if (radius && border && shadow) break;
|
|
984
|
+
bnode = bnode.parentElement;
|
|
985
|
+
}
|
|
986
|
+
// 定位基准:用提供背景的「视觉卡片」矩形,而非内部 textarea 的矩形。
|
|
987
|
+
// 用户看到的“输入框”是这张卡片;textarea 通常有内边距、与卡片存在偏移,
|
|
988
|
+
// 用卡片矩形才能让 XY / 宽高与输入框完全对齐,消除像素偏移。
|
|
989
|
+
const boxEl = (bgNode && bgNode !== document.body && bgNode.getBoundingClientRect) ? bgNode : editor;
|
|
990
|
+
const r = boxEl.getBoundingClientRect();
|
|
991
|
+
if (!r || !r.width) return null;
|
|
992
|
+
return {
|
|
993
|
+
x: r.left, y: r.top, width: r.width, height: r.height,
|
|
994
|
+
bg, color: (cs && cs.color) || '', fontFamily: (cs && cs.fontFamily) || '',
|
|
995
|
+
fontSize: cs ? (parseFloat(cs.fontSize) || 0) : 0,
|
|
996
|
+
lineHeight: cs && cs.lineHeight && cs.lineHeight !== 'normal' ? (parseFloat(cs.lineHeight) || 0) : 0,
|
|
997
|
+
radius: radius || '8px', border, shadow,
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
// 翻页只写轻量状态;正文放 IndexedDB,localStorage 只留书号和进度
|
|
1002
|
+
function persist() {
|
|
1003
|
+
const s = store.get();
|
|
1004
|
+
const base = {
|
|
1005
|
+
style: s.style, pos: s.pos, pinned: s.pinned,
|
|
1006
|
+
bookId: s.book ? s.book.id : null,
|
|
1007
|
+
chapterIndex: s.chapterIndex, pageIndex: s.pageIndex,
|
|
1008
|
+
};
|
|
1009
|
+
try { localStorage.setItem(STORE_KEY, JSON.stringify(base)); } catch (e) { /* 存储不可用 */ }
|
|
1010
|
+
}
|
|
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; }
|
|
1021
|
+
}
|
|
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
|
+
}
|
|
1042
|
+
|
|
1043
|
+
// 读取文件:显式按钮 / 拖放共用
|
|
1044
|
+
async function readFile(file) {
|
|
1045
|
+
if (!file) return;
|
|
1046
|
+
store.set({ notice: tr('importing') });
|
|
1047
|
+
try {
|
|
1048
|
+
let text = '';
|
|
1049
|
+
const buf = await file.arrayBuffer();
|
|
1050
|
+
const bytes = new Uint8Array(buf);
|
|
1051
|
+
if (bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF) {
|
|
1052
|
+
text = new TextDecoder('utf-8').decode(bytes.subarray(3));
|
|
1053
|
+
} else {
|
|
1054
|
+
try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
|
|
1055
|
+
catch (err) {
|
|
1056
|
+
try { text = new TextDecoder('gbk').decode(bytes); }
|
|
1057
|
+
catch (err2) { throw new Error(tr('decodeError')); }
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
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' });
|
|
1066
|
+
} catch (err) {
|
|
1067
|
+
store.set({ notice: (err && err.message) || tr('importFailed') });
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// ---- 触发图标:只保留一个图标,无文字 ----
|
|
1072
|
+
function Trigger() {
|
|
1073
|
+
const s = useStore(store);
|
|
1074
|
+
return h('button', {
|
|
1075
|
+
type: 'button', title: tr('name'),
|
|
1076
|
+
ref: (node) => { anchorEl = node; },
|
|
1077
|
+
// 只有点击才打开/关闭阅读区;悬浮不触发打开
|
|
1078
|
+
onClick: (e) => {
|
|
1079
|
+
e.stopPropagation();
|
|
1080
|
+
cancelHide();
|
|
1081
|
+
const cur = store.get();
|
|
1082
|
+
// 钉住状态下图标不能关闭阅读区,只能点工具栏「收起」关闭
|
|
1083
|
+
if (cur.open && cur.pinned) return;
|
|
1084
|
+
// 打开时清除旧位置:未钉住的阅读区每次都精确贴合输入框当前位置
|
|
1085
|
+
store.set({ open: !cur.open, settingsOpen: false, notice: '', pos: cur.open ? cur.pos : null });
|
|
1086
|
+
},
|
|
1087
|
+
style: {
|
|
1088
|
+
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
|
|
1089
|
+
width: 26, height: 26, padding: 0,
|
|
1090
|
+
border: '1px solid var(--dsw-alias-border-l2, #d6dde7)', borderRadius: 7,
|
|
1091
|
+
background: s.open ? 'var(--dsw-alias-bg-layer-2, #e8eef7)' : 'transparent',
|
|
1092
|
+
cursor: 'pointer', fontSize: 15, lineHeight: 1,
|
|
1093
|
+
},
|
|
1094
|
+
}, '📖');
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
// ---- 伪输入框覆盖层 ----
|
|
1098
|
+
function InlineReader() {
|
|
1099
|
+
const s = useStore(store);
|
|
1100
|
+
const fileRef = useRef(null);
|
|
1101
|
+
const [info, setInfo] = useState(null); // 真实输入框的矩形与计算样式
|
|
1102
|
+
const dragRef = useRef(null);
|
|
1103
|
+
const [dragging, setDragging] = useState(false);
|
|
1104
|
+
const resizeRef = useRef(null); // 边缘缩放:起始鼠标位置 / 起始宽高 / 方向
|
|
1105
|
+
const [resizing, setResizing] = useState(false);
|
|
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]);
|
|
1124
|
+
|
|
1125
|
+
// 读取真实输入框的矩形与配色,作为覆盖层的默认样式
|
|
1126
|
+
useEffect(() => {
|
|
1127
|
+
if (!s.open) return;
|
|
1128
|
+
const measure = () => setInfo(findEditorInfo());
|
|
1129
|
+
measure();
|
|
1130
|
+
const t1 = setTimeout(measure, 60); // 渲染时序兜底
|
|
1131
|
+
const t2 = setTimeout(measure, 320);
|
|
1132
|
+
window.addEventListener('resize', measure);
|
|
1133
|
+
return () => { clearTimeout(t1); clearTimeout(t2); window.removeEventListener('resize', measure); };
|
|
1134
|
+
}, [s.open]);
|
|
1135
|
+
|
|
1136
|
+
useEffect(() => {
|
|
1137
|
+
if (!dragging) return;
|
|
1138
|
+
function move(e) {
|
|
1139
|
+
const d = dragRef.current; if (!d) return;
|
|
1140
|
+
store.set({ pos: { x: Math.max(0, e.clientX - d.dx), y: Math.max(0, e.clientY - d.dy) } });
|
|
1141
|
+
}
|
|
1142
|
+
function up() { setDragging(false); dragActive = false; dragRef.current = null; persist(); }
|
|
1143
|
+
document.addEventListener('mousemove', move);
|
|
1144
|
+
document.addEventListener('mouseup', up);
|
|
1145
|
+
return () => { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', up); };
|
|
1146
|
+
}, [dragging]);
|
|
1147
|
+
|
|
1148
|
+
// 边缘拖拽缩放:移动鼠标实时改写宽高,正文按新尺寸自动重新分页
|
|
1149
|
+
useEffect(() => {
|
|
1150
|
+
if (!resizing) return;
|
|
1151
|
+
function move(e) {
|
|
1152
|
+
const r = resizeRef.current; if (!r) return;
|
|
1153
|
+
const minW = 120, minH = 80;
|
|
1154
|
+
let w = r.w, hh = r.h;
|
|
1155
|
+
if (r.dir.indexOf('e') >= 0) w = Math.max(minW, r.w + (e.clientX - r.x));
|
|
1156
|
+
if (r.dir.indexOf('s') >= 0) hh = Math.max(minH, r.h + (e.clientY - r.y));
|
|
1157
|
+
store.set({ style: { ...store.get().style, width: w, height: hh } });
|
|
1158
|
+
}
|
|
1159
|
+
function up() {
|
|
1160
|
+
resizeRef.current = null; setResizing(false); dragActive = false;
|
|
1161
|
+
persist(); // 缩放结束自动保存样式,下次打开无需重设
|
|
1162
|
+
}
|
|
1163
|
+
document.addEventListener('mousemove', move);
|
|
1164
|
+
document.addEventListener('mouseup', up);
|
|
1165
|
+
return () => { document.removeEventListener('mousemove', move); document.removeEventListener('mouseup', up); };
|
|
1166
|
+
}, [resizing]);
|
|
1167
|
+
|
|
1168
|
+
// 有效样式:用户显式设置优先,否则跟随输入框,再否则用安全兜底
|
|
1169
|
+
const st = s.style;
|
|
1170
|
+
const eff = {
|
|
1171
|
+
// pos 为拖拽后的自定义位置;否则精确贴合输入框矩形(保留亚像素,取整数值会引入 1px 偏移)
|
|
1172
|
+
x: s.pos ? s.pos.x : (info ? info.x : 24),
|
|
1173
|
+
y: s.pos ? s.pos.y : (info ? info.y : Math.max(8, (typeof window !== 'undefined' ? window.innerHeight : 800) - 200)),
|
|
1174
|
+
width: st.width || (info ? info.width : 640),
|
|
1175
|
+
height: st.height || (info ? info.height : 160),
|
|
1176
|
+
bg: st.bgColor || (info && info.bg) || 'rgba(127,127,127,0.08)',
|
|
1177
|
+
color: st.textColor || (info && info.color) || 'inherit',
|
|
1178
|
+
fontFamily: st.fontFamily || (info && info.fontFamily) || 'inherit',
|
|
1179
|
+
fontSize: st.fontSize || (info && info.fontSize) || 14,
|
|
1180
|
+
lineHeight: st.lineHeight || (info && info.lineHeight && info.lineHeight / info.fontSize < 4 ? info.lineHeight / info.fontSize : 1.6),
|
|
1181
|
+
radius: info ? info.radius : '8px',
|
|
1182
|
+
border: info ? info.border : '',
|
|
1183
|
+
shadow: info ? info.shadow : '',
|
|
1184
|
+
};
|
|
1185
|
+
// 设置面板有效样式:与阅读区 eff 一一对应、完全独立。空值 = 跟随输入框。
|
|
1186
|
+
// 必须在所有使用处之前定义,避免 TDZ。
|
|
1187
|
+
const peff = {
|
|
1188
|
+
width: st.panelWidth || 520,
|
|
1189
|
+
height: st.panelHeight || Math.min(560, (typeof window !== 'undefined' ? window.innerHeight : 800) - 60),
|
|
1190
|
+
bg: st.panelBgColor || (info && info.bg) || 'rgba(127,127,127,0.08)',
|
|
1191
|
+
color: st.panelTextColor || (info && info.color) || 'inherit',
|
|
1192
|
+
fontFamily: st.panelFontFamily || (info && info.fontFamily) || 'inherit',
|
|
1193
|
+
fontSize: st.panelFontSize || 13,
|
|
1194
|
+
lineHeight: st.panelLineHeight || 1.6,
|
|
1195
|
+
};
|
|
1196
|
+
|
|
1197
|
+
const chapter = s.book && s.book.chapters[s.chapterIndex] || null;
|
|
1198
|
+
const pages = useMemo(
|
|
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]
|
|
1202
|
+
);
|
|
1203
|
+
const pageCount = pages.length;
|
|
1204
|
+
const pageIndex = Math.min(s.pageIndex, Math.max(0, pageCount - 1));
|
|
1205
|
+
const pageText = pages[pageIndex] || '';
|
|
1206
|
+
|
|
1207
|
+
function goPage(delta) {
|
|
1208
|
+
const next = pageIndex + delta;
|
|
1209
|
+
if (next < 0) { goChapter(-1); return; }
|
|
1210
|
+
if (next >= pageCount) { goChapter(1); return; }
|
|
1211
|
+
store.set({ pageIndex: next }); persist();
|
|
1212
|
+
}
|
|
1213
|
+
function goChapter(delta) {
|
|
1214
|
+
if (!s.book) return;
|
|
1215
|
+
const next = s.chapterIndex + delta;
|
|
1216
|
+
if (next < 0 || next >= s.book.chapters.length) return;
|
|
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);
|
|
1237
|
+
}
|
|
1238
|
+
// 开始边缘缩放:记录初始宽高与鼠标位置、当前面板左上角
|
|
1239
|
+
function startResize(e, dir) {
|
|
1240
|
+
e.preventDefault(); e.stopPropagation();
|
|
1241
|
+
resizeRef.current = {
|
|
1242
|
+
x: e.clientX, y: e.clientY, w: eff.width, h: eff.height, dir: dir,
|
|
1243
|
+
};
|
|
1244
|
+
dragActive = true; cancelHide(); setResizing(true);
|
|
1245
|
+
}
|
|
1246
|
+
function onFile(e) { readFile(e.target.files && e.target.files[0]); e.target.value = ''; }
|
|
1247
|
+
function onDrop(e) {
|
|
1248
|
+
e.preventDefault();
|
|
1249
|
+
const file = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
|
|
1250
|
+
if (file && /\.txt$/i.test(file.name)) readFile(file);
|
|
1251
|
+
else store.set({ notice: tr('importHint') });
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
if (!s.open) return null;
|
|
1255
|
+
const isSettings = !!s.settingsOpen;
|
|
1256
|
+
// 书架/找书/书源:不再挤在输入框大小里,改用与设置面板一样的大面板弹窗
|
|
1257
|
+
const isPopup = s.panelView !== 'read';
|
|
1258
|
+
const isLarge = isSettings || isPopup; // 两种「大面板」共用 peff 尺寸与配色
|
|
1259
|
+
// 设置面板配色直接取自 peff(与阅读区 eff 完全独立),改一边不影响另一边。
|
|
1260
|
+
const panelBg = peff.bg;
|
|
1261
|
+
const panelColor = peff.color;
|
|
1262
|
+
// 阅读区渲染背景:在基础背景色上叠加透明度(跟随开关/取色器仍用 eff.bg 原值,不受影响)
|
|
1263
|
+
const readerBg = withOpacity(eff.bg, st.bgOpacity);
|
|
1264
|
+
// 设置模式用 peff 尺寸(可自定义),超出滚动;阅读模式用 eff 精确贴合输入框尺寸
|
|
1265
|
+
const panelW = isLarge ? peff.width : eff.width;
|
|
1266
|
+
const panelH = isLarge ? peff.height : eff.height;
|
|
1267
|
+
const panelTop = isLarge && typeof window !== 'undefined'
|
|
1268
|
+
? Math.max(8, Math.min(eff.y, window.innerHeight - panelH - 20)) : eff.y;
|
|
1269
|
+
// 边框样式:设置面板与阅读区各自独立(圆角/显示开关分开存),默认都跟随输入框。
|
|
1270
|
+
// 边框颜色源随模式取对应背景所属元素,避免串色。必须在 wrapStyle 之前定义,避免 TDZ。
|
|
1271
|
+
function borderOf(radiusRaw, visible, baseBorder) {
|
|
1272
|
+
const radius = radiusRaw !== '' && radiusRaw != null ? radiusRaw + 'px' : (baseBorder && baseBorder.radius) || eff.radius;
|
|
1273
|
+
const border = visible !== false ? ((baseBorder && baseBorder.border) || eff.border || '1px solid rgba(120,140,170,0.55)') : 'none';
|
|
1274
|
+
return { radius, border };
|
|
1275
|
+
}
|
|
1276
|
+
const readerBorder = borderOf(st.radiusValue, st.borderVisible, { radius: eff.radius, border: eff.border });
|
|
1277
|
+
const panelBorder = borderOf(st.panelRadiusValue, st.panelBorderVisible, { radius: eff.radius, border: eff.border });
|
|
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;
|
|
1284
|
+
const wrapStyle = {
|
|
1285
|
+
position: 'fixed', left: eff.x, top: panelTop, width: panelW, height: panelH,
|
|
1286
|
+
// border-box:让宽高包含边框与内边距,精确覆盖输入框而不多出像素
|
|
1287
|
+
boxSizing: 'border-box',
|
|
1288
|
+
zIndex: 100000, display: 'flex', flexDirection: 'column', overflow: 'hidden',
|
|
1289
|
+
background: isLarge ? panelBg : readerBg,
|
|
1290
|
+
color: isLarge ? panelColor : eff.color,
|
|
1291
|
+
fontFamily: curFont, fontSize: curFontSize,
|
|
1292
|
+
border: finalBorder, borderRadius: finalRadius,
|
|
1293
|
+
boxShadow: eff.shadow || undefined,
|
|
1294
|
+
};
|
|
1295
|
+
const toolBtn = (label, fn, disabled) => h('button', {
|
|
1296
|
+
type: 'button', onClick: fn, disabled: !!disabled,
|
|
1297
|
+
style: {
|
|
1298
|
+
border: 'none', background: 'transparent', color: 'inherit', fontSize: 12,
|
|
1299
|
+
padding: '2px 6px', cursor: disabled ? 'default' : 'pointer', opacity: disabled ? 0.35 : 1,
|
|
1300
|
+
},
|
|
1301
|
+
}, label);
|
|
1302
|
+
|
|
1303
|
+
function onReadClick(e) {
|
|
1304
|
+
if (s.settingsOpen) return;
|
|
1305
|
+
const sel = window.getSelection && window.getSelection();
|
|
1306
|
+
if (sel && String(sel).length > 0) return; // 选中文本时不翻页
|
|
1307
|
+
const r = e.currentTarget.getBoundingClientRect();
|
|
1308
|
+
const rel = (e.clientX - r.left) / r.width;
|
|
1309
|
+
if (rel < 0.28) goPage(-1); else if (rel > 0.72) goPage(1);
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
// 两套「跟随输入框」状态:各自只看自己那组字段是否全空,互不干扰
|
|
1313
|
+
const readerFollow = !st.fontSize && !st.lineHeight && !st.fontFamily && !st.bgColor && !st.textColor && !st.width && !st.height && !st.radiusValue && (st.bgOpacity == null || st.bgOpacity >= 1) && st.borderVisible !== false;
|
|
1314
|
+
const panelFollow = !st.panelFontSize && !st.panelLineHeight && !st.panelFontFamily && !st.panelBgColor && !st.panelTextColor && !st.panelWidth && !st.panelHeight && !st.panelRadiusValue && st.panelBorderVisible !== false;
|
|
1315
|
+
// 各自「跟随」开关切换时只改自己那组字段,绝不碰对方
|
|
1316
|
+
const READER_CLEAR = { fontSize: 0, lineHeight: 0, fontFamily: '', textColor: '', bgColor: '', bgOpacity: 1, width: 0, height: 0, radiusValue: '', borderVisible: true };
|
|
1317
|
+
const PANEL_CLEAR = { panelFontSize: 0, panelLineHeight: 0, panelFontFamily: '', panelTextColor: '', panelBgColor: '', panelWidth: 0, panelHeight: 0, panelRadiusValue: '', panelBorderVisible: true };
|
|
1318
|
+
const READER_FILL = {
|
|
1319
|
+
fontSize: eff.fontSize, lineHeight: eff.lineHeight, fontFamily: eff.fontFamily,
|
|
1320
|
+
textColor: eff.color, bgColor: eff.bg, bgOpacity: 1, width: Math.round(eff.width), height: Math.round(eff.height),
|
|
1321
|
+
radiusValue: Math.round(parseFloat(eff.radius) || 0), borderVisible: st.borderVisible !== false,
|
|
1322
|
+
};
|
|
1323
|
+
const PANEL_FILL = {
|
|
1324
|
+
panelFontSize: peff.fontSize, panelLineHeight: peff.lineHeight, panelFontFamily: peff.fontFamily,
|
|
1325
|
+
panelTextColor: peff.color, panelBgColor: peff.bg, panelWidth: Math.round(peff.width), panelHeight: Math.round(peff.height),
|
|
1326
|
+
panelRadiusValue: Math.round(parseFloat(eff.radius) || 0), panelBorderVisible: st.panelBorderVisible !== false,
|
|
1327
|
+
};
|
|
1328
|
+
function updateStyle(patch) {
|
|
1329
|
+
store.set({ style: { ...store.get().style, ...patch } }); persist();
|
|
1330
|
+
}
|
|
1331
|
+
// 数字输入框统一样式(宽/高用),必须在 return 之前定义避免 TDZ
|
|
1332
|
+
const numberInputStyle = {
|
|
1333
|
+
width: 76, border: '1px solid rgba(120,140,170,0.4)', borderRadius: 5,
|
|
1334
|
+
background: 'transparent', color: 'inherit', fontSize: 12, padding: '2px 4px',
|
|
1335
|
+
};
|
|
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
|
+
|
|
1545
|
+
// 工具栏:置于窗口底部(用户要求),拖动它仍可移动整个面板
|
|
1546
|
+
const toolbar = h('div', {
|
|
1547
|
+
onMouseDown: (e) => {
|
|
1548
|
+
if (e.target.closest('button,select,input,textarea')) return;
|
|
1549
|
+
dragRef.current = { dx: e.clientX - eff.x, dy: e.clientY - panelTop };
|
|
1550
|
+
dragActive = true; cancelHide(); setDragging(true);
|
|
1551
|
+
},
|
|
1552
|
+
style: {
|
|
1553
|
+
position: 'relative', zIndex: 3,
|
|
1554
|
+
display: 'flex', alignItems: 'center', gap: 4, padding: '2px 8px', flexWrap: 'wrap',
|
|
1555
|
+
background: isSettings ? panelBg : readerBg,
|
|
1556
|
+
borderTop: borderOn ? '1px solid rgba(120,140,170,0.25)' : 'none',
|
|
1557
|
+
color: isSettings ? panelColor : eff.color,
|
|
1558
|
+
cursor: dragging ? 'grabbing' : 'grab', flexShrink: 0, fontSize: 12,
|
|
1559
|
+
},
|
|
1560
|
+
},
|
|
1561
|
+
toolBtn('⚙ ' + tr('settings'), () => store.set({ settingsOpen: !s.settingsOpen })),
|
|
1562
|
+
toolBtn(s.pinned ? '📌 ' + tr('unpin') : '📍 ' + tr('pin'), () => {
|
|
1563
|
+
cancelHide();
|
|
1564
|
+
store.set({ pinned: !s.pinned }); persist();
|
|
1565
|
+
}),
|
|
1566
|
+
toolBtn(tr('prevChapter'), () => goChapter(-1), !s.book || s.chapterIndex <= 0),
|
|
1567
|
+
// 章节下拉:按钮只负责开合,弹层在根节点外层用 fixed 渲染(见 chapterMenu)
|
|
1568
|
+
h('div', { style: { position: 'relative' } },
|
|
1569
|
+
h('button', {
|
|
1570
|
+
ref: chapterBtnRef, type: 'button', disabled: !s.book,
|
|
1571
|
+
onClick: toggleChapterMenu,
|
|
1572
|
+
style: {
|
|
1573
|
+
maxWidth: 150, border: '1px solid rgba(120,140,170,0.4)', borderRadius: 6,
|
|
1574
|
+
background: 'transparent', color: 'inherit', fontSize: 12, padding: '2px 6px',
|
|
1575
|
+
cursor: s.book ? 'pointer' : 'default', opacity: s.book ? 1 : 0.4,
|
|
1576
|
+
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
|
1577
|
+
},
|
|
1578
|
+
}, s.book && s.book.chapters[s.chapterIndex] ? s.book.chapters[s.chapterIndex].title : tr('chapterPlaceholder'), ' ▾')
|
|
1579
|
+
),
|
|
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 })),
|
|
1582
|
+
h('span', { style: { flex: 1, minWidth: 4 } }),
|
|
1583
|
+
h('span', { style: { opacity: 0.75, whiteSpace: 'nowrap' } },
|
|
1584
|
+
s.book ? `${s.chapterIndex + 1}/${s.book.chapters.length}${tr('chapterCount')} · ${pageIndex + 1}/${pageCount}${tr('page')}` : ''),
|
|
1585
|
+
toolBtn(tr('import'), () => fileRef.current && fileRef.current.click()),
|
|
1586
|
+
toolBtn('✕ ' + tr('close'), () => {
|
|
1587
|
+
cancelHide();
|
|
1588
|
+
store.set({ open: false, pinned: false, settingsOpen: false, notice: '' }); persist();
|
|
1589
|
+
})
|
|
1590
|
+
);
|
|
1591
|
+
|
|
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', {
|
|
1619
|
+
style: wrapStyle,
|
|
1620
|
+
onMouseEnter: () => cancelHide(), // 鼠标进入阅读区,取消收起
|
|
1621
|
+
// 弹窗里的书架/找书需要持续操作、章节弹层在面板之外,这两种情况鼠标离开都不收起
|
|
1622
|
+
onMouseLeave: () => {
|
|
1623
|
+
if (isPopup || chapterMenuOpen) return;
|
|
1624
|
+
// 刚点了弹窗里的「返回」:鼠标还在原弹窗位置,不算离开阅读区
|
|
1625
|
+
if (keepOpenOnLeave) { keepOpenOnLeave = false; return; }
|
|
1626
|
+
scheduleHide();
|
|
1627
|
+
},
|
|
1628
|
+
onDragOver: (e) => e.preventDefault(),
|
|
1629
|
+
onDrop: onDrop,
|
|
1630
|
+
},
|
|
1631
|
+
// 阅读区只在阅读视图渲染;书架/找书/书源改走下面的独立大弹窗
|
|
1632
|
+
s.settingsOpen || isPopup ? null : mainView,
|
|
1633
|
+
// 隐藏的文件选择 input
|
|
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,
|
|
1643
|
+
// 设置面板:独立大面板完整展示
|
|
1644
|
+
s.settingsOpen ? h('div', {
|
|
1645
|
+
style: {
|
|
1646
|
+
position: 'relative', flex: 1, minHeight: 0, background: panelBg, color: panelColor,
|
|
1647
|
+
padding: '12px 16px 16px', overflowY: 'auto',
|
|
1648
|
+
fontFamily: peff.fontFamily, fontSize: peff.fontSize, lineHeight: peff.lineHeight,
|
|
1649
|
+
},
|
|
1650
|
+
},
|
|
1651
|
+
h('div', { style: { position: 'sticky', top: 0, zIndex: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontWeight: 600, marginBottom: 4, padding: '2px 0 8px', background: panelBg } },
|
|
1652
|
+
h('span', null, tr('settingsTitle')),
|
|
1653
|
+
h('button', {
|
|
1654
|
+
type: 'button', onClick: () => store.set({ settingsOpen: false }),
|
|
1655
|
+
style: { border: 'none', background: 'transparent', color: 'inherit', cursor: 'pointer', fontSize: 13, padding: 0 },
|
|
1656
|
+
}, '✕ ' + tr('done'))
|
|
1657
|
+
),
|
|
1658
|
+
// ---- 分组1:多套样式配置(保存当前 / 应用 / 删除)----
|
|
1659
|
+
group(tr('profileGroup'),
|
|
1660
|
+
h('div', { style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 } },
|
|
1661
|
+
h('input', {
|
|
1662
|
+
type: 'text', value: s.profileName || '', placeholder: tr('profileName'),
|
|
1663
|
+
onChange: e => store.set({ profileName: e.target.value }),
|
|
1664
|
+
style: { flex: 1, minWidth: 0, border: '1px solid rgba(120,140,170,0.4)', borderRadius: 5, background: 'transparent', color: 'inherit', fontSize: 12, padding: '3px 6px' },
|
|
1665
|
+
}),
|
|
1666
|
+
toolBtn(tr('profileSave'), () => {
|
|
1667
|
+
const name = String(store.get().profileName || '').trim();
|
|
1668
|
+
if (!name) { store.set({ notice: tr('profileEmptyName') }); return; }
|
|
1669
|
+
const p = { ...loadProfiles(), [name]: { ...store.get().style } };
|
|
1670
|
+
saveProfiles(p);
|
|
1671
|
+
store.set({ notice: t('profileSaved', { name }) });
|
|
1672
|
+
})
|
|
1673
|
+
),
|
|
1674
|
+
Object.keys(s.profiles || {}).length === 0
|
|
1675
|
+
? h('div', { style: { opacity: 0.6, fontSize: 12, marginBottom: 8 } }, tr('profileNone'))
|
|
1676
|
+
: h('div', { style: { marginBottom: 8 } }, Object.keys(s.profiles).map(name =>
|
|
1677
|
+
h('div', { key: name, style: { display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 } },
|
|
1678
|
+
h('span', { style: { flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, name),
|
|
1679
|
+
toolBtn(tr('profileSelect'), () => {
|
|
1680
|
+
updateStyle({ ...DEFAULT_STYLE, ...(s.profiles[name] || {}) });
|
|
1681
|
+
store.set({ pos: null });
|
|
1682
|
+
if (s.book && fullText) store.set({ book: { ...s.book, chapters: detectChapters(fullText, store.get().style.customRegex) }, chapterIndex: 0, pageIndex: 0 });
|
|
1683
|
+
store.set({ notice: t('profileApplied', { name }) });
|
|
1684
|
+
persist();
|
|
1685
|
+
}),
|
|
1686
|
+
toolBtn(tr('profileDelete'), () => {
|
|
1687
|
+
if (typeof window !== 'undefined' && window.confirm && !window.confirm(t('profileConfirmDelete', { name }))) return;
|
|
1688
|
+
const p = { ...loadProfiles() }; delete p[name];
|
|
1689
|
+
saveProfiles(p);
|
|
1690
|
+
store.set({ notice: t('profileDeleted', { name }) });
|
|
1691
|
+
})
|
|
1692
|
+
)
|
|
1693
|
+
))),
|
|
1694
|
+
divider(),
|
|
1695
|
+
// ===== 大分组A:设置面板样式(内含外观/边框/尺寸小分组)=====
|
|
1696
|
+
bigGroup(tr('panelGroup'),
|
|
1697
|
+
// ---- 小分组2a:设置面板外观(完全独立于阅读区)----
|
|
1698
|
+
group(tr('panelStyleGroup'),
|
|
1699
|
+
h('label', { style: { display: 'flex', alignItems: 'flex-start', gap: 6, marginBottom: 10, cursor: 'pointer' } },
|
|
1700
|
+
h('input', {
|
|
1701
|
+
type: 'checkbox', checked: panelFollow,
|
|
1702
|
+
onChange: e => { updateStyle(e.target.checked ? PANEL_CLEAR : PANEL_FILL); persist(); },
|
|
1703
|
+
}),
|
|
1704
|
+
h('span', null, h('span', null, tr('panelFollowLabel')), h('span', { style: { display: 'block', opacity: 0.65, fontSize: 11 } }, tr('followInputHint')))
|
|
1705
|
+
),
|
|
1706
|
+
// 设置面板独立文字与配色(与阅读区分开)
|
|
1707
|
+
settingRow(tr('panelFontSize'), h('input', { type: 'range', min: 11, max: 24, value: peff.fontSize, onChange: e => updateStyle({ panelFontSize: Number(e.target.value) }) }), peff.fontSize),
|
|
1708
|
+
settingRow(tr('panelLineHeight'), h('input', { type: 'range', min: 1.2, max: 2.4, step: 0.1, value: peff.lineHeight, onChange: e => updateStyle({ panelLineHeight: Number(e.target.value) }) }), peff.lineHeight.toFixed(1)),
|
|
1709
|
+
settingRow(tr('panelFontFamily'), h('select', { value: st.panelFontFamily || 'default', onChange: e => updateStyle({ panelFontFamily: e.target.value === 'default' ? '' : e.target.value }) },
|
|
1710
|
+
h('option', { value: 'default' }, '跟随输入框'),
|
|
1711
|
+
h('option', { value: 'system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", serif' }, '系统字体'),
|
|
1712
|
+
h('option', { value: '"Songti SC", SimSun, serif' }, '宋体'),
|
|
1713
|
+
h('option', { value: '"PingFang SC", "Microsoft YaHei", sans-serif' }, '黑体'),
|
|
1714
|
+
h('option', { value: 'Menlo, Consolas, monospace' }, '等宽')
|
|
1715
|
+
)),
|
|
1716
|
+
settingRow(tr('panelTextColor'), h('input', { type: 'color', value: toHex(panelColor, '#888888'), onChange: e => updateStyle({ panelTextColor: e.target.value }) })),
|
|
1717
|
+
settingRow(tr('panelBgColor'), h('input', { type: 'color', value: toHex(panelBg, '#ffffff'), onChange: e => updateStyle({ panelBgColor: e.target.value }) })),
|
|
1718
|
+
),
|
|
1719
|
+
divider(),
|
|
1720
|
+
// ---- 分组3:设置面板边框(与阅读区独立)----
|
|
1721
|
+
group(tr('panelBorderGroup'),
|
|
1722
|
+
settingRow(tr('borderRadius'), h('input', {
|
|
1723
|
+
type: 'range', min: 0, max: 40, step: 1,
|
|
1724
|
+
value: st.panelRadiusValue !== '' && st.panelRadiusValue != null ? Number(st.panelRadiusValue) : Math.round(parseFloat(eff.radius) || 0),
|
|
1725
|
+
onChange: e => updateStyle({ panelRadiusValue: String(e.target.value) }),
|
|
1726
|
+
}), (st.panelRadiusValue !== '' && st.panelRadiusValue != null ? st.panelRadiusValue : (parseFloat(eff.radius) || 0)) + 'px'),
|
|
1727
|
+
settingRow(tr('borderVisible'), h('input', {
|
|
1728
|
+
type: 'checkbox', checked: st.panelBorderVisible !== false,
|
|
1729
|
+
onChange: e => updateStyle({ panelBorderVisible: e.target.checked }),
|
|
1730
|
+
})),
|
|
1731
|
+
),
|
|
1732
|
+
divider(),
|
|
1733
|
+
// ---- 分组3c:设置面板尺寸(与阅读区独立)----
|
|
1734
|
+
group(tr('panelSizeGroup'),
|
|
1735
|
+
settingRow(tr('windowWidth'), h('input', {
|
|
1736
|
+
type: 'number', min: 200, step: 1, value: Math.round(peff.width),
|
|
1737
|
+
onChange: e => { const v = Number(e.target.value); if (v > 0) updateStyle({ panelWidth: v }); },
|
|
1738
|
+
style: numberInputStyle,
|
|
1739
|
+
}), 'px'),
|
|
1740
|
+
settingRow(tr('windowHeight'), h('input', {
|
|
1741
|
+
type: 'number', min: 200, step: 1, value: Math.round(peff.height),
|
|
1742
|
+
onChange: e => { const v = Number(e.target.value); if (v > 0) updateStyle({ panelHeight: v }); },
|
|
1743
|
+
style: numberInputStyle,
|
|
1744
|
+
}), 'px'),
|
|
1745
|
+
),
|
|
1746
|
+
), // 关闭大分组A:设置面板样式
|
|
1747
|
+
// ===== 大分组B:阅读区样式(内含文字/边框/尺寸小分组)=====
|
|
1748
|
+
bigGroup(tr('readerGroup'),
|
|
1749
|
+
// ---- 小分组4a:阅读区文字与排版 ----
|
|
1750
|
+
group(tr('readerTextGroup'),
|
|
1751
|
+
h('label', { style: { display: 'flex', alignItems: 'flex-start', gap: 6, marginBottom: 10, cursor: 'pointer' } },
|
|
1752
|
+
h('input', {
|
|
1753
|
+
type: 'checkbox', checked: readerFollow,
|
|
1754
|
+
onChange: e => { updateStyle(e.target.checked ? READER_CLEAR : READER_FILL); store.set({ pos: null }); persist(); },
|
|
1755
|
+
}),
|
|
1756
|
+
h('span', null, h('span', null, tr('readerFollowLabel')), h('span', { style: { display: 'block', opacity: 0.65, fontSize: 11 } }, tr('followInputHint')))
|
|
1757
|
+
),
|
|
1758
|
+
settingRow(tr('fontSize'), h('input', { type: 'range', min: 12, max: 36, value: eff.fontSize, onChange: e => updateStyle({ fontSize: Number(e.target.value) }) }), eff.fontSize),
|
|
1759
|
+
settingRow(tr('lineHeight'), h('input', { type: 'range', min: 1.2, max: 2.6, step: 0.1, value: eff.lineHeight, onChange: e => updateStyle({ lineHeight: Number(e.target.value) }) }), eff.lineHeight.toFixed(1)),
|
|
1760
|
+
settingRow(tr('fontFamily'), h('select', { value: st.fontFamily || 'default', onChange: e => updateStyle({ fontFamily: e.target.value === 'default' ? '' : e.target.value }) },
|
|
1761
|
+
h('option', { value: 'default' }, '跟随输入框'),
|
|
1762
|
+
h('option', { value: 'system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", serif' }, '系统字体'),
|
|
1763
|
+
h('option', { value: '"Songti SC", SimSun, serif' }, '宋体'),
|
|
1764
|
+
h('option', { value: '"PingFang SC", "Microsoft YaHei", sans-serif' }, '黑体'),
|
|
1765
|
+
h('option', { value: 'Menlo, Consolas, monospace' }, '等宽')
|
|
1766
|
+
)),
|
|
1767
|
+
settingRow(tr('textColor'), h('input', { type: 'color', value: toHex(eff.color, '#888888'), onChange: e => updateStyle({ textColor: e.target.value }) })),
|
|
1768
|
+
settingRow(tr('backgroundColor'), h('input', { type: 'color', value: toHex(eff.bg, '#ffffff'), onChange: e => updateStyle({ bgColor: e.target.value }) })),
|
|
1769
|
+
settingRow(tr('bgOpacity'), h('input', {
|
|
1770
|
+
type: 'range', min: 0.1, max: 1, step: 0.05,
|
|
1771
|
+
value: st.bgOpacity == null ? 1 : st.bgOpacity,
|
|
1772
|
+
onChange: e => updateStyle({ bgOpacity: Number(e.target.value) }),
|
|
1773
|
+
}), Math.round((st.bgOpacity == null ? 1 : st.bgOpacity) * 100) + '%'),
|
|
1774
|
+
),
|
|
1775
|
+
divider(),
|
|
1776
|
+
// ---- 小分组4b:阅读区边框(与设置面板独立)----
|
|
1777
|
+
group(tr('readerBorderGroup'),
|
|
1778
|
+
settingRow(tr('borderRadius'), h('input', {
|
|
1779
|
+
type: 'range', min: 0, max: 40, step: 1,
|
|
1780
|
+
value: st.radiusValue !== '' && st.radiusValue != null ? Number(st.radiusValue) : Math.round(parseFloat(eff.radius) || 0),
|
|
1781
|
+
onChange: e => updateStyle({ radiusValue: String(e.target.value) }),
|
|
1782
|
+
}), (st.radiusValue !== '' && st.radiusValue != null ? st.radiusValue : (parseFloat(eff.radius) || 0)) + 'px'),
|
|
1783
|
+
settingRow(tr('borderVisible'), h('input', {
|
|
1784
|
+
type: 'checkbox', checked: st.borderVisible !== false,
|
|
1785
|
+
onChange: e => updateStyle({ borderVisible: e.target.checked }),
|
|
1786
|
+
})),
|
|
1787
|
+
),
|
|
1788
|
+
divider(),
|
|
1789
|
+
// ---- 小分组4c:窗口尺寸(宽高用数字输入框,允许自由输入精确值)----
|
|
1790
|
+
group(tr('readerSizeGroup'),
|
|
1791
|
+
settingRow(tr('windowWidth'), h('input', {
|
|
1792
|
+
type: 'number', min: 80, step: 1, value: Math.round(eff.width),
|
|
1793
|
+
onChange: e => { const v = Number(e.target.value); if (v > 0) updateStyle({ width: v }); },
|
|
1794
|
+
style: numberInputStyle,
|
|
1795
|
+
}), 'px'),
|
|
1796
|
+
settingRow(tr('windowHeight'), h('input', {
|
|
1797
|
+
type: 'number', min: 40, step: 1, value: Math.round(eff.height),
|
|
1798
|
+
onChange: e => { const v = Number(e.target.value); if (v > 0) updateStyle({ height: v }); },
|
|
1799
|
+
style: numberInputStyle,
|
|
1800
|
+
}), 'px'),
|
|
1801
|
+
),
|
|
1802
|
+
), // 关闭大分组B:阅读区样式
|
|
1803
|
+
divider(),
|
|
1804
|
+
// ---- 分组6:章节识别 ----
|
|
1805
|
+
group(tr('chapterGroup'),
|
|
1806
|
+
h('div', { style: { fontSize: 12, marginTop: 2, opacity: 0.8 } }, tr('regexHint')),
|
|
1807
|
+
h('textarea', {
|
|
1808
|
+
value: st.customRegex, rows: 2, placeholder: tr('customChapterRegex'),
|
|
1809
|
+
onChange: e => updateStyle({ customRegex: e.target.value }),
|
|
1810
|
+
style: { width: '100%', marginTop: 4, fontSize: 12, fontFamily: 'monospace', boxSizing: 'border-box' },
|
|
1811
|
+
}),
|
|
1812
|
+
),
|
|
1813
|
+
divider(),
|
|
1814
|
+
// ---- 分组7:操作 ----
|
|
1815
|
+
group(tr('actionGroup'),
|
|
1816
|
+
h('div', { style: { display: 'flex', gap: 8, marginTop: 2, flexWrap: 'wrap' } },
|
|
1817
|
+
toolBtn(tr('reset'), () => {
|
|
1818
|
+
updateStyle({ ...DEFAULT_STYLE });
|
|
1819
|
+
store.set({ pos: null });
|
|
1820
|
+
if (s.book && fullText) store.set({ book: { ...s.book, chapters: detectChapters(fullText, '') }, chapterIndex: 0, pageIndex: 0 });
|
|
1821
|
+
}),
|
|
1822
|
+
toolBtn(tr('resetPos'), () => { store.set({ pos: null }); persist(); }),
|
|
1823
|
+
toolBtn(tr('done'), () => {
|
|
1824
|
+
if (s.book && fullText) store.set({ book: { ...s.book, chapters: detectChapters(fullText, store.get().style.customRegex) } });
|
|
1825
|
+
store.set({ settingsOpen: false }); persist();
|
|
1826
|
+
})
|
|
1827
|
+
),
|
|
1828
|
+
)
|
|
1829
|
+
) : null,
|
|
1830
|
+
// 工具栏固定在窗口最下方(弹窗模式不显示阅读工具栏)
|
|
1831
|
+
isPopup ? null : toolbar
|
|
1832
|
+
), chapterMenu);
|
|
1833
|
+
|
|
1834
|
+
function settingRow(label, control, value) {
|
|
1835
|
+
return h('div', {
|
|
1836
|
+
style: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: 6 },
|
|
1837
|
+
}, h('span', null, label), h('span', { style: { display: 'flex', alignItems: 'center', gap: 6 } }, control, value !== undefined ? h('span', { style: { minWidth: 28, textAlign: 'right', opacity: 0.7 } }, value) : null));
|
|
1838
|
+
}
|
|
1839
|
+
// 分组标题:带小色块,便于快速定位
|
|
1840
|
+
function groupTitle(label) {
|
|
1841
|
+
return h('div', {
|
|
1842
|
+
style: { display: 'flex', alignItems: 'center', gap: 6, fontWeight: 600, fontSize: 12, margin: '2px 0 8px' },
|
|
1843
|
+
}, h('span', { style: { width: 3, height: 12, borderRadius: 2, background: 'currentColor', opacity: 0.55 } }), h('span', null, label));
|
|
1844
|
+
}
|
|
1845
|
+
// 分组间的分割线
|
|
1846
|
+
function divider() {
|
|
1847
|
+
return h('div', { style: { height: 1, background: 'currentColor', opacity: 0.15, margin: '12px 0' } });
|
|
1848
|
+
}
|
|
1849
|
+
// 一组:标题 + 若干控件,组间由 divider 分隔
|
|
1850
|
+
function group(label, ...children) {
|
|
1851
|
+
return h('div', null, groupTitle(label), ...children);
|
|
1852
|
+
}
|
|
1853
|
+
// 大分组:把同类小分组收进一个带外框的容器(如「设置面板样式」「阅读区样式」)
|
|
1854
|
+
function bigGroup(label, ...children) {
|
|
1855
|
+
return h('div', {
|
|
1856
|
+
style: {
|
|
1857
|
+
border: '1px solid rgba(120,140,170,0.28)', borderRadius: 8,
|
|
1858
|
+
padding: '10px 12px 4px', margin: '10px 0 4px',
|
|
1859
|
+
},
|
|
1860
|
+
},
|
|
1861
|
+
h('div', {
|
|
1862
|
+
style: {
|
|
1863
|
+
display: 'flex', alignItems: 'center', gap: 8, fontWeight: 700,
|
|
1864
|
+
fontSize: 13, marginBottom: 10, paddingBottom: 6,
|
|
1865
|
+
borderBottom: '1px solid rgba(120,140,170,0.22)',
|
|
1866
|
+
},
|
|
1867
|
+
}, h('span', { style: { width: 4, height: 14, borderRadius: 2, background: 'currentColor', opacity: 0.65 } }), h('span', null, label)),
|
|
1868
|
+
...children
|
|
1869
|
+
);
|
|
1870
|
+
}
|
|
1871
|
+
function toHex(color, fallback) {
|
|
1872
|
+
if (typeof color !== 'string') return fallback;
|
|
1873
|
+
if (/^#[0-9a-fA-F]{6}$/.test(color)) return color;
|
|
1874
|
+
const m = color.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
|
|
1875
|
+
if (!m) return fallback;
|
|
1876
|
+
return '#' + [1, 2, 3].map(i => Number(m[i]).toString(16).padStart(2, '0')).join('');
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
|
|
1880
|
+
// 异步恢复书架与上次在读的书;不阻塞首帧,失败也不影响导入
|
|
1881
|
+
hydrate().catch(() => { /* 首次启动时书库不可用,忽略 */ });
|
|
1882
|
+
|
|
1883
|
+
ctx.slots.inject('conversation.input.left', () => ctx.slots.register({
|
|
1884
|
+
name: 'conversation.input.left', id: 'novel-reader-trigger', order: 6, label: () => tr('name'), locale: NS,
|
|
1885
|
+
}, Trigger));
|
|
1886
|
+
|
|
1887
|
+
ctx.slots.inject('shell.overlay', () => ctx.slots.register({
|
|
1888
|
+
name: 'shell.overlay', id: 'novel-reader-overlay', order: 50, label: () => tr('name'), locale: NS,
|
|
1889
|
+
}, InlineReader));
|
|
1890
|
+
},
|
|
1891
|
+
};
|
|
1892
|
+
},
|
|
1893
|
+
});
|