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