@quran.ws/qvp-react-native 0.6.1 → 0.8.0

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/src/index.tsx CHANGED
@@ -6,7 +6,7 @@
6
6
  * Declarative props (`highlights`, `styles`, `theme`, `mask`, `reveal`) are reconciled against engine
7
7
  * handles on the native side, so JS never sees a handle.
8
8
  */
9
- import React, { forwardRef, useImperativeHandle, useMemo, useRef } from 'react';
9
+ import React, { forwardRef, useImperativeHandle, useMemo, useRef, useState } from 'react';
10
10
  import {
11
11
  findNodeHandle,
12
12
  NativeModules,
@@ -15,6 +15,7 @@ import {
15
15
  type NativeSyntheticEvent,
16
16
  type ViewProps,
17
17
  } from 'react-native';
18
+ import { SELECTOR, TARGET } from './codes';
18
19
 
19
20
  // ── constants (mirror qvp.h) ─────────────────────────────────────────────────────────────────
20
21
  export const KIND = { BODY: 0, MARK: 1, AYAH_NUMBER: 2, AYAH_MARK_ORNAMENT: 3, HEADER_INK: 4, OTHER: 255 } as const;
@@ -23,6 +24,8 @@ export const CATEGORY = { NONE: 0, HARAKAH: 1, TANWIN: 2, LETTER_DOT: 3, ORTHOGR
23
24
  export const DECORATION = { AYAH_MARK: 0, SURAH_NAME: 1, BASMALAH: 2, DIVISION_MARK: 3, SAJDAH_MARK: 4 } as const;
24
25
  export const LAYER = { BASE: 0, THEME: 10, HIGHLIGHT: 50, SELECTION: 60, TOP: 100 } as const;
25
26
  export const DIVISION = { JUZ: 0, HIZB: 1, NISF: 2, RUBU_AL_HIZB: 3 } as const;
27
+ /** The three kinds of ornament a page can be dressed in, in engine order. Pass one to `find` or `ofKind`. */
28
+ export const ORNAMENT_KIND = ['ayah_mark', 'surah_header', 'page_frame'] as const;
26
29
 
27
30
  // ── colours ──────────────────────────────────────────────────────────────────────────────────
28
31
  export type Color = string | number;
@@ -38,42 +41,44 @@ export function css(c: Color | null | undefined): string | undefined {
38
41
  /** Colour with a replaced alpha (0..1). */
39
42
  export function rgba(c: Color, alpha: number): string {
40
43
  const h = css(c)!;
41
- return h.slice(0, 7) + Math.round(Math.max(0, Math.min(1, alpha)) * 255).toString(16).padStart(2, '0');
44
+ return h.slice(0, 7) + Math.round((Number.isNaN(alpha) ? 0 : Math.max(0, Math.min(1, alpha))) * 255).toString(16).padStart(2, '0');
42
45
  }
43
46
 
44
47
  // ── targets and selectors (same shapes as web/qvp.js T / Sel) ────────────────────────────────
48
+ // The codes come from qvp.h through codes.ts, which scripts/gen-rn-enums.py writes; the Android
49
+ // module reads them back with the same table.
45
50
  export interface TargetObj { target: number; a?: number; b?: number; c?: number; words?: number[] }
46
51
  /** 'page' | '2:255' | '2:255:3' | '2:255-257' | 'line:7' | 'surah:2' | word index | [indices] | T.* */
47
52
  export type Target = string | number | number[] | TargetObj;
48
53
  export const T = {
49
- page: (): TargetObj => ({ target: 0 }),
50
- word: (i: number): TargetObj => ({ target: 1, a: i }),
51
- words: (ws: number[]): TargetObj => ({ target: 2, words: ws }),
52
- ayah: (s: number, a: number): TargetObj => ({ target: 3, a: s, b: a }),
53
- ayahRange: (s: number, a: number, b: number): TargetObj => ({ target: 4, a: s, b: a, c: b }),
54
- line: (n: number): TargetObj => ({ target: 5, a: n }),
55
- surah: (s: number): TargetObj => ({ target: 6, a: s }),
56
- range: (a: number, b: number): TargetObj => ({ target: 7, a, b }),
54
+ page: (): TargetObj => ({ target: TARGET.page }),
55
+ word: (i: number): TargetObj => ({ target: TARGET.word, a: i }),
56
+ words: (ws: number[]): TargetObj => ({ target: TARGET.words, words: ws }),
57
+ ayah: (s: number, a: number): TargetObj => ({ target: TARGET.ayah, a: s, b: a }),
58
+ ayahRange: (s: number, a: number, b: number): TargetObj => ({ target: TARGET.ayahRange, a: s, b: a, c: b }),
59
+ line: (n: number): TargetObj => ({ target: TARGET.line, a: n }),
60
+ surah: (s: number): TargetObj => ({ target: TARGET.surah, a: s }),
61
+ range: (a: number, b: number): TargetObj => ({ target: TARGET.range, a, b }),
57
62
  };
58
63
  export interface Selector { selector: number; a?: number; b?: number; c?: number; mark?: string }
59
64
  export const Sel = {
60
- page: (): Selector => ({ selector: 0 }),
61
- path: (p: number): Selector => ({ selector: 1, a: p }),
62
- wordPath: (w: number, nth: number): Selector => ({ selector: 2, a: w, b: nth }),
65
+ page: (): Selector => ({ selector: SELECTOR.page }),
66
+ path: (p: number): Selector => ({ selector: SELECTOR.path, a: p }),
67
+ wordPath: (w: number, nth: number): Selector => ({ selector: SELECTOR.wordPath, a: w, b: nth }),
63
68
  /** nth mark of the word (0-based, marks only) */
64
- wordMark: (w: number, nth: number): Selector => ({ selector: 3, a: w, b: nth }),
65
- wordMarkNamed: (w: number, mark: string, nth = 0): Selector => ({ selector: 4, a: w, b: markId(mark), c: nth, mark }),
66
- wordBody: (w: number): Selector => ({ selector: 5, a: w }),
67
- wordMarks: (w: number): Selector => ({ selector: 6, a: w }),
68
- word: (w: number): Selector => ({ selector: 7, a: w }),
69
- ayah: (s: number, a: number): Selector => ({ selector: 8, a: s, b: a }),
70
- line: (n: number): Selector => ({ selector: 9, a: n }),
71
- mark: (m: string | number): Selector => ({ selector: 10, a: markId(m) }),
72
- category: (c: string | number): Selector => ({ selector: 11, a: named(c, CATEGORY_NAMES) }),
73
- family: (f: string | number): Selector => ({ selector: 12, a: named(f, FAMILY_NAMES) }),
74
- kind: (k: string | number): Selector => ({ selector: 13, a: named(k, KIND_NAMES) }),
75
- decoration: (k: string | number): Selector => ({ selector: 14, a: named(k, DECORATION_NAMES) }),
76
- decorationIndex: (d: number): Selector => ({ selector: 15, a: d }),
69
+ wordMark: (w: number, nth: number): Selector => ({ selector: SELECTOR.wordMark, a: w, b: nth }),
70
+ wordMarkNamed: (w: number, mark: string, nth = 0): Selector => ({ selector: SELECTOR.wordMarkNamed, a: w, b: markId(mark), c: nth, mark }),
71
+ wordBody: (w: number): Selector => ({ selector: SELECTOR.wordBody, a: w }),
72
+ wordMarks: (w: number): Selector => ({ selector: SELECTOR.wordMarks, a: w }),
73
+ word: (w: number): Selector => ({ selector: SELECTOR.word, a: w }),
74
+ ayah: (s: number, a: number): Selector => ({ selector: SELECTOR.ayah, a: s, b: a }),
75
+ line: (n: number): Selector => ({ selector: SELECTOR.line, a: n }),
76
+ mark: (m: string | number): Selector => ({ selector: SELECTOR.mark, a: markId(m) }),
77
+ category: (c: string | number): Selector => ({ selector: SELECTOR.category, a: named(c, CATEGORY_NAMES) }),
78
+ family: (f: string | number): Selector => ({ selector: SELECTOR.family, a: named(f, FAMILY_NAMES) }),
79
+ kind: (k: string | number): Selector => ({ selector: SELECTOR.kind, a: named(k, KIND_NAMES) }),
80
+ decoration: (k: string | number): Selector => ({ selector: SELECTOR.decoration, a: named(k, DECORATION_NAMES) }),
81
+ decorationIndex: (d: number): Selector => ({ selector: SELECTOR.decorationIndex, a: d }),
77
82
  };
78
83
 
79
84
  // ── records ──────────────────────────────────────────────────────────────────────────────────
@@ -88,7 +93,7 @@ export interface Word {
88
93
  wordKey: string; ayahKey: string; forms: Partial<Record<Form, string>>; label: string; paths: WordPath[];
89
94
  }
90
95
  export interface Deco { index: number; decoration: number; decorationName: string; surah: number; ayah: number; line: number; x0: number; y0: number; x1: number; y1: number; text: string; firstPath: number; nPaths: number }
91
- /** The one hit shape for every hit test; the exact variants report distance 0 and `isExact`. */
96
+ /** The one hit shape for every hit test; the exact variants report distance 0. `isExact` is true only when the point is inside an outline. */
92
97
  export interface Hit { word: number; path: number; decoration: number; line: number; distance: number; isExact: boolean; wordKey: string | null; ayahKey: string | null }
93
98
  export interface Ayah { index: number; surah: number; ayah: number; fragment: number; fragments: number; flags: number; rubuAlHizb: number; firstWord: number; nWords: number; ayahMarkDecoration: number; bbox: number[] }
94
99
  export interface Line { index: number; lineNumber: number; isHeader: boolean; firstWord: number; nWords: number; bbox: number[]; bandY0: number; bandY1: number; centre: number }
@@ -102,7 +107,9 @@ export interface SurahHeader { decoration: number; surah: number; line: number;
102
107
  export interface Rosette { decoration: number; surah: number; ayah: number; juz: number; hizb: number; nisf: number; rubuAlHizb: number; rubuAlHizbInHizb: number }
103
108
  export interface Sajdah { decoration: number; surah: number; ayah: number; signPath: number }
104
109
  export interface CropBox { x0: number; y0: number; x1: number; y1: number; nWords: number; ayahMarkDecoration: number }
105
- export interface Layout { scale: number; offsetX: number; offsetY: number; contentW: number; contentH: number; lineSpacing: number; lineDy: number[]; slots: number[][] }
110
+ /** A zoom and pan of the page: the scale and the offset of its origin. */
111
+ export interface ViewState { scale: number; offsetX: number; offsetY: number }
112
+ export interface Layout { scale: number; offsetX: number; offsetY: number; contentW: number; contentH: number; lineSpacing: number; fitScale: number; fitX: number; fitY: number; lineDy: number[]; slots: number[][] }
106
113
  export interface Stats { loadMs: number; bytes: number; baseMs: number; overlayMs: number; basePaths: number; overlayPaths: number; bands: number; hitUs: number; animating: boolean; styleHandles: number; highlightHandles: number; engineVersion: string; viewScale: number; layout: Layout | null }
107
114
  export interface AtlasSurah { number: number; page: number; ayahCount: number; place: string; arabic: string; latin: string; english: string }
108
115
  export interface AtlasRubuAlHizb { rubuAlHizb: number; surah: number; ayah: number; page: number; ayahKey: string }
@@ -118,8 +125,48 @@ export interface Mask { target?: Target; from?: number; mode?: MaskMode; blockCo
118
125
  /** Greyed-page reveal: `revealStart(lit, byAyah, grey, ink, ayahMarks, ms)` then `revealGoto(at)` whenever `at` changes; null → revealStop. */
119
126
  export interface Reveal { lit?: number; byAyah?: boolean; grey?: Color; ink?: Color; ayahMarks?: boolean; ms?: number; at?: number }
120
127
 
128
+ // ── dress: another mushaf's ornaments ──
129
+ /** The kind of an ornament, as `docs/API.md` names it. */
130
+ export type OrnamentKind = 'ayah_mark' | 'surah_header' | 'page_frame';
131
+ /** Where an ornament comes from: a scanned mushaf or a font. */
132
+ export type Lineage = 'scan' | 'font';
133
+ /** One printed colour of an ornament. `color` is 0xRRGGBBAA; alpha 0 is the design's slot. */
134
+ export interface OrnamentPart { index: number; color: number; stroke: boolean; name: string }
135
+ /** What an ornament may be redistributed under. Read it before you publish a dressed page. */
136
+ export interface Licence { id: string; status: string; redistributable: boolean; attribution: string }
137
+ export interface Ornament { index: number; kind: OrnamentKind; lineage: Lineage; style: string; riwayah: string; hasSlices: boolean; licence: Licence; parts: OrnamentPart[] }
138
+ /** One mushaf or font of a set, with the ornament it has of each kind or null. */
139
+ export interface OrnamentStyle { style: string; riwayah: string; lineage: Lineage; ayahMark: Ornament | null; surahHeader: Ornament | null; pageFrame: Ornament | null }
140
+ /** An ornament of the set, its index, or a style name (the ornament of that kind in that style). */
141
+ export type OrnamentRef = Ornament | number | string | null;
142
+ /**
143
+ * What to dress a page in. `style` names a mushaf and takes its medallion, band and border
144
+ * together; a kind key overrides the style for that kind. `gap` is the air between the text and
145
+ * the border and `bandGap` the air between a band and the border, both in page units.
146
+ * `ayahMarkScale` 0 takes the design's own size. `lineArt` is `true` for every kind or a list of
147
+ * kinds. `colors` repaints parts: `[ornament, part, colour]`.
148
+ */
149
+ export interface DressSpec {
150
+ style?: string | null;
151
+ ayahMark?: OrnamentRef; surahHeader?: OrnamentRef; pageFrame?: OrnamentRef;
152
+ gap?: number; bandGap?: number; ayahMarkScale?: number; pageFrameScale?: number;
153
+ lineArt?: boolean | OrnamentKind[];
154
+ colors?: [Ornament | number, number, Color][];
155
+ }
156
+ /** The engine's readout of a dressed page. `viewBox` is [x, y, w, h] in page units; `overflow` is
157
+ * [left, top, right, bottom] in viewport px, how far the border reaches past the content. */
158
+ export interface DressInfo {
159
+ ayahMark: number | null; surahHeader: number | null; pageFrame: number | null;
160
+ ayahMarks: number; surahHeaders: number; frameRepeats: number; frameStretched: boolean;
161
+ draws: number; revision: number; viewBox: [number, number, number, number]; overflow: [number, number, number, number];
162
+ }
163
+ /** The `dress` prop: a spec plus the ornament set it names. */
164
+ export interface Dress extends DressSpec { ornaments: QvpOrnaments | number }
165
+
121
166
  // ── the view ─────────────────────────────────────────────────────────────────────────────────
122
167
  /** What a pinch does to the page: the engine owns the policy, this names which one. */
168
+ /** How the words are broken onto rows. */
169
+ export type Breaks = 'greedy' | 'even' | 'fitted' | 'printed';
123
170
  export type ZoomMode = 'stepped' | 'continuous' | 'magnify';
124
171
  /** Where the reader's zoom control stands: the mode, the step, and the size in force. */
125
172
  export interface Zoom { mode: ZoomMode; step: number; zoom: number }
@@ -135,6 +182,8 @@ export interface QvpPageViewProps extends ViewProps {
135
182
  lineSpacing?: number; fillHeight?: boolean;
136
183
  /** Draw source-native frames around surah names on the printed page. */
137
184
  surahFrames?: boolean;
185
+ /** Keep the printed rows or break them again as the reader zooms in. */
186
+ reflowBreaks?: Breaks;
138
187
  paperColor?: Color; defaultInk?: Color; selectionBand?: Color;
139
188
  selectionEnabled?: boolean; zoomEnabled?: boolean; hitMaxDistance?: number;
140
189
  /** What a pinch does to the page. `stepped` reflows onto the page's own zoom steps and is
@@ -149,6 +198,9 @@ export interface QvpPageViewProps extends ViewProps {
149
198
  highlights?: Highlight[];
150
199
  mask?: Mask | null;
151
200
  reveal?: Reveal | null;
201
+ /** Another mushaf's ornaments, painted behind the ink. Native compares the spec by value: an equal
202
+ * spec is a no-op and a changed one dresses the page again. `null` undresses it. It is applied again to every page the view loads. */
203
+ dress?: Dress | null;
152
204
  onWordTap?: (e: { word: Word; hit: Hit }) => void;
153
205
  onDecorationTap?: (e: { decoration: Deco; hit: Hit }) => void;
154
206
  onEmptyTap?: () => void;
@@ -161,9 +213,13 @@ export interface QvpPageViewProps extends ViewProps {
161
213
  onSwipe?: (e: { pages: number }) => void;
162
214
  /** The size the reader is at changed: a pinch committed, or a step was asked for. */
163
215
  onZoomChanged?: (e: Zoom) => void;
216
+ /** The `dress` prop was applied: the engine's readout, or null when it refused the spec or the page is undressed. */
217
+ onDressChanged?: (e: { info: DressInfo | null }) => void;
164
218
  onError?: (e: { message: string }) => void;
165
219
  }
166
- type NativeProps = ViewProps & Omit<QvpPageViewProps, 'onWordTap' | 'onDecorationTap' | 'onEmptyTap' | 'onSelectionChanged' | 'onPageLoad' | 'onRevealChanged' | 'onSwipe' | 'onZoomChanged' | 'onError'> & {
220
+ type NativeProps = ViewProps & Omit<QvpPageViewProps, 'dress' | 'onWordTap' | 'onDecorationTap' | 'onEmptyTap' | 'onSelectionChanged' | 'onPageLoad' | 'onRevealChanged' | 'onSwipe' | 'onZoomChanged' | 'onDressChanged' | 'onError'> & {
221
+ dress?: object | null;
222
+ onDressChanged?: (e: NativeSyntheticEvent<{ info: DressInfo | null }>) => void;
167
223
  onWordTap?: (e: NativeSyntheticEvent<{ word: Word; hit: Hit }>) => void;
168
224
  onDecorationTap?: (e: NativeSyntheticEvent<{ decoration: Deco; hit: Hit }>) => void;
169
225
  onEmptyTap?: (e: NativeSyntheticEvent<{}>) => void;
@@ -195,7 +251,7 @@ export type QvpPageViewHandle = PageApi & { tag: () => number };
195
251
 
196
252
  export const QvpPageView = forwardRef<QvpPageViewHandle, QvpPageViewProps>(function QvpPageView(props, ref) {
197
253
  const native = useRef<any>(null);
198
- const { theme, styles, highlights, mask, reveal, paperColor, defaultInk, selectionBand, onWordTap, onDecorationTap, onEmptyTap, onSelectionChanged, onPageLoad, onRevealChanged, onSwipe, onZoomChanged, onError, ...rest } = props;
254
+ const { theme, styles, highlights, mask, reveal, dress, paperColor, defaultInk, selectionBand, onWordTap, onDecorationTap, onEmptyTap, onSelectionChanged, onPageLoad, onRevealChanged, onSwipe, onZoomChanged, onDressChanged, onError, ...rest } = props;
199
255
  const tag = () => findNodeHandle(native.current) ?? -1;
200
256
  useImperativeHandle(ref, () => ({ tag, ...bindPage(tag) }), []);
201
257
  const nTheme = useMemo(() => (theme ? normColors(theme) : null), [theme]);
@@ -203,6 +259,7 @@ export const QvpPageView = forwardRef<QvpPageViewHandle, QvpPageViewProps>(funct
203
259
  const nHighlights = useMemo(() => (highlights ? normColors(highlights) : []), [highlights]);
204
260
  const nMask = useMemo(() => (mask ? normColors(mask) : null), [mask]);
205
261
  const nReveal = useMemo(() => (reveal ? normColors(reveal) : null), [reveal]);
262
+ const nDress = useMemo(() => (dress ? { ...dressSpec(dress), ornaments: ornamentsId(dress.ornaments) } : null), [dress]);
206
263
  return (
207
264
  <NativeQvpPageView
208
265
  ref={native}
@@ -215,6 +272,7 @@ export const QvpPageView = forwardRef<QvpPageViewHandle, QvpPageViewProps>(funct
215
272
  highlights={nHighlights}
216
273
  mask={nMask}
217
274
  reveal={nReveal}
275
+ dress={nDress}
218
276
  onWordTap={onWordTap ? (e: NativeSyntheticEvent<{ word: Word; hit: Hit }>) => onWordTap(e.nativeEvent) : undefined}
219
277
  onDecorationTap={onDecorationTap ? (e: NativeSyntheticEvent<{ decoration: Deco; hit: Hit }>) => onDecorationTap(e.nativeEvent) : undefined}
220
278
  onEmptyTap={onEmptyTap ? () => onEmptyTap() : undefined}
@@ -223,26 +281,124 @@ export const QvpPageView = forwardRef<QvpPageViewHandle, QvpPageViewProps>(funct
223
281
  onRevealChanged={onRevealChanged ? (e: NativeSyntheticEvent<{ steps: number; at: number | null }>) => onRevealChanged(e.nativeEvent) : undefined}
224
282
  onSwipe={onSwipe ? (e: NativeSyntheticEvent<{ pages: number }>) => onSwipe(e.nativeEvent) : undefined}
225
283
  onZoomChanged={onZoomChanged ? (e: NativeSyntheticEvent<Zoom>) => onZoomChanged(e.nativeEvent) : undefined}
284
+ onDressChanged={onDressChanged ? (e: NativeSyntheticEvent<{ info: DressInfo | null }>) => onDressChanged(e.nativeEvent) : undefined}
226
285
  onError={onError ? (e: NativeSyntheticEvent<{ message: string }>) => onError(e.nativeEvent) : undefined}
227
286
  />
228
287
  );
229
288
  });
230
289
 
290
+ // ── the passage view ─────────────────────────────────────────────────────────────────────────
291
+ /** Where the rows of a passage start: at the right edge, in the middle, or across the width. */
292
+ export type PassageAlign = 'right' | 'center' | 'justified';
293
+ export interface PassageRow { x0: number; y0: number; x1: number; y1: number; baseline: number }
294
+ /** One word of a laid-out passage with its signs, in dp: its key, the page it is printed on and its row.
295
+ * `x0`…`y1` is the word and its signs; `wordX0`…`wordY1` is the word alone, which leaves out the signs:
296
+ * the word that closes an ayah leaves its medallion out. */
297
+ export interface PassageWord { surah: number; ayah: number; word: number; wordKey: string; page: number; row: number; x0: number; y0: number; x1: number; y1: number;
298
+ wordX0: number; wordY0: number; wordX1: number; wordY1: number }
299
+ export interface PassageAyah { surah: number; ayah: number; x0: number; y0: number; x1: number; y1: number }
300
+ export interface PassageText { surah: number; ayah: number; text: string }
301
+ /** A laid-out passage, in dp. `printedLineSpacing` is the passage's printed line, in page units: what
302
+ * `lineHeight` divides by. `ellipsis` is where the view drew the ellipsis after a cut. */
303
+ export interface PassageLayout {
304
+ width: number; height: number; scale: number; lineSpacing: number; printedLineSpacing: number;
305
+ isTruncated: boolean; ellipsis: number[] | null;
306
+ rows: PassageRow[]; words: PassageWord[]; ayahs: PassageAyah[]; texts: PassageText[];
307
+ }
308
+ export interface QvpPassageViewProps extends ViewProps {
309
+ /** The pages that print the range, in any order; the same URI schemes as `pageUri`. */
310
+ pageUris: string[];
311
+ surah: number;
312
+ /** The first and last ayah; `to` defaults to `from`. Left out for a basmalah. */
313
+ from?: number; to?: number;
314
+ /** The basmalah printed above `surah`, one row and no words. Surahs 1 and 9 have none. */
315
+ basmalah?: boolean;
316
+ /** dp per page unit (1), or `lineHeight`: dp per printed line, which wins when both are given. */
317
+ scale?: number; lineHeight?: number;
318
+ /** Leading as a multiple of the printed line (1), and the padding around the rows in dp (2). */
319
+ lineSpacing?: number; padding?: number;
320
+ align?: PassageAlign;
321
+ /** Cut the passage after this many rows (0 = no cut), with room for an ellipsis this wide in dp.
322
+ * `keepAyahMark` puts the medallion of the last ayah after the ellipsis. */
323
+ maxRows?: number; ellipsisWidth?: number; keepAyahMark?: boolean;
324
+ /** How far a justified row's gaps may open, as a multiple of the usual air (0 = the engine's default). */
325
+ maxStretch?: number;
326
+ ink?: Color; paperColor?: Color;
327
+ /** The layout the engine made for this width. The view takes its height from it unless the style gives one. */
328
+ onPassageLayout?: (e: PassageLayout) => void;
329
+ onError?: (e: { message: string }) => void;
330
+ }
331
+ type NativePassageProps = ViewProps & Omit<QvpPassageViewProps, 'onPassageLayout' | 'onError' | 'ink' | 'paperColor'> & {
332
+ ink?: string; paperColor?: string;
333
+ onPassageLayout?: (e: NativeSyntheticEvent<PassageLayout>) => void;
334
+ onError?: (e: NativeSyntheticEvent<{ message: string }>) => void;
335
+ };
336
+ const NativeQvpPassageView = requireNativeComponent<NativePassageProps>('QvpPassageView') as HostComponent<NativePassageProps>;
337
+
338
+ /** A range of complete ayahs, or a surah's basmalah, laid out on rows of this view's width and drawn
339
+ * natively. The engine lays it out; JS sees the layout through `onPassageLayout`. */
340
+ export function QvpPassageView(props: QvpPassageViewProps) {
341
+ const { ink, paperColor, onPassageLayout, onError, style, ...rest } = props;
342
+ // The height is the engine's answer for the width, so it arrives with the first layout.
343
+ const [height, setHeight] = useState<number | undefined>(undefined);
344
+ return (
345
+ <NativeQvpPassageView
346
+ {...rest}
347
+ style={[{ height }, style]}
348
+ ink={css(ink)}
349
+ paperColor={css(paperColor)}
350
+ onPassageLayout={(e: NativeSyntheticEvent<PassageLayout>) => { setHeight(e.nativeEvent.height); onPassageLayout?.(e.nativeEvent); }}
351
+ onError={onError ? (e: NativeSyntheticEvent<{ message: string }>) => onError(e.nativeEvent) : undefined}
352
+ />
353
+ );
354
+ }
355
+
231
356
  // ── the module ───────────────────────────────────────────────────────────────────────────────
232
357
  const M = NativeModules.QvpModule as any;
358
+ // Before the first use: reading the constants of a missing module is a TypeError, and this
359
+ // message says what to do instead.
360
+ if (!M) throw new Error('@quran.ws/qvp-react-native: native module QvpModule not linked (Android only for now; see README)');
233
361
 
362
+ /** The native module's constants: the engine's name tables, and its defaults by camelCase name
363
+ * (`QVP_DEFAULT_*` in qvp.h; colours as unsigned 0xRRGGBBAA). */
364
+ interface NativeConstants { version?: string; formatVersion?: number; marks?: string[]; kinds?: string[]; families?: string[]; categories?: string[]; decorations?: string[]; divisions?: string[]; places?: string[]; defaults?: Record<string, number> }
234
365
  // The engine's name tables, read through the native module's constants; no table lives here.
235
- const NAMES = (M.getConstants?.() ?? {}) as { marks?: string[]; kinds?: string[]; families?: string[]; categories?: string[]; decorations?: string[]; divisions?: string[]; places?: string[] };
366
+ const NAMES = (M.getConstants?.() ?? {}) as NativeConstants;
236
367
  const KIND_NAMES: string[] = NAMES.kinds ?? [];
237
368
  const FAMILY_NAMES: string[] = NAMES.families ?? [];
238
369
  const CATEGORY_NAMES: string[] = NAMES.categories ?? [];
239
370
  const DECORATION_NAMES: string[] = NAMES.decorations ?? [];
240
371
  export const MARKS: string[] = NAMES.marks ?? [];
372
+ /** One default from the native module. No fallback: a missing key means the native module
373
+ * predates this package, and the error says so. */
374
+ const nativeDefault = (key: string): number => {
375
+ const v = NAMES.defaults?.[key];
376
+ if (typeof v !== 'number') throw new Error(`@quran.ws/qvp-react-native: native module QvpModule is older than this package (no default ${key}); rebuild the Android app`);
377
+ return v;
378
+ };
379
+ const SNAKE = (camel: string) => camel.replace(/([A-Z])/g, '_$1').toUpperCase();
380
+ /** The engine's defaults (QVP_DEFAULT_* in qvp.h), read from the native module: every one under
381
+ * its header name, and the ones a host reads most with their own doc comments. */
382
+ export const DEFAULTS: Readonly<Record<string, number>> & {
383
+ /** The size a scanned medallion takes when `ayahMarkScale` is 0, in rings. */
384
+ readonly AYAH_MARK_SCALE_SCAN: number;
385
+ /** How far a reflowed row much shorter than its neighbours opens towards them. */
386
+ readonly REFLOW_RELAX: number;
387
+ /** How far a reflowed row's gaps may open, in word gaps. */
388
+ readonly REFLOW_MAX_STRETCH: number;
389
+ /** Side padding of the selection band, page units. */
390
+ readonly SELECTION_PAD_X: number;
391
+ } = Object.freeze({
392
+ ...Object.fromEntries(Object.entries(NAMES.defaults ?? {}).map(([k, v]) => [SNAKE(k), v])),
393
+ AYAH_MARK_SCALE_SCAN: nativeDefault('ayahMarkScaleScan'),
394
+ REFLOW_RELAX: nativeDefault('reflowRelax'),
395
+ REFLOW_MAX_STRETCH: nativeDefault('reflowMaxStretch'),
396
+ SELECTION_PAD_X: nativeDefault('selectionPadX'),
397
+ });
241
398
  /** A name's id in a table; 255 when the table has no such name. */
242
399
  export type NameTable = 'marks' | 'kinds' | 'families' | 'categories' | 'decorations' | 'divisions' | 'places';
243
400
  const named = (v: string | number, names: string[]) => { if (typeof v === 'number') return v; const i = names.indexOf(v); return i < 0 ? 255 : i; };
244
401
  export function markId(name: string | number): number { return named(name, MARKS); }
245
- if (!M) throw new Error('@quran.ws/qvp-react-native: native module QvpModule not linked (Android only for now; see README)');
246
402
 
247
403
  export interface SearchOptions { form?: Form; mode?: 'includes' | 'exact' | 'prefix'; normalize?: boolean; looseMatch?: boolean; limit?: number }
248
404
  export interface TextOptions { form?: Form; wordSep?: string; lineSep?: string }
@@ -307,6 +463,18 @@ export const Qvp = {
307
463
  revealStepOf: (tag: number, i: number): Promise<number> => M.revealStepOf(tag, i),
308
464
  cropBounds: (tag: number, target: Target, opts?: CropOptions): Promise<CropBox | null> => M.cropBounds(tag, target, opts ?? null),
309
465
  cropSvg: (tag: number, target: Target, opts?: CropOptions): Promise<string | null> => M.cropSvg(tag, target, opts ? { ...opts, background: css(opts.background) } : null),
466
+ /** Dress the page in a set's ornaments; the readout, or null when the engine refused the spec. Replaces any previous dress. */
467
+ dress: (tag: number, set: QvpOrnaments | number, spec: DressSpec = {}): Promise<DressInfo | null> => M.dress(tag, ornamentsId(set), dressSpec(spec)),
468
+ /** Take the ornaments off: the printed rings and bands come back. */
469
+ undress: (tag: number): Promise<void> => M.undress(tag),
470
+ /** Clamp a view (scale and offsets in dp) over the content plus the dress overflow, as the engine does. An undressed page gets the plain clamp. */
471
+ dressClamp: (tag: number, view: ViewState, viewportW: number, viewportH: number): Promise<ViewState> => M.dressClamp(tag, view.scale, view.offsetX, view.offsetY, viewportW, viewportH),
472
+ /** For a host that scrolls the page itself: the view (offsets in dp) that shows the dressed box at `scale`, centred across `viewportW` dp (at x = 0 when wider) with its top at 0, and the box's `width` and `height` in dp, the size to give the page. */
473
+ dressView: (tag: number, scale: number, viewportW: number): Promise<{ view: ViewState; width: number; height: number }> => M.dressView(tag, scale, viewportW),
474
+ /** The readout, or null when the page is not dressed. */
475
+ dressInfo: (tag: number): Promise<DressInfo | null> => M.dressInfo(tag),
476
+ /** Counts up on every rebuild of the ornament layer: a new dress, and every layout. 0 when undressed. */
477
+ dressRevision: (tag: number): Promise<number> => M.dressRevision(tag),
310
478
 
311
479
  // engine-wide
312
480
  strip: (s: string): Promise<string> => M.arabic('strip', s),
@@ -341,31 +509,103 @@ export const Qvp = {
341
509
  atlasJuzOf: (id: number, s: number, a: number): Promise<number | null> => M.atlasJuzOf(id, s, a),
342
510
  atlasPagesOfJuz: (id: number, n: number): Promise<[number, number] | null> => M.atlasPagesOfJuz(id, n),
343
511
  atlasSearchSurahs: (id: number, text: string): Promise<AtlasSurah[]> => M.atlasSearchSurahs(id, text),
512
+
513
+ // ornament sets (ornaments.qvo)
514
+ loadOrnaments: (uri: string): Promise<number> => M.loadOrnaments(uri),
515
+ freeOrnaments: (id: number): Promise<void> => M.freeOrnaments(id),
516
+ ornamentCount: (id: number): Promise<number> => M.ornamentCount(id),
517
+ ornamentInfo: (id: number, index: number): Promise<Ornament | null> => M.ornamentInfo(id, index),
518
+ ornamentPart: (id: number, index: number, part: number): Promise<OrnamentPart | null> => M.ornamentPart(id, index, part),
519
+ ornamentList: (id: number): Promise<Ornament[]> => M.ornamentList(id),
520
+ /** The index of the ornament of `kind` in `style`, or -1. */
521
+ ornamentFind: (id: number, kind: OrnamentKind, style: string): Promise<number> => M.ornamentFind(id, kind, style),
344
522
  };
345
523
 
346
524
  /** Cross-page lookup (atlas.qva). `const atlas = await QvpAtlas.load('asset://pages/atlas.qva')`. */
347
525
  export class QvpAtlas {
348
526
  private constructor(public readonly id: number) {}
527
+ private freed = false;
528
+ /** The native id. Throws once the atlas is freed, so every call after `free()` rejects. */
529
+ private get h(): number { if (this.freed) throw new Error('QvpAtlas was freed'); return this.id; }
349
530
  static async load(uri: string): Promise<QvpAtlas> { return new QvpAtlas(await Qvp.loadAtlas(uri)); }
350
- free() { return Qvp.freeAtlas(this.id); }
351
- pageOf(s: number, a: number) { return Qvp.atlasPageOf(this.id, s, a); }
352
- pageRange(page: number) { return Qvp.atlasPageRange(this.id, page); }
353
- pageCount() { return Qvp.atlasPageCount(this.id); }
354
- surah(n: number) { return Qvp.atlasSurah(this.id, n); }
355
- surahs() { return Qvp.atlasSurahs(this.id); }
356
- pageOfSurah(n: number) { return Qvp.atlasPageOfSurah(this.id, n); }
357
- division(division: DivisionKind, n: number) { return Qvp.atlasDivision(this.id, division, n); }
358
- juz(n: number) { return Qvp.atlasDivision(this.id, 'juz', n); }
359
- hizb(n: number) { return Qvp.atlasDivision(this.id, 'hizb', n); }
360
- rubuAlHizb(n: number) { return Qvp.atlasDivision(this.id, 'rubuAlHizb', n); }
361
- divisionOf(division: DivisionKind, s: number, a: number) { return Qvp.atlasDivisionOf(this.id, division, s, a); }
362
- juzOf(s: number, a: number) { return Qvp.atlasJuzOf(this.id, s, a); }
363
- pagesOfJuz(n: number) { return Qvp.atlasPagesOfJuz(this.id, n); }
364
- searchSurahs(text: string) { return Qvp.atlasSearchSurahs(this.id, text); }
531
+ /** Free the native atlas. A second call does nothing. */
532
+ async free(): Promise<void> { if (this.freed) return; this.freed = true; await Qvp.freeAtlas(this.id); }
533
+ async pageOf(s: number, a: number) { return Qvp.atlasPageOf(this.h, s, a); }
534
+ async pageRange(page: number) { return Qvp.atlasPageRange(this.h, page); }
535
+ async pageCount() { return Qvp.atlasPageCount(this.h); }
536
+ async surah(n: number) { return Qvp.atlasSurah(this.h, n); }
537
+ async surahs() { return Qvp.atlasSurahs(this.h); }
538
+ async pageOfSurah(n: number) { return Qvp.atlasPageOfSurah(this.h, n); }
539
+ async division(division: DivisionKind, n: number) { return Qvp.atlasDivision(this.h, division, n); }
540
+ async juz(n: number) { return Qvp.atlasDivision(this.h, 'juz', n); }
541
+ async hizb(n: number) { return Qvp.atlasDivision(this.h, 'hizb', n); }
542
+ async rubuAlHizb(n: number) { return Qvp.atlasDivision(this.h, 'rubuAlHizb', n); }
543
+ async divisionOf(division: DivisionKind, s: number, a: number) { return Qvp.atlasDivisionOf(this.h, division, s, a); }
544
+ async juzOf(s: number, a: number) { return Qvp.atlasJuzOf(this.h, s, a); }
545
+ async pagesOfJuz(n: number) { return Qvp.atlasPagesOfJuz(this.h, n); }
546
+ async searchSurahs(text: string) { return Qvp.atlasSearchSurahs(this.h, text); }
547
+ }
548
+
549
+ /**
550
+ * An ornament set (ornaments.qvo): the medallions, bands and borders of other mushafs and fonts.
551
+ * None of these outlines is part of a page, and each one carries its own licence.
552
+ * `const set = await QvpOrnaments.load('asset://pages/ornaments.qvo')`.
553
+ */
554
+ export class QvpOrnaments {
555
+ /** Every ornament of the set, in the set's order. */
556
+ readonly count: number;
557
+ private constructor(public readonly id: number, public readonly list: Ornament[]) { this.count = list.length; }
558
+ private freed = false;
559
+ /** Load a set from a URI (the same schemes as `pageUri`; `base64:…` for bytes in hand). */
560
+ static async load(uri: string): Promise<QvpOrnaments> {
561
+ const id = await Qvp.loadOrnaments(uri);
562
+ return new QvpOrnaments(id, await Qvp.ornamentList(id));
563
+ }
564
+ /** Free the native set. A second call does nothing. `list`, `ofKind` and `styles` stay readable. */
565
+ async free(): Promise<void> { if (this.freed) return; this.freed = true; await Qvp.freeOrnaments(this.id); }
566
+ /** The ornament of `kind` in `style`, or null; the engine looks it up. Rejects once the set is freed. */
567
+ async find(kind: OrnamentKind, style: string): Promise<Ornament | null> {
568
+ if (this.freed) throw new Error('QvpOrnaments was freed');
569
+ const i = await Qvp.ornamentFind(this.id, kind, style);
570
+ return i < 0 ? null : this.list[i] ?? null;
571
+ }
572
+ /** The ornaments of one kind. */
573
+ ofKind(kind: OrnamentKind): Ornament[] { return this.list.filter(o => o && o.kind === kind); }
574
+ /** Every style in the set with the ornament it has of each kind or null, in the set's order. */
575
+ styles(): OrnamentStyle[] {
576
+ const out: OrnamentStyle[] = [];
577
+ const key = { ayah_mark: 'ayahMark', surah_header: 'surahHeader', page_frame: 'pageFrame' } as const;
578
+ for (const o of this.list) {
579
+ if (!o) continue;
580
+ let s = out.find(x => x.style === o.style);
581
+ if (!s) { s = { style: o.style, riwayah: o.riwayah, lineage: o.lineage, ayahMark: null, surahHeader: null, pageFrame: null }; out.push(s); }
582
+ s[key[o.kind]] = o;
583
+ }
584
+ return out;
585
+ }
586
+ }
587
+ const ornamentsId = (set: QvpOrnaments | number) => (typeof set === 'number' ? set : set.id);
588
+ /** A spec as the native side reads it: ornaments as indices or style names, colours as '#rrggbbaa'. */
589
+ function dressSpec(spec: DressSpec): object {
590
+ const ref = (v: OrnamentRef | undefined) => (v == null ? null : typeof v === 'object' ? v.index : v);
591
+ return {
592
+ // A kind key that is left out takes the style; a kind key set to null is none. A style name
593
+ // stays a name: the native side asks the engine for the ornament of that kind.
594
+ ayahMark: ref(spec.ayahMark === undefined ? spec.style : spec.ayahMark),
595
+ surahHeader: ref(spec.surahHeader === undefined ? spec.style : spec.surahHeader),
596
+ pageFrame: ref(spec.pageFrame === undefined ? spec.style : spec.pageFrame),
597
+ gap: spec.gap, bandGap: spec.bandGap, ayahMarkScale: spec.ayahMarkScale, pageFrameScale: spec.pageFrameScale,
598
+ lineArt: spec.lineArt === true ? ['ayah_mark', 'surah_header', 'page_frame'] : Array.isArray(spec.lineArt) ? spec.lineArt : [],
599
+ // A colour that does not parse is skipped, not sent as a transparent repaint.
600
+ colors: (spec.colors ?? []).flatMap(([o, part, colour]) => {
601
+ const c = css(colour);
602
+ return c === undefined ? [] : [[typeof o === 'object' ? o.index : o, part, c]];
603
+ }),
604
+ };
365
605
  }
366
606
 
367
607
  type Tail<F> = F extends (tag: number, ...rest: infer R) => infer Ret ? (...rest: R) => Ret : never;
368
- const pageMethods = ['info', 'words', 'word', 'ayahs', 'lines', 'decorations', 'findWord', 'targetWords', 'wordForm', 'hasForm', 'attachWords', 'surahs', 'divisions', 'surahHeaders', 'surahHeadersView', 'ayahMarks', 'rosettes', 'sajdahs', 'ayahKeys', 'ayahWordCount', 'reciteMap', 'wordLabel', 'ayahLabel', 'text', 'search', 'citation', 'hitTestExact', 'hitTest', 'hitTestExactView', 'hitTestView', 'layoutLineSpacingToFill', 'layoutWastedFraction', 'layoutPrintedHeight', 'grid', 'wordBoundsView', 'currentLayout', 'relayout', 'resetView', 'stats', 'select', 'clearSelection', 'selection', 'selectionText', 'unmaskNext', 'maskBack', 'unmaskWord', 'maskWord', 'unmaskAll', 'maskAll', 'maskHidden', 'maskWords', 'revealStepCount', 'revealPosition', 'revealStepOf', 'cropBounds', 'cropSvg'] as const;
608
+ const pageMethods = ['info', 'words', 'word', 'ayahs', 'lines', 'decorations', 'findWord', 'targetWords', 'wordForm', 'hasForm', 'attachWords', 'surahs', 'divisions', 'surahHeaders', 'surahHeadersView', 'ayahMarks', 'rosettes', 'sajdahs', 'ayahKeys', 'ayahWordCount', 'reciteMap', 'wordLabel', 'ayahLabel', 'text', 'search', 'citation', 'hitTestExact', 'hitTest', 'hitTestExactView', 'hitTestView', 'layoutLineSpacingToFill', 'layoutWastedFraction', 'layoutPrintedHeight', 'grid', 'wordBoundsView', 'currentLayout', 'relayout', 'resetView', 'stats', 'select', 'clearSelection', 'selection', 'selectionText', 'unmaskNext', 'maskBack', 'unmaskWord', 'maskWord', 'unmaskAll', 'maskAll', 'maskHidden', 'maskWords', 'revealStepCount', 'revealPosition', 'revealStepOf', 'cropBounds', 'cropSvg', 'dress', 'undress', 'dressClamp', 'dressView', 'dressInfo', 'dressRevision'] as const;
369
609
  type PageMethod = (typeof pageMethods)[number];
370
610
  export type PageApi = { [K in PageMethod]: Tail<(typeof Qvp)[K]> };
371
611
  function bindPage(tag: () => number): PageApi {