@gongfpp/dsh-novel-fish 1.0.0 → 1.1.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 +42 -14
- package/docs/community-markets.md +18 -1
- package/docs/compatibility-101.md +41 -0
- package/docs/ebook-tests.md +99 -0
- package/docs/evidence/reading-demo-110.png +0 -0
- package/docs/evidence/reading-two-expansions-110.gif +0 -0
- package/docs/evidence/reading-two-expansions-110.json +89 -0
- package/docs/evidence/samples-110-capture.json +49 -0
- package/docs/evidence/settings-110.png +0 -0
- package/docs/marketplace.md +4 -4
- package/docs/release.md +25 -0
- package/index.json +24 -0
- package/lib/client.js +523 -95
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +10 -9
- package/samples/ebooks/LICENSE.md +355 -0
- package/samples/ebooks/NOTICE.md +33 -0
- package/samples/ebooks/aq-zheng-zhuan-wikisource.md +998 -0
- package/samples/ebooks/million-pound-bank-note-pg61522.txt +6970 -0
- package/samples/ebooks/sources.json +58 -0
- package/scripts/build.mjs +1 -0
- package/scripts/check-host-contracts.mjs +3 -2
- package/scripts/make-readme-gif.mjs +69 -0
- package/scripts/test-browser-samples.mjs +665 -0
- package/scripts/test-candidate-books.mjs +71 -0
- package/scripts/test-ebook-corpus.mjs +161 -0
- package/src/bundled-books.js +42 -0
- package/src/chat-adapter.js +34 -9
- package/src/client.js +8 -2
- package/src/novel-content.js +8 -0
- package/src/persistence.js +144 -3
- package/src/pg-notice.js +19 -0
- package/src/segments.js +115 -65
- package/src/settings.js +32 -8
- package/src/store.js +61 -3
- package/test/bundled-library.test.js +526 -0
- package/test/chat-adapter.test.js +87 -2
- package/test/client.test.js +49 -7
- package/test/ebooks.test.js +192 -0
- package/test/pg-notice.test.js +109 -0
- package/test/release.test.js +21 -7
- package/test/segments.test.js +136 -2
- package/test/settings.test.js +42 -1
package/src/segments.js
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
-
|
|
1
|
+
// Half-width display units, not a character/word count: Latin ≈ 1, CJK/emoji ≈ 2.
|
|
2
|
+
// At 13px in a 320–600px text column, 800 units occupy roughly 9–17 lines.
|
|
3
|
+
export const DEFAULT_SEGMENT_LENGTH = 800
|
|
2
4
|
|
|
3
|
-
const TXT_CHAPTER = /^\s*(?:第[0-90-9零〇一二三四五六七八九十百千万两壹贰叁肆伍陆柒捌玖拾佰仟]{1,24}[章节卷篇回部](?:[\t \u3000]+[^。!?!?,,;;\r\n]{1,80})?|chapter\s
|
|
5
|
+
const TXT_CHAPTER = /^\s*(?:第[0-90-9零〇一二三四五六七八九十百千万两壹贰叁肆伍陆柒捌玖拾佰仟]{1,24}[章节卷篇回部](?:[\t \u3000]+[^。!?!?,,;;\r\n]{1,80})?|chapter\s+(?:\d+|[ivxlcdm]+)(?:[\t ]+[^.!?\r\n]{1,80})?|(?:序章|楔子|前言|尾声|后记|附录)(?:[\t \u3000]+[^。!?!?,,;;\r\n]{1,80})?)\s*$/iu
|
|
4
6
|
const MD_HEADING = /^\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*$/u
|
|
7
|
+
const WIDE = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Extended_Pictographic}\u3000-\u303f\uff01-\uff60\uffe0-\uffe6]/u
|
|
8
|
+
const CLOSING = /^[”’"'」』】))\]]+$/u
|
|
5
9
|
|
|
6
10
|
/** Split plain text into chapter groups while retaining paragraph breaks. */
|
|
7
11
|
export function textToChapters(text, format = 'txt') {
|
|
@@ -35,12 +39,18 @@ export function textToChapters(text, format = 'txt') {
|
|
|
35
39
|
return chapters
|
|
36
40
|
}
|
|
37
41
|
|
|
38
|
-
/**
|
|
42
|
+
/**
|
|
43
|
+
* Segment new imports only; stored passages/progress are not read or rewritten.
|
|
44
|
+
* targetLength is a positive-integer soft display-width budget (half-width units).
|
|
45
|
+
* Paragraph/sentence boundaries may extend it to floor(targetLength * 1.25).
|
|
46
|
+
* Newlines cost 40 units (a conservative wrap/blank-line allowance). A single
|
|
47
|
+
* indivisible grapheme may exceed the hard budget rather than being corrupted.
|
|
48
|
+
*/
|
|
39
49
|
export function segmentChapters(chapters, targetLength = DEFAULT_SEGMENT_LENGTH) {
|
|
40
|
-
const
|
|
50
|
+
const target = positiveInteger(targetLength)
|
|
41
51
|
const segments = []
|
|
42
52
|
chapters.forEach((chapter, chapterIndex) => {
|
|
43
|
-
for (const text of splitChapter(chapter.text,
|
|
53
|
+
for (const text of splitChapter(chapter.text, target)) {
|
|
44
54
|
segments.push({ text, chapterTitle: chapter.title, chapterIndex })
|
|
45
55
|
}
|
|
46
56
|
})
|
|
@@ -55,81 +65,121 @@ export function parseTextBook(text, format = 'txt', targetLength = DEFAULT_SEGME
|
|
|
55
65
|
return { chapters, segments }
|
|
56
66
|
}
|
|
57
67
|
|
|
58
|
-
function splitChapter(text,
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
68
|
+
function splitChapter(text, target) {
|
|
69
|
+
const source = String(text).replace(/\r\n?/gu, '\n').split(/\n\s*\n+/u)
|
|
70
|
+
.map(value => value.trim()).filter(Boolean).join('\n\n')
|
|
71
|
+
if (!source) return []
|
|
72
|
+
const parts = graphemes(source)
|
|
73
|
+
const widths = [0]
|
|
74
|
+
const offsets = [0]
|
|
75
|
+
for (const part of parts) {
|
|
76
|
+
widths.push(widths.at(-1) + displayWidth(part))
|
|
77
|
+
offsets.push(offsets.at(-1) + part.length)
|
|
66
78
|
}
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
current = next
|
|
72
|
-
return
|
|
79
|
+
const sentenceEnds = new Set()
|
|
80
|
+
if (typeof Intl.Segmenter === 'function') {
|
|
81
|
+
for (const item of new Intl.Segmenter(undefined, { granularity: 'sentence' }).segment(source)) {
|
|
82
|
+
sentenceEnds.add(item.index + item.segment.length)
|
|
73
83
|
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
84
|
+
}
|
|
85
|
+
const hard = Math.max(1, Math.floor(target * 1.25))
|
|
86
|
+
// A word that fits in one passage stays intact even if that requires a short
|
|
87
|
+
// predecessor. Only genuinely overlong tokens are eligible for forced cuts.
|
|
88
|
+
const insideWord = new Set()
|
|
89
|
+
for (let index = 0; index < parts.length;) {
|
|
90
|
+
if (/^\s+$/u.test(parts[index]) || WIDE.test(parts[index])) { index += 1; continue }
|
|
91
|
+
const begin = index
|
|
92
|
+
while (index < parts.length && !/^\s+$/u.test(parts[index]) && !WIDE.test(parts[index])) index += 1
|
|
93
|
+
if (widths[index] - widths[begin] <= hard) {
|
|
94
|
+
for (let end = begin + 1; end < index; end += 1) insideWord.add(end)
|
|
78
95
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
96
|
+
}
|
|
97
|
+
const segments = []
|
|
98
|
+
let start = 0
|
|
99
|
+
while (start < parts.length) {
|
|
100
|
+
// Boundary whitespace has no meaning outside a passage, and must not create
|
|
101
|
+
// an empty fragment (even for targetLength=1 or punctuation-free input).
|
|
102
|
+
while (start < parts.length && /^\s+$/u.test(parts[start])) start += 1
|
|
103
|
+
if (start === parts.length) break
|
|
104
|
+
const remaining = widths.at(-1) - widths[start]
|
|
105
|
+
if (remaining <= hard) {
|
|
106
|
+
segments.push(source.slice(offsets[start]).trim())
|
|
107
|
+
break
|
|
108
|
+
}
|
|
109
|
+
// Plan balanced passages rather than greedily producing a 20-character tail.
|
|
110
|
+
const count = Math.max(2, Math.round(remaining / target), Math.ceil(remaining / hard))
|
|
111
|
+
const ideal = remaining / count
|
|
112
|
+
const minimum = Math.min(target * 0.55, ideal * 0.7)
|
|
113
|
+
let best = start + 1
|
|
114
|
+
let bestScore = Infinity
|
|
115
|
+
for (let end = start + 1; end <= parts.length; end += 1) {
|
|
116
|
+
const width = widths[end] - widths[start]
|
|
117
|
+
if (width > hard && end > start + 1) break
|
|
118
|
+
if (insideWord.has(end)) continue
|
|
119
|
+
// Discourage short tails, but preserve a fitting word even when no fully
|
|
120
|
+
// balanced cut exists. Chapters and indivisible tokens are never merged.
|
|
121
|
+
const tail = widths.at(-1) - widths[end]
|
|
122
|
+
const priority = boundaryPriority(parts, end, sentenceEnds.has(offsets[end]))
|
|
123
|
+
const shortPenalty = (width < minimum ? target : 0) + (tail < minimum ? target : 0)
|
|
124
|
+
const score = Math.abs(width - ideal) + priority * target + shortPenalty
|
|
125
|
+
if (score < bestScore) {
|
|
126
|
+
bestScore = score
|
|
127
|
+
best = end
|
|
89
128
|
}
|
|
90
129
|
}
|
|
130
|
+
const passage = source.slice(offsets[start], offsets[best]).trim()
|
|
131
|
+
if (passage) segments.push(passage)
|
|
132
|
+
start = best
|
|
91
133
|
}
|
|
92
|
-
|
|
93
|
-
for (const paragraph of paragraphs) append(paragraph)
|
|
94
|
-
flush()
|
|
95
134
|
return segments
|
|
96
135
|
}
|
|
97
136
|
|
|
98
|
-
function
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
137
|
+
function boundaryPriority(parts, end, sentenceEnd) {
|
|
138
|
+
const previous = parts[end - 1]
|
|
139
|
+
const next = parts[end] ?? ''
|
|
140
|
+
if (previous === '\n' && parts[end - 2] === '\n') return 0
|
|
141
|
+
if (previous === '\n') return 0.08
|
|
142
|
+
// Neither leave an opening quote behind nor strand a closing quote/punctuation.
|
|
143
|
+
if (/^[“‘「『【((\[]+$/u.test(previous)
|
|
144
|
+
|| (/^["']$/u.test(previous) && /^\s$/u.test(parts[end - 2] ?? ''))
|
|
145
|
+
|| CLOSING.test(next) || /^[。!?!?,,;;::]/u.test(next)) return 2
|
|
146
|
+
if (sentenceEnd) return 0.10
|
|
147
|
+
let index = end - 1
|
|
148
|
+
while (index >= 0 && (/^\s+$/u.test(parts[index]) || CLOSING.test(parts[index]))) index -= 1
|
|
149
|
+
if (/[。!?!?…]$/u.test(parts[index] ?? '')
|
|
150
|
+
|| (typeof Intl.Segmenter !== 'function' && /\.$/u.test(parts[index] ?? ''))) return 0.10
|
|
151
|
+
if (/[,,;;::]$/u.test(parts[index] ?? '')) return 0.22
|
|
152
|
+
if (/^\s+$/u.test(previous) || /^\s+$/u.test(next)) return 0.30
|
|
153
|
+
// A Latin word may exceed the budget; only then fall back to a grapheme cut.
|
|
154
|
+
return WIDE.test(previous) || WIDE.test(next) ? 0.48 : 2
|
|
105
155
|
}
|
|
106
156
|
|
|
107
|
-
function
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
let end = Math.min(start + limit, points.length)
|
|
112
|
-
if (end < points.length) {
|
|
113
|
-
const minimum = start + Math.floor(limit * 0.65)
|
|
114
|
-
for (let index = end; index > minimum; index -= 1) {
|
|
115
|
-
if (/\s/u.test(points[index - 1] ?? '')) {
|
|
116
|
-
end = index
|
|
117
|
-
break
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
const piece = points.slice(start, end).join('').trim()
|
|
122
|
-
if (piece) pieces.push(piece)
|
|
123
|
-
start = end
|
|
124
|
-
}
|
|
125
|
-
return pieces
|
|
157
|
+
function displayWidth(part) {
|
|
158
|
+
if (part === '\n') return 40
|
|
159
|
+
if (part === '\t') return 4
|
|
160
|
+
return WIDE.test(part) || /\p{Regional_Indicator}/u.test(part) ? 2 : 1
|
|
126
161
|
}
|
|
127
162
|
|
|
128
|
-
function
|
|
129
|
-
|
|
163
|
+
function graphemes(text) {
|
|
164
|
+
if (typeof Intl.Segmenter === 'function') {
|
|
165
|
+
return Array.from(new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(text), item => item.segment)
|
|
166
|
+
}
|
|
167
|
+
// Conservative fallback for older hosts: keep marks, variation selectors,
|
|
168
|
+
// emoji modifiers, ZWJ sequences and regional-indicator flag pairs together.
|
|
169
|
+
const parts = []
|
|
170
|
+
let regionalCount = 0
|
|
171
|
+
for (const point of text) {
|
|
172
|
+
const regional = /\p{Regional_Indicator}/u.test(point)
|
|
173
|
+
if (parts.length && (/^[\p{Mark}\p{Emoji_Modifier}\u200d\ufe0e\ufe0f]$/u.test(point)
|
|
174
|
+
|| parts.at(-1).endsWith('\u200d') || (regional && regionalCount % 2 === 1))) {
|
|
175
|
+
parts[parts.length - 1] += point
|
|
176
|
+
} else parts.push(point)
|
|
177
|
+
regionalCount = regional ? regionalCount + 1 : 0
|
|
178
|
+
}
|
|
179
|
+
return parts
|
|
130
180
|
}
|
|
131
181
|
|
|
132
182
|
function positiveInteger(value) {
|
|
133
|
-
if (!Number.
|
|
183
|
+
if (!Number.isSafeInteger(value) || value < 1) throw new RangeError('分段长度必须是正整数')
|
|
134
184
|
return value
|
|
135
185
|
}
|
package/src/settings.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { TARGET_TYPES } from './store.js'
|
|
2
|
+
import { PG_NOTICE } from './pg-notice.js'
|
|
2
3
|
|
|
3
4
|
const TYPE_LABELS = { reasoning: 'typeReasoning', 'tool-call': 'typeToolCall', 'read-file': 'typeReadFile', command: 'typeCommand', 'file-search': 'typeFileSearch' }
|
|
4
5
|
const MAIN_TITLES = ['', '思考', '分析', '检查', 'Thinking']
|
|
@@ -6,7 +7,7 @@ const EXTRA_TITLES = ['', 'Checking project structure', 'Analyzing the request',
|
|
|
6
7
|
|
|
7
8
|
// Only layout belongs to the plugin. Controls, menus, focus and dialogs belong to DSH.
|
|
8
9
|
const STYLES = `
|
|
9
|
-
.novel-fish-settings{display:flex;flex-direction:column;gap:
|
|
10
|
+
.novel-fish-settings{display:flex;flex-direction:column;gap:24px;min-width:0;font-size:14px;line-height:1.6;color:var(--dsw-alias-label-primary)}
|
|
10
11
|
.novel-fish-settings .novel-fish-section{display:flex;flex-direction:column;gap:16px;min-width:0}
|
|
11
12
|
.novel-fish-settings .novel-fish-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}
|
|
12
13
|
.novel-fish-settings h3{margin:0;font:inherit;font-weight:600}
|
|
@@ -17,6 +18,13 @@ const STYLES = `
|
|
|
17
18
|
.novel-fish-settings .novel-fish-selection{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
|
|
18
19
|
.novel-fish-settings .novel-fish-hint{margin:0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.6}
|
|
19
20
|
.novel-fish-settings .novel-fish-error{color:var(--dsw-alias-state-error-primary)}
|
|
21
|
+
.novel-fish-settings .novel-fish-progress{width:100%;height:4px;border:0;border-radius:4px;overflow:hidden;accent-color:var(--dsw-alias-label-secondary);appearance:none}
|
|
22
|
+
.novel-fish-progress::-webkit-progress-bar{background:var(--dsw-alias-border-l2)}
|
|
23
|
+
.novel-fish-progress::-webkit-progress-value{background:var(--dsw-alias-label-secondary)}
|
|
24
|
+
.novel-fish-progress::-moz-progress-bar{background:var(--dsw-alias-label-secondary)}
|
|
25
|
+
.novel-fish-book-info{display:flex;flex-direction:column;gap:20px;max-height:60vh;overflow-y:auto;font-size:13px;line-height:1.6}
|
|
26
|
+
.novel-fish-book-info .novel-fish-field{display:flex;flex-direction:column;gap:4px}
|
|
27
|
+
.novel-fish-book-info p{margin:0}
|
|
20
28
|
`
|
|
21
29
|
|
|
22
30
|
/** Embedded in this bundle's official configuration slot; never a reading page. */
|
|
@@ -67,7 +75,7 @@ export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, I
|
|
|
67
75
|
)
|
|
68
76
|
}
|
|
69
77
|
|
|
70
|
-
function SettingsRow({ t, useNovelState, useNovelUi, onSetOption, onSetNotice, onSelectBook, onDeleteBook, onImportFile }) {
|
|
78
|
+
function SettingsRow({ t, useNovelState, useNovelUi, onSetOption, onSetNotice, onSelectBook, onDeleteBook, onImportFile, sampleBooks = [], getSampleLicenseHref }) {
|
|
71
79
|
const state = useNovelState(value => value)
|
|
72
80
|
const ui = useNovelUi(value => value)
|
|
73
81
|
const [busy, setBusy] = React.useState(false)
|
|
@@ -76,6 +84,7 @@ export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, I
|
|
|
76
84
|
const [savingContinue, setSavingContinue] = React.useState(false)
|
|
77
85
|
const [removeBook, setRemoveBook] = React.useState(null)
|
|
78
86
|
const [removeError, setRemoveError] = React.useState(null)
|
|
87
|
+
const [bookInfoOpen, setBookInfoOpen] = React.useState(false)
|
|
79
88
|
const enabling = React.useRef(false)
|
|
80
89
|
const continuing = React.useRef(false)
|
|
81
90
|
const changingTypes = React.useRef(false)
|
|
@@ -149,13 +158,18 @@ export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, I
|
|
|
149
158
|
),
|
|
150
159
|
h('input', { ref: fileInput, hidden: true, type: 'file', accept: '.epub,.txt,.md,application/epub+zip,text/plain,text/markdown', onChange: event => { void importFile(event) }, disabled, 'data-novel-file-input': true }),
|
|
151
160
|
h('div', { className: 'novel-fish-field' },
|
|
152
|
-
h('span', null, t('settings.selectBook')),
|
|
153
161
|
h(SelectMenu, {
|
|
154
|
-
label: t('settings.selectBook'), value: state.settings.currentBookId ?? '', disabled
|
|
162
|
+
label: t('settings.selectBook'), value: state.settings.currentBookId ?? '', disabled,
|
|
155
163
|
marker: { 'data-novel-book-select': true },
|
|
156
164
|
items: [{ id: '', label: t('settings.noBook') }, ...state.books.map(book => ({ id: book.id, label: `${book.title} · ${book.format.toUpperCase()}` }))],
|
|
157
|
-
|
|
165
|
+
footer: sampleBooks.length ? [{ id: '__book-info', label: t('settings.bookInfo') }] : undefined,
|
|
166
|
+
onChange: id => {
|
|
167
|
+
if (id === '__book-info') setBookInfoOpen(true)
|
|
168
|
+
else void perform(() => onSelectBook(id))
|
|
169
|
+
},
|
|
158
170
|
}),
|
|
171
|
+
selectedBook ? h('progress', { className: 'novel-fish-progress', value: selectedBook.progress,
|
|
172
|
+
max: selectedBook.segmentCount, 'aria-label': t('settings.readingProgress') }) : null,
|
|
159
173
|
),
|
|
160
174
|
selectedBook ? h('div', { className: 'novel-fish-row' },
|
|
161
175
|
h('span', { className: 'novel-fish-hint', 'data-novel-progress': true }, t('settings.progressValue', { progress: selectedBook.progress, total: selectedBook.segmentCount, percent: Math.floor(selectedBook.progress / selectedBook.segmentCount * 100) })),
|
|
@@ -178,13 +192,11 @@ export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, I
|
|
|
178
192
|
footer: [{ id: '__all', label: t(state.settings.targetTypes.length === TARGET_TYPES.length ? 'settings.clearTypes' : 'settings.allTypes') }],
|
|
179
193
|
onChange: type => { void setTypes(type === '__all' ? (state.settings.targetTypes.length === TARGET_TYPES.length ? [] : [...TARGET_TYPES]) : TARGET_TYPES.filter(value => value === type ? !state.settings.targetTypes.includes(type) : state.settings.targetTypes.includes(value))) },
|
|
180
194
|
}),
|
|
181
|
-
h('p', { className: 'novel-fish-hint' }, t('settings.typeHint')),
|
|
182
195
|
),
|
|
183
196
|
h('div', { className: 'novel-fish-row' },
|
|
184
197
|
h('span', null, t('settings.continueOnReopen')),
|
|
185
198
|
h(Switch, { checked: state.settings.continueOnReopen === true, disabled: disabled || savingContinue, label: t('settings.continueOnReopen'), onChange: enabled => { void setContinue(enabled) } }),
|
|
186
199
|
),
|
|
187
|
-
h('p', { className: 'novel-fish-hint' }, t('settings.continueOnReopenHint')),
|
|
188
200
|
),
|
|
189
201
|
h('section', { className: 'novel-fish-section' },
|
|
190
202
|
h('h3', null, t('settings.appearance')),
|
|
@@ -197,9 +209,21 @@ export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, I
|
|
|
197
209
|
onChange: value => perform(() => onSetOption(key, value)),
|
|
198
210
|
})),
|
|
199
211
|
),
|
|
200
|
-
h('p', { className: 'novel-fish-hint' }, t('settings.nativeControls')),
|
|
201
212
|
),
|
|
202
213
|
ui.notice ? h('div', { role: 'status', 'data-novel-notice': true }, ui.notice) : null,
|
|
214
|
+
bookInfoOpen ? h(Modal, {
|
|
215
|
+
open: true, onClose: () => setBookInfoOpen(false), title: t('settings.bookInfo'), closeLabel: t('settings.close'),
|
|
216
|
+
}, h('div', { className: 'novel-fish-book-info', 'data-novel-book-info': true },
|
|
217
|
+
...sampleBooks.map(book => h('div', { key: book.id, className: 'novel-fish-field' },
|
|
218
|
+
h('a', { href: book.source, target: '_blank', rel: 'noreferrer' }, book.title),
|
|
219
|
+
h('span', null, book.author), h('span', null, book.license),
|
|
220
|
+
)),
|
|
221
|
+
h('a', { href: getSampleLicenseHref?.(), download: 'bundled-ebooks-notices.txt' }, t('settings.sampleLicense')),
|
|
222
|
+
h('p', { 'data-novel-sample-license': true }, t('settings.samplePgNotice'), ' ',
|
|
223
|
+
PG_NOTICE, ' ',
|
|
224
|
+
h('a', { href: 'https://www.gutenberg.org/policy/license.html', target: '_blank', rel: 'noreferrer' }, 'www.gutenberg.org'),
|
|
225
|
+
),
|
|
226
|
+
)) : null,
|
|
203
227
|
h(Modal, {
|
|
204
228
|
open: Boolean(removeBook), onClose: closeRemove, title: t('settings.deleteBook'), closeLabel: t('settings.cancel'),
|
|
205
229
|
description: removeBook ? t('settings.removeConfirm', { title: removeBook.title }) : '',
|
package/src/store.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { parseEpub } from './epub.js'
|
|
2
2
|
import { DEFAULT_SEGMENT_LENGTH, parseTextBook } from './segments.js'
|
|
3
3
|
import { decodeBookText } from './text-decoding.js'
|
|
4
|
+
import { hasProjectGutenbergReference } from './pg-notice.js'
|
|
4
5
|
|
|
5
6
|
export const TARGET_TYPES = Object.freeze(['reasoning', 'tool-call', 'read-file', 'command', 'file-search'])
|
|
6
7
|
|
|
@@ -21,8 +22,10 @@ export function passageSnapshotKey(bookId, stepKey) {
|
|
|
21
22
|
|
|
22
23
|
/** Own persistent books/settings and page-only passage cache for Novel Fish. */
|
|
23
24
|
export class NovelStore {
|
|
24
|
-
constructor(storage) {
|
|
25
|
+
constructor(storage, { bundledBooks = [], bundledCatalog = null } = {}) {
|
|
25
26
|
this.storage = storage
|
|
27
|
+
this.bundledBooks = bundledBooks
|
|
28
|
+
this.bundledCatalog = bundledCatalog
|
|
26
29
|
this.state = { books: [], settings: { ...DEFAULT_SETTINGS }, hydrated: false, error: null }
|
|
27
30
|
this.ui = { notice: null }
|
|
28
31
|
this.listeners = new Set()
|
|
@@ -36,6 +39,9 @@ export class NovelStore {
|
|
|
36
39
|
this.uiSource = Object.freeze({ getSnapshot: this.getUiSnapshot, subscribe: this.subscribeUi })
|
|
37
40
|
this.passageSource = Object.freeze({ getSnapshot: this.getPassageSnapshot, subscribe: this.subscribePassages })
|
|
38
41
|
this.pendingReads = new Map()
|
|
42
|
+
// Page-only provenance, keyed by stored identity (including adopted legacy IDs).
|
|
43
|
+
// No library rewrite/migration and no dependence on mutable titles or filenames.
|
|
44
|
+
this.projectGutenbergBooks = new Map()
|
|
39
45
|
this.cacheGeneration = 0
|
|
40
46
|
this.disposed = false
|
|
41
47
|
this.persistenceError = null
|
|
@@ -64,6 +70,7 @@ export class NovelStore {
|
|
|
64
70
|
this.passageStates.clear()
|
|
65
71
|
this.passageSnapshot = Object.freeze({})
|
|
66
72
|
this.pendingReads.clear()
|
|
73
|
+
this.projectGutenbergBooks.clear()
|
|
67
74
|
this.listeners.clear()
|
|
68
75
|
this.settingsListeners.clear()
|
|
69
76
|
this.uiListeners.clear()
|
|
@@ -140,6 +147,7 @@ export class NovelStore {
|
|
|
140
147
|
await this.#restore(() => this.storage.saveSettings(previousSettings))
|
|
141
148
|
throw error
|
|
142
149
|
}
|
|
150
|
+
this.projectGutenbergBooks.delete(bookId)
|
|
143
151
|
this.#setState({ books, settings })
|
|
144
152
|
if (settings.currentBookId !== previousSettings.currentBookId) this.#clearPassages(false)
|
|
145
153
|
})
|
|
@@ -187,6 +195,15 @@ export class NovelStore {
|
|
|
187
195
|
const passage = await this.storage.getSegment(bookId, index)
|
|
188
196
|
if (!passage?.text) throw new Error('当前段落为空或已损坏')
|
|
189
197
|
if (!this.#canRead(generation, targetType)) return EMPTY_STATUS
|
|
198
|
+
if (!this.projectGutenbergBooks.has(bookId)) {
|
|
199
|
+
// A resumed book may be far beyond the header. Inspect segment zero once
|
|
200
|
+
// per book/page, reusing the claimed segment when starting at zero.
|
|
201
|
+
const first = index === 0 ? passage : await this.storage.getSegment(bookId, 0)
|
|
202
|
+
if (!this.#canRead(generation, targetType)) return EMPTY_STATUS
|
|
203
|
+
if (!first?.text) throw new Error('书籍首段为空或已损坏')
|
|
204
|
+
this.projectGutenbergBooks.set(bookId, hasProjectGutenbergReference(first.text))
|
|
205
|
+
}
|
|
206
|
+
const projectGutenberg = this.projectGutenbergBooks.get(bookId)
|
|
190
207
|
|
|
191
208
|
const updated = { ...book, progress: index + 1 }
|
|
192
209
|
await this.storage.updateBook(updated)
|
|
@@ -194,7 +211,7 @@ export class NovelStore {
|
|
|
194
211
|
await this.#restore(() => this.storage.updateBook(book))
|
|
195
212
|
return EMPTY_STATUS
|
|
196
213
|
}
|
|
197
|
-
const result = { kind: 'ready', bookId, index, passage }
|
|
214
|
+
const result = { kind: 'ready', bookId, index, passage, projectGutenberg }
|
|
198
215
|
this.#setState({ books: this.state.books.map(item => item.id === bookId ? updated : item) })
|
|
199
216
|
return this.#writePassageStatus(bookId, stepKey, result)
|
|
200
217
|
}).catch(error => {
|
|
@@ -217,7 +234,48 @@ export class NovelStore {
|
|
|
217
234
|
|
|
218
235
|
async #hydrate() {
|
|
219
236
|
try {
|
|
220
|
-
|
|
237
|
+
let stored = await this.storage.load()
|
|
238
|
+
if (this.bundledBooks.length && !stored.bundledBooksInitialized) {
|
|
239
|
+
const entries = []
|
|
240
|
+
const bundledIds = new Set()
|
|
241
|
+
// Parse everything before opening the atomic transaction; any failure leaves
|
|
242
|
+
// both the library and its one-time marker untouched for a later retry.
|
|
243
|
+
for (const descriptor of this.bundledBooks) {
|
|
244
|
+
const { id, title, format, createFile } = descriptor
|
|
245
|
+
if (typeof id !== 'string' || !id || bundledIds.has(id) || typeof title !== 'string' || !title.trim()
|
|
246
|
+
|| !['epub', 'txt', 'md'].includes(format) || typeof createFile !== 'function') {
|
|
247
|
+
throw new Error('内置书籍描述无效或重复')
|
|
248
|
+
}
|
|
249
|
+
bundledIds.add(id)
|
|
250
|
+
const file = await createFile()
|
|
251
|
+
const parsed = format === 'epub'
|
|
252
|
+
? await parseEpub(file, DEFAULT_SEGMENT_LENGTH)
|
|
253
|
+
: parseTextBook(decodeBookText(await file.arrayBuffer()), format, DEFAULT_SEGMENT_LENGTH)
|
|
254
|
+
entries.push({
|
|
255
|
+
book: {
|
|
256
|
+
id: `bundled:${id}`, bundledId: id, title: title.trim(), format,
|
|
257
|
+
segmentCount: parsed.segments.length, progress: 0, importedAt: Date.now(),
|
|
258
|
+
},
|
|
259
|
+
segments: parsed.segments,
|
|
260
|
+
})
|
|
261
|
+
}
|
|
262
|
+
// Hydration must not enqueue a mutation that would itself await ready.
|
|
263
|
+
stored = await this.storage.initializeBundledBooks(entries, this.bundledCatalog?.version)
|
|
264
|
+
}
|
|
265
|
+
if (stored.bundledBooksInitialized && this.bundledCatalog
|
|
266
|
+
&& (stored.bundledCatalogVersion ?? 0) < this.bundledCatalog.version) {
|
|
267
|
+
const updates = []
|
|
268
|
+
for (const update of this.bundledCatalog.updates ?? []) {
|
|
269
|
+
// An empty/partially deleted library does not need to parse removed
|
|
270
|
+
// defaults. The atomic migration rechecks identity and current content.
|
|
271
|
+
if (!(stored.books ?? []).some(book => (book.bundledId === update.id || book.id === `bundled:${update.id}`)
|
|
272
|
+
&& book.format === update.fromFormat)) continue
|
|
273
|
+
const file = await update.createFile()
|
|
274
|
+
const parsed = parseTextBook(decodeBookText(await file.arrayBuffer()), update.fromFormat, DEFAULT_SEGMENT_LENGTH)
|
|
275
|
+
updates.push({ id: update.id, fromFormat: update.fromFormat, format: update.format, segments: parsed.segments })
|
|
276
|
+
}
|
|
277
|
+
stored = await this.storage.migrateBundledCatalog({ ...this.bundledCatalog, updates })
|
|
278
|
+
}
|
|
221
279
|
const books = stored.books ?? []
|
|
222
280
|
const storedSettings = stored.settings ?? {}
|
|
223
281
|
const availableIds = new Set(books.map(book => book.id))
|