react-input-chips 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/License ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 [B-Meet]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "react-input-chip-beta"), 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,149 @@
1
+ # React-input-chips
2
+
3
+ A package with minimum dependencies and maximum customization.
4
+
5
+ If you want an input field whose value converts to a customizable chip on a click of keys of your choice then this is the best package for you.
6
+
7
+ You have full control over
8
+
9
+ - validation of the field
10
+ - styling of the chips
11
+ - styling of the wrapper
12
+ - chip conversion trigger
13
+
14
+ ## Demo
15
+
16
+ ![react-chips](https://github.com/user-attachments/assets/ba33d40e-63ea-46fa-8011-d418ea211a0a)
17
+
18
+ ## Installation
19
+
20
+ Install react-input-chips with npm
21
+
22
+ ```bash
23
+ npm install react-input-chips
24
+ ```
25
+
26
+ ## Usage/Examples
27
+
28
+ You just need to import the `<InputChips/>` component in the file you want the **react-input-chip** in and pass the required props that's it. All set!
29
+
30
+ **One important thing** for the default styling of the `<InputChips/>` is that you need to explicitly add CSS file import in the parent or higher or the same component.
31
+ The following is the path to it
32
+
33
+ ```bash
34
+ import "../node_modules/react-input-chip-beta/dist/index.css";
35
+ ```
36
+
37
+ Hers is the simple plain example
38
+ ```javascript
39
+ import { useState } from "react";
40
+ import { InputChips } from "react-input-chip-beta";
41
+
42
+ const MyComponent = () => {
43
+ const [chips, setChips] = useState<string[]>([]);
44
+ const [inputValue, setInputValue] = useState("");
45
+
46
+ return (
47
+ <InputChips
48
+ chips={chips}
49
+ inputValue={inputValue}
50
+ setChips={setChips}
51
+ setInputValue={setInputValue}
52
+ />
53
+ );
54
+ };
55
+
56
+ export default MyComponent;
57
+
58
+
59
+ ```
60
+
61
+ ### Validation
62
+
63
+ If you want to add a validation function and the error message then you might try something like the following in the parent component
64
+
65
+ ```javascript
66
+ const MyComponent = () => {
67
+ const [chips, setChips] = useState<string[]>([]);
68
+ const [inputValue, setInputValue] = useState('');
69
+ const [error, setError] = useState<{inputValueError?: string}>({});
70
+
71
+ const validation = () => {
72
+ const tempErr: {inputValueError?: string} = {};
73
+ if (!inputValue.trim().length) {
74
+ tempErr.inputValueError = 'atleast add one message';
75
+ }
76
+
77
+ setError(tempErr);
78
+ return Object.keys(tempErr).length <= 0;
79
+ };
80
+
81
+ return (
82
+ <InputChips
83
+ chips={chips}
84
+ inputValue={inputValue}
85
+ setChips={setChips}
86
+ setInputValue={setInputValue}
87
+ errorMsg={error?.inputValueError}
88
+ validate={validation}
89
+ />
90
+ );
91
+ };
92
+
93
+ ```
94
+
95
+ ## Props and information
96
+
97
+ I have for you here all the props supported as of now. (\* these are required props)
98
+
99
+
100
+ | Prop | Default Value | Description |
101
+ | --------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
102
+ | chips\* | - | This is a react `state` for storing the chips, it has to be an array |
103
+ | setChips\* | - | This is the `setState` for chips state |
104
+ | inputValue\* | - | This will be a react `state` for handling the user input before it turns into a chip |
105
+ | setInputValue\* | - | This is the `setState` for input value |
106
+ | keysToTriggerChipConversion | `[Enter', ',']` | The keys entered in this array will trigger the chip conversion from the input value. (The values allowed in the array are mentioned below in the typescript interface, so you will be able to add the keys from that set only) |
107
+ | backspaceToRemoveChip | false | This will remove the chip when the user hits backspace after the `inputvalue` is cleared |
108
+ | validate | return value `true` | This is the validation function which must return a boolean value either `true` or `false` based on the conditions you want the field value to be valid or convertible into a chip. If the value is valid then n then only a chip will be created out of it |
109
+ | disabled | false | Enable that to disable the input field |
110
+ | placeholder | - | A placeholder for input field |
111
+ | nextPlaceholder | - | Placeholder after the first chip is created |
112
+ | removeBtnSvg | is an `SVG` which looks like close/X | You can add any HTML element as of now, but it is better to add an `SVG` element |
113
+ | chipStyles | - | You add any styles supported by CSS will be added as inline styles for the chip hence, the highest priority is given to your styles |
114
+ | containerStyles | - | You can add the CSS styles for the whole input container itself
115
+ | errorMsg | - | It's the error message you want to display and expects a string as its value
116
+
117
+ keysToTriggerChipConversion - Allowed key codes
118
+ ```
119
+ 'ShiftRight' | 'ShiftLeft' | 'ControlLeft' | 'ControlRight' | 'AltRight'
120
+ | 'AltLeft' | 'MetaLeft' | 'MetaRight' | 'Tab' | 'Enter' | 'Backspace'
121
+ | 'Space' | 'Comma' | 'Period' | 'Slash' | 'Semicolon' | 'ArrowLeft'
122
+ | 'ArrowRight';
123
+ ```
124
+
125
+
126
+ ## Additional Info
127
+
128
+ Hey guys,
129
+
130
+ It is the first npm package I ever released and it's gonna be so much fun. No worries, The supported props in the current version do not have any issues, in case you face any please open an issue or discussion, a PR for a fix would be much appreciated.
131
+
132
+ I am excited to get some initial issues and feature requests and will work on them on priority until version 1.0.0 😅 also after that.
133
+
134
+ What are the future visions as of now?
135
+
136
+ - Remove the explicit addition of the CSS file path
137
+ - Add 100% test cases for the component
138
+ - `removeBtnSvg` expects any HTML element, I want to enforce only SVG element
139
+ - Add a few more features to it
140
+
141
+ Any suggestions are welcome.
142
+
143
+ ## Support
144
+
145
+ For support, email meetbhalodiya1030@gmail.com or open a discussion/issue
146
+
147
+ ## Authors
148
+
149
+ - [@b-meet](https://github.com/b-meet)
package/dist/index.css ADDED
@@ -0,0 +1,43 @@
1
+ /* src/components/styles.css */
2
+ .chip-input-warpper {
3
+ gap: 4px;
4
+ flex: 2;
5
+ padding: 5px;
6
+ overflow: auto;
7
+ display: flex;
8
+ flex-wrap: wrap;
9
+ align-items: center;
10
+ transform: scale(1);
11
+ border: 1px solid #BBBBBB;
12
+ border-radius: 4px;
13
+ .chip {
14
+ background: #f8e3e3;
15
+ border-radius: 4px;
16
+ color: #333333;
17
+ display: flex;
18
+ gap: 0.5rem;
19
+ align-items: center;
20
+ justify-content: space-between;
21
+ max-width: max-content;
22
+ padding: 6px;
23
+ }
24
+ .chip-input {
25
+ border: none;
26
+ outline: none;
27
+ flex: 1;
28
+ padding: 0 8px;
29
+ height: 30px;
30
+ }
31
+ .closeBtn {
32
+ outline: none;
33
+ border: none;
34
+ background: none;
35
+ height: 18px;
36
+ width: 18px;
37
+ object-fit: cover;
38
+ cursor: pointer;
39
+ display: grid;
40
+ place-items: center;
41
+ }
42
+ }
43
+ /*# sourceMappingURL=index.css.map */
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/styles.css"],"sourcesContent":[".chip-input-warpper {\n gap: 4px;\n flex: 2;\n padding: 5px;\n overflow: auto;\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n transform: scale(1);\n border: 1px solid #BBBBBB;\n border-radius: 4px;\n\n .chip {\n background: #f8e3e3;\n border-radius: 4px;\n color: #333333;\n display: flex;\n gap: 0.5rem;\n align-items: center;\n justify-content: space-between;\n max-width: max-content;\n padding: 6px;\n }\n\n .chip-input {\n border: none;\n outline: none;\n flex: 1;\n padding: 0 8px;\n height: 30px;\n }\n\n .closeBtn {\n outline: none;\n border: none;\n background: none;\n height: 18px;\n width: 18px;\n object-fit: cover;\n cursor: pointer;\n display: grid;\n place-items: center;\n }\n}"],"mappings":";AAAA,CAAC;AACE,OAAK;AACL,QAAM;AACN,WAAS;AACT,YAAU;AACV,WAAS;AACT,aAAW;AACX,eAAa;AACb,aAAW,MAAM;AACjB,UAAQ,IAAI,MAAM;AAClB,iBAAe;AAEf,GAAC;AACE,gBAAY;AACZ,mBAAe;AACf,WAAO;AACP,aAAS;AACT,SAAK;AACL,iBAAa;AACb,qBAAiB;AACjB,eAAW;AACX,aAAS;AACZ;AAEA,GAAC;AACE,YAAQ;AACR,aAAS;AACT,UAAM;AACN,aAAS,EAAE;AACX,YAAQ;AACX;AAEA,GAAC;AACE,aAAS;AACT,YAAQ;AACR,gBAAY;AACZ,YAAQ;AACR,WAAO;AACP,gBAAY;AACZ,YAAQ;AACR,aAAS;AACT,iBAAa;AAChB;AACH;","names":[]}
@@ -0,0 +1,21 @@
1
+ import * as react_jsx_runtime from 'react/jsx-runtime';
2
+
3
+ interface TInputChips {
4
+ chips: string[];
5
+ inputValue: string;
6
+ setChips: (val: string[]) => void;
7
+ setInputValue: React.Dispatch<React.SetStateAction<string>>;
8
+ keysToTriggerChipConversion?: string[];
9
+ needWhiteSpace?: boolean;
10
+ validate?: () => boolean;
11
+ disabled?: boolean;
12
+ placeholder?: string;
13
+ nextPlaceholder?: string;
14
+ removeBtnSvg?: React.ReactElement<React.SVGProps<SVGSVGElement>>;
15
+ chipStyles?: React.CSSProperties;
16
+ containerStyles?: React.CSSProperties;
17
+ }
18
+
19
+ declare const InputChips: ({ chips, setChips, inputValue, setInputValue, keysToTriggerChipConversion, needWhiteSpace, validate, disabled, placeholder, nextPlaceholder, removeBtnSvg, chipStyles, containerStyles, }: TInputChips) => react_jsx_runtime.JSX.Element;
20
+
21
+ export { InputChips };
package/dist/index.js ADDED
@@ -0,0 +1,100 @@
1
+ // src/components/InputChip.tsx
2
+ import { jsx, jsxs } from "react/jsx-runtime";
3
+ var InputChips = ({
4
+ chips,
5
+ setChips,
6
+ inputValue,
7
+ setInputValue,
8
+ keysToTriggerChipConversion = ["Enter", ","],
9
+ needWhiteSpace = true,
10
+ validate,
11
+ disabled = false,
12
+ placeholder,
13
+ nextPlaceholder,
14
+ removeBtnSvg,
15
+ chipStyles,
16
+ containerStyles
17
+ }) => {
18
+ const handleInputChange = (e) => {
19
+ if (needWhiteSpace) {
20
+ setInputValue(e.target.value);
21
+ } else {
22
+ setInputValue(e.target.value.trim());
23
+ }
24
+ };
25
+ const handleInputKeyDown = (e) => {
26
+ if (keysToTriggerChipConversion.includes(e.key) && (!validate || validate())) {
27
+ const regex = new RegExp(
28
+ `[${keysToTriggerChipConversion.join("")}]`,
29
+ "g"
30
+ );
31
+ const chip = inputValue.trim().replace(regex, "");
32
+ if (chip) {
33
+ setChips([...chips, chip]);
34
+ setInputValue("");
35
+ }
36
+ e.preventDefault();
37
+ }
38
+ };
39
+ const removeChip = (e, chipToRemove) => {
40
+ e.preventDefault();
41
+ const filteredChips = chips.filter(
42
+ (chip, index) => chip + index !== chipToRemove
43
+ );
44
+ setChips(filteredChips);
45
+ };
46
+ return /* @__PURE__ */ jsxs("div", { className: "chip-input-warpper", style: containerStyles ?? {}, children: [
47
+ chips?.map((chip, index) => /* @__PURE__ */ jsxs(
48
+ "div",
49
+ {
50
+ "data-testid": `input-value-chip-${index}`,
51
+ className: "chip",
52
+ style: chipStyles ?? {},
53
+ children: [
54
+ chip,
55
+ /* @__PURE__ */ jsx(
56
+ "button",
57
+ {
58
+ type: "button",
59
+ className: "closeBtn",
60
+ "data-testid": `remove-chip-btn-${index}`,
61
+ onClick: (e) => removeChip(e, chip + index),
62
+ children: removeBtnSvg || /* @__PURE__ */ jsxs(
63
+ "svg",
64
+ {
65
+ stroke: "currentColor",
66
+ fill: "currentColor",
67
+ strokeWidth: "0",
68
+ viewBox: "0 0 24 24",
69
+ height: 15,
70
+ children: [
71
+ /* @__PURE__ */ jsx("path", { fill: "none", d: "M0 0h24v24H0z" }),
72
+ /* @__PURE__ */ jsx("path", { d: "M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" })
73
+ ]
74
+ }
75
+ )
76
+ }
77
+ )
78
+ ]
79
+ },
80
+ chip + index
81
+ )),
82
+ /* @__PURE__ */ jsx(
83
+ "input",
84
+ {
85
+ className: "chip-input",
86
+ type: "text",
87
+ placeholder: disabled ? "" : chips.length ? nextPlaceholder : placeholder,
88
+ value: inputValue,
89
+ onChange: handleInputChange,
90
+ onKeyDown: handleInputKeyDown,
91
+ disabled
92
+ }
93
+ )
94
+ ] });
95
+ };
96
+ var InputChip_default = InputChips;
97
+ export {
98
+ InputChip_default as InputChips
99
+ };
100
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/InputChip.tsx"],"sourcesContent":["import React from 'react';\nimport './styles.css';\nimport {TInputChips} from '../types';\n\nconst InputChips = ({\n chips,\n setChips,\n inputValue,\n setInputValue,\n keysToTriggerChipConversion = ['Enter', ','],\n needWhiteSpace = true,\n validate,\n disabled = false,\n placeholder,\n nextPlaceholder,\n removeBtnSvg,\n chipStyles,\n containerStyles,\n}: TInputChips) => {\n const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n if (needWhiteSpace) {\n setInputValue(e.target.value);\n } else {\n setInputValue(e.target.value.trim());\n }\n };\n\n const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n if (\n keysToTriggerChipConversion.includes(e.key) &&\n (!validate || validate())\n ) {\n const regex = new RegExp(\n `[${keysToTriggerChipConversion.join('')}]`,\n 'g'\n );\n const chip = inputValue.trim().replace(regex, '');\n\n if (chip) {\n setChips([...chips, chip]);\n setInputValue('');\n }\n\n e.preventDefault();\n }\n };\n\n const removeChip = (\n e: React.MouseEvent<HTMLButtonElement, MouseEvent>,\n chipToRemove: string\n ) => {\n e.preventDefault();\n const filteredChips = chips.filter(\n (chip, index) => chip + index !== chipToRemove\n );\n setChips(filteredChips);\n };\n\n return (\n <div className=\"chip-input-warpper\" style={containerStyles ?? {}}>\n {chips?.map((chip, index) => (\n <div\n key={chip + index}\n data-testid={`input-value-chip-${index}`}\n className=\"chip\"\n style={chipStyles ?? {}}\n >\n {chip}\n <button\n type=\"button\"\n className=\"closeBtn\"\n data-testid={`remove-chip-btn-${index}`}\n onClick={(e) => removeChip(e, chip + index)}\n >\n {removeBtnSvg || (\n <svg\n stroke=\"currentColor\"\n fill=\"currentColor\"\n strokeWidth=\"0\"\n viewBox=\"0 0 24 24\"\n height={15}\n >\n <path fill=\"none\" d=\"M0 0h24v24H0z\"></path>\n <path d=\"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z\"></path>\n </svg>\n )}\n </button>\n </div>\n ))}\n <input\n className=\"chip-input\"\n type=\"text\"\n placeholder={\n disabled ? '' : chips.length ? nextPlaceholder : placeholder\n }\n value={inputValue}\n onChange={handleInputChange}\n onKeyDown={handleInputKeyDown}\n disabled={disabled}\n />\n </div>\n );\n};\n\nexport default InputChips;\n"],"mappings":";AA2E4B,SAOI,KAPJ;AAvE5B,IAAM,aAAa,CAAC;AAAA,EAChB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,8BAA8B,CAAC,SAAS,GAAG;AAAA,EAC3C,iBAAiB;AAAA,EACjB;AAAA,EACA,WAAW;AAAA,EACX;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,MAAmB;AACf,QAAM,oBAAoB,CAAC,MAA2C;AAClE,QAAI,gBAAgB;AAChB,oBAAc,EAAE,OAAO,KAAK;AAAA,IAChC,OAAO;AACH,oBAAc,EAAE,OAAO,MAAM,KAAK,CAAC;AAAA,IACvC;AAAA,EACJ;AAEA,QAAM,qBAAqB,CAAC,MAA6C;AACrE,QACI,4BAA4B,SAAS,EAAE,GAAG,MACzC,CAAC,YAAY,SAAS,IACzB;AACE,YAAM,QAAQ,IAAI;AAAA,QACd,IAAI,4BAA4B,KAAK,EAAE,CAAC;AAAA,QACxC;AAAA,MACJ;AACA,YAAM,OAAO,WAAW,KAAK,EAAE,QAAQ,OAAO,EAAE;AAEhD,UAAI,MAAM;AACN,iBAAS,CAAC,GAAG,OAAO,IAAI,CAAC;AACzB,sBAAc,EAAE;AAAA,MACpB;AAEA,QAAE,eAAe;AAAA,IACrB;AAAA,EACJ;AAEA,QAAM,aAAa,CACf,GACA,iBACC;AACD,MAAE,eAAe;AACjB,UAAM,gBAAgB,MAAM;AAAA,MACxB,CAAC,MAAM,UAAU,OAAO,UAAU;AAAA,IACtC;AACA,aAAS,aAAa;AAAA,EAC1B;AAEA,SACI,qBAAC,SAAI,WAAU,sBAAqB,OAAO,mBAAmB,CAAC,GAC1D;AAAA,WAAO,IAAI,CAAC,MAAM,UACf;AAAA,MAAC;AAAA;AAAA,QAEG,eAAa,oBAAoB,KAAK;AAAA,QACtC,WAAU;AAAA,QACV,OAAO,cAAc,CAAC;AAAA,QAErB;AAAA;AAAA,UACD;AAAA,YAAC;AAAA;AAAA,cACG,MAAK;AAAA,cACL,WAAU;AAAA,cACV,eAAa,mBAAmB,KAAK;AAAA,cACrC,SAAS,CAAC,MAAM,WAAW,GAAG,OAAO,KAAK;AAAA,cAEzC,0BACG;AAAA,gBAAC;AAAA;AAAA,kBACG,QAAO;AAAA,kBACP,MAAK;AAAA,kBACL,aAAY;AAAA,kBACZ,SAAQ;AAAA,kBACR,QAAQ;AAAA,kBAER;AAAA,wCAAC,UAAK,MAAK,QAAO,GAAE,iBAAgB;AAAA,oBACpC,oBAAC,UAAK,GAAE,yGAAwG;AAAA;AAAA;AAAA,cACpH;AAAA;AAAA,UAER;AAAA;AAAA;AAAA,MAxBK,OAAO;AAAA,IAyBhB,CACH;AAAA,IACD;AAAA,MAAC;AAAA;AAAA,QACG,WAAU;AAAA,QACV,MAAK;AAAA,QACL,aACI,WAAW,KAAK,MAAM,SAAS,kBAAkB;AAAA,QAErD,OAAO;AAAA,QACP,UAAU;AAAA,QACV,WAAW;AAAA,QACX;AAAA;AAAA,IACJ;AAAA,KACJ;AAER;AAEA,IAAO,oBAAQ;","names":[]}
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "react-input-chips",
3
+ "private": false,
4
+ "version": "0.3.0",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "type": "module",
9
+ "keywords": [
10
+ "react-input",
11
+ "react-chips",
12
+ "react-chip",
13
+ "chips-input",
14
+ "input-chips",
15
+ "react-chips-input",
16
+ "react-chip-input",
17
+ "react-input-chips",
18
+ "react-chip-component",
19
+ "react-multi-input",
20
+ "tags-input",
21
+ "react-tags-input",
22
+ "multi-value-input",
23
+ "react-custom-input",
24
+ "chip-input",
25
+ "react-tags",
26
+ "react-token-input",
27
+ "input-chip-component"
28
+ ],
29
+ "homepage": "https://github.com/b-meet/react-input-chips",
30
+ "repository": {
31
+ "type": "github",
32
+ "url": "https://github.com/b-meet/react-input-chips"
33
+ },
34
+ "license": "MIT",
35
+ "author": {
36
+ "name": "Meet",
37
+ "email": "meetbhalodiya1030@gmail.com",
38
+ "url": "https://github.com/b-meet"
39
+ },
40
+ "files": [
41
+ "dist",
42
+ "src",
43
+ "dist/**/*.css"
44
+ ],
45
+ "scripts": {
46
+ "dev": "vite",
47
+ "build": "tsup",
48
+ "lint": "eslint .",
49
+ "preview": "vite preview",
50
+ "bundle": "tsup src/index.ts"
51
+ },
52
+ "dependencies": {
53
+ "react": "^18.3.1",
54
+ "react-dom": "^18.3.1"
55
+ },
56
+ "devDependencies": {
57
+ "@eslint/js": "^9.13.0",
58
+ "@types/react": "^18.3.12",
59
+ "@types/react-dom": "^18.3.1",
60
+ "@vitejs/plugin-react-swc": "^3.5.0",
61
+ "eslint": "^9.13.0",
62
+ "eslint-plugin-react-hooks": "^5.0.0",
63
+ "eslint-plugin-react-refresh": "^0.4.14",
64
+ "globals": "^15.11.0",
65
+ "tsup": "^8.3.5",
66
+ "typescript": "~5.6.2",
67
+ "typescript-eslint": "^8.11.0",
68
+ "vite": "^5.4.10"
69
+ }
70
+ }
package/src/App.tsx ADDED
@@ -0,0 +1,34 @@
1
+ import {useState} from 'react';
2
+ import InputChips from './components/InputChip';
3
+
4
+ const App = () => {
5
+ const [chips, setChips] = useState<string[]>([]);
6
+ const [inputValue, setInputValue] = useState('');
7
+ const [error, setError] = useState<{inputValueError?: string}>({});
8
+
9
+ const validation = () => {
10
+ const tempErr: {inputValueError?: string} = {};
11
+ if (!inputValue.trim().length) {
12
+ tempErr.inputValueError = 'atleast add one message';
13
+ }
14
+
15
+ setError(tempErr);
16
+ return Object.keys(tempErr).length <= 0;
17
+ };
18
+
19
+ return (
20
+ <InputChips
21
+ chips={chips}
22
+ inputValue={inputValue}
23
+ setChips={setChips}
24
+ placeholder="Add user names"
25
+ setInputValue={setInputValue}
26
+ nextPlaceholder="You can add upto 10 user names"
27
+ backspaceToRemoveChip
28
+ errorMsg={error?.inputValueError}
29
+ validate={validation}
30
+ />
31
+ );
32
+ };
33
+
34
+ export default App;
@@ -0,0 +1,148 @@
1
+ import React from 'react';
2
+ import './styles.css';
3
+ import {TInputChips, AllowedKeys} from '../types';
4
+
5
+ const InputChips = ({
6
+ chips,
7
+ setChips,
8
+ inputValue,
9
+ setInputValue,
10
+ keysToTriggerChipConversion = ['Enter', 'Comma'],
11
+ validate,
12
+ disabled = false,
13
+ placeholder,
14
+ nextPlaceholder,
15
+ removeBtnSvg,
16
+ chipStyles,
17
+ containerStyles,
18
+ backspaceToRemoveChip = false,
19
+ errorMsg,
20
+ }: TInputChips) => {
21
+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
22
+ const value = e.target.value;
23
+
24
+ if (keysToTriggerChipConversion.includes('Space')) {
25
+ setInputValue(value.trim());
26
+ } else {
27
+ setInputValue(value);
28
+ }
29
+ };
30
+
31
+ const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
32
+ if (
33
+ backspaceToRemoveChip &&
34
+ e.key === 'Backspace' &&
35
+ inputValue.trim() === ''
36
+ ) {
37
+ setChips((prevState) => {
38
+ const updatedChips = [...prevState];
39
+ updatedChips.pop();
40
+ return updatedChips;
41
+ });
42
+ }
43
+
44
+ const isKeyAllowed = (key: string): key is AllowedKeys => {
45
+ return (keysToTriggerChipConversion as AllowedKeys[]).includes(
46
+ key as AllowedKeys
47
+ );
48
+ };
49
+
50
+ if (isKeyAllowed(e.code) && (!validate || validate())) {
51
+ let chip = inputValue.trim();
52
+
53
+ if (keysToTriggerChipConversion.some((key) => key.length === 1)) {
54
+ const regex = new RegExp(
55
+ `[${keysToTriggerChipConversion
56
+ .filter((key) => key.length === 1)
57
+ .map((key) =>
58
+ key.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
59
+ )
60
+ .join('')}]`,
61
+ 'g'
62
+ );
63
+ chip = chip.replace(regex, '');
64
+ }
65
+
66
+ if (chip) {
67
+ setChips([...chips, chip]);
68
+ setInputValue('');
69
+ }
70
+
71
+ e.preventDefault();
72
+ }
73
+ };
74
+
75
+ const removeChip = (
76
+ e: React.MouseEvent<HTMLButtonElement, MouseEvent>,
77
+ chipToRemove: string
78
+ ) => {
79
+ e.preventDefault();
80
+ const filteredChips = chips.filter(
81
+ (chip, index) => chip + index !== chipToRemove
82
+ );
83
+ setChips(filteredChips);
84
+ };
85
+
86
+ return (
87
+ <>
88
+ <section
89
+ className={
90
+ errorMsg?.length
91
+ ? 'chip-input-wrapper chip-input-wrapper-error'
92
+ : 'chip-input-wrapper'
93
+ }
94
+ style={containerStyles ?? {}}
95
+ >
96
+ {chips.map((chip, index) => (
97
+ <div
98
+ key={chip + index}
99
+ data-testid={`input-value-chip-${index}`}
100
+ className="chip"
101
+ style={chipStyles ?? {}}
102
+ >
103
+ {chip}
104
+ <button
105
+ type="button"
106
+ className="closeBtn"
107
+ data-testid={`remove-chip-btn-${index}`}
108
+ onClick={(e) => removeChip(e, chip + index)}
109
+ >
110
+ {removeBtnSvg || (
111
+ <svg
112
+ stroke="currentColor"
113
+ fill="currentColor"
114
+ strokeWidth="0"
115
+ viewBox="0 0 24 24"
116
+ height={15}
117
+ >
118
+ <path fill="none" d="M0 0h24v24H0z"></path>
119
+ <path d="M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path>
120
+ </svg>
121
+ )}
122
+ </button>
123
+ </div>
124
+ ))}
125
+ <input
126
+ className="chip-input"
127
+ type="text"
128
+ placeholder={
129
+ disabled
130
+ ? ''
131
+ : chips.length
132
+ ? nextPlaceholder
133
+ : placeholder
134
+ }
135
+ value={inputValue}
136
+ onChange={handleInputChange}
137
+ onKeyDown={handleInputKeyDown}
138
+ disabled={disabled}
139
+ />
140
+ </section>
141
+ {errorMsg?.length && (
142
+ <p className="error-msg-wrapper">{errorMsg}</p>
143
+ )}
144
+ </>
145
+ );
146
+ };
147
+
148
+ export default InputChips;
@@ -0,0 +1,55 @@
1
+ .chip-input-wrapper {
2
+ gap: 4px;
3
+ flex: 2;
4
+ padding: 5px;
5
+ overflow: auto;
6
+ display: flex;
7
+ flex-wrap: wrap;
8
+ align-items: center;
9
+ border: 1px solid #BBBBBB;
10
+ border-radius: 4px;
11
+ max-width: 650px;
12
+ min-width: 300px;
13
+
14
+ .chip {
15
+ background: #e5e5e5;
16
+ border-radius: 4px;
17
+ color: #333333;
18
+ display: flex;
19
+ gap: 0.5rem;
20
+ align-items: center;
21
+ justify-content: space-between;
22
+ max-width: max-content;
23
+ padding: 6px;
24
+ }
25
+
26
+ .chip-input {
27
+ border: none;
28
+ outline: none;
29
+ flex: 1;
30
+ padding: 0 8px;
31
+ height: 30px;
32
+ }
33
+
34
+ .closeBtn {
35
+ outline: none;
36
+ border: none;
37
+ background: none;
38
+ height: 18px;
39
+ width: 18px;
40
+ object-fit: cover;
41
+ cursor: pointer;
42
+ display: grid;
43
+ place-items: center;
44
+ }
45
+ }
46
+
47
+ .chip-input-wrapper-error {
48
+ border: 2px solid red
49
+ }
50
+
51
+ .error-msg-wrapper {
52
+ margin: 0;
53
+ font-size: 12px;
54
+ color: red
55
+ }
package/src/index.css ADDED
@@ -0,0 +1,12 @@
1
+ :root {
2
+ font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
3
+ font-synthesis: none;
4
+ text-rendering: optimizeLegibility;
5
+ }
6
+
7
+ body {
8
+ display: flex;
9
+ align-items: center;
10
+ justify-content: center;
11
+ min-height: 100vh;
12
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export {default as InputChips} from './components/InputChip';
package/src/main.tsx ADDED
@@ -0,0 +1,10 @@
1
+ import {StrictMode} from 'react';
2
+ import {createRoot} from 'react-dom/client';
3
+ import './index.css';
4
+ import App from './App';
5
+
6
+ createRoot(document.getElementById('root')!).render(
7
+ <StrictMode>
8
+ <App />
9
+ </StrictMode>
10
+ );
@@ -0,0 +1,36 @@
1
+ export type AllowedKeys =
2
+ | 'ShiftRight'
3
+ | 'ShiftLeft'
4
+ | 'ControlLeft'
5
+ | 'ControlRight'
6
+ | 'AltRight'
7
+ | 'AltLeft'
8
+ | 'MetaLeft'
9
+ | 'MetaRight'
10
+ | 'Tab'
11
+ | 'Enter'
12
+ | 'Backspace'
13
+ | 'Space'
14
+ | 'Comma'
15
+ | 'Period'
16
+ | 'Slash'
17
+ | 'Semicolon'
18
+ | 'ArrowLeft'
19
+ | 'ArrowRight';
20
+
21
+ export interface TInputChips {
22
+ chips: string[];
23
+ inputValue: string;
24
+ setChips: React.Dispatch<React.SetStateAction<string[]>>;
25
+ setInputValue: React.Dispatch<React.SetStateAction<string>>;
26
+ keysToTriggerChipConversion?: AllowedKeys[];
27
+ validate?: () => boolean;
28
+ disabled?: boolean;
29
+ placeholder?: string;
30
+ nextPlaceholder?: string;
31
+ removeBtnSvg?: React.ReactElement<React.SVGProps<SVGSVGElement>>;
32
+ chipStyles?: React.CSSProperties;
33
+ containerStyles?: React.CSSProperties;
34
+ backspaceToRemoveChip?: boolean;
35
+ errorMsg?: string;
36
+ }
@@ -0,0 +1 @@
1
+ /// <reference types="vite/client" />