@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,467 @@
1
+ // @quran.ws/qvp-react-native, iOS. The React Native host of QvpKit's QvpPageView.
2
+ import UIKit
3
+ import React
4
+
5
+ /// What the module's query queue reads of one view: the page in view, its word records and how
6
+ /// it loaded, behind one lock. It holds no UIKit object, so a query that outlives the view
7
+ /// releases nothing UIKit off the main thread. The main thread writes it where the page is
8
+ /// replaced, closed or given a words sidecar. Each write waits for the queries in progress.
9
+ final class QvpRnPageState {
10
+ private let lock: UnsafeMutablePointer<pthread_rwlock_t> = {
11
+ let l = UnsafeMutablePointer<pthread_rwlock_t>.allocate(capacity: 1)
12
+ l.initialize(to: pthread_rwlock_t())
13
+ pthread_rwlock_init(l, nil)
14
+ return l
15
+ }()
16
+ private var page: QvpPage?
17
+ private var wordTable: QvpRnWords?
18
+ private var loadMs = 0.0
19
+ private var pageBytes = 0
20
+
21
+ deinit {
22
+ pthread_rwlock_destroy(lock)
23
+ lock.deinitialize(count: 1)
24
+ lock.deallocate()
25
+ }
26
+
27
+ /// Run `block` on the page in view and how it loaded, held open until the block returns:
28
+ /// nil when no page is loaded. The block must not wait for the main thread, which can be
29
+ /// waiting for this lock.
30
+ func read<T>(_ block: (QvpPage?, _ loadMs: Double, _ bytes: Int) throws -> T) rethrows -> T {
31
+ pthread_rwlock_rdlock(lock); defer { pthread_rwlock_unlock(lock) }
32
+ return try block(page.flatMap { $0.isOpen ? $0 : nil }, loadMs, pageBytes)
33
+ }
34
+ private func write<T>(_ block: () throws -> T) rethrows -> T {
35
+ pthread_rwlock_wrlock(lock); defer { pthread_rwlock_unlock(lock) }
36
+ return try block()
37
+ }
38
+ /// Put `p` in view with how it loaded, and drop the word records of the page before.
39
+ func swap(_ p: QvpPage?, loadMs: Double, bytes: Int) {
40
+ write { page = p; wordTable = nil; self.loadMs = loadMs; pageBytes = bytes }
41
+ }
42
+ /// Attach a words sidecar. Queries in progress finish first, and the word records built
43
+ /// before it are dropped, since the forms they hold have changed.
44
+ func attachWords(_ p: QvpPage, _ json: String) -> Int { write { let n = p.attachWords(json); wordTable = nil; return n } }
45
+ /// Close the page in view, after the queries in progress.
46
+ func close() { write { page?.close(); page = nil; wordTable = nil } }
47
+ /// How the page in view loaded: milliseconds and bytes.
48
+ var load: (ms: Double, bytes: Int) { read { _, ms, bytes in (ms, bytes) } }
49
+
50
+ private let wordsLock = NSLock()
51
+ /// The word records of `p`, built on first use and kept until the page changes or takes a sidecar.
52
+ func words(_ p: QvpPage) -> QvpRnWords {
53
+ wordsLock.lock(); defer { wordsLock.unlock() }
54
+ if let w = wordTable, w.page === p { return w }
55
+ let w = QvpRnWords(p); wordTable = w; return w
56
+ }
57
+ }
58
+
59
+ /// The React Native host of `QvpPageView`. It owns the loaded `QvpPage`, loads bytes from the
60
+ /// prop-given URI, and reconciles the declarative props (theme, styles, highlights, mask, reveal,
61
+ /// dress) against engine handles, so JS never sees a handle. Every decision (hit test, layout,
62
+ /// style resolution, bands, masks) is the engine's. This class marshals and forwards, as
63
+ /// android/.../QvpRnPageView.kt does.
64
+ ///
65
+ /// The module reads the page from its query queue while this view draws on the main thread,
66
+ /// through `state`. Those reads touch only what the page fixed when it loaded.
67
+ ///
68
+ /// Lengths are in points, which are the dp of the JS side.
69
+ @objc(QvpRnPageView)
70
+ final class QvpRnPageView: UIView {
71
+ /// QvpKit's renderer, hosted rather than subclassed.
72
+ let inner = QvpPageView(frame: .zero)
73
+ var page: QvpPage? { inner.page }
74
+ /// What the module's query queue reads.
75
+ let state = QvpRnPageState()
76
+ /// The word records of `p`, built once per page.
77
+ func words(_ p: QvpPage) -> QvpRnWords { state.words(p) }
78
+ /// Attach a words sidecar to the page in view.
79
+ func attachWords(_ p: QvpPage, _ json: String) -> Int { state.attachWords(p, json) }
80
+ var loadMs: Double { state.load.ms }
81
+ var pageBytes: Int { state.load.bytes }
82
+
83
+ override init(frame: CGRect) {
84
+ super.init(frame: frame)
85
+ inner.frame = bounds
86
+ inner.autoresizingMask = [.flexibleWidth, .flexibleHeight]
87
+ addSubview(inner)
88
+ inner.onWordTap = { [weak self] w, h in
89
+ guard let self, let p = self.page else { return }
90
+ self.emit(self.onWordTap, ["word": self.words(p).word(w.index), "hit": QvpRnMarshal.hit(p, h)])
91
+ }
92
+ inner.onDecorationTap = { [weak self] d, h in
93
+ guard let self, let p = self.page else { return }
94
+ self.emit(self.onDecorationTap, ["decoration": QvpRnMarshal.decoration(d), "hit": QvpRnMarshal.hit(p, h)])
95
+ }
96
+ inner.onEmptyTap = { [weak self] in self?.emit(self?.onEmptyTap, [:]) }
97
+ // The engine says a flick turns the page and by how many, in reading order. Which page
98
+ // that is belongs to the app, so this is an event and not a page change.
99
+ inner.onSwipe = { [weak self] pages in self?.emit(self?.onSwipe, ["pages": pages]) }
100
+ inner.onZoomChanged = { [weak self] z in
101
+ self?.emit(self?.onZoomChanged, ["mode": QvpRnMarshal.jsName(z.mode), "step": z.step, "zoom": z.zoom])
102
+ }
103
+ inner.onSelectionChanged = { [weak self] _ in
104
+ guard let self, let p = self.page else { return }
105
+ self.emit(self.onSelectionChanged, QvpRnMarshal.selection(p))
106
+ }
107
+ }
108
+ required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
109
+ deinit { destroy() }
110
+
111
+ /// React Native dropped the view: React Native removes it from its parent when it unmounts
112
+ /// it, and never moves it to another. Close the page now, as Android's onDropViewInstance
113
+ /// does, rather than when the last reference goes.
114
+ private var mounted = false
115
+ override func didMoveToSuperview() {
116
+ super.didMoveToSuperview()
117
+ if superview != nil { mounted = true } else if mounted { destroy() }
118
+ }
119
+ /// Unregister, and close the page after the queries in progress. A later prop batch loads
120
+ /// the page again.
121
+ func destroy() {
122
+ QvpRnRegistry.unregister(self)
123
+ inner.page = nil
124
+ state.close()
125
+ loadedKey = nil
126
+ }
127
+
128
+ // ── events ──
129
+ @objc var onWordTap: RCTDirectEventBlock?
130
+ @objc var onDecorationTap: RCTDirectEventBlock?
131
+ @objc var onEmptyTap: RCTDirectEventBlock?
132
+ @objc var onSelectionChanged: RCTDirectEventBlock?
133
+ @objc var onPageLoad: RCTDirectEventBlock?
134
+ @objc var onRevealChanged: RCTDirectEventBlock?
135
+ @objc var onSwipe: RCTDirectEventBlock?
136
+ @objc var onZoomChanged: RCTDirectEventBlock?
137
+ @objc var onDressChanged: RCTDirectEventBlock?
138
+ @objc var onError: RCTDirectEventBlock?
139
+ private func emit(_ block: RCTDirectEventBlock?, _ payload: [String: Any?]) { block?(QvpRnMarshal.toJsMap(payload)) }
140
+
141
+ // ── props (set by the manager; `commit` applies a batch in one pass) ──
142
+ @objc var pageUri: String? { didSet { changed() } }
143
+ @objc var pageBase64: String? { didSet { changed() } }
144
+ @objc var wordsUri: String? { didSet { changed() } }
145
+ @objc var padTop: CGFloat = 0 { didSet { inner.padTop = padTop; layoutDirty = true; changed() } }
146
+ @objc var padBottom: CGFloat = 0 { didSet { inner.padBottom = padBottom; layoutDirty = true; changed() } }
147
+ @objc var padSide: CGFloat = 0 { didSet { inner.padSide = padSide; layoutDirty = true; changed() } }
148
+ @objc var lineSpacing: CGFloat = 1 { didSet { inner.lineSpacing = Float(lineSpacing); layoutDirty = true; changed() } }
149
+ @objc var reflowBreaks: String? {
150
+ didSet {
151
+ let v = reflowBreaks?.lowercased()
152
+ inner.reflowBreaks = [QvpBreaks.greedy, .even, .fitted, .printed].first { "\($0)" == v } ?? .fitted
153
+ layoutDirty = true; changed()
154
+ }
155
+ }
156
+ @objc var fillHeight = false { didSet { inner.fillHeight = fillHeight; layoutDirty = true; changed() } }
157
+ @objc var surahFrames = true { didSet { inner.surahFrames = surahFrames; layoutDirty = true; changed() } }
158
+ @objc var paperColor: String? {
159
+ didSet {
160
+ let s = paperColor?.trimmingCharacters(in: .whitespaces) ?? ""
161
+ inner.paperColor = s.isEmpty ? nil : UIColor(cgColor: QvpColor.cgColor(QvpRnMarshal.color(s, 0)))
162
+ inner.setNeedsDisplay()
163
+ }
164
+ }
165
+ @objc var defaultInk: String? { didSet { changed() } }
166
+ @objc var selectionBand: String? {
167
+ didSet { if let s = selectionBand, !s.trimmingCharacters(in: .whitespaces).isEmpty { inner.selectionBand = QvpRnMarshal.color(s, inner.selectionBand) } }
168
+ }
169
+ @objc var selectionEnabled = true { didSet { inner.selectionEnabled = selectionEnabled } }
170
+ @objc var zoomEnabled = true { didSet { inner.zoomEnabled = zoomEnabled } }
171
+ @objc var zoomMode: String? { didSet { changed() } }
172
+ @objc var zoomStep: Int = -1 { didSet { changed() } }
173
+ @objc var hitMaxDistance: CGFloat = CGFloat(QvpDefaults.TAP_DISTANCE) { didSet { inner.hitOptions.maxDistance = Float(hitMaxDistance) } }
174
+ @objc var theme: NSDictionary? { didSet { changed() } }
175
+ @objc var styles: NSArray? { didSet { changed() } }
176
+ @objc var highlights: NSArray? { didSet { changed() } }
177
+ /// The `mask` prop. UIView has a `mask` of its own, so QvpModule.m maps the prop to this name.
178
+ @objc var maskProp: NSDictionary? { didSet { changed() } }
179
+ @objc var reveal: NSDictionary? { didSet { changed() } }
180
+ @objc var dress: NSDictionary? { didSet { changed() } }
181
+ private var layoutDirty = true
182
+
183
+ // ── applied state ──
184
+ private var loadedKey: String?
185
+ private var appliedTheme: NSDictionary?
186
+ private var themeHandle = 0
187
+ private struct Rule { let handle: Int; let entry: NSDictionary }
188
+ private var styleHandles: [(id: String, rule: Rule)] = []
189
+ private var highlightHandles: [(id: String, rule: Rule)] = []
190
+ private var appliedMask: NSDictionary?
191
+ private var appliedReveal: NSDictionary? // without "at"
192
+ private var appliedRevealAt: Int?
193
+ private var appliedDress: NSDictionary?
194
+ private var appliedInk: UInt32?
195
+ private(set) var revealStepCount = 0
196
+
197
+ /// A prop changed: commit once, after the rest of the batch has been set.
198
+ private var commitQueued = false
199
+ private func changed() {
200
+ // React Native sets the tag before the first prop, so the module finds the view from
201
+ // the first prop batch on.
202
+ QvpRnRegistry.register(self)
203
+ if commitQueued { return }
204
+ commitQueued = true
205
+ DispatchQueue.main.async { [weak self] in
206
+ guard let self else { return }
207
+ self.commitQueued = false
208
+ self.commit()
209
+ }
210
+ }
211
+
212
+ override func didMoveToWindow() {
213
+ super.didMoveToWindow()
214
+ if window != nil { QvpRnRegistry.register(self) }
215
+ }
216
+
217
+ /// Fit and centre, as the engine's layout says.
218
+ func resetView() { inner.resetView() }
219
+
220
+ // ── the reader's zoom control ──
221
+ // What a pinch does to the page: reflow onto the page's own steps (the default), reflow to
222
+ // the zoom the fingers ask for, or magnify the printed page. The engine owns the policy;
223
+ // these props only say which one the app wants and which step to sit on.
224
+ private func commitZoom() {
225
+ guard let p = page, p.isOpen else { return }
226
+ if let name = zoomMode {
227
+ let mode: QvpZoomMode = name == "continuous" ? .continuous : name == "magnify" ? .magnify : .stepped
228
+ if mode != inner.zoomMode { inner.zoomMode = mode }
229
+ }
230
+ if zoomStep >= 0, zoomStep != inner.zoom.step { inner.zoomToStep(zoomStep) }
231
+ }
232
+
233
+ /// Apply the props set since the last commit.
234
+ func commit() {
235
+ QvpRnRegistry.register(self)
236
+ do {
237
+ try ensurePage()
238
+ let p = page
239
+ if let p {
240
+ applyInk(p); applyTheme(p); applyStyles(p); applyHighlights(p); applyMask(p); applyReveal(p)
241
+ }
242
+ var fit = false
243
+ if layoutDirty { layoutDirty = false; inner.relayout(); fit = true }
244
+ // After the layout: the engine places the ornaments on the layout in force.
245
+ if let p, applyDress(p) { fit = true }
246
+ if fit { resetView() }
247
+ commitZoom()
248
+ inner.setNeedsDisplay()
249
+ } catch {
250
+ NSLog("QvpRn: commit failed: %@", "\(error)")
251
+ emit(onError, ["message": error.localizedDescription])
252
+ }
253
+ }
254
+
255
+ private func ensurePage() throws {
256
+ let key = pageBase64.map { "b64:\($0.hashValue)" } ?? pageUri
257
+ if key == loadedKey { return }
258
+ // drop everything bound to the old page: handles die with it
259
+ themeHandle = 0; appliedTheme = nil; styleHandles = []; highlightHandles = []; appliedMask = nil; appliedReveal = nil
260
+ appliedRevealAt = nil; appliedInk = nil; appliedDress = nil; revealStepCount = 0
261
+ loadedKey = key
262
+ guard let key else { swap(nil); return }
263
+ // Load the new page before the swap, so a query sees the old page or the new one and
264
+ // never a view with no page. A load that fails leaves no page.
265
+ let p: QvpPage, bytes: Data, ms: Double
266
+ do {
267
+ if let b64 = pageBase64 {
268
+ guard let d = Data(base64Encoded: b64, options: .ignoreUnknownCharacters) else { throw QvpRnError("pageBase64 is not base64") }
269
+ bytes = d
270
+ } else {
271
+ bytes = try QvpRnBytes.read(key)
272
+ }
273
+ let t0 = CFAbsoluteTimeGetCurrent()
274
+ do { p = try QvpPage(bytes: bytes) } catch { throw QvpRnError("not a QVP page: \(key.prefix(64)) (QvpError.\(error))") }
275
+ ms = (CFAbsoluteTimeGetCurrent() - t0) * 1000
276
+ // No query sees the page before the swap below, so the sidecar needs no lock.
277
+ if let w = wordsUri {
278
+ do { _ = p.attachWords(try QvpRnBytes.read(w)) } catch { NSLog("QvpRn: words sidecar: %@", "\(error)") }
279
+ }
280
+ } catch {
281
+ swap(nil)
282
+ throw error
283
+ }
284
+ swap(p, loadMs: ms, bytes: bytes.count)
285
+ layoutDirty = true
286
+ emit(onPageLoad, QvpRnMarshal.pageInfo(p, words(p).forms).merging(["loadMs": ms, "bytes": bytes.count, "uri": pageUri]) { a, _ in a })
287
+ }
288
+ /// Put `p` in view and close the old page, with no query reading either.
289
+ private func swap(_ p: QvpPage?, loadMs: Double = 0, bytes: Int = 0) {
290
+ let old = inner.page
291
+ state.swap(p, loadMs: loadMs, bytes: bytes)
292
+ inner.page = p
293
+ // the state no longer holds the old page, so no query reads it now
294
+ if old !== p { old?.close() }
295
+ }
296
+
297
+ private func applyInk(_ p: QvpPage) {
298
+ let ink = QvpRnMarshal.color(defaultInk, QvpDefaults.INK)
299
+ if appliedInk != ink { appliedInk = ink; p.setDefaultColor(ink) }
300
+ }
301
+ private func applyTheme(_ p: QvpPage) {
302
+ if same(theme, appliedTheme) { return }
303
+ if themeHandle != 0 { p.removeStyle(themeHandle); themeHandle = 0 }
304
+ appliedTheme = theme
305
+ if let t = theme { themeHandle = p.theme(QvpRnMarshal.theme(t as? [String: Any])) }
306
+ }
307
+ /// The entries of a list prop by id, in order; an entry without an id is skipped.
308
+ private func entries(_ list: NSArray?) -> [(id: String, entry: NSDictionary)] {
309
+ var out: [(id: String, entry: NSDictionary)] = []
310
+ for case let m as NSDictionary in (list ?? []) {
311
+ guard let raw = QvpRnMarshal.some(m["id"]) else { continue }
312
+ let id = "\(raw)"
313
+ if let i = out.firstIndex(where: { $0.id == id }) { out[i].entry = m } else { out.append((id, m)) }
314
+ }
315
+ return out
316
+ }
317
+ private func applyStyles(_ p: QvpPage) {
318
+ let want = entries(styles)
319
+ let wantIds = Set(want.map(\.id))
320
+ for r in styleHandles where !wantIds.contains(r.id) { p.removeStyle(r.rule.handle) }
321
+ var old = Dictionary(styleHandles.filter { wantIds.contains($0.id) }.map { ($0.id, $0.rule) }) { a, _ in a }
322
+ var next: [(id: String, rule: Rule)] = []
323
+ for (id, e) in want {
324
+ if let o = old[id], same(o.entry, e) { next.append((id, o)); continue }
325
+ let hide = QvpRnMarshal.isTrue(e["hide"])
326
+ if let o = old[id], !hide, same(o.entry["selector"], e["selector"]), same(o.entry["target"], e["target"]),
327
+ same(o.entry["layer"], e["layer"]), same(o.entry["hide"], e["hide"]) {
328
+ p.recolorStyle(o.handle, QvpRnMarshal.color(e["color"], 0), transitionMs: QvpRnMarshal.num(e["ms"]) ?? 0)
329
+ next.append((id, Rule(handle: o.handle, entry: e))); continue
330
+ }
331
+ if let o = old[id] { p.removeStyle(o.handle); old[id] = nil }
332
+ let ms = QvpRnMarshal.num(e["ms"]) ?? 0
333
+ let layer = QvpRnMarshal.num(e["layer"]) ?? QvpLayer.BASE
334
+ let color = QvpRnMarshal.color(e["color"], 0)
335
+ var h = 0
336
+ if hide { h = QvpRnMarshal.selector(e["selector"]).map { p.hide($0) } ?? 0 }
337
+ else if QvpRnMarshal.some(e["selector"]) != nil { h = QvpRnMarshal.selector(e["selector"]).map { p.style($0, color, transitionMs: ms, layer: layer) } ?? 0 }
338
+ else if QvpRnMarshal.some(e["target"]) != nil { h = p.styleTarget(QvpRnMarshal.target(e["target"], p), color, transitionMs: ms, layer: layer) }
339
+ if h != 0 { next.append((id, Rule(handle: h, entry: e))) }
340
+ }
341
+ styleHandles = next
342
+ }
343
+ private func applyHighlights(_ p: QvpPage) {
344
+ let want = entries(highlights)
345
+ let wantIds = Set(want.map(\.id))
346
+ for r in highlightHandles where !wantIds.contains(r.id) { p.removeHighlight(r.rule.handle) }
347
+ let old = Dictionary(highlightHandles.filter { wantIds.contains($0.id) }.map { ($0.id, $0.rule) }) { a, _ in a }
348
+ var next: [(id: String, rule: Rule)] = []
349
+ for (id, e) in want {
350
+ guard let o = old[id] else {
351
+ let h = p.highlight(QvpRnMarshal.target(e["target"], p), QvpRnMarshal.highlightStyle(e["style"]))
352
+ if h != 0 { next.append((id, Rule(handle: h, entry: e))) }
353
+ continue
354
+ }
355
+ if !same(o.entry, e) {
356
+ if !same(o.entry["style"], e["style"]) { p.restyleHighlight(o.handle, QvpRnMarshal.highlightStyle(e["style"])) }
357
+ if !same(o.entry["target"], e["target"]) { p.moveHighlight(o.handle, QvpRnMarshal.target(e["target"], p)) }
358
+ }
359
+ next.append((id, Rule(handle: o.handle, entry: e)))
360
+ }
361
+ highlightHandles = next
362
+ }
363
+ private func applyMask(_ p: QvpPage) {
364
+ if same(maskProp, appliedMask) { return }
365
+ appliedMask = maskProp
366
+ p.unmask()
367
+ guard let m = maskProp else { return }
368
+ p.maskOptions(blockColor: QvpRnMarshal.color(m["blockColor"], QvpDefaults.MASK_BLOCK), padX: QvpRnMarshal.flt(m["padX"], QvpDefaults.MASK_PAD),
369
+ padY: QvpRnMarshal.flt(m["padY"], QvpDefaults.MASK_PAD), radius: QvpRnMarshal.flt(m["radius"], QvpDefaults.MASK_RADIUS),
370
+ reverse: QvpRnMarshal.isTrue(m["reverse"]))
371
+ if let from = QvpRnMarshal.num(m["from"]) { p.maskFrom(from, QvpRnMarshal.maskMode(m["mode"])) }
372
+ else { p.mask(QvpRnMarshal.target(m["target"], p), QvpRnMarshal.maskMode(m["mode"])) }
373
+ }
374
+ private func applyReveal(_ p: QvpPage) {
375
+ let r = reveal
376
+ let cfg: NSDictionary? = r.map { d in
377
+ let m = NSMutableDictionary(dictionary: d); m.removeObject(forKey: "at"); return m
378
+ }
379
+ if !same(cfg, appliedReveal) {
380
+ appliedReveal = cfg; appliedRevealAt = nil
381
+ guard let cfg else { p.revealStop(); revealStepCount = 0; emit(onRevealChanged, ["steps": 0, "at": nil]); return }
382
+ revealStepCount = p.revealStart(lit: QvpRnMarshal.num(cfg["lit"]) ?? QvpDefaults.REVEAL_LIT, byAyah: QvpRnMarshal.isTrue(cfg["byAyah"]),
383
+ grey: QvpRnMarshal.color(cfg["grey"], QvpDefaults.REVEAL_GREY), ink: QvpRnMarshal.color(cfg["ink"], appliedInk ?? QvpDefaults.INK),
384
+ ayahMarks: !QvpRnMarshal.isFalse(cfg["ayahMarks"]), transitionMs: QvpRnMarshal.num(cfg["ms"]) ?? 0)
385
+ emit(onRevealChanged, ["steps": revealStepCount, "at": -1])
386
+ }
387
+ guard let r else { return }
388
+ let at = QvpRnMarshal.num(r["at"]) ?? -1
389
+ if at != appliedRevealAt { appliedRevealAt = at; p.revealGoto(at) }
390
+ }
391
+
392
+ /// The `dress` prop: {ornaments: set id, ...spec}. A new object dresses the page again and
393
+ /// null undresses it. The hosted QvpPageView paints the layer behind the ink and fits the
394
+ /// content plus the dress overflow. True when the page changed.
395
+ private func applyDress(_ p: QvpPage) -> Bool {
396
+ if same(dress, appliedDress) { return false }
397
+ appliedDress = dress
398
+ var info: DressInfo?
399
+ if let d = dress {
400
+ if let set = QvpOrnamentSets.get(QvpRnMarshal.num(d["ornaments"])) {
401
+ info = p.dress(set, QvpRnMarshal.dressSpec(d as? [String: Any]))
402
+ } else {
403
+ p.undress()
404
+ emit(onError, ["message": "dress: no ornament set \(QvpRnMarshal.some(d["ornaments"]).map { "\($0)" } ?? "null")"])
405
+ }
406
+ } else {
407
+ p.undress()
408
+ }
409
+ emit(onDressChanged, ["info": info.map { QvpRnMarshal.dressInfo($0) }])
410
+ return true
411
+ }
412
+ /// The module's imperative dress: dress, fit the border in, draw.
413
+ func dressNow(_ p: QvpPage, _ set: QvpOrnaments, _ spec: DressSpec) -> DressInfo? {
414
+ let info = p.dress(set, spec); resetView(); inner.setNeedsDisplay(); return info
415
+ }
416
+ func undressNow(_ p: QvpPage) { p.undress(); resetView(); inner.setNeedsDisplay() }
417
+
418
+ func stats() -> [String: Any?] {
419
+ ["loadMs": state.load.ms, "bytes": state.load.bytes, "baseMs": inner.lastBaseMs, "overlayMs": inner.lastOverlayMs, "basePaths": inner.lastBasePaths,
420
+ "overlayPaths": inner.lastOverlayPaths, "bands": inner.lastBands, "hitUs": inner.lastHitUs, "animating": inner.animating,
421
+ "styleHandles": page.map { $0.isOpen ? $0.styleHandles().count : 0 } ?? 0, "highlightHandles": page.map { $0.isOpen ? $0.highlightHandles().count : 0 } ?? 0,
422
+ "engineVersion": QvpEngine.version(), "viewScale": Double(inner.viewScale), "layout": page?.currentLayout.map { QvpRnMarshal.layout($0) }]
423
+ }
424
+ }
425
+
426
+ /// Two prop values compared by value, as Kotlin compares its maps: nil and JS null are equal.
427
+ func same(_ a: Any?, _ b: Any?) -> Bool {
428
+ let x = QvpRnMarshal.some(a), y = QvpRnMarshal.some(b)
429
+ if x == nil || y == nil { return x == nil && y == nil }
430
+ return (x as AnyObject).isEqual(y)
431
+ }
432
+
433
+ /// Views by react tag, so the module can find the page behind a `viewTag`. The main thread
434
+ /// registers and looks up views. The query queue looks up only a view's state, which holds no
435
+ /// UIKit object, so no view is retained or released off the main thread. The registry holds a
436
+ /// view weakly, and a view leaves it when React Native drops it.
437
+ enum QvpRnRegistry {
438
+ private final class Entry {
439
+ weak var view: QvpRnPageView?
440
+ let id: ObjectIdentifier
441
+ let state: QvpRnPageState
442
+ init(_ v: QvpRnPageView) { view = v; id = ObjectIdentifier(v); state = v.state }
443
+ }
444
+ private static let lock = NSLock()
445
+ private static var entries: [Int: Entry] = [:]
446
+ /// Main thread.
447
+ static func register(_ v: QvpRnPageView) {
448
+ guard let tag = v.reactTag?.intValue, tag > 0 else { return }
449
+ lock.lock(); defer { lock.unlock() }
450
+ if entries[tag]?.id != ObjectIdentifier(v) { entries[tag] = Entry(v) }
451
+ }
452
+ /// Main thread, and the view's deinit.
453
+ static func unregister(_ v: QvpRnPageView) {
454
+ let id = ObjectIdentifier(v)
455
+ lock.lock(); entries = entries.filter { $0.value.id != id }; lock.unlock()
456
+ }
457
+ /// The view with this tag. Main thread only.
458
+ static func get(_ tag: Int) -> QvpRnPageView? {
459
+ lock.lock(); defer { lock.unlock() }
460
+ return entries[tag]?.view
461
+ }
462
+ /// The state of the view with this tag. Any thread.
463
+ static func state(_ tag: Int) -> QvpRnPageState? {
464
+ lock.lock(); defer { lock.unlock() }
465
+ return entries[tag]?.state
466
+ }
467
+ }
@@ -0,0 +1,160 @@
1
+ // @quran.ws/qvp-react-native, iOS. The React Native host of a passage.
2
+ import UIKit
3
+ import React
4
+
5
+ /// The React Native host of a passage: a range of complete ayahs, or a surah's basmalah, laid out
6
+ /// on rows of this view's width and drawn here. The engine loads, measures and places every word.
7
+ /// This class reads the pages the props name, hands the engine a spec in points, draws the layout
8
+ /// and reports it to JS. Nothing is decided here, as in android/.../QvpRnPassageView.kt.
9
+ @objc(QvpRnPassageView)
10
+ final class QvpRnPassageView: UIView {
11
+ // ── props (set by the manager) ──
12
+ @objc var pageUris: [String] = [] { didSet { changed() } }
13
+ @objc var surah = 0 { didSet { changed() } }
14
+ @objc var from = 0 { didSet { changed() } }
15
+ @objc var to = 0 { didSet { changed() } }
16
+ @objc var basmalah = false { didSet { changed() } }
17
+ /// Points per page unit; `lineHeight` wins when it is set.
18
+ @objc var scale: CGFloat = 1 { didSet { changed() } }
19
+ /// Points per printed line: the scale is this over the passage's printed line spacing.
20
+ @objc var lineHeight: CGFloat = 0 { didSet { changed() } }
21
+ @objc var lineSpacing: CGFloat = 1 { didSet { changed() } }
22
+ @objc var padding: CGFloat = 2 { didSet { changed() } }
23
+ @objc var align: String? { didSet { changed() } }
24
+ @objc var maxRows = 0 { didSet { changed() } }
25
+ @objc var keepAyahMark = false { didSet { changed() } }
26
+ @objc var ellipsisWidth: CGFloat = 0 { didSet { changed() } }
27
+ @objc var maxStretch: CGFloat = 0 { didSet { changed() } }
28
+ @objc var ink: String? { didSet { setNeedsDisplay() } }
29
+ @objc var paperColor: String? { didSet { setNeedsDisplay() } }
30
+ @objc var onPassageLayout: RCTDirectEventBlock?
31
+ @objc var onError: RCTDirectEventBlock?
32
+
33
+ // ── applied state ──
34
+ private var loadedKey: String?
35
+ private var pages: [QvpPage] = []
36
+ private var pagesByNumber: [Int: QvpPage] = [:]
37
+ private var passage: QvpPassage?
38
+ private var layoutKey: String?
39
+ private var passageLayout: QvpPassageLayout?
40
+
41
+ override init(frame: CGRect) {
42
+ super.init(frame: frame)
43
+ isOpaque = false
44
+ backgroundColor = .clear
45
+ contentMode = .redraw
46
+ }
47
+ required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
48
+ deinit { destroy() }
49
+
50
+ /// React Native dropped the view: it removes the view from its parent when it unmounts it,
51
+ /// and never moves it to another. Close the pages now, as Android's onDropViewInstance does.
52
+ private var mounted = false
53
+ override func didMoveToSuperview() {
54
+ super.didMoveToSuperview()
55
+ if superview != nil { mounted = true } else if mounted { destroy() }
56
+ }
57
+
58
+ private func destroy() {
59
+ passage?.close(); passage = nil
60
+ pages.forEach { $0.close() }; pages = []; pagesByNumber = [:]
61
+ loadedKey = nil; layoutKey = nil; passageLayout = nil
62
+ }
63
+
64
+ private var commitQueued = false
65
+ private func changed() {
66
+ if commitQueued { return }
67
+ commitQueued = true
68
+ DispatchQueue.main.async { [weak self] in
69
+ guard let self else { return }
70
+ self.commitQueued = false
71
+ self.commit()
72
+ }
73
+ }
74
+
75
+ /// Apply the props set since the last commit.
76
+ func commit() {
77
+ do {
78
+ try ensurePassage()
79
+ relayout()
80
+ setNeedsDisplay()
81
+ } catch {
82
+ NSLog("QvpRn: passage commit failed: %@", "\(error)")
83
+ emit(onError, ["message": error.localizedDescription])
84
+ }
85
+ }
86
+
87
+ private var lastWidth: CGFloat = 0
88
+ override func layoutSubviews() {
89
+ super.layoutSubviews()
90
+ if bounds.width != lastWidth { lastWidth = bounds.width; commit() }
91
+ }
92
+
93
+ private func ensurePassage() throws {
94
+ let key = "\(pageUris.joined(separator: "|"))#\(surah):\(from)-\(to):\(basmalah)"
95
+ if key == loadedKey { return }
96
+ destroy()
97
+ loadedKey = key
98
+ guard !pageUris.isEmpty, surah > 0 else { return }
99
+ // The passage copies what it needs, but a draw names a path by its page, so the pages
100
+ // stay open for as long as the passage is drawn. Each page goes into `pages` as it opens,
101
+ // so a URI that fails after it leaves nothing for `destroy` to miss.
102
+ for uri in pageUris {
103
+ let bytes = try QvpRnBytes.read(uri)
104
+ let p: QvpPage
105
+ do { p = try QvpPage(bytes: bytes) } catch { throw QvpRnError("not a QVP page: \(uri) (QvpError.\(error))") }
106
+ pages.append(p)
107
+ }
108
+ pagesByNumber = Dictionary(pages.map { ($0.pageNo, $0) }) { a, _ in a }
109
+ do {
110
+ passage = basmalah ? try QvpPassage(basmalahOf: surah, pages: pages)
111
+ : try QvpPassage(pages: pages, surah: surah, from: from, to: to > 0 ? to : from)
112
+ } catch {
113
+ throw QvpRnError((basmalah ? "no basmalah of surah \(surah) on the pages given" : "the pages given do not hold \(surah):\(from)-\(to > 0 ? to : from)") + " (QvpError.\(error))")
114
+ }
115
+ }
116
+
117
+ private func relayout() {
118
+ guard let p = passage, bounds.width > 0 else { return }
119
+ // points per page unit: the host's scale, or the points it wants one printed line to take
120
+ let s = lineHeight > 0 && p.lineSpacing > 0 ? Float(lineHeight) / p.lineSpacing : Float(scale)
121
+ let a: QvpPassageAlign = align == "center" || align == "centre" ? .center : align == "justified" ? .justified : .right
122
+ let rows = max(maxRows, 0)
123
+ // The view draws the ellipsis after a cut, so it knows how wide one is: three dots as
124
+ // tall as a row, unless the host reserved a width of its own.
125
+ let ew: Float = ellipsisWidth > 0 || rows == 0 ? Float(ellipsisWidth)
126
+ : Float((Self.ellipsis as NSString).size(withAttributes: [.font: UIFont.systemFont(ofSize: CGFloat(s * p.lineSpacing))]).width)
127
+ let spec = QvpPassageSpec(width: Float(bounds.width), scale: s, lineSpacing: Float(lineSpacing), padding: Float(padding),
128
+ align: a, maxRows: rows, keepAyahMark: keepAyahMark, ellipsisWidth: ew, maxStretch: Float(maxStretch))
129
+ let key = "\(spec)"
130
+ if key == layoutKey { return }
131
+ let l = p.layout(spec)
132
+ layoutKey = key
133
+ passageLayout = l
134
+ guard let l else { emit(onError, ["message": "the passage spec is out of range: \(spec)"]); return }
135
+ emit(onPassageLayout, QvpRnMarshal.passageLayout(l, p))
136
+ }
137
+
138
+ override func draw(_ rect: CGRect) {
139
+ guard let l = passageLayout, let ctx = UIGraphicsGetCurrentContext() else { return }
140
+ let paper = QvpRnMarshal.color(paperColor, 0)
141
+ if paper != 0 { ctx.setFillColor(QvpColor.cgColor(paper)); ctx.fill(bounds) }
142
+ let inkColor = QvpColor.cgColor(QvpRnMarshal.color(ink, QvpDefaults.INK))
143
+ ctx.setFillColor(inkColor)
144
+ // the layout is in points, and so is the context
145
+ l.draw(in: ctx, pages: pagesByNumber)
146
+ // The engine leaves the ellipsis to the host: three dots in the ink, as tall as the row
147
+ // the cut left room on.
148
+ if let e = l.ellipsis {
149
+ let font = UIFont.systemFont(ofSize: e.height)
150
+ let text = Self.ellipsis as NSString
151
+ let size = text.size(withAttributes: [.font: font])
152
+ text.draw(at: CGPoint(x: e.midX - size.width / 2, y: e.maxY - font.ascender),
153
+ withAttributes: [.font: font, .foregroundColor: UIColor(cgColor: inkColor)])
154
+ }
155
+ }
156
+
157
+ private func emit(_ block: RCTDirectEventBlock?, _ payload: [String: Any?]) { block?(QvpRnMarshal.toJsMap(payload)) }
158
+
159
+ private static let ellipsis = "\u{2026}"
160
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "url": "https://github.com/quran-ws/quran-engine/releases/download/v0.9.0/QvpEngine.xcframework.zip",
3
+ "sha256": "77b7d5ad6eba4fd1a92f30c747e0325b877ca016fed67726ca7450b86d68f79b"
4
+ }