foundation.ts 21 KB

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