xref: /plugin/popupviewer/script.js (revision 131c851545dd34ef7f67e3f5c9351f60dac4f376)
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						if ( !popupData.do || popupData.do != 'export_xhtmlbody') {
196    						node = node.find('div.dokuwiki,body').first();
197    				    }
198
199						node.waitForImages({
200							finished: function() {
201
202							// Force size for the moment
203							content.css({
204								width: content.width(),
205								height: content.height()
206							});
207
208                            $(this).on( "click", "a", function(){
209                               // Insert base URL, so the link will be correct. hopefully.
210                               var base = $('<base href="' + popupData.src + '"/>');
211                               $("head").append(base);
212                            });
213
214							content.html(this);
215
216							// If we want to have all other pages open as well, go with it.
217							if ( popupData.keepOpen ) {
218    							_.propagateClickHandler($(this), popupData);
219							}
220
221							// Check for Javascript to execute
222							var script = "";
223							node.find('popupscript').
224							each(function() {
225								script += (this.innerHTML || this.innerText);
226							});
227
228							if ( script.length > 0 )
229							{
230								var randomID = Math.ceil(Math.random()*1000000);
231								content.attr('id', randomID);
232
233								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"
234
235								try{
236									$.globalEval("try{\n(function(){\n"+newContext+script+"\n}).call(jQuery('div#"+randomID+"').get(0));\n}catch(e){}\n//");
237								} catch (e) {
238									internal.log("Exception!");
239									internal.log(e);
240								}
241							}
242
243							if ( popupData.postPopupHook && typeof popupData.postPopupHook == 'function' ) {
244							    // Post-Hook which as to be a javascript function and my modify the popupData
245    							popupData.postPopupHook(this, popupData);
246							}
247
248                            _.registerCloseHandler();
249                            // At the very end we will resize the popup to fit the content.
250							_.resizePopup(popupData.width, popupData.height, null, content, true, popupData.hasNextPrevious);
251
252						}, waitForAll: true});
253					};
254
255
256					if ( status == "error") {
257						// Go for an iframe
258						var finished = false;
259						var iframe = null;
260
261						var messageFunction = function(event) {
262
263							finished = true;
264							var data = event.data || event.originalEvent.data;
265							// If this message does not come with what we want, discard it.
266							if ((typeof data).toLowerCase() == "string" || !data.message
267									|| data.message != 'frameContent') {
268								alert("Could not load page via popupviewer. The page responded with a wrong message.");
269								return;
270							}
271
272							iframe.remove();
273
274							// Clear the window Event after we are done!
275							$(window).unbind("message", messageFunction);
276
277							success($(data.body));
278						};
279
280						popupData.src = internal.getCurrentLocation();
281						var iframe = $('<iframe/>').load(function(){
282
283							var frame = this;
284							if ( frame.contentWindow.postMessage ) {
285
286								// Register the Message Event for PostMessage receival
287								$(window).bind("message", messageFunction);
288
289								// Send a message
290								var message = "getFrameContent";
291								frame.contentWindow.postMessage(message, "*");
292							}
293
294						}).hide().attr('src', popupData.src ).appendTo('body');
295
296						window.setTimeout(function() {
297							if (!finished) {
298								iframe.remove();
299								alert("Could not load page via popupviewer. The page is not available.");
300							}
301						}, 30000);
302
303					} else {
304						success(wrapper);
305					}
306
307				});
308			}
309		};
310
311		/* has to be called via popupscript in page if needed. */
312		_.propagateClickHandler = function(node, popupData) {
313			node.find('a[href],form[action]').
314			each(function(){
315				// Replace all event handler
316
317				var element = $(this);
318
319				var urlpart = element.attr('href') || element.attr('action') || "";
320				if ( urlpart.match(new RegExp("^#.*?$")) ) {
321					// Scroll to anchor
322					element.click(function(){
323						content.get(0).scrollTop( urlpart == '#' ? 0 : $(urlpart).offset().top);
324					});
325				}
326
327				if ( this.getAttribute('data-popupviewer') ) {
328					this.popupData = $.parseJSON(this.getAttribute('data-popupviewer'));
329					this.removeAttribute('data-popupviewer');
330				} else {
331					this.popupData = jQuery.extend(true, {}, popupData);
332					this.popupData.src = urlpart;
333                    this.popupData.do = 'export_xhtmlbody';
334
335					delete(this.popupData.id); // or it will always load this file.
336				}
337
338				$(this).bind('click', function(e){
339					e.stopPropagation(); e.preventDefault();
340					_.hideViewer(e, _.presentViewerWithContent);
341				});
342			});
343		};
344
345		internal.getCurrentLocation = function() {
346			return content.current.attr('href') || content.current.attr('src') || content.current.attr('action');
347		};
348
349		internal.optimalSize = function(offsetElement, isPageContent) {
350/*
351			if ( !isPageContent ) {
352				return {width: offsetElement.get(0).width, height: offsetElement.get(0).height};
353			}
354*/
355			var prevWidth = content.width();
356			var prevHeight = content.height();
357
358			offsetElement.css({width:'auto', height: 'auto'});
359
360			var width = offsetElement.naturalWidth() || offsetElement.width();
361			var height = offsetElement.naturalHeight() || offsetElement.height();
362
363			// Reset to previous size so the whole thing will animate from the middle
364			offsetElement.css({width:prevWidth, height: prevHeight});
365
366			return {width: width, height: height};
367		};
368
369		_.resizePopup = function(width, height, additionalHeight, offsetElement, isPageContent, needsNextPrevious) {
370
371			internal.log("Initial Size: " + width + " " + height);
372			internal.log(offsetElement);
373
374			if ( offsetElement && !width && !height) {
375				var optimalSize = internal.optimalSize(offsetElement, isPageContent);
376				width = optimalSize.width;
377				height = optimalSize.height;
378			}
379
380			internal.log("OffsetElement Size: " + width + " " + height);
381			width = parseInt(width) || ($(window).width() * 0.7);
382			height = parseInt(height) || ($(window).height() * 0.8);
383
384			var ratio = width / height;
385			var maxHeight = ( $(window).height() * 0.99 ) - 60;
386			var maxWidth = ( $(window).width() * 0.99 ) - 40;
387
388			additionalHeight = additionalHeight || 0;
389			height += additionalHeight;
390
391			internal.log("After Additional Content Size: " + width + " " + height);
392
393			if ( height > maxHeight ) {
394				height = maxHeight;
395				if ( !isPageContent ) { // If this is an image we will have to fix the size
396					width = (height - additionalHeight) * ratio;
397				} else {
398					width += 20; // For the scroller Bar that will apear;
399				}
400			}
401
402			if ( width > maxWidth ) {
403				width = maxWidth;
404				if ( !isPageContent ) { // If this is an image we will have to fix the size
405					height = width / ratio + additionalHeight;
406				}
407			}
408
409			var xOffset = viewerIsFixed ? 0 : $(document).scrollLeft() || 0;
410			var yOffset = viewerIsFixed ? 0 : $(document).scrollTop() || 0;
411
412			yOffset = Math.max(($(window).height() - height) * 0.5 + yOffset, 5);
413			xOffset += ($(window).width() - width) * 0.5;
414
415			internal.log("Final Size: " + width + " " + height);
416			internal.log("Final Offset: " + xOffset + " " + yOffset);
417
418			if ( !isPageContent || (offsetElement && offsetElement.is('img')) ) {
419
420				offsetElement.animate({
421					width : width,
422					height : height - additionalHeight
423				});
424
425				content.css({
426					width : '',
427					height : '',
428					overflow: ''
429				});
430
431			} else {
432				content.animate({
433					width : width,
434					height : isPageContent ? height : 'auto',
435				});
436			}
437
438			content.parent().animate({
439				top : yOffset,
440				left : xOffset,
441				'margin-left' : 0
442			});
443
444			if ( isPageContent ) {
445				content.removeClass('isImage');
446			} else {
447				content.addClass('isImage');
448			}
449
450			_.handleNextAndPrevious(!isPageContent || needsNextPrevious);
451			return _;
452		};
453
454		_.skipImageInDirection = function(e)
455		{
456			e.stopPropagation();
457
458			if ( !$(this).is(':visible') ) { return; }
459
460			var skipTo =  $.inArray(content.current.get(0), _.popupImageStack) + e.data.direction;
461			skipTo = Math.min(_.popupImageStack.length-1, Math.max(skipTo, 0));
462
463			internal.log("skipping " + (e.data.direction < 0 ? 'previous' : 'next') + ' ' + skipTo );
464			return _.skipToImage(skipTo, e.data.direction);
465		};
466
467		_.skipToImage = function(skipTo, inDirection)
468		{
469			if ( !$(_.popupImageStack[skipTo]).is(content.current) ) {
470				_.hideViewer(null, function() {
471					// Deliver extra functionality to clicked item.
472					var nextItem = _.popupImageStack[skipTo];
473					(nextItem.popupData && nextItem.popupData.click && nextItem.popupData.click(skipTo, inDirection)) || $(nextItem).click();
474				});
475			}
476
477			return _;
478		};
479
480		_.isFirst = function() {
481			return _.popupImageStack.first().is(content.current);
482		};
483
484		_.isLast = function() {
485			return _.popupImageStack.last().is(content.current);
486		};
487
488		_.handleNextAndPrevious = function(currentIsImage) {
489
490			if ( currentIsImage && _.popupImageStack && _.popupImageStack.size() > 1) {
491
492				if ( _.isFirst() ) {
493					previous.addClass('inactive');
494				} else {
495					previous.removeClass('inactive');
496				}
497
498				if ( _.isLast() ) {
499					next.addClass('inactive');
500				} else {
501					next.removeClass('inactive');
502				}
503
504				next.addClass('visible');
505				previous.addClass('visible');
506			} else {
507				next.removeClass('visible');
508				previous.removeClass('visible');
509			}
510
511			return _;
512		};
513
514        _.registerCloseHandler = function () {
515            $('*[data-popupviewerclose]').each(function(){
516                $(this).click(function(e){
517                   e && e.preventDefault();
518                   _.hideViewer(e);
519                   return false;
520                });
521                if (this.removeAttribute) this.removeAttribute('data-popupviewerclose');
522            });
523        };
524
525		_.init = function(popupImageStack) {
526
527			_.popupImageStack = $(popupImageStack || '*[data-popupviewer]').each(function(){
528				this.popupData = this.popupData || $.parseJSON(this.getAttribute('data-popupviewer'));
529				if (this.removeAttribute) this.removeAttribute('data-popupviewer');
530				$(this).unbind('click').click(_.presentViewerWithContent);
531			}).filter(function(){
532				// Only images allowed in Stack.
533				return this.popupData.isImage || this.popupData.hasNextPrevious;
534			});
535
536			return _;
537		};
538
539	})(popupviewer.prototype);
540
541    // Namespace all events.
542    var eventNamespace = 'waitForImages';
543
544    // CSS properties which contain references to images.
545    $.waitForImages = {
546        hasImageProperties: ['backgroundImage', 'listStyleImage', 'borderImage', 'borderCornerImage', 'cursor']
547    };
548
549    // Custom selector to find `img` elements that have a valid `src` attribute and have not already loaded.
550    $.expr[':'].uncached = function (obj) {
551        // Ensure we are dealing with an `img` element with a valid `src` attribute.
552        if (!$(obj).is('img[src!=""]')) {
553            return false;
554        }
555
556        // Firefox's `complete` property will always be `true` even if the image has not been downloaded.
557        // Doing it this way works in Firefox.
558        var img = new Image();
559        img.src = obj.src;
560        return !img.complete;
561    };
562
563    $.fn.waitForImages = function (finishedCallback, eachCallback, waitForAll) {
564
565        var allImgsLength = 0;
566        var allImgsLoaded = 0;
567
568        // Handle options object.
569        if ($.isPlainObject(arguments[0])) {
570            waitForAll = arguments[0].waitForAll;
571            eachCallback = arguments[0].each;
572			// This must be last as arguments[0]
573			// is aliased with finishedCallback.
574            finishedCallback = arguments[0].finished;
575        }
576
577        // Handle missing callbacks.
578        finishedCallback = finishedCallback || $.noop;
579        eachCallback = eachCallback || $.noop;
580
581        // Convert waitForAll to Boolean
582        waitForAll = !! waitForAll;
583
584        // Ensure callbacks are functions.
585        if (!$.isFunction(finishedCallback) || !$.isFunction(eachCallback)) {
586            throw new TypeError('An invalid callback was supplied.');
587        }
588
589        return this.each(function () {
590            // Build a list of all imgs, dependent on what images will be considered.
591            var obj = $(this);
592            var allImgs = [];
593            // CSS properties which may contain an image.
594            var hasImgProperties = $.waitForImages.hasImageProperties || [];
595            // To match `url()` references.
596            // Spec: http://www.w3.org/TR/CSS2/syndata.html#value-def-uri
597            var matchUrl = new RegExp("url\(\s*(['\"]?)(.*?)\1\s*\)", "g");
598
599            if (waitForAll) {
600
601                // Get all elements (including the original), as any one of them could have a background image.
602                obj.find('*').addBack().each(function () {
603                    var element = $(this);
604
605                    // If an `img` element, add it. But keep iterating in case it has a background image too.
606                    if (element.is('img:uncached')) {
607                        allImgs.push({
608                            src: element.attr('src'),
609                            element: element[0]
610                        });
611                    }
612
613                    $.each(hasImgProperties, function (i, property) {
614                        var propertyValue = element.css(property);
615                        var match;
616
617                        // If it doesn't contain this property, skip.
618                        if (!propertyValue) {
619                            return true;
620                        }
621
622                        // Get all url() of this element.
623                        while (match = matchUrl.exec(propertyValue)) {
624                            allImgs.push({
625                                src: match[2],
626                                element: element[0]
627                            });
628                        }
629                    });
630                });
631            } else {
632                // For images only, the task is simpler.
633                obj.find('img:uncached')
634                    .each(function () {
635                    allImgs.push({
636                        src: this.src,
637                        element: this
638                    });
639                });
640            }
641
642            allImgsLength = allImgs.length;
643            allImgsLoaded = 0;
644
645            // If no images found, don't bother.
646            if (allImgsLength === 0) {
647                finishedCallback.call(obj[0]);
648            }
649
650            $.each(allImgs, function (i, img) {
651
652                var image = new Image();
653
654                // Handle the image loading and error with the same callback.
655                $(image).on('load.' + eventNamespace + ' error.' + eventNamespace, function (event) {
656                    allImgsLoaded++;
657
658                    // If an error occurred with loading the image, set the third argument accordingly.
659                    eachCallback.call(img.element, allImgsLoaded, allImgsLength, event.type == 'load');
660
661                    if (allImgsLoaded == allImgsLength) {
662                        finishedCallback.call(obj[0]);
663                        return false;
664                    }
665
666                });
667
668                image.src = img.src;
669            });
670        });
671    };
672
673	$(function(){
674
675	    if ( typeof $.fn.naturalWidth != 'undefined' && typeof $.fn.naturalHeight != 'undefined' ) { return; }
676
677		function img(url) { var i = new Image(); i.src = url; return i; }
678		if ('naturalWidth' in (new Image())) {
679			$.fn.naturalWidth  = function() { return this[0].naturalWidth; };
680			$.fn.naturalHeight = function() { return this[0].naturalHeight; };
681			return;
682		}
683
684		$.fn.naturalWidth  = function() { return img(this.src).width; };
685		$.fn.naturalHeight = function() { return img(this.src).height; };
686	});
687
688	$(function(){
689		$.popupviewer().init();
690	});
691
692})(jQuery);
693
694
695/* Loading the content for locally exported content */
696(function($){
697	$(window).bind("message", function(event){
698
699		var data = event.data || event.originalEvent.data;
700		var source = event.source || event.originalEvent.source;
701		if (data != "getFrameContent") {
702			return;
703		}
704
705		try {
706			source.postMessage({
707				message : "frameContent",
708				body : jQuery('html').html()
709			}, "*");
710		} catch (e) {
711			alert("Fatal Exception! Could not load page via popupviewer.\n" + e);
712		}
713	});
714})(jQuery);
715