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.
@@ -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
  /**
@@ -1,4 +1,4 @@
1
- import type { NumberFormatOptions, NumberFormatPart, ResolvedNumberFormatOptions } from './specs/NumberFormat.nitro';
1
+ import type { NumberFigure, NumberFormatLayout, NumberFormatOptions, NumberFormatPart, ResolvedNumberFormatOptions } from './specs/NumberFormat.nitro';
2
2
  /**
3
3
  * A number formatter with the API of `Intl.NumberFormat`, formatted natively.
4
4
  *
@@ -44,4 +44,18 @@ export interface NumberFormatConstructor {
44
44
  * @internal
45
45
  */
46
46
  export declare function sharedFormatterOf(value: unknown): object | undefined;
47
+ /**
48
+ * What `format` shows for `value`, as `NitroNumber` rolls it: the figure
49
+ * rounded and trimmed as the format prints it, and the text around it. Read
50
+ * in C++ off the formatter's own parts, from the number, bigint or decimal
51
+ * string itself.
52
+ * @internal
53
+ */
54
+ export declare function figureOf(format: NumberFormat, value: number | bigint | string): NumberFigure;
55
+ /**
56
+ * The prefix, suffix, separators, sign placement, grouping and digits of
57
+ * `format`, read in C++ off its parts.
58
+ * @internal
59
+ */
60
+ export declare function layoutOf(format: NumberFormat): NumberFormatLayout;
47
61
  export declare const NumberFormat: NumberFormatConstructor;
@@ -1,11 +1,16 @@
1
- import { NumberFormat } from './NumberFormat';
1
+ import { type NumberFormat } from './NumberFormat';
2
+ export { figureOf } from './NumberFormat';
2
3
  /** What `NitroNumber` and `NitroInput` take from a `NumberFormat` through their `format` prop. */
3
4
  export interface FormatProps {
4
5
  prefix: string;
5
6
  suffix: string;
6
7
  groupingSeparator: string;
7
8
  decimalSeparator: string;
8
- /** The digits after the decimal separator: the format's maximum. */
9
+ /**
10
+ * The digits after the decimal separator: the format's maximum. What one
11
+ * value shows can be fewer (`trailingZeroDisplay`, a minimum below the
12
+ * maximum): `figureOf` says per value.
13
+ */
9
14
  fractionDigits: number;
10
15
  minimumIntegerDigits: number;
11
16
  /** Whether a negative amount's sign comes before the prefix ("-$5") or after it ("$-5"). */
@@ -20,28 +25,28 @@ export interface FormatProps {
20
25
  digitGlyphs: string[];
21
26
  /** The first digit group and every later one, from the decimal point ([3, 2]: 12,34,567). */
22
27
  groupingSizes: number[];
23
- /** Compact notation: the prefix, suffix and digits follow the value (`compactParts`). */
28
+ /** Compact notation: the prefix, suffix and digits follow the value (`figureOf`). */
24
29
  compact: boolean;
25
30
  }
26
31
  /**
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
32
+ * The prefix, suffix, separators and digit counts of `format`, read in C++
33
+ * off its parts once and cached per formatter. The components keep their own
34
+ * model (a sign, a prefix, digits in groups, a suffix), so a format outside it
30
35
  * (accounting parentheses, a unit between the digits) is followed as far as
31
36
  * that model goes.
32
37
  */
33
38
  export declare function formatProps(format: NumberFormat): FormatProps;
34
- /** What a compact format shows for one value: the figure to roll and the text around it. */
35
- export interface CompactParts {
36
- /** The figure as the digits show it: 1.2 for "1.2K". */
37
- value: number;
38
- fractionDigits: number;
39
- prefix: string;
40
- suffix: string;
41
- }
39
+ /** A value as `NumberFormat` takes it: a number, a bigint or a decimal string. */
40
+ export type NumericInput = number | bigint | string;
42
41
  /**
43
- * Compact notation's parts for `value`: "1.2K" is the figure 1.2 with the
44
- * suffix "K", so the digits roll and the suffix swaps as the value crosses
45
- * a thousand, a million…
42
+ * `value` read in units of 10^-`minorDigits`, exactly: 123456n with 2 minor
43
+ * digits is "1234.56". A bigint or a numeric string is shifted as text, so no
44
+ * digit goes through a double: a decimal ("1234.5"), one with an exponent
45
+ * ("1e5" becomes "1e3"), or a 0x / 0o / 0b integer, as `Intl.NumberFormat`
46
+ * reads strings. A number that is a safe integer is shifted the same way, any
47
+ * other number is divided. A string that is not a number ("1,234.56") comes
48
+ * back as it is, which the format shows as NaN, never as a wrong amount.
46
49
  */
47
- export declare function compactParts(format: NumberFormat, value: number): CompactParts;
50
+ export declare function withMinorDigits(value: NumericInput, minorDigits: number | undefined): NumericInput;
51
+ /** `value` as a double, for comparisons and for the engine when there is no format. */
52
+ export declare function toNumber(value: NumericInput): number;
@@ -62,6 +62,35 @@ export interface NumberFormatPart {
62
62
  type: string;
63
63
  value: string;
64
64
  }
65
+ /**
66
+ * One value as `NitroNumber` rolls it: the figure its digits show, rounded and
67
+ * trimmed as the format prints it, and the text around it.
68
+ */
69
+ export interface NumberFigure {
70
+ /** The figure as the digits show it, signed: 1.2 for "1.2K", 2.12 for "$2.12"; 0 (never -0) when it rounds to nothing, or for NaN and infinities. */
71
+ value: number;
72
+ /** The fraction digits this value shows ("$1,234" 0, "$1,234.50" 2); the format's maximum for NaN and infinities. */
73
+ fractionDigits: number;
74
+ /** The text before the number, without the sign. */
75
+ prefix: string;
76
+ /** The text after the number, without the sign. */
77
+ suffix: string;
78
+ }
79
+ /** The shape of a format, as `NitroNumber` and `NitroInput` lay a number out. */
80
+ export interface NumberFormatLayout {
81
+ prefix: string;
82
+ suffix: string;
83
+ /** Empty when the format does not group. */
84
+ groupingSeparator: string;
85
+ decimalSeparator: string;
86
+ /** A negative amount's sign comes after the prefix ("$-5"), not before it ("-$5"). */
87
+ signAfterAffix: boolean;
88
+ minusSign: string;
89
+ /** The group nearest the decimal point and every one before it ([3, 2]: 12,34,567). */
90
+ groupingSizes: number[];
91
+ /** The format's digits 0…9, or empty for Latin ones. */
92
+ digitGlyphs: string[];
93
+ }
65
94
  /**
66
95
  * A number formatter with the API of `Intl.NumberFormat`. It learns a
67
96
  * locale's format once from the platform (Foundation on iOS, ICU on Android)
@@ -76,6 +105,10 @@ export interface NitroNumberFormat extends HybridObject<{
76
105
  format(value: number | Int64 | string): string;
77
106
  formatToParts(value: number | Int64 | string): NumberFormatPart[];
78
107
  resolvedOptions(): ResolvedNumberFormatOptions;
108
+ /** For the components, not part of `Intl.NumberFormat`: what `value` shows, as a figure. */
109
+ figure(value: number | Int64 | string): NumberFigure;
110
+ /** For the components, not part of `Intl.NumberFormat`: the shape of the format. */
111
+ layout(): NumberFormatLayout;
79
112
  }
80
113
  export interface NitroNumberFormatFactory extends HybridObject<{
81
114
  ios: 'c++';