├── .gitignore
├── LICENSE
├── README.md
├── build-config.ts
├── index.js
├── lib
├── global.d.ts
├── index.ts
├── jb-input.scss
├── jb-input.ts
├── render.ts
├── types.ts
└── variables.css
├── package.json
├── react
├── LICENSE
├── README.md
├── index.js
├── lib
│ ├── JBInput.tsx
│ ├── attributes-hook.ts
│ └── events-hook.ts
├── package.json
└── tsconfig.json
├── stories
├── JBInput.stories.tsx
└── samples
│ ├── JBInputStylingTest.css
│ ├── JBInputStylingTest.jsx
│ ├── JBInputTest.jsx
│ └── JBInputValidationList.tsx
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | dist/
2 | react/dist/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 javad
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.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # jb-input
2 |
3 | [](https://www.webcomponents.org/element/jb-input)
4 | [](https://raw.githubusercontent.com/javadbat/jb-input/main/LICENSE)
5 | [](https://www.npmjs.com/package/jb-input)
6 |
7 | text input web component with these benefit:
8 |
9 | - easy to add custom regex or function validation.
10 |
11 | - multiple validation with different message.
12 |
13 | - support both RTL and LTR.
14 |
15 | - add label and message in UX friendly format.
16 |
17 | - customizable ui with css variable sp you can have multiple style in different scope of your app.
18 |
19 | - extendable so you can create your own custom input base on jb-input like [jb-number-input](https://github.com/javadbat/jb-number-input).
20 |
21 | - can accept persian number char and convert them to english char in value.
22 |
23 | sample: [codepen](https://codepen.io/javadbat/pen/dyNwddd)
24 |
25 | ## using with JS frameworks
26 |
27 | to use this component in **react** see [`jb-input/react`](https://github.com/javadbat/jb-input/tree/main/react);
28 |
29 | ## instructions
30 |
31 | ### install
32 |
33 | #### using npm
34 |
35 | ```cmd
36 | npm i jb-input
37 | ```
38 |
39 | in one of your js in page
40 |
41 | ```js
42 | import 'jb-input';
43 |
44 | ```
45 |
46 | in your html or jsx
47 |
48 | ```html
49 |
50 | ```
51 | #### using cdn
52 |
53 | you can just add script tag to your html file and then use web component how ever you need
54 |
55 | ```HTML
56 |
57 | ```
58 |
59 | ### get/set value
60 |
61 | ```js
62 | //get value
63 | const inputValue = document.getElementByTagName('jb-input').value;
64 | //set value
65 | document.getElementByTagName('jb-input').value = "new string";
66 | ```
67 |
68 | ### events
69 |
70 | ```js
71 | document.getElementByTagName('jb-input').addEventListener('change',(event)=>{console.log(event.target.value)});
72 | document.getElementByTagName('jb-input').addEventListener('keyup',(event)=>{console.log(event.target.value)});
73 | document.getElementByTagName('jb-input').addEventListener('keydown',(event)=>{console.log(event.target.value)});
74 | document.getElementByTagName('jb-input').addEventListener('keypress',(event)=>{console.log(event.target.value)});
75 | document.getElementByTagName('jb-input').addEventListener('input',(event)=>{console.log(event.target.value)});
76 | document.getElementByTagName('jb-input').addEventListener('beforeinput',(event)=>{console.log(event.target.value)});
77 | // when user press enter on keyboard(dispatched on onKeyup)
78 | document.getElementByTagName('jb-input').addEventListener('enter',(event)=>{console.log(event.target.value)});
79 | ```
80 |
81 | ### set validation
82 |
83 | jb-input use [jb-validation](https://github.com/javadbat/jb-validation) inside to handle validation. so for more information you can read [jb-validation](https://github.com/javadbat/jb-validation) documentation.
84 | for simple usage you can set validation to your input:
85 |
86 | ```js
87 | //you have 2 ways:
88 | //1- set list directly
89 | titleInput.validation.list = [
90 | {
91 | validator: /.{3}/g,
92 | message: 'عنوان حداقل باید سه کارکتر طول داشته باشد'
93 | },
94 | //you can use function as a validator too
95 | {
96 | validator: ({displayValue,value})=>{return value == "سلام"},
97 | message: 'شما تنها میتوانید عبارت سلام را وارد کنید'
98 | },
99 | //you can also return string in validator if you want custom error message in some edge cases
100 | {
101 | validator: ({displayValue,value})=>{
102 | if(value.includes("*")){
103 | return 'you cant write * in your text'
104 | }
105 | return true;
106 | },
107 | message: 'default error when return false'
108 | },
109 | ];
110 | //2- pass a function that returns the validation list so on each validation process we execute your callback function and get the needed validation list
111 | const result = document.getElementByTagName('jb-input').validation.addValidationListGetter(getterFunction)
112 | ```
113 |
114 | ### check validation
115 |
116 | like any other jb design system you can access validation by `validation` property:
117 | ```js
118 | //access validation module
119 | document.getElementByTagName('jb-input').validation
120 | // check if input pass all the validations. showError is a boolean that determine your intent to show error to user on invalid status.
121 | const result = await document.getElementByTagName('jb-input').validation.checkValidity({showError})
122 | //or
123 | const result = document.getElementByTagName('jb-input').validation.checkValiditySync({showError})
124 | //return boolean of if inputted string is valid
125 | const result = document.getElementByTagName('jb-input').checkValidity()
126 | //or return boolean and show error
127 | const result = document.getElementByTagName('jb-input').reportValidity()
128 |
129 | ```
130 | ### intercept user input
131 |
132 | I don't recommend this in most cases but sometimes you need to change what user input in the text field or prevent user from typing or paste the wrong value into the field in this scenario we have a tools to let you do this. to doing so just register a interceptor function like this:
133 | ```ts
134 | this.validation.addStandardValueCallback((inputtedString:string, oldValue:JBInputValue, prevResult:JBInputValue):JBInputValue=>{
135 | //here you can check new string, old value and the value object that return by previous StandardValueCallback if you register multiple callback to modify value
136 | return {
137 | // the value we return as dom.value
138 | value:string,
139 | //the value we ser into the input box that final user see
140 | displayValue:string
141 | }
142 | });
143 | ```
144 |
145 | ### custom inputs
146 | if you want something more than just simple input please check this components that use jb-input but add extra validation and input check layer for better user experience:
147 | - [jb-number-input](https://github.com/javadbat/jb-number-input) for input number
148 | - [jb-payment-input](https://github.com/javadbat/jb-payment-input) for input bank card number and SHABA number
149 | - [jb-date-input](https://github.com/javadbat/jb-date-input) for input date value
150 | - [jb-national-input](https://github.com/javadbat/jb-national-input) for input national ID (کد ملی) value
151 | - [jb-mobile-input](https://github.com/javadbat/jb-mobile-input) for input mobile value
152 | - [jb-time-input](https://github.com/javadbat/jb-time-input) for input time value
153 |
154 | ### other attribute
155 |
156 | | attribute name | description |
157 | | ------------- | ------------- |
158 | | name | name you want to set to actual input element `` |
159 | | message | in bottom of input we show small message for example "user name must be at least 5 char" |
160 | | error | error message to show under the input box |
161 | | autocomplete | set autocomplete directly into dom element in case you need it |
162 | | direction | set web-component direction default set is rtl but if you need ltr use `` |
163 | | disabled | disable the input |
164 | | inputmode | set input mode help mobile device to open proper keyboard for your input like `url`, `search` and `numeric` |
165 |
166 | ### set custom style
167 |
168 | you have 2 way to customize style,
169 |
170 | 1. using selectors like`:states` or `::part` selector
171 | ```css
172 | jb-input::part(label){
173 | font-size: 2rem;
174 | }
175 | jb-input:states(invalid)::part(label){
176 | color:red;
177 | }
178 | ```
179 | we have `label`, `input-box`, `input`, `message` as a supported part in our component. you can also combine them with `disabled`, `invalid` states for different style in different states.
180 |
181 | 2. using css variable
182 |
183 | | css variable name | description |
184 | | ------------- | ------------- |
185 | | --jb-input-margin | web-component margin default is `0 0` |
186 | | --jb-input-border-radius | web-component border-radius default is `16px` |
187 | | --jb-input-border-color | border color of select in normal mode |
188 | | --jb-input-border-color-focus | border color of select in normal mode |
189 | | --jb-input-bgcolor | background color of input |
190 | | --jb-input-border-bottom-width | border bottom thickness default is `3px` |
191 | | --jb-input-label-font-size | font size of input label default is `0.8em` |
192 | | --jb-input-label-color | change label color |
193 | | --jb-input-label-margin | change label margin default is `0 4px` |
194 | | --jb-input-message-font-size | font size of message we show under input |
195 | | --jb-input-message-color | set under box message color |
196 | | --jb-input-message-error-color | change color of error we show under input |
197 | | --jb-input-height | height of input default is 40px |
198 | | --jb-input-placeholder-color | change placeholder color |
199 | | --jb-input-placeholder-font-size | change placeholder font-size |
200 | | --jb-input-value-font-size | input value font-size |
201 | | --jb-input-value-color | input value color |
202 | | --jb-input-input-padding | set input inner padding default is `2px 12px 0 12px` |
203 | | --jb-input-input-text-align | set input element text align for example if you have number Input and want to make it left |
204 | | --jb-input-input-direction | set input element direction to other than inherited value from it's parent element |
205 | | --jb-input-input-font-weight | set input value font-weight default is `initial` (browser setting) |
206 | | --jb-input-box-shadow | set box shadow of input |
207 | | --jb-input-box-shadow-focus | set box shadow of input on focus |
208 | | --jb-input-border-width | border width default is `1px` |
209 | | --jb-input-label-margin | label margin default is `0` |
210 | | --jb-input-label-font-weight | label font weight default is `300` |
211 | | --jb-input-box-overflow | input box overflow default is `hidden` |
212 |
213 | ## add custom element in input box
214 |
215 | in jb-input you can put icon or any other custom html DOM in input box. to doing so you just have to place custom DOM in `jb-input` tag and add `slot="start-section"` or `slot="end-section"` to place it before or after input field.
216 | example:
217 |
218 | ```HTML
219 |
220 |
after
221 |
before
222 |
223 | ```
224 |
225 | ## Other Related Docs:
226 |
227 | - see [jb-input/react](https://github.com/javadbat/jb-input/tree/main/react) if you want to use this component in react.
228 |
229 | - see [All JB Design system Component List](https://github.com/javadbat/design-system/blob/main/docs/component-list.md) for more components.
230 |
231 | - use [Contribution Guide](https://github.com/javadbat/design-system/blob/main/docs/contribution-guide.md) if you want to contribute in this component.
--------------------------------------------------------------------------------
/build-config.ts:
--------------------------------------------------------------------------------
1 | import type { ReactComponentBuildConfig, WebComponentBuildConfig } from "../../tasks/build/builder/src/types.ts";
2 |
3 | export const webComponentList: WebComponentBuildConfig[] = [
4 | {
5 | name: "jb-input",
6 | path: "./lib/index.ts",
7 | outputPath: "./dist/index.js",
8 | umdName: "JBInput",
9 | external: ["jb-validation", "jb-form", "jb-core"],
10 | globals: {
11 | "jb-validation": "JBValidation",
12 | "jb-core":"JBCore"
13 | },
14 | },
15 | ];
16 | export const reactComponentList: ReactComponentBuildConfig[] = [
17 | {
18 | name: "jb-input-react",
19 | path: "./react/lib/JBInput.tsx",
20 | outputPath: "./react/dist/JBInput.js",
21 | external: ["jb-core", "jb-core/react","jb-input", "prop-types", "react"],
22 | globals: {
23 | react: "React",
24 | "prop-types": "PropTypes",
25 | "jb-input": "JBInput",
26 | "jb-core": "JBCore",
27 | "jb-core/react": "JBCoreReact",
28 | },
29 | umdName:"JBInputReact",
30 | dir:"./react"
31 | },
32 | ];
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | export * from './dist/index.js';
2 |
--------------------------------------------------------------------------------
/lib/global.d.ts:
--------------------------------------------------------------------------------
1 | type FileStringModules = {
2 | readonly default: string;
3 | }
4 | declare module '*.scss' {
5 | const value: FileStringModules;
6 | export default value;
7 | }
8 | declare module '*.html' {
9 | const value: FileStringModules;
10 | export default value.default;
11 | }
12 | declare module '*.svg' {
13 | const value: string;
14 | export default value;
15 | }
--------------------------------------------------------------------------------
/lib/index.ts:
--------------------------------------------------------------------------------
1 | export * from './jb-input.js';
2 | export * from './types.js';
--------------------------------------------------------------------------------
/lib/jb-input.scss:
--------------------------------------------------------------------------------
1 | @use './variables.css';
2 |
3 | :host(:focus),
4 | :host(:focus-visible) {
5 | outline: none;
6 | }
7 |
8 | .jb-input-web-component {
9 | width: 100%;
10 | margin: var(--jb-input-margin, 0 0);
11 | &:focus-visible {
12 | outline: none;
13 | }
14 | label {
15 | width: 100%;
16 | margin: var(--jb-input-label-margin, 0.25rem 0px);
17 | display: block;
18 | font-size: var(--jb-input-label-font-size, 0.8em);
19 | color: var(--label-color);
20 | margin: var(--jb-input-label-margin, 0);
21 | font-weight: var(--jb-input-label-font-weight, 300);
22 | &.--hide {
23 | display: none;
24 | }
25 | }
26 | .input-box {
27 | width: 100%;
28 | box-sizing: border-box;
29 | height: var(--jb-input-height, 40px);
30 | border: solid var(--jb-input-border-width, 1px) var(--border-color);
31 | background-color: var(--input-box-bg-color);
32 | border-bottom: solid var(--jb-input-border-bottom-width, 3px) var(--border-color);
33 | border-radius: var(--border-radius);
34 | margin: 4px 0px;
35 | transition: ease 0.3s all;
36 | overflow: var(--jb-input-box-overflow, hidden);
37 | display: grid;
38 | grid-template-columns: auto 1fr auto;
39 | box-shadow: var(--jb-input-box-shadow, none);
40 | &:focus-within {
41 | border-width: var(--jb-input-border-width-focus, var(--jb-input-border-width, 1px));
42 | border-bottom-width: var(--jb-input-border-bottom-width-focus, var(--jb-input-border-bottom-width, 3px));
43 | box-shadow: var(--jb-input-box-shadow-focus, none);
44 | }
45 | input {
46 | border: none;
47 | width: 100%;
48 | box-sizing: border-box;
49 | height: 100%;
50 | background-color: transparent;
51 | padding: var(--jb-input-input-padding, 0.125rem 0.75rem 0 0.75rem);
52 | display: block;
53 | font-family: inherit;
54 | font-size: var(--jb-input-value-font-size, 1.1rem);
55 | color: var(--value-color);
56 | margin: 0;
57 | border-radius: 0;
58 | text-align: var(--jb-input-input-text-align, initial);
59 | direction: var(--jb-input-input-direction, inherit);
60 | font-weight: var(--jb-input-input-font-weight, initial);
61 | &:focus {
62 | outline: none;
63 | }
64 | &::placeholder {
65 | color: var(--placeholder-color);
66 | font-size: var(--jb-input-placeholder-font-size, 1.1rem);
67 | }
68 | //remove number input arrow keys of browser
69 | /* Chrome, Safari, Edge, Opera */
70 | &::-webkit-outer-spin-button,
71 | &::-webkit-inner-spin-button {
72 | -webkit-appearance: none;
73 | margin: 0;
74 | }
75 |
76 | /* Firefox */
77 | &[type="number"] {
78 | -moz-appearance: textfield;
79 | }
80 | }
81 | .jb-input-start-section-wrapper{
82 | display: flex;
83 | height: 100%;
84 | width: auto;
85 | align-items: center;
86 | justify-content: center;
87 | }
88 | ::slotted([slot="start-section"]), ::slotted([slot="end-section"]){
89 | height: 100%;
90 | display: flex;
91 | justify-content: center;
92 | align-items: center;
93 | max-height: 100%;
94 | overflow-y: hidden;
95 | background-color: transparent;
96 | padding: 8px 16px;
97 | width: auto;
98 | box-sizing: border-box;
99 | }
100 | }
101 | .message-box {
102 | font-size: var(--jb-input-message-font-size, 0.7rem);
103 | padding: 0.125rem 0.5rem;
104 | color: var(--message-color);
105 | display: var(--jb-input-message-box-display, block);
106 | &:empty {
107 | padding: 0;
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/lib/jb-input.ts:
--------------------------------------------------------------------------------
1 | import CSS from "./jb-input.scss";
2 | import { type ValidationItem, type ValidationResult, type WithValidation, ValidationHelper, type ShowValidationErrorParameters } from 'jb-validation';
3 | import type { JBFormInputStandards } from 'jb-form';
4 | import type {
5 | ValueSetterEventType,
6 | ElementsObject,
7 | JBInputValue,
8 | StandardValueCallbackFunc,
9 | ValidationValue,
10 | SupportedState,
11 | } from "./types";
12 | import { renderHTML } from "./render";
13 | import { createInputEvent, createKeyboardEvent, listenAndSilentEvent } from "jb-core";
14 | import {registerDefaultVariables} from 'jb-core/theme';
15 | export class JBInputWebComponent extends HTMLElement implements WithValidation, JBFormInputStandards {
16 | static get formAssociated() {
17 | return true;
18 | }
19 | #value: JBInputValue = {
20 | displayValue: "",
21 | value: ""
22 | };
23 | elements!: ElementsObject;
24 | #disabled = false;
25 | get disabled() {
26 | return this.#disabled;
27 | }
28 | set disabled(value: boolean) {
29 | this.#disabled = value;
30 | this.elements.input.disabled = value;
31 | if (value) {
32 | //TODO: remove as any when typescript support
33 | // biome-ignore lint/suspicious/noExplicitAny:
34 | (this.#internals as any).states?.add("disabled");
35 | } else {
36 | // biome-ignore lint/suspicious/noExplicitAny:
37 | (this.#internals as any).states?.delete("disabled");
38 | }
39 | }
40 | #required = false;
41 | set required(value: boolean) {
42 | this.#required = value;
43 | this.#checkValidity(false);
44 | }
45 | get required() {
46 | return this.#required;
47 | }
48 | #internals?: ElementInternals;
49 | hasState(state:SupportedState):boolean {
50 | return (this.#internals as any).states.has(state);
51 | }
52 | /**
53 | * @description will determine if component trigger jb-validation mechanism automatically on user event or it just let user-developer handle validation mechanism by himself
54 | */
55 | get isAutoValidationDisabled(): boolean {
56 | //currently we only support disable-validation in attribute and only in initiate time but later we can add support for change of this
57 | return this.getAttribute('disable-auto-validation') === '' || this.getAttribute('disable-auto-validation') === 'true' ? true : false;
58 | }
59 | #checkValidity(showError: boolean) {
60 | if (!this.isAutoValidationDisabled) {
61 | return this.#validation.checkValidity({ showError });
62 | }
63 | }
64 | #validation = new ValidationHelper({
65 | clearValidationError: () => this.clearValidationError(),
66 | showValidationError: this.showValidationError.bind(this),
67 | getValue: () => this.#value,
68 | getValidations: this.#getInsideValidation.bind(this),
69 | getValueString: () => this.#value.displayValue,
70 | setValidationResult: this.#setValidationResult.bind(this)
71 | });
72 | get validation() {
73 | return this.#validation;
74 | }
75 | get displayValue() {
76 | return this.#value.displayValue;
77 | }
78 | get value(): string {
79 | //do not write any logic or task here this function will be overrides by other inputs like mobile input or payment input
80 | return this.#value.value;
81 | }
82 | //do not call it from inside and use #setValue in inside
83 | set value(value: string) {
84 | //do not write any logic or task here this function will be overrides by other inputs like mobile input or payment input
85 | this.#setValue(value, "SET_VALUE");
86 | }
87 | #setValue(value: string, eventType: ValueSetterEventType) {
88 | if (value === null || value === undefined) {
89 | value = "";
90 | }
91 | const standardValue = this.standardValue(value, eventType);
92 | this.#setValueByObject(standardValue);
93 | }
94 | #setValueByObject(valueOnj: JBInputValue) {
95 | this.#value = valueOnj;
96 | //comment for typescript problem
97 | if (this.#internals && typeof this.#internals.setFormValue == "function") {
98 | this.#internals.setFormValue(valueOnj.value);
99 | }
100 | this.elements.input.value = valueOnj.displayValue;
101 | }
102 | initialValue = "";
103 | get isDirty(): boolean {
104 | return this.#value.value !== this.initialValue;
105 | }
106 | //selection input behavior
107 | get selectionStart(): number {
108 | return this.elements.input.selectionStart;
109 | }
110 | set selectionStart(value: number) {
111 | this.elements.input.selectionStart = value;
112 | }
113 | get selectionEnd(): number {
114 | return this.elements.input.selectionEnd;
115 | }
116 | set selectionEnd(value: number) {
117 | this.elements.input.selectionEnd = value;
118 | }
119 | get selectionDirection(): "forward" | "backward" | "none" {
120 | return this.elements.input.selectionDirection;
121 | }
122 | set selectionDirection(value: "forward" | "backward" | "none") {
123 | this.elements.input.selectionDirection = value;
124 | }
125 | get name() {
126 | return this.getAttribute('name') || '';
127 | }
128 | // end of selection input behavior
129 | constructor() {
130 | super();
131 | if (typeof this.attachInternals == "function") {
132 | //some browser dont support attachInternals
133 | this.#internals = this.attachInternals();
134 | }
135 | this.#initWebComponent();
136 | }
137 | connectedCallback(): void {
138 | // standard web component event that called when all of dom is banded
139 | this.#callOnLoadEvent();
140 | this.initProp();
141 | this.#callOnInitEvent();
142 | }
143 | #callOnLoadEvent(): void {
144 | const event = new CustomEvent("load", { bubbles: true, composed: true });
145 | this.dispatchEvent(event);
146 | }
147 | #callOnInitEvent(): void {
148 | const event = new CustomEvent("init", { bubbles: true, composed: true });
149 | this.dispatchEvent(event);
150 | }
151 | #initWebComponent(): void {
152 | const shadowRoot = this.attachShadow({
153 | mode: "open",
154 | delegatesFocus: true,
155 | });
156 | registerDefaultVariables();
157 | this.#render();
158 | this.elements = {
159 | // biome-ignore lint/style/noNonNullAssertion:
160 | input: shadowRoot.querySelector(".input-box input")!,
161 | // biome-ignore lint/style/noNonNullAssertion:
162 | inputBox: shadowRoot.querySelector(".input-box")!,
163 | // biome-ignore lint/style/noNonNullAssertion:
164 | label: shadowRoot.querySelector("label")!,
165 | // biome-ignore lint/style/noNonNullAssertion:
166 | labelValue: shadowRoot.querySelector("label .label-value")!,
167 | // biome-ignore lint/style/noNonNullAssertion:
168 | messageBox: shadowRoot.querySelector(".message-box")!,
169 | slots: {
170 | // biome-ignore lint/style/noNonNullAssertion:
171 | startSection: shadowRoot.querySelector(".jb-input-start-section-wrapper slot")!,
172 | // biome-ignore lint/style/noNonNullAssertion:
173 | endSection: shadowRoot.querySelector(".jb-input-end-section-wrapper slot")!
174 | }
175 | };
176 | this.#registerEventListener();
177 | }
178 | #render() {
179 | const html = `\n${renderHTML()}`;
180 | const element = document.createElement("template");
181 | element.innerHTML = html;
182 | this.shadowRoot.appendChild(element.content.cloneNode(true));
183 | }
184 | #standardValueCallbacks: StandardValueCallbackFunc[] = []
185 | addStandardValueCallback(func: StandardValueCallbackFunc) {
186 | this.#standardValueCallbacks.push(func);
187 | }
188 | /**
189 | * @description this function will get user inputted or pasted text and convert it to standard one base on developer config
190 | */
191 | standardValue(valueString: string | number, eventType: ValueSetterEventType): JBInputValue {
192 | let standardValue: JBInputValue = {
193 | displayValue: valueString.toString(),
194 | value: valueString.toString(),
195 | };
196 | standardValue = this.#standardValueCallbacks.reduce((acc, func) => {
197 | const res = func(valueString.toString(), this.#value, acc, eventType);
198 | return res;
199 | }, standardValue);
200 | return standardValue;
201 | }
202 |
203 | #registerEventListener(): void {
204 | this.elements.input.addEventListener("change", (e: Event) => this.#onInputChange(e), { capture: false });
205 | this.elements.input.addEventListener("beforeinput", this.#onInputBeforeInput.bind(this), { capture: false });
206 | this.elements.input.addEventListener("input", (e) => this.#onInputInput(e as InputEvent), { capture: false });
207 | //because keyboard event are composable and will scape from shadow dom we need to listen to them in document and stop their propagation
208 | listenAndSilentEvent(this.elements.input, "keyup", this.#onInputKeyup.bind(this));
209 | listenAndSilentEvent(this.elements.input, "keydown", this.#onInputKeyDown.bind(this));
210 | listenAndSilentEvent(this.elements.input, "keypress", this.#onInputKeyPress.bind(this));
211 | }
212 | initProp() {
213 | this.#setValue(this.getAttribute("value") || "", "SET_VALUE");
214 | }
215 | static get observedAttributes(): string[] {
216 | return [
217 | "label",
218 | "type",
219 | "message",
220 | "value",
221 | "name",
222 | "autocomplete",
223 | "placeholder",
224 | "disabled",
225 | "inputmode",
226 | "readonly",
227 | 'disable-auto-validation',
228 | "virtualkeyboardpolicy",
229 | "required",
230 | "error",
231 | ];
232 | }
233 | //please do not add any other functionality in this func because it may override by enstatite d component
234 | attributeChangedCallback(name: string, oldValue: string, newValue: string): void {
235 | // do something when an attribute has changed
236 | this.onAttributeChange(name, newValue);
237 | }
238 | protected onAttributeChange(name: string, value: string): void {
239 | switch (name) {
240 | case "name":
241 | case "autocomplete":
242 | case "inputmode":
243 | case "readonly":
244 | case "virtualkeyboardpolicy":
245 | this.elements.input.setAttribute(name, value);
246 | break;
247 | case "label":
248 | this.elements.labelValue.innerHTML = value;
249 | if (value == null || value === undefined || value === "") {
250 | this.elements.label.classList.add("--hide");
251 | } else {
252 | this.elements.label.classList.remove("--hide");
253 | }
254 | break;
255 | case "type":
256 | this.elements.input.setAttribute("type", value);
257 | if (value == "number") {
258 | if (this.getAttribute("inputmode") == null) {
259 | this.setAttribute("inputmode", "numeric");
260 | }
261 | }
262 | break;
263 | case "message":
264 | if (!this.elements.messageBox.classList.contains("error")) {
265 | this.elements.messageBox.innerHTML = value;
266 | }
267 | break;
268 | case "value":
269 | this.#setValue(value, "SET_VALUE");
270 | break;
271 |
272 | case "placeholder":
273 | this.elements.input.placeholder = value;
274 | break;
275 | case "disabled":
276 | if (value === "" || value === "true") {
277 | this.disabled = true;
278 | } else if (value === "false" || value == null || value === undefined) {
279 | this.disabled = false;
280 | this.elements.input.removeAttribute("disabled");
281 | }
282 | break;
283 | case "required":
284 | //to update validation result base on new requirement
285 | this.required = value ? value !== 'false' : false;
286 | break;
287 | case "error":
288 | //to check error and show or clear error message base on error attribute
289 | this.reportValidity();
290 | }
291 | }
292 |
293 |
294 | #onInputKeyDown(e: KeyboardEvent): void {
295 | this.#dispatchKeydownEvent(e);
296 | }
297 | #dispatchKeydownEvent(e: KeyboardEvent) {
298 | e.stopPropagation();
299 | //trigger component event
300 | const event = createKeyboardEvent("keydown", e, { cancelable: true });
301 | const isPrevented = !this.dispatchEvent(event);
302 | if (isPrevented) {
303 | e.preventDefault();
304 | }
305 | }
306 | #onInputKeyPress(e: KeyboardEvent): void {
307 | e.stopPropagation();
308 | const event = createKeyboardEvent("keypress", e, { cancelable: false });
309 | this.dispatchEvent(event);
310 | }
311 | #onInputKeyup(e: KeyboardEvent): void {
312 | this.#dispatchKeyupEvent(e);
313 | if (e.keyCode == 13) {
314 | this.#onInputEnter(e);
315 | }
316 | }
317 | #dispatchKeyupEvent(e: KeyboardEvent) {
318 | e.stopPropagation();
319 | const event = createKeyboardEvent("keyup", e, { cancelable: false });
320 | this.dispatchEvent(event);
321 | }
322 | #onInputEnter(e:KeyboardEvent): void {
323 | const event = createKeyboardEvent("enter",e,{cancelable:false})
324 | this.dispatchEvent(event);
325 | }
326 | /**
327 | *
328 | * @param {InputEvent} e
329 | */
330 | #onInputInput(e: InputEvent): void {
331 | const endCaretPos = (e.target as HTMLInputElement).selectionEnd || 0;
332 | const startCaretPos = (e.target as HTMLInputElement).selectionStart || 0;
333 | const inputText = (e.target as HTMLInputElement).value;
334 | const target = (e.target as HTMLInputElement);
335 | //to standard value again
336 | this.#setValue(inputText, "INPUT");
337 | //if user type in middle of text we will return the caret position to the middle of text because this.value = inputText will move caret to end
338 | if (endCaretPos !== inputText.length) {
339 | //because number input does not support setSelectionRange
340 | if (!['number'].includes(this.getAttribute('type'))) {
341 | target.setSelectionRange(endCaretPos, endCaretPos);
342 | }
343 |
344 | }
345 | //e.target.setSelectionRange(startCaretPos + e.data, endCaretPos);
346 | this.#checkValidity(false);
347 | this.#dispatchOnInputEvent(e);
348 | }
349 | #dispatchOnInputEvent(e: InputEvent): void {
350 | e.stopPropagation();
351 | const event = createInputEvent('input', e, { cancelable: true });
352 | this.dispatchEvent(event);
353 | }
354 |
355 | #onInputBeforeInput(e: InputEvent): void {
356 | this.#dispatchBeforeInputEvent(e);
357 | }
358 | #dispatchBeforeInputEvent(e: InputEvent): boolean {
359 | e.stopPropagation();
360 | const event = createInputEvent('beforeinput', e, { cancelable: true });
361 | this.dispatchEvent(event);
362 | if (event.defaultPrevented) {
363 | e.preventDefault();
364 | }
365 | return event.defaultPrevented;
366 | }
367 | #onInputChange(e: Event): void {
368 | const inputText = (e.target as HTMLInputElement).value;
369 | //here is the rare time we update value directly because we want trigger event that may read value directly from dom
370 | const oldValue = this.#value;
371 | this.#setValue(inputText, "CHANGE");
372 | this.#checkValidity(true);
373 | const isCanceled = this.#dispatchOnChangeEvent(e);
374 | if (isCanceled) {
375 | this.#value = oldValue;
376 | e.preventDefault();
377 | }
378 | }
379 | #dispatchOnChangeEvent(e: Event): boolean {
380 | e.stopPropagation();
381 | const eventInit: EventInit = {
382 | bubbles: e.bubbles,
383 | cancelable: e.cancelable,
384 | composed: e.composed
385 | };
386 | const event = new Event("change", eventInit);
387 | this.dispatchEvent(event);
388 | if (event.defaultPrevented) {
389 | return true;
390 | }
391 | return false;
392 | }
393 | showValidationError(error: ShowValidationErrorParameters) {
394 | this.elements.messageBox.innerHTML = error.message;
395 | //invalid state is used for ui purpose
396 | (this.#internals as any).states?.add("invalid");
397 | }
398 | clearValidationError() {
399 | const text = this.getAttribute("message") || "";
400 | this.elements.messageBox.innerHTML = text;
401 | (this.#internals as any).states?.delete("invalid");
402 | }
403 | /**
404 | * @public
405 | */
406 | focus() {
407 | //public method
408 | this.elements.input.focus();
409 | }
410 | setSelectionRange(start: number | null, end: number | null, direction?: "forward" | "backward" | "none") {
411 | this.elements.input.setSelectionRange(start, end, direction);
412 | }
413 | #getInsideValidation(): ValidationItem[] {
414 | const validationList: ValidationItem[] = [];
415 | if (this.required) {
416 | validationList.push({
417 | validator: /.{1}/g,
418 | message: `${this.getAttribute("label")} میبایست حتما وارد شود`,
419 | stateType: "valueMissing"
420 | });
421 | }
422 | if(this.getAttribute("error") !== null && this.getAttribute("error").trim().length > 0){
423 | validationList.push({
424 | validator: undefined,
425 | message: this.getAttribute("error"),
426 | stateType: "customError"
427 | });
428 | }
429 | return validationList;
430 | }
431 | /**
432 | * @public
433 | * @description this method used to check for validity but doesn't show error to user and just return the result
434 | * this method used by #internal of component
435 | */
436 | checkValidity(): boolean {
437 | const validationResult = this.#validation.checkValiditySync({ showError: false });
438 | if (!validationResult.isAllValid) {
439 | const event = new CustomEvent('invalid');
440 | this.dispatchEvent(event);
441 | }
442 | return validationResult.isAllValid;
443 | }
444 | /**
445 | * @public
446 | * @description this method used to check for validity and show error to user
447 | */
448 | reportValidity(): boolean {
449 | const validationResult = this.#validation.checkValiditySync({ showError: true });
450 | if (!validationResult.isAllValid) {
451 | const event = new CustomEvent('invalid');
452 | this.dispatchEvent(event);
453 | }
454 | return validationResult.isAllValid;
455 | }
456 | /**
457 | * @description this method called on every checkValidity calls and update validation result of #internal
458 | */
459 | #setValidationResult(result: ValidationResult) {
460 | if (result.isAllValid) {
461 | this.#internals.setValidity({}, '');
462 | } else {
463 | const states: ValidityStateFlags = {};
464 | let message = "";
465 | result.validationList.forEach((res) => {
466 | if (!res.isValid) {
467 | if (res.validation.stateType) { states[res.validation.stateType] = true; }
468 | if (message == '') { message = res.message; }
469 | }
470 | });
471 | this.#internals.setValidity(states, message);
472 | }
473 | }
474 | get validationMessage() {
475 | return this.#internals.validationMessage;
476 | }
477 | }
478 | const myElementNotExists = !customElements.get("jb-input");
479 | if (myElementNotExists) {
480 | window.customElements.define("jb-input", JBInputWebComponent);
481 | }
482 |
--------------------------------------------------------------------------------
/lib/render.ts:
--------------------------------------------------------------------------------
1 | export function renderHTML():string{
2 | return /* html */ `
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 | `;
17 | }
--------------------------------------------------------------------------------
/lib/types.ts:
--------------------------------------------------------------------------------
1 | import { type JBInputWebComponent } from "./jb-input";
2 | import {type EventTypeWithTarget} from 'jb-core';
3 | export type ElementsObject = {
4 | input: HTMLInputElement;
5 | inputBox: HTMLDivElement;
6 | label: HTMLLabelElement;
7 | labelValue: HTMLSpanElement;
8 | messageBox: HTMLDivElement;
9 | slots:{
10 | startSection:HTMLSlotElement;
11 | endSection:HTMLSlotElement;
12 | };
13 | };
14 | /**
15 | * @description "INPUT" is for onInput, "SET_VALUE" is for when value set from outside of component by dom.value="" or in attribute value set, and change call in onChange mean's it execute after blur
16 | */
17 | export type ValueSetterEventType = "INPUT" | "SET_VALUE" | "CHANGE"
18 | /**
19 | * @description this function used by derived input component so they can make different between display value and value value.
20 | * @param prevResult result of prev callback function it maybe useful in some cases when user add chain of value standard
21 | * @param eventType when standard value is called. its for filter some standard function in some events, for example disable min value check on input number and let user do blur before some standard function be applied
22 | */
23 | export type StandardValueCallbackFunc = (inputtedString:string, oldValue:JBInputValue, prevResult:JBInputValue, eventType:ValueSetterEventType)=>JBInputValue
24 | export type JBInputValue = {
25 | // the value we return as dom.value
26 | value:string,
27 | //the value we ser into the input box that final user see
28 | displayValue:string
29 | }
30 | export type SupportedState = "disabled" | "invalid"
31 | export type ValidationValue = JBInputValue;
32 | //because this._internal is not a standard we have to extend HTML ELEMENT to use it
33 | declare global {
34 | interface ElementInternals{
35 | setFormValue(value:string):void;
36 | }
37 | }
38 |
39 | export type JBInputEventType = EventTypeWithTarget
--------------------------------------------------------------------------------
/lib/variables.css:
--------------------------------------------------------------------------------
1 | :host{
2 | --border-radius:var(--jb-input-border-radius, var(--jb-radius));
3 | /*colors*/
4 | --border-color:var(--jb-input-border-color, var(--jb-neutral-10));
5 | --message-color:var(--jb-input-message-color, var(--jb-text-secondary));
6 | --label-color: var(--jb-input-label-color, var(--jb-text-primary));
7 | --value-color: var(--jb-input-value-color, var(--jb-text-primary));
8 | --placeholder-color: var(--jb-input-placeholder-color, var(--jb-neutral-6));
9 | --input-box-bg-color:var(--jb-input-bgcolor, var(--jb-neutral-10));
10 | }
11 | :host(:state(invalid)){
12 | --message-color:var(--jb-input-message-error-color, var(--jb-red));
13 | }
14 | :host(:focus-within){
15 | --border-color:var(--jb-input-border-color-focus, var(--jb-neutral));
16 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "jb-input",
3 | "description": "input web component with built in validation",
4 | "type": "module",
5 | "author": {
6 | "name": "mohammad javad bathaei",
7 | "email": "javadbat@gmail.com"
8 | },
9 | "keywords": [
10 | "jb",
11 | "jb-input",
12 | "input box",
13 | "input with validation",
14 | "input",
15 | "web component",
16 | "react component"
17 | ],
18 | "version": "3.11.1",
19 | "bugs": "https://github.com/javadbat/jb-input/issues",
20 | "license": "MIT",
21 | "files": [
22 | "LICENSE",
23 | "README.md",
24 | "lib/",
25 | "dist/",
26 | "react/",
27 | "react/dist/"
28 | ],
29 | "main": "index.js",
30 | "types": "./dist/index.d.ts",
31 | "sideEffects": true,
32 | "repository": {
33 | "type": "git",
34 | "url": "git@github.com:javadbat/jb-input.git"
35 | },
36 | "dependencies": {
37 | "jb-validation": ">=0.4.0",
38 | "jb-core":">=0.14.0"
39 | },
40 | "devDependencies": {
41 | "jb-form":">=0.6.10"
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/react/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 javad
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.
22 |
--------------------------------------------------------------------------------
/react/README.md:
--------------------------------------------------------------------------------
1 | # JBInput React
2 |
3 | this component is React.js wrapper for [jb-input](https://www.npmjs.com/package/jb-input) web component.
4 |
5 | text input `react component` with these benefits:
6 |
7 | - easy to add custom regex or function validation.
8 |
9 | - multiple validation with different message.
10 |
11 | - support both RTL and LTR.
12 |
13 | - add label and message in UX friendly format.
14 |
15 | - customizable ui with css variable so you can have multiple style in different scope of your app.
16 |
17 | - support typescript.
18 |
19 | - extendable so you can create your own custom input base on jb-input like [jb-number-input](https://github.com/javadbat/jb-number-input).
20 |
21 | Demo : Demo: [codeSandbox preview](https://3f63dj.csb.app/samples/jb-input) for just see the demo and [codeSandbox editor](https://codesandbox.io/p/sandbox/jb-design-system-3f63dj?file=%2Fsrc%2Fsamples%2FJBInput.tsx) if you want to see and play with code
22 |
23 | ## install
24 |
25 | ### using npm
26 |
27 | ``` command
28 | npm i jb-input-react
29 | ```
30 | in your jsx file
31 | ```js
32 | import {JBInput} from 'jb-input/react';
33 | ```
34 | ``` jsx
35 |
36 | ```
37 |
38 |
39 | ## events
40 |
41 | ```jsx
42 | //when default property are defined best time for impl your config
43 | {}}>
44 |
45 | //when dom bound and rendered in browser dom 3 and you can access all property
46 | {}}>
47 |
48 | //keyboard event
49 | console.log(event.target.value)}>
50 | console.log(event.target.value)}>
51 | console.log(event.target.value)}>
52 | console.log(event.target.value)}>
53 | // when user press enter on type good for situation you want so submit form or call search function on user press enter.
54 | console.log(event.target.value)}>
55 | //focus event
56 | console.log(event.target.value)}>
57 | console.log(event.target.value)}>
58 | //input Event
59 | console.log(event.target.value)}>
60 | console.log(event.target.value)}>
61 | ```
62 |
63 |
64 |
65 | ## set validation
66 |
67 | you can set validation to your input by creating a validationList array and passing in to validationList props:
68 |
69 | ``` javascript
70 | const validationList = [
71 | {
72 | validator: /.{3}/g,
73 | message: 'عنوان حداقل باید سه کارکتر طول داشته باشد'
74 | },
75 | #you can use function as a validator too
76 | {
77 | validator: ({displayValue,value})=>{return value == "سلام"},
78 | message: 'شما تنها میتوانید عبارت سلام را وارد کنید'
79 | },
80 | ]
81 | ```
82 | ```jsx
83 |
84 | ```
85 |
86 | ## check validation
87 |
88 | you can check if an input value meet your validation standad by creating a ref of the element using `React.createRef()`.
89 | ```javascript
90 | const elementRef = React.createRef();
91 | const isValid = elementRef.current.checkValidity().isAllValid;
92 | //if you want to show occurred error too
93 | const isValid = elementRef.current.reportValidity().isAllValid;
94 | ```
95 | if `isValid` is `true` the value of input is valid.
96 |
97 | if you want to show your own error message (you may get it from tanstack form or react hook form ,...) you can set `error` prop
98 |
99 | ```jsx
100 |
101 | ```
102 |
103 | ## other props
104 |
105 | |props name | description |
106 | | --------- | ------------------ |
107 | | disabled | disable the input |
108 | | inputmode | set input mode help mobile device to open proper keyboard for your input like url, search and numeric |
109 | | direction | set web-component direction default set is rtl but if you need ltr use |
110 |
111 |
112 | ## set custom style
113 |
114 | since jb-input-react use jb-input underneath, read [jb-input](https://github.com/javadbat/jb-input) custom style section.
115 |
116 | ## add custom element in input box
117 |
118 | in JBInput you can put icon or any other custom html DOM in input box. to doing so you just have to place custom DOM in JBInput tag and add `slot="start-section"` or `slot="end-section"` to place it before or after input field.
119 |
120 | ``` javascript
121 |
122 |