foundation.ts 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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. getInputCharacter: (index: number) => string
  27. }
  28. export interface BaseInputNumberState {
  29. value?: number | string;
  30. number?: number | null;
  31. focusing?: boolean;
  32. hovering?: boolean
  33. }
  34. class InputNumberFoundation extends BaseFoundation<InputNumberAdapter> {
  35. _intervalHasRegistered: boolean;
  36. _interval: any;
  37. _timerHasRegistered: boolean;
  38. _timer: any;
  39. _decimalPointSymbol: string = undefined;
  40. _currencySymbol: string = '';
  41. init() {
  42. if (this._isCurrency()) {
  43. this._setCurrencySymbol();
  44. }
  45. this._setInitValue();
  46. }
  47. destroy() {
  48. this._unregisterInterval();
  49. this._unregisterTimer();
  50. this._adapter.unregisterGlobalEvent('mouseup');
  51. }
  52. isControlled() {
  53. return this._isControlledComponent('value');
  54. }
  55. _isCurrency() {
  56. const { currency } = this.getProps();
  57. return currency === true || (typeof currency === 'string' && currency.trim() !== '');
  58. }
  59. _getFinalCurrency() {
  60. const { currency } = this.getProps();
  61. return currency === true ? this.getProp('defaultCurrency') : currency;
  62. }
  63. _doInput(v = '', event: any = null, updateCb: any = null) {
  64. let notifyVal = v;
  65. let number = v;
  66. let isValidNumber = true;
  67. const isControlled = this.isControlled();
  68. // console.log(v);
  69. if (typeof v !== 'number') {
  70. number = this.doParse(v, false);
  71. isValidNumber = !isNaN(number as unknown as number);
  72. }
  73. if (isValidNumber) {
  74. notifyVal = number;
  75. if (!isControlled) {
  76. this._adapter.setNumber(number as unknown as number);
  77. }
  78. }
  79. if (!isControlled) {
  80. this._adapter.setValue(v, updateCb);
  81. }
  82. if (this.getProp('keepFocus')) {
  83. this._adapter.setFocusing(true, () => {
  84. this._adapter.setClickUpOrDown(true);
  85. });
  86. }
  87. this.notifyChange(notifyVal, event);
  88. }
  89. _registerInterval(cb?: (...args: any) => void) {
  90. const pressInterval = this.getProp('pressInterval') || numbers.DEFAULT_PRESS_INTERVAL;
  91. this._intervalHasRegistered = true;
  92. this._interval = setInterval(() => {
  93. if (typeof cb === 'function' && this._intervalHasRegistered) {
  94. cb();
  95. }
  96. }, pressInterval);
  97. }
  98. _unregisterInterval() {
  99. if (this._interval) {
  100. this._intervalHasRegistered = false;
  101. clearInterval(this._interval);
  102. this._interval = null;
  103. }
  104. }
  105. _registerTimer(cb: (...args: any[]) => void) {
  106. const pressTimeout = this.getProp('pressTimeout') || numbers.DEFAULT_PRESS_TIMEOUT;
  107. this._timerHasRegistered = true;
  108. this._timer = setTimeout(() => {
  109. if (this._timerHasRegistered && typeof cb === 'function') {
  110. cb();
  111. }
  112. }, pressTimeout);
  113. }
  114. _unregisterTimer() {
  115. if (this._timer) {
  116. this._timerHasRegistered = false;
  117. clearTimeout(this._timer);
  118. this._timer = null;
  119. }
  120. }
  121. _setCurrencySymbol() {
  122. const { localeCode, currencyDisplay } = this.getProps();
  123. const parts = new Intl.NumberFormat(localeCode, {
  124. style: 'currency',
  125. currency: this._getFinalCurrency() || this.getCurrencyByLocaleCode(),
  126. currencyDisplay
  127. }).formatToParts(1234.5);
  128. for (const part of parts) {
  129. if (part.type === 'decimal') {
  130. this._decimalPointSymbol = part.value;
  131. console.log('this._decimalPointSymbol: ', this._decimalPointSymbol);
  132. }
  133. // if (part.type === 'group') {
  134. // groupSeparator = part.value;
  135. // }
  136. if (part.type === 'currency') {
  137. this._currencySymbol = part.value;
  138. }
  139. }
  140. }
  141. handleInputFocus(e: any) {
  142. const value = this.getState('value');
  143. if (value !== '') {
  144. // let parsedStr = this.doParse(this.getState('value'));
  145. // this._adapter.setValue(Number(parsedStr));
  146. }
  147. this._adapter.recordCursorPosition();
  148. this._adapter.setFocusing(true, null);
  149. this._adapter.setClickUpOrDown(false);
  150. this._adapter.notifyFocus(e);
  151. }
  152. /**
  153. * Input box content update processing
  154. * @param {String} value
  155. * @param {*} event
  156. */
  157. handleInputChange(value: string, event: any) {
  158. // Check accuracy, adjust accuracy, adjust maximum and minimum values, call parser to parse the number
  159. const parsedNum = this.doParse(value, true, true, true);
  160. // Parser parsed number, type Number (normal number or NaN)
  161. const toNum = this.doParse(value, false, false, false);
  162. // String converted from parser parsed numbers or directly converted without parser
  163. const valueAfterParser = this.afterParser(value);
  164. this._adapter.recordCursorPosition();
  165. let notifyVal;
  166. let num = toNum;
  167. // The formatted input value
  168. let formattedNum = value;
  169. if (value === '') {
  170. if (!this.isControlled()) {
  171. num = null;
  172. }
  173. } else if (this.isValidNumber(toNum) && this.isValidNumber(parsedNum)) {
  174. notifyVal = toNum;
  175. formattedNum = this.doFormat(toNum, false);
  176. } else {
  177. /**
  178. * This logic is used to solve the problem that parsedNum is not a valid number
  179. */
  180. if (typeof toNum === 'number' && !isNaN(toNum)) {
  181. formattedNum = this.doFormat(toNum, false);
  182. // console.log(`parsedStr: `, parsedStr, `toNum: `, toNum);
  183. const dotIndex = valueAfterParser.lastIndexOf('.');
  184. const lengthAfterDot = valueAfterParser.length - 1 - dotIndex;
  185. const precLength = this._getPrecLen(toNum);
  186. if (!precLength) {
  187. const dotBeginStr = dotIndex > -1 ? valueAfterParser.slice(dotIndex) : '';
  188. formattedNum += dotBeginStr;
  189. } else if (precLength < lengthAfterDot) {
  190. for (let i = 0; i < lengthAfterDot - precLength; i++) {
  191. formattedNum += '0';
  192. }
  193. }
  194. // NOUSE:
  195. num = toNum;
  196. } else {
  197. /**
  198. * When the user enters an illegal character, it needs to go through parser and format before displaying
  199. * Ensure that all input is processed by parser and format
  200. *
  201. * 用户输入非法字符时,需要经过 parser 和 format 一下再显示
  202. * 保证所有的输入都经过 parser 和 format 处理
  203. */
  204. formattedNum = this.doFormat(valueAfterParser as unknown as number, false);
  205. }
  206. notifyVal = valueAfterParser;
  207. }
  208. if (!this.isControlled() && (num === null || (typeof num === 'number' && !isNaN(num)))) {
  209. this._adapter.setNumber(num);
  210. }
  211. this._adapter.setValue(this.isControlled() && !this._isCurrency() ? formattedNum : this.doFormat(valueAfterParser as unknown as number, false), () => {
  212. this._adapter.restoreCursor();
  213. });
  214. this.notifyChange(notifyVal, event);
  215. }
  216. handleInputKeyDown(event: any) {
  217. const code = event.keyCode;
  218. if (code === keyCode.UP || code === keyCode.DOWN) {
  219. this._adapter.setClickUpOrDown(true);
  220. this._adapter.recordCursorPosition();
  221. const formattedVal = code === keyCode.UP ? this.add(null, event) : this.minus(null, event);
  222. this._doInput(formattedVal, event, () => {
  223. this._adapter.restoreCursor();
  224. });
  225. event.preventDefault();
  226. }
  227. this._adapter.notifyKeyDown(event);
  228. }
  229. handleInputBlur(e: any) {
  230. const currentValue = toString(this.getState('value'));
  231. let currentNumber = this.getState('number');
  232. if (currentNumber != null || (currentValue != null && currentValue !== '')) {
  233. const parsedNum = this.doParse(currentValue, false, true, true);
  234. let numHasChanged = false;
  235. let strHasChanged = false;
  236. let willSetNum, willSetVal;
  237. if (this.isValidNumber(parsedNum) && currentNumber !== parsedNum) {
  238. willSetNum = parsedNum;
  239. if (!this.isControlled()) {
  240. currentNumber = willSetNum;
  241. }
  242. numHasChanged = true;
  243. }
  244. const currentFormattedNum = this.doFormat(currentNumber, true, true);
  245. if (currentFormattedNum !== currentValue) {
  246. willSetVal = currentFormattedNum;
  247. strHasChanged = true;
  248. }
  249. if (strHasChanged || numHasChanged) {
  250. const notifyVal = willSetVal != null ? willSetVal : willSetNum;
  251. if (willSetVal != null) {
  252. this._adapter.setValue(willSetVal);
  253. // this.notifyChange(willSetVal);
  254. }
  255. if (willSetNum != null) {
  256. if (!this._isControlledComponent('value')) {
  257. this._adapter.setNumber(willSetNum);
  258. }
  259. // this.notifyChange(willSetNum);
  260. }
  261. this.notifyChange(notifyVal, e);
  262. }
  263. }
  264. this._adapter.setFocusing(false);
  265. this._adapter.notifyBlur(e);
  266. }
  267. handleInputMouseEnter(event?: any) {
  268. this._adapter.setHovering(true);
  269. }
  270. handleInputMouseLeave(event?: any) {
  271. this._adapter.setHovering(false);
  272. }
  273. handleInputMouseMove(event?: any) {
  274. this._adapter.setHovering(true);
  275. }
  276. handleMouseUp(e?: any) {
  277. this._unregisterInterval();
  278. this._unregisterTimer();
  279. this._adapter.unregisterGlobalEvent('mouseup');
  280. }
  281. handleUpClick(event: any) {
  282. const { readonly } = this.getProps();
  283. if (!this._isMouseButtonLeft(event) || readonly) {
  284. return;
  285. }
  286. this._adapter.setClickUpOrDown(true);
  287. if (event) {
  288. this._persistEvent(event);
  289. event.stopPropagation();
  290. // Prevent native blurring events
  291. this._preventDefault(event);
  292. }
  293. this.upClick(event);
  294. // Cannot access event objects asynchronously https://reactjs.org/docs/events.html#event-pooling
  295. this._registerTimer(() => {
  296. this._registerInterval(() => {
  297. this.upClick(event);
  298. });
  299. });
  300. }
  301. handleDownClick(event: any) {
  302. const { readonly } = this.getProps();
  303. if (!this._isMouseButtonLeft(event) || readonly) {
  304. return;
  305. }
  306. this._adapter.setClickUpOrDown(true);
  307. if (event) {
  308. this._persistEvent(event);
  309. event.stopPropagation();
  310. this._preventDefault(event);
  311. }
  312. this.downClick(event);
  313. this._registerTimer(() => {
  314. this._registerInterval(() => {
  315. this.downClick(event);
  316. });
  317. });
  318. }
  319. /**
  320. * Whether it is a left mouse button click
  321. * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
  322. */
  323. _isMouseButtonLeft(event: any) {
  324. return get(event, 'button') === numbers.MOUSE_BUTTON_LEFT;
  325. }
  326. _preventDefault(event: any) {
  327. const keepFocus = this._adapter.getProp('keepFocus');
  328. const innerButtons = this._adapter.getProp('innerButtons');
  329. if (keepFocus || innerButtons) {
  330. event.preventDefault();
  331. }
  332. }
  333. handleMouseLeave(event: any) {
  334. this._adapter.registerGlobalEvent('mouseup', () => {
  335. this.handleMouseUp(event);
  336. });
  337. }
  338. upClick(event: any) {
  339. const value = this.add(null, event);
  340. this._doInput(value, event);
  341. this._adapter.notifyUpClick(value, event);
  342. }
  343. downClick(event: any) {
  344. const value = this.minus(null, event);
  345. this._doInput(value, event);
  346. this._adapter.notifyDownClick(value, event);
  347. }
  348. _setInitValue() {
  349. const { defaultValue, value } = this.getProps();
  350. const propsValue = this._isControlledComponent('value') ? value : defaultValue;
  351. const tmpNumber = this.doParse(this._isCurrency() ? propsValue : toString(propsValue), false, true, true);
  352. let number = null;
  353. if (typeof tmpNumber === 'number' && !isNaN(tmpNumber)) {
  354. number = tmpNumber;
  355. }
  356. const formattedValue = typeof number === 'number' ? this.doFormat(number, true, true) : '';
  357. this._adapter.setNumber(number);
  358. this._adapter.setValue(formattedValue);
  359. if (isString(formattedValue) && formattedValue !== String(propsValue ?? '')) {
  360. this.notifyChange(formattedValue, null);
  361. }
  362. }
  363. add(step?: number, event?: any): string {
  364. const pressShift = event && event.shiftKey;
  365. const propStep = pressShift ? this.getProp('shiftStep') : this.getProp('step');
  366. step = step == null ? propStep : Number(step);
  367. const stepAbs = Math.abs(toNumber(step));
  368. const curVal = this.getState('number');
  369. let curNum = this.toNumber(curVal) || 0;
  370. const min = this.getProp('min');
  371. const max = this.getProp('max');
  372. const minPrecLen = this._getPrecLen(min);
  373. const maxPrecLen = this._getPrecLen(max);
  374. const curPrecLen = this._getPrecLen(curNum);
  375. const stepPrecLen = this._getPrecLen(step);
  376. const scale = Math.pow(10, Math.max(minPrecLen, maxPrecLen, curPrecLen, stepPrecLen));
  377. if (step < 0) {
  378. // Js accuracy problem
  379. if (Math.abs(numberMinus(min, curNum)) >= stepAbs) {
  380. curNum = (curNum * scale + step * scale) / scale;
  381. }
  382. } else if (step > 0) {
  383. if (Math.abs(numberMinus(max, curNum)) >= stepAbs) {
  384. curNum = (curNum * scale + step * scale) / scale;
  385. }
  386. }
  387. if (typeof min === 'number' && min > curNum) {
  388. curNum = min;
  389. }
  390. if (typeof max === 'number' && max < curNum) {
  391. curNum = max;
  392. }
  393. // console.log('scale: ', scale, 'curNum: ', curNum);
  394. return this.doFormat(curNum, true, true);
  395. }
  396. minus(step?: number, event?: any): string {
  397. const pressShift = event && event.shiftKey;
  398. const propStep = pressShift ? this.getProp('shiftStep') : this.getProp('step');
  399. step = step == null ? propStep : Number(step);
  400. return this.add(-step, event);
  401. }
  402. /**
  403. * get decimal length
  404. * @param {number} num
  405. * @returns {number}
  406. */
  407. _getPrecLen(num: string | number) {
  408. if (typeof num !== 'string') {
  409. num = String(Math.abs(Number(num || '')));
  410. }
  411. const idx = num.indexOf('.') + 1;
  412. return idx ? num.length - idx : 0;
  413. }
  414. _adjustPrec(num: string | number) {
  415. const precision = this.getProp('precision');
  416. if (typeof precision === 'number' && num !== '' && num !== null && !Number.isNaN(Number(num))) {
  417. num = Number(num).toFixed(precision);
  418. }
  419. return toString(num);
  420. }
  421. formatCurrency(value: number | string) {
  422. const { localeCode, minimumFractionDigits, precision, maximumFractionDigits, currencyDisplay, showCurrencySymbol } = this.getProps();
  423. let formattedValue = value;
  424. if (typeof value === 'string' && Number.isNaN(Number(value))) {
  425. formattedValue = this.parseInternationalCurrency(value);
  426. }
  427. const formatter = new Intl.NumberFormat(localeCode, {
  428. style: 'currency',
  429. currency: this._getFinalCurrency() || this.getCurrencyByLocaleCode(),
  430. currencyDisplay: currencyDisplay,
  431. minimumFractionDigits: minimumFractionDigits || precision || undefined,
  432. maximumFractionDigits: maximumFractionDigits || precision || undefined,
  433. });
  434. const formatted = formatter.format(Number(formattedValue));
  435. return showCurrencySymbol ? formatted : formatted.replace(this._currencySymbol, '').trim();
  436. }
  437. /**
  438. * format number to string
  439. * @param {string|number} value
  440. * @param {boolean} needAdjustPrec
  441. * @returns {string}
  442. */
  443. doFormat(value: string | number = 0, needAdjustPrec = true, needAdjustCurrency = false): string {
  444. // if (typeof value === 'string') {
  445. // return value;
  446. // }
  447. const { formatter } = this.getProps();
  448. let str;
  449. // AdjustCurrency conversion is done only in blur situation, otherwise it is just converted to normal string
  450. if (this._isCurrency() && needAdjustCurrency) {
  451. str = this.formatCurrency(value);
  452. } else if (needAdjustPrec) {
  453. str = this._adjustPrec(value);
  454. } else {
  455. str = toString(value);
  456. }
  457. if (typeof formatter === 'function') {
  458. str = formatter(str);
  459. }
  460. return str;
  461. }
  462. /**
  463. *
  464. * @param {number} current
  465. * @returns {number}
  466. */
  467. fetchMinOrMax(current: number) {
  468. const { min, max } = this.getProps();
  469. if (current < min) {
  470. return min;
  471. } else if (current > max) {
  472. return max;
  473. }
  474. return current;
  475. }
  476. // 将货币模式的货币转化为纯数字
  477. // Convert currency in currency mode to pure numbers
  478. // eg:¥123456.78 to 123456.78
  479. // eg:123456.78 to 123456.78
  480. parseInternationalCurrency(currencyString: string) {
  481. let cleaned = currencyString
  482. .replace(this._currencySymbol, '')
  483. .replace(new RegExp(`[^\\d${this._decimalPointSymbol}\\-]`, 'g'), '');
  484. // Convert the localized decimal point to the standard decimal point
  485. if (this._decimalPointSymbol && this._decimalPointSymbol !== '.') {
  486. cleaned = cleaned.replace(this._decimalPointSymbol, '.');
  487. }
  488. return parseFloat(cleaned);
  489. }
  490. /**
  491. * parse to number
  492. * @param {string|number} value
  493. * @param {boolean} needCheckPrec
  494. * @param {boolean} needAdjustPrec
  495. * @param {boolean} needAdjustMaxMin
  496. * @returns {number}
  497. */
  498. doParse(value: string | number, needCheckPrec = true, needAdjustPrec = false, needAdjustMaxMin = false) {
  499. if (this._isCurrency() && typeof value === 'string') {
  500. value = this.parseInternationalCurrency(value);
  501. }
  502. if (typeof value === 'number') {
  503. if (needAdjustMaxMin) {
  504. value = this.fetchMinOrMax(value);
  505. }
  506. if (needAdjustPrec) {
  507. value = this._adjustPrec(value);
  508. }
  509. return toNumber(value);
  510. }
  511. const parser = this.getProp('parser');
  512. if (typeof parser === 'function') {
  513. value = parser(value);
  514. }
  515. if (needCheckPrec && typeof value === 'string') {
  516. const zeroIsValid =
  517. value.indexOf('.') === -1 ||
  518. (value.indexOf('.') > -1 && (value === '0' || value.lastIndexOf('0') < value.length - 1));
  519. const dotIsValid =
  520. value.lastIndexOf('.') < value.length - 1 && value.split('').filter((v: string) => v === '.').length < 2;
  521. if (
  522. !zeroIsValid ||
  523. !dotIsValid
  524. // (this.getProp('precision') > 0 && this._getPrecLen(value) > this.getProp('precision'))
  525. ) {
  526. return NaN;
  527. }
  528. }
  529. if (needAdjustPrec) {
  530. value = this._adjustPrec(value);
  531. }
  532. if (typeof value === 'string' && value.length) {
  533. return needAdjustMaxMin ? this.fetchMinOrMax(toNumber(value)) : toNumber(value);
  534. }
  535. return NaN;
  536. }
  537. /**
  538. * Parsing the input value
  539. * @param {string} value
  540. * @returns {string}
  541. */
  542. afterParser(value: string) {
  543. const parser = this.getProp('parser');
  544. if (typeof value === 'string' && typeof parser === 'function') {
  545. return toString(parser(value));
  546. }
  547. return toString(value);
  548. }
  549. toNumber(value: number | string, needAdjustPrec = true) {
  550. if (typeof value === 'number') {
  551. return value;
  552. }
  553. if (typeof value === 'string') {
  554. const { parser } = this.getProps();
  555. if (this._isCurrency()) {
  556. value = this.parseInternationalCurrency(value);
  557. }
  558. if (typeof parser === 'function') {
  559. value = parser(value);
  560. }
  561. if (needAdjustPrec) {
  562. value = this._adjustPrec(value);
  563. }
  564. }
  565. return toNumber(value);
  566. }
  567. /**
  568. * Returning true requires both:
  569. * 1.type is number and not equal to NaN
  570. * 2.min < = value < = max
  571. * 3.length after decimal point requires < = precision | | No precision
  572. * @param {*} um
  573. * @param {*} needCheckPrec
  574. * @returns
  575. */
  576. isValidNumber(num: number, needCheckPrec = true) {
  577. if (typeof num === 'number' && !isNaN(num)) {
  578. const { min, max, precision } = this.getProps();
  579. const numPrec = this._getPrecLen(num);
  580. const precIsValid = needCheckPrec ?
  581. (typeof precision === 'number' && numPrec <= precision) || typeof precision !== 'number' :
  582. true;
  583. if (num >= min && num <= max && precIsValid) {
  584. return true;
  585. }
  586. }
  587. return false;
  588. }
  589. isValidString(str: string) {
  590. if (typeof str === 'string' && str.length) {
  591. const parsedNum = this.doParse(str);
  592. return this.isValidNumber(parsedNum);
  593. }
  594. return false;
  595. }
  596. notifyChange(value: string, e: any) {
  597. if (value == null || value === '') {
  598. this._adapter.notifyChange('', e);
  599. } else {
  600. const parsedNum = this.toNumber(value, true);
  601. if (typeof parsedNum === 'number' && !isNaN(parsedNum)) {
  602. // this._adapter.notifyChange(typeof value === 'number' ? parsedNum : this.afterParser(value), e);
  603. this._adapter.notifyChange(parsedNum, e);
  604. this.notifyNumberChange(parsedNum, e);
  605. } else {
  606. this._adapter.notifyChange(this.afterParser(value), e);
  607. }
  608. }
  609. }
  610. notifyNumberChange(value: number, e: any) {
  611. const { number } = this.getStates();
  612. // Does not trigger numberChange if value is not a significant number
  613. if (this.isValidNumber(value) && value !== number) {
  614. this._adapter.notifyNumberChange(value, e);
  615. }
  616. }
  617. updateStates(states: BaseInputNumberState, callback?: () => void) {
  618. this._adapter.updateStates(states, callback);
  619. }
  620. /**
  621. * Get currency by locale code
  622. * @param {string} localeCode
  623. * @returns {string}
  624. */
  625. getCurrencyByLocaleCode() {
  626. const { localeCode } = this.getProps();
  627. // Mapping table of region codes to currency codes
  628. const localeToCurrency: Record<string, string> = {
  629. // Asia
  630. 'zh-CN': 'CNY', // China
  631. 'zh-HK': 'HKD', // Hong Kong
  632. 'zh-TW': 'TWD', // Taiwan
  633. 'ja-JP': 'JPY', // Japan
  634. 'ko-KR': 'KRW', // Korea
  635. 'th-TH': 'THB', // Thailand
  636. 'vi-VN': 'VND', // Vietnam
  637. 'ms-MY': 'MYR', // Malaysia
  638. 'id-ID': 'IDR', // Indonesia
  639. 'hi-IN': 'INR', // India
  640. 'ar-SA': 'SAR', // Saudi Arabia
  641. // Europe
  642. 'en-GB': 'GBP', // United Kingdom
  643. 'de-DE': 'EUR', // Germany
  644. 'fr-FR': 'EUR', // France
  645. 'it-IT': 'EUR', // Italy
  646. 'es-ES': 'EUR', // Spain
  647. 'pt-PT': 'EUR', // Portugal
  648. 'ru-RU': 'RUB', // 俄罗斯
  649. // North America
  650. 'en-US': 'USD', // United States
  651. 'en-CA': 'CAD', // Canada
  652. 'es-MX': 'MXN', // Mexico
  653. // South America
  654. 'pt-BR': 'BRL', // Brazil
  655. 'es-AR': 'ARS', // Argentina
  656. // Oceania
  657. 'en-AU': 'AUD', // Australia
  658. 'en-NZ': 'NZD', // New Zealand
  659. // Africa
  660. 'en-ZA': 'ZAR', // South Africa
  661. 'ar-EG': 'EGP', // Egypt
  662. };
  663. // Try to match the full region code directly
  664. if (localeToCurrency[localeCode]) {
  665. return localeToCurrency[localeCode];
  666. }
  667. // If no direct match, try to match the language part (the first two characters)
  668. const languageCode = localeCode.split('-')[0];
  669. const fallbackMap: Record<string, string> = {
  670. 'en': 'USD', // English defaults to USD
  671. 'zh': 'CNY', // Chinese defaults to CNY
  672. 'es': 'EUR', // Spanish defaults to EUR
  673. 'fr': 'EUR', // French defaults to EUR
  674. 'de': 'EUR', // German defaults to EUR
  675. 'it': 'EUR', // Italian defaults to EUR
  676. 'ja': 'JPY', // Japanese defaults to JPY
  677. 'ko': 'KRW', // Korean defaults to KRW
  678. 'ru': 'RUB', // Russian defaults to RUB
  679. 'ar': 'SAR', // Arabic defaults to SAR
  680. };
  681. if (fallbackMap[languageCode]) {
  682. return fallbackMap[languageCode];
  683. }
  684. // If no match, return USD as the default value
  685. return 'USD';
  686. }
  687. }
  688. export default InputNumberFoundation;