react-native-nitro-input 0.4.1 → 0.4.3
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/CHANGELOG.md +28 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +24 -1
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +60 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +290 -137
- package/lib/commonjs/src/NitroNumber.js +94 -29
- package/lib/module/src/NitroNumber.js +94 -29
- package/package.json +1 -1
- package/src/NitroNumber.tsx +121 -54
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.3
|
|
4
|
+
|
|
5
|
+
0.4.2 was never published; its change is part of this release, with the
|
|
6
|
+
selection-drag regression it brought fixed before it shipped.
|
|
7
|
+
|
|
8
|
+
- **Android: a long-press selection drag or cursor drag inside a scroll view
|
|
9
|
+
or pager stays with the field (#73).** The field's edit text never asked
|
|
10
|
+
its parent not to intercept, so a `ScrollView` (or `KeyboardAwareScrollView`,
|
|
11
|
+
or a pager) could take the touch on the first move and cancel the selection
|
|
12
|
+
or cursor drag. The field now holds the touch from the start, keeps it once
|
|
13
|
+
a long-press has started a drag, and otherwise hands it back once the finger
|
|
14
|
+
has moved past the touch slop, unless the field can scroll its own text in
|
|
15
|
+
that direction. A vertical swipe that starts on a field still scrolls the
|
|
16
|
+
page, and a horizontal one still pages a pager, read-only fields included.
|
|
17
|
+
- **Android: a vertical swipe that starts on a field with more text than fits
|
|
18
|
+
scrolls the page.** A single-line field holding a long value can scroll its
|
|
19
|
+
text sideways, and that no longer makes it keep vertical swipes.
|
|
20
|
+
|
|
21
|
+
React Native's own `TextInput` (`ReactEditText`) has both bugs; NitroInput
|
|
22
|
+
has neither.
|
|
23
|
+
- **Android: `NitroNumber` no longer leaks views or hybrids**, behind the
|
|
24
|
+
out-of-memory crashes on low-end phones. The glyph-mask warm-up queue held
|
|
25
|
+
each dropped view until its tasks ran and grew without bound when the
|
|
26
|
+
typography changed often; its tasks are now plain data, owned and cancelled
|
|
27
|
+
per view, and capped. Callback props rooted the component that held them, so
|
|
28
|
+
Hermes never collected an unmounted `NitroNumber`'s hybrid; they now reach the
|
|
29
|
+
component through a `WeakRef`, and the hybrid drops them when its view goes.
|
|
30
|
+
|
|
3
31
|
## 0.4.1
|
|
4
32
|
|
|
5
33
|
- **`NitroInput`'s `tabularNums` prop: tabular digits in any font.** Digits
|
|
@@ -214,7 +214,8 @@ class HybridNitroNumberView(private val context: ThemedReactContext) : HybridNit
|
|
|
214
214
|
override var onSizeChange: ((width: Double, height: Double) -> Unit)? = null
|
|
215
215
|
set(v) {
|
|
216
216
|
field = v
|
|
217
|
-
|
|
217
|
+
// Not `rollingView`: on a dropped hybrid that would make a fresh view to send nothing.
|
|
218
|
+
onMain { attachedView?.resendIntrinsicSize() }
|
|
218
219
|
}
|
|
219
220
|
|
|
220
221
|
// endregion
|
|
@@ -294,6 +295,7 @@ class HybridNitroNumberView(private val context: ThemedReactContext) : HybridNit
|
|
|
294
295
|
*/
|
|
295
296
|
override fun onDropView() {
|
|
296
297
|
recycled = false
|
|
298
|
+
releaseCallbacks()
|
|
297
299
|
onMain {
|
|
298
300
|
attachedView?.release()
|
|
299
301
|
// With view recycling on, Fabric asks for prepareForRecycle right after
|
|
@@ -305,9 +307,30 @@ class HybridNitroNumberView(private val context: ThemedReactContext) : HybridNit
|
|
|
305
307
|
|
|
306
308
|
/** JS called `dispose()` on the ref: same as a drop. */
|
|
307
309
|
override fun dispose() {
|
|
310
|
+
releaseCallbacks()
|
|
308
311
|
onMain { attachedView?.release() }
|
|
309
312
|
}
|
|
310
313
|
|
|
314
|
+
/**
|
|
315
|
+
* Lets go of the JS functions this hybrid holds (`onSizeChange` and the
|
|
316
|
+
* animation and reveal events). Each is a JS function kept alive from
|
|
317
|
+
* native, so Hermes counts it as a root; its closure reaches the
|
|
318
|
+
* component's refs, one of which holds the JS handle to this hybrid, and
|
|
319
|
+
* that handle keeps this hybrid. Held past the drop, that loop is one
|
|
320
|
+
* Hermes can never collect, however large `memorySize` says it is: every
|
|
321
|
+
* dropped NitroNumber stayed (its hybrid, Nitro's C++ part and the
|
|
322
|
+
* function wrappers), ~7,000 of them after a few minutes of a scrolling
|
|
323
|
+
* list. Dropped, the handle is ordinary garbage. A recycled view gets
|
|
324
|
+
* its callbacks back with its new element's props.
|
|
325
|
+
*/
|
|
326
|
+
private fun releaseCallbacks() {
|
|
327
|
+
onSizeChange = null
|
|
328
|
+
onRevealEnd = null
|
|
329
|
+
onRevealMilestone = null
|
|
330
|
+
onAnimationStart = null
|
|
331
|
+
onAnimationEnd = null
|
|
332
|
+
}
|
|
333
|
+
|
|
311
334
|
/**
|
|
312
335
|
* Reported to the JS garbage collector so a dropped view's handle counts as
|
|
313
336
|
* the memory it holds rather than as an empty object; that is what makes
|
|
@@ -24,7 +24,9 @@ import android.util.TypedValue
|
|
|
24
24
|
import android.view.Choreographer
|
|
25
25
|
import android.view.Gravity
|
|
26
26
|
import android.view.KeyEvent
|
|
27
|
+
import android.view.MotionEvent
|
|
27
28
|
import android.view.View
|
|
29
|
+
import android.view.ViewConfiguration
|
|
28
30
|
import android.view.animation.PathInterpolator
|
|
29
31
|
import android.view.inputmethod.EditorInfo
|
|
30
32
|
import android.view.inputmethod.InputConnection
|
|
@@ -416,6 +418,64 @@ class NitroInputView(context: Context) : FrameLayout(context) {
|
|
|
416
418
|
private inner class HiddenEditText(context: Context) : AppCompatEditText(context) {
|
|
417
419
|
var ready = false
|
|
418
420
|
|
|
421
|
+
// Touch hand-off to scrolling parents (#73). The parent may not intercept
|
|
422
|
+
// until the finger has moved past the touch slop; the touch then goes back
|
|
423
|
+
// to it unless the field can scroll its own text in the direction the
|
|
424
|
+
// finger moves. Holding the whole touch instead (any move but a vertical
|
|
425
|
+
// one) broke paging a horizontal pager from a field.
|
|
426
|
+
//
|
|
427
|
+
// React Native's ReactEditText decides on the first move and keeps the
|
|
428
|
+
// touch whenever the field can scroll in any direction. Two of its bugs
|
|
429
|
+
// stay out of here:
|
|
430
|
+
// - A long-press that fired before the decision keeps the touch: the
|
|
431
|
+
// Editor then runs a selection drag (and has already disallowed
|
|
432
|
+
// intercepting) or has just placed the cursor. Handing the touch back
|
|
433
|
+
// let a ScrollView take a selection drag that drifts a little down, or a
|
|
434
|
+
// pager one that runs sideways, and the selection stuck on the first
|
|
435
|
+
// word. A long-press after the hand-back disallows intercepting again
|
|
436
|
+
// by itself, as does a cursor drag in a focused field.
|
|
437
|
+
// - A field whose single line of text is longer than the field can scroll
|
|
438
|
+
// only sideways, so a vertical swipe that starts on it is the page's.
|
|
439
|
+
private var detectScrollMovement = false
|
|
440
|
+
private var longPressed = false
|
|
441
|
+
private var downX = 0f
|
|
442
|
+
private var downY = 0f
|
|
443
|
+
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
|
|
444
|
+
|
|
445
|
+
override fun onTouchEvent(event: MotionEvent): Boolean {
|
|
446
|
+
when (event.actionMasked) {
|
|
447
|
+
MotionEvent.ACTION_DOWN -> {
|
|
448
|
+
detectScrollMovement = true
|
|
449
|
+
longPressed = false
|
|
450
|
+
downX = event.x
|
|
451
|
+
downY = event.y
|
|
452
|
+
parent?.requestDisallowInterceptTouchEvent(true)
|
|
453
|
+
}
|
|
454
|
+
MotionEvent.ACTION_MOVE -> if (detectScrollMovement) {
|
|
455
|
+
val dx = abs(event.x - downX)
|
|
456
|
+
val dy = abs(event.y - downY)
|
|
457
|
+
if (longPressed) {
|
|
458
|
+
detectScrollMovement = false
|
|
459
|
+
} else if (dx > touchSlop || dy > touchSlop) {
|
|
460
|
+
val scrollsItself = if (dy > dx) {
|
|
461
|
+
canScrollVertically(-1) || canScrollVertically(1)
|
|
462
|
+
} else {
|
|
463
|
+
canScrollHorizontally(-1) || canScrollHorizontally(1)
|
|
464
|
+
}
|
|
465
|
+
if (!scrollsItself) parent?.requestDisallowInterceptTouchEvent(false)
|
|
466
|
+
detectScrollMovement = false
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return super.onTouchEvent(event)
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
override fun performLongClick(): Boolean {
|
|
474
|
+
val handled = super.performLongClick()
|
|
475
|
+
if (handled) longPressed = true
|
|
476
|
+
return handled
|
|
477
|
+
}
|
|
478
|
+
|
|
419
479
|
override fun getOffsetForPosition(x: Float, y: Float): Int {
|
|
420
480
|
// A plain field draws its own text and the engine holds no glyphs for
|
|
421
481
|
// it, so the EditText's own mapping is the right one. (Going through the
|
|
@@ -394,11 +394,14 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
394
394
|
/**
|
|
395
395
|
* This font set's digit masks by role (digit, fraction), digit and level,
|
|
396
396
|
* filled from the shared cache: a swapping glyph looks two up every frame,
|
|
397
|
-
* and a lookup there built a key string each time.
|
|
398
|
-
* thread
|
|
397
|
+
* and a lookup there built a key string each time. Filled by the UI
|
|
398
|
+
* thread only: a queued mask lands in the shared cache, never here.
|
|
399
399
|
*/
|
|
400
400
|
private val digitMasks = AtomicReferenceArray<Bitmap>(2 * 10 * (NUMERIC_BLUR_LEVELS + 1))
|
|
401
401
|
|
|
402
|
+
/** Stands for this font set in the warm queue ([WarmExecutor.cancel]), without being it. */
|
|
403
|
+
val warmToken = Any()
|
|
404
|
+
|
|
402
405
|
fun strip(role: GlyphRole, blankZero: Boolean, modulus: Int): Strip? {
|
|
403
406
|
val cell = digitWidth(role)
|
|
404
407
|
if (cell <= 0f || lineHeight <= 0f) return null
|
|
@@ -440,8 +443,6 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
440
443
|
* at its role's height in the line box.
|
|
441
444
|
*/
|
|
442
445
|
fun blurred(role: GlyphRole, digitIndex: Int, level: Int): Bitmap? {
|
|
443
|
-
val cell = digitWidth(role)
|
|
444
|
-
if (cell <= 0f || lineHeight <= 0f) return null
|
|
445
446
|
// Level 0 (or no blur at all) is the glyph unblurred, still a mask: a
|
|
446
447
|
// swapping glyph's two copies must be the same kind of thing, drawn the
|
|
447
448
|
// same way at the same sub-pixel position. Hardware text snaps to whole
|
|
@@ -450,48 +451,68 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
450
451
|
val slot = (if (role == GlyphRole.FRACTION) 10 * (NUMERIC_BLUR_LEVELS + 1) else 0) +
|
|
451
452
|
digitIndex * (NUMERIC_BLUR_LEVELS + 1) + level.coerceIn(0, NUMERIC_BLUR_LEVELS)
|
|
452
453
|
digitMasks.get(slot)?.let { return it }
|
|
453
|
-
|
|
454
|
-
val
|
|
455
|
-
|
|
454
|
+
// A blur the UI thread wants goes to the warm thread, with the warm thread's paint.
|
|
455
|
+
val queued = level > 0 && isMainThread()
|
|
456
|
+
val spec = digitMaskSpec(role, digitIndex, level, if (queued) maskPaints[role.ordinal] else threadPaint(role)) ?: return null
|
|
457
|
+
if (queued && spec.radius > 0) {
|
|
456
458
|
// Not warmed yet (a font or size that just changed): blur it on the
|
|
457
459
|
// warm thread and draw the sharp mask this frame. A blur in onDraw was
|
|
458
460
|
// ANRing low-end phones, see [BlurredGlyphCache].
|
|
459
|
-
val ready = BlurredGlyphCache.peek(cacheKey)
|
|
461
|
+
val ready = BlurredGlyphCache.peek(spec.cacheKey)
|
|
460
462
|
if (ready == null) {
|
|
461
|
-
WarmExecutor.request(
|
|
463
|
+
WarmExecutor.request(spec)
|
|
462
464
|
return blurred(role, digitIndex, 0)
|
|
463
465
|
}
|
|
464
466
|
digitMasks.set(slot, ready)
|
|
465
467
|
return ready
|
|
466
468
|
}
|
|
467
|
-
val mask =
|
|
468
|
-
val text = glyphs[digitIndex]
|
|
469
|
-
val pad = blurPad
|
|
470
|
-
val w = ceil(cell).toInt() + 2 * pad
|
|
471
|
-
val h = ceil(lineHeight).toInt() + 2 * pad
|
|
472
|
-
// An alpha mask, not a coloured bitmap: the glyph's coverage, blurred,
|
|
473
|
-
// that a draw fills with the digit paint's colour. A coloured
|
|
474
|
-
// ARGB_8888 bitmap round-tripped through get/setPixels came back with
|
|
475
|
-
// its whole rectangle faintly inked on the GPU; a mask has no colour
|
|
476
|
-
// to get wrong, and is a quarter of the memory.
|
|
477
|
-
val mask = Bitmap.createBitmap(w, h, Bitmap.Config.ALPHA_8)
|
|
478
|
-
val canvas = Canvas(mask)
|
|
479
|
-
// A paint of its own: the masks are warmed off the main thread, where
|
|
480
|
-
// the digit paint's alpha is being changed by the draws.
|
|
481
|
-
val paint = TextPaint(threadPaint(role)).apply { alpha = 255 }
|
|
482
|
-
canvas.drawText(text, pad + (cell - width(text, role)) / 2f, pad + digitBaseline(role), paint)
|
|
483
|
-
if (radius > 0) boxBlurMask(mask, radius)
|
|
484
|
-
// Immutable and uploaded ahead of its first draw: HWUI re-pins a mutable
|
|
485
|
-
// bitmap at every sync, and the first frame that drew a fresh mask paid
|
|
486
|
-
// for its texture upload.
|
|
487
|
-
val done = mask.copy(Bitmap.Config.ALPHA_8, false) ?: mask
|
|
488
|
-
if (done !== mask) mask.recycle()
|
|
489
|
-
done
|
|
490
|
-
}
|
|
469
|
+
val mask = spec.make()
|
|
491
470
|
digitMasks.set(slot, mask)
|
|
492
471
|
return mask
|
|
493
472
|
}
|
|
494
473
|
|
|
474
|
+
/**
|
|
475
|
+
* What [blurred] draws for [role]'s digit [digitIndex] at [level], as a
|
|
476
|
+
* [MaskSpec]: a paint and a few numbers, so a mask queued for the warm
|
|
477
|
+
* thread holds neither this font set nor the view. Measured on the calling
|
|
478
|
+
* thread; [paint] is the one the mask will be drawn with (the warm
|
|
479
|
+
* thread's own copy, [maskPaints], for a queued one).
|
|
480
|
+
*/
|
|
481
|
+
private fun digitMaskSpec(role: GlyphRole, digitIndex: Int, level: Int, paint: TextPaint): MaskSpec? {
|
|
482
|
+
val cell = digitWidth(role)
|
|
483
|
+
if (cell <= 0f || lineHeight <= 0f) return null
|
|
484
|
+
val radius = blurRadius(level)
|
|
485
|
+
val pad = blurPad
|
|
486
|
+
val text = glyphs[digitIndex]
|
|
487
|
+
return MaskSpec(
|
|
488
|
+
cacheKey = "${key(role)}|$digitIndex|$radius|$pad",
|
|
489
|
+
paint = paint,
|
|
490
|
+
text = text,
|
|
491
|
+
left = pad + (cell - width(text, role)) / 2f,
|
|
492
|
+
baseline = pad + digitBaseline(role),
|
|
493
|
+
width = ceil(cell).toInt() + 2 * pad,
|
|
494
|
+
height = ceil(lineHeight).toInt() + 2 * pad,
|
|
495
|
+
radius = radius,
|
|
496
|
+
)
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Every digit mask of the numeric transition (ten digits at every blur
|
|
501
|
+
* level, and the fraction's when it has one), for the warm thread.
|
|
502
|
+
*/
|
|
503
|
+
fun swapMaskSpecs(fraction: Boolean): List<MaskSpec> {
|
|
504
|
+
val roles = if (fraction) listOf(GlyphRole.DIGIT, GlyphRole.FRACTION) else listOf(GlyphRole.DIGIT)
|
|
505
|
+
val specs = ArrayList<MaskSpec>(roles.size * 10 * (NUMERIC_BLUR_LEVELS + 1))
|
|
506
|
+
for (role in roles) for (digit in 0..9) for (level in 0..NUMERIC_BLUR_LEVELS) {
|
|
507
|
+
digitMaskSpec(role, digit, level, maskPaints[role.ordinal])?.let { specs.add(it) }
|
|
508
|
+
}
|
|
509
|
+
return specs
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** The blur radius of [level], in px (0: sharp). */
|
|
513
|
+
private fun blurRadius(level: Int): Int =
|
|
514
|
+
if (level <= 0 || numericBlur <= 0f) 0 else Math.round(lineHeight * numericBlur * level / NUMERIC_BLUR_LEVELS).coerceAtLeast(1)
|
|
515
|
+
|
|
495
516
|
/**
|
|
496
517
|
* [text] of [role] as an alpha mask blurred to [level] (of
|
|
497
518
|
* [NUMERIC_BLUR_LEVELS]; 0 sharp), `width + 2 pad` by `lineHeight + 2 pad`
|
|
@@ -500,28 +521,31 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
500
521
|
*/
|
|
501
522
|
fun blurredText(text: String, role: GlyphRole, level: Int): Bitmap? {
|
|
502
523
|
if (text.isEmpty() || lineHeight <= 0f) return null
|
|
503
|
-
val
|
|
504
|
-
val
|
|
505
|
-
if (radius > 0
|
|
524
|
+
val queued = level > 0 && isMainThread()
|
|
525
|
+
val spec = textMaskSpec(text, role, level, if (queued) maskPaints[role.ordinal] else threadPaint(role))
|
|
526
|
+
if (queued && spec.radius > 0) {
|
|
506
527
|
// Never warmed ahead (any text can change into any other): blurred on
|
|
507
528
|
// the warm thread, sharp until it lands, as [blurred] does.
|
|
508
|
-
BlurredGlyphCache.peek(cacheKey)?.let { return it }
|
|
509
|
-
WarmExecutor.request(
|
|
529
|
+
BlurredGlyphCache.peek(spec.cacheKey)?.let { return it }
|
|
530
|
+
WarmExecutor.request(spec)
|
|
510
531
|
return blurredText(text, role, 0)
|
|
511
532
|
}
|
|
512
|
-
return
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
533
|
+
return spec.make()
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
private fun textMaskSpec(text: String, role: GlyphRole, level: Int, paint: TextPaint): MaskSpec {
|
|
537
|
+
val radius = blurRadius(level)
|
|
538
|
+
val pad = blurPad
|
|
539
|
+
return MaskSpec(
|
|
540
|
+
cacheKey = "${key(role)}|t|$text|$radius|$pad",
|
|
541
|
+
paint = paint,
|
|
542
|
+
text = text,
|
|
543
|
+
left = pad.toFloat(),
|
|
544
|
+
baseline = pad + baseline(role, text, 0f),
|
|
545
|
+
width = (ceil(width(text, role)).toInt() + 2 * pad).coerceAtLeast(1),
|
|
546
|
+
height = ceil(lineHeight).toInt() + 2 * pad,
|
|
547
|
+
radius = radius,
|
|
548
|
+
)
|
|
525
549
|
}
|
|
526
550
|
|
|
527
551
|
/** Padding around a blurred glyph's bitmap, enough for the blur's tail. */
|
|
@@ -700,56 +724,6 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
700
724
|
}
|
|
701
725
|
}
|
|
702
726
|
|
|
703
|
-
/**
|
|
704
|
-
* Blurs a single-colour glyph in place: the alpha channel gets three box
|
|
705
|
-
* passes of [radius] in each axis, and every pixel is put back as [color]
|
|
706
|
-
* at its blurred coverage.
|
|
707
|
-
*/
|
|
708
|
-
/**
|
|
709
|
-
* Blurs an ALPHA_8 [mask] in place: three box passes of [radius], which is a
|
|
710
|
-
* Gaussian to the eye with a standard deviation of about the radius.
|
|
711
|
-
*/
|
|
712
|
-
private fun boxBlurMask(mask: Bitmap, radius: Int) {
|
|
713
|
-
val w = mask.width
|
|
714
|
-
val h = mask.height
|
|
715
|
-
val stride = mask.rowBytes
|
|
716
|
-
// Reused, not allocated per mask: two float copies of a large glyph went
|
|
717
|
-
// to the large-object heap, and a screenful of masks collected mid-frame.
|
|
718
|
-
val buffers = BlurBuffers.get(stride * h, w * h)
|
|
719
|
-
val bytes = buffers.bytes
|
|
720
|
-
bytes.clear()
|
|
721
|
-
bytes.limit(stride * h)
|
|
722
|
-
mask.copyPixelsToBuffer(bytes)
|
|
723
|
-
val alpha = buffers.alpha
|
|
724
|
-
val scratch = buffers.scratch
|
|
725
|
-
for (i in 0 until w * h) alpha[i] = (bytes.get((i / w) * stride + i % w).toInt() and 0xff).toFloat()
|
|
726
|
-
val window = (2 * radius + 1).toFloat()
|
|
727
|
-
repeat(3) {
|
|
728
|
-
// horizontal
|
|
729
|
-
for (y in 0 until h) {
|
|
730
|
-
val row = y * w
|
|
731
|
-
var sum = 0f
|
|
732
|
-
for (x in -radius..radius) sum += alpha[row + x.coerceIn(0, w - 1)]
|
|
733
|
-
for (x in 0 until w) {
|
|
734
|
-
scratch[row + x] = sum / window
|
|
735
|
-
sum += alpha[row + (x + radius + 1).coerceIn(0, w - 1)] - alpha[row + (x - radius).coerceIn(0, w - 1)]
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
// vertical
|
|
739
|
-
for (x in 0 until w) {
|
|
740
|
-
var sum = 0f
|
|
741
|
-
for (y in -radius..radius) sum += scratch[y.coerceIn(0, h - 1) * w + x]
|
|
742
|
-
for (y in 0 until h) {
|
|
743
|
-
alpha[y * w + x] = sum / window
|
|
744
|
-
sum += scratch[(y + radius + 1).coerceIn(0, h - 1) * w + x] - scratch[(y - radius).coerceIn(0, h - 1) * w + x]
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
for (i in 0 until w * h) bytes.put((i / w) * stride + i % w, Math.round(alpha[i]).coerceIn(0, 255).toByte())
|
|
749
|
-
bytes.rewind()
|
|
750
|
-
mask.copyPixelsFromBuffer(bytes)
|
|
751
|
-
}
|
|
752
|
-
|
|
753
727
|
/** System font scale for `allowFontScaling`, capped by `maxFontSizeMultiplier`. */
|
|
754
728
|
private fun systemFontMultiplier(t: Typography): Float {
|
|
755
729
|
if (!t.allowFontScaling) return 1f
|
|
@@ -1171,30 +1145,101 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
1171
1145
|
invalidate()
|
|
1172
1146
|
}
|
|
1173
1147
|
|
|
1148
|
+
/** The font set whose swap masks were last queued, and whether with the fraction's. */
|
|
1149
|
+
private var warmedFonts: FontSet? = null
|
|
1150
|
+
private var warmedFraction = false
|
|
1151
|
+
|
|
1174
1152
|
/**
|
|
1175
1153
|
* Renders the numeric transition's glyph masks, every digit at every blur
|
|
1176
1154
|
* level, on a background thread before they are needed. Made on demand, a
|
|
1177
1155
|
* change's first frames each paid for a few software blurs on the UI
|
|
1178
1156
|
* thread and ran late; iOS warms its images the same way.
|
|
1157
|
+
*
|
|
1158
|
+
* Once per font set: the `timing` and the font setters both land here when
|
|
1159
|
+
* a view mounts. A new font set (a font, size or colour change) takes the
|
|
1160
|
+
* old one's warm-ups out of the queue first, unless another view still
|
|
1161
|
+
* wants them: on a colour animation they were never going to be drawn.
|
|
1179
1162
|
*/
|
|
1180
1163
|
private fun warmSwapMasks() {
|
|
1181
|
-
if (timing.transition != Transition.NUMERIC)
|
|
1164
|
+
if (timing.transition != Transition.NUMERIC) {
|
|
1165
|
+
cancelWarmUps()
|
|
1166
|
+
return
|
|
1167
|
+
}
|
|
1182
1168
|
val set = fonts
|
|
1183
1169
|
val fraction = format.fractionDigits > 0
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1170
|
+
if (set === warmedFonts && (warmedFraction || !fraction)) return
|
|
1171
|
+
if (set !== warmedFonts) cancelWarmUps()
|
|
1172
|
+
warmedFonts = set
|
|
1173
|
+
warmedFraction = fraction
|
|
1174
|
+
WarmExecutor.warm(set.warmToken, set.swapMaskSpecs(fraction))
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/** Takes this view's queued warm-ups out of the queue (those no other view asked for). */
|
|
1178
|
+
private fun cancelWarmUps() {
|
|
1179
|
+
val set = warmedFonts ?: return
|
|
1180
|
+
warmedFonts = null
|
|
1181
|
+
warmedFraction = false
|
|
1182
|
+
WarmExecutor.cancel(set.warmToken)
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/**
|
|
1186
|
+
* A glyph mask to make: the text, the paint to draw it with and where it
|
|
1187
|
+
* goes in the bitmap, measured on the UI thread. A nested class and plain
|
|
1188
|
+
* values, so a mask waiting in [WarmExecutor]'s queue holds a paint and a
|
|
1189
|
+
* few numbers, never a font set or the view: when the masks were lambdas
|
|
1190
|
+
* over the (inner) font set, every queued one kept its whole view alive,
|
|
1191
|
+
* strips and layers included, and a backlog of them ran low-end phones out
|
|
1192
|
+
* of memory.
|
|
1193
|
+
*/
|
|
1194
|
+
private class MaskSpec(
|
|
1195
|
+
val cacheKey: String,
|
|
1196
|
+
/** Never drawn with or changed by the UI thread once queued (a font set's mask paint). */
|
|
1197
|
+
val paint: TextPaint,
|
|
1198
|
+
val text: String,
|
|
1199
|
+
/** The text's left edge and baseline in the bitmap, padding included. */
|
|
1200
|
+
val left: Float,
|
|
1201
|
+
val baseline: Float,
|
|
1202
|
+
val width: Int,
|
|
1203
|
+
val height: Int,
|
|
1204
|
+
val radius: Int,
|
|
1205
|
+
) {
|
|
1206
|
+
/** The mask, from the shared cache or drawn (and blurred) now on the calling thread. */
|
|
1207
|
+
fun make(): Bitmap = BlurredGlyphCache.get(cacheKey) {
|
|
1208
|
+
// An alpha mask, not a coloured bitmap: the glyph's coverage, blurred,
|
|
1209
|
+
// that a draw fills with the digit paint's colour. A coloured
|
|
1210
|
+
// ARGB_8888 bitmap round-tripped through get/setPixels came back with
|
|
1211
|
+
// its whole rectangle faintly inked on the GPU; a mask has no colour
|
|
1212
|
+
// to get wrong, and is a quarter of the memory.
|
|
1213
|
+
val mask = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8)
|
|
1214
|
+
val canvas = Canvas(mask)
|
|
1215
|
+
// A paint of its own: the UI thread changes its paints' alpha as it draws.
|
|
1216
|
+
val paint = TextPaint(paint).apply { alpha = 255 }
|
|
1217
|
+
canvas.drawText(text, left, baseline, paint)
|
|
1218
|
+
if (radius > 0) boxBlurMask(mask, radius)
|
|
1219
|
+
// Immutable and uploaded ahead of its first draw: HWUI re-pins a mutable
|
|
1220
|
+
// bitmap at every sync, and the first frame that drew a fresh mask paid
|
|
1221
|
+
// for its texture upload.
|
|
1222
|
+
val done = mask.copy(Bitmap.Config.ALPHA_8, false) ?: mask
|
|
1223
|
+
if (done !== mask) mask.recycle()
|
|
1224
|
+
done
|
|
1189
1225
|
}
|
|
1190
1226
|
}
|
|
1191
1227
|
|
|
1192
1228
|
/**
|
|
1193
1229
|
* One background thread for glyph masks, shared by every view. A mask the UI
|
|
1194
1230
|
* thread is waiting on ([request]) goes to the front of the queue, ahead of
|
|
1195
|
-
* the ten-digits-at-every-level warm-ups ([
|
|
1231
|
+
* the ten-digits-at-every-level warm-ups ([warm]): behind a font change's
|
|
1196
1232
|
* warm-up, the glyph on screen stayed sharp for its whole swap.
|
|
1197
1233
|
*
|
|
1234
|
+
* Bounded both ways, and keyed by mask, so it cannot outgrow its one thread
|
|
1235
|
+
* however many fonts, sizes and colours come and go: a mask is queued once
|
|
1236
|
+
* however many views ask for it, a dropped view's or an old font set's
|
|
1237
|
+
* warm-ups are taken out ([cancel]), and past [MAX_WARM] (or [MAX_URGENT])
|
|
1238
|
+
* the oldest are dropped. A dropped warm-up costs at most a sharp glyph
|
|
1239
|
+
* for a swap's first frames, then [request] makes it. An unbounded queue
|
|
1240
|
+
* of masks for colours already gone grew to hundreds of thousands and
|
|
1241
|
+
* took the app down on low-end phones (0.4.1).
|
|
1242
|
+
*
|
|
1198
1243
|
* At background priority plus one step (Glide's choice): below the UI
|
|
1199
1244
|
* thread, not starved under load (Thread.MIN_PRIORITY is the lowest nice
|
|
1200
1245
|
* level there is). A mask that cannot be made (out of memory, say) is
|
|
@@ -1203,13 +1248,25 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
1203
1248
|
* on Android, and a failure retried every frame logged every frame. Any
|
|
1204
1249
|
* other Error is a bug and is not swallowed.
|
|
1205
1250
|
*/
|
|
1206
|
-
private object WarmExecutor
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1251
|
+
private object WarmExecutor {
|
|
1252
|
+
/** Warm-ups kept at most: four numeric typographies with fractions, ten digits at seven levels in two roles. */
|
|
1253
|
+
const val MAX_WARM = 4 * 2 * 10 * (NUMERIC_BLUR_LEVELS + 1)
|
|
1254
|
+
/** Masks frames are waiting on, kept at most (a screenful of swapping glyphs and texts is far fewer). */
|
|
1255
|
+
const val MAX_URGENT = 256
|
|
1256
|
+
private const val RETRY_MS = 2000L
|
|
1257
|
+
|
|
1258
|
+
private val lock = Object()
|
|
1259
|
+
/** Masks the UI thread is waiting on, newest first, and their keys (also while one is being made). */
|
|
1260
|
+
private val urgent = ArrayDeque<MaskSpec>()
|
|
1261
|
+
private val urgentKeys = HashSet<String>()
|
|
1262
|
+
/** Warm-ups by mask key, oldest first, each with the font sets ([FontSet.warmToken]) that want it. */
|
|
1263
|
+
private val warm = LinkedHashMap<String, WarmUp>()
|
|
1210
1264
|
/** When a mask last failed, by key: not asked for again until [RETRY_MS] later. */
|
|
1211
1265
|
private val failed = java.util.concurrent.ConcurrentHashMap<String, Long>()
|
|
1212
|
-
|
|
1266
|
+
|
|
1267
|
+
private class WarmUp(val spec: MaskSpec) {
|
|
1268
|
+
val owners = HashSet<Any>(2)
|
|
1269
|
+
}
|
|
1213
1270
|
|
|
1214
1271
|
init {
|
|
1215
1272
|
Thread({
|
|
@@ -1217,17 +1274,22 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
1217
1274
|
android.os.Process.THREAD_PRIORITY_BACKGROUND + android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE
|
|
1218
1275
|
)
|
|
1219
1276
|
while (true) {
|
|
1220
|
-
val
|
|
1221
|
-
|
|
1277
|
+
val spec = try {
|
|
1278
|
+
next()
|
|
1222
1279
|
} catch (_: InterruptedException) {
|
|
1223
1280
|
continue
|
|
1224
1281
|
}
|
|
1225
1282
|
try {
|
|
1226
|
-
|
|
1283
|
+
if (BlurredGlyphCache.peek(spec.cacheKey) == null) spec.make()
|
|
1284
|
+
failed.remove(spec.cacheKey)
|
|
1227
1285
|
} catch (e: Exception) {
|
|
1286
|
+
failed[spec.cacheKey] = SystemClock.uptimeMillis()
|
|
1228
1287
|
android.util.Log.w("NitroNumber", "A glyph mask could not be made; the glyph is drawn sharp", e)
|
|
1229
1288
|
} catch (e: OutOfMemoryError) {
|
|
1289
|
+
failed[spec.cacheKey] = SystemClock.uptimeMillis()
|
|
1230
1290
|
android.util.Log.w("NitroNumber", "Out of memory making a glyph mask; the glyph is drawn sharp", e)
|
|
1291
|
+
} finally {
|
|
1292
|
+
synchronized(lock) { urgentKeys.remove(spec.cacheKey) }
|
|
1231
1293
|
}
|
|
1232
1294
|
}
|
|
1233
1295
|
}, "NitroNumberWarm").apply {
|
|
@@ -1236,31 +1298,68 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
1236
1298
|
}
|
|
1237
1299
|
}
|
|
1238
1300
|
|
|
1239
|
-
|
|
1240
|
-
|
|
1301
|
+
/** The next mask to make, waiting for one: a frame's before any warm-up. */
|
|
1302
|
+
private fun next(): MaskSpec = synchronized(lock) {
|
|
1303
|
+
while (urgent.isEmpty() && warm.isEmpty()) lock.wait()
|
|
1304
|
+
if (urgent.isNotEmpty()) return urgent.removeFirst()
|
|
1305
|
+
val oldest = warm.values.iterator()
|
|
1306
|
+
val warmUp = oldest.next()
|
|
1307
|
+
oldest.remove()
|
|
1308
|
+
// Kept in [urgentKeys] while it is made, so a frame asking meanwhile doesn't queue it again.
|
|
1309
|
+
urgentKeys.add(warmUp.spec.cacheKey)
|
|
1310
|
+
warmUp.spec
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
private fun recentlyFailed(key: String): Boolean {
|
|
1314
|
+
val at = failed[key] ?: return false
|
|
1315
|
+
return SystemClock.uptimeMillis() - at < RETRY_MS
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/** Makes [spec]'s mask on the warm thread next, once however many frames ask for it while it is queued. */
|
|
1319
|
+
fun request(spec: MaskSpec) {
|
|
1320
|
+
val key = spec.cacheKey
|
|
1321
|
+
if (recentlyFailed(key)) return
|
|
1322
|
+
synchronized(lock) {
|
|
1323
|
+
if (!urgentKeys.add(key)) return
|
|
1324
|
+
warm.remove(key)
|
|
1325
|
+
urgent.addFirst(spec)
|
|
1326
|
+
while (urgent.size > MAX_URGENT) urgentKeys.remove(urgent.removeLast().cacheKey)
|
|
1327
|
+
lock.notifyAll()
|
|
1328
|
+
}
|
|
1241
1329
|
}
|
|
1242
1330
|
|
|
1243
|
-
/**
|
|
1244
|
-
fun
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
} catch (e: Exception) {
|
|
1253
|
-
failed[key] = SystemClock.uptimeMillis()
|
|
1254
|
-
throw e
|
|
1255
|
-
} catch (e: OutOfMemoryError) {
|
|
1256
|
-
failed[key] = SystemClock.uptimeMillis()
|
|
1257
|
-
throw e
|
|
1258
|
-
} finally {
|
|
1259
|
-
pending.remove(key)
|
|
1260
|
-
}
|
|
1331
|
+
/** Queues [specs] behind every frame's masks, for the font set [owner] stands for. */
|
|
1332
|
+
fun warm(owner: Any, specs: List<MaskSpec>) {
|
|
1333
|
+
// Outside the lock: the cache has a lock of its own.
|
|
1334
|
+
val missing = specs.filter { BlurredGlyphCache.peek(it.cacheKey) == null && !recentlyFailed(it.cacheKey) }
|
|
1335
|
+
if (missing.isEmpty()) return
|
|
1336
|
+
synchronized(lock) {
|
|
1337
|
+
for (spec in missing) {
|
|
1338
|
+
if (spec.cacheKey in urgentKeys) continue
|
|
1339
|
+
warm.getOrPut(spec.cacheKey) { WarmUp(spec) }.owners.add(owner)
|
|
1261
1340
|
}
|
|
1262
|
-
|
|
1341
|
+
val oldest = warm.values.iterator()
|
|
1342
|
+
while (warm.size > MAX_WARM && oldest.hasNext()) {
|
|
1343
|
+
oldest.next()
|
|
1344
|
+
oldest.remove()
|
|
1345
|
+
}
|
|
1346
|
+
lock.notifyAll()
|
|
1347
|
+
}
|
|
1263
1348
|
}
|
|
1349
|
+
|
|
1350
|
+
/** Takes out the warm-ups only [owner] wanted; the ones another font set wants too stay. */
|
|
1351
|
+
fun cancel(owner: Any) {
|
|
1352
|
+
synchronized(lock) {
|
|
1353
|
+
val each = warm.values.iterator()
|
|
1354
|
+
while (each.hasNext()) {
|
|
1355
|
+
val warmUp = each.next()
|
|
1356
|
+
if (warmUp.owners.remove(owner) && warmUp.owners.isEmpty()) each.remove()
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
/** Warm-ups and frame requests waiting, for tests and diagnostics. */
|
|
1362
|
+
fun queued(): Int = synchronized(lock) { warm.size + urgent.size }
|
|
1264
1363
|
}
|
|
1265
1364
|
|
|
1266
1365
|
/** Per-thread buffers for [boxBlurMask], grown to the largest mask that thread has blurred. */
|
|
@@ -2112,6 +2211,7 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
2112
2211
|
*/
|
|
2113
2212
|
fun release() {
|
|
2114
2213
|
stopAnimation()
|
|
2214
|
+
cancelWarmUps()
|
|
2115
2215
|
engine.reset()
|
|
2116
2216
|
moving = false
|
|
2117
2217
|
wheels.clear()
|
|
@@ -2211,6 +2311,59 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
2211
2311
|
}
|
|
2212
2312
|
|
|
2213
2313
|
companion object {
|
|
2314
|
+
/**
|
|
2315
|
+
* Blurs an ALPHA_8 [mask] in place: three box passes of [radius], which is a
|
|
2316
|
+
* Gaussian to the eye with a standard deviation of about the radius.
|
|
2317
|
+
*/
|
|
2318
|
+
private fun boxBlurMask(mask: Bitmap, radius: Int) {
|
|
2319
|
+
val w = mask.width
|
|
2320
|
+
val h = mask.height
|
|
2321
|
+
val stride = mask.rowBytes
|
|
2322
|
+
// Reused, not allocated per mask: two float copies of a large glyph went
|
|
2323
|
+
// to the large-object heap, and a screenful of masks collected mid-frame.
|
|
2324
|
+
val buffers = BlurBuffers.get(stride * h, w * h)
|
|
2325
|
+
val bytes = buffers.bytes
|
|
2326
|
+
bytes.clear()
|
|
2327
|
+
bytes.limit(stride * h)
|
|
2328
|
+
mask.copyPixelsToBuffer(bytes)
|
|
2329
|
+
val alpha = buffers.alpha
|
|
2330
|
+
val scratch = buffers.scratch
|
|
2331
|
+
for (i in 0 until w * h) alpha[i] = (bytes.get((i / w) * stride + i % w).toInt() and 0xff).toFloat()
|
|
2332
|
+
val window = (2 * radius + 1).toFloat()
|
|
2333
|
+
repeat(3) {
|
|
2334
|
+
// horizontal
|
|
2335
|
+
for (y in 0 until h) {
|
|
2336
|
+
val row = y * w
|
|
2337
|
+
var sum = 0f
|
|
2338
|
+
for (x in -radius..radius) sum += alpha[row + x.coerceIn(0, w - 1)]
|
|
2339
|
+
for (x in 0 until w) {
|
|
2340
|
+
scratch[row + x] = sum / window
|
|
2341
|
+
sum += alpha[row + (x + radius + 1).coerceIn(0, w - 1)] - alpha[row + (x - radius).coerceIn(0, w - 1)]
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
// vertical
|
|
2345
|
+
for (x in 0 until w) {
|
|
2346
|
+
var sum = 0f
|
|
2347
|
+
for (y in -radius..radius) sum += scratch[y.coerceIn(0, h - 1) * w + x]
|
|
2348
|
+
for (y in 0 until h) {
|
|
2349
|
+
alpha[y * w + x] = sum / window
|
|
2350
|
+
sum += scratch[(y + radius + 1).coerceIn(0, h - 1) * w + x] - scratch[(y - radius).coerceIn(0, h - 1) * w + x]
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
for (i in 0 until w * h) bytes.put((i / w) * stride + i % w, Math.round(alpha[i]).coerceIn(0, 255).toByte())
|
|
2355
|
+
bytes.rewind()
|
|
2356
|
+
mask.copyPixelsFromBuffer(bytes)
|
|
2357
|
+
}
|
|
2358
|
+
|
|
2359
|
+
|
|
2360
|
+
/**
|
|
2361
|
+
* Glyph masks waiting for the warm thread, warm-ups and frame requests
|
|
2362
|
+
* together; bounded (see WarmExecutor). For tests and diagnostics.
|
|
2363
|
+
*/
|
|
2364
|
+
@JvmStatic
|
|
2365
|
+
fun queuedGlyphMasks(): Int = WarmExecutor.queued()
|
|
2366
|
+
|
|
2214
2367
|
/** The glyphs drawn for 0…9 unless `digitGlyphs` gives ten others. */
|
|
2215
2368
|
private val DIGITS = Array(10) { it.toString() }
|
|
2216
2369
|
/** Flash paints a font set keeps per role (a change flash has an up and a down colour). */
|
|
@@ -50,6 +50,73 @@ const formatProps_1 = require("./formatProps");
|
|
|
50
50
|
exports.NativeNitroNumberView = (0, react_native_nitro_modules_1.getHostComponent)('NitroNumberView', () => NitroNumberViewConfig_json_1.default);
|
|
51
51
|
const EMPTY = [];
|
|
52
52
|
const EMPTY_STRINGS = [];
|
|
53
|
+
/**
|
|
54
|
+
* A weak reference where the engine has them (Hermes, JSC, V8), else a strong
|
|
55
|
+
* one. Two functions on purpose: an engine keeps one scope per function for
|
|
56
|
+
* everything its closures capture, so a `() => target` fallback written beside
|
|
57
|
+
* the weak closure would put `target` in the weak closure's scope too.
|
|
58
|
+
*/
|
|
59
|
+
function weakly(target) {
|
|
60
|
+
return typeof WeakRef === 'function' ? weakDeref(new WeakRef(target)) : strongDeref(target);
|
|
61
|
+
}
|
|
62
|
+
function weakDeref(ref) {
|
|
63
|
+
return () => ref.deref();
|
|
64
|
+
}
|
|
65
|
+
function strongDeref(target) {
|
|
66
|
+
return () => target;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* A Nitro callback that calls `handler(self, ...args)` for as long as the
|
|
70
|
+
* component behind `self` is alive, holding `self` only weakly.
|
|
71
|
+
*
|
|
72
|
+
* Why. Nitro keeps every callback prop of a view as a JS function held from
|
|
73
|
+
* C++ (in the Fabric props of its shadow node), which Hermes treats as a GC
|
|
74
|
+
* root. A closure written inside the component shares the render's scope,
|
|
75
|
+
* so it reaches the fiber (through `setSize`) and the hybrid view's handle
|
|
76
|
+
* (through `nativeRef`), and the fiber holds the shadow node that holds the
|
|
77
|
+
* props that hold the closure: a loop through native code that Hermes can
|
|
78
|
+
* never collect. Every unmounted NitroNumber stayed, its fiber subtree, its
|
|
79
|
+
* hybrid view and Nitro's C++ part included: over 4,000 after a minute of
|
|
80
|
+
* a scrolling list, and the app's memory climbed with them. Built here, in
|
|
81
|
+
* module scope, the closure holds only the weak reference and `handler`
|
|
82
|
+
* (itself module-level); the fiber is what keeps `self` alive.
|
|
83
|
+
*/
|
|
84
|
+
function relay(self, handler) {
|
|
85
|
+
return relayTo(weakly(self), handler);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* The closure itself, made where `self` is not in scope at all: Hermes (in
|
|
89
|
+
* debuggable builds, at least) keeps every variable of a function that makes
|
|
90
|
+
* a closure in that closure's scope, used or not, and a `self` there would
|
|
91
|
+
* hold the component strongly again.
|
|
92
|
+
*/
|
|
93
|
+
function relayTo(live, handler) {
|
|
94
|
+
return (0, react_native_nitro_modules_1.callback)((...args) => {
|
|
95
|
+
const target = live();
|
|
96
|
+
if (target !== undefined)
|
|
97
|
+
handler(target, ...args);
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
function attachNative(self, instance) {
|
|
101
|
+
self.nativeRef.current = instance;
|
|
102
|
+
self.latestOnNativeRef.current?.(instance);
|
|
103
|
+
}
|
|
104
|
+
function applySize(self, width, height) {
|
|
105
|
+
self.setSize((previous) => previous !== null && previous.width === width && previous.height === height ? previous : { width, height });
|
|
106
|
+
}
|
|
107
|
+
function fireRevealEnd(self) {
|
|
108
|
+
self.latestOnRevealEnd.current?.();
|
|
109
|
+
}
|
|
110
|
+
function fireRevealMilestone(self, index, milestone) {
|
|
111
|
+
self.latestOnRevealMilestone.current?.(index, milestone);
|
|
112
|
+
}
|
|
113
|
+
function fireAnimationStart(self) {
|
|
114
|
+
self.latestOnAnimationStart.current?.();
|
|
115
|
+
}
|
|
116
|
+
/** The figure a compact format rolls is not the value (1.2 for 1,234): report the value. */
|
|
117
|
+
function fireAnimationEnd(self, shown) {
|
|
118
|
+
self.latestOnAnimationEnd.current?.(self.compactRef.current ? (0, formatProps_1.toNumber)(self.latestValue.current) : shown);
|
|
119
|
+
}
|
|
53
120
|
/** Each transition's own timing, used when the props leave it unsaid. */
|
|
54
121
|
const TRANSITION_DEFAULTS = {
|
|
55
122
|
roll: { duration: 500, easing: 'easeInOut', stagger: 0 },
|
|
@@ -68,6 +135,8 @@ const TRANSITION_DEFAULTS = {
|
|
|
68
135
|
*/
|
|
69
136
|
exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, minorDigits, fractionDigits, minimumIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, transition, flashUpColor, flashDownColor, flashDuration, popOnChange, duration, easing, bounce, stagger, direction, reveal, revealStyle, revealDuration, revealBounce, revealGrow, revealStagger, revealMilestones, revealMilestoneHold, onRevealEnd, onRevealMilestone, loading, shimmerColor, shimmerDuration, shimmerAngle, shimmerWidth, shimmerBaseColor, shimmerDirection, shimmerDelay, fontSize, prefixFontSize, suffixFontSize, affixAlign, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, tabularNums, format, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, fontWeight, fontFamily, color, textAlign, signDisplay, plusSign, minusSign, prefixColor, suffixColor, fractionColor, fractionFontSize, fractionAlign, digitGlyphs, groupingSizes, digits, continuous, animated, respectReduceMotion, onAnimationStart, onAnimationEnd, onNativeRef, style, ...viewProps }, ref) {
|
|
70
137
|
const nativeRef = (0, react_1.useRef)(null);
|
|
138
|
+
// Whether a compact format is rolling (its figure is not the value); set below.
|
|
139
|
+
const compactRef = (0, react_1.useRef)(false);
|
|
71
140
|
const latestOnNativeRef = (0, react_1.useRef)(onNativeRef);
|
|
72
141
|
latestOnNativeRef.current = onNativeRef;
|
|
73
142
|
const latestOnRevealEnd = (0, react_1.useRef)(onRevealEnd);
|
|
@@ -83,34 +152,31 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, mino
|
|
|
83
152
|
const latestOnAnimationEnd = (0, react_1.useRef)(onAnimationEnd);
|
|
84
153
|
latestOnAnimationEnd.current = onAnimationEnd;
|
|
85
154
|
const [size, setSize] = (0, react_1.useState)(null);
|
|
86
|
-
//
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
//
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
const onAnimationEndCallback = (0, react_1.useMemo)(() => (0, react_native_nitro_modules_1.callback)((shown) => {
|
|
112
|
-
latestOnAnimationEnd.current?.(compactRef.current ? (0, formatProps_1.toNumber)(latestValue.current) : shown);
|
|
113
|
-
}), []);
|
|
155
|
+
// The native callbacks: wrapped with `callback()` and referentially stable
|
|
156
|
+
// (a new wrapper re-sets the prop every render), and built in module scope
|
|
157
|
+
// around a weak reference to this component's state (see `relay`).
|
|
158
|
+
const self = (0, react_1.useMemo)(() => ({
|
|
159
|
+
nativeRef,
|
|
160
|
+
latestOnNativeRef,
|
|
161
|
+
setSize,
|
|
162
|
+
latestOnRevealEnd,
|
|
163
|
+
latestOnRevealMilestone,
|
|
164
|
+
latestOnAnimationStart,
|
|
165
|
+
latestOnAnimationEnd,
|
|
166
|
+
compactRef,
|
|
167
|
+
latestValue,
|
|
168
|
+
}),
|
|
169
|
+
// Every member is a ref or a state setter, stable for the component's life.
|
|
170
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
171
|
+
[]);
|
|
172
|
+
const hybridRef = (0, react_1.useMemo)(() => relay(self, attachNative), [self]);
|
|
173
|
+
const onSizeChange = (0, react_1.useMemo)(() => relay(self, applySize), [self]);
|
|
174
|
+
// The latest handlers are read through refs, so a caller passing an inline
|
|
175
|
+
// arrow doesn't re-set the native prop each render.
|
|
176
|
+
const onRevealEndCallback = (0, react_1.useMemo)(() => relay(self, fireRevealEnd), [self]);
|
|
177
|
+
const onRevealMilestoneCallback = (0, react_1.useMemo)(() => relay(self, fireRevealMilestone), [self]);
|
|
178
|
+
const onAnimationStartCallback = (0, react_1.useMemo)(() => relay(self, fireAnimationStart), [self]);
|
|
179
|
+
const onAnimationEndCallback = (0, react_1.useMemo)(() => relay(self, fireAnimationEnd), [self]);
|
|
114
180
|
// A new array literal each render must not re-set the native prop. Always an
|
|
115
181
|
// array (empty = no tiers): removing the prop would reach native as `null`,
|
|
116
182
|
// which Nitro's array parser rejects ("Value is null, expected an Object").
|
|
@@ -150,7 +216,6 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, mino
|
|
|
150
216
|
// rolls the figure 1.2.
|
|
151
217
|
const figure = (0, react_1.useMemo)(() => (format ? (0, formatProps_1.figureOf)(format, input) : undefined), [format, input]);
|
|
152
218
|
const compact = derived?.compact ? figure : undefined;
|
|
153
|
-
const compactRef = (0, react_1.useRef)(false);
|
|
154
219
|
compactRef.current = compact !== undefined;
|
|
155
220
|
// Which way the value moved, for a compact figure that fell while the value grew (999 → 1K).
|
|
156
221
|
const numericValue = (0, formatProps_1.toNumber)(input);
|
|
@@ -11,6 +11,73 @@ import { figureOf, formatProps, toNumber, withMinorDigits } from './formatProps'
|
|
|
11
11
|
export const NativeNitroNumberView = getHostComponent('NitroNumberView', () => NitroNumberViewConfig);
|
|
12
12
|
const EMPTY = [];
|
|
13
13
|
const EMPTY_STRINGS = [];
|
|
14
|
+
/**
|
|
15
|
+
* A weak reference where the engine has them (Hermes, JSC, V8), else a strong
|
|
16
|
+
* one. Two functions on purpose: an engine keeps one scope per function for
|
|
17
|
+
* everything its closures capture, so a `() => target` fallback written beside
|
|
18
|
+
* the weak closure would put `target` in the weak closure's scope too.
|
|
19
|
+
*/
|
|
20
|
+
function weakly(target) {
|
|
21
|
+
return typeof WeakRef === 'function' ? weakDeref(new WeakRef(target)) : strongDeref(target);
|
|
22
|
+
}
|
|
23
|
+
function weakDeref(ref) {
|
|
24
|
+
return () => ref.deref();
|
|
25
|
+
}
|
|
26
|
+
function strongDeref(target) {
|
|
27
|
+
return () => target;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* A Nitro callback that calls `handler(self, ...args)` for as long as the
|
|
31
|
+
* component behind `self` is alive, holding `self` only weakly.
|
|
32
|
+
*
|
|
33
|
+
* Why. Nitro keeps every callback prop of a view as a JS function held from
|
|
34
|
+
* C++ (in the Fabric props of its shadow node), which Hermes treats as a GC
|
|
35
|
+
* root. A closure written inside the component shares the render's scope,
|
|
36
|
+
* so it reaches the fiber (through `setSize`) and the hybrid view's handle
|
|
37
|
+
* (through `nativeRef`), and the fiber holds the shadow node that holds the
|
|
38
|
+
* props that hold the closure: a loop through native code that Hermes can
|
|
39
|
+
* never collect. Every unmounted NitroNumber stayed, its fiber subtree, its
|
|
40
|
+
* hybrid view and Nitro's C++ part included: over 4,000 after a minute of
|
|
41
|
+
* a scrolling list, and the app's memory climbed with them. Built here, in
|
|
42
|
+
* module scope, the closure holds only the weak reference and `handler`
|
|
43
|
+
* (itself module-level); the fiber is what keeps `self` alive.
|
|
44
|
+
*/
|
|
45
|
+
function relay(self, handler) {
|
|
46
|
+
return relayTo(weakly(self), handler);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The closure itself, made where `self` is not in scope at all: Hermes (in
|
|
50
|
+
* debuggable builds, at least) keeps every variable of a function that makes
|
|
51
|
+
* a closure in that closure's scope, used or not, and a `self` there would
|
|
52
|
+
* hold the component strongly again.
|
|
53
|
+
*/
|
|
54
|
+
function relayTo(live, handler) {
|
|
55
|
+
return callback((...args) => {
|
|
56
|
+
const target = live();
|
|
57
|
+
if (target !== undefined)
|
|
58
|
+
handler(target, ...args);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function attachNative(self, instance) {
|
|
62
|
+
self.nativeRef.current = instance;
|
|
63
|
+
self.latestOnNativeRef.current?.(instance);
|
|
64
|
+
}
|
|
65
|
+
function applySize(self, width, height) {
|
|
66
|
+
self.setSize((previous) => previous !== null && previous.width === width && previous.height === height ? previous : { width, height });
|
|
67
|
+
}
|
|
68
|
+
function fireRevealEnd(self) {
|
|
69
|
+
self.latestOnRevealEnd.current?.();
|
|
70
|
+
}
|
|
71
|
+
function fireRevealMilestone(self, index, milestone) {
|
|
72
|
+
self.latestOnRevealMilestone.current?.(index, milestone);
|
|
73
|
+
}
|
|
74
|
+
function fireAnimationStart(self) {
|
|
75
|
+
self.latestOnAnimationStart.current?.();
|
|
76
|
+
}
|
|
77
|
+
/** The figure a compact format rolls is not the value (1.2 for 1,234): report the value. */
|
|
78
|
+
function fireAnimationEnd(self, shown) {
|
|
79
|
+
self.latestOnAnimationEnd.current?.(self.compactRef.current ? toNumber(self.latestValue.current) : shown);
|
|
80
|
+
}
|
|
14
81
|
/** Each transition's own timing, used when the props leave it unsaid. */
|
|
15
82
|
const TRANSITION_DEFAULTS = {
|
|
16
83
|
roll: { duration: 500, easing: 'easeInOut', stagger: 0 },
|
|
@@ -29,6 +96,8 @@ const TRANSITION_DEFAULTS = {
|
|
|
29
96
|
*/
|
|
30
97
|
export const NitroNumber = forwardRef(function NitroNumber({ value, minorDigits, fractionDigits, minimumIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, transition, flashUpColor, flashDownColor, flashDuration, popOnChange, duration, easing, bounce, stagger, direction, reveal, revealStyle, revealDuration, revealBounce, revealGrow, revealStagger, revealMilestones, revealMilestoneHold, onRevealEnd, onRevealMilestone, loading, shimmerColor, shimmerDuration, shimmerAngle, shimmerWidth, shimmerBaseColor, shimmerDirection, shimmerDelay, fontSize, prefixFontSize, suffixFontSize, affixAlign, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, tabularNums, format, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, fontWeight, fontFamily, color, textAlign, signDisplay, plusSign, minusSign, prefixColor, suffixColor, fractionColor, fractionFontSize, fractionAlign, digitGlyphs, groupingSizes, digits, continuous, animated, respectReduceMotion, onAnimationStart, onAnimationEnd, onNativeRef, style, ...viewProps }, ref) {
|
|
31
98
|
const nativeRef = useRef(null);
|
|
99
|
+
// Whether a compact format is rolling (its figure is not the value); set below.
|
|
100
|
+
const compactRef = useRef(false);
|
|
32
101
|
const latestOnNativeRef = useRef(onNativeRef);
|
|
33
102
|
latestOnNativeRef.current = onNativeRef;
|
|
34
103
|
const latestOnRevealEnd = useRef(onRevealEnd);
|
|
@@ -44,34 +113,31 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, minorDigits,
|
|
|
44
113
|
const latestOnAnimationEnd = useRef(onAnimationEnd);
|
|
45
114
|
latestOnAnimationEnd.current = onAnimationEnd;
|
|
46
115
|
const [size, setSize] = useState(null);
|
|
47
|
-
//
|
|
48
|
-
//
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
//
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
const onAnimationEndCallback = useMemo(() => callback((shown) => {
|
|
73
|
-
latestOnAnimationEnd.current?.(compactRef.current ? toNumber(latestValue.current) : shown);
|
|
74
|
-
}), []);
|
|
116
|
+
// The native callbacks: wrapped with `callback()` and referentially stable
|
|
117
|
+
// (a new wrapper re-sets the prop every render), and built in module scope
|
|
118
|
+
// around a weak reference to this component's state (see `relay`).
|
|
119
|
+
const self = useMemo(() => ({
|
|
120
|
+
nativeRef,
|
|
121
|
+
latestOnNativeRef,
|
|
122
|
+
setSize,
|
|
123
|
+
latestOnRevealEnd,
|
|
124
|
+
latestOnRevealMilestone,
|
|
125
|
+
latestOnAnimationStart,
|
|
126
|
+
latestOnAnimationEnd,
|
|
127
|
+
compactRef,
|
|
128
|
+
latestValue,
|
|
129
|
+
}),
|
|
130
|
+
// Every member is a ref or a state setter, stable for the component's life.
|
|
131
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
132
|
+
[]);
|
|
133
|
+
const hybridRef = useMemo(() => relay(self, attachNative), [self]);
|
|
134
|
+
const onSizeChange = useMemo(() => relay(self, applySize), [self]);
|
|
135
|
+
// The latest handlers are read through refs, so a caller passing an inline
|
|
136
|
+
// arrow doesn't re-set the native prop each render.
|
|
137
|
+
const onRevealEndCallback = useMemo(() => relay(self, fireRevealEnd), [self]);
|
|
138
|
+
const onRevealMilestoneCallback = useMemo(() => relay(self, fireRevealMilestone), [self]);
|
|
139
|
+
const onAnimationStartCallback = useMemo(() => relay(self, fireAnimationStart), [self]);
|
|
140
|
+
const onAnimationEndCallback = useMemo(() => relay(self, fireAnimationEnd), [self]);
|
|
75
141
|
// A new array literal each render must not re-set the native prop. Always an
|
|
76
142
|
// array (empty = no tiers): removing the prop would reach native as `null`,
|
|
77
143
|
// which Nitro's array parser rejects ("Value is null, expected an Object").
|
|
@@ -111,7 +177,6 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, minorDigits,
|
|
|
111
177
|
// rolls the figure 1.2.
|
|
112
178
|
const figure = useMemo(() => (format ? figureOf(format, input) : undefined), [format, input]);
|
|
113
179
|
const compact = derived?.compact ? figure : undefined;
|
|
114
|
-
const compactRef = useRef(false);
|
|
115
180
|
compactRef.current = compact !== undefined;
|
|
116
181
|
// Which way the value moved, for a compact figure that fell while the value grew (999 → 1K).
|
|
117
182
|
const numericValue = toNumber(input);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-nitro-input",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
4
4
|
"description": "Native text for React Native, built with Nitro: a text and amount input with native formatting, masks and a Torph-style reflow, and an animated number (odometer, SwiftUI-style numeric text, ticker) whose digits roll or swap natively, with currency layouts and animated currency switches, shrink-to-fit, a loading shimmer and a jackpot reveal.",
|
|
5
5
|
"main": "lib/commonjs/src/index.js",
|
|
6
6
|
"module": "lib/module/src/index.js",
|
package/src/NitroNumber.tsx
CHANGED
|
@@ -376,6 +376,100 @@ interface Size {
|
|
|
376
376
|
const EMPTY: number[] = []
|
|
377
377
|
const EMPTY_STRINGS: string[] = []
|
|
378
378
|
|
|
379
|
+
/** What the native callbacks reach: one NitroNumber's refs and state setter. */
|
|
380
|
+
interface NumberSelf {
|
|
381
|
+
nativeRef: React.MutableRefObject<NitroNumberRef | null>
|
|
382
|
+
latestOnNativeRef: React.MutableRefObject<((native: NitroNumberRef) => void) | undefined>
|
|
383
|
+
setSize: React.Dispatch<React.SetStateAction<Size | null>>
|
|
384
|
+
latestOnRevealEnd: React.MutableRefObject<(() => void) | undefined>
|
|
385
|
+
latestOnRevealMilestone: React.MutableRefObject<((index: number, milestone: number) => void) | undefined>
|
|
386
|
+
latestOnAnimationStart: React.MutableRefObject<(() => void) | undefined>
|
|
387
|
+
latestOnAnimationEnd: React.MutableRefObject<((value: number) => void) | undefined>
|
|
388
|
+
compactRef: React.MutableRefObject<boolean>
|
|
389
|
+
latestValue: React.MutableRefObject<ReturnType<typeof withMinorDigits>>
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
type Deref<T extends object> = () => T | undefined
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* A weak reference where the engine has them (Hermes, JSC, V8), else a strong
|
|
396
|
+
* one. Two functions on purpose: an engine keeps one scope per function for
|
|
397
|
+
* everything its closures capture, so a `() => target` fallback written beside
|
|
398
|
+
* the weak closure would put `target` in the weak closure's scope too.
|
|
399
|
+
*/
|
|
400
|
+
function weakly<T extends object>(target: T): Deref<T> {
|
|
401
|
+
return typeof WeakRef === 'function' ? weakDeref(new WeakRef(target)) : strongDeref(target)
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function weakDeref<T extends object>(ref: WeakRef<T>): Deref<T> {
|
|
405
|
+
return () => ref.deref()
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function strongDeref<T extends object>(target: T): Deref<T> {
|
|
409
|
+
return () => target
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* A Nitro callback that calls `handler(self, ...args)` for as long as the
|
|
414
|
+
* component behind `self` is alive, holding `self` only weakly.
|
|
415
|
+
*
|
|
416
|
+
* Why. Nitro keeps every callback prop of a view as a JS function held from
|
|
417
|
+
* C++ (in the Fabric props of its shadow node), which Hermes treats as a GC
|
|
418
|
+
* root. A closure written inside the component shares the render's scope,
|
|
419
|
+
* so it reaches the fiber (through `setSize`) and the hybrid view's handle
|
|
420
|
+
* (through `nativeRef`), and the fiber holds the shadow node that holds the
|
|
421
|
+
* props that hold the closure: a loop through native code that Hermes can
|
|
422
|
+
* never collect. Every unmounted NitroNumber stayed, its fiber subtree, its
|
|
423
|
+
* hybrid view and Nitro's C++ part included: over 4,000 after a minute of
|
|
424
|
+
* a scrolling list, and the app's memory climbed with them. Built here, in
|
|
425
|
+
* module scope, the closure holds only the weak reference and `handler`
|
|
426
|
+
* (itself module-level); the fiber is what keeps `self` alive.
|
|
427
|
+
*/
|
|
428
|
+
function relay<A extends unknown[]>(self: NumberSelf, handler: (self: NumberSelf, ...args: A) => void) {
|
|
429
|
+
return relayTo(weakly(self), handler)
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* The closure itself, made where `self` is not in scope at all: Hermes (in
|
|
434
|
+
* debuggable builds, at least) keeps every variable of a function that makes
|
|
435
|
+
* a closure in that closure's scope, used or not, and a `self` there would
|
|
436
|
+
* hold the component strongly again.
|
|
437
|
+
*/
|
|
438
|
+
function relayTo<A extends unknown[]>(live: Deref<NumberSelf>, handler: (self: NumberSelf, ...args: A) => void) {
|
|
439
|
+
return callback((...args: A) => {
|
|
440
|
+
const target = live()
|
|
441
|
+
if (target !== undefined) handler(target, ...args)
|
|
442
|
+
})
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function attachNative(self: NumberSelf, instance: NitroNumberRef) {
|
|
446
|
+
self.nativeRef.current = instance
|
|
447
|
+
self.latestOnNativeRef.current?.(instance)
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function applySize(self: NumberSelf, width: number, height: number) {
|
|
451
|
+
self.setSize((previous) =>
|
|
452
|
+
previous !== null && previous.width === width && previous.height === height ? previous : { width, height }
|
|
453
|
+
)
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function fireRevealEnd(self: NumberSelf) {
|
|
457
|
+
self.latestOnRevealEnd.current?.()
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function fireRevealMilestone(self: NumberSelf, index: number, milestone: number) {
|
|
461
|
+
self.latestOnRevealMilestone.current?.(index, milestone)
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
function fireAnimationStart(self: NumberSelf) {
|
|
465
|
+
self.latestOnAnimationStart.current?.()
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** The figure a compact format rolls is not the value (1.2 for 1,234): report the value. */
|
|
469
|
+
function fireAnimationEnd(self: NumberSelf, shown: number) {
|
|
470
|
+
self.latestOnAnimationEnd.current?.(self.compactRef.current ? toNumber(self.latestValue.current) : shown)
|
|
471
|
+
}
|
|
472
|
+
|
|
379
473
|
/** Each transition's own timing, used when the props leave it unsaid. */
|
|
380
474
|
const TRANSITION_DEFAULTS: Record<NitroNumberTransition, { duration: number; easing: NitroNumberEasing; stagger: number }> = {
|
|
381
475
|
roll: { duration: 500, easing: 'easeInOut', stagger: 0 },
|
|
@@ -476,6 +570,8 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
|
|
|
476
570
|
ref
|
|
477
571
|
) {
|
|
478
572
|
const nativeRef = useRef<NitroNumberRef | null>(null)
|
|
573
|
+
// Whether a compact format is rolling (its figure is not the value); set below.
|
|
574
|
+
const compactRef = useRef(false)
|
|
479
575
|
const latestOnNativeRef = useRef(onNativeRef)
|
|
480
576
|
latestOnNativeRef.current = onNativeRef
|
|
481
577
|
const latestOnRevealEnd = useRef(onRevealEnd)
|
|
@@ -493,61 +589,33 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
|
|
|
493
589
|
|
|
494
590
|
const [size, setSize] = useState<Size | null>(null)
|
|
495
591
|
|
|
496
|
-
//
|
|
497
|
-
//
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
? previous
|
|
514
|
-
: { width, height }
|
|
515
|
-
)
|
|
516
|
-
}),
|
|
517
|
-
[]
|
|
518
|
-
)
|
|
519
|
-
|
|
520
|
-
// Stable like the others; the latest handler is read through a ref so a
|
|
521
|
-
// caller passing an inline arrow doesn't re-set the native prop each render.
|
|
522
|
-
const onRevealEndCallback = useMemo(
|
|
523
|
-
() =>
|
|
524
|
-
callback(() => {
|
|
525
|
-
latestOnRevealEnd.current?.()
|
|
526
|
-
}),
|
|
527
|
-
[]
|
|
528
|
-
)
|
|
529
|
-
const onRevealMilestoneCallback = useMemo(
|
|
530
|
-
() =>
|
|
531
|
-
callback((index: number, milestone: number) => {
|
|
532
|
-
latestOnRevealMilestone.current?.(index, milestone)
|
|
533
|
-
}),
|
|
534
|
-
[]
|
|
535
|
-
)
|
|
536
|
-
const onAnimationStartCallback = useMemo(
|
|
537
|
-
() =>
|
|
538
|
-
callback(() => {
|
|
539
|
-
latestOnAnimationStart.current?.()
|
|
540
|
-
}),
|
|
541
|
-
[]
|
|
542
|
-
)
|
|
543
|
-
// The figure a compact format rolls is not the value (1.2 for 1,234): report the value.
|
|
544
|
-
const onAnimationEndCallback = useMemo(
|
|
545
|
-
() =>
|
|
546
|
-
callback((shown: number) => {
|
|
547
|
-
latestOnAnimationEnd.current?.(compactRef.current ? toNumber(latestValue.current) : shown)
|
|
548
|
-
}),
|
|
592
|
+
// The native callbacks: wrapped with `callback()` and referentially stable
|
|
593
|
+
// (a new wrapper re-sets the prop every render), and built in module scope
|
|
594
|
+
// around a weak reference to this component's state (see `relay`).
|
|
595
|
+
const self = useMemo<NumberSelf>(
|
|
596
|
+
() => ({
|
|
597
|
+
nativeRef,
|
|
598
|
+
latestOnNativeRef,
|
|
599
|
+
setSize,
|
|
600
|
+
latestOnRevealEnd,
|
|
601
|
+
latestOnRevealMilestone,
|
|
602
|
+
latestOnAnimationStart,
|
|
603
|
+
latestOnAnimationEnd,
|
|
604
|
+
compactRef,
|
|
605
|
+
latestValue,
|
|
606
|
+
}),
|
|
607
|
+
// Every member is a ref or a state setter, stable for the component's life.
|
|
608
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
549
609
|
[]
|
|
550
610
|
)
|
|
611
|
+
const hybridRef = useMemo(() => relay(self, attachNative), [self])
|
|
612
|
+
const onSizeChange = useMemo(() => relay(self, applySize), [self])
|
|
613
|
+
// The latest handlers are read through refs, so a caller passing an inline
|
|
614
|
+
// arrow doesn't re-set the native prop each render.
|
|
615
|
+
const onRevealEndCallback = useMemo(() => relay(self, fireRevealEnd), [self])
|
|
616
|
+
const onRevealMilestoneCallback = useMemo(() => relay(self, fireRevealMilestone), [self])
|
|
617
|
+
const onAnimationStartCallback = useMemo(() => relay(self, fireAnimationStart), [self])
|
|
618
|
+
const onAnimationEndCallback = useMemo(() => relay(self, fireAnimationEnd), [self])
|
|
551
619
|
// A new array literal each render must not re-set the native prop. Always an
|
|
552
620
|
// array (empty = no tiers): removing the prop would reach native as `null`,
|
|
553
621
|
// which Nitro's array parser rejects ("Value is null, expected an Object").
|
|
@@ -599,7 +667,6 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
|
|
|
599
667
|
// rolls the figure 1.2.
|
|
600
668
|
const figure = useMemo(() => (format ? figureOf(format, input) : undefined), [format, input])
|
|
601
669
|
const compact = derived?.compact ? figure : undefined
|
|
602
|
-
const compactRef = useRef(false)
|
|
603
670
|
compactRef.current = compact !== undefined
|
|
604
671
|
// Which way the value moved, for a compact figure that fell while the value grew (999 → 1K).
|
|
605
672
|
const numericValue = toNumber(input)
|