aksos-react-native-epub-reader 0.1.0 → 0.1.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/README.md +21 -8
- package/lib/EpubReader.d.ts +20 -7
- package/lib/EpubReader.js +106 -21
- package/lib/EpubReaderView.d.ts +12 -5
- package/lib/EpubReaderView.js +175 -80
- 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 +4 -0
- package/lib/themes.js +1 -1
- package/lib/types.d.ts +16 -0
- package/lib/ui/AppearanceSheet.js +23 -16
- package/lib/ui/ContentsSheet.js +16 -14
- package/lib/ui/CustomizeSheet.js +17 -15
- package/lib/ui/HighlightMenu.js +11 -9
- package/lib/ui/NoteEditor.js +10 -8
- package/lib/ui/SearchSheet.js +15 -3
- package/lib/ui/Sheet.js +5 -3
- package/package.json +75 -75
- package/src/EpubReader.tsx +123 -23
- package/src/EpubReaderView.tsx +229 -85
- package/src/engine/html.ts +1 -1
- package/src/engine/reader.js +455 -104
- package/src/index.ts +5 -2
- package/src/strings.ts +187 -0
- package/src/themes.ts +2 -2
- package/src/types.ts +17 -1
- package/src/ui/AppearanceSheet.tsx +28 -19
- package/src/ui/ContentsSheet.tsx +20 -18
- package/src/ui/CustomizeSheet.tsx +17 -15
- package/src/ui/HighlightMenu.tsx +11 -9
- package/src/ui/NoteEditor.tsx +10 -8
- package/src/ui/SearchSheet.tsx +21 -5
- package/src/ui/Sheet.tsx +5 -3
package/lib/ui/SearchSheet.js
CHANGED
|
@@ -36,10 +36,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
36
36
|
exports.SearchSheet = SearchSheet;
|
|
37
37
|
const react_1 = __importStar(require("react"));
|
|
38
38
|
const react_native_1 = require("react-native");
|
|
39
|
+
const strings_1 = require("../strings");
|
|
39
40
|
const Icons_1 = require("./Icons");
|
|
40
41
|
const Sheet_1 = require("./Sheet");
|
|
41
42
|
function SearchSheet({ visible, colors, results, searching, onClose, onSearch, onPick }) {
|
|
43
|
+
const L = (0, strings_1.useLabels)();
|
|
42
44
|
const [q, setQ] = (0, react_1.useState)('');
|
|
45
|
+
const [kb, setKb] = (0, react_1.useState)(0);
|
|
46
|
+
// the sheet sits at the bottom, so the keyboard would cover the lower results
|
|
47
|
+
(0, react_1.useEffect)(() => {
|
|
48
|
+
const show = react_native_1.Keyboard.addListener('keyboardDidShow', (e) => setKb(e.endCoordinates?.height || 0));
|
|
49
|
+
const hide = react_native_1.Keyboard.addListener('keyboardDidHide', () => setKb(0));
|
|
50
|
+
return () => {
|
|
51
|
+
show.remove();
|
|
52
|
+
hide.remove();
|
|
53
|
+
};
|
|
54
|
+
}, []);
|
|
43
55
|
const timer = (0, react_1.useRef)(undefined);
|
|
44
56
|
(0, react_1.useEffect)(() => {
|
|
45
57
|
clearTimeout(timer.current);
|
|
@@ -47,11 +59,11 @@ function SearchSheet({ visible, colors, results, searching, onClose, onSearch, o
|
|
|
47
59
|
return () => clearTimeout(timer.current);
|
|
48
60
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
49
61
|
}, [q]);
|
|
50
|
-
return (react_1.default.createElement(Sheet_1.Sheet, { visible: visible, colors: colors, onClose: onClose, height: "85%", title:
|
|
62
|
+
return (react_1.default.createElement(Sheet_1.Sheet, { visible: visible, colors: colors, onClose: onClose, height: "85%", title: L.search },
|
|
51
63
|
react_1.default.createElement(react_native_1.View, { style: [styles.field, { backgroundColor: colors.card }] },
|
|
52
64
|
react_1.default.createElement(Icons_1.Icon, { name: "search", color: colors.subtext, size: 20 }),
|
|
53
|
-
react_1.default.createElement(react_native_1.TextInput, { value: q, onChangeText: setQ, placeholder:
|
|
54
|
-
react_1.default.createElement(react_native_1.FlatList, { data: results, keyboardShouldPersistTaps: "handled", keyExtractor: (_, i) => String(i), ListHeaderComponent: q.trim().length >= 2 ? (react_1.default.createElement(react_native_1.Text, { style: [styles.count, { color: colors.subtext }] }, searching ?
|
|
65
|
+
react_1.default.createElement(react_native_1.TextInput, { value: q, onChangeText: setQ, placeholder: L.searchInBook, accessibilityLabel: L.searchInBook, placeholderTextColor: colors.subtext, style: [styles.input, { color: colors.text }], autoCorrect: false, returnKeyType: "search", onSubmitEditing: () => onSearch(q), clearButtonMode: "while-editing" })),
|
|
66
|
+
react_1.default.createElement(react_native_1.FlatList, { data: results, keyboardShouldPersistTaps: "handled", keyboardDismissMode: "on-drag", contentContainerStyle: { paddingBottom: kb }, keyExtractor: (_, i) => String(i), ListHeaderComponent: q.trim().length >= 2 ? (react_1.default.createElement(react_native_1.Text, { style: [styles.count, { color: colors.subtext }] }, searching ? L.searching : results.length === 0 ? L.noResults : `${L.formatNumber(results.length)}${results.length >= 500 ? '+' : ''}`)) : null, renderItem: ({ item }) => (react_1.default.createElement(react_native_1.Pressable, { onPress: () => onPick(item), style: [styles.row, { borderColor: colors.separator }], accessibilityRole: "button" },
|
|
55
67
|
react_1.default.createElement(react_native_1.Text, { style: [styles.chapter, { color: colors.accent }], numberOfLines: 1 }, item.chapter),
|
|
56
68
|
react_1.default.createElement(react_native_1.Text, { style: { color: colors.text, fontSize: 15, lineHeight: 21 }, numberOfLines: 3 },
|
|
57
69
|
item.before,
|
package/lib/ui/Sheet.js
CHANGED
|
@@ -7,11 +7,13 @@ exports.Sheet = Sheet;
|
|
|
7
7
|
const react_1 = __importDefault(require("react"));
|
|
8
8
|
const react_native_1 = require("react-native");
|
|
9
9
|
const Glass_1 = require("./Glass");
|
|
10
|
+
const strings_1 = require("../strings");
|
|
10
11
|
const Icons_1 = require("./Icons");
|
|
11
12
|
/** Rounded frosted-glass sheet: the book stays faintly visible behind it. */
|
|
12
13
|
function Sheet({ visible, title, subtitle, colors, height = '70%', closeIcon = 'x', onClose, children, overlay }) {
|
|
13
|
-
const
|
|
14
|
-
|
|
14
|
+
const L = (0, strings_1.useLabels)();
|
|
15
|
+
const button = closeIcon === 'check' ? (react_1.default.createElement(react_native_1.Pressable, { onPress: onClose, hitSlop: 10, style: [styles.circle, { backgroundColor: colors.dark ? '#ffffff' : '#000000' }], accessibilityRole: "button", accessibilityLabel: L.done },
|
|
16
|
+
react_1.default.createElement(Icons_1.Icon, { name: "check", color: colors.dark ? '#000000' : '#ffffff', size: 24, strokeWidth: 2.2 }))) : (react_1.default.createElement(react_native_1.Pressable, { onPress: onClose, hitSlop: 10, accessibilityRole: "button", accessibilityLabel: L.close },
|
|
15
17
|
react_1.default.createElement(Glass_1.Glass, { dark: colors.dark, background: colors.glass, border: colors.glassBorder, style: styles.circle },
|
|
16
18
|
react_1.default.createElement(Icons_1.Icon, { name: "close", color: colors.text, size: 22 }))));
|
|
17
19
|
return (react_1.default.createElement(react_native_1.Modal, { visible: visible, transparent: true, animationType: "slide", onRequestClose: onClose, statusBarTranslucent: true },
|
|
@@ -20,7 +22,7 @@ function Sheet({ visible, title, subtitle, colors, height = '70%', closeIcon = '
|
|
|
20
22
|
react_1.default.createElement(react_native_1.View, { style: styles.header },
|
|
21
23
|
closeIcon === 'x' && button,
|
|
22
24
|
react_1.default.createElement(react_native_1.View, { style: styles.titleBox, pointerEvents: "none" },
|
|
23
|
-
!!title && (react_1.default.createElement(react_native_1.Text, { style: [styles.title, { color: colors.text }], numberOfLines: 1 }, title)),
|
|
25
|
+
!!title && (react_1.default.createElement(react_native_1.Text, { style: [styles.title, { color: colors.text }], numberOfLines: 1, maxFontSizeMultiplier: 1.3, accessibilityRole: "header" }, title)),
|
|
24
26
|
!!subtitle && react_1.default.createElement(react_native_1.Text, { style: [styles.subtitle, { color: colors.text }] }, subtitle)),
|
|
25
27
|
react_1.default.createElement(react_native_1.View, { style: { flex: 1 } }),
|
|
26
28
|
closeIcon === 'check' && button),
|
package/package.json
CHANGED
|
@@ -1,76 +1,76 @@
|
|
|
1
1
|
{
|
|
2
|
-
"name":
|
|
3
|
-
"version":
|
|
4
|
-
"description":
|
|
5
|
-
"keywords":
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"license":
|
|
21
|
-
"main":
|
|
22
|
-
"types":
|
|
23
|
-
"react-native":
|
|
24
|
-
"source":
|
|
25
|
-
"files":
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
"scripts":
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
"peerDependencies":
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"peerDependenciesMeta":
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
"devDependencies":
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
"author":
|
|
68
|
-
"homepage":
|
|
69
|
-
"repository":
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
"bugs":
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
}
|
|
2
|
+
"name": "aksos-react-native-epub-reader",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "A complete EPUB reader for React Native and Expo: page curl and slide, themes, highlights, notes, bookmarks, search, line guide, and full right-to-left support (Pashto, Dari, Persian, Arabic, Urdu).",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"react-native",
|
|
7
|
+
"expo",
|
|
8
|
+
"epub",
|
|
9
|
+
"ebook",
|
|
10
|
+
"reader",
|
|
11
|
+
"book",
|
|
12
|
+
"pashto",
|
|
13
|
+
"dari",
|
|
14
|
+
"persian",
|
|
15
|
+
"arabic",
|
|
16
|
+
"rtl",
|
|
17
|
+
"highlight",
|
|
18
|
+
"page-curl"
|
|
19
|
+
],
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"main": "lib/index.js",
|
|
22
|
+
"types": "lib/index.d.ts",
|
|
23
|
+
"react-native": "src/index.ts",
|
|
24
|
+
"source": "src/index.ts",
|
|
25
|
+
"files": [
|
|
26
|
+
"src",
|
|
27
|
+
"lib",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build:engine": "node scripts/build-engine.js",
|
|
33
|
+
"build:lib": "node scripts/build-lib.js",
|
|
34
|
+
"typecheck": "tsc -p tsconfig.build.json --noEmit",
|
|
35
|
+
"prepublishOnly": "npm run build:engine && npm run build:lib",
|
|
36
|
+
"test:harness": "node test/serve.js"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"expo-audio": "*",
|
|
40
|
+
"expo-blur": "*",
|
|
41
|
+
"expo-screen-orientation": "*",
|
|
42
|
+
"react": ">=18",
|
|
43
|
+
"react-native": ">=0.73",
|
|
44
|
+
"react-native-svg": ">=13",
|
|
45
|
+
"react-native-webview": ">=13"
|
|
46
|
+
},
|
|
47
|
+
"peerDependenciesMeta": {
|
|
48
|
+
"expo-audio": {
|
|
49
|
+
"optional": true
|
|
50
|
+
},
|
|
51
|
+
"expo-blur": {
|
|
52
|
+
"optional": true
|
|
53
|
+
},
|
|
54
|
+
"expo-screen-orientation": {
|
|
55
|
+
"optional": true
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
"devDependencies": {
|
|
59
|
+
"@types/react": "^18.3.0",
|
|
60
|
+
"jszip": "3.10.1",
|
|
61
|
+
"react": "18.3.1",
|
|
62
|
+
"react-native": "0.76.5",
|
|
63
|
+
"react-native-svg": "15.9.0",
|
|
64
|
+
"react-native-webview": "13.12.5",
|
|
65
|
+
"typescript": "^5.6.0"
|
|
66
|
+
},
|
|
67
|
+
"author": "Aksos",
|
|
68
|
+
"homepage": "https://github.com/AhmadNasary/aksos-react-native-epub-reader#readme",
|
|
69
|
+
"repository": {
|
|
70
|
+
"type": "git",
|
|
71
|
+
"url": "git+https://github.com/AhmadNasary/aksos-react-native-epub-reader.git"
|
|
72
|
+
},
|
|
73
|
+
"bugs": {
|
|
74
|
+
"url": "https://github.com/AhmadNasary/aksos-react-native-epub-reader/issues"
|
|
75
|
+
}
|
|
76
|
+
}
|
package/src/EpubReader.tsx
CHANGED
|
@@ -11,20 +11,31 @@ import type {
|
|
|
11
11
|
Highlight,
|
|
12
12
|
ReaderSettings,
|
|
13
13
|
RelocateEvent,
|
|
14
|
+
SafeInsets,
|
|
14
15
|
SearchResult,
|
|
15
16
|
SelectionEvent,
|
|
16
17
|
TocItem
|
|
17
18
|
} from './types';
|
|
18
19
|
|
|
20
|
+
export interface ReaderErrorInfo {
|
|
21
|
+
/** true when the book cannot be shown (failed to open, reader engine stopped); false for a problem on one page */
|
|
22
|
+
fatal: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
19
25
|
export interface EpubReaderProps {
|
|
20
26
|
source: EpubSource;
|
|
21
27
|
settings: ReaderSettings;
|
|
22
28
|
/** system colour scheme, used when settings.appearance is 'device' */
|
|
23
29
|
systemDark?: boolean;
|
|
24
|
-
/** Space reserved for status bar / home indicator. The engine adds room for the running header and footer. */
|
|
25
|
-
safeInsets?:
|
|
30
|
+
/** Space reserved for status bar / home indicator (and the notch in landscape). The engine adds room for the running header and footer. */
|
|
31
|
+
safeInsets?: SafeInsets;
|
|
26
32
|
initialLocation?: BookLocation | { progress: number };
|
|
27
33
|
highlights?: Highlight[];
|
|
34
|
+
/**
|
|
35
|
+
* Largest EPUB (bytes) that will be loaded. The whole book is held in memory while it is opened, so very large
|
|
36
|
+
* files can crash low-memory phones. Default 150 MB, 0 disables the check.
|
|
37
|
+
*/
|
|
38
|
+
maxFileSize?: number;
|
|
28
39
|
/** Items added to the native text-selection menu. `onMenuAction` fires with the item key. */
|
|
29
40
|
menuItems?: { label: string; key: string }[];
|
|
30
41
|
onMenuAction?: (key: string, selection: SelectionEvent | null) => void;
|
|
@@ -39,10 +50,15 @@ export interface EpubReaderProps {
|
|
|
39
50
|
onTap?: () => void;
|
|
40
51
|
/** a page turn animation is starting (use it to play a sound) */
|
|
41
52
|
onPageTurn?: () => void;
|
|
53
|
+
/** a web or mail link was tapped (other schemes are never forwarded). Open it yourself, ideally after asking. */
|
|
42
54
|
onLink?: (href: string) => void;
|
|
55
|
+
/** an internal link (footnote, cross reference) is about to jump; `from` is where the reader was, so you can offer a way back */
|
|
56
|
+
onLinkJump?: (from: BookLocation) => void;
|
|
57
|
+
/** the reading direction changed (the user overrode it in the settings) */
|
|
58
|
+
onDirectionChange?: (rtl: boolean) => void;
|
|
43
59
|
onSearchResults?: (searchId: number, results: SearchResult[], done: boolean) => void;
|
|
44
60
|
onEndReached?: (edge: 'start' | 'end') => void;
|
|
45
|
-
onError?: (message: string) => void;
|
|
61
|
+
onError?: (message: string, info: ReaderErrorInfo) => void;
|
|
46
62
|
}
|
|
47
63
|
|
|
48
64
|
export interface EpubReaderHandle {
|
|
@@ -58,12 +74,38 @@ export interface EpubReaderHandle {
|
|
|
58
74
|
setLabels(header: string, footer: string): void;
|
|
59
75
|
}
|
|
60
76
|
|
|
61
|
-
|
|
62
|
-
|
|
77
|
+
const DEFAULT_MAX_FILE = 150 * 1024 * 1024;
|
|
78
|
+
const ENGINE_START_TIMEOUT = 20000;
|
|
79
|
+
const CHUNK = 256 * 1024;
|
|
80
|
+
|
|
81
|
+
/** Identity of a source: the explicit `key`, the uri, or a fingerprint sampled across the base64 data. */
|
|
82
|
+
export function sourceKeyOf(source: EpubSource): string {
|
|
83
|
+
if (source.key) return source.key;
|
|
84
|
+
if ('uri' in source) return source.uri;
|
|
85
|
+
const b = source.base64;
|
|
86
|
+
let h = 5381;
|
|
87
|
+
const step = Math.max(1, Math.floor(b.length / 512));
|
|
88
|
+
for (let i = 0; i < b.length; i += step) h = ((h << 5) + h + b.charCodeAt(i)) | 0;
|
|
89
|
+
return `b64:${b.length}:${h >>> 0}`;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function uriToBase64(source: { uri: string; headers?: Record<string, string> }, maxBytes: number): Promise<string> {
|
|
93
|
+
let res: Response;
|
|
94
|
+
try {
|
|
95
|
+
res = await fetch(source.uri, source.headers ? { headers: source.headers } : undefined);
|
|
96
|
+
} catch {
|
|
97
|
+
throw new Error('The book file could not be opened (it may have been moved or deleted, or there is no connection).');
|
|
98
|
+
}
|
|
99
|
+
// file:// responses report status 0 on some platforms, so only real HTTP errors count
|
|
100
|
+
if (res.status >= 400) throw new Error(`The book could not be downloaded (error ${res.status}).`);
|
|
63
101
|
const blob = await res.blob();
|
|
102
|
+
if (maxBytes > 0 && blob.size > maxBytes) {
|
|
103
|
+
throw new Error(`This book is too large to open (${Math.round(blob.size / 1048576)} MB).`);
|
|
104
|
+
}
|
|
105
|
+
if (blob.size === 0) throw new Error('The book file is empty.');
|
|
64
106
|
return new Promise<string>((resolve, reject) => {
|
|
65
107
|
const fr = new FileReader();
|
|
66
|
-
fr.onerror = () => reject(
|
|
108
|
+
fr.onerror = () => reject(new Error('The book file could not be read.'));
|
|
67
109
|
fr.onloadend = () => {
|
|
68
110
|
const s = String(fr.result);
|
|
69
111
|
resolve(s.slice(s.indexOf(',') + 1));
|
|
@@ -72,6 +114,13 @@ async function uriToBase64(uri: string): Promise<string> {
|
|
|
72
114
|
});
|
|
73
115
|
}
|
|
74
116
|
|
|
117
|
+
function cleanBase64(data: string): string {
|
|
118
|
+
let s = data;
|
|
119
|
+
if (s.startsWith('data:')) s = s.slice(s.indexOf(',') + 1);
|
|
120
|
+
if (/\s/.test(s.slice(0, 4096)) || s.indexOf('\n') >= 0) s = s.replace(/\s+/g, '');
|
|
121
|
+
return s;
|
|
122
|
+
}
|
|
123
|
+
|
|
75
124
|
const LS = String.fromCharCode(0x2028);
|
|
76
125
|
const PS = String.fromCharCode(0x2029);
|
|
77
126
|
|
|
@@ -87,40 +136,66 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
87
136
|
const cb = useRef(props);
|
|
88
137
|
cb.current = props;
|
|
89
138
|
const [engineReady, setEngineReady] = useState(false);
|
|
139
|
+
// bumping this remounts the WebView (after the system killed its process)
|
|
140
|
+
const [webKey, setWebKey] = useState(0);
|
|
90
141
|
const opened = useRef(false);
|
|
91
142
|
const selection = useRef<SelectionEvent | null>(null);
|
|
92
143
|
const metaRef = useRef<BookMetadata>({ title: '', author: '', language: '', publisher: '' });
|
|
144
|
+
const lastLoc = useRef<BookLocation | null>(null);
|
|
145
|
+
const lastKey = useRef('');
|
|
93
146
|
|
|
94
147
|
const engineSettings = useMemo(
|
|
95
148
|
() => toEngineSettings(settings, systemDark, safeInsets),
|
|
96
149
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
97
|
-
[settings, systemDark, safeInsets.top, safeInsets.bottom]
|
|
150
|
+
[settings, systemDark, safeInsets.top, safeInsets.bottom, safeInsets.left, safeInsets.right]
|
|
98
151
|
);
|
|
152
|
+
// only what the engine actually uses decides about re-layout (the brightness slider, the page sound ... must not)
|
|
153
|
+
const engineJson = JSON.stringify(engineSettings);
|
|
154
|
+
const latest = useRef({ engineSettings, highlights });
|
|
155
|
+
latest.current = { engineSettings, highlights };
|
|
99
156
|
|
|
100
157
|
const send = useCallback((cmd: object) => {
|
|
101
158
|
web.current?.injectJavaScript(toScript(cmd));
|
|
102
159
|
}, []);
|
|
103
160
|
|
|
161
|
+
// the engine never started (blocked WebView, out of memory ...)
|
|
162
|
+
useEffect(() => {
|
|
163
|
+
if (engineReady) return;
|
|
164
|
+
const t = setTimeout(() => cb.current.onError?.('The reader could not be started.', { fatal: true }), ENGINE_START_TIMEOUT);
|
|
165
|
+
return () => clearTimeout(t);
|
|
166
|
+
}, [engineReady, webKey]);
|
|
167
|
+
|
|
104
168
|
// open (or re-open) the book once the engine is up
|
|
105
|
-
const sourceKey =
|
|
169
|
+
const sourceKey = sourceKeyOf(source);
|
|
106
170
|
useEffect(() => {
|
|
107
171
|
if (!engineReady) return;
|
|
108
172
|
let cancelled = false;
|
|
109
173
|
opened.current = false;
|
|
174
|
+
if (lastKey.current !== sourceKey) {
|
|
175
|
+
lastKey.current = sourceKey;
|
|
176
|
+
lastLoc.current = null;
|
|
177
|
+
}
|
|
110
178
|
(async () => {
|
|
111
179
|
try {
|
|
112
|
-
const
|
|
180
|
+
const limit = cb.current.maxFileSize ?? DEFAULT_MAX_FILE;
|
|
181
|
+
let data = 'uri' in source ? await uriToBase64(source, limit) : cleanBase64(source.base64);
|
|
113
182
|
if (cancelled) return;
|
|
183
|
+
if (!data) throw new Error('The book file is empty.');
|
|
184
|
+
// the book travels in pieces: one huge string would exist several times over (JSON, bridge, page)
|
|
185
|
+
for (let i = 0; i < data.length; i += CHUNK) {
|
|
186
|
+
web.current?.injectJavaScript(`window.__chunk(${i === 0 ? 1 : 0},"${data.slice(i, i + CHUNK)}");true;`);
|
|
187
|
+
}
|
|
188
|
+
data = '';
|
|
189
|
+
// settings, highlights and position are read now, not when loading started
|
|
114
190
|
send({
|
|
115
191
|
cmd: 'open',
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
location: cb.current.initialLocation
|
|
192
|
+
settings: latest.current.engineSettings,
|
|
193
|
+
highlights: latest.current.highlights || [],
|
|
194
|
+
location: lastLoc.current || cb.current.initialLocation
|
|
120
195
|
});
|
|
121
196
|
opened.current = true;
|
|
122
197
|
} catch (e) {
|
|
123
|
-
cb.current.onError?.(String((e as Error)?.message || e));
|
|
198
|
+
cb.current.onError?.(String((e as Error)?.message || e), { fatal: true });
|
|
124
199
|
}
|
|
125
200
|
})();
|
|
126
201
|
return () => {
|
|
@@ -130,13 +205,20 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
130
205
|
}, [engineReady, sourceKey]);
|
|
131
206
|
|
|
132
207
|
useEffect(() => {
|
|
133
|
-
if (opened.current) send({ cmd: 'settings', settings: engineSettings });
|
|
134
|
-
}, [
|
|
208
|
+
if (opened.current) send({ cmd: 'settings', settings: latest.current.engineSettings });
|
|
209
|
+
}, [engineJson, send]);
|
|
135
210
|
|
|
136
211
|
useEffect(() => {
|
|
137
212
|
if (opened.current) send({ cmd: 'highlights', list: highlights || [] });
|
|
138
213
|
}, [highlights, send]);
|
|
139
214
|
|
|
215
|
+
// Android killed the renderer / iOS terminated the web content process: start over at the last position
|
|
216
|
+
const recover = useCallback(() => {
|
|
217
|
+
opened.current = false;
|
|
218
|
+
setEngineReady(false);
|
|
219
|
+
setWebKey((k) => k + 1);
|
|
220
|
+
}, []);
|
|
221
|
+
|
|
140
222
|
useImperativeHandle(
|
|
141
223
|
ref,
|
|
142
224
|
() => ({
|
|
@@ -165,8 +247,9 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
165
247
|
} catch {
|
|
166
248
|
return;
|
|
167
249
|
}
|
|
250
|
+
if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string') return;
|
|
168
251
|
const p = cb.current;
|
|
169
|
-
const d = msg.data;
|
|
252
|
+
const d = msg.data && typeof msg.data === 'object' ? msg.data : {};
|
|
170
253
|
switch (msg.type) {
|
|
171
254
|
case 'ready':
|
|
172
255
|
setEngineReady(true);
|
|
@@ -176,12 +259,13 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
176
259
|
break;
|
|
177
260
|
case 'toc':
|
|
178
261
|
p.onReady?.({ metadata: metaRef.current, rtl: !!d.rtl });
|
|
179
|
-
p.onToc?.(d.items);
|
|
262
|
+
p.onToc?.(Array.isArray(d.items) ? d.items : []);
|
|
180
263
|
break;
|
|
181
264
|
case 'cover':
|
|
182
|
-
p.onCover?.(d.uri);
|
|
265
|
+
if (typeof d.uri === 'string') p.onCover?.(d.uri);
|
|
183
266
|
break;
|
|
184
267
|
case 'relocate':
|
|
268
|
+
lastLoc.current = { spine: d.spine, offset: d.offset };
|
|
185
269
|
p.onRelocate?.(d);
|
|
186
270
|
break;
|
|
187
271
|
case 'indexed':
|
|
@@ -205,16 +289,22 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
205
289
|
p.onPageTurn?.();
|
|
206
290
|
break;
|
|
207
291
|
case 'link':
|
|
208
|
-
p.onLink?.(d.href);
|
|
292
|
+
if (typeof d.href === 'string' && /^(https?|mailto):/i.test(d.href)) p.onLink?.(d.href);
|
|
293
|
+
break;
|
|
294
|
+
case 'linkJump':
|
|
295
|
+
p.onLinkJump?.({ spine: d.spine, offset: d.offset });
|
|
296
|
+
break;
|
|
297
|
+
case 'direction':
|
|
298
|
+
p.onDirectionChange?.(!!d.rtl);
|
|
209
299
|
break;
|
|
210
300
|
case 'searchResults':
|
|
211
|
-
p.onSearchResults?.(d.id, d.results, d.done);
|
|
301
|
+
p.onSearchResults?.(d.id, Array.isArray(d.results) ? d.results : [], !!d.done);
|
|
212
302
|
break;
|
|
213
303
|
case 'end':
|
|
214
304
|
p.onEndReached?.(d.edge);
|
|
215
305
|
break;
|
|
216
306
|
case 'error':
|
|
217
|
-
p.onError?.(d.message);
|
|
307
|
+
p.onError?.(String(d.message || 'Unknown error'), { fatal: !!d.fatal });
|
|
218
308
|
break;
|
|
219
309
|
}
|
|
220
310
|
}, []);
|
|
@@ -224,6 +314,7 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
224
314
|
return (
|
|
225
315
|
<View style={[styles.fill, { backgroundColor: bg }]}>
|
|
226
316
|
<WebView
|
|
317
|
+
key={webKey}
|
|
227
318
|
ref={web}
|
|
228
319
|
style={[styles.fill, { backgroundColor: bg }]}
|
|
229
320
|
originWhitelist={['*']}
|
|
@@ -241,13 +332,22 @@ export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function
|
|
|
241
332
|
allowsInlineMediaPlayback
|
|
242
333
|
hideKeyboardAccessoryView
|
|
243
334
|
setSupportMultipleWindows={false}
|
|
335
|
+
// the page is generated here and never needs the file system, the network or the system font scale
|
|
336
|
+
allowFileAccess={false}
|
|
337
|
+
allowFileAccessFromFileURLs={false}
|
|
338
|
+
allowUniversalAccessFromFileURLs={false}
|
|
339
|
+
mixedContentMode="never"
|
|
340
|
+
cacheEnabled={false}
|
|
341
|
+
textZoom={100}
|
|
244
342
|
menuItems={menuItems}
|
|
245
343
|
onCustomMenuSelection={(e) => {
|
|
246
344
|
const key = (e.nativeEvent as { key: string }).key;
|
|
247
345
|
cb.current.onMenuAction?.(key, selection.current);
|
|
248
346
|
}}
|
|
249
347
|
onShouldStartLoadWithRequest={(req) => req.url === 'about:blank' || req.url.startsWith('data:') || req.url.startsWith('about:')}
|
|
250
|
-
|
|
348
|
+
onRenderProcessGone={recover}
|
|
349
|
+
onContentProcessDidTerminate={recover}
|
|
350
|
+
onError={(e) => cb.current.onError?.(e.nativeEvent.description || 'The reader failed to load.', { fatal: true })}
|
|
251
351
|
/>
|
|
252
352
|
</View>
|
|
253
353
|
);
|