ux/Lightbox.js
[roojs1] / ux / Lightbox.js
1 /* <script type="text/javascript">
2 // -----------------------------------------------------------------------------------
3 // Roo lightbox - based on..
4 //
5 //      Lightbox v2.04
6 //      by Lokesh Dhakar - http://www.lokeshdhakar.com
7 //      Last Modification: 2/9/08
8 //
9 //      For more information, visit:
10 //      http://lokeshdhakar.com/projects/lightbox2/
11 //
12 //      Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
13 //      - Free for use in both personal and commercial projects
14 //              - Attribution requires leaving author name, author link, and the license info intact.
15 //      
16 //  Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
17 //              Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
18 //
19 // -----------------------------------------------------------------------------------
20 /*
21
22     Table of Contents
23     -----------------
24     Configuration
25
26     Lightbox Class Declaration
27     - initialize()
28     - updateImageList()
29     - start()
30     - changeImage()
31     - resizeImageContainer()
32     - showImage()
33     - updateDetails()
34     - updateNav()
35     - enableKeyboardNav()
36     - disableKeyboardNav()
37     - keyboardAction()
38     - preloadNeighborImages()
39     - end()
40     
41     Function Calls
42     - document.observe()
43    
44 */
45 Roo.namespace('Roo.ux'); 
46  
47 Roo.ux.Lightbox = function(cfg) {
48     Roo.apply(this,cfg);
49     this.initialize();
50 }
51
52 Roo.apply(Roo.ux.Lightbox.prototype,  
53 {
54     // optiosn..
55     /**
56      * @cfg fileLoadingImage {string} loading image
57      */
58     fileLoadingImage:        '/lightbox/images/loading.gif',     
59     /**
60      * @cfg fileBottomNavCloseImage {string} close image
61      */
62     fileBottomNavCloseImage: '/lightbox/images/closelabel.gif',
63     /**
64      * @cfg overlayOpacity {number} controls transparency of shadow overlay
65      */
66     overlayOpacity: 0.8,   
67     /**
68      * @cfg fileLoadingImage {boolean} toggles resizing animations
69      */
70     animate: true,          
71     /**
72      * @cfg resizeSpeed {number} controls the speed of the image 
73      * resizing animations (1=slowest and 10=fastest)
74      */
75     resizeSpeed: 9,
76     /**
77      * @cfg borderSize {number} if you adjust the padding in the CSS, 
78      * you will need to update this variable
79      */
80     borderSize: 10,
81     /**
82      * @cfg labelImage {string} When grouping images this is used to write: Image # of #.
83      * Change it for non-english localization
84      */
85         labelImage: "Image",
86         /**
87      * @cfg labelOf {string}  When grouping images this is used to write: Image # of #.
88      */
89     labelOf: "of",
90     
91     
92     
93     
94     /**
95      * List of images
96      */
97     imageArray: [],
98     
99     /**
100      * Current image.
101      * 
102      */
103      
104     activeImage: undefined,
105     
106     /**
107      * initialize() 
108      *  Constructor runs on completion of the DOM loading. Calls updateImageList and then
109      * the function inserts html at the bottom of the page which is used to display the shadow 
110      *  overlay and the image container.
111      * 
112      * 
113      */
114     initialize: function() {    
115         
116         this.updateImageList();
117         
118         // TBD this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
119         this.resizeSpeed  = Math.min(this.resizeSpeed, 10);
120         this.resizeSpeed  = Math.max(this.resizeSpeed, 1);
121         
122             this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
123             this.overlayDuration = this.animate ? 0.2 : 0;  // shadow fade in/out duration
124
125         // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
126         // If animations are turned off, it will be hidden as to prevent a flicker of a
127         // white 250 by 250 box.
128         var size = (this.animate ? 250 : 1) + 'px';
129         var dh = Roo.DomHelper;
130         this.el = dh.append(document.body, {
131                 html: 
132                //   '<div id="overlay"></div>' +
133                   '<div id="lightbox">' +
134                   '   <div id="outerImageContainer">' +
135                   '       <div id="imageContainer">' +
136                   '           <img id="lightboxImage">' +
137                   '           <div style="" id="hoverNav">' +
138                   '               <a href="#" id="prevLink"></a>' +
139                   '               <a href="#" id="nextLink"></a>' +
140                   '           </div>' +
141                   '           <div id="loading">' +
142                   '               <a href="#" id="loadingLink">&nbsp;</a>' +
143                   '           </div>' +
144                   '       </div>' +
145                   '   </div>' +
146                   '   <div id="imageDataContainer">' +
147                   '       <div id="imageData">' +
148                   '           <div id="imageDetails">' +
149                   '               <span id="caption"></span>' +
150                   '               <span id="numberDisplay"></span>' +
151                   '           </div>' +
152                   '           <div id="bottomNav">' +
153                   '               <a href="#" id="bottomNavClose">' +
154                   '                   <img src="images/close.gif">' +
155                   '               </a>' +
156                   '           </div>' +
157                   '       </div>' +
158                   '   </div>' +
159                  '</div>'
160             }, true);
161          
162          
163         
164
165
166                 //Roo.get('overlay').hide();
167         //Roo.get('overlay').on('click', this.end, this);
168                 Roo.get('lightbox').hide();
169         Roo.get('lightbox').on('click',  function(event) { 
170                 if (event.getTarget().id == 'lightbox') {
171                     this.end(); 
172                 }
173             }, this);
174             
175                 Roo.get('outerImageContainer').setStyle({ width: size, height: size });
176         
177                 Roo.get('prevLink').on('click', 
178             function(event) { 
179                 event.stopEvent(); 
180                 this.changeImage(this.activeImage - 1); 
181             }, this);
182             
183                 Roo.get('nextLink').on('click', 
184             function(event) { 
185                 event.stopEvent(); 
186                 this.changeImage(this.activeImage + 1); 
187             },this);
188             
189                 Roo.get('loadingLink').on('click', 
190             function(event) { 
191                 event.stopEvent(); 
192                 this.end(); 
193             }, this);
194             
195                 Roo.get('bottomNavClose').on('click',  
196             function(event) { 
197                 event.stopEvent(); 
198                 this.end(); 
199             }, this);
200
201         var th = this;
202         (function(){
203             var ids = 
204                 'lightbox outerImageContainer imageContainer ' + 
205                 'lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
206                 'imageDataContainer imageData imageDetails caption numberDisplay '
207                 'bottomNav bottomNavClose';   
208                 
209             Roo.each(ids.split(' '), 
210                 function(id){ 
211                     
212                     th[id] = Roo.get(id); 
213                     if (!th[id]) {
214                         return;
215                        }
216                     th[id].setVisibilityMode(Element.DISPLAY);
217                 });
218         }).defer(100);
219     },
220
221     /**
222      * updateImageList()
223      * Loops through anchor tags looking for 'lightbox' references and applies onclick
224      * events to appropriate links. You can rerun after dynamically adding images w/ajax.
225      * 
226      */
227     updateImageList: function() {   
228         this.updateImageList = Roo.emptyFn;
229         
230         Roo.each(Roo.DomQuery.select('a[rel^=lightbox]'), function(e) {
231             this.imageArray.push(Roo.get(e));
232             Roo.get(e).on('click', function(event) {
233                 event.stopEvent();
234                 this.start(e);
235             }, this);
236         }, this)
237         
238     },
239     
240     /**
241     * start()
242     *  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
243     */
244     start: function(imageLink) {
245         /*
246         // hide all the objects that cause problems..
247         $$('select', 'object', 'embed').each(
248             function(node){ 
249             node.style.visibility = 'hidden' }
250         );
251         */
252         // stretch overlay to fill page and fade in
253         //var arrayPageSize = this.getPageSize();
254         
255         if(!this._mask){
256             this._mask = Roo.DomHelper.append(document.body, {cls:"roo-el-mask"}, true);
257             this._mask.on('click', this.end, this);
258         }
259         this._mask.setDisplayed(true); // no animation..
260         
261         // ie will not expand full height automatically
262         if(Roo.isIE && !(Roo.isIE7 && Roo.isStrict) && this.getStyle('height') == 'auto'){ 
263             this._mask.setHeight( Roo.lib.Dom.getViewHeight());
264         }
265         
266         //new Effect.Appear(this.overlay,
267         //    { duration: this.overlayDuration, from: 0.0, to: this.overlayOpacity });
268
269         //this.imageArray = [];
270         var imageNum = 0;       
271
272         // let's assume the constructor sorts out the list of images..
273         /*
274         if ((imageLink.rel == 'lightbox')){
275             // if image is NOT part of a set, add single image to imageArray
276             this.imageArray.push([imageLink.href, imageLink.title]);         
277         } else {
278             // if image is part of a set..
279             this.imageArray = 
280                 $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
281                 collect(function(anchor){ return [anchor.href, anchor.title]; }).
282                 uniq();
283             
284             while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
285         }
286         */
287         var s = Roo.get(document).getScroll();
288         
289         // calculate top and left offset for the lightbox 
290         // weird.. why / 10?
291         var lightboxTop = s.top + (Roo.lib.Dom.getViewHeight() / 10);
292         var lightboxLeft = s.left
293         this.lightbox.setStyle({ 
294             top: lightboxTop + 'px', 
295             left: lightboxLeft + 'px' ,
296             zIndex : this._mask.getStyle('zIndex') * 1.1
297         })
298         this.lightbox.show();
299         
300         
301         
302         this.changeImage(imageNum);
303     },
304
305     //
306     //  changeImage()
307     //  Hide most elements and preload image in preparation for resizing image container.
308     //
309     changeImage: function(imageNum) {   
310         
311         this.activeImage = imageNum; // update global var
312
313         // hide elements during transition
314         if (this.animate) {
315             this.loading.setStyle({
316                 zIndex : this._mask.getStyle('zIndex') * 1.2
317             });
318             this.loading.show();
319             this.loading.setX( (Roo.lib.Dom.getViewWidth() / 2) - 16);
320             // center the loading?
321             
322         }
323         this.lightboxImage.hide();
324         
325         this.hoverNav.hide();
326         this.prevLink.hide();
327         this.nextLink.hide();
328                 // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
329         this.imageDataContainer.setStyle({opacity: .0001});
330         this.numberDisplay.hide();
331         
332         var imgPreloader =  Roo.DomHelper.append(document.body, { tag: 'img' } , true);
333         // once image is preloaded, resize image container
334
335
336         imgPreloader.on('load', function() {
337             this.lightboxImage.src = this.imageArray[this.activeImage].dom.href;
338             this.resizeImageContainer(imgPreloader.getWidth(), imgPreloader.getHeight());
339         }, this);
340         imgPreloader.src = this.imageArray[this.activeImage].dom.href;
341     },
342
343     //
344     //  resizeImageContainer()
345     //
346     resizeImageContainer: function(imgWidth, imgHeight) {
347
348         // make sure we have some sensible sizes..
349         imgWidth = Math.max(50, imgWidth);
350         imgHeight = Math.max(50, imgHeight);
351         
352         // get current width and height
353         var widthCurrent  = this.outerImageContainer.getWidth();
354         var heightCurrent = this.outerImageContainer.getHeight();
355         
356         //fixme need better calcs.
357         var w = window;
358         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
359         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
360         
361         ww -= 150;
362         wh -= 150;
363         // get new width and height
364         var bs =  this.borderSize * 2;
365         
366         var widthNew  =  imgWidth  + bs;
367         var heightNew =  imgHeight + bs;
368         
369         if (widthNew > ww || heightNew > wh) {
370             // bigger than window.
371             // scale here... - bit nasty..
372             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
373              //console.log(rescale);
374             imgWidth = Math.floor(imgWidth / rescale);
375             imgHeight = Math.floor(imgHeight / rescale);
376             widthNew  =  imgWidth  + bs;
377             heightNew =  imgHeight + bs;
378                     
379             
380         }
381         
382         this.lightboxImage.set( { width : imgWidth, height : imgHeight });
383         
384         
385         // scalars based on change from old to new
386         var xScale = (widthNew  / widthCurrent)  * 100;
387         var yScale = (heightNew / heightCurrent) * 100;
388
389         // calculate size difference between new and old image, and resize if necessary
390         var wDiff = widthCurrent - widthNew;
391         var hDiff = heightCurrent - heightNew;
392         
393          
394         this.outerImageContainer.animate(
395             { width: {to: widthNew}, height: {to: heightNew} },
396             duration,
397             null, // on complete
398             'easeOut', // easing
399             'run' // effect
400         
401         )        
402        
403         
404         // if new and old image are same size and no scaling transition is necessary, 
405         // do a quick pause to prevent image flicker.
406         var timeout = 0;
407         if ((hDiff == 0) && (wDiff == 0)){
408             timeout = 100;
409             if (Roo.isIE) timeout = 250;   
410         }
411
412         (function(){
413             this.prevLink.setStyle({ height: imgHeight + 'px' });
414             this.nextLink.setStyle({ height: imgHeight + 'px' });
415             this.imageDataContainer.setStyle({ width: widthNew + 'px',  width: heightNew + 'px', });
416             this.showImage();
417         }).defer(timeout / 1000, this);
418     },
419     
420     //
421     //  showImage()
422     //  Display image and begin preloading neighbors.
423     //
424     showImage: function(){
425         this.loading.hide();
426         this.loadingLink.hide();
427         var _this=  this;
428         this.lightboxImage.animate( 
429             {
430                 opacity : { from : 0.0 , to: 1.0 }
431             },
432             function(){ 
433                 _this.updateDetails(); 
434             },
435             duration
436         );
437         this.preloadNeighborImages();
438     },
439
440     //
441     //  updateDetails()
442     //  Display caption, image number, and bottom nav.
443     //
444     updateDetails: function() {
445     
446         // if caption is not null
447         if (this.imageArray[this.activeImage].dom.title  != ""){
448             this.caption.update(this.imageArray[this.activeImage].dom.title);
449             this.caption.show();
450         }
451         
452         // if image is part of set display 'Image x of x' 
453         if (this.imageArray.length > 1){
454             this.numberDisplay.update(
455                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length)
456             this.numberDisplay.show();
457         }
458         var _this = this;
459         this.imageDataContainer.animate(
460             {
461                 //slide down ?: , from: 0.0, to: 1.0 
462                 opacity :  { from : 0.0 , to: 1.0 }
463             },
464             this.resizeDuration,
465             function() {
466                         // update overlay size and update nav
467                         //var arrayPageSize = this.getPageSize();
468                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
469                         _this.updateNav();
470             }
471              
472         );
473     },
474
475     //
476     //  updateNav()
477     //  Display appropriate previous and next hover navigation.
478     //
479     updateNav: function() {
480
481         this.hoverNav.show();               
482
483         // if not first image in set, display prev image button
484         if (this.activeImage > 0) this.prevLink.show();
485
486         // if not last image in set, display next image button
487         if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();
488         
489         this.enableKeyboardNav();
490     },
491
492     //
493     //  enableKeyboardNav()
494     //
495     enableKeyboardNav: function() {
496         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
497     },
498
499     //
500     //  disableKeyboardNav()
501     //
502     disableKeyboardNav: function() {
503         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
504     },
505
506     //
507     //  keyboardAction()
508     //
509     keyboardAction: function(event) {
510         var keycode = event.keyCode;
511
512         var escapeKey;
513         if (event.DOM_VK_ESCAPE) {  // mozilla
514             escapeKey = event.DOM_VK_ESCAPE;
515         } else { // ie
516             escapeKey = 27;
517         }
518
519         var key = String.fromCharCode(keycode).toLowerCase();
520         
521         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
522             this.end();
523         } else if ((key == 'p') || (keycode == 37)){ // display previous image
524             if (this.activeImage != 0){
525                 this.disableKeyboardNav();
526                 this.changeImage(this.activeImage - 1);
527             }
528         } else if ((key == 'n') || (keycode == 39)){ // display next image
529             if (this.activeImage != (this.imageArray.length - 1)){
530                 this.disableKeyboardNav();
531                 this.changeImage(this.activeImage + 1);
532             }
533         }
534     },
535
536     //
537     //  preloadNeighborImages()
538     //  Preload previous and next images.
539     //
540     preloadNeighborImages: function(){
541         var preloadNextImage, preloadPrevImage;
542         if (this.imageArray.length > this.activeImage + 1){
543             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
544             preloadNextImage.src = this.imageArray[this.activeImage + 1].dom.href;
545         }
546         if (this.activeImage > 0){
547             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
548             preloadPrevImage.src = this.imageArray[this.activeImage - 1].dom.href;
549         }
550     
551     },
552
553     //
554     //  end()
555     //
556     end: function() {
557         this.disableKeyboardNav();
558         this.lightbox.hide();
559         this._mask.setDisplayed(false);
560         // show all the objects that cause problems..
561         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
562     }
563
564      
565 });
566