243b5485d3f0c83a85d4290b2719005f56dd4e61
[roojs1] / Roo / bootstrap / MessageBox.js
1 /*
2  * - LGPL
3  *
4  * messagebox - can be used as a replace
5  * 
6  */
7 /**
8  * @class Roo.MessageBox
9  * Utility class for generating different styles of message boxes.  The alias Roo.Msg can also be used.
10  * Example usage:
11  *<pre><code>
12 // Basic alert:
13 Roo.Msg.alert('Status', 'Changes saved successfully.');
14
15 // Prompt for user data:
16 Roo.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
17     if (btn == 'ok'){
18         // process text value...
19     }
20 });
21
22 // Show a dialog using config options:
23 Roo.Msg.show({
24    title:'Save Changes?',
25    msg: 'Your are closing a tab that has unsaved changes. Would you like to save your changes?',
26    buttons: Roo.Msg.YESNOCANCEL,
27    fn: processResult,
28    animEl: 'elId'
29 });
30 </code></pre>
31  * @singleton
32  */
33 Roo.bootstrap.MessageBox = function(){
34     var dlg, opt, mask, waitTimer;
35     var bodyEl, msgEl, textboxEl, textareaEl, progressEl, pp;
36     var buttons, activeTextEl, bwidth;
37
38     
39     // private
40     var handleButton = function(button){
41         dlg.hide();
42         Roo.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value], 1);
43     };
44
45     // private
46     var handleHide = function(){
47         if(opt && opt.cls){
48             dlg.el.removeClass(opt.cls);
49         }
50         //if(waitTimer){
51         //    Roo.TaskMgr.stop(waitTimer);
52         //    waitTimer = null;
53         //}
54     };
55
56     // private
57     var updateButtons = function(b){
58         var width = 0;
59         if(!b){
60             buttons["ok"].hide();
61             buttons["cancel"].hide();
62             buttons["yes"].hide();
63             buttons["no"].hide();
64             //dlg.footer.dom.style.display = 'none';
65             return width;
66         }
67         dlg.footerEl.dom.style.display = '';
68         for(var k in buttons){
69             if(typeof buttons[k] != "function"){
70                 if(b[k]){
71                     buttons[k].show();
72                     buttons[k].setText(typeof b[k] == "string" ? b[k] : Roo.bootstrap.MessageBox.buttonText[k]);
73                     width += buttons[k].el.getWidth()+15;
74                 }else{
75                     buttons[k].hide();
76                 }
77             }
78         }
79         return width;
80     };
81
82     // private
83     var handleEsc = function(d, k, e){
84         if(opt && opt.closable !== false){
85             dlg.hide();
86         }
87         if(e){
88             e.stopEvent();
89         }
90     };
91
92     return {
93         /**
94          * Returns a reference to the underlying {@link Roo.BasicDialog} element
95          * @return {Roo.BasicDialog} The BasicDialog element
96          */
97         getDialog : function(){
98            if(!dlg){
99                 dlg = new Roo.bootstrap.Modal( {
100                     //draggable: true,
101                     //resizable:false,
102                     //constraintoviewport:false,
103                     //fixedcenter:true,
104                     //collapsible : false,
105                     //shim:true,
106                     //modal: true,
107                 //    width: 'auto',
108                   //  height:100,
109                     //buttonAlign:"center",
110                     closeClick : function(){
111                         if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
112                             handleButton("no");
113                         }else{
114                             handleButton("cancel");
115                         }
116                     }
117                 });
118                 dlg.render();
119                 dlg.on("hide", handleHide);
120                 mask = dlg.mask;
121                 //dlg.addKeyListener(27, handleEsc);
122                 buttons = {};
123                 this.buttons = buttons;
124                 var bt = this.buttonText;
125                 buttons["ok"] = dlg.addButton(bt["ok"], handleButton.createCallback("ok"));
126                 buttons["yes"] = dlg.addButton(bt["yes"], handleButton.createCallback("yes"));
127                 buttons["no"] = dlg.addButton(bt["no"], handleButton.createCallback("no"));
128                 buttons["cancel"] = dlg.addButton(bt["cancel"], handleButton.createCallback("cancel"));
129                 //Roo.log(buttons);
130                 bodyEl = dlg.bodyEl.createChild({
131
132                     html:'<span class="roo-mb-text"></span><br /><input type="text" class="roo-mb-input" />' +
133                         '<textarea class="roo-mb-textarea"></textarea>' +
134                         '<div class="roo-mb-progress-wrap"><div class="roo-mb-progress"><div class="roo-mb-progress-bar">&#160;</div></div></div>'
135                 });
136                 msgEl = bodyEl.dom.firstChild;
137                 textboxEl = Roo.get(bodyEl.dom.childNodes[2]);
138                 textboxEl.enableDisplayMode();
139                 textboxEl.addKeyListener([10,13], function(){
140                     if(dlg.isVisible() && opt && opt.buttons){
141                         if(opt.buttons.ok){
142                             handleButton("ok");
143                         }else if(opt.buttons.yes){
144                             handleButton("yes");
145                         }
146                     }
147                 });
148                 textareaEl = Roo.get(bodyEl.dom.childNodes[3]);
149                 textareaEl.enableDisplayMode();
150                 progressEl = Roo.get(bodyEl.dom.childNodes[4]);
151                 progressEl.enableDisplayMode();
152                 
153                 // This is supposed to be the progessElement.. but I think it's controlling the height of everything..
154                 var pf = progressEl.dom.firstChild;
155                 if (pf) {
156                     pp = Roo.get(pf.firstChild);
157                     pp.setHeight(pf.offsetHeight);
158                 }
159                 
160             }
161             return dlg;
162         },
163
164         /**
165          * Updates the message box body text
166          * @param {String} text (optional) Replaces the message box element's innerHTML with the specified string (defaults to
167          * the XHTML-compliant non-breaking space character '&amp;#160;')
168          * @return {Roo.MessageBox} This message box
169          */
170         updateText : function(text)
171         {
172             if(!dlg.isVisible() && !opt.width){
173                 dlg.dialogEl.setStyle({ 'max-width' : this.maxWidth});
174                 // dlg.resizeTo(this.maxWidth, 100); // forcing the height breaks long alerts()
175             }
176             msgEl.innerHTML = text || '&#160;';
177       
178             var cw =  Math.max(msgEl.offsetWidth, msgEl.parentNode.scrollWidth);
179             //Roo.log("guesed size: " + JSON.stringify([cw,msgEl.offsetWidth, msgEl.parentNode.scrollWidth]));
180             var w = Math.max(
181                     Math.min(opt.width || cw , this.maxWidth), 
182                     Math.max(opt.minWidth || this.minWidth, bwidth)
183             );
184             if(opt.prompt){
185                 activeTextEl.setWidth(w);
186             }
187             if(dlg.isVisible()){
188                 dlg.fixedcenter = false;
189             }
190             // to big, make it scroll. = But as usual stupid IE does not support
191             // !important..
192             
193             if ( bodyEl.getHeight() > (Roo.lib.Dom.getViewHeight() - 100)) {
194                 bodyEl.setHeight ( Roo.lib.Dom.getViewHeight() - 100 );
195                 bodyEl.dom.style.overflowY = 'auto' + ( Roo.isIE ? '' : ' !important');
196             } else {
197                 bodyEl.dom.style.height = '';
198                 bodyEl.dom.style.overflowY = '';
199             }
200             if (cw > w) {
201                 bodyEl.dom.style.get = 'auto' + ( Roo.isIE ? '' : ' !important');
202             } else {
203                 bodyEl.dom.style.overflowX = '';
204             }
205             
206             dlg.setContentSize(w, bodyEl.getHeight());
207             if(dlg.isVisible()){
208                 dlg.fixedcenter = true;
209             }
210             return this;
211         },
212
213         /**
214          * Updates a progress-style message box's text and progress bar.  Only relevant on message boxes
215          * initiated via {@link Roo.MessageBox#progress} or by calling {@link Roo.MessageBox#show} with progress: true.
216          * @param {Number} value Any number between 0 and 1 (e.g., .5)
217          * @param {String} text (optional) If defined, the message box's body text is replaced with the specified string (defaults to undefined)
218          * @return {Roo.MessageBox} This message box
219          */
220         updateProgress : function(value, text){
221             if(text){
222                 this.updateText(text);
223             }
224             
225             if (pp) { // weird bug on my firefox - for some reason this is not defined
226                 pp.setWidth(Math.floor(value*progressEl.dom.firstChild.offsetWidth));
227                 pp.setHeight(Math.floor(progressEl.dom.firstChild.offsetHeight));
228             }
229             return this;
230         },        
231
232         /**
233          * Returns true if the message box is currently displayed
234          * @return {Boolean} True if the message box is visible, else false
235          */
236         isVisible : function(){
237             return dlg && dlg.isVisible();  
238         },
239
240         /**
241          * Hides the message box if it is displayed
242          */
243         hide : function(){
244             if(this.isVisible()){
245                 dlg.hide();
246             }  
247         },
248
249         /**
250          * Displays a new message box, or reinitializes an existing message box, based on the config options
251          * passed in. All functions (e.g. prompt, alert, etc) on MessageBox call this function internally.
252          * The following config object properties are supported:
253          * <pre>
254 Property    Type             Description
255 ----------  ---------------  ------------------------------------------------------------------------------------
256 animEl            String/Element   An id or Element from which the message box should animate as it opens and
257                                    closes (defaults to undefined)
258 buttons           Object/Boolean   A button config object (e.g., Roo.MessageBox.OKCANCEL or {ok:'Foo',
259                                    cancel:'Bar'}), or false to not show any buttons (defaults to false)
260 closable          Boolean          False to hide the top-right close button (defaults to true).  Note that
261                                    progress and wait dialogs will ignore this property and always hide the
262                                    close button as they can only be closed programmatically.
263 cls               String           A custom CSS class to apply to the message box element
264 defaultTextHeight Number           The default height in pixels of the message box's multiline textarea if
265                                    displayed (defaults to 75)
266 fn                Function         A callback function to execute after closing the dialog.  The arguments to the
267                                    function will be btn (the name of the button that was clicked, if applicable,
268                                    e.g. "ok"), and text (the value of the active text field, if applicable).
269                                    Progress and wait dialogs will ignore this option since they do not respond to
270                                    user actions and can only be closed programmatically, so any required function
271                                    should be called by the same code after it closes the dialog.
272 icon              String           A CSS class that provides a background image to be used as an icon for
273                                    the dialog (e.g., Roo.MessageBox.WARNING or 'custom-class', defaults to '')
274 maxWidth          Number           The maximum width in pixels of the message box (defaults to 600)
275 minWidth          Number           The minimum width in pixels of the message box (defaults to 100)
276 modal             Boolean          False to allow user interaction with the page while the message box is
277                                    displayed (defaults to true)
278 msg               String           A string that will replace the existing message box body text (defaults
279                                    to the XHTML-compliant non-breaking space character '&#160;')
280 multiline         Boolean          True to prompt the user to enter multi-line text (defaults to false)
281 progress          Boolean          True to display a progress bar (defaults to false)
282 progressText      String           The text to display inside the progress bar if progress = true (defaults to '')
283 prompt            Boolean          True to prompt the user to enter single-line text (defaults to false)
284 proxyDrag         Boolean          True to display a lightweight proxy while dragging (defaults to false)
285 title             String           The title text
286 value             String           The string value to set into the active textbox element if displayed
287 wait              Boolean          True to display a progress bar (defaults to false)
288 width             Number           The width of the dialog in pixels
289 </pre>
290          *
291          * Example usage:
292          * <pre><code>
293 Roo.Msg.show({
294    title: 'Address',
295    msg: 'Please enter your address:',
296    width: 300,
297    buttons: Roo.MessageBox.OKCANCEL,
298    multiline: true,
299    fn: saveAddress,
300    animEl: 'addAddressBtn'
301 });
302 </code></pre>
303          * @param {Object} config Configuration options
304          * @return {Roo.MessageBox} This message box
305          */
306         show : function(options)
307         {
308             
309             // this causes nightmares if you show one dialog after another
310             // especially on callbacks..
311              
312             if(this.isVisible()){
313                 
314                 this.hide();
315                 Roo.log("[Roo.Messagebox] Show called while message displayed:" );
316                 Roo.log("Old Dialog Message:" +  msgEl.innerHTML );
317                 Roo.log("New Dialog Message:" +  options.msg )
318                 //this.alert("ERROR", "Multiple dialogs where displayed at the same time");
319                 //throw "Roo.MessageBox ERROR : Multiple dialogs where displayed at the same time";
320                 
321             }
322             var d = this.getDialog();
323             opt = options;
324             d.setTitle(opt.title || "&#160;");
325             d.closeEl.setDisplayed(opt.closable !== false);
326             activeTextEl = textboxEl;
327             opt.prompt = opt.prompt || (opt.multiline ? true : false);
328             if(opt.prompt){
329                 if(opt.multiline){
330                     textboxEl.hide();
331                     textareaEl.show();
332                     textareaEl.setHeight(typeof opt.multiline == "number" ?
333                         opt.multiline : this.defaultTextHeight);
334                     activeTextEl = textareaEl;
335                 }else{
336                     textboxEl.show();
337                     textareaEl.hide();
338                 }
339             }else{
340                 textboxEl.hide();
341                 textareaEl.hide();
342             }
343             progressEl.setDisplayed(opt.progress === true);
344             this.updateProgress(0);
345             activeTextEl.dom.value = opt.value || "";
346             if(opt.prompt){
347                 dlg.setDefaultButton(activeTextEl);
348             }else{
349                 var bs = opt.buttons;
350                 var db = null;
351                 if(bs && bs.ok){
352                     db = buttons["ok"];
353                 }else if(bs && bs.yes){
354                     db = buttons["yes"];
355                 }
356                 dlg.setDefaultButton(db);
357             }
358             bwidth = updateButtons(opt.buttons);
359             this.updateText(opt.msg);
360             if(opt.cls){
361                 d.el.addClass(opt.cls);
362             }
363             d.proxyDrag = opt.proxyDrag === true;
364             d.modal = opt.modal !== false;
365             d.mask = opt.modal !== false ? mask : false;
366             if(!d.isVisible()){
367                 // force it to the end of the z-index stack so it gets a cursor in FF
368                 document.body.appendChild(dlg.el.dom);
369                 d.animateTarget = null;
370                 d.show(options.animEl);
371             }
372             return this;
373         },
374
375         /**
376          * Displays a message box with a progress bar.  This message box has no buttons and is not closeable by
377          * the user.  You are responsible for updating the progress bar as needed via {@link Roo.MessageBox#updateProgress}
378          * and closing the message box when the process is complete.
379          * @param {String} title The title bar text
380          * @param {String} msg The message box body text
381          * @return {Roo.MessageBox} This message box
382          */
383         progress : function(title, msg){
384             this.show({
385                 title : title,
386                 msg : msg,
387                 buttons: false,
388                 progress:true,
389                 closable:false,
390                 minWidth: this.minProgressWidth,
391                 modal : true
392             });
393             return this;
394         },
395
396         /**
397          * Displays a standard read-only message box with an OK button (comparable to the basic JavaScript Window.alert).
398          * If a callback function is passed it will be called after the user clicks the button, and the
399          * id of the button that was clicked will be passed as the only parameter to the callback
400          * (could also be the top-right close button).
401          * @param {String} title The title bar text
402          * @param {String} msg The message box body text
403          * @param {Function} fn (optional) The callback function invoked after the message box is closed
404          * @param {Object} scope (optional) The scope of the callback function
405          * @return {Roo.MessageBox} This message box
406          */
407         alert : function(title, msg, fn, scope)
408         {
409             this.show({
410                 title : title,
411                 msg : msg,
412                 buttons: this.OK,
413                 fn: fn,
414                 closable : false,
415                 scope : scope,
416                 modal : true
417             });
418             return this;
419         },
420
421         /**
422          * Displays a message box with an infinitely auto-updating progress bar.  This can be used to block user
423          * interaction while waiting for a long-running process to complete that does not have defined intervals.
424          * You are responsible for closing the message box when the process is complete.
425          * @param {String} msg The message box body text
426          * @param {String} title (optional) The title bar text
427          * @return {Roo.MessageBox} This message box
428          */
429         wait : function(msg, title){
430             this.show({
431                 title : title,
432                 msg : msg,
433                 buttons: false,
434                 closable:false,
435                 progress:true,
436                 modal:true,
437                 width:300,
438                 wait:true
439             });
440             waitTimer = Roo.TaskMgr.start({
441                 run: function(i){
442                     Roo.MessageBox.updateProgress(((((i+20)%20)+1)*5)*.01);
443                 },
444                 interval: 1000
445             });
446             return this;
447         },
448
449         /**
450          * Displays a confirmation message box with Yes and No buttons (comparable to JavaScript's Window.confirm).
451          * If a callback function is passed it will be called after the user clicks either button, and the id of the
452          * button that was clicked will be passed as the only parameter to the callback (could also be the top-right close button).
453          * @param {String} title The title bar text
454          * @param {String} msg The message box body text
455          * @param {Function} fn (optional) The callback function invoked after the message box is closed
456          * @param {Object} scope (optional) The scope of the callback function
457          * @return {Roo.MessageBox} This message box
458          */
459         confirm : function(title, msg, fn, scope){
460             this.show({
461                 title : title,
462                 msg : msg,
463                 buttons: this.YESNO,
464                 fn: fn,
465                 scope : scope,
466                 modal : true
467             });
468             return this;
469         },
470
471         /**
472          * Displays a message box with OK and Cancel buttons prompting the user to enter some text (comparable to
473          * JavaScript's Window.prompt).  The prompt can be a single-line or multi-line textbox.  If a callback function
474          * is passed it will be called after the user clicks either button, and the id of the button that was clicked
475          * (could also be the top-right close button) and the text that was entered will be passed as the two
476          * parameters to the callback.
477          * @param {String} title The title bar text
478          * @param {String} msg The message box body text
479          * @param {Function} fn (optional) The callback function invoked after the message box is closed
480          * @param {Object} scope (optional) The scope of the callback function
481          * @param {Boolean/Number} multiline (optional) True to create a multiline textbox using the defaultTextHeight
482          * property, or the height in pixels to create the textbox (defaults to false / single-line)
483          * @return {Roo.MessageBox} This message box
484          */
485         prompt : function(title, msg, fn, scope, multiline){
486             this.show({
487                 title : title,
488                 msg : msg,
489                 buttons: this.OKCANCEL,
490                 fn: fn,
491                 minWidth:250,
492                 scope : scope,
493                 prompt:true,
494                 multiline: multiline,
495                 modal : true
496             });
497             return this;
498         },
499
500         /**
501          * Button config that displays a single OK button
502          * @type Object
503          */
504         OK : {ok:true},
505         /**
506          * Button config that displays Yes and No buttons
507          * @type Object
508          */
509         YESNO : {yes:true, no:true},
510         /**
511          * Button config that displays OK and Cancel buttons
512          * @type Object
513          */
514         OKCANCEL : {ok:true, cancel:true},
515         /**
516          * Button config that displays Yes, No and Cancel buttons
517          * @type Object
518          */
519         YESNOCANCEL : {yes:true, no:true, cancel:true},
520
521         /**
522          * The default height in pixels of the message box's multiline textarea if displayed (defaults to 75)
523          * @type Number
524          */
525         defaultTextHeight : 75,
526         /**
527          * The maximum width in pixels of the message box (defaults to 600)
528          * @type Number
529          */
530         maxWidth : 600,
531         /**
532          * The minimum width in pixels of the message box (defaults to 100)
533          * @type Number
534          */
535         minWidth : 100,
536         /**
537          * The minimum width in pixels of the message box if it is a progress-style dialog.  This is useful
538          * for setting a different minimum width than text-only dialogs may need (defaults to 250)
539          * @type Number
540          */
541         minProgressWidth : 250,
542         /**
543          * An object containing the default button text strings that can be overriden for localized language support.
544          * Supported properties are: ok, cancel, yes and no.
545          * Customize the default text like so: Roo.MessageBox.buttonText.yes = "S?";
546          * @type Object
547          */
548         buttonText : {
549             ok : "OK",
550             cancel : "Cancel",
551             yes : "Yes",
552             no : "No"
553         }
554     };
555 }();
556
557 /**
558  * Shorthand for {@link Roo.MessageBox}
559  */
560 Roo.MessageBox = Roo.MessageBox || Roo.bootstrap.MessageBox;
561 Roo.Msg = Roo.Msg || Roo.MessageBox;