Fix #6596 - lightbox on images
[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     /**
58      * @cfg overlayOpacity {number} controls transparency of shadow overlay
59      */
60     overlayOpacity: 0.8,   
61     /**
62      * @cfg animate {boolean} toggles resizing animations
63      */
64     animate: true,          
65     /**
66      * @cfg resizeSpeed {number} controls the speed of the image 
67      * resizing animations (1=slowest and 10=fastest)
68      */
69     resizeSpeed: 9,
70     /**
71      * @cfg borderSize {number} if you adjust the padding in the CSS, 
72      * you will need to update this variable
73      */
74     borderSize: 10,
75     /**
76      * @cfg labelImage {string} When grouping images this is used to write: Image # of #.
77      * Change it for non-english localization
78      */
79         labelImage: "Image",
80         /**
81      * @cfg labelOf {string}  When grouping images this is used to write: Image # of #.
82      */
83     labelOf: "of",
84     
85     
86     
87     
88     /**
89      * Array of images Roo.Elements (which should be images)
90      * properties can be 
91      */
92     imageArray: false,
93     
94     /**
95      * Current image.
96      * 
97      */
98      
99     activeImage: undefined,
100     
101     /**
102      * initialize() 
103      *  Constructor runs on completion of the DOM loading. Calls updateImageList and then
104      * the function inserts html at the bottom of the page which is used to display the shadow 
105      *  overlay and the image container.
106      * 
107      * 
108      */
109     initialize: function() {    
110         
111         this.updateImageList();
112         this.initializeCSS();
113         // TBD this.keyboardAction = this.keyboardAction.bindAsEventListener(this);
114         this.resizeSpeed  = Math.min(this.resizeSpeed, 10);
115         this.resizeSpeed  = Math.max(this.resizeSpeed, 1);
116         
117         this.resizeDuration = this.animate ? ((11 - this.resizeSpeed) * 0.15) : 0;
118         this.overlayDuration = this.animate ? 0.2 : 0;  // shadow fade in/out duration
119
120         // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
121         // If animations are turned off, it will be hidden as to prevent a flicker of a
122         // white 250 by 250 box.
123         var size = (this.animate ? 250 : 1) + 'px';
124         var dh = Roo.DomHelper;
125         this.el = Roo.DomHelper.append(document.body, {
126                 html: 
127                   '<div class="roo-lightbox-overlay"></div>' +
128                   '<div class="roo-lightbox">' +
129                   '   <div class="outer-image-container">' +
130                   '       <div class="image-container">' +
131                   '           <img class="lightbox-image">' +
132                   '           <div style="" class="hover-nav">' +
133                   '               <a href="#" class="prev-link"></a>' +
134                   '               <a href="#" class="next-link"></a>' +
135                   '           </div>' +
136                   '           <div class="loading">' +
137                   '               <a href="#" class="loading-link">&nbsp;</a>' +
138                   '           </div>' +
139                   '       </div>' +
140                   '   </div>' +
141                   '   <div class="image-data-container">' +
142                   '       <div class="image-data">' +
143                   '           <div class="image-details">' +
144                   '               <span class="caption"></span>' +
145                   '               <span class="number-display"></span>' +
146                   '           </div>' +
147                   '           <div class="bottom-nav">' +
148                   '               <div href="#" class="bottom-nav-close"></div>' +
149                   '           </div>' +
150                   '       </div>' +
151                   '   </div>' +
152                  '</div>'
153             }, true);
154          
155          
156         
157         var th = this;
158         
159         var ids = 'roo-lightbox outer-image-container image-container ' + 
160             'lightbox-image hover-nav prev-link next-link loading loading-link ' + 
161             'image-data-container image-data image-details caption number-display ' +
162             'bottom-nav bottom-nav-close roo-lightbox-overlay';   
163             
164         Roo.each(ids.split(' '), 
165             function(id){ 
166                 var vid = id.replace(/\-/g,'');
167                 th[vid] = th.el.child('.'+id); 
168                 if (!th[vid]) {
169                     return;
170                 }
171                 
172                 th[vid].setVisibilityMode(Roo.Element.DISPLAY);
173             });
174         this.lightbox = this.roolightbox;
175
176         this.overlay = this.roolightboxoverlay;
177         this.overlay.hide();
178          
179                 this.lightbox.hide();
180         this.lightbox.on('click',  function(event) { 
181                  if (Roo.get(event.getTarget()).hasClass('roo-lightbox')) {
182                     this.end(); 
183                 }
184             }, this);
185             
186                 this.outerimagecontainer.setStyle({ width: size, height: size });
187         
188                 this.prevlink.on('click', 
189             function(event) { 
190                 event.stopEvent(); 
191                 this.changeImage(this.activeImage - 1); 
192             }, this);
193             
194                 this.nextlink.on('click', 
195             function(event) { 
196                 event.stopEvent(); 
197                 this.changeImage(this.activeImage + 1); 
198             },this);
199             
200                 this.loadinglink.on('click', 
201             function(event) { 
202                 event.stopEvent(); 
203                 this.end(); 
204             }, this);
205             
206                 this.bottomnavclose.on('click',  
207             function(event) { 
208                 event.stopEvent(); 
209                 this.end(); 
210             }, this);
211
212         this.overlay.on('click',  
213             function(event) { 
214                 event.stopEvent(); 
215                 this.end(); 
216             }, this);
217
218     },
219
220     initializeCSS: function() {    
221         if (typeof(Roo.ux.Lightbox.css) != 'undefined') {
222             return;
223         }
224         var rootURL = Roo.BLANK_IMAGE_URL.replace(/\/gray\/s\.gif$/, '');
225         
226         Roo.ux.Lightbox.css = Roo.util.CSS.createStyleSheet( {
227             '.roo-lightbox' : {
228                 position: 'absolute',
229                 left: 0,
230                 width: '100%',
231                 'text-align': 'center',
232                 'line-height': 0
233             },
234             '.roo-lightbox a img' : { border: 'none'  },
235             '.roo-lightbox .outer-image-container' : {
236                 position: 'relative',
237                 'background-color': '#fff',
238                 width: '250px',
239                 height: '250px',
240                 margin: '0 auto'
241             },
242             
243             '.roo-lightbox image-container'  :{ padding: '10px'  },
244
245             '.roo-lightbox .loading' : { 
246                 position:'absolute', 
247                 top:'40%',
248                 left:'0%',
249                 height:'25%',
250                 width:'100%',
251                 'text-align':'center',
252                 'line-height':'0'
253             
254             },
255             '.roo-lightbox .loading a' : { 
256                 background:'url('+ rootURL  + '/ux/lightbox/loading.gif) 0 0 no-repeat', 
257                 display:'block',
258                 width:'32px',
259                 height:'32px',
260                 cursor:'pointer'
261             },
262             '.roo-lightbox .bottom-nav-close' : {
263                 background:'url('+ rootURL  + '/ux/lightbox/close.gif) 0 0 no-repeat', 
264                 height:'26px',
265                 width:'26px',
266                 cursor:'pointer'
267             },
268             '.roo-lightbox .hover-nav' :{ 
269                 position:'absolute', 
270                 top:'0', 
271                 left:'0', 
272                 height:'100%', 
273                 width:'100%', 
274                 'z-index':'10'
275             },
276             '.roo-lightbox .image-container>.hover-nav' :{ left:'0' },
277             '.roo-lightbox .hover-nav a' :{ outline:'none'},
278
279             '.roo-lightbox .prev-link, .roo-lightbox .next-link' : { 
280                 width:'49%', 
281                 height:'100%', 
282                 'background-image':'url(data:image/gif;base64,AAAA)', 
283                 display:'block' 
284             },
285             '.roo-lightbox .prev-link' : { left:'0','float':'left'},
286             '.roo-lightbox .next-link' : { right:'0','float':'right'},
287             '.roo-lightbox .prev-link:hover, .roo-lightbox .prev-link:visited:hover ' :{ 
288                     background:'url('+ rootURL  + '/ux/lightbox/prevlabel.gif) left 15% no-repeat'
289             },
290             '.roo-lightbox .next-link:hover, .roo-lightbox .next-link:visited:hover ' :{ 
291                 background:'url('+ rootURL  + '/ux/lightbox/nextlabel.gif) right 15% no-repeat'
292             },
293
294             '.roo-lightbox .image-data-container' : { 
295                 font: '10px Verdana, Helvetica, sans-serif',
296                 'background-color': '#fff',
297                 margin: '0 auto',
298                 'line-height': '1.4em', 
299                 overflow: 'auto', 
300                 width: '100%'
301             },
302
303             '.roo-lightbox .image-data' : { padding:'0 10px', color: '#666' },
304             '.roo-lightbox .image-data .image-details ' : { width: '70%', 'float': 'left', 'text-align': 'left'}  ,
305             '.roo-lightbox .image-data .caption' : { 'font-weight': 'bold' },
306             '.roo-lightbox .image-data .number-display' : { 'display': 'block', clear: 'left', 'padding-bottom': '1.0em'  } ,   
307             '.roo-lightbox .image-data .bottom-nav-close' : {  'float': 'right',  'padding-bottom': '0.7em','outline': 'none'} ,
308             '.roo-lightbox-overlay' : {
309                 'background-color': 'black',
310                 height: '500px',
311                 left: '0px',
312                 position: 'absolute',
313                 top: '0px',
314                 width: '100%',
315                 'z-index': '999'
316             }
317         });
318     },
319
320
321     
322     /**
323      * updateImageList()
324      * Loops through anchor tags looking for 'lightbox' references and applies onclick
325      * events to appropriate links. You can rerun after dynamically adding images w/ajax.
326      * 
327      */
328     updateImageList: function() {   
329         this.updateImageList = Roo.emptyFn;
330         if (this.imageArray.length) {
331             return;
332         }
333         Roo.each(Roo.DomQuery.select('a[rel^=lightbox]'), function(e) {
334             this.imageArray.push(Roo.get(e));
335             Roo.get(e).on('click', (function(event, tg, tga,tgb) {
336                
337              
338                 event.stopEvent();
339                 this.start(tgb);
340             }).createDelegate(this, [e], true));
341         }, this)
342         
343     },
344     
345     /**
346     * start()
347     *  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
348     */
349     start: function(imageLink) {
350         /*
351         // hide all the objects that cause problems..
352         $$('select', 'object', 'embed').each(
353             function(node){ 
354             node.style.visibility = 'hidden' }
355         );
356         */
357         // stretch overlay to fill page and fade in
358         //var arrayPageSize = this.getPageSize();
359         
360         this.overlay.setHeight(Roo.lib.Dom.getDocumentHeight()) ;
361         this.overlay.setWidth(Roo.lib.Dom.getDocumentWidth());
362         this.overlay.fadeIn({
363                 endOpacity: this.overlayOpacity, 
364                 easing: 'easeOut',
365                 duration: this.overlayDuration
366         });
367          
368         //this.imageArray = [];
369         var imageNum = 0;       
370         
371         if (imageLink) {
372             imageLink = Roo.get(imageLink);
373             //console.log(imageLink.id);
374             Roo.each(this.imageArray, function (e, i) {
375               //  console.log(e.id);
376                 if (e.id == imageLink.id) {
377                     imageNum = i;
378                 }
379             });
380         }
381         
382         // let's assume the constructor sorts out the list of images..
383         /*
384         if ((imageLink.rel == 'lightbox')){
385             // if image is NOT part of a set, add single image to imageArray
386             this.imageArray.push([imageLink.href, imageLink.title]);         
387         } else {
388             // if image is part of a set..
389             this.imageArray = 
390                 $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
391                 collect(function(anchor){ return [anchor.href, anchor.title]; }).
392                 uniq();
393             
394             while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
395         }
396         */
397         var s = Roo.get(document).getScroll();
398          // calculate top and left offset for the lightbox 
399         // weird.. why / 10?
400         
401         //var lightboxTop = s.top + (Roo.lib.Dom.getViewHeight() / 10);
402         var lightboxTop = (Roo.lib.Dom.getViewHeight() / 10);
403         var lightboxLeft = s.left;
404         this.lightbox.setStyle({ 
405             top: lightboxTop + 'px', 
406             left: lightboxLeft + 'px' ,
407             zIndex : 1000
408         });
409         //console.log("show lightbox");
410         this.lightbox.show();
411         
412         
413         this.changeImage(imageNum);
414     },
415
416     //
417     //  changeImage()
418     //  Hide most elements and preload image in preparation for resizing image container.
419     //
420     changeImage: function(imageNum) {   
421         
422         this.activeImage = imageNum; // update global var
423
424         // hide elements during transition
425         if (this.animate) {
426             this.loading.setStyle({
427                 zIndex :1200
428             });
429             this.loading.show();
430             this.loadinglink.setX( (Roo.lib.Dom.getViewWidth() / 2) - 16);
431             //this.loadingLink.show();
432             // center the loading?
433             
434         }
435         
436         this.hovernav.hide();
437         this.prevlink.hide();
438         this.nextlink.hide();
439                 // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
440         this.imagedatacontainer.setStyle({opacity: .0001});
441         this.numberdisplay.hide();
442         
443         var imgPreloader =  Roo.DomHelper.append(document.body, { tag: 'img' } , true);
444         // once image is preloaded, resize image container
445
446         imgPreloader.on('load', function() {
447             
448             this.lightboximage.dom.src = this.imageArray[this.activeImage].srcfull  ||  this.imageArray[this.activeImage].href || 
449                 this.imageArray[this.activeImage].dom.href || this.imageArray[this.activeImage].dom.src;
450             
451             this.resizeImageContainer(this.imageArray[this.activeImage].dom.lwidth || imgPreloader.getWidth(),
452                                       this.imageArray[this.activeImage].dom.lheight || imgPreloader.getHeight());
453             imgPreloader.remove();
454         }, this);
455         Roo.log(this.imageArray[this.activeImage]);
456         imgPreloader.dom.src = this.imageArray[this.activeImage].srcfull || this.imageArray[this.activeImage].href || 
457             this.imageArray[this.activeImage].dom.href ||  this.imageArray[this.activeImage].dom.src;
458     },
459
460     
461     
462     //
463     //  resizeImageContainer()
464     //
465     resizeImageContainer: function(imgWidth, imgHeight) {
466
467         // make sure we have some sensible sizes..
468         imgWidth = Math.max(50, imgWidth);
469         imgHeight = Math.max(50, imgHeight);
470         
471         // get current width and height
472         var widthCurrent  = this.outerimagecontainer.getWidth();
473         var heightCurrent = this.outerimagecontainer.getHeight();
474         
475         //fixme need better calcs.
476         var w = window;
477         var ww = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
478         var wh = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
479         
480         ww -= 150;
481         wh -= 150;
482         
483         // get new width and height
484         var bs =  this.borderSize * 2;
485         
486         var widthNew  =  imgWidth  + bs;
487         var heightNew =  imgHeight + bs;
488         
489         if (widthNew > ww || heightNew > wh) {
490             // bigger than window.
491             // scale here... - bit nasty..
492             var rescale = 1.1 * Math.max( widthNew / ww , heightNew  / wh);
493              //console.log(rescale);
494             imgWidth = Math.floor(imgWidth / rescale);
495             imgHeight = Math.floor(imgHeight / rescale);
496             widthNew  =  imgWidth  + bs;
497             heightNew =  imgHeight + bs;
498                     
499             
500         }
501         
502         this.lightboximage.set( { width : imgWidth, height : imgHeight });
503         
504         
505         // scalars based on change from old to new
506         var xScale = (widthNew  / widthCurrent)  * 100;
507         var yScale = (heightNew / heightCurrent) * 100;
508
509         // calculate size difference between new and old image, and resize if necessary
510         var wDiff = widthCurrent - widthNew;
511         var hDiff = heightCurrent - heightNew;
512         
513          
514         this.outerimagecontainer.animate(
515             { width: {to: widthNew}, height: {to: heightNew} },
516             this.resizeDuration,
517             null, // on complete
518             'easeOut', // easing
519             'run' // effect
520         
521         );  
522        
523         
524         // if new and old image are same size and no scaling transition is necessary, 
525         // do a quick pause to prevent image flicker.
526         var timeout = 0;
527         if ((hDiff == 0) && (wDiff == 0)){
528             timeout = 100;
529             if (Roo.isIE) {
530                 timeout = 250;
531             }
532         }
533
534         (function(){
535             this.prevlink.setStyle({ height: imgHeight + 'px' });
536             this.nextlink.setStyle({ height: imgHeight + 'px' });
537             this.imagedatacontainer.setStyle({ width: widthNew + 'px'}); // the text area..
538             this.showImage();
539         }).defer(timeout / 1000, this);
540     },
541     
542     //
543     //  showImage()
544     //  Display image and begin preloading neighbors.
545     //
546     showImage: function(){
547         
548         this.loading.hide();
549         //this.loadingLink.hide();
550         var _this=  this;
551         this.lightboximage.animate( 
552             {
553                 opacity : {  to: 1.0 }
554             },
555             this.resizeDuration,
556             function(){ 
557                 _this.updateDetails(); 
558             }
559             
560         );
561         this.preloadNeighborImages();
562     },
563
564     //
565     //  updateDetails()
566     //  Display caption, image number, and bottom nav.
567     //
568     updateDetails: function() {
569     
570         // if caption is not null
571         if (this.imageArray[this.activeImage].dom.title  != ""){
572             this.caption.update(this.imageArray[this.activeImage].dom.title);
573             this.caption.show();
574         }
575         
576         // if image is part of set display 'Image x of x' 
577         if (this.imageArray.length > 1){
578             this.numberdisplay.update(
579                 this.labelImage + ' ' + (this.activeImage + 1) + ' ' + this.labelOf + '  ' + this.imageArray.length);
580             this.numberdisplay.show();
581         }
582         var _this = this;
583         this.imagedatacontainer.animate(
584             {
585                 //slide down ?: , from: 0.0, to: 1.0 
586                 opacity :  {  to: 1.0 }
587             },
588             this.resizeDuration,
589             function() {
590                         // update overlay size and update nav
591                         //var arrayPageSize = this.getPageSize();
592                         //this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
593                         _this.updateNav();
594             }
595              
596         );
597     },
598
599     //
600     //  updateNav()
601     //  Display appropriate previous and next hover navigation.
602     //
603     updateNav: function() {
604
605         this.hovernav.show();               
606
607         // if not first image in set, display prev image button
608         if (this.activeImage > 0) {
609             this.prevlink.show();
610         }
611
612         // if not last image in set, display next image button
613         if (this.activeImage < (this.imageArray.length - 1)) {
614             this.nextlink.show();
615         }
616         
617         this.enableKeyboardNav();
618     },
619
620     //
621     //  enableKeyboardNav()
622     //
623     enableKeyboardNav: function() {
624         Roo.get(document.body).on('keydown', this.keyboardAction, this); 
625     },
626
627     //
628     //  disableKeyboardNav()
629     //
630     disableKeyboardNav: function() {
631         Roo.get(document.body).un('keydown', this.keyboardAction, this); 
632     },
633
634     //
635     //  keyboardAction()
636     //
637     keyboardAction: function(event)
638     {
639         var keycode = event.keyCode;
640
641         var escapeKey;
642         if (event.DOM_VK_ESCAPE) {  // mozilla
643             escapeKey = event.DOM_VK_ESCAPE;
644         } else { // ie
645             escapeKey = 27;
646         }
647
648         var key = String.fromCharCode(keycode).toLowerCase();
649         
650         if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
651             this.end();
652         } else if ((key == 'p') || (keycode == 37)){ // display previous image
653             if (this.activeImage != 0){
654                 this.disableKeyboardNav();
655                 this.changeImage(this.activeImage - 1);
656             }
657         } else if ((key == 'n') || (keycode == 39)){ // display next image
658             if (this.activeImage != (this.imageArray.length - 1)){
659                 this.disableKeyboardNav();
660                 this.changeImage(this.activeImage + 1);
661             }
662         }
663     },
664
665     //
666     //  preloadNeighborImages()
667     //  Preload previous and next images.
668     //
669     preloadNeighborImages: function(){
670         var preloadNextImage, preloadPrevImage;
671         if (this.imageArray.length > this.activeImage + 1){
672             preloadNextImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
673             preloadNextImage.on('load', function() { preloadNextImage.remove() });
674             preloadNextImage.dom.src = this.imageArray[this.activeImage + 1].href ||
675                     this.imageArray[this.activeImage + 1].dom.href || this.imageArray[this.activeImage + 1 ].dom.src;;
676         }
677         if (this.activeImage > 0){
678             preloadPrevImage = Roo.DomHelper.append(document.body, { tag: 'img' } , true);
679             preloadPrevImage.on('load', function() { preloadPrevImage.remove() });
680             preloadPrevImage.dom.src = this.imageArray[this.activeImage - 1].href || 
681                    this.imageArray[this.activeImage - 1].dom.href || this.imageArray[this.activeImage - 1].dom.src;
682         }
683     
684     },
685
686     //
687     //  end()
688     //
689     end: function() {
690         this.disableKeyboardNav();
691         //console.log('lightbox hide');
692         this.lightbox.hide();
693         this.loading.hide();
694         this.overlay.hide();
695         Roo.get(document.body).unmask();
696         // show all the objects that cause problems..
697         //$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
698     }
699
700      
701 });
702