foundation.ts 20 KB

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