@gongfpp/dsh-novel-fish 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +41 -20
- package/docs/evidence/settings-reliability.png +0 -0
- package/index.json +12 -0
- package/lib/client.js +734 -128
- package/locale/en.json +15 -0
- package/locale/zh.json +15 -0
- package/package.json +5 -7
- package/screenshots.json +6 -0
- package/docs/acceptance.md +0 -42
- package/docs/community-markets.md +0 -88
- package/docs/compatibility-017.md +0 -70
- package/docs/compatibility-101.md +0 -41
- package/docs/continuous-reading-020.md +0 -46
- package/docs/ebook-tests.md +0 -99
- package/docs/evidence/abc-result.json +0 -9
- package/docs/evidence/banner-100.png +0 -0
- package/docs/evidence/community-market-014-result.json +0 -170
- package/docs/evidence/compatibility-017-result.json +0 -65
- package/docs/evidence/continuous-reading-020-result.json +0 -72
- package/docs/evidence/formats-result.json +0 -12
- package/docs/evidence/live-ab.png +0 -0
- package/docs/evidence/live-collapsed.png +0 -0
- package/docs/evidence/live-disabled.png +0 -0
- package/docs/evidence/live-epub.png +0 -0
- package/docs/evidence/live-market.png +0 -0
- package/docs/evidence/live-resume.png +0 -0
- package/docs/evidence/live-unloaded.png +0 -0
- package/docs/evidence/long-result.json +0 -11
- package/docs/evidence/multi-region-014-result.json +0 -47
- package/docs/evidence/native-disclosure-013-result.json +0 -36
- package/docs/evidence/native-disclosures-013.png +0 -0
- package/docs/evidence/native-open-013.png +0 -0
- package/docs/evidence/native-settings-sample.md +0 -11
- package/docs/evidence/native-settings-types-015.png +0 -0
- package/docs/evidence/npm-market-014-result.json +0 -132
- package/docs/evidence/plugin-settings-details.png +0 -0
- package/docs/evidence/public-release-014-result.json +0 -51
- package/docs/evidence/public-release-015-result.json +0 -36
- package/docs/evidence/public-release-result.json +0 -48
- package/docs/evidence/reading-demo-100.png +0 -0
- package/docs/evidence/reading-two-expansions-110.gif +0 -0
- package/docs/evidence/reading-two-expansions-110.json +0 -89
- package/docs/evidence/samples-110-capture.json +0 -49
- package/docs/evidence/settings-011-result.json +0 -28
- package/docs/evidence/settings-011.png +0 -0
- package/docs/evidence/settings-100.png +0 -0
- package/docs/evidence/settings-110.png +0 -0
- package/docs/evidence/settings-chat-011.png +0 -0
- package/docs/evidence/type-append-012-result.json +0 -30
- package/docs/evidence/type-append-012.png +0 -0
- package/docs/evidence/type-settings-012.png +0 -0
- package/docs/evidence/unload-result.json +0 -7
- package/docs/host-adapter.md +0 -43
- package/docs/icon-metadata-021.md +0 -40
- package/docs/interaction-paths-020.md +0 -39
- package/docs/marketplace.md +0 -42
- package/docs/multi-region-update.md +0 -53
- package/docs/native-disclosure-update.md +0 -39
- package/docs/native-settings-update.md +0 -48
- package/docs/plugin-settings-update.md +0 -61
- package/docs/release.md +0 -151
- package/docs/settings-update.md +0 -49
- package/docs/type-append-update.md +0 -50
- package/pnpm-workspace.yaml +0 -5
- package/scripts/build.mjs +0 -70
- package/scripts/check-host-contracts.mjs +0 -247
- package/scripts/licenses/path-webpack.txt +0 -28
- package/scripts/make-readme-gif.mjs +0 -69
- package/scripts/test-browser-samples.mjs +0 -665
- package/scripts/test-candidate-books.mjs +0 -71
- package/scripts/test-ebook-corpus.mjs +0 -161
- package/src/bundled-books.js +0 -42
- package/src/chat-adapter.js +0 -278
- package/src/client.js +0 -61
- package/src/epub.js +0 -166
- package/src/novel-content.js +0 -28
- package/src/persistence.js +0 -271
- package/src/pg-notice.js +0 -19
- package/src/segments.js +0 -185
- package/src/settings.js +0 -243
- package/src/store.js +0 -429
- package/src/text-decoding.js +0 -28
- package/test/bundled-library.test.js +0 -526
- package/test/chat-adapter.test.js +0 -518
- package/test/client.test.js +0 -124
- package/test/ebooks.test.js +0 -192
- package/test/epub.test.js +0 -185
- package/test/helpers/host-primitives.js +0 -28
- package/test/helpers/memory-storage.js +0 -48
- package/test/host-contracts.test.js +0 -32
- package/test/import.test.js +0 -102
- package/test/persistence.test.js +0 -27
- package/test/pg-notice.test.js +0 -109
- package/test/release.test.js +0 -87
- package/test/segments.test.js +0 -182
- package/test/settings.test.js +0 -312
- package/test/store.test.js +0 -617
- package/test/text-decoding.test.js +0 -49
package/src/settings.js
DELETED
|
@@ -1,243 +0,0 @@
|
|
|
1
|
-
import { TARGET_TYPES } from './store.js'
|
|
2
|
-
import { PG_NOTICE } from './pg-notice.js'
|
|
3
|
-
|
|
4
|
-
const TYPE_LABELS = { reasoning: 'typeReasoning', 'tool-call': 'typeToolCall', 'read-file': 'typeReadFile', command: 'typeCommand', 'file-search': 'typeFileSearch' }
|
|
5
|
-
const MAIN_TITLES = ['', '思考', '分析', '检查', 'Thinking']
|
|
6
|
-
const EXTRA_TITLES = ['', 'Checking project structure', 'Analyzing the request', 'Reviewing implementation', 'Verifying results']
|
|
7
|
-
|
|
8
|
-
// Only layout belongs to the plugin. Controls, menus, focus and dialogs belong to DSH.
|
|
9
|
-
const STYLES = `
|
|
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)}
|
|
11
|
-
.novel-fish-settings .novel-fish-section{display:flex;flex-direction:column;gap:16px;min-width:0}
|
|
12
|
-
.novel-fish-settings .novel-fish-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px}
|
|
13
|
-
.novel-fish-settings h3{margin:0;font:inherit;font-weight:600}
|
|
14
|
-
.novel-fish-settings .novel-fish-field{display:flex;flex-direction:column;gap:8px;min-width:0}
|
|
15
|
-
.novel-fish-settings .novel-fish-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:16px}
|
|
16
|
-
.novel-fish-settings .novel-fish-select,.novel-fish-settings .novel-fish-input{display:flex;width:100%;min-width:0}
|
|
17
|
-
.novel-fish-settings .novel-fish-select-button{width:100%;justify-content:space-between;gap:12px;text-align:start}
|
|
18
|
-
.novel-fish-settings .novel-fish-selection{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
|
|
19
|
-
.novel-fish-settings .novel-fish-hint{margin:0;color:var(--dsw-alias-label-tertiary);font-size:13px;line-height:1.6}
|
|
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}
|
|
28
|
-
`
|
|
29
|
-
|
|
30
|
-
/** Embedded in this bundle's official configuration slot; never a reading page. */
|
|
31
|
-
export function createSettingsRow(React, { Switch, Button, Input, Menu, Modal, IconChevronDownOutlineRegular }) {
|
|
32
|
-
const h = React.createElement
|
|
33
|
-
|
|
34
|
-
function SelectMenu({ label, summary, value, items, disabled, onChange, marker, multiple = false, footer }) {
|
|
35
|
-
const [open, setOpen] = React.useState(false)
|
|
36
|
-
const selection = multiple ? summary : items.find(item => item.id === value)?.label ?? label
|
|
37
|
-
return h(Menu, {
|
|
38
|
-
open, onClose: () => setOpen(false), portal: true, autoFocus: true,
|
|
39
|
-
className: 'novel-fish-select',
|
|
40
|
-
items: items.map(item => ({ ...item, disabled: disabled || item.disabled })),
|
|
41
|
-
footer: footer?.map(item => ({ ...item, disabled })),
|
|
42
|
-
...(multiple ? { selectedIds: value } : { selectedId: value }),
|
|
43
|
-
onSelect: id => {
|
|
44
|
-
if (disabled) return
|
|
45
|
-
if (!multiple) setOpen(false)
|
|
46
|
-
onChange(id)
|
|
47
|
-
},
|
|
48
|
-
anchor: h(Button, {
|
|
49
|
-
variant: 'outline', disabled, className: 'novel-fish-select-button',
|
|
50
|
-
'aria-label': label, 'aria-haspopup': 'menu', 'aria-expanded': open,
|
|
51
|
-
...marker, onClick: () => { if (!disabled) setOpen(current => !current) },
|
|
52
|
-
}, h('span', { className: 'novel-fish-selection' }, selection), h(IconChevronDownOutlineRegular, { size: 16 })),
|
|
53
|
-
})
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function PresetField({ t, label, value, choices, disabled, onChange, testId }) {
|
|
57
|
-
const [custom, setCustom] = React.useState(!choices.includes(value))
|
|
58
|
-
const showCustom = custom || !choices.includes(value)
|
|
59
|
-
return h('div', { className: 'novel-fish-field' },
|
|
60
|
-
h('span', null, label),
|
|
61
|
-
h(SelectMenu, {
|
|
62
|
-
label, value: showCustom ? '__custom' : value, disabled,
|
|
63
|
-
marker: { 'data-novel-preset': testId },
|
|
64
|
-
items: [...choices.map(choice => ({ id: choice, label: choice || t(testId === 'title' ? 'settings.nativeTitle' : 'settings.noExtra') })), { id: '__custom', label: t('settings.custom') }],
|
|
65
|
-
onChange: next => {
|
|
66
|
-
if (next === '__custom') setCustom(true)
|
|
67
|
-
else void onChange(next).then(saved => { if (saved) setCustom(false) })
|
|
68
|
-
},
|
|
69
|
-
}),
|
|
70
|
-
showCustom ? h(Input, {
|
|
71
|
-
className: 'novel-fish-input', defaultValue: value, disabled,
|
|
72
|
-
'aria-label': t('settings.customField', { label }), [`data-novel-${testId}`]: true,
|
|
73
|
-
onChange: event => { void onChange(event.currentTarget.value) },
|
|
74
|
-
}) : null,
|
|
75
|
-
)
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
function SettingsRow({ t, useNovelState, useNovelUi, onSetOption, onSetNotice, onSelectBook, onDeleteBook, onImportFile, sampleBooks = [], getSampleLicenseHref }) {
|
|
79
|
-
const state = useNovelState(value => value)
|
|
80
|
-
const ui = useNovelUi(value => value)
|
|
81
|
-
const [busy, setBusy] = React.useState(false)
|
|
82
|
-
const [savingTypes, setSavingTypes] = React.useState(false)
|
|
83
|
-
const [savingEnabled, setSavingEnabled] = React.useState(false)
|
|
84
|
-
const [savingContinue, setSavingContinue] = React.useState(false)
|
|
85
|
-
const [removeBook, setRemoveBook] = React.useState(null)
|
|
86
|
-
const [removeError, setRemoveError] = React.useState(null)
|
|
87
|
-
const [bookInfoOpen, setBookInfoOpen] = React.useState(false)
|
|
88
|
-
const enabling = React.useRef(false)
|
|
89
|
-
const continuing = React.useRef(false)
|
|
90
|
-
const changingTypes = React.useRef(false)
|
|
91
|
-
const importing = React.useRef(false)
|
|
92
|
-
const removing = React.useRef(false)
|
|
93
|
-
const fileInput = React.useRef(null)
|
|
94
|
-
const selectedBook = state.books.find(book => book.id === state.settings.currentBookId)
|
|
95
|
-
const disabled = busy || !state.hydrated || Boolean(state.error)
|
|
96
|
-
const perform = async action => {
|
|
97
|
-
try { await action(); return true }
|
|
98
|
-
catch (error) { onSetNotice(t('settings.actionError', { message: errorMessage(error) })); return false }
|
|
99
|
-
}
|
|
100
|
-
const setEnabled = async enabled => {
|
|
101
|
-
if (disabled || enabling.current) return
|
|
102
|
-
enabling.current = true
|
|
103
|
-
setSavingEnabled(true)
|
|
104
|
-
try { await perform(() => onSetOption('enabled', enabled)) }
|
|
105
|
-
finally { enabling.current = false; setSavingEnabled(false) }
|
|
106
|
-
}
|
|
107
|
-
const setContinue = async enabled => {
|
|
108
|
-
if (disabled || continuing.current) return
|
|
109
|
-
continuing.current = true
|
|
110
|
-
setSavingContinue(true)
|
|
111
|
-
try { await perform(() => onSetOption('continueOnReopen', enabled)) }
|
|
112
|
-
finally { continuing.current = false; setSavingContinue(false) }
|
|
113
|
-
}
|
|
114
|
-
const setTypes = async types => {
|
|
115
|
-
if (disabled || changingTypes.current) return
|
|
116
|
-
changingTypes.current = true
|
|
117
|
-
setSavingTypes(true)
|
|
118
|
-
try { await perform(() => onSetOption('targetTypes', types)) }
|
|
119
|
-
finally { changingTypes.current = false; setSavingTypes(false) }
|
|
120
|
-
}
|
|
121
|
-
const importFile = async event => {
|
|
122
|
-
const input = event.currentTarget
|
|
123
|
-
const file = input.files?.[0]
|
|
124
|
-
if (!file || disabled || importing.current) return
|
|
125
|
-
importing.current = true
|
|
126
|
-
setBusy(true)
|
|
127
|
-
onSetNotice(t('settings.importing'))
|
|
128
|
-
try {
|
|
129
|
-
const book = await onImportFile(file)
|
|
130
|
-
onSetNotice(t('settings.importDone', { count: book.segmentCount }))
|
|
131
|
-
} catch (error) {
|
|
132
|
-
onSetNotice(t('settings.importError', { message: errorMessage(error) }))
|
|
133
|
-
} finally {
|
|
134
|
-
input.value = ''
|
|
135
|
-
importing.current = false
|
|
136
|
-
setBusy(false)
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
const closeRemove = () => { if (!removing.current) setRemoveBook(null) }
|
|
140
|
-
const confirmRemove = async () => {
|
|
141
|
-
if (!removeBook || disabled || removing.current) return
|
|
142
|
-
removing.current = true
|
|
143
|
-
setRemoveError(null)
|
|
144
|
-
setBusy(true)
|
|
145
|
-
try { await onDeleteBook(removeBook.id); setRemoveBook(null) }
|
|
146
|
-
catch (error) { setRemoveError(t('settings.actionError', { message: errorMessage(error) })) }
|
|
147
|
-
finally { removing.current = false; setBusy(false) }
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
return h('section', { className: 'novel-fish-settings', 'data-novel-settings': true },
|
|
151
|
-
h('style', null, STYLES),
|
|
152
|
-
!state.hydrated && !state.error ? h('div', { role: 'status' }, t('settings.storageLoading')) : null,
|
|
153
|
-
state.error ? h('div', { role: 'alert', className: 'novel-fish-error' }, state.error) : null,
|
|
154
|
-
h('section', { className: 'novel-fish-section' },
|
|
155
|
-
h('div', { className: 'novel-fish-row' },
|
|
156
|
-
h('h3', null, t('settings.books')),
|
|
157
|
-
h(Button, { variant: 'outline', disabled, 'data-novel-import': true, onClick: () => { if (!disabled) fileInput.current?.click() } }, t('settings.importBook')),
|
|
158
|
-
),
|
|
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 }),
|
|
160
|
-
h('div', { className: 'novel-fish-field' },
|
|
161
|
-
h(SelectMenu, {
|
|
162
|
-
label: t('settings.selectBook'), value: state.settings.currentBookId ?? '', disabled,
|
|
163
|
-
marker: { 'data-novel-book-select': true },
|
|
164
|
-
items: [{ id: '', label: t('settings.noBook') }, ...state.books.map(book => ({ id: book.id, label: `${book.title} · ${book.format.toUpperCase()}` }))],
|
|
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
|
-
},
|
|
170
|
-
}),
|
|
171
|
-
selectedBook ? h('progress', { className: 'novel-fish-progress', value: selectedBook.progress,
|
|
172
|
-
max: selectedBook.segmentCount, 'aria-label': t('settings.readingProgress') }) : null,
|
|
173
|
-
),
|
|
174
|
-
selectedBook ? h('div', { className: 'novel-fish-row' },
|
|
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) })),
|
|
176
|
-
h(Button, { variant: 'ghost', disabled, 'data-novel-delete': true, onClick: () => { setRemoveError(null); setRemoveBook(selectedBook) } }, t('settings.deleteBook')),
|
|
177
|
-
) : h('p', { className: 'novel-fish-hint' }, t('settings.emptyLibrary')),
|
|
178
|
-
),
|
|
179
|
-
h('section', { className: 'novel-fish-section' },
|
|
180
|
-
h('h3', null, t('settings.reading')),
|
|
181
|
-
h('div', { className: 'novel-fish-row' },
|
|
182
|
-
h('span', null, t('settings.enabled')),
|
|
183
|
-
h(Switch, { checked: state.settings.enabled, disabled: disabled || savingEnabled, label: t('settings.enabled'), onChange: enabled => { void setEnabled(enabled) } }),
|
|
184
|
-
),
|
|
185
|
-
h('div', { className: 'novel-fish-field' },
|
|
186
|
-
h('span', null, t('settings.targetType')),
|
|
187
|
-
h(SelectMenu, {
|
|
188
|
-
label: t('settings.targetType'), summary: t('settings.selectedTypes', { count: state.settings.targetTypes.length, total: TARGET_TYPES.length }),
|
|
189
|
-
value: state.settings.targetTypes, multiple: true, disabled: disabled || savingTypes,
|
|
190
|
-
marker: { 'data-novel-type-select': true },
|
|
191
|
-
items: TARGET_TYPES.map(type => ({ id: type, label: t(`settings.${TYPE_LABELS[type]}`) })),
|
|
192
|
-
footer: [{ id: '__all', label: t(state.settings.targetTypes.length === TARGET_TYPES.length ? 'settings.clearTypes' : 'settings.allTypes') }],
|
|
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))) },
|
|
194
|
-
}),
|
|
195
|
-
),
|
|
196
|
-
h('div', { className: 'novel-fish-row' },
|
|
197
|
-
h('span', null, t('settings.continueOnReopen')),
|
|
198
|
-
h(Switch, { checked: state.settings.continueOnReopen === true, disabled: disabled || savingContinue, label: t('settings.continueOnReopen'), onChange: enabled => { void setContinue(enabled) } }),
|
|
199
|
-
),
|
|
200
|
-
),
|
|
201
|
-
h('section', { className: 'novel-fish-section' },
|
|
202
|
-
h('h3', null, t('settings.appearance')),
|
|
203
|
-
h('div', { key: String(state.hydrated), className: 'novel-fish-grid' },
|
|
204
|
-
[
|
|
205
|
-
['mainTitle', 'settings.titleMain', 'title', MAIN_TITLES],
|
|
206
|
-
['extraTitle', 'settings.titleExtra', 'extra', EXTRA_TITLES],
|
|
207
|
-
].map(([key, label, testId, choices]) => h(PresetField, {
|
|
208
|
-
key, t, label: t(label), value: state.settings[key], choices, disabled, testId,
|
|
209
|
-
onChange: value => perform(() => onSetOption(key, value)),
|
|
210
|
-
})),
|
|
211
|
-
),
|
|
212
|
-
),
|
|
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,
|
|
227
|
-
h(Modal, {
|
|
228
|
-
open: Boolean(removeBook), onClose: closeRemove, title: t('settings.deleteBook'), closeLabel: t('settings.cancel'),
|
|
229
|
-
description: removeBook ? t('settings.removeConfirm', { title: removeBook.title }) : '',
|
|
230
|
-
footer: h(React.Fragment, null,
|
|
231
|
-
h(Button, { variant: 'outline', disabled: busy, onClick: closeRemove }, t('settings.cancel')),
|
|
232
|
-
h(Button, { variant: 'primary', disabled: disabled || !removeBook, 'data-novel-delete-confirm': true, onClick: () => { void confirmRemove() } }, t('settings.confirmDelete')),
|
|
233
|
-
),
|
|
234
|
-
}, removeError ? h('p', { role: 'alert' }, removeError) : null),
|
|
235
|
-
)
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
return React.memo(SettingsRow)
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
function errorMessage(error) {
|
|
242
|
-
return error instanceof Error ? error.message : String(error)
|
|
243
|
-
}
|
package/src/store.js
DELETED
|
@@ -1,429 +0,0 @@
|
|
|
1
|
-
import { parseEpub } from './epub.js'
|
|
2
|
-
import { DEFAULT_SEGMENT_LENGTH, parseTextBook } from './segments.js'
|
|
3
|
-
import { decodeBookText } from './text-decoding.js'
|
|
4
|
-
import { hasProjectGutenbergReference } from './pg-notice.js'
|
|
5
|
-
|
|
6
|
-
export const TARGET_TYPES = Object.freeze(['reasoning', 'tool-call', 'read-file', 'command', 'file-search'])
|
|
7
|
-
|
|
8
|
-
export const DEFAULT_SETTINGS = Object.freeze({
|
|
9
|
-
enabled: true,
|
|
10
|
-
currentBookId: null,
|
|
11
|
-
targetTypes: Object.freeze(['reasoning']),
|
|
12
|
-
mainTitle: '',
|
|
13
|
-
extraTitle: '',
|
|
14
|
-
continueOnReopen: false,
|
|
15
|
-
})
|
|
16
|
-
|
|
17
|
-
const EMPTY_STATUS = Object.freeze({ kind: 'empty' })
|
|
18
|
-
|
|
19
|
-
export function passageSnapshotKey(bookId, stepKey) {
|
|
20
|
-
return `${bookId}\u0000${stepKey}`
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** Own persistent books/settings and page-only passage cache for Novel Fish. */
|
|
24
|
-
export class NovelStore {
|
|
25
|
-
constructor(storage, { bundledBooks = [], bundledCatalog = null } = {}) {
|
|
26
|
-
this.storage = storage
|
|
27
|
-
this.bundledBooks = bundledBooks
|
|
28
|
-
this.bundledCatalog = bundledCatalog
|
|
29
|
-
this.state = { books: [], settings: { ...DEFAULT_SETTINGS }, hydrated: false, error: null }
|
|
30
|
-
this.ui = { notice: null }
|
|
31
|
-
this.listeners = new Set()
|
|
32
|
-
this.settingsListeners = new Set()
|
|
33
|
-
this.uiListeners = new Set()
|
|
34
|
-
this.passageListeners = new Set()
|
|
35
|
-
this.passageStates = new Map()
|
|
36
|
-
this.passageSnapshot = Object.freeze({})
|
|
37
|
-
this.stateSource = Object.freeze({ getSnapshot: this.getSnapshot, subscribe: this.subscribe })
|
|
38
|
-
this.settingsSource = Object.freeze({ getSnapshot: this.getSettingsSnapshot, subscribe: this.subscribeSettings })
|
|
39
|
-
this.uiSource = Object.freeze({ getSnapshot: this.getUiSnapshot, subscribe: this.subscribeUi })
|
|
40
|
-
this.passageSource = Object.freeze({ getSnapshot: this.getPassageSnapshot, subscribe: this.subscribePassages })
|
|
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()
|
|
45
|
-
this.cacheGeneration = 0
|
|
46
|
-
this.disposed = false
|
|
47
|
-
this.persistenceError = null
|
|
48
|
-
this.mutationQueue = Promise.resolve()
|
|
49
|
-
this.ready = this.#hydrate()
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
getSnapshot = () => this.state
|
|
53
|
-
getSettingsSnapshot = () => this.state.settings
|
|
54
|
-
getUiSnapshot = () => this.ui
|
|
55
|
-
getPassageSnapshot = () => this.passageSnapshot
|
|
56
|
-
|
|
57
|
-
subscribe = listener => this.#subscribe(this.listeners, listener)
|
|
58
|
-
subscribeSettings = listener => this.#subscribe(this.settingsListeners, listener)
|
|
59
|
-
subscribeUi = listener => this.#subscribe(this.uiListeners, listener)
|
|
60
|
-
subscribePassages = listener => this.#subscribe(this.passageListeners, listener)
|
|
61
|
-
|
|
62
|
-
getPassageStatus(bookId, stepKey) {
|
|
63
|
-
if (!bookId) return EMPTY_STATUS
|
|
64
|
-
return this.passageStates.get(passageSnapshotKey(bookId, stepKey)) ?? EMPTY_STATUS
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
dispose() {
|
|
68
|
-
this.disposed = true
|
|
69
|
-
this.cacheGeneration += 1
|
|
70
|
-
this.passageStates.clear()
|
|
71
|
-
this.passageSnapshot = Object.freeze({})
|
|
72
|
-
this.pendingReads.clear()
|
|
73
|
-
this.projectGutenbergBooks.clear()
|
|
74
|
-
this.listeners.clear()
|
|
75
|
-
this.settingsListeners.clear()
|
|
76
|
-
this.uiListeners.clear()
|
|
77
|
-
this.passageListeners.clear()
|
|
78
|
-
this.storage.close?.()
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
setNotice(notice) {
|
|
82
|
-
this.ui = { ...this.ui, notice: notice ? String(notice) : null }
|
|
83
|
-
this.#emitUi()
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
async setOption(key, value) {
|
|
87
|
-
if (!['enabled', 'targetTypes', 'mainTitle', 'extraTitle', 'continueOnReopen'].includes(key)) throw new Error('未知设置项')
|
|
88
|
-
let normalized
|
|
89
|
-
if (key === 'targetTypes') {
|
|
90
|
-
if (!Array.isArray(value) || value.some(type => !TARGET_TYPES.includes(type)) || new Set(value).size !== value.length) {
|
|
91
|
-
throw new Error('阅读类型必须是有效且不重复的类型数组')
|
|
92
|
-
}
|
|
93
|
-
normalized = Object.freeze([...value])
|
|
94
|
-
} else if (key === 'enabled' || key === 'continueOnReopen') {
|
|
95
|
-
normalized = Boolean(value)
|
|
96
|
-
} else {
|
|
97
|
-
normalized = String(value)
|
|
98
|
-
}
|
|
99
|
-
// Invalidate at intent time, not after a queued settings write finishes.
|
|
100
|
-
// Any type update also covers removals from settings writes still in flight.
|
|
101
|
-
if ((key === 'enabled' && !normalized) || key === 'targetTypes') this.#cancelPendingReads()
|
|
102
|
-
return this.#updateSettings(() => ({ [key]: normalized }))
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
async selectBook(bookId) {
|
|
106
|
-
const nextId = bookId || null
|
|
107
|
-
this.cacheGeneration += 1
|
|
108
|
-
return this.#enqueueMutation(async () => {
|
|
109
|
-
if (nextId && !this.state.books.some(book => book.id === nextId)) throw new Error('找不到这本书')
|
|
110
|
-
if (nextId === this.state.settings.currentBookId) return
|
|
111
|
-
await this.#saveSettings({ ...this.state.settings, currentBookId: nextId })
|
|
112
|
-
this.#clearPassages(false)
|
|
113
|
-
})
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async importFile(file) {
|
|
117
|
-
await this.ready
|
|
118
|
-
this.#assertWritable()
|
|
119
|
-
const extension = String(file.name).split('.').at(-1)?.toLowerCase()
|
|
120
|
-
if (!['epub', 'txt', 'md'].includes(extension)) throw new Error('只支持 EPUB、TXT、MD 文件')
|
|
121
|
-
const parsed = extension === 'epub'
|
|
122
|
-
? await parseEpub(file, DEFAULT_SEGMENT_LENGTH)
|
|
123
|
-
: parseTextBook(decodeBookText(await file.arrayBuffer()), extension, DEFAULT_SEGMENT_LENGTH)
|
|
124
|
-
const fallbackTitle = String(file.name).replace(/\.(epub|txt|md)$/iu, '')
|
|
125
|
-
return this.#addBook({
|
|
126
|
-
title: parsed.title?.trim() || fallbackTitle || '未命名书籍',
|
|
127
|
-
format: extension,
|
|
128
|
-
segments: parsed.segments,
|
|
129
|
-
})
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
async deleteBook(bookId) {
|
|
133
|
-
if (bookId === this.state.settings.currentBookId) this.cacheGeneration += 1
|
|
134
|
-
return this.#enqueueMutation(async () => {
|
|
135
|
-
if (!this.state.books.some(item => item.id === bookId)) return
|
|
136
|
-
const books = this.state.books.filter(item => item.id !== bookId)
|
|
137
|
-
const previousSettings = this.state.settings
|
|
138
|
-
const settings = {
|
|
139
|
-
...previousSettings,
|
|
140
|
-
currentBookId: previousSettings.currentBookId === bookId ? books[0]?.id ?? null : previousSettings.currentBookId,
|
|
141
|
-
}
|
|
142
|
-
// Save selection first: a failed settings write must not delete the selected book.
|
|
143
|
-
await this.storage.saveSettings(settings)
|
|
144
|
-
try {
|
|
145
|
-
await this.storage.deleteBook(bookId)
|
|
146
|
-
} catch (error) {
|
|
147
|
-
await this.#restore(() => this.storage.saveSettings(previousSettings))
|
|
148
|
-
throw error
|
|
149
|
-
}
|
|
150
|
-
this.projectGutenbergBooks.delete(bookId)
|
|
151
|
-
this.#setState({ books, settings })
|
|
152
|
-
if (settings.currentBookId !== previousSettings.currentBookId) this.#clearPassages(false)
|
|
153
|
-
})
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/** Reopening a region shows the passage it already holds; a first expansion reads the next one. */
|
|
157
|
-
async claimPassage(stepKey, targetType = 'reasoning') {
|
|
158
|
-
return this.#readPassage(stepKey, targetType, false)
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/**
|
|
162
|
-
* Same contract as claimPassage, except a region that already shows a passage
|
|
163
|
-
* advances to the next one. Only an explicit reopen can reach this path, so a
|
|
164
|
-
* repeated expansion still cannot paginate by accident while long reads
|
|
165
|
-
* continue inside the same native row.
|
|
166
|
-
*/
|
|
167
|
-
async continuePassage(stepKey, targetType = 'reasoning') {
|
|
168
|
-
return this.#readPassage(stepKey, targetType, true)
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
async #readPassage(stepKey, targetType, advance) {
|
|
172
|
-
if (this.disposed) return EMPTY_STATUS
|
|
173
|
-
const generation = this.cacheGeneration
|
|
174
|
-
const requestKey = `${generation}\u0000${targetType}\u0000${stepKey}`
|
|
175
|
-
const inFlight = this.pendingReads.get(requestKey)
|
|
176
|
-
if (inFlight) return inFlight
|
|
177
|
-
|
|
178
|
-
let bookId
|
|
179
|
-
let loadingStatus
|
|
180
|
-
const operation = this.#enqueueMutation(async () => {
|
|
181
|
-
if (!this.#canRead(generation, targetType)) return EMPTY_STATUS
|
|
182
|
-
bookId = this.state.settings.currentBookId
|
|
183
|
-
if (!bookId) return EMPTY_STATUS
|
|
184
|
-
const existing = this.getPassageStatus(bookId, stepKey)
|
|
185
|
-
if (existing.kind === 'end') return existing
|
|
186
|
-
if (!advance && existing.kind === 'ready') return existing
|
|
187
|
-
const book = this.state.books.find(item => item.id === bookId)
|
|
188
|
-
if (!book || book.progress >= book.segmentCount) {
|
|
189
|
-
return this.#writePassageStatus(bookId, stepKey, { kind: 'end', bookId })
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
loadingStatus = { kind: 'loading' }
|
|
193
|
-
this.#writePassageStatus(bookId, stepKey, loadingStatus)
|
|
194
|
-
const index = book.progress
|
|
195
|
-
const passage = await this.storage.getSegment(bookId, index)
|
|
196
|
-
if (!passage?.text) throw new Error('当前段落为空或已损坏')
|
|
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)
|
|
207
|
-
|
|
208
|
-
const updated = { ...book, progress: index + 1 }
|
|
209
|
-
await this.storage.updateBook(updated)
|
|
210
|
-
if (!this.#canRead(generation, targetType)) {
|
|
211
|
-
await this.#restore(() => this.storage.updateBook(book))
|
|
212
|
-
return EMPTY_STATUS
|
|
213
|
-
}
|
|
214
|
-
const result = { kind: 'ready', bookId, index, passage, projectGutenberg }
|
|
215
|
-
this.#setState({ books: this.state.books.map(item => item.id === bookId ? updated : item) })
|
|
216
|
-
return this.#writePassageStatus(bookId, stepKey, result)
|
|
217
|
-
}).catch(error => {
|
|
218
|
-
if (!this.persistenceError && !this.#canRead(generation, targetType)) return EMPTY_STATUS
|
|
219
|
-
const failure = { kind: 'error', message: messageOf(error) }
|
|
220
|
-
if (this.#canRead(generation, targetType) && bookId) this.#writePassageStatus(bookId, stepKey, failure)
|
|
221
|
-
return failure
|
|
222
|
-
})
|
|
223
|
-
|
|
224
|
-
this.pendingReads.set(requestKey, operation)
|
|
225
|
-
try {
|
|
226
|
-
return await operation
|
|
227
|
-
} finally {
|
|
228
|
-
if (this.pendingReads.get(requestKey) === operation) this.pendingReads.delete(requestKey)
|
|
229
|
-
if (bookId && loadingStatus && generation !== this.cacheGeneration && this.getPassageStatus(bookId, stepKey) === loadingStatus) {
|
|
230
|
-
this.#writePassageStatus(bookId, stepKey, EMPTY_STATUS)
|
|
231
|
-
}
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
async #hydrate() {
|
|
236
|
-
try {
|
|
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
|
-
}
|
|
279
|
-
const books = stored.books ?? []
|
|
280
|
-
const storedSettings = stored.settings ?? {}
|
|
281
|
-
const availableIds = new Set(books.map(book => book.id))
|
|
282
|
-
const settings = {
|
|
283
|
-
...Object.fromEntries(Object.entries(DEFAULT_SETTINGS).map(([key, fallback]) => [key, storedSettings[key] ?? fallback])),
|
|
284
|
-
currentBookId: availableIds.has(storedSettings.currentBookId) ? storedSettings.currentBookId : null,
|
|
285
|
-
// Migrate the old reasoning-only field once; never carry it into writes.
|
|
286
|
-
targetTypes: Object.freeze(Array.isArray(storedSettings.targetTypes)
|
|
287
|
-
? [...new Set(storedSettings.targetTypes.filter(type => TARGET_TYPES.includes(type)))]
|
|
288
|
-
: [...DEFAULT_SETTINGS.targetTypes]),
|
|
289
|
-
}
|
|
290
|
-
this.#setState({ books, settings, hydrated: true, error: null })
|
|
291
|
-
} catch (error) {
|
|
292
|
-
this.persistenceError = error
|
|
293
|
-
this.#setState({ hydrated: true, error: messageOf(error) })
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
#addBook({ title, format, segments }) {
|
|
298
|
-
return this.#enqueueMutation(async () => {
|
|
299
|
-
if (!segments.length) throw new Error('没有可导入的正文')
|
|
300
|
-
const book = {
|
|
301
|
-
id: randomId(),
|
|
302
|
-
title: String(title).trim() || '未命名书籍',
|
|
303
|
-
format,
|
|
304
|
-
segmentCount: segments.length,
|
|
305
|
-
progress: 0,
|
|
306
|
-
importedAt: Date.now(),
|
|
307
|
-
}
|
|
308
|
-
await this.storage.addBook(book, segments)
|
|
309
|
-
const settings = this.state.settings.currentBookId
|
|
310
|
-
? this.state.settings
|
|
311
|
-
: { ...this.state.settings, currentBookId: book.id }
|
|
312
|
-
try {
|
|
313
|
-
if (settings !== this.state.settings) await this.storage.saveSettings(settings)
|
|
314
|
-
} catch (error) {
|
|
315
|
-
await this.#restore(() => this.storage.deleteBook(book.id))
|
|
316
|
-
throw error
|
|
317
|
-
}
|
|
318
|
-
if (settings !== this.state.settings) this.#clearPassages()
|
|
319
|
-
this.#setState({ books: [...this.state.books, book], settings })
|
|
320
|
-
return book
|
|
321
|
-
})
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
#updateSettings(update) {
|
|
325
|
-
return this.#enqueueMutation(async () => {
|
|
326
|
-
const patch = update(this.state.settings)
|
|
327
|
-
if (!patch) return this.state.settings
|
|
328
|
-
return this.#saveSettings({ ...this.state.settings, ...patch })
|
|
329
|
-
})
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
async #saveSettings(settings) {
|
|
333
|
-
await this.storage.saveSettings(settings)
|
|
334
|
-
this.#setState({ settings })
|
|
335
|
-
return settings
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
#enqueueMutation(action) {
|
|
339
|
-
const operation = this.mutationQueue.then(async () => {
|
|
340
|
-
await this.ready
|
|
341
|
-
this.#assertWritable()
|
|
342
|
-
return action()
|
|
343
|
-
})
|
|
344
|
-
this.mutationQueue = operation.catch(() => undefined)
|
|
345
|
-
return operation
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
#assertWritable() {
|
|
349
|
-
if (this.persistenceError) throw new Error(`本地书库不可用,请刷新后重试:${messageOf(this.persistenceError)}`)
|
|
350
|
-
if (this.disposed) throw new Error('本地书库已关闭')
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
async #restore(action) {
|
|
354
|
-
try {
|
|
355
|
-
await action()
|
|
356
|
-
} catch (error) {
|
|
357
|
-
this.persistenceError = error
|
|
358
|
-
this.#setState({ error: `本地书库恢复失败,请刷新后检查阅读进度:${messageOf(error)}` })
|
|
359
|
-
throw error
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
#canRead(generation, targetType) {
|
|
364
|
-
return !this.disposed && generation === this.cacheGeneration
|
|
365
|
-
&& this.state.settings.enabled && this.state.settings.targetTypes.includes(targetType)
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
#cancelPendingReads() {
|
|
369
|
-
this.cacheGeneration += 1
|
|
370
|
-
this.pendingReads.clear()
|
|
371
|
-
let changed = false
|
|
372
|
-
for (const [key, status] of this.passageStates) {
|
|
373
|
-
if (status.kind === 'loading') {
|
|
374
|
-
this.passageStates.delete(key)
|
|
375
|
-
changed = true
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
if (changed) {
|
|
379
|
-
this.passageSnapshot = Object.freeze(Object.fromEntries(this.passageStates))
|
|
380
|
-
this.#emitPassages()
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
#clearPassages(cancelReads = true) {
|
|
385
|
-
if (cancelReads) this.cacheGeneration += 1
|
|
386
|
-
this.passageStates.clear()
|
|
387
|
-
this.passageSnapshot = Object.freeze({})
|
|
388
|
-
this.#emitPassages()
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
#writePassageStatus(bookId, stepKey, status) {
|
|
392
|
-
if (!bookId) return status
|
|
393
|
-
const key = passageSnapshotKey(bookId, stepKey)
|
|
394
|
-
this.passageStates.set(key, status)
|
|
395
|
-
this.passageSnapshot = Object.freeze({ ...this.passageSnapshot, [key]: status })
|
|
396
|
-
this.#emitPassages()
|
|
397
|
-
return status
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
#setState(changes) {
|
|
401
|
-
const next = { ...this.state, ...changes }
|
|
402
|
-
this.state = next
|
|
403
|
-
for (const listener of [...this.listeners]) listener()
|
|
404
|
-
if (changes.settings !== undefined) {
|
|
405
|
-
for (const listener of [...this.settingsListeners]) listener()
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
#emitPassages() {
|
|
410
|
-
for (const listener of [...this.passageListeners]) listener()
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
#emitUi() {
|
|
414
|
-
for (const listener of [...this.uiListeners]) listener()
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
#subscribe(listeners, listener) {
|
|
418
|
-
listeners.add(listener)
|
|
419
|
-
return () => listeners.delete(listener)
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
function randomId() {
|
|
424
|
-
return globalThis.crypto?.randomUUID?.() ?? `book-${Date.now()}-${Math.random().toString(36).slice(2)}`
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
function messageOf(error) {
|
|
428
|
-
return error instanceof Error ? error.message : String(error)
|
|
429
|
-
}
|