]> git.wh0rd.org - tt-rss.git/blame - lib/modalbox/modalbox.js
add dijit/dojo stuff; initial ui mockup
[tt-rss.git] / lib / modalbox / modalbox.js
CommitLineData
951906dc
AD
1//
2// ModalBox - The pop-up window thingie with AJAX, based on Prototype JS framework.
3//
4// Created by Andrew Okonetchnikov
5// Copyright 2006-2010 okonet.ru. All rights reserved.
6//
7// Licensed under MIT license.
8//
9
10if (!window.Modalbox)
11 var Modalbox = new Object();
12
13Modalbox.Methods = {
14 overrideAlert: false, // Override standard browser alert message with ModalBox
15 focusableElements: new Array,
16 currFocused: 0,
17 initialized: false,
18 active: true,
19 options: {
20 title: "ModalBox Window", // Title of the ModalBox window
21 overlayClose: true, // Close modal box by clicking on overlay
22 width: 500, // Default width in px
23 height: 90, // Default height in px
24 overlayOpacity: .65, // Default overlay opacity
25 overlayDuration: .25, // Default overlay fade in/out duration in seconds
26 slideDownDuration: .5, // Default Modalbox appear slide down effect in seconds
27 slideUpDuration: .5, // Default Modalbox hiding slide up effect in seconds
28 resizeDuration: .25, // Default resize duration seconds
29 inactiveFade: true, // Fades MB window on inactive state
30 transitions: true, // Toggles transition effects. Transitions are enabled by default
31 loadingString: "Please wait. Loading...", // Default loading string message
32 closeString: "Close window", // Default title attribute for close window link
33 closeValue: "×", // Default string for close link in the header
34 params: {},
35 method: 'get', // Default Ajax request method
36 autoFocusing: true, // Toggles auto-focusing for form elements. Disable for long text pages.
37 aspnet: false, // Should be use then using with ASP.NET costrols. Then true Modalbox window will be injected into the first form element.
38 resizeCSSID: ''
39 },
40 _options: new Object,
41
42 setOptions: function(options) {
43 Object.extend(this.options, options || {});
44 },
45
46 _init: function(options) {
47 // Setting up original options with default options
48 Object.extend(this._options, this.options);
49 this.setOptions(options);
50
51 //Creating the overlay
52 this.MBoverlay = new Element("div", { id: "MB_overlay", style: "opacity: 0" });
53
54 //Creating the modal window
55 this.MBwindowwrapper = new Element("div", {id: "MB_windowwrapper"}).update(
56 this.MBwindow = new Element("div", {id: "MB_window", style: "display: none"}).update(
57 this.MBframe = new Element("div", {id: "MB_frame"}).update(
58 this.MBheader = new Element("div", {id: "MB_header"}).update(
59 this.MBcaption = new Element("div", {id: "MB_caption"})
60 )
61 )
62 )
63 );
64
65 this.MBclose = new Element("a", {id: "MB_close", title: this.options.closeString, href: "#"}).update("<span>" + this.options.closeValue + "</span>");
66 this.MBheader.insert({'bottom':this.MBclose});
67
68 this.MBcontent = new Element("div", {id: "MB_content"}).update(
69 this.MBloading = new Element("div", {id: "MB_loading"}).update(this.options.loadingString)
70 );
71 this.MBframe.insert({'bottom':this.MBcontent});
72
73 // Inserting into DOM. If parameter set and form element have been found will inject into it. Otherwise will inject into body as topmost element.
74 // Be sure to set padding and marging to null via CSS for both body and (in case of asp.net) form elements.
75 var injectToEl = this.options.aspnet ? $(document.body).down('form') : $(document.body);
76 injectToEl.insert({'top':this.MBwindowwrapper});
77 injectToEl.insert({'top':this.MBoverlay});
78
79 var scrollOffsets = document.viewport.getScrollOffsets();
80 if (scrollOffsets[1] > 0) {
81 $('MB_window').setStyle({top:scrollOffsets[1] + 'px'});
82 }
83
84 Event.observe(window, 'scroll', function() {
85 scrollOffsets = document.viewport.getScrollOffsets();
86 $('MB_window').setStyle({top:scrollOffsets[1] + 'px'});
87 });
88
89 // Initial scrolling position of the window. To be used for remove scrolling effect during ModalBox appearing
90 this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
91 this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
92
93 //Adding event observers
94 this.hideObserver = this._hide.bindAsEventListener(this);
95 this.kbdObserver = this._kbdHandler.bindAsEventListener(this);
96 this._initObservers();
97
98 this.initialized = true; // Mark as initialized
99 },
100
101 show: function(content, options) {
102 if(!this.initialized) this._init(options); // Check for is already initialized
103
104 this.content = content;
105 this.setOptions(options);
106
107 if(this.options.title) // Updating title of the MB
108 $(this.MBcaption).update(this.options.title);
109 else { // If title isn't given, the header will not displayed
110 $(this.MBheader).hide();
111 $(this.MBcaption).hide();
112 }
113
114 if(this.MBwindow.style.display == "none") { // First modal box appearing
115 this._appear();
116 this.event("onShow"); // Passing onShow callback
117 }
118 else { // If MB already on the screen, update it
119 this._update();
120 this.event("onUpdate"); // Passing onUpdate callback
121 }
122 },
123
124 hide: function(options) { // External hide method to use from external HTML and JS
125 if(this.initialized) {
126 // Reading for options/callbacks except if event given as a pararmeter
127 if(options && typeof options.element != 'function') Object.extend(this.options, options);
128 // Passing beforeHide callback
129 this.event("beforeHide");
130 if(this.options.transitions)
131 Effect.SlideUp(this.MBwindow, { duration: this.options.slideUpDuration, transition: Effect.Transitions.sinoidal, afterFinish: this._deinit.bind(this) } );
132 else {
133 $(this.MBwindow).hide();
134 this._deinit();
135 }
136 Event.stopObserving(window, 'scroll');
137 } else throw("Modalbox is not initialized.");
138 },
139
140 _hide: function(event) { // Internal hide method to use with overlay and close link
141 event.stop(); // Stop event propaganation for link elements
142 /* Then clicked on overlay we'll check the option and in case of overlayClose == false we'll break hiding execution [Fix for #139] */
143 if(event.element().id == 'MB_overlay' && !this.options.overlayClose) return false;
144 this.hide();
145 },
146
147 alert: function(message){
148 var html = '<div class="MB_alert"><p>' + message + '</p><input type="button" onclick="Modalbox.hide()" value="OK" /></div>';
149 Modalbox.show(html, {title: 'Alert: ' + document.title, width: 300});
150 },
151
152 _appear: function() { // First appearing of MB
153 if(Prototype.Browser.IE && !navigator.appVersion.match(/\b7.0\b/)) { // Preparing IE 6 for showing modalbox
154 window.scrollTo(0,0);
155 this._prepareIE("100%", "hidden");
156 }
157 this._setWidth();
158 if(this.options.transitions) {
159 $(this.MBoverlay).setStyle({opacity: 0});
160 new Effect.Fade(this.MBoverlay, {
161 from: 0,
162 to: this.options.overlayOpacity,
163 duration: this.options.overlayDuration,
164 afterFinish: function() {
165 new Effect.SlideDown(this.MBwindow, {
166 duration: this.options.slideDownDuration,
167 transition: Effect.Transitions.sinoidal,
168 afterFinish: function(){
169 this.loadContent();
170 }.bind(this)
171 });
172 }.bind(this)
173 });
174 } else {
175 $(this.MBoverlay).setStyle({opacity: this.options.overlayOpacity});
176 $(this.MBwindow).show();
177 this.loadContent();
178 }
179 this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
180 Event.observe(window, "resize", this._setWidthAndPosition);
181 },
182
183 resize: function(byWidth, byHeight, options) { // Change size of MB without loading content
184 var oWidth = $(this.MBoverlay).getWidth();
185 var wHeight = $(this.MBwindow).getHeight();
186 var wWidth = $(this.MBwindow).getWidth();
187 var hHeight = $(this.MBheader).getHeight();
188 var cHeight = $(this.MBcontent).getHeight();
189 var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight) : (wHeight + byHeight);
190
191 var el = $(this.MBwindow);
192 var contentEl = $(this.MBcontent);
193 var windowBottomMargin = 10;
194 var windowOffset = (parseInt(el.getStyle('margin-top'), 0) + parseInt(el.getStyle('margin-bottom'), 0) + parseInt(el.getStyle('border-top-width'), 0) + parseInt(el.getStyle('border-bottom-width'), 0)) + windowBottomMargin;
195 var contentPadding = (parseInt(contentEl.getStyle('padding-top')) + parseInt(contentEl.getStyle('padding-bottom')));
196
197 if ((newHeight + windowOffset + contentPadding) > document.viewport.getHeight()) {
198 // adjust window height to account for margins and border widths
199 newHeight = document.viewport.getHeight() - windowOffset - windowBottomMargin;
200 // calculate content height including header height and padding values
201 newcHeight = newHeight - hHeight - parseInt($(this.MBframe).getStyle('padding-bottom'), 0) - parseInt($(this.MBcontent).getStyle('padding-bottom'), 0);
202 $(this.MBcontent).setStyle({height:newcHeight + 'px'});
203 }
204 else if ($(this.MBcontent).getStyle('height')) {
205 // release any MB_content height set prior to establish scrollbars in content area
206 $(this.MBcontent).setStyle({height:''});
207 }
208
209 var newWidth = wWidth + byWidth;
210 this.options.width = newWidth;
211 if(options) this.setOptions(options); // Passing callbacks
212 if(this.options.transitions && !Modalbox.animating) {
213 Modalbox.animating = true;
214 new Effect.Morph(this.MBwindow, {
215 style: "width:" + newWidth + "px; height:" + newHeight + "px;",
216 duration: this.options.resizeDuration,
217 beforeStart: function(fx){
218 fx.element.setStyle({overflow:"hidden"}); // Fix for MSIE 6 to resize correctly
219 },
220 afterFinish: function(fx) {
221 fx.element.setStyle({overflow:"visible"});
222 this.event("_afterResize"); // Passing internal callback
223 this.event("afterResize"); // Passing callback
224 Modalbox.animating = false;
225 }.bind(this)
226 });
227 } else {
228 this.MBwindow.setStyle({width: newWidth + "px", height: newHeight + "px"});
229 setTimeout(function() {
230 this.event("_afterResize"); // Passing internal callback
231 this.event("afterResize"); // Passing callback
232 }.bind(this), 1);
233 }
234
235 },
236
237 resizeToContent: function(options){
238 // Resizes the modalbox window to the actual content height.
239 // This might be useful to resize modalbox after some content modifications which were changed ccontent height.
240
241 if (typeof options == "undefined") {
242 options = new Object();
243 }
244
245 // check to see if MB_content includes any images
246 var mbimages = $('MB_content').select('img');
247 var totalimages = mbimages.length;
248 if (mbimages[0]) {
249 if (typeof options.imagesloaded == "undefined") {
250
251 var loadedImages = $A();
252 var loadedImageTotal = 0;
253 mbimages.each(function(o,idx) {
254 loadedImages[idx] = new Image();
255 loadedImages[idx].src = o.src;
256 loadedImages[idx].onload = function() {
257 loadedImageTotal++;
258 if (loadedImageTotal == totalimages) {
259 // make sure all images have been rendered by checking their height
260 var imageincomplete = false;
261 mbimages.each(function(i) {
262 if (i.height == 0) {
263 imageincomplete = true;
264 }
265 });
266 if (imageincomplete || Modalbox.animating) {
267 // some image hasn't been rendered yet, trigger resize loop until it is
268 Modalbox.resizeToContent();
269 }
270 else {
271 // trigger one final resize, but set imagesloaded option to skip inspection of images
272 options.imagesloaded = true;
273 Modalbox.resizeToContent(options);
274 }
275 }
276 }
277 })
278 }
279 }
280
281 var byHeight = this.options.height - $(this.MBwindow).getHeight();
282 if (options.resizeCSSID && $(options.resizeCSSID)) {
283 // byWidth is the amount of pixels needed to increase/decrease window to meet width of options.resizeCSSID
284 // plus a 10 pixel margin to accommodate scrollbars
285 var byWidth = $(options.resizeCSSID).getWidth() - $(this.MBwindow).getWidth() + (parseInt($(this.MBcontent).getStyle('padding-left'), 0) + parseInt($(this.MBcontent).getStyle('padding-right'), 0)) + 15;
286 }
287 else {
288 // don't change width
289 var byWidth = 0;
290 }
291 if(byHeight != 0) {
292 if(options) this.setOptions(options); // Passing callbacks
293 Modalbox.resize(byWidth, byHeight);
294 }
295 },
296
297 resizeToInclude: function(element, options){
298
299 // Resizes the modalbox window to the camulative height of element. Calculations are using CSS properties for margins and border.
300 // This method might be useful to resize modalbox before including or updating content.
301
302 var el = $(element);
303 var elHeight = el.getHeight() + parseInt(el.getStyle('margin-top'), 0) + parseInt(el.getStyle('margin-bottom'), 0) + parseInt(el.getStyle('border-top-width'), 0) + parseInt(el.getStyle('border-bottom-width'), 0);
304 if(elHeight > 0) {
305 if(options) this.setOptions(options); // Passing callbacks
306 Modalbox.resize(0, elHeight);
307 }
308 },
309
310 _update: function() { // Updating MB in case of wizards
311 $(this.MBcontent).update($(this.MBloading).update(this.options.loadingString));
312 this.loadContent();
313 },
314
315 loadContent: function () {
316 if(this.event("beforeLoad") != false) { // If callback passed false, skip loading of the content
317 if(typeof this.content == 'string') {
318 var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
319 if(htmlRegExp.test(this.content)) { // Plain HTML given as a parameter
320 this._insertContent(this.content.stripScripts(), function(){
321 this.content.extractScripts().map(function(script) {
322 return eval(script.replace("<!--", "").replace("// -->", ""));
323 }.bind(window));
324 }.bind(this));
325 } else // URL given as a parameter. We'll request it via Ajax
326 new Ajax.Request( this.content, { method: this.options.method.toLowerCase(), parameters: this.options.params,
327 onComplete: function(transport) {
328 var response = new String(transport.responseText);
329 this._insertContent(transport.responseText.stripScripts(), function(){
330 response.extractScripts().map(function(script) {
331 return eval(script.replace("<!--", "").replace("// -->", ""));
332 }.bind(window));
333 });
334 }.bind(this),
335 onException: function(instance, exception){
336 Modalbox.hide();
337 throw('Modalbox Loading Error: ' + exception);
338 }
339 });
340
341 } else if (typeof this.content == 'object') {// HTML Object is given
342 this._insertContent(this.content);
343 } else {
344 Modalbox.hide();
345 throw('Modalbox Parameters Error: Please specify correct URL or HTML element (plain HTML or object)');
346 }
347 }
348 },
349
350 _insertContent: function(content, callback){
351 $(this.MBcontent).hide().update("");
352 if(typeof content == 'string') { // Plain HTML is given
353 this.MBcontent.update(new Element("div", { style: "display: none" }).update(content)).down().show();
354 } else if (typeof content == 'object') { // HTML Object is given
355 var _htmlObj = content.cloneNode(true); // If node already a part of DOM we'll clone it
356 // If clonable element has ID attribute defined, modifying it to prevent duplicates
357 if(content.id) content.id = "MB_" + content.id;
358 /* Add prefix for IDs on all elements inside the DOM node */
359 $(content).select('*[id]').each(function(el){ el.id = "MB_" + el.id; });
360 this.MBcontent.update(_htmlObj).down('div').show();
361 if(Prototype.Browser.IE) // Toggling back visibility for hidden selects in IE
362 $$("#MB_content select").invoke('setStyle', {'visibility': ''});
363 }
364
365 // Prepare and resize modal box for content
366 if(this.options.height == this._options.height) {
367 Modalbox.resize((this.options.width - $(this.MBwindow).getWidth()), $(this.MBcontent).getHeight() - $(this.MBwindow).getHeight() + $(this.MBheader).getHeight(), {
368 afterResize: function(){
369 setTimeout(function(){ // MSIE fix
370 this._putContent(callback);
371 }.bind(this),1);
372 }.bind(this)
373 });
374 } else { // Height is defined. Creating a scrollable window
375 this._setWidth();
376 this.MBcontent.setStyle({overflow: 'auto', height: $(this.MBwindow).getHeight() - $(this.MBheader).getHeight() - 13 + 'px'});
377 setTimeout(function(){ // MSIE fix
378 this._putContent(callback);
379 }.bind(this),1);
380 }
381 },
382
383 _putContent: function(callback){
384 this.MBcontent.show();
385 this.focusableElements = this._findFocusableElements();
386 this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
387 if(callback != undefined)
388 callback(); // Executing internal JS from loaded content
389 this.event("afterLoad"); // Passing callback
390 },
391
392 activate: function(options){
393 this.setOptions(options);
394 this.active = true;
395 $(this.MBclose).observe("click", this.hideObserver);
396 if(this.options.overlayClose)
397 $(this.MBoverlay).observe("click", this.hideObserver);
398 $(this.MBclose).show();
399 if(this.options.transitions && this.options.inactiveFade)
400 new Effect.Appear(this.MBwindow, {duration: this.options.slideUpDuration});
401 },
402
403 deactivate: function(options) {
404 this.setOptions(options);
405 this.active = false;
406 $(this.MBclose).stopObserving("click", this.hideObserver);
407 if(this.options.overlayClose)
408 $(this.MBoverlay).stopObserving("click", this.hideObserver);
409 $(this.MBclose).hide();
410 if(this.options.transitions && this.options.inactiveFade)
411 new Effect.Fade(this.MBwindow, {duration: this.options.slideUpDuration, to: .75});
412 },
413
414 _initObservers: function(){
415 $(this.MBclose).observe("click", this.hideObserver);
416 if(this.options.overlayClose)
417 $(this.MBoverlay).observe("click", this.hideObserver);
418 if(Prototype.Browser.Gecko)
419 Event.observe(document, "keypress", this.kbdObserver); // Gecko is moving focus a way too fast
420 else
421 Event.observe(document, "keydown", this.kbdObserver); // All other browsers are okay with keydown
422 },
423
424 _removeObservers: function(){
425 $(this.MBclose).stopObserving("click", this.hideObserver);
426 if(this.options.overlayClose)
427 $(this.MBoverlay).stopObserving("click", this.hideObserver);
428 if(Prototype.Browser.Gecko)
429 Event.stopObserving(document, "keypress", this.kbdObserver);
430 else
431 Event.stopObserving(document, "keydown", this.kbdObserver);
432 },
433
434 _setFocus: function() {
435 /* Setting focus to the first 'focusable' element which is one with tabindex = 1 or the first in the form loaded. */
436 if(this.focusableElements.length > 0 && this.options.autoFocusing == true) {
437 var firstEl = this.focusableElements.find(function (el){
438 return el.tabIndex == 1;
439 }) || this.focusableElements.first();
440 this.currFocused = this.focusableElements.toArray().indexOf(firstEl);
441 firstEl.focus(); // Focus on first focusable element except close button
442 } else if($(this.MBclose).visible())
443 $(this.MBclose).focus(); // If no focusable elements exist focus on close button
444 },
445
446 _findFocusableElements: function(){ // Collect form elements or links from MB content
447 this.MBcontent.select('input:not([type~=hidden]), select, textarea, button, a[href]').invoke('addClassName', 'MB_focusable');
448 return this.MBcontent.select('.MB_focusable');
449 },
450
451 _kbdHandler: function(event) {
452 var node = event.element();
453 switch(event.keyCode) {
454 case Event.KEY_TAB:
455 event.stop();
456
457 /* Switching currFocused to the element which was focused by mouse instead of TAB-key. Fix for #134 */
458 if(node != this.focusableElements[this.currFocused])
459 this.currFocused = this.focusableElements.toArray().indexOf(node);
460
461 if(!event.shiftKey) { //Focusing in direct order
462 if(this.currFocused == this.focusableElements.length - 1) {
463 this.focusableElements.first().focus();
464 this.currFocused = 0;
465 } else {
466 this.currFocused++;
467 this.focusableElements[this.currFocused].focus();
468 }
469 } else { // Shift key is pressed. Focusing in reverse order
470 if(this.currFocused == 0) {
471 this.focusableElements.last().focus();
472 this.currFocused = this.focusableElements.length - 1;
473 } else {
474 this.currFocused--;
475 this.focusableElements[this.currFocused].focus();
476 }
477 }
478 break;
479 case Event.KEY_ESC:
480 if(this.active) this._hide(event);
481 break;
482 case 32:
483 this._preventScroll(event);
484 break;
485 case 0: // For Gecko browsers compatibility
486 if(event.which == 32) this._preventScroll(event);
487 break;
488 case Event.KEY_UP:
489 case Event.KEY_DOWN:
490 case Event.KEY_PAGEDOWN:
491 case Event.KEY_PAGEUP:
492 case Event.KEY_HOME:
493 case Event.KEY_END:
494 // Safari operates in slightly different way. This realization is still buggy in Safari.
495 if(Prototype.Browser.WebKit && !["textarea", "select"].include(node.tagName.toLowerCase()))
496 event.stop();
497 else if( (node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a") )
498 event.stop();
499 break;
500 }
501 },
502
503 _preventScroll: function(event) { // Disabling scrolling by "space" key
504 if(!["input", "textarea", "select", "button"].include(event.element().tagName.toLowerCase()))
505 event.stop();
506 },
507
508 _deinit: function()
509 {
510 this._removeObservers();
511 Event.stopObserving(window, "resize", this._setWidthAndPosition );
512 if(this.options.transitions) {
513 Effect.toggle(this.MBoverlay, 'appear', {duration: this.options.overlayDuration, afterFinish: this._removeElements.bind(this) });
514 } else {
515 this.MBoverlay.hide();
516 this._removeElements();
517 }
518 $(this.MBcontent).setStyle({overflow: '', height: ''});
519 },
520
521 _removeElements: function () {
522 $(this.MBoverlay).remove();
523 $(this.MBwindow).remove();
524 if(Prototype.Browser.IE && !navigator.appVersion.match(/\b7.0\b/)) {
525 this._prepareIE("", ""); // If set to auto MSIE will show horizontal scrolling
526 window.scrollTo(this.initScrollX, this.initScrollY);
527 }
528
529 /* Replacing prefixes 'MB_' in IDs for the original content */
530 if(typeof this.content == 'object') {
531 if(this.content.id && this.content.id.match(/MB_/)) {
532 this.content.id = this.content.id.replace(/MB_/, "");
533 }
534 this.content.select('*[id]').each(function(el){ el.id = el.id.replace(/MB_/, ""); });
535 }
536 /* Initialized will be set to false */
537 this.initialized = false;
538 this.event("afterHide"); // Passing afterHide callback
539 this.setOptions(this._options); //Settings options object into intial state
540 },
541
542 _setWidth: function () { //Set size
543 $(this.MBwindow).setStyle({width: this.options.width + "px", height: this.options.height + "px"});
544 },
545
546 _setWidthAndPosition: function () {
547 $(this.MBwindow).setStyle({width: this.options.width + "px"});
548 },
549
550 _getScrollTop: function () { //From: http://www.quirksmode.org/js/doctypes.html
551 var theTop;
552 if (document.documentElement && document.documentElement.scrollTop)
553 theTop = document.documentElement.scrollTop;
554 else if (document.body)
555 theTop = document.body.scrollTop;
556 return theTop;
557 },
558 _prepareIE: function(height, overflow){
559 $$('html, body').invoke('setStyle', {width: height, height: height, overflow: overflow}); // IE requires width and height set to 100% and overflow hidden
560 $$("select").invoke('setStyle', {'visibility': overflow}); // Toggle visibility for all selects in the common document
561 },
562 event: function(eventName) {
563 if(this.options[eventName]) {
564 var returnValue = this.options[eventName](); // Executing callback
565 this.options[eventName] = null; // Removing callback after execution
566 if(returnValue != undefined)
567 return returnValue;
568 else
569 return true;
570 }
571 return true;
572 }
573};
574
575Object.extend(Modalbox, Modalbox.Methods);
576
577if(Modalbox.overrideAlert) window.alert = Modalbox.alert;