1 define("dijit/form/_TextBoxMixin", [
2 "dojo/_base/array", // array.forEach
3 "dojo/_base/declare", // declare
4 "dojo/dom", // dom.byId
5 "dojo/_base/event", // event.stop
6 "dojo/keys", // keys.ALT keys.CAPS_LOCK keys.CTRL keys.META keys.SHIFT
7 "dojo/_base/lang", // lang.mixin
9 "../main" // for exporting dijit._setSelectionRange, dijit.selectInputText
10 ], function(array, declare, dom, event, keys, lang, on, dijit){
13 // dijit/form/_TextBoxMixin
15 var _TextBoxMixin = declare("dijit.form._TextBoxMixin", null, {
17 // A mixin for textbox form input widgets
20 // Removes leading and trailing whitespace if true. Default is false.
24 // Converts all characters to uppercase if true. Default is false.
28 // Converts all characters to lowercase if true. Default is false.
31 // propercase: Boolean
32 // Converts the first character of each word to uppercase if true.
36 // HTML INPUT tag maxLength declaration.
39 // selectOnClick: [const] Boolean
40 // If true, all text will be selected when focused with mouse
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).
48 _getValueAttr: function(){
50 // Hook so get('value') works as we like.
52 // For `dijit/form/TextBox` this basically returns the value of the `<input>`.
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);
61 _setValueAttr: function(value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){
63 // Hook so set('value', ...) works.
66 // Sets the value of the widget to "value" which can be of
67 // any type as determined by the widget.
70 // The visual element value is also set to a corresponding,
71 // but not necessarily the same, value.
74 // If specified, used to set the visual element value,
75 // otherwise a computed visual value is used.
78 // If true, an onChange event is fired immediately instead of
79 // waiting for the next blur event.
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{ formattedValue = ''; }
92 if(formattedValue != null /* and !undefined */ && ((typeof formattedValue) != "number" || !isNaN(formattedValue)) && this.textbox.value != formattedValue){
93 this.textbox.value = formattedValue;
94 this._set("displayedValue", this.get("displayedValue"));
97 if(this.textDir == "auto"){
98 this.applyTextDir(this.focusNode, formattedValue);
101 this.inherited(arguments, [filteredValue, priorityChange]);
104 // displayedValue: String
105 // For subclasses like ComboBox where the displayed value
106 // (ex: Kentucky) and the serialized value (ex: KY) are different,
107 // this represents the displayed value.
109 // Setting 'displayedValue' through set('displayedValue', ...)
110 // updates 'value', and vice-versa. Otherwise 'value' is updated
111 // from 'displayedValue' periodically, like onBlur etc.
113 // TODO: move declaration to MappedTextBox?
114 // Problem is that ComboBox references displayedValue,
115 // for benefit of FilteringSelect.
118 _getDisplayedValueAttr: function(){
120 // Hook so get('displayedValue') works.
122 // Returns the displayed value (what the user sees on the screen),
123 // after filtering (ie, trimming spaces etc.).
125 // For some subclasses of TextBox (like ComboBox), the displayed value
126 // is different from the serialized value that's actually
127 // sent to the server (see `dijit/form/ValidationTextBox.serialize()`)
129 // TODO: maybe we should update this.displayedValue on every keystroke so that we don't need
131 // TODO: this isn't really the displayed value when the user is typing
132 return this.filter(this.textbox.value);
135 _setDisplayedValueAttr: function(/*String*/ value){
137 // Hook so set('displayedValue', ...) works.
139 // Sets the value of the visual element to the string "value".
140 // The widget value is also set to a corresponding,
141 // but not necessarily the same, value.
143 if(value == null /* or undefined */){ value = '' }
144 else if(typeof value != "string"){ value = String(value) }
146 this.textbox.value = value;
148 // sets the serialized value to something corresponding to specified displayedValue
149 // (if possible), and also updates the textbox.value, for example converting "123"
151 this._setValueAttr(this.get('value'), undefined);
153 this._set("displayedValue", this.get('displayedValue'));
156 if(this.textDir == "auto"){
157 this.applyTextDir(this.focusNode, value);
161 format: function(value /*=====, constraints =====*/){
163 // Replaceable function to convert a value to a properly formatted string.
165 // constraints: Object
167 // protected extension
168 return value == null /* or undefined */ ? "" : (value.toString ? value.toString() : value);
171 parse: function(value /*=====, constraints =====*/){
173 // Replaceable function to convert a formatted string to a value
175 // constraints: Object
177 // protected extension
179 return value; // String
182 _refreshState: function(){
184 // After the user types some characters, etc., this method is
185 // called to check the field for validity etc. The base method
186 // in `dijit/form/TextBox` does nothing, but subclasses override.
192 onInput: function(event){
194 // Connect to this function to receive notifications of various user data-input events.
195 // Return false to cancel the event and prevent it from being processed.
197 // keydown | keypress | cut | paste | input
202 onInput: function(){},
204 __skipInputEvent: false,
205 _onInput: function(/*Event*/ evt){
207 // Called AFTER the input event has happened
209 // set text direction according to textDir that was defined in creation
210 if(this.textDir == "auto"){
211 this.applyTextDir(this.focusNode, this.focusNode.value);
214 this._processInput(evt);
217 _processInput: function(/*Event*/ evt){
219 // Default action handler for user input events
221 this._refreshState();
223 // In case someone is watch()'ing for changes to displayedValue
224 this._set("displayedValue", this.get("displayedValue"));
227 postCreate: function(){
228 // setting the value here is needed since value="" in the template causes "undefined"
229 // and setting in the DOM (instead of the JS object) helps with form reset actions
230 this.textbox.setAttribute("value", this.textbox.value); // DOM and JS values should be the same
232 this.inherited(arguments);
234 // normalize input events to reduce spurious event processing
235 // onkeydown: do not forward modifier keys
236 // set charOrCode to numeric keycode
237 // onkeypress: do not forward numeric charOrCode keys (already sent through onkeydown)
238 // onpaste & oncut: set charOrCode to 229 (IME)
239 // oninput: if primary event not already processed, set charOrCode to 229 (IME), else do not forward
240 var handleEvent = function(e){
242 if(e.type == "keydown"){
243 charOrCode = e.keyCode;
244 switch(charOrCode){ // ignore state keys
251 case keys.SCROLL_LOCK:
254 if(!e.ctrlKey && !e.metaKey && !e.altKey){ // no modifiers
255 switch(charOrCode){ // ignore location keys
266 case keys.NUMPAD_MULTIPLY:
267 case keys.NUMPAD_PLUS:
268 case keys.NUMPAD_ENTER:
269 case keys.NUMPAD_MINUS:
270 case keys.NUMPAD_PERIOD:
271 case keys.NUMPAD_DIVIDE:
274 if((charOrCode >= 65 && charOrCode <= 90) || (charOrCode >= 48 && charOrCode <= 57) || charOrCode == keys.SPACE){
275 return; // keypress will handle simple non-modified printable keys
279 if(keys[i] === e.keyCode){
284 if(!named){ return; } // only allow named ones through
287 charOrCode = e.charCode >= 32 ? String.fromCharCode(e.charCode) : e.charCode;
289 charOrCode = (e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode == keys.SPACE ? String.fromCharCode(e.keyCode) : e.keyCode;
292 charOrCode = 229; // IME
294 if(e.type == "keypress"){
295 if(typeof charOrCode != "string"){ return; }
296 if((charOrCode >= 'a' && charOrCode <= 'z') || (charOrCode >= 'A' && charOrCode <= 'Z') || (charOrCode >= '0' && charOrCode <= '9') || (charOrCode === ' ')){
297 if(e.ctrlKey || e.metaKey || e.altKey){ return; } // can only be stopped reliably in keydown
300 if(e.type == "input"){
301 if(this.__skipInputEvent){ // duplicate event
302 this.__skipInputEvent = false;
306 this.__skipInputEvent = true;
308 // create fake event to set charOrCode and to know if preventDefault() was called
309 var faux = { faux: true }, attr;
311 if(attr != "layerX" && attr != "layerY"){ // prevent WebKit warnings
313 if(typeof v != "function" && typeof v != "undefined"){ faux[attr] = v; }
317 charOrCode: charOrCode,
319 preventDefault: function(){
320 faux._wasConsumed = true;
323 stopPropagation: function(){ e.stopPropagation(); }
325 // give web page author a chance to consume the event
326 //console.log(faux.type + ', charOrCode = (' + (typeof charOrCode) + ') ' + charOrCode + ', ctrl ' + !!faux.ctrlKey + ', alt ' + !!faux.altKey + ', meta ' + !!faux.metaKey + ', shift ' + !!faux.shiftKey);
327 if(this.onInput(faux) === false){ // return false means stop
328 faux.preventDefault();
329 faux.stopPropagation();
331 if(faux._wasConsumed){ return; } // if preventDefault was called
332 this.defer(function(){ this._onInput(faux); }); // widget notification after key has posted
334 this.own(on(this.textbox, "keydown, keypress, paste, cut, input, compositionend", lang.hitch(this, handleEvent)));
337 _blankValue: '', // if the textbox is blank, what value should be reported
338 filter: function(val){
340 // Auto-corrections (such as trimming) that are applied to textbox
341 // value on blur or form submit.
343 // For MappedTextBox subclasses, this is called twice
345 // - once with the display value
346 // - once the value as set/returned by set('value', ...)
348 // and get('value'), ex: a Number for NumberTextBox.
350 // In the latter case it does corrections like converting null to NaN. In
351 // the former case the NumberTextBox.filter() method calls this.inherited()
352 // to execute standard trimming code in TextBox.filter().
354 // TODO: break this into two methods in 2.0
357 // protected extension
358 if(val === null){ return this._blankValue; }
359 if(typeof val != "string"){ return val; }
361 val = lang.trim(val);
364 val = val.toUpperCase();
367 val = val.toLowerCase();
370 val = val.replace(/[^\s]+/g, function(word){
371 return word.substring(0,1).toUpperCase() + word.substring(1);
377 _setBlurValue: function(){
378 this._setValueAttr(this.get('value'), true);
381 _onBlur: function(e){
382 if(this.disabled){ return; }
383 this._setBlurValue();
384 this.inherited(arguments);
387 _isTextSelected: function(){
388 return this.textbox.selectionStart != this.textbox.selectionEnd;
391 _onFocus: function(/*String*/ by){
392 if(this.disabled || this.readOnly){ return; }
394 // Select all text on focus via click if nothing already selected.
395 // Since mouse-up will clear the selection, need to defer selection until after mouse-up.
396 // Don't do anything on focus by tabbing into the widget since there's no associated mouse-up event.
397 if(this.selectOnClick && by == "mouse"){
398 this._selectOnClickHandle = this.connect(this.domNode, "onmouseup", function(){
399 // Only select all text on first click; otherwise users would have no way to clear
401 this.disconnect(this._selectOnClickHandle);
402 this._selectOnClickHandle = null;
404 // Check if the user selected some text manually (mouse-down, mouse-move, mouse-up)
405 // and if not, then select all the text
406 if(!this._isTextSelected()){
407 _TextBoxMixin.selectInputText(this.textbox);
410 // in case the mouseup never comes
411 this.defer(function(){
412 if(this._selectOnClickHandle){
413 this.disconnect(this._selectOnClickHandle);
414 this._selectOnClickHandle = null;
416 }, 500); // if mouseup not received soon, then treat it as some gesture
418 // call this.inherited() before refreshState(), since this.inherited() will possibly scroll the viewport
419 // (to scroll the TextBox into view), which will affect how _refreshState() positions the tooltip
420 this.inherited(arguments);
422 this._refreshState();
426 // Overrides `dijit/_FormWidget/reset()`.
427 // Additionally resets the displayed textbox value to ''
428 this.textbox.value = '';
429 this.inherited(arguments);
432 _setTextDirAttr: function(/*String*/ textDir){
434 // Setter for textDir.
436 // Users shouldn't call this function; they should be calling
437 // set('textDir', value)
441 // only if new textDir is different from the old one
442 // and on widgets creation.
444 || this.textDir != textDir){
445 this._set("textDir", textDir);
446 // so the change of the textDir will take place immediately.
447 this.applyTextDir(this.focusNode, this.focusNode.value);
453 _TextBoxMixin._setSelectionRange = dijit._setSelectionRange = function(/*DomNode*/ element, /*Number?*/ start, /*Number?*/ stop){
454 if(element.setSelectionRange){
455 element.setSelectionRange(start, stop);
459 _TextBoxMixin.selectInputText = dijit.selectInputText = function(/*DomNode*/ element, /*Number?*/ start, /*Number?*/ stop){
461 // Select text in the input element argument, from start (default 0), to stop (default end).
463 // TODO: use functions in _editor/selection.js?
464 element = dom.byId(element);
465 if(isNaN(start)){ start = 0; }
466 if(isNaN(stop)){ stop = element.value ? element.value.length : 0; }
469 _TextBoxMixin._setSelectionRange(element, start, stop);
470 }catch(e){ /* squelch random errors (esp. on IE) from unexpected focus changes or DOM nodes being hidden */ }
473 return _TextBoxMixin;