├── .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 | [![Published on webcomponents.org](https://img.shields.io/badge/webcomponents.org-published-blue.svg)](https://www.webcomponents.org/element/jb-input) 4 | [![GitHub license](https://img.shields.io/badge/license-MIT-brightgreen.svg)](https://raw.githubusercontent.com/javadbat/jb-input/main/LICENSE) 5 | [![NPM Downloads](https://img.shields.io/npm/dw/jb-input)](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 |
after
123 |
before
124 |
125 | ``` 126 | 127 | ## Other Related Docs: 128 | 129 | - see [jb-input](https://github.com/javadbat/jb-input) if you want to use this component as a pure-js web-component 130 | 131 | - see [All JB Design system Component List](https://github.com/javadbat/design-system/blob/main/docs/component-list.md) for more components 132 | 133 | - use [Contribution Guide](https://github.com/javadbat/design-system/blob/main/docs/contribution-guide.md) if you want to contribute in this component. -------------------------------------------------------------------------------- /react/index.js: -------------------------------------------------------------------------------- 1 | export * from './dist/JBInput.js'; -------------------------------------------------------------------------------- /react/lib/JBInput.tsx: -------------------------------------------------------------------------------- 1 | import React ,{ useRef, useEffect, useImperativeHandle, useState, DetailedHTMLProps, HTMLAttributes,forwardRef } from 'react'; 2 | import 'jb-input'; 3 | // eslint-disable-next-line no-duplicate-imports 4 | import {JBInputWebComponent, type JBInputEventType } from 'jb-input'; 5 | import { type JBInputEvents, useJBInputEvents } from './events-hook.js'; 6 | import { type JBInputAttributes, useJBInputAttribute } from './attributes-hook.js'; 7 | 8 | export { JBInputEvents, useJBInputEvents,JBInputAttributes, useJBInputAttribute, JBInputEventType}; 9 | interface JBInputType extends DetailedHTMLProps, JBInputWebComponent> { 10 | class?: string, 11 | label?: string, 12 | name?: string, 13 | message?: string, 14 | placeholder?:string, 15 | // ref:React.RefObject, 16 | } 17 | declare global { 18 | // eslint-disable-next-line @typescript-eslint/no-namespace 19 | namespace JSX { 20 | interface IntrinsicElements { 21 | 'jb-input': JBInputType; 22 | } 23 | } 24 | } 25 | // eslint-disable-next-line react/display-name 26 | export const JBInput = forwardRef((props: Props, ref) => { 27 | const element = useRef(null); 28 | const [refChangeCount, refChangeCountSetter] = useState(0); 29 | useImperativeHandle( 30 | ref, 31 | () => (element ? element.current : {}), 32 | [element], 33 | ); 34 | //to force rerender for events 35 | useEffect(() => { 36 | refChangeCountSetter(refChangeCount + 1); 37 | }, [element.current]); 38 | useJBInputEvents(element,props); 39 | useJBInputAttribute(element,props); 40 | return ( 41 | 42 | {props.children} 43 | 44 | ); 45 | }); 46 | //used in derived jb-input react components like number input. 47 | export type BaseProps = JBInputEvents & JBInputAttributes & { 48 | className?: string, 49 | children?: React.ReactNode | React.ReactNode[], 50 | } 51 | export type Props = BaseProps; 52 | JBInput.displayName = "JBInput"; 53 | 54 | -------------------------------------------------------------------------------- /react/lib/attributes-hook.ts: -------------------------------------------------------------------------------- 1 | import { JBInputWebComponent, type ValidationValue} from "jb-input"; 2 | import { type ValidationItem } from "jb-validation"; 3 | import { RefObject, useEffect } from "react"; 4 | 5 | export type JBInputAttributes = { 6 | message?: string, 7 | value?: string | number | null | undefined, 8 | validationList?: ValidationItem[], 9 | type?: string, 10 | placeholder?: string, 11 | disabled?: boolean, 12 | required?:boolean, 13 | inputmode?: string, 14 | label?: string, 15 | name?: string, 16 | error?: string, 17 | } 18 | export function useJBInputAttribute(element: RefObject, props: JBInputAttributes) { 19 | useEffect(() => { 20 | let value = props.value; 21 | if (props.value == null || props.value === undefined) { 22 | value = ''; 23 | } 24 | if (element && element.current && element.current) { 25 | element.current.value = value?.toString() || ""; 26 | } 27 | }, [props.value]); 28 | useEffect(() => { 29 | if (props.type) { 30 | element?.current?.setAttribute('type', props.type); 31 | } 32 | }, [props.type]); 33 | useEffect(() => { 34 | if(props.name){ 35 | element?.current?.setAttribute('name', props.name || ''); 36 | }else{ 37 | element?.current?.removeAttribute('name'); 38 | } 39 | }, [props.name]); 40 | useEffect(() => { 41 | if (element && element.current) { 42 | element.current.validation.list = props.validationList || []; 43 | } 44 | }, [props.validationList]); 45 | useEffect(() => { 46 | element?.current?.setAttribute('label', props.label || ""); 47 | }, [props.label]); 48 | useEffect(() => { 49 | if (typeof props.disabled == "boolean") { 50 | element?.current?.setAttribute('disabled', `${props.disabled}`); 51 | } 52 | }, [props.disabled]); 53 | useEffect(() => { 54 | if (typeof props.required == "boolean") { 55 | element?.current?.setAttribute('required', `${props.required}`); 56 | } 57 | }, [props.required]); 58 | useEffect(() => { 59 | if (props.inputmode) { 60 | element.current?.setAttribute('inputmode', props.inputmode); 61 | } else { 62 | element.current?.removeAttribute('inputmode'); 63 | } 64 | } 65 | , [props.inputmode]); 66 | useEffect(() => { 67 | element?.current?.setAttribute('message', props.message || ""); 68 | }, [props.message]); 69 | useEffect(() => { 70 | element?.current?.setAttribute('placeholder', props.placeholder || ""); 71 | }, [props.placeholder]); 72 | useEffect(() => { 73 | if(props.error){ 74 | element?.current?.setAttribute('error', props.error); 75 | }else{ 76 | element?.current?.removeAttribute('error'); 77 | } 78 | }, [props.error]); 79 | } -------------------------------------------------------------------------------- /react/lib/events-hook.ts: -------------------------------------------------------------------------------- 1 | import { useEvent } from "jb-core/react"; 2 | import { type EventTypeWithTarget } from "jb-core"; 3 | import { RefObject } from "react"; 4 | import { type JBInputWebComponent } from "jb-input"; 5 | 6 | export type JBInputEvents = { 7 | onEnter?: (e: EventTypeWithTarget) => void, 8 | onInput?: (e: EventTypeWithTarget) => void, 9 | onBeforeinput?: (e: EventTypeWithTarget) => void, 10 | onFocus?: (e: EventTypeWithTarget) => void, 11 | onBlur?: (e: EventTypeWithTarget) => void, 12 | onKeyup?: (e: EventTypeWithTarget) => void, 13 | onKeydown?: (e: EventTypeWithTarget) => void, 14 | onChange?: (e: EventTypeWithTarget) => void, 15 | } 16 | export function useJBInputEvents(element:RefObject,props:JBInputEvents){ 17 | useEvent(element, 'enter', props.onEnter); 18 | useEvent(element, 'input', props.onInput); 19 | useEvent(element, 'beforeinput', props.onBeforeinput); 20 | useEvent(element, 'change', props.onChange); 21 | useEvent(element, 'keydown', props.onKeydown); 22 | useEvent(element, 'keyup', props.onKeyup); 23 | useEvent(element, 'focus', props.onFocus); 24 | useEvent(element, 'blur', props.onBlur); 25 | } -------------------------------------------------------------------------------- /react/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jb-input-react", 3 | "description": "input react component", 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", 13 | "input box", 14 | "react component" 15 | ], 16 | "version": "3.5.0", 17 | "bugs": "https://github.com/javadbat/jb-input-react/issues", 18 | "license": "MIT", 19 | "files": [ 20 | "LICENSE", 21 | "README.md", 22 | "lib/", 23 | "dist/" 24 | ], 25 | "main": "index.js", 26 | "types": "./dist/JBInput.d.ts", 27 | "repository": { 28 | "type": "git", 29 | "url": "git@github.com:javadbat/jb-input-react.git" 30 | }, 31 | "dependencies": { 32 | "jb-input": ">=3.11.0", 33 | "jb-core": ">=0.1.0" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /react/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "rootDir": "./lib", 5 | "declarationDir": "./dist" 6 | }, 7 | "include": [ 8 | "lib/**/*.ts", 9 | "lib/**/*.tsx" 10 | ], 11 | "exclude": [ 12 | "node_modules", 13 | "**/*.spec.ts", 14 | "dist", 15 | ], 16 | "extends":"jb-core/configs/tsconfig-react.json" 17 | } -------------------------------------------------------------------------------- /stories/JBInput.stories.tsx: -------------------------------------------------------------------------------- 1 | import React, { Fragment } from 'react'; 2 | import { JBInput, Props } from 'jb-input/react'; 3 | import JBInputStylingTest from './samples/JBInputStylingTest'; 4 | import JBInputTest from './samples/JBInputTest'; 5 | import JBInputValidationList from './samples/JBInputValidationList'; 6 | import type { Meta, StoryObj } from '@storybook/react'; 7 | 8 | 9 | const meta: Meta = { 10 | title: "Components/form elements/Inputs/JBInput", 11 | component: JBInput, 12 | }; 13 | export default meta; 14 | type Story = StoryObj; 15 | 16 | export const Normal: Story = { 17 | args: { 18 | label: 'label', 19 | message: 'static text under input show all the time', 20 | placeholder: 'place holder', 21 | disabled: false 22 | } 23 | }; 24 | 25 | export const Large: Story = { 26 | args: { 27 | label: 'متن ساختگی جهت نمایش در لیبل برای تست کردن طول کاراکترها و اندازه ی صفحه و زیر هم شدن متن در اندازه صفحه کوچک مثلا در سایز موبایل. این یک متن ساختگی می باشد', 28 | message: 'متن ساختگی جهت نمایش در پیام برای تست کردن طول کاراکترها و اندازه ی صفحه و زیر هم شدن متن در اندازه صفحه کوچک مثلا در سایز موبایل. این یک متن ساختگی می باشد', 29 | } 30 | }; 31 | 32 | export const WithError: Story = { 33 | args: { 34 | label: 'has error message', 35 | message: 'simple hint message', 36 | error: 'error message', 37 | validationList:[{validator: /^.{3,}$/g, message: 'you must enter at least 3 characters'}], 38 | type: 'password' 39 | } 40 | }; 41 | 42 | export const WithPlaceholder: Story = { 43 | args: { 44 | label: 'with placeholder', 45 | placeholder: 'test placeholder' 46 | } 47 | }; 48 | 49 | export const testActions: Story = { 50 | render: () => 51 | }; 52 | 53 | export const testStyles: Story = { 54 | render: () => 55 | }; 56 | 57 | 58 | export const ValidationList: StoryObj = { 59 | render: (args) => , 60 | args: { 61 | inputRegex: /^.{8,}$/g, 62 | inputMessage: 'ورودی باید حداقل 8 کارکتر باشد', 63 | passwordRegex: /^(?=.*?[a-z])(?=.*?[0-9]).{8,}$/g, 64 | passwordMessage: 'رمز باید حداقل 8 کارکتر و حداقل شامل یک حرف انگلیسی و حداقل شامل یک عدد باشد', 65 | emailRegex: /^[^\s@]+@[^\s@]+\.[^\s@]+$/g, 66 | emailMessage: 'آدرس ایمیل معتبر نیست ', 67 | mobileRegex: /^(\+98|0|0098)?9\d{9}$/g, 68 | mobileMessage: 'شماره موبایل معتبر نیست ', 69 | } 70 | }; 71 | 72 | export const WithStartSection: Story = { 73 | args: { 74 | label: 'label', 75 | message: 'static text under input show all the time', 76 | placeholder: 'place holder', 77 | children:
78 | } 79 | }; 80 | 81 | 82 | export const WithEndSection: Story = { 83 | args: { 84 | label: 'label', 85 | message: 'static text under input show all the time', 86 | placeholder: 'place holder', 87 | children:
88 | } 89 | }; 90 | 91 | export const WithStartAndEndSection: Story = { 92 | args: { 93 | label: 'label', 94 | message: 'static text under input show all the time', 95 | placeholder: 'place holder', 96 | children: ( 97 | 98 |
99 |
100 |
) 101 | } 102 | }; 103 | 104 | export const CustomMobileKeyboard: Story = { 105 | args: { 106 | 'label': 'number keyboard', 107 | 'inputmode': 'numeric' 108 | } 109 | }; -------------------------------------------------------------------------------- /stories/samples/JBInputStylingTest.css: -------------------------------------------------------------------------------- 1 | .cloudy-style{ 2 | --jb-input-border-color:#DCDCDC; 3 | --jb-input-bgcolor:#F9F9F9; 4 | --jb-input-height:164px; 5 | --jb-input-border-bottom-width:1px; 6 | --jb-input-box-shadow-focus:0px 4px 8px rgba(0, 0, 0, 0.25); 7 | --jb-input-increase-button-color: green; 8 | --jb-input-increase-button-color-hover: blue; 9 | --jb-input-decrease-button-color:red; 10 | --jb-input-decrease-button-color-hover:blue; 11 | --jb-input-number-button-width:120px; 12 | --jb-input-decrease-button-border:1px solid #dcdcdc; 13 | --jb-input-increase-button-border:1px solid #dcdcdc; 14 | --jb-input-increase-button-border-radius:16px 0 0px 16px; 15 | --jb-input-increase-button-bg:#000; 16 | --jb-input-decrease-button-bg:#fff; 17 | } -------------------------------------------------------------------------------- /stories/samples/JBInputStylingTest.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import {JBInput} from 'jb-input/react'; 3 | import './JBInputStylingTest.css'; 4 | function JBInputStylingTest() { 5 | return ( 6 |
7 |

JBInput different Styling test

8 |
9 | 10 |
11 |
12 | ); 13 | } 14 | 15 | export default JBInputStylingTest; 16 | -------------------------------------------------------------------------------- /stories/samples/JBInputTest.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, useRef}from 'react'; 2 | import {JBInput} from 'jb-input/react'; 3 | 4 | function JBInputTest() { 5 | const input = useRef(null); 6 | const [value, setValue] = useState('09'); 7 | const [numberValue, setNumberValue] = useState(0); 8 | useEffect(()=>{ 9 | input.current.focus(); 10 | },[]); 11 | return ( 12 |
13 | setValue(e.target.value)} onKeydown={(e)=>{console.log(e);}} label="تست تایپ"> 14 | value: 15 | setValue(e.target.value)} /> 16 |

test events

17 | {alert('you press Enter');}} label="تست تایپ"> 18 |

number input test

19 |

step:2, Decimalpecission:4

y 20 | 21 | {setNumberValue(e.target.value);}} type="number" label="عدد عشاری" numberFieldParameter={{step:2,decimalPrecision:4,invalidNumberReplacement:""}}> 22 |

number after change event

23 |

{numberValue}

24 |
25 | ); 26 | } 27 | 28 | export default JBInputTest; 29 | -------------------------------------------------------------------------------- /stories/samples/JBInputValidationList.tsx: -------------------------------------------------------------------------------- 1 | import React, { useRef } from 'react'; 2 | import {JBInput} from 'jb-input/react'; 3 | import { JBInputWebComponent, ValidationValue } from 'jb-input'; 4 | import { ValidationItem } from 'jb-validation'; 5 | 6 | 7 | function JBInputValidationList(props:JBInputValidationListProps) { 8 | const inputValidation:ValidationItem[]=[ 9 | { 10 | validator: props.inputRegex, 11 | message: props.inputMessage 12 | } 13 | ]; 14 | const passwordValidation=[ 15 | { 16 | validator: props.passwordRegex, 17 | message: props.passwordMessage 18 | } 19 | ]; 20 | const emailValidation:ValidationItem[]=[ 21 | { 22 | validator: props.emailRegex, 23 | message: props.emailMessage 24 | }, 25 | { 26 | validator:({displayValue,value})=>{ 27 | if(value.includes('yahoo')){ 28 | return 'you cant enter yahoo email9'; 29 | } 30 | return true; 31 | }, 32 | message:"email must be gmail" 33 | }, 34 | { 35 | validator:({displayValue,value})=>{ 36 | return new Promise((resolve)=>{ 37 | setTimeout(()=>{ 38 | if(value.includes('outlook')){ 39 | resolve('you cant enter outlook email') ; 40 | } 41 | resolve(true); 42 | },3000); 43 | 44 | }); 45 | 46 | }, 47 | message:"outlook doesn't respond", 48 | defer:true 49 | } 50 | ]; 51 | const mobileValidation:ValidationItem[]=[ 52 | { 53 | validator: props.mobileRegex, 54 | message: props.mobileMessage 55 | } 56 | ]; 57 | 58 | const passwordInputDom = useRef(); 59 | function onButtonClicked(){ 60 | if(passwordInputDom.current){ 61 | console.log(passwordInputDom.current.validation.result); 62 | } 63 | } 64 | 65 | return ( 66 |
67 | 68 | 69 | 70 | 71 | 72 | 73 |
74 | ); 75 | } 76 | export type JBInputValidationListProps = { 77 | inputRegex: RegExp, 78 | inputMessage: string, 79 | passwordRegex: RegExp, 80 | passwordMessage: string, 81 | emailRegex: RegExp, 82 | emailMessage: string, 83 | mobileRegex: RegExp, 84 | mobileMessage: string, 85 | }; 86 | 87 | 88 | export default JBInputValidationList; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "rootDir": "./lib", 5 | "declarationDir": "./dist" 6 | }, 7 | "include": [ 8 | "../global.d.ts", 9 | "lib/**/*.ts", 10 | "lib/**/*.js", 11 | ], 12 | "exclude": [ 13 | "node_modules", 14 | "**/*.spec.ts", 15 | "dist", 16 | ], 17 | "extends":"jb-core/configs/tsconfig-web-component.json" 18 | } --------------------------------------------------------------------------------