index.tsx 21 KB

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