xref: /plugin/popupviewer/script.js (revision 71189f11f14f9f06f76600af7d5cbbe4dd7d540e)
1(function($){
2
3	var popupviewer = function() {
4	};
5
6	/* singleton */
7	var instance = null;
8	$.popupviewer = function() {
9		return instance || (instance = new popupviewer());
10	};
11
12	// Static functions
13	(function(_){
14
15		var viewer = null;
16		var content = null;
17		var additionalContent = null;
18		var BASE_URL = DOKU_BASE + 'lib/exe/ajax.php';
19		var viewerIsFixed = false;
20		var next = null;
21		var previous = null;
22		var internal = {};
23
24		_.popupImageStack = null;
25
26		internal.log = function(message) {
27			// console.log(message);
28		};
29
30		_.showViewer = function() {
31
32			if ( viewer == null ) {
33
34				viewer = $('<div id="popupviewer"/>').click(_.hideViewer).appendTo('body');
35				content = $('<div class="content"/>').click(function(e){e.stopPropagation()});
36				content.current = $();
37
38				additionalContent = $('<div class="additionalContent dokuwiki"/>');
39				viewerIsFixed = viewer.css('position');
40
41				$('<div class="controls"/>').
42					append(content).
43					append(additionalContent).
44					append(previous = $('<a class="previous"/>').click({'direction': -1}, _.skipImageInDirection)).
45					append(next = $('<a class="next"/>').click({'direction': 1}, _.skipImageInDirection)).
46					append($('<a class="close"/>').addClass('visible').click(_.hideViewer)).
47					appendTo(viewer);
48
49				$(document).keydown(internal.globalKeyHandler);
50
51			}
52
53			content.empty();
54			additionalContent.empty();
55			$('body').css('overflow', 'hidden');
56			viewer.show();
57			return _;
58		};
59
60		_.hideViewer = function(e, finalFunction) {
61			if ( viewer != null ) {
62				$('body').css('overflow', 'auto');
63
64				additionalContent.animate({
65					opacity: 0,
66					height: 0
67				});
68
69				content.animate({
70					width : 208,
71					height : 13,
72				}).parent('.controls').animate({
73					top : '50%',
74					left : '50%',
75					'margin-left' : -104
76				}).parent('#popupviewer').animate({
77					opacity: finalFunction ? 1 : 0
78				}, function(){
79					viewer.hide();
80
81					content.empty();
82					additionalContent.empty();
83					content.current = null;
84
85					additionalContent.css({
86						opacity: 1,
87						height: ''
88					});
89
90					content.css({
91						width : '',
92						height : '',
93					}).parent('.controls').css({
94						top : '',
95						left : '',
96						'margin-left' : ''
97					}).parent('#popupviewer').css({
98						opacity : 1
99					});
100
101					if ( typeof finalFunction == 'function' ) {
102						finalFunction(e);
103					}
104				});
105			}
106
107			return _;
108		};
109
110		internal.globalKeyHandler = function(e) {
111
112			if ( !viewer.is(":visible") ) return;
113
114			switch(e.keyCode) {
115				case 39: // Right
116					e.stopPropagation();
117					next.click();
118					break;
119				case 37: // Left
120					e.stopPropagation();
121					previous.click();
122					break;
123				case 27: // Escape
124					e.stopPropagation();
125					_.hideViewer();
126					break;
127			}
128		};
129
130		_.presentViewerWithContent = function(e, popupData) {
131
132			popupData = popupData || this.popupData || e.target.popupData; // Either as param or from object
133
134			/*
135				popupData = {
136					isImage: boolean,
137					call: ajax_handler,
138					src: URL,
139					id: alternate_wiki_page,
140					width: width_of_window,
141					height: height_of_window
142				}
143			*/
144
145			if ( !popupData ) { return; }
146			e && e.preventDefault();
147
148			if ( content && !content.is(':empty') ) {
149				e.target.popupData = popupData;
150				_.hideViewer(e, _.presentViewerWithContent);
151				return _;
152			}
153
154			_.showViewer();
155
156			content.current = $(this);
157
158			internal.log(popupData);
159
160			if ( popupData.isImage ) {
161
162				// Load image routine
163				internal.log("loading an image");
164				popupData.call = popupData.call || '_popup_load_image_meta';
165				$(new Image()).attr('src', popupData.src || this.href).load(function(){
166
167					var image = $(this);
168
169					var wrapper = $('<div/>').load(BASE_URL, popupData, function() {
170
171						// Force size for the moment
172						content.css({
173							width: content.width(),
174							height: content.height(),
175							overflow: 'hidden'
176						});
177
178						content.append(image);
179						content.popupData = jQuery.extend(true, {}, popupData);
180
181						additionalContent.html(wrapper.html());
182                        _.registerCloseHandler();
183						_.resizePopup(popupData.width, popupData.height, additionalContent.innerHeight(), image, false, popupData.hasNextPrevious);
184					});
185				});
186
187			} else {
188
189				popupData.call = popupData.call || '_popup_load_file';
190				popupData.src = popupData.src || BASE_URL;
191				var wrapper = $('<div/>').load(popupData.src, popupData, function(response, status, xhr) {
192
193					var success = function(node)
194					{
195						node.find('div.dokuwiki,body').first().waitForImages({
196							finished: function() {
197
198							// Force size for the moment
199							content.css({
200								width: content.width(),
201								height: content.height()
202							});
203
204							content.html(this);
205
206							// Check for Javascript to execute
207							var script = "";
208							node.find('popupscript').
209							each(function() {
210								script += (this.innerHTML || this.innerText);
211							});
212
213							if ( script.length > 0 )
214							{
215								var randomID = Math.ceil(Math.random()*1000000);
216								content.attr('id', randomID);
217
218								var newContext = ""; //"jQuery.noConflict(); containerContext = this; ___ = function( selector, context ){return new jQuery.fn.init(selector,context||containerContext);}; ___.fn = ___.prototype = jQuery.fn;jQuery.extend( ___, jQuery );jQuery = ___;\n"
219
220								try{
221									$.globalEval("try{\n(function(){\n"+newContext+script+"\n}).call(jQuery('div#"+randomID+"').get(0));\n}catch(e){}\n//");
222								} catch (e) {
223									internal.log("Exception!");
224									internal.log(e);
225								}
226							}
227
228							if ( popupData.postPopupHook && typeof popupData.postPopupHook == 'function' ) {
229							    // Post-Hook which as to be a javascript function and my modify the popupData
230    							popupData.postPopupHook(this, popupData);
231							}
232
233                            _.registerCloseHandler();
234                            // At the very end we will resize the popup to fit the content.
235							_.resizePopup(popupData.width, popupData.height, null, content, true, popupData.hasNextPrevious);
236
237						}, waitForAll: true});
238					};
239
240
241					if ( status == "error") {
242						// Go for an iframe
243						var finished = false;
244						var iframe = null;
245
246						var messageFunction = function(event) {
247
248							finished = true;
249							var data = event.data || event.originalEvent.data;
250							// If this message does not come with what we want, discard it.
251							if ((typeof data).toLowerCase() == "string" || !data.message
252									|| data.message != 'frameContent') {
253								alert("Could not load page via popupviewer. The page responded with a wrong message.");
254								return;
255							}
256
257							iframe.remove();
258
259							// Clear the window Event after we are done!
260							$(window).unbind("message", messageFunction);
261
262							success($(data.body));
263						};
264
265						var iframe = $('<iframe/>').load(function(){
266
267							var frame = this;
268							if ( frame.contentWindow.postMessage ) {
269
270								// Register the Message Event for PostMessage receival
271								$(window).bind("message", messageFunction);
272
273								// Send a message
274								var message = "getFrameContent";
275								frame.contentWindow.postMessage(message, "*");
276							}
277
278						}).hide().attr('src', internal.getCurrentLocation() ).appendTo('body');
279
280						window.setTimeout(function() {
281							if (!finished) {
282								iframe.remove();
283								alert("Could not load page via popupviewer. The page is not available.");
284							}
285						}, 30000);
286
287					} else {
288						success(wrapper)
289					}
290
291				});
292			}
293		};
294
295		/* has to be called via popupscript in page if needed. */
296		_.propagateClickHandler = function(node) {
297			node.find('a[href],form[action]').
298			each(function(){
299				// Replace all event handler
300
301				var element = $(this);
302
303				urlpart = element.attr('href') || element.attr('action') || "";
304				if ( urlpart.match(new RegExp("^#.*?$")) ) {
305					// Scroll to anchor
306					element.click(function(){
307						content.get(0).scrollTop( urlpart == '#' ? 0 : $(urlpart).offset().top);
308					});
309				}
310
311				if ( this.getAttribute('data-popupviewer') ) {
312					this.popupData = $.parseJSON(this.getAttribute('data-popupviewer'));
313					this.removeAttribute('data-popupviewer');
314				} else {
315					this.popupData = jQuery.extend(true, {}, popupData);
316					this.popupData.src = urlpart;
317					delete(this.popupData.id); // or it will always load this file.
318				}
319
320				$(this).bind('click', function(e){
321					e.stopPropagation(); e.preventDefault();
322					_.hideViewer(e, _.presentViewerWithContent);
323				});
324			});
325		};
326
327		internal.getCurrentLocation = function() {
328			return content.current.attr('href') || content.current.attr('src') || content.current.attr('action');
329		};
330
331		internal.optimalSize = function(offsetElement, isPageContent) {
332/*
333			if ( !isPageContent ) {
334				return {width: offsetElement.get(0).width, height: offsetElement.get(0).height};
335			}
336*/
337			var prevWidth = content.width();
338			var prevHeight = content.height();
339
340			offsetElement.css({width:'auto', height: 'auto'});
341
342			width = offsetElement.naturalWidth() || offsetElement.width();
343			height = offsetElement.naturalHeight() || offsetElement.height();
344
345			// Reset to previous size so the whole thing will animate from the middle
346			offsetElement.css({width:prevWidth, height: prevHeight});
347
348			return {width: width, height: height};
349		};
350
351		_.resizePopup = function(width, height, additionalHeight, offsetElement, isPageContent, needsNextPrevious) {
352
353			internal.log("Initial Size: " + width + " " + height);
354			internal.log(offsetElement);
355
356			if ( offsetElement && !width && !height) {
357				var optimalSize = internal.optimalSize(offsetElement, isPageContent);
358				width = optimalSize.width;
359				height = optimalSize.height;
360			}
361
362			internal.log("OffsetElement Size: " + width + " " + height);
363			width = parseInt(width) || ($(window).width() * 0.7);
364			height = parseInt(height) || ($(window).height() * 0.8);
365
366			var ratio = width / height;
367			var maxHeight = ( $(window).height() * 0.99 ) - 60;
368			var maxWidth = ( $(window).width() * 0.99 ) - 40;
369
370			additionalHeight = additionalHeight || 0;
371			height += additionalHeight;
372
373			internal.log("After Additional Content Size: " + width + " " + height);
374
375			if ( height > maxHeight ) {
376				height = maxHeight;
377				if ( !isPageContent ) { // If this is an image we will have to fix the size
378					width = (height - additionalHeight) * ratio;
379				} else {
380					width += 20; // For the scroller Bar that will apear;
381				}
382			}
383
384			if ( width > maxWidth ) {
385				width = maxWidth;
386				if ( !isPageContent ) { // If this is an image we will have to fix the size
387					height = width / ratio + additionalHeight;
388				}
389			}
390
391			var xOffset = viewerIsFixed ? 0 : $(document).scrollLeft() || 0;
392			var yOffset = viewerIsFixed ? 0 : $(document).scrollTop() || 0;
393
394			yOffset = Math.max(($(window).height() - height) * 0.5 + yOffset, 5);
395			xOffset += ($(window).width() - width) * 0.5;
396
397			internal.log("Final Size: " + width + " " + height);
398			internal.log("Final Offset: " + xOffset + " " + yOffset);
399
400			if ( !isPageContent || (offsetElement && offsetElement.is('img')) ) {
401
402				offsetElement.animate({
403					width : width,
404					height : height - additionalHeight
405				});
406
407				content.css({
408					width : '',
409					height : '',
410					overflow: ''
411				});
412
413			} else {
414				content.animate({
415					width : width,
416					height : isPageContent ? height : 'auto',
417				});
418			}
419
420			content.parent().animate({
421				top : yOffset,
422				left : xOffset,
423				'margin-left' : 0
424			});
425
426			if ( isPageContent ) {
427				content.removeClass('isImage');
428			} else {
429				content.addClass('isImage');
430			}
431
432			_.handleNextAndPrevious(!isPageContent || needsNextPrevious);
433			return _;
434		};
435
436		_.skipImageInDirection = function(e)
437		{
438			e.stopPropagation();
439
440			if ( !$(this).is(':visible') ) { return; }
441
442			var skipTo =  $.inArray(content.current.get(0), _.popupImageStack) + e.data.direction;
443			skipTo = Math.min(_.popupImageStack.length-1, Math.max(skipTo, 0));
444
445			internal.log("skipping " + (e.data.direction < 0 ? 'previous' : 'next') + ' ' + skipTo );
446			return _.skipToImage(skipTo, e.data.direction);
447		};
448
449		_.skipToImage = function(skipTo, inDirection)
450		{
451			if ( !$(_.popupImageStack[skipTo]).is(content.current) ) {
452				_.hideViewer(null, function() {
453					// Deliver extra functionality to clicked item.
454					var nextItem = _.popupImageStack[skipTo];
455					(nextItem.popupData && nextItem.popupData.click && nextItem.popupData.click(skipTo, inDirection)) || $(nextItem).click();
456				});
457			}
458
459			return _;
460		};
461
462		_.isFirst = function() {
463			return _.popupImageStack.first().is(content.current);
464		};
465
466		_.isLast = function() {
467			return _.popupImageStack.last().is(content.current);
468		};
469
470		_.handleNextAndPrevious = function(currentIsImage) {
471
472			if ( currentIsImage && _.popupImageStack && _.popupImageStack.size() > 1) {
473
474				if ( _.isFirst() ) {
475					previous.addClass('inactive');
476				} else {
477					previous.removeClass('inactive');
478				}
479
480				if ( _.isLast() ) {
481					next.addClass('inactive');
482				} else {
483					next.removeClass('inactive');
484				}
485
486				next.addClass('visible');
487				previous.addClass('visible');
488			} else {
489				next.removeClass('visible');
490				previous.removeClass('visible');
491			}
492
493			return _;
494		};
495
496        _.registerCloseHandler = function () {
497            $('*[data-popupviewerclose]').each(function(){
498                $(this).click(function(e){
499                   e && e.preventDefault();
500                   _.hideViewer(e);
501                   return false;
502                });
503                if (this.removeAttribute) this.removeAttribute('data-popupviewerclose');
504            });
505        };
506
507		_.init = function(popupImageStack) {
508
509			_.popupImageStack = $(popupImageStack || '*[data-popupviewer]').each(function(){
510				this.popupData = this.popupData || $.parseJSON(this.getAttribute('data-popupviewer'));
511				if (this.removeAttribute) this.removeAttribute('data-popupviewer');
512				$(this).unbind('click').click(_.presentViewerWithContent);
513			}).filter(function(){
514				// Only images allowed in Stack.
515				return this.popupData.isImage || this.popupData.hasNextPrevious;
516			});
517
518			return _;
519		};
520
521	})(popupviewer.prototype);
522
523    // Namespace all events.
524    var eventNamespace = 'waitForImages';
525
526    // CSS properties which contain references to images.
527    $.waitForImages = {
528        hasImageProperties: ['backgroundImage', 'listStyleImage', 'borderImage', 'borderCornerImage', 'cursor']
529    };
530
531    // Custom selector to find `img` elements that have a valid `src` attribute and have not already loaded.
532    $.expr[':'].uncached = function (obj) {
533        // Ensure we are dealing with an `img` element with a valid `src` attribute.
534        if (!$(obj).is('img[src!=""]')) {
535            return false;
536        }
537
538        // Firefox's `complete` property will always be `true` even if the image has not been downloaded.
539        // Doing it this way works in Firefox.
540        var img = new Image();
541        img.src = obj.src;
542        return !img.complete;
543    };
544
545    $.fn.waitForImages = function (finishedCallback, eachCallback, waitForAll) {
546
547        var allImgsLength = 0;
548        var allImgsLoaded = 0;
549
550        // Handle options object.
551        if ($.isPlainObject(arguments[0])) {
552            waitForAll = arguments[0].waitForAll;
553            eachCallback = arguments[0].each;
554			// This must be last as arguments[0]
555			// is aliased with finishedCallback.
556            finishedCallback = arguments[0].finished;
557        }
558
559        // Handle missing callbacks.
560        finishedCallback = finishedCallback || $.noop;
561        eachCallback = eachCallback || $.noop;
562
563        // Convert waitForAll to Boolean
564        waitForAll = !! waitForAll;
565
566        // Ensure callbacks are functions.
567        if (!$.isFunction(finishedCallback) || !$.isFunction(eachCallback)) {
568            throw new TypeError('An invalid callback was supplied.');
569        }
570
571        return this.each(function () {
572            // Build a list of all imgs, dependent on what images will be considered.
573            var obj = $(this);
574            var allImgs = [];
575            // CSS properties which may contain an image.
576            var hasImgProperties = $.waitForImages.hasImageProperties || [];
577            // To match `url()` references.
578            // Spec: http://www.w3.org/TR/CSS2/syndata.html#value-def-uri
579            var matchUrl = new RegExp("url\(\s*(['\"]?)(.*?)\1\s*\)", "g");
580
581            if (waitForAll) {
582
583                // Get all elements (including the original), as any one of them could have a background image.
584                obj.find('*').addBack().each(function () {
585                    var element = $(this);
586
587                    // If an `img` element, add it. But keep iterating in case it has a background image too.
588                    if (element.is('img:uncached')) {
589                        allImgs.push({
590                            src: element.attr('src'),
591                            element: element[0]
592                        });
593                    }
594
595                    $.each(hasImgProperties, function (i, property) {
596                        var propertyValue = element.css(property);
597                        var match;
598
599                        // If it doesn't contain this property, skip.
600                        if (!propertyValue) {
601                            return true;
602                        }
603
604                        // Get all url() of this element.
605                        while (match = matchUrl.exec(propertyValue)) {
606                            allImgs.push({
607                                src: match[2],
608                                element: element[0]
609                            });
610                        }
611                    });
612                });
613            } else {
614                // For images only, the task is simpler.
615                obj.find('img:uncached')
616                    .each(function () {
617                    allImgs.push({
618                        src: this.src,
619                        element: this
620                    });
621                });
622            }
623
624            allImgsLength = allImgs.length;
625            allImgsLoaded = 0;
626
627            // If no images found, don't bother.
628            if (allImgsLength === 0) {
629                finishedCallback.call(obj[0]);
630            }
631
632            $.each(allImgs, function (i, img) {
633
634                var image = new Image();
635
636                // Handle the image loading and error with the same callback.
637                $(image).on('load.' + eventNamespace + ' error.' + eventNamespace, function (event) {
638                    allImgsLoaded++;
639
640                    // If an error occurred with loading the image, set the third argument accordingly.
641                    eachCallback.call(img.element, allImgsLoaded, allImgsLength, event.type == 'load');
642
643                    if (allImgsLoaded == allImgsLength) {
644                        finishedCallback.call(obj[0]);
645                        return false;
646                    }
647
648                });
649
650                image.src = img.src;
651            });
652        });
653    };
654
655	$(function(){
656		$.popupviewer().init();
657	});
658
659})(jQuery);
660
661
662/* Loading the content for locally exported content */
663(function($){
664	$(window).bind("message", function(event){
665
666		var data = event.data || event.originalEvent.data;
667		var source = event.source || event.originalEvent.source;
668		if (data != "getFrameContent") {
669			return;
670		}
671
672		try {
673			source.postMessage({
674				message : "frameContent",
675				body : jQuery('html').html()
676			}, "*");
677		} catch (e) {
678			alert("Fatal Exception! Could not load page via popupviewer.\n" + e);
679		}
680	});
681})(jQuery);
682