@jobber/components 7.10.0 → 7.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/Autocomplete/index.cjs +1 -0
  2. package/dist/Autocomplete/index.mjs +1 -0
  3. package/dist/Card/index.cjs +3 -0
  4. package/dist/Card/index.mjs +3 -0
  5. package/dist/Chip/index.cjs +1 -0
  6. package/dist/Chip/index.mjs +1 -0
  7. package/dist/Chips/InternalChipDismissible/hooks/index.cjs +1 -0
  8. package/dist/Chips/InternalChipDismissible/hooks/index.mjs +1 -0
  9. package/dist/Chips/InternalChipDismissible/index.cjs +1 -0
  10. package/dist/Chips/InternalChipDismissible/index.mjs +1 -0
  11. package/dist/Chips/index.cjs +1 -0
  12. package/dist/Chips/index.mjs +1 -0
  13. package/dist/Combobox/components/ComboboxActivator/index.cjs +1 -0
  14. package/dist/Combobox/components/ComboboxActivator/index.mjs +1 -0
  15. package/dist/Combobox/components/ComboboxContent/index.cjs +1 -0
  16. package/dist/Combobox/components/ComboboxContent/index.mjs +1 -0
  17. package/dist/Combobox/components/ComboboxTrigger/index.cjs +1 -0
  18. package/dist/Combobox/components/ComboboxTrigger/index.mjs +1 -0
  19. package/dist/Combobox/index.cjs +1 -0
  20. package/dist/Combobox/index.mjs +1 -0
  21. package/dist/ConfirmationModal/index.cjs +1 -0
  22. package/dist/ConfirmationModal/index.mjs +1 -0
  23. package/dist/DataDump/index.cjs +3 -0
  24. package/dist/DataDump/index.mjs +3 -0
  25. package/dist/DataList/components/DataListActions/index.cjs +1 -0
  26. package/dist/DataList/components/DataListActions/index.mjs +1 -0
  27. package/dist/DataList/components/DataListBulkActions/index.cjs +1 -0
  28. package/dist/DataList/components/DataListBulkActions/index.mjs +1 -0
  29. package/dist/DataList/components/DataListFilters/components/DataListSort/index.cjs +1 -0
  30. package/dist/DataList/components/DataListFilters/components/DataListSort/index.mjs +1 -0
  31. package/dist/DataList/components/DataListFilters/index.cjs +1 -0
  32. package/dist/DataList/components/DataListFilters/index.mjs +1 -0
  33. package/dist/DataList/components/DataListHeader/index.cjs +1 -0
  34. package/dist/DataList/components/DataListHeader/index.mjs +1 -0
  35. package/dist/DataList/components/DataListItem/index.cjs +1 -0
  36. package/dist/DataList/components/DataListItem/index.mjs +1 -0
  37. package/dist/DataList/components/DataListItemActions/index.cjs +1 -0
  38. package/dist/DataList/components/DataListItemActions/index.mjs +1 -0
  39. package/dist/DataList/components/DataListItemActionsOverflow/index.cjs +1 -0
  40. package/dist/DataList/components/DataListItemActionsOverflow/index.mjs +1 -0
  41. package/dist/DataList/components/DataListItems/index.cjs +1 -0
  42. package/dist/DataList/components/DataListItems/index.mjs +1 -0
  43. package/dist/DataList/components/DataListLayout/index.cjs +1 -0
  44. package/dist/DataList/components/DataListLayout/index.mjs +1 -0
  45. package/dist/DataList/components/DataListLayoutActions/index.cjs +1 -0
  46. package/dist/DataList/components/DataListLayoutActions/index.mjs +1 -0
  47. package/dist/DataList/index.cjs +1 -0
  48. package/dist/DataList/index.mjs +1 -0
  49. package/dist/DatePicker/index.cjs +1 -0
  50. package/dist/DatePicker/index.mjs +1 -0
  51. package/dist/DrawerRoot-cjs.js +181 -968
  52. package/dist/DrawerRoot-es.js +5 -734
  53. package/dist/FormatFile/index.cjs +1 -0
  54. package/dist/FormatFile/index.mjs +1 -0
  55. package/dist/Gallery/index.cjs +1 -0
  56. package/dist/Gallery/index.mjs +1 -0
  57. package/dist/InputDate/index.cjs +1 -0
  58. package/dist/InputDate/index.mjs +1 -0
  59. package/dist/InputNumberExperimental-cjs.js +783 -0
  60. package/dist/InputNumberExperimental-es.js +763 -0
  61. package/dist/LightBox/index.cjs +1 -0
  62. package/dist/LightBox/index.mjs +1 -0
  63. package/dist/Menu/index.cjs +3 -0
  64. package/dist/Menu/index.mjs +3 -0
  65. package/dist/MenuSubmenuTrigger-cjs.js +202 -447
  66. package/dist/MenuSubmenuTrigger-es.js +7 -249
  67. package/dist/Modal/index.cjs +1 -0
  68. package/dist/Modal/index.mjs +1 -0
  69. package/dist/NumberFieldInput-cjs.js +1828 -0
  70. package/dist/NumberFieldInput-es.js +1788 -0
  71. package/dist/Page/index.cjs +3 -0
  72. package/dist/Page/index.mjs +3 -0
  73. package/dist/Popover/index.cjs +1 -0
  74. package/dist/Popover/index.mjs +1 -0
  75. package/dist/Tooltip/index.cjs +1 -0
  76. package/dist/Tooltip/index.mjs +1 -0
  77. package/dist/docs/Menu/Menu.md +197 -37
  78. package/dist/floating-ui.react-cjs.js +35 -34
  79. package/dist/floating-ui.react-dom-cjs.js +65 -64
  80. package/dist/floating-ui.react-dom-es.js +2 -1
  81. package/dist/floating-ui.react-es.js +2 -1
  82. package/dist/floating-ui.utils.dom-cjs.js +185 -0
  83. package/dist/floating-ui.utils.dom-es.js +165 -0
  84. package/dist/index.cjs +3 -0
  85. package/dist/index.esm-cjs.js +0 -183
  86. package/dist/index.esm-es.js +1 -165
  87. package/dist/index.mjs +3 -0
  88. package/dist/primitives/BottomSheet/index.cjs +3 -1
  89. package/dist/primitives/BottomSheet/index.mjs +3 -1
  90. package/dist/primitives/InputNumberExperimental/InputNumberExperimental.d.ts +20 -0
  91. package/dist/primitives/InputNumberExperimental/index.cjs +22 -0
  92. package/dist/primitives/InputNumberExperimental/index.d.ts +2 -0
  93. package/dist/primitives/InputNumberExperimental/index.mjs +16 -0
  94. package/dist/primitives/InputNumberExperimental/types.d.ts +147 -0
  95. package/dist/primitives/index.cjs +9 -1
  96. package/dist/primitives/index.d.ts +2 -0
  97. package/dist/primitives/index.mjs +8 -1
  98. package/dist/styles.css +499 -0
  99. package/dist/unstyledPrimitives/index.cjs +264 -2039
  100. package/dist/unstyledPrimitives/index.mjs +72 -1847
  101. package/dist/useBaseUiId-cjs.js +275 -0
  102. package/dist/useBaseUiId-es.js +251 -0
  103. package/dist/useValueChanged-cjs.js +820 -0
  104. package/dist/useValueChanged-es.js +736 -0
  105. package/package.json +2 -2
  106. package/rollup.config.mjs +13 -2
@@ -0,0 +1,1788 @@
1
+ import * as React from 'react';
2
+ import { a as useStableCallback, u as useIsoLayoutEffect, f as useOnMount, T as Timeout, g as clamp, h as useControlled, i as useValueAsRef, c as useTimeout, j as isIOS, k as createChangeEventDetails, n as none, v as visuallyHiddenInput, l as visuallyHidden, m as inputChange, o as inputClear, p as inputBlur, q as inputPaste, r as createGenericEventDetails, s as ownerDocument, w as incrementPress, x as decrementPress, y as useValueChanged, z as stopEvent, A as keyboard } from './useValueChanged-es.js';
3
+ import { N as NOOP, f as formatErrorMessage, E as EMPTY_OBJECT, b as useRefWithInit, c as useMergedRefs, u as useRenderElement } from './useRenderElement-es.js';
4
+ import { b as isElement, k as getWindow } from './floating-ui.utils.dom-es.js';
5
+ import { u as useBaseUiId, a as useButton } from './useBaseUiId-es.js';
6
+ import { jsxs, jsx } from 'react/jsx-runtime';
7
+ import * as ReactDOM from 'react-dom';
8
+
9
+ /**
10
+ * Returns a function that forces a rerender.
11
+ */
12
+ function useForcedRerendering() {
13
+ const [, setState] = React.useState({});
14
+ return React.useCallback(() => {
15
+ setState({});
16
+ }, []);
17
+ }
18
+
19
+ let FieldControlDataAttributes = /*#__PURE__*/function (FieldControlDataAttributes) {
20
+ /**
21
+ * Present when the field is disabled.
22
+ */
23
+ FieldControlDataAttributes["disabled"] = "data-disabled";
24
+ /**
25
+ * Present when the field is in valid state.
26
+ */
27
+ FieldControlDataAttributes["valid"] = "data-valid";
28
+ /**
29
+ * Present when the field is in invalid state.
30
+ */
31
+ FieldControlDataAttributes["invalid"] = "data-invalid";
32
+ /**
33
+ * Present when the field has been touched.
34
+ */
35
+ FieldControlDataAttributes["touched"] = "data-touched";
36
+ /**
37
+ * Present when the field's value has changed.
38
+ */
39
+ FieldControlDataAttributes["dirty"] = "data-dirty";
40
+ /**
41
+ * Present when the field is filled.
42
+ */
43
+ FieldControlDataAttributes["filled"] = "data-filled";
44
+ /**
45
+ * Present when the field control is focused.
46
+ */
47
+ FieldControlDataAttributes["focused"] = "data-focused";
48
+ return FieldControlDataAttributes;
49
+ }({});
50
+
51
+ const DEFAULT_VALIDITY_STATE = {
52
+ badInput: false,
53
+ customError: false,
54
+ patternMismatch: false,
55
+ rangeOverflow: false,
56
+ rangeUnderflow: false,
57
+ stepMismatch: false,
58
+ tooLong: false,
59
+ tooShort: false,
60
+ typeMismatch: false,
61
+ valid: null,
62
+ valueMissing: false
63
+ };
64
+ const DEFAULT_FIELD_STATE_ATTRIBUTES = {
65
+ valid: null,
66
+ touched: false,
67
+ dirty: false,
68
+ filled: false,
69
+ focused: false
70
+ };
71
+ const DEFAULT_FIELD_ROOT_STATE = {
72
+ disabled: false,
73
+ ...DEFAULT_FIELD_STATE_ATTRIBUTES
74
+ };
75
+ const fieldValidityMapping = {
76
+ valid(value) {
77
+ if (value === null) {
78
+ return null;
79
+ }
80
+ if (value) {
81
+ return {
82
+ [FieldControlDataAttributes.valid]: ''
83
+ };
84
+ }
85
+ return {
86
+ [FieldControlDataAttributes.invalid]: ''
87
+ };
88
+ }
89
+ };
90
+
91
+ const FieldRootContext = /*#__PURE__*/React.createContext({
92
+ invalid: undefined,
93
+ name: undefined,
94
+ validityData: {
95
+ state: DEFAULT_VALIDITY_STATE,
96
+ errors: [],
97
+ error: '',
98
+ value: '',
99
+ initialValue: null
100
+ },
101
+ setValidityData: NOOP,
102
+ disabled: undefined,
103
+ touched: DEFAULT_FIELD_STATE_ATTRIBUTES.touched,
104
+ setTouched: NOOP,
105
+ dirty: DEFAULT_FIELD_STATE_ATTRIBUTES.dirty,
106
+ setDirty: NOOP,
107
+ filled: DEFAULT_FIELD_STATE_ATTRIBUTES.filled,
108
+ setFilled: NOOP,
109
+ focused: DEFAULT_FIELD_STATE_ATTRIBUTES.focused,
110
+ setFocused: NOOP,
111
+ validate: () => null,
112
+ validationMode: 'onSubmit',
113
+ validationDebounceTime: 0,
114
+ shouldValidateOnChange: () => false,
115
+ state: DEFAULT_FIELD_ROOT_STATE,
116
+ markedDirtyRef: {
117
+ current: false
118
+ },
119
+ validation: {
120
+ getValidationProps: (props = EMPTY_OBJECT) => props,
121
+ getInputValidationProps: (props = EMPTY_OBJECT) => props,
122
+ inputRef: {
123
+ current: null
124
+ },
125
+ commit: async () => {}
126
+ }
127
+ });
128
+ if (process.env.NODE_ENV !== "production") FieldRootContext.displayName = "FieldRootContext";
129
+ function useFieldRootContext(optional = true) {
130
+ const context = React.useContext(FieldRootContext);
131
+ if (context.setValidityData === NOOP && !optional) {
132
+ throw new Error(process.env.NODE_ENV !== "production" ? 'Base UI: FieldRootContext is missing. Field parts must be placed within <Field.Root>.' : formatErrorMessage(28));
133
+ }
134
+ return context;
135
+ }
136
+
137
+ /**
138
+ * Combines the field's client-side, stateful validity data with the external invalid state to
139
+ * determine the field's true validity.
140
+ */
141
+ function getCombinedFieldValidityData(validityData, invalid) {
142
+ return {
143
+ ...validityData,
144
+ state: {
145
+ ...validityData.state,
146
+ valid: !invalid && validityData.state.valid
147
+ }
148
+ };
149
+ }
150
+
151
+ const FormContext = /*#__PURE__*/React.createContext({
152
+ formRef: {
153
+ current: {
154
+ fields: new Map()
155
+ }
156
+ },
157
+ errors: {},
158
+ clearErrors: NOOP,
159
+ validationMode: 'onSubmit',
160
+ submitAttemptedRef: {
161
+ current: false
162
+ }
163
+ });
164
+ if (process.env.NODE_ENV !== "production") FormContext.displayName = "FormContext";
165
+ function useFormContext() {
166
+ return React.useContext(FormContext);
167
+ }
168
+
169
+ function useField(params) {
170
+ const {
171
+ enabled = true,
172
+ value,
173
+ id,
174
+ name,
175
+ controlRef,
176
+ commit
177
+ } = params;
178
+ const {
179
+ formRef
180
+ } = useFormContext();
181
+ const {
182
+ invalid,
183
+ markedDirtyRef,
184
+ validityData,
185
+ setValidityData
186
+ } = useFieldRootContext();
187
+ const getValue = useStableCallback(params.getValue);
188
+ useIsoLayoutEffect(() => {
189
+ if (!enabled) {
190
+ return;
191
+ }
192
+ let initialValue = value;
193
+ if (initialValue === undefined) {
194
+ initialValue = getValue();
195
+ }
196
+ if (validityData.initialValue === null && initialValue !== null) {
197
+ setValidityData(prev => ({
198
+ ...prev,
199
+ initialValue
200
+ }));
201
+ }
202
+ }, [enabled, setValidityData, value, validityData.initialValue, getValue]);
203
+ useIsoLayoutEffect(() => {
204
+ if (!enabled || !id) {
205
+ return;
206
+ }
207
+ formRef.current.fields.set(id, {
208
+ getValue,
209
+ name,
210
+ controlRef,
211
+ validityData: getCombinedFieldValidityData(validityData, invalid),
212
+ validate(flushSync = true) {
213
+ let nextValue = value;
214
+ if (nextValue === undefined) {
215
+ nextValue = getValue();
216
+ }
217
+ markedDirtyRef.current = true;
218
+ if (!flushSync) {
219
+ commit(nextValue);
220
+ } else {
221
+ // Synchronously update the validity state so the submit event can be prevented.
222
+ ReactDOM.flushSync(() => commit(nextValue));
223
+ }
224
+ }
225
+ });
226
+ }, [commit, controlRef, enabled, formRef, getValue, id, invalid, markedDirtyRef, name, validityData, value]);
227
+ useIsoLayoutEffect(() => {
228
+ const fields = formRef.current.fields;
229
+ return () => {
230
+ if (id) {
231
+ fields.delete(id);
232
+ }
233
+ };
234
+ }, [formRef, id]);
235
+ }
236
+
237
+ /**
238
+ * A context for providing [labelable elements](https://html.spec.whatwg.org/multipage/forms.html#category-label)\
239
+ * with an accessible name (label) and description.
240
+ */
241
+ const LabelableContext = /*#__PURE__*/React.createContext({
242
+ controlId: undefined,
243
+ registerControlId: NOOP,
244
+ labelId: undefined,
245
+ setLabelId: NOOP,
246
+ messageIds: [],
247
+ setMessageIds: NOOP,
248
+ getDescriptionProps: externalProps => externalProps
249
+ });
250
+ if (process.env.NODE_ENV !== "production") LabelableContext.displayName = "LabelableContext";
251
+ function useLabelableContext() {
252
+ return React.useContext(LabelableContext);
253
+ }
254
+
255
+ function useLabelableId(params = {}) {
256
+ const {
257
+ id,
258
+ implicit = false,
259
+ controlRef
260
+ } = params;
261
+ const {
262
+ controlId,
263
+ registerControlId
264
+ } = useLabelableContext();
265
+ const defaultId = useBaseUiId(id);
266
+ const controlIdForEffect = implicit ? controlId : undefined;
267
+ const controlSourceRef = useRefWithInit(() => Symbol('labelable-control'));
268
+ const hasRegisteredRef = React.useRef(false);
269
+ const hadExplicitIdRef = React.useRef(id != null);
270
+ const unregisterControlId = useStableCallback(() => {
271
+ if (!hasRegisteredRef.current || registerControlId === NOOP) {
272
+ return;
273
+ }
274
+ hasRegisteredRef.current = false;
275
+ registerControlId(controlSourceRef.current, undefined);
276
+ });
277
+ useIsoLayoutEffect(() => {
278
+ if (registerControlId === NOOP) {
279
+ return undefined;
280
+ }
281
+ let nextId;
282
+ if (implicit) {
283
+ const elem = controlRef?.current;
284
+ if (isElement(elem) && elem.closest('label') != null) {
285
+ nextId = id ?? null;
286
+ } else {
287
+ nextId = controlIdForEffect ?? defaultId;
288
+ }
289
+ } else if (id != null) {
290
+ hadExplicitIdRef.current = true;
291
+ nextId = id;
292
+ } else if (hadExplicitIdRef.current) {
293
+ nextId = defaultId;
294
+ } else {
295
+ unregisterControlId();
296
+ return undefined;
297
+ }
298
+ if (nextId === undefined) {
299
+ unregisterControlId();
300
+ return undefined;
301
+ }
302
+ hasRegisteredRef.current = true;
303
+ registerControlId(controlSourceRef.current, nextId);
304
+ return undefined;
305
+ }, [id, controlRef, controlIdForEffect, registerControlId, implicit, defaultId, controlSourceRef, unregisterControlId]);
306
+ React.useEffect(() => {
307
+ return unregisterControlId;
308
+ }, [unregisterControlId]);
309
+ return controlId ?? defaultId;
310
+ }
311
+
312
+ const cache = new Map();
313
+ function getFormatter(locale, options) {
314
+ const optionsString = JSON.stringify({
315
+ locale,
316
+ options
317
+ });
318
+ const cachedFormatter = cache.get(optionsString);
319
+ if (cachedFormatter) {
320
+ return cachedFormatter;
321
+ }
322
+ const formatter = new Intl.NumberFormat(locale, options);
323
+ cache.set(optionsString, formatter);
324
+ return formatter;
325
+ }
326
+ function formatNumber(value, locale, options) {
327
+ if (value == null) {
328
+ return '';
329
+ }
330
+ return getFormatter(locale, options).format(value);
331
+ }
332
+ function formatNumberMaxPrecision(value, locale, options) {
333
+ return formatNumber(value, locale, {
334
+ ...options,
335
+ maximumFractionDigits: 20
336
+ });
337
+ }
338
+
339
+ const EMPTY = 0;
340
+ class Interval extends Timeout {
341
+ static create() {
342
+ return new Interval();
343
+ }
344
+
345
+ /**
346
+ * Executes `fn` at `delay` interval, clearing any previously scheduled call.
347
+ */
348
+ start(delay, fn) {
349
+ this.clear();
350
+ this.currentId = setInterval(() => {
351
+ fn();
352
+ }, delay);
353
+ }
354
+ clear = () => {
355
+ if (this.currentId !== EMPTY) {
356
+ clearInterval(this.currentId);
357
+ this.currentId = EMPTY;
358
+ }
359
+ };
360
+ }
361
+
362
+ /**
363
+ * A `setInterval` with automatic cleanup and guard.
364
+ */
365
+ function useInterval() {
366
+ const timeout = useRefWithInit(Interval.create).current;
367
+ useOnMount(timeout.disposeEffect);
368
+ return timeout;
369
+ }
370
+
371
+ const NumberFieldRootContext = /*#__PURE__*/React.createContext(undefined);
372
+ if (process.env.NODE_ENV !== "production") NumberFieldRootContext.displayName = "NumberFieldRootContext";
373
+ function useNumberFieldRootContext() {
374
+ const context = React.useContext(NumberFieldRootContext);
375
+ if (context === undefined) {
376
+ throw new Error(process.env.NODE_ENV !== "production" ? 'Base UI: NumberFieldRootContext is missing. NumberField parts must be placed within <NumberField.Root>.' : formatErrorMessage(43));
377
+ }
378
+ return context;
379
+ }
380
+
381
+ const stateAttributesMapping$1 = {
382
+ inputValue: () => null,
383
+ value: () => null,
384
+ ...fieldValidityMapping
385
+ };
386
+
387
+ const HAN_NUMERALS = ['零', '〇', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
388
+ // Map Han numeral characters to ASCII digits. Includes both forms of zero.
389
+ const HAN_NUMERAL_TO_DIGIT = {
390
+ 零: '0',
391
+ 〇: '0',
392
+ 一: '1',
393
+ 二: '2',
394
+ 三: '3',
395
+ 四: '4',
396
+ 五: '5',
397
+ 六: '6',
398
+ 七: '7',
399
+ 八: '8',
400
+ 九: '9'
401
+ };
402
+ const ARABIC_NUMERALS = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
403
+ const PERSIAN_NUMERALS = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
404
+ const FULLWIDTH_NUMERALS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
405
+ const PERCENTAGES = ['%', '٪', '%', '﹪'];
406
+ const PERMILLE = ['‰', '؉'];
407
+ const UNICODE_MINUS_SIGNS = ['−', '-', '‒', '–', '—', '﹣'];
408
+ const UNICODE_PLUS_SIGNS = ['+', '﹢'];
409
+
410
+ // Fullwidth punctuation common in CJK inputs
411
+ const FULLWIDTH_DECIMAL = '.'; // U+FF0E
412
+ const FULLWIDTH_GROUP = ','; // U+FF0C
413
+
414
+ const ARABIC_RE = new RegExp(`[${ARABIC_NUMERALS.join('')}]`, 'g');
415
+ const PERSIAN_RE = new RegExp(`[${PERSIAN_NUMERALS.join('')}]`, 'g');
416
+ const FULLWIDTH_RE = new RegExp(`[${FULLWIDTH_NUMERALS.join('')}]`, 'g');
417
+ const HAN_RE = new RegExp(`[${HAN_NUMERALS.join('')}]`, 'g');
418
+ const PERCENT_RE = new RegExp(`[${PERCENTAGES.join('')}]`);
419
+ const PERMILLE_RE = new RegExp(`[${PERMILLE.join('')}]`);
420
+
421
+ // Detection regexes (non-global to avoid lastIndex side effects)
422
+ const ARABIC_DETECT_RE = /[٠١٢٣٤٥٦٧٨٩]/;
423
+ const PERSIAN_DETECT_RE = /[۰۱۲۳۴۵۶۷۸۹]/;
424
+ const HAN_DETECT_RE = /[零〇一二三四五六七八九]/;
425
+ const FULLWIDTH_DETECT_RE = new RegExp(`[${FULLWIDTH_NUMERALS.join('')}]`);
426
+ const BASE_NON_NUMERIC_SYMBOLS = ['.', ',', FULLWIDTH_DECIMAL, FULLWIDTH_GROUP, '٫', '٬'];
427
+ const SPACE_SEPARATOR_RE = /\p{Zs}/u;
428
+ const PLUS_SIGNS_WITH_ASCII = ['+', ...UNICODE_PLUS_SIGNS];
429
+ const MINUS_SIGNS_WITH_ASCII = ['-', ...UNICODE_MINUS_SIGNS];
430
+ const escapeRegExp = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
431
+ const escapeClassChar = s => s.replace(/[-\\\]^]/g, m => `\\${m}`); // escape for use inside [...]
432
+
433
+ const charClassFrom = chars => `[${chars.map(escapeClassChar).join('')}]`;
434
+ const ANY_MINUS_CLASS = charClassFrom(['-'].concat(UNICODE_MINUS_SIGNS));
435
+ const ANY_PLUS_CLASS = charClassFrom(['+'].concat(UNICODE_PLUS_SIGNS));
436
+ const ANY_MINUS_RE = new RegExp(ANY_MINUS_CLASS, 'gu');
437
+ const ANY_PLUS_RE = new RegExp(ANY_PLUS_CLASS, 'gu');
438
+ const ANY_MINUS_DETECT_RE = new RegExp(ANY_MINUS_CLASS);
439
+ const ANY_PLUS_DETECT_RE = new RegExp(ANY_PLUS_CLASS);
440
+ function getNumberLocaleDetails(locale, options) {
441
+ const parts = getFormatter(locale, options).formatToParts(11111.1);
442
+ const result = {};
443
+ parts.forEach(part => {
444
+ result[part.type] = part.value;
445
+ });
446
+
447
+ // The formatting options may result in not returning a decimal.
448
+ getFormatter(locale).formatToParts(0.1).forEach(part => {
449
+ if (part.type === 'decimal') {
450
+ result[part.type] = part.value;
451
+ }
452
+ });
453
+ return result;
454
+ }
455
+ function parseNumber(formattedNumber, locale, options) {
456
+ if (formattedNumber == null) {
457
+ return null;
458
+ }
459
+
460
+ // Normalize control characters and whitespace; remove bidi/format controls
461
+ let input = String(formattedNumber).replace(/\p{Cf}/gu, '').trim();
462
+
463
+ // Normalize unicode minus/plus to ASCII, handle leading/trailing signs
464
+ input = input.replace(ANY_MINUS_RE, '-').replace(ANY_PLUS_RE, '+');
465
+ let isNegative = false;
466
+
467
+ // Trailing sign, e.g. "1234-" / "1234+"
468
+ const trailing = input.match(/([+-])\s*$/);
469
+ if (trailing) {
470
+ if (trailing[1] === '-') {
471
+ isNegative = true;
472
+ }
473
+ input = input.replace(/([+-])\s*$/, '');
474
+ }
475
+ // Leading sign
476
+ const leading = input.match(/^\s*([+-])/);
477
+ if (leading) {
478
+ if (leading[1] === '-') {
479
+ isNegative = true;
480
+ }
481
+ input = input.replace(/^\s*[+-]/, '');
482
+ }
483
+
484
+ // Heuristic locale detection
485
+ let computedLocale = locale;
486
+ if (computedLocale === undefined) {
487
+ if (ARABIC_DETECT_RE.test(input) || PERSIAN_DETECT_RE.test(input)) {
488
+ computedLocale = 'ar';
489
+ } else if (HAN_DETECT_RE.test(input)) {
490
+ computedLocale = 'zh';
491
+ }
492
+ }
493
+ const {
494
+ group,
495
+ decimal,
496
+ currency
497
+ } = getNumberLocaleDetails(computedLocale, options);
498
+
499
+ // Build robust unit regex from all unit parts (such as "km/h")
500
+ const unitParts = getFormatter(computedLocale, options).formatToParts(1).filter(p => p.type === 'unit').map(p => escapeRegExp(p.value));
501
+ const unitRegex = unitParts.length ? new RegExp(unitParts.join('|'), 'g') : null;
502
+ let groupRegex = null;
503
+ if (group) {
504
+ const isSpaceGroup = /\p{Zs}/u.test(group);
505
+ const isApostropheGroup = group === "'" || group === '’';
506
+
507
+ // Check if the group separator is a space-like character.
508
+ // If so, we'll replace all such characters with an empty string.
509
+ if (isSpaceGroup) {
510
+ groupRegex = /\p{Zs}/gu;
511
+ } else if (isApostropheGroup) {
512
+ // Some environments format numbers with ASCII apostrophe and others with a curly apostrophe.
513
+ groupRegex = /['’]/g;
514
+ } else {
515
+ groupRegex = new RegExp(escapeRegExp(group), 'g');
516
+ }
517
+ }
518
+ const replacements = [{
519
+ regex: group ? groupRegex : null,
520
+ replacement: ''
521
+ }, {
522
+ regex: decimal ? new RegExp(escapeRegExp(decimal), 'g') : null,
523
+ replacement: '.'
524
+ },
525
+ // Fullwidth punctuation
526
+ {
527
+ regex: /./g,
528
+ replacement: '.'
529
+ },
530
+ // FULLWIDTH_DECIMAL
531
+ {
532
+ regex: /,/g,
533
+ replacement: ''
534
+ },
535
+ // FULLWIDTH_GROUP
536
+ // Arabic punctuation
537
+ {
538
+ regex: /٫/g,
539
+ replacement: '.'
540
+ },
541
+ // ARABIC DECIMAL SEPARATOR (U+066B)
542
+ {
543
+ regex: /٬/g,
544
+ replacement: ''
545
+ },
546
+ // ARABIC THOUSANDS SEPARATOR (U+066C)
547
+ // Currency & unit labels
548
+ {
549
+ regex: currency ? new RegExp(escapeRegExp(currency), 'g') : null,
550
+ replacement: ''
551
+ }, {
552
+ regex: unitRegex,
553
+ replacement: ''
554
+ },
555
+ // Numeral systems to ASCII digits
556
+ {
557
+ regex: ARABIC_RE,
558
+ replacement: ch => String(ARABIC_NUMERALS.indexOf(ch))
559
+ }, {
560
+ regex: PERSIAN_RE,
561
+ replacement: ch => String(PERSIAN_NUMERALS.indexOf(ch))
562
+ }, {
563
+ regex: FULLWIDTH_RE,
564
+ replacement: ch => String(FULLWIDTH_NUMERALS.indexOf(ch))
565
+ }, {
566
+ regex: HAN_RE,
567
+ replacement: ch => HAN_NUMERAL_TO_DIGIT[ch]
568
+ }];
569
+ let unformatted = replacements.reduce((acc, {
570
+ regex,
571
+ replacement
572
+ }) => {
573
+ return regex ? acc.replace(regex, replacement) : acc;
574
+ }, input);
575
+
576
+ // Mixed-locale safety: keep only the last '.' as decimal
577
+ const lastDot = unformatted.lastIndexOf('.');
578
+ if (lastDot !== -1) {
579
+ unformatted = `${unformatted.slice(0, lastDot).replace(/\./g, '')}.${unformatted.slice(lastDot + 1).replace(/\./g, '')}`;
580
+ }
581
+
582
+ // Guard against Infinity inputs (ASCII and symbol)
583
+ if (/^[-+]?Infinity$/i.test(input) || /[∞]/.test(input)) {
584
+ return null;
585
+ }
586
+ const parseTarget = (isNegative ? '-' : '') + unformatted;
587
+ let num = parseFloat(parseTarget);
588
+ const style = options?.style;
589
+ const isUnitPercent = style === 'unit' && options?.unit === 'percent';
590
+ const hasPercentSymbol = PERCENT_RE.test(formattedNumber) || style === 'percent';
591
+ const hasPermilleSymbol = PERMILLE_RE.test(formattedNumber);
592
+ if (hasPermilleSymbol) {
593
+ num /= 1000;
594
+ } else if (!isUnitPercent && hasPercentSymbol) {
595
+ num /= 100;
596
+ }
597
+ if (Number.isNaN(num)) {
598
+ return null;
599
+ }
600
+ return num;
601
+ }
602
+
603
+ const CHANGE_VALUE_TICK_DELAY = 60;
604
+ const START_AUTO_CHANGE_DELAY = 400;
605
+ const TOUCH_TIMEOUT = 50;
606
+ const MAX_POINTER_MOVES_AFTER_TOUCH = 3;
607
+ const SCROLLING_POINTER_MOVE_DISTANCE = 8;
608
+ const DEFAULT_STEP = 1;
609
+
610
+ const STEP_EPSILON_FACTOR = 1e-10;
611
+ function getFractionDigits(format) {
612
+ const defaultOptions = getFormatter('en-US').resolvedOptions();
613
+ const minimumFractionDigits = format?.minimumFractionDigits ?? defaultOptions.minimumFractionDigits ?? 0;
614
+ const maximumFractionDigits = Math.max(format?.maximumFractionDigits ?? defaultOptions.maximumFractionDigits ?? 20, minimumFractionDigits);
615
+ return {
616
+ maximumFractionDigits,
617
+ minimumFractionDigits
618
+ };
619
+ }
620
+ function roundToFractionDigits(value, maximumFractionDigits) {
621
+ if (!Number.isFinite(value)) {
622
+ return value;
623
+ }
624
+ const digits = Math.min(Math.max(maximumFractionDigits, 0), 20);
625
+ return Number(value.toFixed(digits));
626
+ }
627
+ function removeFloatingPointErrors(value, format) {
628
+ const {
629
+ maximumFractionDigits
630
+ } = getFractionDigits(format);
631
+ return roundToFractionDigits(value, maximumFractionDigits);
632
+ }
633
+ function snapToStep(clampedValue, base, step, mode = 'directional') {
634
+ if (step === 0) {
635
+ return clampedValue;
636
+ }
637
+ const stepSize = Math.abs(step);
638
+ const direction = Math.sign(step);
639
+ const tolerance = stepSize * STEP_EPSILON_FACTOR * direction;
640
+ const divisor = mode === 'nearest' ? step : stepSize;
641
+ const rawSteps = (clampedValue - base + tolerance) / divisor;
642
+ let snappedSteps;
643
+ if (mode === 'nearest') {
644
+ snappedSteps = Math.round(rawSteps);
645
+ } else if (direction > 0) {
646
+ snappedSteps = Math.floor(rawSteps);
647
+ } else {
648
+ snappedSteps = Math.ceil(rawSteps);
649
+ }
650
+ const stepForResult = mode === 'nearest' ? step : stepSize;
651
+ return base + snappedSteps * stepForResult;
652
+ }
653
+ function toValidatedNumber(value, {
654
+ step,
655
+ minWithDefault,
656
+ maxWithDefault,
657
+ minWithZeroDefault,
658
+ format,
659
+ snapOnStep,
660
+ small,
661
+ clamp: shouldClamp
662
+ }) {
663
+ if (value === null) {
664
+ return value;
665
+ }
666
+ const clampedValue = shouldClamp ? clamp(value, minWithDefault, maxWithDefault) : value;
667
+ if (step != null && snapOnStep) {
668
+ if (step === 0) {
669
+ return removeFloatingPointErrors(clampedValue, format);
670
+ }
671
+
672
+ // If a real minimum is provided, use it
673
+ let base = minWithZeroDefault;
674
+ if (!small && minWithDefault !== Number.MIN_SAFE_INTEGER) {
675
+ base = minWithDefault;
676
+ }
677
+ const snappedValue = snapToStep(clampedValue, base, step, small ? 'nearest' : 'directional');
678
+ return removeFloatingPointErrors(snappedValue, format);
679
+ }
680
+ return removeFloatingPointErrors(clampedValue, format);
681
+ }
682
+
683
+ const NumberFieldRoot = /*#__PURE__*/React.forwardRef(function NumberFieldRoot(componentProps, forwardedRef) {
684
+ const {
685
+ id: idProp,
686
+ min,
687
+ max,
688
+ smallStep = 0.1,
689
+ step: stepProp = 1,
690
+ largeStep = 10,
691
+ required = false,
692
+ disabled: disabledProp = false,
693
+ readOnly = false,
694
+ name: nameProp,
695
+ defaultValue,
696
+ value: valueProp,
697
+ onValueChange: onValueChangeProp,
698
+ onValueCommitted: onValueCommittedProp,
699
+ allowWheelScrub = false,
700
+ snapOnStep = false,
701
+ allowOutOfRange = false,
702
+ format,
703
+ locale,
704
+ render,
705
+ className,
706
+ inputRef: inputRefProp,
707
+ ...elementProps
708
+ } = componentProps;
709
+ const {
710
+ setDirty,
711
+ validityData,
712
+ disabled: fieldDisabled,
713
+ setFilled,
714
+ invalid,
715
+ name: fieldName,
716
+ state: fieldState,
717
+ validation,
718
+ shouldValidateOnChange
719
+ } = useFieldRootContext();
720
+ const disabled = fieldDisabled || disabledProp;
721
+ const name = fieldName ?? nameProp;
722
+ const step = stepProp === 'any' ? 1 : stepProp;
723
+ const [isScrubbing, setIsScrubbing] = React.useState(false);
724
+ const minWithDefault = min ?? Number.MIN_SAFE_INTEGER;
725
+ const maxWithDefault = max ?? Number.MAX_SAFE_INTEGER;
726
+ const minWithZeroDefault = min ?? 0;
727
+ const formatStyle = format?.style;
728
+ const inputRef = React.useRef(null);
729
+ const hiddenInputRef = useMergedRefs(inputRefProp, validation.inputRef);
730
+ const id = useLabelableId({
731
+ id: idProp
732
+ });
733
+ const [valueUnwrapped, setValueUnwrapped] = useControlled({
734
+ controlled: valueProp,
735
+ default: defaultValue,
736
+ name: 'NumberField',
737
+ state: 'value'
738
+ });
739
+ const value = valueUnwrapped ?? null;
740
+ const valueRef = useValueAsRef(value);
741
+ useIsoLayoutEffect(() => {
742
+ setFilled(value !== null);
743
+ }, [setFilled, value]);
744
+ const forceRender = useForcedRerendering();
745
+ const formatOptionsRef = useValueAsRef(format);
746
+ const hasPendingCommitRef = React.useRef(false);
747
+ const onValueCommitted = useStableCallback((nextValue, eventDetails) => {
748
+ hasPendingCommitRef.current = false;
749
+ onValueCommittedProp?.(nextValue, eventDetails);
750
+ });
751
+ const startTickTimeout = useTimeout();
752
+ const tickInterval = useInterval();
753
+ const intentionalTouchCheckTimeout = useTimeout();
754
+ const isPressedRef = React.useRef(false);
755
+ const movesAfterTouchRef = React.useRef(0);
756
+ const allowInputSyncRef = React.useRef(true);
757
+ const lastChangedValueRef = React.useRef(null);
758
+ const unsubscribeFromGlobalContextMenuRef = React.useRef(() => {});
759
+
760
+ // During SSR, the value is formatted on the server, whose locale may differ from the client's
761
+ // locale. This causes a hydration mismatch, which we manually suppress. This is preferable to
762
+ // rendering an empty input field and then updating it with the formatted value, as the user
763
+ // can still see the value prior to hydration, even if it's not formatted correctly.
764
+ const [inputValue, setInputValue] = React.useState(() => {
765
+ if (valueProp !== undefined) {
766
+ return getControlledInputValue(value, locale, format);
767
+ }
768
+ return formatNumber(value, locale, format);
769
+ });
770
+ const [inputMode, setInputMode] = React.useState('numeric');
771
+ const getAllowedNonNumericKeys = useStableCallback(() => {
772
+ const {
773
+ decimal,
774
+ group,
775
+ currency,
776
+ literal
777
+ } = getNumberLocaleDetails(locale, format);
778
+ const keys = new Set();
779
+ BASE_NON_NUMERIC_SYMBOLS.forEach(symbol => keys.add(symbol));
780
+ if (decimal) {
781
+ keys.add(decimal);
782
+ }
783
+ if (group) {
784
+ keys.add(group);
785
+ if (SPACE_SEPARATOR_RE.test(group)) {
786
+ keys.add(' ');
787
+ }
788
+ }
789
+ const allowPercentSymbols = formatStyle === 'percent' || formatStyle === 'unit' && format?.unit === 'percent';
790
+ const allowPermilleSymbols = formatStyle === 'percent' || formatStyle === 'unit' && format?.unit === 'permille';
791
+ if (allowPercentSymbols) {
792
+ PERCENTAGES.forEach(key => keys.add(key));
793
+ }
794
+ if (allowPermilleSymbols) {
795
+ PERMILLE.forEach(key => keys.add(key));
796
+ }
797
+ if (formatStyle === 'currency' && currency) {
798
+ keys.add(currency);
799
+ }
800
+ if (literal) {
801
+ // Some locales (e.g. de-DE) insert a literal space character between the number
802
+ // and the symbol, so allow those characters to be typed/removed.
803
+ Array.from(literal).forEach(char => keys.add(char));
804
+ if (SPACE_SEPARATOR_RE.test(literal)) {
805
+ keys.add(' ');
806
+ }
807
+ }
808
+
809
+ // Allow plus sign in all cases; minus sign only when negatives are valid
810
+ PLUS_SIGNS_WITH_ASCII.forEach(key => keys.add(key));
811
+ if (minWithDefault < 0) {
812
+ MINUS_SIGNS_WITH_ASCII.forEach(key => keys.add(key));
813
+ }
814
+ return keys;
815
+ });
816
+ const getStepAmount = useStableCallback(event => {
817
+ if (event?.altKey) {
818
+ return smallStep;
819
+ }
820
+ if (event?.shiftKey) {
821
+ return largeStep;
822
+ }
823
+ return step;
824
+ });
825
+ const setValue = useStableCallback((unvalidatedValue, details) => {
826
+ const eventWithOptionalKeyState = details.event;
827
+ const dir = details.direction;
828
+ const reason = details.reason;
829
+ // Only allow out-of-range values for direct text entry (native-like behavior).
830
+ // Step-based interactions (keyboard arrows, buttons, wheel, scrub) still clamp to min/max.
831
+ const shouldClampValue = !allowOutOfRange || !(reason === inputChange || reason === inputBlur || reason === inputPaste || reason === inputClear || reason === none);
832
+ const validatedValue = toValidatedNumber(unvalidatedValue, {
833
+ step: dir ? getStepAmount(eventWithOptionalKeyState) * dir : undefined,
834
+ format: formatOptionsRef.current,
835
+ minWithDefault,
836
+ maxWithDefault,
837
+ minWithZeroDefault,
838
+ snapOnStep,
839
+ small: eventWithOptionalKeyState?.altKey ?? false,
840
+ clamp: shouldClampValue
841
+ });
842
+
843
+ // Determine whether we should notify about a change even if the numeric value is unchanged.
844
+ // This is needed when the user input is clamped/snapped to the same current value, or when
845
+ // the source value differs but validation normalizes to the existing value.
846
+ const isInputReason = details.reason === inputChange || details.reason === inputClear || details.reason === inputBlur || details.reason === inputPaste || details.reason === none;
847
+ const shouldFireChange = validatedValue !== value || isInputReason && (unvalidatedValue !== value || allowInputSyncRef.current === false);
848
+ if (shouldFireChange) {
849
+ lastChangedValueRef.current = validatedValue;
850
+ onValueChangeProp?.(validatedValue, details);
851
+ if (details.isCanceled) {
852
+ return shouldFireChange;
853
+ }
854
+ setValueUnwrapped(validatedValue);
855
+ setDirty(validatedValue !== validityData.initialValue);
856
+ hasPendingCommitRef.current = true;
857
+ }
858
+
859
+ // Keep the visible input in sync immediately when programmatic changes occur
860
+ // (increment/decrement, wheel, etc). During direct typing we don't want
861
+ // to overwrite the user-provided text until blur, so we gate on
862
+ // `allowInputSyncRef`.
863
+ if (allowInputSyncRef.current) {
864
+ setInputValue(formatNumber(validatedValue, locale, format));
865
+ }
866
+
867
+ // Formatting can change even if the numeric value hasn't, so ensure a re-render when needed.
868
+ forceRender();
869
+ return shouldFireChange;
870
+ });
871
+ const incrementValue = useStableCallback((amount, {
872
+ direction,
873
+ currentValue,
874
+ event,
875
+ reason
876
+ }) => {
877
+ const prevValue = currentValue == null ? valueRef.current : currentValue;
878
+ const nextValue = typeof prevValue === 'number' ? prevValue + amount * direction : Math.max(0, min ?? 0);
879
+ const nativeEvent = event;
880
+ return setValue(nextValue, createChangeEventDetails(reason, nativeEvent, undefined, {
881
+ direction
882
+ }));
883
+ });
884
+ const stopAutoChange = useStableCallback(() => {
885
+ intentionalTouchCheckTimeout.clear();
886
+ startTickTimeout.clear();
887
+ tickInterval.clear();
888
+ unsubscribeFromGlobalContextMenuRef.current();
889
+ movesAfterTouchRef.current = 0;
890
+ });
891
+ const startAutoChange = useStableCallback((isIncrement, triggerEvent) => {
892
+ stopAutoChange();
893
+ if (!inputRef.current) {
894
+ return;
895
+ }
896
+ const win = getWindow(inputRef.current);
897
+ function handleContextMenu(event) {
898
+ event.preventDefault();
899
+ }
900
+
901
+ // A global context menu is necessary to prevent the context menu from appearing when the touch
902
+ // is slightly outside of the element's hit area.
903
+ win.addEventListener('contextmenu', handleContextMenu);
904
+ unsubscribeFromGlobalContextMenuRef.current = () => {
905
+ win.removeEventListener('contextmenu', handleContextMenu);
906
+ };
907
+ win.addEventListener('pointerup', event => {
908
+ isPressedRef.current = false;
909
+ stopAutoChange();
910
+ const committed = lastChangedValueRef.current ?? valueRef.current;
911
+ const commitReason = isIncrement ? incrementPress : decrementPress;
912
+ onValueCommitted(committed, createGenericEventDetails(commitReason, event));
913
+ }, {
914
+ once: true
915
+ });
916
+ function tick() {
917
+ const amount = getStepAmount(triggerEvent) ?? DEFAULT_STEP;
918
+ return incrementValue(amount, {
919
+ direction: isIncrement ? 1 : -1,
920
+ event: triggerEvent,
921
+ reason: isIncrement ? 'increment-press' : 'decrement-press'
922
+ });
923
+ }
924
+ if (!tick()) {
925
+ stopAutoChange();
926
+ return;
927
+ }
928
+ startTickTimeout.start(START_AUTO_CHANGE_DELAY, () => {
929
+ tickInterval.start(CHANGE_VALUE_TICK_DELAY, () => {
930
+ if (!tick()) {
931
+ stopAutoChange();
932
+ }
933
+ });
934
+ });
935
+ });
936
+
937
+ // We need to update the input value when the external `value` prop changes. This ends up acting
938
+ // as a single source of truth to update the input value, bypassing the need to manually set it in
939
+ // each event handler internally in this hook.
940
+ // This is done inside a layout effect as an alternative to the technique to set state during
941
+ // render as we're accessing a ref, which must be inside an effect.
942
+ // https://react.dev/learn/you-might-not-need-an-effect#adjusting-some-state-when-a-prop-changes
943
+ //
944
+ // ESLint is disabled because it needs to run even if the parsed value hasn't changed, since the
945
+ // value still can be formatted differently.
946
+ // eslint-disable-next-line react-hooks/exhaustive-deps
947
+ useIsoLayoutEffect(function syncFormattedInputValueOnValueChange() {
948
+ // This ensures the value is only updated on blur rather than every keystroke, but still
949
+ // allows the input value to be updated when the value is changed externally.
950
+ if (!allowInputSyncRef.current) {
951
+ return;
952
+ }
953
+ const nextInputValue = valueProp !== undefined ? getControlledInputValue(value, locale, format) : formatNumber(value, locale, format);
954
+ if (nextInputValue !== inputValue) {
955
+ setInputValue(nextInputValue);
956
+ }
957
+ });
958
+ useIsoLayoutEffect(function setDynamicInputModeForIOS() {
959
+ if (!isIOS) {
960
+ return;
961
+ }
962
+
963
+ // iOS numeric software keyboard doesn't have a minus key, so we need to use the default
964
+ // keyboard to let the user input a negative number.
965
+ let computedInputMode = 'text';
966
+ if (minWithDefault >= 0) {
967
+ // iOS numeric software keyboard doesn't have a decimal key for "numeric" input mode, but
968
+ // this is better than the "text" input if possible to use.
969
+ computedInputMode = 'decimal';
970
+ }
971
+ setInputMode(computedInputMode);
972
+ }, [minWithDefault, formatStyle]);
973
+ React.useEffect(() => {
974
+ return () => stopAutoChange();
975
+ }, [stopAutoChange]);
976
+
977
+ // The `onWheel` prop can't be prevented, so we need to use a global event listener.
978
+ React.useEffect(function registerElementWheelListener() {
979
+ const element = inputRef.current;
980
+ if (disabled || readOnly || !allowWheelScrub || !element) {
981
+ return undefined;
982
+ }
983
+ function handleWheel(event) {
984
+ if (
985
+ // Allow pinch-zooming.
986
+ event.ctrlKey || ownerDocument(inputRef.current).activeElement !== inputRef.current) {
987
+ return;
988
+ }
989
+
990
+ // Prevent the default behavior to avoid scrolling the page.
991
+ event.preventDefault();
992
+ const amount = getStepAmount(event) ?? DEFAULT_STEP;
993
+ incrementValue(amount, {
994
+ direction: event.deltaY > 0 ? -1 : 1,
995
+ event,
996
+ reason: 'wheel'
997
+ });
998
+ }
999
+ element.addEventListener('wheel', handleWheel);
1000
+ return () => {
1001
+ element.removeEventListener('wheel', handleWheel);
1002
+ };
1003
+ }, [allowWheelScrub, incrementValue, disabled, readOnly, largeStep, step, getStepAmount]);
1004
+ const state = React.useMemo(() => ({
1005
+ ...fieldState,
1006
+ disabled,
1007
+ readOnly,
1008
+ required,
1009
+ value,
1010
+ inputValue,
1011
+ scrubbing: isScrubbing
1012
+ }), [fieldState, disabled, readOnly, required, value, inputValue, isScrubbing]);
1013
+ const contextValue = React.useMemo(() => ({
1014
+ inputRef,
1015
+ inputValue,
1016
+ value,
1017
+ startAutoChange,
1018
+ stopAutoChange,
1019
+ minWithDefault,
1020
+ maxWithDefault,
1021
+ disabled,
1022
+ readOnly,
1023
+ id,
1024
+ setValue,
1025
+ incrementValue,
1026
+ getStepAmount,
1027
+ allowInputSyncRef,
1028
+ formatOptionsRef,
1029
+ valueRef,
1030
+ lastChangedValueRef,
1031
+ hasPendingCommitRef,
1032
+ isPressedRef,
1033
+ intentionalTouchCheckTimeout,
1034
+ movesAfterTouchRef,
1035
+ name,
1036
+ required,
1037
+ invalid,
1038
+ inputMode,
1039
+ getAllowedNonNumericKeys,
1040
+ min,
1041
+ max,
1042
+ setInputValue,
1043
+ locale,
1044
+ isScrubbing,
1045
+ setIsScrubbing,
1046
+ state,
1047
+ onValueCommitted
1048
+ }), [inputRef, inputValue, value, startAutoChange, stopAutoChange, minWithDefault, maxWithDefault, disabled, readOnly, id, setValue, incrementValue, getStepAmount, formatOptionsRef, valueRef, intentionalTouchCheckTimeout, name, required, invalid, inputMode, getAllowedNonNumericKeys, min, max, setInputValue, locale, isScrubbing, state, onValueCommitted]);
1049
+ const element = useRenderElement('div', componentProps, {
1050
+ ref: forwardedRef,
1051
+ state,
1052
+ props: elementProps,
1053
+ stateAttributesMapping: stateAttributesMapping$1
1054
+ });
1055
+ return /*#__PURE__*/jsxs(NumberFieldRootContext.Provider, {
1056
+ value: contextValue,
1057
+ children: [element, /*#__PURE__*/jsx("input", {
1058
+ ...validation.getInputValidationProps({
1059
+ onFocus() {
1060
+ inputRef.current?.focus();
1061
+ },
1062
+ onChange(event) {
1063
+ // Workaround for https://github.com/facebook/react/issues/9023
1064
+ if (event.nativeEvent.defaultPrevented) {
1065
+ return;
1066
+ }
1067
+
1068
+ // Handle browser autofill.
1069
+ const nextValue = event.currentTarget.valueAsNumber;
1070
+ const parsedValue = Number.isNaN(nextValue) ? null : nextValue;
1071
+ const details = createChangeEventDetails(none, event.nativeEvent);
1072
+ setDirty(parsedValue !== validityData.initialValue);
1073
+ setValue(parsedValue, details);
1074
+ if (shouldValidateOnChange()) {
1075
+ validation.commit(parsedValue);
1076
+ }
1077
+ }
1078
+ }),
1079
+ ref: hiddenInputRef,
1080
+ type: "number",
1081
+ name: name,
1082
+ value: value ?? '',
1083
+ min: min,
1084
+ max: max
1085
+ // stepMismatch validation is broken unless an explicit `min` is added.
1086
+ // See https://github.com/facebook/react/issues/12334.
1087
+ ,
1088
+ step: stepProp,
1089
+ disabled: disabled,
1090
+ required: required,
1091
+ "aria-hidden": true,
1092
+ tabIndex: -1,
1093
+ style: name ? visuallyHiddenInput : visuallyHidden
1094
+ })]
1095
+ });
1096
+ });
1097
+ if (process.env.NODE_ENV !== "production") NumberFieldRoot.displayName = "NumberFieldRoot";
1098
+ function getControlledInputValue(value, locale, format) {
1099
+ const explicitPrecision = format?.maximumFractionDigits != null || format?.minimumFractionDigits != null;
1100
+ return explicitPrecision ? formatNumber(value, locale, format) : formatNumberMaxPrecision(value, locale, format);
1101
+ }
1102
+
1103
+ /**
1104
+ * Groups the input with the increment and decrement buttons.
1105
+ * Renders a `<div>` element.
1106
+ *
1107
+ * Documentation: [Base UI Number Field](https://base-ui.com/react/components/number-field)
1108
+ */
1109
+ const NumberFieldGroup = /*#__PURE__*/React.forwardRef(function NumberFieldGroup(componentProps, forwardedRef) {
1110
+ const {
1111
+ render,
1112
+ className,
1113
+ ...elementProps
1114
+ } = componentProps;
1115
+ const {
1116
+ state
1117
+ } = useNumberFieldRootContext();
1118
+ const element = useRenderElement('div', componentProps, {
1119
+ ref: forwardedRef,
1120
+ state,
1121
+ props: [{
1122
+ role: 'group'
1123
+ }, elementProps],
1124
+ stateAttributesMapping: stateAttributesMapping$1
1125
+ });
1126
+ return element;
1127
+ });
1128
+ if (process.env.NODE_ENV !== "production") NumberFieldGroup.displayName = "NumberFieldGroup";
1129
+
1130
+ // Treat pen as touch-like to avoid forcing the software keyboard on stylus taps.
1131
+ // Linux Chrome may emit "pen" historically for mouse usage due to a bug, but the touch path
1132
+ // still works with minor behavioral differences.
1133
+ function isTouchLikePointerType(pointerType) {
1134
+ return pointerType === 'touch' || pointerType === 'pen';
1135
+ }
1136
+ function useNumberFieldButton(params) {
1137
+ const {
1138
+ allowInputSyncRef,
1139
+ disabled,
1140
+ formatOptionsRef,
1141
+ getStepAmount,
1142
+ id,
1143
+ incrementValue,
1144
+ inputRef,
1145
+ inputValue,
1146
+ intentionalTouchCheckTimeout,
1147
+ isIncrement,
1148
+ isPressedRef,
1149
+ locale,
1150
+ movesAfterTouchRef,
1151
+ readOnly,
1152
+ setValue,
1153
+ startAutoChange,
1154
+ stopAutoChange,
1155
+ valueRef,
1156
+ lastChangedValueRef,
1157
+ onValueCommitted
1158
+ } = params;
1159
+ const incrementDownCoordsRef = React.useRef({
1160
+ x: 0,
1161
+ y: 0
1162
+ });
1163
+ const isTouchingButtonRef = React.useRef(false);
1164
+ const ignoreClickRef = React.useRef(false);
1165
+ const pointerTypeRef = React.useRef('');
1166
+ const pressReason = isIncrement ? 'increment-press' : 'decrement-press';
1167
+ function commitValue(nativeEvent) {
1168
+ allowInputSyncRef.current = true;
1169
+
1170
+ // The input may be dirty but not yet blurred, so the value won't have been committed.
1171
+ const parsedValue = parseNumber(inputValue, locale, formatOptionsRef.current);
1172
+ if (parsedValue !== null) {
1173
+ // The increment value function needs to know the current input value to increment it
1174
+ // correctly.
1175
+ valueRef.current = parsedValue;
1176
+ setValue(parsedValue, createChangeEventDetails(pressReason, nativeEvent, undefined, {
1177
+ direction: isIncrement ? 1 : -1
1178
+ }));
1179
+ }
1180
+ }
1181
+ const props = {
1182
+ disabled,
1183
+ 'aria-readonly': readOnly || undefined,
1184
+ 'aria-label': isIncrement ? 'Increase' : 'Decrease',
1185
+ 'aria-controls': id,
1186
+ // Keyboard users shouldn't have access to the buttons, since they can use the input element
1187
+ // to change the value. On the other hand, `aria-hidden` is not applied because touch screen
1188
+ // readers should be able to use the buttons.
1189
+ tabIndex: -1,
1190
+ style: {
1191
+ WebkitUserSelect: 'none',
1192
+ userSelect: 'none'
1193
+ },
1194
+ onTouchStart() {
1195
+ isTouchingButtonRef.current = true;
1196
+ },
1197
+ onTouchEnd() {
1198
+ isTouchingButtonRef.current = false;
1199
+ },
1200
+ onClick(event) {
1201
+ const isDisabled = disabled || readOnly;
1202
+ if (event.defaultPrevented || isDisabled || (
1203
+ // If it's not a keyboard/virtual click, ignore.
1204
+ isTouchLikePointerType(pointerTypeRef.current) ? ignoreClickRef.current : event.detail !== 0)) {
1205
+ return;
1206
+ }
1207
+ commitValue(event.nativeEvent);
1208
+ const amount = getStepAmount(event) ?? DEFAULT_STEP;
1209
+ const prev = valueRef.current;
1210
+ incrementValue(amount, {
1211
+ direction: isIncrement ? 1 : -1,
1212
+ event: event.nativeEvent,
1213
+ reason: pressReason
1214
+ });
1215
+ const committed = lastChangedValueRef.current ?? valueRef.current;
1216
+ if (committed !== prev) {
1217
+ onValueCommitted(committed, createGenericEventDetails(pressReason, event.nativeEvent));
1218
+ }
1219
+ },
1220
+ onPointerDown(event) {
1221
+ const isMainButton = !event.button || event.button === 0;
1222
+ if (event.defaultPrevented || readOnly || !isMainButton || disabled) {
1223
+ return;
1224
+ }
1225
+ pointerTypeRef.current = event.pointerType;
1226
+ ignoreClickRef.current = false;
1227
+ isPressedRef.current = true;
1228
+ incrementDownCoordsRef.current = {
1229
+ x: event.clientX,
1230
+ y: event.clientY
1231
+ };
1232
+ commitValue(event.nativeEvent);
1233
+ const isTouchPointer = isTouchLikePointerType(event.pointerType);
1234
+ if (!isTouchPointer) {
1235
+ event.preventDefault();
1236
+ inputRef.current?.focus();
1237
+ startAutoChange(isIncrement, event);
1238
+ } else {
1239
+ // We need to check if the pointerdown was intentional, and not the result of a scroll
1240
+ // or pinch-zoom. In that case, we don't want to change the value.
1241
+ intentionalTouchCheckTimeout.start(TOUCH_TIMEOUT, () => {
1242
+ const moves = movesAfterTouchRef.current;
1243
+ movesAfterTouchRef.current = 0;
1244
+ // Only start auto-change if the touch is still pressed (prevents races
1245
+ // with pointerup occurring before the timeout fires on quick taps).
1246
+ const stillPressed = isPressedRef.current;
1247
+ if (stillPressed && moves != null && moves < MAX_POINTER_MOVES_AFTER_TOUCH) {
1248
+ startAutoChange(isIncrement, event);
1249
+ ignoreClickRef.current = true; // synthesized click should be ignored
1250
+ } else {
1251
+ // No auto-change (simple tap or scroll gesture), allow the click handler
1252
+ // to perform a single increment and commit.
1253
+ ignoreClickRef.current = false;
1254
+ stopAutoChange();
1255
+ }
1256
+ });
1257
+ }
1258
+ },
1259
+ onPointerUp(event) {
1260
+ // Ensure we mark the press as released for touch flows even if auto-change never started,
1261
+ // so the delayed auto-change check won’t start after a quick tap.
1262
+ if (isTouchLikePointerType(event.pointerType)) {
1263
+ isPressedRef.current = false;
1264
+ }
1265
+ },
1266
+ onPointerMove(event) {
1267
+ const isDisabled = disabled || readOnly;
1268
+ if (isDisabled || !isTouchLikePointerType(event.pointerType) || !isPressedRef.current) {
1269
+ return;
1270
+ }
1271
+ if (movesAfterTouchRef.current != null) {
1272
+ movesAfterTouchRef.current += 1;
1273
+ }
1274
+ const {
1275
+ x,
1276
+ y
1277
+ } = incrementDownCoordsRef.current;
1278
+ const dx = x - event.clientX;
1279
+ const dy = y - event.clientY;
1280
+
1281
+ // An alternative to this technique is to detect when the NumberField's parent container
1282
+ // has been scrolled
1283
+ if (dx ** 2 + dy ** 2 > SCROLLING_POINTER_MOVE_DISTANCE ** 2) {
1284
+ stopAutoChange();
1285
+ }
1286
+ },
1287
+ onMouseEnter(event) {
1288
+ const isDisabled = disabled || readOnly;
1289
+ if (event.defaultPrevented || isDisabled || !isPressedRef.current || isTouchingButtonRef.current || isTouchLikePointerType(pointerTypeRef.current)) {
1290
+ return;
1291
+ }
1292
+ startAutoChange(isIncrement, event);
1293
+ },
1294
+ onMouseLeave() {
1295
+ if (isTouchingButtonRef.current) {
1296
+ return;
1297
+ }
1298
+ stopAutoChange();
1299
+ },
1300
+ onMouseUp() {
1301
+ if (isTouchingButtonRef.current) {
1302
+ return;
1303
+ }
1304
+ stopAutoChange();
1305
+ }
1306
+ };
1307
+ return props;
1308
+ }
1309
+
1310
+ /**
1311
+ * A stepper button that increases the field value when clicked.
1312
+ * Renders an `<button>` element.
1313
+ *
1314
+ * Documentation: [Base UI Number Field](https://base-ui.com/react/components/number-field)
1315
+ */
1316
+ const NumberFieldIncrement = /*#__PURE__*/React.forwardRef(function NumberFieldIncrement(componentProps, forwardedRef) {
1317
+ const {
1318
+ render,
1319
+ className,
1320
+ disabled: disabledProp = false,
1321
+ nativeButton = true,
1322
+ ...elementProps
1323
+ } = componentProps;
1324
+ const {
1325
+ allowInputSyncRef,
1326
+ disabled: contextDisabled,
1327
+ formatOptionsRef,
1328
+ getStepAmount,
1329
+ id,
1330
+ incrementValue,
1331
+ inputRef,
1332
+ inputValue,
1333
+ intentionalTouchCheckTimeout,
1334
+ isPressedRef,
1335
+ locale,
1336
+ maxWithDefault,
1337
+ movesAfterTouchRef,
1338
+ readOnly,
1339
+ setValue,
1340
+ startAutoChange,
1341
+ state,
1342
+ stopAutoChange,
1343
+ value,
1344
+ valueRef,
1345
+ lastChangedValueRef,
1346
+ onValueCommitted
1347
+ } = useNumberFieldRootContext();
1348
+ const isMax = value != null && value >= maxWithDefault;
1349
+ const disabled = disabledProp || contextDisabled || isMax;
1350
+ const props = useNumberFieldButton({
1351
+ isIncrement: true,
1352
+ inputRef,
1353
+ startAutoChange,
1354
+ stopAutoChange,
1355
+ inputValue,
1356
+ disabled,
1357
+ readOnly,
1358
+ id,
1359
+ setValue,
1360
+ getStepAmount,
1361
+ incrementValue,
1362
+ allowInputSyncRef,
1363
+ formatOptionsRef,
1364
+ valueRef,
1365
+ isPressedRef,
1366
+ intentionalTouchCheckTimeout,
1367
+ movesAfterTouchRef,
1368
+ locale,
1369
+ lastChangedValueRef,
1370
+ onValueCommitted
1371
+ });
1372
+ const {
1373
+ getButtonProps,
1374
+ buttonRef
1375
+ } = useButton({
1376
+ disabled,
1377
+ native: nativeButton,
1378
+ focusableWhenDisabled: true
1379
+ });
1380
+ const buttonState = React.useMemo(() => ({
1381
+ ...state,
1382
+ disabled
1383
+ }), [state, disabled]);
1384
+ const element = useRenderElement('button', componentProps, {
1385
+ ref: [forwardedRef, buttonRef],
1386
+ state: buttonState,
1387
+ props: [props, elementProps, getButtonProps],
1388
+ stateAttributesMapping: stateAttributesMapping$1
1389
+ });
1390
+ return element;
1391
+ });
1392
+ if (process.env.NODE_ENV !== "production") NumberFieldIncrement.displayName = "NumberFieldIncrement";
1393
+
1394
+ /**
1395
+ * A stepper button that decreases the field value when clicked.
1396
+ * Renders an `<button>` element.
1397
+ *
1398
+ * Documentation: [Base UI Number Field](https://base-ui.com/react/components/number-field)
1399
+ */
1400
+ const NumberFieldDecrement = /*#__PURE__*/React.forwardRef(function NumberFieldDecrement(componentProps, forwardedRef) {
1401
+ const {
1402
+ render,
1403
+ className,
1404
+ disabled: disabledProp = false,
1405
+ nativeButton = true,
1406
+ ...elementProps
1407
+ } = componentProps;
1408
+ const {
1409
+ allowInputSyncRef,
1410
+ disabled: contextDisabled,
1411
+ formatOptionsRef,
1412
+ getStepAmount,
1413
+ id,
1414
+ incrementValue,
1415
+ inputRef,
1416
+ inputValue,
1417
+ intentionalTouchCheckTimeout,
1418
+ isPressedRef,
1419
+ minWithDefault,
1420
+ movesAfterTouchRef,
1421
+ readOnly,
1422
+ setValue,
1423
+ startAutoChange,
1424
+ state,
1425
+ stopAutoChange,
1426
+ value,
1427
+ valueRef,
1428
+ locale,
1429
+ lastChangedValueRef,
1430
+ onValueCommitted
1431
+ } = useNumberFieldRootContext();
1432
+ const isMin = value != null && value <= minWithDefault;
1433
+ const disabled = disabledProp || contextDisabled || isMin;
1434
+ const props = useNumberFieldButton({
1435
+ isIncrement: false,
1436
+ inputRef,
1437
+ startAutoChange,
1438
+ stopAutoChange,
1439
+ inputValue,
1440
+ disabled,
1441
+ readOnly,
1442
+ id,
1443
+ setValue,
1444
+ getStepAmount,
1445
+ incrementValue,
1446
+ allowInputSyncRef,
1447
+ formatOptionsRef,
1448
+ valueRef,
1449
+ isPressedRef,
1450
+ intentionalTouchCheckTimeout,
1451
+ movesAfterTouchRef,
1452
+ locale,
1453
+ lastChangedValueRef,
1454
+ onValueCommitted
1455
+ });
1456
+ const {
1457
+ getButtonProps,
1458
+ buttonRef
1459
+ } = useButton({
1460
+ disabled,
1461
+ native: nativeButton,
1462
+ focusableWhenDisabled: true
1463
+ });
1464
+ const buttonState = React.useMemo(() => ({
1465
+ ...state,
1466
+ disabled
1467
+ }), [state, disabled]);
1468
+ const element = useRenderElement('button', componentProps, {
1469
+ ref: [forwardedRef, buttonRef],
1470
+ state: buttonState,
1471
+ props: [props, elementProps, getButtonProps],
1472
+ stateAttributesMapping: stateAttributesMapping$1
1473
+ });
1474
+ return element;
1475
+ });
1476
+ if (process.env.NODE_ENV !== "production") NumberFieldDecrement.displayName = "NumberFieldDecrement";
1477
+
1478
+ const stateAttributesMapping = {
1479
+ ...fieldValidityMapping,
1480
+ ...stateAttributesMapping$1
1481
+ };
1482
+ const NAVIGATE_KEYS = new Set(['Backspace', 'Delete', 'ArrowLeft', 'ArrowRight', 'Tab', 'Enter', 'Escape']);
1483
+
1484
+ /**
1485
+ * The native input control in the number field.
1486
+ * Renders an `<input>` element.
1487
+ *
1488
+ * Documentation: [Base UI Number Field](https://base-ui.com/react/components/number-field)
1489
+ */
1490
+ const NumberFieldInput = /*#__PURE__*/React.forwardRef(function NumberFieldInput(componentProps, forwardedRef) {
1491
+ const {
1492
+ render,
1493
+ className,
1494
+ ...elementProps
1495
+ } = componentProps;
1496
+ const {
1497
+ allowInputSyncRef,
1498
+ disabled,
1499
+ formatOptionsRef,
1500
+ getAllowedNonNumericKeys,
1501
+ getStepAmount,
1502
+ id,
1503
+ incrementValue,
1504
+ inputMode,
1505
+ inputValue,
1506
+ max,
1507
+ min,
1508
+ name,
1509
+ readOnly,
1510
+ required,
1511
+ setValue,
1512
+ state,
1513
+ setInputValue,
1514
+ locale,
1515
+ inputRef,
1516
+ value,
1517
+ onValueCommitted,
1518
+ lastChangedValueRef,
1519
+ hasPendingCommitRef,
1520
+ valueRef
1521
+ } = useNumberFieldRootContext();
1522
+ const {
1523
+ clearErrors
1524
+ } = useFormContext();
1525
+ const {
1526
+ validationMode,
1527
+ setTouched,
1528
+ setFocused,
1529
+ invalid,
1530
+ shouldValidateOnChange,
1531
+ validation
1532
+ } = useFieldRootContext();
1533
+ const {
1534
+ labelId
1535
+ } = useLabelableContext();
1536
+ const hasTouchedInputRef = React.useRef(false);
1537
+ const blockRevalidationRef = React.useRef(false);
1538
+ useField({
1539
+ id,
1540
+ commit: validation.commit,
1541
+ value,
1542
+ controlRef: inputRef,
1543
+ name,
1544
+ getValue: () => value ?? null
1545
+ });
1546
+ useValueChanged(value, previousValue => {
1547
+ const validateOnChange = shouldValidateOnChange();
1548
+ clearErrors(name);
1549
+ if (validateOnChange) {
1550
+ validation.commit(value);
1551
+ }
1552
+ if (previousValue === value || validateOnChange) {
1553
+ return;
1554
+ }
1555
+ if (blockRevalidationRef.current) {
1556
+ blockRevalidationRef.current = false;
1557
+ return;
1558
+ }
1559
+ validation.commit(value, true);
1560
+ });
1561
+ const inputProps = {
1562
+ id,
1563
+ required,
1564
+ disabled,
1565
+ readOnly,
1566
+ inputMode,
1567
+ value: inputValue,
1568
+ type: 'text',
1569
+ autoComplete: 'off',
1570
+ autoCorrect: 'off',
1571
+ spellCheck: 'false',
1572
+ 'aria-roledescription': 'Number field',
1573
+ 'aria-invalid': invalid || undefined,
1574
+ 'aria-labelledby': labelId,
1575
+ // If the server's locale does not match the client's locale, the formatting may not match,
1576
+ // causing a hydration mismatch.
1577
+ suppressHydrationWarning: true,
1578
+ onFocus(event) {
1579
+ if (event.defaultPrevented || readOnly || disabled) {
1580
+ return;
1581
+ }
1582
+ setFocused(true);
1583
+ if (hasTouchedInputRef.current) {
1584
+ return;
1585
+ }
1586
+ hasTouchedInputRef.current = true;
1587
+
1588
+ // Browsers set selection at the start of the input field by default. We want to set it at
1589
+ // the end for the first focus.
1590
+ const target = event.currentTarget;
1591
+ const length = target.value.length;
1592
+ target.setSelectionRange(length, length);
1593
+ },
1594
+ onBlur(event) {
1595
+ if (event.defaultPrevented || readOnly || disabled) {
1596
+ return;
1597
+ }
1598
+ setTouched(true);
1599
+ setFocused(false);
1600
+ const hadManualInput = !allowInputSyncRef.current;
1601
+ const hadPendingProgrammaticChange = hasPendingCommitRef.current;
1602
+ allowInputSyncRef.current = true;
1603
+ if (inputValue.trim() === '') {
1604
+ setValue(null, createChangeEventDetails(inputClear, event.nativeEvent));
1605
+ if (validationMode === 'onBlur') {
1606
+ validation.commit(null);
1607
+ }
1608
+ onValueCommitted(null, createGenericEventDetails(inputClear, event.nativeEvent));
1609
+ return;
1610
+ }
1611
+ const formatOptions = formatOptionsRef.current;
1612
+ const parsedValue = parseNumber(inputValue, locale, formatOptions);
1613
+ if (parsedValue === null) {
1614
+ return;
1615
+ }
1616
+
1617
+ // If an explicit precision is requested, round the committed numeric value.
1618
+ const hasExplicitPrecision = formatOptions?.maximumFractionDigits != null || formatOptions?.minimumFractionDigits != null;
1619
+ const maxFrac = formatOptions?.maximumFractionDigits;
1620
+ const committed = hasExplicitPrecision && typeof maxFrac === 'number' ? Number(parsedValue.toFixed(maxFrac)) : parsedValue;
1621
+ const nextEventDetails = createGenericEventDetails(inputBlur, event.nativeEvent);
1622
+ const shouldUpdateValue = value !== committed;
1623
+ const shouldCommit = hadManualInput || shouldUpdateValue || hadPendingProgrammaticChange;
1624
+ if (validationMode === 'onBlur') {
1625
+ validation.commit(committed);
1626
+ }
1627
+ if (shouldUpdateValue) {
1628
+ blockRevalidationRef.current = true;
1629
+ setValue(committed, createChangeEventDetails(inputBlur, event.nativeEvent));
1630
+ }
1631
+ if (shouldCommit) {
1632
+ onValueCommitted(committed, nextEventDetails);
1633
+ }
1634
+
1635
+ // Normalize only the displayed text
1636
+ const canonicalText = formatNumber(committed, locale, formatOptions);
1637
+ const maxPrecisionText = formatNumberMaxPrecision(parsedValue, locale, formatOptions);
1638
+ const shouldPreserveFullPrecision = !hasExplicitPrecision && parsedValue === value && inputValue === maxPrecisionText;
1639
+ if (!shouldPreserveFullPrecision && inputValue !== canonicalText) {
1640
+ setInputValue(canonicalText);
1641
+ }
1642
+ },
1643
+ onChange(event) {
1644
+ // Workaround for https://github.com/facebook/react/issues/9023
1645
+ if (event.nativeEvent.defaultPrevented) {
1646
+ return;
1647
+ }
1648
+ allowInputSyncRef.current = false;
1649
+ const targetValue = event.target.value;
1650
+ if (targetValue.trim() === '') {
1651
+ setInputValue(targetValue);
1652
+ setValue(null, createChangeEventDetails(inputClear, event.nativeEvent));
1653
+ return;
1654
+ }
1655
+
1656
+ // Update the input text immediately and only fire onValueChange if the typed value is
1657
+ // currently parseable into a number. This preserves good UX for IME
1658
+ // composition/partial input while still providing live numeric updates when possible.
1659
+ const allowedNonNumericKeys = getAllowedNonNumericKeys();
1660
+ const isValidCharacterString = Array.from(targetValue).every(ch => {
1661
+ const isAsciiDigit = ch >= '0' && ch <= '9';
1662
+ const isArabicNumeral = ARABIC_DETECT_RE.test(ch);
1663
+ const isHanNumeral = HAN_DETECT_RE.test(ch);
1664
+ const isPersianNumeral = PERSIAN_DETECT_RE.test(ch);
1665
+ const isFullwidthNumeral = FULLWIDTH_DETECT_RE.test(ch);
1666
+ const isMinus = ANY_MINUS_DETECT_RE.test(ch);
1667
+ return isAsciiDigit || isArabicNumeral || isHanNumeral || isPersianNumeral || isFullwidthNumeral || isMinus || allowedNonNumericKeys.has(ch);
1668
+ });
1669
+ if (!isValidCharacterString) {
1670
+ return;
1671
+ }
1672
+ const parsedValue = parseNumber(targetValue, locale, formatOptionsRef.current);
1673
+ setInputValue(targetValue);
1674
+ if (parsedValue !== null) {
1675
+ setValue(parsedValue, createChangeEventDetails(inputChange, event.nativeEvent));
1676
+ }
1677
+ },
1678
+ onKeyDown(event) {
1679
+ if (event.defaultPrevented || readOnly || disabled) {
1680
+ return;
1681
+ }
1682
+ const nativeEvent = event.nativeEvent;
1683
+ allowInputSyncRef.current = true;
1684
+ const allowedNonNumericKeys = getAllowedNonNumericKeys();
1685
+ let isAllowedNonNumericKey = allowedNonNumericKeys.has(event.key);
1686
+ const {
1687
+ decimal,
1688
+ currency,
1689
+ percentSign
1690
+ } = getNumberLocaleDetails(locale, formatOptionsRef.current);
1691
+ const selectionStart = event.currentTarget.selectionStart;
1692
+ const selectionEnd = event.currentTarget.selectionEnd;
1693
+ const isAllSelected = selectionStart === 0 && selectionEnd === inputValue.length;
1694
+
1695
+ // Normalize handling of plus/minus signs via precomputed regexes
1696
+ const selectionContainsIndex = index => selectionStart != null && selectionEnd != null && index >= selectionStart && index < selectionEnd;
1697
+ if (ANY_MINUS_DETECT_RE.test(event.key) && Array.from(allowedNonNumericKeys).some(k => ANY_MINUS_DETECT_RE.test(k || ''))) {
1698
+ // Only allow one sign unless replacing the existing one or all text is selected
1699
+ const existingIndex = inputValue.search(ANY_MINUS_RE);
1700
+ const isReplacingExisting = existingIndex != null && existingIndex !== -1 && selectionContainsIndex(existingIndex);
1701
+ isAllowedNonNumericKey = !(ANY_MINUS_DETECT_RE.test(inputValue) || ANY_PLUS_DETECT_RE.test(inputValue)) || isAllSelected || isReplacingExisting;
1702
+ }
1703
+ if (ANY_PLUS_DETECT_RE.test(event.key) && Array.from(allowedNonNumericKeys).some(k => ANY_PLUS_DETECT_RE.test(k || ''))) {
1704
+ const existingIndex = inputValue.search(ANY_PLUS_RE);
1705
+ const isReplacingExisting = existingIndex != null && existingIndex !== -1 && selectionContainsIndex(existingIndex);
1706
+ isAllowedNonNumericKey = !(ANY_MINUS_DETECT_RE.test(inputValue) || ANY_PLUS_DETECT_RE.test(inputValue)) || isAllSelected || isReplacingExisting;
1707
+ }
1708
+
1709
+ // Only allow one of each symbol.
1710
+ [decimal, currency, percentSign].forEach(symbol => {
1711
+ if (event.key === symbol) {
1712
+ const symbolIndex = inputValue.indexOf(symbol);
1713
+ const isSymbolHighlighted = selectionContainsIndex(symbolIndex);
1714
+ isAllowedNonNumericKey = !inputValue.includes(symbol) || isAllSelected || isSymbolHighlighted;
1715
+ }
1716
+ });
1717
+ const isAsciiDigit = event.key >= '0' && event.key <= '9';
1718
+ const isArabicNumeral = ARABIC_DETECT_RE.test(event.key);
1719
+ const isHanNumeral = HAN_DETECT_RE.test(event.key);
1720
+ const isFullwidthNumeral = FULLWIDTH_DETECT_RE.test(event.key);
1721
+ const isNavigateKey = NAVIGATE_KEYS.has(event.key);
1722
+ if (
1723
+ // Allow composition events (e.g., pinyin)
1724
+ // event.nativeEvent.isComposing does not work in Safari:
1725
+ // https://bugs.webkit.org/show_bug.cgi?id=165004
1726
+ event.which === 229 || event.altKey || event.ctrlKey || event.metaKey || isAllowedNonNumericKey || isAsciiDigit || isArabicNumeral || isFullwidthNumeral || isHanNumeral || isNavigateKey) {
1727
+ return;
1728
+ }
1729
+
1730
+ // We need to commit the number at this point if the input hasn't been blurred.
1731
+ const parsedValue = parseNumber(inputValue, locale, formatOptionsRef.current);
1732
+ const amount = getStepAmount(event) ?? DEFAULT_STEP;
1733
+
1734
+ // Prevent insertion of text or caret from moving.
1735
+ stopEvent(event);
1736
+ const commitDetails = createGenericEventDetails(keyboard, nativeEvent);
1737
+ if (event.key === 'ArrowUp') {
1738
+ incrementValue(amount, {
1739
+ direction: 1,
1740
+ currentValue: parsedValue,
1741
+ event: nativeEvent,
1742
+ reason: keyboard
1743
+ });
1744
+ onValueCommitted(lastChangedValueRef.current ?? valueRef.current, commitDetails);
1745
+ } else if (event.key === 'ArrowDown') {
1746
+ incrementValue(amount, {
1747
+ direction: -1,
1748
+ currentValue: parsedValue,
1749
+ event: nativeEvent,
1750
+ reason: keyboard
1751
+ });
1752
+ onValueCommitted(lastChangedValueRef.current ?? valueRef.current, commitDetails);
1753
+ } else if (event.key === 'Home' && min != null) {
1754
+ setValue(min, createChangeEventDetails(keyboard, nativeEvent));
1755
+ onValueCommitted(lastChangedValueRef.current ?? valueRef.current, commitDetails);
1756
+ } else if (event.key === 'End' && max != null) {
1757
+ setValue(max, createChangeEventDetails(keyboard, nativeEvent));
1758
+ onValueCommitted(lastChangedValueRef.current ?? valueRef.current, commitDetails);
1759
+ }
1760
+ },
1761
+ onPaste(event) {
1762
+ if (event.defaultPrevented || readOnly || disabled) {
1763
+ return;
1764
+ }
1765
+
1766
+ // Prevent `onChange` from being called.
1767
+ event.preventDefault();
1768
+ const clipboardData = event.clipboardData || window.Clipboard;
1769
+ const pastedData = clipboardData.getData('text/plain');
1770
+ const parsedValue = parseNumber(pastedData, locale, formatOptionsRef.current);
1771
+ if (parsedValue !== null) {
1772
+ allowInputSyncRef.current = false;
1773
+ setValue(parsedValue, createChangeEventDetails(inputPaste, event.nativeEvent));
1774
+ setInputValue(pastedData);
1775
+ }
1776
+ }
1777
+ };
1778
+ const element = useRenderElement('input', componentProps, {
1779
+ ref: [forwardedRef, inputRef],
1780
+ state,
1781
+ props: [inputProps, validation.getValidationProps(), elementProps],
1782
+ stateAttributesMapping
1783
+ });
1784
+ return element;
1785
+ });
1786
+ if (process.env.NODE_ENV !== "production") NumberFieldInput.displayName = "NumberFieldInput";
1787
+
1788
+ export { DEFAULT_VALIDITY_STATE as D, FieldRootContext as F, LabelableContext as L, NumberFieldRoot as N, useFormContext as a, useFieldRootContext as b, NumberFieldGroup as c, NumberFieldInput as d, NumberFieldIncrement as e, fieldValidityMapping as f, getCombinedFieldValidityData as g, NumberFieldDecrement as h, useLabelableId as i, useField as j, DEFAULT_FIELD_STATE_ATTRIBUTES as k, useNumberFieldRootContext as l, DEFAULT_STEP as m, stateAttributesMapping$1 as s, useLabelableContext as u };