react-native-nitro-input 0.3.6 → 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.
@@ -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];
@@ -1,36 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.figureOf = void 0;
3
4
  exports.formatProps = formatProps;
4
- exports.compactParts = compactParts;
5
+ exports.withMinorDigits = withMinorDigits;
6
+ exports.toNumber = toNumber;
5
7
  const NumberFormat_1 = require("./NumberFormat");
6
- const NUMBER_PARTS = new Set(['integer', 'group', 'decimal', 'fraction']);
8
+ var NumberFormat_2 = require("./NumberFormat");
9
+ Object.defineProperty(exports, "figureOf", { enumerable: true, get: function () { return NumberFormat_2.figureOf; } });
7
10
  // By the native formatter, which instances built with the same locales and options share.
8
11
  const cache = new WeakMap();
9
- function join(parts, from, to) {
10
- return parts
11
- .slice(from, to)
12
- .map((p) => p.value)
13
- .join('');
14
- }
15
- /** The text before and after the number in `parts`. */
16
- function affixes(parts) {
17
- const first = parts.findIndex((p) => NUMBER_PARTS.has(p.type));
18
- let last = first;
19
- parts.forEach((p, i) => {
20
- if (NUMBER_PARTS.has(p.type))
21
- last = i;
22
- });
23
- // The sign is the component's own glyph, not part of an affix.
24
- const unsigned = (from, to) => join(parts.map((p) => (p.type === 'minusSign' || p.type === 'plusSign' ? { ...p, value: '' } : p)), from, to);
25
- return {
26
- prefix: first < 0 ? '' : unsigned(0, first),
27
- suffix: first < 0 ? '' : unsigned(last + 1, parts.length),
28
- };
29
- }
30
12
  /**
31
- * The prefix, suffix, separators and digit counts of `format`, read off its
32
- * parts once and cached per formatter. The components keep their own model
33
- * (a sign, a prefix, digits in groups, a suffix), so a format outside it
13
+ * The prefix, suffix, separators and digit counts of `format`, read in C++
14
+ * off its parts once and cached per formatter. The components keep their own
15
+ * model (a sign, a prefix, digits in groups, a suffix), so a format outside it
34
16
  * (accounting parentheses, a unit between the digits) is followed as far as
35
17
  * that model goes.
36
18
  */
@@ -40,69 +22,63 @@ function formatProps(format) {
40
22
  if (cached)
41
23
  return cached;
42
24
  const resolved = format.resolvedOptions();
43
- const compact = resolved.notation === 'compact';
44
- const fractionDigits = resolved.maximumFractionDigits ?? 0;
45
- // A value with every part: groups, and a fraction when the format has one.
46
- // Compact notation would print it "1.2M", so its affixes come per value.
47
- const parts = format.formatToParts(compact ? 1 : fractionDigits > 0 ? 1234567.5 : 1234567);
48
- const negative = format.formatToParts(-1);
49
- const minus = negative.findIndex((p) => p.type === 'minusSign');
50
- const currency = negative.findIndex((p) => p.type === 'currency' || p.type === 'percentSign');
51
- const integers = parts.filter((p) => p.type === 'integer').map((p) => p.value.length);
25
+ const layout = (0, NumberFormat_1.layoutOf)(format);
52
26
  const props = {
53
- ...affixes(parts),
54
- groupingSeparator: parts.find((p) => p.type === 'group')?.value ?? '',
55
- decimalSeparator: parts.find((p) => p.type === 'decimal')?.value ?? '.',
56
- fractionDigits,
27
+ prefix: layout.prefix,
28
+ suffix: layout.suffix,
29
+ groupingSeparator: layout.groupingSeparator,
30
+ decimalSeparator: layout.decimalSeparator,
31
+ fractionDigits: resolved.maximumFractionDigits ?? 0,
57
32
  minimumIntegerDigits: resolved.minimumIntegerDigits,
58
- signPlacement: minus >= 0 && currency >= 0 && minus > currency ? 'afterAffix' : 'beforeAffix',
33
+ signPlacement: layout.signAfterAffix ? 'afterAffix' : 'beforeAffix',
59
34
  signDisplay: (resolved.signDisplay ?? 'auto'),
60
- minusSign: negative[minus]?.value ?? '-',
35
+ minusSign: layout.minusSign,
61
36
  plusSign: '+',
62
- digitGlyphs: digitGlyphsOf(resolved.locale, resolved.numberingSystem),
63
- // "12,34,567": the last group is the first size, the one before it every later one.
64
- groupingSizes: integers.length >= 3 ? [integers[integers.length - 1], integers[integers.length - 2]] : [3],
65
- compact,
37
+ digitGlyphs: layout.digitGlyphs,
38
+ groupingSizes: layout.groupingSizes,
39
+ compact: resolved.notation === 'compact',
66
40
  };
67
41
  cache.set(key, props);
68
42
  return props;
69
43
  }
70
- const digitGlyphCache = new Map();
71
- /** The ten digits of a numbering system, or [] for Latin ones. */
72
- function digitGlyphsOf(locale, numberingSystem) {
73
- if (!numberingSystem || numberingSystem === 'latn')
74
- return [];
75
- const cached = digitGlyphCache.get(numberingSystem);
76
- if (cached)
77
- return cached;
78
- const digits = new NumberFormat_1.NumberFormat(locale, { numberingSystem, useGrouping: false });
79
- const glyphs = Array.from({ length: 10 }, (_, d) => digits.format(d));
80
- const result = glyphs.every((g, d) => g === String(d)) ? [] : glyphs;
81
- digitGlyphCache.set(numberingSystem, result);
82
- return result;
83
- }
84
44
  /**
85
- * Compact notation's parts for `value`: "1.2K" is the figure 1.2 with the
86
- * suffix "K", so the digits roll and the suffix swaps as the value crosses
87
- * a thousand, a million…
45
+ * `value` read in units of 10^-`minorDigits`, exactly: 123456n with 2 minor
46
+ * digits is "1234.56". A bigint or a numeric string is shifted as text, so no
47
+ * digit goes through a double: a decimal ("1234.5"), one with an exponent
48
+ * ("1e5" becomes "1e3"), or a 0x / 0o / 0b integer, as `Intl.NumberFormat`
49
+ * reads strings. A number that is a safe integer is shifted the same way, any
50
+ * other number is divided. A string that is not a number ("1,234.56") comes
51
+ * back as it is, which the format shows as NaN, never as a wrong amount.
88
52
  */
89
- function compactParts(format, value) {
90
- const parts = format.formatToParts(value);
91
- const props = formatProps(format);
92
- const latin = (text) => props.digitGlyphs.length === 10
93
- ? Array.from(text)
94
- .map((c) => {
95
- const d = props.digitGlyphs.indexOf(c);
96
- return d >= 0 ? String(d) : c;
97
- })
98
- .join('')
99
- : text;
100
- const integer = latin(parts.filter((p) => p.type === 'integer').map((p) => p.value).join(''));
101
- const fraction = latin(parts.filter((p) => p.type === 'fraction').map((p) => p.value).join(''));
102
- const magnitude = Number(fraction ? `${integer}.${fraction}` : integer);
103
- return {
104
- value: (value < 0 ? -1 : 1) * (Number.isFinite(magnitude) ? magnitude : 0),
105
- fractionDigits: fraction.length,
106
- ...affixes(parts),
107
- };
53
+ function withMinorDigits(value, minorDigits) {
54
+ const digits = minorDigits === undefined ? 0 : Math.max(0, Math.trunc(minorDigits));
55
+ if (digits === 0)
56
+ return value;
57
+ if (typeof value === 'number') {
58
+ if (!Number.isSafeInteger(value))
59
+ return value / 10 ** digits;
60
+ value = BigInt(value);
61
+ }
62
+ let text = typeof value === 'bigint' ? value.toString() : value.trim();
63
+ if (/^0[xob][0-9a-f]+$/i.test(text)) {
64
+ // A non-decimal integer: BigInt reads it as Intl does, exactly.
65
+ text = BigInt(text).toString();
66
+ }
67
+ const match = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text);
68
+ if (!match || (match[2] === '' && match[3] === undefined && text !== ''))
69
+ return value;
70
+ const [, sign = '', whole = '', fraction = '', exponent] = match;
71
+ if (whole === '' && fraction === '' && text.includes('.'))
72
+ return value;
73
+ if (exponent !== undefined) {
74
+ // Moving the point is moving the exponent.
75
+ return `${sign}${whole}${fraction ? `.${fraction}` : ''}e${Number(exponent) - digits}`;
76
+ }
77
+ const all = (whole + fraction).padStart(digits + fraction.length + 1, '0');
78
+ const point = all.length - fraction.length - digits;
79
+ return `${sign}${all.slice(0, point)}.${all.slice(point)}`;
80
+ }
81
+ /** `value` as a double, for comparisons and for the engine when there is no format. */
82
+ function toNumber(value) {
83
+ return typeof value === 'number' ? value : Number(value);
108
84
  }
@@ -3,7 +3,7 @@ import { I18nManager, StyleSheet, } from 'react-native';
3
3
  import { callback, getHostComponent, } from 'react-native-nitro-modules';
4
4
  import NitroNumberViewConfig from '../nitrogen/generated/shared/json/NitroNumberViewConfig.json';
5
5
  import { toNumericWeight, toProcessedColor } from './styleHelpers';
6
- import { compactParts, formatProps } from './formatProps';
6
+ import { figureOf, formatProps, toNumber, withMinorDigits } from './formatProps';
7
7
  /**
8
8
  * The raw Nitro host component. Prefer {@link NitroNumber}, which adds
9
9
  * auto-sizing, color/weight conversion and a convenient handle.
@@ -27,7 +27,7 @@ const TRANSITION_DEFAULTS = {
27
27
  * The view sizes itself to its content unless you pass an explicit `width` /
28
28
  * `height` in `style`.
29
29
  */
30
- export const NitroNumber = 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) {
30
+ 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
31
  const nativeRef = useRef(null);
32
32
  const latestOnNativeRef = useRef(onNativeRef);
33
33
  latestOnNativeRef.current = onNativeRef;
@@ -35,8 +35,10 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, fractionDigi
35
35
  latestOnRevealEnd.current = onRevealEnd;
36
36
  const latestOnRevealMilestone = useRef(onRevealMilestone);
37
37
  latestOnRevealMilestone.current = onRevealMilestone;
38
- const latestValue = useRef(value);
39
- latestValue.current = value;
38
+ // The value as the format takes it: minor units shifted in, exactly.
39
+ const input = withMinorDigits(value, minorDigits);
40
+ const latestValue = useRef(input);
41
+ latestValue.current = input;
40
42
  const latestOnAnimationStart = useRef(onAnimationStart);
41
43
  latestOnAnimationStart.current = onAnimationStart;
42
44
  const latestOnAnimationEnd = useRef(onAnimationEnd);
@@ -68,7 +70,7 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, fractionDigi
68
70
  }), []);
69
71
  // The figure a compact format rolls is not the value (1.2 for 1,234): report the value.
70
72
  const onAnimationEndCallback = useMemo(() => callback((shown) => {
71
- latestOnAnimationEnd.current?.(compactRef.current ? latestValue.current : shown);
73
+ latestOnAnimationEnd.current?.(compactRef.current ? toNumber(latestValue.current) : shown);
72
74
  }), []);
73
75
  // A new array literal each render must not re-set the native prop. Always an
74
76
  // array (empty = no tiers): removing the prop would reach native as `null`,
@@ -83,7 +85,7 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, fractionDigi
83
85
  jumpTo: (next) => nativeRef.current?.jumpTo(next),
84
86
  animateTo: (next) => nativeRef.current?.animateTo(next),
85
87
  revealTo: (next) => nativeRef.current?.revealTo(next),
86
- getValue: () => (compactRef.current ? latestValue.current : nativeRef.current?.value ?? latestValue.current),
88
+ getValue: () => compactRef.current ? toNumber(latestValue.current) : nativeRef.current?.value ?? toNumber(latestValue.current),
87
89
  get native() {
88
90
  return nativeRef.current;
89
91
  },
@@ -104,14 +106,20 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, fractionDigi
104
106
  const resolvedFontSize = fontSize ?? 32;
105
107
  const resolvedAffixAlign = affixAlign ?? 'baseline';
106
108
  const derived = format ? formatProps(format) : undefined;
107
- // Compact notation: "1.2K" rolls the figure 1.2 and swaps the suffix.
108
- const compact = format && derived?.compact ? compactParts(format, value) : undefined;
109
+ // What the format shows for this value: the figure rounded its way, in the
110
+ // fraction digits it prints. Compact notation also swaps the suffix: "1.2K"
111
+ // rolls the figure 1.2.
112
+ const figure = useMemo(() => (format ? figureOf(format, input) : undefined), [format, input]);
113
+ const compact = derived?.compact ? figure : undefined;
109
114
  const compactRef = useRef(false);
110
115
  compactRef.current = compact !== undefined;
111
116
  // Which way the value moved, for a compact figure that fell while the value grew (999 → 1K).
112
- const previousValue = useRef(value);
113
- const compactDirection = compact && direction === undefined ? (value >= previousValue.current ? 'up' : 'down') : undefined;
114
- previousValue.current = value;
117
+ const numericValue = toNumber(input);
118
+ const previousValue = useRef(numericValue);
119
+ const compactDirection = compact && direction === undefined ? (numericValue >= previousValue.current ? 'up' : 'down') : undefined;
120
+ previousValue.current = numericValue;
121
+ // Without a format the engine rounds the double, as it always has.
122
+ const shownValue = figure ? figure.value : numericValue;
115
123
  const processedPrefixColor = useMemo(() => toProcessedColor(prefixColor) ?? Infinity, [prefixColor]);
116
124
  const processedSuffixColor = useMemo(() => toProcessedColor(suffixColor) ?? Infinity, [suffixColor]);
117
125
  const processedFractionColor = useMemo(() => toProcessedColor(fractionColor) ?? Infinity, [fractionColor]);
@@ -147,5 +155,5 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, fractionDigi
147
155
  // does not hand a Hybrid View its resolved direction, so native is told.
148
156
  const layoutDirection = useMemo(() => StyleSheet.flatten(style)?.direction, [style]);
149
157
  const rightToLeft = layoutDirection === 'rtl' || (layoutDirection !== 'ltr' && I18nManager.isRTL);
150
- return (React.createElement(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 }));
158
+ return (React.createElement(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 }));
151
159
  });
@@ -350,6 +350,24 @@ const nativeOf = (value, method, unwrap = false) => slotsOf(value, method, unwra
350
350
  export function sharedFormatterOf(value) {
351
351
  return typeof value === 'object' && value !== null ? slots.get(value)?.native : undefined;
352
352
  }
353
+ /**
354
+ * What `format` shows for `value`, as `NitroNumber` rolls it: the figure
355
+ * rounded and trimmed as the format prints it, and the text around it. Read
356
+ * in C++ off the formatter's own parts, from the number, bigint or decimal
357
+ * string itself.
358
+ * @internal
359
+ */
360
+ export function figureOf(format, value) {
361
+ return nativeOf(format, 'figure').figure(toMathematicalValue(value));
362
+ }
363
+ /**
364
+ * The prefix, suffix, separators, sign placement, grouping and digits of
365
+ * `format`, read in C++ off its parts.
366
+ * @internal
367
+ */
368
+ export function layoutOf(format) {
369
+ return nativeOf(format, 'layout').layout();
370
+ }
353
371
  // `length` is 0 as the specification says: the arguments are read from `arguments`.
354
372
  function NumberFormatConstructor() {
355
373
  const locales = arguments[0];
@@ -1,32 +1,11 @@
1
- import { NumberFormat, sharedFormatterOf } from './NumberFormat';
2
- const NUMBER_PARTS = new Set(['integer', 'group', 'decimal', 'fraction']);
1
+ import { layoutOf, sharedFormatterOf } from './NumberFormat';
2
+ export { figureOf } from './NumberFormat';
3
3
  // By the native formatter, which instances built with the same locales and options share.
4
4
  const cache = new WeakMap();
5
- function join(parts, from, to) {
6
- return parts
7
- .slice(from, to)
8
- .map((p) => p.value)
9
- .join('');
10
- }
11
- /** The text before and after the number in `parts`. */
12
- function affixes(parts) {
13
- const first = parts.findIndex((p) => NUMBER_PARTS.has(p.type));
14
- let last = first;
15
- parts.forEach((p, i) => {
16
- if (NUMBER_PARTS.has(p.type))
17
- last = i;
18
- });
19
- // The sign is the component's own glyph, not part of an affix.
20
- const unsigned = (from, to) => join(parts.map((p) => (p.type === 'minusSign' || p.type === 'plusSign' ? { ...p, value: '' } : p)), from, to);
21
- return {
22
- prefix: first < 0 ? '' : unsigned(0, first),
23
- suffix: first < 0 ? '' : unsigned(last + 1, parts.length),
24
- };
25
- }
26
5
  /**
27
- * The prefix, suffix, separators and digit counts of `format`, read off its
28
- * parts once and cached per formatter. The components keep their own model
29
- * (a sign, a prefix, digits in groups, a suffix), so a format outside it
6
+ * The prefix, suffix, separators and digit counts of `format`, read in C++
7
+ * off its parts once and cached per formatter. The components keep their own
8
+ * model (a sign, a prefix, digits in groups, a suffix), so a format outside it
30
9
  * (accounting parentheses, a unit between the digits) is followed as far as
31
10
  * that model goes.
32
11
  */
@@ -36,69 +15,63 @@ export function formatProps(format) {
36
15
  if (cached)
37
16
  return cached;
38
17
  const resolved = format.resolvedOptions();
39
- const compact = resolved.notation === 'compact';
40
- const fractionDigits = resolved.maximumFractionDigits ?? 0;
41
- // A value with every part: groups, and a fraction when the format has one.
42
- // Compact notation would print it "1.2M", so its affixes come per value.
43
- const parts = format.formatToParts(compact ? 1 : fractionDigits > 0 ? 1234567.5 : 1234567);
44
- const negative = format.formatToParts(-1);
45
- const minus = negative.findIndex((p) => p.type === 'minusSign');
46
- const currency = negative.findIndex((p) => p.type === 'currency' || p.type === 'percentSign');
47
- const integers = parts.filter((p) => p.type === 'integer').map((p) => p.value.length);
18
+ const layout = layoutOf(format);
48
19
  const props = {
49
- ...affixes(parts),
50
- groupingSeparator: parts.find((p) => p.type === 'group')?.value ?? '',
51
- decimalSeparator: parts.find((p) => p.type === 'decimal')?.value ?? '.',
52
- fractionDigits,
20
+ prefix: layout.prefix,
21
+ suffix: layout.suffix,
22
+ groupingSeparator: layout.groupingSeparator,
23
+ decimalSeparator: layout.decimalSeparator,
24
+ fractionDigits: resolved.maximumFractionDigits ?? 0,
53
25
  minimumIntegerDigits: resolved.minimumIntegerDigits,
54
- signPlacement: minus >= 0 && currency >= 0 && minus > currency ? 'afterAffix' : 'beforeAffix',
26
+ signPlacement: layout.signAfterAffix ? 'afterAffix' : 'beforeAffix',
55
27
  signDisplay: (resolved.signDisplay ?? 'auto'),
56
- minusSign: negative[minus]?.value ?? '-',
28
+ minusSign: layout.minusSign,
57
29
  plusSign: '+',
58
- digitGlyphs: digitGlyphsOf(resolved.locale, resolved.numberingSystem),
59
- // "12,34,567": the last group is the first size, the one before it every later one.
60
- groupingSizes: integers.length >= 3 ? [integers[integers.length - 1], integers[integers.length - 2]] : [3],
61
- compact,
30
+ digitGlyphs: layout.digitGlyphs,
31
+ groupingSizes: layout.groupingSizes,
32
+ compact: resolved.notation === 'compact',
62
33
  };
63
34
  cache.set(key, props);
64
35
  return props;
65
36
  }
66
- const digitGlyphCache = new Map();
67
- /** The ten digits of a numbering system, or [] for Latin ones. */
68
- function digitGlyphsOf(locale, numberingSystem) {
69
- if (!numberingSystem || numberingSystem === 'latn')
70
- return [];
71
- const cached = digitGlyphCache.get(numberingSystem);
72
- if (cached)
73
- return cached;
74
- const digits = new NumberFormat(locale, { numberingSystem, useGrouping: false });
75
- const glyphs = Array.from({ length: 10 }, (_, d) => digits.format(d));
76
- const result = glyphs.every((g, d) => g === String(d)) ? [] : glyphs;
77
- digitGlyphCache.set(numberingSystem, result);
78
- return result;
79
- }
80
37
  /**
81
- * Compact notation's parts for `value`: "1.2K" is the figure 1.2 with the
82
- * suffix "K", so the digits roll and the suffix swaps as the value crosses
83
- * a thousand, a million…
38
+ * `value` read in units of 10^-`minorDigits`, exactly: 123456n with 2 minor
39
+ * digits is "1234.56". A bigint or a numeric string is shifted as text, so no
40
+ * digit goes through a double: a decimal ("1234.5"), one with an exponent
41
+ * ("1e5" becomes "1e3"), or a 0x / 0o / 0b integer, as `Intl.NumberFormat`
42
+ * reads strings. A number that is a safe integer is shifted the same way, any
43
+ * other number is divided. A string that is not a number ("1,234.56") comes
44
+ * back as it is, which the format shows as NaN, never as a wrong amount.
84
45
  */
85
- export function compactParts(format, value) {
86
- const parts = format.formatToParts(value);
87
- const props = formatProps(format);
88
- const latin = (text) => props.digitGlyphs.length === 10
89
- ? Array.from(text)
90
- .map((c) => {
91
- const d = props.digitGlyphs.indexOf(c);
92
- return d >= 0 ? String(d) : c;
93
- })
94
- .join('')
95
- : text;
96
- const integer = latin(parts.filter((p) => p.type === 'integer').map((p) => p.value).join(''));
97
- const fraction = latin(parts.filter((p) => p.type === 'fraction').map((p) => p.value).join(''));
98
- const magnitude = Number(fraction ? `${integer}.${fraction}` : integer);
99
- return {
100
- value: (value < 0 ? -1 : 1) * (Number.isFinite(magnitude) ? magnitude : 0),
101
- fractionDigits: fraction.length,
102
- ...affixes(parts),
103
- };
46
+ export function withMinorDigits(value, minorDigits) {
47
+ const digits = minorDigits === undefined ? 0 : Math.max(0, Math.trunc(minorDigits));
48
+ if (digits === 0)
49
+ return value;
50
+ if (typeof value === 'number') {
51
+ if (!Number.isSafeInteger(value))
52
+ return value / 10 ** digits;
53
+ value = BigInt(value);
54
+ }
55
+ let text = typeof value === 'bigint' ? value.toString() : value.trim();
56
+ if (/^0[xob][0-9a-f]+$/i.test(text)) {
57
+ // A non-decimal integer: BigInt reads it as Intl does, exactly.
58
+ text = BigInt(text).toString();
59
+ }
60
+ const match = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text);
61
+ if (!match || (match[2] === '' && match[3] === undefined && text !== ''))
62
+ return value;
63
+ const [, sign = '', whole = '', fraction = '', exponent] = match;
64
+ if (whole === '' && fraction === '' && text.includes('.'))
65
+ return value;
66
+ if (exponent !== undefined) {
67
+ // Moving the point is moving the exponent.
68
+ return `${sign}${whole}${fraction ? `.${fraction}` : ''}e${Number(exponent) - digits}`;
69
+ }
70
+ const all = (whole + fraction).padStart(digits + fraction.length + 1, '0');
71
+ const point = all.length - fraction.length - digits;
72
+ return `${sign}${all.slice(0, point)}.${all.slice(point)}`;
73
+ }
74
+ /** `value` as a double, for comparisons and for the engine when there is no format. */
75
+ export function toNumber(value) {
76
+ return typeof value === 'number' ? value : Number(value);
104
77
  }
@@ -14,11 +14,28 @@ export interface NitroNumberProps extends Omit<ViewProps, 'children'> {
14
14
  /**
15
15
  * The number to display. Every change rolls each digit natively to its new
16
16
  * glyph, in the direction of the change. The first value is shown instantly.
17
- * At most 18 digits are shown: `|value| × 10^fractionDigits` is clamped at
18
- * 10^17, and a JS number carries exact integers only up to 2^53.
17
+ *
18
+ * A `bigint` or a decimal string (`"1234.56"`) is taken as is, with no
19
+ * conversion on your side: money kept as minor units passes straight in
20
+ * with `minorDigits`. With a `format`, it is rounded by the format, in
21
+ * decimal, so it never goes through a double first. The digits themselves
22
+ * animate as a double: exact while `|value| × 10^fractionDigits` stays
23
+ * within 2^53, and at most 18 digits are shown.
24
+ */
25
+ value: number | bigint | string;
26
+ /**
27
+ * The decimal places `value` is counted in: `value={123456n}` with
28
+ * `minorDigits={2}` is 1234.56, cents to dollars without dividing. Applied
29
+ * to a bigint or a decimal string exactly. Default: `0`.
30
+ */
31
+ minorDigits?: number;
32
+ /**
33
+ * Digits shown after the decimal separator. Default: `0`, or with a
34
+ * `format`, what the format shows for each value: its
35
+ * `trailingZeroDisplay`, a minimum below its maximum and significant
36
+ * digits all decide it per value, and the decimal columns roll in and out as
37
+ * the count changes. Set, it holds every value to this many.
19
38
  */
20
- value: number;
21
- /** Digits shown after the decimal separator. Default: `0`. */
22
39
  fractionDigits?: number;
23
40
  /** Zero-pads the integer part to at least this many digits. Default: `1`. */
24
41
  minimumIntegerDigits?: number;
@@ -192,9 +209,10 @@ export interface NitroNumberProps extends Omit<ViewProps, 'children'> {
192
209
  tabularNums?: boolean;
193
210
  /**
194
211
  * A `NumberFormat` the number follows: its prefix and suffix (the currency
195
- * where the locale puts it), grouping and decimal separators, fraction
196
- * digits and minimum integer digits. The individual props override what it
197
- * says.
212
+ * where the locale puts it), grouping and decimal separators, minimum
213
+ * integer digits, and per value the digits it prints: rounded with its
214
+ * `roundingMode`, trimmed by its `trailingZeroDisplay`. The figure is what
215
+ * `format.format(value)` shows. The individual props override what it says.
198
216
  */
199
217
  format?: NumberFormat;
200
218
  /**