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