@yamada-ui/number-input 0.0.0-dev-20230603042803

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Hirotomo Yamada
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,28 @@
1
+ # @yamada-ui/number-input
2
+
3
+ ## Installation
4
+
5
+ ```sh
6
+ $ pnpm add @yamada-ui/number-input
7
+ ```
8
+
9
+ or
10
+
11
+ ```sh
12
+ $ yarn add @yamada-ui/number-input
13
+ ```
14
+
15
+ or
16
+
17
+ ```sh
18
+ $ npm install @yamada-ui/number-input
19
+ ```
20
+
21
+ ## Contribution
22
+
23
+ Wouldn't you like to contribute? That's amazing! We have prepared a [contribution guide](https://github.com/hirotomoyamada/yamada-ui/blob/main/CONTRIBUTING.md) to assist you.
24
+
25
+ ## Licence
26
+
27
+ This package is licensed under the terms of the
28
+ [MIT license](https://github.com/hirotomoyamada/yamada-ui/blob/main/LICENSE).
@@ -0,0 +1,538 @@
1
+ // src/number-input.tsx
2
+ import {
3
+ ui,
4
+ forwardRef,
5
+ useMultiComponentStyle,
6
+ omitThemeProps
7
+ } from "@yamada-ui/core";
8
+ import {
9
+ useFormControlProps,
10
+ formControlProperties
11
+ } from "@yamada-ui/form-control";
12
+ import { ChevronIcon } from "@yamada-ui/icon";
13
+ import { useCounter } from "@yamada-ui/use-counter";
14
+ import { useEventListener } from "@yamada-ui/use-event-listener";
15
+ import { useInterval } from "@yamada-ui/use-interval";
16
+ import {
17
+ ariaAttr,
18
+ createContext,
19
+ cx,
20
+ handlerAll,
21
+ mergeRefs,
22
+ omitObject,
23
+ pickObject,
24
+ useCallbackRef,
25
+ useSafeLayoutEffect,
26
+ useUpdateEffect
27
+ } from "@yamada-ui/utils";
28
+ import {
29
+ useCallback,
30
+ useEffect,
31
+ useRef,
32
+ useState
33
+ } from "react";
34
+ import { jsx, jsxs } from "react/jsx-runtime";
35
+ var isDefaultValidCharacter = (character) => /^[Ee0-9+\-.]$/.test(character);
36
+ var isValidNumericKeyboardEvent = ({ key, ctrlKey, altKey, metaKey }, isValid) => {
37
+ if (key == null)
38
+ return true;
39
+ const isModifierKey = ctrlKey || altKey || metaKey;
40
+ const isSingleCharacterKey = key.length === 1;
41
+ if (!isSingleCharacterKey || isModifierKey)
42
+ return true;
43
+ return isValid(key);
44
+ };
45
+ var getStep = ({ ctrlKey, shiftKey, metaKey }) => {
46
+ let ratio = 1;
47
+ if (metaKey || ctrlKey)
48
+ ratio = 0.1;
49
+ if (shiftKey)
50
+ ratio = 10;
51
+ return ratio;
52
+ };
53
+ var useNumberInput = (props = {}) => {
54
+ var _a;
55
+ const {
56
+ id,
57
+ name,
58
+ inputMode = "decimal",
59
+ pattern = "[0-9]*(.[0-9]+)?",
60
+ required,
61
+ disabled,
62
+ readOnly,
63
+ focusInputOnChange = true,
64
+ clampValueOnBlur = true,
65
+ keepWithinRange = true,
66
+ allowMouseWheel,
67
+ min = Number.MIN_SAFE_INTEGER,
68
+ max = Number.MAX_SAFE_INTEGER,
69
+ precision,
70
+ "aria-invalid": isInvalid,
71
+ ...rest
72
+ } = useFormControlProps(props);
73
+ const isRequired = required;
74
+ const isReadOnly = readOnly;
75
+ const isDisabled = disabled;
76
+ const [isFocused, setFocused] = useState(false);
77
+ const isInteractive = !(readOnly || disabled);
78
+ const inputRef = useRef(null);
79
+ const inputSelectionRef = useRef(null);
80
+ const incrementRef = useRef(null);
81
+ const decrementRef = useRef(null);
82
+ const onFocus = useCallbackRef(
83
+ handlerAll(rest.onFocus, (ev) => {
84
+ var _a2, _b, _c;
85
+ setFocused(true);
86
+ if (!inputSelectionRef.current)
87
+ return;
88
+ ev.target.selectionStart = (_b = inputSelectionRef.current.start) != null ? _b : (_a2 = ev.currentTarget.value) == null ? void 0 : _a2.length;
89
+ ev.currentTarget.selectionEnd = (_c = inputSelectionRef.current.end) != null ? _c : ev.currentTarget.selectionStart;
90
+ })
91
+ );
92
+ const onBlur = useCallbackRef(
93
+ handlerAll(rest.onBlur, () => {
94
+ setFocused(false);
95
+ if (clampValueOnBlur)
96
+ validateAndClamp();
97
+ })
98
+ );
99
+ const onInvalid = useCallbackRef(rest.onInvalid);
100
+ const isValidCharacter = useCallbackRef((_a = rest.isValidCharacter) != null ? _a : isDefaultValidCharacter);
101
+ const { isMin, isMax, isOut, value, valueAsNumber, setValue, update, cast, ...counter } = useCounter({
102
+ min,
103
+ max,
104
+ precision,
105
+ keepWithinRange,
106
+ ...rest
107
+ });
108
+ const sanitize = useCallback(
109
+ (value2) => value2.split("").filter(isValidCharacter).join(""),
110
+ [isValidCharacter]
111
+ );
112
+ const parse = useCallback((value2) => {
113
+ var _a2, _b;
114
+ return (_b = (_a2 = rest.parse) == null ? void 0 : _a2.call(rest, value2)) != null ? _b : value2;
115
+ }, [rest]);
116
+ const format = useCallback(
117
+ (value2) => {
118
+ var _a2, _b;
119
+ return ((_b = (_a2 = rest.format) == null ? void 0 : _a2.call(rest, value2)) != null ? _b : value2).toString();
120
+ },
121
+ [rest]
122
+ );
123
+ const increment = useCallback(
124
+ (step = ((_b) => (_b = rest.step) != null ? _b : 1)()) => {
125
+ if (isInteractive)
126
+ counter.increment(step);
127
+ },
128
+ [isInteractive, counter, rest.step]
129
+ );
130
+ const decrement = useCallback(
131
+ (step = ((_c) => (_c = rest.step) != null ? _c : 1)()) => {
132
+ if (isInteractive)
133
+ counter.decrement(step);
134
+ },
135
+ [isInteractive, counter, rest.step]
136
+ );
137
+ const validateAndClamp = useCallback(() => {
138
+ let next = value;
139
+ if (value === "")
140
+ return;
141
+ const valueStartsWithE = /^[eE]/.test(value.toString());
142
+ if (valueStartsWithE) {
143
+ setValue("");
144
+ } else {
145
+ if (valueAsNumber < min)
146
+ next = min;
147
+ if (valueAsNumber > max)
148
+ next = max;
149
+ cast(next);
150
+ }
151
+ }, [cast, max, min, setValue, value, valueAsNumber]);
152
+ const onChange = useCallback(
153
+ (event) => {
154
+ const evt = event.nativeEvent;
155
+ if (evt.isComposing)
156
+ return;
157
+ const parsedInput = parse(event.currentTarget.value);
158
+ update(sanitize(parsedInput));
159
+ inputSelectionRef.current = {
160
+ start: event.currentTarget.selectionStart,
161
+ end: event.currentTarget.selectionEnd
162
+ };
163
+ },
164
+ [parse, update, sanitize]
165
+ );
166
+ const onKeyDown = useCallback(
167
+ (ev) => {
168
+ var _a2;
169
+ if (ev.nativeEvent.isComposing)
170
+ return;
171
+ if (!isValidNumericKeyboardEvent(ev, isValidCharacter))
172
+ ev.preventDefault();
173
+ const step = getStep(ev) * ((_a2 = rest.step) != null ? _a2 : 1);
174
+ const keyMap = {
175
+ ArrowUp: () => increment(step),
176
+ ArrowDown: () => decrement(step),
177
+ Home: () => update(min),
178
+ End: () => update(max)
179
+ };
180
+ const action = keyMap[ev.key];
181
+ if (!action)
182
+ return;
183
+ ev.preventDefault();
184
+ action(ev);
185
+ },
186
+ [decrement, increment, isValidCharacter, max, min, rest.step, update]
187
+ );
188
+ const { up, down, stop, isSpinning } = useSpinner(increment, decrement);
189
+ useAttributeObserver(incrementRef, ["disabled"], isSpinning, stop);
190
+ useAttributeObserver(decrementRef, ["disabled"], isSpinning, stop);
191
+ const focusInput = useCallback(() => {
192
+ if (focusInputOnChange)
193
+ requestAnimationFrame(() => {
194
+ var _a2;
195
+ (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
196
+ });
197
+ }, [focusInputOnChange]);
198
+ const eventUp = useCallback(
199
+ (ev) => {
200
+ ev.preventDefault();
201
+ up();
202
+ focusInput();
203
+ },
204
+ [focusInput, up]
205
+ );
206
+ const eventDown = useCallback(
207
+ (ev) => {
208
+ ev.preventDefault();
209
+ down();
210
+ focusInput();
211
+ },
212
+ [focusInput, down]
213
+ );
214
+ useUpdateEffect(() => {
215
+ if (valueAsNumber > max) {
216
+ onInvalid == null ? void 0 : onInvalid("rangeOverflow", format(value), valueAsNumber);
217
+ } else if (valueAsNumber < min) {
218
+ onInvalid == null ? void 0 : onInvalid("rangeOverflow", format(value), valueAsNumber);
219
+ }
220
+ }, [valueAsNumber, value, format, onInvalid]);
221
+ useSafeLayoutEffect(() => {
222
+ if (!inputRef.current)
223
+ return;
224
+ const notInSync = inputRef.current.value != value;
225
+ if (!notInSync)
226
+ return;
227
+ const parsedInput = parse(inputRef.current.value);
228
+ setValue(sanitize(parsedInput));
229
+ }, [parse, sanitize]);
230
+ useEventListener(
231
+ () => inputRef.current,
232
+ "wheel",
233
+ (ev) => {
234
+ var _a2, _b, _c;
235
+ const ownerDocument = (_b = (_a2 = inputRef.current) == null ? void 0 : _a2.ownerDocument) != null ? _b : document;
236
+ const isFocused2 = ownerDocument.activeElement === inputRef.current;
237
+ if (!allowMouseWheel || !isFocused2)
238
+ return;
239
+ ev.preventDefault();
240
+ const step = getStep(ev) * ((_c = rest.step) != null ? _c : 1);
241
+ const direction = Math.sign(ev.deltaY);
242
+ if (direction === -1) {
243
+ increment(step);
244
+ } else if (direction === 1) {
245
+ decrement(step);
246
+ }
247
+ },
248
+ { passive: false }
249
+ );
250
+ const getInputProps = useCallback(
251
+ (props2 = {}, ref = null) => ({
252
+ id,
253
+ name,
254
+ type: "text",
255
+ inputMode,
256
+ pattern,
257
+ required,
258
+ disabled,
259
+ readOnly,
260
+ ...pickObject(rest, formControlProperties),
261
+ ...omitObject(props2, ["defaultValue"]),
262
+ ref: mergeRefs(inputRef, ref),
263
+ value: format(value),
264
+ "aria-invalid": ariaAttr(isInvalid != null ? isInvalid : isOut),
265
+ autoComplete: "off",
266
+ autoCorrect: "off",
267
+ onChange: handlerAll(props2.onChange, onChange),
268
+ onKeyDown: handlerAll(props2.onKeyDown, onKeyDown),
269
+ onFocus: handlerAll(props2.onFocus, onFocus),
270
+ onBlur: handlerAll(props2.onBlur, onBlur)
271
+ }),
272
+ [
273
+ id,
274
+ name,
275
+ inputMode,
276
+ pattern,
277
+ required,
278
+ disabled,
279
+ readOnly,
280
+ rest,
281
+ format,
282
+ value,
283
+ isInvalid,
284
+ isOut,
285
+ onChange,
286
+ onKeyDown,
287
+ onFocus,
288
+ onBlur
289
+ ]
290
+ );
291
+ const getIncrementProps = useCallback(
292
+ (props2 = {}, ref = null) => {
293
+ const disabled2 = props2.disabled || keepWithinRange && isMax;
294
+ return {
295
+ required,
296
+ readOnly,
297
+ disabled: disabled2,
298
+ ...pickObject(rest, formControlProperties),
299
+ ...props2,
300
+ ref: mergeRefs(ref, incrementRef),
301
+ role: "button",
302
+ tabIndex: -1,
303
+ cursor: readOnly ? "not-allowed" : props2.cursor,
304
+ onPointerDown: handlerAll(props2.onPointerDown, (ev) => {
305
+ if (ev.button === 0 && !disabled2)
306
+ eventUp(ev);
307
+ }),
308
+ onPointerLeave: handlerAll(props2.onPointerLeave, stop),
309
+ onPointerUp: handlerAll(props2.onPointerUp, stop)
310
+ };
311
+ },
312
+ [keepWithinRange, isMax, required, readOnly, rest, stop, eventUp]
313
+ );
314
+ const getDecrementProps = useCallback(
315
+ (props2 = {}, ref = null) => {
316
+ const disabled2 = props2.disabled || keepWithinRange && isMin;
317
+ return {
318
+ required,
319
+ readOnly,
320
+ disabled: disabled2,
321
+ ...pickObject(rest, formControlProperties),
322
+ ...props2,
323
+ ref: mergeRefs(ref, decrementRef),
324
+ role: "button",
325
+ tabIndex: -1,
326
+ cursor: readOnly ? "not-allowed" : props2.cursor,
327
+ onPointerDown: handlerAll(props2.onPointerDown, (ev) => {
328
+ if (ev.button === 0 && !disabled2)
329
+ eventDown(ev);
330
+ }),
331
+ onPointerLeave: handlerAll(props2.onPointerLeave, stop),
332
+ onPointerUp: handlerAll(props2.onPointerUp, stop)
333
+ };
334
+ },
335
+ [keepWithinRange, isMin, required, readOnly, rest, stop, eventDown]
336
+ );
337
+ return {
338
+ value: format(value),
339
+ valueAsNumber,
340
+ isFocused,
341
+ isRequired,
342
+ isReadOnly,
343
+ isDisabled,
344
+ getInputProps,
345
+ getIncrementProps,
346
+ getDecrementProps
347
+ };
348
+ };
349
+ var INTERVAL = 50;
350
+ var DELAY = 300;
351
+ var useSpinner = (increment, decrement) => {
352
+ const [isSpinning, setIsSpinning] = useState(false);
353
+ const [action, setAction] = useState(null);
354
+ const [isOnce, setIsOnce] = useState(true);
355
+ const timeoutRef = useRef(null);
356
+ const removeTimeout = () => clearTimeout(timeoutRef.current);
357
+ useInterval(
358
+ () => {
359
+ if (action === "increment")
360
+ increment();
361
+ if (action === "decrement")
362
+ decrement();
363
+ },
364
+ isSpinning ? INTERVAL : null
365
+ );
366
+ const up = useCallback(() => {
367
+ if (isOnce)
368
+ increment();
369
+ timeoutRef.current = setTimeout(() => {
370
+ setIsOnce(false);
371
+ setIsSpinning(true);
372
+ setAction("increment");
373
+ }, DELAY);
374
+ }, [increment, isOnce]);
375
+ const down = useCallback(() => {
376
+ if (isOnce)
377
+ decrement();
378
+ timeoutRef.current = setTimeout(() => {
379
+ setIsOnce(false);
380
+ setIsSpinning(true);
381
+ setAction("decrement");
382
+ }, DELAY);
383
+ }, [decrement, isOnce]);
384
+ const stop = useCallback(() => {
385
+ setIsOnce(true);
386
+ setIsSpinning(false);
387
+ removeTimeout();
388
+ }, []);
389
+ useEffect(() => {
390
+ return () => removeTimeout();
391
+ }, []);
392
+ return { up, down, stop, isSpinning };
393
+ };
394
+ var useAttributeObserver = (ref, attributeFilter, enabled, func) => {
395
+ useEffect(() => {
396
+ var _a;
397
+ if (!ref.current || !enabled)
398
+ return;
399
+ const ownerDocument = (_a = ref.current.ownerDocument.defaultView) != null ? _a : window;
400
+ const observer = new ownerDocument.MutationObserver((changes) => {
401
+ for (const { type, attributeName } of changes) {
402
+ if (type === "attributes" && attributeName && attributeFilter.includes(attributeName))
403
+ func();
404
+ }
405
+ });
406
+ observer.observe(ref.current, { attributes: true, attributeFilter });
407
+ return () => observer.disconnect();
408
+ });
409
+ };
410
+ var [NumberInputContextProvider, useNumberInputContext] = createContext({
411
+ strict: false,
412
+ name: "NumberInputContext"
413
+ });
414
+ var NumberInput = forwardRef((props, ref) => {
415
+ const [styles, mergedProps] = useMultiComponentStyle("NumberInput", props);
416
+ const {
417
+ className,
418
+ isStepper = true,
419
+ container,
420
+ addon,
421
+ increment,
422
+ decrement,
423
+ onChange,
424
+ ...rest
425
+ } = omitThemeProps(mergedProps);
426
+ const { getInputProps, getIncrementProps, getDecrementProps } = useNumberInput({
427
+ onChange,
428
+ ...rest
429
+ });
430
+ const css = {
431
+ position: "relative",
432
+ zIndex: 0,
433
+ ...styles.container
434
+ };
435
+ return /* @__PURE__ */ jsx(
436
+ NumberInputContextProvider,
437
+ {
438
+ value: { getInputProps, getIncrementProps, getDecrementProps, styles },
439
+ children: /* @__PURE__ */ jsxs(ui.div, { className: cx("ui-number-input", className), __css: css, ...container, children: [
440
+ /* @__PURE__ */ jsx(NumberInputField, { ...getInputProps(rest, ref) }),
441
+ isStepper ? /* @__PURE__ */ jsxs(NumberInputAddon, { ...addon, children: [
442
+ /* @__PURE__ */ jsx(NumberIncrementStepper, { ...increment }),
443
+ /* @__PURE__ */ jsx(NumberDecrementStepper, { ...decrement })
444
+ ] }) : null
445
+ ] })
446
+ }
447
+ );
448
+ });
449
+ var NumberInputField = forwardRef(
450
+ ({ className, ...rest }, ref) => {
451
+ const { styles } = useNumberInputContext();
452
+ const css = {
453
+ width: "100%",
454
+ ...styles.field
455
+ };
456
+ return /* @__PURE__ */ jsx(
457
+ ui.input,
458
+ {
459
+ ref,
460
+ className: cx("ui-number-input-field", className),
461
+ __css: css,
462
+ ...rest
463
+ }
464
+ );
465
+ }
466
+ );
467
+ var NumberInputAddon = forwardRef(({ className, ...rest }, ref) => {
468
+ const { styles } = useNumberInputContext();
469
+ const css = {
470
+ display: "flex",
471
+ flexDirection: "column",
472
+ position: "absolute",
473
+ top: "0",
474
+ insetEnd: "0px",
475
+ margin: "1px",
476
+ height: "calc(100% - 2px)",
477
+ zIndex: 1,
478
+ ...styles.addon
479
+ };
480
+ return /* @__PURE__ */ jsx(
481
+ ui.div,
482
+ {
483
+ ref,
484
+ className: cx("ui-number-input-addon", className),
485
+ "aria-hidden": true,
486
+ __css: css,
487
+ ...rest
488
+ }
489
+ );
490
+ });
491
+ var Stepper = ui("div", {
492
+ baseStyle: {
493
+ display: "flex",
494
+ justifyContent: "center",
495
+ alignItems: "center",
496
+ flex: 1,
497
+ transitionProperty: "common",
498
+ transitionDuration: "normal",
499
+ userSelect: "none",
500
+ cursor: "pointer",
501
+ lineHeight: "normal"
502
+ }
503
+ });
504
+ var NumberIncrementStepper = forwardRef(
505
+ ({ className, children, ...rest }, ref) => {
506
+ const { getIncrementProps, styles } = useNumberInputContext();
507
+ const css = { ...styles.stepper };
508
+ return /* @__PURE__ */ jsx(
509
+ Stepper,
510
+ {
511
+ className: cx("ui-number-input-stepper", className),
512
+ ...getIncrementProps(rest, ref),
513
+ __css: css,
514
+ children: children != null ? children : /* @__PURE__ */ jsx(ChevronIcon, { __css: { transform: "rotate(180deg)" } })
515
+ }
516
+ );
517
+ }
518
+ );
519
+ var NumberDecrementStepper = forwardRef(
520
+ ({ className, children, ...rest }, ref) => {
521
+ const { getDecrementProps, styles } = useNumberInputContext();
522
+ const css = { ...styles.stepper };
523
+ return /* @__PURE__ */ jsx(
524
+ Stepper,
525
+ {
526
+ className: cx("ui-number-input-stepper", className),
527
+ ...getDecrementProps(rest, ref),
528
+ __css: css,
529
+ children: children != null ? children : /* @__PURE__ */ jsx(ChevronIcon, {})
530
+ }
531
+ );
532
+ }
533
+ );
534
+
535
+ export {
536
+ useNumberInput,
537
+ NumberInput
538
+ };
@@ -0,0 +1,6 @@
1
+ export { NumberInput, NumberInputProps, UseNumberInputProps, useNumberInput } from './number-input.js';
2
+ import '@yamada-ui/core';
3
+ import '@yamada-ui/utils';
4
+ import '@yamada-ui/form-control';
5
+ import '@yamada-ui/use-counter';
6
+ import 'react';