aksos-react-native-epub-reader 0.1.1 → 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.
Files changed (44) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +158 -13
  3. package/lib/EpubReader.d.ts +47 -9
  4. package/lib/EpubReader.js +69 -16
  5. package/lib/EpubReaderView.d.ts +27 -2
  6. package/lib/EpubReaderView.js +38 -32
  7. package/lib/cfiOrder.d.ts +2 -0
  8. package/lib/cfiOrder.js +34 -0
  9. package/lib/engine/html.js +1 -1
  10. package/lib/index.d.ts +1 -1
  11. package/lib/themes.d.ts +24 -6
  12. package/lib/themes.js +80 -20
  13. package/lib/types.d.ts +66 -1
  14. package/lib/ui/AppearanceSheet.d.ts +4 -2
  15. package/lib/ui/AppearanceSheet.js +20 -13
  16. package/lib/ui/ContentsSheet.d.ts +2 -0
  17. package/lib/ui/ContentsSheet.js +21 -13
  18. package/lib/ui/CustomizeSheet.d.ts +4 -2
  19. package/lib/ui/CustomizeSheet.js +20 -18
  20. package/lib/ui/HighlightMenu.d.ts +4 -2
  21. package/lib/ui/HighlightMenu.js +3 -3
  22. package/lib/ui/NoteEditor.js +6 -5
  23. package/lib/ui/SearchSheet.js +6 -5
  24. package/lib/ui/Sheet.js +5 -4
  25. package/lib/ui/Text.d.ts +9 -0
  26. package/lib/ui/Text.js +62 -0
  27. package/package.json +81 -76
  28. package/src/EpubReader.tsx +121 -25
  29. package/src/EpubReaderView.tsx +61 -17
  30. package/src/cfiOrder.ts +28 -0
  31. package/src/engine/epubcfi.js +527 -0
  32. package/src/engine/html.ts +1 -1
  33. package/src/engine/reader.js +830 -65
  34. package/src/index.ts +1 -1
  35. package/src/themes.ts +97 -21
  36. package/src/types.ts +71 -1
  37. package/src/ui/AppearanceSheet.tsx +19 -10
  38. package/src/ui/ContentsSheet.tsx +14 -4
  39. package/src/ui/CustomizeSheet.tsx +14 -10
  40. package/src/ui/HighlightMenu.tsx +6 -4
  41. package/src/ui/NoteEditor.tsx +2 -1
  42. package/src/ui/SearchSheet.tsx +2 -1
  43. package/src/ui/Sheet.tsx +4 -3
  44. package/src/ui/Text.tsx +27 -0
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@ export type { EpubReaderViewProps } from './EpubReaderView';
3
3
  export { EpubReader } from './EpubReader';
4
4
  export type { EpubReaderProps, EpubReaderHandle, ReaderErrorInfo } from './EpubReader';
5
5
  export { THEMES, FONTS, HIGHLIGHT_COLORS, DEFAULT_SETTINGS, getTheme, getFont, chromeColors, themeColors, isDark } from './themes';
6
- export type { ChromeColors } from './themes';
6
+ export type { ChromeColors, ChromeOverrides } from './themes';
7
7
  export { DEFAULT_LABELS } from './strings';
8
8
  export type { ReaderLabels } from './strings';
9
9
  export * from './types';
package/src/themes.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Platform } from 'react-native';
2
- import type { HighlightColor, ReaderFont, ReaderSettings, ReaderTheme, ThemeColors } from './types';
2
+ import type { CustomFont, HighlightColor, ReaderFont, ReaderSettings, ReaderTheme, ThemeColors } from './types';
3
3
 
4
4
  export const THEMES: ReaderTheme[] = [
5
5
  {
@@ -85,32 +85,55 @@ export const DEFAULT_SETTINGS: ReaderSettings = {
85
85
  direction: 'auto'
86
86
  };
87
87
 
88
- export const getTheme = (id: string): ReaderTheme => THEMES.find((t) => t.id === id) || THEMES[0];
89
- export const getFont = (id: string): ReaderFont => FONTS.find((f) => f.id === id) || FONTS[0];
88
+ /** `themes`: the host's own list (see the `themes` prop), or the built-in one. Unknown ids get the first theme. */
89
+ export const getTheme = (id: string, themes: ReaderTheme[] = THEMES): ReaderTheme =>
90
+ themes.find((t) => t.id === id) || themes[0] || THEMES[0];
91
+ /** The built-in fonts plus the app's own (the CustomFont entries that have an id). */
92
+ export function fontChoices(custom?: CustomFont[]): ReaderFont[] {
93
+ // one entry per id: a family shipped as several files (regular, bold ...) shares one id
94
+ const seen = new Set<string>();
95
+ const extra = (custom || [])
96
+ .filter((f) => f.id && !seen.has(f.id) && !!seen.add(f.id))
97
+ .map((f) => ({ id: f.id as string, name: f.name || f.family, css: `"${f.family}"` }));
98
+ return extra.length ? FONTS.concat(extra) : FONTS;
99
+ }
100
+ export const getFont = (id: string, custom?: CustomFont[]): ReaderFont => {
101
+ const list = fontChoices(custom);
102
+ return list.find((f) => f.id === id) || list[0];
103
+ };
90
104
  export const serifFont = SERIF;
91
105
 
92
106
  export function isDark(settings: ReaderSettings, systemDark: boolean): boolean {
93
107
  return settings.appearance === 'device' ? systemDark : settings.appearance === 'dark';
94
108
  }
95
109
 
96
- export function themeColors(settings: ReaderSettings, systemDark: boolean): ThemeColors {
97
- const t = getTheme(settings.themeId);
110
+ export function themeColors(settings: ReaderSettings, systemDark: boolean, themes?: ReaderTheme[]): ThemeColors {
111
+ const t = getTheme(settings.themeId, themes);
98
112
  return isDark(settings, systemDark) ? t.dark : t.light;
99
113
  }
100
114
 
101
115
  const BASE_MARGIN = 28;
102
116
 
103
117
  /** Settings object understood by the WebView engine. */
104
- export function toEngineSettings(settings: ReaderSettings, systemDark: boolean, insets: { top: number; bottom: number; left?: number; right?: number }) {
105
- const theme = getTheme(settings.themeId);
106
- const c = themeColors(settings, systemDark);
118
+ export function toEngineSettings(
119
+ settings: ReaderSettings,
120
+ systemDark: boolean,
121
+ insets: { top: number; bottom: number; left?: number; right?: number },
122
+ fonts?: CustomFont[],
123
+ themes?: ReaderTheme[],
124
+ /** false: no running header / footer, and no space kept for them */
125
+ runningLabels = true
126
+ ) {
127
+ const theme = getTheme(settings.themeId, themes);
128
+ const labelSpace = runningLabels ? 40 : 0;
129
+ const c = themeColors(settings, systemDark, themes);
107
130
  const custom = settings.customize;
108
131
  return {
109
132
  bg: c.bg,
110
133
  fg: c.fg,
111
134
  link: c.link,
112
135
  bold: !!theme.bold || settings.bold,
113
- fontFamily: getFont(settings.fontId).css,
136
+ fontFamily: getFont(settings.fontId, fonts).css,
114
137
  fontSize: settings.fontSize,
115
138
  lineHeight: custom ? settings.lineHeight : 1.5,
116
139
  letterSpacing: custom ? (settings.letterSpacing / 100) * 0.25 : 0,
@@ -120,7 +143,9 @@ export function toEngineSettings(settings: ReaderSettings, systemDark: boolean,
120
143
  justify: settings.justify,
121
144
  mode: settings.pageTurn,
122
145
  direction: settings.direction,
123
- insets: { top: insets.top + 40, bottom: insets.bottom + 40, left: insets.left || 0, right: insets.right || 0 }
146
+ insets: { top: insets.top + labelSpace, bottom: insets.bottom + labelSpace, left: insets.left || 0, right: insets.right || 0 },
147
+ showHeader: runningLabels,
148
+ showFooter: runningLabels
124
149
  };
125
150
  }
126
151
 
@@ -138,19 +163,44 @@ export interface ChromeColors {
138
163
  separator: string;
139
164
  /** highlight for the current chapter / selected items */
140
165
  accent: string;
166
+ /** solid buttons and fills (Done, the progress pill, switches). Default: black / white per control */
167
+ strong?: string;
168
+ /** text and icons on `strong` */
169
+ onStrong?: string;
141
170
  dark: boolean;
142
171
  }
143
172
 
173
+ const NAMED: Record<string, string> = { white: '#ffffff', black: '#000000' };
174
+
175
+ /** [r, g, b] of '#rgb', '#rgba', '#rrggbb', '#rrggbbaa', 'rgb(...)', 'rgba(...)', 'white' or 'black'. null for anything else. */
176
+ function rgbOf(color: string): number[] | null {
177
+ const c = (NAMED[color.trim().toLowerCase()] || color).trim();
178
+ let m = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(c);
179
+ if (m) {
180
+ const h = m[1].length <= 4 ? m[1].replace(/./g, '$&$&') : m[1];
181
+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
182
+ }
183
+ m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(c);
184
+ if (m) return [m[1], m[2], m[3]].map((v) => Math.min(255, Math.round(+v)));
185
+ return null;
186
+ }
187
+
188
+ // a theme colour the chrome cannot read falls back to plain white / black
189
+ function hexOf(color: string, dark: boolean): string {
190
+ const v = rgbOf(color) || (dark ? [0, 0, 0] : [255, 255, 255]);
191
+ return '#' + v.map((n) => n.toString(16).padStart(2, '0')).join('');
192
+ }
193
+
194
+ // both colours are '#rrggbb' here (see hexOf)
144
195
  function mix(hex: string, other: string, amount: number): string {
145
- const p = (h: string) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
146
- const a = p(hex);
147
- const b = p(other);
196
+ const a = rgbOf(hex)!;
197
+ const b = rgbOf(other)!;
148
198
  const m = a.map((v, i) => Math.round(v + (b[i] - v) * amount));
149
199
  return '#' + m.map((v) => v.toString(16).padStart(2, '0')).join('');
150
200
  }
151
201
 
152
202
  function rgba(hex: string, alpha: number): string {
153
- const v = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16));
203
+ const v = rgbOf(hex)!;
154
204
  return `rgba(${v[0]},${v[1]},${v[2]},${alpha})`;
155
205
  }
156
206
 
@@ -158,13 +208,39 @@ function rgba(hex: string, alpha: number): string {
158
208
  * Chrome (buttons, menus, sheets) is frosted glass tinted with the page colour, so a Calm page gets warm glass and a
159
209
  * black page gets dark glass. Text and icons use the neutral text colour of the light / dark variant.
160
210
  */
161
- export function chromeColors(colors: ThemeColors, dark: boolean): ChromeColors {
211
+ export function chromeColors(colors: ThemeColors, dark: boolean, chrome?: ChromeOverrides): ChromeColors {
212
+ const own = chrome && (dark ? chrome.dark : chrome.light);
213
+ const base = defaultChrome(colors, dark);
214
+ if (!own) return base;
215
+ // a key set to undefined keeps the default
216
+ const set = Object.fromEntries(Object.entries(own).filter(([, v]) => v !== undefined)) as Partial<ChromeColors>;
217
+ const out = { ...base, ...set, dark };
218
+ // a host `strong` without `onStrong`: black or white, whichever reads on it
219
+ if (set.strong && !set.onStrong) out.onStrong = textOn(set.strong);
220
+ return out;
221
+ }
222
+
223
+ /** '#000000' on a light colour, '#ffffff' on a dark one (or one that cannot be read). */
224
+ export function textOn(color: string): string {
225
+ const v = rgbOf(color);
226
+ if (!v) return '#ffffff';
227
+ return (0.299 * v[0] + 0.587 * v[1] + 0.114 * v[2]) / 255 > 0.6 ? '#000000' : '#ffffff';
228
+ }
229
+
230
+ /** The host's chrome colours for light and dark pages (see the `chrome` prop). Missing ones keep the default. */
231
+ export interface ChromeOverrides {
232
+ light?: Partial<Omit<ChromeColors, 'dark'>>;
233
+ dark?: Partial<Omit<ChromeColors, 'dark'>>;
234
+ }
235
+
236
+ function defaultChrome(colors: ThemeColors, dark: boolean): ChromeColors {
237
+ const bg = hexOf(colors.bg, dark);
162
238
  if (dark) {
163
239
  return {
164
- glass: rgba(mix(colors.bg, '#ffffff', 0.22), 0.4),
240
+ glass: rgba(mix(bg, '#ffffff', 0.22), 0.4),
165
241
  glassBorder: 'rgba(255,255,255,0.16)',
166
- sheet: mix(colors.bg, '#ffffff', 0.1),
167
- sheetGlass: rgba(mix(colors.bg, '#ffffff', 0.1), 0.84),
242
+ sheet: mix(bg, '#ffffff', 0.1),
243
+ sheetGlass: rgba(mix(bg, '#ffffff', 0.1), 0.84),
168
244
  card: 'rgba(255,255,255,0.1)',
169
245
  text: '#ffffff',
170
246
  subtext: '#a09d96',
@@ -174,10 +250,10 @@ export function chromeColors(colors: ThemeColors, dark: boolean): ChromeColors {
174
250
  };
175
251
  }
176
252
  return {
177
- glass: rgba(mix(colors.bg, '#ffffff', 0.55), 0.5),
253
+ glass: rgba(mix(bg, '#ffffff', 0.55), 0.5),
178
254
  glassBorder: 'rgba(0,0,0,0.1)',
179
- sheet: mix(colors.bg, '#ffffff', 0.5),
180
- sheetGlass: rgba(mix(colors.bg, '#ffffff', 0.5), 0.86),
255
+ sheet: mix(bg, '#ffffff', 0.5),
256
+ sheetGlass: rgba(mix(bg, '#ffffff', 0.5), 0.86),
181
257
  card: 'rgba(0,0,0,0.06)',
182
258
  text: '#000000',
183
259
  subtext: '#6c6c70',
package/src/types.ts CHANGED
@@ -13,17 +13,30 @@ export interface Highlight {
13
13
  start: number;
14
14
  end: number;
15
15
  text: string;
16
- color: HighlightColor;
16
+ /** a built-in colour name, or a key of the `highlightColors` prop, or a CSS colour such as '#ffff00' */
17
+ color: HighlightColor | (string & {});
18
+ /** epub.js range CFI. When set, it decides where the highlight is (spine/start/end are ignored). */
19
+ cfi?: string;
17
20
  style?: HighlightStyle;
18
21
  note?: string;
19
22
  chapter?: string;
20
23
  createdAt: number;
21
24
  }
22
25
 
26
+ /** A highlight known only by its epub.js CFI (for example one saved by an epub.js reader). The engine finds the text. */
27
+ export interface CfiHighlight {
28
+ id: string;
29
+ cfi: string;
30
+ color: Highlight['color'];
31
+ style?: HighlightStyle;
32
+ }
33
+
23
34
  export interface Bookmark {
24
35
  id: string;
25
36
  spine: number;
26
37
  offset: number;
38
+ /** epub.js point CFI of the same spot */
39
+ cfi?: string;
27
40
  chapter: string;
28
41
  excerpt: string;
29
42
  progress: number;
@@ -32,9 +45,12 @@ export interface Bookmark {
32
45
 
33
46
  export interface TocItem {
34
47
  label: string;
48
+ /** -1 when the entry's file is not in the book (only in the `all` list of onToc) */
35
49
  spine: number;
36
50
  fragment: string;
37
51
  level: number;
52
+ /** path relative to the package (.opf) file, with '#fragment' when there is one, e.g. 'text/ch1.xhtml#s2' */
53
+ href: string;
38
54
  }
39
55
 
40
56
  export interface BookMetadata {
@@ -60,6 +76,28 @@ export interface RelocateEvent {
60
76
  chapter: string;
61
77
  excerpt: string;
62
78
  indexed: boolean;
79
+ /** href of the spine item, relative to the package (.opf) file (epub.js location.start.href) */
80
+ href: string;
81
+ /** index in the TOC list (onToc) of the entry this page belongs to, -1 before the first entry */
82
+ tocIndex: number;
83
+ /** epub.js point CFI of the first character on the page */
84
+ startCfi?: string;
85
+ /** epub.js point CFI just after the last character on the page */
86
+ endCfi?: string;
87
+ /** epub.js locations ("chunks") of this page, once they are counted (see onLocations) */
88
+ locations?: LocationsInfo;
89
+ }
90
+
91
+ /** The page's place in the epub.js locations of the book. Same numbers as epub.js gives for the same CFIs. */
92
+ export interface LocationsInfo {
93
+ /** location index of startCfi (epub.js locationFromCfi) */
94
+ start: number;
95
+ /** location index of endCfi */
96
+ end: number;
97
+ /** number of locations in the book (epub.js locations.total + 1) */
98
+ count: number;
99
+ /** 0..1, epub.js percentageFromCfi(startCfi) */
100
+ progress: number;
63
101
  }
64
102
 
65
103
  export interface SelectionEvent {
@@ -68,6 +106,8 @@ export interface SelectionEvent {
68
106
  end: number;
69
107
  text: string;
70
108
  rect: { x: number; y: number; width: number; height: number };
109
+ /** epub.js range CFI of the selection */
110
+ cfi?: string;
71
111
  }
72
112
 
73
113
  export interface SearchResult {
@@ -152,3 +192,33 @@ export interface SafeInsets {
152
192
  left?: number;
153
193
  right?: number;
154
194
  }
195
+
196
+ /** A font shipped by the app and loaded into every chapter with @font-face. Use `family` in a ReaderFont's css. */
197
+ export interface CustomFont {
198
+ /** set it to make the font a choice for settings.fontId (and in the font list of EpubReaderView) */
199
+ id?: string;
200
+ /** name in the font list (default: family) */
201
+ name?: string;
202
+ family: string;
203
+ /** the font file as base64 (a data: prefix is accepted) */
204
+ base64: string;
205
+ /** e.g. 'font/ttf', 'font/otf', 'font/woff2' */
206
+ mime: string;
207
+ weight?: 'normal' | 'bold' | number;
208
+ style?: 'normal' | 'italic';
209
+ }
210
+
211
+ /**
212
+ * Fonts for the reader's own interface (buttons, sheets, menus), e.g. the app's brand font. Not the book text.
213
+ * Text that asks for weight 500 uses `medium`, 600 and up uses `bold`, when given.
214
+ * Give `bold`: without it, iOS draws bold text (titles, search matches) in the regular font, not bold.
215
+ * Text fields (search, notes) use `regular`.
216
+ */
217
+ export interface UiFonts {
218
+ regular: string;
219
+ medium?: string;
220
+ bold?: string;
221
+ }
222
+
223
+ /** 'theme': every text in the theme colour. 'keep': the book's own colours stay, made readable on the theme. */
224
+ export type BookColors = 'theme' | 'keep';
@@ -1,8 +1,9 @@
1
1
  import React, { useEffect, useState } from 'react';
2
- import { Pressable, StyleSheet, Text, View } from 'react-native';
3
- import { isDark, serifFont, THEMES } from '../themes';
2
+ import { Pressable, StyleSheet, View } from 'react-native';
3
+ import { Text } from './Text';
4
+ import { getTheme, isDark, serifFont, THEMES } from '../themes';
4
5
  import type { ChromeColors } from '../themes';
5
- import type { Appearance, PageTurn, ReaderSettings } from '../types';
6
+ import type { Appearance, PageTurn, ReaderSettings, ReaderTheme } from '../types';
6
7
  import { useLabels } from '../strings';
7
8
  import type { ReaderLabels } from '../strings';
8
9
  import { Icon } from './Icons';
@@ -15,12 +16,15 @@ interface Props {
15
16
  colors: ChromeColors;
16
17
  settings: ReaderSettings;
17
18
  systemDark: boolean;
19
+ /** the host's themes (default: the built-in ones) */
20
+ themes?: ReaderTheme[];
18
21
  onChange: (patch: Partial<ReaderSettings>) => void;
19
22
  onCustomize: () => void;
20
23
  onClose: () => void;
21
24
  }
22
25
 
23
26
  const SIZE = { min: 12, max: 40, step: 2 };
27
+ const GRID_GAP = 10;
24
28
 
25
29
  const TURNS: { id: PageTurn; label: keyof ReaderLabels; icon: IconName }[] = [
26
30
  { id: 'slide', label: 'slide', icon: 'pageSlide' },
@@ -40,9 +44,12 @@ const APPEARANCES: { id: Appearance; label: keyof ReaderLabels; icon: IconName;
40
44
  const appearanceIcon = (a: Appearance): IconName => (a === 'light' ? 'sun' : a === 'dark' ? 'moon' : 'contrast');
41
45
 
42
46
  /** "Themes & Settings" sheet. */
43
- export function AppearanceSheet({ visible, colors, settings: s, systemDark, onChange, onCustomize, onClose }: Props) {
47
+ export function AppearanceSheet({ visible, colors, settings: s, systemDark, themes, onChange, onCustomize, onClose }: Props) {
44
48
  const L = useLabels();
45
49
  const [menu, setMenu] = useState<null | 'turn' | 'appearance'>(null);
50
+ // Three tiles a row. Measured, because a percentage width does not count the gaps and wrapped to two.
51
+ const [gridW, setGridW] = useState(0);
52
+ const tileW = gridW ? Math.floor((gridW - GRID_GAP * 2) / 3) : '30%';
46
53
  // a popup left open must not reappear the next time the sheet is shown
47
54
  useEffect(() => {
48
55
  if (!visible) setMenu(null);
@@ -128,15 +135,16 @@ export function AppearanceSheet({ visible, colors, settings: s, systemDark, onCh
128
135
  <Icon name="sun" color={colors.subtext} size={26} />
129
136
  </View>
130
137
 
131
- <View style={styles.grid}>
132
- {THEMES.map((t) => {
138
+ <View style={styles.grid} onLayout={(e) => setGridW(e.nativeEvent.layout.width)}>
139
+ {(themes || THEMES).map((t) => {
133
140
  const c = dark ? t.dark : t.light;
134
- const on = t.id === s.themeId;
141
+ // an id the list does not have shows as its first theme, like the page does
142
+ const on = t.id === getTheme(s.themeId, themes).id;
135
143
  return (
136
144
  <Pressable
137
145
  key={t.id}
138
146
  onPress={() => onChange({ themeId: t.id })}
139
- style={[styles.tile, { backgroundColor: c.bg, borderColor: on ? colors.text : colors.separator, borderWidth: on ? 3 : StyleSheet.hairlineWidth }]}
147
+ style={[styles.tile, { width: tileW, backgroundColor: c.bg, borderColor: on ? colors.text : colors.separator, borderWidth: on ? 3 : StyleSheet.hairlineWidth }]}
140
148
  accessibilityRole="radio"
141
149
  accessibilityState={{ selected: on }}
142
150
  >
@@ -163,8 +171,9 @@ const styles = StyleSheet.create({
163
171
  half: { flex: 1, height: '100%', alignItems: 'center', justifyContent: 'center' },
164
172
  divider: { width: StyleSheet.hairlineWidth, height: 24 },
165
173
  brightness: { flexDirection: 'row', alignItems: 'center', marginTop: 14, marginBottom: 8, paddingHorizontal: 4 },
166
- grid: { flexDirection: 'row', flexWrap: 'wrap', gap: 10, marginTop: 6 },
167
- tile: { width: '31.6%', height: 92, borderRadius: 22, alignItems: 'center', justifyContent: 'center' },
174
+ // centred, so a last row that is not full sits in the middle
175
+ grid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', gap: GRID_GAP, marginTop: 6 },
176
+ tile: { height: 92, borderRadius: 22, alignItems: 'center', justifyContent: 'center' },
168
177
  customize: { marginTop: 12, height: 58, borderRadius: 29, flexDirection: 'row', alignItems: 'center', justifyContent: 'center' },
169
178
  menu: {
170
179
  position: 'absolute', top: 80, right: 16, width: 250, borderRadius: 24, paddingVertical: 8, borderWidth: StyleSheet.hairlineWidth,
@@ -1,10 +1,18 @@
1
1
  import React, { useState } from 'react';
2
- import { Alert, FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
2
+ import { Alert, FlatList, Pressable, StyleSheet, View } from 'react-native';
3
+ import { Text } from './Text';
3
4
  import { HIGHLIGHT_COLORS } from '../themes';
4
5
  import type { ChromeColors } from '../themes';
5
- import type { Bookmark, Highlight, TocItem } from '../types';
6
+ import type { Bookmark, Highlight, HighlightColor, TocItem } from '../types';
6
7
  import { useLabels } from '../strings';
7
8
  import { Sheet } from './Sheet';
9
+ import { compareCfi } from '../cfiOrder';
10
+
11
+ // book order: by CFI when both have one (their offsets may be placeholders), else by offsets
12
+ function byPosition(a: Highlight, b: Highlight): number {
13
+ if (a.cfi && b.cfi) return compareCfi(a.cfi, b.cfi) || a.createdAt - b.createdAt;
14
+ return a.spine - b.spine || a.start - b.start;
15
+ }
8
16
 
9
17
  export type ContentsTab = 'contents' | 'bookmarks' | 'notes';
10
18
 
@@ -20,6 +28,8 @@ interface Props {
20
28
  pageOf: (spine: number, offset: number) => number;
21
29
  bookmarks: Bookmark[];
22
30
  highlights: Highlight[];
31
+ /** host highlight colours (name -> CSS colour) */
32
+ palette?: Record<string, string>;
23
33
  initialTab?: ContentsTab;
24
34
  onClose: () => void;
25
35
  onGoToc: (item: TocItem) => void;
@@ -108,7 +118,7 @@ export function ContentsSheet(p: Props) {
108
118
 
109
119
  {tab === 'notes' && (
110
120
  <FlatList
111
- data={p.highlights.slice().sort((a, b) => a.spine - b.spine || a.start - b.start)}
121
+ data={p.highlights.slice().sort(byPosition)}
112
122
  keyExtractor={(h) => h.id}
113
123
  ListEmptyComponent={empty(L.noHighlights)}
114
124
  renderItem={({ item }) => (
@@ -117,7 +127,7 @@ export function ContentsSheet(p: Props) {
117
127
  onLongPress={() => confirmDelete(L.deleteHighlight, () => p.onDeleteHighlight(item.id))}
118
128
  style={[styles.row, rowBorder]}
119
129
  >
120
- <View style={[styles.bar, { backgroundColor: HIGHLIGHT_COLORS[item.color] }]} />
130
+ <View style={[styles.bar, { backgroundColor: p.palette?.[item.color] || HIGHLIGHT_COLORS[item.color as HighlightColor] || item.color }]} />
121
131
  <View style={{ flex: 1 }}>
122
132
  {!!item.note && <Text style={[styles.rowText, { color: colors.text, fontWeight: '600' }]}>{item.note}</Text>}
123
133
  <Text style={[styles.rowText, { color: item.note ? colors.subtext : colors.text }]} numberOfLines={3}>
@@ -1,8 +1,9 @@
1
1
  import React, { useState } from 'react';
2
- import { Pressable, ScrollView, StyleSheet, Switch, Text, View } from 'react-native';
3
- import { FONTS, getFont, serifFont } from '../themes';
2
+ import { Pressable, ScrollView, StyleSheet, Switch, View } from 'react-native';
3
+ import { Text } from './Text';
4
+ import { FONTS, serifFont } from '../themes';
4
5
  import type { ChromeColors } from '../themes';
5
- import type { ColumnsSetting, ReaderSettings, ThemeColors } from '../types';
6
+ import type { ColumnsSetting, ReaderFont, ReaderSettings, ThemeColors } from '../types';
6
7
  import { useLabels } from '../strings';
7
8
  import { Icon } from './Icons';
8
9
  import type { IconName } from './Icons';
@@ -15,6 +16,8 @@ interface Props {
15
16
  page: ThemeColors;
16
17
  settings: ReaderSettings;
17
18
  sample: string;
19
+ /** fonts to choose from (default: the built-in FONTS) */
20
+ fontList?: ReaderFont[];
18
21
  onChange: (patch: Partial<ReaderSettings>) => void;
19
22
  onReset: () => void;
20
23
  onClose: () => void;
@@ -31,13 +34,14 @@ function Toggle(props: React.ComponentProps<typeof Switch>) {
31
34
  }
32
35
 
33
36
  /** "Customize Theme" sheet: font, bold, spacing, margins, columns, justify, sound. */
34
- export function CustomizeSheet({ visible, colors, page, settings: s, sample, onChange, onReset, onClose }: Props) {
37
+ export function CustomizeSheet({ visible, colors, page, settings: s, sample, fontList = FONTS, onChange, onReset, onClose }: Props) {
38
+ const track = colors.strong ? { true: colors.strong } : GREEN;
35
39
  const L = useLabels();
36
40
  const COLUMN_LABEL: Record<string, string> = { auto: L.columnsAuto, '1': L.columnsOne, '2': L.columnsTwo };
37
41
  const [fonts, setFonts] = useState(false);
38
42
  const [columnsMenu, setColumnsMenu] = useState(false);
39
43
  const off = !s.customize;
40
- const font = getFont(s.fontId);
44
+ const font = fontList.find((f) => f.id === s.fontId) || fontList[0];
41
45
  const previewFont = s.fontId === 'system' ? undefined : serifFont;
42
46
  const border = { borderTopWidth: StyleSheet.hairlineWidth, borderColor: colors.separator };
43
47
 
@@ -108,7 +112,7 @@ export function CustomizeSheet({ visible, colors, page, settings: s, sample, onC
108
112
  false
109
113
  )}
110
114
  {fonts &&
111
- FONTS.map((f) => (
115
+ fontList.map((f) => (
112
116
  <Pressable
113
117
  key={f.id}
114
118
  onPress={() => {
@@ -121,12 +125,12 @@ export function CustomizeSheet({ visible, colors, page, settings: s, sample, onC
121
125
  <Text style={[styles.label, { color: colors.text }]}>{f.name}</Text>
122
126
  </Pressable>
123
127
  ))}
124
- {row('bold', L.boldText, <Toggle value={s.bold} onValueChange={(v) => onChange({ bold: v })} trackColor={GREEN} />)}
128
+ {row('bold', L.boldText, <Toggle value={s.bold} onValueChange={(v) => onChange({ bold: v })} trackColor={track} />)}
125
129
  </View>
126
130
 
127
131
  <Text style={[styles.heading, { color: colors.text }]}>{L.accessibilityLayout}</Text>
128
132
  <View style={[styles.group, { backgroundColor: colors.card }]}>
129
- {row('sliders', L.customize, <Toggle value={s.customize} onValueChange={(v) => onChange({ customize: v })} trackColor={GREEN} />, undefined, false)}
133
+ {row('sliders', L.customize, <Toggle value={s.customize} onValueChange={(v) => onChange({ customize: v })} trackColor={track} />, undefined, false)}
130
134
  {sliderRow(L.lineSpacing, 'lineSpacing', s.lineHeight, 1.1, 2.2, 0.05, s.lineHeight.toFixed(2), 'lineHeight')}
131
135
  {sliderRow(L.characterSpacing, 'charSpacing', s.letterSpacing, -50, 100, 5, `${s.letterSpacing}%`, 'letterSpacing')}
132
136
  {sliderRow(L.wordSpacing, 'wordSpacing', s.wordSpacing, -50, 100, 5, `${s.wordSpacing}%`, 'wordSpacing')}
@@ -158,8 +162,8 @@ export function CustomizeSheet({ visible, colors, page, settings: s, sample, onC
158
162
  <Text style={[styles.label, { color: colors.text }]}>{COLUMN_LABEL[String(c)]}</Text>
159
163
  </Pressable>
160
164
  ))}
161
- {row('justify', L.justifyText, <Toggle value={s.justify} onValueChange={(v) => onChange({ justify: v })} trackColor={GREEN} />)}
162
- {row(s.pageSound ? 'sound' : 'soundOff', L.pageTurnSound, <Toggle value={s.pageSound} onValueChange={(v) => onChange({ pageSound: v })} trackColor={GREEN} />)}
165
+ {row('justify', L.justifyText, <Toggle value={s.justify} onValueChange={(v) => onChange({ justify: v })} trackColor={track} />)}
166
+ {row(s.pageSound ? 'sound' : 'soundOff', L.pageTurnSound, <Toggle value={s.pageSound} onValueChange={(v) => onChange({ pageSound: v })} trackColor={track} />)}
163
167
  </View>
164
168
 
165
169
  <Pressable onPress={onReset} style={[styles.reset, { backgroundColor: colors.card }]} accessibilityRole="button">
@@ -9,10 +9,12 @@ import { Icon } from './Icons';
9
9
 
10
10
  interface Props {
11
11
  highlight: Highlight;
12
+ /** colour name -> CSS colour shown as a dot (default: the built-in HIGHLIGHT_COLORS) */
13
+ palette?: Record<string, string>;
12
14
  rect: { x: number; y: number; width: number; height: number };
13
15
  screen: { width: number; height: number };
14
16
  colors: ChromeColors;
15
- onColor: (c: HighlightColor) => void;
17
+ onColor: (c: HighlightColor | (string & {})) => void;
16
18
  onToggleUnderline: () => void;
17
19
  onNote: () => void;
18
20
  onDelete: () => void;
@@ -23,7 +25,7 @@ const MAX_W = 316;
23
25
  const H = 50;
24
26
 
25
27
  /** Floating glass palette shown over a highlight, like Apple Books. */
26
- export function HighlightMenu({ highlight, rect, screen, colors, onColor, onToggleUnderline, onNote, onDelete, onDismiss }: Props) {
28
+ export function HighlightMenu({ highlight, palette = HIGHLIGHT_COLORS, rect, screen, colors, onColor, onToggleUnderline, onNote, onDelete, onDismiss }: Props) {
27
29
  const L = useLabels();
28
30
  const W = Math.min(MAX_W, screen.width - 16); // narrow windows (split screen, foldable cover screens)
29
31
  const left = Math.max(8, Math.min(screen.width - W - 8, rect.x + rect.width / 2 - W / 2));
@@ -33,9 +35,9 @@ export function HighlightMenu({ highlight, rect, screen, colors, onColor, onTogg
33
35
  <>
34
36
  <Pressable style={StyleSheet.absoluteFill} onPress={onDismiss} accessibilityLabel={L.dismiss} />
35
37
  <Glass dark={colors.dark} background={colors.sheetGlass} border={colors.glassBorder} intensity={55} style={[styles.menu, { left, top, width: W }]}>
36
- {(Object.keys(HIGHLIGHT_COLORS) as HighlightColor[]).map((c) => (
38
+ {Object.keys(palette).map((c) => (
37
39
  <Pressable key={c} onPress={() => onColor(c)} hitSlop={8} accessibilityRole="button" accessibilityLabel={`${c} ${L.highlight}`} accessibilityState={{ selected: highlight.color === c }}>
38
- <View style={[styles.dot, { backgroundColor: HIGHLIGHT_COLORS[c], borderWidth: highlight.color === c ? 2 : 0, borderColor: colors.text }]} />
40
+ <View style={[styles.dot, { backgroundColor: palette[c], borderWidth: highlight.color === c ? 2 : 0, borderColor: colors.text }]} />
39
41
  </Pressable>
40
42
  ))}
41
43
  <Pressable onPress={onToggleUnderline} hitSlop={11} accessibilityRole="button" accessibilityLabel={L.underline} accessibilityState={{ selected: highlight.style === 'underline' }}>
@@ -1,5 +1,6 @@
1
1
  import React, { useEffect, useState } from 'react';
2
- import { KeyboardAvoidingView, Modal, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
2
+ import { KeyboardAvoidingView, Modal, Platform, Pressable, StyleSheet, View } from 'react-native';
3
+ import { Text, TextInput } from './Text';
3
4
  import type { ChromeColors } from '../themes';
4
5
  import { useLabels } from '../strings';
5
6
 
@@ -1,5 +1,6 @@
1
1
  import React, { useEffect, useRef, useState } from 'react';
2
- import { FlatList, Keyboard, Pressable, StyleSheet, Text, TextInput, View } from 'react-native';
2
+ import { FlatList, Keyboard, Pressable, StyleSheet, View } from 'react-native';
3
+ import { Text, TextInput } from './Text';
3
4
  import type { ChromeColors } from '../themes';
4
5
  import type { SearchResult } from '../types';
5
6
  import { useLabels } from '../strings';
package/src/ui/Sheet.tsx CHANGED
@@ -1,5 +1,6 @@
1
1
  import React from 'react';
2
- import { Modal, Pressable, StyleSheet, Text, View } from 'react-native';
2
+ import { Modal, Pressable, StyleSheet, View } from 'react-native';
3
+ import { Text } from './Text';
3
4
  import type { ViewStyle } from 'react-native';
4
5
  import type { ChromeColors } from '../themes';
5
6
  import { Glass } from './Glass';
@@ -25,8 +26,8 @@ export function Sheet({ visible, title, subtitle, colors, height = '70%', closeI
25
26
  const L = useLabels();
26
27
  const button =
27
28
  closeIcon === 'check' ? (
28
- <Pressable onPress={onClose} hitSlop={10} style={[styles.circle, { backgroundColor: colors.dark ? '#ffffff' : '#000000' }]} accessibilityRole="button" accessibilityLabel={L.done}>
29
- <Icon name="check" color={colors.dark ? '#000000' : '#ffffff'} size={24} strokeWidth={2.2} />
29
+ <Pressable onPress={onClose} hitSlop={10} style={[styles.circle, { backgroundColor: colors.strong || (colors.dark ? '#ffffff' : '#000000') }]} accessibilityRole="button" accessibilityLabel={L.done}>
30
+ <Icon name="check" color={colors.onStrong || (colors.dark ? '#000000' : '#ffffff')} size={24} strokeWidth={2.2} />
30
31
  </Pressable>
31
32
  ) : (
32
33
  <Pressable onPress={onClose} hitSlop={10} accessibilityRole="button" accessibilityLabel={L.close}>
@@ -0,0 +1,27 @@
1
+ import React, { createContext, forwardRef, useContext } from 'react';
2
+ import { StyleSheet, Text as RNText, TextInput as RNTextInput } from 'react-native';
3
+ import type { TextInputProps, TextProps } from 'react-native';
4
+ import type { UiFonts } from '../types';
5
+
6
+ export const UiFontsContext = createContext<UiFonts | null>(null);
7
+
8
+ /** Text of the reader's interface. Uses the host's `uiFonts` when given; a style with its own fontFamily keeps it. */
9
+ export function Text(props: TextProps) {
10
+ const fonts = useContext(UiFontsContext);
11
+ if (!fonts) return <RNText {...props} />;
12
+ const flat = StyleSheet.flatten(props.style) || {};
13
+ if (flat.fontFamily) return <RNText {...props} />;
14
+ const weight = flat.fontWeight === 'bold' ? 700 : Number(flat.fontWeight) || 400;
15
+ // a font file per weight: the weight is in the family, so the style's weight must not be applied again
16
+ const family = (weight >= 600 && fonts.bold) || (weight >= 500 && fonts.medium) || null;
17
+ const style = family ? { fontFamily: family, fontWeight: 'normal' as const } : { fontFamily: fonts.regular };
18
+ return <RNText {...props} style={[props.style, style]} />;
19
+ }
20
+
21
+ /** Text field of the reader's interface, in the host's regular `uiFonts` font when given. */
22
+ export const TextInput = forwardRef<RNTextInput, TextInputProps>(function TextInput(props, ref) {
23
+ const fonts = useContext(UiFontsContext);
24
+ const flat = StyleSheet.flatten(props.style) || {};
25
+ if (!fonts || flat.fontFamily) return <RNTextInput ref={ref} {...props} />;
26
+ return <RNTextInput ref={ref} {...props} style={[props.style, { fontFamily: fonts.regular }]} />;
27
+ });