| 1 | define([ |
| 2 | "dojo/_base/declare", // declare |
| 3 | "dojo/_base/lang", // lang.hitch lang.mixin |
| 4 | "dojo/i18n", // i18n.normalizeLocale, i18n.getLocalization |
| 5 | "dojo/string", // string.rep |
| 6 | "dojo/number", // number._realNumberRegexp number.format number.parse number.regexp |
| 7 | "./RangeBoundTextBox" |
| 8 | ], function(declare, lang, i18n, string, number, RangeBoundTextBox){ |
| 9 | |
| 10 | // module: |
| 11 | // dijit/form/NumberTextBox |
| 12 | |
| 13 | // A private helper function to determine decimal information |
| 14 | // Returns an object with "sep" and "places" properties |
| 15 | var getDecimalInfo = function(constraints){ |
| 16 | var constraints = constraints || {}, |
| 17 | bundle = i18n.getLocalization("dojo.cldr", "number", i18n.normalizeLocale(constraints.locale)), |
| 18 | pattern = constraints.pattern ? constraints.pattern : bundle[(constraints.type || "decimal")+"Format"]; |
| 19 | |
| 20 | // The number of places in the constraint can be specified in several ways, |
| 21 | // the resolution order is: |
| 22 | // |
| 23 | // 1. If constraints.places is a number, use that |
| 24 | // 2. If constraints.places is a string, which specifies a range, use the range max (e.g. 0,4) |
| 25 | // 3. If a pattern is specified, use the implicit number of places in the pattern. |
| 26 | // 4. If neither constraints.pattern or constraints.places is specified, use the locale default pattern |
| 27 | var places; |
| 28 | if(typeof constraints.places == "number"){ |
| 29 | places = constraints.places; |
| 30 | }else if(typeof constraints.places === "string" && constraints.places.length > 0){ |
| 31 | places = constraints.places.replace(/.*,/, ""); |
| 32 | }else{ |
| 33 | places = (pattern.indexOf(".") != -1 ? pattern.split(".")[1].replace(/[^#0]/g, "").length : 0); |
| 34 | } |
| 35 | |
| 36 | return { sep: bundle.decimal, places: places }; |
| 37 | }; |
| 38 | |
| 39 | var NumberTextBoxMixin = declare("dijit.form.NumberTextBoxMixin", null, { |
| 40 | // summary: |
| 41 | // A mixin for all number textboxes |
| 42 | // tags: |
| 43 | // protected |
| 44 | |
| 45 | // Override ValidationTextBox.pattern.... we use a reg-ex generating function rather |
| 46 | // than a straight regexp to deal with locale (plus formatting options too?) |
| 47 | pattern: function(constraints){ |
| 48 | // if focused, accept either currency data or NumberTextBox format |
| 49 | return '(' + (this.focused && this.editOptions ? this._regExpGenerator(lang.delegate(constraints, this.editOptions)) + '|' : '') |
| 50 | + this._regExpGenerator(constraints) + ')'; |
| 51 | }, |
| 52 | |
| 53 | /*===== |
| 54 | // constraints: NumberTextBox.__Constraints |
| 55 | // Despite the name, this parameter specifies both constraints on the input |
| 56 | // (including minimum/maximum allowed values) as well as |
| 57 | // formatting options like places (the number of digits to display after |
| 58 | // the decimal point). |
| 59 | constraints: {}, |
| 60 | ======*/ |
| 61 | |
| 62 | // value: Number |
| 63 | // The value of this NumberTextBox as a Javascript Number (i.e., not a String). |
| 64 | // If the displayed value is blank, the value is NaN, and if the user types in |
| 65 | // an gibberish value (like "hello world"), the value is undefined |
| 66 | // (i.e. get('value') returns undefined). |
| 67 | // |
| 68 | // Symmetrically, set('value', NaN) will clear the displayed value, |
| 69 | // whereas set('value', undefined) will have no effect. |
| 70 | value: NaN, |
| 71 | |
| 72 | // editOptions: [protected] Object |
| 73 | // Properties to mix into constraints when the value is being edited. |
| 74 | // This is here because we edit the number in the format "12345", which is |
| 75 | // different than the display value (ex: "12,345") |
| 76 | editOptions: { pattern: '#.######' }, |
| 77 | |
| 78 | /*===== |
| 79 | _formatter: function(value, options){ |
| 80 | // summary: |
| 81 | // _formatter() is called by format(). It's the base routine for formatting a number, |
| 82 | // as a string, for example converting 12345 into "12,345". |
| 83 | // value: Number |
| 84 | // The number to be converted into a string. |
| 85 | // options: number.__FormatOptions? |
| 86 | // Formatting options |
| 87 | // tags: |
| 88 | // protected extension |
| 89 | |
| 90 | return "12345"; // String |
| 91 | }, |
| 92 | =====*/ |
| 93 | _formatter: number.format, |
| 94 | |
| 95 | /*===== |
| 96 | _regExpGenerator: function(constraints){ |
| 97 | // summary: |
| 98 | // Generate a localized regular expression as a string, according to constraints. |
| 99 | // constraints: number.__ParseOptions |
| 100 | // Formatting options |
| 101 | // tags: |
| 102 | // protected |
| 103 | |
| 104 | return "(\d*).(\d*)"; // string |
| 105 | }, |
| 106 | =====*/ |
| 107 | _regExpGenerator: number.regexp, |
| 108 | |
| 109 | // _decimalInfo: Object |
| 110 | // summary: |
| 111 | // An object containing decimal related properties relevant to this TextBox. |
| 112 | // tags: |
| 113 | // private |
| 114 | _decimalInfo: getDecimalInfo(), |
| 115 | |
| 116 | postMixInProperties: function(){ |
| 117 | this.inherited(arguments); |
| 118 | this._set("type", "text"); // in case type="number" was specified which messes up parse/format |
| 119 | }, |
| 120 | |
| 121 | _setConstraintsAttr: function(/*Object*/ constraints){ |
| 122 | var places = typeof constraints.places == "number"? constraints.places : 0; |
| 123 | if(places){ places++; } // decimal rounding errors take away another digit of precision |
| 124 | if(typeof constraints.max != "number"){ |
| 125 | constraints.max = 9 * Math.pow(10, 15-places); |
| 126 | } |
| 127 | if(typeof constraints.min != "number"){ |
| 128 | constraints.min = -9 * Math.pow(10, 15-places); |
| 129 | } |
| 130 | this.inherited(arguments, [ constraints ]); |
| 131 | if(this.focusNode && this.focusNode.value && !isNaN(this.value)){ |
| 132 | this.set('value', this.value); |
| 133 | } |
| 134 | // Capture decimal information based on the constraint locale and pattern. |
| 135 | this._decimalInfo = getDecimalInfo(constraints); |
| 136 | }, |
| 137 | |
| 138 | _onFocus: function(/*String*/ by){ |
| 139 | if(this.disabled || this.readOnly){ return; } |
| 140 | var val = this.get('value'); |
| 141 | if(typeof val == "number" && !isNaN(val)){ |
| 142 | var formattedValue = this.format(val, this.constraints); |
| 143 | if(formattedValue !== undefined){ |
| 144 | this.textbox.value = formattedValue; |
| 145 | // when NumberTextBox or descendants (i.e. CurrencyTextBox) format textbox.value when focused |
| 146 | // all browsers except Chrome will select textbox contents when tabbed to by keyboard |
| 147 | // force selection if not focused by mouse |
| 148 | if (by !== "mouse") { |
| 149 | this.textbox.select(); |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | this.inherited(arguments); |
| 154 | }, |
| 155 | |
| 156 | format: function(/*Number*/ value, /*number.__FormatOptions*/ constraints){ |
| 157 | // summary: |
| 158 | // Formats the value as a Number, according to constraints. |
| 159 | // tags: |
| 160 | // protected |
| 161 | |
| 162 | var formattedValue = String(value); |
| 163 | if(typeof value != "number"){ return formattedValue; } |
| 164 | if(isNaN(value)){ return ""; } |
| 165 | // check for exponential notation that dojo/number.format() chokes on |
| 166 | if(!("rangeCheck" in this && this.rangeCheck(value, constraints)) && constraints.exponent !== false && /\de[-+]?\d/i.test(formattedValue)){ |
| 167 | return formattedValue; |
| 168 | } |
| 169 | if(this.editOptions && this.focused){ |
| 170 | constraints = lang.mixin({}, constraints, this.editOptions); |
| 171 | } |
| 172 | return this._formatter(value, constraints); |
| 173 | }, |
| 174 | |
| 175 | /*===== |
| 176 | _parser: function(value, constraints){ |
| 177 | // summary: |
| 178 | // Parses the string value as a Number, according to constraints. |
| 179 | // value: String |
| 180 | // String representing a number |
| 181 | // constraints: number.__ParseOptions |
| 182 | // Formatting options |
| 183 | // tags: |
| 184 | // protected |
| 185 | |
| 186 | return 123.45; // Number |
| 187 | }, |
| 188 | =====*/ |
| 189 | _parser: number.parse, |
| 190 | |
| 191 | parse: function(/*String*/ value, /*number.__FormatOptions*/ constraints){ |
| 192 | // summary: |
| 193 | // Replaceable function to convert a formatted string to a number value |
| 194 | // tags: |
| 195 | // protected extension |
| 196 | var parserOptions = lang.mixin({}, constraints, (this.editOptions && this.focused) ? this.editOptions : {}) |
| 197 | if(this.focused && parserOptions.places != null /* or undefined */){ |
| 198 | var places = parserOptions.places; |
| 199 | var maxPlaces = typeof places === "number" ? places : Number(places.split(",").pop()); // handle number and range |
| 200 | parserOptions.places = "0," + maxPlaces; |
| 201 | } |
| 202 | var v = this._parser(value, parserOptions); |
| 203 | if(this.editOptions && this.focused && isNaN(v)){ |
| 204 | v = this._parser(value, constraints); // parse w/o editOptions: not technically needed but is nice for the user |
| 205 | } |
| 206 | return v; |
| 207 | }, |
| 208 | |
| 209 | _getDisplayedValueAttr: function(){ |
| 210 | var v = this.inherited(arguments); |
| 211 | return isNaN(v) ? this.textbox.value : v; |
| 212 | }, |
| 213 | |
| 214 | filter: function(/*Number*/ value){ |
| 215 | // summary: |
| 216 | // This is called with both the display value (string), and the actual value (a number). |
| 217 | // When called with the actual value it does corrections so that '' etc. are represented as NaN. |
| 218 | // Otherwise it dispatches to the superclass's filter() method. |
| 219 | // |
| 220 | // See `dijit/form/TextBox.filter()` for more details. |
| 221 | if(value == null /* or undefined */ || typeof value == "string" && value ==''){ |
| 222 | return NaN; |
| 223 | }else if(typeof value == "number" && !isNaN(value) && value != 0){ |
| 224 | value = number.round(value, this._decimalInfo.places); |
| 225 | } |
| 226 | return this.inherited(arguments, [value]); |
| 227 | }, |
| 228 | |
| 229 | serialize: function(/*Number*/ value, /*Object?*/ options){ |
| 230 | // summary: |
| 231 | // Convert value (a Number) into a canonical string (ie, how the number literal is written in javascript/java/C/etc.) |
| 232 | // tags: |
| 233 | // protected |
| 234 | return (typeof value != "number" || isNaN(value)) ? '' : this.inherited(arguments); |
| 235 | }, |
| 236 | |
| 237 | _setBlurValue: function(){ |
| 238 | var val = lang.hitch(lang.delegate(this, { focused: true }), "get")('value'); // parse with editOptions |
| 239 | this._setValueAttr(val, true); |
| 240 | }, |
| 241 | |
| 242 | _setValueAttr: function(/*Number*/ value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){ |
| 243 | // summary: |
| 244 | // Hook so set('value', ...) works. |
| 245 | if(value !== undefined && formattedValue === undefined){ |
| 246 | formattedValue = String(value); |
| 247 | if(typeof value == "number"){ |
| 248 | if(isNaN(value)){ formattedValue = '' } |
| 249 | // check for exponential notation that number.format chokes on |
| 250 | else if(("rangeCheck" in this && this.rangeCheck(value, this.constraints)) || this.constraints.exponent === false || !/\de[-+]?\d/i.test(formattedValue)){ |
| 251 | formattedValue = undefined; // lets format compute a real string value |
| 252 | } |
| 253 | }else if(!value){ // 0 processed in if branch above, ''|null|undefined flows through here |
| 254 | formattedValue = ''; |
| 255 | value = NaN; |
| 256 | }else{ // non-numeric values |
| 257 | value = undefined; |
| 258 | } |
| 259 | } |
| 260 | this.inherited(arguments, [value, priorityChange, formattedValue]); |
| 261 | }, |
| 262 | |
| 263 | _getValueAttr: function(){ |
| 264 | // summary: |
| 265 | // Hook so get('value') works. |
| 266 | // Returns Number, NaN for '', or undefined for unparseable text |
| 267 | var v = this.inherited(arguments); // returns Number for all values accepted by parse() or NaN for all other displayed values |
| 268 | |
| 269 | // If the displayed value of the textbox is gibberish (ex: "hello world"), this.inherited() above |
| 270 | // returns NaN; this if() branch converts the return value to undefined. |
| 271 | // Returning undefined prevents user text from being overwritten when doing _setValueAttr(_getValueAttr()). |
| 272 | // A blank displayed value is still returned as NaN. |
| 273 | if(isNaN(v) && this.textbox.value !== ''){ |
| 274 | if(this.constraints.exponent !== false && /\de[-+]?\d/i.test(this.textbox.value) && (new RegExp("^"+number._realNumberRegexp(lang.delegate(this.constraints))+"$").test(this.textbox.value))){ // check for exponential notation that parse() rejected (erroneously?) |
| 275 | var n = Number(this.textbox.value); |
| 276 | return isNaN(n) ? undefined : n; // return exponential Number or undefined for random text (may not be possible to do with the above RegExp check) |
| 277 | }else{ |
| 278 | return undefined; // gibberish |
| 279 | } |
| 280 | }else{ |
| 281 | return v; // Number or NaN for '' |
| 282 | } |
| 283 | }, |
| 284 | |
| 285 | isValid: function(/*Boolean*/ isFocused){ |
| 286 | // Overrides dijit/form/RangeBoundTextBox.isValid() to check that the editing-mode value is valid since |
| 287 | // it may not be formatted according to the regExp validation rules |
| 288 | if(!this.focused || this._isEmpty(this.textbox.value)){ |
| 289 | return this.inherited(arguments); |
| 290 | }else{ |
| 291 | var v = this.get('value'); |
| 292 | if(!isNaN(v) && this.rangeCheck(v, this.constraints)){ |
| 293 | if(this.constraints.exponent !== false && /\de[-+]?\d/i.test(this.textbox.value)){ // exponential, parse doesn't like it |
| 294 | return true; // valid exponential number in range |
| 295 | }else{ |
| 296 | return this.inherited(arguments); |
| 297 | } |
| 298 | }else{ |
| 299 | return false; |
| 300 | } |
| 301 | } |
| 302 | }, |
| 303 | |
| 304 | _isValidSubset: function(){ |
| 305 | // Overrides dijit/form/ValidationTextBox._isValidSubset() |
| 306 | // |
| 307 | // The inherited method only checks that the computed regex pattern is valid, which doesn't |
| 308 | // take into account that numbers are a special case. Specifically: |
| 309 | // |
| 310 | // (1) An arbitrary amount of leading or trailing zero's can be ignored. |
| 311 | // (2) Since numeric input always occurs in the order of most significant to least significant |
| 312 | // digits, the maximum and minimum possible values for partially inputted numbers can easily |
| 313 | // be determined by using the number of remaining digit spaces available. |
| 314 | // |
| 315 | // For example, if an input has a maxLength of 5, and a min value of greater than 100, then the subset |
| 316 | // is invalid if there are 3 leading 0s. It remains valid for the first two. |
| 317 | // |
| 318 | // Another example is if the min value is 1.1. Once a value of 1.0 is entered, no additional trailing digits |
| 319 | // could possibly satisify the min requirement. |
| 320 | // |
| 321 | // See ticket #17923 |
| 322 | var hasMinConstraint = (typeof this.constraints.min == "number"), |
| 323 | hasMaxConstraint = (typeof this.constraints.max == "number"), |
| 324 | curVal = this.get('value'); |
| 325 | |
| 326 | // If there is no parsable number, or there are no min or max bounds, then we can safely |
| 327 | // skip all remaining checks |
| 328 | if(isNaN(curVal) || (!hasMinConstraint && !hasMaxConstraint)){ |
| 329 | return this.inherited(arguments); |
| 330 | } |
| 331 | |
| 332 | // This block picks apart the values in the text box to be used later to compute the min and max possible |
| 333 | // values based on the current value and the remaining available digits. |
| 334 | // |
| 335 | // Warning: The use of a "num|0" expression, can be confusing. See the link below |
| 336 | // for an explanation. |
| 337 | // |
| 338 | // http://stackoverflow.com/questions/12125421/why-does-a-shift-by-0-truncate-the-decimal |
| 339 | var integerDigits = curVal|0, |
| 340 | valNegative = curVal < 0, |
| 341 | // Check if the current number has a decimal based on its locale |
| 342 | hasDecimal = this.textbox.value.indexOf(this._decimalInfo.sep) != -1, |
| 343 | // Determine the max digits based on the textbox length. If no length is |
| 344 | // specified, chose a huge number to account for crazy formatting. |
| 345 | maxDigits = this.maxLength || 20, |
| 346 | // Determine the remaining digits, based on the max digits |
| 347 | remainingDigitsCount = maxDigits - this.textbox.value.length, |
| 348 | // avoid approximation issues by capturing the decimal portion of the value as the user-entered string |
| 349 | fractionalDigitStr = hasDecimal ? this.textbox.value.split(this._decimalInfo.sep)[1].replace(/[^0-9]/g, "") : ""; |
| 350 | |
| 351 | // Create a normalized value string in the form of #.### |
| 352 | var normalizedValueStr = hasDecimal ? integerDigits+"."+fractionalDigitStr : integerDigits+""; |
| 353 | |
| 354 | // The min and max values for the field can be determined using the following |
| 355 | // logic: |
| 356 | // |
| 357 | // If the number is positive: |
| 358 | // min value = the current value |
| 359 | // max value = the current value with 9s appended for all remaining possible digits |
| 360 | // else |
| 361 | // min value = the current value with 9s appended for all remaining possible digits |
| 362 | // max value = the current value |
| 363 | // |
| 364 | var ninePaddingStr = string.rep("9", remainingDigitsCount), |
| 365 | minPossibleValue = curVal, |
| 366 | maxPossibleValue = curVal; |
| 367 | if (valNegative){ |
| 368 | minPossibleValue = Number(normalizedValueStr+ninePaddingStr); |
| 369 | } else{ |
| 370 | maxPossibleValue = Number(normalizedValueStr+ninePaddingStr); |
| 371 | } |
| 372 | |
| 373 | return !((hasMinConstraint && maxPossibleValue < this.constraints.min) |
| 374 | || (hasMaxConstraint && minPossibleValue > this.constraints.max)); |
| 375 | } |
| 376 | }); |
| 377 | |
| 378 | var NumberTextBox = declare("dijit.form.NumberTextBox", [RangeBoundTextBox, NumberTextBoxMixin], { |
| 379 | // summary: |
| 380 | // A TextBox for entering numbers, with formatting and range checking |
| 381 | // description: |
| 382 | // NumberTextBox is a textbox for entering and displaying numbers, supporting |
| 383 | // the following main features: |
| 384 | // |
| 385 | // 1. Enforce minimum/maximum allowed values (as well as enforcing that the user types |
| 386 | // a number rather than a random string) |
| 387 | // 2. NLS support (altering roles of comma and dot as "thousands-separator" and "decimal-point" |
| 388 | // depending on locale). |
| 389 | // 3. Separate modes for editing the value and displaying it, specifically that |
| 390 | // the thousands separator character (typically comma) disappears when editing |
| 391 | // but reappears after the field is blurred. |
| 392 | // 4. Formatting and constraints regarding the number of places (digits after the decimal point) |
| 393 | // allowed on input, and number of places displayed when blurred (see `constraints` parameter). |
| 394 | |
| 395 | baseClass: "dijitTextBox dijitNumberTextBox" |
| 396 | }); |
| 397 | |
| 398 | NumberTextBox.Mixin = NumberTextBoxMixin; // for monkey patching |
| 399 | |
| 400 | /*===== |
| 401 | NumberTextBox.__Constraints = declare([RangeBoundTextBox.__Constraints, number.__FormatOptions, number.__ParseOptions], { |
| 402 | // summary: |
| 403 | // Specifies both the rules on valid/invalid values (minimum, maximum, |
| 404 | // number of required decimal places), and also formatting options for |
| 405 | // displaying the value when the field is not focused. |
| 406 | // example: |
| 407 | // Minimum/maximum: |
| 408 | // To specify a field between 0 and 120: |
| 409 | // | {min:0,max:120} |
| 410 | // To specify a field that must be an integer: |
| 411 | // | {fractional:false} |
| 412 | // To specify a field where 0 to 3 decimal places are allowed on input: |
| 413 | // | {places:'0,3'} |
| 414 | }); |
| 415 | =====*/ |
| 416 | |
| 417 | return NumberTextBox; |
| 418 | }); |