index.js 7.3 KB

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