From 14232b56df71574a774ab8653346273e535f985d Mon Sep 17 00:00:00 2001 From: Ritik Banger Date: Wed, 30 Nov 2022 15:58:54 +0530 Subject: [PATCH] bug fix: value update for current index and backspace fix --- README.md | 2 +- lib/index.js | 2 +- package.json | 4 ++-- src/lib/index.jsx | 20 ++++++++++++++++---- 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 4f58aa4a..fde71219 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # react18-input-otp -[![npm version](https://badge.fury.io/js/react18-input-otp.svg)](https://badge.fury.io/js/react18-input-otp) [![npm](https://img.shields.io/npm/dw/react18-input-otp.svg?logo=npm)](https://www.npmjs.com/package/react18-input-otp) [![npm](https://img.shields.io/bundlephobia/minzip/react18-input-otp)](https://www.npmjs.com/package/react18-input-otp) +[![npm version](https://badge.fury.io/js/react18-input-otp.svg)](https://badge.fury.io/js/react18-input-otp) [![npm](https://img.shields.io/npm/dm/react18-input-otp.svg?logo=npm)](https://www.npmjs.com/package/react18-input-otp) [![npm](https://img.shields.io/bundlephobia/minzip/react18-input-otp)](https://www.npmjs.com/package/react18-input-otp) diff --git a/lib/index.js b/lib/index.js index e7af6da2..a811c30c 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1 +1 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _react=_interopRequireWildcard(require("react"));var _excluded=["placeholder","separator","isLastChild","ariaLabelOverride","shouldRender","inputStyle","focus","isDisabled","hasErrored","errorStyle","focusStyle","disabledStyle","shouldAutoFocus","isInputNum","index","value","className","isInputSecure","onSubmit"];function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap();var cacheNodeInterop=new WeakMap();return(_getRequireWildcardCache=function _getRequireWildcardCache(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop;})(nodeInterop);}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj;}if(obj===null||_typeof(obj)!=="object"&&typeof obj!=="function"){return{"default":obj};}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj);}return newObj;}function _extends(){_extends=Object.assign?Object.assign.bind():function(target){for(var i=1;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i=0)continue;target[key]=source[key];}return target;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0){console.error('Length of the placeholder should be equal to the number of inputs.');}}});_defineProperty(_assertThisInitialized(_this2),"handleOtpChange",function(otp){var onChange=_this2.props.onChange;var otpValue=otp.join('');onChange(otpValue);});_defineProperty(_assertThisInitialized(_this2),"isInputValueValid",function(value){var isTypeValid=_this2.props.isInputNum?!isNaN(parseInt(value,10)):typeof value==='string';return isTypeValid&&value.trim().length===1;});_defineProperty(_assertThisInitialized(_this2),"focusInput",function(input){var numInputs=_this2.props.numInputs;var activeInput=Math.max(Math.min(numInputs-1,input),0);_this2.setState({activeInput:activeInput});});_defineProperty(_assertThisInitialized(_this2),"focusNextInput",function(){var activeInput=_this2.state.activeInput;_this2.focusInput(activeInput+1);});_defineProperty(_assertThisInitialized(_this2),"focusPrevInput",function(){var activeInput=_this2.state.activeInput;_this2.focusInput(activeInput-1);});_defineProperty(_assertThisInitialized(_this2),"changeCodeAtFocus",function(value){var activeInput=_this2.state.activeInput;var otp=_this2.getOtpValue();otp[activeInput]=value[0];_this2.handleOtpChange(otp);});_defineProperty(_assertThisInitialized(_this2),"handleOnPaste",function(e){e.preventDefault();var activeInput=_this2.state.activeInput;var _this2$props2=_this2.props,numInputs=_this2$props2.numInputs,isDisabled=_this2$props2.isDisabled;if(isDisabled){return;}var otp=_this2.getOtpValue();var nextActiveInput=activeInput;var rawPastedData=e.clipboardData.getData('text/plain');var filteredData=_this2.props.isInputNum?rawPastedData.replace(/\D/g,''):rawPastedData;var pastedData=filteredData.slice(0,numInputs-activeInput).split('');for(var pos=0;pos=activeInput&&pastedData.length>0){otp[pos]=pastedData.shift();nextActiveInput++;}}_this2.setState({activeInput:nextActiveInput},function(){_this2.focusInput(nextActiveInput);_this2.handleOtpChange(otp);});});_defineProperty(_assertThisInitialized(_this2),"handleOnChange",function(e){var value=e.target.value;if(_this2.isInputValueValid(value)){_this2.changeCodeAtFocus(value);}});_defineProperty(_assertThisInitialized(_this2),"handleOnKeyDown",function(e){if(e.keyCode===BACKSPACE||e.key==='Backspace'){e.preventDefault();_this2.changeCodeAtFocus('');_this2.focusPrevInput();}else if(e.keyCode===DELETE||e.key==='Delete'){e.preventDefault();_this2.changeCodeAtFocus('');}else if(e.keyCode===LEFT_ARROW||e.key==='ArrowLeft'){e.preventDefault();_this2.focusPrevInput();}else if(e.keyCode===RIGHT_ARROW||e.key==='ArrowRight'){e.preventDefault();_this2.focusNextInput();}else if(e.keyCode===SPACEBAR||e.key===' '||e.key==='Spacebar'||e.key==='Space'){e.preventDefault();}else if(e.keyCode===ENTER||e.key==='Enter'){_this2.props.onSubmit();}else{_this2.changeCodeAtFocus('');}});_defineProperty(_assertThisInitialized(_this2),"handleOnInput",function(e){var value=e.target.value;if(!e.target.value)return;if(e.target.value&&e.target.value.length>1){e.preventDefault();var numInputs=_this2.props.numInputs;var activeInput=_this2.state.activeInput;var otp=_this2.getOtpValue();var pastedData=e.target.value.slice(0,numInputs-activeInput).split('');for(var pos=0;pos=activeInput&&pastedData.length>0){otp[pos]=pastedData.shift();}}_this2.handleOtpChange(otp);_this2.focusInput(_this2.props.numInputs);}else if(value&&value.trim().length>1){e.clipboardData={getData:function getData(){return value.trim();}};_this2.handleOnPaste(e);}else if(_this2.isInputValueValid(e.target.value)){_this2.focusNextInput();}else{if(!_this2.props.isInputNum){var nativeEvent=e.nativeEvent;if(nativeEvent.data===null&&nativeEvent.inputType==='deleteContentBackward'){e.preventDefault();_this2.changeCodeAtFocus('');_this2.focusPrevInput();}}}});_defineProperty(_assertThisInitialized(_this2),"renderInputs",function(){var activeInput=_this2.state.activeInput;var _this2$props3=_this2.props,id=_this2$props3.id,autoComplete=_this2$props3.autoComplete,numInputs=_this2$props3.numInputs,inputStyle=_this2$props3.inputStyle,focusStyle=_this2$props3.focusStyle,separator=_this2$props3.separator,_this2$props3$separat=_this2$props3.separateAfter,separateAfter=_this2$props3$separat===void 0?1:_this2$props3$separat,isDisabled=_this2$props3.isDisabled,disabledStyle=_this2$props3.disabledStyle,hasErrored=_this2$props3.hasErrored,errorStyle=_this2$props3.errorStyle,shouldAutoFocus=_this2$props3.shouldAutoFocus,isInputNum=_this2$props3.isInputNum,isInputSecure=_this2$props3.isInputSecure,className=_this2$props3.className,inputProps=_this2$props3.inputProps,onSubmit=_this2$props3.onSubmit;var inputs=[];var otp=_this2.getOtpValue();var placeholder=_this2.getPlaceholderValue();var dataCy=_this2.props['data-cy'];var dataTestId=_this2.props['data-testid'];var customTestAttr=_this2.props['custom-test-attr'];var customTestId=_this2.props['custom-test-id'];var _loop=function _loop(i){var shouldRender=void 0;if((i+1)%parseInt(separateAfter)===0){shouldRender=true;}else{shouldRender=false;}var testAttr={};if(customTestAttr){testAttr[customTestAttr]=customTestId&&"".concat(customTestId,"-").concat(i);}var currentInputProps={};if(inputProps){if(Array.isArray(inputProps)){if(inputProps[i]){currentInputProps=inputProps[i];}}else{currentInputProps=inputProps;}}inputs.push(_react["default"].createElement(SingleOtpInput,_extends({id:id&&"".concat(id,"-").concat(i),autoComplete:autoComplete!==null&&autoComplete!==void 0?autoComplete:'off',placeholder:placeholder&&placeholder[i],key:i,index:i,focus:activeInput===i,value:otp&&otp[i],onChange:_this2.handleOnChange,onKeyDown:_this2.handleOnKeyDown,onInput:_this2.handleOnInput,onPaste:_this2.handleOnPaste,onFocus:function onFocus(e){_this2.setState({activeInput:i});e.target.select();},onBlur:function onBlur(){return _this2.setState({activeInput:-1});},separator:separator,inputStyle:inputStyle,focusStyle:focusStyle,isLastChild:i===numInputs-1,isDisabled:isDisabled,disabledStyle:disabledStyle,hasErrored:hasErrored,errorStyle:errorStyle,shouldAutoFocus:shouldAutoFocus,isInputNum:isInputNum,isInputSecure:isInputSecure,className:className,"data-cy":dataCy&&"".concat(dataCy,"-").concat(i),"data-testid":dataTestId&&"".concat(dataTestId,"-").concat(i),shouldRender:shouldRender,onSubmit:onSubmit},currentInputProps,testAttr)));};for(var i=0;i0){this.setState({activeInput:0});}}},{key:"render",value:function render(){var containerStyle=this.props.containerStyle;return _react["default"].createElement("div",{style:Object.assign({display:'flex'},isStyleObject(containerStyle)&&containerStyle),className:!isStyleObject(containerStyle)?containerStyle:''},this.renderInputs());}}]);return OtpInput;}(_react.Component);_defineProperty(OtpInput,"defaultProps",{numInputs:4,onChange:function onChange(otp){return console.log(otp);},isDisabled:false,shouldAutoFocus:false,value:'',isInputSecure:false,onSubmit:function onSubmit(otp){return console.log(otp);}});var _default=OtpInput;exports["default"]=_default; \ No newline at end of file +"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports["default"]=void 0;var _react=_interopRequireWildcard(require("react"));var _excluded=["placeholder","separator","isLastChild","ariaLabelOverride","shouldRender","inputStyle","focus","isDisabled","hasErrored","errorStyle","focusStyle","disabledStyle","shouldAutoFocus","isInputNum","index","value","className","isInputSecure","onSubmit"];function _getRequireWildcardCache(nodeInterop){if(typeof WeakMap!=="function")return null;var cacheBabelInterop=new WeakMap();var cacheNodeInterop=new WeakMap();return(_getRequireWildcardCache=function _getRequireWildcardCache(nodeInterop){return nodeInterop?cacheNodeInterop:cacheBabelInterop;})(nodeInterop);}function _interopRequireWildcard(obj,nodeInterop){if(!nodeInterop&&obj&&obj.__esModule){return obj;}if(obj===null||_typeof(obj)!=="object"&&typeof obj!=="function"){return{"default":obj};}var cache=_getRequireWildcardCache(nodeInterop);if(cache&&cache.has(obj)){return cache.get(obj);}var newObj={};var hasPropertyDescriptor=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var key in obj){if(key!=="default"&&Object.prototype.hasOwnProperty.call(obj,key)){var desc=hasPropertyDescriptor?Object.getOwnPropertyDescriptor(obj,key):null;if(desc&&(desc.get||desc.set)){Object.defineProperty(newObj,key,desc);}else{newObj[key]=obj[key];}}}newObj["default"]=obj;if(cache){cache.set(obj,newObj);}return newObj;}function _extends(){_extends=Object.assign?Object.assign.bind():function(target){for(var i=1;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i=0)continue;target[key]=source[key];}return target;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i0){console.error('Length of the placeholder should be equal to the number of inputs.');}}});_defineProperty(_assertThisInitialized(_this2),"handleOtpChange",function(otp){var onChange=_this2.props.onChange;var otpValue=otp.join('');onChange(otpValue);});_defineProperty(_assertThisInitialized(_this2),"isInputValueValid",function(value){var isTypeValid=_this2.props.isInputNum?!isNaN(parseInt(value,10)):typeof value==='string';return isTypeValid&&value.trim().length===1;});_defineProperty(_assertThisInitialized(_this2),"focusInput",function(input){var numInputs=_this2.props.numInputs;var activeInput=Math.max(Math.min(numInputs-1,input),0);_this2.setState({activeInput:activeInput});});_defineProperty(_assertThisInitialized(_this2),"focusNextInput",function(){var activeInput=_this2.state.activeInput;_this2.focusInput(activeInput+1);});_defineProperty(_assertThisInitialized(_this2),"focusPrevInput",function(){var activeInput=_this2.state.activeInput;_this2.focusInput(activeInput-1);});_defineProperty(_assertThisInitialized(_this2),"changeCodeAtFocus",function(value){var activeInput=_this2.state.activeInput;var otp=_this2.getOtpValue();otp[activeInput]=value[0];_this2.handleOtpChange(otp);});_defineProperty(_assertThisInitialized(_this2),"handleOnPaste",function(e){e.preventDefault();var activeInput=_this2.state.activeInput;var _this2$props2=_this2.props,numInputs=_this2$props2.numInputs,isDisabled=_this2$props2.isDisabled;if(isDisabled){return;}var otp=_this2.getOtpValue();var nextActiveInput=activeInput;var rawPastedData=e.clipboardData.getData('text/plain');var filteredData=_this2.props.isInputNum?rawPastedData.replace(/\D/g,''):rawPastedData;var pastedData=filteredData.slice(0,numInputs-activeInput).split('');for(var pos=0;pos=activeInput&&pastedData.length>0){otp[pos]=pastedData.shift();nextActiveInput++;}}_this2.setState({activeInput:nextActiveInput},function(){_this2.focusInput(nextActiveInput);_this2.handleOtpChange(otp);});});_defineProperty(_assertThisInitialized(_this2),"handleOnChange",function(e){var value=e.target.value;if(_this2.isInputValueValid(value)){_this2.changeCodeAtFocus(value);}});_defineProperty(_assertThisInitialized(_this2),"focusPrevInputAndChangeCode",function(value){var activeInput=_this2.state.activeInput;var otp=_this2.getOtpValue();if(otp[activeInput]!=value[0]){otp[activeInput]=value[0];if(otp[activeInput+1]!=value[0]){_this2.focusInput(otp.length-1);}}else{_this2.focusInput(activeInput-1);}_this2.handleOtpChange(otp);});_defineProperty(_assertThisInitialized(_this2),"handleOnKeyDown",function(e){if(e.keyCode===BACKSPACE||e.key==='Backspace'){e.preventDefault();_this2.focusPrevInputAndChangeCode('');}else if(e.keyCode===DELETE||e.key==='Delete'){e.preventDefault();_this2.changeCodeAtFocus('');}else if(e.keyCode===LEFT_ARROW||e.key==='ArrowLeft'){e.preventDefault();_this2.focusPrevInput();}else if(e.keyCode===RIGHT_ARROW||e.key==='ArrowRight'){e.preventDefault();_this2.focusNextInput();}else if(e.keyCode===SPACEBAR||e.key===' '||e.key==='Spacebar'||e.key==='Space'){e.preventDefault();}else if(e.keyCode===ENTER||e.key==='Enter'){_this2.props.onSubmit();}});_defineProperty(_assertThisInitialized(_this2),"handleOnInput",function(e){var value=e.target.value;if(!e.target.value)return;if(e.target.value&&e.target.value.length>1){e.preventDefault();var numInputs=_this2.props.numInputs;var activeInput=_this2.state.activeInput;var otp=_this2.getOtpValue();var pastedData=e.target.value.slice(0,numInputs-activeInput).split('');for(var pos=0;pos=activeInput&&pastedData.length>0){otp[pos]=pastedData.shift();}}_this2.handleOtpChange(otp);_this2.focusInput(_this2.props.numInputs);}else if(value&&value.trim().length>1){e.clipboardData={getData:function getData(){return value.trim();}};_this2.handleOnPaste(e);}else if(_this2.isInputValueValid(e.target.value)){_this2.focusNextInput();}else{if(!_this2.props.isInputNum){var nativeEvent=e.nativeEvent;if(nativeEvent.data===null&&nativeEvent.inputType==='deleteContentBackward'){e.preventDefault();_this2.changeCodeAtFocus('');_this2.focusPrevInput();}}}});_defineProperty(_assertThisInitialized(_this2),"renderInputs",function(){var activeInput=_this2.state.activeInput;var _this2$props3=_this2.props,id=_this2$props3.id,autoComplete=_this2$props3.autoComplete,numInputs=_this2$props3.numInputs,inputStyle=_this2$props3.inputStyle,focusStyle=_this2$props3.focusStyle,separator=_this2$props3.separator,_this2$props3$separat=_this2$props3.separateAfter,separateAfter=_this2$props3$separat===void 0?1:_this2$props3$separat,isDisabled=_this2$props3.isDisabled,disabledStyle=_this2$props3.disabledStyle,hasErrored=_this2$props3.hasErrored,errorStyle=_this2$props3.errorStyle,shouldAutoFocus=_this2$props3.shouldAutoFocus,isInputNum=_this2$props3.isInputNum,isInputSecure=_this2$props3.isInputSecure,className=_this2$props3.className,inputProps=_this2$props3.inputProps,onSubmit=_this2$props3.onSubmit;var inputs=[];var otp=_this2.getOtpValue();var placeholder=_this2.getPlaceholderValue();var dataCy=_this2.props['data-cy'];var dataTestId=_this2.props['data-testid'];var customTestAttr=_this2.props['custom-test-attr'];var customTestId=_this2.props['custom-test-id'];var _loop=function _loop(i){var shouldRender=void 0;if((i+1)%parseInt(separateAfter)===0){shouldRender=true;}else{shouldRender=false;}var testAttr={};if(customTestAttr){testAttr[customTestAttr]=customTestId&&"".concat(customTestId,"-").concat(i);}var currentInputProps={};if(inputProps){if(Array.isArray(inputProps)){if(inputProps[i]){currentInputProps=inputProps[i];}}else{currentInputProps=inputProps;}}inputs.push(_react["default"].createElement(SingleOtpInput,_extends({id:id&&"".concat(id,"-").concat(i),autoComplete:autoComplete!==null&&autoComplete!==void 0?autoComplete:'off',placeholder:placeholder&&placeholder[i],key:i,index:i,focus:activeInput===i,value:otp&&otp[i],onChange:_this2.handleOnChange,onKeyDown:_this2.handleOnKeyDown,onInput:_this2.handleOnInput,onPaste:_this2.handleOnPaste,onFocus:function onFocus(e){_this2.setState({activeInput:i});e.target.select();},onBlur:function onBlur(){return _this2.setState({activeInput:-1});},separator:separator,inputStyle:inputStyle,focusStyle:focusStyle,isLastChild:i===numInputs-1,isDisabled:isDisabled,disabledStyle:disabledStyle,hasErrored:hasErrored,errorStyle:errorStyle,shouldAutoFocus:shouldAutoFocus,isInputNum:isInputNum,isInputSecure:isInputSecure,className:className,"data-cy":dataCy&&"".concat(dataCy,"-").concat(i),"data-testid":dataTestId&&"".concat(dataTestId,"-").concat(i),shouldRender:shouldRender,onSubmit:onSubmit},currentInputProps,testAttr)));};for(var i=0;i0){this.setState({activeInput:0});}}},{key:"render",value:function render(){var containerStyle=this.props.containerStyle;return _react["default"].createElement("div",{style:Object.assign({display:'flex'},isStyleObject(containerStyle)&&containerStyle),className:!isStyleObject(containerStyle)?containerStyle:''},this.renderInputs());}}]);return OtpInput;}(_react.Component);_defineProperty(OtpInput,"defaultProps",{numInputs:4,onChange:function onChange(otp){return console.log(otp);},isDisabled:false,shouldAutoFocus:false,value:'',isInputSecure:false,onSubmit:function onSubmit(otp){return console.log(otp);}});var _default=OtpInput;exports["default"]=_default; \ No newline at end of file diff --git a/package.json b/package.json index ef740b5c..d5e2749f 100644 --- a/package.json +++ b/package.json @@ -24,8 +24,8 @@ "component" ], "peerDependencies": { - "react": "^18.1.0", - "react-dom": "^18.1.0" + "react": "16.2.0 - 18", + "react-dom": "16.2.0 - 18" }, "typings": "typings/index.d.ts", "devDependencies": { diff --git a/src/lib/index.jsx b/src/lib/index.jsx index 4c8b51e5..8097bfb6 100644 --- a/src/lib/index.jsx +++ b/src/lib/index.jsx @@ -249,12 +249,26 @@ class OtpInput extends Component { } }; + //If the OTP value at focused input exists, it gets changed; else, the previous input is focused. + focusPrevInputAndChangeCode = (value) => { + const { activeInput } = this.state; + const otp = this.getOtpValue(); + if (otp[activeInput] != value[0]) { + otp[activeInput] = value[0]; + if (otp[activeInput + 1] != value[0]) { + this.focusInput(otp.length - 1); + } + } else { + this.focusInput(activeInput - 1); + } + this.handleOtpChange(otp); + }; + // Handle cases of backspace, delete, left arrow, right arrow, space handleOnKeyDown = (e) => { if (e.keyCode === BACKSPACE || e.key === 'Backspace') { e.preventDefault(); - this.changeCodeAtFocus(''); - this.focusPrevInput(); + this.focusPrevInputAndChangeCode(''); } else if (e.keyCode === DELETE || e.key === 'Delete') { e.preventDefault(); this.changeCodeAtFocus(''); @@ -268,8 +282,6 @@ class OtpInput extends Component { e.preventDefault(); } else if (e.keyCode === ENTER || e.key === 'Enter') { this.props.onSubmit(); - } else { - this.changeCodeAtFocus(''); } };