Debian Codegraph @

dijit/form/_TextBoxMixin.js

raw symbols SCIP
1 define([
2 "dojo/_base/array", // array.forEach
3 "dojo/_base/declare", // declare
4 "dojo/dom", // dom.byId
5 "dojo/sniff", // has("ie"), has("dojo-bidi")
6 "dojo/keys", // keys.ALT keys.CAPS_LOCK keys.CTRL keys.META keys.SHIFT
7 "dojo/_base/lang", // lang.mixin
8 "dojo/on", // on
9 "../main" // for exporting dijit._setSelectionRange, dijit.selectInputText
10 ], function(array, declare, dom, has, keys, lang, on, dijit){
11
12 // module:
13 // dijit/form/_TextBoxMixin
14
15 var _TextBoxMixin = declare("dijit.form._TextBoxMixin" + (has("dojo-bidi") ? "_NoBidi" : ""), null, {
16 // summary:
17 // A mixin for textbox form input widgets
18
19 // trim: Boolean
20 // Removes leading and trailing whitespace if true. Default is false.
21 trim: false,
22
23 // uppercase: Boolean
24 // Converts all characters to uppercase if true. Default is false.
25 uppercase: false,
26
27 // lowercase: Boolean
28 // Converts all characters to lowercase if true. Default is false.
29 lowercase: false,
30
31 // propercase: Boolean
32 // Converts the first character of each word to uppercase if true.
33 propercase: false,
34
35 // maxLength: String
36 // HTML INPUT tag maxLength declaration.
37 maxLength: "",
38
39 // selectOnClick: [const] Boolean
40 // If true, all text will be selected when focused with mouse
41 selectOnClick: false,
42
43 // placeHolder: String
44 // Defines a hint to help users fill out the input field (as defined in HTML 5).
45 // This should only contain plain text (no html markup).
46 placeHolder: "",
47
48 _getValueAttr: function(){
49 // summary:
50 // Hook so get('value') works as we like.
51 // description:
52 // For `dijit/form/TextBox` this basically returns the value of the `<input>`.
53 //
54 // For `dijit/form/MappedTextBox` subclasses, which have both
55 // a "displayed value" and a separate "submit value",
56 // This treats the "displayed value" as the master value, computing the
57 // submit value from it via this.parse().
58 return this.parse(this.get('displayedValue'), this.constraints);
59 },
60
61 _setValueAttr: function(value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
62 // summary:
63 // Hook so set('value', ...) works.
64 //
65 // description:
66 // Sets the value of the widget to "value" which can be of
67 // any type as determined by the widget.
68 //
69 // value:
70 // The visual element value is also set to a corresponding,
71 // but not necessarily the same, value.
72 //
73 // formattedValue:
74 // If specified, used to set the visual element value,
75 // otherwise a computed visual value is used.
76 //
77 // priorityChange:
78 // If true, an onChange event is fired immediately instead of
79 // waiting for the next blur event.
80
81 var filteredValue;
82 if(value !== undefined){
83 // TODO: this is calling filter() on both the display value and the actual value.
84 // I added a comment to the filter() definition about this, but it should be changed.
85 filteredValue = this.filter(value);
86 if(typeof formattedValue != "string"){
87 if(filteredValue !== null && ((typeof filteredValue != "number") || !isNaN(filteredValue))){
88 formattedValue = this.filter(this.format(filteredValue, this.constraints));
89 }else{
90 formattedValue = '';
91 }
92 // Ensure the filtered value does not change after being formatted. See track #17955.
93 //
94 // This check is only applied when the formatted value is not specified by the caller in order to allow the
95 // behavior to be overriden. This is needed whenever value synonyms cannot be determined using parse/compare. For
96 // example, dijit/form/FilteringSelect determines the formatted value asynchronously and applies it using a
97 // callback to this method.
98 //
99 // TODO: Should developers be warned that they broke the round trip on format?
100 if (this.compare(filteredValue, this.filter(this.parse(formattedValue, this.constraints))) != 0){
101 formattedValue = null;
102 }
103 }
104 }
105 if(formattedValue != null /* and !undefined */ && ((typeof formattedValue) != "number" || !isNaN(formattedValue)) && this.textbox.value != formattedValue){
106 this.textbox.value = formattedValue;
107 this._set("displayedValue", this.get("displayedValue"));
108 }
109
110 this.inherited(arguments, [filteredValue, priorityChange]);
111 },
112
113 // displayedValue: String
114 // For subclasses like ComboBox where the displayed value
115 // (ex: Kentucky) and the serialized value (ex: KY) are different,
116 // this represents the displayed value.
117 //
118 // Setting 'displayedValue' through set('displayedValue', ...)
119 // updates 'value', and vice-versa. Otherwise 'value' is updated
120 // from 'displayedValue' periodically, like onBlur etc.
121 //
122 // TODO: move declaration to MappedTextBox?
123 // Problem is that ComboBox references displayedValue,
124 // for benefit of FilteringSelect.
125 displayedValue: "",
126
127 _getDisplayedValueAttr: function(){
128 // summary:
129 // Hook so get('displayedValue') works.
130 // description:
131 // Returns the displayed value (what the user sees on the screen),
132 // after filtering (ie, trimming spaces etc.).
133 //
134 // For some subclasses of TextBox (like ComboBox), the displayed value
135 // is different from the serialized value that's actually
136 // sent to the server (see `dijit/form/ValidationTextBox.serialize()`)
137
138 // TODO: maybe we should update this.displayedValue on every keystroke so that we don't need
139 // this method
140 // TODO: this isn't really the displayed value when the user is typing
141 return this.filter(this.textbox.value);
142 },
143
144 _setDisplayedValueAttr: function(/*String*/ value){
145 // summary:
146 // Hook so set('displayedValue', ...) works.
147 // description:
148 // Sets the value of the visual element to the string "value".
149 // The widget value is also set to a corresponding,
150 // but not necessarily the same, value.
151
152 if(value == null /* or undefined */){
153 value = ''
154 }
155 else if(typeof value != "string"){
156 value = String(value)
157 }
158
159 this.textbox.value = value;
160
161 // sets the serialized value to something corresponding to specified displayedValue
162 // (if possible), and also updates the textbox.value, for example converting "123"
163 // to "123.00"
164 this._setValueAttr(this.get('value'), undefined);
165
166 this._set("displayedValue", this.get('displayedValue'));
167 },
168
169 format: function(value /*=====, constraints =====*/){
170 // summary:
171 // Replaceable function to convert a value to a properly formatted string.
172 // value: String
173 // constraints: Object
174 // tags:
175 // protected extension
176 return value == null /* or undefined */ ? "" : (value.toString ? value.toString() : value);
177 },
178
179 parse: function(value /*=====, constraints =====*/){
180 // summary:
181 // Replaceable function to convert a formatted string to a value
182 // value: String
183 // constraints: Object
184 // tags:
185 // protected extension
186
187 return value; // String
188 },
189
190 _refreshState: function(){
191 // summary:
192 // After the user types some characters, etc., this method is
193 // called to check the field for validity etc. The base method
194 // in `dijit/form/TextBox` does nothing, but subclasses override.
195 // tags:
196 // protected
197 },
198
199 onInput: function(/*Event*/ /*===== evt =====*/){
200 // summary:
201 // Connect to this function to receive notifications of various user data-input events.
202 // Return false to cancel the event and prevent it from being processed.
203 // Note that although for historical reasons this method is called `onInput()`, it doesn't
204 // correspond to the standard DOM "input" event, because it occurs before the input has been processed.
205 // event:
206 // keydown | keypress | cut | paste | compositionend
207 // tags:
208 // callback
209 },
210
211 _onInput: function(/*Event*/ evt){
212 // summary:
213 // Called AFTER the input event has happened and this.textbox.value has new value.
214
215 this._lastInputEventValue = this.textbox.value;
216
217 // For Combobox, this needs to be called w/the keydown/keypress event that was passed to onInput().
218 // As a backup, use the "input" event itself.
219 this._processInput(this._lastInputProducingEvent || evt);
220 delete this._lastInputProducingEvent;
221
222 if(this.intermediateChanges){
223 this._handleOnChange(this.get('value'), false);
224 }
225 },
226
227 _processInput: function(/*Event*/ /*===== evt =====*/){
228 // summary:
229 // Default action handler for user input events.
230 // Called after the "input" event (i.e. after this.textbox.value has been updated),
231 // but `evt` is the keydown/keypress/etc. event that triggered the "input" event.
232 // tags:
233 // protected
234
235 this._refreshState();
236
237 // In case someone is watch()'ing for changes to displayedValue
238 this._set("displayedValue", this.get("displayedValue"));
239 },
240
241 postCreate: function(){
242 // setting the value here is needed since value="" in the template causes "undefined"
243 // and setting in the DOM (instead of the JS object) helps with form reset actions
244 this.textbox.setAttribute("value", this.textbox.value); // DOM and JS values should be the same
245
246 this.inherited(arguments);
247
248 // normalize input events to reduce spurious event processing
249 // keydown: do not forward modifier keys
250 // set charOrCode to numeric keycode
251 // keypress: do not forward numeric charOrCode keys (already sent through onkeydown)
252 // paste, cut, compositionend: set charOrCode to 229 (IME)
253 function handleEvent(e){
254 var charOrCode;
255
256 // Filter out keydown events that will be followed by keypress events. Note that chrome/android
257 // w/word suggestion has keydown/229 events on typing with no corresponding keypress events.
258 if(e.type == "keydown" && e.keyCode != 229){
259 charOrCode = e.keyCode;
260 switch(charOrCode){ // ignore state keys
261 case keys.SHIFT:
262 case keys.ALT:
263 case keys.CTRL:
264 case keys.META:
265 case keys.CAPS_LOCK:
266 case keys.NUM_LOCK:
267 case keys.SCROLL_LOCK:
268 return;
269 }
270 if(!e.ctrlKey && !e.metaKey && !e.altKey){ // no modifiers
271 switch(charOrCode){ // ignore location keys
272 case keys.NUMPAD_0:
273 case keys.NUMPAD_1:
274 case keys.NUMPAD_2:
275 case keys.NUMPAD_3:
276 case keys.NUMPAD_4:
277 case keys.NUMPAD_5:
278 case keys.NUMPAD_6:
279 case keys.NUMPAD_7:
280 case keys.NUMPAD_8:
281 case keys.NUMPAD_9:
282 case keys.NUMPAD_MULTIPLY:
283 case keys.NUMPAD_PLUS:
284 case keys.NUMPAD_ENTER:
285 case keys.NUMPAD_MINUS:
286 case keys.NUMPAD_PERIOD:
287 case keys.NUMPAD_DIVIDE:
288 return;
289 }
290 if((charOrCode >= 65 && charOrCode <= 90) || (charOrCode >= 48 && charOrCode <= 57) || charOrCode == keys.SPACE){
291 return; // keypress will handle simple non-modified printable keys
292 }
293 var named = false;
294 for(var i in keys){
295 if(keys[i] === e.keyCode){
296 named = true;
297 break;
298 }
299 }
300 if(!named){
301 return;
302 } // only allow named ones through
303 }
304 }
305
306 charOrCode = e.charCode >= 32 ? String.fromCharCode(e.charCode) : e.charCode;
307 if(!charOrCode){
308 charOrCode = (e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode == keys.SPACE ? String.fromCharCode(e.keyCode) : e.keyCode;
309 }
310 if(!charOrCode){
311 charOrCode = 229; // IME
312 }
313 if(e.type == "keypress"){
314 if(typeof charOrCode != "string"){
315 return;
316 }
317 if((charOrCode >= 'a' && charOrCode <= 'z') || (charOrCode >= 'A' && charOrCode <= 'Z') || (charOrCode >= '0' && charOrCode <= '9') || (charOrCode === ' ')){
318 if(e.ctrlKey || e.metaKey || e.altKey){
319 return;
320 } // can only be stopped reliably in keydown
321 }
322 }
323
324 // create fake event to set charOrCode and to know if preventDefault() was called
325 var faux = { faux: true }, attr;
326 for(attr in e){
327 if(!/^(layer[XY]|returnValue|keyLocation)$/.test(attr)){ // prevent WebKit warnings
328 var v = e[attr];
329 if(typeof v != "function" && typeof v != "undefined"){
330 faux[attr] = v;
331 }
332 }
333 }
334 lang.mixin(faux, {
335 charOrCode: charOrCode,
336 _wasConsumed: false,
337 preventDefault: function(){
338 faux._wasConsumed = true;
339 e.preventDefault();
340 },
341 stopPropagation: function(){
342 e.stopPropagation();
343 }
344 });
345
346 this._lastInputProducingEvent = faux;
347
348 // Give web page author a chance to consume the event. Note that onInput() may be called multiple times
349 // for same keystroke: once for keypress event and once for input event.
350 //console.log(faux.type + ', charOrCode = (' + (typeof charOrCode) + ') ' + charOrCode + ', ctrl ' + !!faux.ctrlKey + ', alt ' + !!faux.altKey + ', meta ' + !!faux.metaKey + ', shift ' + !!faux.shiftKey);
351 if(this.onInput(faux) === false){ // return false means stop
352 faux.preventDefault();
353 faux.stopPropagation();
354 }
355 if(faux._wasConsumed){
356 return;
357 } // if preventDefault was called
358
359 // IE8 doesn't emit the "input" event at all, and IE9 doesn't emit it for backspace, delete, cut, etc.
360 // Since the code below (and perhaps user code) depends on that event, emit it synthetically.
361 // See http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html.
362 if(has("ie") <= 9){
363 switch(e.keyCode){
364 case keys.TAB:
365 case keys.ESCAPE:
366 case keys.DOWN_ARROW:
367 case keys.UP_ARROW:
368 case keys.LEFT_ARROW:
369 case keys.RIGHT_ARROW:
370 // These keys may alter the <input>'s value indirectly, but we don't want to emit an "input"
371 // event. For example, the up/down arrows in TimeTextBox or ComboBox will cause the next
372 // dropdown item's value to be copied to the <input>.
373 break;
374 default:
375 if(e.keyCode == keys.ENTER && this.textbox.tagName.toLowerCase() != "textarea"){
376 break;
377 }
378 this.defer(function(){
379 if(this.textbox.value !== this._lastInputEventValue){
380 on.emit(this.textbox, "input", {bubbles: true});
381 }
382 });
383 }
384 }
385 }
386 this.own(
387 on(this.textbox, "keydown, keypress, paste, cut, compositionend", lang.hitch(this, handleEvent)),
388 on(this.textbox, "input", lang.hitch(this, "_onInput")),
389
390 // Allow keypress to bubble to this.domNode, so that TextBox.on("keypress", ...) works,
391 // but prevent it from further propagating, so that typing into a TextBox inside a Toolbar doesn't
392 // trigger the Toolbar's letter key navigation.
393 on(this.domNode, "keypress", function(e){ e.stopPropagation(); })
394 );
395 },
396
397 _blankValue: '', // if the textbox is blank, what value should be reported
398 filter: function(val){
399 // summary:
400 // Auto-corrections (such as trimming) that are applied to textbox
401 // value on blur or form submit.
402 // description:
403 // For MappedTextBox subclasses, this is called twice
404 //
405 // - once with the display value
406 // - once the value as set/returned by set('value', ...)
407 //
408 // and get('value'), ex: a Number for NumberTextBox.
409 //
410 // In the latter case it does corrections like converting null to NaN. In
411 // the former case the NumberTextBox.filter() method calls this.inherited()
412 // to execute standard trimming code in TextBox.filter().
413 //
414 // TODO: break this into two methods in 2.0
415 //
416 // tags:
417 // protected extension
418 if(val === null){
419 return this._blankValue;
420 }
421 if(typeof val != "string"){
422 return val;
423 }
424 if(this.trim){
425 val = lang.trim(val);
426 }
427 if(this.uppercase){
428 val = val.toUpperCase();
429 }
430 if(this.lowercase){
431 val = val.toLowerCase();
432 }
433 if(this.propercase){
434 val = val.replace(/[^\s]+/g, function(word){
435 return word.substring(0, 1).toUpperCase() + word.substring(1);
436 });
437 }
438 return val;
439 },
440
441 _setBlurValue: function(){
442 // Format the displayed value, for example (for NumberTextBox) convert 1.4 to 1.400,
443 // or (for CurrencyTextBox) 2.50 to $2.50
444
445 this._setValueAttr(this.get('value'), true);
446 },
447
448 _onBlur: function(e){
449 if(this.disabled){
450 return;
451 }
452 this._setBlurValue();
453 this.inherited(arguments);
454 },
455
456 _isTextSelected: function(){
457 return this.textbox.selectionStart != this.textbox.selectionEnd;
458 },
459
460 _onFocus: function(/*String*/ by){
461 if(this.disabled || this.readOnly){
462 return;
463 }
464
465 // Select all text on focus via click if nothing already selected.
466 // Since mouse-up will clear the selection, need to defer selection until after mouse-up.
467 // Don't do anything on focus by tabbing into the widget since there's no associated mouse-up event.
468 if(this.selectOnClick && by == "mouse"){
469 // Use on.once() to only select all text on first click only; otherwise users would have no way to clear
470 // the selection.
471 this._selectOnClickHandle = on.once(this.domNode, "mouseup, touchend", lang.hitch(this, function(evt){
472 // Check if the user selected some text manually (mouse-down, mouse-move, mouse-up)
473 // and if not, then select all the text
474 if(!this._isTextSelected()){
475 _TextBoxMixin.selectInputText(this.textbox);
476 }
477 }));
478 this.own(this._selectOnClickHandle);
479
480 // in case the mouseup never comes
481 this.defer(function(){
482 if(this._selectOnClickHandle){
483 this._selectOnClickHandle.remove();
484 this._selectOnClickHandle = null;
485 }
486 }, 500); // if mouseup not received soon, then treat it as some gesture
487 }
488 // call this.inherited() before refreshState(), since this.inherited() will possibly scroll the viewport
489 // (to scroll the TextBox into view), which will affect how _refreshState() positions the tooltip
490 this.inherited(arguments);
491
492 this._refreshState();
493 },
494
495 reset: function(){
496 // Overrides `dijit/_FormWidget/reset()`.
497 // Additionally resets the displayed textbox value to ''
498 this.textbox.value = '';
499 this.inherited(arguments);
500 }
501 });
502
503 if(has("dojo-bidi")){
504 _TextBoxMixin = declare("dijit.form._TextBoxMixin", _TextBoxMixin, {
505 _setValueAttr: function(){
506 this.inherited(arguments);
507 this.applyTextDir(this.focusNode);
508 },
509 _setDisplayedValueAttr: function(){
510 this.inherited(arguments);
511 this.applyTextDir(this.focusNode);
512 },
513 _onInput: function(){
514 this.applyTextDir(this.focusNode);
515 this.inherited(arguments);
516 }
517 });
518 }
519
520 _TextBoxMixin._setSelectionRange = dijit._setSelectionRange = function(/*DomNode*/ element, /*Number?*/ start, /*Number?*/ stop){
521 if(element.setSelectionRange){
522 element.setSelectionRange(start, stop);
523 }
524 };
525
526 _TextBoxMixin.selectInputText = dijit.selectInputText = function(/*DomNode*/ element, /*Number?*/ start, /*Number?*/ stop){
527 // summary:
528 // Select text in the input element argument, from start (default 0), to stop (default end).
529
530 // TODO: use functions in _editor/selection.js?
531 element = dom.byId(element);
532 if(isNaN(start)){
533 start = 0;
534 }
535 if(isNaN(stop)){
536 stop = element.value ? element.value.length : 0;
537 }
538 try{
539 element.focus();
540 _TextBoxMixin._setSelectionRange(element, start, stop);
541 }catch(e){ /* squelch random errors (esp. on IE) from unexpected focus changes or DOM nodes being hidden */
542 }
543 };
544
545 return _TextBoxMixin;
546 });