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