index.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /* eslint-disable jsx-a11y/no-static-element-interactions */
  2. import React from 'react';
  3. import PropTypes from 'prop-types';
  4. import classnames from 'classnames';
  5. import Input, { InputProps } from '../input';
  6. import { forwardStatics } from '@douyinfe/semi-foundation/utils/object';
  7. import isNullOrUndefined from '@douyinfe/semi-foundation/utils/isNullOrUndefined';
  8. import isBothNaN from '@douyinfe/semi-foundation/utils/isBothNaN';
  9. import InputNumberFoundation, { BaseInputNumberState, InputNumberAdapter } from '@douyinfe/semi-foundation/inputNumber/foundation';
  10. import BaseComponent from '../_base/baseComponent';
  11. import { cssClasses, numbers, strings } from '@douyinfe/semi-foundation/inputNumber/constants';
  12. import { IconChevronUp, IconChevronDown } from '@douyinfe/semi-icons';
  13. import '@douyinfe/semi-foundation/inputNumber/inputNumber.scss';
  14. import { isNaN, isString, noop } from 'lodash';
  15. import { ArrayElement } from '../_base/base';
  16. export interface InputNumberProps extends InputProps {
  17. autofocus?: boolean;
  18. className?: string;
  19. clearIcon?: React.ReactNode;
  20. defaultValue?: number | string;
  21. disabled?: boolean;
  22. formatter?: (value: number | string) => string;
  23. forwardedRef?: React.MutableRefObject<HTMLInputElement> | ((instance: HTMLInputElement) => void);
  24. hideButtons?: boolean;
  25. innerButtons?: boolean;
  26. insetLabel?: React.ReactNode;
  27. insetLabelId?: string;
  28. keepFocus?: boolean;
  29. max?: number;
  30. min?: number;
  31. parser?: (value: string) => string;
  32. precision?: number;
  33. prefixCls?: string;
  34. pressInterval?: number;
  35. pressTimeout?: number;
  36. shiftStep?: number;
  37. showClear?: boolean;
  38. size?: ArrayElement<typeof strings.SIZE>;
  39. step?: number;
  40. style?: React.CSSProperties;
  41. suffix?: React.ReactNode;
  42. value?: number | string;
  43. onBlur?: (e: React.FocusEvent<HTMLInputElement>) => void;
  44. onChange?: (value: number | string, e?: React.ChangeEvent) => void;
  45. onDownClick?: (value: string, e: React.MouseEvent<HTMLButtonElement>) => void;
  46. onFocus?: (e: React.FocusEvent<HTMLInputElement>) => void;
  47. onKeyDown?: React.KeyboardEventHandler;
  48. onNumberChange?: (value: number, e?: React.ChangeEvent) => void;
  49. onUpClick?: (value: string, e: React.MouseEvent<HTMLButtonElement>) => void
  50. }
  51. export interface InputNumberState extends BaseInputNumberState {}
  52. class InputNumber extends BaseComponent<InputNumberProps, InputNumberState> {
  53. static propTypes = {
  54. 'aria-label': PropTypes.string,
  55. 'aria-labelledby': PropTypes.string,
  56. 'aria-invalid': PropTypes.bool,
  57. 'aria-errormessage': PropTypes.string,
  58. 'aria-describedby': PropTypes.string,
  59. 'aria-required': PropTypes.bool,
  60. autofocus: PropTypes.bool,
  61. clearIcon: PropTypes.node,
  62. className: PropTypes.string,
  63. defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  64. disabled: PropTypes.bool,
  65. formatter: PropTypes.func,
  66. forwardedRef: PropTypes.any,
  67. hideButtons: PropTypes.bool,
  68. innerButtons: PropTypes.bool,
  69. insetLabel: PropTypes.node,
  70. insetLabelId: PropTypes.string,
  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. preventScroll: PropTypes.bool,
  80. shiftStep: PropTypes.number,
  81. step: PropTypes.number,
  82. style: PropTypes.object,
  83. suffix: PropTypes.any,
  84. value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  85. onBlur: PropTypes.func,
  86. onChange: PropTypes.func,
  87. onDownClick: PropTypes.func,
  88. onKeyDown: PropTypes.func,
  89. onNumberChange: PropTypes.func,
  90. onUpClick: PropTypes.func,
  91. };
  92. static defaultProps: InputNumberProps = {
  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. updateStates: (states, callback) => {
  205. this.setState(states, callback);
  206. },
  207. };
  208. }
  209. inputNode: HTMLInputElement;
  210. clickUpOrDown: boolean;
  211. cursorStart!: number;
  212. cursorEnd!: number;
  213. currentValue!: number | string;
  214. cursorBefore!: string;
  215. cursorAfter!: string;
  216. foundation: InputNumberFoundation;
  217. constructor(props: InputNumberProps) {
  218. super(props);
  219. this.state = {
  220. value: '',
  221. number: null, // Current parsed numbers
  222. focusing: Boolean(props.autofocus) || false,
  223. hovering: false,
  224. };
  225. this.inputNode = null;
  226. this.foundation = new InputNumberFoundation(this.adapter);
  227. this.clickUpOrDown = false;
  228. }
  229. componentDidUpdate(prevProps: InputNumberProps) {
  230. const { value, preventScroll } = this.props;
  231. const { focusing } = this.state;
  232. let newValue;
  233. /**
  234. * To determine whether the front and back are equal
  235. * NaN need to check whether both are NaN
  236. */
  237. if (value !== prevProps.value && !isBothNaN(value, prevProps.value)) {
  238. if (isNullOrUndefined(value) || value === '') {
  239. newValue = '';
  240. this.foundation.updateStates({ value: newValue, number: null });
  241. } else {
  242. let valueStr = value;
  243. if (typeof value === 'number') {
  244. valueStr = this.foundation.doFormat(value);
  245. }
  246. const parsedNum = this.foundation.doParse(valueStr, false, true, true);
  247. const toNum = typeof value === 'number' ? value : this.foundation.doParse(valueStr, false, false, false);
  248. /**
  249. * focusing 状态为输入状态,输入状态的受控值要特殊处理
  250. * 如:
  251. * - 输入合法值
  252. * 123 => input value 也应该是 123,同时需要设置 number 为 123
  253. * - 输入非法值,只设置 input value,不设置非法的number
  254. * abc => input value 这时是 abc,但失焦后会进行格式化
  255. * 100(超出范围) => input value 应该是 100,但不设置 number
  256. *
  257. * 保持输入态有三种方式
  258. * 1. 输入框输入
  259. * - 输入可以解析为合法数字,input value根据输入值确定,失焦时更新input value
  260. * - 输入不可解析为合法数字,进行格式化后显示在input框
  261. * 2. 键盘点击上下按钮(input value根据受控值进行更改)
  262. * 3. keepFocus+鼠标点击上下按钮(input value根据受控值进行更改)
  263. *
  264. * The focusing state is the input state, and the controlled value of the input state needs special treatment
  265. * For example:
  266. * - input legal value
  267. * 123 = > input value should also be 123, and the number should be set to 123
  268. * - input illegal value, only set the input value, do not set the illegal number
  269. * abc = > input value This is abc at this time, but it will be formatted after being out of focus
  270. * 100 (out of range) = > input value should be 100, but no number
  271. *
  272. * There are three ways to maintain the input state
  273. * 1. input box input
  274. * - 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
  275. * - input cannot be resolved into legal numbers, and it will be displayed in the input box after formatting
  276. * 2. Keyboard click on the up and down button (input value is changed according to the controlled value)
  277. * 3.keepFocus + mouse click on the up and down button (input value is changed according to the controlled value)
  278. */
  279. if (focusing) {
  280. if (this.foundation.isValidNumber(parsedNum) && parsedNum !== this.state.number) {
  281. const obj: { number?: number; value?: string } = { number: parsedNum };
  282. /**
  283. * If you are clicking the button, it will automatically format once
  284. * We need to set the status to false after trigger focus event
  285. */
  286. if (this.clickUpOrDown) {
  287. obj.value = this.foundation.doFormat(obj.number, true);
  288. newValue = obj.value;
  289. }
  290. this.foundation.updateStates(obj, () => this.adapter.restoreCursor());
  291. } else if (!isNaN(toNum)) {
  292. // Update input content when controlled input is illegal and not NaN
  293. newValue = this.foundation.doFormat(toNum, false);
  294. this.foundation.updateStates({ value: newValue });
  295. } else {
  296. // Update input content when controlled input NaN
  297. this.foundation.updateStates({ value: valueStr });
  298. }
  299. } else if (this.foundation.isValidNumber(parsedNum)) {
  300. newValue = this.foundation.doFormat(parsedNum);
  301. this.foundation.updateStates({ number: parsedNum, value: newValue });
  302. } else {
  303. // Invalid digital analog blurring effect instead of controlled failure
  304. newValue = '';
  305. this.foundation.updateStates({ number: null, value: newValue });
  306. }
  307. }
  308. if (newValue && isString(newValue) && newValue !== String(this.props.value)) {
  309. this.foundation.notifyChange(newValue, null);
  310. }
  311. }
  312. if (!this.clickUpOrDown) {
  313. return;
  314. }
  315. if (this.props.keepFocus && this.state.focusing) {
  316. if (document.activeElement !== this.inputNode) {
  317. this.inputNode.focus({ preventScroll });
  318. }
  319. }
  320. }
  321. setInputRef = (node: HTMLInputElement) => {
  322. const { forwardedRef } = this.props;
  323. this.inputNode = node;
  324. if (forwardedRef && typeof forwardedRef === 'object') {
  325. forwardedRef.current = node;
  326. } else if (typeof forwardedRef === 'function') {
  327. forwardedRef(node);
  328. }
  329. };
  330. handleInputFocus = (e: React.FocusEvent<HTMLInputElement>) => this.foundation.handleInputFocus(e);
  331. handleInputChange = (value: string, event: React.ChangeEvent<HTMLInputElement>) => this.foundation.handleInputChange(value, event);
  332. handleInputBlur = (e: React.FocusEvent<HTMLInputElement>) => this.foundation.handleInputBlur(e);
  333. handleInputKeyDown = (e: React.KeyboardEvent) => this.foundation.handleInputKeyDown(e);
  334. handleInputMouseEnter = (e: React.MouseEvent) => this.foundation.handleInputMouseEnter(e);
  335. handleInputMouseLeave = (e: React.MouseEvent) => this.foundation.handleInputMouseLeave(e);
  336. handleInputMouseMove = (e: React.MouseEvent) => this.foundation.handleInputMouseMove(e);
  337. handleUpClick = (e: React.KeyboardEvent) => this.foundation.handleUpClick(e);
  338. handleDownClick = (e: React.KeyboardEvent) => this.foundation.handleDownClick(e);
  339. handleMouseUp = (e: React.MouseEvent) => this.foundation.handleMouseUp(e);
  340. handleMouseLeave = (e: React.MouseEvent) => this.foundation.handleMouseLeave(e);
  341. renderButtons = () => {
  342. const { prefixCls, disabled, innerButtons, max, min } = this.props;
  343. const { hovering, focusing, number } = this.state;
  344. const notAllowedUp = disabled ? disabled : number === max;
  345. const notAllowedDown = disabled ? disabled : number === min;
  346. const suffixChildrenCls = classnames(`${prefixCls}-number-suffix-btns`, {
  347. [`${prefixCls}-number-suffix-btns-inner`]: innerButtons,
  348. [`${prefixCls}-number-suffix-btns-inner-hover`]: innerButtons && hovering && !focusing
  349. });
  350. const upClassName = classnames(`${prefixCls}-number-button`, `${prefixCls}-number-button-up`, {
  351. [`${prefixCls}-number-button-up-disabled`]: disabled,
  352. [`${prefixCls}-number-button-up-not-allowed`]: notAllowedUp,
  353. });
  354. const downClassName = classnames(`${prefixCls}-number-button`, `${prefixCls}-number-button-down`, {
  355. [`${prefixCls}-number-button-down-disabled`]: disabled,
  356. [`${prefixCls}-number-button-down-not-allowed`]: notAllowedDown,
  357. });
  358. return (
  359. <div className={suffixChildrenCls}>
  360. <span
  361. className={upClassName}
  362. onMouseDown={notAllowedUp ? noop : this.handleUpClick}
  363. onMouseUp={this.handleMouseUp}
  364. onMouseLeave={this.handleMouseLeave}
  365. >
  366. <IconChevronUp size="extra-small" />
  367. </span>
  368. <span
  369. className={downClassName}
  370. onMouseDown={notAllowedDown ? noop : this.handleDownClick}
  371. onMouseUp={this.handleMouseUp}
  372. onMouseLeave={this.handleMouseLeave}
  373. >
  374. <IconChevronDown size="extra-small" />
  375. </span>
  376. </div>
  377. );
  378. };
  379. renderSuffix = () => {
  380. const { innerButtons, suffix } = this.props;
  381. const { hovering, focusing } = this.state;
  382. if (innerButtons && (hovering || focusing)) {
  383. const buttons = this.renderButtons();
  384. return buttons;
  385. }
  386. return suffix;
  387. };
  388. render() {
  389. const {
  390. disabled,
  391. className,
  392. prefixCls,
  393. min,
  394. max,
  395. step,
  396. shiftStep,
  397. precision,
  398. formatter,
  399. parser,
  400. forwardedRef,
  401. onUpClick,
  402. onDownClick,
  403. pressInterval,
  404. pressTimeout,
  405. suffix,
  406. size,
  407. hideButtons,
  408. innerButtons,
  409. style,
  410. onNumberChange,
  411. keepFocus,
  412. defaultValue,
  413. ...rest
  414. } = this.props;
  415. const { value, number } = this.state;
  416. const inputNumberCls = classnames(className, `${prefixCls}-number`, {
  417. [`${prefixCls}-number-size-${size}`]: size,
  418. });
  419. const buttons = this.renderButtons();
  420. const ariaProps = {
  421. 'aria-disabled': disabled,
  422. step,
  423. };
  424. if (number) {
  425. ariaProps['aria-valuenow'] = number;
  426. }
  427. if (max !== Infinity) {
  428. ariaProps['aria-valuemax'] = max;
  429. }
  430. if (min !== -Infinity) {
  431. ariaProps['aria-valuemin'] = min;
  432. }
  433. const input = (
  434. <div
  435. className={inputNumberCls}
  436. style={style}
  437. onMouseMove={e => this.handleInputMouseMove(e)}
  438. onMouseEnter={e => this.handleInputMouseEnter(e)}
  439. onMouseLeave={e => this.handleInputMouseLeave(e)}
  440. >
  441. <Input
  442. role="spinbutton"
  443. {...ariaProps}
  444. {...rest}
  445. size={size}
  446. disabled={disabled}
  447. ref={this.setInputRef}
  448. value={value}
  449. onFocus={this.handleInputFocus}
  450. onChange={this.handleInputChange}
  451. onBlur={this.handleInputBlur}
  452. onKeyDown={this.handleInputKeyDown}
  453. suffix={this.renderSuffix()}
  454. />
  455. {(hideButtons || innerButtons) ? null : (
  456. buttons
  457. )}
  458. </div>
  459. );
  460. return input;
  461. }
  462. }
  463. export default forwardStatics(
  464. React.forwardRef<HTMLInputElement, InputNumberProps>(function SemiInputNumber(props, ref) {
  465. return <InputNumber {...props} forwardedRef={ref} />;
  466. }),
  467. InputNumber
  468. );
  469. export { InputNumber };