UNPKG

7.4 kBJavaScriptView Raw
1/*
2 * Copyright 2018 Palantir Technologies, Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16import { clamp } from "../../common/utils";
17/** Returns the `decimal` number separator based on locale */
18function getDecimalSeparator(locale) {
19 var testNumber = 1.9;
20 var testText = testNumber.toLocaleString(locale);
21 var one = (1).toLocaleString(locale);
22 var nine = (9).toLocaleString(locale);
23 var pattern = one + "(.+)" + nine;
24 var result = new RegExp(pattern).exec(testText);
25 return (result && result[1]) || ".";
26}
27export function toLocaleString(num, locale) {
28 if (locale === void 0) { locale = "en-US"; }
29 return sanitizeNumericInput(num.toLocaleString(locale), locale);
30}
31export function clampValue(value, min, max) {
32 // defaultProps won't work if the user passes in null, so just default
33 // to +/- infinity here instead, as a catch-all.
34 var adjustedMin = min != null ? min : -Infinity;
35 var adjustedMax = max != null ? max : Infinity;
36 return clamp(value, adjustedMin, adjustedMax);
37}
38export function getValueOrEmptyValue(value) {
39 if (value === void 0) { value = ""; }
40 return value.toString();
41}
42/** Transform the localized character (ex. "") to a javascript recognizable string number (ex. "10.99") */
43function transformLocalizedNumberToStringNumber(character, locale) {
44 var charactersMap = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function (value) { return value.toLocaleString(locale); });
45 var jsNumber = charactersMap.indexOf(character);
46 if (jsNumber !== -1) {
47 return jsNumber;
48 }
49 else {
50 return character;
51 }
52}
53/** Transforms the localized number (ex. "10,99") to a javascript recognizable string number (ex. "10.99") */
54export function parseStringToStringNumber(value, locale) {
55 var valueAsString = "" + value;
56 if (parseFloat(valueAsString).toString() === value.toString()) {
57 return value.toString();
58 }
59 if (locale !== undefined) {
60 var decimalSeparator = getDecimalSeparator(locale);
61 var sanitizedString = sanitizeNumericInput(valueAsString, locale);
62 return sanitizedString
63 .split("")
64 .map(function (character) { return transformLocalizedNumberToStringNumber(character, locale); })
65 .join("")
66 .replace(decimalSeparator, ".");
67 }
68 return value.toString();
69}
70/** Returns `true` if the string represents a valid numeric value, like "1e6". */
71export function isValueNumeric(value, locale) {
72 // checking if a string is numeric in Typescript is a big pain, because
73 // we can't simply toss a string parameter to isFinite. below is the
74 // essential approach that jQuery uses, which involves subtracting a
75 // parsed numeric value from the string representation of the value. we
76 // need to cast the value to the `any` type to allow this operation
77 // between dissimilar types.
78 var stringToStringNumber = parseStringToStringNumber(value, locale);
79 return value != null && stringToStringNumber - parseFloat(stringToStringNumber) + 1 >= 0;
80}
81export function isValidNumericKeyboardEvent(e, locale) {
82 // unit tests may not include e.key. don't bother disabling those events.
83 if (e.key == null) {
84 return true;
85 }
86 // allow modified key strokes that may involve letters and other
87 // non-numeric/invalid characters (Cmd + A, Cmd + C, Cmd + V, Cmd + X).
88 if (e.ctrlKey || e.altKey || e.metaKey) {
89 return true;
90 }
91 // keys that print a single character when pressed have a `key` name of
92 // length 1. every other key has a longer `key` name (e.g. "Backspace",
93 // "ArrowUp", "Shift"). since none of those keys can print a character
94 // to the field--and since they may have important native behaviors
95 // beyond printing a character--we don't want to disable their effects.
96 var isSingleCharKey = e.key.length === 1;
97 if (!isSingleCharKey) {
98 return true;
99 }
100 // now we can simply check that the single character that wants to be printed
101 // is a floating-point number character that we're allowed to print.
102 return isFloatingPointNumericCharacter(e.key, locale);
103}
104/**
105 * A regex that matches a string of length 1 (i.e. a standalone character)
106 * if and only if it is a floating-point number character as defined by W3C:
107 * https://www.w3.org/TR/2012/WD-html-markup-20120329/datatypes.html#common.data.float
108 *
109 * Floating-point number characters are the only characters that can be
110 * printed within a default input[type="number"]. This component should
111 * behave the same way when this.props.allowNumericCharactersOnly = true.
112 * See here for the input[type="number"].value spec:
113 * https://www.w3.org/TR/2012/WD-html-markup-20120329/input.number.html#input.number.attrs.value
114 */
115function isFloatingPointNumericCharacter(character, locale) {
116 if (locale !== undefined) {
117 var decimalSeparator = getDecimalSeparator(locale).replace(".", "\\.");
118 var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(function (value) { return value.toLocaleString(locale); }).join("");
119 var localeFloatingPointNumericCharacterRegex = new RegExp("^[Ee" + numbers + "\\+\\-" + decimalSeparator + "]$");
120 return localeFloatingPointNumericCharacterRegex.test(character);
121 }
122 else {
123 var floatingPointNumericCharacterRegex = /^[Ee0-9\+\-\.]$/;
124 return floatingPointNumericCharacterRegex.test(character);
125 }
126}
127/**
128 * Round the value to have _up to_ the specified maximum precision.
129 *
130 * This differs from `toFixed(5)` in that trailing zeroes are not added on
131 * more precise values, resulting in shorter strings.
132 */
133export function toMaxPrecision(value, maxPrecision) {
134 // round the value to have the specified maximum precision (toFixed is the wrong choice,
135 // because it would show trailing zeros in the decimal part out to the specified precision)
136 // source: http://stackoverflow.com/a/18358056/5199574
137 var scaleFactor = Math.pow(10, maxPrecision);
138 return Math.round(value * scaleFactor) / scaleFactor;
139}
140/**
141 * Convert Japanese full-width numbers, e.g. '5', to ASCII, e.g. '5'
142 * This should be called before performing any other numeric string input validation.
143 */
144function convertFullWidthNumbersToAscii(value) {
145 return value.replace(/[\uFF10-\uFF19]/g, function (m) { return String.fromCharCode(m.charCodeAt(0) - 0xfee0); });
146}
147/**
148 * Convert full-width (Japanese) numbers to ASCII, and strip all characters that are not valid floating-point numeric characters
149 */
150export function sanitizeNumericInput(value, locale) {
151 var valueChars = convertFullWidthNumbersToAscii(value).split("");
152 var sanitizedValueChars = valueChars.filter(function (valueChar) { return isFloatingPointNumericCharacter(valueChar, locale); });
153 return sanitizedValueChars.join("");
154}
155//# sourceMappingURL=numericInputUtils.js.map
\No newline at end of file