aksos-react-native-epub-reader 0.1.0 → 0.2.1
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 +60 -0
- package/README.md +178 -20
- package/lib/EpubReader.d.ts +66 -15
- package/lib/EpubReader.js +168 -30
- package/lib/EpubReaderView.d.ts +37 -5
- package/lib/EpubReaderView.js +194 -93
- package/lib/cfiOrder.d.ts +2 -0
- package/lib/cfiOrder.js +34 -0
- package/lib/engine/html.js +1 -1
- package/lib/index.d.ts +5 -2
- package/lib/index.js +5 -1
- package/lib/strings.d.ts +94 -0
- package/lib/strings.js +96 -0
- package/lib/themes.d.ts +28 -6
- package/lib/themes.js +80 -20
- package/lib/types.d.ts +82 -1
- package/lib/ui/AppearanceSheet.d.ts +4 -2
- package/lib/ui/AppearanceSheet.js +40 -26
- package/lib/ui/ContentsSheet.d.ts +2 -0
- package/lib/ui/ContentsSheet.js +32 -22
- package/lib/ui/CustomizeSheet.d.ts +4 -2
- package/lib/ui/CustomizeSheet.js +31 -27
- package/lib/ui/HighlightMenu.d.ts +4 -2
- package/lib/ui/HighlightMenu.js +13 -11
- package/lib/ui/NoteEditor.js +12 -9
- package/lib/ui/SearchSheet.js +19 -6
- package/lib/ui/Sheet.js +7 -4
- package/lib/ui/Text.d.ts +9 -0
- package/lib/ui/Text.js +62 -0
- package/package.json +81 -76
- package/src/EpubReader.tsx +239 -43
- package/src/EpubReaderView.tsx +287 -99
- package/src/cfiOrder.ts +28 -0
- package/src/engine/epubcfi.js +527 -0
- package/src/engine/html.ts +1 -1
- package/src/engine/reader.js +1273 -157
- package/src/index.ts +5 -2
- package/src/strings.ts +187 -0
- package/src/themes.ts +97 -21
- package/src/types.ts +88 -2
- package/src/ui/AppearanceSheet.tsx +47 -29
- package/src/ui/ContentsSheet.tsx +34 -22
- package/src/ui/CustomizeSheet.tsx +27 -21
- package/src/ui/HighlightMenu.tsx +17 -13
- package/src/ui/NoteEditor.tsx +12 -9
- package/src/ui/SearchSheet.tsx +22 -5
- package/src/ui/Sheet.tsx +8 -5
- package/src/ui/Text.tsx +27 -0
package/src/EpubReader.tsx
CHANGED
|
@@ -1,35 +1,77 @@
|
|
|
1
1
|
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
|
|
2
|
-
import { StyleSheet, View } from 'react-native';
|
|
2
|
+
import { AppState, StyleSheet, View } from 'react-native';
|
|
3
3
|
import { WebView } from 'react-native-webview';
|
|
4
4
|
import type { WebViewMessageEvent } from 'react-native-webview';
|
|
5
5
|
import { READER_HTML } from './engine/html';
|
|
6
6
|
import { themeColors, toEngineSettings } from './themes';
|
|
7
7
|
import type {
|
|
8
|
+
BookColors,
|
|
8
9
|
BookLocation,
|
|
9
10
|
BookMetadata,
|
|
11
|
+
CfiHighlight,
|
|
12
|
+
CustomFont,
|
|
10
13
|
EpubSource,
|
|
11
14
|
Highlight,
|
|
12
15
|
ReaderSettings,
|
|
16
|
+
ReaderTheme,
|
|
13
17
|
RelocateEvent,
|
|
18
|
+
SafeInsets,
|
|
14
19
|
SearchResult,
|
|
15
20
|
SelectionEvent,
|
|
16
21
|
TocItem
|
|
17
22
|
} from './types';
|
|
18
23
|
|
|
24
|
+
export interface ReaderErrorInfo {
|
|
25
|
+
/** true when the book cannot be shown (failed to open, reader engine stopped); false for a problem on one page */
|
|
26
|
+
fatal: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
19
29
|
export interface EpubReaderProps {
|
|
20
30
|
source: EpubSource;
|
|
21
31
|
settings: ReaderSettings;
|
|
22
32
|
/** system colour scheme, used when settings.appearance is 'device' */
|
|
23
33
|
systemDark?: boolean;
|
|
24
|
-
/** Space reserved for status bar / home indicator. The engine adds room for the running header and footer. */
|
|
25
|
-
safeInsets?:
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
|
|
30
|
-
|
|
34
|
+
/** Space reserved for status bar / home indicator (and the notch in landscape). The engine adds room for the running header and footer. */
|
|
35
|
+
safeInsets?: SafeInsets;
|
|
36
|
+
/** Running header (chapter) and footer (page) on the page. false: none, and no space is kept for them. Default true. */
|
|
37
|
+
runningLabels?: boolean;
|
|
38
|
+
/** where to open: an offset, a share of the book, or an epub.js CFI ({ cfi: 'epubcfi(...)' }) */
|
|
39
|
+
initialLocation?: BookLocation | { progress: number } | { cfi: string };
|
|
40
|
+
/** highlights as offsets, or as epub.js CFIs only (CfiHighlight). A `cfi` always wins over offsets. */
|
|
41
|
+
highlights?: (Highlight | CfiHighlight)[];
|
|
42
|
+
/**
|
|
43
|
+
* Characters per epub.js location ("chunk"), as in epub.js book.locations.generate(n). Default 150 (the epub.js
|
|
44
|
+
* default). Keep it the same for a book forever if you store or pay by location numbers. 0 turns locations off.
|
|
45
|
+
*/
|
|
46
|
+
locationChars?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Show runs of 3+ zero-width characters (U+200B/C/D, U+FEFF), such as a hidden watermark, as U+2060 WORD JOINER,
|
|
49
|
+
* one for one, so they do not break words. Nothing is deleted, so offsets and CFIs do not change. Default true.
|
|
50
|
+
*/
|
|
51
|
+
repairZeroWidth?: boolean;
|
|
52
|
+
/** Highlight colours by name, e.g. { yellow: '#ffff00' }. A Highlight's `color` may also be a CSS colour itself. */
|
|
53
|
+
highlightColors?: Record<string, string>;
|
|
54
|
+
/** Fill opacity for highlightColors (default 0.3, like epub.js). */
|
|
55
|
+
highlightOpacity?: number;
|
|
56
|
+
/** Fonts loaded into every chapter with @font-face. A font with an `id` can be chosen with settings.fontId. */
|
|
57
|
+
fonts?: CustomFont[];
|
|
58
|
+
/** 'theme' (default): all text in the theme colour. 'keep': the book's own colours stay, made readable. */
|
|
59
|
+
bookColors?: BookColors;
|
|
60
|
+
/** Largest pinch zoom (default 3). 1 turns pinch zoom off. Paged modes only. */
|
|
61
|
+
maxZoom?: number;
|
|
62
|
+
/** Page themes to use instead of the built-in ones. settings.themeId picks one; an unknown id gets the first. */
|
|
63
|
+
themes?: ReaderTheme[];
|
|
64
|
+
/**
|
|
65
|
+
* Largest EPUB (bytes) that will be loaded. The whole book is held in memory while it is opened, so very large
|
|
66
|
+
* files can crash low-memory phones. Default 150 MB, 0 disables the check.
|
|
67
|
+
*/
|
|
68
|
+
maxFileSize?: number;
|
|
31
69
|
onReady?: (info: { metadata: BookMetadata; rtl: boolean }) => void;
|
|
32
|
-
|
|
70
|
+
/**
|
|
71
|
+
* items: the entries whose file is in the book. all: every entry, in the same order, with spine -1 for an entry
|
|
72
|
+
* whose file is missing (for example the chapters a preview leaves out). tocIndex points into items.
|
|
73
|
+
*/
|
|
74
|
+
onToc?: (items: TocItem[], all: TocItem[]) => void;
|
|
33
75
|
onCover?: (dataUri: string) => void;
|
|
34
76
|
onRelocate?: (e: RelocateEvent) => void;
|
|
35
77
|
/** fired once the whole book has been indexed: cumulative character offset of every spine item */
|
|
@@ -39,16 +81,31 @@ export interface EpubReaderProps {
|
|
|
39
81
|
onTap?: () => void;
|
|
40
82
|
/** a page turn animation is starting (use it to play a sound) */
|
|
41
83
|
onPageTurn?: () => void;
|
|
84
|
+
/** a web or mail link was tapped (other schemes are never forwarded). Open it yourself, ideally after asking. */
|
|
42
85
|
onLink?: (href: string) => void;
|
|
86
|
+
/** an internal link (footnote, cross reference) is about to jump; `from` is where the reader was, so you can offer a way back */
|
|
87
|
+
onLinkJump?: (from: BookLocation) => void;
|
|
88
|
+
/** the reading direction changed (the user overrode it in the settings) */
|
|
89
|
+
onDirectionChange?: (rtl: boolean) => void;
|
|
43
90
|
onSearchResults?: (searchId: number, results: SearchResult[], done: boolean) => void;
|
|
91
|
+
/** epub.js locations are counted (after the book is indexed). From now on onRelocate carries `locations`. */
|
|
92
|
+
onLocations?: (info: { count: number }) => void;
|
|
93
|
+
/** the page was zoomed with two fingers (scale 1 = back to normal) */
|
|
94
|
+
onZoom?: (scale: number) => void;
|
|
44
95
|
onEndReached?: (edge: 'start' | 'end') => void;
|
|
45
|
-
onError?: (message: string) => void;
|
|
96
|
+
onError?: (message: string, info: ReaderErrorInfo) => void;
|
|
46
97
|
}
|
|
47
98
|
|
|
48
99
|
export interface EpubReaderHandle {
|
|
49
100
|
next(): void;
|
|
50
101
|
prev(): void;
|
|
51
|
-
goTo(
|
|
102
|
+
goTo(
|
|
103
|
+
location:
|
|
104
|
+
| { spine: number; offset?: number; fragment?: string }
|
|
105
|
+
| { progress: number }
|
|
106
|
+
/** spine / offset: where to go when the CFI is not found in this book */
|
|
107
|
+
| { cfi: string; spine?: number; offset?: number }
|
|
108
|
+
): void;
|
|
52
109
|
search(query: string, searchId: number): void;
|
|
53
110
|
cancelSearch(searchId?: number): void;
|
|
54
111
|
/** Jump to a search result and flash the match. */
|
|
@@ -58,12 +115,53 @@ export interface EpubReaderHandle {
|
|
|
58
115
|
setLabels(header: string, footer: string): void;
|
|
59
116
|
}
|
|
60
117
|
|
|
61
|
-
|
|
62
|
-
|
|
118
|
+
const DEFAULT_MAX_FILE = 150 * 1024 * 1024;
|
|
119
|
+
const ENGINE_START_TIMEOUT = 20000;
|
|
120
|
+
const CHUNK = 256 * 1024;
|
|
121
|
+
|
|
122
|
+
function stripDataPrefix(b64: string): string {
|
|
123
|
+
return b64.startsWith('data:') ? b64.slice(b64.indexOf(',') + 1) : b64;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Font data as plain base64, or '' when it is not base64. Only these characters may go into the injected script.
|
|
127
|
+
function cleanFontBase64(b64: string): string {
|
|
128
|
+
const data = stripDataPrefix(b64 || '').replace(/\s+/g, '').replace(/-/g, '+').replace(/_/g, '/');
|
|
129
|
+
return /^[A-Za-z0-9+/]+=*$/.test(data) ? data : '';
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// identity of a font list: changes when a font is added, removed or replaced
|
|
133
|
+
function fontsKeyOf(fonts?: CustomFont[]): string {
|
|
134
|
+
return (fonts || []).map((f) => [f.id, f.family, f.weight, f.style, f.mime, sourceKeyOf({ base64: f.base64 })].join('|')).join(';');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Identity of a source: the explicit `key`, the uri, or a fingerprint sampled across the base64 data. */
|
|
138
|
+
export function sourceKeyOf(source: EpubSource): string {
|
|
139
|
+
if (source.key) return source.key;
|
|
140
|
+
if ('uri' in source) return source.uri;
|
|
141
|
+
const b = source.base64;
|
|
142
|
+
let h = 5381;
|
|
143
|
+
const step = Math.max(1, Math.floor(b.length / 512));
|
|
144
|
+
for (let i = 0; i < b.length; i += step) h = ((h << 5) + h + b.charCodeAt(i)) | 0;
|
|
145
|
+
return `b64:${b.length}:${h >>> 0}`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async function uriToBase64(source: { uri: string; headers?: Record<string, string> }, maxBytes: number): Promise<string> {
|
|
149
|
+
let res: Response;
|
|
150
|
+
try {
|
|
151
|
+
res = await fetch(source.uri, source.headers ? { headers: source.headers } : undefined);
|
|
152
|
+
} catch {
|
|
153
|
+
throw new Error('The book file could not be opened (it may have been moved or deleted, or there is no connection).');
|
|
154
|
+
}
|
|
155
|
+
// file:// responses report status 0 on some platforms, so only real HTTP errors count
|
|
156
|
+
if (res.status >= 400) throw new Error(`The book could not be downloaded (error ${res.status}).`);
|
|
63
157
|
const blob = await res.blob();
|
|
158
|
+
if (maxBytes > 0 && blob.size > maxBytes) {
|
|
159
|
+
throw new Error(`This book is too large to open (${Math.round(blob.size / 1048576)} MB).`);
|
|
160
|
+
}
|
|
161
|
+
if (blob.size === 0) throw new Error('The book file is empty.');
|
|
64
162
|
return new Promise<string>((resolve, reject) => {
|
|
65
163
|
const fr = new FileReader();
|
|
66
|
-
fr.onerror = () => reject(
|
|
164
|
+
fr.onerror = () => reject(new Error('The book file could not be read.'));
|
|
67
165
|
fr.onloadend = () => {
|
|
68
166
|
const s = String(fr.result);
|
|
69
167
|
resolve(s.slice(s.indexOf(',') + 1));
|
|
@@ -72,6 +170,13 @@ async function uriToBase64(uri: string): Promise<string> {
|
|
|
72
170
|
});
|
|
73
171
|
}
|
|
74
172
|
|
|
173
|
+
function cleanBase64(data: string): string {
|
|
174
|
+
let s = data;
|
|
175
|
+
if (s.startsWith('data:')) s = s.slice(s.indexOf(',') + 1);
|
|
176
|
+
if (/\s/.test(s.slice(0, 4096)) || s.indexOf('\n') >= 0) s = s.replace(/\s+/g, '');
|
|
177
|
+
return s;
|
|
178
|
+
}
|
|
179
|
+
|
|
75
180
|
const LS = String.fromCharCode(0x2028);
|
|
76
181
|
const PS = String.fromCharCode(0x2029);
|
|
77
182
|
|
|
@@ -82,45 +187,110 @@ function toScript(cmd: object): string {
|
|
|
82
187
|
}
|
|
83
188
|
|
|
84
189
|
export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function EpubReader(props, ref) {
|
|
85
|
-
const { source, settings, systemDark = false, safeInsets = { top: 0, bottom: 0 }, highlights,
|
|
190
|
+
const { source, settings, systemDark = false, safeInsets = { top: 0, bottom: 0 }, highlights, fonts } = props;
|
|
86
191
|
const web = useRef<WebView>(null);
|
|
87
192
|
const cb = useRef(props);
|
|
88
193
|
cb.current = props;
|
|
89
194
|
const [engineReady, setEngineReady] = useState(false);
|
|
195
|
+
// bumping this remounts the WebView (after the system killed its process)
|
|
196
|
+
const [webKey, setWebKey] = useState(0);
|
|
90
197
|
const opened = useRef(false);
|
|
91
|
-
const selection = useRef<SelectionEvent | null>(null);
|
|
92
198
|
const metaRef = useRef<BookMetadata>({ title: '', author: '', language: '', publisher: '' });
|
|
199
|
+
const lastLoc = useRef<BookLocation | null>(null);
|
|
200
|
+
const lastKey = useRef('');
|
|
201
|
+
const fontGen = useRef(0);
|
|
93
202
|
|
|
203
|
+
const fontsKey = fontsKeyOf(fonts);
|
|
204
|
+
const hlColorsJson = JSON.stringify(props.highlightColors || null);
|
|
205
|
+
const themesJson = JSON.stringify(props.themes || null);
|
|
94
206
|
const engineSettings = useMemo(
|
|
95
|
-
() =>
|
|
207
|
+
() => ({
|
|
208
|
+
...toEngineSettings(settings, systemDark, safeInsets, fonts, props.themes, props.runningLabels !== false),
|
|
209
|
+
highlightColors: props.highlightColors || {},
|
|
210
|
+
highlightOpacity: props.highlightOpacity ?? 0.3,
|
|
211
|
+
bookColors: props.bookColors || 'theme',
|
|
212
|
+
maxZoom: props.maxZoom ?? 3
|
|
213
|
+
}),
|
|
96
214
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
97
|
-
[settings, systemDark, safeInsets.top, safeInsets.bottom]
|
|
215
|
+
[settings, systemDark, safeInsets.top, safeInsets.bottom, safeInsets.left, safeInsets.right, fontsKey, hlColorsJson, themesJson, props.highlightOpacity, props.bookColors, props.maxZoom, props.runningLabels]
|
|
98
216
|
);
|
|
217
|
+
// only what the engine actually uses decides about re-layout (the brightness slider, the page sound ... must not)
|
|
218
|
+
const engineJson = JSON.stringify(engineSettings);
|
|
219
|
+
const latest = useRef({ engineSettings, highlights });
|
|
220
|
+
latest.current = { engineSettings, highlights };
|
|
99
221
|
|
|
100
222
|
const send = useCallback((cmd: object) => {
|
|
101
223
|
web.current?.injectJavaScript(toScript(cmd));
|
|
102
224
|
}, []);
|
|
103
225
|
|
|
226
|
+
// iOS pauses the WebView in the background, so the start timer only counts while the app is in front
|
|
227
|
+
const [inFront, setInFront] = useState(AppState.currentState !== 'background');
|
|
228
|
+
useEffect(() => {
|
|
229
|
+
const sub = AppState.addEventListener('change', (state) => setInFront(state !== 'background'));
|
|
230
|
+
return () => sub.remove();
|
|
231
|
+
}, []);
|
|
232
|
+
|
|
233
|
+
// the engine never started (blocked WebView, out of memory ...)
|
|
234
|
+
useEffect(() => {
|
|
235
|
+
if (engineReady || !inFront) return;
|
|
236
|
+
const t = setTimeout(() => cb.current.onError?.('The reader could not be started.', { fatal: true }), ENGINE_START_TIMEOUT);
|
|
237
|
+
return () => clearTimeout(t);
|
|
238
|
+
}, [engineReady, webKey, inFront]);
|
|
239
|
+
|
|
240
|
+
// Fonts go before the book (so the first page already uses them), in pieces like the book. Only when they change.
|
|
241
|
+
useEffect(() => {
|
|
242
|
+
if (!engineReady) return;
|
|
243
|
+
// new keys for every update, so a later update cannot overwrite the data of one still waiting in the queue
|
|
244
|
+
const gen = ++fontGen.current;
|
|
245
|
+
const list: { key: string; family: string; mime?: string; weight?: CustomFont['weight']; style?: CustomFont['style'] }[] = [];
|
|
246
|
+
(cb.current.fonts || []).forEach((f, i) => {
|
|
247
|
+
const data = cleanFontBase64(f.base64);
|
|
248
|
+
if (!data) {
|
|
249
|
+
cb.current.onError?.(`The font "${f.family}" was skipped: its data is not valid base64.`, { fatal: false });
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const key = `f${gen}_${i}`;
|
|
253
|
+
for (let k = 0; k < data.length; k += CHUNK) {
|
|
254
|
+
web.current?.injectJavaScript(`window.__blob("${key}",${k === 0 ? 1 : 0},"${data.slice(k, k + CHUNK)}");true;`);
|
|
255
|
+
}
|
|
256
|
+
list.push({ key, family: f.family, mime: f.mime, weight: f.weight, style: f.style });
|
|
257
|
+
});
|
|
258
|
+
send({ cmd: 'fonts', list });
|
|
259
|
+
}, [engineReady, fontsKey, send]);
|
|
260
|
+
|
|
104
261
|
// open (or re-open) the book once the engine is up
|
|
105
|
-
const sourceKey =
|
|
262
|
+
const sourceKey = sourceKeyOf(source);
|
|
106
263
|
useEffect(() => {
|
|
107
264
|
if (!engineReady) return;
|
|
108
265
|
let cancelled = false;
|
|
109
266
|
opened.current = false;
|
|
267
|
+
if (lastKey.current !== sourceKey) {
|
|
268
|
+
lastKey.current = sourceKey;
|
|
269
|
+
lastLoc.current = null;
|
|
270
|
+
}
|
|
110
271
|
(async () => {
|
|
111
272
|
try {
|
|
112
|
-
const
|
|
273
|
+
const limit = cb.current.maxFileSize ?? DEFAULT_MAX_FILE;
|
|
274
|
+
let data = 'uri' in source ? await uriToBase64(source, limit) : cleanBase64(source.base64);
|
|
113
275
|
if (cancelled) return;
|
|
276
|
+
if (!data) throw new Error('The book file is empty.');
|
|
277
|
+
// the book travels in pieces: one huge string would exist several times over (JSON, bridge, page)
|
|
278
|
+
for (let i = 0; i < data.length; i += CHUNK) {
|
|
279
|
+
web.current?.injectJavaScript(`window.__chunk(${i === 0 ? 1 : 0},"${data.slice(i, i + CHUNK)}");true;`);
|
|
280
|
+
}
|
|
281
|
+
data = '';
|
|
282
|
+
// settings, highlights and position are read now, not when loading started
|
|
114
283
|
send({
|
|
115
284
|
cmd: 'open',
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
285
|
+
settings: latest.current.engineSettings,
|
|
286
|
+
highlights: latest.current.highlights || [],
|
|
287
|
+
location: lastLoc.current || cb.current.initialLocation,
|
|
288
|
+
locationChars: cb.current.locationChars ?? 150,
|
|
289
|
+
repairZeroWidth: cb.current.repairZeroWidth !== false
|
|
120
290
|
});
|
|
121
291
|
opened.current = true;
|
|
122
292
|
} catch (e) {
|
|
123
|
-
cb.current.onError?.(String((e as Error)?.message || e));
|
|
293
|
+
cb.current.onError?.(String((e as Error)?.message || e), { fatal: true });
|
|
124
294
|
}
|
|
125
295
|
})();
|
|
126
296
|
return () => {
|
|
@@ -130,13 +300,20 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
130
300
|
}, [engineReady, sourceKey]);
|
|
131
301
|
|
|
132
302
|
useEffect(() => {
|
|
133
|
-
if (opened.current) send({ cmd: 'settings', settings: engineSettings });
|
|
134
|
-
}, [
|
|
303
|
+
if (opened.current) send({ cmd: 'settings', settings: latest.current.engineSettings });
|
|
304
|
+
}, [engineJson, send]);
|
|
135
305
|
|
|
136
306
|
useEffect(() => {
|
|
137
307
|
if (opened.current) send({ cmd: 'highlights', list: highlights || [] });
|
|
138
308
|
}, [highlights, send]);
|
|
139
309
|
|
|
310
|
+
// Android killed the renderer / iOS terminated the web content process: start over at the last position
|
|
311
|
+
const recover = useCallback(() => {
|
|
312
|
+
opened.current = false;
|
|
313
|
+
setEngineReady(false);
|
|
314
|
+
setWebKey((k) => k + 1);
|
|
315
|
+
}, []);
|
|
316
|
+
|
|
140
317
|
useImperativeHandle(
|
|
141
318
|
ref,
|
|
142
319
|
() => ({
|
|
@@ -150,7 +327,6 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
150
327
|
send({ cmd: 'showHit', offset: r.offset, length: r.length });
|
|
151
328
|
},
|
|
152
329
|
clearSelection: () => {
|
|
153
|
-
selection.current = null;
|
|
154
330
|
send({ cmd: 'clearSelection' });
|
|
155
331
|
},
|
|
156
332
|
setLabels: (header, footer) => send({ cmd: 'labels', header, footer })
|
|
@@ -165,8 +341,9 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
165
341
|
} catch {
|
|
166
342
|
return;
|
|
167
343
|
}
|
|
344
|
+
if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string') return;
|
|
168
345
|
const p = cb.current;
|
|
169
|
-
const d = msg.data;
|
|
346
|
+
const d = msg.data && typeof msg.data === 'object' ? msg.data : {};
|
|
170
347
|
switch (msg.type) {
|
|
171
348
|
case 'ready':
|
|
172
349
|
setEngineReady(true);
|
|
@@ -176,23 +353,25 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
176
353
|
break;
|
|
177
354
|
case 'toc':
|
|
178
355
|
p.onReady?.({ metadata: metaRef.current, rtl: !!d.rtl });
|
|
179
|
-
|
|
356
|
+
{
|
|
357
|
+
const items = Array.isArray(d.items) ? d.items : [];
|
|
358
|
+
p.onToc?.(items, Array.isArray(d.all) ? d.all : items);
|
|
359
|
+
}
|
|
180
360
|
break;
|
|
181
361
|
case 'cover':
|
|
182
|
-
p.onCover?.(d.uri);
|
|
362
|
+
if (typeof d.uri === 'string') p.onCover?.(d.uri);
|
|
183
363
|
break;
|
|
184
364
|
case 'relocate':
|
|
365
|
+
lastLoc.current = { spine: d.spine, offset: d.offset };
|
|
185
366
|
p.onRelocate?.(d);
|
|
186
367
|
break;
|
|
187
368
|
case 'indexed':
|
|
188
369
|
p.onIndexed?.(d);
|
|
189
370
|
break;
|
|
190
371
|
case 'selection':
|
|
191
|
-
selection.current = d;
|
|
192
372
|
p.onSelection?.(d);
|
|
193
373
|
break;
|
|
194
374
|
case 'selectionClear':
|
|
195
|
-
selection.current = null;
|
|
196
375
|
p.onSelection?.(null);
|
|
197
376
|
break;
|
|
198
377
|
case 'highlightTap':
|
|
@@ -205,25 +384,38 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
205
384
|
p.onPageTurn?.();
|
|
206
385
|
break;
|
|
207
386
|
case 'link':
|
|
208
|
-
p.onLink?.(d.href);
|
|
387
|
+
if (typeof d.href === 'string' && /^(https?|mailto):/i.test(d.href)) p.onLink?.(d.href);
|
|
388
|
+
break;
|
|
389
|
+
case 'linkJump':
|
|
390
|
+
p.onLinkJump?.({ spine: d.spine, offset: d.offset });
|
|
391
|
+
break;
|
|
392
|
+
case 'direction':
|
|
393
|
+
p.onDirectionChange?.(!!d.rtl);
|
|
209
394
|
break;
|
|
210
395
|
case 'searchResults':
|
|
211
|
-
p.onSearchResults?.(d.id, d.results, d.done);
|
|
396
|
+
p.onSearchResults?.(d.id, Array.isArray(d.results) ? d.results : [], !!d.done);
|
|
212
397
|
break;
|
|
213
398
|
case 'end':
|
|
214
399
|
p.onEndReached?.(d.edge);
|
|
215
400
|
break;
|
|
401
|
+
case 'locations':
|
|
402
|
+
p.onLocations?.({ count: d.count });
|
|
403
|
+
break;
|
|
404
|
+
case 'zoom':
|
|
405
|
+
p.onZoom?.(typeof d.scale === 'number' ? d.scale : 1);
|
|
406
|
+
break;
|
|
216
407
|
case 'error':
|
|
217
|
-
p.onError?.(d.message);
|
|
408
|
+
p.onError?.(String(d.message || 'Unknown error'), { fatal: !!d.fatal });
|
|
218
409
|
break;
|
|
219
410
|
}
|
|
220
411
|
}, []);
|
|
221
412
|
|
|
222
|
-
const bg = themeColors(settings, systemDark).bg;
|
|
413
|
+
const bg = themeColors(settings, systemDark, props.themes).bg;
|
|
223
414
|
|
|
224
415
|
return (
|
|
225
416
|
<View style={[styles.fill, { backgroundColor: bg }]}>
|
|
226
417
|
<WebView
|
|
418
|
+
key={webKey}
|
|
227
419
|
ref={web}
|
|
228
420
|
style={[styles.fill, { backgroundColor: bg }]}
|
|
229
421
|
originWhitelist={['*']}
|
|
@@ -241,13 +433,17 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
241
433
|
allowsInlineMediaPlayback
|
|
242
434
|
hideKeyboardAccessoryView
|
|
243
435
|
setSupportMultipleWindows={false}
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
436
|
+
// the page is generated here and never needs the file system, the network or the system font scale
|
|
437
|
+
allowFileAccess={false}
|
|
438
|
+
allowFileAccessFromFileURLs={false}
|
|
439
|
+
allowUniversalAccessFromFileURLs={false}
|
|
440
|
+
mixedContentMode="never"
|
|
441
|
+
cacheEnabled={false}
|
|
442
|
+
textZoom={100}
|
|
249
443
|
onShouldStartLoadWithRequest={(req) => req.url === 'about:blank' || req.url.startsWith('data:') || req.url.startsWith('about:')}
|
|
250
|
-
|
|
444
|
+
onRenderProcessGone={recover}
|
|
445
|
+
onContentProcessDidTerminate={recover}
|
|
446
|
+
onError={(e) => cb.current.onError?.(e.nativeEvent.description || 'The reader failed to load.', { fatal: true })}
|
|
251
447
|
/>
|
|
252
448
|
</View>
|
|
253
449
|
);
|