react-native-nitro-input 0.2.0 → 0.3.0

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.
Files changed (164) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +43 -1
  3. package/android/CMakeLists.txt +4 -0
  4. package/android/gradle.properties +1 -1
  5. package/android/src/main/cpp/JRollingEngine.cpp +3 -2
  6. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +20 -0
  7. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberFormatPlatform.kt +209 -0
  8. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +25 -0
  9. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +69 -10
  10. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +164 -24
  11. package/android/src/main/java/com/margelo/nitro/nitroinput/RollingEngine.kt +2 -1
  12. package/cpp/RollingEngine.cpp +12 -2
  13. package/cpp/RollingEngine.hpp +8 -1
  14. package/cpp/numberformat/HybridNitroNumberFormat.cpp +498 -0
  15. package/cpp/numberformat/HybridNitroNumberFormat.hpp +74 -0
  16. package/cpp/numberformat/HybridNitroNumberFormatFactory.hpp +11 -0
  17. package/cpp/numberformat/NumberFormatCore.cpp +629 -0
  18. package/cpp/numberformat/NumberFormatCore.hpp +154 -0
  19. package/cpp/numberformat/NumberFormatProbe.cpp +354 -0
  20. package/cpp/numberformat/NumberFormatProbe.hpp +63 -0
  21. package/ios/HybridNitroInputView.swift +15 -0
  22. package/ios/HybridNitroNumberFormatPlatform.swift +348 -0
  23. package/ios/HybridNitroNumberView.swift +19 -0
  24. package/ios/NitroInputView.swift +79 -19
  25. package/ios/NitroNumberView.swift +171 -31
  26. package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +5 -0
  27. package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -0
  28. package/lib/commonjs/src/NitroInput.js +8 -6
  29. package/lib/commonjs/src/NitroNumber.js +4 -2
  30. package/lib/commonjs/src/NumberFormat.js +525 -0
  31. package/lib/commonjs/src/formatProps.js +48 -0
  32. package/lib/commonjs/src/index.js +3 -1
  33. package/lib/commonjs/src/specs/NumberFormat.nitro.js +2 -0
  34. package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +5 -0
  35. package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -0
  36. package/lib/module/src/NitroInput.js +8 -6
  37. package/lib/module/src/NitroNumber.js +4 -2
  38. package/lib/module/src/NumberFormat.js +521 -0
  39. package/lib/module/src/formatProps.js +45 -0
  40. package/lib/module/src/index.js +1 -0
  41. package/lib/module/src/specs/NumberFormat.nitro.js +1 -0
  42. package/lib/typescript/src/NitroInput.d.ts +22 -0
  43. package/lib/typescript/src/NitroNumber.d.ts +36 -1
  44. package/lib/typescript/src/NumberFormat.d.ts +47 -0
  45. package/lib/typescript/src/formatProps.d.ts +21 -0
  46. package/lib/typescript/src/index.d.ts +2 -0
  47. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +10 -0
  48. package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +13 -1
  49. package/lib/typescript/src/specs/NumberFormat.nitro.d.ts +139 -0
  50. package/nitro.json +16 -0
  51. package/nitrogen/generated/android/NitroInput+autolinking.cmake +6 -0
  52. package/nitrogen/generated/android/NitroInputOnLoad.cpp +28 -0
  53. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +45 -0
  54. package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +10 -0
  55. package/nitrogen/generated/android/c++/JHybridNitroNumberFormatPlatformSpec.cpp +118 -0
  56. package/nitrogen/generated/android/c++/JHybridNitroNumberFormatPlatformSpec.hpp +64 -0
  57. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +54 -0
  58. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +12 -0
  59. package/nitrogen/generated/android/c++/JHybridNitroPlatformNumberFormatterSpec.cpp +65 -0
  60. package/nitrogen/generated/android/c++/JHybridNitroPlatformNumberFormatterSpec.hpp +64 -0
  61. package/nitrogen/generated/android/c++/JNitroNumberDirection.hpp +3 -0
  62. package/nitrogen/generated/android/c++/JNumberFormatCompactDisplay.hpp +58 -0
  63. package/nitrogen/generated/android/c++/JNumberFormatCurrencyDisplay.hpp +64 -0
  64. package/nitrogen/generated/android/c++/JNumberFormatCurrencySign.hpp +58 -0
  65. package/nitrogen/generated/android/c++/JNumberFormatNotation.hpp +64 -0
  66. package/nitrogen/generated/android/c++/JNumberFormatPlatformOptions.hpp +161 -0
  67. package/nitrogen/generated/android/c++/JNumberFormatPlatformSymbols.hpp +89 -0
  68. package/nitrogen/generated/android/c++/JNumberFormatRoundingMode.hpp +79 -0
  69. package/nitrogen/generated/android/c++/JNumberFormatSignDisplay.hpp +67 -0
  70. package/nitrogen/generated/android/c++/JNumberFormatStyle.hpp +64 -0
  71. package/nitrogen/generated/android/c++/JNumberFormatUnitDisplay.hpp +61 -0
  72. package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +25 -0
  73. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +30 -0
  74. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +30 -0
  75. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberFormatPlatformSpec.kt +60 -0
  76. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +36 -0
  77. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroPlatformNumberFormatterSpec.kt +62 -0
  78. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberDirection.kt +2 -1
  79. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatCompactDisplay.kt +23 -0
  80. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatCurrencyDisplay.kt +25 -0
  81. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatCurrencySign.kt +23 -0
  82. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatNotation.kt +25 -0
  83. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatPlatformOptions.kt +136 -0
  84. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatPlatformSymbols.kt +91 -0
  85. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatRoundingMode.kt +30 -0
  86. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatSignDisplay.kt +26 -0
  87. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatStyle.kt +25 -0
  88. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NumberFormatUnitDisplay.kt +24 -0
  89. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +34 -0
  90. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +63 -0
  91. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +40 -0
  92. package/nitrogen/generated/ios/NitroInputAutolinking.mm +18 -0
  93. package/nitrogen/generated/ios/NitroInputAutolinking.swift +12 -0
  94. package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +30 -0
  95. package/nitrogen/generated/ios/c++/HybridNitroNumberFormatPlatformSpecSwift.cpp +11 -0
  96. package/nitrogen/generated/ios/c++/HybridNitroNumberFormatPlatformSpecSwift.hpp +122 -0
  97. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +42 -0
  98. package/nitrogen/generated/ios/c++/HybridNitroPlatformNumberFormatterSpecSwift.cpp +11 -0
  99. package/nitrogen/generated/ios/c++/HybridNitroPlatformNumberFormatterSpecSwift.hpp +94 -0
  100. package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +30 -0
  101. package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +36 -0
  102. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +5 -0
  103. package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +55 -0
  104. package/nitrogen/generated/ios/swift/HybridNitroNumberFormatPlatformSpec.swift +56 -0
  105. package/nitrogen/generated/ios/swift/HybridNitroNumberFormatPlatformSpec_cxx.swift +159 -0
  106. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +6 -0
  107. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +144 -0
  108. package/nitrogen/generated/ios/swift/HybridNitroPlatformNumberFormatterSpec.swift +56 -0
  109. package/nitrogen/generated/ios/swift/HybridNitroPlatformNumberFormatterSpec_cxx.swift +155 -0
  110. package/nitrogen/generated/ios/swift/NitroNumberDirection.swift +4 -0
  111. package/nitrogen/generated/ios/swift/NumberFormatCompactDisplay.swift +40 -0
  112. package/nitrogen/generated/ios/swift/NumberFormatCurrencyDisplay.swift +48 -0
  113. package/nitrogen/generated/ios/swift/NumberFormatCurrencySign.swift +40 -0
  114. package/nitrogen/generated/ios/swift/NumberFormatNotation.swift +48 -0
  115. package/nitrogen/generated/ios/swift/NumberFormatPlatformOptions.swift +159 -0
  116. package/nitrogen/generated/ios/swift/NumberFormatPlatformSymbols.swift +69 -0
  117. package/nitrogen/generated/ios/swift/NumberFormatRoundingMode.swift +68 -0
  118. package/nitrogen/generated/ios/swift/NumberFormatSignDisplay.swift +52 -0
  119. package/nitrogen/generated/ios/swift/NumberFormatStyle.swift +48 -0
  120. package/nitrogen/generated/ios/swift/NumberFormatUnitDisplay.swift +44 -0
  121. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +10 -0
  122. package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +10 -0
  123. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatFactorySpec.cpp +22 -0
  124. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatFactorySpec.hpp +70 -0
  125. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatPlatformSpec.cpp +22 -0
  126. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatPlatformSpec.hpp +70 -0
  127. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatSpec.cpp +23 -0
  128. package/nitrogen/generated/shared/c++/HybridNitroNumberFormatSpec.hpp +71 -0
  129. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +12 -0
  130. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +12 -0
  131. package/nitrogen/generated/shared/c++/HybridNitroPlatformNumberFormatterSpec.cpp +23 -0
  132. package/nitrogen/generated/shared/c++/HybridNitroPlatformNumberFormatterSpec.hpp +65 -0
  133. package/nitrogen/generated/shared/c++/NitroNumberDirection.hpp +4 -0
  134. package/nitrogen/generated/shared/c++/NumberFormatCompactDisplay.hpp +76 -0
  135. package/nitrogen/generated/shared/c++/NumberFormatCurrencyDisplay.hpp +84 -0
  136. package/nitrogen/generated/shared/c++/NumberFormatCurrencySign.hpp +76 -0
  137. package/nitrogen/generated/shared/c++/NumberFormatGrouping.hpp +80 -0
  138. package/nitrogen/generated/shared/c++/NumberFormatNotation.hpp +84 -0
  139. package/nitrogen/generated/shared/c++/NumberFormatOptions.hpp +193 -0
  140. package/nitrogen/generated/shared/c++/NumberFormatPart.hpp +87 -0
  141. package/nitrogen/generated/shared/c++/NumberFormatPlatformOptions.hpp +176 -0
  142. package/nitrogen/generated/shared/c++/NumberFormatPlatformSymbols.hpp +115 -0
  143. package/nitrogen/generated/shared/c++/NumberFormatRoundingMode.hpp +104 -0
  144. package/nitrogen/generated/shared/c++/NumberFormatRoundingPriority.hpp +80 -0
  145. package/nitrogen/generated/shared/c++/NumberFormatSignDisplay.hpp +88 -0
  146. package/nitrogen/generated/shared/c++/NumberFormatStyle.hpp +84 -0
  147. package/nitrogen/generated/shared/c++/NumberFormatTrailingZeroDisplay.hpp +76 -0
  148. package/nitrogen/generated/shared/c++/NumberFormatUnitDisplay.hpp +80 -0
  149. package/nitrogen/generated/shared/c++/ResolvedNumberFormatOptions.hpp +197 -0
  150. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +10 -0
  151. package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +15 -0
  152. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +12 -0
  153. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +18 -0
  154. package/nitrogen/generated/shared/json/NitroInputViewConfig.json +5 -0
  155. package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -0
  156. package/package.json +2 -2
  157. package/src/NitroInput.tsx +42 -7
  158. package/src/NitroNumber.tsx +57 -7
  159. package/src/NumberFormat.ts +563 -0
  160. package/src/formatProps.ts +59 -0
  161. package/src/index.ts +18 -0
  162. package/src/specs/NitroInput.nitro.ts +10 -0
  163. package/src/specs/NitroNumber.nitro.ts +13 -1
  164. package/src/specs/NumberFormat.nitro.ts +145 -0
@@ -4,6 +4,7 @@ import { callback, getHostComponent, } from 'react-native-nitro-modules';
4
4
  import NitroInputViewConfig from '../nitrogen/generated/shared/json/NitroInputViewConfig.json';
5
5
  import { allocateWorkletId, isWorklet, registerFocusChange, registerKeyPress, registerSelectionChange, registerTextEvent, registerCallback, registerTransform, unregisterWorklet, } from './worklets';
6
6
  import { toNumericWeight, toProcessedColor } from './styleHelpers';
7
+ import { formatProps } from './formatProps';
7
8
  const textInputRegistry = (() => {
8
9
  try {
9
10
  // The registry has no public surface: `TextInput.State` exposes the focus
@@ -136,7 +137,7 @@ function warnIncompatible(what) {
136
137
  * Like a `TextInput`, it takes its width from its parent; `autoWidth` sizes
137
138
  * it to its content instead, and is on by default when the text reflows.
138
139
  */
139
- export const NitroInput = forwardRef(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize, lineHeight, fontWeight, fontFamily, color, textAlign, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
140
+ export const NitroInput = forwardRef(function NitroInput({ value, defaultValue, mode, fractionDigits, maxIntegerDigits, groupingSeparator, decimalSeparator, prefix, suffix, prefixFontSize, suffixFontSize, affixAlign, signPlacement, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, format, placeholder, placeholderTextColor, duration, easing, bounce, effect, fontSize, lineHeight, fontWeight, fontFamily, color, textAlign, cursorColor, selectionColor, caretHidden, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, variant, label, labelBehavior, labelColor, labelFocusedColor, labelFontSize, strokeColor, focusedStrokeColor, strokeWidth, cornerRadius, fillColor, keyboardType, inputMode, enterKeyHint, mask, maskNotations, maskAutocomplete, maskAutoSkip, returnKeyType, autoCapitalize, autoCorrect, editable, multiline, numberOfLines, rows, textAlignVertical, scrollEnabled, autoFocus, transition, autoWidth: autoWidthProp, submitBehavior, blurOnSubmit, secureTextEntry, keyboardAppearance, textContentType, autoComplete, enablesReturnKeyAutomatically, showSoftInputOnFocus, selectTextOnFocus, clearTextOnFocus, contextMenuHidden, spellCheck, readOnly, selection, onEndEditing, onSelectionChange, onKeyPress, maxLength, transform, onChangeText, onChange, onChangeValue, onChangeMask, onFocus, onBlur, onSubmitEditing, onNativeRef, style, ...viewProps }, ref) {
140
141
  const nativeRef = useRef(null);
141
142
  // What React Native's registry stores for this field. The React host
142
143
  // instance when there is one (iOS), otherwise a stable per-instance token:
@@ -428,13 +429,14 @@ export const NitroInput = forwardRef(function NitroInput({ value, defaultValue,
428
429
  if (suffix)
429
430
  warnIncompatible('suffix');
430
431
  }
431
- const resolvedMode = isMultiline ? 'text' : (mode ?? 'text');
432
+ const derived = format ? formatProps(format) : undefined;
433
+ const resolvedMode = isMultiline ? 'text' : (mode ?? (derived ? 'number' : 'text'));
432
434
  const reflows = !isMultiline && transition === 'reflow';
433
435
  // The affixes are accessory views beside one line of text; a wrapping text
434
436
  // view has no slot for them, so they go with the mode rather than being
435
437
  // half-drawn on one platform and not the other.
436
- const resolvedPrefix = isMultiline ? '' : (prefix ?? '');
437
- const resolvedSuffix = isMultiline ? '' : (suffix ?? '');
438
+ const resolvedPrefix = isMultiline ? '' : (prefix ?? derived?.prefix ?? '');
439
+ const resolvedSuffix = isMultiline ? '' : (suffix ?? derived?.suffix ?? '');
438
440
  // A new `maskNotations` literal each render must not re-set the native
439
441
  // prop, so it is keyed on its contents. Always an array (empty = none):
440
442
  // removing the prop would reach native as `null`, which Nitro's array
@@ -443,7 +445,7 @@ export const NitroInput = forwardRef(function NitroInput({ value, defaultValue,
443
445
  const stableNotations = useMemo(() => (notationsKey !== '' && maskNotations ? [...maskNotations] : EMPTY_NOTATIONS),
444
446
  // eslint-disable-next-line react-hooks/exhaustive-deps
445
447
  [notationsKey]);
446
- const resolvedFractionDigits = fractionDigits ?? 2;
448
+ const resolvedFractionDigits = fractionDigits ?? derived?.fractionDigits ?? 2;
447
449
  const resolvedKeyboardType = keyboardType ??
448
450
  (inputMode != null
449
451
  ? INPUT_MODE_TO_KEYBOARD[inputMode]
@@ -505,7 +507,7 @@ export const NitroInput = forwardRef(function NitroInput({ value, defaultValue,
505
507
  ? { width: size.width, height: size.height }
506
508
  : { height: size.height }
507
509
  : { height: resolvedFontSize * 1.25 }, [size, resolvedFontSize, autoWidth]);
508
- return (React.createElement(NativeNitroInputView, { ...hostViewProps, ref: hostRef, style: [autoSize, style], hybridRef: hybridRef, text: value ?? initialText, mostRecentEventCount: eventCountRef.current, mode: resolvedMode, plain: !reflows, fractionDigits: resolvedFractionDigits, maxIntegerDigits: maxIntegerDigits ?? 15, groupingSeparator: groupingSeparator ?? ',', decimalSeparator: decimalSeparator ?? '.', prefix: resolvedPrefix, suffix: resolvedSuffix, prefixFontSize: prefixFontSize ?? resolvedFontSize, suffixFontSize: suffixFontSize ?? resolvedFontSize, signPlacement: signPlacement ?? 'beforeAffix', prefixAlign: prefixAlign ?? resolvedAffixAlign, suffixAlign: suffixAlign ?? resolvedAffixAlign, placeholder: placeholder ?? '', placeholderColor: processedPlaceholderColor, duration: duration ?? 400, easing: easing ?? 'expo', bounce: bounce ?? 0.15, effect: effect ?? 'auto', fontSize: resolvedFontSize, lineHeight: Math.max(0, lineHeight ?? 0), fontWeight: numericWeight, fontFamily: fontFamily ?? '', color: processedColor, textAlign: textAlign ?? 'auto', rightToLeft: rightToLeft, caretColor: processedCursorColor, selectionColor: processedSelectionColor, caretHidden: caretHidden ?? false, adjustsFontSizeToFit: adjustsFontSizeToFit ?? false, minimumFontScale: minimumFontScale ?? 0.5, allowFontScaling: allowFontScaling ?? false, maxFontSizeMultiplier: maxFontSizeMultiplier ?? 0, variant: variant ?? 'none', label: label ?? '', labelBehavior: labelBehavior ?? 'float', labelColor: processedLabelColor, labelFocusedColor: processedLabelFocusedColor, labelFontSize: labelFontSize ?? 0, strokeColor: processedStrokeColor, focusedStrokeColor: processedFocusedStrokeColor, strokeWidth: strokeWidth ?? 1, cornerRadius: cornerRadius ?? 8, fillColor: processedFillColor, mask: resolvedMode === 'mask' ? (mask ?? '') : '', maskNotations: stableNotations, maskAutocomplete: maskAutocomplete ?? true, maskAutoSkip: maskAutoSkip ?? false, onChangeMask: onChangeMaskCallback, keyboardType: resolvedKeyboardType, returnKeyType: resolvedReturnKeyType, autoCapitalize: autoCapitalize ?? 'sentences', autoCorrect: autoCorrect ?? true, editable: (editable ?? true) && !(readOnly ?? false), multiline: isMultiline, numberOfLines: Math.max(0, Math.trunc(numberOfLines ?? rows ?? 0)), textAlignVertical: textAlignVertical ?? 'auto', scrollEnabled: scrollEnabled ?? true, autoFocus: autoFocus ?? false, fieldTestID: viewProps.testID ?? '', fieldAccessibilityLabel: resolvedAccessibilityLabel ?? '', submitBehavior: submitBehavior ??
510
+ return (React.createElement(NativeNitroInputView, { ...hostViewProps, ref: hostRef, style: [autoSize, style], hybridRef: hybridRef, text: value ?? initialText, mostRecentEventCount: eventCountRef.current, mode: resolvedMode, plain: !reflows, fractionDigits: resolvedFractionDigits, maxIntegerDigits: maxIntegerDigits ?? 15, groupingSeparator: groupingSeparator ?? derived?.groupingSeparator ?? ',', decimalSeparator: decimalSeparator ?? derived?.decimalSeparator ?? '.', prefix: resolvedPrefix, suffix: resolvedSuffix, prefixFontSize: prefixFontSize ?? resolvedFontSize, suffixFontSize: suffixFontSize ?? resolvedFontSize, signPlacement: signPlacement ?? derived?.signPlacement ?? 'beforeAffix', prefixAlign: prefixAlign ?? resolvedAffixAlign, suffixAlign: suffixAlign ?? resolvedAffixAlign, letterSpacing: letterSpacing ?? 0, prefixSpacing: prefixSpacing ?? Infinity, suffixSpacing: suffixSpacing ?? Infinity, prefixOffset: prefixOffset ?? 0, suffixOffset: suffixOffset ?? 0, placeholder: placeholder ?? '', placeholderColor: processedPlaceholderColor, duration: duration ?? 400, easing: easing ?? 'expo', bounce: bounce ?? 0.15, effect: effect ?? 'auto', fontSize: resolvedFontSize, lineHeight: Math.max(0, lineHeight ?? 0), fontWeight: numericWeight, fontFamily: fontFamily ?? '', color: processedColor, textAlign: textAlign ?? 'auto', rightToLeft: rightToLeft, caretColor: processedCursorColor, selectionColor: processedSelectionColor, caretHidden: caretHidden ?? false, adjustsFontSizeToFit: adjustsFontSizeToFit ?? false, minimumFontScale: minimumFontScale ?? 0.5, allowFontScaling: allowFontScaling ?? false, maxFontSizeMultiplier: maxFontSizeMultiplier ?? 0, variant: variant ?? 'none', label: label ?? '', labelBehavior: labelBehavior ?? 'float', labelColor: processedLabelColor, labelFocusedColor: processedLabelFocusedColor, labelFontSize: labelFontSize ?? 0, strokeColor: processedStrokeColor, focusedStrokeColor: processedFocusedStrokeColor, strokeWidth: strokeWidth ?? 1, cornerRadius: cornerRadius ?? 8, fillColor: processedFillColor, mask: resolvedMode === 'mask' ? (mask ?? '') : '', maskNotations: stableNotations, maskAutocomplete: maskAutocomplete ?? true, maskAutoSkip: maskAutoSkip ?? false, onChangeMask: onChangeMaskCallback, keyboardType: resolvedKeyboardType, returnKeyType: resolvedReturnKeyType, autoCapitalize: autoCapitalize ?? 'sentences', autoCorrect: autoCorrect ?? true, editable: (editable ?? true) && !(readOnly ?? false), multiline: isMultiline, numberOfLines: Math.max(0, Math.trunc(numberOfLines ?? rows ?? 0)), textAlignVertical: textAlignVertical ?? 'auto', scrollEnabled: scrollEnabled ?? true, autoFocus: autoFocus ?? false, fieldTestID: viewProps.testID ?? '', fieldAccessibilityLabel: resolvedAccessibilityLabel ?? '', submitBehavior: submitBehavior ??
509
511
  // As `TextInput` resolves the legacy `blurOnSubmit`: a multiline
510
512
  // field's return key inserts a line break unless told to blur.
511
513
  (multiline
@@ -3,6 +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 { formatProps } from './formatProps';
6
7
  /**
7
8
  * The raw Nitro host component. Prefer {@link NitroNumber}, which adds
8
9
  * auto-sizing, color/weight conversion and a convenient handle.
@@ -24,7 +25,7 @@ const TRANSITION_DEFAULTS = {
24
25
  * The view sizes itself to its content unless you pass an explicit `width` /
25
26
  * `height` in `style`.
26
27
  */
27
- 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, fontSize, prefixFontSize, suffixFontSize, affixAlign, prefixAlign, suffixAlign, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, fontWeight, fontFamily, color, textAlign, onNativeRef, style, ...viewProps }, ref) {
28
+ 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, fontSize, prefixFontSize, suffixFontSize, affixAlign, prefixAlign, suffixAlign, letterSpacing, prefixSpacing, suffixSpacing, prefixOffset, suffixOffset, tabularNums, format, adjustsFontSizeToFit, minimumFontScale, allowFontScaling, maxFontSizeMultiplier, fontWeight, fontFamily, color, textAlign, onNativeRef, style, ...viewProps }, ref) {
28
29
  const nativeRef = useRef(null);
29
30
  const latestOnNativeRef = useRef(onNativeRef);
30
31
  latestOnNativeRef.current = onNativeRef;
@@ -88,6 +89,7 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, fractionDigi
88
89
  const numericWeight = toNumericWeight(fontWeight) ?? 400;
89
90
  const resolvedFontSize = fontSize ?? 32;
90
91
  const resolvedAffixAlign = affixAlign ?? 'baseline';
92
+ const derived = format ? formatProps(format) : undefined;
91
93
  const autoSize = useMemo(() => size !== null
92
94
  ? { width: size.width, height: size.height }
93
95
  : { height: (fontSize ?? 32) * 1.25 }, [size, fontSize]);
@@ -96,5 +98,5 @@ export const NitroNumber = forwardRef(function NitroNumber({ value, fractionDigi
96
98
  // does not hand a Hybrid View its resolved direction, so native is told.
97
99
  const layoutDirection = useMemo(() => StyleSheet.flatten(style)?.direction, [style]);
98
100
  const rightToLeft = layoutDirection === 'rtl' || (layoutDirection !== 'ltr' && I18nManager.isRTL);
99
- return (React.createElement(NativeNitroNumberView, { ...viewProps, style: [autoSize, style], hybridRef: hybridRef, value: value, fractionDigits: fractionDigits ?? 0, minimumIntegerDigits: minimumIntegerDigits ?? 1, groupingSeparator: groupingSeparator ?? '', decimalSeparator: decimalSeparator ?? '.', prefix: prefix ?? '', suffix: suffix ?? '', transition: transition ?? 'roll', flashUpColor: processedFlashUp, flashDownColor: processedFlashDown, flashDuration: flashDuration ?? 600, popOnChange: popOnChange ?? 0, duration: 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 ?? 'auto', revealState: reveal === undefined ? 0 : reveal ? 2 : 1, revealStyle: revealStyle ?? 'count', revealDuration: revealDuration ?? 2200, revealBounce: revealBounce ?? 0.12, revealGrow: revealGrow ?? 0.2, revealStagger: revealStagger ?? 200, revealMilestones: stableMilestones, revealMilestoneHold: revealMilestoneHold ?? 0, onRevealEnd: onRevealEndCallback, onRevealMilestone: onRevealMilestoneCallback, loading: loading ?? false, shimmerColor: processedShimmerColor, shimmerDuration: shimmerDuration ?? 950, fontSize: resolvedFontSize, prefixFontSize: prefixFontSize ?? resolvedFontSize, suffixFontSize: suffixFontSize ?? resolvedFontSize, affixAlign: resolvedAffixAlign, prefixAlign: prefixAlign ?? resolvedAffixAlign, suffixAlign: suffixAlign ?? resolvedAffixAlign, 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 }));
101
+ return (React.createElement(NativeNitroNumberView, { ...viewProps, style: [autoSize, style], hybridRef: hybridRef, value: value, fractionDigits: fractionDigits ?? derived?.fractionDigits ?? 0, minimumIntegerDigits: minimumIntegerDigits ?? derived?.minimumIntegerDigits ?? 1, groupingSeparator: groupingSeparator ?? derived?.groupingSeparator ?? '', decimalSeparator: decimalSeparator ?? derived?.decimalSeparator ?? '.', prefix: prefix ?? derived?.prefix ?? '', suffix: suffix ?? derived?.suffix ?? '', transition: transition ?? 'roll', flashUpColor: processedFlashUp, flashDownColor: processedFlashDown, flashDuration: flashDuration ?? 600, popOnChange: popOnChange ?? 0, duration: 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 ?? 'auto', revealState: reveal === undefined ? 0 : reveal ? 2 : 1, revealStyle: revealStyle ?? 'count', revealDuration: revealDuration ?? 2200, revealBounce: revealBounce ?? 0.12, revealGrow: revealGrow ?? 0.2, revealStagger: revealStagger ?? 200, revealMilestones: stableMilestones, revealMilestoneHold: revealMilestoneHold ?? 0, onRevealEnd: onRevealEndCallback, onRevealMilestone: onRevealMilestoneCallback, loading: loading ?? false, shimmerColor: processedShimmerColor, shimmerDuration: shimmerDuration ?? 950, 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, 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 }));
100
102
  });
@@ -0,0 +1,521 @@
1
+ import { NitroModules } from 'react-native-nitro-modules';
2
+ // MARK: - The native side
3
+ let factory;
4
+ function getFactory() {
5
+ factory ??= NitroModules.createHybridObject('NitroNumberFormatFactory');
6
+ return factory;
7
+ }
8
+ /** Native formatters by locales and resolved options: building one twice is a Map lookup. */
9
+ const natives = new Map();
10
+ const MAX_NATIVES = 512;
11
+ // MARK: - ECMA-402 abstract operations
12
+ /** ToString, which (unlike `String()`) throws for a Symbol. */
13
+ const toString = (value) => `${value}`;
14
+ /** ToNumber, which throws for a Symbol and a BigInt. */
15
+ const toNumber = (value) => +value;
16
+ function getOption(options, property, values, fallback) {
17
+ const value = options[property];
18
+ if (value === undefined)
19
+ return fallback;
20
+ const text = toString(value);
21
+ if (values && !values.includes(text))
22
+ throw new RangeError(`Value ${text} out of range for Intl.NumberFormat options property ${property}`);
23
+ return text;
24
+ }
25
+ function defaultNumberOption(value, min, max, property) {
26
+ if (value === undefined)
27
+ return undefined;
28
+ const n = toNumber(value);
29
+ if (Number.isNaN(n) || n < min || n > max)
30
+ throw new RangeError(`${property} value is out of range.`);
31
+ return Math.floor(n);
32
+ }
33
+ function getNumberOption(options, property, min, max, fallback) {
34
+ return defaultNumberOption(options[property], min, max, property) ?? fallback;
35
+ }
36
+ const isAlphanumeric = (c) => (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
37
+ const isLetter = (c) => (c >= 65 && c <= 90) || (c >= 97 && c <= 122);
38
+ /** A Unicode `type`: parts of 3 to 8 letters or digits. Without a RegExp: it would update the legacy RegExp statics. */
39
+ function isUnicodeType(value) {
40
+ let part = 0;
41
+ for (let i = 0; i <= value.length; i++) {
42
+ if (i === value.length || value.charCodeAt(i) === 45) {
43
+ if (part < 3 || part > 8)
44
+ return false;
45
+ part = 0;
46
+ }
47
+ else if (isAlphanumeric(value.charCodeAt(i))) {
48
+ part++;
49
+ }
50
+ else {
51
+ return false;
52
+ }
53
+ }
54
+ return true;
55
+ }
56
+ const SANCTIONED_UNITS = new Set('acre bit byte celsius centimeter day degree fahrenheit fluid-ounce foot gallon gigabit gigabyte gram hectare hour inch kilobit kilobyte kilogram kilometer liter megabit megabyte meter microsecond mile mile-scandinavian milliliter millimeter millisecond minute month nanosecond ounce percent petabyte pound second stone terabit terabyte week yard year'.split(' '));
57
+ function isWellFormedUnit(unit) {
58
+ if (SANCTIONED_UNITS.has(unit))
59
+ return true;
60
+ const per = unit.indexOf('-per-');
61
+ return per > 0 && SANCTIONED_UNITS.has(unit.slice(0, per)) && SANCTIONED_UNITS.has(unit.slice(per + 5));
62
+ }
63
+ /** ISO 4217 minor-unit digits, as ECMA-402's CurrencyDigits. */
64
+ const CURRENCY_DIGITS = {
65
+ BHD: 3, BIF: 0, CLF: 4, CLP: 0, DJF: 0, GNF: 0, IQD: 3, ISK: 0, JOD: 3, JPY: 0, KMF: 0, KRW: 0, KWD: 3,
66
+ LYD: 3, OMR: 3, PYG: 0, RWF: 0, TND: 3, UGX: 0, UYI: 0, UYW: 4, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
67
+ };
68
+ const ROUNDING_INCREMENTS = [1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000];
69
+ /** CanonicalizeLocaleList; each tag is checked and canonicalized by Hermes' `Intl.getCanonicalLocales`. */
70
+ function canonicalizeLocaleList(locales) {
71
+ if (locales === undefined)
72
+ return [];
73
+ if (locales === null)
74
+ throw new TypeError('Cannot convert null to object');
75
+ const list = typeof locales === 'string' ? [locales] : Object(locales);
76
+ const length = Math.min(Math.max(Math.floor(toNumber(list.length)) || 0, 0), Number.MAX_SAFE_INTEGER);
77
+ const seen = [];
78
+ for (let k = 0; k < length; k++) {
79
+ const key = String(k);
80
+ if (!(key in list))
81
+ continue;
82
+ const value = list[key];
83
+ if (typeof value !== 'string' && (typeof value !== 'object' || value === null))
84
+ throw new TypeError('Language ID should be string or object.');
85
+ const tag = Intl.getCanonicalLocales(toString(value))[0];
86
+ if (!seen.includes(tag))
87
+ seen.push(tag);
88
+ }
89
+ return seen;
90
+ }
91
+ /** The `-u-nu-` of a tag, when it names a numbering system Intl accepts there. */
92
+ function unicodeNumberingSystem(tag) {
93
+ if (tag === undefined)
94
+ return undefined;
95
+ const subtags = tag.toLowerCase().split('-');
96
+ const u = subtags.indexOf('u');
97
+ if (u < 0)
98
+ return undefined;
99
+ for (let i = u + 1; i < subtags.length - 1; i++) {
100
+ if (subtags[i].length === 1)
101
+ break;
102
+ if (subtags[i] === 'nu') {
103
+ const value = subtags[i + 1];
104
+ return value === 'native' || value === 'traditio' || value === 'finance' ? undefined : value;
105
+ }
106
+ }
107
+ return undefined;
108
+ }
109
+ /** ToIntlMathematicalValue: numbers stay numbers; bigints and strings go to native as exact decimal text. */
110
+ function toMathematicalValue(value) {
111
+ let primitive = value;
112
+ if ((typeof value === 'object' && value !== null) || typeof value === 'function')
113
+ primitive = toPrimitiveNumber(value);
114
+ if (typeof primitive === 'bigint')
115
+ return primitive.toString();
116
+ if (typeof primitive === 'string')
117
+ return primitive;
118
+ return toNumber(primitive);
119
+ }
120
+ function toPrimitiveNumber(object) {
121
+ const exotic = object[Symbol.toPrimitive];
122
+ if (exotic !== undefined && exotic !== null) {
123
+ if (typeof exotic !== 'function')
124
+ throw new TypeError('Symbol.toPrimitive is not a function');
125
+ const result = exotic.call(object, 'number');
126
+ if ((typeof result === 'object' && result !== null) || typeof result === 'function')
127
+ throw new TypeError('Cannot convert object to primitive value');
128
+ return result;
129
+ }
130
+ for (const method of ['valueOf', 'toString']) {
131
+ const fn = object[method];
132
+ if (typeof fn === 'function') {
133
+ const result = fn.call(object);
134
+ if (!((typeof result === 'object' && result !== null) || typeof result === 'function'))
135
+ return result;
136
+ }
137
+ }
138
+ throw new TypeError('Cannot convert object to primitive value');
139
+ }
140
+ // MARK: - InitializeNumberFormat
141
+ const STYLES = ['decimal', 'percent', 'currency', 'unit'];
142
+ const CURRENCY_DISPLAYS = ['code', 'symbol', 'narrowSymbol', 'name'];
143
+ const CURRENCY_SIGNS = ['standard', 'accounting'];
144
+ const UNIT_DISPLAYS = ['short', 'narrow', 'long'];
145
+ const NOTATIONS = ['standard', 'scientific', 'engineering', 'compact'];
146
+ const ROUNDING_MODES = ['ceil', 'floor', 'expand', 'trunc', 'halfCeil', 'halfFloor', 'halfExpand', 'halfTrunc', 'halfEven'];
147
+ const ROUNDING_PRIORITIES = ['auto', 'morePrecision', 'lessPrecision'];
148
+ const TRAILING_ZERO_DISPLAYS = ['auto', 'stripIfInteger'];
149
+ const COMPACT_DISPLAYS = ['short', 'long'];
150
+ const SIGN_DISPLAYS = ['auto', 'never', 'always', 'exceptZero', 'negative'];
151
+ /** Reads `options` the way ECMA-402's InitializeNumberFormat does and returns the native formatter. */
152
+ function createNative(locales, optionsArgument) {
153
+ const requested = canonicalizeLocaleList(locales);
154
+ // The numbering system of the locale's -u-nu-, when options do not override it.
155
+ const localeNumberingSystem = unicodeNumberingSystem(requested[0]);
156
+ // CoerceOptionsToObject.
157
+ if (optionsArgument === null)
158
+ throw new TypeError('Cannot convert null to object');
159
+ const options = (optionsArgument === undefined ? Object.create(null) : Object(optionsArgument));
160
+ getOption(options, 'localeMatcher', ['lookup', 'best fit'], 'best fit');
161
+ const numberingSystem = getOption(options, 'numberingSystem', null, undefined);
162
+ if (numberingSystem !== undefined && !isUnicodeType(numberingSystem))
163
+ throw new RangeError(`Invalid numberingSystem: ${numberingSystem}`);
164
+ // SetNumberFormatUnitOptions.
165
+ const style = getOption(options, 'style', STYLES, 'decimal');
166
+ let currency = getOption(options, 'currency', null, undefined);
167
+ if (currency === undefined) {
168
+ if (style === 'currency')
169
+ throw new TypeError('Currency code is required with currency style.');
170
+ }
171
+ else if (currency.length !== 3 || !isLetter(currency.charCodeAt(0)) || !isLetter(currency.charCodeAt(1)) || !isLetter(currency.charCodeAt(2))) {
172
+ throw new RangeError(`Invalid currency code: ${currency}`);
173
+ }
174
+ const currencyDisplay = getOption(options, 'currencyDisplay', CURRENCY_DISPLAYS, 'symbol');
175
+ const currencySign = getOption(options, 'currencySign', CURRENCY_SIGNS, 'standard');
176
+ const unit = getOption(options, 'unit', null, undefined);
177
+ if (unit === undefined) {
178
+ if (style === 'unit')
179
+ throw new TypeError('Unit is required with unit style.');
180
+ }
181
+ else if (!isWellFormedUnit(unit)) {
182
+ throw new RangeError(`Invalid unit argument for Intl.NumberFormat() '${unit}'`);
183
+ }
184
+ const unitDisplay = getOption(options, 'unitDisplay', UNIT_DISPLAYS, 'short');
185
+ if (currency !== undefined)
186
+ currency = currency.toUpperCase();
187
+ const notation = getOption(options, 'notation', NOTATIONS, 'standard');
188
+ let mnfdDefault = 0;
189
+ let mxfdDefault = style === 'percent' ? 0 : 3;
190
+ if (style === 'currency' && notation === 'standard')
191
+ mnfdDefault = mxfdDefault = CURRENCY_DIGITS[currency] ?? 2;
192
+ // SetNumberFormatDigitOptions.
193
+ const minimumIntegerDigits = getNumberOption(options, 'minimumIntegerDigits', 1, 21, 1);
194
+ const mnfdValue = options.minimumFractionDigits;
195
+ const mxfdValue = options.maximumFractionDigits;
196
+ const mnsdValue = options.minimumSignificantDigits;
197
+ const mxsdValue = options.maximumSignificantDigits;
198
+ const roundingIncrement = getNumberOption(options, 'roundingIncrement', 1, 5000, 1);
199
+ if (!ROUNDING_INCREMENTS.includes(roundingIncrement))
200
+ throw new RangeError('roundingIncrement value is out of range.');
201
+ const roundingMode = getOption(options, 'roundingMode', ROUNDING_MODES, 'halfExpand');
202
+ const roundingPriority = getOption(options, 'roundingPriority', ROUNDING_PRIORITIES, 'auto');
203
+ const trailingZeroDisplay = getOption(options, 'trailingZeroDisplay', TRAILING_ZERO_DISPLAYS, 'auto');
204
+ if (roundingIncrement !== 1)
205
+ mxfdDefault = mnfdDefault;
206
+ const hasSd = mnsdValue !== undefined || mxsdValue !== undefined;
207
+ const hasFd = mnfdValue !== undefined || mxfdValue !== undefined;
208
+ let needSd = true;
209
+ let needFd = true;
210
+ if (roundingPriority === 'auto') {
211
+ needSd = hasSd;
212
+ if (needSd || (!hasFd && notation === 'compact'))
213
+ needFd = false;
214
+ }
215
+ let minimumSignificantDigits;
216
+ let maximumSignificantDigits;
217
+ if (needSd && hasSd) {
218
+ minimumSignificantDigits = defaultNumberOption(mnsdValue, 1, 21, 'minimumSignificantDigits') ?? 1;
219
+ maximumSignificantDigits = defaultNumberOption(mxsdValue, minimumSignificantDigits, 21, 'maximumSignificantDigits') ?? 21;
220
+ }
221
+ let minimumFractionDigits;
222
+ let maximumFractionDigits;
223
+ if (needFd && hasFd) {
224
+ minimumFractionDigits = defaultNumberOption(mnfdValue, 0, 100, 'minimumFractionDigits');
225
+ maximumFractionDigits = defaultNumberOption(mxfdValue, 0, 100, 'maximumFractionDigits');
226
+ if (minimumFractionDigits === undefined)
227
+ minimumFractionDigits = Math.min(mnfdDefault, maximumFractionDigits);
228
+ else if (maximumFractionDigits === undefined)
229
+ maximumFractionDigits = Math.max(mxfdDefault, minimumFractionDigits);
230
+ else if (minimumFractionDigits > maximumFractionDigits)
231
+ throw new RangeError('maximumFractionDigits value is out of range.');
232
+ }
233
+ if (roundingIncrement !== 1) {
234
+ const fractionOnly = !needSd && needFd;
235
+ if (!fractionOnly)
236
+ throw new TypeError('roundingIncrement can only be used with fraction digits.');
237
+ const mn = minimumFractionDigits ?? mnfdDefault;
238
+ const mx = maximumFractionDigits ?? mxfdDefault;
239
+ if (mn !== mx)
240
+ throw new RangeError('maximumFractionDigits must equal minimumFractionDigits with a roundingIncrement.');
241
+ }
242
+ const compactDisplay = getOption(options, 'compactDisplay', COMPACT_DISPLAYS, 'short');
243
+ // GetBooleanOrStringNumberFormatOption.
244
+ const defaultUseGrouping = notation === 'compact' ? 'min2' : 'auto';
245
+ let useGrouping;
246
+ const groupingValue = options.useGrouping;
247
+ if (groupingValue === undefined)
248
+ useGrouping = defaultUseGrouping;
249
+ else if (groupingValue === true)
250
+ useGrouping = 'always';
251
+ else if (!groupingValue)
252
+ useGrouping = false;
253
+ else {
254
+ const text = toString(groupingValue);
255
+ if (text === 'true' || text === 'false')
256
+ useGrouping = defaultUseGrouping;
257
+ else if (text === 'min2' || text === 'auto' || text === 'always')
258
+ useGrouping = text;
259
+ else
260
+ throw new RangeError(`Value ${text} out of range for Intl.NumberFormat options property useGrouping`);
261
+ }
262
+ const signDisplay = getOption(options, 'signDisplay', SIGN_DISPLAYS, 'auto');
263
+ // Only what was read goes to native, already checked and coerced.
264
+ const clean = {
265
+ numberingSystem: numberingSystem?.toLowerCase() ?? localeNumberingSystem,
266
+ style,
267
+ currency,
268
+ currencyDisplay,
269
+ currencySign,
270
+ unit,
271
+ unitDisplay,
272
+ notation,
273
+ minimumIntegerDigits,
274
+ minimumFractionDigits: needFd ? minimumFractionDigits : undefined,
275
+ maximumFractionDigits: needFd ? maximumFractionDigits : undefined,
276
+ minimumSignificantDigits: needSd ? minimumSignificantDigits : undefined,
277
+ maximumSignificantDigits: needSd ? maximumSignificantDigits : undefined,
278
+ roundingIncrement,
279
+ roundingMode,
280
+ roundingPriority,
281
+ trailingZeroDisplay,
282
+ compactDisplay,
283
+ useGrouping,
284
+ signDisplay,
285
+ };
286
+ const key = requested.join(',') +
287
+ '|' +
288
+ [
289
+ clean.numberingSystem, style, currency, currencyDisplay, currencySign, unit, unitDisplay, notation, minimumIntegerDigits,
290
+ clean.minimumFractionDigits, clean.maximumFractionDigits, clean.minimumSignificantDigits, clean.maximumSignificantDigits,
291
+ roundingIncrement, roundingMode, roundingPriority, trailingZeroDisplay, compactDisplay, useGrouping, signDisplay,
292
+ ].join('|');
293
+ let native = natives.get(key);
294
+ let fromLocale = numberingSystem === undefined ? localeNumberingSystem : undefined;
295
+ if (native === undefined) {
296
+ // The numbering system travels as an option; native gets the tags without -u- extensions.
297
+ const tags = requested.map(withoutUnicodeExtension);
298
+ native = getFactory().create(tags, clean);
299
+ // An option naming a numbering system the platform lacks is ignored for the locale's.
300
+ if (numberingSystem !== undefined && localeNumberingSystem !== undefined && native.resolvedOptions().numberingSystem !== clean.numberingSystem) {
301
+ native = getFactory().create(tags, { ...clean, numberingSystem: localeNumberingSystem });
302
+ }
303
+ if (natives.size >= MAX_NATIVES)
304
+ natives.clear();
305
+ natives.set(key, native);
306
+ }
307
+ if (numberingSystem !== undefined && native.resolvedOptions().numberingSystem === localeNumberingSystem)
308
+ fromLocale = localeNumberingSystem;
309
+ return { native, localeNumberingSystem: fromLocale };
310
+ }
311
+ function withoutUnicodeExtension(tag) {
312
+ const subtags = tag.split('-');
313
+ const u = subtags.findIndex((t, i) => i > 0 && t.toLowerCase() === 'u');
314
+ if (u < 0)
315
+ return tag;
316
+ let end = u + 1;
317
+ while (end < subtags.length && subtags[end].length > 1)
318
+ end++;
319
+ return [...subtags.slice(0, u), ...subtags.slice(end)].join('-');
320
+ }
321
+ const slots = new WeakMap();
322
+ /** %Intl%.[[FallbackSymbol]]: where the legacy constructor mode keeps the real instance. */
323
+ const FALLBACK = Symbol('IntlLegacyConstructedSymbol');
324
+ /** OrdinaryHasInstance(%NumberFormat%, value): the prototype chain, not Symbol.hasInstance. */
325
+ function inheritsFromNumberFormat(value) {
326
+ if ((typeof value !== 'object' || value === null) && typeof value !== 'function')
327
+ return false;
328
+ for (let p = Object.getPrototypeOf(value); p !== null; p = Object.getPrototypeOf(p))
329
+ if (p === prototype)
330
+ return true;
331
+ return false;
332
+ }
333
+ /** The receiver's slots; `unwrap` follows the legacy constructor mode's fallback (UnwrapNumberFormat). */
334
+ function slotsOf(value, method, unwrap = false) {
335
+ let found = typeof value === 'object' && value !== null ? slots.get(value) : undefined;
336
+ if (found === undefined && unwrap && inheritsFromNumberFormat(value)) {
337
+ const inner = value[FALLBACK];
338
+ found = typeof inner === 'object' && inner !== null ? slots.get(inner) : undefined;
339
+ }
340
+ if (found === undefined)
341
+ throw new TypeError(`Method Intl.NumberFormat.prototype.${method} called on incompatible receiver ${String(value)}`);
342
+ return found;
343
+ }
344
+ const nativeOf = (value, method, unwrap = false) => slotsOf(value, method, unwrap).native;
345
+ /**
346
+ * The native formatter behind a `NumberFormat`, which every instance with the
347
+ * same locales and options shares: a key for caching what is derived from one.
348
+ * @internal
349
+ */
350
+ export function sharedFormatterOf(value) {
351
+ return typeof value === 'object' && value !== null ? slots.get(value)?.native : undefined;
352
+ }
353
+ // `length` is 0 as the specification says: the arguments are read from `arguments`.
354
+ function NumberFormatConstructor() {
355
+ const locales = arguments[0];
356
+ const options = arguments[1];
357
+ if (new.target === undefined) {
358
+ const numberFormat = new NumberFormatConstructor(locales, options);
359
+ // ChainNumberFormat, the normative optional legacy mode: `NumberFormat.call(instance)` initializes it.
360
+ if (inheritsFromNumberFormat(this)) {
361
+ Object.defineProperty(this, FALLBACK, { value: numberFormat, writable: false, enumerable: false, configurable: false });
362
+ return this;
363
+ }
364
+ return numberFormat;
365
+ }
366
+ const { native, localeNumberingSystem } = createNative(locales, options);
367
+ slots.set(this, { native, localeNumberingSystem });
368
+ return this;
369
+ }
370
+ Object.defineProperty(NumberFormatConstructor, 'name', { value: 'NumberFormat' });
371
+ const prototype = NumberFormatConstructor.prototype;
372
+ export const NumberFormat = NumberFormatConstructor;
373
+ // MARK: - formatRange
374
+ /** CLDR's range separator where it is not "–" (en dash), by language or locale. */
375
+ const RANGE_SEPARATORS = {
376
+ 'bg': ' – ', 'bs': ' – ', 'ca': '-', 'da': '-', 'es': '-', 'et': '‒', 'eu': '-', 'fil': '-', 'gu': '-',
377
+ 'hr': ' – ', 'it': '-', 'ja': '~', 'ka': '-', 'ko': '~', 'mk': ' – ', 'ml': '-', 'my': ' - ',
378
+ 'nl': '-', 'pt-PT': ' - ', 'ro': ' - ', 'sk': ' – ', 'sq': '-', 'th': '-', 'vi': '-', 'zh': '-',
379
+ };
380
+ /** CLDR's approximately sign where it is not "~". */
381
+ const APPROXIMATELY_SIGNS = {
382
+ 'be': '≈', 'bs': '≈', 'de': '≈', 'et': '≈', 'fr': '≃', 'ja': '約', 'ka': '≈',
383
+ 'lt': '∼', 'mk': '≈', 'nb': 'ca.', 'ru': '≈', 'sq': '≈',
384
+ };
385
+ /** A locale's entry: the whole tag, then language-region, then the language. */
386
+ function localeData(locale, table, fallback) {
387
+ const subtags = locale.split('-');
388
+ const language = subtags[0];
389
+ const region = subtags.slice(1).find((t) => t.length === 2 || (t.length === 3 && t >= '000' && t <= '999'));
390
+ return table[locale] ?? (region ? table[`${language}-${region}`] : undefined) ?? table[language] ?? fallback;
391
+ }
392
+ const NUMBER_PARTS = new Set(['integer', 'group', 'decimal', 'fraction', 'nan', 'infinity', 'exponentSeparator', 'exponentMinusSign', 'exponentInteger']);
393
+ /** A formatted number split into the text before the number, the number, and the text after it. */
394
+ function splitNumber(parts) {
395
+ let first = parts.findIndex((p) => NUMBER_PARTS.has(p.type));
396
+ if (first < 0)
397
+ first = parts.length;
398
+ let last = first;
399
+ for (let i = first; i < parts.length; i++)
400
+ if (NUMBER_PARTS.has(parts[i].type))
401
+ last = i;
402
+ return { prefix: parts.slice(0, first), number: parts.slice(first, last + 1), suffix: parts.slice(last + 1) };
403
+ }
404
+ const text = (parts) => parts.map((p) => p.value).join('');
405
+ const codePoints = (parts) => [...text(parts)].length;
406
+ const withSource = (parts, source) => parts.map((p) => ({ type: p.type, value: p.value, source }));
407
+ function isNaNValue(value) {
408
+ return typeof value === 'number' ? Number.isNaN(value) : Number.isNaN(Number(value));
409
+ }
410
+ /** ICU's range formatting: a shared sign or currency longer than one character is written once. */
411
+ function formatRangeToParts(self, start, end) {
412
+ const native = nativeOf(self, 'formatRangeToParts');
413
+ if (start === undefined || end === undefined)
414
+ throw new TypeError('start and end are required');
415
+ const x = toMathematicalValue(start);
416
+ const y = toMathematicalValue(end);
417
+ if (isNaNValue(x) || isNaNValue(y))
418
+ throw new RangeError('start and end must not be NaN');
419
+ const xParts = native.formatToParts(x);
420
+ const yParts = native.formatToParts(y);
421
+ const locale = native.resolvedOptions().locale;
422
+ if (text(xParts) === text(yParts)) {
423
+ // FormatApproximately: the approximately sign goes before the sign, or in front of everything.
424
+ const sign = xParts.findIndex((p) => p.type === 'minusSign' || p.type === 'plusSign');
425
+ const parts = [...xParts];
426
+ parts.splice(Math.max(sign, 0), 0, { type: 'approximatelySign', value: localeData(locale, APPROXIMATELY_SIGNS, '~') });
427
+ return withSource(parts, 'shared');
428
+ }
429
+ const a = splitNumber(xParts);
430
+ const b = splitNumber(yParts);
431
+ let separator = localeData(locale, RANGE_SEPARATORS, '–');
432
+ const affixCount = codePoints(a.prefix) + codePoints(a.suffix);
433
+ const collapse = text(a.prefix) === text(b.prefix) && text(a.suffix) === text(b.suffix) && affixCount > 1;
434
+ if (collapse) {
435
+ return [
436
+ ...withSource(a.prefix, 'shared'),
437
+ ...withSource(a.number, 'startRange'),
438
+ { type: 'literal', value: separator, source: 'shared' },
439
+ ...withSource(b.number, 'endRange'),
440
+ ...withSource(a.suffix, 'shared'),
441
+ ];
442
+ }
443
+ // Repeated affixes get spaces around the separator.
444
+ if (affixCount > 0) {
445
+ const isSpace = (c) => c === ' ' || c === '\u00a0' || c === '\u2009' || c === '\u202f';
446
+ if (!isSpace(separator[0]))
447
+ separator = ' ' + separator;
448
+ if (!isSpace(separator[separator.length - 1]))
449
+ separator = separator + ' ';
450
+ }
451
+ return [...withSource(xParts, 'startRange'), { type: 'literal', value: separator, source: 'shared' }, ...withSource(yParts, 'endRange')];
452
+ }
453
+ // MARK: - The prototype
454
+ const methods = {
455
+ // A plain method, installed as the `format` getter below: an accessor
456
+ // written as `get format()` gets a `prototype` property in Hermes, which a
457
+ // built-in getter must not have.
458
+ formatGetter() {
459
+ const state = slotsOf(this, 'format', true);
460
+ const native = state.native;
461
+ let bound = state.boundFormat;
462
+ if (bound === undefined) {
463
+ // An arrow function: like the specification's bound format function, not a constructor.
464
+ bound = (value) => native.format(typeof value === 'number' ? value : toMathematicalValue(value));
465
+ Object.defineProperty(bound, 'name', { value: '' });
466
+ state.boundFormat = bound;
467
+ }
468
+ return bound;
469
+ },
470
+ formatToParts(value) {
471
+ const native = nativeOf(this, 'formatToParts');
472
+ return native.formatToParts(typeof value === 'number' ? value : toMathematicalValue(value)).map((p) => ({ type: p.type, value: p.value }));
473
+ },
474
+ formatRange(start, end) {
475
+ return formatRangeToParts(this, start, end)
476
+ .map((p) => p.value)
477
+ .join('');
478
+ },
479
+ formatRangeToParts(start, end) {
480
+ return formatRangeToParts(this, start, end);
481
+ },
482
+ resolvedOptions() {
483
+ const state = slotsOf(this, 'resolvedOptions', true);
484
+ const resolved = state.native.resolvedOptions();
485
+ // A -u-nu- that was honoured stays in the locale, as ResolveLocale keeps it.
486
+ const nu = state.localeNumberingSystem;
487
+ if (nu !== undefined && resolved.numberingSystem === nu)
488
+ resolved.locale = `${resolved.locale}-u-nu-${nu}`;
489
+ // A fresh object with only the options that apply, in the specified order.
490
+ const out = {};
491
+ for (const key of RESOLVED_ORDER)
492
+ if (resolved[key] !== undefined)
493
+ out[key] = resolved[key];
494
+ return out;
495
+ },
496
+ };
497
+ const RESOLVED_ORDER = [
498
+ 'locale', 'numberingSystem', 'style', 'currency', 'currencyDisplay', 'currencySign', 'unit', 'unitDisplay', 'minimumIntegerDigits',
499
+ 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits', 'useGrouping', 'notation',
500
+ 'compactDisplay', 'signDisplay', 'roundingIncrement', 'roundingMode', 'roundingPriority', 'trailingZeroDisplay',
501
+ ];
502
+ Object.defineProperty(methods.formatGetter, 'name', { value: 'get format' });
503
+ Object.defineProperty(prototype, 'format', { get: methods.formatGetter, enumerable: false, configurable: true });
504
+ for (const name of ['formatToParts', 'formatRange', 'formatRangeToParts', 'resolvedOptions']) {
505
+ Object.defineProperty(prototype, name, { value: methods[name], writable: true, enumerable: false, configurable: true });
506
+ }
507
+ Object.defineProperty(prototype, Symbol.toStringTag, { value: 'Intl.NumberFormat', writable: false, enumerable: false, configurable: true });
508
+ Object.defineProperty(NumberFormatConstructor, 'prototype', { writable: false, enumerable: false, configurable: false });
509
+ // supportedLocalesOf(locales [, options]): `length` 1, and a method, so not a constructor.
510
+ const statics = {
511
+ supportedLocalesOf(locales) {
512
+ const requested = canonicalizeLocaleList(locales);
513
+ const optionsArgument = arguments[1];
514
+ if (optionsArgument === null)
515
+ throw new TypeError('Cannot convert null to object');
516
+ const options = (optionsArgument === undefined ? Object.create(null) : Object(optionsArgument));
517
+ getOption(options, 'localeMatcher', ['lookup', 'best fit'], 'best fit');
518
+ return requested.length === 0 ? [] : getFactory().supportedLocalesOf(requested.map(withoutUnicodeExtension));
519
+ },
520
+ };
521
+ Object.defineProperty(NumberFormatConstructor, 'supportedLocalesOf', { value: statics.supportedLocalesOf, writable: true, enumerable: false, configurable: true });