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