aksos-react-native-epub-reader 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +351 -2
- package/lib/EpubReader.d.ts +76 -0
- package/lib/EpubReader.js +284 -0
- package/lib/EpubReaderView.d.ts +31 -0
- package/lib/EpubReaderView.js +599 -0
- package/lib/assets/page-turn-1.wav +0 -0
- package/lib/assets/page-turn-2.wav +0 -0
- package/lib/assets/page-turn-3.wav +0 -0
- package/lib/assets/page-turn-4.wav +0 -0
- package/lib/engine/html.d.ts +1 -0
- package/lib/engine/html.js +5 -0
- package/lib/index.d.ts +9 -0
- package/lib/index.js +34 -0
- package/lib/sound.d.ts +1 -0
- package/lib/sound.js +71 -0
- package/lib/strings.d.ts +94 -0
- package/lib/strings.js +96 -0
- package/lib/themes.d.ts +60 -0
- package/lib/themes.js +166 -0
- package/lib/types.d.ts +149 -0
- package/lib/types.js +2 -0
- package/lib/ui/AppearanceSheet.d.ts +15 -0
- package/lib/ui/AppearanceSheet.js +134 -0
- package/lib/ui/ContentsSheet.d.ts +27 -0
- package/lib/ui/ContentsSheet.js +89 -0
- package/lib/ui/CustomizeSheet.d.ts +16 -0
- package/lib/ui/CustomizeSheet.js +141 -0
- package/lib/ui/Glass.d.ts +15 -0
- package/lib/ui/Glass.js +27 -0
- package/lib/ui/HighlightMenu.d.ts +25 -0
- package/lib/ui/HighlightMenu.js +45 -0
- package/lib/ui/Icons.d.ts +17 -0
- package/lib/ui/Icons.js +193 -0
- package/lib/ui/LineGuide.d.ts +21 -0
- package/lib/ui/LineGuide.js +92 -0
- package/lib/ui/NoteEditor.d.ts +12 -0
- package/lib/ui/NoteEditor.js +63 -0
- package/lib/ui/Scrubber.d.ts +15 -0
- package/lib/ui/Scrubber.js +86 -0
- package/lib/ui/SearchSheet.d.ts +14 -0
- package/lib/ui/SearchSheet.js +79 -0
- package/lib/ui/Sheet.d.ts +19 -0
- package/lib/ui/Sheet.js +40 -0
- package/lib/ui/Slider.d.ts +14 -0
- package/lib/ui/Slider.js +53 -0
- package/package.json +76 -6
- package/src/EpubReader.tsx +356 -0
- package/src/EpubReaderView.tsx +865 -0
- package/src/assets/page-turn-1.wav +0 -0
- package/src/assets/page-turn-2.wav +0 -0
- package/src/assets/page-turn-3.wav +0 -0
- package/src/assets/page-turn-4.wav +0 -0
- package/src/engine/html.ts +2 -0
- package/src/engine/reader.js +2047 -0
- package/src/index.ts +9 -0
- package/src/sound.ts +66 -0
- package/src/strings.ts +187 -0
- package/src/themes.ts +188 -0
- package/src/types.ts +154 -0
- package/src/ui/AppearanceSheet.tsx +176 -0
- package/src/ui/ContentsSheet.tsx +146 -0
- package/src/ui/CustomizeSheet.tsx +191 -0
- package/src/ui/Glass.tsx +37 -0
- package/src/ui/HighlightMenu.tsx +66 -0
- package/src/ui/Icons.tsx +246 -0
- package/src/ui/LineGuide.tsx +87 -0
- package/src/ui/NoteEditor.tsx +57 -0
- package/src/ui/Scrubber.tsx +78 -0
- package/src/ui/SearchSheet.tsx +95 -0
- package/src/ui/Sheet.tsx +71 -0
- package/src/ui/Slider.tsx +30 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
interface Props {
|
|
3
|
+
value: number;
|
|
4
|
+
min: number;
|
|
5
|
+
max: number;
|
|
6
|
+
step: number;
|
|
7
|
+
onChange: (v: number) => void;
|
|
8
|
+
color: string;
|
|
9
|
+
track: string;
|
|
10
|
+
thumbColor?: string;
|
|
11
|
+
}
|
|
12
|
+
/** Value slider on top of Scrubber; emits only when the stepped value changes. */
|
|
13
|
+
export declare function Slider({ value, min, max, step, onChange, color, track, thumbColor }: Props): React.JSX.Element;
|
|
14
|
+
export {};
|
package/lib/ui/Slider.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.Slider = Slider;
|
|
37
|
+
const react_1 = __importStar(require("react"));
|
|
38
|
+
const Scrubber_1 = require("./Scrubber");
|
|
39
|
+
const round = (v, step) => Math.round(v / step) * step;
|
|
40
|
+
/** Value slider on top of Scrubber; emits only when the stepped value changes. */
|
|
41
|
+
function Slider({ value, min, max, step, onChange, color, track, thumbColor }) {
|
|
42
|
+
const last = (0, react_1.useRef)(value);
|
|
43
|
+
const toValue = (f) => +(round(min + f * (max - min), step)).toFixed(4);
|
|
44
|
+
const emit = (f) => {
|
|
45
|
+
const v = toValue(f);
|
|
46
|
+
if (v !== last.current) {
|
|
47
|
+
last.current = v;
|
|
48
|
+
onChange(v);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
last.current = value;
|
|
52
|
+
return react_1.default.createElement(Scrubber_1.Scrubber, { value: (value - min) / (max - min), color: color, track: track, thumbColor: thumbColor, onScrub: emit, onComplete: emit });
|
|
53
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,76 @@
|
|
|
1
|
-
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
{
|
|
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
|
+
}
|
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
|
|
2
|
+
import { StyleSheet, View } from 'react-native';
|
|
3
|
+
import { WebView } from 'react-native-webview';
|
|
4
|
+
import type { WebViewMessageEvent } from 'react-native-webview';
|
|
5
|
+
import { READER_HTML } from './engine/html';
|
|
6
|
+
import { themeColors, toEngineSettings } from './themes';
|
|
7
|
+
import type {
|
|
8
|
+
BookLocation,
|
|
9
|
+
BookMetadata,
|
|
10
|
+
EpubSource,
|
|
11
|
+
Highlight,
|
|
12
|
+
ReaderSettings,
|
|
13
|
+
RelocateEvent,
|
|
14
|
+
SafeInsets,
|
|
15
|
+
SearchResult,
|
|
16
|
+
SelectionEvent,
|
|
17
|
+
TocItem
|
|
18
|
+
} from './types';
|
|
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
|
+
|
|
25
|
+
export interface EpubReaderProps {
|
|
26
|
+
source: EpubSource;
|
|
27
|
+
settings: ReaderSettings;
|
|
28
|
+
/** system colour scheme, used when settings.appearance is 'device' */
|
|
29
|
+
systemDark?: boolean;
|
|
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;
|
|
32
|
+
initialLocation?: BookLocation | { progress: number };
|
|
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;
|
|
39
|
+
/** Items added to the native text-selection menu. `onMenuAction` fires with the item key. */
|
|
40
|
+
menuItems?: { label: string; key: string }[];
|
|
41
|
+
onMenuAction?: (key: string, selection: SelectionEvent | null) => void;
|
|
42
|
+
onReady?: (info: { metadata: BookMetadata; rtl: boolean }) => void;
|
|
43
|
+
onToc?: (items: TocItem[]) => void;
|
|
44
|
+
onCover?: (dataUri: string) => void;
|
|
45
|
+
onRelocate?: (e: RelocateEvent) => void;
|
|
46
|
+
/** fired once the whole book has been indexed: cumulative character offset of every spine item */
|
|
47
|
+
onIndexed?: (info: { totalLength: number; cum: number[] }) => void;
|
|
48
|
+
onSelection?: (e: SelectionEvent | null) => void;
|
|
49
|
+
onHighlightTap?: (id: string, rect: SelectionEvent['rect']) => void;
|
|
50
|
+
onTap?: () => void;
|
|
51
|
+
/** a page turn animation is starting (use it to play a sound) */
|
|
52
|
+
onPageTurn?: () => void;
|
|
53
|
+
/** a web or mail link was tapped (other schemes are never forwarded). Open it yourself, ideally after asking. */
|
|
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;
|
|
59
|
+
onSearchResults?: (searchId: number, results: SearchResult[], done: boolean) => void;
|
|
60
|
+
onEndReached?: (edge: 'start' | 'end') => void;
|
|
61
|
+
onError?: (message: string, info: ReaderErrorInfo) => void;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface EpubReaderHandle {
|
|
65
|
+
next(): void;
|
|
66
|
+
prev(): void;
|
|
67
|
+
goTo(location: { spine: number; offset?: number; fragment?: string } | { progress: number }): void;
|
|
68
|
+
search(query: string, searchId: number): void;
|
|
69
|
+
cancelSearch(searchId?: number): void;
|
|
70
|
+
/** Jump to a search result and flash the match. */
|
|
71
|
+
showSearchResult(r: SearchResult): void;
|
|
72
|
+
clearSelection(): void;
|
|
73
|
+
/** Replace the running header / footer text drawn on the page. */
|
|
74
|
+
setLabels(header: string, footer: string): void;
|
|
75
|
+
}
|
|
76
|
+
|
|
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}).`);
|
|
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.');
|
|
106
|
+
return new Promise<string>((resolve, reject) => {
|
|
107
|
+
const fr = new FileReader();
|
|
108
|
+
fr.onerror = () => reject(new Error('The book file could not be read.'));
|
|
109
|
+
fr.onloadend = () => {
|
|
110
|
+
const s = String(fr.result);
|
|
111
|
+
resolve(s.slice(s.indexOf(',') + 1));
|
|
112
|
+
};
|
|
113
|
+
fr.readAsDataURL(blob);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
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
|
+
|
|
124
|
+
const LS = String.fromCharCode(0x2028);
|
|
125
|
+
const PS = String.fromCharCode(0x2029);
|
|
126
|
+
|
|
127
|
+
// U+2028/2029 are legal in JSON but terminate a JS string literal, so escape them.
|
|
128
|
+
function toScript(cmd: object): string {
|
|
129
|
+
const json = JSON.stringify(JSON.stringify(cmd)).split(LS).join('\\u2028').split(PS).join('\\u2029');
|
|
130
|
+
return `window.__cmd(${json});true;`;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export const EpubReader = forwardRef<EpubReaderHandle, EpubReaderProps>(function EpubReader(props, ref) {
|
|
134
|
+
const { source, settings, systemDark = false, safeInsets = { top: 0, bottom: 0 }, highlights, menuItems } = props;
|
|
135
|
+
const web = useRef<WebView>(null);
|
|
136
|
+
const cb = useRef(props);
|
|
137
|
+
cb.current = props;
|
|
138
|
+
const [engineReady, setEngineReady] = useState(false);
|
|
139
|
+
// bumping this remounts the WebView (after the system killed its process)
|
|
140
|
+
const [webKey, setWebKey] = useState(0);
|
|
141
|
+
const opened = useRef(false);
|
|
142
|
+
const selection = useRef<SelectionEvent | null>(null);
|
|
143
|
+
const metaRef = useRef<BookMetadata>({ title: '', author: '', language: '', publisher: '' });
|
|
144
|
+
const lastLoc = useRef<BookLocation | null>(null);
|
|
145
|
+
const lastKey = useRef('');
|
|
146
|
+
|
|
147
|
+
const engineSettings = useMemo(
|
|
148
|
+
() => toEngineSettings(settings, systemDark, safeInsets),
|
|
149
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
150
|
+
[settings, systemDark, safeInsets.top, safeInsets.bottom, safeInsets.left, safeInsets.right]
|
|
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 };
|
|
156
|
+
|
|
157
|
+
const send = useCallback((cmd: object) => {
|
|
158
|
+
web.current?.injectJavaScript(toScript(cmd));
|
|
159
|
+
}, []);
|
|
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
|
+
|
|
168
|
+
// open (or re-open) the book once the engine is up
|
|
169
|
+
const sourceKey = sourceKeyOf(source);
|
|
170
|
+
useEffect(() => {
|
|
171
|
+
if (!engineReady) return;
|
|
172
|
+
let cancelled = false;
|
|
173
|
+
opened.current = false;
|
|
174
|
+
if (lastKey.current !== sourceKey) {
|
|
175
|
+
lastKey.current = sourceKey;
|
|
176
|
+
lastLoc.current = null;
|
|
177
|
+
}
|
|
178
|
+
(async () => {
|
|
179
|
+
try {
|
|
180
|
+
const limit = cb.current.maxFileSize ?? DEFAULT_MAX_FILE;
|
|
181
|
+
let data = 'uri' in source ? await uriToBase64(source, limit) : cleanBase64(source.base64);
|
|
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
|
|
190
|
+
send({
|
|
191
|
+
cmd: 'open',
|
|
192
|
+
settings: latest.current.engineSettings,
|
|
193
|
+
highlights: latest.current.highlights || [],
|
|
194
|
+
location: lastLoc.current || cb.current.initialLocation
|
|
195
|
+
});
|
|
196
|
+
opened.current = true;
|
|
197
|
+
} catch (e) {
|
|
198
|
+
cb.current.onError?.(String((e as Error)?.message || e), { fatal: true });
|
|
199
|
+
}
|
|
200
|
+
})();
|
|
201
|
+
return () => {
|
|
202
|
+
cancelled = true;
|
|
203
|
+
};
|
|
204
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
205
|
+
}, [engineReady, sourceKey]);
|
|
206
|
+
|
|
207
|
+
useEffect(() => {
|
|
208
|
+
if (opened.current) send({ cmd: 'settings', settings: latest.current.engineSettings });
|
|
209
|
+
}, [engineJson, send]);
|
|
210
|
+
|
|
211
|
+
useEffect(() => {
|
|
212
|
+
if (opened.current) send({ cmd: 'highlights', list: highlights || [] });
|
|
213
|
+
}, [highlights, send]);
|
|
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
|
+
|
|
222
|
+
useImperativeHandle(
|
|
223
|
+
ref,
|
|
224
|
+
() => ({
|
|
225
|
+
next: () => send({ cmd: 'next' }),
|
|
226
|
+
prev: () => send({ cmd: 'prev' }),
|
|
227
|
+
goTo: (location) => send({ cmd: 'goto', location }),
|
|
228
|
+
search: (query, searchId) => send({ cmd: 'search', query, id: searchId }),
|
|
229
|
+
cancelSearch: (searchId) => send({ cmd: 'cancelSearch', id: searchId }),
|
|
230
|
+
showSearchResult: (r) => {
|
|
231
|
+
send({ cmd: 'goto', location: { spine: r.spine, offset: r.offset } });
|
|
232
|
+
send({ cmd: 'showHit', offset: r.offset, length: r.length });
|
|
233
|
+
},
|
|
234
|
+
clearSelection: () => {
|
|
235
|
+
selection.current = null;
|
|
236
|
+
send({ cmd: 'clearSelection' });
|
|
237
|
+
},
|
|
238
|
+
setLabels: (header, footer) => send({ cmd: 'labels', header, footer })
|
|
239
|
+
}),
|
|
240
|
+
[send]
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
const onMessage = useCallback((e: WebViewMessageEvent) => {
|
|
244
|
+
let msg: { type: string; data: any };
|
|
245
|
+
try {
|
|
246
|
+
msg = JSON.parse(e.nativeEvent.data);
|
|
247
|
+
} catch {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string') return;
|
|
251
|
+
const p = cb.current;
|
|
252
|
+
const d = msg.data && typeof msg.data === 'object' ? msg.data : {};
|
|
253
|
+
switch (msg.type) {
|
|
254
|
+
case 'ready':
|
|
255
|
+
setEngineReady(true);
|
|
256
|
+
break;
|
|
257
|
+
case 'metadata':
|
|
258
|
+
metaRef.current = d;
|
|
259
|
+
break;
|
|
260
|
+
case 'toc':
|
|
261
|
+
p.onReady?.({ metadata: metaRef.current, rtl: !!d.rtl });
|
|
262
|
+
p.onToc?.(Array.isArray(d.items) ? d.items : []);
|
|
263
|
+
break;
|
|
264
|
+
case 'cover':
|
|
265
|
+
if (typeof d.uri === 'string') p.onCover?.(d.uri);
|
|
266
|
+
break;
|
|
267
|
+
case 'relocate':
|
|
268
|
+
lastLoc.current = { spine: d.spine, offset: d.offset };
|
|
269
|
+
p.onRelocate?.(d);
|
|
270
|
+
break;
|
|
271
|
+
case 'indexed':
|
|
272
|
+
p.onIndexed?.(d);
|
|
273
|
+
break;
|
|
274
|
+
case 'selection':
|
|
275
|
+
selection.current = d;
|
|
276
|
+
p.onSelection?.(d);
|
|
277
|
+
break;
|
|
278
|
+
case 'selectionClear':
|
|
279
|
+
selection.current = null;
|
|
280
|
+
p.onSelection?.(null);
|
|
281
|
+
break;
|
|
282
|
+
case 'highlightTap':
|
|
283
|
+
p.onHighlightTap?.(d.id, d.rect);
|
|
284
|
+
break;
|
|
285
|
+
case 'tap':
|
|
286
|
+
p.onTap?.();
|
|
287
|
+
break;
|
|
288
|
+
case 'pageTurn':
|
|
289
|
+
p.onPageTurn?.();
|
|
290
|
+
break;
|
|
291
|
+
case 'link':
|
|
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);
|
|
299
|
+
break;
|
|
300
|
+
case 'searchResults':
|
|
301
|
+
p.onSearchResults?.(d.id, Array.isArray(d.results) ? d.results : [], !!d.done);
|
|
302
|
+
break;
|
|
303
|
+
case 'end':
|
|
304
|
+
p.onEndReached?.(d.edge);
|
|
305
|
+
break;
|
|
306
|
+
case 'error':
|
|
307
|
+
p.onError?.(String(d.message || 'Unknown error'), { fatal: !!d.fatal });
|
|
308
|
+
break;
|
|
309
|
+
}
|
|
310
|
+
}, []);
|
|
311
|
+
|
|
312
|
+
const bg = themeColors(settings, systemDark).bg;
|
|
313
|
+
|
|
314
|
+
return (
|
|
315
|
+
<View style={[styles.fill, { backgroundColor: bg }]}>
|
|
316
|
+
<WebView
|
|
317
|
+
key={webKey}
|
|
318
|
+
ref={web}
|
|
319
|
+
style={[styles.fill, { backgroundColor: bg }]}
|
|
320
|
+
originWhitelist={['*']}
|
|
321
|
+
source={{ html: READER_HTML }}
|
|
322
|
+
onMessage={onMessage}
|
|
323
|
+
javaScriptEnabled
|
|
324
|
+
domStorageEnabled={false}
|
|
325
|
+
scrollEnabled={false}
|
|
326
|
+
bounces={false}
|
|
327
|
+
overScrollMode="never"
|
|
328
|
+
showsHorizontalScrollIndicator={false}
|
|
329
|
+
showsVerticalScrollIndicator={false}
|
|
330
|
+
automaticallyAdjustContentInsets={false}
|
|
331
|
+
contentInsetAdjustmentBehavior="never"
|
|
332
|
+
allowsInlineMediaPlayback
|
|
333
|
+
hideKeyboardAccessoryView
|
|
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}
|
|
342
|
+
menuItems={menuItems}
|
|
343
|
+
onCustomMenuSelection={(e) => {
|
|
344
|
+
const key = (e.nativeEvent as { key: string }).key;
|
|
345
|
+
cb.current.onMenuAction?.(key, selection.current);
|
|
346
|
+
}}
|
|
347
|
+
onShouldStartLoadWithRequest={(req) => req.url === 'about:blank' || req.url.startsWith('data:') || req.url.startsWith('about:')}
|
|
348
|
+
onRenderProcessGone={recover}
|
|
349
|
+
onContentProcessDidTerminate={recover}
|
|
350
|
+
onError={(e) => cb.current.onError?.(e.nativeEvent.description || 'The reader failed to load.', { fatal: true })}
|
|
351
|
+
/>
|
|
352
|
+
</View>
|
|
353
|
+
);
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
const styles = StyleSheet.create({ fill: { flex: 1 } });
|