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