@quran.ws/qvp-react-native 0.6.1 → 0.7.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/README.md CHANGED
@@ -88,6 +88,52 @@ Colours: `'#rgb' | '#rrggbb' | '#rrggbbaa' | 0xRRGGBBAA` (`css()` / `rgba(c, alp
88
88
  Targets: `'page' | '2:255' | '2:255:3' | '2:255-257' | 'line:7' | 'surah:2' | wordIdx | [index…] | T.*`.
89
89
  Selectors: `Sel.page/path/wordPath/wordMark/wordMarkNamed/wordBody/wordMarks/word/ayah/line/mark/category/family/kind/decoration/decorationIndex`.
90
90
 
91
+ ## The passage view
92
+
93
+ A passage is a range of complete ayahs shown away from its page, or a surah's basmalah. The
94
+ engine lays it out on rows of the view's width and the view draws it; the layout comes back
95
+ through `onPassageLayout`, and the view takes its height from it.
96
+
97
+ ```tsx
98
+ <QvpPassageView
99
+ style={{ width: '100%' }}
100
+ pageUris={['asset://pages/042.qvp']} // the pages that print the range, in any order
101
+ surah={2} from={255} // to={…} for a range; basmalah for the surah's basmalah
102
+ lineHeight={22} // dp per printed line (or scale: dp per page unit)
103
+ align="justified" maxStretch={2} // right (the default), center or justified
104
+ maxRows={2} ellipsisWidth={12} keepAyahMark // cut after two rows, ellipsis, then the medallion
105
+ ink="#231f20" paperColor="#fffdf7"
106
+ onPassageLayout={l => console.log(l.rows.length, l.words.length, l.isTruncated)}
107
+ />
108
+ ```
109
+
110
+ ## Dress
111
+
112
+ A page can wear another mushaf's ornaments: an ayah medallion, a surah band and a page border
113
+ from an ornament set (`ornaments.qvo`, in the data release). The engine places each ornament.
114
+ The native view paints the layer behind the ink and fits the border into the view.
115
+
116
+ ```tsx
117
+ const set = await QvpOrnaments.load('asset://pages/ornaments.qvo');
118
+ const medallion = await set.find('ayah_mark', 'font-003-regular');
119
+ <QvpPageView
120
+ pageUri="asset://pages/604.qvp"
121
+ dress={{ ornaments: set, style: 'mushaf-qalon', ayahMark: medallion, gap: 5, lineArt: ['surah_header'] }}
122
+ onDressChanged={({ info }) => console.log(info?.ayahMarks, info?.frameRepeats)} // null: refused
123
+ />
124
+ ```
125
+
126
+ - `style` takes a mushaf's medallion, band and border together. A kind key (`ayahMark`,
127
+ `surahHeader`, `pageFrame`) overrides the style for that kind. It takes an ornament, an
128
+ index or a style name. `null` is none.
129
+ - The knobs are `gap`, `bandGap`, `ayahMarkScale` (0 takes the design's own size),
130
+ `pageFrameScale`, `lineArt` (`true` or a list of kinds) and `colors` (`[ornament, part, colour]`).
131
+ - `set.list` gives each ornament with its `licence` and `parts`. `set.styles()` groups the
132
+ ornaments by mushaf, and `set.ofKind(kind)` filters them. Read the licence before you
133
+ publish a dressed page.
134
+ - The prop dresses every page the view loads. `qvp.dress(set, spec)`, `qvp.undress()`,
135
+ `qvp.dressInfo()` and `qvp.dressRevision()` act on the page in the view now. Do not mix them with the `dress` prop on one view.
136
+
91
137
  ## The module
92
138
 
93
139
  Everything takes the view's react tag (`findNodeHandle`) — or use the bound forms:
@@ -134,10 +180,13 @@ android/build.gradle library module; depends on project(':
134
180
  android/src/main/java/ws/quran/qvp/rn/
135
181
  QvpRnPageView.kt QvpPageView subclass: page loading, prop → handle reconciliation, events
136
182
  QvpPageViewManager.kt SimpleViewManager<QvpRnPageView> (props, events, commit after each prop batch)
137
- QvpModule.kt ReactContextBaseJavaModule: page queries by react tag, engine helpers, atlas
183
+ QvpRnPassageView.kt View: loads the pages, lays the passage out at the view's width, draws it, reports the layout
184
+ QvpPassageViewManager.kt SimpleViewManager<QvpRnPassageView>
185
+ QvpRnBytes.kt the bytes a URI names (asset, file, path, base64)
186
+ QvpModule.kt ReactContextBaseJavaModule: page queries by react tag, engine helpers, atlas, ornament sets
138
187
  Marshal.kt JS shapes ↔ Kotlin types (targets, selectors, styles, records)
139
188
  QvpPackage.kt
140
- src/index.tsx typed API: <QvpPageView/>, useQvp(), Qvp, QvpAtlas, Sel, T, constants
189
+ src/index.tsx typed API: <QvpPageView/>, <QvpPassageView/>, useQvp(), Qvp, QvpAtlas, QvpOrnaments, Sel, T, constants
141
190
  ```
142
191
 
143
192
  ## iOS — TODO
@@ -50,4 +50,5 @@ dependencies {
50
50
  // version pinned by the React Native Gradle Plugin of the consuming app
51
51
  implementation "com.facebook.react:react-android"
52
52
  if (qvpProject != null) implementation project(":qvp")
53
+ testImplementation "junit:junit:4.13.2"
53
54
  }
@@ -114,6 +114,49 @@ object Marshal {
114
114
  ayahMark = colorOrNull(m["ayahMark"]), numeral = colorOrNull(m["numeral"]), headers = colorOrNull(m["headers"]), marks = marks, transitionMs = num(m["ms"] ?: m["transitionMs"]) ?: 0)
115
115
  }
116
116
 
117
+ // ── dress ──
118
+ private val ORNAMENT_KINDS = QvpOrnamentKind.entries.associateBy { it.name.lowercase() }
119
+ /** 'ayah_mark' | 'surah_header' | 'page_frame' (or QVP_ORNAMENT_*) → [QvpOrnamentKind], or null. */
120
+ fun ornamentKind(v: Any?): QvpOrnamentKind? = when (v) {
121
+ is String -> ORNAMENT_KINDS[v.lowercase()]
122
+ is Number -> QvpOrnamentKind.entries.getOrNull(v.toInt())
123
+ else -> null
124
+ }
125
+ /** One kind of a JS spec: an index, a style name, or null for none (JS has already put the style in each kind). */
126
+ private fun ornamentRef(v: Any?): QvpOrnamentRef = when (v) {
127
+ is Number -> QvpOrnamentRef.Index(v.toInt())
128
+ is String -> QvpOrnamentRef.Style(v)
129
+ else -> QvpOrnamentRef.None
130
+ }
131
+ /** {ayahMark, surahHeader, pageFrame, gap, bandGap, ayahMarkScale, pageFrameScale, lineArt: [kind], colors: [[ornament, part, colour]]} → [QvpDressSpec].
132
+ * A missing number keeps the library's default. A missing kind draws none. */
133
+ fun dressSpec(v: Any?): QvpDressSpec {
134
+ val m = v as? Map<*, *> ?: return QvpDressSpec()
135
+ val d = QvpDressSpec()
136
+ val lineArt = (m["lineArt"] as? Iterable<*>)?.mapNotNull { ornamentKind(it) }?.toSet() ?: emptySet()
137
+ val colors = (m["colors"] as? Iterable<*>)?.mapNotNull { t ->
138
+ val l = (t as? Iterable<*>)?.toList() ?: return@mapNotNull null
139
+ val o = num(l.getOrNull(0)) ?: return@mapNotNull null
140
+ val part = num(l.getOrNull(1)) ?: return@mapNotNull null
141
+ QvpPartColor(o, part, color(l.getOrNull(2), 0))
142
+ } ?: emptyList()
143
+ return QvpDressSpec(style = null, ayahMark = ornamentRef(m["ayahMark"]), surahHeader = ornamentRef(m["surahHeader"]), pageFrame = ornamentRef(m["pageFrame"]),
144
+ gap = flt(m["gap"], d.gap), bandGap = flt(m["bandGap"], d.bandGap), ayahMarkScale = flt(m["ayahMarkScale"], d.ayahMarkScale),
145
+ pageFrameScale = flt(m["pageFrameScale"], d.pageFrameScale), lineArt = lineArt, colors = colors)
146
+ }
147
+ /** 0xRRGGBBAA as JS reads it: unsigned. */
148
+ private fun rgbaJs(c: Int): Long = c.toLong() and 0xffffffffL
149
+ fun ornamentPart(p: QvpOrnamentPart): Map<String, Any?> = mapOf("index" to p.index, "color" to rgbaJs(p.color), "stroke" to p.stroke, "name" to p.name)
150
+ fun ornament(o: QvpOrnament): Map<String, Any?> = mapOf("index" to o.index, "kind" to o.kind.name.lowercase(), "lineage" to o.lineage.name.lowercase(),
151
+ "style" to o.style, "riwayah" to o.riwayah, "hasSlices" to o.hasSlices,
152
+ "licence" to mapOf("id" to o.licence.id, "status" to o.licence.status, "redistributable" to o.licence.redistributable, "attribution" to o.licence.attribution),
153
+ "parts" to o.parts.map { ornamentPart(it) })
154
+ fun dressInfo(i: QvpDressInfo): Map<String, Any?> = mapOf("ayahMark" to i.ayahMark, "surahHeader" to i.surahHeader, "pageFrame" to i.pageFrame,
155
+ "ayahMarks" to i.ayahMarks, "surahHeaders" to i.surahHeaders, "frameRepeats" to i.frameRepeats, "frameStretched" to i.frameStretched,
156
+ "draws" to i.draws, "revision" to i.revision,
157
+ "viewBox" to listOf(i.viewBox.x, i.viewBox.y, i.viewBox.width, i.viewBox.height),
158
+ "overflow" to listOf(i.overflow.left, i.overflow.top, i.overflow.right, i.overflow.bottom))
159
+
117
160
  // ── Kotlin → JS ──
118
161
  fun word(p: QvpPage, w: QvpWord): Map<String, Any?> {
119
162
  val forms = LinkedHashMap<String, String>()
@@ -145,6 +188,13 @@ object Marshal {
145
188
  fun rosette(r: QvpRosette): Map<String, Any?> = mapOf("decoration" to r.decoration, "surah" to r.surah, "ayah" to r.ayah, "juz" to r.juz, "hizb" to r.hizb, "nisf" to r.nisf, "rubuAlHizb" to r.rubuAlHizb, "rubuAlHizbInHizb" to r.rubuAlHizbInHizb)
146
189
  fun sajdah(s: QvpSajdah): Map<String, Any?> = mapOf("decoration" to s.decoration, "surah" to s.surah, "ayah" to s.ayah, "signPath" to s.signPath)
147
190
  fun match(m: QvpMatch): Map<String, Any?> = mapOf("word" to m.word, "index" to m.index, "isLooseMatch" to m.isLooseMatch, "wordKey" to m.wordKey, "text" to m.text)
191
+ fun passageLayoutMap(l: QvpPassageLayout, p: QvpPassage): Map<String, Any?> = mapOf("width" to l.width, "height" to l.height, "scale" to l.scale, "lineSpacing" to l.lineSpacing,
192
+ "printedLineSpacing" to p.lineSpacing, "isTruncated" to l.isTruncated, "ellipsis" to l.ellipsis?.let { listOf(it.left, it.top, it.right, it.bottom) },
193
+ "rows" to l.rows.map { mapOf("x0" to it.x0, "y0" to it.y0, "x1" to it.x1, "y1" to it.y1, "baseline" to it.baseline) },
194
+ "words" to l.words.map { mapOf("surah" to it.surah, "ayah" to it.ayah, "word" to it.word, "wordKey" to it.wordKey, "page" to it.page, "row" to it.row, "x0" to it.x0, "y0" to it.y0, "x1" to it.x1, "y1" to it.y1,
195
+ "wordX0" to it.wordX0, "wordY0" to it.wordY0, "wordX1" to it.wordX1, "wordY1" to it.wordY1) },
196
+ "ayahs" to l.ayahs.map { mapOf("surah" to it.surah, "ayah" to it.ayah, "x0" to it.x0, "y0" to it.y0, "x1" to it.x1, "y1" to it.y1) },
197
+ "texts" to p.ayahs.map { mapOf("surah" to it.surah, "ayah" to it.ayah, "text" to it.text) })
148
198
  fun cropBounds(c: QvpCropBounds): Map<String, Any?> = mapOf("x0" to c.x0, "y0" to c.y0, "x1" to c.x1, "y1" to c.y1, "nWords" to c.nWords, "ayahMarkDecoration" to c.ayahMarkDecoration)
149
199
  fun atlasSurah(s: QvpAtlasSurah): Map<String, Any?> = mapOf("number" to s.number, "page" to s.page, "ayahCount" to s.ayahCount, "place" to s.place, "arabic" to s.arabic, "latin" to s.latin, "english" to s.english)
150
200
  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)
@@ -152,6 +152,39 @@ class QvpModule(private val ctx: ReactApplicationContext) : ReactContextBaseJava
152
152
  @ReactMethod fun atlasPagesOfJuz(id: Int, n: Int, promise: Promise) = withAtlas(id, promise) { it.pagesOfJuz(n)?.let { r -> listOf(r.first, r.second) } }
153
153
  @ReactMethod fun atlasSearchSurahs(id: Int, text: String, promise: Promise) = withAtlas(id, promise) { it.searchSurahs(text).map { s -> Marshal.atlasSurah(s) } }
154
154
 
155
+ // ── dress ──
156
+ // An ornament set is held here by id, like an atlas. The C calls behind each method:
157
+ // qvp_ornaments_load, qvp_ornaments_free, qvp_ornament_count, qvp_ornament_info and
158
+ // qvp_ornament_part (one ornament and its parts), qvp_ornament_find, then on the page
159
+ // qvp_dress, qvp_undress and qvp_dress_info. qvp_dress_geometry is the view's: it paints the layer.
160
+ private fun withOrnaments(id: Int, promise: Promise, block: (QvpOrnaments) -> Any?) { ui(promise) { block(QvpOrnamentSets.get(id) ?: throw IllegalStateException("no ornament set $id")) } }
161
+ @ReactMethod fun loadOrnaments(uri: String, promise: Promise) = ui(promise) { QvpOrnamentSets.add(QvpOrnaments(QvpRnBytes.read(ctx, uri))) }
162
+ @ReactMethod fun freeOrnaments(id: Int, promise: Promise) = ui(promise) { QvpOrnamentSets.free(id); null }
163
+ @ReactMethod fun ornamentCount(id: Int, promise: Promise) = withOrnaments(id, promise) { it.count }
164
+ @ReactMethod fun ornamentInfo(id: Int, index: Int, promise: Promise) = withOrnaments(id, promise) { it.list.getOrNull(index)?.let { o -> Marshal.ornament(o) } }
165
+ @ReactMethod fun ornamentPart(id: Int, index: Int, part: Int, promise: Promise) = withOrnaments(id, promise) { it.list.getOrNull(index)?.parts?.getOrNull(part)?.let { q -> Marshal.ornamentPart(q) } }
166
+ @ReactMethod fun ornamentList(id: Int, promise: Promise) = withOrnaments(id, promise) { it.list.map { o -> Marshal.ornament(o) } }
167
+ @ReactMethod fun ornamentFind(id: Int, kind: String, style: String, promise: Promise) = withOrnaments(id, promise) { set ->
168
+ Marshal.ornamentKind(kind)?.let { k -> set.find(k, style)?.index } ?: -1 }
169
+ /** Dress the page behind a view. The `dress` prop does the same declaratively; this call lasts until the next page. */
170
+ @ReactMethod fun dress(tag: Int, id: Int, spec: ReadableMap?, promise: Promise) = withPage(tag, promise) { v, p ->
171
+ val set = QvpOrnamentSets.get(id) ?: throw IllegalStateException("no ornament set $id")
172
+ v.dressNow(p, set, Marshal.dressSpec(opt(spec)))?.let { Marshal.dressInfo(it) } }
173
+ @ReactMethod fun undress(tag: Int, promise: Promise) = withPage(tag, promise) { v, p -> v.undressNow(p); null }
174
+ /** The engine's clamp of a view over the content plus the dress overflow. Offsets and viewport are in dp, like the other view methods. */
175
+ @ReactMethod fun dressClamp(tag: Int, scale: Double, offsetX: Double, offsetY: Double, viewportW: Double, viewportH: Double, promise: Promise) = withPage(tag, promise) { v, p ->
176
+ val d = v.resources.displayMetrics.density
177
+ val c = p.dressClamp(QvpView(scale.toFloat(), (offsetX * d).toFloat(), (offsetY * d).toFloat()), (viewportW * d).toFloat(), (viewportH * d).toFloat())
178
+ mapOf("scale" to c.scale, "offsetX" to c.offsetX / d, "offsetY" to c.offsetY / d) }
179
+ /** The engine's view and dressed box size for a host that scrolls the page. The viewport, offsets and size are in dp. */
180
+ @ReactMethod fun dressView(tag: Int, scale: Double, viewportW: Double, promise: Promise) = withPage(tag, promise) { v, p ->
181
+ val d = v.resources.displayMetrics.density
182
+ val r = p.dressView(scale.toFloat(), (viewportW * d).toFloat())
183
+ mapOf("view" to mapOf("scale" to r.view.scale, "offsetX" to r.view.offsetX / d, "offsetY" to r.view.offsetY / d),
184
+ "width" to r.width / d, "height" to r.height / d) }
185
+ @ReactMethod fun dressInfo(tag: Int, promise: Promise) = withPage(tag, promise) { _, p -> p.dressInfo()?.let { Marshal.dressInfo(it) } }
186
+ @ReactMethod fun dressRevision(tag: Int, promise: Promise) = withPage(tag, promise) { _, p -> p.dressRevision() }
187
+
155
188
  // ── names ──
156
189
  @ReactMethod fun markName(m: Int, promise: Promise) = ui(promise) { QvpEngine.markName(m) }
157
190
  @ReactMethod fun markFromName(s: String, promise: Promise) = ui(promise) { QvpEngine.markFromName(s) }
@@ -162,8 +195,20 @@ class QvpModule(private val ctx: ReactApplicationContext) : ReactContextBaseJava
162
195
  "marks" to QvpEngine.names(QvpEngine.Names.MARK), "kinds" to QvpEngine.names(QvpEngine.Names.KIND),
163
196
  "families" to QvpEngine.names(QvpEngine.Names.FAMILY), "categories" to QvpEngine.names(QvpEngine.Names.CATEGORY),
164
197
  "decorations" to QvpEngine.names(QvpEngine.Names.DECORATION), "divisions" to QvpEngine.names(QvpEngine.Names.DIVISION),
165
- "places" to QvpEngine.names(QvpEngine.Names.PLACE))
198
+ "places" to QvpEngine.names(QvpEngine.Names.PLACE),
199
+ "defaults" to mapOf("ayahMarkScaleScan" to QvpDefaults.AYAH_MARK_SCALE_SCAN.toDouble()))
166
200
 
167
- override fun invalidate() { atlases.values.forEach { it.close() }; atlases.clear(); atlasByUri.clear(); super.invalidate() }
201
+ override fun invalidate() { atlases.values.forEach { it.close() }; atlases.clear(); atlasByUri.clear(); QvpOrnamentSets.clear(); super.invalidate() }
168
202
  companion object { const val NAME = "QvpModule" }
169
203
  }
204
+
205
+ /** Ornament sets by id, shared by the module and the views: the `dress` prop names its set by this id.
206
+ * A dressed page keeps what it needs, so freeing a set never breaks a page that wears it. */
207
+ object QvpOrnamentSets {
208
+ private val sets = HashMap<Int, QvpOrnaments>()
209
+ private var next = 1
210
+ fun add(set: QvpOrnaments): Int { val id = next++; sets[id] = set; return id }
211
+ fun get(id: Int?): QvpOrnaments? = id?.let { sets[it] }
212
+ fun free(id: Int) { sets.remove(id)?.close() }
213
+ fun clear() { sets.values.forEach { it.close() }; sets.clear() }
214
+ }
@@ -7,5 +7,5 @@ import com.facebook.react.uimanager.ViewManager
7
7
 
8
8
  class QvpPackage : ReactPackage {
9
9
  override fun createNativeModules(ctx: ReactApplicationContext): List<NativeModule> = listOf(QvpModule(ctx))
10
- override fun createViewManagers(ctx: ReactApplicationContext): List<ViewManager<*, *>> = listOf(QvpPageViewManager())
10
+ override fun createViewManagers(ctx: ReactApplicationContext): List<ViewManager<*, *>> = listOf(QvpPageViewManager(), QvpPassageViewManager())
11
11
  }
@@ -15,11 +15,7 @@ class QvpPageViewManager : SimpleViewManager<QvpRnPageView>() {
15
15
  override fun onDropViewInstance(view: QvpRnPageView) { view.destroy(); super.onDropViewInstance(view) }
16
16
  override fun onAfterUpdateTransaction(view: QvpRnPageView) { super.onAfterUpdateTransaction(view); view.commit() }
17
17
 
18
- override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> {
19
- val m = HashMap<String, Any>()
20
- for (e in EVENTS) m[e] = mapOf("registrationName" to e)
21
- return m
22
- }
18
+ override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> = QvpRnEvents.constants(EVENTS)
23
19
 
24
20
  @ReactProp(name = "pageUri") fun setPageUri(v: QvpRnPageView, s: String?) { v.pageUri = s }
25
21
  @ReactProp(name = "pageBase64") fun setPageBase64(v: QvpRnPageView, s: String?) { v.pageBase64 = s }
@@ -43,9 +39,10 @@ class QvpPageViewManager : SimpleViewManager<QvpRnPageView>() {
43
39
  @ReactProp(name = "highlights") fun setHighlights(v: QvpRnPageView, a: ReadableArray?) { v.highlightsProp = Marshal.plain(a) }
44
40
  @ReactProp(name = "mask") fun setMask(v: QvpRnPageView, m: ReadableMap?) { v.maskProp = Marshal.plain(m) }
45
41
  @ReactProp(name = "reveal") fun setReveal(v: QvpRnPageView, m: ReadableMap?) { v.revealProp = Marshal.plain(m) }
42
+ @ReactProp(name = "dress") fun setDress(v: QvpRnPageView, m: ReadableMap?) { v.dressProp = Marshal.plain(m) }
46
43
 
47
44
  companion object {
48
45
  const val NAME = "QvpPageView"
49
- val EVENTS = listOf("onWordTap", "onDecorationTap", "onEmptyTap", "onSelectionChanged", "onPageLoad", "onRevealChanged", "onSwipe", "onZoomChanged", "onError")
46
+ val EVENTS = listOf("onWordTap", "onDecorationTap", "onEmptyTap", "onSelectionChanged", "onPageLoad", "onRevealChanged", "onSwipe", "onZoomChanged", "onDressChanged", "onError")
50
47
  }
51
48
  }
@@ -0,0 +1,39 @@
1
+ package ws.quran.qvp.rn
2
+
3
+ import com.facebook.react.bridge.ReadableArray
4
+ import com.facebook.react.uimanager.SimpleViewManager
5
+ import com.facebook.react.uimanager.ThemedReactContext
6
+ import com.facebook.react.uimanager.annotations.ReactProp
7
+ import ws.quran.qvp.QvpColor
8
+
9
+ /** `<QvpPassageView />`: props are marshalled onto [QvpRnPassageView]; [onAfterUpdateTransaction] commits them in one pass. */
10
+ class QvpPassageViewManager : SimpleViewManager<QvpRnPassageView>() {
11
+ override fun getName() = NAME
12
+ override fun createViewInstance(c: ThemedReactContext) = QvpRnPassageView(c)
13
+ override fun onDropViewInstance(view: QvpRnPassageView) { view.destroy(); super.onDropViewInstance(view) }
14
+ override fun onAfterUpdateTransaction(view: QvpRnPassageView) { super.onAfterUpdateTransaction(view); view.commit() }
15
+
16
+ override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> = QvpRnEvents.constants(EVENTS)
17
+
18
+ @ReactProp(name = "pageUris") fun setPageUris(v: QvpRnPassageView, a: ReadableArray?) { v.pageUris = Marshal.plain(a)?.map { it.toString() } ?: emptyList() }
19
+ @ReactProp(name = "surah", defaultInt = 0) fun setSurah(v: QvpRnPassageView, i: Int) { v.surahProp = i }
20
+ @ReactProp(name = "from", defaultInt = 0) fun setFrom(v: QvpRnPassageView, i: Int) { v.fromProp = i }
21
+ @ReactProp(name = "to", defaultInt = 0) fun setTo(v: QvpRnPassageView, i: Int) { v.toProp = i }
22
+ @ReactProp(name = "basmalah", defaultBoolean = false) fun setBasmalah(v: QvpRnPassageView, b: Boolean) { v.basmalahProp = b }
23
+ @ReactProp(name = "scale", defaultFloat = 1f) fun setScale(v: QvpRnPassageView, f: Float) { v.scaleProp = f }
24
+ @ReactProp(name = "lineHeight", defaultFloat = 0f) fun setLineHeight(v: QvpRnPassageView, f: Float) { v.lineHeightProp = f }
25
+ @ReactProp(name = "lineSpacing", defaultFloat = 1f) fun setLineSpacing(v: QvpRnPassageView, f: Float) { v.lineSpacingProp = f }
26
+ @ReactProp(name = "padding", defaultFloat = 2f) fun setPadding(v: QvpRnPassageView, f: Float) { v.paddingProp = f }
27
+ @ReactProp(name = "align") fun setAlign(v: QvpRnPassageView, s: String?) { v.alignProp = s }
28
+ @ReactProp(name = "maxRows", defaultInt = 0) fun setMaxRows(v: QvpRnPassageView, i: Int) { v.maxRowsProp = i }
29
+ @ReactProp(name = "keepAyahMark", defaultBoolean = false) fun setKeepAyahMark(v: QvpRnPassageView, b: Boolean) { v.keepAyahMarkProp = b }
30
+ @ReactProp(name = "ellipsisWidth", defaultFloat = 0f) fun setEllipsisWidth(v: QvpRnPassageView, f: Float) { v.ellipsisWidthProp = f }
31
+ @ReactProp(name = "maxStretch", defaultFloat = 0f) fun setMaxStretch(v: QvpRnPassageView, f: Float) { v.maxStretchProp = f }
32
+ @ReactProp(name = "ink") fun setInk(v: QvpRnPassageView, s: String?) { v.inkProp = s }
33
+ @ReactProp(name = "paperColor") fun setPaperColor(v: QvpRnPassageView, s: String?) { v.paperColor = Marshal.color(s, 0).let { if (it == 0) 0 else QvpColor.argb(it) } }
34
+
35
+ companion object {
36
+ const val NAME = "QvpPassageView"
37
+ val EVENTS = listOf("onPassageLayout", "onError")
38
+ }
39
+ }
@@ -0,0 +1,20 @@
1
+ package ws.quran.qvp.rn
2
+
3
+ import android.content.Context
4
+ import android.util.Base64
5
+ import java.io.File
6
+
7
+ /** The bytes a prop-given URI names: an asset, a file, an absolute path or inline base64. */
8
+ object QvpRnBytes {
9
+ fun read(ctx: Context, uri: String): ByteArray {
10
+ val u = uri.trim()
11
+ return when {
12
+ u.startsWith("asset://") -> ctx.assets.open(u.removePrefix("asset://")).use { it.readBytes() }
13
+ u.startsWith("asset:") -> ctx.assets.open(u.removePrefix("asset:")).use { it.readBytes() }
14
+ u.startsWith("file://") -> File(u.removePrefix("file://")).readBytes()
15
+ u.startsWith("/") -> File(u).readBytes()
16
+ u.startsWith("base64:") -> Base64.decode(u.removePrefix("base64:"), Base64.DEFAULT)
17
+ else -> ctx.assets.open(u).use { it.readBytes() }
18
+ }
19
+ }
20
+ }
@@ -0,0 +1,28 @@
1
+ package ws.quran.qvp.rn
2
+
3
+ import android.view.View
4
+ import com.facebook.react.bridge.WritableMap
5
+ import com.facebook.react.uimanager.ThemedReactContext
6
+ import com.facebook.react.uimanager.UIManagerHelper
7
+ import com.facebook.react.uimanager.events.Event
8
+
9
+ /** The event plumbing both native views share: a named event with a map payload, sent to the view's tag. */
10
+ object QvpRnEvents {
11
+ private class QvpEvent(surfaceId: Int, viewTag: Int, private val name: String, private val payload: WritableMap) : Event<QvpEvent>(surfaceId, viewTag) {
12
+ override fun getEventName() = name
13
+ override fun getEventData(): WritableMap = payload
14
+ }
15
+
16
+ fun emit(ctx: ThemedReactContext, view: View, name: String, payload: Map<String, Any?>) {
17
+ if (view.id <= 0) return
18
+ val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(ctx, view.id) ?: return
19
+ dispatcher.dispatchEvent(QvpEvent(UIManagerHelper.getSurfaceId(view), view.id, name, Marshal.toMap(payload)))
20
+ }
21
+
22
+ /** The direct event map a manager exports: each name registers under itself. */
23
+ fun constants(names: List<String>): MutableMap<String, Any> {
24
+ val m = HashMap<String, Any>()
25
+ for (e in names) m[e] = mapOf("registrationName" to e)
26
+ return m
27
+ }
28
+ }
@@ -3,14 +3,10 @@ package ws.quran.qvp.rn
3
3
  import android.util.Base64
4
4
  import android.util.Log
5
5
  import com.facebook.react.bridge.Arguments
6
- import com.facebook.react.bridge.WritableMap
7
6
  import com.facebook.react.uimanager.ThemedReactContext
8
- import com.facebook.react.uimanager.UIManagerHelper
9
- import com.facebook.react.uimanager.events.Event
10
7
  import android.widget.FrameLayout
11
8
  import ws.quran.qvp.*
12
9
  import ws.quran.qvp.Target
13
- import java.io.File
14
10
 
15
11
  /**
16
12
  * The React Native host of [QvpPageView]. It owns the loaded [QvpPage], loads bytes from the prop-given
@@ -52,6 +48,7 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
52
48
  var highlightsProp: List<Any?>? = null
53
49
  var maskProp: Map<String, Any?>? = null
54
50
  var revealProp: Map<String, Any?>? = null
51
+ var dressProp: Map<String, Any?>? = null
55
52
  var layoutDirty = true
56
53
 
57
54
  // ── applied state ──
@@ -64,6 +61,7 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
64
61
  private var appliedMask: Map<String, Any?>? = null
65
62
  private var appliedReveal: Map<String, Any?>? = null // without "at"
66
63
  private var appliedRevealAt: Long? = null
64
+ private var appliedDress: Map<String, Any?>? = null
67
65
  private var appliedInk: Int? = null
68
66
  var revealStepCount = 0; private set
69
67
  var loadMs = 0.0; private set
@@ -116,18 +114,7 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
116
114
  fun setFillHeightProp(v: Boolean) { inner.fillHeight = v; layoutDirty = true }
117
115
  fun setSurahFramesProp(v: Boolean) { inner.surahFrames = v; layoutDirty = true }
118
116
 
119
- // ── bytes ──
120
- private fun readUri(uri: String): ByteArray {
121
- val u = uri.trim()
122
- return when {
123
- u.startsWith("asset://") -> ctx.assets.open(u.removePrefix("asset://")).use { it.readBytes() }
124
- u.startsWith("asset:") -> ctx.assets.open(u.removePrefix("asset:")).use { it.readBytes() }
125
- u.startsWith("file://") -> File(u.removePrefix("file://")).readBytes()
126
- u.startsWith("/") -> File(u).readBytes()
127
- u.startsWith("base64:") -> Base64.decode(u.removePrefix("base64:"), Base64.DEFAULT)
128
- else -> ctx.assets.open(u).use { it.readBytes() }
129
- }
130
- }
117
+ private fun readUri(uri: String): ByteArray = QvpRnBytes.read(ctx, uri)
131
118
 
132
119
  /** Called by the manager after every prop batch. */
133
120
  fun commit() {
@@ -137,7 +124,11 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
137
124
  if (p != null) {
138
125
  applyInk(p); applyTheme(p); applyStyles(p); applyHighlights(p); applyMask(p); applyReveal(p)
139
126
  }
140
- if (layoutDirty) { layoutDirty = false; inner.relayout(); resetView() }
127
+ var fit = false
128
+ if (layoutDirty) { layoutDirty = false; inner.relayout(); fit = true }
129
+ // After the layout: the engine places the ornaments on the layout in force.
130
+ if (p != null && applyDress(p)) fit = true
131
+ if (fit) resetView()
141
132
  commitZoom()
142
133
  inner.invalidate()
143
134
  } catch (e: Exception) {
@@ -150,7 +141,7 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
150
141
  val key = pageBase64?.let { "b64:" + it.hashCode() } ?: pageUri
151
142
  if (key == loadedKey) return
152
143
  // drop everything bound to the old page: handles die with it
153
- themeHandle = 0; appliedTheme = null; styleHandles.clear(); highlightHandles.clear(); appliedMask = null; appliedReveal = null; appliedRevealAt = null; appliedInk = null; revealStepCount = 0
144
+ themeHandle = 0; appliedTheme = null; styleHandles.clear(); highlightHandles.clear(); appliedMask = null; appliedReveal = null; appliedRevealAt = null; appliedInk = null; appliedDress = null; revealStepCount = 0
154
145
  page?.close(); page = null; loadedKey = key
155
146
  if (key == null) return
156
147
  val bytes = pageBase64?.let { Base64.decode(it, Base64.DEFAULT) } ?: readUri(pageUri!!)
@@ -236,16 +227,30 @@ class QvpRnPageView(private val ctx: ThemedReactContext) : FrameLayout(ctx) {
236
227
  if (at != appliedRevealAt) { appliedRevealAt = at; p.revealGoto(at) }
237
228
  }
238
229
 
239
- // ── events ──
240
- private class QvpEvent(surfaceId: Int, viewTag: Int, private val name: String, private val payload: WritableMap) : Event<QvpEvent>(surfaceId, viewTag) {
241
- override fun getEventName() = name
242
- override fun getEventData(): WritableMap = payload
243
- }
244
- fun emit(name: String, payload: Map<String, Any?>) {
245
- if (id <= 0) return
246
- val dispatcher = UIManagerHelper.getEventDispatcherForReactTag(ctx, id) ?: return
247
- dispatcher.dispatchEvent(QvpEvent(UIManagerHelper.getSurfaceId(this), id, name, Marshal.toMap(payload)))
230
+ /**
231
+ * The `dress` prop: {ornaments: set id, ...spec}. A new object dresses the page again and null
232
+ * undresses it. The hosted [QvpPageView] paints the layer behind the ink (qvp_dress_geometry,
233
+ * through the placements it applies to the ink, rasterised once per dress revision and scale)
234
+ * and fits the content plus the dress overflow. True when the page changed.
235
+ */
236
+ private fun applyDress(p: QvpPage): Boolean {
237
+ if (dressProp == appliedDress) return false
238
+ appliedDress = dressProp
239
+ val d = dressProp
240
+ val set = d?.let { QvpOrnamentSets.get((it["ornaments"] as? Number)?.toInt()) }
241
+ val info = when {
242
+ d == null -> { p.undress(); null }
243
+ set == null -> { p.undress(); emit("onError", mapOf("message" to "dress: no ornament set ${d["ornaments"]}")); null }
244
+ else -> p.dress(set, Marshal.dressSpec(d))
245
+ }
246
+ emit("onDressChanged", mapOf("info" to info?.let { Marshal.dressInfo(it) }))
247
+ return true
248
248
  }
249
+ /** The module's imperative dress: dress, fit the border in, draw. */
250
+ fun dressNow(p: QvpPage, set: QvpOrnaments, spec: QvpDressSpec): QvpDressInfo? = p.dress(set, spec).also { resetView(); inner.invalidate() }
251
+ fun undressNow(p: QvpPage) { p.undress(); resetView(); inner.invalidate() }
252
+
253
+ fun emit(name: String, payload: Map<String, Any?>) = QvpRnEvents.emit(ctx, this, name, payload)
249
254
 
250
255
  fun stats(): Map<String, Any?> = mapOf("loadMs" to loadMs, "bytes" to pageBytes, "baseMs" to inner.lastBaseMs, "overlayMs" to inner.lastOverlayMs, "basePaths" to inner.lastBasePaths, "overlayPaths" to inner.lastOverlayPaths,
251
256
  "bands" to inner.lastBands, "hitUs" to inner.lastHitUs, "animating" to inner.animating, "styleHandles" to (page?.styleHandles()?.size ?: 0), "highlightHandles" to (page?.highlightHandles()?.size ?: 0),
@@ -0,0 +1,144 @@
1
+ package ws.quran.qvp.rn
2
+
3
+ import android.graphics.Canvas
4
+ import android.graphics.Paint
5
+ import android.util.Log
6
+ import android.view.View
7
+ import com.facebook.react.uimanager.ThemedReactContext
8
+ import ws.quran.qvp.*
9
+
10
+ /**
11
+ * The React Native host of a passage: a range of complete ayahs, or a surah's basmalah, laid out on
12
+ * rows of this view's width and drawn here. The engine loads, measures and places every word; this
13
+ * class reads the pages the props name, hands the engine a spec in dp, draws the layout and reports
14
+ * it to JS. Nothing is decided here.
15
+ */
16
+ class QvpRnPassageView(private val ctx: ThemedReactContext) : View(ctx) {
17
+ private val density = ctx.resources.displayMetrics.density
18
+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
19
+
20
+ // ── desired props (set by the manager) ──
21
+ var pageUris: List<String> = emptyList()
22
+ var surahProp = 0
23
+ var fromProp = 0
24
+ var toProp = 0
25
+ var basmalahProp = false
26
+ /** dp per page unit; [lineHeightProp] wins when it is set. */
27
+ var scaleProp = 1f
28
+ /** dp per printed line: the scale is this over the passage's printed line spacing. */
29
+ var lineHeightProp = 0f
30
+ var lineSpacingProp = 1f
31
+ var paddingProp = 2f
32
+ var alignProp: String? = null
33
+ var maxRowsProp = 0
34
+ var keepAyahMarkProp = false
35
+ var ellipsisWidthProp = 0f
36
+ var maxStretchProp = 0f
37
+ var inkProp: String? = null
38
+ var paperColor = 0
39
+
40
+ // ── applied state ──
41
+ private var loadedKey: String? = null
42
+ private var pages: List<QvpPage> = emptyList()
43
+ private var pagesByNumber: Map<Int, QvpPage> = emptyMap()
44
+ private var passage: QvpPassage? = null
45
+ private var layoutKey: String? = null
46
+ private var layout: QvpPassageLayout? = null
47
+
48
+ fun destroy() {
49
+ passage?.close(); passage = null
50
+ pages.forEach { it.close() }; pages = emptyList(); pagesByNumber = emptyMap()
51
+ loadedKey = null; layoutKey = null; layout = null
52
+ }
53
+
54
+ /** Called by the manager after every prop batch. */
55
+ fun commit() {
56
+ try {
57
+ ensurePassage()
58
+ relayout()
59
+ invalidate()
60
+ } catch (e: Exception) {
61
+ Log.e("QvpRn", "passage commit failed", e)
62
+ emit("onError", mapOf("message" to (e.message ?: e.toString())))
63
+ }
64
+ }
65
+
66
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
67
+ super.onSizeChanged(w, h, oldw, oldh)
68
+ if (w != oldw) commit()
69
+ }
70
+
71
+ private fun ensurePassage() {
72
+ val key = "${pageUris.joinToString("|")}#$surahProp:$fromProp-$toProp:$basmalahProp"
73
+ if (key == loadedKey) return
74
+ destroy()
75
+ loadedKey = key
76
+ if (pageUris.isEmpty() || surahProp <= 0) return
77
+ // The passage copies what it needs, but a draw names a path by its page, so the pages stay
78
+ // open for as long as the passage is drawn. Each page goes into `pages` as it opens, so a
79
+ // URI that fails after it leaves nothing for `destroy` to miss.
80
+ val loaded = ArrayList<QvpPage>(pageUris.size)
81
+ pages = loaded
82
+ for (uri in pageUris) loaded.add(QvpPage(QvpRnBytes.read(ctx, uri)).also { p -> p.buildPaths() })
83
+ pagesByNumber = loaded.associateBy { it.pageNo }
84
+ passage = if (basmalahProp) QvpPassage.basmalah(loaded, surahProp)
85
+ else QvpPassage.load(loaded, surahProp, fromProp, if (toProp > 0) toProp else fromProp)
86
+ }
87
+
88
+ private fun relayout() {
89
+ val p = passage ?: return
90
+ if (width <= 0) return
91
+ val widthDp = width / density
92
+ // dp per page unit: the host's scale, or the dp it wants one printed line to take
93
+ val scale = if (lineHeightProp > 0f && p.lineSpacing > 0f) lineHeightProp / p.lineSpacing else scaleProp
94
+ val align = when (alignProp) {
95
+ "center", "centre" -> QvpPassageAlign.CENTER
96
+ "justified" -> QvpPassageAlign.JUSTIFIED
97
+ else -> QvpPassageAlign.RIGHT
98
+ }
99
+ val maxRows = maxRowsProp.coerceAtLeast(0)
100
+ // The view draws the ellipsis after a cut, so it knows how wide one is: three dots as
101
+ // tall as a row, unless the host reserved a width of its own.
102
+ val ellipsisWidth = if (ellipsisWidthProp > 0f || maxRows == 0) ellipsisWidthProp else {
103
+ paint.textSize = scale * p.lineSpacing
104
+ paint.measureText(ELLIPSIS)
105
+ }
106
+ val spec = QvpPassageSpec(width = widthDp, scale = scale, lineSpacing = lineSpacingProp, padding = paddingProp,
107
+ align = align, maxRows = maxRows, keepAyahMark = keepAyahMarkProp,
108
+ ellipsisWidth = ellipsisWidth, maxStretch = maxStretchProp)
109
+ val key = spec.toString()
110
+ if (key == layoutKey) return
111
+ val l = p.layout(spec)
112
+ layoutKey = key
113
+ layout = l
114
+ if (l == null) {
115
+ emit("onError", mapOf("message" to "the passage spec is out of range: $spec"))
116
+ return
117
+ }
118
+ emit("onPassageLayout", Marshal.passageLayoutMap(l, p))
119
+ }
120
+
121
+ override fun onDraw(canvas: Canvas) {
122
+ val l = layout ?: return
123
+ if (paperColor != 0) { paint.color = paperColor; canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint) }
124
+ paint.color = Marshal.color(inkProp, QvpDefaults.INK).let { QvpColor.argb(it) }
125
+ canvas.save()
126
+ // the layout is in dp; the canvas is in px
127
+ canvas.scale(density, density)
128
+ l.draw(canvas, pagesByNumber, paint)
129
+ // The engine leaves the ellipsis to the host: three dots in the ink, as tall as the row
130
+ // the cut left room on.
131
+ l.ellipsis?.let { e ->
132
+ paint.textSize = e.height()
133
+ paint.textAlign = Paint.Align.CENTER
134
+ canvas.drawText(ELLIPSIS, e.centerX(), e.bottom, paint)
135
+ }
136
+ canvas.restore()
137
+ }
138
+
139
+ private fun emit(name: String, payload: Map<String, Any?>) = QvpRnEvents.emit(ctx, this, name, payload)
140
+
141
+ private companion object {
142
+ const val ELLIPSIS = "\u2026"
143
+ }
144
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quran.ws/qvp-react-native",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
4
4
  "description": "React Native wrapper for the QVP vector mushaf engine (Android; iOS TODO). Thin marshalling over the Kotlin library, which is JNI over qvp.h.",
5
5
  "main": "src/index.tsx",
6
6
  "types": "src/index.tsx",
@@ -10,6 +10,7 @@
10
10
  "src",
11
11
  "android/build.gradle",
12
12
  "android/src",
13
+ "!android/src/test",
13
14
  "README.md",
14
15
  "package.json"
15
16
  ],
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,
@@ -23,6 +23,8 @@ export const CATEGORY = { NONE: 0, HARAKAH: 1, TANWIN: 2, LETTER_DOT: 3, ORTHOGR
23
23
  export const DECORATION = { AYAH_MARK: 0, SURAH_NAME: 1, BASMALAH: 2, DIVISION_MARK: 3, SAJDAH_MARK: 4 } as const;
24
24
  export const LAYER = { BASE: 0, THEME: 10, HIGHLIGHT: 50, SELECTION: 60, TOP: 100 } as const;
25
25
  export const DIVISION = { JUZ: 0, HIZB: 1, NISF: 2, RUBU_AL_HIZB: 3 } as const;
26
+ /** The three kinds of ornament a page can be dressed in, in engine order. Pass one to `find` or `ofKind`. */
27
+ export const ORNAMENT_KIND = ['ayah_mark', 'surah_header', 'page_frame'] as const;
26
28
 
27
29
  // ── colours ──────────────────────────────────────────────────────────────────────────────────
28
30
  export type Color = string | number;
@@ -102,7 +104,9 @@ export interface SurahHeader { decoration: number; surah: number; line: number;
102
104
  export interface Rosette { decoration: number; surah: number; ayah: number; juz: number; hizb: number; nisf: number; rubuAlHizb: number; rubuAlHizbInHizb: number }
103
105
  export interface Sajdah { decoration: number; surah: number; ayah: number; signPath: number }
104
106
  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[][] }
107
+ /** A zoom and pan of the page: the scale and the offset of its origin. */
108
+ export interface ViewState { scale: number; offsetX: number; offsetY: number }
109
+ 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
110
  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
111
  export interface AtlasSurah { number: number; page: number; ayahCount: number; place: string; arabic: string; latin: string; english: string }
108
112
  export interface AtlasRubuAlHizb { rubuAlHizb: number; surah: number; ayah: number; page: number; ayahKey: string }
@@ -118,6 +122,44 @@ export interface Mask { target?: Target; from?: number; mode?: MaskMode; blockCo
118
122
  /** Greyed-page reveal: `revealStart(lit, byAyah, grey, ink, ayahMarks, ms)` then `revealGoto(at)` whenever `at` changes; null → revealStop. */
119
123
  export interface Reveal { lit?: number; byAyah?: boolean; grey?: Color; ink?: Color; ayahMarks?: boolean; ms?: number; at?: number }
120
124
 
125
+ // ── dress: another mushaf's ornaments ──
126
+ /** The kind of an ornament, as `docs/API.md` names it. */
127
+ export type OrnamentKind = 'ayah_mark' | 'surah_header' | 'page_frame';
128
+ /** Where an ornament comes from: a scanned mushaf or a font. */
129
+ export type Lineage = 'scan' | 'font';
130
+ /** One printed colour of an ornament. `color` is 0xRRGGBBAA; alpha 0 is the design's slot. */
131
+ export interface OrnamentPart { index: number; color: number; stroke: boolean; name: string }
132
+ /** What an ornament may be redistributed under. Read it before you publish a dressed page. */
133
+ export interface Licence { id: string; status: string; redistributable: boolean; attribution: string }
134
+ export interface Ornament { index: number; kind: OrnamentKind; lineage: Lineage; style: string; riwayah: string; hasSlices: boolean; licence: Licence; parts: OrnamentPart[] }
135
+ /** One mushaf or font of a set, with the ornament it has of each kind or null. */
136
+ export interface OrnamentStyle { style: string; riwayah: string; lineage: Lineage; ayahMark: Ornament | null; surahHeader: Ornament | null; pageFrame: Ornament | null }
137
+ /** An ornament of the set, its index, or a style name (the ornament of that kind in that style). */
138
+ export type OrnamentRef = Ornament | number | string | null;
139
+ /**
140
+ * What to dress a page in. `style` names a mushaf and takes its medallion, band and border
141
+ * together; a kind key overrides the style for that kind. `gap` is the air between the text and
142
+ * the border and `bandGap` the air between a band and the border, both in page units.
143
+ * `ayahMarkScale` 0 takes the design's own size. `lineArt` is `true` for every kind or a list of
144
+ * kinds. `colors` repaints parts: `[ornament, part, colour]`.
145
+ */
146
+ export interface DressSpec {
147
+ style?: string | null;
148
+ ayahMark?: OrnamentRef; surahHeader?: OrnamentRef; pageFrame?: OrnamentRef;
149
+ gap?: number; bandGap?: number; ayahMarkScale?: number; pageFrameScale?: number;
150
+ lineArt?: boolean | OrnamentKind[];
151
+ colors?: [Ornament | number, number, Color][];
152
+ }
153
+ /** The engine's readout of a dressed page. `viewBox` is [x, y, w, h] in page units; `overflow` is
154
+ * [left, top, right, bottom] in viewport px, how far the border reaches past the content. */
155
+ export interface DressInfo {
156
+ ayahMark: number | null; surahHeader: number | null; pageFrame: number | null;
157
+ ayahMarks: number; surahHeaders: number; frameRepeats: number; frameStretched: boolean;
158
+ draws: number; revision: number; viewBox: [number, number, number, number]; overflow: [number, number, number, number];
159
+ }
160
+ /** The `dress` prop: a spec plus the ornament set it names. */
161
+ export interface Dress extends DressSpec { ornaments: QvpOrnaments | number }
162
+
121
163
  // ── the view ─────────────────────────────────────────────────────────────────────────────────
122
164
  /** What a pinch does to the page: the engine owns the policy, this names which one. */
123
165
  export type ZoomMode = 'stepped' | 'continuous' | 'magnify';
@@ -149,6 +191,9 @@ export interface QvpPageViewProps extends ViewProps {
149
191
  highlights?: Highlight[];
150
192
  mask?: Mask | null;
151
193
  reveal?: Reveal | null;
194
+ /** Another mushaf's ornaments, painted behind the ink. Native compares the spec by value: an equal
195
+ * 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. */
196
+ dress?: Dress | null;
152
197
  onWordTap?: (e: { word: Word; hit: Hit }) => void;
153
198
  onDecorationTap?: (e: { decoration: Deco; hit: Hit }) => void;
154
199
  onEmptyTap?: () => void;
@@ -161,9 +206,13 @@ export interface QvpPageViewProps extends ViewProps {
161
206
  onSwipe?: (e: { pages: number }) => void;
162
207
  /** The size the reader is at changed: a pinch committed, or a step was asked for. */
163
208
  onZoomChanged?: (e: Zoom) => void;
209
+ /** The `dress` prop was applied: the engine's readout, or null when it refused the spec or the page is undressed. */
210
+ onDressChanged?: (e: { info: DressInfo | null }) => void;
164
211
  onError?: (e: { message: string }) => void;
165
212
  }
166
- type NativeProps = ViewProps & Omit<QvpPageViewProps, 'onWordTap' | 'onDecorationTap' | 'onEmptyTap' | 'onSelectionChanged' | 'onPageLoad' | 'onRevealChanged' | 'onSwipe' | 'onZoomChanged' | 'onError'> & {
213
+ type NativeProps = ViewProps & Omit<QvpPageViewProps, 'dress' | 'onWordTap' | 'onDecorationTap' | 'onEmptyTap' | 'onSelectionChanged' | 'onPageLoad' | 'onRevealChanged' | 'onSwipe' | 'onZoomChanged' | 'onDressChanged' | 'onError'> & {
214
+ dress?: object | null;
215
+ onDressChanged?: (e: NativeSyntheticEvent<{ info: DressInfo | null }>) => void;
167
216
  onWordTap?: (e: NativeSyntheticEvent<{ word: Word; hit: Hit }>) => void;
168
217
  onDecorationTap?: (e: NativeSyntheticEvent<{ decoration: Deco; hit: Hit }>) => void;
169
218
  onEmptyTap?: (e: NativeSyntheticEvent<{}>) => void;
@@ -195,7 +244,7 @@ export type QvpPageViewHandle = PageApi & { tag: () => number };
195
244
 
196
245
  export const QvpPageView = forwardRef<QvpPageViewHandle, QvpPageViewProps>(function QvpPageView(props, ref) {
197
246
  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;
247
+ const { theme, styles, highlights, mask, reveal, dress, paperColor, defaultInk, selectionBand, onWordTap, onDecorationTap, onEmptyTap, onSelectionChanged, onPageLoad, onRevealChanged, onSwipe, onZoomChanged, onDressChanged, onError, ...rest } = props;
199
248
  const tag = () => findNodeHandle(native.current) ?? -1;
200
249
  useImperativeHandle(ref, () => ({ tag, ...bindPage(tag) }), []);
201
250
  const nTheme = useMemo(() => (theme ? normColors(theme) : null), [theme]);
@@ -203,6 +252,7 @@ export const QvpPageView = forwardRef<QvpPageViewHandle, QvpPageViewProps>(funct
203
252
  const nHighlights = useMemo(() => (highlights ? normColors(highlights) : []), [highlights]);
204
253
  const nMask = useMemo(() => (mask ? normColors(mask) : null), [mask]);
205
254
  const nReveal = useMemo(() => (reveal ? normColors(reveal) : null), [reveal]);
255
+ const nDress = useMemo(() => (dress ? { ...dressSpec(dress), ornaments: ornamentsId(dress.ornaments) } : null), [dress]);
206
256
  return (
207
257
  <NativeQvpPageView
208
258
  ref={native}
@@ -215,6 +265,7 @@ export const QvpPageView = forwardRef<QvpPageViewHandle, QvpPageViewProps>(funct
215
265
  highlights={nHighlights}
216
266
  mask={nMask}
217
267
  reveal={nReveal}
268
+ dress={nDress}
218
269
  onWordTap={onWordTap ? (e: NativeSyntheticEvent<{ word: Word; hit: Hit }>) => onWordTap(e.nativeEvent) : undefined}
219
270
  onDecorationTap={onDecorationTap ? (e: NativeSyntheticEvent<{ decoration: Deco; hit: Hit }>) => onDecorationTap(e.nativeEvent) : undefined}
220
271
  onEmptyTap={onEmptyTap ? () => onEmptyTap() : undefined}
@@ -223,11 +274,78 @@ export const QvpPageView = forwardRef<QvpPageViewHandle, QvpPageViewProps>(funct
223
274
  onRevealChanged={onRevealChanged ? (e: NativeSyntheticEvent<{ steps: number; at: number | null }>) => onRevealChanged(e.nativeEvent) : undefined}
224
275
  onSwipe={onSwipe ? (e: NativeSyntheticEvent<{ pages: number }>) => onSwipe(e.nativeEvent) : undefined}
225
276
  onZoomChanged={onZoomChanged ? (e: NativeSyntheticEvent<Zoom>) => onZoomChanged(e.nativeEvent) : undefined}
277
+ onDressChanged={onDressChanged ? (e: NativeSyntheticEvent<{ info: DressInfo | null }>) => onDressChanged(e.nativeEvent) : undefined}
226
278
  onError={onError ? (e: NativeSyntheticEvent<{ message: string }>) => onError(e.nativeEvent) : undefined}
227
279
  />
228
280
  );
229
281
  });
230
282
 
283
+ // ── the passage view ─────────────────────────────────────────────────────────────────────────
284
+ /** Where the rows of a passage start: at the right edge, in the middle, or across the width. */
285
+ export type PassageAlign = 'right' | 'center' | 'justified';
286
+ export interface PassageRow { x0: number; y0: number; x1: number; y1: number; baseline: number }
287
+ /** One word of a laid-out passage with its signs, in dp: its key, the page it is printed on and its row.
288
+ * `x0`…`y1` is the word and its signs; `wordX0`…`wordY1` is the word alone, which leaves out the signs:
289
+ * the word that closes an ayah leaves its medallion out. */
290
+ export interface PassageWord { surah: number; ayah: number; word: number; wordKey: string; page: number; row: number; x0: number; y0: number; x1: number; y1: number;
291
+ wordX0: number; wordY0: number; wordX1: number; wordY1: number }
292
+ export interface PassageAyah { surah: number; ayah: number; x0: number; y0: number; x1: number; y1: number }
293
+ export interface PassageText { surah: number; ayah: number; text: string }
294
+ /** A laid-out passage, in dp. `printedLineSpacing` is the passage's printed line, in page units: what
295
+ * `lineHeight` divides by. `ellipsis` is where the view drew the ellipsis after a cut. */
296
+ export interface PassageLayout {
297
+ width: number; height: number; scale: number; lineSpacing: number; printedLineSpacing: number;
298
+ isTruncated: boolean; ellipsis: number[] | null;
299
+ rows: PassageRow[]; words: PassageWord[]; ayahs: PassageAyah[]; texts: PassageText[];
300
+ }
301
+ export interface QvpPassageViewProps extends ViewProps {
302
+ /** The pages that print the range, in any order; the same URI schemes as `pageUri`. */
303
+ pageUris: string[];
304
+ surah: number;
305
+ /** The first and last ayah; `to` defaults to `from`. Left out for a basmalah. */
306
+ from?: number; to?: number;
307
+ /** The basmalah printed above `surah`, one row and no words. Surahs 1 and 9 have none. */
308
+ basmalah?: boolean;
309
+ /** dp per page unit (1), or `lineHeight`: dp per printed line, which wins when both are given. */
310
+ scale?: number; lineHeight?: number;
311
+ /** Leading as a multiple of the printed line (1), and the padding around the rows in dp (2). */
312
+ lineSpacing?: number; padding?: number;
313
+ align?: PassageAlign;
314
+ /** Cut the passage after this many rows (0 = no cut), with room for an ellipsis this wide in dp.
315
+ * `keepAyahMark` puts the medallion of the last ayah after the ellipsis. */
316
+ maxRows?: number; ellipsisWidth?: number; keepAyahMark?: boolean;
317
+ /** How far a justified row's gaps may open, as a multiple of the usual air (0 = the engine's default). */
318
+ maxStretch?: number;
319
+ ink?: Color; paperColor?: Color;
320
+ /** The layout the engine made for this width. The view takes its height from it unless the style gives one. */
321
+ onPassageLayout?: (e: PassageLayout) => void;
322
+ onError?: (e: { message: string }) => void;
323
+ }
324
+ type NativePassageProps = ViewProps & Omit<QvpPassageViewProps, 'onPassageLayout' | 'onError' | 'ink' | 'paperColor'> & {
325
+ ink?: string; paperColor?: string;
326
+ onPassageLayout?: (e: NativeSyntheticEvent<PassageLayout>) => void;
327
+ onError?: (e: NativeSyntheticEvent<{ message: string }>) => void;
328
+ };
329
+ const NativeQvpPassageView = requireNativeComponent<NativePassageProps>('QvpPassageView') as HostComponent<NativePassageProps>;
330
+
331
+ /** A range of complete ayahs, or a surah's basmalah, laid out on rows of this view's width and drawn
332
+ * natively. The engine lays it out; JS sees the layout through `onPassageLayout`. */
333
+ export function QvpPassageView(props: QvpPassageViewProps) {
334
+ const { ink, paperColor, onPassageLayout, onError, style, ...rest } = props;
335
+ // The height is the engine's answer for the width, so it arrives with the first layout.
336
+ const [height, setHeight] = useState<number | undefined>(undefined);
337
+ return (
338
+ <NativeQvpPassageView
339
+ {...rest}
340
+ style={[{ height }, style]}
341
+ ink={css(ink)}
342
+ paperColor={css(paperColor)}
343
+ onPassageLayout={(e: NativeSyntheticEvent<PassageLayout>) => { setHeight(e.nativeEvent.height); onPassageLayout?.(e.nativeEvent); }}
344
+ onError={onError ? (e: NativeSyntheticEvent<{ message: string }>) => onError(e.nativeEvent) : undefined}
345
+ />
346
+ );
347
+ }
348
+
231
349
  // ── the module ───────────────────────────────────────────────────────────────────────────────
232
350
  const M = NativeModules.QvpModule as any;
233
351
 
@@ -238,6 +356,11 @@ const FAMILY_NAMES: string[] = NAMES.families ?? [];
238
356
  const CATEGORY_NAMES: string[] = NAMES.categories ?? [];
239
357
  const DECORATION_NAMES: string[] = NAMES.decorations ?? [];
240
358
  export const MARKS: string[] = NAMES.marks ?? [];
359
+ /** The engine's defaults a host shows, read from the native module (QVP_DEFAULT_* in qvp.h). */
360
+ export const DEFAULTS = {
361
+ /** The size a scanned medallion takes when `ayahMarkScale` is 0, in rings. */
362
+ AYAH_MARK_SCALE_SCAN: ((NAMES as any).defaults?.ayahMarkScaleScan ?? 0) as number,
363
+ };
241
364
  /** A name's id in a table; 255 when the table has no such name. */
242
365
  export type NameTable = 'marks' | 'kinds' | 'families' | 'categories' | 'decorations' | 'divisions' | 'places';
243
366
  const named = (v: string | number, names: string[]) => { if (typeof v === 'number') return v; const i = names.indexOf(v); return i < 0 ? 255 : i; };
@@ -307,6 +430,18 @@ export const Qvp = {
307
430
  revealStepOf: (tag: number, i: number): Promise<number> => M.revealStepOf(tag, i),
308
431
  cropBounds: (tag: number, target: Target, opts?: CropOptions): Promise<CropBox | null> => M.cropBounds(tag, target, opts ?? null),
309
432
  cropSvg: (tag: number, target: Target, opts?: CropOptions): Promise<string | null> => M.cropSvg(tag, target, opts ? { ...opts, background: css(opts.background) } : null),
433
+ /** Dress the page in a set's ornaments; the readout, or null when the engine refused the spec. Replaces any previous dress. */
434
+ dress: (tag: number, set: QvpOrnaments | number, spec: DressSpec = {}): Promise<DressInfo | null> => M.dress(tag, ornamentsId(set), dressSpec(spec)),
435
+ /** Take the ornaments off: the printed rings and bands come back. */
436
+ undress: (tag: number): Promise<void> => M.undress(tag),
437
+ /** 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. */
438
+ dressClamp: (tag: number, view: ViewState, viewportW: number, viewportH: number): Promise<ViewState> => M.dressClamp(tag, view.scale, view.offsetX, view.offsetY, viewportW, viewportH),
439
+ /** 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. */
440
+ dressView: (tag: number, scale: number, viewportW: number): Promise<{ view: ViewState; width: number; height: number }> => M.dressView(tag, scale, viewportW),
441
+ /** The readout, or null when the page is not dressed. */
442
+ dressInfo: (tag: number): Promise<DressInfo | null> => M.dressInfo(tag),
443
+ /** Counts up on every rebuild of the ornament layer: a new dress, and every layout. 0 when undressed. */
444
+ dressRevision: (tag: number): Promise<number> => M.dressRevision(tag),
310
445
 
311
446
  // engine-wide
312
447
  strip: (s: string): Promise<string> => M.arabic('strip', s),
@@ -341,6 +476,16 @@ export const Qvp = {
341
476
  atlasJuzOf: (id: number, s: number, a: number): Promise<number | null> => M.atlasJuzOf(id, s, a),
342
477
  atlasPagesOfJuz: (id: number, n: number): Promise<[number, number] | null> => M.atlasPagesOfJuz(id, n),
343
478
  atlasSearchSurahs: (id: number, text: string): Promise<AtlasSurah[]> => M.atlasSearchSurahs(id, text),
479
+
480
+ // ornament sets (ornaments.qvo)
481
+ loadOrnaments: (uri: string): Promise<number> => M.loadOrnaments(uri),
482
+ freeOrnaments: (id: number): Promise<void> => M.freeOrnaments(id),
483
+ ornamentCount: (id: number): Promise<number> => M.ornamentCount(id),
484
+ ornamentInfo: (id: number, index: number): Promise<Ornament | null> => M.ornamentInfo(id, index),
485
+ ornamentPart: (id: number, index: number, part: number): Promise<OrnamentPart | null> => M.ornamentPart(id, index, part),
486
+ ornamentList: (id: number): Promise<Ornament[]> => M.ornamentList(id),
487
+ /** The index of the ornament of `kind` in `style`, or -1. */
488
+ ornamentFind: (id: number, kind: OrnamentKind, style: string): Promise<number> => M.ornamentFind(id, kind, style),
344
489
  };
345
490
 
346
491
  /** Cross-page lookup (atlas.qva). `const atlas = await QvpAtlas.load('asset://pages/atlas.qva')`. */
@@ -364,8 +509,63 @@ export class QvpAtlas {
364
509
  searchSurahs(text: string) { return Qvp.atlasSearchSurahs(this.id, text); }
365
510
  }
366
511
 
512
+ /**
513
+ * An ornament set (ornaments.qvo): the medallions, bands and borders of other mushafs and fonts.
514
+ * None of these outlines is part of a page, and each one carries its own licence.
515
+ * `const set = await QvpOrnaments.load('asset://pages/ornaments.qvo')`.
516
+ */
517
+ export class QvpOrnaments {
518
+ /** Every ornament of the set, in the set's order. */
519
+ readonly count: number;
520
+ private constructor(public readonly id: number, public readonly list: Ornament[]) { this.count = list.length; }
521
+ /** Load a set from a URI (the same schemes as `pageUri`; `base64:…` for bytes in hand). */
522
+ static async load(uri: string): Promise<QvpOrnaments> {
523
+ const id = await Qvp.loadOrnaments(uri);
524
+ return new QvpOrnaments(id, await Qvp.ornamentList(id));
525
+ }
526
+ free() { return Qvp.freeOrnaments(this.id); }
527
+ /** The ornament of `kind` in `style`, or null; the engine looks it up. */
528
+ async find(kind: OrnamentKind, style: string): Promise<Ornament | null> {
529
+ const i = await Qvp.ornamentFind(this.id, kind, style);
530
+ return i < 0 ? null : this.list[i] ?? null;
531
+ }
532
+ /** The ornaments of one kind. */
533
+ ofKind(kind: OrnamentKind): Ornament[] { return this.list.filter(o => o && o.kind === kind); }
534
+ /** Every style in the set with the ornament it has of each kind or null, in the set's order. */
535
+ styles(): OrnamentStyle[] {
536
+ const out: OrnamentStyle[] = [];
537
+ const key = { ayah_mark: 'ayahMark', surah_header: 'surahHeader', page_frame: 'pageFrame' } as const;
538
+ for (const o of this.list) {
539
+ if (!o) continue;
540
+ let s = out.find(x => x.style === o.style);
541
+ if (!s) { s = { style: o.style, riwayah: o.riwayah, lineage: o.lineage, ayahMark: null, surahHeader: null, pageFrame: null }; out.push(s); }
542
+ s[key[o.kind]] = o;
543
+ }
544
+ return out;
545
+ }
546
+ }
547
+ const ornamentsId = (set: QvpOrnaments | number) => (typeof set === 'number' ? set : set.id);
548
+ /** A spec as the native side reads it: ornaments as indices or style names, colours as '#rrggbbaa'. */
549
+ function dressSpec(spec: DressSpec): object {
550
+ const ref = (v: OrnamentRef | undefined) => (v == null ? null : typeof v === 'object' ? v.index : v);
551
+ return {
552
+ // A kind key that is left out takes the style; a kind key set to null is none. A style name
553
+ // stays a name: the native side asks the engine for the ornament of that kind.
554
+ ayahMark: ref(spec.ayahMark === undefined ? spec.style : spec.ayahMark),
555
+ surahHeader: ref(spec.surahHeader === undefined ? spec.style : spec.surahHeader),
556
+ pageFrame: ref(spec.pageFrame === undefined ? spec.style : spec.pageFrame),
557
+ gap: spec.gap, bandGap: spec.bandGap, ayahMarkScale: spec.ayahMarkScale, pageFrameScale: spec.pageFrameScale,
558
+ lineArt: spec.lineArt === true ? ['ayah_mark', 'surah_header', 'page_frame'] : Array.isArray(spec.lineArt) ? spec.lineArt : [],
559
+ // A colour that does not parse is skipped, not sent as a transparent repaint.
560
+ colors: (spec.colors ?? []).flatMap(([o, part, colour]) => {
561
+ const c = css(colour);
562
+ return c === undefined ? [] : [[typeof o === 'object' ? o.index : o, part, c]];
563
+ }),
564
+ };
565
+ }
566
+
367
567
  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;
568
+ 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
569
  type PageMethod = (typeof pageMethods)[number];
370
570
  export type PageApi = { [K in PageMethod]: Tail<(typeof Qvp)[K]> };
371
571
  function bindPage(tag: () => number): PageApi {