react-native-nitro-input 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,6 @@
1
- import { NumberFormat, sharedFormatterOf } from './NumberFormat'
1
+ import { layoutOf, sharedFormatterOf, type NumberFormat } from './NumberFormat'
2
+
3
+ export { figureOf } from './NumberFormat'
2
4
 
3
5
  /** What `NitroNumber` and `NitroInput` take from a `NumberFormat` through their `format` prop. */
4
6
  export interface FormatProps {
@@ -6,7 +8,11 @@ export interface FormatProps {
6
8
  suffix: string
7
9
  groupingSeparator: string
8
10
  decimalSeparator: string
9
- /** The digits after the decimal separator: the format's maximum. */
11
+ /**
12
+ * The digits after the decimal separator: the format's maximum. What one
13
+ * value shows can be fewer (`trailingZeroDisplay`, a minimum below the
14
+ * maximum): `figureOf` says per value.
15
+ */
10
16
  fractionDigits: number
11
17
  minimumIntegerDigits: number
12
18
  /** Whether a negative amount's sign comes before the prefix ("-$5") or after it ("$-5"). */
@@ -21,47 +27,17 @@ export interface FormatProps {
21
27
  digitGlyphs: string[]
22
28
  /** The first digit group and every later one, from the decimal point ([3, 2]: 12,34,567). */
23
29
  groupingSizes: number[]
24
- /** Compact notation: the prefix, suffix and digits follow the value (`compactParts`). */
30
+ /** Compact notation: the prefix, suffix and digits follow the value (`figureOf`). */
25
31
  compact: boolean
26
32
  }
27
33
 
28
- const NUMBER_PARTS = new Set(['integer', 'group', 'decimal', 'fraction'])
29
34
  // By the native formatter, which instances built with the same locales and options share.
30
35
  const cache = new WeakMap<object, FormatProps>()
31
36
 
32
- type Part = { type: string; value: string }
33
-
34
- function join(parts: Part[], from: number, to: number): string {
35
- return parts
36
- .slice(from, to)
37
- .map((p) => p.value)
38
- .join('')
39
- }
40
-
41
- /** The text before and after the number in `parts`. */
42
- function affixes(parts: Part[]): { prefix: string; suffix: string } {
43
- const first = parts.findIndex((p) => NUMBER_PARTS.has(p.type))
44
- let last = first
45
- parts.forEach((p, i) => {
46
- if (NUMBER_PARTS.has(p.type)) last = i
47
- })
48
- // The sign is the component's own glyph, not part of an affix.
49
- const unsigned = (from: number, to: number) =>
50
- join(
51
- parts.map((p) => (p.type === 'minusSign' || p.type === 'plusSign' ? { ...p, value: '' } : p)),
52
- from,
53
- to
54
- )
55
- return {
56
- prefix: first < 0 ? '' : unsigned(0, first),
57
- suffix: first < 0 ? '' : unsigned(last + 1, parts.length),
58
- }
59
- }
60
-
61
37
  /**
62
- * The prefix, suffix, separators and digit counts of `format`, read off its
63
- * parts once and cached per formatter. The components keep their own model
64
- * (a sign, a prefix, digits in groups, a suffix), so a format outside it
38
+ * The prefix, suffix, separators and digit counts of `format`, read in C++
39
+ * off its parts once and cached per formatter. The components keep their own
40
+ * model (a sign, a prefix, digits in groups, a suffix), so a format outside it
65
41
  * (accounting parentheses, a unit between the digits) is followed as far as
66
42
  * that model goes.
67
43
  */
@@ -70,80 +46,64 @@ export function formatProps(format: NumberFormat): FormatProps {
70
46
  const cached = cache.get(key)
71
47
  if (cached) return cached
72
48
  const resolved = format.resolvedOptions()
73
- const compact = resolved.notation === 'compact'
74
- const fractionDigits = resolved.maximumFractionDigits ?? 0
75
- // A value with every part: groups, and a fraction when the format has one.
76
- // Compact notation would print it "1.2M", so its affixes come per value.
77
- const parts = format.formatToParts(compact ? 1 : fractionDigits > 0 ? 1234567.5 : 1234567) as Part[]
78
- const negative = format.formatToParts(-1) as Part[]
79
- const minus = negative.findIndex((p) => p.type === 'minusSign')
80
- const currency = negative.findIndex((p) => p.type === 'currency' || p.type === 'percentSign')
81
- const integers = parts.filter((p) => p.type === 'integer').map((p) => p.value.length)
49
+ const layout = layoutOf(format)
82
50
  const props: FormatProps = {
83
- ...affixes(parts),
84
- groupingSeparator: parts.find((p) => p.type === 'group')?.value ?? '',
85
- decimalSeparator: parts.find((p) => p.type === 'decimal')?.value ?? '.',
86
- fractionDigits,
51
+ prefix: layout.prefix,
52
+ suffix: layout.suffix,
53
+ groupingSeparator: layout.groupingSeparator,
54
+ decimalSeparator: layout.decimalSeparator,
55
+ fractionDigits: resolved.maximumFractionDigits ?? 0,
87
56
  minimumIntegerDigits: resolved.minimumIntegerDigits,
88
- signPlacement: minus >= 0 && currency >= 0 && minus > currency ? 'afterAffix' : 'beforeAffix',
57
+ signPlacement: layout.signAfterAffix ? 'afterAffix' : 'beforeAffix',
89
58
  signDisplay: (resolved.signDisplay ?? 'auto') as FormatProps['signDisplay'],
90
- minusSign: negative[minus]?.value ?? '-',
59
+ minusSign: layout.minusSign,
91
60
  plusSign: '+',
92
- digitGlyphs: digitGlyphsOf(resolved.locale, resolved.numberingSystem),
93
- // "12,34,567": the last group is the first size, the one before it every later one.
94
- groupingSizes: integers.length >= 3 ? [integers[integers.length - 1]!, integers[integers.length - 2]!] : [3],
95
- compact,
61
+ digitGlyphs: layout.digitGlyphs,
62
+ groupingSizes: layout.groupingSizes,
63
+ compact: resolved.notation === 'compact',
96
64
  }
97
65
  cache.set(key, props)
98
66
  return props
99
67
  }
100
68
 
101
- const digitGlyphCache = new Map<string, string[]>()
102
-
103
- /** The ten digits of a numbering system, or [] for Latin ones. */
104
- function digitGlyphsOf(locale: string, numberingSystem: string | undefined): string[] {
105
- if (!numberingSystem || numberingSystem === 'latn') return []
106
- const cached = digitGlyphCache.get(numberingSystem)
107
- if (cached) return cached
108
- const digits = new NumberFormat(locale, { numberingSystem, useGrouping: false })
109
- const glyphs = Array.from({ length: 10 }, (_, d) => digits.format(d))
110
- const result = glyphs.every((g, d) => g === String(d)) ? [] : glyphs
111
- digitGlyphCache.set(numberingSystem, result)
112
- return result
113
- }
114
-
115
- /** What a compact format shows for one value: the figure to roll and the text around it. */
116
- export interface CompactParts {
117
- /** The figure as the digits show it: 1.2 for "1.2K". */
118
- value: number
119
- fractionDigits: number
120
- prefix: string
121
- suffix: string
122
- }
69
+ /** A value as `NumberFormat` takes it: a number, a bigint or a decimal string. */
70
+ export type NumericInput = number | bigint | string
123
71
 
124
72
  /**
125
- * Compact notation's parts for `value`: "1.2K" is the figure 1.2 with the
126
- * suffix "K", so the digits roll and the suffix swaps as the value crosses
127
- * a thousand, a million…
73
+ * `value` read in units of 10^-`minorDigits`, exactly: 123456n with 2 minor
74
+ * digits is "1234.56". A bigint or a numeric string is shifted as text, so no
75
+ * digit goes through a double: a decimal ("1234.5"), one with an exponent
76
+ * ("1e5" becomes "1e3"), or a 0x / 0o / 0b integer, as `Intl.NumberFormat`
77
+ * reads strings. A number that is a safe integer is shifted the same way, any
78
+ * other number is divided. A string that is not a number ("1,234.56") comes
79
+ * back as it is, which the format shows as NaN, never as a wrong amount.
128
80
  */
129
- export function compactParts(format: NumberFormat, value: number): CompactParts {
130
- const parts = format.formatToParts(value) as Part[]
131
- const props = formatProps(format)
132
- const latin = (text: string) =>
133
- props.digitGlyphs.length === 10
134
- ? Array.from(text)
135
- .map((c) => {
136
- const d = props.digitGlyphs.indexOf(c)
137
- return d >= 0 ? String(d) : c
138
- })
139
- .join('')
140
- : text
141
- const integer = latin(parts.filter((p) => p.type === 'integer').map((p) => p.value).join(''))
142
- const fraction = latin(parts.filter((p) => p.type === 'fraction').map((p) => p.value).join(''))
143
- const magnitude = Number(fraction ? `${integer}.${fraction}` : integer)
144
- return {
145
- value: (value < 0 ? -1 : 1) * (Number.isFinite(magnitude) ? magnitude : 0),
146
- fractionDigits: fraction.length,
147
- ...affixes(parts),
81
+ export function withMinorDigits(value: NumericInput, minorDigits: number | undefined): NumericInput {
82
+ const digits = minorDigits === undefined ? 0 : Math.max(0, Math.trunc(minorDigits))
83
+ if (digits === 0) return value
84
+ if (typeof value === 'number') {
85
+ if (!Number.isSafeInteger(value)) return value / 10 ** digits
86
+ value = BigInt(value)
148
87
  }
88
+ let text = typeof value === 'bigint' ? value.toString() : value.trim()
89
+ if (/^0[xob][0-9a-f]+$/i.test(text)) {
90
+ // A non-decimal integer: BigInt reads it as Intl does, exactly.
91
+ text = BigInt(text).toString()
92
+ }
93
+ const match = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(text)
94
+ if (!match || (match[2] === '' && match[3] === undefined && text !== '')) return value
95
+ const [, sign = '', whole = '', fraction = '', exponent] = match
96
+ if (whole === '' && fraction === '' && text.includes('.')) return value
97
+ if (exponent !== undefined) {
98
+ // Moving the point is moving the exponent.
99
+ return `${sign}${whole}${fraction ? `.${fraction}` : ''}e${Number(exponent) - digits}`
100
+ }
101
+ const all = (whole + fraction).padStart(digits + fraction.length + 1, '0')
102
+ const point = all.length - fraction.length - digits
103
+ return `${sign}${all.slice(0, point)}.${all.slice(point)}`
104
+ }
105
+
106
+ /** `value` as a double, for comparisons and for the engine when there is no format. */
107
+ export function toNumber(value: NumericInput): number {
108
+ return typeof value === 'number' ? value : Number(value)
149
109
  }
@@ -69,6 +69,37 @@ export interface NumberFormatPart {
69
69
  value: string
70
70
  }
71
71
 
72
+ /**
73
+ * One value as `NitroNumber` rolls it: the figure its digits show, rounded and
74
+ * trimmed as the format prints it, and the text around it.
75
+ */
76
+ export interface NumberFigure {
77
+ /** 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. */
78
+ value: number
79
+ /** The fraction digits this value shows ("$1,234" 0, "$1,234.50" 2); the format's maximum for NaN and infinities. */
80
+ fractionDigits: number
81
+ /** The text before the number, without the sign. */
82
+ prefix: string
83
+ /** The text after the number, without the sign. */
84
+ suffix: string
85
+ }
86
+
87
+ /** The shape of a format, as `NitroNumber` and `NitroInput` lay a number out. */
88
+ export interface NumberFormatLayout {
89
+ prefix: string
90
+ suffix: string
91
+ /** Empty when the format does not group. */
92
+ groupingSeparator: string
93
+ decimalSeparator: string
94
+ /** A negative amount's sign comes after the prefix ("$-5"), not before it ("-$5"). */
95
+ signAfterAffix: boolean
96
+ minusSign: string
97
+ /** The group nearest the decimal point and every one before it ([3, 2]: 12,34,567). */
98
+ groupingSizes: number[]
99
+ /** The format's digits 0…9, or empty for Latin ones. */
100
+ digitGlyphs: string[]
101
+ }
102
+
72
103
  /**
73
104
  * A number formatter with the API of `Intl.NumberFormat`. It learns a
74
105
  * locale's format once from the platform (Foundation on iOS, ICU on Android)
@@ -80,6 +111,10 @@ export interface NitroNumberFormat extends HybridObject<{ ios: 'c++'; android: '
80
111
  format(value: number | Int64 | string): string
81
112
  formatToParts(value: number | Int64 | string): NumberFormatPart[]
82
113
  resolvedOptions(): ResolvedNumberFormatOptions
114
+ /** For the components, not part of `Intl.NumberFormat`: what `value` shows, as a figure. */
115
+ figure(value: number | Int64 | string): NumberFigure
116
+ /** For the components, not part of `Intl.NumberFormat`: the shape of the format. */
117
+ layout(): NumberFormatLayout
83
118
  }
84
119
 
85
120
  export interface NitroNumberFormatFactory extends HybridObject<{ ios: 'c++'; android: 'c++' }> {