react18-input-otp
Version:
A fully customizable, one-time password (OTP) and phone number with separator input component for the web built with React.
1 lines • 17.3 kB
JavaScript
;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","isSuccessed","successStyle","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<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=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<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=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;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);Object.defineProperty(Constructor,"prototype",{writable:false});return Constructor;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function");}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:true,configurable:true}});Object.defineProperty(subClass,"prototype",{writable:false});if(superClass)_setPrototypeOf(subClass,superClass);}function _setPrototypeOf(o,p){_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function _setPrototypeOf(o,p){o.__proto__=p;return o;};return _setPrototypeOf(o,p);}function _createSuper(Derived){var hasNativeReflectConstruct=_isNativeReflectConstruct();return function _createSuperInternal(){var Super=_getPrototypeOf(Derived),result;if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget);}else{result=Super.apply(this,arguments);}return _possibleConstructorReturn(this,result);};}function _possibleConstructorReturn(self,call){if(call&&(_typeof(call)==="object"||typeof call==="function")){return call;}else if(call!==void 0){throw new TypeError("Derived constructors may only return object or undefined");}return _assertThisInitialized(self);}function _assertThisInitialized(self){if(self===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return self;}function _isNativeReflectConstruct(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));return true;}catch(e){return false;}}function _getPrototypeOf(o){_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf.bind():function _getPrototypeOf(o){return o.__proto__||Object.getPrototypeOf(o);};return _getPrototypeOf(o);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj;}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;},_typeof(obj);}var BACKSPACE=8;var LEFT_ARROW=37;var RIGHT_ARROW=39;var DELETE=46;var SPACEBAR=32;var ENTER=13;var isStyleObject=function isStyleObject(obj){return _typeof(obj)==='object';};var SingleOtpInput=function(_PureComponent){_inherits(SingleOtpInput,_PureComponent);var _super=_createSuper(SingleOtpInput);function SingleOtpInput(props){var _this;_classCallCheck(this,SingleOtpInput);_this=_super.call(this,props);_defineProperty(_assertThisInitialized(_this),"getClasses",function(){for(var _len=arguments.length,classes=new Array(_len),_key=0;_key<_len;_key++){classes[_key]=arguments[_key];}return classes.filter(function(c){return!isStyleObject(c)&&c!==false;}).join(' ');});_defineProperty(_assertThisInitialized(_this),"getType",function(){var _this$props=_this.props,isInputSecure=_this$props.isInputSecure,isInputNum=_this$props.isInputNum;if(isInputSecure){return'password';}if(isInputNum){return'tel';}return'text';});_defineProperty(_assertThisInitialized(_this),"getAriaLabel",function(index,isInputNum){var ariaLabelOverride=_this.props.ariaLabelOverride;if(ariaLabelOverride){return ariaLabelOverride;}return"".concat(index===0?'Please enter verification code. ':'').concat(isInputNum?'Digit':'Character'," ").concat(index+1);});_this.input=_react["default"].createRef();return _this;}_createClass(SingleOtpInput,[{key:"componentDidMount",value:function componentDidMount(){var _this$props2=this.props,focus=_this$props2.focus,shouldAutoFocus=_this$props2.shouldAutoFocus;var inputEl=this.input.current;if(inputEl&&focus&&shouldAutoFocus){inputEl.focus();}}},{key:"componentDidUpdate",value:function componentDidUpdate(prevProps){var focus=this.props.focus;var inputEl=this.input.current;if(prevProps.focus!==focus&&inputEl&&focus){inputEl.focus();inputEl.select();}}},{key:"render",value:function render(){var _this$props3=this.props,placeholder=_this$props3.placeholder,separator=_this$props3.separator,isLastChild=_this$props3.isLastChild,ariaLabelOverride=_this$props3.ariaLabelOverride,shouldRender=_this$props3.shouldRender,inputStyle=_this$props3.inputStyle,focus=_this$props3.focus,isDisabled=_this$props3.isDisabled,hasErrored=_this$props3.hasErrored,errorStyle=_this$props3.errorStyle,isSuccessed=_this$props3.isSuccessed,successStyle=_this$props3.successStyle,focusStyle=_this$props3.focusStyle,disabledStyle=_this$props3.disabledStyle,shouldAutoFocus=_this$props3.shouldAutoFocus,isInputNum=_this$props3.isInputNum,index=_this$props3.index,value=_this$props3.value,className=_this$props3.className,isInputSecure=_this$props3.isInputSecure,onSubmit=_this$props3.onSubmit,rest=_objectWithoutProperties(_this$props3,_excluded);return _react["default"].createElement("div",{className:className,style:{display:'flex',alignItems:'center'}},_react["default"].createElement("input",_extends({"aria-label":this.getAriaLabel(index,isInputNum),style:Object.assign({width:'1em',textAlign:'center',padding:0},isStyleObject(inputStyle)&&inputStyle,focus&&isStyleObject(focusStyle)&&focusStyle,isDisabled&&isStyleObject(disabledStyle)&&disabledStyle,hasErrored&&!isSuccessed&&isStyleObject(errorStyle)&&errorStyle,isSuccessed&&!hasErrored&&isStyleObject(successStyle)&&successStyle),placeholder:placeholder,className:this.getClasses(inputStyle,focus&&focusStyle,isDisabled&&disabledStyle,hasErrored&&!isSuccessed&&errorStyle,isSuccessed&&!hasErrored&&successStyle),type:this.getType(),ref:this.input,disabled:isDisabled,value:value?value:''},rest)),!isLastChild&&shouldRender&&separator);}}]);return SingleOtpInput;}(_react.PureComponent);var OtpInput=function(_Component){_inherits(OtpInput,_Component);var _super2=_createSuper(OtpInput);function OtpInput(){var _this2;_classCallCheck(this,OtpInput);for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2];}_this2=_super2.call.apply(_super2,[this].concat(args));_defineProperty(_assertThisInitialized(_this2),"state",{activeInput:0});_defineProperty(_assertThisInitialized(_this2),"getOtpValue",function(){return _this2.props.value?_this2.props.value.toString().split(''):[];});_defineProperty(_assertThisInitialized(_this2),"getPlaceholderValue",function(){var _this2$props=_this2.props,placeholder=_this2$props.placeholder,numInputs=_this2$props.numInputs;if(typeof placeholder==='string'){if(placeholder.length===numInputs){return placeholder;}if(placeholder.length>0){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<numInputs;++pos){if(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.focusInput(_this2.state.activeInput-1);}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<numInputs;++pos){if(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,isSuccessed=_this2$props3.isSuccessed,successStyle=_this2$props3.successStyle,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,isSuccessed:isSuccessed,successStyle:successStyle,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;i<numInputs;i++){_loop(i);}return inputs;});return _this2;}_createClass(OtpInput,[{key:"componentDidUpdate",value:function componentDidUpdate(){var value=this.props.value;var activeInput=this.state.activeInput;if(value==''&&activeInput>0){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;