index.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. "use strict";
  2. "use client";
  3. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
  4. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
  5. Object.defineProperty(exports, "__esModule", {
  6. value: true
  7. });
  8. exports.default = void 0;
  9. var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
  10. var React = _interopRequireWildcard(require("react"));
  11. var _classnames = _interopRequireDefault(require("classnames"));
  12. var _useEvent = _interopRequireDefault(require("rc-util/lib/hooks/useEvent"));
  13. var _pickAttrs = _interopRequireDefault(require("rc-util/lib/pickAttrs"));
  14. var _statusUtils = require("../../_util/statusUtils");
  15. var _warning = require("../../_util/warning");
  16. var _configProvider = require("../../config-provider");
  17. var _useSize = _interopRequireDefault(require("../../config-provider/hooks/useSize"));
  18. var _context = require("../../form/context");
  19. var _otp = _interopRequireDefault(require("../style/otp"));
  20. var _OTPInput = _interopRequireDefault(require("./OTPInput"));
  21. var __rest = void 0 && (void 0).__rest || function (s, e) {
  22. var t = {};
  23. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  24. if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  25. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  26. }
  27. return t;
  28. };
  29. function strToArr(str) {
  30. return (str || '').split('');
  31. }
  32. const Separator = props => {
  33. const {
  34. index,
  35. prefixCls,
  36. separator
  37. } = props;
  38. const separatorNode = typeof separator === 'function' ? separator(index) : separator;
  39. if (!separatorNode) {
  40. return null;
  41. }
  42. return /*#__PURE__*/React.createElement("span", {
  43. className: `${prefixCls}-separator`
  44. }, separatorNode);
  45. };
  46. const OTP = /*#__PURE__*/React.forwardRef((props, ref) => {
  47. const {
  48. prefixCls: customizePrefixCls,
  49. length = 6,
  50. size: customSize,
  51. defaultValue,
  52. value,
  53. onChange,
  54. formatter,
  55. separator,
  56. variant,
  57. disabled,
  58. status: customStatus,
  59. autoFocus,
  60. mask,
  61. type,
  62. onInput,
  63. inputMode
  64. } = props,
  65. restProps = __rest(props, ["prefixCls", "length", "size", "defaultValue", "value", "onChange", "formatter", "separator", "variant", "disabled", "status", "autoFocus", "mask", "type", "onInput", "inputMode"]);
  66. if (process.env.NODE_ENV !== 'production') {
  67. const warning = (0, _warning.devUseWarning)('Input.OTP');
  68. process.env.NODE_ENV !== "production" ? warning(!(typeof mask === 'string' && mask.length > 1), 'usage', '`mask` prop should be a single character.') : void 0;
  69. }
  70. const {
  71. getPrefixCls,
  72. direction
  73. } = React.useContext(_configProvider.ConfigContext);
  74. const prefixCls = getPrefixCls('otp', customizePrefixCls);
  75. const domAttrs = (0, _pickAttrs.default)(restProps, {
  76. aria: true,
  77. data: true,
  78. attr: true
  79. });
  80. // ========================= Root =========================
  81. // Style
  82. const [wrapCSSVar, hashId, cssVarCls] = (0, _otp.default)(prefixCls);
  83. // ========================= Size =========================
  84. const mergedSize = (0, _useSize.default)(ctx => customSize !== null && customSize !== void 0 ? customSize : ctx);
  85. // ======================== Status ========================
  86. const formContext = React.useContext(_context.FormItemInputContext);
  87. const mergedStatus = (0, _statusUtils.getMergedStatus)(formContext.status, customStatus);
  88. const proxyFormContext = React.useMemo(() => Object.assign(Object.assign({}, formContext), {
  89. status: mergedStatus,
  90. hasFeedback: false,
  91. feedbackIcon: null
  92. }), [formContext, mergedStatus]);
  93. // ========================= Refs =========================
  94. const containerRef = React.useRef(null);
  95. const refs = React.useRef({});
  96. React.useImperativeHandle(ref, () => ({
  97. focus: () => {
  98. var _a;
  99. (_a = refs.current[0]) === null || _a === void 0 ? void 0 : _a.focus();
  100. },
  101. blur: () => {
  102. var _a;
  103. for (let i = 0; i < length; i += 1) {
  104. (_a = refs.current[i]) === null || _a === void 0 ? void 0 : _a.blur();
  105. }
  106. },
  107. nativeElement: containerRef.current
  108. }));
  109. // ======================= Formatter ======================
  110. const internalFormatter = txt => formatter ? formatter(txt) : txt;
  111. // ======================== Values ========================
  112. const [valueCells, setValueCells] = React.useState(() => strToArr(internalFormatter(defaultValue || '')));
  113. React.useEffect(() => {
  114. if (value !== undefined) {
  115. setValueCells(strToArr(value));
  116. }
  117. }, [value]);
  118. const triggerValueCellsChange = (0, _useEvent.default)(nextValueCells => {
  119. setValueCells(nextValueCells);
  120. if (onInput) {
  121. onInput(nextValueCells);
  122. }
  123. // Trigger if all cells are filled
  124. if (onChange && nextValueCells.length === length && nextValueCells.every(c => c) && nextValueCells.some((c, index) => valueCells[index] !== c)) {
  125. onChange(nextValueCells.join(''));
  126. }
  127. });
  128. const patchValue = (0, _useEvent.default)((index, txt) => {
  129. let nextCells = (0, _toConsumableArray2.default)(valueCells);
  130. // Fill cells till index
  131. for (let i = 0; i < index; i += 1) {
  132. if (!nextCells[i]) {
  133. nextCells[i] = '';
  134. }
  135. }
  136. if (txt.length <= 1) {
  137. nextCells[index] = txt;
  138. } else {
  139. nextCells = nextCells.slice(0, index).concat(strToArr(txt));
  140. }
  141. nextCells = nextCells.slice(0, length);
  142. // Clean the last empty cell
  143. for (let i = nextCells.length - 1; i >= 0; i -= 1) {
  144. if (nextCells[i]) {
  145. break;
  146. }
  147. nextCells.pop();
  148. }
  149. // Format if needed
  150. const formattedValue = internalFormatter(nextCells.map(c => c || ' ').join(''));
  151. nextCells = strToArr(formattedValue).map((c, i) => {
  152. if (c === ' ' && !nextCells[i]) {
  153. return nextCells[i];
  154. }
  155. return c;
  156. });
  157. return nextCells;
  158. });
  159. // ======================== Change ========================
  160. const onInputChange = (index, txt) => {
  161. var _a;
  162. const nextCells = patchValue(index, txt);
  163. const nextIndex = Math.min(index + txt.length, length - 1);
  164. if (nextIndex !== index && nextCells[index] !== undefined) {
  165. (_a = refs.current[nextIndex]) === null || _a === void 0 ? void 0 : _a.focus();
  166. }
  167. triggerValueCellsChange(nextCells);
  168. };
  169. const onInputActiveChange = nextIndex => {
  170. var _a;
  171. (_a = refs.current[nextIndex]) === null || _a === void 0 ? void 0 : _a.focus();
  172. };
  173. // ======================== Render ========================
  174. const inputSharedProps = {
  175. variant,
  176. disabled,
  177. status: mergedStatus,
  178. mask,
  179. type,
  180. inputMode
  181. };
  182. return wrapCSSVar(/*#__PURE__*/React.createElement("div", Object.assign({}, domAttrs, {
  183. ref: containerRef,
  184. className: (0, _classnames.default)(prefixCls, {
  185. [`${prefixCls}-sm`]: mergedSize === 'small',
  186. [`${prefixCls}-lg`]: mergedSize === 'large',
  187. [`${prefixCls}-rtl`]: direction === 'rtl'
  188. }, cssVarCls, hashId),
  189. role: "group"
  190. }), /*#__PURE__*/React.createElement(_context.FormItemInputContext.Provider, {
  191. value: proxyFormContext
  192. }, Array.from({
  193. length
  194. }).map((_, index) => {
  195. const key = `otp-${index}`;
  196. const singleValue = valueCells[index] || '';
  197. return /*#__PURE__*/React.createElement(React.Fragment, {
  198. key: key
  199. }, /*#__PURE__*/React.createElement(_OTPInput.default, Object.assign({
  200. ref: inputEle => {
  201. refs.current[index] = inputEle;
  202. },
  203. index: index,
  204. size: mergedSize,
  205. htmlSize: 1,
  206. className: `${prefixCls}-input`,
  207. onChange: onInputChange,
  208. value: singleValue,
  209. onActiveChange: onInputActiveChange,
  210. autoFocus: index === 0 && autoFocus
  211. }, inputSharedProps)), index < length - 1 && (/*#__PURE__*/React.createElement(Separator, {
  212. separator: separator,
  213. index: index,
  214. prefixCls: prefixCls
  215. })));
  216. }))));
  217. });
  218. var _default = exports.default = OTP;