foundation.ts 20 KB

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