foundation.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /* eslint-disable max-len */
  2. /* eslint-disable no-param-reassign */
  3. /* eslint-disable eqeqeq */
  4. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  5. import keyCode from '../utils/keyCode';
  6. import { numbers } from './constants';
  7. import { toNumber, toString, get, isString } from 'lodash';
  8. import { minus as numberMinus } from '../utils/number';
  9. export interface InputNumberAdapter extends DefaultAdapter {
  10. setValue: (value: number | string, cb?: (...args: any[]) => void) => void;
  11. setNumber: (number: number | null, cb?: (...args: any[]) => void) => void;
  12. setFocusing: (focusing: boolean, cb?: (...args: any[]) => void) => void;
  13. setHovering: (hovering: boolean) => void;
  14. notifyChange: (value: string | number, e?: any) => void;
  15. notifyNumberChange: (value: number, e?: any) => void;
  16. notifyBlur: (e: any) => void;
  17. notifyFocus: (e: any) => void;
  18. notifyUpClick: (value: string, e: any) => void;
  19. notifyDownClick: (value: string, e: any) => void;
  20. notifyKeyDown: (e: any) => void;
  21. registerGlobalEvent: (eventName: string, handler: (...args: any[]) => void) => void;
  22. unregisterGlobalEvent: (eventName: string) => void;
  23. recordCursorPosition: () => void;
  24. restoreByAfter: (str?: string) => boolean;
  25. restoreCursor: (str?: string) => boolean;
  26. fixCaret: (start: number, end: number) => void;
  27. setClickUpOrDown: (clicked: boolean) => void;
  28. updateStates: (states: BaseInputNumberState, callback?: () => void) => void;
  29. }
  30. export interface BaseInputNumberState {
  31. value?: number | string;
  32. number?: number | null;
  33. focusing?: boolean;
  34. hovering?: boolean;
  35. }
  36. class InputNumberFoundation extends BaseFoundation<InputNumberAdapter> {
  37. _intervalHasRegistered: boolean;
  38. _interval: any;
  39. _timerHasRegistered: boolean;
  40. _timer: any;
  41. init() {
  42. this._setInitValue();
  43. }
  44. destroy() {
  45. this._unregisterInterval();
  46. this._unregisterTimer();
  47. this._adapter.unregisterGlobalEvent('mouseup');
  48. }
  49. isControlled() {
  50. return this._isControlledComponent('value');
  51. }
  52. _doInput(v = '', event: any = null, updateCb: any = null) {
  53. let notifyVal = v;
  54. let number = v;
  55. let isValidNumber = true;
  56. const isControlled = this.isControlled();
  57. // console.log(v);
  58. if (typeof v !== 'number') {
  59. number = this.doParse(v, false);
  60. isValidNumber = !isNaN(number as unknown as number);
  61. }
  62. if (isValidNumber) {
  63. notifyVal = number;
  64. if (!isControlled) {
  65. this._adapter.setNumber(number as unknown as number);
  66. }
  67. }
  68. if (!isControlled) {
  69. this._adapter.setValue(v, updateCb);
  70. }
  71. if (this.getProp('keepFocus')) {
  72. this._adapter.setFocusing(true, () => {
  73. this._adapter.setClickUpOrDown(true);
  74. });
  75. }
  76. this.notifyChange(notifyVal, event);
  77. }
  78. _registerInterval(cb?: (...args: any) => void) {
  79. const pressInterval = this.getProp('pressInterval') || numbers.DEFAULT_PRESS_INTERVAL;
  80. this._intervalHasRegistered = true;
  81. this._interval = setInterval(() => {
  82. if (typeof cb === 'function' && this._intervalHasRegistered) {
  83. cb();
  84. }
  85. }, pressInterval);
  86. }
  87. _unregisterInterval() {
  88. if (this._interval) {
  89. this._intervalHasRegistered = false;
  90. clearInterval(this._interval);
  91. this._interval = null;
  92. }
  93. }
  94. _registerTimer(cb: (...args: any[]) => void) {
  95. const pressTimeout = this.getProp('pressTimeout') || numbers.DEFAULT_PRESS_TIMEOUT;
  96. this._timerHasRegistered = true;
  97. this._timer = setTimeout(() => {
  98. if (this._timerHasRegistered && typeof cb === 'function') {
  99. cb();
  100. }
  101. }, pressTimeout);
  102. }
  103. _unregisterTimer() {
  104. if (this._timer) {
  105. this._timerHasRegistered = false;
  106. clearTimeout(this._timer);
  107. this._timer = null;
  108. }
  109. }
  110. handleInputFocus(e: any) {
  111. const value = this.getState('value');
  112. if (value !== '') {
  113. // let parsedStr = this.doParse(this.getState('value'));
  114. // this._adapter.setValue(Number(parsedStr));
  115. }
  116. this._adapter.recordCursorPosition();
  117. this._adapter.setFocusing(true, null);
  118. this._adapter.setClickUpOrDown(false);
  119. this._adapter.notifyFocus(e);
  120. }
  121. /**
  122. * Input box content update processing
  123. * @param {String} value
  124. * @param {*} event
  125. */
  126. handleInputChange(value: string, event: any) {
  127. // Check accuracy, adjust accuracy, adjust maximum and minimum values, call parser to parse the number
  128. const parsedNum = this.doParse(value, true, true, true);
  129. // Parser parsed number, type Number (normal number or NaN)
  130. const toNum = this.doParse(value, false, false, false);
  131. // String converted from parser parsed numbers or directly converted without parser
  132. const valueAfterParser = this.afterParser(value);
  133. this._adapter.recordCursorPosition();
  134. let notifyVal;
  135. let num = toNum;
  136. // The formatted input value
  137. let formattedNum = value;
  138. if (value === '') {
  139. if (!this.isControlled()) {
  140. num = null;
  141. }
  142. } else if (this.isValidNumber(toNum) && this.isValidNumber(parsedNum)) {
  143. notifyVal = toNum;
  144. formattedNum = this.doFormat(toNum, false);
  145. } else {
  146. /**
  147. * This logic is used to solve the problem that parsedNum is not a valid number
  148. */
  149. if (typeof toNum === 'number' && !isNaN(toNum)) {
  150. formattedNum = this.doFormat(toNum, false);
  151. // console.log(`parsedStr: `, parsedStr, `toNum: `, toNum);
  152. const dotIndex = valueAfterParser.lastIndexOf('.');
  153. const lengthAfterDot = valueAfterParser.length - 1 - dotIndex;
  154. const precLength = this._getPrecLen(toNum);
  155. if (!precLength) {
  156. const dotBeginStr = dotIndex > -1 ? valueAfterParser.slice(dotIndex) : '';
  157. formattedNum += dotBeginStr;
  158. } else if (precLength < lengthAfterDot) {
  159. // eslint-disable-next-line max-depth
  160. for (let i = 0; i < lengthAfterDot - precLength; i++) {
  161. formattedNum += '0';
  162. }
  163. }
  164. // NOUSE:
  165. num = toNum;
  166. } else {
  167. /**
  168. * When the user enters an illegal character, it needs to go through parser and format before displaying
  169. * Ensure that all input is processed by parser and format
  170. *
  171. * 用户输入非法字符时,需要经过 parser 和 format 一下再显示
  172. * 保证所有的输入都经过 parser 和 format 处理
  173. */
  174. formattedNum = this.doFormat(valueAfterParser as unknown as number, false);
  175. }
  176. notifyVal = valueAfterParser;
  177. }
  178. if (!this.isControlled() && (num === null || (typeof num === 'number' && !isNaN(num)))) {
  179. this._adapter.setNumber(num);
  180. }
  181. this._adapter.setValue(this.isControlled() ? formattedNum : this.doFormat(valueAfterParser as unknown as number, false), () => {
  182. this._adapter.restoreCursor();
  183. });
  184. this.notifyChange(notifyVal, event);
  185. }
  186. handleInputKeyDown(event: any) {
  187. const code = event.keyCode;
  188. if (code === keyCode.UP || code === keyCode.DOWN) {
  189. this._adapter.setClickUpOrDown(true);
  190. this._adapter.recordCursorPosition();
  191. const formattedVal = code === keyCode.UP ? this.add(null, event) : this.minus(null, event);
  192. this._doInput(formattedVal, event, () => {
  193. this._adapter.restoreCursor();
  194. });
  195. event.preventDefault();
  196. }
  197. this._adapter.notifyKeyDown(event);
  198. }
  199. handleInputBlur(e: any) {
  200. const currentValue = toString(this.getState('value'));
  201. let currentNumber = this.getState('number');
  202. if (currentNumber != null || (currentValue != null && currentValue !== '')) {
  203. const parsedNum = this.doParse(currentValue, false, true, true);
  204. let numHasChanged = false;
  205. let strHasChanged = false;
  206. let willSetNum, willSetVal;
  207. if (this.isValidNumber(parsedNum) && currentNumber !== parsedNum) {
  208. willSetNum = parsedNum;
  209. if (!this.isControlled()) {
  210. currentNumber = willSetNum;
  211. }
  212. numHasChanged = true;
  213. }
  214. const currentFormattedNum = this.doFormat(currentNumber, true);
  215. if (currentFormattedNum !== currentValue) {
  216. willSetVal = currentFormattedNum;
  217. strHasChanged = true;
  218. }
  219. if (strHasChanged || numHasChanged) {
  220. const notifyVal = willSetVal != null ? willSetVal : willSetNum;
  221. if (willSetVal != null) {
  222. this._adapter.setValue(willSetVal);
  223. // this.notifyChange(willSetVal);
  224. }
  225. if (willSetNum != null) {
  226. // eslint-disable-next-line max-depth
  227. if (!this._isControlledComponent('value')) {
  228. this._adapter.setNumber(willSetNum);
  229. }
  230. // this.notifyChange(willSetNum);
  231. }
  232. this.notifyChange(notifyVal, e);
  233. }
  234. }
  235. this._adapter.setFocusing(false);
  236. this._adapter.notifyBlur(e);
  237. }
  238. handleInputMouseEnter(event?: any) {
  239. this._adapter.setHovering(true);
  240. }
  241. handleInputMouseLeave(event?: any) {
  242. this._adapter.setHovering(false);
  243. }
  244. handleInputMouseMove(event?: any) {
  245. this._adapter.setHovering(true);
  246. }
  247. handleMouseUp(e?: any) {
  248. this._unregisterInterval();
  249. this._unregisterTimer();
  250. this._adapter.unregisterGlobalEvent('mouseup');
  251. }
  252. handleUpClick(event: any) {
  253. const { readonly } = this.getProps();
  254. if (!this._isMouseButtonLeft(event) || readonly) {
  255. return;
  256. }
  257. this._adapter.setClickUpOrDown(true);
  258. if (event) {
  259. event.persist();
  260. event.stopPropagation();
  261. // Prevent native blurring events
  262. this._preventDefault(event);
  263. }
  264. this.upClick(event);
  265. // Cannot access event objects asynchronously https://reactjs.org/docs/events.html#event-pooling
  266. this._registerTimer(() => {
  267. this._registerInterval(() => {
  268. this.upClick(event);
  269. });
  270. });
  271. }
  272. handleDownClick(event: any) {
  273. const { readonly } = this.getProps();
  274. if (!this._isMouseButtonLeft(event) || readonly) {
  275. return;
  276. }
  277. this._adapter.setClickUpOrDown(true);
  278. if (event) {
  279. event.persist();
  280. event.stopPropagation();
  281. this._preventDefault(event);
  282. }
  283. this.downClick(event);
  284. this._registerTimer(() => {
  285. this._registerInterval(() => {
  286. this.downClick(event);
  287. });
  288. });
  289. }
  290. /**
  291. * Whether it is a left mouse button click
  292. * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
  293. */
  294. _isMouseButtonLeft(event: any) {
  295. return get(event, 'button') === numbers.MOUSE_BUTTON_LEFT;
  296. }
  297. _preventDefault(event: any) {
  298. const keepFocus = this._adapter.getProp('keepFocus');
  299. if (keepFocus) {
  300. event.preventDefault();
  301. }
  302. }
  303. handleMouseLeave(event: any) {
  304. this._adapter.registerGlobalEvent('mouseup', () => {
  305. this.handleMouseUp(event);
  306. });
  307. }
  308. upClick(event: any) {
  309. const value = this.add(null, event);
  310. this._doInput(value, event);
  311. this._adapter.notifyUpClick(value, event);
  312. }
  313. downClick(event: any) {
  314. const value = this.minus(null, event);
  315. this._doInput(value, event);
  316. this._adapter.notifyDownClick(value, event);
  317. }
  318. _setInitValue() {
  319. const { defaultValue, value } = this.getProps();
  320. const propsValue = this._isControlledComponent('value') ? value : defaultValue;
  321. const tmpNumber = this.doParse(toString(propsValue), false, true, true);
  322. let number = null;
  323. if (typeof tmpNumber === 'number' && !isNaN(tmpNumber)) {
  324. number = tmpNumber;
  325. }
  326. const formattedValue = typeof number === 'number' ? this.doFormat(number, true) : '';
  327. this._adapter.setNumber(number);
  328. this._adapter.setValue(formattedValue);
  329. if (isString(formattedValue) && formattedValue !== String(propsValue ?? '')) {
  330. this.notifyChange(formattedValue, null);
  331. }
  332. }
  333. add(step?: number, event?: any): string {
  334. const pressShift = event && event.shiftKey;
  335. const propStep = pressShift ? this.getProp('shiftStep') : this.getProp('step');
  336. step = step == null ? propStep : Number(step);
  337. const stepAbs = Math.abs(toNumber(step));
  338. const curVal = this.getState('number');
  339. let curNum = this.toNumber(curVal) || 0;
  340. const min = this.getProp('min');
  341. const max = this.getProp('max');
  342. const minPrecLen = this._getPrecLen(min);
  343. const maxPrecLen = this._getPrecLen(max);
  344. const curPrecLen = this._getPrecLen(curNum);
  345. const stepPrecLen = this._getPrecLen(step);
  346. const scale = Math.pow(10, Math.max(minPrecLen, maxPrecLen, curPrecLen, stepPrecLen));
  347. if (step < 0) {
  348. // Js accuracy problem
  349. if (Math.abs(numberMinus(min, curNum)) >= stepAbs) {
  350. curNum = (curNum * scale + step * scale) / scale;
  351. }
  352. } else if (step > 0) {
  353. if (Math.abs(numberMinus(max, curNum)) >= stepAbs) {
  354. curNum = (curNum * scale + step * scale) / scale;
  355. }
  356. }
  357. if (typeof min === 'number' && min > curNum) {
  358. curNum = min;
  359. }
  360. if (typeof max === 'number' && max < curNum) {
  361. curNum = max;
  362. }
  363. // console.log('scale: ', scale, 'curNum: ', curNum);
  364. return this.doFormat(curNum, true);
  365. }
  366. minus(step?: number, event?: any): string {
  367. const pressShift = event && event.shiftKey;
  368. const propStep = pressShift ? this.getProp('shiftStep') : this.getProp('step');
  369. step = step == null ? propStep : Number(step);
  370. return this.add(-step, event);
  371. }
  372. /**
  373. * get decimal length
  374. * @param {number} num
  375. * @returns {number}
  376. */
  377. _getPrecLen(num: string | number) {
  378. if (typeof num !== 'string') {
  379. num = String(Math.abs(Number(num || '')));
  380. }
  381. const idx = num.indexOf('.') + 1;
  382. return idx ? num.length - idx : 0;
  383. }
  384. _adjustPrec(num: string | number) {
  385. const precision = this.getProp('precision');
  386. if (typeof precision === 'number' && num !== '' && num !== null && !Number.isNaN(Number(num))) {
  387. num = Number(num).toFixed(precision);
  388. }
  389. return toString(num);
  390. }
  391. /**
  392. * format number to string
  393. * @param {string|number} value
  394. * @param {boolean} needAdjustPrec
  395. * @returns {string}
  396. */
  397. doFormat(value: string | number = 0, needAdjustPrec = true): string {
  398. // if (typeof value === 'string') {
  399. // return value;
  400. // }
  401. let str;
  402. const formatter = this.getProp('formatter');
  403. if (needAdjustPrec) {
  404. str = this._adjustPrec(value);
  405. } else {
  406. str = toString(value);
  407. }
  408. if (typeof formatter === 'function') {
  409. str = formatter(str);
  410. }
  411. return str;
  412. }
  413. /**
  414. *
  415. * @param {number} current
  416. * @returns {number}
  417. */
  418. fetchMinOrMax(current: number) {
  419. const { min, max } = this.getProps();
  420. if (current < min) {
  421. return min;
  422. } else if (current > max) {
  423. return max;
  424. }
  425. return current;
  426. }
  427. /**
  428. * parse to number
  429. * @param {string|number} value
  430. * @param {boolean} needCheckPrec
  431. * @param {boolean} needAdjustPrec
  432. * @param {boolean} needAdjustMaxMin
  433. * @returns {number}
  434. */
  435. doParse(value: string | number, needCheckPrec = true, needAdjustPrec = false, needAdjustMaxMin = false) {
  436. if (typeof value === 'number') {
  437. if (needAdjustMaxMin) {
  438. value = this.fetchMinOrMax(value);
  439. }
  440. if (needAdjustPrec) {
  441. value = this._adjustPrec(value);
  442. }
  443. return toNumber(value);
  444. }
  445. const parser = this.getProp('parser');
  446. if (typeof parser === 'function') {
  447. value = parser(value);
  448. }
  449. if (needCheckPrec && typeof value === 'string') {
  450. const zeroIsValid =
  451. value.indexOf('.') === -1 ||
  452. (value.indexOf('.') > -1 && (value === '0' || value.lastIndexOf('0') < value.length - 1));
  453. const dotIsValid =
  454. value.lastIndexOf('.') < value.length - 1 && value.split('').filter((v: string) => v === '.').length < 2;
  455. if (
  456. !zeroIsValid ||
  457. !dotIsValid
  458. // (this.getProp('precision') > 0 && this._getPrecLen(value) > this.getProp('precision'))
  459. ) {
  460. return NaN;
  461. }
  462. }
  463. if (needAdjustPrec) {
  464. value = this._adjustPrec(value);
  465. }
  466. if (typeof value === 'string' && value.length) {
  467. return needAdjustMaxMin ? this.fetchMinOrMax(toNumber(value)) : toNumber(value);
  468. }
  469. return NaN;
  470. }
  471. /**
  472. * Parsing the input value
  473. * @param {string} value
  474. * @returns {string}
  475. */
  476. afterParser(value: string) {
  477. const parser = this.getProp('parser');
  478. if (typeof value === 'string' && typeof parser === 'function') {
  479. return toString(parser(value));
  480. }
  481. return toString(value);
  482. }
  483. toNumber(value: number | string, needAdjustPrec = true) {
  484. if (typeof value === 'number') {
  485. return value;
  486. }
  487. if (typeof value === 'string') {
  488. const parser = this.getProp('parser');
  489. if (typeof parser === 'function') {
  490. value = parser(value);
  491. }
  492. if (needAdjustPrec) {
  493. value = this._adjustPrec(value);
  494. }
  495. }
  496. return toNumber(value);
  497. }
  498. /**
  499. * Returning true requires both:
  500. * 1.type is number and not equal to NaN
  501. * 2.min < = value < = max
  502. * 3.length after decimal point requires < = precision | | No precision
  503. * @param {*} um
  504. * @param {*} needCheckPrec
  505. * @returns
  506. */
  507. isValidNumber(num: number, needCheckPrec = true) {
  508. if (typeof num === 'number' && !isNaN(num)) {
  509. const { min, max, precision } = this.getProps();
  510. const numPrec = this._getPrecLen(num);
  511. const precIsValid = needCheckPrec ?
  512. (typeof precision === 'number' && numPrec <= precision) || typeof precision !== 'number' :
  513. true;
  514. if (num >= min && num <= max && precIsValid) {
  515. return true;
  516. }
  517. }
  518. return false;
  519. }
  520. isValidString(str: string) {
  521. if (typeof str === 'string' && str.length) {
  522. const parsedNum = this.doParse(str);
  523. return this.isValidNumber(parsedNum);
  524. }
  525. return false;
  526. }
  527. notifyChange(value: string, e: any) {
  528. if (value == null || value === '') {
  529. this._adapter.notifyChange('', e);
  530. } else {
  531. const parsedNum = this.toNumber(value, true);
  532. if (typeof parsedNum === 'number' && !isNaN(parsedNum)) {
  533. // this._adapter.notifyChange(typeof value === 'number' ? parsedNum : this.afterParser(value), e);
  534. this._adapter.notifyChange(parsedNum, e);
  535. this.notifyNumberChange(parsedNum, e);
  536. } else {
  537. this._adapter.notifyChange(this.afterParser(value), e);
  538. }
  539. }
  540. }
  541. notifyNumberChange(value: number, e: any) {
  542. const { number } = this.getStates();
  543. // Does not trigger numberChange if value is not a significant number
  544. if (this.isValidNumber(value) && value !== number) {
  545. this._adapter.notifyNumberChange(value, e);
  546. }
  547. }
  548. updateStates(states: BaseInputNumberState, callback?: () => void) {
  549. this._adapter.updateStates(states, callback);
  550. }
  551. }
  552. export default InputNumberFoundation;