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