react-native-nitro-input 0.3.7 → 0.3.8

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 CHANGED
@@ -1,5 +1,49 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.8
4
+
5
+ - **`NitroNumber` shows what its `format` prints, value by value.** It read the
6
+ format once and showed every value at its maximum fraction digits, rounded
7
+ by the engine (half away from zero, through a double). Now each value is
8
+ formatted:
9
+ - `trailingZeroDisplay: 'stripIfInteger'` and a minimum below the maximum
10
+ show the digits the format prints ("$1,234", then "$1,234.50"), and the
11
+ decimal columns roll in and out as the count changes.
12
+ - The figure is rounded with the format's `roundingMode` (`halfEven`
13
+ included), on the exact decimal: `"1.005"` is $1.01.
14
+ - A value that rounds to zero shows no minus.
15
+ - A format whose minimum fraction digits is below its maximum (a plain
16
+ decimal style, say) now drops the trailing zeros `Intl` drops; pass
17
+ `fractionDigits` to keep a fixed count.
18
+ - **`value` takes a `bigint` or a decimal string, and `minorDigits` reads it in
19
+ minor units**: `<NitroNumber value={123456n} minorDigits={2} format={usd} />`
20
+ shows $1,234.56. With a format, nothing goes through a double before it is
21
+ rounded; the rounded figure then rolls as a double, exact to 15 significant
22
+ digits. A string with an exponent (`"1e5"`) or a `0x` / `0o` / `0b` integer is
23
+ shifted exactly too; a string that is not a number shows as NaN rather than
24
+ an unshifted amount.
25
+ - **The components read their `format` in C++.** What `NitroNumber` and
26
+ `NitroInput` take from a `NumberFormat` (the figure per value, the prefix
27
+ and suffix, separators, grouping, sign placement, the locale's digits) is
28
+ read off the formatter's own parts natively, instead of formatting sample
29
+ values into JS objects and parsing them back there.
30
+ - **`NitroNumber` keeps rolling while its value keeps changing** (a slider, a
31
+ dial, a live price) (#62).
32
+ - With `easing="spring"`, each new value restarted the spring from rest, so
33
+ while a slider moved the figure stood still and only caught up when the
34
+ finger stopped. A wheel now keeps its speed through a new value (the
35
+ spring's response with the speed it had).
36
+ - With any easing, a new value mid-roll sent each wheel to the new digit
37
+ from where it stood, the way the value moved, so a wheel that lagged
38
+ behind or ran past its digit went a whole turn round. A new value now
39
+ moves where the wheel is going, by the step from the digit it was
40
+ heading for (as NumberFlow accumulates), so a stream one way spins it
41
+ faster and a drag that turns back slows it and turns it round.
42
+
43
+ Every digit still rolls on its own and lands within one `duration` of the
44
+ last value, as the numeric transition does. A single change from rest rolls
45
+ as before.
46
+
3
47
  ## 0.3.7
4
48
 
5
49
  - **Android: no longer breaks VisionCamera frame processors.** NitroInput
package/README.md CHANGED
@@ -855,8 +855,9 @@ import { NitroTime } from 'react-native-nitro-input'
855
855
 
856
856
  | Prop | Type | Default | Description |
857
857
  | --- | --- | --- | --- |
858
- | `value` | `number` | – | The number to display. Shown with at most 18 digits: `|value| × 10^fractionDigits` is clamped at 10^17, and a JS number carries exact integers only up to 2^53. |
859
- | `fractionDigits` | `number` | `0` | Digits after the decimal separator. |
858
+ | `value` | `number \| bigint \| string` | – | The number to display. A bigint or a decimal string passes straight in (with a `format`, rounded by it in decimal). Animated as a double: exact while `|value| × 10^fractionDigits` stays within 2^53, at most 18 digits shown. |
859
+ | `minorDigits` | `number` | `0` | The decimal places `value` is counted in: `value={123456n} minorDigits={2}` is 1234.56. |
860
+ | `fractionDigits` | `number` | `0` | Digits after the decimal separator. With a `format`, what the format prints per value (`trailingZeroDisplay`, a minimum below the maximum); set, every value shows this many. |
860
861
  | `minimumIntegerDigits` | `number` | `1` | Zero-pads the integer part. |
861
862
  | `groupingSeparator` | `string` | `''` | Inserted between digit groups. |
862
863
  | `groupingSizes` | `number[]` | `[3]` | Group sizes from the decimal point: `[3, 2]` is Indian grouping (12,34,567). |
@@ -907,7 +908,7 @@ import { NitroTime } from 'react-native-nitro-input'
907
908
  | `prefixColor` / `suffixColor` | `ColorValue` | `color` | The affixes' colours. |
908
909
  | `fractionFontSize` / `fractionColor` | `number` / `ColorValue` | `fontSize` / `color` | Smaller, dimmer cents (the decimal separator follows). |
909
910
  | `fractionAlign` | `'baseline' \| 'center' \| 'top' \| 'bottom'` | `'baseline'` | `'top'`: superscript cents. |
910
- | `format` | `NumberFormat` | none | The number follows it: prefix and suffix, separators and group sizes, fraction and minimum integer digits, sign display, native digits; a compact format rolls its figure and swaps its suffix ("950" → "1.5K"). The individual props override it. |
911
+ | `format` | `NumberFormat` | none | The number follows it: prefix and suffix, separators and group sizes, minimum integer digits, sign display, native digits, and per value the digits it prints (its `roundingMode`, its `trailingZeroDisplay`); a compact format rolls its figure and swaps its suffix ("950" → "1.5K"). The individual props override it. |
911
912
  | `tabularNums` | boolean | `true` | `false` lays each digit out at its own width (proportional figures); a changing column eases once from the old digit's width to the new one's. |
912
913
  | `adjustsFontSizeToFit` | `boolean` | `false` | Shrink the whole number to fit the view's fixed `width`; the view keeps its full height. |
913
914
  | `minimumFontScale` | `number` | `0.5` | Lower bound for `adjustsFontSizeToFit`. |
@@ -22,6 +22,7 @@ add_library(${PACKAGE_NAME} SHARED
22
22
  ../cpp/worklets/NitroInputWorkletsBridge.cpp
23
23
  ../cpp/worklets/HybridNitroInputWorklets.cpp
24
24
  ../cpp/numberformat/NumberFormatCore.cpp
25
+ ../cpp/numberformat/FormatFigure.cpp
25
26
  ../cpp/numberformat/NumberFormatProbe.cpp
26
27
  ../cpp/numberformat/HybridNitroNumberFormat.cpp
27
28
  )
@@ -459,12 +459,39 @@ void RollingEngine::animateTo(double value, double now) {
459
459
  popStart_ = now;
460
460
  }
461
461
 
462
+ // On the spring, a wheel that was already rolling carries its speed into
463
+ // this roll. The spring's step response starts at rest, so every value of
464
+ // a stream (a slider, a dial, a live price) stopped each wheel and started
465
+ // it again: a figure fed by a slider stood still until the finger stopped.
466
+ if (easing_ == 4 && !next.numeric && transition_.active && !transition_.numeric && next.duration > 0) {
467
+ constexpr double h = 1.0 / 240.0;
468
+ const size_t shared = std::min(next.wheels.size(), transition_.wheels.size());
469
+ for (size_t i = 0; i < shared; i++) {
470
+ WheelTransition& wt = next.wheels[i];
471
+ const double travel = wt.to.position - wt.from.position;
472
+ if (std::fabs(travel) < 1e-6 || wt.from.linear != transition_.wheels[i].from.linear) {
473
+ continue;
474
+ }
475
+ const double speed = (rollPosition(transition_, i, now) - rollPosition(transition_, i, now - h)) / h;
476
+ wt.carriesSpeed = true;
477
+ wt.startSpeed = speed * next.duration / travel;
478
+ }
479
+ }
480
+
462
481
  transition_ = std::move(next);
463
482
  apply(0);
464
483
  applyEffects(now);
465
484
  settle(target);
466
485
  }
467
486
 
487
+ double RollingEngine::rollPosition(const Transition& tr, size_t index, double now) const {
488
+ const WheelTransition& wt = tr.wheels[index];
489
+ const double delay = index < tr.delays.size() ? tr.delays[index] : 0;
490
+ const double raw = tr.duration > 0 ? clamp01((now - tr.start - delay) / tr.duration) : 1.0;
491
+ const double t = !tr.fromMotion ? ease(raw) : wt.carriesSpeed ? easeFromMotion(raw, wt.startSpeed) : easeFromMotion(raw);
492
+ return wt.from.position + (wt.to.position - wt.from.position) * t;
493
+ }
494
+
468
495
  void RollingEngine::planRoll(Transition& next, const Target& target, bool increasing, int count, int mandatory) const {
469
496
  const int currentCount = static_cast<int>(wheels_.size());
470
497
  // Below `pad`: decimal columns the format dropped (`changeFormat`).
@@ -510,15 +537,29 @@ void RollingEngine::planRoll(Transition& next, const Target& target, bool increa
510
537
  // Interior wheel: shortest roll in the direction of the change, or
511
538
  // with `shortest` the shorter way round for this wheel alone (8 → 2
512
539
  // rolls back through 5), a tie (five apart) going with the change.
513
- const double base = wrapTo(from.position, modulus);
514
- from.position = base;
540
+ // A value arriving mid-roll moves where the wheel is going, not where
541
+ // it stands: by the step from the digit it was rolling to, onto the
542
+ // one it still had to cover (NumberFlow's accumulating composite). A
543
+ // stream that runs one way piles up and the wheel spins to keep up;
544
+ // one that turns back takes it off, and the wheel slows and turns with
545
+ // it. Measured from where the wheel stood, a wheel that lagged behind
546
+ // or ran past its digit went a whole turn round, or the short way
547
+ // backwards, and a fast drag left it stalling.
548
+ const bool rolling = next.fromMotion && transition_.active && !transition_.numeric &&
549
+ power < static_cast<int>(transition_.wheels.size()) && !current.linear &&
550
+ !transition_.wheels[static_cast<size_t>(power)].to.linear && current.blend >= 1;
551
+ const double heading = rolling ? transition_.wheels[static_cast<size_t>(power)].to.position : 0;
552
+ const double base = rolling ? wrapTo(heading, modulus) : wrapTo(from.position, modulus);
553
+ if (!rolling) {
554
+ from.position = base;
555
+ }
515
556
  from.linear = false;
516
557
  const double up = wrapTo(digit - base, modulus);
517
558
  const double down = wrapTo(base - digit, modulus);
518
559
  double delta = increasing ? up : -down;
519
560
  if (direction_ == 3 && up != down) delta = up < down ? up : -down;
520
561
  if (delta == 0 && power < highestChange) delta = increasing ? modulus : -modulus;
521
- to = Wheel{base + delta, 1.0, false, false};
562
+ to = Wheel{(rolling ? heading : base) + delta, 1.0, false, false};
522
563
  }
523
564
  next.finals.push_back(Wheel{digit, 1.0, false, false});
524
565
  } else {
@@ -961,7 +1002,7 @@ void RollingEngine::apply(double elapsed) {
961
1002
  // a column opens and closes over the duration itself.
962
1003
  const double span = tr.style == 1 ? tr.duration / kNumericTail : tr.duration;
963
1004
  const double rawSpan = span > 0 ? clamp01((elapsed - delay) / span) : 1.0;
964
- double t = tr.fromMotion ? easeFromMotion(rawSpan) : ease(rawSpan);
1005
+ double t = !tr.fromMotion ? ease(rawSpan) : wt.carriesSpeed ? easeFromMotion(rawSpan, wt.startSpeed) : easeFromMotion(rawSpan);
965
1006
  if (tr.numeric) {
966
1007
  // A column opens on the arriving glyph's size-and-opacity spring and
967
1008
  // closes on the leaving glyph's blur, the faster one: on the
@@ -1223,12 +1264,34 @@ double RollingEngine::easeFromMotion(double t) const {
1223
1264
  case 1:
1224
1265
  return t; // linear / easeIn: keep the wheel moving at a steady pace
1225
1266
  case 4:
1226
- return spring(t, bounce_); // the spring already starts with velocity
1267
+ return spring(t, bounce_); // from rest; a wheel in motion carries its speed (below)
1227
1268
  default:
1228
1269
  return 1 - std::pow(1 - t, 3); // easeOut / easeInOut: decelerate into the new target
1229
1270
  }
1230
1271
  }
1231
1272
 
1273
+ double RollingEngine::easeFromMotion(double t, double startSpeed) const {
1274
+ if (easing_ == 4) {
1275
+ // Bounded: a wheel a hair from its digit would otherwise read as flying.
1276
+ return springFrom(t, bounce_, std::min(12.0, std::max(-12.0, startSpeed)));
1277
+ }
1278
+ return easeFromMotion(t);
1279
+ }
1280
+
1281
+ double RollingEngine::springFrom(double t, double bounce, double startSpeed) {
1282
+ // x(t) of the same spring as `spring`, released at 0 towards 1 at speed v0:
1283
+ // 1 - e^{-kt}(cos ωd t + ((k - v0)/ωd) sin ωd t), or 1 - (1 + (k - v0)t)e^{-kt}
1284
+ // critically damped. v0 = 0 is `spring` exactly.
1285
+ const double zeta = std::min(1.0, std::max(0.05, 1.0 - clamp01(bounce)));
1286
+ const double omega = 3.0 * kPi;
1287
+ const double k = zeta * omega;
1288
+ if (zeta >= 0.999) {
1289
+ return 1 - (1 + (k - startSpeed) * t) * std::exp(-k * t);
1290
+ }
1291
+ const double wd = omega * std::sqrt(1 - zeta * zeta);
1292
+ return 1 - std::exp(-k * t) * (std::cos(wd * t) + ((k - startSpeed) / wd) * std::sin(wd * t));
1293
+ }
1294
+
1232
1295
  /// Step response of a damped spring, normalised so it has settled at t == 1.
1233
1296
  /// `bounce` maps to the damping ratio like SwiftUI's `.spring(duration:bounce:)`.
1234
1297
  double RollingEngine::spring(double t, double bounce) {
@@ -341,6 +341,11 @@ private:
341
341
  /// being cut short. `clock` is how far into the swap it was (seconds).
342
342
  bool continues = false;
343
343
  double clock = 0;
344
+ /// Roll: the wheel was already moving when the value changed, at
345
+ /// `startSpeed` in this roll's own units (its travel per duration); the
346
+ /// spring starts at that speed rather than from rest.
347
+ bool carriesSpeed = false;
348
+ double startSpeed = 0;
344
349
  };
345
350
  struct Transition {
346
351
  bool active = false;
@@ -427,7 +432,15 @@ private:
427
432
  /// The curve used when re-targeting mid-roll: the ease-in curves collapse to
428
433
  /// their ease-out / linear counterparts so a wheel in motion never stalls.
429
434
  double easeFromMotion(double t) const;
435
+ /// The roll's curve for a wheel that was already moving at `startSpeed`
436
+ /// (travel per duration) when the value changed: the spring starts at that
437
+ /// speed, the other curves are `easeFromMotion(t)`.
438
+ double easeFromMotion(double t, double startSpeed) const;
430
439
  static double spring(double t, double bounce);
440
+ /// `spring` starting at `startSpeed` (travel per duration) instead of from rest.
441
+ static double springFrom(double t, double bounce, double startSpeed);
442
+ /// Where wheel `index` of a roll stands at `now`.
443
+ double rollPosition(const Transition& tr, size_t index, double now) const;
431
444
  /// Step response of a damped spring with damping ratio `zeta`, scaled so it
432
445
  /// has settled (within 2 %) at t == `settle`; 0 at t <= 0.
433
446
  static double damped(double t, double zeta, double settle);
@@ -0,0 +1,134 @@
1
+ //
2
+ // FormatFigure.cpp
3
+ // NitroInput
4
+ //
5
+
6
+ #include "FormatFigure.hpp"
7
+
8
+ #include <cstdlib>
9
+
10
+ namespace margelo::nitro::nitroinput::numberformat {
11
+
12
+ namespace {
13
+
14
+ bool isNumberPart(PartType type) {
15
+ return type == PartType::Integer || type == PartType::Group || type == PartType::Decimal || type == PartType::Fraction;
16
+ }
17
+
18
+ /// `text` with the locale's digits written as Latin ones.
19
+ std::string latin(const std::string& text, const std::array<std::string, 10>& localeDigits) {
20
+ std::string out;
21
+ out.reserve(text.size());
22
+ size_t i = 0;
23
+ while (i < text.size()) {
24
+ bool matched = false;
25
+ for (int d = 0; d < 10; d++) {
26
+ const std::string& glyph = localeDigits[static_cast<size_t>(d)];
27
+ if (!glyph.empty() && text.compare(i, glyph.size(), glyph) == 0) {
28
+ out.push_back(static_cast<char>('0' + d));
29
+ i += glyph.size();
30
+ matched = true;
31
+ break;
32
+ }
33
+ }
34
+ if (!matched) out.push_back(text[i++]);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ std::string joined(const std::vector<Part>& parts, PartType type, const std::array<std::string, 10>& localeDigits) {
40
+ std::string out;
41
+ for (const Part& p : parts) {
42
+ if (p.type == type) out += p.value;
43
+ }
44
+ return latin(out, localeDigits);
45
+ }
46
+
47
+ /// The text before and after the number in `parts`; the sign is the components' own glyph, not part of either.
48
+ void affixesOf(const std::vector<Part>& parts, std::string& prefix, std::string& suffix) {
49
+ int first = -1;
50
+ int last = -1;
51
+ for (int i = 0; i < static_cast<int>(parts.size()); i++) {
52
+ if (isNumberPart(parts[static_cast<size_t>(i)].type)) {
53
+ if (first < 0) first = i;
54
+ last = i;
55
+ }
56
+ }
57
+ prefix.clear();
58
+ suffix.clear();
59
+ if (first < 0) return;
60
+ for (int i = 0; i < static_cast<int>(parts.size()); i++) {
61
+ const Part& p = parts[static_cast<size_t>(i)];
62
+ if (p.type == PartType::MinusSign || p.type == PartType::PlusSign) continue;
63
+ if (i < first) prefix += p.value;
64
+ if (i > last) suffix += p.value;
65
+ }
66
+ }
67
+
68
+ bool isLatin(const std::array<std::string, 10>& localeDigits) {
69
+ for (int d = 0; d < 10; d++) {
70
+ if (localeDigits[static_cast<size_t>(d)] != std::string(1, static_cast<char>('0' + d))) return false;
71
+ }
72
+ return true;
73
+ }
74
+
75
+ } // namespace
76
+
77
+ double Figure::value() const {
78
+ if (!finite) return 0;
79
+ const double magnitude = std::strtod(digits.c_str(), nullptr);
80
+ if (magnitude == 0) return 0;
81
+ return negative ? -magnitude : magnitude;
82
+ }
83
+
84
+ Figure figureOf(const std::vector<Part>& parts, bool negative, const std::array<std::string, 10>& localeDigits) {
85
+ Figure figure;
86
+ affixesOf(parts, figure.prefix, figure.suffix);
87
+ const std::string integer = joined(parts, PartType::Integer, localeDigits);
88
+ const std::string fraction = joined(parts, PartType::Fraction, localeDigits);
89
+ // NaN and infinities have no integer part: nothing the digits can roll to.
90
+ if (integer.empty()) return figure;
91
+ figure.finite = true;
92
+ figure.digits = fraction.empty() ? integer : integer + "." + fraction;
93
+ figure.fractionDigits = static_cast<int>(fraction.size());
94
+ bool nonZero = false;
95
+ for (char c : figure.digits) nonZero = nonZero || (c >= '1' && c <= '9');
96
+ figure.negative = negative && nonZero;
97
+ return figure;
98
+ }
99
+
100
+ Layout layoutOf(const std::vector<Part>& sample, const std::vector<Part>& negativeOne, const std::array<std::string, 10>& localeDigits) {
101
+ Layout layout;
102
+ affixesOf(sample, layout.prefix, layout.suffix);
103
+ std::vector<int> integers;
104
+ bool hasGroup = false;
105
+ bool hasDecimal = false;
106
+ for (const Part& p : sample) {
107
+ if (p.type == PartType::Group && !hasGroup) {
108
+ layout.groupingSeparator = p.value;
109
+ hasGroup = true;
110
+ } else if (p.type == PartType::Decimal && !hasDecimal) {
111
+ layout.decimalSeparator = p.value;
112
+ hasDecimal = true;
113
+ } else if (p.type == PartType::Integer) {
114
+ integers.push_back(static_cast<int>(latin(p.value, localeDigits).size()));
115
+ }
116
+ }
117
+ // "12,34,567": the last group is the first size, the one before it every later one.
118
+ if (integers.size() >= 3) {
119
+ layout.groupingSizes = {integers[integers.size() - 1], integers[integers.size() - 2]};
120
+ }
121
+ int minus = -1;
122
+ int currency = -1;
123
+ for (int i = 0; i < static_cast<int>(negativeOne.size()); i++) {
124
+ const PartType type = negativeOne[static_cast<size_t>(i)].type;
125
+ if (type == PartType::MinusSign && minus < 0) minus = i;
126
+ if ((type == PartType::Currency || type == PartType::PercentSign) && currency < 0) currency = i;
127
+ }
128
+ if (minus >= 0) layout.minusSign = negativeOne[static_cast<size_t>(minus)].value;
129
+ layout.signAfterAffix = minus >= 0 && currency >= 0 && minus > currency;
130
+ if (!isLatin(localeDigits)) layout.digitGlyphs.assign(localeDigits.begin(), localeDigits.end());
131
+ return layout;
132
+ }
133
+
134
+ } // namespace margelo::nitro::nitroinput::numberformat
@@ -0,0 +1,65 @@
1
+ //
2
+ // FormatFigure.hpp
3
+ // NitroInput
4
+ //
5
+ // What `NitroNumber` and `NitroInput` take from a formatted number: the
6
+ // figure the digits show, and the text around it. Read off the parts the
7
+ // formatter produced, so the figure is rounded and trimmed exactly as the
8
+ // format prints it (its rounding mode, trailing zeros, significant digits,
9
+ // compact notation), from the decimal the value was, never through a double.
10
+ // Plain C++, unit-tested on the host.
11
+ //
12
+
13
+ #pragma once
14
+
15
+ #include "NumberFormatCore.hpp"
16
+
17
+ #include <array>
18
+ #include <string>
19
+ #include <vector>
20
+
21
+ namespace margelo::nitro::nitroinput::numberformat {
22
+
23
+ /// One formatted value, as the rolling figure takes it.
24
+ struct Figure {
25
+ /// Finite, and so a figure the digits can roll to (NaN and infinities are not).
26
+ bool finite = false;
27
+ /// The value was below zero and its shown digits are not all zero: "-$0.00" is not negative.
28
+ bool negative = false;
29
+ /// The digits shown, in Latin digits with "." before the fraction ("1234.5"), without sign or grouping.
30
+ std::string digits;
31
+ /// How many of `digits` follow the point: what this value shows ("$1,234" 0, "$1,234.50" 2).
32
+ int fractionDigits = 0;
33
+ /// The text before and after the number, without the sign: the components draw their own.
34
+ std::string prefix;
35
+ std::string suffix;
36
+
37
+ /// The figure as a double: its digits, signed. 0 (never -0) for a figure that is not finite or rounds to nothing.
38
+ double value() const;
39
+ };
40
+
41
+ /// The figure in `parts`, formatted from a value that was `negative`.
42
+ /// `localeDigits` are the format's digits 0…9, which map back to Latin ones.
43
+ Figure figureOf(const std::vector<Part>& parts, bool negative, const std::array<std::string, 10>& localeDigits);
44
+
45
+ /// The shape of a format, as the components lay a number out.
46
+ struct Layout {
47
+ std::string prefix;
48
+ std::string suffix;
49
+ /// Empty when the format does not group.
50
+ std::string groupingSeparator;
51
+ std::string decimalSeparator = ".";
52
+ /// A negative amount's sign comes after the prefix ("$-5"), not before it ("-$5").
53
+ bool signAfterAffix = false;
54
+ std::string minusSign = "-";
55
+ /// The group nearest the decimal point and every one before it ([3, 2]: 12,34,567).
56
+ std::vector<int> groupingSizes = {3};
57
+ /// The format's digits 0…9, or empty for Latin ones.
58
+ std::vector<std::string> digitGlyphs;
59
+ };
60
+
61
+ /// The layout of a format, read off its parts for a value with every part
62
+ /// (`sample`: 1234567, or 1234567.5 when it shows a fraction) and for -1.
63
+ Layout layoutOf(const std::vector<Part>& sample, const std::vector<Part>& negativeOne, const std::array<std::string, 10>& localeDigits);
64
+
65
+ } // namespace margelo::nitro::nitroinput::numberformat
@@ -175,28 +175,50 @@ HybridNitroNumberFormat::HybridNitroNumberFormat(ResolvedNumberFormatOptions res
175
175
  : HybridObject(TAG), resolved_(std::move(resolved)), platform_(std::move(platform)), platformFormat_(std::move(format)),
176
176
  platformSymbols_(std::move(symbols)), words_(words), scientific_(scientific) {}
177
177
 
178
- std::string HybridNitroNumberFormat::formatWithPlatform(const std::variant<int64_t, double, std::string>& value) {
178
+ std::string HybridNitroNumberFormat::formatWithPlatform(const std::variant<int64_t, double, std::string>& value, const Decimal* decimal) {
179
179
  if (compactRounding_) {
180
- const Decimal d = toDecimal(value);
180
+ const Decimal d = decimal ? *decimal : toDecimal(value);
181
181
  if (d.kind != Decimal::Kind::Finite && nonFinite_) return nonFinite_->format(d);
182
182
  return platform_->formatDecimal(decimalString(roundCompact(d, *compactRounding_, compactExponents_)));
183
183
  }
184
184
  if (std::holds_alternative<double>(value)) return platform_->format(std::get<double>(value));
185
- return platform_->formatDecimal(decimalString(toDecimal(value)));
185
+ return platform_->formatDecimal(decimalString(decimal ? *decimal : toDecimal(value)));
186
186
  }
187
187
 
188
188
  std::string HybridNitroNumberFormat::format(const std::variant<int64_t, double, std::string>& value) {
189
189
  if (core_) return core_->format(toDecimal(value));
190
- return formatWithPlatform(value);
190
+ return formatWithPlatform(value, nullptr);
191
+ }
192
+
193
+ std::vector<Part> HybridNitroNumberFormat::partsOf(const std::variant<int64_t, double, std::string>& value, const Decimal& decimal) {
194
+ if (core_) return core_->formatToParts(decimal);
195
+ if (compactRounding_ && nonFinite_ && decimal.kind != Decimal::Kind::Finite) return nonFinite_->formatToParts(decimal);
196
+ return partsOfFormatted(formatWithPlatform(value, &decimal), platformFormat_, platformSymbols_, words_, scientific_);
191
197
  }
192
198
 
193
199
  std::vector<NumberFormatPart> HybridNitroNumberFormat::formatToParts(const std::variant<int64_t, double, std::string>& value) {
194
- if (core_) return toParts(core_->formatToParts(toDecimal(value)));
195
- if (compactRounding_ && nonFinite_) {
196
- const Decimal d = toDecimal(value);
197
- if (d.kind != Decimal::Kind::Finite) return toParts(nonFinite_->formatToParts(d));
198
- }
199
- return toParts(partsOfFormatted(formatWithPlatform(value), platformFormat_, platformSymbols_, words_, scientific_));
200
+ return toParts(partsOf(value, toDecimal(value)));
201
+ }
202
+
203
+ NumberFigure HybridNitroNumberFormat::figure(const std::variant<int64_t, double, std::string>& value) {
204
+ // Read once: the parts and the sign come from the same decimal.
205
+ const Decimal decimal = toDecimal(value);
206
+ const Figure f = figureOf(partsOf(value, decimal), decimal.negative, localeDigits());
207
+ // NaN and infinities roll nowhere; they keep the format's own fraction digits.
208
+ const double fractionDigits = f.finite ? static_cast<double>(f.fractionDigits) : resolved_.maximumFractionDigits.value_or(0);
209
+ return NumberFigure(f.value(), fractionDigits, f.prefix, f.suffix);
210
+ }
211
+
212
+ NumberFormatLayout HybridNitroNumberFormat::layout() {
213
+ // A value with every part: groups, and a fraction when the format has one.
214
+ // Compact notation would print it "1.2M", so its affixes come per value.
215
+ const bool compact = resolved_.notation == NumberFormatNotation::COMPACT;
216
+ const std::string sample = compact ? "1" : resolved_.maximumFractionDigits.value_or(0) > 0 ? "1234567.5" : "1234567";
217
+ const std::string minusOne = "-1";
218
+ const Layout l = layoutOf(partsOf(sample, toDecimal(sample)), partsOf(minusOne, toDecimal(minusOne)), localeDigits());
219
+ std::vector<double> groupingSizes(l.groupingSizes.begin(), l.groupingSizes.end());
220
+ return NumberFormatLayout(l.prefix, l.suffix, l.groupingSeparator, l.decimalSeparator, l.signAfterAffix, l.minusSign, std::move(groupingSizes),
221
+ l.digitGlyphs);
200
222
  }
201
223
 
202
224
  // MARK: - The factory
@@ -15,6 +15,7 @@
15
15
  #include "HybridNitroNumberFormatFactorySpec.hpp"
16
16
  #include "HybridNitroNumberFormatSpec.hpp"
17
17
  #include "HybridNitroPlatformNumberFormatterSpec.hpp"
18
+ #include "FormatFigure.hpp"
18
19
  #include "NumberFormatCore.hpp"
19
20
  #include "NumberFormatProbe.hpp"
20
21
 
@@ -41,6 +42,8 @@ public:
41
42
  std::string format(const std::variant<int64_t, double, std::string>& value) override;
42
43
  std::vector<NumberFormatPart> formatToParts(const std::variant<int64_t, double, std::string>& value) override;
43
44
  ResolvedNumberFormatOptions resolvedOptions() override { return resolved_; }
45
+ NumberFigure figure(const std::variant<int64_t, double, std::string>& value) override;
46
+ NumberFormatLayout layout() override;
44
47
 
45
48
  /// The C++ core, or null for a formatter the platform draws.
46
49
  const numberformat::NumberFormatCore* core() const { return core_ ? &*core_ : nullptr; }
@@ -48,7 +51,12 @@ public:
48
51
  size_t getExternalMemorySize() noexcept override { return 2048; }
49
52
 
50
53
  private:
51
- std::string formatWithPlatform(const std::variant<int64_t, double, std::string>& value);
54
+ /// The parts for `value`, read already as `decimal`.
55
+ std::vector<numberformat::Part> partsOf(const std::variant<int64_t, double, std::string>& value, const numberformat::Decimal& decimal);
56
+ /// The digits 0…9 this formatter prints.
57
+ const std::array<std::string, 10>& localeDigits() const { return core_ ? core_->localeFormat().digits : platformFormat_.digits; }
58
+ /// `decimal`: `value` read already, or null to read it here when needed.
59
+ std::string formatWithPlatform(const std::variant<int64_t, double, std::string>& value, const numberformat::Decimal* decimal);
52
60
 
53
61
  ResolvedNumberFormatOptions resolved_;
54
62
  std::optional<numberformat::NumberFormatCore> core_;
@@ -66,7 +66,7 @@ const TRANSITION_DEFAULTS = {
66
66
  * The view sizes itself to its content unless you pass an explicit `width` /
67
67
  * `height` in `style`.
68
68
  */
69
- exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, 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) {
69
+ 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
70
  const nativeRef = (0, react_1.useRef)(null);
71
71
  const latestOnNativeRef = (0, react_1.useRef)(onNativeRef);
72
72
  latestOnNativeRef.current = onNativeRef;
@@ -74,8 +74,10 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, frac
74
74
  latestOnRevealEnd.current = onRevealEnd;
75
75
  const latestOnRevealMilestone = (0, react_1.useRef)(onRevealMilestone);
76
76
  latestOnRevealMilestone.current = onRevealMilestone;
77
- const latestValue = (0, react_1.useRef)(value);
78
- latestValue.current = value;
77
+ // The value as the format takes it: minor units shifted in, exactly.
78
+ const input = (0, formatProps_1.withMinorDigits)(value, minorDigits);
79
+ const latestValue = (0, react_1.useRef)(input);
80
+ latestValue.current = input;
79
81
  const latestOnAnimationStart = (0, react_1.useRef)(onAnimationStart);
80
82
  latestOnAnimationStart.current = onAnimationStart;
81
83
  const latestOnAnimationEnd = (0, react_1.useRef)(onAnimationEnd);
@@ -107,7 +109,7 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, frac
107
109
  }), []);
108
110
  // The figure a compact format rolls is not the value (1.2 for 1,234): report the value.
109
111
  const onAnimationEndCallback = (0, react_1.useMemo)(() => (0, react_native_nitro_modules_1.callback)((shown) => {
110
- latestOnAnimationEnd.current?.(compactRef.current ? latestValue.current : shown);
112
+ latestOnAnimationEnd.current?.(compactRef.current ? (0, formatProps_1.toNumber)(latestValue.current) : shown);
111
113
  }), []);
112
114
  // A new array literal each render must not re-set the native prop. Always an
113
115
  // array (empty = no tiers): removing the prop would reach native as `null`,
@@ -122,7 +124,7 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, frac
122
124
  jumpTo: (next) => nativeRef.current?.jumpTo(next),
123
125
  animateTo: (next) => nativeRef.current?.animateTo(next),
124
126
  revealTo: (next) => nativeRef.current?.revealTo(next),
125
- getValue: () => (compactRef.current ? latestValue.current : nativeRef.current?.value ?? latestValue.current),
127
+ getValue: () => compactRef.current ? (0, formatProps_1.toNumber)(latestValue.current) : nativeRef.current?.value ?? (0, formatProps_1.toNumber)(latestValue.current),
126
128
  get native() {
127
129
  return nativeRef.current;
128
130
  },
@@ -143,14 +145,20 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, frac
143
145
  const resolvedFontSize = fontSize ?? 32;
144
146
  const resolvedAffixAlign = affixAlign ?? 'baseline';
145
147
  const derived = format ? (0, formatProps_1.formatProps)(format) : undefined;
146
- // Compact notation: "1.2K" rolls the figure 1.2 and swaps the suffix.
147
- const compact = format && derived?.compact ? (0, formatProps_1.compactParts)(format, value) : undefined;
148
+ // What the format shows for this value: the figure rounded its way, in the
149
+ // fraction digits it prints. Compact notation also swaps the suffix: "1.2K"
150
+ // rolls the figure 1.2.
151
+ const figure = (0, react_1.useMemo)(() => (format ? (0, formatProps_1.figureOf)(format, input) : undefined), [format, input]);
152
+ const compact = derived?.compact ? figure : undefined;
148
153
  const compactRef = (0, react_1.useRef)(false);
149
154
  compactRef.current = compact !== undefined;
150
155
  // Which way the value moved, for a compact figure that fell while the value grew (999 → 1K).
151
- const previousValue = (0, react_1.useRef)(value);
152
- const compactDirection = compact && direction === undefined ? (value >= previousValue.current ? 'up' : 'down') : undefined;
153
- previousValue.current = value;
156
+ const numericValue = (0, formatProps_1.toNumber)(input);
157
+ const previousValue = (0, react_1.useRef)(numericValue);
158
+ const compactDirection = compact && direction === undefined ? (numericValue >= previousValue.current ? 'up' : 'down') : undefined;
159
+ previousValue.current = numericValue;
160
+ // Without a format the engine rounds the double, as it always has.
161
+ const shownValue = figure ? figure.value : numericValue;
154
162
  const processedPrefixColor = (0, react_1.useMemo)(() => (0, styleHelpers_1.toProcessedColor)(prefixColor) ?? Infinity, [prefixColor]);
155
163
  const processedSuffixColor = (0, react_1.useMemo)(() => (0, styleHelpers_1.toProcessedColor)(suffixColor) ?? Infinity, [suffixColor]);
156
164
  const processedFractionColor = (0, react_1.useMemo)(() => (0, styleHelpers_1.toProcessedColor)(fractionColor) ?? Infinity, [fractionColor]);
@@ -186,5 +194,5 @@ exports.NitroNumber = (0, react_1.forwardRef)(function NitroNumber({ value, frac
186
194
  // does not hand a Hybrid View its resolved direction, so native is told.
187
195
  const layoutDirection = (0, react_1.useMemo)(() => react_native_1.StyleSheet.flatten(style)?.direction, [style]);
188
196
  const rightToLeft = layoutDirection === 'rtl' || (layoutDirection !== 'ltr' && react_native_1.I18nManager.isRTL);
189
- return (react_1.default.createElement(exports.NativeNitroNumberView, { ...viewProps, style: [autoSize, style], hybridRef: hybridRef, value: compact ? compact.value : value, fractionDigits: fractionDigits ?? compact?.fractionDigits ?? derived?.fractionDigits ?? 0, minimumIntegerDigits: minimumIntegerDigits ?? derived?.minimumIntegerDigits ?? 1, groupingSeparator: groupingSeparator ?? derived?.groupingSeparator ?? '', decimalSeparator: decimalSeparator ?? derived?.decimalSeparator ?? '.', prefix: prefix ?? compact?.prefix ?? derived?.prefix ?? '', suffix: suffix ?? compact?.suffix ?? derived?.suffix ?? '', transition: transition ?? 'roll', flashUpColor: processedFlashUp, flashDownColor: processedFlashDown, flashDuration: flashDuration ?? 600, popOnChange: popOnChange ?? 0, duration: still ? 0 : duration ?? TRANSITION_DEFAULTS[transition ?? 'roll'].duration, easing: easing ?? TRANSITION_DEFAULTS[transition ?? 'roll'].easing, bounce: bounce ?? 0.15, stagger: stagger ?? TRANSITION_DEFAULTS[transition ?? 'roll'].stagger, rollDirection: direction ?? compactDirection ?? 'auto', revealState: reveal === undefined ? 0 : reveal ? 2 : 1, revealStyle: revealStyle ?? 'count', revealDuration: still ? 0 : revealDuration ?? 2200, revealBounce: revealBounce ?? 0.12, revealGrow: revealGrow ?? 0.2, revealStagger: revealStagger ?? 200, revealMilestones: stableMilestones, revealMilestoneHold: revealMilestoneHold ?? 0, onRevealEnd: onRevealEndCallback, onRevealMilestone: onRevealMilestoneCallback, onAnimationStart: onAnimationStartCallback, onAnimationEnd: onAnimationEndCallback, loading: loading ?? false, shimmerColor: processedShimmerColor, shimmerDuration: shimmerDuration ?? 950, shimmerAngle: shimmerAngle ?? 31, shimmerWidth: shimmerWidth ?? 1, shimmerBaseColor: processedShimmerBase, shimmerDirection: shimmerDirection ?? 'auto', shimmerDelay: shimmerDelay ?? 0, fontSize: resolvedFontSize, prefixFontSize: prefixFontSize ?? resolvedFontSize, suffixFontSize: suffixFontSize ?? resolvedFontSize, affixAlign: resolvedAffixAlign, prefixAlign: prefixAlign ?? resolvedAffixAlign, suffixAlign: suffixAlign ?? resolvedAffixAlign, letterSpacing: letterSpacing ?? 0, prefixSpacing: prefixSpacing ?? Infinity, suffixSpacing: suffixSpacing ?? Infinity, prefixOffset: prefixOffset ?? 0, suffixOffset: suffixOffset ?? 0, tabularNums: tabularNums ?? true, signDisplay: signDisplay ?? derived?.signDisplay ?? 'auto', plusSign: plusSign ?? derived?.plusSign ?? '+', minusSign: minusSign ?? derived?.minusSign ?? '-', digitGlyphs: stableGlyphs, groupingSizes: stableGroups, digitMax: digitMax, continuous: continuous ?? false, prefixColor: processedPrefixColor, suffixColor: processedSuffixColor, fractionColor: processedFractionColor, fractionFontSize: fractionFontSize ?? Infinity, fractionAlign: fractionAlign ?? 'baseline', respectReduceMotion: respectReduceMotion ?? true, adjustsFontSizeToFit: adjustsFontSizeToFit ?? false, minimumFontScale: minimumFontScale ?? 0.5, allowFontScaling: allowFontScaling ?? false, maxFontSizeMultiplier: maxFontSizeMultiplier ?? 0, fontWeight: numericWeight, fontFamily: fontFamily ?? '', color: processedColor, textAlign: textAlign ?? 'auto', rightToLeft: rightToLeft, onSizeChange: onSizeChange }));
197
+ return (react_1.default.createElement(exports.NativeNitroNumberView, { ...viewProps, style: [autoSize, style], hybridRef: hybridRef, value: shownValue, fractionDigits: fractionDigits ?? figure?.fractionDigits ?? 0, minimumIntegerDigits: minimumIntegerDigits ?? derived?.minimumIntegerDigits ?? 1, groupingSeparator: groupingSeparator ?? derived?.groupingSeparator ?? '', decimalSeparator: decimalSeparator ?? derived?.decimalSeparator ?? '.', prefix: prefix ?? compact?.prefix ?? derived?.prefix ?? '', suffix: suffix ?? compact?.suffix ?? derived?.suffix ?? '', transition: transition ?? 'roll', flashUpColor: processedFlashUp, flashDownColor: processedFlashDown, flashDuration: flashDuration ?? 600, popOnChange: popOnChange ?? 0, duration: still ? 0 : duration ?? TRANSITION_DEFAULTS[transition ?? 'roll'].duration, easing: easing ?? TRANSITION_DEFAULTS[transition ?? 'roll'].easing, bounce: bounce ?? 0.15, stagger: stagger ?? TRANSITION_DEFAULTS[transition ?? 'roll'].stagger, rollDirection: direction ?? compactDirection ?? 'auto', revealState: reveal === undefined ? 0 : reveal ? 2 : 1, revealStyle: revealStyle ?? 'count', revealDuration: still ? 0 : revealDuration ?? 2200, revealBounce: revealBounce ?? 0.12, revealGrow: revealGrow ?? 0.2, revealStagger: revealStagger ?? 200, revealMilestones: stableMilestones, revealMilestoneHold: revealMilestoneHold ?? 0, onRevealEnd: onRevealEndCallback, onRevealMilestone: onRevealMilestoneCallback, onAnimationStart: onAnimationStartCallback, onAnimationEnd: onAnimationEndCallback, loading: loading ?? false, shimmerColor: processedShimmerColor, shimmerDuration: shimmerDuration ?? 950, shimmerAngle: shimmerAngle ?? 31, shimmerWidth: shimmerWidth ?? 1, shimmerBaseColor: processedShimmerBase, shimmerDirection: shimmerDirection ?? 'auto', shimmerDelay: shimmerDelay ?? 0, fontSize: resolvedFontSize, prefixFontSize: prefixFontSize ?? resolvedFontSize, suffixFontSize: suffixFontSize ?? resolvedFontSize, affixAlign: resolvedAffixAlign, prefixAlign: prefixAlign ?? resolvedAffixAlign, suffixAlign: suffixAlign ?? resolvedAffixAlign, letterSpacing: letterSpacing ?? 0, prefixSpacing: prefixSpacing ?? Infinity, suffixSpacing: suffixSpacing ?? Infinity, prefixOffset: prefixOffset ?? 0, suffixOffset: suffixOffset ?? 0, tabularNums: tabularNums ?? true, signDisplay: signDisplay ?? derived?.signDisplay ?? 'auto', plusSign: plusSign ?? derived?.plusSign ?? '+', minusSign: minusSign ?? derived?.minusSign ?? '-', digitGlyphs: stableGlyphs, groupingSizes: stableGroups, digitMax: digitMax, continuous: continuous ?? false, prefixColor: processedPrefixColor, suffixColor: processedSuffixColor, fractionColor: processedFractionColor, fractionFontSize: fractionFontSize ?? Infinity, fractionAlign: fractionAlign ?? 'baseline', respectReduceMotion: respectReduceMotion ?? true, adjustsFontSizeToFit: adjustsFontSizeToFit ?? false, minimumFontScale: minimumFontScale ?? 0.5, allowFontScaling: allowFontScaling ?? false, maxFontSizeMultiplier: maxFontSizeMultiplier ?? 0, fontWeight: numericWeight, fontFamily: fontFamily ?? '', color: processedColor, textAlign: textAlign ?? 'auto', rightToLeft: rightToLeft, onSizeChange: onSizeChange }));
190
198
  });
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.NumberFormat = void 0;
4
4
  exports.sharedFormatterOf = sharedFormatterOf;
5
+ exports.figureOf = figureOf;
6
+ exports.layoutOf = layoutOf;
5
7
  const react_native_nitro_modules_1 = require("react-native-nitro-modules");
6
8
  // MARK: - The native side
7
9
  let factory;
@@ -354,6 +356,24 @@ const nativeOf = (value, method, unwrap = false) => slotsOf(value, method, unwra
354
356
  function sharedFormatterOf(value) {
355
357
  return typeof value === 'object' && value !== null ? slots.get(value)?.native : undefined;
356
358
  }
359
+ /**
360
+ * What `format` shows for `value`, as `NitroNumber` rolls it: the figure
361
+ * rounded and trimmed as the format prints it, and the text around it. Read
362
+ * in C++ off the formatter's own parts, from the number, bigint or decimal
363
+ * string itself.
364
+ * @internal
365
+ */
366
+ function figureOf(format, value) {
367
+ return nativeOf(format, 'figure').figure(toMathematicalValue(value));
368
+ }
369
+ /**
370
+ * The prefix, suffix, separators, sign placement, grouping and digits of
371
+ * `format`, read in C++ off its parts.
372
+ * @internal
373
+ */
374
+ function layoutOf(format) {
375
+ return nativeOf(format, 'layout').layout();
376
+ }
357
377
  // `length` is 0 as the specification says: the arguments are read from `arguments`.
358
378
  function NumberFormatConstructor() {
359
379
  const locales = arguments[0];