1
0

index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. /* eslint-disable @typescript-eslint/no-unused-vars */
  2. /* eslint-disable no-unused-vars */
  3. /* eslint-disable max-depth */
  4. /* eslint-disable react/no-did-update-set-state */
  5. /* eslint-disable max-len */
  6. import React from 'react';
  7. import PropTypes from 'prop-types';
  8. import classnames from 'classnames';
  9. import Input, { InputProps } from '../input';
  10. import { forwardStatics } from '@douyinfe/semi-foundation/utils/object';
  11. import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined';
  12. import isBothNaN from '@douyinfe/semi-foundation/utils/isBothNaN';
  13. import InputNumberFoundation, { InputNumberAdapter } from '@douyinfe/semi-foundation/inputNumber/foundation';
  14. import BaseComponent from '../_base/baseComponent';
  15. import { cssClasses, numbers, strings } from '@douyinfe/semi-foundation/inputNumber/constants';
  16. import { IconChevronUp, IconChevronDown } from '@douyinfe/semi-icons';
  17. import '@douyinfe/semi-foundation/inputNumber/inputNumber.scss';
  18. import { isNaN, noop } from 'lodash-es';
  19. import { ArrayElement } from '../_base/base';
  20. export interface InputNumberProps extends InputProps {
  21. [x: string]: any;
  22. autofocus?: boolean;
  23. className?: string;
  24. defaultValue?: number | string;
  25. disabled?: boolean;
  26. formatter?: (value: number | string) => string;
  27. forwardedRef?: React.MutableRefObject<HTMLInputElement> | ((instance: HTMLInputElement) => void);
  28. hideButtons?: boolean;
  29. innerButtons?: boolean;
  30. insetLabel?: React.ReactNode;
  31. keepFocus?: boolean;
  32. max?: number;
  33. min?: number;
  34. parser?: (value: string) => string;
  35. precision?: number;
  36. prefixCls?: string;
  37. pressInterval?: number;
  38. pressTimeout?: number;
  39. shiftStep?: number;
  40. showClear?: boolean;
  41. size?: ArrayElement<typeof strings.SIZE>;
  42. step?: number;
  43. style?: React.CSSProperties;
  44. suffix?: React.ReactNode;
  45. value?: number | string;
  46. onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
  47. onChange?: (value: number | string, e?: React.ChangeEvent) => void;
  48. onDownClick?: (value: string, e: React.MouseEvent<HTMLButtonElement>) => void;
  49. onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void;
  50. onKeyDown?: React.KeyboardEventHandler;
  51. onNumberChange?: (value: number, e?: React.ChangeEvent) => void;
  52. onUpClick?: (value: string, e: React.MouseEvent<HTMLButtonElement>) => void;
  53. }
  54. export interface InputNumberState {
  55. value?: number | string;
  56. number?: number | null; // Current parsed numbers
  57. focusing?: boolean;
  58. hovering?: boolean;
  59. }
  60. class InputNumber extends BaseComponent<InputNumberProps, InputNumberState> {
  61. static propTypes = {
  62. autofocus: PropTypes.bool,
  63. className: PropTypes.string,
  64. defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  65. disabled: PropTypes.bool,
  66. formatter: PropTypes.func,
  67. forwardedRef: PropTypes.any,
  68. hideButtons: PropTypes.bool,
  69. innerButtons: PropTypes.bool,
  70. insetLabel: PropTypes.node,
  71. keepFocus: PropTypes.bool,
  72. max: PropTypes.number,
  73. min: PropTypes.number,
  74. parser: PropTypes.func,
  75. precision: PropTypes.number,
  76. prefixCls: PropTypes.string,
  77. pressInterval: PropTypes.number,
  78. pressTimeout: PropTypes.number,
  79. shiftStep: PropTypes.number,
  80. step: PropTypes.number,
  81. style: PropTypes.object,
  82. suffix: PropTypes.any,
  83. value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  84. onBlur: PropTypes.func,
  85. onChange: PropTypes.func,
  86. onDownClick: PropTypes.func,
  87. onKeyDown: PropTypes.func,
  88. onNumberChange: PropTypes.func,
  89. onUpClick: PropTypes.func,
  90. };
  91. static defaultProps: InputNumberProps = {
  92. disabled: false,
  93. forwardedRef: noop,
  94. innerButtons: false,
  95. keepFocus: false,
  96. max: Infinity,
  97. min: -Infinity,
  98. prefixCls: cssClasses.PREFIX,
  99. pressInterval: numbers.DEFAULT_PRESS_TIMEOUT,
  100. pressTimeout: numbers.DEFAULT_PRESS_TIMEOUT,
  101. shiftStep: numbers.DEFAULT_SHIFT_STEP,
  102. size: strings.DEFAULT_SIZE,
  103. step: numbers.DEFAULT_STEP,
  104. onBlur: noop,
  105. onChange: noop,
  106. onDownClick: noop,
  107. onFocus: noop,
  108. onKeyDown: noop,
  109. onNumberChange: noop,
  110. onUpClick: noop,
  111. };
  112. get adapter(): InputNumberAdapter {
  113. return {
  114. ...super.adapter,
  115. setValue: (value, cb) => this.setState({ value }, cb),
  116. setNumber: (number, cb) => this.setState({ number }, cb),
  117. setFocusing: (focusing, cb) => this.setState({ focusing }, cb),
  118. setHovering: hovering => this.setState({ hovering }),
  119. notifyChange: (...args) => this.props.onChange(...args),
  120. notifyNumberChange: (...args) => this.props.onNumberChange(...args),
  121. notifyBlur: e => this.props.onBlur(e),
  122. notifyFocus: e => this.props.onFocus(e),
  123. notifyUpClick: (value, e) => this.props.onUpClick(value, e),
  124. notifyDownClick: (value, e) => this.props.onDownClick(value, e),
  125. notifyKeyDown: e => this.props.onKeyDown(e),
  126. registerGlobalEvent: (eventName, handler) => {
  127. if (eventName && typeof handler === 'function') {
  128. this.adapter.unregisterGlobalEvent(eventName);
  129. this.adapter.setCache(eventName, handler);
  130. document.addEventListener(eventName, handler);
  131. }
  132. },
  133. unregisterGlobalEvent: eventName => {
  134. if (eventName) {
  135. const handler = this.adapter.getCache(eventName);
  136. document.removeEventListener(eventName, handler);
  137. this.adapter.setCache(eventName, null);
  138. }
  139. },
  140. recordCursorPosition: () => {
  141. // Record position
  142. try {
  143. if (this.inputNode) {
  144. this.cursorStart = this.inputNode.selectionStart;
  145. this.cursorEnd = this.inputNode.selectionEnd;
  146. this.currentValue = this.inputNode.value;
  147. this.cursorBefore = this.inputNode.value.substring(0, this.cursorStart);
  148. this.cursorAfter = this.inputNode.value.substring(this.cursorEnd);
  149. }
  150. } catch (e) {
  151. console.warn(e);
  152. // Fix error in Chrome:
  153. // Failed to read the 'selectionStart' property from 'HTMLInputElement'
  154. // http://stackoverflow.com/q/21177489/3040605
  155. }
  156. },
  157. restoreByAfter: str => {
  158. if (isNullOrUndefined(str)) {
  159. return false;
  160. }
  161. const fullStr = this.inputNode.value;
  162. const index = fullStr.lastIndexOf(str);
  163. if (index === -1) {
  164. return false;
  165. }
  166. if (index + str.length === fullStr.length) {
  167. this.adapter.fixCaret(index, index);
  168. return true;
  169. }
  170. return false;
  171. },
  172. restoreCursor: (str = this.cursorAfter) => {
  173. if (isNullOrUndefined(str)) {
  174. return false;
  175. }
  176. // For loop from full str to the str with last char to map. e.g. 123
  177. // -> 123
  178. // -> 23
  179. // -> 3
  180. return Array.prototype.some.call(str, (_: any, start: number) => {
  181. const partStr = str.substring(start);
  182. return this.adapter.restoreByAfter(partStr);
  183. });
  184. },
  185. fixCaret: (start, end) => {
  186. if (start === undefined || end === undefined || !this.inputNode || !this.inputNode.value) {
  187. return;
  188. }
  189. try {
  190. const currentStart = this.inputNode.selectionStart;
  191. const currentEnd = this.inputNode.selectionEnd;
  192. if (start !== currentStart || end !== currentEnd) {
  193. this.inputNode.setSelectionRange(start, end);
  194. }
  195. } catch (e) {
  196. // Fix error in Chrome:
  197. // Failed to read the 'selectionStart' property from 'HTMLInputElement'
  198. // http://stackoverflow.com/q/21177489/3040605
  199. }
  200. },
  201. setClickUpOrDown: value => {
  202. this.clickUpOrDown = value;
  203. }
  204. };
  205. }
  206. inputNode: HTMLInputElement;
  207. clickUpOrDown: boolean;
  208. cursorStart!: number;
  209. cursorEnd!: number;
  210. currentValue!: number | string;
  211. cursorBefore!: string;
  212. cursorAfter!: string;
  213. constructor(props: InputNumberProps) {
  214. super(props);
  215. this.state = {
  216. value: '',
  217. number: null, // Current parsed numbers
  218. focusing: Boolean(props.autofocus) || false,
  219. hovering: false,
  220. };
  221. this.inputNode = null;
  222. this.foundation = new InputNumberFoundation(this.adapter);
  223. this.clickUpOrDown = false;
  224. }
  225. componentDidUpdate(prevProps: InputNumberProps) {
  226. const { value } = this.props;
  227. const { focusing } = this.state;
  228. /**
  229. * To determine whether the front and back are equal
  230. * NaN need to check whether both are NaN
  231. */
  232. if (value !== prevProps.value && !isBothNaN(value, prevProps.value)) {
  233. if (isNullOrUndefined(value) || value === '') {
  234. this.setState({ value: '', number: null });
  235. } else {
  236. let valueStr = value;
  237. if (typeof value === 'number') {
  238. valueStr = value.toString();
  239. }
  240. const parsedNum = this.foundation.doParse(valueStr, false, true, true);
  241. const toNum = typeof value === 'number' ? value : this.foundation.doParse(valueStr, false, false, false);
  242. /**
  243. * focusing 状态为输入状态,输入状态的受控值要特殊处理
  244. * 如:
  245. * - 输入合法值
  246. * 123 => input value 也应该是 123,同时需要设置 number 为 123
  247. * - 输入非法值,只设置 input value,不设置非法的number
  248. * abc => input value 这时是 abc,但失焦后会进行格式化
  249. * 100(超出范围) => input value 应该是 100,但不设置 number
  250. *
  251. * 保持输入态有三种方式
  252. * 1. 输入框输入
  253. * - 输入可以解析为合法数字,input value根据输入值确定,失焦时更新input value
  254. * - 输入不可解析为合法数字,进行格式化后显示在input框
  255. * 2. 键盘点击上下按钮(input value根据受控值进行更改)
  256. * 3. keepFocus+鼠标点击上下按钮(input value根据受控值进行更改)
  257. *
  258. * The focusing state is the input state, and the controlled value of the input state needs special treatment
  259. * For example:
  260. * - input legal value
  261. * 123 = > input value should also be 123, and the number should be set to 123
  262. * - input illegal value, only set the input value, do not set the illegal number
  263. * abc = > input value This is abc at this time, but it will be formatted after being out of focus
  264. * 100 (out of range) = > input value should be 100, but no number
  265. *
  266. * There are three ways to maintain the input state
  267. * 1. input box input
  268. * - input can be resolved into legal numbers, input value is determined according to the input value, and input value is updated when out of focus
  269. * - input cannot be resolved into legal numbers, and it will be displayed in the input box after formatting
  270. * 2. Keyboard click on the up and down button (input value is changed according to the controlled value)
  271. * 3.keepFocus + mouse click on the up and down button (input value is changed according to the controlled value)
  272. */
  273. if (focusing) {
  274. if (this.foundation.isValidNumber(parsedNum) && parsedNum !== this.state.number) {
  275. const obj: { number?: number; value?: string } = { number: parsedNum };
  276. // Updates input when a button is clicked
  277. if (this.clickUpOrDown) {
  278. obj.value = this.foundation.doFormat(valueStr, true);
  279. }
  280. this.setState(obj, () => this.adapter.restoreCursor());
  281. } else if (!isNaN(toNum)) {
  282. // Update input content when controlled input is illegal and not NaN
  283. this.setState({ value: this.foundation.doFormat(toNum, false) });
  284. } else {
  285. // Update input content when controlled input NaN
  286. this.setState({ value: this.foundation.doFormat(valueStr, false) });
  287. }
  288. } else if (this.foundation.isValidNumber(parsedNum)) {
  289. this.setState({ number: parsedNum, value: this.foundation.doFormat(parsedNum) });
  290. } else {
  291. // Invalid digital analog blurring effect instead of controlled failure
  292. this.setState({ number: null, value: '' });
  293. }
  294. }
  295. }
  296. if (!this.clickUpOrDown) {
  297. return;
  298. }
  299. if (this.props.keepFocus && this.state.focusing) {
  300. if (document.activeElement !== this.inputNode) {
  301. this.inputNode.focus();
  302. }
  303. }
  304. }
  305. setInputRef = (node: HTMLInputElement) => {
  306. const { forwardedRef } = this.props;
  307. this.inputNode = node;
  308. if (forwardedRef && typeof forwardedRef === 'object') {
  309. forwardedRef.current = node;
  310. } else if (typeof forwardedRef === 'function') {
  311. forwardedRef(node);
  312. }
  313. };
  314. handleInputFocus = (e: React.FocusEvent<HTMLInputElement>) => this.foundation.handleInputFocus(e);
  315. handleInputChange = (value: string, event: React.ChangeEvent<HTMLInputElement>) => this.foundation.handleInputChange(value, event);
  316. handleInputBlur = (e: React.FocusEvent<HTMLInputElement>) => this.foundation.handleInputBlur(e);
  317. handleInputKeyDown = (e: React.KeyboardEvent) => this.foundation.handleInputKeyDown(e);
  318. handleInputMouseEnter = (e: React.MouseEvent) => this.foundation.handleInputMouseEnter(e);
  319. handleInputMouseLeave = (e: React.MouseEvent) => this.foundation.handleInputMouseLeave(e);
  320. handleInputMouseMove = (e: React.MouseEvent) => this.foundation.handleInputMouseMove(e);
  321. handleUpClick = (e: React.KeyboardEvent) => this.foundation.handleUpClick(e);
  322. handleDownClick = (e: React.KeyboardEvent) => this.foundation.handleDownClick(e);
  323. handleMouseUp = (e: React.MouseEvent) => this.foundation.handleMouseUp(e);
  324. handleMouseLeave = (e: React.MouseEvent) => this.foundation.handleMouseLeave(e);
  325. renderButtons = () => {
  326. const { prefixCls, disabled, innerButtons, max, min } = this.props;
  327. const { hovering, focusing, number } = this.state;
  328. const notAllowedUp = disabled ? disabled : number === max;
  329. const notAllowedDown = disabled ? disabled : number === min;
  330. const suffixChildrenCls = classnames(`${prefixCls}-number-suffix-btns`, {
  331. [`${prefixCls}-number-suffix-btns-inner`]: innerButtons,
  332. [`${prefixCls}-number-suffix-btns-inner-hover`]: innerButtons && hovering && !focusing
  333. });
  334. const upClassName = classnames(`${prefixCls}-number-button`, `${prefixCls}-number-button-up`, {
  335. [`${prefixCls}-number-button-up-disabled`]: disabled,
  336. [`${prefixCls}-number-button-up-not-allowed`]: notAllowedUp,
  337. });
  338. const downClassName = classnames(`${prefixCls}-number-button`, `${prefixCls}-number-button-down`, {
  339. [`${prefixCls}-number-button-down-disabled`]: disabled,
  340. [`${prefixCls}-number-button-down-not-allowed`]: notAllowedDown,
  341. });
  342. return (
  343. <div className={suffixChildrenCls}>
  344. <span
  345. className={upClassName}
  346. onMouseDown={notAllowedUp ? noop : this.handleUpClick}
  347. onMouseUp={this.handleMouseUp}
  348. onMouseLeave={this.handleMouseLeave}
  349. >
  350. <IconChevronUp size="extra-small" />
  351. </span>
  352. <span
  353. className={downClassName}
  354. onMouseDown={notAllowedDown ? noop : this.handleDownClick}
  355. onMouseUp={this.handleMouseUp}
  356. onMouseLeave={this.handleMouseLeave}
  357. >
  358. <IconChevronDown size="extra-small" />
  359. </span>
  360. </div>
  361. );
  362. };
  363. renderSuffix = () => {
  364. const { innerButtons, suffix } = this.props;
  365. const { hovering, focusing } = this.state;
  366. if (innerButtons && (hovering || focusing)) {
  367. const buttons = this.renderButtons();
  368. return buttons;
  369. }
  370. return suffix;
  371. };
  372. render() {
  373. const {
  374. disabled,
  375. className,
  376. prefixCls,
  377. min,
  378. max,
  379. step,
  380. shiftStep,
  381. precision,
  382. formatter,
  383. parser,
  384. forwardedRef,
  385. onUpClick,
  386. onDownClick,
  387. pressInterval,
  388. pressTimeout,
  389. suffix,
  390. size,
  391. hideButtons,
  392. innerButtons,
  393. style,
  394. onNumberChange,
  395. keepFocus,
  396. ...rest
  397. } = this.props;
  398. const { value } = this.state;
  399. const inputNumberCls = classnames(className, `${prefixCls}-number`, {
  400. [`${prefixCls}-number-size-${size}`]: size,
  401. });
  402. const buttons = this.renderButtons();
  403. const input = (
  404. <div
  405. className={inputNumberCls}
  406. style={style}
  407. onMouseMove={e => this.handleInputMouseMove(e)}
  408. onMouseEnter={e => this.handleInputMouseEnter(e)}
  409. onMouseLeave={e => this.handleInputMouseLeave(e)}
  410. >
  411. <Input
  412. {...rest}
  413. size={size}
  414. disabled={disabled}
  415. ref={this.setInputRef}
  416. value={value}
  417. onFocus={this.handleInputFocus}
  418. onChange={this.handleInputChange}
  419. onBlur={this.handleInputBlur}
  420. onKeyDown={this.handleInputKeyDown}
  421. suffix={this.renderSuffix()}
  422. />
  423. {(hideButtons || innerButtons) ? null : (
  424. buttons
  425. )}
  426. </div>
  427. );
  428. return input;
  429. }
  430. }
  431. export default forwardStatics(
  432. React.forwardRef<HTMLInputElement, InputNumberProps>(function SemiInputNumber(props, ref) {
  433. return <InputNumber {...props} forwardedRef={ref} />;
  434. }),
  435. InputNumber
  436. );
  437. export { InputNumber };