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.
@@ -17,6 +17,8 @@ namespace margelo::nitro::nitroinput {
17
17
  prototype.registerHybridMethod("format", &HybridNitroNumberFormatSpec::format);
18
18
  prototype.registerHybridMethod("formatToParts", &HybridNitroNumberFormatSpec::formatToParts);
19
19
  prototype.registerHybridMethod("resolvedOptions", &HybridNitroNumberFormatSpec::resolvedOptions);
20
+ prototype.registerHybridMethod("figure", &HybridNitroNumberFormatSpec::figure);
21
+ prototype.registerHybridMethod("layout", &HybridNitroNumberFormatSpec::layout);
20
22
  });
21
23
  }
22
24
 
@@ -17,12 +17,18 @@
17
17
  namespace margelo::nitro::nitroinput { struct NumberFormatPart; }
18
18
  // Forward declaration of `ResolvedNumberFormatOptions` to properly resolve imports.
19
19
  namespace margelo::nitro::nitroinput { struct ResolvedNumberFormatOptions; }
20
+ // Forward declaration of `NumberFigure` to properly resolve imports.
21
+ namespace margelo::nitro::nitroinput { struct NumberFigure; }
22
+ // Forward declaration of `NumberFormatLayout` to properly resolve imports.
23
+ namespace margelo::nitro::nitroinput { struct NumberFormatLayout; }
20
24
 
21
25
  #include <string>
22
26
  #include <variant>
23
27
  #include "NumberFormatPart.hpp"
24
28
  #include <vector>
25
29
  #include "ResolvedNumberFormatOptions.hpp"
30
+ #include "NumberFigure.hpp"
31
+ #include "NumberFormatLayout.hpp"
26
32
 
27
33
  namespace margelo::nitro::nitroinput {
28
34
 
@@ -58,6 +64,8 @@ namespace margelo::nitro::nitroinput {
58
64
  virtual std::string format(const std::variant<int64_t, double, std::string>& value) = 0;
59
65
  virtual std::vector<NumberFormatPart> formatToParts(const std::variant<int64_t, double, std::string>& value) = 0;
60
66
  virtual ResolvedNumberFormatOptions resolvedOptions() = 0;
67
+ virtual NumberFigure figure(const std::variant<int64_t, double, std::string>& value) = 0;
68
+ virtual NumberFormatLayout layout() = 0;
61
69
 
62
70
  protected:
63
71
  // Hybrid Setup
@@ -0,0 +1,95 @@
1
+ ///
2
+ /// NumberFigure.hpp
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ #pragma once
9
+
10
+ #if __has_include(<NitroModules/JSIConverter.hpp>)
11
+ #include <NitroModules/JSIConverter.hpp>
12
+ #else
13
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
14
+ #endif
15
+ #if __has_include(<NitroModules/NitroDefines.hpp>)
16
+ #include <NitroModules/NitroDefines.hpp>
17
+ #else
18
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
19
+ #endif
20
+ #if __has_include(<NitroModules/JSIHelpers.hpp>)
21
+ #include <NitroModules/JSIHelpers.hpp>
22
+ #else
23
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
24
+ #endif
25
+ #if __has_include(<NitroModules/PropNameIDCache.hpp>)
26
+ #include <NitroModules/PropNameIDCache.hpp>
27
+ #else
28
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
29
+ #endif
30
+
31
+
32
+
33
+ #include <string>
34
+
35
+ namespace margelo::nitro::nitroinput {
36
+
37
+ /**
38
+ * A struct which can be represented as a JavaScript object (NumberFigure).
39
+ */
40
+ struct NumberFigure final {
41
+ public:
42
+ double value SWIFT_PRIVATE;
43
+ double fractionDigits SWIFT_PRIVATE;
44
+ std::string prefix SWIFT_PRIVATE;
45
+ std::string suffix SWIFT_PRIVATE;
46
+
47
+ public:
48
+ NumberFigure() = default;
49
+ explicit NumberFigure(double value, double fractionDigits, std::string prefix, std::string suffix): value(value), fractionDigits(fractionDigits), prefix(prefix), suffix(suffix) {}
50
+
51
+ public:
52
+ friend bool operator==(const NumberFigure& lhs, const NumberFigure& rhs) = default;
53
+ };
54
+
55
+ } // namespace margelo::nitro::nitroinput
56
+
57
+ namespace margelo::nitro {
58
+
59
+ // C++ NumberFigure <> JS NumberFigure (object)
60
+ template <>
61
+ struct JSIConverter<margelo::nitro::nitroinput::NumberFigure> final {
62
+ static inline margelo::nitro::nitroinput::NumberFigure fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
63
+ jsi::Object obj = arg.asObject(runtime);
64
+ return margelo::nitro::nitroinput::NumberFigure(
65
+ JSIConverter<double>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "value"))),
66
+ JSIConverter<double>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "fractionDigits"))),
67
+ JSIConverter<std::string>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "prefix"))),
68
+ JSIConverter<std::string>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "suffix")))
69
+ );
70
+ }
71
+ static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::nitroinput::NumberFigure& arg) {
72
+ jsi::Object obj(runtime);
73
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "value"), JSIConverter<double>::toJSI(runtime, arg.value));
74
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "fractionDigits"), JSIConverter<double>::toJSI(runtime, arg.fractionDigits));
75
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "prefix"), JSIConverter<std::string>::toJSI(runtime, arg.prefix));
76
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "suffix"), JSIConverter<std::string>::toJSI(runtime, arg.suffix));
77
+ return obj;
78
+ }
79
+ static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) {
80
+ if (!value.isObject()) {
81
+ return false;
82
+ }
83
+ jsi::Object obj = value.getObject(runtime);
84
+ if (!nitro::isPlainObject(runtime, obj)) {
85
+ return false;
86
+ }
87
+ if (!JSIConverter<double>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "value")))) return false;
88
+ if (!JSIConverter<double>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "fractionDigits")))) return false;
89
+ if (!JSIConverter<std::string>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "prefix")))) return false;
90
+ if (!JSIConverter<std::string>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "suffix")))) return false;
91
+ return true;
92
+ }
93
+ };
94
+
95
+ } // namespace margelo::nitro
@@ -0,0 +1,112 @@
1
+ ///
2
+ /// NumberFormatLayout.hpp
3
+ /// This file was generated by nitrogen. DO NOT MODIFY THIS FILE.
4
+ /// https://github.com/mrousavy/nitro
5
+ /// Copyright © Marc Rousavy @ Margelo
6
+ ///
7
+
8
+ #pragma once
9
+
10
+ #if __has_include(<NitroModules/JSIConverter.hpp>)
11
+ #include <NitroModules/JSIConverter.hpp>
12
+ #else
13
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
14
+ #endif
15
+ #if __has_include(<NitroModules/NitroDefines.hpp>)
16
+ #include <NitroModules/NitroDefines.hpp>
17
+ #else
18
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
19
+ #endif
20
+ #if __has_include(<NitroModules/JSIHelpers.hpp>)
21
+ #include <NitroModules/JSIHelpers.hpp>
22
+ #else
23
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
24
+ #endif
25
+ #if __has_include(<NitroModules/PropNameIDCache.hpp>)
26
+ #include <NitroModules/PropNameIDCache.hpp>
27
+ #else
28
+ #error NitroModules cannot be found! Are you sure you installed NitroModules properly?
29
+ #endif
30
+
31
+
32
+
33
+ #include <string>
34
+ #include <vector>
35
+
36
+ namespace margelo::nitro::nitroinput {
37
+
38
+ /**
39
+ * A struct which can be represented as a JavaScript object (NumberFormatLayout).
40
+ */
41
+ struct NumberFormatLayout final {
42
+ public:
43
+ std::string prefix SWIFT_PRIVATE;
44
+ std::string suffix SWIFT_PRIVATE;
45
+ std::string groupingSeparator SWIFT_PRIVATE;
46
+ std::string decimalSeparator SWIFT_PRIVATE;
47
+ bool signAfterAffix SWIFT_PRIVATE;
48
+ std::string minusSign SWIFT_PRIVATE;
49
+ std::vector<double> groupingSizes SWIFT_PRIVATE;
50
+ std::vector<std::string> digitGlyphs SWIFT_PRIVATE;
51
+
52
+ public:
53
+ NumberFormatLayout() = default;
54
+ explicit NumberFormatLayout(std::string prefix, std::string suffix, std::string groupingSeparator, std::string decimalSeparator, bool signAfterAffix, std::string minusSign, std::vector<double> groupingSizes, std::vector<std::string> digitGlyphs): prefix(prefix), suffix(suffix), groupingSeparator(groupingSeparator), decimalSeparator(decimalSeparator), signAfterAffix(signAfterAffix), minusSign(minusSign), groupingSizes(groupingSizes), digitGlyphs(digitGlyphs) {}
55
+
56
+ public:
57
+ friend bool operator==(const NumberFormatLayout& lhs, const NumberFormatLayout& rhs) = default;
58
+ };
59
+
60
+ } // namespace margelo::nitro::nitroinput
61
+
62
+ namespace margelo::nitro {
63
+
64
+ // C++ NumberFormatLayout <> JS NumberFormatLayout (object)
65
+ template <>
66
+ struct JSIConverter<margelo::nitro::nitroinput::NumberFormatLayout> final {
67
+ static inline margelo::nitro::nitroinput::NumberFormatLayout fromJSI(jsi::Runtime& runtime, const jsi::Value& arg) {
68
+ jsi::Object obj = arg.asObject(runtime);
69
+ return margelo::nitro::nitroinput::NumberFormatLayout(
70
+ JSIConverter<std::string>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "prefix"))),
71
+ JSIConverter<std::string>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "suffix"))),
72
+ JSIConverter<std::string>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "groupingSeparator"))),
73
+ JSIConverter<std::string>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "decimalSeparator"))),
74
+ JSIConverter<bool>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "signAfterAffix"))),
75
+ JSIConverter<std::string>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "minusSign"))),
76
+ JSIConverter<std::vector<double>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "groupingSizes"))),
77
+ JSIConverter<std::vector<std::string>>::fromJSI(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "digitGlyphs")))
78
+ );
79
+ }
80
+ static inline jsi::Value toJSI(jsi::Runtime& runtime, const margelo::nitro::nitroinput::NumberFormatLayout& arg) {
81
+ jsi::Object obj(runtime);
82
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "prefix"), JSIConverter<std::string>::toJSI(runtime, arg.prefix));
83
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "suffix"), JSIConverter<std::string>::toJSI(runtime, arg.suffix));
84
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "groupingSeparator"), JSIConverter<std::string>::toJSI(runtime, arg.groupingSeparator));
85
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "decimalSeparator"), JSIConverter<std::string>::toJSI(runtime, arg.decimalSeparator));
86
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "signAfterAffix"), JSIConverter<bool>::toJSI(runtime, arg.signAfterAffix));
87
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "minusSign"), JSIConverter<std::string>::toJSI(runtime, arg.minusSign));
88
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "groupingSizes"), JSIConverter<std::vector<double>>::toJSI(runtime, arg.groupingSizes));
89
+ obj.setProperty(runtime, PropNameIDCache::get(runtime, "digitGlyphs"), JSIConverter<std::vector<std::string>>::toJSI(runtime, arg.digitGlyphs));
90
+ return obj;
91
+ }
92
+ static inline bool canConvert(jsi::Runtime& runtime, const jsi::Value& value) {
93
+ if (!value.isObject()) {
94
+ return false;
95
+ }
96
+ jsi::Object obj = value.getObject(runtime);
97
+ if (!nitro::isPlainObject(runtime, obj)) {
98
+ return false;
99
+ }
100
+ if (!JSIConverter<std::string>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "prefix")))) return false;
101
+ if (!JSIConverter<std::string>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "suffix")))) return false;
102
+ if (!JSIConverter<std::string>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "groupingSeparator")))) return false;
103
+ if (!JSIConverter<std::string>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "decimalSeparator")))) return false;
104
+ if (!JSIConverter<bool>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "signAfterAffix")))) return false;
105
+ if (!JSIConverter<std::string>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "minusSign")))) return false;
106
+ if (!JSIConverter<std::vector<double>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "groupingSizes")))) return false;
107
+ if (!JSIConverter<std::vector<std::string>>::canConvert(runtime, obj.getProperty(runtime, PropNameIDCache::get(runtime, "digitGlyphs")))) return false;
108
+ return true;
109
+ }
110
+ };
111
+
112
+ } // namespace margelo::nitro
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-nitro-input",
3
- "version": "0.3.7",
3
+ "version": "0.3.8",
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",
@@ -39,7 +39,7 @@
39
39
  "specs": "nitrogen --logLevel=\"debug\"",
40
40
  "prepack": "bun run build",
41
41
  "test": "jest",
42
- "test:cpp": "mkdir -p .cache && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/ReflowEngine.cpp cpp/AmountFormatter.cpp cpp/__tests__/ReflowEngineTest.cpp -o .cache/reflow-engine-test && .cache/reflow-engine-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/AmountFormatter.cpp cpp/__tests__/AmountFormatterTest.cpp -o .cache/amount-formatter-test && .cache/amount-formatter-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/AmountFormatter.cpp cpp/MaskEngine.cpp cpp/__tests__/MaskEngineTest.cpp -o .cache/mask-engine-test && .cache/mask-engine-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/AmountFormatter.cpp cpp/MaskEngine.cpp cpp/__tests__/MaskEngineCorpusTest.cpp -o .cache/mask-engine-corpus-test && .cache/mask-engine-corpus-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/OutlineGeometry.cpp cpp/__tests__/OutlineGeometryTest.cpp -o .cache/outline-geometry-test && .cache/outline-geometry-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/RollingEngine.cpp cpp/__tests__/RollingEngineTest.cpp -o .cache/rolling-engine-test && .cache/rolling-engine-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/numberformat/NumberFormatCore.cpp cpp/__tests__/NumberFormatCoreTest.cpp -o .cache/number-format-core-test && .cache/number-format-core-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/numberformat/NumberFormatCore.cpp cpp/numberformat/NumberFormatProbe.cpp cpp/__tests__/NumberFormatProbeTest.cpp -o .cache/number-format-probe-test && .cache/number-format-probe-test",
42
+ "test:cpp": "mkdir -p .cache && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/ReflowEngine.cpp cpp/AmountFormatter.cpp cpp/__tests__/ReflowEngineTest.cpp -o .cache/reflow-engine-test && .cache/reflow-engine-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/AmountFormatter.cpp cpp/__tests__/AmountFormatterTest.cpp -o .cache/amount-formatter-test && .cache/amount-formatter-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/AmountFormatter.cpp cpp/MaskEngine.cpp cpp/__tests__/MaskEngineTest.cpp -o .cache/mask-engine-test && .cache/mask-engine-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/AmountFormatter.cpp cpp/MaskEngine.cpp cpp/__tests__/MaskEngineCorpusTest.cpp -o .cache/mask-engine-corpus-test && .cache/mask-engine-corpus-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/OutlineGeometry.cpp cpp/__tests__/OutlineGeometryTest.cpp -o .cache/outline-geometry-test && .cache/outline-geometry-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/RollingEngine.cpp cpp/__tests__/RollingEngineTest.cpp -o .cache/rolling-engine-test && .cache/rolling-engine-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/numberformat/NumberFormatCore.cpp cpp/numberformat/FormatFigure.cpp cpp/__tests__/NumberFormatCoreTest.cpp -o .cache/number-format-core-test && .cache/number-format-core-test && clang++ -std=c++20 -O1 -Wall -Wextra -Icpp cpp/numberformat/NumberFormatCore.cpp cpp/numberformat/NumberFormatProbe.cpp cpp/__tests__/NumberFormatProbeTest.cpp -o .cache/number-format-probe-test && .cache/number-format-probe-test",
43
43
  "test:cpp:sanitize": "mkdir -p .cache && clang++ -std=c++20 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer -Icpp cpp/RollingEngine.cpp cpp/__tests__/RollingEngineTest.cpp -o .cache/rolling-engine-sanitize && .cache/rolling-engine-sanitize",
44
44
  "release": "release-it"
45
45
  },
@@ -31,7 +31,7 @@ import type {
31
31
  NitroNumberTextAlign,
32
32
  } from './specs/NitroNumber.nitro'
33
33
  import { toNumericWeight, toProcessedColor } from './styleHelpers'
34
- import { compactParts, formatProps } from './formatProps'
34
+ import { figureOf, formatProps, toNumber, withMinorDigits } from './formatProps'
35
35
  import type { NumberFormat } from './NumberFormat'
36
36
 
37
37
  /**
@@ -53,11 +53,28 @@ export interface NitroNumberProps extends Omit<ViewProps, 'children'> {
53
53
  /**
54
54
  * The number to display. Every change rolls each digit natively to its new
55
55
  * glyph, in the direction of the change. The first value is shown instantly.
56
- * At most 18 digits are shown: `|value| × 10^fractionDigits` is clamped at
57
- * 10^17, and a JS number carries exact integers only up to 2^53.
56
+ *
57
+ * A `bigint` or a decimal string (`"1234.56"`) is taken as is, with no
58
+ * conversion on your side: money kept as minor units passes straight in
59
+ * with `minorDigits`. With a `format`, it is rounded by the format, in
60
+ * decimal, so it never goes through a double first. The digits themselves
61
+ * animate as a double: exact while `|value| × 10^fractionDigits` stays
62
+ * within 2^53, and at most 18 digits are shown.
63
+ */
64
+ value: number | bigint | string
65
+ /**
66
+ * The decimal places `value` is counted in: `value={123456n}` with
67
+ * `minorDigits={2}` is 1234.56, cents to dollars without dividing. Applied
68
+ * to a bigint or a decimal string exactly. Default: `0`.
69
+ */
70
+ minorDigits?: number
71
+ /**
72
+ * Digits shown after the decimal separator. Default: `0`, or with a
73
+ * `format`, what the format shows for each value: its
74
+ * `trailingZeroDisplay`, a minimum below its maximum and significant
75
+ * digits all decide it per value, and the decimal columns roll in and out as
76
+ * the count changes. Set, it holds every value to this many.
58
77
  */
59
- value: number
60
- /** Digits shown after the decimal separator. Default: `0`. */
61
78
  fractionDigits?: number
62
79
  /** Zero-pads the integer part to at least this many digits. Default: `1`. */
63
80
  minimumIntegerDigits?: number
@@ -231,9 +248,10 @@ export interface NitroNumberProps extends Omit<ViewProps, 'children'> {
231
248
  tabularNums?: boolean
232
249
  /**
233
250
  * A `NumberFormat` the number follows: its prefix and suffix (the currency
234
- * where the locale puts it), grouping and decimal separators, fraction
235
- * digits and minimum integer digits. The individual props override what it
236
- * says.
251
+ * where the locale puts it), grouping and decimal separators, minimum
252
+ * integer digits, and per value the digits it prints: rounded with its
253
+ * `roundingMode`, trimmed by its `trailingZeroDisplay`. The figure is what
254
+ * `format.format(value)` shows. The individual props override what it says.
237
255
  */
238
256
  format?: NumberFormat
239
257
  /**
@@ -379,6 +397,7 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
379
397
  function NitroNumber(
380
398
  {
381
399
  value,
400
+ minorDigits,
382
401
  fractionDigits,
383
402
  minimumIntegerDigits,
384
403
  groupingSeparator,
@@ -463,8 +482,10 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
463
482
  latestOnRevealEnd.current = onRevealEnd
464
483
  const latestOnRevealMilestone = useRef(onRevealMilestone)
465
484
  latestOnRevealMilestone.current = onRevealMilestone
466
- const latestValue = useRef(value)
467
- latestValue.current = value
485
+ // The value as the format takes it: minor units shifted in, exactly.
486
+ const input = withMinorDigits(value, minorDigits)
487
+ const latestValue = useRef(input)
488
+ latestValue.current = input
468
489
  const latestOnAnimationStart = useRef(onAnimationStart)
469
490
  latestOnAnimationStart.current = onAnimationStart
470
491
  const latestOnAnimationEnd = useRef(onAnimationEnd)
@@ -523,7 +544,7 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
523
544
  const onAnimationEndCallback = useMemo(
524
545
  () =>
525
546
  callback((shown: number) => {
526
- latestOnAnimationEnd.current?.(compactRef.current ? latestValue.current : shown)
547
+ latestOnAnimationEnd.current?.(compactRef.current ? toNumber(latestValue.current) : shown)
527
548
  }),
528
549
  []
529
550
  )
@@ -545,7 +566,8 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
545
566
  jumpTo: (next) => nativeRef.current?.jumpTo(next),
546
567
  animateTo: (next) => nativeRef.current?.animateTo(next),
547
568
  revealTo: (next) => nativeRef.current?.revealTo(next),
548
- getValue: () => (compactRef.current ? latestValue.current : nativeRef.current?.value ?? latestValue.current),
569
+ getValue: () =>
570
+ compactRef.current ? toNumber(latestValue.current) : nativeRef.current?.value ?? toNumber(latestValue.current),
549
571
  get native() {
550
572
  return nativeRef.current
551
573
  },
@@ -572,14 +594,21 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
572
594
  const resolvedFontSize = fontSize ?? 32
573
595
  const resolvedAffixAlign = affixAlign ?? 'baseline'
574
596
  const derived = format ? formatProps(format) : undefined
575
- // Compact notation: "1.2K" rolls the figure 1.2 and swaps the suffix.
576
- const compact = format && derived?.compact ? compactParts(format, value) : undefined
597
+ // What the format shows for this value: the figure rounded its way, in the
598
+ // fraction digits it prints. Compact notation also swaps the suffix: "1.2K"
599
+ // rolls the figure 1.2.
600
+ const figure = useMemo(() => (format ? figureOf(format, input) : undefined), [format, input])
601
+ const compact = derived?.compact ? figure : undefined
577
602
  const compactRef = useRef(false)
578
603
  compactRef.current = compact !== undefined
579
604
  // Which way the value moved, for a compact figure that fell while the value grew (999 → 1K).
580
- const previousValue = useRef(value)
581
- const compactDirection = compact && direction === undefined ? (value >= previousValue.current ? 'up' : 'down') : undefined
582
- previousValue.current = value
605
+ const numericValue = toNumber(input)
606
+ const previousValue = useRef(numericValue)
607
+ const compactDirection =
608
+ compact && direction === undefined ? (numericValue >= previousValue.current ? 'up' : 'down') : undefined
609
+ previousValue.current = numericValue
610
+ // Without a format the engine rounds the double, as it always has.
611
+ const shownValue = figure ? figure.value : numericValue
583
612
  const processedPrefixColor = useMemo(() => toProcessedColor(prefixColor) ?? Infinity, [prefixColor])
584
613
  const processedSuffixColor = useMemo(() => toProcessedColor(suffixColor) ?? Infinity, [suffixColor])
585
614
  const processedFractionColor = useMemo(() => toProcessedColor(fractionColor) ?? Infinity, [fractionColor])
@@ -627,8 +656,8 @@ export const NitroNumber = forwardRef<NitroNumberHandle, NitroNumberProps>(
627
656
  {...viewProps}
628
657
  style={[autoSize, style]}
629
658
  hybridRef={hybridRef}
630
- value={compact ? compact.value : value}
631
- fractionDigits={fractionDigits ?? compact?.fractionDigits ?? derived?.fractionDigits ?? 0}
659
+ value={shownValue}
660
+ fractionDigits={fractionDigits ?? figure?.fractionDigits ?? 0}
632
661
  minimumIntegerDigits={minimumIntegerDigits ?? derived?.minimumIntegerDigits ?? 1}
633
662
  groupingSeparator={groupingSeparator ?? derived?.groupingSeparator ?? ''}
634
663
  decimalSeparator={decimalSeparator ?? derived?.decimalSeparator ?? '.'}
@@ -2,6 +2,8 @@ import { NitroModules } from 'react-native-nitro-modules'
2
2
  import type {
3
3
  NitroNumberFormat,
4
4
  NitroNumberFormatFactory,
5
+ NumberFigure,
6
+ NumberFormatLayout,
5
7
  NumberFormatOptions,
6
8
  NumberFormatPart,
7
9
  ResolvedNumberFormatOptions,
@@ -390,6 +392,26 @@ export function sharedFormatterOf(value: unknown): object | undefined {
390
392
  return typeof value === 'object' && value !== null ? slots.get(value)?.native : undefined
391
393
  }
392
394
 
395
+ /**
396
+ * What `format` shows for `value`, as `NitroNumber` rolls it: the figure
397
+ * rounded and trimmed as the format prints it, and the text around it. Read
398
+ * in C++ off the formatter's own parts, from the number, bigint or decimal
399
+ * string itself.
400
+ * @internal
401
+ */
402
+ export function figureOf(format: NumberFormat, value: number | bigint | string): NumberFigure {
403
+ return nativeOf(format, 'figure').figure(toMathematicalValue(value))
404
+ }
405
+
406
+ /**
407
+ * The prefix, suffix, separators, sign placement, grouping and digits of
408
+ * `format`, read in C++ off its parts.
409
+ * @internal
410
+ */
411
+ export function layoutOf(format: NumberFormat): NumberFormatLayout {
412
+ return nativeOf(format, 'layout').layout()
413
+ }
414
+
393
415
  // `length` is 0 as the specification says: the arguments are read from `arguments`.
394
416
  function NumberFormatConstructor(this: unknown): unknown {
395
417
  const locales = arguments[0]
@@ -1,4 +1,6 @@
1
- import { NumberFormat, sharedFormatterOf } from './NumberFormat'
1
+ import { layoutOf, sharedFormatterOf, type NumberFormat } from './NumberFormat'
2
+
3
+ export { figureOf } from './NumberFormat'
2
4
 
3
5
  /** What `NitroNumber` and `NitroInput` take from a `NumberFormat` through their `format` prop. */
4
6
  export interface FormatProps {
@@ -6,7 +8,11 @@ export interface FormatProps {
6
8
  suffix: string
7
9
  groupingSeparator: string
8
10
  decimalSeparator: string
9
- /** The digits after the decimal separator: the format's maximum. */
11
+ /**
12
+ * The digits after the decimal separator: the format's maximum. What one
13
+ * value shows can be fewer (`trailingZeroDisplay`, a minimum below the
14
+ * maximum): `figureOf` says per value.
15
+ */
10
16
  fractionDigits: number
11
17
  minimumIntegerDigits: number
12
18
  /** Whether a negative amount's sign comes before the prefix ("-$5") or after it ("$-5"). */
@@ -21,47 +27,17 @@ export interface FormatProps {
21
27
  digitGlyphs: string[]
22
28
  /** The first digit group and every later one, from the decimal point ([3, 2]: 12,34,567). */
23
29
  groupingSizes: number[]
24
- /** Compact notation: the prefix, suffix and digits follow the value (`compactParts`). */
30
+ /** Compact notation: the prefix, suffix and digits follow the value (`figureOf`). */
25
31
  compact: boolean
26
32
  }
27
33
 
28
- const NUMBER_PARTS = new Set(['integer', 'group', 'decimal', 'fraction'])
29
34
  // By the native formatter, which instances built with the same locales and options share.
30
35
  const cache = new WeakMap<object, FormatProps>()
31
36
 
32
- type Part = { type: string; value: string }
33
-
34
- function join(parts: Part[], from: number, to: number): string {
35
- return parts
36
- .slice(from, to)
37
- .map((p) => p.value)
38
- .join('')
39
- }
40
-
41
- /** The text before and after the number in `parts`. */
42
- function affixes(parts: Part[]): { prefix: string; suffix: string } {
43
- const first = parts.findIndex((p) => NUMBER_PARTS.has(p.type))
44
- let last = first
45
- parts.forEach((p, i) => {
46
- if (NUMBER_PARTS.has(p.type)) last = i
47
- })
48
- // The sign is the component's own glyph, not part of an affix.
49
- const unsigned = (from: number, to: number) =>
50
- join(
51
- parts.map((p) => (p.type === 'minusSign' || p.type === 'plusSign' ? { ...p, value: '' } : p)),
52
- from,
53
- to
54
- )
55
- return {
56
- prefix: first < 0 ? '' : unsigned(0, first),
57
- suffix: first < 0 ? '' : unsigned(last + 1, parts.length),
58
- }
59
- }
60
-
61
37
  /**
62
- * The prefix, suffix, separators and digit counts of `format`, read off its
63
- * parts once and cached per formatter. The components keep their own model
64
- * (a sign, a prefix, digits in groups, a suffix), so a format outside it
38
+ * The prefix, suffix, separators and digit counts of `format`, read in C++
39
+ * off its parts once and cached per formatter. The components keep their own
40
+ * model (a sign, a prefix, digits in groups, a suffix), so a format outside it
65
41
  * (accounting parentheses, a unit between the digits) is followed as far as
66
42
  * that model goes.
67
43
  */
@@ -70,80 +46,64 @@ export function formatProps(format: NumberFormat): FormatProps {
70
46
  const cached = cache.get(key)
71
47
  if (cached) return cached
72
48
  const resolved = format.resolvedOptions()
73
- const compact = resolved.notation === 'compact'
74
- const fractionDigits = resolved.maximumFractionDigits ?? 0
75
- // A value with every part: groups, and a fraction when the format has one.
76
- // Compact notation would print it "1.2M", so its affixes come per value.
77
- const parts = format.formatToParts(compact ? 1 : fractionDigits > 0 ? 1234567.5 : 1234567) as Part[]
78
- const negative = format.formatToParts(-1) as Part[]
79
- const minus = negative.findIndex((p) => p.type === 'minusSign')
80
- const currency = negative.findIndex((p) => p.type === 'currency' || p.type === 'percentSign')
81
- const integers = parts.filter((p) => p.type === 'integer').map((p) => p.value.length)
49
+ const layout = layoutOf(format)
82
50
  const props: FormatProps = {
83
- ...affixes(parts),
84
- groupingSeparator: parts.find((p) => p.type === 'group')?.value ?? '',
85
- decimalSeparator: parts.find((p) => p.type === 'decimal')?.value ?? '.',
86
- fractionDigits,
51
+ prefix: layout.prefix,
52
+ suffix: layout.suffix,
53
+ groupingSeparator: layout.groupingSeparator,
54
+ decimalSeparator: layout.decimalSeparator,
55
+ fractionDigits: resolved.maximumFractionDigits ?? 0,
87
56
  minimumIntegerDigits: resolved.minimumIntegerDigits,
88
- signPlacement: minus >= 0 && currency >= 0 && minus > currency ? 'afterAffix' : 'beforeAffix',
57
+ signPlacement: layout.signAfterAffix ? 'afterAffix' : 'beforeAffix',
89
58
  signDisplay: (resolved.signDisplay ?? 'auto') as FormatProps['signDisplay'],
90
- minusSign: negative[minus]?.value ?? '-',
59
+ minusSign: layout.minusSign,
91
60
  plusSign: '+',
92
- digitGlyphs: digitGlyphsOf(resolved.locale, resolved.numberingSystem),
93
- // "12,34,567": the last group is the first size, the one before it every later one.
94
- groupingSizes: integers.length >= 3 ? [integers[integers.length - 1]!, integers[integers.length - 2]!] : [3],
95
- compact,
61
+ digitGlyphs: layout.digitGlyphs,
62
+ groupingSizes: layout.groupingSizes,
63
+ compact: resolved.notation === 'compact',
96
64
  }
97
65
  cache.set(key, props)
98
66
  return props
99
67
  }
100
68
 
101
- const digitGlyphCache = new Map<string, string[]>()
102
-
103
- /** The ten digits of a numbering system, or [] for Latin ones. */
104
- function digitGlyphsOf(locale: string, numberingSystem: string | undefined): string[] {
105
- if (!numberingSystem || numberingSystem === 'latn') return []
106
- const cached = digitGlyphCache.get(numberingSystem)
107
- if (cached) return cached
108
- const digits = new NumberFormat(locale, { numberingSystem, useGrouping: false })
109
- const glyphs = Array.from({ length: 10 }, (_, d) => digits.format(d))
110
- const result = glyphs.every((g, d) => g === String(d)) ? [] : glyphs
111
- digitGlyphCache.set(numberingSystem, result)
112
- return result
113
- }
114
-
115
- /** What a compact format shows for one value: the figure to roll and the text around it. */
116
- export interface CompactParts {
117
- /** The figure as the digits show it: 1.2 for "1.2K". */
118
- value: number
119
- fractionDigits: number
120
- prefix: string
121
- suffix: string
122
- }
69
+ /** A value as `NumberFormat` takes it: a number, a bigint or a decimal string. */
70
+ export type NumericInput = number | bigint | string
123
71
 
124
72
  /**
125
- * Compact notation's parts for `value`: "1.2K" is the figure 1.2 with the
126
- * suffix "K", so the digits roll and the suffix swaps as the value crosses
127
- * a thousand, a million…
73
+ * `value` read in units of 10^-`minorDigits`, exactly: 123456n with 2 minor
74
+ * digits is "1234.56". A bigint or a numeric string is shifted as text, so no
75
+ * digit goes through a double: a decimal ("1234.5"), one with an exponent
76
+ * ("1e5" becomes "1e3"), or a 0x / 0o / 0b integer, as `Intl.NumberFormat`
77
+ * reads strings. A number that is a safe integer is shifted the same way, any
78
+ * other number is divided. A string that is not a number ("1,234.56") comes
79
+ * back as it is, which the format shows as NaN, never as a wrong amount.
128
80
  */
129
- export function compactParts(format: NumberFormat, value: number): CompactParts {
130
- const parts = format.formatToParts(value) as Part[]
131
- const props = formatProps(format)
132
- const latin = (text: string) =>
133
- props.digitGlyphs.length === 10
134
- ? Array.from(text)
135
- .map((c) => {
136
- const d = props.digitGlyphs.indexOf(c)
137
- return d >= 0 ? String(d) : c
138
- })
139
- .join('')
140
- : text
141
- const integer = latin(parts.filter((p) => p.type === 'integer').map((p) => p.value).join(''))
142
- const fraction = latin(parts.filter((p) => p.type === 'fraction').map((p) => p.value).join(''))
143
- const magnitude = Number(fraction ? `${integer}.${fraction}` : integer)
144
- return {
145
- value: (value < 0 ? -1 : 1) * (Number.isFinite(magnitude) ? magnitude : 0),
146
- fractionDigits: fraction.length,
147
- ...affixes(parts),
81
+ export function withMinorDigits(value: NumericInput, minorDigits: number | undefined): NumericInput {
82
+ const digits = minorDigits === undefined ? 0 : Math.max(0, Math.trunc(minorDigits))
83
+ if (digits === 0) return value
84
+ if (typeof value === 'number') {
85
+ if (!Number.isSafeInteger(value)) return value / 10 ** digits
86
+ value = BigInt(value)
148
87
  }
88
+ let text = typeof value === 'bigint' ? value.toString() : value.trim()
89
+ if (/^0[xob][0-9a-f]+$/i.test(text)) {
90
+ // A non-decimal integer: BigInt reads it as Intl does, exactly.
91
+ text = BigInt(text).toString()
92
+ }
93
+ const match = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text)
94
+ if (!match || (match[2] === '' && match[3] === undefined && text !== '')) return value
95
+ const [, sign = '', whole = '', fraction = '', exponent] = match
96
+ if (whole === '' && fraction === '' && text.includes('.')) return value
97
+ if (exponent !== undefined) {
98
+ // Moving the point is moving the exponent.
99
+ return `${sign}${whole}${fraction ? `.${fraction}` : ''}e${Number(exponent) - digits}`
100
+ }
101
+ const all = (whole + fraction).padStart(digits + fraction.length + 1, '0')
102
+ const point = all.length - fraction.length - digits
103
+ return `${sign}${all.slice(0, point)}.${all.slice(point)}`
104
+ }
105
+
106
+ /** `value` as a double, for comparisons and for the engine when there is no format. */
107
+ export function toNumber(value: NumericInput): number {
108
+ return typeof value === 'number' ? value : Number(value)
149
109
  }