@gongfpp/dsh-novel-fish 1.0.1 → 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.
Files changed (91) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +65 -22
  3. package/docs/evidence/reading-demo-110.png +0 -0
  4. package/docs/evidence/settings-reliability.png +0 -0
  5. package/index.json +24 -0
  6. package/lib/client.js +1225 -191
  7. package/locale/en.json +21 -0
  8. package/locale/zh.json +21 -0
  9. package/package.json +6 -7
  10. package/samples/ebooks/LICENSE.md +355 -0
  11. package/samples/ebooks/NOTICE.md +33 -0
  12. package/samples/ebooks/aq-zheng-zhuan-wikisource.md +998 -0
  13. package/samples/ebooks/million-pound-bank-note-pg61522.txt +6970 -0
  14. package/samples/ebooks/sources.json +58 -0
  15. package/screenshots.json +6 -0
  16. package/docs/acceptance.md +0 -42
  17. package/docs/community-markets.md +0 -71
  18. package/docs/compatibility-017.md +0 -70
  19. package/docs/compatibility-101.md +0 -41
  20. package/docs/continuous-reading-020.md +0 -46
  21. package/docs/evidence/abc-result.json +0 -9
  22. package/docs/evidence/banner-100.png +0 -0
  23. package/docs/evidence/community-market-014-result.json +0 -170
  24. package/docs/evidence/compatibility-017-result.json +0 -65
  25. package/docs/evidence/continuous-reading-020-result.json +0 -72
  26. package/docs/evidence/formats-result.json +0 -12
  27. package/docs/evidence/live-ab.png +0 -0
  28. package/docs/evidence/live-collapsed.png +0 -0
  29. package/docs/evidence/live-disabled.png +0 -0
  30. package/docs/evidence/live-epub.png +0 -0
  31. package/docs/evidence/live-market.png +0 -0
  32. package/docs/evidence/live-resume.png +0 -0
  33. package/docs/evidence/live-unloaded.png +0 -0
  34. package/docs/evidence/long-result.json +0 -11
  35. package/docs/evidence/multi-region-014-result.json +0 -47
  36. package/docs/evidence/native-disclosure-013-result.json +0 -36
  37. package/docs/evidence/native-disclosures-013.png +0 -0
  38. package/docs/evidence/native-open-013.png +0 -0
  39. package/docs/evidence/native-settings-sample.md +0 -11
  40. package/docs/evidence/native-settings-types-015.png +0 -0
  41. package/docs/evidence/npm-market-014-result.json +0 -132
  42. package/docs/evidence/plugin-settings-details.png +0 -0
  43. package/docs/evidence/public-release-014-result.json +0 -51
  44. package/docs/evidence/public-release-015-result.json +0 -36
  45. package/docs/evidence/public-release-result.json +0 -48
  46. package/docs/evidence/reading-demo-100.png +0 -0
  47. package/docs/evidence/settings-011-result.json +0 -28
  48. package/docs/evidence/settings-011.png +0 -0
  49. package/docs/evidence/settings-100.png +0 -0
  50. package/docs/evidence/settings-chat-011.png +0 -0
  51. package/docs/evidence/type-append-012-result.json +0 -30
  52. package/docs/evidence/type-append-012.png +0 -0
  53. package/docs/evidence/type-settings-012.png +0 -0
  54. package/docs/evidence/unload-result.json +0 -7
  55. package/docs/host-adapter.md +0 -43
  56. package/docs/icon-metadata-021.md +0 -40
  57. package/docs/interaction-paths-020.md +0 -39
  58. package/docs/marketplace.md +0 -42
  59. package/docs/multi-region-update.md +0 -53
  60. package/docs/native-disclosure-update.md +0 -39
  61. package/docs/native-settings-update.md +0 -48
  62. package/docs/plugin-settings-update.md +0 -61
  63. package/docs/release.md +0 -139
  64. package/docs/settings-update.md +0 -49
  65. package/docs/type-append-update.md +0 -50
  66. package/pnpm-workspace.yaml +0 -5
  67. package/scripts/build.mjs +0 -69
  68. package/scripts/check-host-contracts.mjs +0 -246
  69. package/scripts/licenses/path-webpack.txt +0 -28
  70. package/src/chat-adapter.js +0 -253
  71. package/src/client.js +0 -55
  72. package/src/epub.js +0 -166
  73. package/src/novel-content.js +0 -20
  74. package/src/persistence.js +0 -130
  75. package/src/segments.js +0 -135
  76. package/src/settings.js +0 -219
  77. package/src/store.js +0 -371
  78. package/src/text-decoding.js +0 -28
  79. package/test/chat-adapter.test.js +0 -433
  80. package/test/client.test.js +0 -82
  81. package/test/epub.test.js +0 -185
  82. package/test/helpers/host-primitives.js +0 -28
  83. package/test/helpers/memory-storage.js +0 -48
  84. package/test/host-contracts.test.js +0 -32
  85. package/test/import.test.js +0 -102
  86. package/test/persistence.test.js +0 -27
  87. package/test/release.test.js +0 -85
  88. package/test/segments.test.js +0 -48
  89. package/test/settings.test.js +0 -271
  90. package/test/store.test.js +0 -617
  91. package/test/text-decoding.test.js +0 -49
package/src/epub.js DELETED
@@ -1,166 +0,0 @@
1
- import JSZip from 'jszip'
2
- import CRC32 from 'crc-32'
3
- import { decodeBookText } from './text-decoding.js'
4
- import { DOMParser } from '@xmldom/xmldom'
5
- import containerModule from 'epubjs/lib/container.js'
6
- import packagingModule from 'epubjs/lib/packaging.js'
7
- import navigationModule from 'epubjs/lib/navigation.js'
8
- import { segmentChapters } from './segments.js'
9
-
10
- // Use epubjs's actual container/OPF/navigation parsers, not its rendering lifecycle.
11
- const Container = containerModule.default ?? containerModule
12
- const Packaging = packagingModule.default ?? packagingModule
13
- const Navigation = navigationModule.default ?? navigationModule
14
- const ORIGIN = 'https://local-epub.invalid/'
15
- const MAX_UNPACKED_BYTES = 128 * 1024 * 1024
16
-
17
- /** Parse an EPUB's declared linear spine once; no iframe, script, CSS, or network is used. */
18
- export async function parseEpub(file, targetLength = 600) {
19
- try {
20
- // 不启用全包 CRC 检查:它会在读取正文前解压所有未引用资源。
21
- const zip = await JSZip.loadAsync(await file.arrayBuffer())
22
- const budget = { remaining: MAX_UNPACKED_BYTES }
23
- const readXml = async path => {
24
- const entry = zip.file(path)
25
- if (!entry) throw new Error(`书内文件缺失:${path}`)
26
- const bytes = await readEntry(entry, budget)
27
- const source = decodeBookText(bytes, { xml: true })
28
- if (/<!ENTITY|<!DOCTYPE[^>]*\[/iu.test(source)) throw new Error(`不支持含外部实体声明的书内文件:${path}`)
29
- return new DOMParser({
30
- onError(level, message) { if (level !== 'warning') throw new Error(`${path}: ${message}`) },
31
- }).parseFromString(source, 'application/xml')
32
- }
33
- const container = new Container(await readXml('META-INF/container.xml'))
34
- const packagePath = archivePath(container.packagePath)
35
- const packaging = new Packaging(await readXml(packagePath))
36
- const navPath = packaging.navPath || packaging.ncxPath
37
- const navigation = navPath ? new Navigation(await readXml(archivePath(navPath, packagePath))) : null
38
- const labels = tocLabels(navigation?.toc ?? [], packagePath)
39
- const chapters = []
40
- for (const item of packaging.spine) {
41
- if (item.linear === 'no') continue
42
- const manifest = packaging.manifest[item.idref]
43
- if (!manifest) throw new Error(`阅读顺序引用了缺失章节:${item.idref}`)
44
- if (!['application/xhtml+xml', 'text/html'].includes(manifest.type)) {
45
- throw new Error(`不支持的章节格式:${manifest.type}`)
46
- }
47
- const path = archivePath(manifest.href, packagePath)
48
- const document = await readXml(path)
49
- const body = document.getElementsByTagNameNS('http://www.w3.org/1999/xhtml', 'body')[0]
50
- || document.getElementsByTagNameNS(null, 'body')[0]
51
- if (!body) throw new Error(`章节没有正文:${path}`)
52
- const sectionTitle = labels.get(path) || manifest.href.replace(/\.[^.]+$/u, '')
53
- let current = { title: sectionTitle, paragraphs: [] }
54
- const flush = () => {
55
- const text = current.paragraphs.join('\n\n').trim()
56
- if (text) chapters.push({ title: current.title, text })
57
- current = { title: sectionTitle, paragraphs: [] }
58
- }
59
- for (const block of extractBlocks(body)) {
60
- if (block.kind === 'heading') {
61
- flush()
62
- current = { title: block.text, paragraphs: [] }
63
- } else current.paragraphs.push(block.text)
64
- }
65
- flush()
66
- }
67
- const segments = segmentChapters(chapters, targetLength)
68
- if (!segments.length) throw new Error('EPUB 没有可读取的线性正文')
69
- return { chapters, segments, title: packaging.metadata.title || '' }
70
- } catch (error) {
71
- throw new Error(`EPUB 无法解析:${error instanceof Error ? error.message : String(error)}`)
72
- }
73
- }
74
-
75
- // 使用 JSZip 的分块流而非 async() 的全量累积,预算在保存每个块之前扣除。
76
- function readEntry(entry, budget) {
77
- return new Promise((resolve, reject) => {
78
- const stream = entry.internalStream('uint8array')
79
- let chunks = []
80
- let length = 0
81
- let checksum = 0
82
- let settled = false
83
- const fail = error => {
84
- if (settled) return
85
- settled = true
86
- // pause 会停止后续压缩输入;当前 inflate 输入仍可能产出少量块,回调不再保留它们。
87
- stream.pause()
88
- chunks = []
89
- reject(error)
90
- }
91
- stream.on('data', chunk => {
92
- if (settled) return
93
- if (chunk.byteLength > budget.remaining) {
94
- fail(new Error('EPUB 解压正文超过 128 MiB,请使用较小书籍'))
95
- return
96
- }
97
- budget.remaining -= chunk.byteLength
98
- length += chunk.byteLength
99
- checksum = CRC32.buf(chunk, checksum)
100
- chunks.push(chunk)
101
- }).on('error', fail).on('end', () => {
102
- if (settled) return
103
- // JSZip 未公开期望 CRC;此字段来自它解析的中央目录,只用于校验实际读取项。
104
- if ((checksum >>> 0) !== (entry._data.crc32 >>> 0)) {
105
- fail(new Error(`书内文件 CRC 校验失败:${entry.name}`))
106
- return
107
- }
108
- const bytes = new Uint8Array(length)
109
- let offset = 0
110
- for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength }
111
- chunks = []
112
- settled = true
113
- resolve(bytes)
114
- }).resume()
115
- })
116
- }
117
-
118
- function archivePath(href, base = '') {
119
- const url = new URL(href, new URL(base, ORIGIN))
120
- if (url.origin !== new URL(ORIGIN).origin || url.search) throw new Error('EPUB 只能引用书内文件')
121
- return decodeURIComponent(url.pathname.slice(1))
122
- }
123
-
124
- function hidden(node) {
125
- const tag = String(node.localName ?? node.nodeName).toLowerCase()
126
- return ['script', 'style', 'noscript', 'iframe', 'object', 'svg', 'nav'].includes(tag)
127
- || node.hasAttribute('hidden') || node.getAttribute('aria-hidden') === 'true'
128
- || /(?:display\s*:\s*none|visibility\s*:\s*hidden)/iu.test(node.getAttribute('style') || '')
129
- }
130
-
131
- function extractBlocks(root) {
132
- const blocks = []
133
- const blockTags = new Set(['div', 'section', 'article', 'aside', 'main', 'header', 'footer', 'address',
134
- 'p', 'li', 'ul', 'ol', 'blockquote', 'pre', 'figure', 'figcaption', 'dl', 'dt', 'dd',
135
- 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'hr'])
136
- let pending = ''
137
- let kind = 'paragraph'
138
- const flush = () => {
139
- const text = pending.replace(/\u00a0/gu, ' ').trim()
140
- if (text) blocks.push({ kind, text })
141
- pending = ''
142
- }
143
- const walk = node => {
144
- if (node.nodeType === 3 || node.nodeType === 4) { pending += node.nodeValue || ''; return }
145
- if (node.nodeType !== 1 || hidden(node)) return
146
- const tag = String(node.localName ?? node.nodeName).toLowerCase()
147
- if (tag === 'br') { pending += '\n'; return }
148
- const heading = /^h[1-6]$/u.test(tag)
149
- const block = heading || blockTags.has(tag)
150
- const previousKind = kind
151
- if (block) { flush(); kind = heading ? 'heading' : 'paragraph' }
152
- for (const child of Array.from(node.childNodes ?? [])) walk(child)
153
- if (block) { flush(); kind = previousKind }
154
- }
155
- walk(root)
156
- flush()
157
- return blocks
158
- }
159
-
160
- function tocLabels(items, base, labels = new Map()) {
161
- for (const item of items) {
162
- if (item.href && item.label) labels.set(archivePath(item.href, base), String(item.label).trim())
163
- tocLabels(item.subitems ?? item.items ?? [], base, labels)
164
- }
165
- return labels
166
- }
@@ -1,20 +0,0 @@
1
- // 小说只作为纯文本呈现,不交给 Markdown / 数学 / 自动链接解析器。
2
- export const NOVEL_STYLE = {
3
- fontSize: 'var(--dsh-content-font-size-secondary, 13px)',
4
- lineHeight: 'var(--dsh-content-line-height-secondary, 1.6)',
5
- color: 'var(--dsw-alias-label-tertiary)',
6
- whiteSpace: 'pre-wrap', overflowWrap: 'anywhere',
7
- }
8
- export const SEPARATOR_STYLE = {
9
- border: 0, borderTop: '1px solid var(--dsw-alias-border-l2)', margin: '10px 0 8px',
10
- }
11
-
12
- export function novelContent(status, hasBook, t) {
13
- if (status.kind === 'ready') return {
14
- label: t('chat.novel'), chapter: status.passage.chapterTitle || '',
15
- text: status.passage.text, index: status.index + 1,
16
- }
17
- const message = status.kind === 'loading' ? 'chat.loading' : status.kind === 'end' ? 'chat.end'
18
- : status.kind === 'error' ? 'chat.readError' : hasBook ? 'chat.switchHint' : 'chat.noBook'
19
- return { label: t('chat.novel'), chapter: '', text: t(message), role: status.kind === 'error' ? 'alert' : 'status' }
20
- }
@@ -1,130 +0,0 @@
1
- const DATABASE_NAME = 'dsh-touch-fish-novel'
2
- const DATABASE_VERSION = 1
3
- const SETTINGS_KEY = 'settings'
4
-
5
- /** IndexedDB persistence for book metadata, parsed passages, and plugin settings. */
6
- export class IndexedDbStorage {
7
- constructor(indexedDb = globalThis.indexedDB, keyRange = globalThis.IDBKeyRange) {
8
- this.indexedDb = indexedDb
9
- this.keyRange = keyRange
10
- this.database = undefined
11
- }
12
-
13
- close() {
14
- this.database?.close()
15
- this.database = undefined
16
- }
17
-
18
- async load() {
19
- const db = await this.#open()
20
- const tx = db.transaction(['books', 'settings'], 'readonly')
21
- const done = transactionDone(tx)
22
- const books = await requestResult(tx.objectStore('books').getAll())
23
- const settings = await requestResult(tx.objectStore('settings').get(SETTINGS_KEY))
24
- await done
25
- return { books, settings: settings?.value }
26
- }
27
-
28
- async saveSettings(value) {
29
- const db = await this.#open()
30
- const tx = db.transaction('settings', 'readwrite')
31
- const done = transactionDone(tx)
32
- tx.objectStore('settings').put({ key: SETTINGS_KEY, value })
33
- await done
34
- }
35
-
36
- async addBook(book, segments) {
37
- const db = await this.#open()
38
- const tx = db.transaction(['books', 'segments'], 'readwrite')
39
- const done = transactionDone(tx)
40
- tx.objectStore('books').put(book)
41
- const segmentStore = tx.objectStore('segments')
42
- segments.forEach((segment, index) => segmentStore.put({
43
- id: `${book.id}:${index}`,
44
- bookId: book.id,
45
- index,
46
- ...segment,
47
- }))
48
- await done
49
- }
50
-
51
- async updateBook(book) {
52
- const db = await this.#open()
53
- const tx = db.transaction('books', 'readwrite')
54
- const done = transactionDone(tx)
55
- const books = tx.objectStore('books')
56
- const existing = await requestResult(books.get(book.id))
57
- if (!existing) {
58
- await done
59
- throw new Error('找不到这本书,无法保存阅读进度')
60
- }
61
- books.put(book)
62
- await done
63
- }
64
-
65
- async getSegment(bookId, index) {
66
- const db = await this.#open()
67
- const tx = db.transaction('segments', 'readonly')
68
- const done = transactionDone(tx)
69
- const result = await requestResult(tx.objectStore('segments').get(`${bookId}:${index}`))
70
- await done
71
- if (!result) return null
72
- const { id: _id, bookId: _bookId, index: _index, ...segment } = result
73
- return segment
74
- }
75
-
76
- async deleteBook(bookId) {
77
- const db = await this.#open()
78
- const tx = db.transaction(['books', 'segments'], 'readwrite')
79
- const done = transactionDone(tx)
80
- tx.objectStore('books').delete(bookId)
81
- const cursorRequest = tx.objectStore('segments').index('bookId').openCursor(this.keyRange.only(bookId))
82
- cursorRequest.onsuccess = () => {
83
- const cursor = cursorRequest.result
84
- if (!cursor) return
85
- cursor.delete()
86
- cursor.continue()
87
- }
88
- await done
89
- }
90
-
91
- async #open() {
92
- if (this.database) return this.database
93
- if (!this.indexedDb) throw new Error('当前浏览器不支持 IndexedDB')
94
- this.database = await new Promise((resolve, reject) => {
95
- const request = this.indexedDb.open(DATABASE_NAME, DATABASE_VERSION)
96
- request.onupgradeneeded = () => {
97
- const db = request.result
98
- if (!db.objectStoreNames.contains('books')) db.createObjectStore('books', { keyPath: 'id' })
99
- if (!db.objectStoreNames.contains('segments')) {
100
- const store = db.createObjectStore('segments', { keyPath: 'id' })
101
- store.createIndex('bookId', 'bookId', { unique: false })
102
- }
103
- if (!db.objectStoreNames.contains('settings')) db.createObjectStore('settings', { keyPath: 'key' })
104
- }
105
- request.onsuccess = () => resolve(request.result)
106
- request.onerror = () => reject(request.error ?? new Error('无法打开本地书库'))
107
- request.onblocked = () => reject(new Error('本地书库正在被其他页面占用,请关闭重复页面后重试'))
108
- })
109
- this.database.onversionchange = () => {
110
- this.database?.close()
111
- this.database = undefined
112
- }
113
- return this.database
114
- }
115
- }
116
-
117
- function requestResult(request) {
118
- return new Promise((resolve, reject) => {
119
- request.onsuccess = () => resolve(request.result)
120
- request.onerror = () => reject(request.error ?? new Error('本地书库读写失败'))
121
- })
122
- }
123
-
124
- function transactionDone(transaction) {
125
- return new Promise((resolve, reject) => {
126
- transaction.oncomplete = () => resolve()
127
- transaction.onerror = () => reject(transaction.error ?? new Error('本地书库事务失败'))
128
- transaction.onabort = () => reject(transaction.error ?? new Error('本地书库事务已取消'))
129
- })
130
- }
package/src/segments.js DELETED
@@ -1,135 +0,0 @@
1
- export const DEFAULT_SEGMENT_LENGTH = 600
2
-
3
- const TXT_CHAPTER = /^\s*(?:第[0-90-9零〇一二三四五六七八九十百千万两壹贰叁肆伍陆柒捌玖拾佰仟]{1,24}[章节卷篇回部](?:[\t \u3000]+[^。!?!?,,;;\r\n]{1,80})?|chapter\s+\d+(?:[\t ]+[^.!?\r\n]{1,80})?|(?:序章|楔子|前言|尾声|后记|附录)(?:[\t \u3000]+[^。!?!?,,;;\r\n]{1,80})?)\s*$/iu
4
- const MD_HEADING = /^\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*$/u
5
-
6
- /** Split plain text into chapter groups while retaining paragraph breaks. */
7
- export function textToChapters(text, format = 'txt') {
8
- const lines = String(text).replace(/^\uFEFF/u, '').replace(/\r\n?/gu, '\n').split('\n')
9
- const chapters = []
10
- let title = '正文'
11
- let body = []
12
- let sawHeading = false
13
-
14
- const flush = () => {
15
- const content = body.join('\n').trim()
16
- if (content) chapters.push({ title, text: content })
17
- body = []
18
- }
19
-
20
- for (const line of lines) {
21
- const heading = format === 'md' ? line.match(MD_HEADING) : line.match(TXT_CHAPTER)
22
- if (!heading) {
23
- body.push(line)
24
- continue
25
- }
26
- flush()
27
- title = format === 'md' ? heading[2].trim() : line.trim()
28
- sawHeading = true
29
- }
30
- flush()
31
- if (!chapters.length && !sawHeading) {
32
- const content = lines.join('\n').trim()
33
- if (content) chapters.push({ title: '正文', text: content })
34
- }
35
- return chapters
36
- }
37
-
38
- /** Segment one or more chapters once, preferring paragraph and sentence boundaries. */
39
- export function segmentChapters(chapters, targetLength = DEFAULT_SEGMENT_LENGTH) {
40
- const limit = positiveInteger(targetLength)
41
- const segments = []
42
- chapters.forEach((chapter, chapterIndex) => {
43
- for (const text of splitChapter(chapter.text, limit)) {
44
- segments.push({ text, chapterTitle: chapter.title, chapterIndex })
45
- }
46
- })
47
- return segments
48
- }
49
-
50
- /** Normalize a parsed text file into titled reading passages. */
51
- export function parseTextBook(text, format = 'txt', targetLength = DEFAULT_SEGMENT_LENGTH) {
52
- const chapters = textToChapters(text, format)
53
- const segments = segmentChapters(chapters, targetLength)
54
- if (!segments.length) throw new Error('文件里没有可阅读的正文文本')
55
- return { chapters, segments }
56
- }
57
-
58
- function splitChapter(text, limit) {
59
- const paragraphs = String(text).split(/\n\s*\n+/u).map(value => value.trim()).filter(Boolean)
60
- const segments = []
61
- let current = ''
62
-
63
- const flush = () => {
64
- if (current) segments.push(current)
65
- current = ''
66
- }
67
- const append = part => {
68
- if (!part) return
69
- const next = current ? `${current}\n\n${part}` : part
70
- if (lengthOf(next) <= limit) {
71
- current = next
72
- return
73
- }
74
- flush()
75
- if (lengthOf(part) <= limit) {
76
- current = part
77
- return
78
- }
79
- for (const sentence of splitSentences(part)) {
80
- if (lengthOf(sentence) > limit) {
81
- for (const fragment of splitLongText(sentence, limit)) append(fragment)
82
- } else {
83
- const joined = current ? `${current} ${sentence}` : sentence
84
- if (lengthOf(joined) <= limit) current = joined
85
- else {
86
- flush()
87
- current = sentence
88
- }
89
- }
90
- }
91
- }
92
-
93
- for (const paragraph of paragraphs) append(paragraph)
94
- flush()
95
- return segments
96
- }
97
-
98
- function splitSentences(text) {
99
- if (typeof Intl.Segmenter === 'function') {
100
- const segmenter = new Intl.Segmenter(undefined, { granularity: 'sentence' })
101
- const sentences = [...segmenter.segment(text)].map(item => item.segment.trim()).filter(Boolean)
102
- if (sentences.length > 1) return sentences
103
- }
104
- return text.match(/[^。!?!?;;]+[。!?!?;;…]*[”’」』】))]*|[^。!?!?;;]+$/gu)?.map(value => value.trim()).filter(Boolean) ?? [text]
105
- }
106
-
107
- function splitLongText(text, limit) {
108
- const points = [...text]
109
- const pieces = []
110
- for (let start = 0; start < points.length;) {
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
126
- }
127
-
128
- function lengthOf(text) {
129
- return [...text].length
130
- }
131
-
132
- function positiveInteger(value) {
133
- if (!Number.isInteger(value) || value < 1) throw new RangeError('分段长度必须是正整数')
134
- return value
135
- }
package/src/settings.js DELETED
@@ -1,219 +0,0 @@
1
- import { TARGET_TYPES } from './store.js'
2
-
3
- const TYPE_LABELS = { reasoning: 'typeReasoning', 'tool-call': 'typeToolCall', 'read-file': 'typeReadFile', command: 'typeCommand', 'file-search': 'typeFileSearch' }
4
- const MAIN_TITLES = ['', '思考', '分析', '检查', 'Thinking']
5
- const EXTRA_TITLES = ['', 'Checking project structure', 'Analyzing the request', 'Reviewing implementation', 'Verifying results']
6
-
7
- // Only layout belongs to the plugin. Controls, menus, focus and dialogs belong to DSH.
8
- const STYLES = `
9
- .novel-fish-settings{display:flex;flex-direction:column;gap:32px;min-width:0;font-size:14px;line-height:1.6;color:var(--dsw-alias-label-primary)}
10
- .novel-fish-settings .novel-fish-section{display:flex;flex-direction:column;gap:16px;min-width:0}
11
- .novel-fish-settings .novel-fish-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}
12
- .novel-fish-settings h3{margin:0;font:inherit;font-weight:600}
13
- .novel-fish-settings .novel-fish-field{display:flex;flex-direction:column;gap:8px;min-width:0}
14
- .novel-fish-settings .novel-fish-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:16px}
15
- .novel-fish-settings .novel-fish-select,.novel-fish-settings .novel-fish-input{display:flex;width:100%;min-width:0}
16
- .novel-fish-settings .novel-fish-select-button{width:100%;justify-content:space-between;gap:12px;text-align:start}
17
- .novel-fish-settings .novel-fish-selection{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
18
- .novel-fish-settings .novel-fish-hint{margin:0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.6}
19
- .novel-fish-settings .novel-fish-error{color:var(--dsw-alias-state-error-primary)}
20
- `
21
-
22
- /** Embedded in this bundle's official configuration slot; never a reading page. */
23
- export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, IconChevronDownOutlineRegular }) {
24
- const h = React.createElement
25
-
26
- function SelectMenu({ label, summary, value, items, disabled, onChange, marker, multiple = false, footer }) {
27
- const [open, setOpen] = React.useState(false)
28
- const selection = multiple ? summary : items.find(item => item.id === value)?.label ?? label
29
- return h(Menu, {
30
- open, onClose: () => setOpen(false), portal: true, autoFocus: true,
31
- className: 'novel-fish-select',
32
- items: items.map(item => ({ ...item, disabled: disabled || item.disabled })),
33
- footer: footer?.map(item => ({ ...item, disabled })),
34
- ...(multiple ? { selectedIds: value } : { selectedId: value }),
35
- onSelect: id => {
36
- if (disabled) return
37
- if (!multiple) setOpen(false)
38
- onChange(id)
39
- },
40
- anchor: h(Button, {
41
- variant: 'outline', disabled, className: 'novel-fish-select-button',
42
- 'aria-label': label, 'aria-haspopup': 'menu', 'aria-expanded': open,
43
- ...marker, onClick: () => { if (!disabled) setOpen(current => !current) },
44
- }, h('span', { className: 'novel-fish-selection' }, selection), h(IconChevronDownOutlineRegular, { size: 16 })),
45
- })
46
- }
47
-
48
- function PresetField({ t, label, value, choices, disabled, onChange, testId }) {
49
- const [custom, setCustom] = React.useState(!choices.includes(value))
50
- const showCustom = custom || !choices.includes(value)
51
- return h('div', { className: 'novel-fish-field' },
52
- h('span', null, label),
53
- h(SelectMenu, {
54
- label, value: showCustom ? '__custom' : value, disabled,
55
- marker: { 'data-novel-preset': testId },
56
- items: [...choices.map(choice => ({ id: choice, label: choice || t(testId === 'title' ? 'settings.nativeTitle' : 'settings.noExtra') })), { id: '__custom', label: t('settings.custom') }],
57
- onChange: next => {
58
- if (next === '__custom') setCustom(true)
59
- else void onChange(next).then(saved => { if (saved) setCustom(false) })
60
- },
61
- }),
62
- showCustom ? h(Input, {
63
- className: 'novel-fish-input', defaultValue: value, disabled,
64
- 'aria-label': t('settings.customField', { label }), [`data-novel-${testId}`]: true,
65
- onChange: event => { void onChange(event.currentTarget.value) },
66
- }) : null,
67
- )
68
- }
69
-
70
- function SettingsRow({ t, useNovelState, useNovelUi, onSetOption, onSetNotice, onSelectBook, onDeleteBook, onImportFile }) {
71
- const state = useNovelState(value => value)
72
- const ui = useNovelUi(value => value)
73
- const [busy, setBusy] = React.useState(false)
74
- const [savingTypes, setSavingTypes] = React.useState(false)
75
- const [savingEnabled, setSavingEnabled] = React.useState(false)
76
- const [savingContinue, setSavingContinue] = React.useState(false)
77
- const [removeBook, setRemoveBook] = React.useState(null)
78
- const [removeError, setRemoveError] = React.useState(null)
79
- const enabling = React.useRef(false)
80
- const continuing = React.useRef(false)
81
- const changingTypes = React.useRef(false)
82
- const importing = React.useRef(false)
83
- const removing = React.useRef(false)
84
- const fileInput = React.useRef(null)
85
- const selectedBook = state.books.find(book => book.id === state.settings.currentBookId)
86
- const disabled = busy || !state.hydrated || Boolean(state.error)
87
- const perform = async action => {
88
- try { await action(); return true }
89
- catch (error) { onSetNotice(t('settings.actionError', { message: errorMessage(error) })); return false }
90
- }
91
- const setEnabled = async enabled => {
92
- if (disabled || enabling.current) return
93
- enabling.current = true
94
- setSavingEnabled(true)
95
- try { await perform(() => onSetOption('enabled', enabled)) }
96
- finally { enabling.current = false; setSavingEnabled(false) }
97
- }
98
- const setContinue = async enabled => {
99
- if (disabled || continuing.current) return
100
- continuing.current = true
101
- setSavingContinue(true)
102
- try { await perform(() => onSetOption('continueOnReopen', enabled)) }
103
- finally { continuing.current = false; setSavingContinue(false) }
104
- }
105
- const setTypes = async types => {
106
- if (disabled || changingTypes.current) return
107
- changingTypes.current = true
108
- setSavingTypes(true)
109
- try { await perform(() => onSetOption('targetTypes', types)) }
110
- finally { changingTypes.current = false; setSavingTypes(false) }
111
- }
112
- const importFile = async event => {
113
- const input = event.currentTarget
114
- const file = input.files?.[0]
115
- if (!file || disabled || importing.current) return
116
- importing.current = true
117
- setBusy(true)
118
- onSetNotice(t('settings.importing'))
119
- try {
120
- const book = await onImportFile(file)
121
- onSetNotice(t('settings.importDone', { count: book.segmentCount }))
122
- } catch (error) {
123
- onSetNotice(t('settings.importError', { message: errorMessage(error) }))
124
- } finally {
125
- input.value = ''
126
- importing.current = false
127
- setBusy(false)
128
- }
129
- }
130
- const closeRemove = () => { if (!removing.current) setRemoveBook(null) }
131
- const confirmRemove = async () => {
132
- if (!removeBook || disabled || removing.current) return
133
- removing.current = true
134
- setRemoveError(null)
135
- setBusy(true)
136
- try { await onDeleteBook(removeBook.id); setRemoveBook(null) }
137
- catch (error) { setRemoveError(t('settings.actionError', { message: errorMessage(error) })) }
138
- finally { removing.current = false; setBusy(false) }
139
- }
140
-
141
- return h('section', { className: 'novel-fish-settings', 'data-novel-settings': true },
142
- h('style', null, STYLES),
143
- !state.hydrated && !state.error ? h('div', { role: 'status' }, t('settings.storageLoading')) : null,
144
- state.error ? h('div', { role: 'alert', className: 'novel-fish-error' }, state.error) : null,
145
- h('section', { className: 'novel-fish-section' },
146
- h('div', { className: 'novel-fish-row' },
147
- h('h3', null, t('settings.books')),
148
- h(Button, { variant: 'outline', disabled, 'data-novel-import': true, onClick: () => { if (!disabled) fileInput.current?.click() } }, t('settings.importBook')),
149
- ),
150
- 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
- h('div', { className: 'novel-fish-field' },
152
- h('span', null, t('settings.selectBook')),
153
- h(SelectMenu, {
154
- label: t('settings.selectBook'), value: state.settings.currentBookId ?? '', disabled: disabled || !state.books.length,
155
- marker: { 'data-novel-book-select': true },
156
- items: [{ id: '', label: t('settings.noBook') }, ...state.books.map(book => ({ id: book.id, label: `${book.title} · ${book.format.toUpperCase()}` }))],
157
- onChange: id => { void perform(() => onSelectBook(id)) },
158
- }),
159
- ),
160
- selectedBook ? h('div', { className: 'novel-fish-row' },
161
- 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) })),
162
- h(Button, { variant: 'ghost', disabled, 'data-novel-delete': true, onClick: () => { setRemoveError(null); setRemoveBook(selectedBook) } }, t('settings.deleteBook')),
163
- ) : h('p', { className: 'novel-fish-hint' }, t('settings.emptyLibrary')),
164
- ),
165
- h('section', { className: 'novel-fish-section' },
166
- h('h3', null, t('settings.reading')),
167
- h('div', { className: 'novel-fish-row' },
168
- h('span', null, t('settings.enabled')),
169
- h(Switch, { checked: state.settings.enabled, disabled: disabled || savingEnabled, label: t('settings.enabled'), onChange: enabled => { void setEnabled(enabled) } }),
170
- ),
171
- h('div', { className: 'novel-fish-field' },
172
- h('span', null, t('settings.targetType')),
173
- h(SelectMenu, {
174
- label: t('settings.targetType'), summary: t('settings.selectedTypes', { count: state.settings.targetTypes.length, total: TARGET_TYPES.length }),
175
- value: state.settings.targetTypes, multiple: true, disabled: disabled || savingTypes,
176
- marker: { 'data-novel-type-select': true },
177
- items: TARGET_TYPES.map(type => ({ id: type, label: t(`settings.${TYPE_LABELS[type]}`) })),
178
- footer: [{ id: '__all', label: t(state.settings.targetTypes.length === TARGET_TYPES.length ? 'settings.clearTypes' : 'settings.allTypes') }],
179
- 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
- }),
181
- h('p', { className: 'novel-fish-hint' }, t('settings.typeHint')),
182
- ),
183
- h('div', { className: 'novel-fish-row' },
184
- h('span', null, t('settings.continueOnReopen')),
185
- h(Switch, { checked: state.settings.continueOnReopen === true, disabled: disabled || savingContinue, label: t('settings.continueOnReopen'), onChange: enabled => { void setContinue(enabled) } }),
186
- ),
187
- h('p', { className: 'novel-fish-hint' }, t('settings.continueOnReopenHint')),
188
- ),
189
- h('section', { className: 'novel-fish-section' },
190
- h('h3', null, t('settings.appearance')),
191
- h('div', { key: String(state.hydrated), className: 'novel-fish-grid' },
192
- [
193
- ['mainTitle', 'settings.titleMain', 'title', MAIN_TITLES],
194
- ['extraTitle', 'settings.titleExtra', 'extra', EXTRA_TITLES],
195
- ].map(([key, label, testId, choices]) => h(PresetField, {
196
- key, t, label: t(label), value: state.settings[key], choices, disabled, testId,
197
- onChange: value => perform(() => onSetOption(key, value)),
198
- })),
199
- ),
200
- h('p', { className: 'novel-fish-hint' }, t('settings.nativeControls')),
201
- ),
202
- ui.notice ? h('div', { role: 'status', 'data-novel-notice': true }, ui.notice) : null,
203
- h(Modal, {
204
- open: Boolean(removeBook), onClose: closeRemove, title: t('settings.deleteBook'), closeLabel: t('settings.cancel'),
205
- description: removeBook ? t('settings.removeConfirm', { title: removeBook.title }) : '',
206
- footer: h(React.Fragment, null,
207
- h(Button, { variant: 'outline', disabled: busy, onClick: closeRemove }, t('settings.cancel')),
208
- h(Button, { variant: 'primary', disabled: disabled || !removeBook, 'data-novel-delete-confirm': true, onClick: () => { void confirmRemove() } }, t('settings.confirmDelete')),
209
- ),
210
- }, removeError ? h('p', { role: 'alert' }, removeError) : null),
211
- )
212
- }
213
-
214
- return React.memo(SettingsRow)
215
- }
216
-
217
- function errorMessage(error) {
218
- return error instanceof Error ? error.message : String(error)
219
- }