@quran.ws/qvp-react-native 0.8.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.
@@ -0,0 +1,360 @@
1
+ // @quran.ws/qvp-react-native, iOS. Marshalling only: JS shapes (docs/API.md) to QvpKit types and
2
+ // back. No hit test, layout or style decision lives here. Every call goes to QvpPage, QvpAtlas or
3
+ // QvpOrnaments, which go to the engine. This file mirrors android/.../Marshal.kt key for key, so
4
+ // the two platforms hand JavaScript the same shapes.
5
+ //
6
+ // Targets from JS: "page" | "2:255" | "2:255:3" | "2:255-257" | "line:7" | "surah:2" | word index |
7
+ // [word indices] | {target, a, b, c, words} (target = QVP_TARGET_* or its name in QvpRnCodes).
8
+ // Selectors from JS: {selector, a, b, c} (selector = QVP_SELECTOR_* or its name in QvpRnCodes).
9
+ // Colours: '#rgb' | '#rrggbb' | '#rrggbbaa' | 0xRRGGBBAA.
10
+ //
11
+ // QvpKit's sources compile into this pod's module, so its types need no import.
12
+ import Foundation
13
+
14
+ enum QvpRnMarshal {
15
+ // ── JS values in ──
16
+ /// The value, or nil for a missing value and for JS null.
17
+ static func some(_ v: Any?) -> Any? { v is NSNull ? nil : v }
18
+ static func num(_ v: Any?) -> Int? {
19
+ switch some(v) {
20
+ case let n as NSNumber: return n.intValue
21
+ case let s as String: return Int(s)
22
+ default: return nil
23
+ }
24
+ }
25
+ static func flt(_ v: Any?, _ d: Float) -> Float {
26
+ switch some(v) {
27
+ case let n as NSNumber: return n.floatValue
28
+ case let s as String: return Float(s) ?? d
29
+ default: return d
30
+ }
31
+ }
32
+ static func bool(_ v: Any?, _ d: Bool) -> Bool { (some(v) as? NSNumber)?.boolValue ?? d }
33
+ /// True only for JS `true`, as Kotlin's `v == true`.
34
+ static func isTrue(_ v: Any?) -> Bool { (some(v) as? NSNumber)?.boolValue == true }
35
+ /// False only for JS `false`, as Kotlin's `v == false`: a missing key is not false.
36
+ static func isFalse(_ v: Any?) -> Bool { (some(v) as? NSNumber).map { !$0.boolValue } ?? false }
37
+ static func ints(_ v: Any?) -> [Int] {
38
+ switch some(v) {
39
+ case let a as [Any]: return a.compactMap { num($0) }
40
+ case let n as NSNumber: return [n.intValue]
41
+ default: return []
42
+ }
43
+ }
44
+ static func dict(_ v: Any?) -> [String: Any]? { some(v) as? [String: Any] }
45
+ static func str(_ v: Any?) -> String? { some(v) as? String }
46
+
47
+ // ── colours ──
48
+ /// A colour as 0xRRGGBBAA, or `d` when the value is missing or does not parse.
49
+ static func color(_ v: Any?, _ d: UInt32) -> UInt32 {
50
+ switch some(v) {
51
+ case let s as String:
52
+ let h = s.trimmingCharacters(in: .whitespaces)
53
+ let digits = h.hasPrefix("#") ? String(h.dropFirst()) : h
54
+ // QvpColor.parse reads a bad string as 0; Kotlin's throws and the default stands.
55
+ guard [3, 4, 6, 8].contains(digits.count), digits.allSatisfy({ $0.isASCII && $0.isHexDigit }) else { return d }
56
+ return QvpColor.parse(h)
57
+ case let n as NSNumber: return UInt32(truncatingIfNeeded: n.int64Value)
58
+ default: return d
59
+ }
60
+ }
61
+ /// A colour, or nil when it is missing or transparent black.
62
+ static func colorOrNil(_ v: Any?) -> UInt32? {
63
+ guard some(v) != nil else { return nil }
64
+ let c = color(v, 0)
65
+ return c == 0 ? nil : c
66
+ }
67
+
68
+ /// A code given as a number, or by its name in `names` (or as a numeral); -1 when neither.
69
+ private static func code(_ v: Any?, _ names: [String: Int]) -> Int {
70
+ switch some(v) {
71
+ case let n as NSNumber: return n.intValue
72
+ case let s as String: return names[s] ?? Int(s) ?? -1
73
+ default: return -1
74
+ }
75
+ }
76
+
77
+ /// A JS target as a QvpKit Target. An unknown one is the empty word list.
78
+ static func target(_ v: Any?, _ page: QvpPage?) -> Target {
79
+ switch some(v) {
80
+ case nil: return .page()
81
+ case let s as String: return Target(parsing: s, page: page) ?? .words([])
82
+ case let n as NSNumber: return .word(n.intValue)
83
+ case let a as [Any]: return .words(ints(a))
84
+ case let m as [String: Any]:
85
+ let a = num(m["a"]) ?? 0, b = num(m["b"]) ?? 0, c = num(m["c"]) ?? 0
86
+ switch code(m["target"], QvpRnCodes.TARGETS) {
87
+ case QvpRnCodes.TARGET_PAGE: return .page()
88
+ case QvpRnCodes.TARGET_WORD: return .word(a)
89
+ case QvpRnCodes.TARGET_WORDS: return .words(ints(some(m["words"]) ?? m["a"]))
90
+ case QvpRnCodes.TARGET_AYAH: return .ayah(a, b)
91
+ case QvpRnCodes.TARGET_AYAH_RANGE: return .ayahRange(a, b, c)
92
+ case QvpRnCodes.TARGET_LINE: return .line(a)
93
+ case QvpRnCodes.TARGET_SURAH: return .surah(a)
94
+ case QvpRnCodes.TARGET_RANGE: return .range(a, b)
95
+ default: return .words([])
96
+ }
97
+ default: return .words([])
98
+ }
99
+ }
100
+
101
+ /// A JS selector {selector, a, b, c} as a QvpKit Selector, or nil when it is malformed.
102
+ static func selector(_ v: Any?) -> Selector? {
103
+ guard let m = dict(v) else { return nil }
104
+ let a = num(m["a"]) ?? 0, b = num(m["b"]) ?? 0, c = num(m["c"]) ?? 0
105
+ switch code(m["selector"], QvpRnCodes.SELECTORS) {
106
+ case QvpRnCodes.SELECTOR_PAGE: return .page()
107
+ case QvpRnCodes.SELECTOR_PATH: return .path(a)
108
+ case QvpRnCodes.SELECTOR_WORD_PATH: return .wordPath(a, b)
109
+ case QvpRnCodes.SELECTOR_WORD_MARK: return .wordMark(a, b)
110
+ case QvpRnCodes.SELECTOR_WORD_MARK_NAMED: return .wordMarkNamed(a, str(m["mark"]) ?? QvpEngine.markName(b), c)
111
+ case QvpRnCodes.SELECTOR_WORD_BODY: return .wordBody(a)
112
+ case QvpRnCodes.SELECTOR_WORD_MARKS: return .wordMarks(a)
113
+ case QvpRnCodes.SELECTOR_WORD: return .word(a)
114
+ case QvpRnCodes.SELECTOR_AYAH: return .ayah(a, b)
115
+ case QvpRnCodes.SELECTOR_LINE: return .line(a)
116
+ case QvpRnCodes.SELECTOR_MARK: return str(m["mark"]).map { Selector.mark($0) } ?? .mark(a)
117
+ case QvpRnCodes.SELECTOR_CATEGORY: return .category(a)
118
+ case QvpRnCodes.SELECTOR_FAMILY: return .family(a)
119
+ case QvpRnCodes.SELECTOR_KIND: return .kind(a)
120
+ case QvpRnCodes.SELECTOR_DECORATION: return .decoration(a)
121
+ case QvpRnCodes.SELECTOR_DECORATION_INDEX: return .decorationIndex(a)
122
+ default: return nil
123
+ }
124
+ }
125
+
126
+ /// The case of an Int-backed enum that `v` names, in any of its spellings: the Kotlin
127
+ /// constant's (RASM_IMLAI), snake case (rasm_imlai) or camelCase (rasmImlai). A number is the
128
+ /// raw value.
129
+ static func named<E: RawRepresentable>(_ v: Any?, _ d: E) -> E where E.RawValue == Int {
130
+ switch some(v) {
131
+ case let n as NSNumber: return E(rawValue: n.intValue) ?? d
132
+ case let s as String:
133
+ let key = s.replacingOccurrences(of: "_", with: "").lowercased()
134
+ var i = 0
135
+ while let e = E(rawValue: i) {
136
+ if String(describing: e).lowercased() == key { return e }
137
+ i += 1
138
+ }
139
+ return d
140
+ default: return d
141
+ }
142
+ }
143
+ /// A case's name as the TypeScript types spell it: `rasmImlai`.
144
+ static func jsName<E>(_ e: E) -> String { String(describing: e) }
145
+ /// A case's name as Kotlin's lower-cased constant spells it: `rubuAlHizb` is `rubu_al_hizb`.
146
+ static func snakeName<E>(_ e: E) -> String {
147
+ String(describing: e).reduce(into: "") { out, ch in
148
+ if ch.isUppercase { out += "_" + ch.lowercased() } else { out.append(ch) }
149
+ }
150
+ }
151
+
152
+ static func form(_ v: Any?, _ d: Form = .rasmUthmani) -> Form { named(v, d) }
153
+ static func searchMode(_ v: Any?) -> SearchMode { named(v, .includes) }
154
+ static func maskMode(_ v: Any?) -> MaskMode { named(v, .hide) }
155
+ static func division(_ v: Any?) -> Division { named(v, .juz) }
156
+
157
+ /// {mode, ink, band, height, padX, padY, radius, seam, ms, layer}. A missing key keeps the library default.
158
+ static func highlightStyle(_ v: Any?) -> QvpHighlightStyle {
159
+ let d = QvpHighlightStyle()
160
+ guard let m = dict(v) else { return d }
161
+ return QvpHighlightStyle(mode: named(m["mode"], d.mode), ink: color(m["ink"], d.ink), band: color(m["band"], d.band),
162
+ height: named(m["height"], d.height), padX: flt(m["padX"], d.padX), padY: flt(m["padY"], d.padY),
163
+ radius: flt(m["radius"], d.radius), seam: flt(m["seam"], d.seam),
164
+ transitionMs: num(some(m["ms"]) ?? m["transitionMs"]) ?? d.transitionMs, layer: num(m["layer"]) ?? d.layer)
165
+ }
166
+ /// {ink, diacritics, dots, waqf, sifr, ayahMark, numeral, headers, marks: {name: colour}, ms}.
167
+ static func theme(_ v: Any?) -> QvpTheme {
168
+ guard let m = dict(v) else { return QvpTheme() }
169
+ var marks: [String: UInt32] = [:]
170
+ for (k, c) in dict(m["marks"]) ?? [:] { if let c = colorOrNil(c) { marks[k] = c } }
171
+ return QvpTheme(ink: colorOrNil(m["ink"]), diacritics: colorOrNil(m["diacritics"]), dots: colorOrNil(m["dots"]), waqf: colorOrNil(m["waqf"]),
172
+ sifr: colorOrNil(m["sifr"]), ayahMark: colorOrNil(m["ayahMark"]), numeral: colorOrNil(m["numeral"]), headers: colorOrNil(m["headers"]),
173
+ marks: marks, transitionMs: num(some(m["ms"]) ?? m["transitionMs"]) ?? 0)
174
+ }
175
+
176
+ // ── dress ──
177
+ /// 'ayah_mark' | 'surah_header' | 'page_frame' (or QVP_ORNAMENT_*), or nil.
178
+ static func ornamentKind(_ v: Any?) -> OrnamentKind? {
179
+ switch some(v) {
180
+ case let s as String: return OrnamentKind.allCases.first { $0.name == s.lowercased() }
181
+ case let n as NSNumber: return OrnamentKind(rawValue: n.intValue)
182
+ default: return nil
183
+ }
184
+ }
185
+ /// One kind of a JS spec: an index, a style name, or null for none. JS has already put the
186
+ /// style in each kind, so a missing kind is none and not "take the style".
187
+ private static func ornamentRef(_ v: Any?) -> OrnamentChoice {
188
+ switch some(v) {
189
+ case let n as NSNumber: return .index(n.intValue)
190
+ case let s as String: return .style(s)
191
+ default: return .absent
192
+ }
193
+ }
194
+ /// {ayahMark, surahHeader, pageFrame, gap, bandGap, ayahMarkScale, pageFrameScale, lineArt: [kind],
195
+ /// colors: [[ornament, part, colour]]}. A missing number keeps the library's default.
196
+ static func dressSpec(_ v: Any?) -> DressSpec {
197
+ let d = DressSpec()
198
+ guard let m = dict(v) else { return d }
199
+ let lineArt = Set(((some(m["lineArt"]) as? [Any]) ?? []).compactMap { ornamentKind($0) })
200
+ let colors: [OrnamentColor] = ((some(m["colors"]) as? [Any]) ?? []).compactMap { t in
201
+ guard let l = t as? [Any], l.count >= 2, let o = num(l[0]), let part = num(l[1]) else { return nil }
202
+ return OrnamentColor(ornament: o, part: part, color: color(l.count > 2 ? l[2] : nil, 0))
203
+ }
204
+ return DressSpec(style: nil, ayahMark: ornamentRef(m["ayahMark"]), surahHeader: ornamentRef(m["surahHeader"]), pageFrame: ornamentRef(m["pageFrame"]),
205
+ gap: flt(m["gap"], d.gap), bandGap: flt(m["bandGap"], d.bandGap), ayahMarkScale: flt(m["ayahMarkScale"], d.ayahMarkScale),
206
+ pageFrameScale: flt(m["pageFrameScale"], d.pageFrameScale), lineArt: lineArt, colors: colors)
207
+ }
208
+ static func ornamentPart(_ p: OrnamentPart) -> [String: Any?] {
209
+ ["index": p.index, "color": p.color, "stroke": p.stroke, "name": p.name]
210
+ }
211
+ static func ornament(_ o: Ornament) -> [String: Any?] {
212
+ ["index": o.index, "kind": o.kind.name, "lineage": o.lineage.name, "style": o.style, "riwayah": o.riwayah, "hasSlices": o.hasSlices,
213
+ "licence": ["id": o.licence.id, "status": o.licence.status, "redistributable": o.licence.redistributable, "attribution": o.licence.attribution] as [String: Any?],
214
+ "parts": o.parts.map { ornamentPart($0) }]
215
+ }
216
+ static func dressInfo(_ i: DressInfo) -> [String: Any?] {
217
+ ["ayahMark": i.ayahMark, "surahHeader": i.surahHeader, "pageFrame": i.pageFrame,
218
+ "ayahMarks": i.ayahMarks, "surahHeaders": i.surahHeaders, "frameRepeats": i.frameRepeats, "frameStretched": i.frameStretched,
219
+ "draws": i.draws, "revision": i.revision, "viewBox": i.viewBox, "overflow": i.overflow]
220
+ }
221
+
222
+ // ── QvpKit to JS ──
223
+ /// The engine's name of every id of the path and decoration tables, read once. A page has
224
+ /// hundreds of paths, and each names its kind, mark, category and family: a lookup here is an
225
+ /// array read, not four calls into the engine. Ids run 0 to 255, so the table covers every id
226
+ /// a path can hold.
227
+ private struct Names {
228
+ let kind = (0..<256).map { QvpEngine.kindName($0) }
229
+ let mark = (0..<256).map { QvpEngine.markName($0) }
230
+ let category = (0..<256).map { QvpEngine.categoryName($0) }
231
+ let family = (0..<256).map { QvpEngine.familyName($0) }
232
+ let decoration = (0..<256).map { (k: Int) -> String in let n = QvpEngine.decorationName(k); return n.isEmpty ? "other" : n }
233
+ }
234
+ private static let names = Names()
235
+
236
+ /// The forms a page has: rasmUthmani always, and each other form the words sidecar gave.
237
+ static func forms(_ p: QvpPage) -> [Form] {
238
+ var out: [Form] = []
239
+ var i = 0
240
+ while let f = Form(rawValue: i) { if f == .rasmUthmani || p.hasForm(f) { out.append(f) }; i += 1 }
241
+ return out
242
+ }
243
+
244
+ /// One word and its paths. `forms` is `forms(p)`, read once by the caller.
245
+ static func word(_ p: QvpPage, _ w: QvpWord, _ forms: [Form]) -> [String: Any?] {
246
+ let n = names
247
+ var text: [String: Any?] = [:]
248
+ for f in forms { text[jsName(f)] = p.wordForm(w.index, f) }
249
+ let paths: [[String: Any?]] = (w.firstPath..<(w.firstPath + w.nPaths)).map { i in
250
+ let kind = p.pathKind(i), mark = p.pathMark(i), cat = p.pathCategory(i), fam = p.pathFamily(i)
251
+ return ["index": i, "kind": kind, "kindName": n.kind[kind], "mark": mark, "markName": n.mark[mark], "nthMark": p.pathNthMark(i),
252
+ "nthInWord": p.pathNthInWord(i), "category": cat, "categoryName": n.category[cat], "family": fam, "familyName": n.family[fam], "line": p.pathLine(i)]
253
+ }
254
+ return ["index": w.index, "surah": w.surah, "ayah": w.ayah, "word": w.word, "line": w.line, "lineIndex": w.lineIndex, "ayahIndex": w.ayahIndex,
255
+ "x0": w.x0, "y0": w.y0, "x1": w.x1, "y1": w.y1, "text": w.text, "firstPath": w.firstPath, "nPaths": w.nPaths,
256
+ "wordKey": w.wordKey, "ayahKey": w.ayahKey, "forms": text, "label": p.wordLabel(w.index), "paths": paths]
257
+ }
258
+ static func decoration(_ d: QvpDecoration) -> [String: Any?] {
259
+ ["index": d.index, "decoration": d.decoration, "decorationName": names.decoration[d.decoration & 0xff],
260
+ "surah": d.surah, "ayah": d.ayah, "line": d.line, "x0": d.x0, "y0": d.y0, "x1": d.x1, "y1": d.y1, "text": d.text, "firstPath": d.firstPath, "nPaths": d.nPaths]
261
+ }
262
+ static func hit(_ p: QvpPage, _ h: QvpHit) -> [String: Any?] {
263
+ let w = h.word >= 0 && h.word < p.words.count ? p.words[h.word] : nil
264
+ return ["word": h.word, "path": h.path, "decoration": h.decoration, "line": h.line, "distance": h.distance, "isExact": h.isExact,
265
+ "wordKey": w?.wordKey, "ayahKey": w?.ayahKey]
266
+ }
267
+ static func ayah(_ a: QvpAyah) -> [String: Any?] {
268
+ ["index": a.index, "surah": a.surah, "ayah": a.ayah, "fragment": a.fragment, "fragments": a.fragments, "flags": a.flags, "rubuAlHizb": a.rubuAlHizb,
269
+ "firstWord": a.firstWord, "nWords": a.nWords, "ayahMarkDecoration": a.ayahMarkDecoration, "bbox": [a.x0, a.y0, a.x1, a.y1]]
270
+ }
271
+ static func line(_ l: QvpLine) -> [String: Any?] {
272
+ ["index": l.index, "lineNumber": l.lineNumber, "isHeader": l.isHeader, "firstWord": l.firstWord, "nWords": l.nWords, "bbox": [l.x0, l.y0, l.x1, l.y1],
273
+ "bandY0": l.bandY0, "bandY1": l.bandY1, "centre": l.centre]
274
+ }
275
+ static func surah(_ s: QvpSurah) -> [String: Any?] {
276
+ ["number": s.number, "ayahCount": s.ayahCount, "hasBanner": s.hasBanner, "hasBasmalah": s.hasBasmalah, "place": s.place,
277
+ "bannerDecoration": s.bannerDecoration, "arabic": s.arabic, "latin": s.latin, "english": s.english]
278
+ }
279
+ static func division(_ d: QvpDivision) -> [String: Any?] {
280
+ ["division": snakeName(d.division), "number": d.number, "surah": d.surah, "ayah": d.ayah, "line": d.line, "ayahIndex": d.ayahIndex]
281
+ }
282
+ static func surahHeader(_ h: QvpSurahHeader) -> [String: Any?] {
283
+ ["decoration": h.decoration, "surah": h.surah, "line": h.line, "x0": h.x0, "y0": h.y0, "x1": h.x1, "y1": h.y1,
284
+ "titleX0": h.titleX0, "titleY0": h.titleY0, "titleX1": h.titleX1, "titleY1": h.titleY1]
285
+ }
286
+ static func ayahMark(_ m: QvpAyahMark) -> [String: Any?] {
287
+ ["decoration": m.decoration, "surah": m.surah, "ayah": m.ayah, "line": m.line, "cx": m.cx, "cy": m.cy, "r": m.r,
288
+ "ornamentPath": m.ornamentPath, "numeralPath": m.numeralPath]
289
+ }
290
+ static func rosette(_ r: QvpRosette) -> [String: Any?] {
291
+ ["decoration": r.decoration, "surah": r.surah, "ayah": r.ayah, "juz": r.juz, "hizb": r.hizb, "nisf": r.nisf,
292
+ "rubuAlHizb": r.rubuAlHizb, "rubuAlHizbInHizb": r.rubuAlHizbInHizb]
293
+ }
294
+ static func sajdah(_ s: QvpSajdah) -> [String: Any?] { ["decoration": s.decoration, "surah": s.surah, "ayah": s.ayah, "signPath": s.signPath] }
295
+ static func match(_ m: QvpMatch) -> [String: Any?] { ["word": m.word, "index": m.index, "isLooseMatch": m.isLooseMatch, "wordKey": m.wordKey, "text": m.text] }
296
+ static func passageLayout(_ l: QvpPassageLayout, _ p: QvpPassage) -> [String: Any?] {
297
+ let e = l.ellipsis
298
+ return ["width": l.width, "height": l.height, "scale": l.scale, "lineSpacing": l.lineSpacing, "printedLineSpacing": p.lineSpacing,
299
+ "isTruncated": l.isTruncated, "ellipsis": e.map { [$0.minX, $0.minY, $0.maxX, $0.maxY] },
300
+ "rows": l.rows.map { ["x0": $0.x0, "y0": $0.y0, "x1": $0.x1, "y1": $0.y1, "baseline": $0.baseline] as [String: Any?] },
301
+ "words": l.words.map { ["surah": $0.surah, "ayah": $0.ayah, "word": $0.word, "wordKey": $0.wordKey, "page": $0.page, "row": $0.row,
302
+ "x0": $0.x0, "y0": $0.y0, "x1": $0.x1, "y1": $0.y1,
303
+ "wordX0": $0.wordX0, "wordY0": $0.wordY0, "wordX1": $0.wordX1, "wordY1": $0.wordY1] as [String: Any?] },
304
+ "ayahs": l.ayahs.map { ["surah": $0.surah, "ayah": $0.ayah, "x0": $0.x0, "y0": $0.y0, "x1": $0.x1, "y1": $0.y1] as [String: Any?] },
305
+ "texts": p.ayahs.map { ["surah": $0.surah, "ayah": $0.ayah, "text": $0.text] as [String: Any?] }]
306
+ }
307
+ static func cropBounds(_ c: QvpCropBounds) -> [String: Any?] {
308
+ ["x0": c.x0, "y0": c.y0, "x1": c.x1, "y1": c.y1, "nWords": c.nWords, "ayahMarkDecoration": c.ayahMarkDecoration]
309
+ }
310
+ static func atlasSurah(_ s: QvpAtlasSurah) -> [String: Any?] {
311
+ ["number": s.number, "page": s.page, "ayahCount": s.ayahCount, "place": s.place, "arabic": s.arabic, "latin": s.latin, "english": s.english]
312
+ }
313
+ static func atlasRubuAlHizb(_ r: QvpAtlasRubuAlHizb) -> [String: Any?] {
314
+ ["rubuAlHizb": r.rubuAlHizb, "surah": r.surah, "ayah": r.ayah, "page": r.page, "ayahKey": r.ayahKey]
315
+ }
316
+ static func layout(_ l: QvpLayout) -> [String: Any?] {
317
+ ["scale": l.scale, "offsetX": l.offsetX, "offsetY": l.offsetY, "contentW": l.contentW, "contentH": l.contentH, "lineSpacing": l.lineSpacing,
318
+ "fitScale": l.fitScale, "fitX": l.fitX, "fitY": l.fitY, "lineDy": l.lineDy,
319
+ "slots": l.slotTop.indices.map { [l.slotTop[$0], l.slotBottom[$0]] }]
320
+ }
321
+ static func pageInfo(_ p: QvpPage, _ forms: [Form]) -> [String: Any?] {
322
+ ["page": p.pageNo, "width": p.width, "height": p.height, "nLines": p.nLines, "nAyahs": p.nAyahs, "nWords": p.nWords, "nPaths": p.nPaths,
323
+ "nDecorations": p.nDecorations, "lineSpacing": p.lineSpacing, "forms": forms.map { jsName($0) }]
324
+ }
325
+ static func selection(_ p: QvpPage) -> [String: Any?] {
326
+ let ws = p.selection()
327
+ return ["words": ws, "text": ws.isEmpty ? "" : p.text(.words(ws)), "citation": ws.isEmpty ? "" : p.citation(ws),
328
+ "textWithCitation": ws.isEmpty ? "" : p.selectionText(.rasmUthmani, includeCitation: true)]
329
+ }
330
+
331
+ /// Any Swift value (dictionaries, arrays, numbers, strings, optionals) as a bridge value:
332
+ /// nil is NSNull, a Float is a Double, an enum is its lower-case name.
333
+ static func toJs(_ v: Any?) -> Any {
334
+ guard let v = flatten(v) else { return NSNull() }
335
+ switch v {
336
+ case let d as [String: Any?]: return d.mapValues { toJs($0) }
337
+ case let d as [String: Any]: return d.mapValues { toJs($0) }
338
+ case let a as [Any?]: return a.map { toJs($0) }
339
+ case let a as [Any]: return a.map { toJs($0) }
340
+ case let b as Bool: return b
341
+ case let i as Int: return i
342
+ case let u as UInt32: return NSNumber(value: u)
343
+ case let f as Float: return Double(f)
344
+ case let d as Double: return d
345
+ case let c as CGFloat: return Double(c)
346
+ case let s as String: return s
347
+ case let n as NSNumber: return n
348
+ case is NSNull: return NSNull()
349
+ default: return String(describing: v).lowercased()
350
+ }
351
+ }
352
+ /// The value inside any depth of Optional, or nil when one of them is empty.
353
+ private static func flatten(_ v: Any?) -> Any? {
354
+ guard let v else { return nil }
355
+ let m = Mirror(reflecting: v)
356
+ guard m.displayStyle == .optional else { return v }
357
+ return m.children.first.flatMap { flatten($0.value) }
358
+ }
359
+ static func toJsMap(_ m: [String: Any?]) -> [String: Any] { toJs(m) as? [String: Any] ?? [:] }
360
+ }