diff --git a/.changeset/angry-hotels-run.md b/.changeset/angry-hotels-run.md deleted file mode 100644 index 5a5762b..0000000 --- a/.changeset/angry-hotels-run.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'reactjs-otp-input': patch ---- - -update ci diff --git a/.changeset/slimy-tigers-notice.md b/.changeset/slimy-tigers-notice.md deleted file mode 100644 index 485aa6e..0000000 --- a/.changeset/slimy-tigers-notice.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'reactjs-otp-input': patch ---- - -update github actions diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..02bc216 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +# reactjs-otp-input + +## 2.0.8 + +### Patch Changes + +- 064ce6f: update ci +- 95ddb05: update github actions diff --git a/dist/cjs/index.d.ts b/dist/cjs/index.d.ts new file mode 100644 index 0000000..ef41977 --- /dev/null +++ b/dist/cjs/index.d.ts @@ -0,0 +1,26 @@ +import React from 'react'; +interface IOtpInput { + className?: string; + containerStyle?: React.CSSProperties | string; + disabledStyle?: React.CSSProperties | string; + errorStyle?: React.CSSProperties | string; + focusStyle?: React.CSSProperties | string; + inputStyle?: React.CSSProperties | string; + hasErrored?: boolean; + isDisabled?: boolean; + isInputNum?: boolean; + isInputSecure?: boolean; + numInputs: number; + onChange: (otp: string) => void; + placeholder?: string; + separator?: React.ReactNode | string; + shouldAutoFocus?: boolean; + value?: string; + 'data-testid'?: string; + 'data-cy'?: string; +} +export type OtpInputHandle = { + focusInput: (index: number) => void; +}; +declare const OtpInput: React.ForwardRefExoticComponent>; +export { OtpInput }; diff --git a/dist/cjs/index.js b/dist/cjs/index.js new file mode 100644 index 0000000..50d034d --- /dev/null +++ b/dist/cjs/index.js @@ -0,0 +1,2 @@ +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("react/jsx-runtime"),t=require("react"),n=function(){return n=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0)return console.error("Length of the placeholder should be equal to the number of inputs."),""}return""}),[i,b]);t.useImperativeHandle(u,(function(){return{focusInput:R}}));var q=function(e){var t=e.join("");c(t)},B=function(e){return(S?!isNaN(parseInt(e,10)):"string"==typeof e)&&1===e.trim().length},R=function(e){var t=Math.max(Math.min(i-1,e),0);F(t)},_=function(){R(P+1)},H=function(){R(P-1)},K=function(e){M[P]=e[0],q(M)},T=function(e){if(e.preventDefault(),!p){for(var t=P,n=e.clipboardData.getData("text/plain").slice(0,i-P).split(""),r=0;r=P&&n.length>0&&(M[r]=n.shift(),t++);F(t),R(t),q(M)}},z=function(e){8===e.keyCode||"Backspace"===e.key?(e.preventDefault(),K(""),H()):46===e.keyCode||"Delete"===e.key?(e.preventDefault(),K("")):37===e.keyCode||"ArrowLeft"===e.key?(e.preventDefault(),H()):39===e.keyCode||"ArrowRight"===e.key?(e.preventDefault(),_()):32!==e.keyCode&&" "!==e.key&&"Spacebar"!==e.key&&"Space"!==e.key||e.preventDefault()},G=function(e){if(B(e.target.value))_();else if(!S){var t=e.nativeEvent;null===t.data&&"deleteContentBackward"===t.inputType&&(e.preventDefault(),K(""),H())}},J=function(e){return function(t){F(e),t.target.select()}},Q=function(){return F(-1)};return e.jsx("div",n({style:Object.assign({display:"flex"},r(x)&&x),className:r(x)?"":x},{children:new Array(i).fill(null).map((function(t,n){var r,a;return e.jsx(o,{placeholder:null!==(r=L[n])&&void 0!==r?r:"",index:n,focus:P===n,value:M[n],onChange:(a=n,function(e){var t=e.target.value;0!==a||t.length!==i?B(t)&&K(t):q(t.split(""))}),onKeyDown:z,onInput:G,onPaste:T,onFocus:J(n),onBlur:Q,separator:I,inputStyle:j,focusStyle:D,isLastChild:n===i-1,isDisabled:p,disabledStyle:O,hasErrored:k,errorStyle:C,shouldAutoFocus:y,isInputNum:S,isInputSecure:m,className:N,"data-cy":w&&"".concat(w,"-").concat(n),"data-testid":A&&"".concat(A,"-").concat(n)},n)}))}))}));exports.OtpInput=u; +//# sourceMappingURL=index.js.map diff --git a/dist/cjs/index.js.map b/dist/cjs/index.js.map new file mode 100644 index 0000000..e0be194 --- /dev/null +++ b/dist/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../../node_modules/tslib/tslib.es6.js","../../src/index.tsx"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport default {\r\n __extends,\r\n __assign,\r\n __rest,\r\n __decorate,\r\n __param,\r\n __metadata,\r\n __awaiter,\r\n __generator,\r\n __createBinding,\r\n __exportStar,\r\n __values,\r\n __read,\r\n __spread,\r\n __spreadArrays,\r\n __spreadArray,\r\n __await,\r\n __asyncGenerator,\r\n __asyncDelegator,\r\n __asyncValues,\r\n __makeTemplateObject,\r\n __importStar,\r\n __importDefault,\r\n __classPrivateFieldGet,\r\n __classPrivateFieldSet,\r\n __classPrivateFieldIn,\r\n};\r\n","import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\n\nconst BACKSPACE = 8;\nconst LEFT_ARROW = 37;\nconst RIGHT_ARROW = 39;\nconst DELETE = 46;\nconst SPACEBAR = 32;\n\nconst isStyleObject = (obj: any) => typeof obj === 'object';\n\ninterface ISingleOtpInput {\n className?: string;\n containerStyle?: React.CSSProperties | string;\n disabledStyle?: React.CSSProperties | string;\n errorStyle?: React.CSSProperties | string;\n focusStyle?: React.CSSProperties | string;\n inputStyle?: React.CSSProperties | string;\n hasErrored?: boolean;\n isDisabled?: boolean;\n isInputNum?: boolean;\n isInputSecure?: boolean;\n numInputs?: number;\n onChange: any;\n onKeyDown: any;\n onInput: any;\n onPaste: any;\n onFocus: any;\n onBlur: any;\n placeholder?: string;\n separator?: React.ReactNode | string;\n shouldAutoFocus?: boolean;\n value?: string;\n 'data-testid'?: string;\n 'data-cy'?: string;\n index: number;\n isLastChild: boolean;\n focus: boolean;\n}\n\ninterface IOtpInput {\n className?: string;\n containerStyle?: React.CSSProperties | string;\n disabledStyle?: React.CSSProperties | string;\n errorStyle?: React.CSSProperties | string;\n focusStyle?: React.CSSProperties | string;\n inputStyle?: React.CSSProperties | string;\n hasErrored?: boolean;\n isDisabled?: boolean;\n isInputNum?: boolean;\n isInputSecure?: boolean;\n numInputs: number;\n onChange: (otp: string) => void;\n placeholder?: string;\n separator?: React.ReactNode | string;\n shouldAutoFocus?: boolean;\n value?: string;\n 'data-testid'?: string;\n 'data-cy'?: string;\n}\n\nconst getClasses = (...classes: any) => classes.filter((c: any) => !isStyleObject(c) && c !== false).join(' ');\n\nconst SingleOtpInput = (props: ISingleOtpInput) => {\n const {\n placeholder,\n separator,\n isLastChild,\n inputStyle,\n focus,\n isDisabled,\n hasErrored,\n errorStyle,\n focusStyle,\n disabledStyle,\n shouldAutoFocus,\n isInputNum,\n index,\n value,\n className,\n isInputSecure,\n ...rest\n } = props;\n const input = useRef(null);\n\n // Focus on first render\n // Only when shouldAutoFocus is true\n useEffect(() => {\n const { current: inputEl } = input;\n\n if (inputEl && focus && shouldAutoFocus) {\n inputEl.focus();\n }\n }, []);\n\n useEffect(() => {\n const { current: inputEl } = input;\n\n if (focus && inputEl) {\n inputEl.focus();\n inputEl.select();\n }\n }, [focus]);\n\n const typeInput = useMemo(() => {\n if (isInputSecure) {\n return 'password';\n }\n\n if (isInputNum) {\n return 'tel';\n }\n\n return 'text';\n }, [isInputSecure, isInputNum]);\n\n return (\n
\n \n {!isLastChild && <>{separator}}\n
\n );\n};\n\nexport type OtpInputHandle = {\n focusInput: (index: number) => void;\n};\n\nconst OtpInput = forwardRef((props, ref) => {\n const {\n numInputs = 4,\n onChange = (otp: string) => console.log(otp),\n isDisabled = false,\n shouldAutoFocus = false,\n value = '',\n isInputSecure = false,\n placeholder,\n isInputNum,\n containerStyle,\n inputStyle,\n focusStyle,\n separator,\n disabledStyle,\n hasErrored,\n errorStyle,\n className,\n } = props;\n const dataCy = props['data-cy'];\n const dataTestId = props['data-testid'];\n\n const [activeInput, setActiveInput] = useState(0);\n\n const valueOtp = useMemo(() => {\n return value ? value.toString().split('') : [];\n }, [value]);\n\n const valuePlaceholder = useMemo(() => {\n if (typeof placeholder === 'string') {\n if (placeholder.length === numInputs) {\n return placeholder;\n }\n\n if (placeholder.length > 0) {\n console.error('Length of the placeholder should be equal to the number of inputs.');\n return '';\n }\n }\n\n return '';\n }, [numInputs, placeholder]);\n\n useImperativeHandle(ref, () => {\n return {\n focusInput,\n };\n });\n\n // Helper to return OTP from input\n const handleOtpChange = (otp: string[]) => {\n const otpValue = otp.join('');\n\n onChange(otpValue);\n };\n\n const isInputValueValid = (value: string) => {\n const isTypeValid = isInputNum ? !isNaN(parseInt(value, 10)) : typeof value === 'string';\n\n return isTypeValid && value.trim().length === 1;\n };\n\n // Focus on input by index\n const focusInput = (input: number) => {\n const activeInput = Math.max(Math.min(numInputs - 1, input), 0);\n\n setActiveInput(activeInput);\n };\n\n // Focus on next input\n const focusNextInput = () => {\n focusInput(activeInput + 1);\n };\n\n // Focus on previous input\n const focusPrevInput = () => {\n focusInput(activeInput - 1);\n };\n\n // Change OTP value at focused input\n const changeCodeAtFocus = (value: string) => {\n valueOtp[activeInput] = value[0];\n\n handleOtpChange(valueOtp);\n };\n\n // Handle pasted OTP\n const handleOnPaste = (e: React.ClipboardEvent) => {\n e.preventDefault();\n\n if (isDisabled) {\n return;\n }\n\n let nextActiveInput = activeInput;\n\n // Get pastedData in an array of max size (num of inputs - current position)\n const pastedData = e.clipboardData\n .getData('text/plain')\n .slice(0, numInputs - activeInput)\n .split('');\n\n // Paste data from focused input onwards\n for (let pos = 0; pos < numInputs; ++pos) {\n if (pos >= activeInput && pastedData.length > 0) {\n valueOtp[pos] = pastedData.shift() as string;\n nextActiveInput++;\n }\n }\n\n setActiveInput(nextActiveInput);\n focusInput(nextActiveInput);\n handleOtpChange(valueOtp);\n };\n\n const handleOnChange = (idx: number) => (e: React.ChangeEvent) => {\n const { value } = e.target;\n\n // Fix Fill value\n if (idx === 0 && value.length === numInputs) {\n handleOtpChange(value.split(''));\n return;\n }\n\n if (isInputValueValid(value)) {\n changeCodeAtFocus(value);\n }\n };\n\n // Handle cases of backspace, delete, left arrow, right arrow, space\n const handleOnKeyDown = (e: React.KeyboardEvent) => {\n if (e.keyCode === BACKSPACE || e.key === 'Backspace') {\n e.preventDefault();\n changeCodeAtFocus('');\n focusPrevInput();\n } else if (e.keyCode === DELETE || e.key === 'Delete') {\n e.preventDefault();\n changeCodeAtFocus('');\n } else if (e.keyCode === LEFT_ARROW || e.key === 'ArrowLeft') {\n e.preventDefault();\n focusPrevInput();\n } else if (e.keyCode === RIGHT_ARROW || e.key === 'ArrowRight') {\n e.preventDefault();\n focusNextInput();\n } else if (e.keyCode === SPACEBAR || e.key === ' ' || e.key === 'Spacebar' || e.key === 'Space') {\n e.preventDefault();\n }\n };\n\n // The content may not have changed, but some input took place hence change the focus\n const handleOnInput = (e: any) => {\n if (isInputValueValid(e.target.value)) {\n focusNextInput();\n return;\n }\n // This is a workaround for dealing with keyCode \"229 Unidentified\" on Android.\n\n if (!isInputNum) {\n const { nativeEvent } = e;\n\n if (nativeEvent.data === null && nativeEvent.inputType === 'deleteContentBackward') {\n e.preventDefault();\n changeCodeAtFocus('');\n focusPrevInput();\n }\n }\n };\n\n const handleOnFocus = (i: number) => (e: React.FocusEvent) => {\n setActiveInput(i);\n e.target.select();\n };\n\n const onBlur = () => setActiveInput(-1);\n\n return (\n \n {new Array(numInputs).fill(null).map((_, i) => {\n return (\n \n );\n })}\n \n );\n});\n\nexport { OtpInput };\n"],"names":["__assign","Object","assign","t","s","i","n","arguments","length","p","prototype","hasOwnProperty","call","apply","this","isStyleObject","obj","getClasses","classes","_i","filter","c","join","SingleOtpInput","props","placeholder","separator","isLastChild","inputStyle","focus","isDisabled","hasErrored","errorStyle","focusStyle","disabledStyle","shouldAutoFocus","isInputNum","index","value","className","isInputSecure","rest","e","indexOf","getOwnPropertySymbols","propertyIsEnumerable","__rest","input","useRef","useEffect","inputEl","current","select","typeInput","useMemo","_jsxs","jsxs","style","display","alignItems","children","_jsx","concat","autoComplete","width","textAlign","type","ref","disabled","_Fragment","Fragment","OtpInput","forwardRef","_a","numInputs","_b","onChange","otp","console","log","_c","_d","_e","_f","containerStyle","dataCy","dataTestId","_g","useState","activeInput","setActiveInput","valueOtp","toString","split","valuePlaceholder","error","useImperativeHandle","focusInput","handleOtpChange","otpValue","isInputValueValid","isNaN","parseInt","trim","Math","max","min","focusNextInput","focusPrevInput","changeCodeAtFocus","handleOnPaste","preventDefault","nextActiveInput","pastedData","clipboardData","getData","slice","pos","shift","handleOnKeyDown","keyCode","key","handleOnInput","target","nativeEvent","data","inputType","handleOnFocus","onBlur","Array","fill","map","_","idx","jsx","onKeyDown","onInput","onPaste","onFocus"],"mappings":"0HA+BWA,EAAW,WAQlB,OAPAA,EAAWC,OAAOC,QAAU,SAAkBC,GAC1C,IAAK,IAAIC,EAAGC,EAAI,EAAGC,EAAIC,UAAUC,OAAQH,EAAIC,EAAGD,IAE5C,IAAK,IAAII,KADTL,EAAIG,UAAUF,GACOJ,OAAOS,UAAUC,eAAeC,KAAKR,EAAGK,KAAIN,EAAEM,GAAKL,EAAEK,IAE9E,OAAON,CACV,EACMH,EAASa,MAAMC,KAAMP,UAChC,ECtCA,IAMMQ,EAAgB,SAACC,GAAa,MAAe,iBAARA,GAoDrCC,EAAa,eAAC,IAAeC,EAAA,GAAAC,EAAA,EAAfA,EAAeZ,UAAAC,OAAfW,IAAAD,EAAeC,GAAAZ,UAAAY,GAAK,OAAAD,EAAQE,QAAO,SAACC,GAAW,OAACN,EAAcM,KAAY,IAANA,CAArB,IAAkCC,KAAK,IAAlE,EAElCC,EAAiB,SAACC,GAEpB,IAAAC,EAiBED,cAhBFE,EAgBEF,EAAKE,UAfPC,EAeEH,EAAKG,YAdPC,EAcEJ,EAdQI,WACVC,EAaEL,EAbGK,MACLC,EAYEN,aAXFO,EAWEP,EAAKO,WAVPC,EAUER,EAVQQ,WACVC,EASET,EATQS,WACVC,EAQEV,gBAPFW,EAOEX,EAAKW,gBANPC,EAMEZ,EAAKY,WALPC,EAKEb,EALGa,MACLC,EAIEd,EAJGc,MACLC,EAGEf,YAFFgB,EAEEhB,EAAKgB,cADJC,EDtCA,SAAgBrC,EAAGsC,GACtB,IAAIvC,EAAI,CAAA,EACR,IAAK,IAAIM,KAAKL,EAAOH,OAAOS,UAAUC,eAAeC,KAAKR,EAAGK,IAAMi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YA,EACZK,WAAYA,EACZN,YAAatB,IAAMqE,EAAY,EAC/B5C,WAAYA,EACZI,cAAeA,EACfH,WAAYA,EACZC,WAAYA,EACZG,gBAAiBA,EACjBC,WAAYA,EACZI,cAAeA,EACfD,UAAWA,EACF,UAAA8C,GAAU,GAAGvB,OAAAuB,EAAU,KAAAvB,OAAAzD,GAAG,cACtBiF,GAAc,GAAGxB,OAAAwB,EAAc,KAAAxB,OAAAzD,IAxBvCA,QA8BjB"} \ No newline at end of file diff --git a/dist/esm/index.d.ts b/dist/esm/index.d.ts new file mode 100644 index 0000000..ef41977 --- /dev/null +++ b/dist/esm/index.d.ts @@ -0,0 +1,26 @@ +import React from 'react'; +interface IOtpInput { + className?: string; + containerStyle?: React.CSSProperties | string; + disabledStyle?: React.CSSProperties | string; + errorStyle?: React.CSSProperties | string; + focusStyle?: React.CSSProperties | string; + inputStyle?: React.CSSProperties | string; + hasErrored?: boolean; + isDisabled?: boolean; + isInputNum?: boolean; + isInputSecure?: boolean; + numInputs: number; + onChange: (otp: string) => void; + placeholder?: string; + separator?: React.ReactNode | string; + shouldAutoFocus?: boolean; + value?: string; + 'data-testid'?: string; + 'data-cy'?: string; +} +export type OtpInputHandle = { + focusInput: (index: number) => void; +}; +declare const OtpInput: React.ForwardRefExoticComponent>; +export { OtpInput }; diff --git a/dist/esm/index.js b/dist/esm/index.js new file mode 100644 index 0000000..ccf9c62 --- /dev/null +++ b/dist/esm/index.js @@ -0,0 +1,2 @@ +import{jsx as e,jsxs as t,Fragment as n}from"react/jsx-runtime";import{forwardRef as r,useState as o,useMemo as a,useImperativeHandle as l,useRef as i,useEffect as u}from"react";var c=function(){return c=Object.assign||function(e){for(var t,n=1,r=arguments.length;n0)return console.error("Length of the placeholder should be equal to the number of inputs."),""}return""}),[i,D]);l(n,(function(){return{focusInput:T}}));var K=function(e){var t=e.join("");f(t)},R=function(e){return(k?!isNaN(parseInt(e,10)):"string"==typeof e)&&1===e.trim().length},T=function(e){var t=Math.max(Math.min(i-1,e),0);B(t)},z=function(){T(L+1)},G=function(){T(L-1)},H=function(e){M[L]=e[0],K(M)},J=function(e){if(e.preventDefault(),!y){for(var t=L,n=e.clipboardData.getData("text/plain").slice(0,i-L).split(""),r=0;r=L&&n.length>0&&(M[r]=n.shift(),t++);B(t),T(t),K(M)}},Q=function(e){8===e.keyCode||"Backspace"===e.key?(e.preventDefault(),H(""),G()):46===e.keyCode||"Delete"===e.key?(e.preventDefault(),H("")):37===e.keyCode||"ArrowLeft"===e.key?(e.preventDefault(),G()):39===e.keyCode||"ArrowRight"===e.key?(e.preventDefault(),z()):32!==e.keyCode&&" "!==e.key&&"Spacebar"!==e.key&&"Space"!==e.key||e.preventDefault()},U=function(e){if(R(e.target.value))z();else if(!k){var t=e.nativeEvent;null===t.data&&"deleteContentBackward"===t.inputType&&(e.preventDefault(),H(""),G())}},V=function(e){return function(t){B(e),t.target.select()}},W=function(){return B(-1)};return e("div",c({style:Object.assign({display:"flex"},s(I)&&I),className:s(I)?"":I},{children:new Array(i).fill(null).map((function(t,n){var r,o;return e(p,{placeholder:null!==(r=q[n])&&void 0!==r?r:"",index:n,focus:L===n,value:M[n],onChange:(o=n,function(e){var t=e.target.value;0!==o||t.length!==i?R(t)&&H(t):K(t.split(""))}),onKeyDown:Q,onInput:U,onPaste:J,onFocus:V(n),onBlur:W,separator:C,inputStyle:O,focusStyle:x,isLastChild:n===i-1,isDisabled:y,disabledStyle:N,hasErrored:j,errorStyle:w,shouldAutoFocus:h,isInputNum:k,isInputSecure:S,className:A,"data-cy":E&&"".concat(E,"-").concat(n),"data-testid":P&&"".concat(P,"-").concat(n)},n)}))}))}));export{d as OtpInput}; +//# sourceMappingURL=index.js.map diff --git a/dist/esm/index.js.map b/dist/esm/index.js.map new file mode 100644 index 0000000..4a5dc46 --- /dev/null +++ b/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sources":["../../node_modules/tslib/tslib.es6.js","../../src/index.tsx"],"sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport default {\r\n __extends,\r\n __assign,\r\n __rest,\r\n __decorate,\r\n __param,\r\n __metadata,\r\n __awaiter,\r\n __generator,\r\n __createBinding,\r\n __exportStar,\r\n __values,\r\n __read,\r\n __spread,\r\n __spreadArrays,\r\n __spreadArray,\r\n __await,\r\n __asyncGenerator,\r\n __asyncDelegator,\r\n __asyncValues,\r\n __makeTemplateObject,\r\n __importStar,\r\n __importDefault,\r\n __classPrivateFieldGet,\r\n __classPrivateFieldSet,\r\n __classPrivateFieldIn,\r\n};\r\n","import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\n\nconst BACKSPACE = 8;\nconst LEFT_ARROW = 37;\nconst RIGHT_ARROW = 39;\nconst DELETE = 46;\nconst SPACEBAR = 32;\n\nconst isStyleObject = (obj: any) => typeof obj === 'object';\n\ninterface ISingleOtpInput {\n className?: string;\n containerStyle?: React.CSSProperties | string;\n disabledStyle?: React.CSSProperties | string;\n errorStyle?: React.CSSProperties | string;\n focusStyle?: React.CSSProperties | string;\n inputStyle?: React.CSSProperties | string;\n hasErrored?: boolean;\n isDisabled?: boolean;\n isInputNum?: boolean;\n isInputSecure?: boolean;\n numInputs?: number;\n onChange: any;\n onKeyDown: any;\n onInput: any;\n onPaste: any;\n onFocus: any;\n onBlur: any;\n placeholder?: string;\n separator?: React.ReactNode | string;\n shouldAutoFocus?: boolean;\n value?: string;\n 'data-testid'?: string;\n 'data-cy'?: string;\n index: number;\n isLastChild: boolean;\n focus: boolean;\n}\n\ninterface IOtpInput {\n className?: string;\n containerStyle?: React.CSSProperties | string;\n disabledStyle?: React.CSSProperties | string;\n errorStyle?: React.CSSProperties | string;\n focusStyle?: React.CSSProperties | string;\n inputStyle?: React.CSSProperties | string;\n hasErrored?: boolean;\n isDisabled?: boolean;\n isInputNum?: boolean;\n isInputSecure?: boolean;\n numInputs: number;\n onChange: (otp: string) => void;\n placeholder?: string;\n separator?: React.ReactNode | string;\n shouldAutoFocus?: boolean;\n value?: string;\n 'data-testid'?: string;\n 'data-cy'?: string;\n}\n\nconst getClasses = (...classes: any) => classes.filter((c: any) => !isStyleObject(c) && c !== false).join(' ');\n\nconst SingleOtpInput = (props: ISingleOtpInput) => {\n const {\n placeholder,\n separator,\n isLastChild,\n inputStyle,\n focus,\n isDisabled,\n hasErrored,\n errorStyle,\n focusStyle,\n disabledStyle,\n shouldAutoFocus,\n isInputNum,\n index,\n value,\n className,\n isInputSecure,\n ...rest\n } = props;\n const input = useRef(null);\n\n // Focus on first render\n // Only when shouldAutoFocus is true\n useEffect(() => {\n const { current: inputEl } = input;\n\n if (inputEl && focus && shouldAutoFocus) {\n inputEl.focus();\n }\n }, []);\n\n useEffect(() => {\n const { current: inputEl } = input;\n\n if (focus && inputEl) {\n inputEl.focus();\n inputEl.select();\n }\n }, [focus]);\n\n const typeInput = useMemo(() => {\n if (isInputSecure) {\n return 'password';\n }\n\n if (isInputNum) {\n return 'tel';\n }\n\n return 'text';\n }, [isInputSecure, isInputNum]);\n\n return (\n
\n \n {!isLastChild && <>{separator}}\n
\n );\n};\n\nexport type OtpInputHandle = {\n focusInput: (index: number) => void;\n};\n\nconst OtpInput = forwardRef((props, ref) => {\n const {\n numInputs = 4,\n onChange = (otp: string) => console.log(otp),\n isDisabled = false,\n shouldAutoFocus = false,\n value = '',\n isInputSecure = false,\n placeholder,\n isInputNum,\n containerStyle,\n inputStyle,\n focusStyle,\n separator,\n disabledStyle,\n hasErrored,\n errorStyle,\n className,\n } = props;\n const dataCy = props['data-cy'];\n const dataTestId = props['data-testid'];\n\n const [activeInput, setActiveInput] = useState(0);\n\n const valueOtp = useMemo(() => {\n return value ? value.toString().split('') : [];\n }, [value]);\n\n const valuePlaceholder = useMemo(() => {\n if (typeof placeholder === 'string') {\n if (placeholder.length === numInputs) {\n return placeholder;\n }\n\n if (placeholder.length > 0) {\n console.error('Length of the placeholder should be equal to the number of inputs.');\n return '';\n }\n }\n\n return '';\n }, [numInputs, placeholder]);\n\n useImperativeHandle(ref, () => {\n return {\n focusInput,\n };\n });\n\n // Helper to return OTP from input\n const handleOtpChange = (otp: string[]) => {\n const otpValue = otp.join('');\n\n onChange(otpValue);\n };\n\n const isInputValueValid = (value: string) => {\n const isTypeValid = isInputNum ? !isNaN(parseInt(value, 10)) : typeof value === 'string';\n\n return isTypeValid && value.trim().length === 1;\n };\n\n // Focus on input by index\n const focusInput = (input: number) => {\n const activeInput = Math.max(Math.min(numInputs - 1, input), 0);\n\n setActiveInput(activeInput);\n };\n\n // Focus on next input\n const focusNextInput = () => {\n focusInput(activeInput + 1);\n };\n\n // Focus on previous input\n const focusPrevInput = () => {\n focusInput(activeInput - 1);\n };\n\n // Change OTP value at focused input\n const changeCodeAtFocus = (value: string) => {\n valueOtp[activeInput] = value[0];\n\n handleOtpChange(valueOtp);\n };\n\n // Handle pasted OTP\n const handleOnPaste = (e: React.ClipboardEvent) => {\n e.preventDefault();\n\n if (isDisabled) {\n return;\n }\n\n let nextActiveInput = activeInput;\n\n // Get pastedData in an array of max size (num of inputs - current position)\n const pastedData = e.clipboardData\n .getData('text/plain')\n .slice(0, numInputs - activeInput)\n .split('');\n\n // Paste data from focused input onwards\n for (let pos = 0; pos < numInputs; ++pos) {\n if (pos >= activeInput && pastedData.length > 0) {\n valueOtp[pos] = pastedData.shift() as string;\n nextActiveInput++;\n }\n }\n\n setActiveInput(nextActiveInput);\n focusInput(nextActiveInput);\n handleOtpChange(valueOtp);\n };\n\n const handleOnChange = (idx: number) => (e: React.ChangeEvent) => {\n const { value } = e.target;\n\n // Fix Fill value\n if (idx === 0 && value.length === numInputs) {\n handleOtpChange(value.split(''));\n return;\n }\n\n if (isInputValueValid(value)) {\n changeCodeAtFocus(value);\n }\n };\n\n // Handle cases of backspace, delete, left arrow, right arrow, space\n const handleOnKeyDown = (e: React.KeyboardEvent) => {\n if (e.keyCode === BACKSPACE || e.key === 'Backspace') {\n e.preventDefault();\n changeCodeAtFocus('');\n focusPrevInput();\n } else if (e.keyCode === DELETE || e.key === 'Delete') {\n e.preventDefault();\n changeCodeAtFocus('');\n } else if (e.keyCode === LEFT_ARROW || e.key === 'ArrowLeft') {\n e.preventDefault();\n focusPrevInput();\n } else if (e.keyCode === RIGHT_ARROW || e.key === 'ArrowRight') {\n e.preventDefault();\n focusNextInput();\n } else if (e.keyCode === SPACEBAR || e.key === ' ' || e.key === 'Spacebar' || e.key === 'Space') {\n e.preventDefault();\n }\n };\n\n // The content may not have changed, but some input took place hence change the focus\n const handleOnInput = (e: any) => {\n if (isInputValueValid(e.target.value)) {\n focusNextInput();\n return;\n }\n // This is a workaround for dealing with keyCode \"229 Unidentified\" on Android.\n\n if (!isInputNum) {\n const { nativeEvent } = e;\n\n if (nativeEvent.data === null && nativeEvent.inputType === 'deleteContentBackward') {\n e.preventDefault();\n changeCodeAtFocus('');\n focusPrevInput();\n }\n }\n };\n\n const handleOnFocus = (i: number) => (e: React.FocusEvent) => {\n setActiveInput(i);\n e.target.select();\n };\n\n const onBlur = () => setActiveInput(-1);\n\n return (\n \n {new Array(numInputs).fill(null).map((_, i) => {\n return (\n \n );\n })}\n \n );\n});\n\nexport { OtpInput };\n"],"names":["__assign","Object","assign","t","s","i","n","arguments","length","p","prototype","hasOwnProperty","call","apply","this","isStyleObject","obj","getClasses","classes","_i","filter","c","join","SingleOtpInput","props","placeholder","separator","isLastChild","inputStyle","focus","isDisabled","hasErrored","errorStyle","focusStyle","disabledStyle","shouldAutoFocus","isInputNum","index","value","className","isInputSecure","rest","e","indexOf","getOwnPropertySymbols","propertyIsEnumerable","__rest","input","useRef","useEffect","inputEl","current","select","typeInput","useMemo","_jsxs","style","display","alignItems","children","_jsx","concat","autoComplete","width","textAlign","type","ref","disabled","_Fragment","OtpInput","forwardRef","_a","numInputs","_b","onChange","otp","console","log","_c","_d","_e","_f","containerStyle","dataCy","dataTestId","_g","useState","activeInput","setActiveInput","valueOtp","toString","split","valuePlaceholder","error","useImperativeHandle","focusInput","handleOtpChange","otpValue","isInputValueValid","isNaN","parseInt","trim","Math","max","min","focusNextInput","focusPrevInput","changeCodeAtFocus","handleOnPaste","preventDefault","nextActiveInput","pastedData","clipboardData","getData","slice","pos","shift","handleOnKeyDown","keyCode","key","handleOnInput","target","nativeEvent","data","inputType","handleOnFocus","onBlur","Array","fill","map","_","idx","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xD,IAxBvCA,QA8BjB"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..fc84960 --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,28 @@ +import React from 'react'; + +interface IOtpInput { + className?: string; + containerStyle?: React.CSSProperties | string; + disabledStyle?: React.CSSProperties | string; + errorStyle?: React.CSSProperties | string; + focusStyle?: React.CSSProperties | string; + inputStyle?: React.CSSProperties | string; + hasErrored?: boolean; + isDisabled?: boolean; + isInputNum?: boolean; + isInputSecure?: boolean; + numInputs: number; + onChange: (otp: string) => void; + placeholder?: string; + separator?: React.ReactNode | string; + shouldAutoFocus?: boolean; + value?: string; + 'data-testid'?: string; + 'data-cy'?: string; +} +type OtpInputHandle = { + focusInput: (index: number) => void; +}; +declare const OtpInput: React.ForwardRefExoticComponent>; + +export { OtpInput, OtpInputHandle }; diff --git a/package.json b/package.json index f8e3efa..8210856 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "reactjs-otp-input", - "version": "2.0.7", + "version": "2.0.8", "description": "A fully customizable, one-time password input component for the web built with React", "scripts": { "build": "rollup -c",