@tounsoo/input-number-mask 1.0.1
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 +21 -0
- package/README.md +125 -0
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.mjs +149 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +102 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 tounsoo
|
|
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,125 @@
|
|
|
1
|
+
# @tounsoo/input-number-mask
|
|
2
|
+
|
|
3
|
+
A lightweight, dependency-free React hook for masking input values. Perfect for phone numbers, dates, credit cards, and more.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 0️⃣ **Template-based masking** (e.g., `(ddd) ddd-dddd`)
|
|
8
|
+
- ⌨️ **Intuitive typing & deletion**
|
|
9
|
+
- 📍 **`keepPosition` option** to maintain cursor position and placeholder structure on deletion
|
|
10
|
+
- 🧩 **Headless UI** - completely unstyled, brings your own inputs
|
|
11
|
+
- 📦 **Zero dependencies** (peer dependency on React)
|
|
12
|
+
- 🧪 **Fully tested**
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pnpm add @tounsoo/input-number-mask
|
|
18
|
+
# or
|
|
19
|
+
npm install @tounsoo/input-number-mask
|
|
20
|
+
# or
|
|
21
|
+
yarn add @tounsoo/input-number-mask
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
### Basic Example
|
|
27
|
+
|
|
28
|
+
```tsx
|
|
29
|
+
import { useInputNumberMask } from '@tounsoo/input-number-mask';
|
|
30
|
+
|
|
31
|
+
const PhoneInput = () => {
|
|
32
|
+
const mask = useInputNumberMask({
|
|
33
|
+
template: '(ddd) ddd-dddd',
|
|
34
|
+
placeholder: '(___) ___-____'
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
return (
|
|
38
|
+
<input {...mask} type="tel" />
|
|
39
|
+
);
|
|
40
|
+
};
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Using with `<form>` (Submitting Raw Values)
|
|
44
|
+
|
|
45
|
+
The hook exposes the `rawValue` (unmasked) which you can include in your form submission using a hidden input.
|
|
46
|
+
|
|
47
|
+
```tsx
|
|
48
|
+
import { useInputNumberMask } from '@tounsoo/input-number-mask';
|
|
49
|
+
|
|
50
|
+
export const MyForm = () => {
|
|
51
|
+
// 1. Initialise the mask
|
|
52
|
+
const phoneMask = useInputNumberMask({
|
|
53
|
+
template: '(ddd) ddd-dddd',
|
|
54
|
+
placeholder: '(___) ___-____'
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const handleSubmit = (e) => {
|
|
58
|
+
e.preventDefault();
|
|
59
|
+
const formData = new FormData(e.target);
|
|
60
|
+
|
|
61
|
+
// Access the raw value from the hidden input
|
|
62
|
+
console.log('Phone (Raw):', formData.get('phone_raw'));
|
|
63
|
+
// Output: "1234567890"
|
|
64
|
+
|
|
65
|
+
// Access the formatted value if needed
|
|
66
|
+
console.log('Phone (Formatted):', formData.get('phone_display'));
|
|
67
|
+
// Output: "(123) 456-7890"
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
return (
|
|
71
|
+
<form onSubmit={handleSubmit}>
|
|
72
|
+
<label htmlFor="phone">Phone Number</label>
|
|
73
|
+
{/* The visible input handles the mask interaction */}
|
|
74
|
+
<input
|
|
75
|
+
{...phoneMask}
|
|
76
|
+
name="phone_display"
|
|
77
|
+
id="phone"
|
|
78
|
+
required
|
|
79
|
+
/>
|
|
80
|
+
|
|
81
|
+
{/* Hidden input to submit the clean value */}
|
|
82
|
+
<input
|
|
83
|
+
type="hidden"
|
|
84
|
+
name="phone_raw"
|
|
85
|
+
value={phoneMask.rawValue}
|
|
86
|
+
/>
|
|
87
|
+
|
|
88
|
+
<button type="submit">Submit</button>
|
|
89
|
+
</form>
|
|
90
|
+
);
|
|
91
|
+
};
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Options
|
|
95
|
+
|
|
96
|
+
| Option | Type | Default | Description |
|
|
97
|
+
|Template|`string`|Required|The mask pattern. `d` represents a digit.|
|
|
98
|
+
|Placeholder|`string`|Required| The display string when input is empty or partial.|
|
|
99
|
+
|keepPosition|`boolean`|`false`| If true, deleting a character replaces it with the placeholder char instead of shifting subsequent characters.|
|
|
100
|
+
|
|
101
|
+
## Contributing
|
|
102
|
+
|
|
103
|
+
### Release Process
|
|
104
|
+
|
|
105
|
+
This project uses [Changesets](https://github.com/changesets/changesets) for version management and publishing.
|
|
106
|
+
|
|
107
|
+
**When making changes:**
|
|
108
|
+
|
|
109
|
+
1. Make your code changes
|
|
110
|
+
2. Create a changeset:
|
|
111
|
+
```bash
|
|
112
|
+
pnpm changeset
|
|
113
|
+
```
|
|
114
|
+
3. Follow the prompts to describe your changes and select the version bump type (patch/minor/major)
|
|
115
|
+
4. Commit the changeset file along with your changes
|
|
116
|
+
5. Push to main
|
|
117
|
+
|
|
118
|
+
**Publishing flow:**
|
|
119
|
+
|
|
120
|
+
- When changesets are merged to main, a "Version Packages" PR is automatically created
|
|
121
|
+
- Merging the Version Packages PR will automatically publish to npm
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react"),S=e=>/\d/.test(e),d=(e,s)=>{let l="",n=0;for(let g=0;g<e.length;g++){const c=e[g];if(n>=s.length)break;if(s[n]==="d")S(c)&&(l+=c,n++);else if(s[n]===c)n++;else{let u=n;for(;u<s.length&&s[u]!=="d"&&s[u]!==c;)u++;u<s.length&&s[u]==="d"?S(c)&&(l+=c,n=u+1):u<s.length&&s[u]===c&&(n=u+1)}}return l},h=(e,s,l)=>{let n="",g=0;for(let c=0;c<s.length;c++)if(s[c]==="d"){if(g<e.length)n+=e[g++];else if(l&&c<l.length)n+=l[c];else if(!l)break}else n+=s[c];return n};function R({template:e,placeholder:s,keepPosition:l=!1}){const[n,g]=y.useState(()=>h("",e,s)),[c,u]=y.useState(null),C=y.useRef(null);y.useLayoutEffect(()=>{C.current&&c!==null&&C.current.setSelectionRange(c,c)},[c,n]),y.useLayoutEffect(()=>{const V=C.current;if(!V)return;const k=a=>{const v=a.target,f=v.selectionStart||0,w=v.selectionEnd||0,b=f!==w;if(a.key==="Backspace"){if(f===0&&!b)return;a.preventDefault();let i=f-1;if(b)if(l){let r=n;for(let t=f;t<w;t++)if(e[t]==="d"){const o=s&&t<s.length?s[t]:"_";r=r.substring(0,t)+o+r.substring(t+1)}g(r),u(f);return}else{const r=n.slice(0,f)+n.slice(w),t=d(r,e),o=h(t,e,s);g(o),u(f);return}for(;i>=0&&e[i]!=="d";)i--;if(i<0)return;if(l){const r=s&&i<s.length?s[i]:"_",t=n.substring(0,i)+r+n.substring(i+1);g(t),u(i)}else{const r=n.slice(0,i)+n.slice(i+1),t=d(r,e),o=h(t,e,s);g(o),u(i)}}else if(a.key==="Delete"){if(a.preventDefault(),b)if(l){let r=n;for(let t=f;t<w;t++)if(e[t]==="d"){const o=s&&t<s.length?s[t]:"_";r=r.substring(0,t)+o+r.substring(t+1)}g(r),u(f);return}else{const r=n.slice(0,f)+n.slice(w),t=d(r,e),o=h(t,e,s);g(o),u(f);return}let i=f;for(;i<e.length&&e[i]!=="d";)i++;if(i>=n.length)return;if(l){const r=s&&i<s.length?s[i]:"_",t=n.substring(0,i)+r+n.substring(i+1);g(t),u(f)}else{const r=n.slice(0,i)+n.slice(i+1),t=d(r,e),o=h(t,e,s);g(o),u(f)}}},I=a=>{const v=a.target,f=v.value,w=v.selectionStart||0,b=()=>{const i=f.slice(0,w),r=d(i,e).length,t=d(f,e),o=h(t,e,s);g(o);let x=0,D=0;for(let L=0;L<o.length&&!(x>=r);L++)S(o[L])&&e[L]==="d"&&x++,D++;for(;D<o.length&&e[D]!=="d";)D++;u(D)};if(l&&f.length>n.length){const i=w-1,r=f[i];if(!S(r)){b();return}let t=i;for(;t<e.length&&e[t]!=="d";)t++;if(t>=e.length){b();return}const o=n.substring(0,t)+r+n.substring(t+1);g(o),u(t+1);return}b()};return V.addEventListener("keydown",k),V.addEventListener("input",I),()=>{V.removeEventListener("keydown",k),V.removeEventListener("input",I)}},[n,e,s,l]);const E=d(n,e);return{value:n,displayValue:n,rawValue:E,ref:C}}exports.useInputNumberMask=R;
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/utils/maskUtils.ts","../src/useInputNumberMask.ts"],"sourcesContent":["export const isDigit = (char: string) => /\\d/.test(char);\n\nexport const cleanInput = (input: string, template: string): string => {\n let extracted = '';\n let t = 0;\n\n for (let i = 0; i < input.length; i++) {\n const char = input[i];\n\n if (t >= template.length) {\n break;\n }\n\n if (template[t] === 'd') {\n if (isDigit(char)) {\n extracted += char;\n t++;\n } else {\n // Ignore placeholders or garbage\n }\n } else if (template[t] === char) {\n t++;\n } else {\n let nextT = t;\n while (nextT < template.length && template[nextT] !== 'd' && template[nextT] !== char) {\n nextT++;\n }\n if (nextT < template.length && template[nextT] === 'd') {\n if (isDigit(char)) {\n extracted += char;\n t = nextT + 1;\n }\n } else if (nextT < template.length && template[nextT] === char) {\n t = nextT + 1;\n }\n }\n }\n return extracted;\n};\n\nexport const formatWithMask = (digits: string, template: string, placeholder?: string): string => {\n let res = '';\n let dIdx = 0;\n\n for (let i = 0; i < template.length; i++) {\n const isSlot = template[i] === 'd';\n\n if (isSlot) {\n if (dIdx < digits.length) {\n res += digits[dIdx++];\n } else {\n // Empty slot\n if (placeholder && i < placeholder.length) {\n res += placeholder[i];\n } else {\n if (!placeholder) {\n break;\n }\n }\n }\n } else {\n res += template[i];\n }\n }\n return res;\n};\n","import { useRef, useState, useLayoutEffect } from 'react';\nimport { cleanInput, formatWithMask, isDigit } from './utils/maskUtils';\n\n/**\n * useInputNumberMask\n * \n * A hook for masking number inputs with template support.\n * \n * @param template The mask template. 'd' represents a digit. All other characters are treated as literals.\n * Example: \"+1 (ddd) ddd-dddd\" for US phone numbers.\n * @param placeholder Optional full-length placeholder. Characters that match the template literals \n * will be displayed. 'd' positions can be filled with a placeholder char or kept as is.\n * Example: \"dd/mm/yyyy\" for a date mask \"dd/mm/yyyy\".\n * @param keepPosition If true, deleting a character will replace it with the placeholder char (if valid)\n * or keep the cursor position without shifting subsequent characters (if supported).\n * For now, we'll implement standard behavior where backspace deletes and shifts, \n * unless specific requirements enforce strict position keeping.\n * TODO: fully implement \"keep position\" logic if needed.\n */\nexport interface UseInputNumberMaskProps {\n template: string;\n placeholder?: string;\n keepPosition?: boolean;\n}\n\nexport interface UseInputNumberMaskReturn {\n value: string; // The raw value with formatting (e.g. \"+1 (234) 567-8900\")\n displayValue: string; // The value to display in the input\n rawValue: string; // The unmasked digits (e.g. \"12345678\")\n ref: React.RefObject<HTMLInputElement | null>;\n}\n\nexport function useInputNumberMask({\n template,\n placeholder,\n keepPosition = false,\n}: UseInputNumberMaskProps): UseInputNumberMaskReturn {\n\n const [value, setValue] = useState(() => formatWithMask('', template, placeholder));\n const [cursor, setCursor] = useState<number | null>(null);\n const ref = useRef<HTMLInputElement>(null);\n\n useLayoutEffect(() => {\n if (ref.current && cursor !== null) {\n ref.current.setSelectionRange(cursor, cursor);\n }\n }, [cursor, value]);\n\n // Ref-based Event Handling\n useLayoutEffect(() => {\n const input = ref.current;\n if (!input) return;\n\n const handleKeyDown = (e: globalThis.KeyboardEvent) => {\n const el = e.target as HTMLInputElement;\n const start = el.selectionStart || 0;\n const end = el.selectionEnd || 0;\n const isSelection = start !== end;\n\n if (e.key === 'Backspace') {\n if (start === 0 && !isSelection) return;\n // We prevent default to handle the state update manually\n e.preventDefault();\n\n let deleteIndex = start - 1;\n\n if (isSelection) {\n if (keepPosition) {\n // Replace range with placeholders\n let newVal = value;\n for (let i = start; i < end; i++) {\n if (template[i] === 'd') {\n const pChar = placeholder && i < placeholder.length ? placeholder[i] : '_';\n newVal = newVal.substring(0, i) + pChar + newVal.substring(i + 1);\n }\n }\n setValue(newVal);\n setCursor(start);\n return;\n } else {\n // Standard delete range (shift)\n const newValRaw = value.slice(0, start) + value.slice(end);\n const newDigits = cleanInput(newValRaw, template);\n const formatted = formatWithMask(newDigits, template, placeholder);\n setValue(formatted);\n setCursor(start);\n return;\n }\n }\n\n // Single char backspace\n while (deleteIndex >= 0) {\n const isTemplateLiteral = template[deleteIndex] !== 'd';\n if (isTemplateLiteral) {\n deleteIndex--;\n } else {\n break;\n }\n }\n\n if (deleteIndex < 0) return; // Nothing to delete\n\n if (keepPosition) {\n const pChar = placeholder && deleteIndex < placeholder.length ? placeholder[deleteIndex] : '_';\n const newVal = value.substring(0, deleteIndex) + pChar + value.substring(deleteIndex + 1);\n setValue(newVal);\n setCursor(deleteIndex);\n } else {\n // Shift behavior\n const newValRaw = value.slice(0, deleteIndex) + value.slice(deleteIndex + 1);\n const newDigits = cleanInput(newValRaw, template);\n const formatted = formatWithMask(newDigits, template, placeholder);\n setValue(formatted);\n setCursor(deleteIndex);\n }\n } else if (e.key === 'Delete') {\n e.preventDefault();\n // Delete forward\n if (isSelection) {\n if (keepPosition) {\n let newVal = value;\n for (let i = start; i < end; i++) {\n if (template[i] === 'd') {\n const pChar = placeholder && i < placeholder.length ? placeholder[i] : '_';\n newVal = newVal.substring(0, i) + pChar + newVal.substring(i + 1);\n }\n }\n setValue(newVal);\n setCursor(start);\n return;\n } else {\n const newValRaw = value.slice(0, start) + value.slice(end);\n const newDigits = cleanInput(newValRaw, template);\n const formatted = formatWithMask(newDigits, template, placeholder);\n setValue(formatted);\n setCursor(start);\n return;\n }\n }\n\n // Single char delete\n let deleteIndex = start;\n while (deleteIndex < template.length) {\n const isTemplateLiteral = template[deleteIndex] !== 'd';\n if (isTemplateLiteral) {\n deleteIndex++;\n } else {\n break;\n }\n }\n\n if (deleteIndex >= value.length) return;\n\n if (keepPosition) {\n const pChar = placeholder && deleteIndex < placeholder.length ? placeholder[deleteIndex] : '_';\n const newVal = value.substring(0, deleteIndex) + pChar + value.substring(deleteIndex + 1);\n setValue(newVal);\n setCursor(start);\n } else {\n // Shift behavior\n const newValRaw = value.slice(0, deleteIndex) + value.slice(deleteIndex + 1);\n const newDigits = cleanInput(newValRaw, template);\n const formatted = formatWithMask(newDigits, template, placeholder);\n setValue(formatted);\n setCursor(start);\n }\n }\n };\n\n const handleInput = (e: Event) => {\n // We cast to InputEvent or basic Event. target is HTMLInputElement.\n const target = e.target as HTMLInputElement;\n const inputVal = target.value;\n const rawCursor = target.selectionStart || 0;\n\n // Standard behavior logic\n const standardChange = () => {\n const beforeCursor = inputVal.slice(0, rawCursor);\n const digitsBeforeCursor = cleanInput(beforeCursor, template).length;\n\n const newDigits = cleanInput(inputVal, template);\n const newFormatted = formatWithMask(newDigits, template, placeholder);\n\n setValue(newFormatted);\n\n let currentDigits = 0;\n let newCursor = 0;\n for (let i = 0; i < newFormatted.length; i++) {\n if (currentDigits >= digitsBeforeCursor) {\n break;\n }\n if (isDigit(newFormatted[i]) && template[i] === 'd') {\n currentDigits++;\n }\n newCursor++;\n }\n\n while (newCursor < newFormatted.length && template[newCursor] !== 'd') {\n newCursor++;\n }\n\n setCursor(newCursor);\n };\n\n if (keepPosition) {\n // Measure diff against current state `value` (mapped in closure)\n // NOTE: `value` in this closure is stale if not included in dependency array.\n // We need strict dependency on `value`.\n if (inputVal.length > value.length) {\n const insertIndex = rawCursor - 1;\n const char = inputVal[insertIndex];\n\n if (!isDigit(char)) {\n standardChange();\n return;\n }\n\n let targetIndex = insertIndex;\n while (targetIndex < template.length) {\n if (template[targetIndex] === 'd') {\n break;\n }\n targetIndex++;\n }\n\n if (targetIndex >= template.length) {\n standardChange();\n return;\n }\n\n const newValue = value.substring(0, targetIndex) + char + value.substring(targetIndex + 1);\n\n setValue(newValue);\n setCursor(targetIndex + 1);\n return;\n }\n }\n\n standardChange();\n };\n\n input.addEventListener('keydown', handleKeyDown);\n input.addEventListener('input', handleInput);\n\n return () => {\n input.removeEventListener('keydown', handleKeyDown);\n input.removeEventListener('input', handleInput);\n };\n }, [value, template, placeholder, keepPosition]); // Re-bind when value changes to have fresh closure\n\n const rawValue = cleanInput(value, template);\n\n return {\n value,\n displayValue: value,\n rawValue,\n ref\n };\n}\n"],"names":["isDigit","char","cleanInput","input","template","extracted","t","i","nextT","formatWithMask","digits","placeholder","res","dIdx","useInputNumberMask","keepPosition","value","setValue","useState","cursor","setCursor","ref","useRef","useLayoutEffect","handleKeyDown","e","el","start","end","isSelection","deleteIndex","newVal","pChar","newValRaw","newDigits","formatted","handleInput","target","inputVal","rawCursor","standardChange","beforeCursor","digitsBeforeCursor","newFormatted","currentDigits","newCursor","insertIndex","targetIndex","newValue","rawValue"],"mappings":"yGAAaA,EAAWC,GAAiB,KAAK,KAAKA,CAAI,EAE1CC,EAAa,CAACC,EAAeC,IAA6B,CACnE,IAAIC,EAAY,GACZC,EAAI,EAER,QAASC,EAAI,EAAGA,EAAIJ,EAAM,OAAQI,IAAK,CACnC,MAAMN,EAAOE,EAAMI,CAAC,EAEpB,GAAID,GAAKF,EAAS,OACd,MAGJ,GAAIA,EAASE,CAAC,IAAM,IACZN,EAAQC,CAAI,IACZI,GAAaJ,EACbK,aAIGF,EAASE,CAAC,IAAML,EACvBK,QACG,CACH,IAAIE,EAAQF,EACZ,KAAOE,EAAQJ,EAAS,QAAUA,EAASI,CAAK,IAAM,KAAOJ,EAASI,CAAK,IAAMP,GAC7EO,IAEAA,EAAQJ,EAAS,QAAUA,EAASI,CAAK,IAAM,IAC3CR,EAAQC,CAAI,IACZI,GAAaJ,EACbK,EAAIE,EAAQ,GAETA,EAAQJ,EAAS,QAAUA,EAASI,CAAK,IAAMP,IACtDK,EAAIE,EAAQ,EAEpB,CACJ,CACA,OAAOH,CACX,EAEaI,EAAiB,CAACC,EAAgBN,EAAkBO,IAAiC,CAC9F,IAAIC,EAAM,GACNC,EAAO,EAEX,QAASN,EAAI,EAAGA,EAAIH,EAAS,OAAQG,IAGjC,GAFeH,EAASG,CAAC,IAAM,KAG3B,GAAIM,EAAOH,EAAO,OACdE,GAAOF,EAAOG,GAAM,UAGhBF,GAAeJ,EAAII,EAAY,OAC/BC,GAAOD,EAAYJ,CAAC,UAEhB,CAACI,EACD,WAKZC,GAAOR,EAASG,CAAC,EAGzB,OAAOK,CACX,ECjCO,SAASE,EAAmB,CAC/B,SAAAV,EACA,YAAAO,EACA,aA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A,MACJ,CAEA,IAAIO,EAAcD,EAClB,KAAOC,EAAc3C,EAAS,QACtBA,EAAS2C,CAAW,IAAM,KAG9BA,IAGJ,GAAIA,GAAe3C,EAAS,OAAQ,CAChCoC,EAAA,EACA,MACJ,CAEA,MAAMQ,EAAWhC,EAAM,UAAU,EAAG+B,CAAW,EAAI9C,EAAOe,EAAM,UAAU+B,EAAc,CAAC,EAEzF9B,EAAS+B,CAAQ,EACjB5B,EAAU2B,EAAc,CAAC,EACzB,MACJ,CAGJP,EAAA,CACJ,EAEA,OAAArC,EAAM,iBAAiB,UAAWqB,CAAa,EAC/CrB,EAAM,iBAAiB,QAASiC,CAAW,EAEpC,IAAM,CACTjC,EAAM,oBAAoB,UAAWqB,CAAa,EAClDrB,EAAM,oBAAoB,QAASiC,CAAW,CAClD,CACJ,EAAG,CAACpB,EAAOZ,EAAUO,EAAaI,CAAY,CAAC,EAE/C,MAAMkC,EAAW/C,EAAWc,EAAOZ,CAAQ,EAE3C,MAAO,CACH,MAAAY,EACA,aAAcA,EACd,SAAAiC,EACA,IAAA5B,CAAA,CAER"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { useState as S, useRef as T, useLayoutEffect as E } from "react";
|
|
2
|
+
const k = (e) => /\d/.test(e), d = (e, t) => {
|
|
3
|
+
let l = "", n = 0;
|
|
4
|
+
for (let g = 0; g < e.length; g++) {
|
|
5
|
+
const f = e[g];
|
|
6
|
+
if (n >= t.length)
|
|
7
|
+
break;
|
|
8
|
+
if (t[n] === "d")
|
|
9
|
+
k(f) && (l += f, n++);
|
|
10
|
+
else if (t[n] === f)
|
|
11
|
+
n++;
|
|
12
|
+
else {
|
|
13
|
+
let u = n;
|
|
14
|
+
for (; u < t.length && t[u] !== "d" && t[u] !== f; )
|
|
15
|
+
u++;
|
|
16
|
+
u < t.length && t[u] === "d" ? k(f) && (l += f, n = u + 1) : u < t.length && t[u] === f && (n = u + 1);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return l;
|
|
20
|
+
}, h = (e, t, l) => {
|
|
21
|
+
let n = "", g = 0;
|
|
22
|
+
for (let f = 0; f < t.length; f++)
|
|
23
|
+
if (t[f] === "d") {
|
|
24
|
+
if (g < e.length)
|
|
25
|
+
n += e[g++];
|
|
26
|
+
else if (l && f < l.length)
|
|
27
|
+
n += l[f];
|
|
28
|
+
else if (!l)
|
|
29
|
+
break;
|
|
30
|
+
} else
|
|
31
|
+
n += t[f];
|
|
32
|
+
return n;
|
|
33
|
+
};
|
|
34
|
+
function B({
|
|
35
|
+
template: e,
|
|
36
|
+
placeholder: t,
|
|
37
|
+
keepPosition: l = !1
|
|
38
|
+
}) {
|
|
39
|
+
const [n, g] = S(() => h("", e, t)), [f, u] = S(null), C = T(null);
|
|
40
|
+
E(() => {
|
|
41
|
+
C.current && f !== null && C.current.setSelectionRange(f, f);
|
|
42
|
+
}, [f, n]), E(() => {
|
|
43
|
+
const V = C.current;
|
|
44
|
+
if (!V) return;
|
|
45
|
+
const x = (a) => {
|
|
46
|
+
const D = a.target, c = D.selectionStart || 0, w = D.selectionEnd || 0, b = c !== w;
|
|
47
|
+
if (a.key === "Backspace") {
|
|
48
|
+
if (c === 0 && !b) return;
|
|
49
|
+
a.preventDefault();
|
|
50
|
+
let i = c - 1;
|
|
51
|
+
if (b)
|
|
52
|
+
if (l) {
|
|
53
|
+
let r = n;
|
|
54
|
+
for (let s = c; s < w; s++)
|
|
55
|
+
if (e[s] === "d") {
|
|
56
|
+
const o = t && s < t.length ? t[s] : "_";
|
|
57
|
+
r = r.substring(0, s) + o + r.substring(s + 1);
|
|
58
|
+
}
|
|
59
|
+
g(r), u(c);
|
|
60
|
+
return;
|
|
61
|
+
} else {
|
|
62
|
+
const r = n.slice(0, c) + n.slice(w), s = d(r, e), o = h(s, e, t);
|
|
63
|
+
g(o), u(c);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
for (; i >= 0 && e[i] !== "d"; )
|
|
67
|
+
i--;
|
|
68
|
+
if (i < 0) return;
|
|
69
|
+
if (l) {
|
|
70
|
+
const r = t && i < t.length ? t[i] : "_", s = n.substring(0, i) + r + n.substring(i + 1);
|
|
71
|
+
g(s), u(i);
|
|
72
|
+
} else {
|
|
73
|
+
const r = n.slice(0, i) + n.slice(i + 1), s = d(r, e), o = h(s, e, t);
|
|
74
|
+
g(o), u(i);
|
|
75
|
+
}
|
|
76
|
+
} else if (a.key === "Delete") {
|
|
77
|
+
if (a.preventDefault(), b)
|
|
78
|
+
if (l) {
|
|
79
|
+
let r = n;
|
|
80
|
+
for (let s = c; s < w; s++)
|
|
81
|
+
if (e[s] === "d") {
|
|
82
|
+
const o = t && s < t.length ? t[s] : "_";
|
|
83
|
+
r = r.substring(0, s) + o + r.substring(s + 1);
|
|
84
|
+
}
|
|
85
|
+
g(r), u(c);
|
|
86
|
+
return;
|
|
87
|
+
} else {
|
|
88
|
+
const r = n.slice(0, c) + n.slice(w), s = d(r, e), o = h(s, e, t);
|
|
89
|
+
g(o), u(c);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
let i = c;
|
|
93
|
+
for (; i < e.length && e[i] !== "d"; )
|
|
94
|
+
i++;
|
|
95
|
+
if (i >= n.length) return;
|
|
96
|
+
if (l) {
|
|
97
|
+
const r = t && i < t.length ? t[i] : "_", s = n.substring(0, i) + r + n.substring(i + 1);
|
|
98
|
+
g(s), u(c);
|
|
99
|
+
} else {
|
|
100
|
+
const r = n.slice(0, i) + n.slice(i + 1), s = d(r, e), o = h(s, e, t);
|
|
101
|
+
g(o), u(c);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}, I = (a) => {
|
|
105
|
+
const D = a.target, c = D.value, w = D.selectionStart || 0, b = () => {
|
|
106
|
+
const i = c.slice(0, w), r = d(i, e).length, s = d(c, e), o = h(s, e, t);
|
|
107
|
+
g(o);
|
|
108
|
+
let y = 0, v = 0;
|
|
109
|
+
for (let L = 0; L < o.length && !(y >= r); L++)
|
|
110
|
+
k(o[L]) && e[L] === "d" && y++, v++;
|
|
111
|
+
for (; v < o.length && e[v] !== "d"; )
|
|
112
|
+
v++;
|
|
113
|
+
u(v);
|
|
114
|
+
};
|
|
115
|
+
if (l && c.length > n.length) {
|
|
116
|
+
const i = w - 1, r = c[i];
|
|
117
|
+
if (!k(r)) {
|
|
118
|
+
b();
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
let s = i;
|
|
122
|
+
for (; s < e.length && e[s] !== "d"; )
|
|
123
|
+
s++;
|
|
124
|
+
if (s >= e.length) {
|
|
125
|
+
b();
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const o = n.substring(0, s) + r + n.substring(s + 1);
|
|
129
|
+
g(o), u(s + 1);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
b();
|
|
133
|
+
};
|
|
134
|
+
return V.addEventListener("keydown", x), V.addEventListener("input", I), () => {
|
|
135
|
+
V.removeEventListener("keydown", x), V.removeEventListener("input", I);
|
|
136
|
+
};
|
|
137
|
+
}, [n, e, t, l]);
|
|
138
|
+
const R = d(n, e);
|
|
139
|
+
return {
|
|
140
|
+
value: n,
|
|
141
|
+
displayValue: n,
|
|
142
|
+
rawValue: R,
|
|
143
|
+
ref: C
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
export {
|
|
147
|
+
B as useInputNumberMask
|
|
148
|
+
};
|
|
149
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/utils/maskUtils.ts","../src/useInputNumberMask.ts"],"sourcesContent":["export const isDigit = (char: string) => /\\d/.test(char);\n\nexport const cleanInput = (input: string, template: string): string => {\n let extracted = '';\n let t = 0;\n\n for (let i = 0; i < input.length; i++) {\n const char = input[i];\n\n if (t >= template.length) {\n break;\n }\n\n if (template[t] === 'd') {\n if (isDigit(char)) {\n extracted += char;\n t++;\n } else {\n // Ignore placeholders or garbage\n }\n } else if (template[t] === char) {\n t++;\n } else {\n let nextT = t;\n while (nextT < template.length && template[nextT] !== 'd' && template[nextT] !== char) {\n nextT++;\n }\n if (nextT < template.length && template[nextT] === 'd') {\n if (isDigit(char)) {\n extracted += char;\n t = nextT + 1;\n }\n } else if (nextT < template.length && template[nextT] === char) {\n t = nextT + 1;\n }\n }\n }\n return extracted;\n};\n\nexport const formatWithMask = (digits: string, template: string, placeholder?: string): string => {\n let res = '';\n let dIdx = 0;\n\n for (let i = 0; i < template.length; i++) {\n const isSlot = template[i] === 'd';\n\n if (isSlot) {\n if (dIdx < digits.length) {\n res += digits[dIdx++];\n } else {\n // Empty slot\n if (placeholder && i < placeholder.length) {\n res += placeholder[i];\n } else {\n if (!placeholder) {\n break;\n }\n }\n }\n } else {\n res += template[i];\n }\n }\n return res;\n};\n","import { useRef, useState, useLayoutEffect } from 'react';\nimport { cleanInput, formatWithMask, isDigit } from './utils/maskUtils';\n\n/**\n * useInputNumberMask\n * \n * A hook for masking number inputs with template support.\n * \n * @param template The mask template. 'd' represents a digit. All other characters are treated as literals.\n * Example: \"+1 (ddd) ddd-dddd\" for US phone numbers.\n * @param placeholder Optional full-length placeholder. Characters that match the template literals \n * will be displayed. 'd' positions can be filled with a placeholder char or kept as is.\n * Example: \"dd/mm/yyyy\" for a date mask \"dd/mm/yyyy\".\n * @param keepPosition If true, deleting a character will replace it with the placeholder char (if valid)\n * or keep the cursor position without shifting subsequent characters (if supported).\n * For now, we'll implement standard behavior where backspace deletes and shifts, \n * unless specific requirements enforce strict position keeping.\n * TODO: fully implement \"keep position\" logic if needed.\n */\nexport interface UseInputNumberMaskProps {\n template: string;\n placeholder?: string;\n keepPosition?: boolean;\n}\n\nexport interface UseInputNumberMaskReturn {\n value: string; // The raw value with formatting (e.g. \"+1 (234) 567-8900\")\n displayValue: string; // The value to display in the input\n rawValue: string; // The unmasked digits (e.g. \"12345678\")\n ref: React.RefObject<HTMLInputElement | null>;\n}\n\nexport function useInputNumberMask({\n template,\n placeholder,\n keepPosition = false,\n}: UseInputNumberMaskProps): UseInputNumberMaskReturn {\n\n const [value, setValue] = useState(() => formatWithMask('', template, placeholder));\n const [cursor, setCursor] = useState<number | null>(null);\n const ref = useRef<HTMLInputElement>(null);\n\n useLayoutEffect(() => {\n if (ref.current && cursor !== null) {\n ref.current.setSelectionRange(cursor, cursor);\n }\n }, [cursor, value]);\n\n // Ref-based Event Handling\n useLayoutEffect(() => {\n const input = ref.current;\n if (!input) return;\n\n const handleKeyDown = (e: globalThis.KeyboardEvent) => {\n const el = e.target as HTMLInputElement;\n const start = el.selectionStart || 0;\n const end = el.selectionEnd || 0;\n const isSelection = start !== end;\n\n if (e.key === 'Backspace') {\n if (start === 0 && !isSelection) return;\n // We prevent default to handle the state update manually\n e.preventDefault();\n\n let deleteIndex = start - 1;\n\n if (isSelection) {\n if (keepPosition) {\n // Replace range with placeholders\n let newVal = value;\n for (let i = start; i < end; i++) {\n if (template[i] === 'd') {\n const pChar = placeholder && i < placeholder.length ? placeholder[i] : '_';\n newVal = newVal.substring(0, i) + pChar + newVal.substring(i + 1);\n }\n }\n setValue(newVal);\n setCursor(start);\n return;\n } else {\n // Standard delete range (shift)\n const newValRaw = value.slice(0, start) + value.slice(end);\n const newDigits = cleanInput(newValRaw, template);\n const formatted = formatWithMask(newDigits, template, placeholder);\n setValue(formatted);\n setCursor(start);\n return;\n }\n }\n\n // Single char backspace\n while (deleteIndex >= 0) {\n const isTemplateLiteral = template[deleteIndex] !== 'd';\n if (isTemplateLiteral) {\n deleteIndex--;\n } else {\n break;\n }\n }\n\n if (deleteIndex < 0) return; // Nothing to delete\n\n if (keepPosition) {\n const pChar = placeholder && deleteIndex < placeholder.length ? placeholder[deleteIndex] : '_';\n const newVal = value.substring(0, deleteIndex) + pChar + value.substring(deleteIndex + 1);\n setValue(newVal);\n setCursor(deleteIndex);\n } else {\n // Shift behavior\n const newValRaw = value.slice(0, deleteIndex) + value.slice(deleteIndex + 1);\n const newDigits = cleanInput(newValRaw, template);\n const formatted = formatWithMask(newDigits, template, placeholder);\n setValue(formatted);\n setCursor(deleteIndex);\n }\n } else if (e.key === 'Delete') {\n e.preventDefault();\n // Delete forward\n if (isSelection) {\n if (keepPosition) {\n let newVal = value;\n for (let i = start; i < end; i++) {\n if (template[i] === 'd') {\n const pChar = placeholder && i < placeholder.length ? placeholder[i] : '_';\n newVal = newVal.substring(0, i) + pChar + newVal.substring(i + 1);\n }\n }\n setValue(newVal);\n setCursor(start);\n return;\n } else {\n const newValRaw = value.slice(0, start) + value.slice(end);\n const newDigits = cleanInput(newValRaw, template);\n const formatted = formatWithMask(newDigits, template, placeholder);\n setValue(formatted);\n setCursor(start);\n return;\n }\n }\n\n // Single char delete\n let deleteIndex = start;\n while (deleteIndex < template.length) {\n const isTemplateLiteral = template[deleteIndex] !== 'd';\n if (isTemplateLiteral) {\n deleteIndex++;\n } else {\n break;\n }\n }\n\n if (deleteIndex >= value.length) return;\n\n if (keepPosition) {\n const pChar = placeholder && deleteIndex < placeholder.length ? placeholder[deleteIndex] : '_';\n const newVal = value.substring(0, deleteIndex) + pChar + value.substring(deleteIndex + 1);\n setValue(newVal);\n setCursor(start);\n } else {\n // Shift behavior\n const newValRaw = value.slice(0, deleteIndex) + value.slice(deleteIndex + 1);\n const newDigits = cleanInput(newValRaw, template);\n const formatted = formatWithMask(newDigits, template, placeholder);\n setValue(formatted);\n setCursor(start);\n }\n }\n };\n\n const handleInput = (e: Event) => {\n // We cast to InputEvent or basic Event. target is HTMLInputElement.\n const target = e.target as HTMLInputElement;\n const inputVal = target.value;\n const rawCursor = target.selectionStart || 0;\n\n // Standard behavior logic\n const standardChange = () => {\n const beforeCursor = inputVal.slice(0, rawCursor);\n const digitsBeforeCursor = cleanInput(beforeCursor, template).length;\n\n const newDigits = cleanInput(inputVal, template);\n const newFormatted = formatWithMask(newDigits, template, placeholder);\n\n setValue(newFormatted);\n\n let currentDigits = 0;\n let newCursor = 0;\n for (let i = 0; i < newFormatted.length; i++) {\n if (currentDigits >= digitsBeforeCursor) {\n break;\n }\n if (isDigit(newFormatted[i]) && template[i] === 'd') {\n currentDigits++;\n }\n newCursor++;\n }\n\n while (newCursor < newFormatted.length && template[newCursor] !== 'd') {\n newCursor++;\n }\n\n setCursor(newCursor);\n };\n\n if (keepPosition) {\n // Measure diff against current state `value` (mapped in closure)\n // NOTE: `value` in this closure is stale if not included in dependency array.\n // We need strict dependency on `value`.\n if (inputVal.length > value.length) {\n const insertIndex = rawCursor - 1;\n const char = inputVal[insertIndex];\n\n if (!isDigit(char)) {\n standardChange();\n return;\n }\n\n let targetIndex = insertIndex;\n while (targetIndex < template.length) {\n if (template[targetIndex] === 'd') {\n break;\n }\n targetIndex++;\n }\n\n if (targetIndex >= template.length) {\n standardChange();\n return;\n }\n\n const newValue = value.substring(0, targetIndex) + char + value.substring(targetIndex + 1);\n\n setValue(newValue);\n setCursor(targetIndex + 1);\n return;\n }\n }\n\n standardChange();\n };\n\n input.addEventListener('keydown', handleKeyDown);\n input.addEventListener('input', handleInput);\n\n return () => {\n input.removeEventListener('keydown', handleKeyDown);\n input.removeEventListener('input', handleInput);\n };\n }, [value, template, placeholder, keepPosition]); // Re-bind when value changes to have fresh closure\n\n const rawValue = cleanInput(value, template);\n\n return {\n value,\n displayValue: value,\n rawValue,\n ref\n };\n}\n"],"names":["isDigit","char","cleanInput","input","template","extracted","t","i","nextT","formatWithMask","digits","placeholder","res","dIdx","useInputNumberMask","keepPosition","value","setValue","useState","cursor","setCursor","ref","useRef","useLayoutEffect","handleKeyDown","e","el","start","end","isSelection","deleteIndex","newVal","pChar","newValRaw","newDigits","formatted","handleInput","target","inputVal","rawCursor","standardChange","beforeCursor","digitsBeforeCursor","newFormatted","currentDigits","newCursor","insertIndex","targetIndex","newValue","rawValue"],"mappings":";AAAO,MAAMA,IAAU,CAACC,MAAiB,KAAK,KAAKA,CAAI,GAE1CC,IAAa,CAACC,GAAeC,MAA6B;AACnE,MAAIC,IAAY,IACZC,IAAI;A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;AACA;AAAA,QACJ;AAEA,YAAIO,IAAcD;AAClB,eAAOC,IAAc3C,EAAS,UACtBA,EAAS2C,CAAW,MAAM;AAG9B,UAAAA;AAGJ,YAAIA,KAAe3C,EAAS,QAAQ;AAChC,UAAAoC,EAAA;AACA;AAAA,QACJ;AAEA,cAAMQ,IAAWhC,EAAM,UAAU,GAAG+B,CAAW,IAAI9C,IAAOe,EAAM,UAAU+B,IAAc,CAAC;AAEzF,QAAA9B,EAAS+B,CAAQ,GACjB5B,EAAU2B,IAAc,CAAC;AACzB;AAAA,MACJ;AAGJ,MAAAP,EAAA;AAAA,IACJ;AAEA,WAAArC,EAAM,iBAAiB,WAAWqB,CAAa,GAC/CrB,EAAM,iBAAiB,SAASiC,CAAW,GAEpC,MAAM;AACT,MAAAjC,EAAM,oBAAoB,WAAWqB,CAAa,GAClDrB,EAAM,oBAAoB,SAASiC,CAAW;AAAA,IAClD;AAAA,EACJ,GAAG,CAACpB,GAAOZ,GAAUO,GAAaI,CAAY,CAAC;AAE/C,QAAMkC,IAAW/C,EAAWc,GAAOZ,CAAQ;AAE3C,SAAO;AAAA,IACH,OAAAY;AAAA,IACA,cAAcA;AAAA,IACd,UAAAiC;AAAA,IACA,KAAA5B;AAAA,EAAA;AAER;"}
|
package/package.json
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tounsoo/input-number-mask",
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "A lightweight, dependency-free React hook for masking input values. Perfect for phone numbers, dates, credit cards, and more.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.cjs",
|
|
7
|
+
"module": "./dist/index.mjs",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.mjs"
|
|
14
|
+
},
|
|
15
|
+
"require": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"default": "./dist/index.cjs"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"README.md",
|
|
24
|
+
"LICENSE"
|
|
25
|
+
],
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"react": "^18.0.0 || ^19.0.0",
|
|
28
|
+
"react-dom": "^18.0.0 || ^19.0.0"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@changesets/cli": "^2.29.8",
|
|
32
|
+
"@chromatic-com/storybook": "^5.0.0",
|
|
33
|
+
"@eslint/js": "^9.39.1",
|
|
34
|
+
"@storybook/addon-a11y": "^10.2.7",
|
|
35
|
+
"@storybook/addon-docs": "^10.2.7",
|
|
36
|
+
"@storybook/addon-vitest": "^10.2.7",
|
|
37
|
+
"@storybook/react": "^10.2.7",
|
|
38
|
+
"@storybook/react-vite": "^10.2.7",
|
|
39
|
+
"@testing-library/dom": "^10.4.1",
|
|
40
|
+
"@testing-library/jest-dom": "^6.9.1",
|
|
41
|
+
"@testing-library/react": "^16.3.2",
|
|
42
|
+
"@testing-library/user-event": "^14.6.1",
|
|
43
|
+
"@types/node": "^24.10.1",
|
|
44
|
+
"@types/react": "^19.2.5",
|
|
45
|
+
"@types/react-dom": "^19.2.3",
|
|
46
|
+
"@vitejs/plugin-react": "^5.1.1",
|
|
47
|
+
"@vitest/browser-playwright": "^4.0.18",
|
|
48
|
+
"@vitest/coverage-v8": "^4.0.18",
|
|
49
|
+
"eslint": "^9.39.1",
|
|
50
|
+
"eslint-plugin-react-hooks": "^7.0.1",
|
|
51
|
+
"eslint-plugin-react-refresh": "^0.4.24",
|
|
52
|
+
"eslint-plugin-storybook": "^10.2.7",
|
|
53
|
+
"globals": "^16.5.0",
|
|
54
|
+
"jsdom": "^28.0.0",
|
|
55
|
+
"playwright": "^1.58.2",
|
|
56
|
+
"react": "^19.2.0",
|
|
57
|
+
"react-dom": "^19.2.0",
|
|
58
|
+
"storybook": "^10.2.7",
|
|
59
|
+
"typescript": "~5.9.3",
|
|
60
|
+
"typescript-eslint": "^8.46.4",
|
|
61
|
+
"vite": "^7.2.4",
|
|
62
|
+
"vitest": "^4.0.18"
|
|
63
|
+
},
|
|
64
|
+
"keywords": [
|
|
65
|
+
"react",
|
|
66
|
+
"hook",
|
|
67
|
+
"input",
|
|
68
|
+
"mask",
|
|
69
|
+
"phone",
|
|
70
|
+
"date",
|
|
71
|
+
"credit-card",
|
|
72
|
+
"formatting",
|
|
73
|
+
"form"
|
|
74
|
+
],
|
|
75
|
+
"repository": {
|
|
76
|
+
"type": "git",
|
|
77
|
+
"url": "git+https://github.com/tounsoo/input-number-mask.git"
|
|
78
|
+
},
|
|
79
|
+
"bugs": {
|
|
80
|
+
"url": "https://github.com/tounsoo/input-number-mask/issues"
|
|
81
|
+
},
|
|
82
|
+
"homepage": "https://github.com/tounsoo/input-number-mask#readme",
|
|
83
|
+
"author": "tounsoo",
|
|
84
|
+
"license": "MIT",
|
|
85
|
+
"publishConfig": {
|
|
86
|
+
"access": "public"
|
|
87
|
+
},
|
|
88
|
+
"scripts": {
|
|
89
|
+
"dev": "vite",
|
|
90
|
+
"build": "tsc -b && vite build",
|
|
91
|
+
"build:lib": "tsc -p tsconfig.lib.json && vite build --config vite.config.lib.ts",
|
|
92
|
+
"lint": "eslint .",
|
|
93
|
+
"preview": "vite preview",
|
|
94
|
+
"storybook": "storybook dev -p 6006",
|
|
95
|
+
"build-storybook": "storybook build",
|
|
96
|
+
"test": "vitest run",
|
|
97
|
+
"test:ci": "vitest run --config vitest.config.ci.ts",
|
|
98
|
+
"changeset": "changeset",
|
|
99
|
+
"version": "changeset version",
|
|
100
|
+
"release": "pnpm build:lib && changeset publish"
|
|
101
|
+
}
|
|
102
|
+
}
|