raqam 0.3.2 → 0.4.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.
- package/README.md +25 -9
- package/dist/chunk-4GNLVHAM.js +2 -0
- package/dist/chunk-4GNLVHAM.js.map +1 -0
- package/dist/chunk-5LYK54TH.js +2 -0
- package/dist/chunk-5LYK54TH.js.map +1 -0
- package/dist/chunk-C5MK5U3F.js +2 -0
- package/dist/chunk-C5MK5U3F.js.map +1 -0
- package/dist/chunk-CAHEQQ5J.cjs +2 -0
- package/dist/chunk-CAHEQQ5J.cjs.map +1 -0
- package/dist/chunk-G7ACJUKH.js +2 -0
- package/dist/chunk-G7ACJUKH.js.map +1 -0
- package/dist/chunk-GAKIDRGS.cjs +2 -0
- package/dist/chunk-GAKIDRGS.cjs.map +1 -0
- package/dist/chunk-I3H3UMZD.cjs +2 -0
- package/dist/chunk-I3H3UMZD.cjs.map +1 -0
- package/dist/chunk-LD6OTXXT.js +2 -0
- package/dist/chunk-LD6OTXXT.js.map +1 -0
- package/dist/chunk-MNYIBO2M.cjs +2 -0
- package/dist/chunk-MNYIBO2M.cjs.map +1 -0
- package/dist/chunk-MOES3T6R.js +2 -0
- package/dist/chunk-MOES3T6R.js.map +1 -0
- package/dist/chunk-MUO4XNLX.cjs +2 -0
- package/dist/chunk-MUO4XNLX.cjs.map +1 -0
- package/dist/chunk-P6AWGQPY.js +2 -0
- package/dist/chunk-P6AWGQPY.js.map +1 -0
- package/dist/chunk-TFY7JMI6.js +2 -0
- package/dist/chunk-TFY7JMI6.js.map +1 -0
- package/dist/chunk-UYZYSVT5.cjs +2 -0
- package/dist/chunk-UYZYSVT5.cjs.map +1 -0
- package/dist/chunk-XJZHLJ2C.cjs +2 -0
- package/dist/chunk-XJZHLJ2C.cjs.map +1 -0
- package/dist/chunk-YUKLLK4G.cjs +2 -0
- package/dist/chunk-YUKLLK4G.cjs.map +1 -0
- package/dist/chunk-ZKLZ7UKZ.cjs +2 -0
- package/dist/chunk-ZKLZ7UKZ.cjs.map +1 -0
- package/dist/chunk-ZWDI6EPF.js +2 -0
- package/dist/chunk-ZWDI6EPF.js.map +1 -0
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +68 -295
- package/dist/core.d.ts +68 -295
- package/dist/core.js +1 -1
- package/dist/core.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -133
- package/dist/index.d.ts +12 -133
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/locales/ar.cjs +1 -35
- package/dist/locales/ar.cjs.map +1 -1
- package/dist/locales/ar.js +1 -3
- package/dist/locales/bn.cjs +1 -35
- package/dist/locales/bn.cjs.map +1 -1
- package/dist/locales/bn.js +1 -3
- package/dist/locales/fa.cjs +1 -37
- package/dist/locales/fa.cjs.map +1 -1
- package/dist/locales/fa.js +1 -3
- package/dist/locales/hi.cjs +1 -35
- package/dist/locales/hi.cjs.map +1 -1
- package/dist/locales/hi.js +1 -3
- package/dist/locales/index.cjs +1 -77
- package/dist/locales/index.cjs.map +1 -1
- package/dist/locales/index.js +1 -7
- package/dist/locales/th.cjs +1 -35
- package/dist/locales/th.cjs.map +1 -1
- package/dist/locales/th.js +1 -3
- package/dist/react.cjs +1 -1
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +117 -3
- package/dist/react.d.ts +117 -3
- package/dist/react.js +1 -1
- package/dist/react.js.map +1 -1
- package/dist/{index-BMFJwudG.d.cts → types-B2ZqkJI-.d.cts} +34 -107
- package/dist/{index-BMFJwudG.d.ts → types-B2ZqkJI-.d.ts} +34 -107
- package/package.json +28 -6
- package/dist/chunk-4AMLNJEK.js +0 -14
- package/dist/chunk-4AMLNJEK.js.map +0 -1
- package/dist/chunk-7IEJOMYT.js +0 -14
- package/dist/chunk-7IEJOMYT.js.map +0 -1
- package/dist/chunk-HPUEM7JB.js +0 -14
- package/dist/chunk-HPUEM7JB.js.map +0 -1
- package/dist/chunk-OLLREWX6.js +0 -16
- package/dist/chunk-OLLREWX6.js.map +0 -1
- package/dist/chunk-RP3DVBGJ.js +0 -14
- package/dist/chunk-RP3DVBGJ.js.map +0 -1
- package/dist/chunk-TISOJTKH.js +0 -25
- package/dist/chunk-TISOJTKH.js.map +0 -1
package/dist/core.d.ts
CHANGED
|
@@ -1,297 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
decimalSeparator: string;
|
|
4
|
-
/** Grouping (thousands) separator (e.g. "," en-US, "." de-DE, "٬" fa-IR) */
|
|
5
|
-
groupingSeparator: string;
|
|
6
|
-
/** Minus sign character (usually "-" but can differ) */
|
|
7
|
-
minusSign: string;
|
|
8
|
-
/** Locale's representation of "0" (e.g. "0" for Latin, "۰" for Persian) */
|
|
9
|
-
zero: string;
|
|
10
|
-
/** Whether this is an RTL locale */
|
|
11
|
-
isRTL: boolean;
|
|
12
|
-
}
|
|
13
|
-
interface FormatResult {
|
|
14
|
-
formatted: string;
|
|
15
|
-
parts: Intl.NumberFormatPart[];
|
|
16
|
-
}
|
|
17
|
-
interface ParseResult {
|
|
18
|
-
/** The parsed number, or null if empty / un-parseable */
|
|
19
|
-
value: number | null;
|
|
20
|
-
/** True for valid numbers */
|
|
21
|
-
isValid: boolean;
|
|
22
|
-
/**
|
|
23
|
-
* True for valid-but-incomplete input that must not be reformatted yet:
|
|
24
|
-
* "-", "1.", "1.0", "1.00", etc.
|
|
25
|
-
*/
|
|
26
|
-
isIntermediate: boolean;
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* boolean[] of length formattedValue.length + 1.
|
|
30
|
-
* true → cursor may rest at this index
|
|
31
|
-
* false → cursor must not rest here (e.g. inside a thousands separator)
|
|
32
|
-
*/
|
|
33
|
-
type CaretBoundary = boolean[];
|
|
34
|
-
/** Unicode codepoint range [start, end] inclusive representing a digit block */
|
|
35
|
-
type DigitBlock = readonly [number, number];
|
|
36
|
-
interface UseNumberFieldStateOptions {
|
|
37
|
-
/** Controlled numeric value */
|
|
38
|
-
value?: number | null;
|
|
39
|
-
/** Uncontrolled default value */
|
|
40
|
-
defaultValue?: number | null;
|
|
41
|
-
/** Fires on every meaningful value change */
|
|
42
|
-
onChange?: (value: number | null) => void;
|
|
43
|
-
/** BCP 47 locale tag (default: browser locale) */
|
|
44
|
-
locale?: string;
|
|
45
|
-
/** Full Intl.NumberFormatOptions — currency, percent, decimal, etc. */
|
|
46
|
-
formatOptions?: Intl.NumberFormatOptions;
|
|
47
|
-
/** Minimum allowed value */
|
|
48
|
-
minValue?: number;
|
|
49
|
-
/** Maximum allowed value */
|
|
50
|
-
maxValue?: number;
|
|
51
|
-
/** Step amount for increment/decrement (default: 1) */
|
|
52
|
-
step?: number;
|
|
53
|
-
/** Large step — Shift+Arrow / PageUp/Down (default: step * 10) */
|
|
54
|
-
largeStep?: number;
|
|
55
|
-
/** Small step — Meta/Ctrl+Arrow (default: step * 0.1) */
|
|
56
|
-
smallStep?: number;
|
|
57
|
-
/** Allow negative values (default: true) */
|
|
58
|
-
allowNegative?: boolean;
|
|
59
|
-
/** Allow decimal values (default: true) */
|
|
60
|
-
allowDecimal?: boolean;
|
|
61
|
-
/** Override maximumFractionDigits from formatOptions */
|
|
62
|
-
maximumFractionDigits?: number;
|
|
63
|
-
/** Override minimumFractionDigits from formatOptions */
|
|
64
|
-
minimumFractionDigits?: number;
|
|
65
|
-
/** Always show exactly maximumFractionDigits decimal places */
|
|
66
|
-
fixedDecimalScale?: boolean;
|
|
67
|
-
/** When clamping happens (default: "blur") */
|
|
68
|
-
clampBehavior?: "blur" | "strict" | "none";
|
|
69
|
-
/** Apply live formatting while typing (default: true) */
|
|
70
|
-
liveFormat?: boolean;
|
|
71
|
-
/** Arbitrary prefix string (e.g. "$") */
|
|
72
|
-
prefix?: string;
|
|
73
|
-
/** Arbitrary suffix string (e.g. " تومان") */
|
|
74
|
-
suffix?: string;
|
|
75
|
-
/** Disable the field */
|
|
76
|
-
disabled?: boolean;
|
|
77
|
-
/** Make the field read-only */
|
|
78
|
-
readOnly?: boolean;
|
|
79
|
-
/** Mark the field as required */
|
|
80
|
-
required?: boolean;
|
|
81
|
-
/**
|
|
82
|
-
* Allow values outside min/max to be typed and committed without clamping.
|
|
83
|
-
* Useful when server-side validation handles clamping.
|
|
84
|
-
* When true, aria-invalid is set when value is out of range.
|
|
85
|
-
* default: false
|
|
86
|
-
*/
|
|
87
|
-
allowOutOfRange?: boolean;
|
|
88
|
-
/**
|
|
89
|
-
* Custom validation function. Called on every value change.
|
|
90
|
-
* - Return `true` or `null`/`undefined` → valid
|
|
91
|
-
* - Return `false` → invalid (aria-invalid set, no error message)
|
|
92
|
-
* - Return a `string` → invalid with that string as the error message
|
|
93
|
-
*/
|
|
94
|
-
validate?: (value: number | null) => boolean | string | null | undefined;
|
|
95
|
-
/**
|
|
96
|
-
* Fires with the raw unformatted string the user typed, preserving full
|
|
97
|
-
* decimal precision before JS float conversion. Useful for financial apps
|
|
98
|
-
* that need arbitrary-precision string arithmetic.
|
|
99
|
-
* Fires alongside `onChange`.
|
|
100
|
-
*/
|
|
101
|
-
onRawChange?: (rawValue: string | null) => void;
|
|
102
|
-
/**
|
|
103
|
-
* Custom format function. When provided, replaces the built-in Intl.NumberFormat
|
|
104
|
-
* formatter for display purposes. Also used for initial display value.
|
|
105
|
-
*/
|
|
106
|
-
formatValue?: (value: number) => string;
|
|
107
|
-
/**
|
|
108
|
-
* Custom parse function. When provided, replaces the built-in locale-aware parser.
|
|
109
|
-
* Must return `{ value: number | null, isIntermediate: boolean }`.
|
|
110
|
-
*/
|
|
111
|
-
parseValue?: (input: string) => {
|
|
112
|
-
value: number | null;
|
|
113
|
-
isIntermediate: boolean;
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
interface NumberFieldState {
|
|
117
|
-
/** The display string shown in the input */
|
|
118
|
-
inputValue: string;
|
|
119
|
-
/** The parsed numeric value (null for empty/invalid) */
|
|
120
|
-
numberValue: number | null;
|
|
121
|
-
/**
|
|
122
|
-
* The raw string value exactly as the user typed it (before formatting).
|
|
123
|
-
* Preserves full decimal precision — useful for financial arbitrary-precision math.
|
|
124
|
-
*/
|
|
125
|
-
rawValue: string | null;
|
|
126
|
-
/** Whether increment is currently possible */
|
|
127
|
-
canIncrement: boolean;
|
|
128
|
-
/** Whether decrement is currently possible */
|
|
129
|
-
canDecrement: boolean;
|
|
130
|
-
/** Whether the ScrubArea is currently being dragged */
|
|
131
|
-
isScrubbing: boolean;
|
|
132
|
-
/** Update the isScrubbing state (called by useScrubArea) */
|
|
133
|
-
setIsScrubbing: (val: boolean) => void;
|
|
134
|
-
/** Whether the input is currently focused */
|
|
135
|
-
isFocused: boolean;
|
|
136
|
-
/** Update the isFocused state (called by useNumberField) */
|
|
137
|
-
setIsFocused: (val: boolean) => void;
|
|
138
|
-
/** Current validation state — 'valid' if no validate prop, or based on validate result */
|
|
139
|
-
validationState: "valid" | "invalid";
|
|
140
|
-
/** Error message from validate() if it returned a string, otherwise null */
|
|
141
|
-
validationError: string | null;
|
|
142
|
-
/** Internal: set the reason for the next onChange call (used by useNumberField) */
|
|
143
|
-
_setLastChangeReason: (reason: ChangeReason) => void;
|
|
144
|
-
/** Internal: read the current change reason (used by NumberField.Root) */
|
|
145
|
-
_getLastChangeReason: () => ChangeReason;
|
|
146
|
-
/**
|
|
147
|
-
* Update display string (triggers parse + onChange). `knownValue` overrides
|
|
148
|
-
* the parsed value when `val` is a formatted string that cannot be reversed
|
|
149
|
-
* (compact "2.5K", scientific, unit notation).
|
|
150
|
-
*/
|
|
151
|
-
setInputValue: (val: string, knownValue?: number | null) => void;
|
|
152
|
-
/** Directly set the numeric value (triggers format + onChange) */
|
|
153
|
-
setNumberValue: (val: number | null) => void;
|
|
154
|
-
/** Format + clamp on blur — call from onBlur. Returns the committed numeric value. */
|
|
155
|
-
commit: () => number | null;
|
|
156
|
-
/** Increment by step */
|
|
157
|
-
increment: (amount?: number) => void;
|
|
158
|
-
/** Decrement by step */
|
|
159
|
-
decrement: (amount?: number) => void;
|
|
160
|
-
/** Jump to maxValue */
|
|
161
|
-
incrementToMax: () => void;
|
|
162
|
-
/** Jump to minValue */
|
|
163
|
-
decrementToMin: () => void;
|
|
164
|
-
/** Raw options (for hooks that need them) */
|
|
165
|
-
options: UseNumberFieldStateOptions;
|
|
166
|
-
}
|
|
167
|
-
/** Reason for a value change — propagated through onValueChange details */
|
|
168
|
-
type ChangeReason = "input" | "clear" | "blur" | "paste" | "keyboard" | "increment" | "decrement" | "wheel" | "scrub";
|
|
169
|
-
interface UseNumberFieldProps extends UseNumberFieldStateOptions {
|
|
170
|
-
/** Visible label text (used for aria-label fallback) */
|
|
171
|
-
label?: string;
|
|
172
|
-
"aria-label"?: string;
|
|
173
|
-
"aria-describedby"?: string;
|
|
174
|
-
"aria-labelledby"?: string;
|
|
175
|
-
/** Form field name — renders a hidden input */
|
|
176
|
-
name?: string;
|
|
177
|
-
/** id for the input element */
|
|
178
|
-
id?: string;
|
|
179
|
-
/** Enable mouse-wheel increment/decrement */
|
|
180
|
-
allowMouseWheel?: boolean;
|
|
181
|
-
/**
|
|
182
|
-
* Controls what is placed in the clipboard on copy/cut.
|
|
183
|
-
* - 'formatted' (default): browser-native copy of display string
|
|
184
|
-
* - 'raw': numberValue as a plain JS number string (e.g. "1234.56")
|
|
185
|
-
* - 'number': alias for 'raw'
|
|
186
|
-
*/
|
|
187
|
-
copyBehavior?: "formatted" | "raw" | "number";
|
|
188
|
-
/** Milliseconds before press-and-hold repeat starts (default: 400) */
|
|
189
|
-
stepHoldDelay?: number;
|
|
190
|
-
/** Initial milliseconds between repeats during press-and-hold (default: 200) */
|
|
191
|
-
stepHoldInterval?: number;
|
|
192
|
-
onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void;
|
|
193
|
-
onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
|
|
194
|
-
/**
|
|
195
|
-
* Fires only when the value is committed — i.e. on blur, or when the user
|
|
196
|
-
* presses Enter — after formatting and clamping have been applied.
|
|
197
|
-
* `reason` is `"blur"` for focus loss and `"keyboard"` for Enter.
|
|
198
|
-
* Reach for this (instead of `onChange`) when you only care about the final,
|
|
199
|
-
* settled value: persisting it, validating server-side, firing a request, etc.
|
|
200
|
-
*/
|
|
201
|
-
onValueCommitted?: (value: number | null, details: {
|
|
202
|
-
reason: "blur" | "keyboard";
|
|
203
|
-
}) => void;
|
|
204
|
-
}
|
|
205
|
-
interface NumberFieldAria {
|
|
206
|
-
/**
|
|
207
|
-
* Props for the label element. Includes a `ref` callback that registers the
|
|
208
|
-
* label's presence with the hook — spread it onto whatever element you render
|
|
209
|
-
* as the label (built-in `<NumberField.Label>` or a custom primitive) so the
|
|
210
|
-
* input/group keep their `aria-labelledby` wiring and avoid dangling refs.
|
|
211
|
-
*/
|
|
212
|
-
labelProps: React.LabelHTMLAttributes<HTMLLabelElement> & {
|
|
213
|
-
ref?: React.RefCallback<HTMLElement>;
|
|
214
|
-
};
|
|
215
|
-
groupProps: React.HTMLAttributes<HTMLDivElement>;
|
|
216
|
-
inputProps: React.InputHTMLAttributes<HTMLInputElement>;
|
|
217
|
-
hiddenInputProps: React.InputHTMLAttributes<HTMLInputElement> | null;
|
|
218
|
-
incrementButtonProps: React.ButtonHTMLAttributes<HTMLButtonElement>;
|
|
219
|
-
decrementButtonProps: React.ButtonHTMLAttributes<HTMLButtonElement>;
|
|
220
|
-
descriptionProps: React.HTMLAttributes<HTMLElement>;
|
|
221
|
-
errorMessageProps: React.HTMLAttributes<HTMLElement>;
|
|
222
|
-
}
|
|
223
|
-
type StateRenderFn = (props: Record<string, unknown>, state: NumberFieldState) => React.ReactElement;
|
|
224
|
-
type RenderProp = React.ReactElement | StateRenderFn;
|
|
225
|
-
interface NumberFieldRootProps extends UseNumberFieldProps {
|
|
226
|
-
children?: React.ReactNode;
|
|
227
|
-
/** CSS class for the root wrapper div */
|
|
228
|
-
className?: string;
|
|
229
|
-
/** Inline style for the root wrapper div */
|
|
230
|
-
style?: React.CSSProperties;
|
|
231
|
-
/** Fires on every meaningful value change */
|
|
232
|
-
onValueChange?: (value: number | null, details: {
|
|
233
|
-
reason: ChangeReason;
|
|
234
|
-
formattedValue: string;
|
|
235
|
-
event?: React.SyntheticEvent;
|
|
236
|
-
}) => void;
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
/**
|
|
240
|
-
* Format presets — named Intl.NumberFormatOptions configurations for common
|
|
241
|
-
* number input patterns. Use these as the `formatOptions` prop value.
|
|
242
|
-
*
|
|
243
|
-
* @example
|
|
244
|
-
* import { presets } from 'raqam'
|
|
245
|
-
* <NumberField.Root formatOptions={presets.currency('USD')} />
|
|
246
|
-
* <NumberField.Root formatOptions={presets.percent} />
|
|
247
|
-
* <NumberField.Root formatOptions={presets.compact} />
|
|
248
|
-
*/
|
|
249
|
-
declare const presets: {
|
|
250
|
-
/** Currency with standard sign display. Shorthand for `{ style:'currency', currency:code }`. */
|
|
251
|
-
readonly currency: (code: string) => Intl.NumberFormatOptions;
|
|
252
|
-
/**
|
|
253
|
-
* Accounting currency — negatives shown as `(1,234.56)` instead of `-$1,234.56`.
|
|
254
|
-
* Requires the accounting format parser fix (built-in to raqam).
|
|
255
|
-
*/
|
|
256
|
-
readonly accounting: (code: string) => Intl.NumberFormatOptions;
|
|
257
|
-
/** Percentage — formats 0.42 as "42%" */
|
|
258
|
-
readonly percent: Intl.NumberFormatOptions;
|
|
259
|
-
/** Compact short — "1.2K", "3.4M" */
|
|
260
|
-
readonly compact: Intl.NumberFormatOptions;
|
|
261
|
-
/** Compact long — "1.2 thousand", "3.4 million" */
|
|
262
|
-
readonly compactLong: Intl.NumberFormatOptions;
|
|
263
|
-
/** Scientific notation — "1.234E3" */
|
|
264
|
-
readonly scientific: Intl.NumberFormatOptions;
|
|
265
|
-
/** Engineering notation — exponents always multiples of 3 */
|
|
266
|
-
readonly engineering: Intl.NumberFormatOptions;
|
|
267
|
-
/** Integer — no decimal places */
|
|
268
|
-
readonly integer: Intl.NumberFormatOptions;
|
|
269
|
-
/**
|
|
270
|
-
* Financial — always exactly 2 decimal places (fixed scale).
|
|
271
|
-
* Combine with `fixedDecimalScale` prop for strict display.
|
|
272
|
-
*/
|
|
273
|
-
readonly financial: Intl.NumberFormatOptions;
|
|
274
|
-
/**
|
|
275
|
-
* Unit — shorthand for `{ style:'unit', unit:unitCode }`.
|
|
276
|
-
* @example presets.unit('kilometer-per-hour') → { style:'unit', unit:'kilometer-per-hour' }
|
|
277
|
-
*/
|
|
278
|
-
readonly unit: (unit: string) => Intl.NumberFormatOptions;
|
|
279
|
-
};
|
|
280
|
-
|
|
281
|
-
interface LocaleConfig {
|
|
282
|
-
/** Extra digit block ranges to register */
|
|
283
|
-
digitBlocks?: DigitBlock[];
|
|
284
|
-
}
|
|
285
|
-
/**
|
|
286
|
-
* Register additional digit blocks (called by locale plugins as a side effect).
|
|
287
|
-
* Duplicate ranges are silently ignored.
|
|
288
|
-
*/
|
|
289
|
-
declare function registerLocale(config: LocaleConfig): void;
|
|
290
|
-
/**
|
|
291
|
-
* Normalise any Unicode decimal digit in `input` to its ASCII equivalent (0–9).
|
|
292
|
-
* Non-digit characters pass through unchanged.
|
|
293
|
-
*/
|
|
294
|
-
declare function normalizeDigits(input: string): string;
|
|
1
|
+
import { L as LocaleInfo, F as FormatResult, P as ParseResult, D as DigitBlock, C as CaretBoundary } from './types-B2ZqkJI-.js';
|
|
2
|
+
export { a as ChangeReason, b as NumberFieldAria, c as NumberFieldRootProps, N as NumberFieldState, R as RenderProp, f as StateRenderFn, U as UseNumberFieldProps, g as UseNumberFieldStateOptions } from './types-B2ZqkJI-.js';
|
|
295
3
|
|
|
296
4
|
interface FormatterOptions {
|
|
297
5
|
locale?: string;
|
|
@@ -326,6 +34,14 @@ interface Parser {
|
|
|
326
34
|
parse(input: string): ParseResult;
|
|
327
35
|
isIntermediate(input: string): boolean;
|
|
328
36
|
getLocaleInfo(): LocaleInfo;
|
|
37
|
+
/**
|
|
38
|
+
* Strip formatting affordances (grouping separators, currency symbol, prefix/
|
|
39
|
+
* suffix, percent sign…) from `input`, returning the bare numeric string
|
|
40
|
+
* (ASCII digits, an optional leading "-", and at most one "."). Trailing zeros
|
|
41
|
+
* the user typed are preserved. Useful for deriving a precision-preserving raw
|
|
42
|
+
* value from a formatted display string.
|
|
43
|
+
*/
|
|
44
|
+
strip(input: string): string;
|
|
329
45
|
}
|
|
330
46
|
/**
|
|
331
47
|
* Create a locale-aware parser. Separator characters are extracted from
|
|
@@ -333,6 +49,21 @@ interface Parser {
|
|
|
333
49
|
*/
|
|
334
50
|
declare function createParser(opts?: ParserOptions): Parser;
|
|
335
51
|
|
|
52
|
+
interface LocaleConfig {
|
|
53
|
+
/** Extra digit block ranges to register */
|
|
54
|
+
digitBlocks?: DigitBlock[];
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Register additional digit blocks (called by locale plugins as a side effect).
|
|
58
|
+
* Duplicate ranges are silently ignored.
|
|
59
|
+
*/
|
|
60
|
+
declare function registerLocale(config: LocaleConfig): void;
|
|
61
|
+
/**
|
|
62
|
+
* Normalise any Unicode decimal digit in `input` to its ASCII equivalent (0–9).
|
|
63
|
+
* Non-digit characters pass through unchanged.
|
|
64
|
+
*/
|
|
65
|
+
declare function normalizeDigits(input: string): string;
|
|
66
|
+
|
|
336
67
|
/**
|
|
337
68
|
* Build a boolean array of length `formattedValue.length + 1`.
|
|
338
69
|
* `true` → cursor may rest at this position.
|
|
@@ -366,4 +97,46 @@ declare function getCaretBoundary(formattedValue: string, info: LocaleInfo): Car
|
|
|
366
97
|
*/
|
|
367
98
|
declare function computeNewCursorPosition(oldInput: string, oldCursor: number, newFormatted: string, info: LocaleInfo, inputType?: string): number;
|
|
368
99
|
|
|
369
|
-
|
|
100
|
+
/**
|
|
101
|
+
* Format presets — named Intl.NumberFormatOptions configurations for common
|
|
102
|
+
* number input patterns. Use these as the `formatOptions` prop value.
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* import { presets } from 'raqam'
|
|
106
|
+
* <NumberField.Root formatOptions={presets.currency('USD')} />
|
|
107
|
+
* <NumberField.Root formatOptions={presets.percent} />
|
|
108
|
+
* <NumberField.Root formatOptions={presets.compact} />
|
|
109
|
+
*/
|
|
110
|
+
declare const presets: {
|
|
111
|
+
/** Currency with standard sign display. Shorthand for `{ style:'currency', currency:code }`. */
|
|
112
|
+
readonly currency: (code: string) => Intl.NumberFormatOptions;
|
|
113
|
+
/**
|
|
114
|
+
* Accounting currency — negatives shown as `(1,234.56)` instead of `-$1,234.56`.
|
|
115
|
+
* Requires the accounting format parser fix (built-in to raqam).
|
|
116
|
+
*/
|
|
117
|
+
readonly accounting: (code: string) => Intl.NumberFormatOptions;
|
|
118
|
+
/** Percentage — formats 0.42 as "42%" */
|
|
119
|
+
readonly percent: Intl.NumberFormatOptions;
|
|
120
|
+
/** Compact short — "1.2K", "3.4M" */
|
|
121
|
+
readonly compact: Intl.NumberFormatOptions;
|
|
122
|
+
/** Compact long — "1.2 thousand", "3.4 million" */
|
|
123
|
+
readonly compactLong: Intl.NumberFormatOptions;
|
|
124
|
+
/** Scientific notation — "1.234E3" */
|
|
125
|
+
readonly scientific: Intl.NumberFormatOptions;
|
|
126
|
+
/** Engineering notation — exponents always multiples of 3 */
|
|
127
|
+
readonly engineering: Intl.NumberFormatOptions;
|
|
128
|
+
/** Integer — no decimal places */
|
|
129
|
+
readonly integer: Intl.NumberFormatOptions;
|
|
130
|
+
/**
|
|
131
|
+
* Financial — always exactly 2 decimal places (fixed scale).
|
|
132
|
+
* Combine with `fixedDecimalScale` prop for strict display.
|
|
133
|
+
*/
|
|
134
|
+
readonly financial: Intl.NumberFormatOptions;
|
|
135
|
+
/**
|
|
136
|
+
* Unit — shorthand for `{ style:'unit', unit:unitCode }`.
|
|
137
|
+
* @example presets.unit('kilometer-per-hour') → { style:'unit', unit:'kilometer-per-hour' }
|
|
138
|
+
*/
|
|
139
|
+
readonly unit: (unit: string) => Intl.NumberFormatOptions;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export { CaretBoundary, DigitBlock, FormatResult, type Formatter, type FormatterOptions, type LocaleConfig, LocaleInfo, ParseResult, type Parser, type ParserOptions, computeNewCursorPosition, createFormatter, createParser, getCaretBoundary, normalizeDigits, presets, registerLocale };
|
package/dist/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
export{a as presets}from'./chunk-ZWDI6EPF.js';export{e as computeNewCursorPosition,b as createFormatter,c as createParser,d as getCaretBoundary}from'./chunk-P6AWGQPY.js';export{b as normalizeDigits,a as registerLocale}from'./chunk-4GNLVHAM.js';//# sourceMappingURL=core.js.map
|
|
2
2
|
//# sourceMappingURL=core.js.map
|
package/dist/core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/presets.ts","../src/core/normalizer.ts","../src/core/formatter.ts","../src/core/parser.ts","../src/core/cursor.ts"],"names":["presets","code","unit","BUILTIN_DIGIT_BLOCKS","registeredBlocks","registerLocale","config","block","s","normalizeDigits","input","ch","start","end","digit","formatterCache","getFormatter","locale","options","key","fmt","extractLocaleInfo","styledFmt","probeFmt","parts","decimalSeparator","groupingSeparator","minusSign","zero","part","rtlLocales","resolvedLocale","isRTL","createFormatter","opts","intlOptions","intlFmt","cachedLocaleInfo","getLocaleInfo","formatToParts","value","result","format","formatted","formatResult","p","isIntermediateStripped","stripped","allowDecimal","createParser","allowNegative","isPercent","currencySymbol","stripAffordances","raw","info","accountingMatch","negative","parse","n","isIntermediate","isAccepted","countAcceptedBefore","str","cursor","normalised","count","i","getCaretBoundary","formattedValue","len","boundary","computeNewCursorPosition","oldInput","oldCursor","newFormatted","inputType","acceptedCount","before","minusBeforeCaret","newHasMinus","normNew","pos","snapToBoundary"],"mappings":"AAWO,IAAMA,CAAAA,CAAU,CAErB,QAAA,CAAWC,CAAAA,GAA4C,CACrD,KAAA,CAAO,UAAA,CACP,QAAA,CAAUA,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,CAAA,CAE3BW,CACT,CAMA,SAASC,CAAAA,CAAeD,CAAAA,CAAaX,CAAAA,CAAiC,CACpE,GAAIA,CAAAA,CAASW,CAAG,CAAA,CAAG,OAAOA,CAAAA,CAG1B,IAAA,IAAS,CAAA,CAAIA,CAAAA,CAAM,EAAG,CAAA,CAAIX,CAAAA,CAAS,MAAA,CAAQ,CAAA,EAAA,CACzC,GAAIA,CAAAA,CAAS,CAAC,CAAA,CAAG,OAAO,CAAA,CAG1B,IAAA,IAAS,CAAA,CAAIW,CAAAA,CAAM,EAAG,CAAA,EAAK,CAAA,CAAG,CAAA,EAAA,CAC5B,GAAIX,EAAS,CAAC,CAAA,CAAG,OAAO,CAAA,CAE1B,OAAO,CACT","file":"core.js","sourcesContent":["/**\n * Format presets — named Intl.NumberFormatOptions configurations for common\n * number input patterns. Use these as the `formatOptions` prop value.\n *\n * @example\n * import { presets } from 'raqam'\n * <NumberField.Root formatOptions={presets.currency('USD')} />\n * <NumberField.Root formatOptions={presets.percent} />\n * <NumberField.Root formatOptions={presets.compact} />\n */\n\nexport const presets = {\n /** Currency with standard sign display. Shorthand for `{ style:'currency', currency:code }`. */\n currency: (code: string): Intl.NumberFormatOptions => ({\n style: \"currency\",\n currency: code,\n }),\n\n /**\n * Accounting currency — negatives shown as `(1,234.56)` instead of `-$1,234.56`.\n * Requires the accounting format parser fix (built-in to raqam).\n */\n accounting: (code: string): Intl.NumberFormatOptions => ({\n style: \"currency\",\n currency: code,\n currencySign: \"accounting\",\n }),\n\n /** Percentage — formats 0.42 as \"42%\" */\n percent: { style: \"percent\" } as Intl.NumberFormatOptions,\n\n /** Compact short — \"1.2K\", \"3.4M\" */\n compact: { notation: \"compact\" } as Intl.NumberFormatOptions,\n\n /** Compact long — \"1.2 thousand\", \"3.4 million\" */\n compactLong: {\n notation: \"compact\",\n compactDisplay: \"long\",\n } as Intl.NumberFormatOptions,\n\n /** Scientific notation — \"1.234E3\" */\n scientific: { notation: \"scientific\" } as Intl.NumberFormatOptions,\n\n /** Engineering notation — exponents always multiples of 3 */\n engineering: { notation: \"engineering\" } as Intl.NumberFormatOptions,\n\n /** Integer — no decimal places */\n integer: { maximumFractionDigits: 0 } as Intl.NumberFormatOptions,\n\n /**\n * Financial — always exactly 2 decimal places (fixed scale).\n * Combine with `fixedDecimalScale` prop for strict display.\n */\n financial: {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n } as Intl.NumberFormatOptions,\n\n /**\n * Unit — shorthand for `{ style:'unit', unit:unitCode }`.\n * @example presets.unit('kilometer-per-hour') → { style:'unit', unit:'kilometer-per-hour' }\n */\n unit: (unit: string): Intl.NumberFormatOptions => ({\n style: \"unit\",\n unit,\n }),\n} as const;\n","import type { DigitBlock } from \"./types.js\";\n\n// ── Built-in digit blocks ────────────────────────────────────────────────────\n// These cover the digit systems required by the spec.\n// Additional blocks can be registered via registerLocale().\n\nconst BUILTIN_DIGIT_BLOCKS: DigitBlock[] = [\n [0x0660, 0x0669], // Arabic-Indic (arab)\n [0x06f0, 0x06f9], // Extended Arabic-Indic / Persian (arabext)\n [0x0966, 0x096f], // Devanagari / Hindi (deva)\n [0x09e6, 0x09ef], // Bengali (beng)\n [0x0e50, 0x0e59], // Thai (thai)\n];\n\n// Mutable registry — locale plugins can add blocks here\nconst registeredBlocks: DigitBlock[] = [...BUILTIN_DIGIT_BLOCKS];\n\n// ── Public API ────────────────────────────────────────────────────────────────\n\nexport interface LocaleConfig {\n /** Extra digit block ranges to register */\n digitBlocks?: DigitBlock[];\n}\n\n/**\n * Register additional digit blocks (called by locale plugins as a side effect).\n * Duplicate ranges are silently ignored.\n */\nexport function registerLocale(config: LocaleConfig): void {\n if (!config.digitBlocks) return;\n for (const block of config.digitBlocks) {\n const already = registeredBlocks.some(([s]) => s === block[0]);\n if (!already) registeredBlocks.push(block);\n }\n}\n\n/**\n * Normalise any Unicode decimal digit in `input` to its ASCII equivalent (0–9).\n * Non-digit characters pass through unchanged.\n */\nexport function normalizeDigits(input: string): string {\n // Fast path: if there are no non-ASCII chars, return as-is\n if (!/[^\\u0020-\\u007e]/.test(input)) return input;\n\n return input.replace(/\\p{Nd}/gu, (ch) => {\n const code = ch.codePointAt(0)!;\n for (const [start, end] of registeredBlocks) {\n if (code >= start && code <= end) {\n return String(code - start);\n }\n }\n // Fallback: let JS try to parse it as a decimal digit\n const digit = Number.parseInt(ch, 10);\n return Number.isNaN(digit) ? ch : String(digit);\n });\n}\n\n/**\n * Inverse of {@link normalizeDigits}: map ASCII digits 0–9 to the locale's\n * native digit block (identified by its \"zero\" character). No-op when the\n * locale already uses ASCII digits. Used to keep intermediate (still-typing)\n * display strings in the user's native script.\n */\nexport function localizeDigits(input: string, zero: string): string {\n if (!zero || zero === \"0\") return input;\n const base = zero.codePointAt(0);\n if (base === undefined) return input;\n return input.replace(/[0-9]/g, (d) => String.fromCodePoint(base + (d.charCodeAt(0) - 48)));\n}\n\n/**\n * Returns true if the character is a non-Latin Unicode decimal digit\n * (i.e. would need normalization).\n */\nexport function isNonLatinDigit(ch: string): boolean {\n const code = ch.codePointAt(0);\n if (code === undefined) return false;\n if (code >= 0x30 && code <= 0x39) return false; // ASCII 0-9\n for (const [start, end] of registeredBlocks) {\n if (code >= start && code <= end) return true;\n }\n return false;\n}\n","import type { FormatResult, LocaleInfo } from \"./types.js\";\n\n// ── Internal ──────────────────────────────────────────────────────────────────\n\n/** Probe value that will surface decimal AND grouping parts */\nconst PROBE_VALUE = 12345.6;\n\n/** Cache key = locale + JSON.stringify(options) */\nconst formatterCache = new Map<string, Intl.NumberFormat>();\n\nfunction getFormatter(\n locale: string | undefined,\n options: Intl.NumberFormatOptions | undefined\n): Intl.NumberFormat {\n const key = `${locale ?? \"\"}::${JSON.stringify(options ?? {})}`;\n let fmt = formatterCache.get(key);\n if (!fmt) {\n fmt = new Intl.NumberFormat(locale, options);\n formatterCache.set(key, fmt);\n }\n return fmt;\n}\n\n/** Extract locale meta from formatToParts — never hardcoded. */\nfunction extractLocaleInfo(\n locale: string | undefined,\n options: Intl.NumberFormatOptions | undefined\n): LocaleInfo {\n const styledFmt = getFormatter(locale, options);\n\n // Probe the separators with a NEUTRAL decimal formatter (same locale +\n // numbering system, but plain decimal style with a forced fraction). The\n // styled formatter can hide them — e.g. percent scales the probe so it has no\n // fraction (decimal separator invisible) and a positive value never yields a\n // minusSign. A negative, fractional decimal probe always surfaces all four.\n const probeFmt = getFormatter(locale, {\n minimumFractionDigits: 1,\n maximumFractionDigits: 1,\n numberingSystem: options?.numberingSystem,\n });\n const parts = probeFmt.formatToParts(-PROBE_VALUE);\n\n let decimalSeparator = \".\";\n let groupingSeparator = \",\";\n let minusSign = \"-\";\n let zero = \"0\";\n\n for (const part of parts) {\n if (part.type === \"decimal\") decimalSeparator = part.value;\n if (part.type === \"group\") groupingSeparator = part.value;\n if (part.type === \"minusSign\") minusSign = part.value;\n }\n\n // Detect locale zero digit\n for (const part of probeFmt.formatToParts(0)) {\n if (part.type === \"integer\") {\n zero = part.value;\n break;\n }\n }\n\n // RTL locales: Arabic / Hebrew / Persian / Urdu / Syriac etc.\n const rtlLocales = /^(ar|he|fa|ur|syc|nqo|ug|yi)/i;\n const resolvedLocale = styledFmt.resolvedOptions().locale;\n const isRTL = rtlLocales.test(resolvedLocale);\n\n return { decimalSeparator, groupingSeparator, minusSign, zero, isRTL };\n}\n\n// ── Factory ───────────────────────────────────────────────────────────────────\n\nexport interface FormatterOptions {\n locale?: string;\n formatOptions?: Intl.NumberFormatOptions;\n prefix?: string;\n suffix?: string;\n minimumFractionDigits?: number;\n maximumFractionDigits?: number;\n fixedDecimalScale?: boolean;\n}\n\nexport interface Formatter {\n format(value: number): string;\n formatToParts(value: number): Intl.NumberFormatPart[];\n getLocaleInfo(): LocaleInfo;\n formatResult(value: number): FormatResult;\n}\n\n/**\n * Create a formatter instance. Intl.NumberFormat is cached — safe to call\n * on every render.\n */\nexport function createFormatter(opts: FormatterOptions): Formatter {\n // Merge fraction digit overrides into formatOptions\n const intlOptions: Intl.NumberFormatOptions = { ...opts.formatOptions };\n\n if (opts.minimumFractionDigits !== undefined) {\n intlOptions.minimumFractionDigits = opts.minimumFractionDigits;\n }\n if (opts.maximumFractionDigits !== undefined) {\n intlOptions.maximumFractionDigits = opts.maximumFractionDigits;\n }\n if (opts.fixedDecimalScale && opts.maximumFractionDigits !== undefined) {\n intlOptions.minimumFractionDigits = opts.maximumFractionDigits;\n intlOptions.maximumFractionDigits = opts.maximumFractionDigits;\n }\n\n const intlFmt = getFormatter(opts.locale, intlOptions);\n // Lazy — computed once on first call\n let cachedLocaleInfo: LocaleInfo | null = null;\n\n function getLocaleInfo(): LocaleInfo {\n if (!cachedLocaleInfo) {\n cachedLocaleInfo = extractLocaleInfo(opts.locale, intlOptions);\n }\n return cachedLocaleInfo;\n }\n\n function formatToParts(value: number): Intl.NumberFormatPart[] {\n const parts = intlFmt.formatToParts(value);\n if (!opts.prefix && !opts.suffix) return parts;\n\n const result: Intl.NumberFormatPart[] = [];\n if (opts.prefix) result.push({ type: \"literal\", value: opts.prefix });\n result.push(...parts);\n if (opts.suffix) result.push({ type: \"literal\", value: opts.suffix });\n return result;\n }\n\n function format(value: number): string {\n if (!Number.isFinite(value)) return \"\";\n const formatted = intlFmt.format(value);\n return (opts.prefix ?? \"\") + formatted + (opts.suffix ?? \"\");\n }\n\n function formatResult(value: number): FormatResult {\n const parts = formatToParts(value);\n const formatted = parts.map((p) => p.value).join(\"\");\n return { formatted, parts };\n }\n\n return { format, formatToParts, getLocaleInfo, formatResult };\n}\n","import { createFormatter } from \"./formatter.js\";\nimport { normalizeDigits } from \"./normalizer.js\";\nimport type { LocaleInfo, ParseResult } from \"./types.js\";\n\n// ── Helpers ───────────────────────────────────────────────────────────────────\n\n/**\n * Given an ASCII-normalised numeric string (`stripped` — digits, an optional\n * leading \"-\", and at most one \".\"), report whether it is a valid-but-incomplete\n * value that must NOT be reformatted while the user is still typing:\n * \"1.\" trailing decimal separator\n * \"1.0\" trailing zero after decimal\n * \"1.50\" trailing zeros after decimal\n * \".5\" leading decimal point (normalised to \"0.5\" only on blur)\n *\n * This runs on the *stripped* string, so grouping separators, prefixes,\n * suffixes and currency symbols never break the detection.\n */\nfunction isIntermediateStripped(stripped: string, allowDecimal: boolean): boolean {\n if (!allowDecimal) return false;\n if (/^-0+$/.test(stripped)) return true; // \"-0\" — user may still type \"-0.5\"\n if (/\\.$/.test(stripped)) return true; // \"1.\", \"-1.\"\n if (/\\.\\d*0$/.test(stripped)) return true; // \"1.0\", \"1.50\", \"1.230\"\n if (/^-?\\.\\d+$/.test(stripped)) return true; // \".5\", \"-.5\"\n return false;\n}\n\n// ── Factory ───────────────────────────────────────────────────────────────────\n\nexport interface ParserOptions {\n locale?: string;\n formatOptions?: Intl.NumberFormatOptions;\n allowNegative?: boolean;\n allowDecimal?: boolean;\n prefix?: string;\n suffix?: string;\n}\n\nexport interface Parser {\n parse(input: string): ParseResult;\n isIntermediate(input: string): boolean;\n getLocaleInfo(): LocaleInfo;\n}\n\n/**\n * Create a locale-aware parser. Separator characters are extracted from\n * Intl.NumberFormat — never hardcoded.\n */\nexport function createParser(opts: ParserOptions = {}): Parser {\n const allowNegative = opts.allowNegative ?? true;\n const allowDecimal = opts.allowDecimal ?? true;\n // Percent fields hold the *fraction* (Intl multiplies by 100 on display), so\n // typed digits must be divided by 100: typing \"50\" means 50% i.e. value 0.5.\n const isPercent = opts.formatOptions?.style === \"percent\";\n\n // Re-use the formatter to get locale info\n const fmt = createFormatter({\n locale: opts.locale,\n formatOptions: opts.formatOptions,\n prefix: opts.prefix,\n suffix: opts.suffix,\n });\n\n // The literal currency symbol (e.g. \"$\", \"€\", or Arabic \"ج.م.\" which embeds\n // ASCII dots). Captured so it can be removed wholesale before separator\n // handling — otherwise its dots would be mistaken for a decimal point.\n let currencySymbol = \"\";\n if (opts.formatOptions?.style === \"currency\") {\n try {\n currencySymbol = fmt\n .formatToParts(1)\n .filter((p) => p.type === \"currency\")\n .map((p) => p.value)\n .join(\"\");\n } catch {\n currencySymbol = \"\";\n }\n }\n\n function getLocaleInfo(): LocaleInfo {\n return fmt.getLocaleInfo();\n }\n\n function stripAffordances(raw: string): string {\n const info = getLocaleInfo();\n\n // 1. Normalise non-Latin digits to ASCII\n let s = normalizeDigits(raw);\n\n // 1b. Remove the currency symbol wholesale (before separators are touched),\n // so a symbol containing ASCII dots — e.g. Arabic \"ج.م.\" — does not leave\n // stray \".\" that the numeric validation would reject.\n if (currencySymbol) {\n s = s.split(currencySymbol).join(\"\");\n }\n\n // 2. Accounting format: \"(1,234.56)\" or \"($1,234.56)\" → negative\n // Intl.NumberFormat with currencySign:\"accounting\" wraps negatives in parens\n const accountingMatch = s.match(/^\\((.+)\\)$/);\n if (accountingMatch) {\n s = `-${accountingMatch[1]}`;\n }\n\n // 3. Strip prefix / suffix\n if (opts.prefix && s.startsWith(opts.prefix)) {\n s = s.slice(opts.prefix.length);\n }\n if (opts.suffix && s.endsWith(opts.suffix)) {\n s = s.slice(0, -opts.suffix.length);\n }\n\n // 4. Strip grouping separators (escape special chars)\n if (info.groupingSeparator) {\n s = s.split(info.groupingSeparator).join(\"\");\n }\n\n // 5. Replace locale decimal separator with ASCII \".\"\n if (info.decimalSeparator !== \".\") {\n s = s.split(info.decimalSeparator).join(\".\");\n }\n\n // 6. Replace locale minus sign with ASCII \"-\"\n if (info.minusSign !== \"-\") {\n s = s.split(info.minusSign).join(\"-\");\n }\n // Also normalise the Unicode minus U+2212 (used by fa/sv/fi/nb… and often\n // pasted) so it is never stripped as a non-numeric character below.\n if (s.includes(\"−\")) {\n s = s.split(\"−\").join(\"-\");\n }\n\n // 7. Strip currency symbol, percent sign, spaces that Intl might prepend/append\n // Strip any remaining non-numeric chars except digits, \".\", \"-\"\n // (handles currency prefixes/suffixes from Intl)\n s = s.replace(/[^\\d.\\-]/g, \"\").trim();\n\n // 8. Collapse minus signs to a single leading one, so stray minuses typed in\n // the middle (\"1-23\") or doubled (\"--5\") never invalidate the whole value.\n if (s.includes(\"-\")) {\n const negative = s.startsWith(\"-\");\n s = s.replace(/-/g, \"\");\n if (negative) s = `-${s}`;\n }\n\n return s;\n }\n\n function parse(input: string): ParseResult {\n if (!input || input.trim() === \"\") {\n return { value: null, isValid: false, isIntermediate: false };\n }\n\n // Strip *first*, so intermediate detection never trips over grouping\n // separators, prefixes, suffixes or currency symbols.\n const stripped = stripAffordances(input);\n\n if (stripped === \"\") {\n return { value: null, isValid: false, isIntermediate: false };\n }\n\n // Lone minus — intermediate only if negatives are allowed.\n if (stripped === \"-\") {\n return { value: null, isValid: false, isIntermediate: allowNegative };\n }\n\n // Lone decimal point (\".\" or \"-.\") — intermediate only if decimals allowed.\n if (stripped === \".\" || stripped === \"-.\") {\n return {\n value: null,\n isValid: false,\n isIntermediate: allowDecimal && (stripped === \".\" || allowNegative),\n };\n }\n\n if (!allowNegative && stripped.startsWith(\"-\")) {\n return { value: null, isValid: false, isIntermediate: false };\n }\n\n if (!allowDecimal && stripped.includes(\".\")) {\n return { value: null, isValid: false, isIntermediate: false };\n }\n\n // Accept integers and decimals with the dot either trailing (\"1.\") or\n // leading (\".5\") so partially-typed values still yield a numeric value.\n if (!/^-?(?:\\d+\\.?\\d*|\\.\\d+)$/.test(stripped)) {\n return { value: null, isValid: false, isIntermediate: false };\n }\n\n let n = Number.parseFloat(stripped);\n if (!Number.isFinite(n)) {\n return { value: null, isValid: false, isIntermediate: false };\n }\n // Normalise negative zero so consumers never receive -0 from onChange.\n if (Object.is(n, -0)) n = 0;\n // Percent: divide by 100, snapping to canonical precision so the IEEE-754\n // division artifact (12.99/100 = 0.12990000000000002) never surfaces.\n if (isPercent && n !== 0) n = Number((n / 100).toPrecision(15));\n\n // A trailing-zero / trailing-dot / leading-dot value is still a real number\n // (so it is never wiped on blur) but must not be reformatted mid-typing.\n return {\n value: n,\n isValid: true,\n isIntermediate: isIntermediateStripped(stripped, allowDecimal),\n };\n }\n\n function isIntermediate(input: string): boolean {\n return parse(input).isIntermediate;\n }\n\n return { parse, isIntermediate, getLocaleInfo };\n}\n","import { normalizeDigits } from \"./normalizer.js\";\nimport type { CaretBoundary, LocaleInfo } from \"./types.js\";\n\n// ── Accepted-character helpers ────────────────────────────────────────────────\n\n/**\n * Returns true if `ch` is an \"accepted\" character — one that the user typed\n * intentionally and that contributes to the numeric value:\n * - ASCII digit 0-9\n * - The locale decimal separator\n * - The locale minus sign\n */\nfunction isAccepted(ch: string, info: LocaleInfo): boolean {\n if (ch >= \"0\" && ch <= \"9\") return true;\n if (ch === info.decimalSeparator) return true;\n if (ch === info.minusSign || ch === \"-\") return true;\n // ASCII \".\" stands in for the decimal point in locales whose separator is\n // non-ASCII (ar/fa: ٫) — but not when \".\" is the grouping separator (de-DE).\n if (ch === \".\" && info.decimalSeparator !== \".\" && info.groupingSeparator !== \".\") return true;\n return false;\n}\n\n/**\n * Count how many \"accepted\" characters appear before position `cursor`\n * in `str` (after normalising non-Latin digits to ASCII).\n */\nfunction countAcceptedBefore(str: string, cursor: number, info: LocaleInfo): number {\n const normalised = normalizeDigits(str);\n let count = 0;\n for (let i = 0; i < cursor && i < normalised.length; i++) {\n if (isAccepted(normalised[i]!, info)) count++;\n }\n return count;\n}\n\n// ── Caret boundary ────────────────────────────────────────────────────────────\n\n/**\n * Build a boolean array of length `formattedValue.length + 1`.\n * `true` → cursor may rest at this position.\n * `false` → cursor must snap away (sits inside a formatting-only character\n * such as a grouping separator or a currency prefix).\n *\n * Rules:\n * - Start and end positions are always valid.\n * - A position immediately AFTER a grouping separator is invalid (the\n * cursor would look like it's between two digits but moving left would\n * skip the comma).\n * - A position immediately BEFORE a grouping separator is valid.\n */\nexport function getCaretBoundary(formattedValue: string, info: LocaleInfo): CaretBoundary {\n const len = formattedValue.length;\n const boundary: CaretBoundary = new Array(len + 1).fill(true) as boolean[];\n\n for (let i = 0; i < len; i++) {\n const ch = formattedValue[i]!;\n if (ch === info.groupingSeparator) {\n // Position immediately after the grouping separator is invalid\n boundary[i + 1] = false;\n }\n }\n\n // First and last are always valid\n boundary[0] = true;\n boundary[len] = true;\n\n return boundary;\n}\n\n// ── Cursor computation ────────────────────────────────────────────────────────\n\n/**\n * Compute the new cursor position in `newFormatted` that corresponds\n * semantically to `oldCursor` in `oldInput`.\n *\n * Algorithm (3 stages from the spec):\n *\n * 1. Count accepted characters before `oldCursor` in `oldInput`.\n * 2. Adjust for backspace-over-separator edge case.\n * 3. Walk `newFormatted` to find the position where the same count of\n * accepted chars precede it; snap to the nearest valid boundary.\n *\n * @param oldInput The raw string the user just typed into (pre-format)\n * @param oldCursor selectionStart captured from the native event\n * @param newFormatted The formatted string we're about to display\n * @param info Locale separators\n * @param inputType e.nativeEvent.inputType (optional — for backspace detection)\n */\nexport function computeNewCursorPosition(\n oldInput: string,\n oldCursor: number,\n newFormatted: string,\n info: LocaleInfo,\n inputType?: string\n): number {\n const normalised = normalizeDigits(oldInput);\n\n // Stage 1: count accepted chars before cursor in old input\n let acceptedCount = countAcceptedBefore(normalised, oldCursor, info);\n\n // Stage 1b: accounting/parens negatives drop the minus sign. If a minus was\n // counted before the caret but the reformatted output represents the sign\n // without one (e.g. \"($1.00)\"), the accepted-char counts are off by one —\n // correct for it so integer digits don't land inside the fraction.\n const before = oldInput.slice(0, oldCursor);\n const minusBeforeCaret = before.includes(\"-\") || before.includes(info.minusSign);\n const newHasMinus = newFormatted.includes(\"-\") || newFormatted.includes(info.minusSign);\n if (minusBeforeCaret && !newHasMinus) {\n acceptedCount = Math.max(0, acceptedCount - 1);\n }\n\n // Stage 2: backspace on grouping separator — also delete the preceding digit\n if (\n inputType === \"deleteContentBackward\" &&\n oldCursor > 0 &&\n oldInput[oldCursor - 1] === info.groupingSeparator\n ) {\n // The separator was deleted but we want to remove the preceding digit too\n acceptedCount = Math.max(0, acceptedCount - 1);\n }\n\n // Stage 3: build boundary and walk new formatted string\n const boundary = getCaretBoundary(newFormatted, info);\n const normNew = normalizeDigits(newFormatted);\n let count = 0;\n let pos = 0;\n\n for (let i = 0; i < normNew.length; i++) {\n if (count === acceptedCount) {\n pos = i;\n break;\n }\n if (isAccepted(normNew[i]!, info)) count++;\n pos = i + 1;\n }\n\n // If we ran through the entire string without reaching the target count,\n // place the cursor at the end. Note: acceptedCount === 0 means we correctly\n // want pos = 0 (set in the loop), so we must NOT override that case.\n if (acceptedCount > 0 && count < acceptedCount) {\n pos = newFormatted.length;\n }\n\n // Snap to nearest valid boundary\n pos = snapToBoundary(pos, boundary);\n\n return pos;\n}\n\n/**\n * If `pos` is at a false (invalid) boundary position, find the nearest\n * true position. Prefers moving forward; falls back to backward.\n */\nfunction snapToBoundary(pos: number, boundary: CaretBoundary): number {\n if (boundary[pos]) return pos;\n\n // Try forward first\n for (let i = pos + 1; i < boundary.length; i++) {\n if (boundary[i]) return i;\n }\n // Fall back to backward\n for (let i = pos - 1; i >= 0; i--) {\n if (boundary[i]) return i;\n }\n return 0;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"core.js"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
'use strict';var it=require('react'),jsxRuntime=require('react/jsx-runtime');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var it__default=/*#__PURE__*/_interopDefault(it);var at=new Map;function We(t,e){let r=`${t??""}::${JSON.stringify(e??{})}`,n=at.get(r);return n||(n=new Intl.NumberFormat(t,e),at.set(r,n)),n}function yt(t,e){let r=We(t,e),n=We(t,{minimumFractionDigits:1,maximumFractionDigits:1,numberingSystem:e?.numberingSystem}),i=n.formatToParts(-12345.6),o=".",u=",",p="-",c="0";for(let a of i)a.type==="decimal"&&(o=a.value),a.type==="group"&&(u=a.value),a.type==="minusSign"&&(p=a.value);for(let a of n.formatToParts(0))if(a.type==="integer"){c=a.value;break}let m=/^(ar|he|fa|ur|syc|nqo|ug|yi)/i,b=r.resolvedOptions().locale,l=m.test(b);return {decimalSeparator:o,groupingSeparator:u,minusSign:p,zero:c,isRTL:l}}function q(t){let e={...t.formatOptions};t.minimumFractionDigits!==void 0&&(e.minimumFractionDigits=t.minimumFractionDigits),t.maximumFractionDigits!==void 0&&(e.maximumFractionDigits=t.maximumFractionDigits),t.fixedDecimalScale&&t.maximumFractionDigits!==void 0&&(e.minimumFractionDigits=t.maximumFractionDigits,e.maximumFractionDigits=t.maximumFractionDigits);let r=We(t.locale,e),n=null;function i(){return n||(n=yt(t.locale,e)),n}function o(c){let m=r.formatToParts(c);if(!t.prefix&&!t.suffix)return m;let b=[];return t.prefix&&b.push({type:"literal",value:t.prefix}),b.push(...m),t.suffix&&b.push({type:"literal",value:t.suffix}),b}function u(c){if(!Number.isFinite(c))return "";let m=r.format(c);return (t.prefix??"")+m+(t.suffix??"")}function p(c){let m=o(c);return {formatted:m.map(l=>l.value).join(""),parts:m}}return {format:u,formatToParts:o,getLocaleInfo:i,formatResult:p}}var St=[[1632,1641],[1776,1785],[2406,2415],[2534,2543],[3664,3673]],Je=[...St];function It(t){if(t.digitBlocks)for(let e of t.digitBlocks)Je.some(([n])=>n===e[0])||Je.push(e);}function _(t){return /[^\u0020-\u007e]/.test(t)?t.replace(/\p{Nd}/gu,e=>{let r=e.codePointAt(0);for(let[i,o]of Je)if(r>=i&&r<=o)return String(r-i);let n=Number.parseInt(e,10);return Number.isNaN(n)?e:String(n)}):t}function Ge(t,e){if(!e||e==="0")return t;let r=e.codePointAt(0);return r===void 0?t:t.replace(/[0-9]/g,n=>String.fromCodePoint(r+(n.charCodeAt(0)-48)))}function Lt(t,e){return e?!!(/^-0+$/.test(t)||/\.$/.test(t)||/\.\d*0$/.test(t)||/^-?\.\d+$/.test(t)):false}function Pe(t={}){let e=t.allowNegative??true,r=t.allowDecimal??true,n=t.formatOptions?.style==="percent",i=q({locale:t.locale,formatOptions:t.formatOptions,prefix:t.prefix,suffix:t.suffix}),o="";if(t.formatOptions?.style==="currency")try{o=i.formatToParts(1).filter(b=>b.type==="currency").map(b=>b.value).join("");}catch{o="";}function u(){return i.getLocaleInfo()}function p(b){let l=u(),a=_(b);o&&(a=a.split(o).join(""));let I=a.match(/^\((.+)\)$/);if(I&&(a=`-${I[1]}`),t.prefix&&a.startsWith(t.prefix)&&(a=a.slice(t.prefix.length)),t.suffix&&a.endsWith(t.suffix)&&(a=a.slice(0,-t.suffix.length)),l.groupingSeparator&&(a=a.split(l.groupingSeparator).join("")),l.decimalSeparator!=="."&&(a=a.split(l.decimalSeparator).join(".")),l.minusSign!=="-"&&(a=a.split(l.minusSign).join("-")),a.includes("\u2212")&&(a=a.split("\u2212").join("-")),a=a.replace(/[^\d.\-]/g,"").trim(),a.includes("-")){let F=a.startsWith("-");a=a.replace(/-/g,""),F&&(a=`-${a}`);}return a}function c(b){if(!b||b.trim()==="")return {value:null,isValid:false,isIntermediate:false};let l=p(b);if(l==="")return {value:null,isValid:false,isIntermediate:false};if(l==="-")return {value:null,isValid:false,isIntermediate:e};if(l==="."||l==="-.")return {value:null,isValid:false,isIntermediate:r&&(l==="."||e)};if(!e&&l.startsWith("-"))return {value:null,isValid:false,isIntermediate:false};if(!r&&l.includes("."))return {value:null,isValid:false,isIntermediate:false};if(!/^-?(?:\d+\.?\d*|\.\d+)$/.test(l))return {value:null,isValid:false,isIntermediate:false};let a=Number.parseFloat(l);return Number.isFinite(a)?(Object.is(a,-0)&&(a=0),n&&a!==0&&(a=Number((a/100).toPrecision(15))),{value:a,isValid:true,isIntermediate:Lt(l,r)}):{value:null,isValid:false,isIntermediate:false}}function m(b){return c(b).isIntermediate}return {parse:c,isIntermediate:m,getLocaleInfo:u}}function Xe({value:t,defaultValue:e,onChange:r}){let n=t!==void 0,i=it.useRef(n);typeof window<"u"&&window.__DEV__!==false&&i.current!==n&&console.warn(`[raqam] Component is changing from ${i.current?"controlled":"uncontrolled"} to ${n?"controlled":"uncontrolled"}. Decide between using a controlled or uncontrolled component and don't switch.`);let[o,u]=it.useState(e),p=it.useCallback(c=>{let m=typeof c=="function"?c(n?t:o):c;n||u(m),r?.(m);},[n,t,o,r]);return [n?t:o,p]}function Qe(t,e,r){let n=t;return e!==void 0&&(n=Math.max(n,e)),r!==void 0&&(n=Math.min(n,r)),n}function ut(t,e){let n=10**Math.max(lt(t),lt(e));return Math.round(t*n+e*n)/n}function lt(t){if(!Number.isFinite(t))return 0;let e=String(t),r=e.indexOf("e");if(r!==-1){let i=Number(e.slice(r+1)),o=e.indexOf("."),u=o===-1?0:r-o-1;return Math.max(0,u-i)}let n=e.indexOf(".");return n===-1?0:e.length-n-1}function Ze(t){let{locale:e,formatOptions:r,minValue:n,maxValue:i,step:o=1,largeStep:u,smallStep:p,allowNegative:c=true,allowDecimal:m=true,maximumFractionDigits:b,minimumFractionDigits:l,fixedDecimalScale:a,clampBehavior:I="blur",prefix:F,suffix:C,allowOutOfRange:P=false,validate:G,onRawChange:X,formatValue:re}=t,se=m?l:0,S=m?b:0,H=m?a:false,ae=it.useMemo(()=>q({locale:e,formatOptions:r,prefix:F,suffix:C,minimumFractionDigits:se,maximumFractionDigits:S,fixedDecimalScale:H}),[e,JSON.stringify(r),F,C,se,S,H]),Q=it.useMemo(()=>Pe({locale:e,formatOptions:r,allowNegative:c,allowDecimal:m,prefix:F,suffix:C}),[e,JSON.stringify(r),c,m,F,C]),[v,M]=Xe({value:t.value,defaultValue:t.defaultValue??null,onChange:t.onChange}),Z=it.useRef(t.value??t.defaultValue??null),k=it.useCallback(d=>re?re(Object.is(d,-0)?0:d):ae.format(Object.is(d,-0)?0:d),[ae,re]),ce=it.useMemo(()=>t.defaultValue!=null?k(t.defaultValue):t.value!=null?k(t.value):"",[]),[Fe,B]=it.useState(ce),ee=it.useRef(ce),[je,te]=it.useState(t.defaultValue!=null?String(t.defaultValue):null),be=it.useCallback(d=>{if(!G)return {validationState:"valid",validationError:null};let D=G(d);return D===false?{validationState:"invalid",validationError:null}:typeof D=="string"?{validationState:"invalid",validationError:D}:{validationState:"valid",validationError:null}},[G]),Ee=it.useMemo(()=>{let d=t.defaultValue??t.value??null;return be(d??null)},[]),[Te,De]=it.useState(Ee.validationState),[me,Ce]=it.useState(Ee.validationError),[T,_e]=it.useState(false),[ye,ne]=it.useState(false),w=it.useRef("input"),fe=it.useCallback(d=>{w.current=d;},[]),V=it.useCallback(()=>w.current,[]),z=t.value,Me=it.useRef(z);if(!Object.is(Me.current,z)&&(Me.current=z,!Object.is(z,Z.current))){Z.current=z;let d=Object.is(z,-0)?0:z,D=d!=null&&Number.isFinite(d),h=D?k(d):"";ee.current=h,B(h),te(D?String(d):null);}let Se=`${e??""}|${JSON.stringify(r??{})}|${F??""}|${C??""}|${se??""}|${S??""}|${H??""}`,Ve=it.useRef(Se);if(Ve.current!==Se&&(Ve.current=Se,v!=null&&Number.isFinite(v)&&!ye)){let d=k(v);d!==Fe&&(B(d),ee.current=d);}let ue=it.useCallback(d=>{let{validationState:D,validationError:h}=be(d);De(D),Ce(h);},[be]),$e=it.useCallback((d,D)=>{let h=D!==void 0?D:Q.parse(d).value;I==="strict"&&!P&&h!==null&&(n!==void 0&&h<n||i!==void 0&&h>i)||(B(d),Z.current=h,M(h),te(h!==null?d:null),X?.(h!==null?d:null),ue(h));},[Q,I,P,n,i,M,X,ue]),Y=it.useCallback(d=>{if(Z.current=d,M(d),d!=null){let D=k(d);B(D),ee.current=D;let h=String(d);te(h),X?.(h);}else B(""),ee.current="",te(null),X?.(null);ue(d);},[k,M,X,ue]),Ue=it.useCallback(()=>{if(v==null)return B(""),ee.current="",null;let d=v;I==="blur"&&!P&&(d=Qe(v,n,i)),Object.is(d,-0)&&(d=0);let D=k(d);B(D),ee.current=D;let h=d;if(!re){let j=Q.parse(D).value;j!==null&&Number.isFinite(j)&&k(j)===D&&(h=j);}return h!==v&&(Z.current=h,M(h)),ue(h),h},[v,I,P,n,i,Q,k,re,M,ue]),ie=v!=null&&Number.isFinite(v)?v:null,Ke=u??o*10,ze=p??o*.1,Ye=!t.disabled&&!t.readOnly&&(P||i===void 0||(ie??Number.NEGATIVE_INFINITY)<i),qe=!t.disabled&&!t.readOnly&&(P||n===void 0||(ie??Number.POSITIVE_INFINITY)>n),Oe=it.useCallback(d=>{let j=ut(ie??0,d??o),Le=P?j:Qe(j,n,i);Y(Le);},[ie,o,n,i,P,Y]),ot=it.useCallback(d=>{let j=ut(ie??0,-(d??o)),Le=P?j:Qe(j,n,i);Y(Le);},[ie,o,n,i,P,Y]),Ie=it.useCallback(()=>{i!==void 0&&Y(i);},[i,Y]),ge=it.useCallback(()=>{n!==void 0&&Y(n);},[n,Y]);return {inputValue:Fe,numberValue:ie,rawValue:je,canIncrement:Ye,canDecrement:qe,isScrubbing:T,setIsScrubbing:_e,isFocused:ye,setIsFocused:ne,validationState:Te,validationError:me,_setLastChangeReason:fe,_getLastChangeReason:V,setInputValue:$e,setNumberValue:Y,commit:Ue,increment:Oe,decrement:ot,incrementToMax:Ie,decrementToMin:ge,options:{...t,step:o,largeStep:Ke,smallStep:ze}}}function st(t,e){return t>="0"&&t<="9"||t===e.decimalSeparator||t===e.minusSign||t==="-"||t==="."&&e.decimalSeparator!=="."&&e.groupingSeparator!=="."}function Et(t,e,r){let n=_(t),i=0;for(let o=0;o<e&&o<n.length;o++)st(n[o],r)&&i++;return i}function ct(t,e){let r=t.length,n=new Array(r+1).fill(true);for(let i=0;i<r;i++)t[i]===e.groupingSeparator&&(n[i+1]=false);return n[0]=true,n[r]=true,n}function xe(t,e,r,n,i){let o=_(t),u=Et(o,e,n),p=t.slice(0,e),c=p.includes("-")||p.includes(n.minusSign),m=r.includes("-")||r.includes(n.minusSign);c&&!m&&(u=Math.max(0,u-1)),i==="deleteContentBackward"&&e>0&&t[e-1]===n.groupingSeparator&&(u=Math.max(0,u-1));let b=ct(r,n),l=_(r),a=0,I=0;for(let F=0;F<l.length;F++){if(a===u){I=F;break}st(l[F],n)&&a++,I=F+1;}return u>0&&a<u&&(I=r.length),I=Tt(I,b),I}function Tt(t,e){if(e[t])return t;for(let r=t+1;r<e.length;r++)if(e[r])return r;for(let r=t-1;r>=0;r--)if(e[r])return r;return 0}function we(t,e={}){let{delay:r=400,interval:n=200,disabled:i=false}=e,o=it.useRef(t);it.useEffect(()=>{o.current=t;});let u=it.useRef(r);it.useEffect(()=>{u.current=r;});let p=it.useRef(n);it.useEffect(()=>{p.current=n;});let c=it.useRef(null),m=it.useRef(null),b=it.useRef(false),l=it.useCallback(()=>{b.current=false,c.current!==null&&(clearTimeout(c.current),c.current=null),m.current!==null&&(clearTimeout(m.current),m.current=null);},[]),a=it.useCallback(P=>{if(!b.current)return;o.current();let G=Math.max(50,Math.floor(P/2));m.current=setTimeout(()=>{a(G);},P);},[]),I=it.useCallback(P=>{i||P.button!==0&&P.pointerType==="mouse"||(o.current(),b.current=true,c.current=setTimeout(()=>{a(p.current);},u.current));},[i,a]),F=it.useCallback(P=>{P.preventDefault(),l();},[l]),C=it.useCallback(P=>{l();},[l]);return it.useEffect(()=>l,[l]),{onPointerDown:I,onPointerUp:F,onPointerLeave:C}}function mt(t){return t.replace(/[.*+?^${}()|[\]\\\-]/g,"\\$&")}function Ot(t){let e=t.replace(/\s+/g,"");if(/^[+-]?(?:\d+\.?\d*|\.\d+)[eE][+-]?\d+$/.test(e)){let n=Number(e);return Number.isFinite(n)?n:null}let r=e.match(/^([+-]?(?:\d+\.?\d*|\.\d+))(k|m|b|t|thousand|million|billion|trillion)$/i);if(r){let n={k:1e3,thousand:1e3,m:1e6,million:1e6,b:1e9,billion:1e9,t:1e12,trillion:1e12},i=Number(r[1])*n[r[2].toLowerCase()];return Number.isFinite(i)?i:null}return null}function tt(t,e,r){let{locale:n,formatOptions:i,minValue:o,maxValue:u,allowNegative:p=true,allowDecimal:c=true,allowMouseWheel:m=false,liveFormat:b=true,prefix:l,suffix:a,name:I,disabled:F,readOnly:C,required:P,onFocus:G,onBlur:X,maximumFractionDigits:re,minimumFractionDigits:se,fixedDecimalScale:S,copyBehavior:H="formatted",stepHoldDelay:ae=400,stepHoldInterval:Q=200,formatValue:v,parseValue:M,onValueCommitted:Z}=t,k=i?.notation,ce=b&&k!=="compact"&&k!=="scientific"&&k!=="engineering",{step:Fe=1,largeStep:B=Fe*10,smallStep:ee=Fe*.1}=e.options,je=it.useId(),te=t.id??`raqam-${je}`,be=`${te}-label`,Ee=`${te}-description`,Te=`${te}-error`,De=c?se:0,me=c?re:0,Ce=c?S:false,T=it.useMemo(()=>q({locale:n,formatOptions:i,prefix:l,suffix:a,minimumFractionDigits:De,maximumFractionDigits:me,fixedDecimalScale:Ce}),[n,JSON.stringify(i),l,a,De,me,Ce]),_e=i?.style==="percent",ye=c?_e?20:me:0,ne=it.useMemo(()=>q({locale:n,formatOptions:i,prefix:l,suffix:a,minimumFractionDigits:0,maximumFractionDigits:ye,fixedDecimalScale:false}),[n,JSON.stringify(i),l,a,ye]),w=it.useMemo(()=>Pe({locale:n,formatOptions:i,allowNegative:p,allowDecimal:c,prefix:l,suffix:a}),[n,JSON.stringify(i),p,c,l,a]),fe=it.useCallback((f,x)=>{let L=T.getLocaleInfo(),g=x.lastIndexOf(L.decimalSeparator);if(g===-1&&L.decimalSeparator!=="."&&L.groupingSeparator!=="."&&(g=x.lastIndexOf(".")),g===-1||!/\d/.test(_(x.slice(0,g))))return null;let y=_(x.slice(g+1)).match(/^\d+/);if(!y)return null;let s=Math.min(y[0].length,me??20,20);return s===0?null:q({locale:n,formatOptions:i,prefix:l,suffix:a,minimumFractionDigits:s,maximumFractionDigits:s}).format(f)},[T,n,JSON.stringify(i),l,a,me]),V=it.useRef(null);it.useLayoutEffect(()=>{V.current!==null&&r.current&&document.activeElement===r.current&&(r.current.setSelectionRange(V.current,V.current),V.current=null);},[e.inputValue,r]),it.useEffect(()=>{let f=r.current;if(!f||!m)return;let x=L=>{F||C||document.activeElement===f&&(L.preventDefault(),e._setLastChangeReason("wheel"),L.deltaY<0?e.increment():e.decrement());};return f.addEventListener("wheel",x,{passive:false}),()=>f.removeEventListener("wheel",x)},[m,F,C,e,r]);let z=it.useRef(false),Me=it.useCallback(()=>{z.current=true;},[]),Se=it.useCallback(f=>{z.current=false;let x=f.currentTarget.value,L=T.getLocaleInfo(),g=_(x),y;if(M){let s=M(g);s.isIntermediate?y=g:s.value!==null&&v?y=v(s.value):s.value!==null?y=T.format(s.value):y=g,V.current=y.length;}else if(ce){let s=w.parse(g);s.isIntermediate?y=Ge(g,L.zero):s.value!==null?y=v?v(s.value):ne.format(s.value):y=g===""?"":g,V.current=xe(x,x.length,y,L,"insertCompositionText");}else y=g,V.current=g.length;e._setLastChangeReason("input"),e.setInputValue(y);},[T,ne,w,ce,e,v,M]),Ve=it.useCallback(f=>{let x=f.target.value,L=f.target.selectionStart??x.length,g=f.nativeEvent.inputType,y=T.getLocaleInfo();if(z.current){e.setInputValue(x);return}let s=_(x);p||(s=s.split("-").join("").split(y.minusSign).join("")),c?y.decimalSeparator!=="."&&y.groupingSeparator!=="."&&(s=s.replace(/\./g,(O,R,N)=>/\d/.test(N[R-1]??"")||/\d/.test(N[R+1]??"")?y.decimalSeparator:".")):s=s.split(".").join("").split(y.decimalSeparator).join("");let E,de;if(M){let O=M(s);O.isIntermediate?E=s:O.value!==null?E=v?v(O.value):T.format(O.value):s===""?E="":E=s,V.current=E.length;}else if(ce){let O=w.parse(s);if(O.isIntermediate)E=(!v&&O.value!==null?fe(O.value,s):null)??Ge(s,y.zero);else if(O.value!==null)if(v)E=v(O.value);else {E=ne.format(O.value);let R=w.parse(E).value;de=R!==null&&Number.isFinite(R)&&ne.format(R)===E?R:O.value;}else s===""||!/\d/.test(s)?E="":E=s;v?V.current=E.length:V.current=xe(x,L,E,y,g);}else E=s,V.current=L;e._setLastChangeReason(E===""?"clear":"input"),e.setInputValue(E,de);},[T,ne,w,ce,e,v,M,fe]),ue=it.useCallback(f=>{f.preventDefault();let x=f.clipboardData.getData("text/plain");if(!x)return;let L=x.replace(/[€$£¥₹₺₽﷼฿₩¢₦₨₪₫₱]/g,"").trim(),g=_(L);if(!p){let N=T.getLocaleInfo();g=g.split("-").join("").split(N.minusSign).join("");}if(!c){let N=T.getLocaleInfo();g=g.split(".").join("").split(N.decimalSeparator).join("");}if(e._setLastChangeReason("paste"),M){let N=M(g);if(N.value!==null){let A=v?v(N.value):T.format(N.value);e.setInputValue(A,N.value),V.current=A.length;}return}let y=Ot(g);if(y!==null){let A=i?.style==="percent"?y/100:y,pe=v?v(A):T.format(A);e.setInputValue(pe,A),V.current=pe.length;return}let s=w.parse(g);if(s.value!==null){let N=T.format(s.value);e.setInputValue(N,s.value),V.current=N.length;return}let E=T.getLocaleInfo(),de=new RegExp(`[^0-9${mt(E.decimalSeparator)}${mt(E.minusSign)}-]`,"g"),O=g.replace(de,""),R=w.parse(O);if(R.value!==null){let N=T.format(R.value);e.setInputValue(N,R.value),V.current=N.length;}},[w,T,e,v,M]),$e=it.useCallback(f=>{if(H==="formatted")return;f.preventDefault();let x=String(e.numberValue??"");f.clipboardData.setData("text/plain",x);},[H,e.numberValue]),Y=it.useCallback(f=>{if(H==="formatted")return;f.preventDefault();let x=String(e.numberValue??"");f.clipboardData.setData("text/plain",x),e._setLastChangeReason("clear"),e.setInputValue("");},[H,e]),Ue=it.useCallback(f=>{if(F||C)return;let x=f.key;if(!f.metaKey&&!f.ctrlKey&&!f.altKey&&c){let L=T.getLocaleInfo();if(x===L.decimalSeparator||x==="."&&L.decimalSeparator!=="."&&L.groupingSeparator!=="."){let y=r.current;if(y){let s=y.value.indexOf(L.decimalSeparator);if(s!==-1){f.preventDefault(),y.setSelectionRange(s+1,s+1);return}}}}if(x==="Backspace"&&!f.shiftKey&&!f.altKey&&!f.metaKey&&!f.ctrlKey){let L=r.current;if(L){let g=L.selectionStart??0,y=L.selectionEnd??g,s=L.value,E=T.getLocaleInfo();if(g===y&&g>=2&&s[g-1]===E.groupingSeparator){f.preventDefault();let R=s.slice(0,g-2)+s.slice(g),N=w.parse(R);e._setLastChangeReason("input");let A;N.value!==null?(A=fe(N.value,R)??ne.format(N.value),e.setInputValue(A,N.value)):(A=R,R===""&&e._setLastChangeReason("clear"),e.setInputValue(R)),V.current=xe(R,g-2,A,E,"deleteContentBackward");return}let de=R=>R!==void 0&&/\p{Nd}/u.test(R),O=R=>R!==void 0&&!de(R)&&R!==E.decimalSeparator&&R!==E.minusSign&&R!=="-";if(g===y&&g===s.length&&g>=1&&O(s[g-1])){let R=g;for(;R>0&&O(s[R-1]);)R--;if(R>0&&de(s[R-1])){f.preventDefault();let N=s.slice(0,R-1)+s.slice(R),A=w.parse(N);e._setLastChangeReason("input");let pe;A.value!==null&&/\p{Nd}/u.test(N)?(pe=fe(A.value,N)??ne.format(A.value),e.setInputValue(pe,A.value)):(pe="",e._setLastChangeReason("clear"),e.setInputValue("")),V.current=xe(N,R-1,pe,E,"deleteContentBackward");return}}}}if(x==="ArrowUp"||x==="ArrowDown"){f.preventDefault();let L=x==="ArrowUp"?1:-1;e._setLastChangeReason("keyboard"),f.shiftKey?L>0?e.increment(B):e.decrement(B):f.metaKey||f.ctrlKey?L>0?e.increment(ee):e.decrement(ee):L>0?e.increment():e.decrement();return}if(x==="PageUp"){f.preventDefault(),e._setLastChangeReason("keyboard"),e.increment(B);return}if(x==="PageDown"){f.preventDefault(),e._setLastChangeReason("keyboard"),e.decrement(B);return}if(x==="Home"){o!==void 0&&(f.preventDefault(),e._setLastChangeReason("keyboard"),e.decrementToMin());return}if(x==="End"){u!==void 0&&(f.preventDefault(),e._setLastChangeReason("keyboard"),e.incrementToMax());return}if(x==="Enter"){e._setLastChangeReason("blur");let L=e.commit();Z?.(L,{reason:"keyboard"});return}},[F,C,e,B,ee,o,u,T,ne,w,r,c,fe,Z]),ie=it.useCallback(f=>{e.setIsFocused(false),e._setLastChangeReason("blur");let x=e.commit();Z?.(x,{reason:"blur"}),X?.(f);},[e,X,Z]),Ke=it.useCallback(f=>{e.setIsFocused(true),G?.(f);},[e,G]),ze=we(()=>{e._setLastChangeReason("increment"),e.increment();},{delay:ae,interval:Q,disabled:F||!e.canIncrement}),Ye=we(()=>{e._setLastChangeReason("decrement"),e.decrement();},{delay:ae,interval:Q,disabled:F||!e.canDecrement}),qe=it.useMemo(()=>{if(e.numberValue!=null)return v?v(e.numberValue):T.format(e.numberValue)},[e.numberValue,T,v]),Oe=T.getLocaleInfo(),Ie=e.numberValue!==null&&(o!==void 0&&e.numberValue<o||u!==void 0&&e.numberValue>u)||e.validationState==="invalid",ge=it.useRef(0),[d,D]=it.useState(false),h=it.useCallback(f=>{f?(ge.current+=1,D(true)):ge.current>0&&(ge.current-=1,ge.current===0&&D(false));},[]),j=t["aria-labelledby"]??(t["aria-label"]?void 0:d?be:void 0),Le={id:be,htmlFor:te,ref:h},gt={role:"group","aria-labelledby":j},vt={id:te,type:"text",inputMode:"decimal",role:"spinbutton",autoComplete:"off",autoCorrect:"off",spellCheck:false,"aria-label":t["aria-label"],"aria-labelledby":j,"aria-describedby":t["aria-describedby"],"aria-valuenow":e.numberValue??void 0,"aria-valuemin":o,"aria-valuemax":u,"aria-valuetext":qe,"aria-disabled":F||void 0,"aria-readonly":C||void 0,"aria-required":P||void 0,"aria-invalid":Ie?true:void 0,"aria-errormessage":Ie&&e.validationError?Te:void 0,disabled:F,readOnly:C,required:P,value:e.inputValue,onChange:Ve,onKeyDown:Ue,onBlur:ie,onFocus:Ke,onPaste:ue,onCopy:H!=="formatted"?$e:void 0,onCut:H!=="formatted"?Y:void 0,onCompositionStart:Me,onCompositionEnd:Se,style:Oe.isRTL?{direction:"ltr",textAlign:"right",unicodeBidi:"embed"}:void 0,"data-disabled":F?"":void 0,"data-readonly":C?"":void 0,"data-required":P?"":void 0,"data-invalid":Ie?"":void 0,"data-rtl":Oe.isRTL?"":void 0},xt=I?{type:"hidden",name:I,value:e.numberValue??"","aria-hidden":true}:null,Rt={type:"button",tabIndex:-1,"aria-label":"Increase",disabled:F||!e.canIncrement,...ze,"data-disabled":F||!e.canIncrement?"":void 0},Ft={type:"button",tabIndex:-1,"aria-label":"Decrease",disabled:F||!e.canDecrement,...Ye,"data-disabled":F||!e.canDecrement?"":void 0};return {labelProps:Le,groupProps:gt,inputProps:vt,hiddenInputProps:xt,incrementButtonProps:Rt,decrementButtonProps:Ft,descriptionProps:{id:Ee},errorMessageProps:{id:Te,role:"alert","aria-live":"polite"}}}function Ht(t,e={}){let{locale:r,formatOptions:n,prefix:i,suffix:o,minimumFractionDigits:u,maximumFractionDigits:p,fixedDecimalScale:c}=e,m=it.useMemo(()=>q({locale:r,formatOptions:n,prefix:i,suffix:o,minimumFractionDigits:u,maximumFractionDigits:p,fixedDecimalScale:c}),[r,JSON.stringify(n),i,o,u,p,c]);return it.useMemo(()=>t==null?"":m.format(t),[t,m])}function nt(t,e={}){let{direction:r="horizontal",pixelSensitivity:n=4}=e,[i,o]=it.useState(false),u=it.useRef(t);u.current=t;let p=it.useRef(r);p.current=r;let c=it.useRef(n);c.current=n;let m=it.useRef(false),b=it.useRef(0),l=it.useRef(null),a=it.useRef({x:0,y:0}),[I,F]=it.useState({x:0,y:0}),C=it.useRef(S=>{if(!m.current)return;let H=a.current.x+S.movementX,ae=a.current.y+S.movementY;a.current={x:H,y:ae},F({x:H,y:ae});let Q=p.current,v=0;Q==="horizontal"?v=S.movementX:Q==="vertical"?v=-S.movementY:v=Math.abs(S.movementX)>=Math.abs(S.movementY)?S.movementX:-S.movementY,b.current+=v;let M=c.current;for(;b.current>=M;)u.current.increment(),b.current-=M;for(;b.current<=-M;)u.current.decrement(),b.current+=M;}),P=it.useRef(()=>{document.pointerLockElement===l.current?(m.current=true,b.current=0,o(true),u.current.setIsScrubbing(true),document.addEventListener("mousemove",C.current)):(m.current=false,b.current=0,document.removeEventListener("mousemove",C.current),o(false),u.current.setIsScrubbing(false));});it.useEffect(()=>{let S=P.current;return document.addEventListener("pointerlockchange",S),()=>{document.removeEventListener("pointerlockchange",S),document.removeEventListener("mousemove",C.current);}},[]);let G=it.useCallback(S=>{if(u.current.options.disabled||u.current.options.readOnly||S.button!==0)return;let H=S.currentTarget;l.current=H,a.current={x:S.clientX,y:S.clientY},F({x:S.clientX,y:S.clientY}),H.requestPointerLock();},[]),X=it.useCallback(S=>{u.current.options.disabled||u.current.options.readOnly||(S.key==="ArrowRight"||S.key==="ArrowUp"?(S.preventDefault(),u.current.increment()):(S.key==="ArrowLeft"||S.key==="ArrowDown")&&(S.preventDefault(),u.current.decrement()));},[]),re=r==="horizontal"?"ew-resize":r==="vertical"?"ns-resize":"move",se={role:"slider",tabIndex:t.options.disabled?-1:0,style:{cursor:t.options.disabled?void 0:re,userSelect:"none",WebkitUserSelect:"none"},"aria-label":"Scrub to change value","data-scrubbing":i?"":void 0,onPointerDown:G,onKeyDown:X};return {isScrubbing:i,scrubAreaProps:se,virtualCursor:I}}var Be=it.createContext(null);function $(){let t=it.useContext(Be);if(!t)throw new Error("[raqam] NumberField sub-components must be used inside <NumberField.Root>.");return t}function le(t,e,r,n){if(!e)return t;let i={...t.props};if(n!=null&&(i.ref=n),typeof e=="function")return e(i,r);let o=Object.assign({},i,e.props);return n!=null&&(o.ref=n),it__default.default.cloneElement(e,o)}var bt=Number.parseInt(it__default.default.version,10)>=19,jt=bt;function _t(t){return bt?t.props.ref:t.ref}function $t(...t){let e=n=>{let i=[];for(let o of t)if(o!=null)if(typeof o=="function"){let u=o(n);i.push(typeof u=="function"?u:()=>o(null));}else o.current=n,i.push(()=>{o.current=null;});return i};if(jt)return n=>{let i=e(n);return ()=>{for(let o of i)o();}};let r=[];return n=>{for(let i of r)i();r=n==null?[]:e(n);}}function Ut(t,e){let{options:r}=t;return {"data-disabled":r.disabled?"":void 0,"data-readonly":r.readOnly?"":void 0,"data-required":r.required?"":void 0,"data-scrubbing":t.isScrubbing?"":void 0,"data-focused":t.isFocused?"":void 0,"data-invalid":e?"":void 0}}var Kt=new Set(["className","style","id","tabIndex","title","role","aria-label","data-testid","onClick","onMouseEnter","onMouseLeave"]);function zt(t){let e={},r={};for(let[n,i]of Object.entries(t))Kt.has(n)||n.startsWith("data-")||n.startsWith("aria-")?r[n]=i:e[n]=i;return {fieldProps:e,divProps:r}}var Yt=it.forwardRef(function({children:e,onValueChange:r,onValueCommitted:n,...i},o){let u=it.useRef(null),{fieldProps:p,divProps:c}=zt(i),m=p,b=it.useRef(r);b.current=r;let l=it.useRef(null),a={...m,onValueCommitted:n,onChange:P=>{m.onChange?.(P),b.current&&l.current&&b.current(P,{reason:l.current._getLastChangeReason(),formattedValue:l.current.inputValue});}},I=Ze(a);l.current=I;let F=tt(a,I,u),C=I.validationState==="invalid"||I.numberValue!==null&&(m.minValue!==void 0&&I.numberValue<m.minValue||m.maxValue!==void 0&&I.numberValue>m.maxValue);return jsxRuntime.jsx(Be.Provider,{value:{state:I,aria:F,inputRef:u,props:a},children:jsxRuntime.jsx("div",{ref:o,...c,...Ut(I,C),children:e})})}),qt=it.forwardRef(function({render:e,children:r,...n},i){let{aria:o,state:u}=$(),{ref:p,...c}=o.labelProps,m=it__default.default.isValidElement(e)?_t(e):void 0,b=it.useMemo(()=>$t(i,p,m),[i,p,m]),l=jsxRuntime.jsx("label",{ref:b,...c,...n,children:r});return le(l,e,u,b)}),Wt=it.forwardRef(function({render:e,children:r,...n},i){let{aria:o,state:u}=$(),p=jsxRuntime.jsx("div",{ref:i,...o.groupProps,...n,children:r});return le(p,e,u)}),Jt=it.forwardRef(function({render:e,...r},n){let{aria:i,state:o,inputRef:u}=$(),p=jsxRuntime.jsx("input",{ref:u,...i.inputProps,...r});return le(p,e,o)}),Gt=it.forwardRef(function({render:e,children:r,...n},i){let{aria:o,state:u}=$(),p=jsxRuntime.jsx("button",{ref:i,...o.incrementButtonProps,...n,children:r??"+"});return le(p,e,u)}),Xt=it.forwardRef(function({render:e,children:r,...n},i){let{aria:o,state:u}=$(),p=jsxRuntime.jsx("button",{ref:i,...o.decrementButtonProps,...n,children:r??"\u2212"});return le(p,e,u)}),Qt=function(){let{aria:e}=$();return e.hiddenInputProps?jsxRuntime.jsx("input",{...e.hiddenInputProps}):null},Zt=it.forwardRef(function({render:e,children:r,direction:n="horizontal",pixelSensitivity:i=4,...o},u){let{state:p}=$(),{scrubAreaProps:c}=nt(p,{direction:n,pixelSensitivity:i}),m=jsxRuntime.jsx("span",{ref:u,...c,...o,children:r});return le(m,e,p)}),en=it.forwardRef(function({render:e,children:r,style:n,...i},o){let{state:u}=$();if(!u.isScrubbing)return null;let p=jsxRuntime.jsx("span",{ref:o,style:{position:"fixed",pointerEvents:"none",zIndex:9999,...n},...i,children:r});return le(p,e,u)}),tn=it.forwardRef(function({children:e,...r},n){let{aria:i}=$();return jsxRuntime.jsx("p",{ref:n,...i.descriptionProps,...r,children:e})}),nn=it.forwardRef(function({children:e,...r},n){let{aria:i,state:o}=$(),u=e??o.validationError??null;return u?jsxRuntime.jsx("p",{ref:n,...i.errorMessageProps,...r,children:u}):null}),rn=it.forwardRef(function({render:e,...r},n){let{state:i}=$(),o=jsxRuntime.jsx("span",{ref:n,"aria-hidden":"true",...r,children:i.inputValue});return le(o,e,i)}),on={Root:Yt,Label:qt,Group:Wt,Input:Jt,Increment:Gt,Decrement:Xt,HiddenInput:Qt,ScrubArea:Zt,ScrubAreaCursor:en,Description:tn,ErrorMessage:nn,Formatted:rn};var an={currency:t=>({style:"currency",currency:t}),accounting:t=>({style:"currency",currency:t,currencySign:"accounting"}),percent:{style:"percent"},compact:{notation:"compact"},compactLong:{notation:"compact",compactDisplay:"long"},scientific:{notation:"scientific"},engineering:{notation:"engineering"},integer:{maximumFractionDigits:0},financial:{minimumFractionDigits:2,maximumFractionDigits:2},unit:t=>({style:"unit",unit:t})};exports.NumberField=on;exports.NumberFieldContext=Be;exports.computeNewCursorPosition=xe;exports.createFormatter=q;exports.createParser=Pe;exports.getCaretBoundary=ct;exports.normalizeDigits=_;exports.presets=an;exports.registerLocale=It;exports.useControllableState=Xe;exports.useNumberField=tt;exports.useNumberFieldContext=$;exports.useNumberFieldFormat=Ht;exports.useNumberFieldState=Ze;exports.usePressAndHold=we;exports.useScrubArea=nt;//# sourceMappingURL=index.cjs.map
|
|
2
|
+
'use strict';var chunkGAKIDRGS_cjs=require('./chunk-GAKIDRGS.cjs'),chunkXJZHLJ2C_cjs=require('./chunk-XJZHLJ2C.cjs'),chunkYUKLLK4G_cjs=require('./chunk-YUKLLK4G.cjs'),chunkZKLZ7UKZ_cjs=require('./chunk-ZKLZ7UKZ.cjs');Object.defineProperty(exports,"NumberField",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.i}});Object.defineProperty(exports,"NumberFieldContext",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.g}});Object.defineProperty(exports,"useControllableState",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.a}});Object.defineProperty(exports,"useNumberField",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.d}});Object.defineProperty(exports,"useNumberFieldContext",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.h}});Object.defineProperty(exports,"useNumberFieldFormat",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.e}});Object.defineProperty(exports,"useNumberFieldState",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.b}});Object.defineProperty(exports,"usePressAndHold",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.c}});Object.defineProperty(exports,"useScrubArea",{enumerable:true,get:function(){return chunkGAKIDRGS_cjs.f}});Object.defineProperty(exports,"presets",{enumerable:true,get:function(){return chunkXJZHLJ2C_cjs.a}});Object.defineProperty(exports,"computeNewCursorPosition",{enumerable:true,get:function(){return chunkYUKLLK4G_cjs.e}});Object.defineProperty(exports,"createFormatter",{enumerable:true,get:function(){return chunkYUKLLK4G_cjs.b}});Object.defineProperty(exports,"createParser",{enumerable:true,get:function(){return chunkYUKLLK4G_cjs.c}});Object.defineProperty(exports,"getCaretBoundary",{enumerable:true,get:function(){return chunkYUKLLK4G_cjs.d}});Object.defineProperty(exports,"normalizeDigits",{enumerable:true,get:function(){return chunkZKLZ7UKZ_cjs.b}});Object.defineProperty(exports,"registerLocale",{enumerable:true,get:function(){return chunkZKLZ7UKZ_cjs.a}});//# sourceMappingURL=index.cjs.map
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|