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 CHANGED
@@ -154,9 +154,11 @@ changes font size, theme or rotates the device.
154
154
 
155
155
  | Prop | Type | Description |
156
156
  |---|---|---|
157
- | `source` | `{ uri: string } \| { base64: string }` | **Required.** The EPUB. |
157
+ | `source` | `{ uri; headers?; key? } \| { base64; key? }` | **Required.** The EPUB: a `file://`, `content://` (Android) or `https://` uri, or base64 data. `key` identifies the book; a different source starts a fresh reader (highlights, bookmarks and position of one book never reach another). |
158
158
  | `title` | `string` | Shown in Contents until the book's own title is read. |
159
- | `safeInsets` | `{ top: number; bottom: number }` | Status-bar and home-indicator space. Use `useSafeAreaInsets()`. |
159
+ | `safeInsets` | `{ top; bottom; left?; right? }` | Status-bar, home-indicator and (landscape) notch space. Use `useSafeAreaInsets()` from `react-native-safe-area-context`. Without it a guess from the screen size is used. |
160
+ | `labels` | `Partial<ReaderLabels>` | Every text of the interface, for translation (Pashto, Dari, Arabic ...). `formatNumber` lets you show Arabic-Indic digits. See `DEFAULT_LABELS`. |
161
+ | `maxFileSize` | `number` | Largest EPUB in bytes (default 150 MB, `0` = no limit). Bigger files raise an error instead of crashing low-memory phones. |
160
162
  | `initialLocation` | `{ spine: number; offset: number }` | Where to open. Defaults to the start. |
161
163
  | `initialSettings` | `Partial<ReaderSettings>` | Theme, font, size, spacing ... |
162
164
  | `initialHighlights` | `Highlight[]` | |
@@ -168,7 +170,7 @@ changes font size, theme or rotates the device.
168
170
  | `onSettingsChange` | `(s: ReaderSettings) => void` | |
169
171
  | `onMetadata` | `(m: BookMetadata) => void` | `title`, `author`, `language`, `publisher`. |
170
172
  | `onCover` | `(dataUri: string) => void` | The cover image, if the book has one. |
171
- | `onError` | `(message: string) => void` | Unreadable file, DRM, ... |
173
+ | `onError` | `(message: string) => void` | Unreadable file, DRM, ... The reader itself shows an error screen with **Try again** and **Close**, so the user is never stuck. |
172
174
 
173
175
  ---
174
176
 
@@ -298,10 +300,12 @@ The sound can be disabled by the user in Themes & Settings, Customize.
298
300
 
299
301
  **Controls are not blurred on Android.** `expo-blur` blur is limited on Android; the controls fall back to translucent colour.
300
302
 
301
- **A book will not open.** `onError` receives the reason. DRM-protected files (Adobe, Apple FairPlay) cannot be opened.
303
+ **A book will not open.** `onError` receives the reason and the reader shows it with Try again / Close. DRM-protected files (Adobe, Apple FairPlay, Readium LCP) cannot be opened and are reported as such.
302
304
 
303
- **Opening is slow for a very large book.** The file is sent to the page engine as base64. Typical novels take well under
304
- a second; a 50 MB illustrated book will be slow.
305
+ **The reader goes blank after the app was in the background.** If the system kills the web view process (low memory), the reader restarts by itself at the last position.
306
+
307
+ **Opening is slow for a very large book.** The file is sent to the page engine as base64 in pieces. Typical novels take well under
308
+ a second; a 50 MB illustrated book will be slow, and files above `maxFileSize` are refused.
305
309
 
306
310
  ---
307
311
 
@@ -309,10 +313,12 @@ a second; a 50 MB illustrated book will be slow.
309
313
 
310
314
  - Reflowable EPUBs only. Fixed-layout EPUBs and media overlays are not supported.
311
315
  - Themes and fonts are chosen from the built-in lists (no custom theme prop yet).
312
- - Embedded fonts that are obfuscated by the publisher fall back to a system font.
316
+ - Vertical writing modes (Japanese `writing-mode: vertical-rl`) are laid out horizontally.
317
+ - Character spacing is ignored in right-to-left books: it would break the joins of Arabic-script letters.
318
+ - Audio and video elements in a book are removed.
313
319
  - Text selection and highlights work in the chapter that is on screen; in Scroll mode a neighbouring chapter becomes
314
320
  selectable once it scrolls into the middle of the screen.
315
- - Search folds case and common Arabic / Persian letter variants (for example ي and ی) but does not strip diacritics.
321
+ - Search ignores case, diacritics (tashkeel), tatweel and ZWNJ, unifies Arabic / Persian letter variants (for example ي and ی) and all digit systems.
316
322
  - The page curl is a geometric corner fold, not a physical simulation of paper.
317
323
 
318
324
  ---
@@ -326,6 +332,13 @@ The page-turn sounds (`src/assets/page-turn-*.wav`) are trimmed and softened rec
326
332
 
327
333
  EPUB parsing uses [JSZip](https://stuk.github.io/jszip/).
328
334
 
335
+ ### Security
336
+
337
+ Books are untrusted input. Chapter HTML is sanitized (scripts, event handlers, `javascript:` URLs, forms, `<base>`, remote images and
338
+ styles are removed), chapters render in frames under a Content-Security-Policy that blocks script and network, and only
339
+ `http(s)` and `mailto` links can leave the book, after a confirmation. Publisher font obfuscation (IDPF and Adobe) is decoded, so
340
+ embedded fonts work; real DRM is detected and refused.
341
+
329
342
  ### Developing
330
343
 
331
344
  ```bash
@@ -1,19 +1,25 @@
1
1
  import React from 'react';
2
- import type { BookLocation, BookMetadata, EpubSource, Highlight, ReaderSettings, RelocateEvent, SearchResult, SelectionEvent, TocItem } from './types';
2
+ import type { BookLocation, BookMetadata, EpubSource, Highlight, ReaderSettings, RelocateEvent, SafeInsets, SearchResult, SelectionEvent, TocItem } from './types';
3
+ export interface ReaderErrorInfo {
4
+ /** true when the book cannot be shown (failed to open, reader engine stopped); false for a problem on one page */
5
+ fatal: boolean;
6
+ }
3
7
  export interface EpubReaderProps {
4
8
  source: EpubSource;
5
9
  settings: ReaderSettings;
6
10
  /** system colour scheme, used when settings.appearance is 'device' */
7
11
  systemDark?: boolean;
8
- /** Space reserved for status bar / home indicator. The engine adds room for the running header and footer. */
9
- safeInsets?: {
10
- top: number;
11
- bottom: number;
12
- };
12
+ /** Space reserved for status bar / home indicator (and the notch in landscape). The engine adds room for the running header and footer. */
13
+ safeInsets?: SafeInsets;
13
14
  initialLocation?: BookLocation | {
14
15
  progress: number;
15
16
  };
16
17
  highlights?: Highlight[];
18
+ /**
19
+ * Largest EPUB (bytes) that will be loaded. The whole book is held in memory while it is opened, so very large
20
+ * files can crash low-memory phones. Default 150 MB, 0 disables the check.
21
+ */
22
+ maxFileSize?: number;
17
23
  /** Items added to the native text-selection menu. `onMenuAction` fires with the item key. */
18
24
  menuItems?: {
19
25
  label: string;
@@ -37,10 +43,15 @@ export interface EpubReaderProps {
37
43
  onTap?: () => void;
38
44
  /** a page turn animation is starting (use it to play a sound) */
39
45
  onPageTurn?: () => void;
46
+ /** a web or mail link was tapped (other schemes are never forwarded). Open it yourself, ideally after asking. */
40
47
  onLink?: (href: string) => void;
48
+ /** an internal link (footnote, cross reference) is about to jump; `from` is where the reader was, so you can offer a way back */
49
+ onLinkJump?: (from: BookLocation) => void;
50
+ /** the reading direction changed (the user overrode it in the settings) */
51
+ onDirectionChange?: (rtl: boolean) => void;
41
52
  onSearchResults?: (searchId: number, results: SearchResult[], done: boolean) => void;
42
53
  onEndReached?: (edge: 'start' | 'end') => void;
43
- onError?: (message: string) => void;
54
+ onError?: (message: string, info: ReaderErrorInfo) => void;
44
55
  }
45
56
  export interface EpubReaderHandle {
46
57
  next(): void;
@@ -60,4 +71,6 @@ export interface EpubReaderHandle {
60
71
  /** Replace the running header / footer text drawn on the page. */
61
72
  setLabels(header: string, footer: string): void;
62
73
  }
74
+ /** Identity of a source: the explicit `key`, the uri, or a fingerprint sampled across the base64 data. */
75
+ export declare function sourceKeyOf(source: EpubSource): string;
63
76
  export declare const EpubReader: React.ForwardRefExoticComponent<EpubReaderProps & React.RefAttributes<EpubReaderHandle>>;
package/lib/EpubReader.js CHANGED
@@ -34,17 +34,48 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.EpubReader = void 0;
37
+ exports.sourceKeyOf = sourceKeyOf;
37
38
  const react_1 = __importStar(require("react"));
38
39
  const react_native_1 = require("react-native");
39
40
  const react_native_webview_1 = require("react-native-webview");
40
41
  const html_1 = require("./engine/html");
41
42
  const themes_1 = require("./themes");
42
- async function uriToBase64(uri) {
43
- const res = await fetch(uri);
43
+ const DEFAULT_MAX_FILE = 150 * 1024 * 1024;
44
+ const ENGINE_START_TIMEOUT = 20000;
45
+ const CHUNK = 256 * 1024;
46
+ /** Identity of a source: the explicit `key`, the uri, or a fingerprint sampled across the base64 data. */
47
+ function sourceKeyOf(source) {
48
+ if (source.key)
49
+ return source.key;
50
+ if ('uri' in source)
51
+ return source.uri;
52
+ const b = source.base64;
53
+ let h = 5381;
54
+ const step = Math.max(1, Math.floor(b.length / 512));
55
+ for (let i = 0; i < b.length; i += step)
56
+ h = ((h << 5) + h + b.charCodeAt(i)) | 0;
57
+ return `b64:${b.length}:${h >>> 0}`;
58
+ }
59
+ async function uriToBase64(source, maxBytes) {
60
+ let res;
61
+ try {
62
+ res = await fetch(source.uri, source.headers ? { headers: source.headers } : undefined);
63
+ }
64
+ catch {
65
+ throw new Error('The book file could not be opened (it may have been moved or deleted, or there is no connection).');
66
+ }
67
+ // file:// responses report status 0 on some platforms, so only real HTTP errors count
68
+ if (res.status >= 400)
69
+ throw new Error(`The book could not be downloaded (error ${res.status}).`);
44
70
  const blob = await res.blob();
71
+ if (maxBytes > 0 && blob.size > maxBytes) {
72
+ throw new Error(`This book is too large to open (${Math.round(blob.size / 1048576)} MB).`);
73
+ }
74
+ if (blob.size === 0)
75
+ throw new Error('The book file is empty.');
45
76
  return new Promise((resolve, reject) => {
46
77
  const fr = new FileReader();
47
- fr.onerror = () => reject(fr.error);
78
+ fr.onerror = () => reject(new Error('The book file could not be read.'));
48
79
  fr.onloadend = () => {
49
80
  const s = String(fr.result);
50
81
  resolve(s.slice(s.indexOf(',') + 1));
@@ -52,6 +83,14 @@ async function uriToBase64(uri) {
52
83
  fr.readAsDataURL(blob);
53
84
  });
54
85
  }
86
+ function cleanBase64(data) {
87
+ let s = data;
88
+ if (s.startsWith('data:'))
89
+ s = s.slice(s.indexOf(',') + 1);
90
+ if (/\s/.test(s.slice(0, 4096)) || s.indexOf('\n') >= 0)
91
+ s = s.replace(/\s+/g, '');
92
+ return s;
93
+ }
55
94
  const LS = String.fromCharCode(0x2028);
56
95
  const PS = String.fromCharCode(0x2029);
57
96
  // U+2028/2029 are legal in JSON but terminate a JS string literal, so escape them.
@@ -65,38 +104,65 @@ exports.EpubReader = (0, react_1.forwardRef)(function EpubReader(props, ref) {
65
104
  const cb = (0, react_1.useRef)(props);
66
105
  cb.current = props;
67
106
  const [engineReady, setEngineReady] = (0, react_1.useState)(false);
107
+ // bumping this remounts the WebView (after the system killed its process)
108
+ const [webKey, setWebKey] = (0, react_1.useState)(0);
68
109
  const opened = (0, react_1.useRef)(false);
69
110
  const selection = (0, react_1.useRef)(null);
70
111
  const metaRef = (0, react_1.useRef)({ title: '', author: '', language: '', publisher: '' });
112
+ const lastLoc = (0, react_1.useRef)(null);
113
+ const lastKey = (0, react_1.useRef)('');
71
114
  const engineSettings = (0, react_1.useMemo)(() => (0, themes_1.toEngineSettings)(settings, systemDark, safeInsets),
72
115
  // eslint-disable-next-line react-hooks/exhaustive-deps
73
- [settings, systemDark, safeInsets.top, safeInsets.bottom]);
116
+ [settings, systemDark, safeInsets.top, safeInsets.bottom, safeInsets.left, safeInsets.right]);
117
+ // only what the engine actually uses decides about re-layout (the brightness slider, the page sound ... must not)
118
+ const engineJson = JSON.stringify(engineSettings);
119
+ const latest = (0, react_1.useRef)({ engineSettings, highlights });
120
+ latest.current = { engineSettings, highlights };
74
121
  const send = (0, react_1.useCallback)((cmd) => {
75
122
  web.current?.injectJavaScript(toScript(cmd));
76
123
  }, []);
124
+ // the engine never started (blocked WebView, out of memory ...)
125
+ (0, react_1.useEffect)(() => {
126
+ if (engineReady)
127
+ return;
128
+ const t = setTimeout(() => cb.current.onError?.('The reader could not be started.', { fatal: true }), ENGINE_START_TIMEOUT);
129
+ return () => clearTimeout(t);
130
+ }, [engineReady, webKey]);
77
131
  // open (or re-open) the book once the engine is up
78
- const sourceKey = 'uri' in source ? source.uri : source.base64.length + ':' + source.base64.slice(0, 32);
132
+ const sourceKey = sourceKeyOf(source);
79
133
  (0, react_1.useEffect)(() => {
80
134
  if (!engineReady)
81
135
  return;
82
136
  let cancelled = false;
83
137
  opened.current = false;
138
+ if (lastKey.current !== sourceKey) {
139
+ lastKey.current = sourceKey;
140
+ lastLoc.current = null;
141
+ }
84
142
  (async () => {
85
143
  try {
86
- const data = 'uri' in source ? await uriToBase64(source.uri) : source.base64;
144
+ const limit = cb.current.maxFileSize ?? DEFAULT_MAX_FILE;
145
+ let data = 'uri' in source ? await uriToBase64(source, limit) : cleanBase64(source.base64);
87
146
  if (cancelled)
88
147
  return;
148
+ if (!data)
149
+ throw new Error('The book file is empty.');
150
+ // the book travels in pieces: one huge string would exist several times over (JSON, bridge, page)
151
+ for (let i = 0; i < data.length; i += CHUNK) {
152
+ web.current?.injectJavaScript(`window.__chunk(${i === 0 ? 1 : 0},"${data.slice(i, i + CHUNK)}");true;`);
153
+ }
154
+ data = '';
155
+ // settings, highlights and position are read now, not when loading started
89
156
  send({
90
157
  cmd: 'open',
91
- data,
92
- settings: engineSettings,
93
- highlights: highlights || [],
94
- location: cb.current.initialLocation
158
+ settings: latest.current.engineSettings,
159
+ highlights: latest.current.highlights || [],
160
+ location: lastLoc.current || cb.current.initialLocation
95
161
  });
96
162
  opened.current = true;
97
163
  }
98
164
  catch (e) {
99
- cb.current.onError?.(String(e?.message || e));
165
+ cb.current.onError?.(String(e?.message || e), { fatal: true });
100
166
  }
101
167
  })();
102
168
  return () => {
@@ -106,12 +172,18 @@ exports.EpubReader = (0, react_1.forwardRef)(function EpubReader(props, ref) {
106
172
  }, [engineReady, sourceKey]);
107
173
  (0, react_1.useEffect)(() => {
108
174
  if (opened.current)
109
- send({ cmd: 'settings', settings: engineSettings });
110
- }, [engineSettings, send]);
175
+ send({ cmd: 'settings', settings: latest.current.engineSettings });
176
+ }, [engineJson, send]);
111
177
  (0, react_1.useEffect)(() => {
112
178
  if (opened.current)
113
179
  send({ cmd: 'highlights', list: highlights || [] });
114
180
  }, [highlights, send]);
181
+ // Android killed the renderer / iOS terminated the web content process: start over at the last position
182
+ const recover = (0, react_1.useCallback)(() => {
183
+ opened.current = false;
184
+ setEngineReady(false);
185
+ setWebKey((k) => k + 1);
186
+ }, []);
115
187
  (0, react_1.useImperativeHandle)(ref, () => ({
116
188
  next: () => send({ cmd: 'next' }),
117
189
  prev: () => send({ cmd: 'prev' }),
@@ -136,8 +208,10 @@ exports.EpubReader = (0, react_1.forwardRef)(function EpubReader(props, ref) {
136
208
  catch {
137
209
  return;
138
210
  }
211
+ if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string')
212
+ return;
139
213
  const p = cb.current;
140
- const d = msg.data;
214
+ const d = msg.data && typeof msg.data === 'object' ? msg.data : {};
141
215
  switch (msg.type) {
142
216
  case 'ready':
143
217
  setEngineReady(true);
@@ -147,12 +221,14 @@ exports.EpubReader = (0, react_1.forwardRef)(function EpubReader(props, ref) {
147
221
  break;
148
222
  case 'toc':
149
223
  p.onReady?.({ metadata: metaRef.current, rtl: !!d.rtl });
150
- p.onToc?.(d.items);
224
+ p.onToc?.(Array.isArray(d.items) ? d.items : []);
151
225
  break;
152
226
  case 'cover':
153
- p.onCover?.(d.uri);
227
+ if (typeof d.uri === 'string')
228
+ p.onCover?.(d.uri);
154
229
  break;
155
230
  case 'relocate':
231
+ lastLoc.current = { spine: d.spine, offset: d.offset };
156
232
  p.onRelocate?.(d);
157
233
  break;
158
234
  case 'indexed':
@@ -176,24 +252,33 @@ exports.EpubReader = (0, react_1.forwardRef)(function EpubReader(props, ref) {
176
252
  p.onPageTurn?.();
177
253
  break;
178
254
  case 'link':
179
- p.onLink?.(d.href);
255
+ if (typeof d.href === 'string' && /^(https?|mailto):/i.test(d.href))
256
+ p.onLink?.(d.href);
257
+ break;
258
+ case 'linkJump':
259
+ p.onLinkJump?.({ spine: d.spine, offset: d.offset });
260
+ break;
261
+ case 'direction':
262
+ p.onDirectionChange?.(!!d.rtl);
180
263
  break;
181
264
  case 'searchResults':
182
- p.onSearchResults?.(d.id, d.results, d.done);
265
+ p.onSearchResults?.(d.id, Array.isArray(d.results) ? d.results : [], !!d.done);
183
266
  break;
184
267
  case 'end':
185
268
  p.onEndReached?.(d.edge);
186
269
  break;
187
270
  case 'error':
188
- p.onError?.(d.message);
271
+ p.onError?.(String(d.message || 'Unknown error'), { fatal: !!d.fatal });
189
272
  break;
190
273
  }
191
274
  }, []);
192
275
  const bg = (0, themes_1.themeColors)(settings, systemDark).bg;
193
276
  return (react_1.default.createElement(react_native_1.View, { style: [styles.fill, { backgroundColor: bg }] },
194
- react_1.default.createElement(react_native_webview_1.WebView, { ref: web, style: [styles.fill, { backgroundColor: bg }], originWhitelist: ['*'], source: { html: html_1.READER_HTML }, onMessage: onMessage, javaScriptEnabled: true, domStorageEnabled: false, scrollEnabled: false, bounces: false, overScrollMode: "never", showsHorizontalScrollIndicator: false, showsVerticalScrollIndicator: false, automaticallyAdjustContentInsets: false, contentInsetAdjustmentBehavior: "never", allowsInlineMediaPlayback: true, hideKeyboardAccessoryView: true, setSupportMultipleWindows: false, menuItems: menuItems, onCustomMenuSelection: (e) => {
277
+ react_1.default.createElement(react_native_webview_1.WebView, { key: webKey, ref: web, style: [styles.fill, { backgroundColor: bg }], originWhitelist: ['*'], source: { html: html_1.READER_HTML }, onMessage: onMessage, javaScriptEnabled: true, domStorageEnabled: false, scrollEnabled: false, bounces: false, overScrollMode: "never", showsHorizontalScrollIndicator: false, showsVerticalScrollIndicator: false, automaticallyAdjustContentInsets: false, contentInsetAdjustmentBehavior: "never", allowsInlineMediaPlayback: true, hideKeyboardAccessoryView: true, setSupportMultipleWindows: false,
278
+ // the page is generated here and never needs the file system, the network or the system font scale
279
+ allowFileAccess: false, allowFileAccessFromFileURLs: false, allowUniversalAccessFromFileURLs: false, mixedContentMode: "never", cacheEnabled: false, textZoom: 100, menuItems: menuItems, onCustomMenuSelection: (e) => {
195
280
  const key = e.nativeEvent.key;
196
281
  cb.current.onMenuAction?.(key, selection.current);
197
- }, onShouldStartLoadWithRequest: (req) => req.url === 'about:blank' || req.url.startsWith('data:') || req.url.startsWith('about:'), onError: (e) => cb.current.onError?.(e.nativeEvent.description) })));
282
+ }, onShouldStartLoadWithRequest: (req) => req.url === 'about:blank' || req.url.startsWith('data:') || req.url.startsWith('about:'), onRenderProcessGone: recover, onContentProcessDidTerminate: recover, onError: (e) => cb.current.onError?.(e.nativeEvent.description || 'The reader failed to load.', { fatal: true }) })));
198
283
  });
199
284
  const styles = react_native_1.StyleSheet.create({ fill: { flex: 1 } });
@@ -1,13 +1,12 @@
1
1
  import React from 'react';
2
- import type { Bookmark, BookLocation, BookMetadata, EpubSource, Highlight, ReaderSettings, RelocateEvent } from './types';
2
+ import type { Bookmark, BookLocation, BookMetadata, EpubSource, Highlight, ReaderSettings, RelocateEvent, SafeInsets } from './types';
3
+ import type { ReaderLabels } from './strings';
3
4
  export interface EpubReaderViewProps {
4
5
  source: EpubSource;
5
6
  /** shown in the Contents sheet until the book's own title is read */
6
7
  title?: string;
7
- safeInsets?: {
8
- top: number;
9
- bottom: number;
10
- };
8
+ /** Space for the status bar / home indicator (and notch in landscape). Use useSafeAreaInsets() from react-native-safe-area-context. */
9
+ safeInsets?: SafeInsets;
11
10
  initialLocation?: BookLocation;
12
11
  initialSettings?: Partial<ReaderSettings>;
13
12
  initialHighlights?: Highlight[];
@@ -20,5 +19,13 @@ export interface EpubReaderViewProps {
20
19
  onMetadata?: (m: BookMetadata) => void;
21
20
  onCover?: (dataUri: string) => void;
22
21
  onError?: (message: string) => void;
22
+ /** Texts of the interface; leave out what you do not translate (see ReaderLabels). */
23
+ labels?: Partial<ReaderLabels>;
24
+ /** Largest EPUB in bytes that will be opened (default 150 MB, 0 = no limit). */
25
+ maxFileSize?: number;
23
26
  }
27
+ /**
28
+ * Full reader screen. A different `source` (or Try again after an error) starts a fresh screen, so highlights,
29
+ * bookmarks and position of one book can never leak into another.
30
+ */
24
31
  export declare function EpubReaderView(props: EpubReaderViewProps): React.JSX.Element;