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                   '               <div href="#" id="bottomNavClose">&nbsp;</div>' +
154                   '           </div>' +
155                   '       </div>' +
156                   '   </div>' +
157                  '</div>'
158             }, true);
159          
160          
161         
162
163
164                 //Roo.get('overlay').hide();
165         //Roo.get('overlay').on('click', this.end, this);
166                 Roo.get('lightbox').hide();
167         Roo.get('lightbox').on('click',  function(event) { 
168                 if (event.getTarget().id == 'lightbox') {
169                     this.end(); 
170                 }
171             }, this);
172             
173                 Roo.get('outerImageContainer').setStyle({ width: size, height: size });
174         
175                 Roo.get('prevLink').on('click', 
176             function(event) { 
177                 event.stopEvent(); 
178                 this.changeImage(this.activeImage - 1); 
179             }, this);
180             
181                 Roo.get('nextLink').on('click', 
182             function(event) { 
183                 event.stopEvent(); 
184                 this.changeImage(this.activeImage + 1); 
185             },this);
186             
187                 Roo.get('loadingLink').on('click', 
188             function(event) { 
189                 event.stopEvent(); 
190                 this.end(); 
191             }, this);
192             
193                 Roo.get('bottomNavClose').on('click',  
194             function(event) { 
195                 event.stopEvent(); 
196                 this.end(); 
197             }, this);
198
199         var th = this;
200         (function(){
201             var ids = 
202                 'lightbox outerImageContainer imageContainer ' + 
203                 'lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
204                 'imageDataContainer imageData imageDetails caption numberDisplay '
205                 'bottomNav bottomNavClose';   
206                 
207             Roo.each(ids.split(' '), 
208                 function(id){ 
209                     
210                     th[id] = Roo.get(id); 
211                     if (!th[id]) {
212                         return;
213                        }
214                     th[id].setVisibilityMode(Element.DISPLAY);
215                 });
216         }).defer(100);
217     },
218
219     /**
220      * updateImageList()
221      * Loops through anchor tags looking for 'lightbox' references and applies onclick
222      * events to appropriate links. You can rerun after dynamically adding images w/ajax.
223      * 
224      */
225     updateImageList: function() {   
226         this.updateImageList = Roo.emptyFn;
227         
228         Roo.each(Roo.DomQuery.select('a[rel^=lightbox]'), function(e) {
229             this.imageArray.push(Roo.get(e));
230             Roo.get(e).on('click', function(event) {
231                 event.stopEvent();
232                 this.start(e);
233             }, this);
234         }, this)
235         
236     },
237     
238     /**
239     * start()
240     *  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
241     */
242     start: function(imageLink) {
243         /*
244         // hide all the objects that cause problems..
245         $$('select', 'object', 'embed').each(
246             function(node){ 
247             node.style.visibility = 'hidden' }
248         );
249         */
250         // stretch overlay to fill page and fade in
251         //var arrayPageSize = this.getPageSize();
252         Roo.get(document.body).mask(false);
253         Roo.get(document.body)._mask.setHeight(Roo.lib.Dom.getDocumentHeight())        
254         //new Effect.Appear(this.overlay,
255         //    { duration: this.overlayDuration, from: 0.0, to: this.overlayOpacity });
256
257         //this.imageArray = [];
258         var imageNum = 0;       
259
260         // let's assume the constructor sorts out the list of images..
261         /*
262         if ((imageLink.rel == 'lightbox')){
263             // if image is NOT part of a set, add single image to imageArray
264             this.imageArray.push([imageLink.href, imageLink.title]);         
265         } else {
266             // if image is part of a set..
267             this.imageArray = 
268                 $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
269                 collect(function(anchor){ return [anchor.href, anchor.title]; }).
270                 uniq();
271             
272             while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
273         }
274         */
275         var s = Roo.get(document).getScroll();
276         
277         // calculate top and left offset for the lightbox 
278         // weird.. why / 10?
279         var lightboxTop = s.top + (Roo.lib.Dom.getViewHeight() / 10);
280         var lightboxLeft = s.left
281         this.lightbox.setStyle({ 
282             top: lightboxTop + 'px', 
283             left: lightboxLeft + 'px' ,
284             zIndex : Roo.get(document.body)._mask.getStyle('zIndex') * 1.1
285         })
286         this.lightbox.show();
287         
288         
289         
290         this.changeImage(imageNum);
291     },
292
293     //
294     //  changeImage()
295     //  Hide most elements and preload image in preparation for resizing image container.
296     //
297     changeImage: function(imageNum) {   
298         
299         this.activeImage = imageNum; // update global var
300
301         // hide elements during transition
302         if (this.animate) {
303             this.loading.setStyle({
304                 zIndex : Roo.get(document.body)._mask.getStyle('zIndex') * 1.2
305             });
306             this.loading.show();
307             this.loadingLink.setX( (Roo.lib.Dom.getViewWidth() / 2) - 16);
308             //this.loadingLink.show();
309             // center the loading?
310             
311         }
312         
313         this.hoverNav.hide();
314         this.prevLink.hide();
315         this.nextLink.hide();
316                 // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
317         this.imageDataContainer.setStyle({opacity: .0001});
318         this.numberDisplay.hide();
319         
320         var imgPreloader =  Roo.DomHelper.append(document.body, { tag: 'img' } , true);
321         // once image is preloaded, resize image container
322
323
324         imgPreloader.on('load', function() {
325             this.lightboxImage.dom.src = this.imageArray[this.activeImage].dom.href;
326             this.resizeImageContainer(imgPreloader.getWidth(), imgPreloader.getHeight());
327         }, this);
328         imgPreloader.dom.src = this.imageArray[this.activeImage].dom.href;
329     },
330
331     //
332     //  resizeImageContainer()
333     //
334     resizeImageContainer: function(imgWidth, imgHeight) {
335
336         // make sure we have some sensible sizes..
337         imgWidth = Math.max(50, imgWidth);
338         imgHeight = Math.max(50, imgHeight);
339         
340         // get current width and height
341         var widthCurrent  = this.outerImageContainer.getWidth();
342         var heightCurrent = this.outerImageContainer.getHeight();
343         
344         //fixme need better calcs.
345         var w = window;
346         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
347         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
348         
349         ww -= 150;
350         wh -= 150;
351         // get new width and height
352         var bs =  this.borderSize * 2;
353         
354         var widthNew  =  imgWidth  + bs;
355         var heightNew =  imgHeight + bs;
356         
357         if (widthNew > ww || heightNew > wh) {
358             // bigger than window.
359             // scale here... - bit nasty..
360             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
361              //console.log(rescale);
362             imgWidth = Math.floor(imgWidth / rescale);
363             imgHeight = Math.floor(imgHeight / rescale);
364             widthNew  =  imgWidth  + bs;
365             heightNew =  imgHeight + bs;
366                     
367             
368         }
369         
370         this.lightboxImage.set( { width : imgWidth, height : imgHeight });
371         
372         
373         // scalars based on change from old to new
374         var xScale = (widthNew  / widthCurrent)  * 100;
375         var yScale = (heightNew / heightCurrent) * 100;
376
377         // calculate size difference between new and old image, and resize if necessary
378         var wDiff = widthCurrent - widthNew;
379         var hDiff = heightCurrent - heightNew;
380         
381          
382         this.outerImageContainer.animate(
383             { width: {to: widthNew}, height: {to: heightNew} },
384             this.resizeDuration,
385             null, // on complete
386             'easeOut', // easing
387             'run' // effect
388         
389         )        
390        
391         
392         // if new and old image are same size and no scaling transition is necessary, 
393         // do a quick pause to prevent image flicker.
394         var timeout = 0;
395         if ((hDiff == 0) && (wDiff == 0)){
396             timeout = 100;
397             if (Roo.isIE) timeout = 250;   
398         }
399
400         (function(){
401             this.prevLink.setStyle({ height: imgHeight + 'px' });
402             this.nextLink.setStyle({ height: imgHeight + 'px' });
403             this.imageDataContainer.setStyle({ width: widthNew + 'px',}); // the text area..
404             this.showImage();
405         }).defer(timeout / 1000, this);
406     },
407     
408     //
409     //  showImage()
410     //  Display image and begin preloading neighbors.
411     //
412     showImage: function(){
413         
414         this.loading.hide();
415         //this.loadingLink.hide();
416         var _this=  this;
417         this.lightboxImage.animate( 
418             {
419                 opacity : {  to: 1.0 }
420             },
421             this.resizeDuration,
422             function(){ 
423                 _this.updateDetails(); 
424             }
425             
426         );
427         this.preloadNeighborImages();
428     },
429
430     //
431     //  updateDetails()
432     //  Display caption, image number, and bottom nav.
433     //
434     updateDetails: function() {
435     
436         // if caption is not null
437         if (this.imageArray[this.activeImage].dom.title  != ""){
438             this.caption.update(this.imageArray[this.activeImage].dom.title);
439             this.caption.show();
440         }
441         
442         // if image is part of set display 'Image x of x' 
443         if (this.imageArray.length > 1){
444             this.numberDisplay.update(
445                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length)
446             this.numberDisplay.show();
447         }
448         var _this = this;
449         this.imageDataContainer.animate(
450             {
451                 //slide down ?: , from: 0.0, to: 1.0 
452                 opacity :  {  to: 1.0 }
453             },
454             this.resizeDuration,
455             function() {
456                         // update overlay size and update nav
457                         //var arrayPageSize = this.getPageSize();
458                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
459                         _this.updateNav();
460             }
461              
462         );
463     },
464
465     //
466     //  updateNav()
467     //  Display appropriate previous and next hover navigation.
468     //
469     updateNav: function() {
470
471         this.hoverNav.show();               
472
473         // if not first image in set, display prev image button
474         if (this.activeImage > 0) this.prevLink.show();
475
476         // if not last image in set, display next image button
477         if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();
478         
479         this.enableKeyboardNav();
480     },
481
482     //
483     //  enableKeyboardNav()
484     //
485     enableKeyboardNav: function() {
486         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
487     },
488
489     //
490     //  disableKeyboardNav()
491     //
492     disableKeyboardNav: function() {
493         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
494     },
495
496     //
497     //  keyboardAction()
498     //
499     keyboardAction: function(event) {
500         var keycode = event.keyCode;
501
502         var escapeKey;
503         if (event.DOM_VK_ESCAPE) {  // mozilla
504             escapeKey = event.DOM_VK_ESCAPE;
505         } else { // ie
506             escapeKey = 27;
507         }
508
509         var key = String.fromCharCode(keycode).toLowerCase();
510         
511         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
512             this.end();
513         } else if ((key == 'p') || (keycode == 37)){ // display previous image
514             if (this.activeImage != 0){
515                 this.disableKeyboardNav();
516                 this.changeImage(this.activeImage - 1);
517             }
518         } else if ((key == 'n') || (keycode == 39)){ // display next image
519             if (this.activeImage != (this.imageArray.length - 1)){
520                 this.disableKeyboardNav();
521                 this.changeImage(this.activeImage + 1);
522             }
523         }
524     },
525
526     //
527     //  preloadNeighborImages()
528     //  Preload previous and next images.
529     //
530     preloadNeighborImages: function(){
531         var preloadNextImage, preloadPrevImage;
532         if (this.imageArray.length > this.activeImage + 1){
533             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
534             preloadNextImage.dom.src = this.imageArray[this.activeImage + 1].dom.href;
535         }
536         if (this.activeImage > 0){
537             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
538             preloadPrevImage.dom.src = this.imageArray[this.activeImage - 1].dom.href;
539         }
540     
541     },
542
543     //
544     //  end()
545     //
546     end: function() {
547         this.disableKeyboardNav();
548         this.lightbox.hide();
549         this.loading.hide();
550         Roo.get(document.body).unmask();
551         // show all the objects that cause problems..
552         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
553     }
554
555      
556 });
557