Roo/bootstrap/PhoneInput.js
[roojs1] / Roo / bootstrap / PhoneInput.js
1 /**
2 *    This script refer to:
3 *    Title: International Telephone Input
4 *    Author: Jack O'Connor
5 *    Code version:  v12.1.12
6 *    Availability: https://github.com/jackocnr/intl-tel-input.git
7 **/
8
9 /**
10  * @class Roo.bootstrap.PhoneInput
11  * @extends Roo.bootstrap.TriggerField
12  * An input with International dial-code selection
13  
14  * @cfg {String} defaultDialCode default '+852'
15  * @cfg {Array} preferedCountries default []
16   
17  * @constructor
18  * Create a new PhoneInput.
19  * @param {Object} config Configuration options
20  */
21
22 Roo.bootstrap.PhoneInput = function(config) {
23     Roo.bootstrap.PhoneInput.superclass.constructor.call(this, config);
24 };
25
26 Roo.extend(Roo.bootstrap.PhoneInput, Roo.bootstrap.TriggerField, {
27         
28         triggerList : true,
29         
30         listWidth: undefined,
31         
32         selectedClass: 'active',
33         
34         invalidClass : "has-warning",
35         
36         validClass: 'has-success',
37         
38         allowed: '0123456789+',
39         
40         defaultDialCode: '+852',
41         
42         preferedCountries: false,
43         
44         //white list / black list for countries?
45         
46         getAutoCreate : function()
47         {
48             var data = Roo.bootstrap.PhoneInputData();
49             var align = this.labelAlign || this.parentLabelAlign();
50             var id = Roo.id();
51             
52             this.allCountries = [];
53             this.dialCodeMapping = [];
54             
55             for (var i = 0; i < data.length; i++) {
56               var c = data[i];
57               this.allCountries[i] = {
58                 name: c[0],
59                 iso2: c[1],
60                 dialCode: c[2],
61                 priority: c[3] || 0,
62                 areaCodes: c[4] || null
63               };
64               this.dialCodeMapping[c[2]] = {
65                   name: c[0],
66                   iso2: c[1],
67                   priority: c[3] || 0,
68                   areaCodes: c[4] || null
69               };
70             }
71             
72             var cfg = {
73                 cls: 'form-group',
74                 cn: []
75             };
76             
77             var input =  {
78                 tag: 'input',
79                 id : id,
80                 cls : 'form-control tel-input',
81                 autocomplete: 'new-password'
82             };
83             
84             var hiddenInput = {
85                 tag: 'input',
86                 type: 'hidden',
87                 cls: 'hidden-tel-input'
88             };
89             
90             if (this.name) {
91                 hiddenInput.name = this.name;
92             }
93             
94             if (this.disabled) {
95                 input.disabled = true;
96             }
97             
98             var flag_container = {
99                 tag: 'div',
100                 cls: 'flag-box',
101                 cn: [
102                     {
103                         tag: 'div',
104                         cls: 'flag'
105                     },
106                     {
107                         tag: 'div',
108                         cls: 'caret'
109                     }
110                 ]
111             };
112             
113             var box = {
114                 tag: 'div',
115                 cls: this.hasFeedback ? 'has-feedback' : '',
116                 cn: [
117                     hiddenInput,
118                     input,
119                     {
120                         tag: 'input',
121                         cls: 'dial-code-holder',
122                         disabled: true
123                     }
124                 ]
125             };
126             
127             var container = {
128                 cls: 'roo-select2-container input-group',
129                 cn: [
130                     flag_container,
131                     box
132                 ]
133             };
134             
135             if (this.fieldLabel.length) {
136                 var indicator = {
137                     tag: 'i',
138                     tooltip: 'This field is required'
139                 };
140                 
141                 var label = {
142                     tag: 'label',
143                     'for':  id,
144                     cls: 'control-label',
145                     cn: []
146                 };
147                 
148                 var label_text = {
149                     tag: 'span',
150                     html: this.fieldLabel
151                 };
152                 
153                 indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star left-indicator';
154                 label.cn = [
155                     indicator,
156                     label_text
157                 ];
158                 
159                 if(this.indicatorpos == 'right') {
160                     indicator.cls = 'roo-required-indicator text-danger fa fa-lg fa-star right-indicator';
161                     label.cn = [
162                         label_text,
163                         indicator
164                     ];
165                 }
166                 
167                 if(align == 'left') {
168                     container = {
169                         tag: 'div',
170                         cn: [
171                             container
172                         ]
173                     };
174                     
175                     if(this.labelWidth > 12){
176                         label.style = "width: " + this.labelWidth + 'px';
177                     }
178                     if(this.labelWidth < 13 && this.labelmd == 0){
179                         this.labelmd = this.labelWidth;
180                     }
181                     if(this.labellg > 0){
182                         label.cls += ' col-lg-' + this.labellg;
183                         input.cls += ' col-lg-' + (12 - this.labellg);
184                     }
185                     if(this.labelmd > 0){
186                         label.cls += ' col-md-' + this.labelmd;
187                         container.cls += ' col-md-' + (12 - this.labelmd);
188                     }
189                     if(this.labelsm > 0){
190                         label.cls += ' col-sm-' + this.labelsm;
191                         container.cls += ' col-sm-' + (12 - this.labelsm);
192                     }
193                     if(this.labelxs > 0){
194                         label.cls += ' col-xs-' + this.labelxs;
195                         container.cls += ' col-xs-' + (12 - this.labelxs);
196                     }
197                 }
198             }
199             
200             cfg.cn = [
201                 label,
202                 container
203             ];
204             
205             var settings = this;
206             
207             ['xs','sm','md','lg'].map(function(size){
208                 if (settings[size]) {
209                     cfg.cls += ' col-' + size + '-' + settings[size];
210                 }
211             });
212             
213             this.store = new Roo.data.Store({
214                 proxy : new Roo.data.MemoryProxy({}),
215                 reader : new Roo.data.JsonReader({
216                     fields : [
217                         {
218                             'name' : 'name',
219                             'type' : 'string'
220                         },
221                         {
222                             'name' : 'iso2',
223                             'type' : 'string'
224                         },
225                         {
226                             'name' : 'dialCode',
227                             'type' : 'string'
228                         },
229                         {
230                             'name' : 'priority',
231                             'type' : 'string'
232                         },
233                         {
234                             'name' : 'areaCodes',
235                             'type' : 'string'
236                         }
237                     ]
238                 })
239             });
240             
241             if(!this.preferedCountries) {
242                 this.preferedCountries = [
243                     'hk',
244                     'gb',
245                     'us'
246                 ];
247             }
248             
249             var p = this.preferedCountries.reverse();
250             
251             if(p) {
252                 for (var i = 0; i < p.length; i++) {
253                     for (var j = 0; j < this.allCountries.length; j++) {
254                         if(this.allCountries[j].iso2 == p[i]) {
255                             var t = this.allCountries[j];
256                             this.allCountries.splice(j,1);
257                             this.allCountries.unshift(t);
258                         }
259                     } 
260                 }
261             }
262             
263             this.store.proxy.data = {
264                 success: true,
265                 data: this.allCountries
266             };
267             
268             return cfg;
269         },
270         
271         initEvents : function()
272         {
273             this.createList();
274             Roo.bootstrap.PhoneInput.superclass.initEvents.call(this);
275             
276             this.indicator = this.indicatorEl();
277             this.flag = this.flagEl();
278             this.dialCodeHolder = this.dialCodeHolderEl();
279             
280             this.trigger = this.el.select('div.flag-box',true).first();
281             this.trigger.on("click", this.onTriggerClick, this, {preventDefault:true});
282             
283             var _this = this;
284             
285             (function(){
286                 var lw = _this.listWidth || Math.max(_this.inputEl().getWidth(), _this.minListWidth);
287                 _this.list.setWidth(lw);
288             }).defer(100);
289             
290             this.list.on('mouseover', this.onViewOver, this);
291             this.list.on('mousemove', this.onViewMove, this);
292             //this.list.on('scroll', this.onViewScroll, this);
293             // this.inputEl().on("keyup", this.onKeyUp, this);
294             this.inputEl().on("keypress", this.onKeyPress, this);
295             
296             this.tpl = '<li><a href="#"><div class="flag {iso2}"></div>{name} <span class="dial-code">+{dialCode}</span></a></li>';
297
298             this.view = new Roo.View(this.list, this.tpl, {
299                 singleSelect:true, store: this.store, selectedClass: this.selectedClass
300             });
301             
302             this.view.on('click', this.onViewClick, this);
303             this.setValue(this.defaultDialCode);
304         },
305         
306         onTriggerClick : function(e)
307         {
308             Roo.log('trigger click');
309             if(this.disabled || !this.triggerList){
310                 return;
311             }
312             
313             if(this.isExpanded()){
314                 this.collapse();
315                 this.hasFocus = false;
316             }else {
317                 this.store.load({});
318                 this.hasFocus = true;
319                 this.expand();
320             }
321         },
322         
323         isExpanded : function()
324         {
325             return this.list.isVisible();
326         },
327         
328         collapse : function()
329         {
330             if(!this.isExpanded()){
331                 return;
332             }
333             this.list.hide();
334             Roo.get(document).un('mousedown', this.collapseIf, this);
335             Roo.get(document).un('mousewheel', this.collapseIf, this);
336             this.fireEvent('collapse', this);
337             this.validate();
338         },
339         
340         expand : function()
341         {
342             Roo.log('expand');
343
344             if(this.isExpanded() || !this.hasFocus){
345                 return;
346             }
347             
348             var lw = this.listWidth || Math.max(this.inputEl().getWidth(), this.minListWidth);
349             this.list.setWidth(lw);
350             
351             this.list.show();
352             this.restrictHeight();
353             
354             Roo.get(document).on('mousedown', this.collapseIf, this);
355             Roo.get(document).on('mousewheel', this.collapseIf, this);
356             
357             this.fireEvent('expand', this);
358         },
359         
360         restrictHeight : function()
361         {
362             this.list.alignTo(this.inputEl(), this.listAlign);
363             this.list.alignTo(this.inputEl(), this.listAlign);
364         },
365         
366         onViewOver : function(e, t)
367         {
368             if(this.inKeyMode){
369                 return;
370             }
371             var item = this.view.findItemFromChild(t);
372             
373             if(item){
374                 var index = this.view.indexOf(item);
375                 this.select(index, false);
376             }
377         },
378
379         // private
380         onViewClick : function(view, doFocus, el, e)
381         {
382             var index = this.view.getSelectedIndexes()[0];
383             
384             var r = this.store.getAt(index);
385             
386             if(r){
387                 this.onSelect(r, index);
388             }
389             if(doFocus !== false && !this.blockFocus){
390                 this.inputEl().focus();
391             }
392         },
393         
394         onViewMove : function(e, t)
395         {
396             this.inKeyMode = false;
397         },
398         
399         select : function(index, scrollIntoView)
400         {
401             this.selectedIndex = index;
402             this.view.select(index);
403             if(scrollIntoView !== false){
404                 var el = this.view.getNode(index);
405                 if(el){
406                     this.list.scrollChildIntoView(el, false);
407                 }
408             }
409         },
410         
411         createList : function()
412         {
413             this.list = Roo.get(document.body).createChild({
414                 tag: 'ul',
415                 cls: 'typeahead typeahead-long dropdown-menu tel-list',
416                 style: 'display:none'
417             });
418             this.list.setVisibilityMode(Roo.Element.DISPLAY).originalDisplay = 'block';;
419         },
420         
421         collapseIf : function(e)
422         {
423             var in_combo  = e.within(this.el);
424             var in_list =  e.within(this.list);
425             var is_list = (Roo.get(e.getTarget()).id == this.list.id) ? true : false;
426             
427             if (in_combo || in_list || is_list) {
428                 return;
429             }
430             this.collapse();
431         },
432         
433         onSelect : function(record, index)
434         {
435             if(this.fireEvent('beforeselect', this, record, index) !== false){
436                 
437                 this.setFlagClass(record.data.iso2);
438                 this.setDialCode(record.data.dialCode);
439                 this.hasFocus = false;
440                 this.collapse();
441                 this.fireEvent('select', this, record, index);
442             }
443         },
444         
445         flagEl : function()
446         {
447             var flag = this.el.select('div.flag',true).first();
448             if(!flag){
449                 return false;
450             }
451             return flag;
452         },
453         
454         dialCodeHolderEl : function()
455         {
456             var d = this.el.select('input.dial-code-holder',true).first();
457             if(!d){
458                 return false;
459             }
460             return d;
461         },
462         
463         setDialCode : function(v)
464         {
465             this.dialCodeHolder.dom.value = '+'+v;
466         },
467         
468         setFlagClass : function(n)
469         {
470             this.flag.dom.className = 'flag '+n;
471         },
472         
473         getValue : function()
474         {
475             var v = this.inputEl().getValue();
476             if(this.dialCodeHolder) {
477                 v = this.dialCodeHolder.dom.value+this.inputEl().getValue();
478             }
479             return v;
480         },
481         
482         setValue : function(v)
483         {
484             var d = this.getDialCode(v);
485             
486             //invalid dial code
487             if(v.length == 0 || !d || d.length == 0) {
488                 if(this.rendered){
489                     this.inputEl().dom.value = (v === null || v === undefined ? '' : v);
490                     this.hiddenEl().dom.value = (v === null || v === undefined ? '' : v);
491                 }
492                 return;
493             }
494             
495             //valid dial code
496             this.setFlagClass(this.dialCodeMapping[d].iso2);
497             this.setDialCode(d);
498             this.inputEl().dom.value = v.replace('+'+d,'');
499             this.hiddenEl().dom.value = this.getValue();
500             
501             this.validate();
502         },
503         
504         getDialCode : function(v = '')
505         {
506             if (v.length == 0) {
507                 return this.dialCodeHolder.dom.value;
508             }
509             
510             var dialCode = "";
511             if (v.charAt(0) != "+") {
512                 return false;
513             }
514             var numericChars = "";
515             for (var i = 1; i < v.length; i++) {
516               var c = v.charAt(i);
517               if (!isNaN(c)) {
518                 numericChars += c;
519                 if (this.dialCodeMapping[numericChars]) {
520                   dialCode = v.substr(1, i);
521                 }
522                 if (numericChars.length == 4) {
523                   break;
524                 }
525               }
526             }
527             return dialCode;
528         },
529         
530         reset : function()
531         {
532             this.setValue(this.defaultDialCode);
533             this.validate();
534         },
535         
536         hiddenEl : function()
537         {
538             return this.el.select('input.hidden-tel-input',true).first();
539         },
540         
541         onKeyUp : function(e)
542         {
543             Roo.log(e.getKey());
544             this.setValue(this.getValue());
545         },
546         
547         onKeyPress : function(e){
548             
549             var k = e.getKey();
550             
551             var c = e.getCharCode();
552             
553             if(
554                     (String.fromCharCode(c) == '.' || String.fromCharCode(c) == '-') &&
555                     allowed.indexOf(String.fromCharCode(c)) === -1
556             ){
557                 e.stopEvent();
558                 return;
559             }
560             
561             if(!Roo.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
562                 return;
563             }
564             
565             if(allowed.indexOf(String.fromCharCode(c)) === -1){
566                 e.stopEvent();
567             }
568         }
569         
570 });