@quran.ws/qvp-react-native 0.7.0 → 0.9.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.
Files changed (32) hide show
  1. package/README.md +86 -32
  2. package/android/build.gradle +16 -8
  3. package/android/src/main/java/ws/quran/qvp/rn/Codes.kt +34 -0
  4. package/android/src/main/java/ws/quran/qvp/rn/Marshal.kt +78 -30
  5. package/android/src/main/java/ws/quran/qvp/rn/QvpModule.kt +105 -50
  6. package/android/src/main/java/ws/quran/qvp/rn/QvpPageViewManager.kt +1 -0
  7. package/android/src/main/java/ws/quran/qvp/rn/QvpRnPageView.kt +55 -14
  8. package/android/src/main/java/ws/quran/qvp/rn/QvpRnWords.kt +26 -0
  9. package/ios/QvpModule.m +167 -0
  10. package/ios/QvpModule.swift +508 -0
  11. package/ios/QvpRnBytes.swift +66 -0
  12. package/ios/QvpRnCodes.swift +33 -0
  13. package/ios/QvpRnMarshal.swift +360 -0
  14. package/ios/QvpRnPageView.swift +467 -0
  15. package/ios/QvpRnPassageView.swift +160 -0
  16. package/ios/vendor/QvpEngine.json +4 -0
  17. package/ios/vendor/QvpKit/QvpDress.swift +390 -0
  18. package/ios/vendor/QvpKit/QvpEngine.swift +55 -0
  19. package/ios/vendor/QvpKit/QvpPage.swift +469 -0
  20. package/ios/vendor/QvpKit/QvpPageCache.swift +176 -0
  21. package/ios/vendor/QvpKit/QvpPageCanvas.swift +1031 -0
  22. package/ios/vendor/QvpKit/QvpPageView.swift +711 -0
  23. package/ios/vendor/QvpKit/QvpPassage.swift +240 -0
  24. package/ios/vendor/QvpKit/QvpViewPolicy.swift +26 -0
  25. package/ios/vendor/QvpKit/QvpZoom.swift +200 -0
  26. package/ios/vendor/QvpKit/QvpZoomSpring.swift +22 -0
  27. package/ios/vendor/QvpKit/Types.swift +440 -0
  28. package/ios/vendor-qvpkit.sh +36 -0
  29. package/package.json +10 -3
  30. package/qvp-react-native.podspec +97 -0
  31. package/src/codes.ts +33 -0
  32. package/src/index.tsx +171 -55
package/README.md CHANGED
@@ -1,10 +1,13 @@
1
1
  # @quran.ws/qvp-react-native
2
2
 
3
- React Native wrapper for the QVP vector mushaf engine. Android-first: a native view
4
- (`<QvpPageView />`) hosting the Kotlin library's `QvpPageView` (`ws.quran.qvp`,
5
- `packages/android/qvp`, JNI over `crates/qvp-ffi/include/qvp.h`) plus a promise-based module
6
- (`QvpModule`) for queries. The wrapper is *thin*: no hit-testing, layout or styling logic in JS or
7
- in the module — it marshals props/targets/selectors and reconciles declarative arrays against engine
3
+ React Native wrapper for the QVP vector mushaf engine, on Android and iOS. Each platform has
4
+ a native view (`<QvpPageView />`) and a promise-based module (`QvpModule`) for queries. On
5
+ Android the view hosts the Kotlin library's `QvpPageView` (`ws.quran.qvp`,
6
+ `packages/android/qvp`, JNI over `crates/qvp-ffi/include/qvp.h`). On iOS it hosts QvpKit's
7
+ `QvpPageView` (`packages/ios/QvpKit`, Swift over the same header). The two modules have the
8
+ same method names and give the same result shapes, so the JavaScript side has no platform
9
+ branch. The wrapper is *thin*: no hit-testing, layout or styling logic in JS or in the
10
+ module — it marshals props/targets/selectors and reconciles declarative arrays against engine
8
11
  handles. Names follow `docs/API.md`. **The package ships no page data.**
9
12
 
10
13
  ## Install
@@ -13,26 +16,60 @@ handles. Names follow `docs/API.md`. **The package ships no page data.**
13
16
  npm install @quran.ws/qvp-react-native # or a file:/git dependency inside the monorepo
14
17
  ```
15
18
 
16
- Android needs the Kotlin library. Preferred: include it as a Gradle project in your app's
17
- `android/settings.gradle` (this is what `../example` does):
19
+ Android needs the Kotlin library `ws.quran.qvp`. The module finds it in one of three ways,
20
+ and the first that applies wins:
18
21
 
19
- ```groovy
20
- include ':qvp'
21
- project(':qvp').projectDir = file('<repo>/packages/android/qvp') // e.g. '../../../android/qvp'
22
- ```
22
+ 1. Your app's `android/settings.gradle` includes the library as the Gradle project `:qvp`.
23
+ The module then depends on `project(':qvp')`. `../example` does this:
24
+
25
+ ```groovy
26
+ include ':qvp'
27
+ project(':qvp').projectDir = file('<repo>/packages/android/qvp') // e.g. '../../../android/qvp'
28
+ ```
29
+
30
+ 2. The Gradle property `qvpAndroidDir` names a checkout of `packages/android/qvp`. The module
31
+ compiles the library's Kotlin and JNI sources from that folder.
32
+ 3. Otherwise the module depends on `ws.quran:qvp-android` from Maven Central, at the version
33
+ of this package. An app that installs the package from npm needs nothing more. To use a
34
+ different library version, set the Gradle property `qvpVersion`, for example
35
+ `qvpVersion=0.9.0` in `android/gradle.properties`.
36
+
37
+ The Maven Central library holds the engine. In ways 1 and 2 the engine comes from
38
+ `packages/android/qvp/prebuilt/<abi>/libqvp_ffi.a`. Make it once with
39
+ `scripts/build-engine-android.sh` from the repository root.
40
+
41
+ iOS needs CocoaPods. React Native's autolinking finds `qvp-react-native.podspec`, so run
42
+ `pod install` in your app's `ios` folder after `npm install`. The pod compiles QvpKit's Swift
43
+ sources with the module and links the engine, `QvpEngine.xcframework`. It takes the engine in
44
+ one of three ways, and the first that applies wins:
45
+
46
+ 1. Inside this repository, as `../example` does, the pod takes the XCFramework that
47
+ `scripts/build-engine-ios.sh` writes at `packages/ios/QvpKit/QvpEngine.xcframework`. It
48
+ copies QvpKit's sources from `packages/ios/QvpKit` at each `pod install`, so run
49
+ `pod install` again after you change them.
50
+ 2. The environment variable `QVP_ENGINE_XCFRAMEWORK` names an XCFramework to link, for
51
+ example an engine that you built yourself:
52
+
53
+ ```sh
54
+ QVP_ENGINE_XCFRAMEWORK=/path/to/QvpEngine.xcframework pod install
55
+ ```
23
56
 
24
- The module then depends on `project(':qvp')`. If `:qvp` is not included, the module compiles the
25
- library's Kotlin + JNI sources itself from `qvpAndroidDir` (Gradle property; default
26
- `../../../android/qvp`, right for the monorepo). Either way the engine comes from
27
- `packages/android/qvp/prebuilt/<abi>/libqvp_ffi.a` — produce it once with
28
- `scripts/build-engine-android.sh` from the repo root.
57
+ 3. Otherwise `pod install` downloads the XCFramework of this package's release from GitHub,
58
+ the one that SwiftPM takes for QvpKit, and checks its SHA-256 checksum. An app that
59
+ installs the package from npm needs nothing more. The download needs `curl` and `unzip`.
60
+
61
+ The pod and QvpKit through SwiftPM each link the engine. Do not use both in one app: the
62
+ engine's C symbols would be defined twice.
29
63
 
30
64
  Requirements: RN ≥ 0.76 (legacy view manager / native module through the interop layer, verified on
31
- 0.87 with the New Architecture), minSdk 24, NDK 27, CMake 3.22.
65
+ 0.87 with the New Architecture). Android: minSdk 24, and ways 1 and 2 also need NDK 27 and
66
+ CMake 3.22. iOS: iOS 15.1, CocoaPods and Xcode 16.
32
67
 
33
68
  Page data: `cargo run -p qvp-convert --release -- batch pages dist/pages` → `NNN.qvp`,
34
69
  `NNN.words.json`, `atlas.qva`. Put them wherever you like (assets, files dir, downloads) and pass
35
- URIs: `asset://pages/042.qvp`, `file:///…`, `/abs/path`, or `base64:…`.
70
+ URIs: `asset://pages/042.qvp`, `file:///…`, `/abs/path`, or `base64:…`. On iOS an `asset://`
71
+ URI names a file in the app bundle: `asset://pages/042.qvp` is `pages/042.qvp` under the
72
+ bundle's resources, for example a folder reference named `pages`.
36
73
 
37
74
  ## The view
38
75
 
@@ -80,7 +117,7 @@ Reconciliation: each `highlights` entry maps to one engine handle. A new id →
80
117
  changes (`null` → `revealStop`). When `pageUri` changes, the old page is freed and every declarative
81
118
  prop is re-applied to the new page.
82
119
 
83
- Gestures are the Kotlin view's: tap → gap-aware `hitTestView` → `onWordTap` / `onDecorationTap` /
120
+ Gestures are the native view's (Kotlin or QvpKit): tap → gap-aware `hitTestView` → `onWordTap` / `onDecorationTap` /
84
121
  `onEmptyTap`; long-press-drag → engine `select` with a band in `LAYER.SELECTION`; pinch / pan;
85
122
  double-tap resets. Props `selectionEnabled`, `zoomEnabled`, `hitMaxDistance`, `selectionBand`.
86
123
 
@@ -146,7 +183,7 @@ await qvp.search('الرحمان', { mode: 'includes' }); // [{word, wordKey
146
183
  await qvp.text('2:255', { form: 'search', wordSep: ' ' });
147
184
  await qvp.targetWords('line:7'); qvp.findWord(2, 255, 3); qvp.wordForm(i, 'rasm_imlai'); qvp.hasForm('qpc');
148
185
  await qvp.attachWords(jsonString); // when you do not use the wordsUri prop
149
- await qvp.surahs(); qvp.divisions(); qvp.ayahMarks(); qvp.rosettes(); qvp.sajdahs(); qvp.ayahKeys();
186
+ await qvp.surahs(); qvp.divisions(); qvp.ayahMarks(); qvp.ayahMarksView(); qvp.rosettes(); qvp.sajdahs(); qvp.ayahKeys();
150
187
  await qvp.ayahWordCount(2, 255); qvp.reciteMap(2, 255, 4); qvp.wordLabel(i); qvp.ayahLabel(ayahIndex);
151
188
  await qvp.citation([12, 13, 14]);
152
189
  await qvp.cropSvg('2:255', { pad: 3, keepMarkers: true, background: '#fffdf7' }); qvp.cropBounds(target);
@@ -169,9 +206,22 @@ await atlas.pagesOfJuz(30); atlas.searchSurahs('cow' | 'البقرة' | '2'); at
169
206
  // tag-level equivalents: Qvp.atlasPageOf(id, s, a), Qvp.atlasSearchSurahs(id, text), Qvp.atlasPagesOfJuz(id, n), Qvp.atlasJuzOf(id, s, a), …
170
207
  ```
171
208
 
172
- All page calls run on the UI thread (where the view draws), so the engine is never touched from two
173
- threads. Only `maskHidden`, `unmask` (via the `mask` prop), `unmaskNext` etc. mutate state; queries are
174
- microseconds.
209
+ On iOS, a view method takes and returns points, where Android takes dp.
210
+
211
+ `layoutLineSpacingToFill`, `layoutWastedFraction` and `layoutPrintedHeight` measure the
212
+ printed page. Both platforms pass the engine the view's spec before the reader's zoom.
213
+
214
+ The module runs a call on one of two threads (on iOS, two queues). Its own query thread runs each call that reads only
215
+ what a page fixed when it loaded: `info`, `words`, `word`, `ayahs`, `lines`, `decorations`, `findWord`,
216
+ `targetWords`, `wordForm`, `hasForm`, the metadata calls except `surahHeaders`, `surahHeadersView`
217
+ and `ayahMarksView`, `text`, `search`, `citation`, `cropBounds`, `grid`, the engine-wide helpers and
218
+ the atlas. A long call there does not hold up a frame. The view keeps its page open until such a call returns. Every other
219
+ call reads or changes the layout, the view, the styles or the page state, and runs on the UI thread
220
+ (the main thread on iOS), where the view draws. `attachWords` runs on the UI thread after the queries queued before it, and the
221
+ queries queued after it wait for it.
222
+
223
+ `words` builds each word's record once per page: its forms, its label and the names of its paths.
224
+ A later call sends the same records again, and `attachWords` drops them.
175
225
 
176
226
  ## Layout of this package
177
227
 
@@ -185,15 +235,19 @@ android/src/main/java/ws/quran/qvp/rn/
185
235
  QvpRnBytes.kt the bytes a URI names (asset, file, path, base64)
186
236
  QvpModule.kt ReactContextBaseJavaModule: page queries by react tag, engine helpers, atlas, ornament sets
187
237
  Marshal.kt JS shapes ↔ Kotlin types (targets, selectors, styles, records)
238
+ QvpRnWords.kt each word's record, built once per page
239
+ Codes.kt QVP_TARGET_* and QVP_SELECTOR_* by name (scripts/gen-rn-enums.py writes it)
188
240
  QvpPackage.kt
241
+ qvp-react-native.podspec the iOS pod: the module, QvpKit's sources and QvpEngine.xcframework
242
+ ios/
243
+ QvpModule.m what React Native sees: the module's methods, the two view managers' props and events
244
+ QvpModule.swift the module over QvpKit, with the method names of QvpModule.kt
245
+ QvpRnPageView.swift hosts QvpKit's QvpPageView: page loading, prop → handle reconciliation, events
246
+ QvpRnPassageView.swift loads the pages, lays the passage out at the view's width, draws it, reports the layout
247
+ QvpRnMarshal.swift JS shapes ↔ QvpKit types, key for key as Marshal.kt
248
+ QvpRnBytes.swift the bytes a URI names, and each word's record, built once per page
249
+ QvpRnCodes.swift QVP_TARGET_* and QVP_SELECTOR_* by name (scripts/gen-rn-enums.py writes it)
250
+ vendor-qvpkit.sh copies QvpKit's sources and the XCFramework's URL and checksum into ios/vendor (prepack)
189
251
  src/index.tsx typed API: <QvpPageView/>, <QvpPassageView/>, useQvp(), Qvp, QvpAtlas, QvpOrnaments, Sel, T, constants
252
+ src/codes.ts the same codes for T and Sel (scripts/gen-rn-enums.py writes it)
190
253
  ```
191
-
192
- ## iOS — TODO
193
-
194
- Not implemented (no macOS in the build environment). The iOS side mirrors the Android module over the
195
- same `qvp.h`: a Swift `QvpPage`/`QvpAtlas` over `libqvp_ffi.a` (build with
196
- `cargo build -p qvp-ffi --release --target aarch64-apple-ios[-sim]`), a `UIView` renderer with the
197
- same draw order (highlight bands → cached base ink → styled ink → mask boxes, `tick(now)` per
198
- `CADisplayLink` frame), an `RCTViewManager` exposing the props above with the same reconciliation, and
199
- an `RCTBridgeModule` with the same method names. `src/index.tsx` needs no changes.
@@ -1,12 +1,16 @@
1
1
  // @quran.ws/qvp-react-native — Android module. Thin: marshalling + handle reconciliation over the Kotlin
2
2
  // library `ws.quran.qvp` (packages/android/qvp), which is JNI over crates/qvp-ffi/include/qvp.h.
3
3
  //
4
- // Linking the Kotlin library, two ways:
5
- // 1. (preferred) the app's settings.gradle includes it as a Gradle project:
4
+ // The module links the Kotlin library in one of three ways. The first that applies wins:
5
+ // 1. The app's settings.gradle includes the library as the Gradle project `:qvp`:
6
6
  // include(":qvp"); project(":qvp").projectDir = file("<repo>/packages/android/qvp")
7
- // and this module depends on `project(":qvp")`.
8
- // 2. otherwise this module compiles the library's Kotlin + JNI sources straight from `qvpAndroidDir`
9
- // (gradle property; default: ../../../android/qvp inside the monorepo). Same code, one AAR.
7
+ // The module then depends on `project(":qvp")`. The example in this repository does this.
8
+ // 2. The Gradle property `qvpAndroidDir` names a checkout of packages/android/qvp. The module
9
+ // compiles the library's Kotlin and JNI sources from that folder.
10
+ // 3. Otherwise the module depends on `ws.quran:qvp-android` from Maven Central. This is the
11
+ // way for an app that installs the package from npm. The version is the version in this
12
+ // package's package.json, so the two stay in step. The Gradle property `qvpVersion` sets
13
+ // a different version.
10
14
  buildscript {
11
15
  if (project == rootProject) {
12
16
  repositories { google(); mavenCentral() }
@@ -22,19 +26,22 @@ apply plugin: "org.jetbrains.kotlin.android"
22
26
 
23
27
  def safeExtGet(prop, fallback) { rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback }
24
28
  def qvpProject = findProject(":qvp")
25
- def qvpDir = file(rootProject.findProperty("qvpAndroidDir") ?: "$projectDir/../../../android/qvp")
29
+ def qvpAndroidDir = rootProject.findProperty("qvpAndroidDir")
30
+ def qvpDir = qvpProject == null && qvpAndroidDir != null ? file(qvpAndroidDir) : null
31
+ def qvpVersion = rootProject.findProperty("qvpVersion") ?:
32
+ new groovy.json.JsonSlurper().parse(file("$projectDir/../package.json")).version
26
33
 
27
34
  android {
28
35
  namespace "ws.quran.qvp.rn"
29
36
  compileSdk safeExtGet("compileSdkVersion", 35)
30
37
  defaultConfig {
31
38
  minSdkVersion safeExtGet("minSdkVersion", 24)
32
- if (qvpProject == null) {
39
+ if (qvpDir != null) {
33
40
  externalNativeBuild { cmake { arguments "-DANDROID_STL=none" } }
34
41
  ndk { abiFilters "arm64-v8a", "x86_64", "armeabi-v7a" }
35
42
  }
36
43
  }
37
- if (qvpProject == null) {
44
+ if (qvpDir != null) {
38
45
  ndkVersion safeExtGet("ndkVersion", "27.2.12479018")
39
46
  externalNativeBuild { cmake { path file("$qvpDir/src/main/cpp/CMakeLists.txt"); version "3.22.1" } }
40
47
  sourceSets { main { kotlin.srcDirs += "$qvpDir/src/main/kotlin"; java.srcDirs += "$qvpDir/src/main/kotlin" } }
@@ -50,5 +57,6 @@ dependencies {
50
57
  // version pinned by the React Native Gradle Plugin of the consuming app
51
58
  implementation "com.facebook.react:react-android"
52
59
  if (qvpProject != null) implementation project(":qvp")
60
+ else if (qvpDir == null) implementation "ws.quran:qvp-android:$qvpVersion"
53
61
  testImplementation "junit:junit:4.13.2"
54
62
  }
@@ -0,0 +1,34 @@
1
+ // Generated by scripts/gen-rn-enums.py from crates/qvp-ffi/include/qvp.h. Do not edit.
2
+ package ws.quran.qvp.rn
3
+
4
+ /** The QVP_TARGET_* and QVP_SELECTOR_* codes, and each code by its JavaScript name. */
5
+ object Codes {
6
+ const val TARGET_PAGE = 0
7
+ const val TARGET_WORD = 1
8
+ const val TARGET_WORDS = 2
9
+ const val TARGET_AYAH = 3
10
+ const val TARGET_AYAH_RANGE = 4
11
+ const val TARGET_LINE = 5
12
+ const val TARGET_SURAH = 6
13
+ const val TARGET_RANGE = 7
14
+ /** QVP_TARGET_*: the kind of a target, by name. */
15
+ val TARGETS: Map<String, Int> = mapOf("page" to TARGET_PAGE, "word" to TARGET_WORD, "words" to TARGET_WORDS, "ayah" to TARGET_AYAH, "ayahRange" to TARGET_AYAH_RANGE, "line" to TARGET_LINE, "surah" to TARGET_SURAH, "range" to TARGET_RANGE)
16
+ const val SELECTOR_PAGE = 0
17
+ const val SELECTOR_PATH = 1
18
+ const val SELECTOR_WORD_PATH = 2
19
+ const val SELECTOR_WORD_MARK = 3
20
+ const val SELECTOR_WORD_MARK_NAMED = 4
21
+ const val SELECTOR_WORD_BODY = 5
22
+ const val SELECTOR_WORD_MARKS = 6
23
+ const val SELECTOR_WORD = 7
24
+ const val SELECTOR_AYAH = 8
25
+ const val SELECTOR_LINE = 9
26
+ const val SELECTOR_MARK = 10
27
+ const val SELECTOR_CATEGORY = 11
28
+ const val SELECTOR_FAMILY = 12
29
+ const val SELECTOR_KIND = 13
30
+ const val SELECTOR_DECORATION = 14
31
+ const val SELECTOR_DECORATION_INDEX = 15
32
+ /** QVP_SELECTOR_*: the kind of a selector, by name. */
33
+ val SELECTORS: Map<String, Int> = mapOf("page" to SELECTOR_PAGE, "path" to SELECTOR_PATH, "wordPath" to SELECTOR_WORD_PATH, "wordMark" to SELECTOR_WORD_MARK, "wordMarkNamed" to SELECTOR_WORD_MARK_NAMED, "wordBody" to SELECTOR_WORD_BODY, "wordMarks" to SELECTOR_WORD_MARKS, "word" to SELECTOR_WORD, "ayah" to SELECTOR_AYAH, "line" to SELECTOR_LINE, "mark" to SELECTOR_MARK, "category" to SELECTOR_CATEGORY, "family" to SELECTOR_FAMILY, "kind" to SELECTOR_KIND, "decoration" to SELECTOR_DECORATION, "decorationIndex" to SELECTOR_DECORATION_INDEX)
34
+ }
@@ -13,8 +13,8 @@ import ws.quran.qvp.Target
13
13
  * styling decisions live here — every call goes to [QvpPage] / [QvpAtlas], which go to the engine.
14
14
  *
15
15
  * Targets from JS: "page" | "2:255" | "2:255:3" | "2:255-257" | "line:7" | "surah:2" | word index |
16
- * [word indices] | {target, a, b, c, words} (target = QVP_TARGET_* or its name).
17
- * Selectors from JS: {selector, a, b, c} (selector = QVP_SELECTOR_* or its name). Colours: '#rgb' | '#rrggbb' | '#rrggbbaa'.
16
+ * [word indices] | {target, a, b, c, words} (target = QVP_TARGET_* or its name in [Codes]).
17
+ * Selectors from JS: {selector, a, b, c} (selector = QVP_SELECTOR_* or its name in [Codes]). Colours: '#rgb' | '#rrggbb' | '#rrggbbaa'.
18
18
  */
19
19
  object Marshal {
20
20
  // ── colours ──
@@ -36,11 +36,10 @@ object Marshal {
36
36
  else -> IntArray(0)
37
37
  }
38
38
 
39
- private val TARGET_KINDS = listOf("page", "word", "words", "ayah", "ayahRange", "line", "surah", "range")
40
- private val SEL_KINDS = listOf("page", "path", "wordPath", "wordMark", "wordMarkNamed", "wordBody", "wordMarks", "word", "ayah", "line", "mark", "category", "family", "kind", "decoration", "decorationIndex")
41
- private fun kindOf(v: Any?, names: List<String>): Int = when (v) {
39
+ /** A code given as a number, or by its name in [names] (or as a numeral); -1 when neither. */
40
+ private fun codeOf(v: Any?, names: Map<String, Int>): Int = when (v) {
42
41
  is Number -> v.toInt()
43
- is String -> names.indexOf(v).let { if (it >= 0) it else v.toIntOrNull() ?: -1 }
42
+ is String -> names[v] ?: v.toIntOrNull() ?: -1
44
43
  else -> -1
45
44
  }
46
45
 
@@ -53,9 +52,15 @@ object Marshal {
53
52
  is IntArray -> Target.words(v)
54
53
  is Map<*, *> -> {
55
54
  val a = num(v["a"]) ?: 0; val b = num(v["b"]) ?: 0; val c = num(v["c"]) ?: 0
56
- when (kindOf(v["target"], TARGET_KINDS)) {
57
- 0 -> Target.page(); 1 -> Target.word(a); 2 -> Target.words(ints(v["words"] ?: v["a"]))
58
- 3 -> Target.ayah(a, b); 4 -> Target.ayahRange(a, b, c); 5 -> Target.line(a); 6 -> Target.surah(a); 7 -> Target.range(a, b)
55
+ when (codeOf(v["target"], Codes.TARGETS)) {
56
+ Codes.TARGET_PAGE -> Target.page()
57
+ Codes.TARGET_WORD -> Target.word(a)
58
+ Codes.TARGET_WORDS -> Target.words(ints(v["words"] ?: v["a"]))
59
+ Codes.TARGET_AYAH -> Target.ayah(a, b)
60
+ Codes.TARGET_AYAH_RANGE -> Target.ayahRange(a, b, c)
61
+ Codes.TARGET_LINE -> Target.line(a)
62
+ Codes.TARGET_SURAH -> Target.surah(a)
63
+ Codes.TARGET_RANGE -> Target.range(a, b)
59
64
  else -> Target.words(IntArray(0))
60
65
  }
61
66
  }
@@ -66,34 +71,57 @@ object Marshal {
66
71
  fun selector(v: Any?): Selector? {
67
72
  val m = v as? Map<*, *> ?: return null
68
73
  val a = num(m["a"]) ?: 0; val b = num(m["b"]) ?: 0; val c = num(m["c"]) ?: 0
69
- return when (kindOf(m["selector"], SEL_KINDS)) {
70
- 0 -> Selector.page(); 1 -> Selector.path(a); 2 -> Selector.wordPath(a, b); 3 -> Selector.wordMark(a, b)
71
- 4 -> Selector.wordMarkNamed(a, (m["mark"] as? String) ?: QvpEngine.markName(b), c)
72
- 5 -> Selector.wordBody(a); 6 -> Selector.wordMarks(a); 7 -> Selector.word(a); 8 -> Selector.ayah(a, b); 9 -> Selector.line(a)
73
- 10 -> (m["mark"] as? String)?.let { Selector.mark(it) } ?: Selector.mark(a)
74
- 11 -> Selector.category(a); 12 -> Selector.family(a); 13 -> Selector.kind(a); 14 -> Selector.decoration(a); 15 -> Selector.decorationIndex(a)
74
+ return when (codeOf(m["selector"], Codes.SELECTORS)) {
75
+ Codes.SELECTOR_PAGE -> Selector.page()
76
+ Codes.SELECTOR_PATH -> Selector.path(a)
77
+ Codes.SELECTOR_WORD_PATH -> Selector.wordPath(a, b)
78
+ Codes.SELECTOR_WORD_MARK -> Selector.wordMark(a, b)
79
+ Codes.SELECTOR_WORD_MARK_NAMED -> Selector.wordMarkNamed(a, (m["mark"] as? String) ?: QvpEngine.markName(b), c)
80
+ Codes.SELECTOR_WORD_BODY -> Selector.wordBody(a)
81
+ Codes.SELECTOR_WORD_MARKS -> Selector.wordMarks(a)
82
+ Codes.SELECTOR_WORD -> Selector.word(a)
83
+ Codes.SELECTOR_AYAH -> Selector.ayah(a, b)
84
+ Codes.SELECTOR_LINE -> Selector.line(a)
85
+ Codes.SELECTOR_MARK -> (m["mark"] as? String)?.let { Selector.mark(it) } ?: Selector.mark(a)
86
+ Codes.SELECTOR_CATEGORY -> Selector.category(a)
87
+ Codes.SELECTOR_FAMILY -> Selector.family(a)
88
+ Codes.SELECTOR_KIND -> Selector.kind(a)
89
+ Codes.SELECTOR_DECORATION -> Selector.decoration(a)
90
+ Codes.SELECTOR_DECORATION_INDEX -> Selector.decorationIndex(a)
75
91
  else -> null
76
92
  }
77
93
  }
78
94
 
95
+ /** The constant of [entries] that [v] names, in any of its spellings: the constant's own
96
+ * (RASM_IMLAI), snake case (rasm_imlai) or the camelCase of the TypeScript types (rasmImlai). */
97
+ private fun <E : Enum<E>> named(entries: List<E>, v: String): E? {
98
+ val key = v.replace("_", "")
99
+ return entries.firstOrNull { it.name.replace("_", "").equals(key, ignoreCase = true) }
100
+ }
101
+ /** A constant's name as the TypeScript types spell it: RASM_IMLAI is rasmImlai. */
102
+ fun jsName(e: Enum<*>): String {
103
+ val parts = e.name.lowercase().split('_')
104
+ return parts[0] + parts.drop(1).joinToString("") { it.replaceFirstChar(Char::uppercaseChar) }
105
+ }
106
+
79
107
  fun form(v: Any?, d: Form = Form.RASM_UTHMANI): Form = when (v) {
80
108
  is Number -> Form.entries.getOrElse(v.toInt()) { d }
81
- is String -> Form.entries.firstOrNull { it.name.equals(v, true) } ?: d
109
+ is String -> named(Form.entries, v) ?: d
82
110
  else -> d
83
111
  }
84
112
  fun searchMode(v: Any?): SearchMode = when (v) {
85
113
  is Number -> SearchMode.entries.getOrElse(v.toInt()) { SearchMode.INCLUDES }
86
- is String -> SearchMode.entries.firstOrNull { it.name.equals(v, true) } ?: SearchMode.INCLUDES
114
+ is String -> named(SearchMode.entries, v) ?: SearchMode.INCLUDES
87
115
  else -> SearchMode.INCLUDES
88
116
  }
89
117
  fun maskMode(v: Any?): MaskMode = when (v) {
90
118
  is Number -> MaskMode.entries.getOrElse(v.toInt()) { MaskMode.HIDE }
91
- is String -> MaskMode.entries.firstOrNull { it.name.equals(v, true) } ?: MaskMode.HIDE
119
+ is String -> named(MaskMode.entries, v) ?: MaskMode.HIDE
92
120
  else -> MaskMode.HIDE
93
121
  }
94
122
  fun division(v: Any?): Division = when (v) {
95
123
  is Number -> Division.entries.getOrElse(v.toInt()) { Division.JUZ }
96
- is String -> Division.entries.firstOrNull { it.name.equals(v, true) } ?: Division.JUZ
124
+ is String -> named(Division.entries, v) ?: Division.JUZ
97
125
  else -> Division.JUZ
98
126
  }
99
127
 
@@ -101,8 +129,8 @@ object Marshal {
101
129
  fun highlightStyle(v: Any?): QvpHighlightStyle {
102
130
  val m = v as? Map<*, *> ?: return QvpHighlightStyle()
103
131
  val d = QvpHighlightStyle()
104
- val mode = when (val x = m["mode"]) { is Number -> HighlightMode.entries.getOrElse(x.toInt()) { d.mode }; is String -> HighlightMode.entries.firstOrNull { it.name.equals(x, true) } ?: d.mode; else -> d.mode }
105
- val height = when (val x = m["height"]) { is Number -> BandHeight.entries.getOrElse(x.toInt()) { d.height }; is String -> BandHeight.entries.firstOrNull { it.name.equals(x, true) } ?: d.height; else -> d.height }
132
+ val mode = when (val x = m["mode"]) { is Number -> HighlightMode.entries.getOrElse(x.toInt()) { d.mode }; is String -> named(HighlightMode.entries, x) ?: d.mode; else -> d.mode }
133
+ val height = when (val x = m["height"]) { is Number -> BandHeight.entries.getOrElse(x.toInt()) { d.height }; is String -> named(BandHeight.entries, x) ?: d.height; else -> d.height }
106
134
  return QvpHighlightStyle(mode = mode, ink = color(m["ink"], d.ink), band = color(m["band"], d.band), height = height, padX = flt(m["padX"], d.padX), padY = flt(m["padY"], d.padY),
107
135
  radius = flt(m["radius"], d.radius), seam = flt(m["seam"], d.seam), transitionMs = num(m["ms"] ?: m["transitionMs"]) ?: d.transitionMs, layer = num(m["layer"]) ?: d.layer)
108
136
  }
@@ -158,19 +186,39 @@ object Marshal {
158
186
  "overflow" to listOf(i.overflow.left, i.overflow.top, i.overflow.right, i.overflow.bottom))
159
187
 
160
188
  // ── Kotlin → JS ──
161
- fun word(p: QvpPage, w: QvpWord): Map<String, Any?> {
162
- val forms = LinkedHashMap<String, String>()
163
- for (f in Form.entries) if (f == Form.RASM_UTHMANI || p.hasForm(f)) forms[f.name.lowercase()] = p.wordForm(w.index, f)
189
+ /**
190
+ * The engine's name of every id of the path and decoration tables, read once. A page has
191
+ * hundreds of paths, and each names its kind, mark, category and family: a lookup here is
192
+ * an array read, not four calls into the engine. Ids run 0..255, so the table covers every
193
+ * id a path can hold, and an id the engine does not know gets the engine's own answer.
194
+ */
195
+ private class Names {
196
+ val kind = Array(256) { QvpEngine.kindName(it) }
197
+ val mark = Array(256) { QvpEngine.markName(it) }
198
+ val category = Array(256) { QvpEngine.categoryName(it) }
199
+ val family = Array(256) { QvpEngine.familyName(it) }
200
+ val decoration = Array(256) { QvpEngine.decorationName(it).ifEmpty { "other" } }
201
+ }
202
+ private val names by lazy { Names() }
203
+
204
+ /** The forms a page has: [Form.RASM_UTHMANI] always, and each other form the words sidecar gave. */
205
+ fun forms(p: QvpPage): List<Form> = Form.entries.filter { it == Form.RASM_UTHMANI || p.hasForm(it) }
206
+
207
+ /** One word and its paths. [forms] is [forms] of the page, read once by the caller. */
208
+ fun word(p: QvpPage, w: QvpWord, forms: List<Form>): Map<String, Any?> {
209
+ val n = names
210
+ val text = LinkedHashMap<String, String>()
211
+ for (f in forms) text[jsName(f)] = p.wordForm(w.index, f)
164
212
  val paths = (w.firstPath until w.firstPath + w.nPaths).map { i ->
165
213
  val kind = p.pathKind(i); val mark = p.pathMark(i); val cat = p.pathCategory(i); val fam = p.pathFamily(i)
166
- mapOf("index" to i, "kind" to kind, "kindName" to QvpEngine.kindName(kind), "mark" to mark, "markName" to QvpEngine.markName(mark), "nthMark" to p.pathNthMark(i),
167
- "nthInWord" to p.pathNthInWord(i), "category" to cat, "categoryName" to QvpEngine.categoryName(cat), "family" to fam, "familyName" to QvpEngine.familyName(fam), "line" to p.pathLine(i))
214
+ mapOf("index" to i, "kind" to kind, "kindName" to n.kind[kind], "mark" to mark, "markName" to n.mark[mark], "nthMark" to p.pathNthMark(i),
215
+ "nthInWord" to p.pathNthInWord(i), "category" to cat, "categoryName" to n.category[cat], "family" to fam, "familyName" to n.family[fam], "line" to p.pathLine(i))
168
216
  }
169
217
  return mapOf("index" to w.index, "surah" to w.surah, "ayah" to w.ayah, "word" to w.word, "line" to w.line, "lineIndex" to w.lineIndex, "ayahIndex" to w.ayahIndex,
170
218
  "x0" to w.x0, "y0" to w.y0, "x1" to w.x1, "y1" to w.y1, "text" to w.text, "firstPath" to w.firstPath, "nPaths" to w.nPaths,
171
- "wordKey" to w.wordKey, "ayahKey" to w.ayahKey, "forms" to forms, "label" to p.wordLabel(w.index), "paths" to paths)
219
+ "wordKey" to w.wordKey, "ayahKey" to w.ayahKey, "forms" to text, "label" to p.wordLabel(w.index), "paths" to paths)
172
220
  }
173
- fun decoration(d: QvpDecoration): Map<String, Any?> = mapOf("index" to d.index, "decoration" to d.decoration, "decorationName" to QvpEngine.decorationName(d.decoration).ifEmpty { "other" },
221
+ fun decoration(d: QvpDecoration): Map<String, Any?> = mapOf("index" to d.index, "decoration" to d.decoration, "decorationName" to names.decoration[d.decoration and 0xff],
174
222
  "surah" to d.surah, "ayah" to d.ayah, "line" to d.line, "x0" to d.x0, "y0" to d.y0, "x1" to d.x1, "y1" to d.y1, "text" to d.text, "firstPath" to d.firstPath, "nPaths" to d.nPaths)
175
223
  fun hit(p: QvpPage, h: QvpHit): Map<String, Any?> {
176
224
  val w = if (h.word >= 0) p.words[h.word] else null
@@ -200,8 +248,8 @@ object Marshal {
200
248
  fun atlasRubuAlHizb(r: QvpAtlasRubuAlHizb): Map<String, Any?> = mapOf("rubuAlHizb" to r.rubuAlHizb, "surah" to r.surah, "ayah" to r.ayah, "page" to r.page, "ayahKey" to r.ayahKey)
201
249
  fun layout(l: QvpLayout): Map<String, Any?> = mapOf("scale" to l.scale, "offsetX" to l.offsetX, "offsetY" to l.offsetY, "contentW" to l.contentW, "contentH" to l.contentH, "lineSpacing" to l.lineSpacing, "fitScale" to l.fitScale, "fitX" to l.fitX, "fitY" to l.fitY, "lineDy" to l.lineDy.toList(),
202
250
  "slots" to l.slotTop.indices.map { listOf(l.slotTop[it], l.slotBottom[it]) })
203
- fun pageInfo(p: QvpPage): Map<String, Any?> = mapOf("page" to p.pageNo, "width" to p.width, "height" to p.height, "nLines" to p.nLines, "nAyahs" to p.nAyahs, "nWords" to p.nWords, "nPaths" to p.nPaths, "nDecorations" to p.nDecorations,
204
- "lineSpacing" to p.lineSpacing, "forms" to Form.entries.filter { it == Form.RASM_UTHMANI || p.hasForm(it) }.map { it.name.lowercase() })
251
+ fun pageInfo(p: QvpPage, forms: List<Form>): Map<String, Any?> = mapOf("page" to p.pageNo, "width" to p.width, "height" to p.height, "nLines" to p.nLines, "nAyahs" to p.nAyahs, "nWords" to p.nWords, "nPaths" to p.nPaths, "nDecorations" to p.nDecorations,
252
+ "lineSpacing" to p.lineSpacing, "forms" to forms.map { jsName(it) })
205
253
  fun selection(p: QvpPage): Map<String, Any?> {
206
254
  val ws = p.selection()
207
255
  return mapOf("words" to ws.toList(), "text" to (if (ws.isEmpty()) "" else p.text(Target.words(ws))), "citation" to (if (ws.isEmpty()) "" else p.citation(ws)),